platform_windows.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. if re.search(r'MuMuPlayer(?:Global)?-15\.0-\d+', instance.name):
  149. self.execute(f'"{Emulator.single_to_console(exe)}" control -v {instance.MuMuPlayer12_id} --version 15 launch', show_window=show_window)
  150. else:
  151. self.execute(f'"{exe}" -v {instance.MuMuPlayer12_id}', show_window=show_window)
  152. elif instance == Emulator.LDPlayerFamily:
  153. # ldconsole.exe launch --index 0
  154. self.execute(f'"{Emulator.single_to_console(exe)}" launch --index {instance.LDPlayer_id}', show_window=show_window)
  155. elif instance == Emulator.NoxPlayerFamily:
  156. # Nox.exe -clone:Nox_1
  157. self.execute(f'"{exe}" -clone:{instance.name}', show_window=show_window)
  158. elif instance == Emulator.BlueStacks5:
  159. # HD-Player.exe --instance Pie64
  160. self.execute(f'"{exe}" --instance {instance.name}', show_window=show_window)
  161. elif instance == Emulator.BlueStacks4:
  162. # Bluestacks.exe -vmname Android_1
  163. self.execute(f'"{exe}" -vmname {instance.name}', show_window=show_window)
  164. elif instance == Emulator.MEmuPlayer:
  165. # MEmu.exe MEmu_0
  166. self.execute(f'"{exe}" {instance.name}', show_window=show_window)
  167. else:
  168. raise EmulatorUnknown(f'Cannot start an unknown emulator instance: {instance}')
  169. def _emulator_stop(self, instance: EmulatorInstance):
  170. """
  171. Stop a emulator without error handling
  172. """
  173. exe: str = instance.emulator.path
  174. if instance == Emulator.MuMuPlayer:
  175. # MuMu6 does not have multi instance, kill one means kill all
  176. # Has 4 processes
  177. # "C:\Program Files\NemuVbox\Hypervisor\NemuHeadless.exe" --comment nemu-6.0-x64-default --startvm
  178. # "E:\ProgramFiles\MuMu\emulator\nemu\EmulatorShell\NemuPlayer.exe"
  179. # E:\ProgramFiles\MuMu\emulator\nemu\EmulatorShell\NemuService.exe
  180. # "C:\Program Files\NemuVbox\Hypervisor\NemuSVC.exe" -Embedding
  181. self.kill_process_by_regex(
  182. rf'('
  183. rf'NemuHeadless.exe'
  184. rf'|NemuPlayer.exe\"'
  185. rf'|NemuPlayer.exe$'
  186. rf'|NemuService.exe'
  187. rf'|NemuSVC.exe'
  188. rf')'
  189. )
  190. elif instance == Emulator.MuMuPlayerX:
  191. # MuMu X has 3 processes
  192. # "E:\ProgramFiles\MuMu9\emulator\nemu9\EmulatorShell\NemuPlayer.exe" -m nemu-12.0-x64-default -s 0 -l
  193. # "C:\Program Files\Muvm6Vbox\Hypervisor\Muvm6Headless.exe" --comment nemu-12.0-x64-default --startvm xxx
  194. # "C:\Program Files\Muvm6Vbox\Hypervisor\Muvm6SVC.exe" --Embedding
  195. self.kill_process_by_regex(
  196. rf'('
  197. rf'NemuPlayer.exe.*-m {instance.name}'
  198. rf'|Muvm6Headless.exe'
  199. rf'|Muvm6SVC.exe'
  200. rf')'
  201. )
  202. elif instance == Emulator.MuMuPlayer12:
  203. # MuMuManager.exe api -v 1 shutdown_player
  204. if instance.MuMuPlayer12_id is None:
  205. logger.warning(f'Cannot get MuMu instance index from name {instance.name}')
  206. if re.search(r'MuMuPlayer(?:Global)?-15\.0-\d+', instance.name):
  207. # Finish shutdown before emulator_start() launches the same instance.
  208. self.execute(f'"{Emulator.single_to_console(exe)}" control -v {instance.MuMuPlayer12_id} --version 15 shutdown').wait(timeout=30)
  209. else:
  210. self.execute(f'"{Emulator.single_to_console(exe)}" api -v {instance.MuMuPlayer12_id} shutdown_player')
  211. elif instance == Emulator.LDPlayerFamily:
  212. # ldconsole.exe quit --index 0
  213. self.execute(f'"{Emulator.single_to_console(exe)}" quit --index {instance.LDPlayer_id}')
  214. elif instance == Emulator.NoxPlayerFamily:
  215. # Nox.exe -clone:Nox_1 -quit
  216. self.execute(f'"{exe}" -clone:{instance.name} -quit')
  217. elif instance == Emulator.BlueStacks5:
  218. # BlueStack has 2 processes
  219. # C:\Program Files\BlueStacks_nxt_cn\HD-Player.exe --instance Pie64
  220. # C:\Program Files\BlueStacks_nxt_cn\BstkSVC.exe -Embedding
  221. self.kill_process_by_regex(
  222. rf'('
  223. rf'HD-Player.exe.*"--instance" "{instance.name}"'
  224. rf')'
  225. )
  226. elif instance == Emulator.BlueStacks4:
  227. # E:\Program Files (x86)\BluestacksCN\bsconsole.exe quit --name Android
  228. self.execute(f'"{Emulator.single_to_console(exe)}" quit --name {instance.name}')
  229. elif instance == Emulator.MEmuPlayer:
  230. # F:\Program Files\Microvirt\MEmu\memuc.exe stop -n MEmu_0
  231. self.execute(f'"{Emulator.single_to_console(exe)}" stop -n {instance.name}')
  232. else:
  233. raise EmulatorUnknown(f'Cannot stop an unknown emulator instance: {instance}')
  234. def _emulator_function_wrapper(self, func: callable):
  235. """
  236. Args:
  237. func (callable): _emulator_start or _emulator_stop
  238. Returns:
  239. bool: If success
  240. """
  241. try:
  242. func(self.emulator_instance)
  243. return True
  244. except OSError as e:
  245. msg = str(e)
  246. # OSError: [WinError 740] 请求的操作需要提升。
  247. if 'WinError 740' in msg:
  248. logger.error('To start/stop MumuAppPlayer, ALAS needs to be run as administrator')
  249. except EmulatorUnknown as e:
  250. logger.error(e)
  251. except Exception as e:
  252. logger.exception(e)
  253. logger.error(f'Emulator function {func.__name__}() failed')
  254. return False
  255. def emulator_start_watch(self):
  256. """
  257. Returns:
  258. bool: True if startup completed
  259. False if timeout, unexpected stop, adb preemptive
  260. """
  261. logger.hr('Emulator start', level=2)
  262. current_window = get_focused_window()
  263. serial = self.emulator_instance.serial
  264. logger.info(f'Current window: {current_window}')
  265. def adb_connect():
  266. m = self.adb_client.connect(self.serial)
  267. if 'connected' in m:
  268. # Connected to 127.0.0.1:59865
  269. # Already connected to 127.0.0.1:59865
  270. return False
  271. elif '(10061)' in m:
  272. # cannot connect to 127.0.0.1:55555:
  273. # No connection could be made because the target machine actively refused it. (10061)
  274. return False
  275. else:
  276. return True
  277. @run_once
  278. def show_online(m):
  279. logger.info(f'Emulator online: {m}')
  280. @run_once
  281. def show_ping(m):
  282. logger.info(f'Command ping: {m}')
  283. @run_once
  284. def show_package(m):
  285. logger.info(f'Found azurlane packages: {m}')
  286. interval = Timer(1).start()
  287. timeout = Timer(120).start()
  288. struct_window = Timer(10)
  289. new_window = 0
  290. while 1:
  291. interval.wait()
  292. interval.reset()
  293. if timeout.reached():
  294. logger.warning(f'Emulator start timeout')
  295. return False
  296. # Check emulator window showing up
  297. # logger.info([get_focused_window(), get_window_title(get_focused_window())])
  298. if current_window != 0 and new_window == 0:
  299. new_window = get_focused_window()
  300. if current_window != new_window and not self.config.script.device.emulator_window_minimize and not self.config.script.device.run_background_only:
  301. logger.info(f'New window showing up: {new_window}, focus back')
  302. set_focus_window(current_window)
  303. else:
  304. new_window = 0
  305. try:
  306. logger.info(f'Try to connect emulator, remain[{timeout.remain():.1f}s]')
  307. # Check device connection
  308. devices = self.list_device().select(serial=serial)
  309. # logger.info(devices)
  310. if devices:
  311. device: AdbDeviceWithStatus = devices.first_or_none()
  312. if device.status == 'device':
  313. # Emulator online
  314. pass
  315. if device.status == 'offline':
  316. self.adb_client.disconnect(serial)
  317. adb_connect()
  318. continue
  319. else:
  320. # Try to connect
  321. adb_connect()
  322. continue
  323. except Exception as e:
  324. logger.warning(f'Error during adb_connect in watch loop: {e}')
  325. return False
  326. show_online(devices.first_or_none())
  327. # Check command availability
  328. try:
  329. pong = self.adb_shell(['echo', 'pong'])
  330. except Exception as e:
  331. logger.info(e)
  332. continue
  333. show_ping(pong)
  334. # Check game package
  335. packages = self.list_app_packages(show_log=False)
  336. if len(packages):
  337. pass
  338. else:
  339. continue
  340. show_package(packages)
  341. # Check Window structure
  342. if not struct_window.started():
  343. struct_window.start()
  344. elif struct_window.reached():
  345. break
  346. if new_window == 0:
  347. continue
  348. if not Handle.handle_has_children(hwnd=new_window):
  349. continue
  350. # All check passed
  351. break
  352. emulator_window_minimize = self.config.script.device.emulator_window_minimize
  353. if (emulator_window_minimize): logger.info(f'Minimize new emulator window: {emulator_window_minimize}')
  354. if (self.config.script.device.run_background_only):
  355. logger.info(f'run background only: {self.config.script.device.run_background_only}')
  356. logger.warning('run_background_only will not show any UI, emulator will run background only')
  357. if emulator_window_minimize and not self.config.script.device.run_background_only:
  358. # 直接使用窗口名称最小化
  359. sleep_time = 3
  360. logger.info(f'Waiting {sleep_time} seconds before minimizing window')
  361. Timer(sleep_time).wait()
  362. target_window_name = self.config.script.device.handle # 在这里输入你的具体窗口名称
  363. minimize_by_name(target_window_name)
  364. logger.info(f'最小化窗口: {target_window_name}')
  365. # if current_window:
  366. # logger.info(f'De-flash current window: {current_window}')
  367. # flash_window(current_window, flash=False)
  368. logger.info('Emulator start completed')
  369. return True
  370. def emulator_start(self):
  371. logger.hr('Emulator start', level=1)
  372. for i in range(3):
  373. # Stop
  374. if not self._emulator_function_wrapper(self._emulator_stop):
  375. return False
  376. # Start
  377. if self._emulator_function_wrapper(self._emulator_start):
  378. # Success
  379. if self.emulator_start_watch():
  380. return True
  381. logger.attr(2 - i, f'Failed to connect or start, try again')
  382. continue
  383. else:
  384. # Failed to start, stop and start again
  385. if self._emulator_function_wrapper(self._emulator_stop):
  386. continue
  387. else:
  388. return False
  389. logger.error('Failed to start emulator 3 times, stopped')
  390. return False
  391. def emulator_stop(self):
  392. # 桌面客户端无模拟器生命周期,空闲关闭改走关闭客户端。
  393. # desktop_stop_client 内部已做「窗口消失 且 进程退出」验证并多轮重杀,直接用其结论
  394. if getattr(self, 'is_desktop', False):
  395. return self.desktop_stop_client()
  396. logger.hr('Emulator stop', level=1)
  397. for _ in range(3):
  398. # Stop
  399. if self._emulator_function_wrapper(self._emulator_stop):
  400. # Success
  401. return True
  402. else:
  403. # Failed to stop, start and stop again
  404. if self._emulator_function_wrapper(self._emulator_start):
  405. continue
  406. else:
  407. return False
  408. logger.error('Failed to stop emulator 3 times, stopped')
  409. return False
  410. if __name__ == '__main__':
  411. self = PlatformWindows()
  412. d = self.emulator_instance
  413. print(d)