platform_windows.py 17 KB

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