platform_windows.py 15 KB

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