emulator_base.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. MuMuPlayerGlobal-15.0-1
  85. YXArkNights-12.0-1
  86. Returns:
  87. int: Instance ID, or None if this is not a MuMu 12 instance
  88. """
  89. res = re.search(r'MuMuPlayer(?:Global)?-(?:12|15)\.0-(\d+)', self.name)
  90. if res:
  91. return int(res.group(1))
  92. res = re.search(r'YXArkNights-12.0-(\d+)', self.name)
  93. if res:
  94. return int(res.group(1))
  95. return None
  96. @cached_property
  97. def LDPlayer_id(self):
  98. """
  99. Convert LDPlayer instance name to instance id.
  100. Example names:
  101. leidian0
  102. leidian1
  103. Returns:
  104. int: Instance ID, or None if this is not a LDPlayer instance
  105. """
  106. res = re.search(r'leidian(\d+)', self.name)
  107. if res:
  108. return int(res.group(1))
  109. return None
  110. class EmulatorBase:
  111. # Values here must match those in argument.yaml EmulatorInfo.Emulator.option
  112. NoxPlayer = 'NoxPlayer'
  113. NoxPlayer64 = 'NoxPlayer64'
  114. NoxPlayerFamily = [NoxPlayer, NoxPlayer64]
  115. BlueStacks4 = 'BlueStacks4'
  116. BlueStacks5 = 'BlueStacks5'
  117. BlueStacks4HyperV = 'BlueStacks4HyperV'
  118. BlueStacks5HyperV = 'BlueStacks5HyperV'
  119. BlueStacksFamily = [BlueStacks4, BlueStacks5]
  120. LDPlayer3 = 'LDPlayer3'
  121. LDPlayer4 = 'LDPlayer4'
  122. LDPlayer9 = 'LDPlayer9'
  123. LDPlayerFamily = [LDPlayer3, LDPlayer4, LDPlayer9]
  124. MuMuPlayer = 'MuMuPlayer'
  125. MuMuPlayerX = 'MuMuPlayerX'
  126. MuMuPlayer12 = 'MuMuPlayer12'
  127. MuMuPlayerFamily = [MuMuPlayer, MuMuPlayerX, MuMuPlayer12]
  128. MEmuPlayer = 'MEmuPlayer'
  129. @classmethod
  130. def path_to_type(cls, path: str) -> str:
  131. """
  132. Args:
  133. path: Path to .exe file
  134. Returns:
  135. str: Emulator type, such as Emulator.NoxPlayer,
  136. or '' if this is not a emulator.
  137. """
  138. return ''
  139. def iter_instances(self) -> t.Iterable[EmulatorInstanceBase]:
  140. """
  141. Yields:
  142. EmulatorInstance: Emulator instances found in this emulator
  143. """
  144. pass
  145. def iter_adb_binaries(self) -> t.Iterable[str]:
  146. """
  147. Yields:
  148. str: Filepath to adb binaries found in this emulator
  149. """
  150. pass
  151. def __init__(self, path):
  152. # Path to .exe file
  153. self.path = path.replace('\\', '/')
  154. # Path to emulator folder
  155. self.dir = os.path.dirname(path)
  156. # str: Emulator type, or '' if this is not a emulator.
  157. self.type = self.__class__.path_to_type(path)
  158. def __eq__(self, other):
  159. if isinstance(other, str) and self.type == other:
  160. return True
  161. if isinstance(other, list) and self.type in other:
  162. return True
  163. return super().__eq__(other)
  164. def __str__(self):
  165. return f'{self.type}(path="{self.path}")'
  166. __repr__ = __str__
  167. def __hash__(self):
  168. return hash(self.path)
  169. def __bool__(self):
  170. return True
  171. def abspath(self, path, folder=None):
  172. if folder is None:
  173. folder = self.dir
  174. return abspath(os.path.join(folder, path))
  175. @classmethod
  176. def is_emulator(cls, path: str) -> bool:
  177. """
  178. Args:
  179. path: Path to .exe file.
  180. Returns:
  181. bool: If this is a emulator.
  182. """
  183. return bool(cls.path_to_type(path))
  184. def list_folder(self, folder, is_dir=False, ext=None):
  185. """
  186. Safely list files in a folder
  187. Args:
  188. folder:
  189. is_dir:
  190. ext:
  191. Returns:
  192. list[str]:
  193. """
  194. folder = self.abspath(folder)
  195. return list(iter_folder(folder, is_dir=is_dir, ext=ext))
  196. class EmulatorManagerBase:
  197. @staticmethod
  198. def iter_running_emulator():
  199. """
  200. Yields:
  201. str: Path to emulator executables, may contains duplicate values
  202. """
  203. return
  204. @cached_property
  205. def all_emulators(self) -> t.List[EmulatorBase]:
  206. """
  207. Get all emulators installed on current computer.
  208. """
  209. return []
  210. @cached_property
  211. def all_emulator_instances(self) -> t.List[EmulatorInstanceBase]:
  212. """
  213. Get all emulator instances installed on current computer.
  214. """
  215. return []
  216. @cached_property
  217. def all_emulator_serials(self) -> t.List[str]:
  218. """
  219. Returns:
  220. list[str]: All possible serials on current computer.
  221. """
  222. out = []
  223. for emulator in self.all_emulator_instances:
  224. out.append(emulator.serial)
  225. # Also add serial like `emulator-5554`
  226. port_serial, emu_serial = get_serial_pair(emulator.serial)
  227. if emu_serial:
  228. out.append(emu_serial)
  229. return out
  230. @cached_property
  231. def all_adb_binaries(self) -> t.List[str]:
  232. """
  233. Returns:
  234. list[str]: All adb binaries of emulators on current computer.
  235. """
  236. out = []
  237. for emulator in self.all_emulators:
  238. for exe in emulator.iter_adb_binaries():
  239. out.append(exe)
  240. return out