platform_windows.py 19 KB

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