platform_windows.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. import ctypes
  2. import re
  3. import subprocess
  4. import psutil
  5. from adbutils import AdbDevice, AdbClient
  6. from deploy.utils import DataProcessInfo
  7. from module.base.decorator import run_once
  8. from module.base.timer import Timer
  9. from module.device.handle import Handle
  10. from module.device.platform2.platform_base import PlatformBase
  11. from module.device.platform2.emulator_windows import Emulator, EmulatorInstance, EmulatorManager
  12. from module.logger import logger
  13. class EmulatorUnknown(Exception):
  14. pass
  15. def get_focused_window():
  16. return ctypes.windll.user32.GetForegroundWindow()
  17. def set_focus_window(hwnd):
  18. ctypes.windll.user32.SetForegroundWindow(hwnd)
  19. def minimize_window(hwnd):
  20. ctypes.windll.user32.ShowWindow(hwnd, 6)
  21. def get_window_title(hwnd):
  22. """Returns the window title as a string."""
  23. text_len_in_characters = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
  24. string_buffer = ctypes.create_unicode_buffer(
  25. text_len_in_characters + 1) # +1 for the \0 at the end of the null-terminated string.
  26. ctypes.windll.user32.GetWindowTextW(hwnd, string_buffer, text_len_in_characters + 1)
  27. return string_buffer.value
  28. def flash_window(hwnd, flash=True):
  29. ctypes.windll.user32.FlashWindow(hwnd, flash)
  30. class AdbDeviceWithStatus(AdbDevice):
  31. def __init__(self, client: AdbClient, serial: str, status: str):
  32. self.status = status
  33. super().__init__(client, serial)
  34. def __str__(self):
  35. return f'AdbDevice({self.serial}, {self.status})'
  36. __repr__ = __str__
  37. def __bool__(self):
  38. return True
  39. class PlatformWindows(PlatformBase, EmulatorManager):
  40. @classmethod
  41. def execute(cls, command):
  42. """
  43. Args:
  44. command (str):
  45. Returns:
  46. subprocess.Popen:
  47. """
  48. command = command.replace(r"\\", "/").replace("\\", "/").replace('"', '"')
  49. logger.info(f'Execute: {command}')
  50. return subprocess.Popen(command, close_fds=True) # only work on Windows
  51. @classmethod
  52. def kill_process_by_regex(cls, regex: str) -> int:
  53. """
  54. Kill processes with cmdline match the given regex.
  55. Args:
  56. regex:
  57. Returns:
  58. int: Number of processes killed
  59. """
  60. count = 0
  61. for proc in psutil.process_iter():
  62. cmdline = DataProcessInfo(proc=proc, pid=proc.pid).cmdline
  63. if re.search(regex, cmdline):
  64. logger.info(f'Kill emulator: {cmdline}')
  65. proc.kill()
  66. count += 1
  67. return count
  68. def _emulator_start(self, instance: EmulatorInstance):
  69. """
  70. Start a emulator without error handling
  71. """
  72. exe: str = instance.emulator.path
  73. if instance == Emulator.MuMuPlayer:
  74. # NemuPlayer.exe
  75. self.execute(exe)
  76. elif instance == Emulator.MuMuPlayerX:
  77. # NemuPlayer.exe -m nemu-12.0-x64-default
  78. self.execute(f'"{exe}" -m {instance.name}')
  79. elif instance == Emulator.MuMuPlayer12:
  80. # MuMuPlayer.exe -v 0
  81. if instance.MuMuPlayer12_id is None:
  82. logger.warning(f'Cannot get MuMu instance index from name {instance.name}')
  83. self.execute(f'"{exe}" -v {instance.MuMuPlayer12_id}')
  84. elif instance == Emulator.LDPlayerFamily:
  85. # ldconsole.exe launch --index 0
  86. self.execute(f'"{Emulator.single_to_console(exe)}" launch --index {instance.LDPlayer_id}')
  87. elif instance == Emulator.NoxPlayerFamily:
  88. # Nox.exe -clone:Nox_1
  89. self.execute(f'"{exe}" -clone:{instance.name}')
  90. elif instance == Emulator.BlueStacks5:
  91. # HD-Player.exe --instance Pie64
  92. self.execute(f'"{exe}" --instance {instance.name}')
  93. elif instance == Emulator.BlueStacks4:
  94. # Bluestacks.exe -vmname Android_1
  95. self.execute(f'"{exe}" -vmname {instance.name}')
  96. elif instance == Emulator.MEmuPlayer:
  97. # MEmu.exe MEmu_0
  98. self.execute(f'"{exe}" {instance.name}')
  99. else:
  100. raise EmulatorUnknown(f'Cannot start an unknown emulator instance: {instance}')
  101. def _emulator_stop(self, instance: EmulatorInstance):
  102. """
  103. Stop a emulator without error handling
  104. """
  105. exe: str = instance.emulator.path
  106. if instance == Emulator.MuMuPlayer:
  107. # MuMu6 does not have multi instance, kill one means kill all
  108. # Has 4 processes
  109. # "C:\Program Files\NemuVbox\Hypervisor\NemuHeadless.exe" --comment nemu-6.0-x64-default --startvm
  110. # "E:\ProgramFiles\MuMu\emulator\nemu\EmulatorShell\NemuPlayer.exe"
  111. # E:\ProgramFiles\MuMu\emulator\nemu\EmulatorShell\NemuService.exe
  112. # "C:\Program Files\NemuVbox\Hypervisor\NemuSVC.exe" -Embedding
  113. self.kill_process_by_regex(
  114. rf'('
  115. rf'NemuHeadless.exe'
  116. rf'|NemuPlayer.exe\"'
  117. rf'|NemuPlayer.exe$'
  118. rf'|NemuService.exe'
  119. rf'|NemuSVC.exe'
  120. rf')'
  121. )
  122. elif instance == Emulator.MuMuPlayerX:
  123. # MuMu X has 3 processes
  124. # "E:\ProgramFiles\MuMu9\emulator\nemu9\EmulatorShell\NemuPlayer.exe" -m nemu-12.0-x64-default -s 0 -l
  125. # "C:\Program Files\Muvm6Vbox\Hypervisor\Muvm6Headless.exe" --comment nemu-12.0-x64-default --startvm xxx
  126. # "C:\Program Files\Muvm6Vbox\Hypervisor\Muvm6SVC.exe" --Embedding
  127. self.kill_process_by_regex(
  128. rf'('
  129. rf'NemuPlayer.exe.*-m {instance.name}'
  130. rf'|Muvm6Headless.exe'
  131. rf'|Muvm6SVC.exe'
  132. rf')'
  133. )
  134. elif instance == Emulator.MuMuPlayer12:
  135. # MuMuManager.exe api -v 1 shutdown_player
  136. if instance.MuMuPlayer12_id is None:
  137. logger.warning(f'Cannot get MuMu instance index from name {instance.name}')
  138. self.execute(f'"{Emulator.single_to_console(exe)}" api -v {instance.MuMuPlayer12_id} shutdown_player')
  139. elif instance == Emulator.LDPlayerFamily:
  140. # ldconsole.exe quit --index 0
  141. self.execute(f'"{Emulator.single_to_console(exe)}" quit --index {instance.LDPlayer_id}')
  142. elif instance == Emulator.NoxPlayerFamily:
  143. # Nox.exe -clone:Nox_1 -quit
  144. self.execute(f'"{exe}" -clone:{instance.name} -quit')
  145. elif instance == Emulator.BlueStacks5:
  146. # BlueStack has 2 processes
  147. # C:\Program Files\BlueStacks_nxt_cn\HD-Player.exe --instance Pie64
  148. # C:\Program Files\BlueStacks_nxt_cn\BstkSVC.exe -Embedding
  149. self.kill_process_by_regex(
  150. rf'('
  151. rf'HD-Player.exe.*"--instance" "{instance.name}"'
  152. rf')'
  153. )
  154. elif instance == Emulator.BlueStacks4:
  155. # E:\Program Files (x86)\BluestacksCN\bsconsole.exe quit --name Android
  156. self.execute(f'"{Emulator.single_to_console(exe)}" quit --name {instance.name}')
  157. elif instance == Emulator.MEmuPlayer:
  158. # F:\Program Files\Microvirt\MEmu\memuc.exe stop -n MEmu_0
  159. self.execute(f'"{Emulator.single_to_console(exe)}" stop -n {instance.name}')
  160. else:
  161. raise EmulatorUnknown(f'Cannot stop an unknown emulator instance: {instance}')
  162. def _emulator_function_wrapper(self, func: callable):
  163. """
  164. Args:
  165. func (callable): _emulator_start or _emulator_stop
  166. Returns:
  167. bool: If success
  168. """
  169. try:
  170. func(self.emulator_instance)
  171. return True
  172. except OSError as e:
  173. msg = str(e)
  174. # OSError: [WinError 740] 请求的操作需要提升。
  175. if 'WinError 740' in msg:
  176. logger.error('To start/stop MumuAppPlayer, ALAS needs to be run as administrator')
  177. except EmulatorUnknown as e:
  178. logger.error(e)
  179. except Exception as e:
  180. logger.exception(e)
  181. logger.error(f'Emulator function {func.__name__}() failed')
  182. return False
  183. def emulator_start_watch(self):
  184. """
  185. Returns:
  186. bool: True if startup completed
  187. False if timeout
  188. """
  189. logger.hr('Emulator start', level=2)
  190. current_window = get_focused_window()
  191. serial = self.emulator_instance.serial
  192. logger.info(f'Current window: {current_window}')
  193. def adb_connect():
  194. m = self.adb_client.connect(self.serial)
  195. if 'connected' in m:
  196. # Connected to 127.0.0.1:59865
  197. # Already connected to 127.0.0.1:59865
  198. return False
  199. elif '(10061)' in m:
  200. # cannot connect to 127.0.0.1:55555:
  201. # No connection could be made because the target machine actively refused it. (10061)
  202. return False
  203. else:
  204. return True
  205. @run_once
  206. def show_online(m):
  207. logger.info(f'Emulator online: {m}')
  208. @run_once
  209. def show_ping(m):
  210. logger.info(f'Command ping: {m}')
  211. @run_once
  212. def show_package(m):
  213. logger.info(f'Found azurlane packages: {m}')
  214. interval = Timer(1).start()
  215. timeout = Timer(180).start()
  216. struct_window = Timer(10)
  217. new_window = 0
  218. while 1:
  219. interval.wait()
  220. interval.reset()
  221. if timeout.reached():
  222. logger.warning(f'Emulator start timeout')
  223. return False
  224. # Check emulator window showing up
  225. # logger.info([get_focused_window(), get_window_title(get_focused_window())])
  226. if current_window != 0 and new_window == 0:
  227. new_window = get_focused_window()
  228. if current_window != new_window:
  229. logger.info(f'New window showing up: {new_window}, focus back')
  230. set_focus_window(current_window)
  231. else:
  232. new_window = 0
  233. # Check device connection
  234. devices = self.list_device().select(serial=serial)
  235. # logger.info(devices)
  236. if devices:
  237. device: AdbDeviceWithStatus = devices.first_or_none()
  238. if device.status == 'device':
  239. # Emulator online
  240. pass
  241. if device.status == 'offline':
  242. self.adb_client.disconnect(serial)
  243. adb_connect()
  244. continue
  245. else:
  246. # Try to connect
  247. adb_connect()
  248. continue
  249. show_online(devices.first_or_none())
  250. # Check command availability
  251. try:
  252. pong = self.adb_shell(['echo', 'pong'])
  253. except Exception as e:
  254. logger.info(e)
  255. continue
  256. show_ping(pong)
  257. # Check game package
  258. packages = self.list_app_packages(show_log=False)
  259. if len(packages):
  260. pass
  261. else:
  262. continue
  263. show_package(packages)
  264. # Check Window structure
  265. if not struct_window.started():
  266. struct_window.start()
  267. elif struct_window.reached():
  268. break
  269. if new_window == 0:
  270. continue
  271. if not Handle.handle_has_children(hwnd=new_window):
  272. continue
  273. # All check passed
  274. break
  275. if new_window != 0 and new_window != current_window:
  276. logger.info(f'Minimize new window: {new_window}')
  277. minimize_window(new_window)
  278. if current_window:
  279. logger.info(f'De-flash current window: {current_window}')
  280. flash_window(current_window, flash=False)
  281. if new_window:
  282. logger.info(f'Flash new window: {new_window}')
  283. flash_window(new_window, flash=True)
  284. logger.info('Emulator start completed')
  285. return True
  286. def emulator_start(self):
  287. logger.hr('Emulator start', level=1)
  288. for _ in range(3):
  289. # Stop
  290. if not self._emulator_function_wrapper(self._emulator_stop):
  291. return False
  292. # Start
  293. if self._emulator_function_wrapper(self._emulator_start):
  294. # Success
  295. self.emulator_start_watch()
  296. return True
  297. else:
  298. # Failed to start, stop and start again
  299. if self._emulator_function_wrapper(self._emulator_stop):
  300. continue
  301. else:
  302. return False
  303. logger.error('Failed to start emulator 3 times, stopped')
  304. return False
  305. def emulator_stop(self):
  306. logger.hr('Emulator stop', level=1)
  307. for _ in range(3):
  308. # Stop
  309. if self._emulator_function_wrapper(self._emulator_stop):
  310. # Success
  311. return True
  312. else:
  313. # Failed to stop, start and stop again
  314. if self._emulator_function_wrapper(self._emulator_start):
  315. continue
  316. else:
  317. return False
  318. logger.error('Failed to stop emulator 3 times, stopped')
  319. return False
  320. if __name__ == '__main__':
  321. self = PlatformWindows()
  322. d = self.emulator_instance
  323. print(d)