platform_windows.py 14 KB

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