emulator_base.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import os
  2. import re
  3. import typing as t
  4. from dataclasses import dataclass
  5. from module.device.platform2.utils import cached_property, iter_folder
  6. def abspath(path):
  7. return os.path.abspath(path).replace('\\', '/')
  8. def get_serial_pair(serial):
  9. """
  10. Args:
  11. serial (str):
  12. Returns:
  13. str, str: `127.0.0.1:5555+{X}` and `emulator-5554+{X}`, 0 <= X <= 32
  14. """
  15. if serial.startswith('127.0.0.1:'):
  16. try:
  17. port = int(serial[10:])
  18. if 5555 <= port <= 5555 + 32:
  19. return f'127.0.0.1:{port}', f'emulator-{port - 1}'
  20. except (ValueError, IndexError):
  21. pass
  22. if serial.startswith('emulator-'):
  23. try:
  24. port = int(serial[9:])
  25. if 5554 <= port <= 5554 + 32:
  26. return f'127.0.0.1:{port + 1}', f'emulator-{port}'
  27. except (ValueError, IndexError):
  28. pass
  29. return None, None
  30. def remove_duplicated_path(paths):
  31. """
  32. Args:
  33. paths (list[str]):
  34. Returns:
  35. list[str]:
  36. """
  37. paths = sorted(set(paths))
  38. dic = {}
  39. for path in paths:
  40. dic.setdefault(path.lower(), path)
  41. return list(dic.values())
  42. @dataclass
  43. class EmulatorInstanceBase:
  44. # Serial for adb connection
  45. serial: str
  46. # Emulator instance name, used for start/stop emulator
  47. name: str
  48. # Path to emulator .exe
  49. path: str
  50. def __str__(self):
  51. return f'{self.type}(serial="{self.serial}", name="{self.name}", path="{self.path}")'
  52. @cached_property
  53. def type(self) -> str:
  54. """
  55. Returns:
  56. str: Emulator type, such as Emulator.NoxPlayer
  57. """
  58. return self.emulator.type
  59. @cached_property
  60. def emulator(self):
  61. """
  62. Returns:
  63. Emulator:
  64. """
  65. return EmulatorBase(self.path)
  66. def __eq__(self, other):
  67. if isinstance(other, str) and self.type == other:
  68. return True
  69. if isinstance(other, list) and self.type in other:
  70. return True
  71. if isinstance(other, EmulatorInstanceBase):
  72. return super().__eq__(other) and self.type == other.type
  73. return super().__eq__(other)
  74. def __hash__(self):
  75. return hash(str(self))
  76. def __bool__(self):
  77. return True
  78. @cached_property
  79. def MuMuPlayer12_id(self):
  80. """
  81. Convert MuMu 12 instance name to instance id.
  82. Example names:
  83. MuMuPlayer-12.0-3
  84. YXArkNights-12.0-1
  85. Returns:
  86. int: Instance ID, or None if this is not a MuMu 12 instance
  87. """
  88. res = re.search(r'MuMuPlayer(?:Global)?-12.0-(\d+)', self.name)
  89. if res:
  90. return int(res.group(1))
  91. res = re.search(r'YXArkNights-12.0-(\d+)', self.name)
  92. if res:
  93. return int(res.group(1))
  94. return None
  95. @cached_property
  96. def LDPlayer_id(self):
  97. """
  98. Convert LDPlayer instance name to instance id.
  99. Example names:
  100. leidian0
  101. leidian1
  102. Returns:
  103. int: Instance ID, or None if this is not a LDPlayer instance
  104. """
  105. res = re.search(r'leidian(\d+)', self.name)
  106. if res:
  107. return int(res.group(1))
  108. return None
  109. class EmulatorBase:
  110. # Values here must match those in argument.yaml EmulatorInfo.Emulator.option
  111. NoxPlayer = 'NoxPlayer'
  112. NoxPlayer64 = 'NoxPlayer64'
  113. NoxPlayerFamily = [NoxPlayer, NoxPlayer64]
  114. BlueStacks4 = 'BlueStacks4'
  115. BlueStacks5 = 'BlueStacks5'
  116. BlueStacks4HyperV = 'BlueStacks4HyperV'
  117. BlueStacks5HyperV = 'BlueStacks5HyperV'
  118. BlueStacksFamily = [BlueStacks4, BlueStacks5]
  119. LDPlayer3 = 'LDPlayer3'
  120. LDPlayer4 = 'LDPlayer4'
  121. LDPlayer9 = 'LDPlayer9'
  122. LDPlayerFamily = [LDPlayer3, LDPlayer4, LDPlayer9]
  123. MuMuPlayer = 'MuMuPlayer'
  124. MuMuPlayerX = 'MuMuPlayerX'
  125. MuMuPlayer12 = 'MuMuPlayer12'
  126. MuMuPlayerFamily = [MuMuPlayer, MuMuPlayerX, MuMuPlayer12]
  127. MEmuPlayer = 'MEmuPlayer'
  128. @classmethod
  129. def path_to_type(cls, path: str) -> str:
  130. """
  131. Args:
  132. path: Path to .exe file
  133. Returns:
  134. str: Emulator type, such as Emulator.NoxPlayer,
  135. or '' if this is not a emulator.
  136. """
  137. return ''
  138. def iter_instances(self) -> t.Iterable[EmulatorInstanceBase]:
  139. """
  140. Yields:
  141. EmulatorInstance: Emulator instances found in this emulator
  142. """
  143. pass
  144. def iter_adb_binaries(self) -> t.Iterable[str]:
  145. """
  146. Yields:
  147. str: Filepath to adb binaries found in this emulator
  148. """
  149. pass
  150. def __init__(self, path):
  151. # Path to .exe file
  152. self.path = path.replace('\\', '/')
  153. # Path to emulator folder
  154. self.dir = os.path.dirname(path)
  155. # str: Emulator type, or '' if this is not a emulator.
  156. self.type = self.__class__.path_to_type(path)
  157. def __eq__(self, other):
  158. if isinstance(other, str) and self.type == other:
  159. return True
  160. if isinstance(other, list) and self.type in other:
  161. return True
  162. return super().__eq__(other)
  163. def __str__(self):
  164. return f'{self.type}(path="{self.path}")'
  165. __repr__ = __str__
  166. def __hash__(self):
  167. return hash(self.path)
  168. def __bool__(self):
  169. return True
  170. def abspath(self, path, folder=None):
  171. if folder is None:
  172. folder = self.dir
  173. return abspath(os.path.join(folder, path))
  174. @classmethod
  175. def is_emulator(cls, path: str) -> bool:
  176. """
  177. Args:
  178. path: Path to .exe file.
  179. Returns:
  180. bool: If this is a emulator.
  181. """
  182. return bool(cls.path_to_type(path))
  183. def list_folder(self, folder, is_dir=False, ext=None):
  184. """
  185. Safely list files in a folder
  186. Args:
  187. folder:
  188. is_dir:
  189. ext:
  190. Returns:
  191. list[str]:
  192. """
  193. folder = self.abspath(folder)
  194. return list(iter_folder(folder, is_dir=is_dir, ext=ext))
  195. class EmulatorManagerBase:
  196. @staticmethod
  197. def iter_running_emulator():
  198. """
  199. Yields:
  200. str: Path to emulator executables, may contains duplicate values
  201. """
  202. return
  203. @cached_property
  204. def all_emulators(self) -> t.List[EmulatorBase]:
  205. """
  206. Get all emulators installed on current computer.
  207. """
  208. return []
  209. @cached_property
  210. def all_emulator_instances(self) -> t.List[EmulatorInstanceBase]:
  211. """
  212. Get all emulator instances installed on current computer.
  213. """
  214. return []
  215. @cached_property
  216. def all_emulator_serials(self) -> t.List[str]:
  217. """
  218. Returns:
  219. list[str]: All possible serials on current computer.
  220. """
  221. out = []
  222. for emulator in self.all_emulator_instances:
  223. out.append(emulator.serial)
  224. # Also add serial like `emulator-5554`
  225. port_serial, emu_serial = get_serial_pair(emulator.serial)
  226. if emu_serial:
  227. out.append(emu_serial)
  228. return out
  229. @cached_property
  230. def all_adb_binaries(self) -> t.List[str]:
  231. """
  232. Returns:
  233. list[str]: All adb binaries of emulators on current computer.
  234. """
  235. out = []
  236. for emulator in self.all_emulators:
  237. for exe in emulator.iter_adb_binaries():
  238. out.append(exe)
  239. return out