desktop_impl.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. # This Python file uses the following encoding: utf-8
  2. """桌面客户端(阴阳师 PC 版)窗口控制实现。
  3. 从 module/device/handle.py 拆出:桌面模式与模拟器模式除"窗口句柄怎么拿到"外没有
  4. 任何共享逻辑,两者同处一个类会把 handle.py 撑到 1300+ 行,也让"移植到底动没动
  5. 模拟器基线"难以一眼看清。这里用纯 mixin ``DesktopWindow`` 承载全部桌面分支
  6. (``Handle`` 继承它),handle.py 只保留模拟器逻辑与少量桌面内联判断。
  7. 边界约定:
  8. - ``DesktopWindow`` 不定义 ``__init__``,全部实例状态由 ``Handle.__init__`` 的
  9. 桌面分支设置;类内方法名与 Handle 模拟器方法无重名,MRO 无歧义;
  10. - 本模块不反向依赖 handle.py,是叶子模块,无循环导入;
  11. - 模块级常量与 helper(``list_desktop_windows`` / ``desktop_window_option`` /
  12. ``desktop_option2pid`` / ``dpi_awareness`` 等)一并住在这里,外部调用方直接
  13. 从本模块导入,不经 handle.py 转出——避免"补丁打在转出别名上静默失效"。
  14. """
  15. import os
  16. import re
  17. import subprocess
  18. import time
  19. import ctypes
  20. from ctypes import c_long, byref, POINTER, Structure, wintypes
  21. from contextlib import contextmanager
  22. from pathlib import Path
  23. from win32api import SendMessage
  24. from win32process import GetWindowThreadProcessId
  25. from win32gui import (GetWindowText, EnumWindows, GetWindowRect, IsWindow,
  26. GetClientRect, ClientToScreen, GetWindowLong,
  27. SetWindowPos, GetClassName, IsIconic, ShowWindow)
  28. from win32con import (WM_KEYDOWN, WM_KEYUP, VK_RETURN, GWL_STYLE, GWL_EXSTYLE,
  29. HWND_TOP, SWP_NOMOVE, SWP_SHOWWINDOW, SW_RESTORE)
  30. from module.base.decorator import del_cached_property
  31. from module.exception import EmulatorNotRunningError
  32. from module.logger import logger
  33. # 桌面客户端窗口标题(官方桌面版,多开共用同一标题)
  34. DESKTOP_WINDOW_TITLES = ('阴阳师-网易游戏', '阴阳师-MuMu模拟器专版')
  35. # 「进程活着但窗口还没就绪」时的等待上限(秒)与轮询间隔。空窗期有两种:客户端
  36. # 启动期还没出窗口、确认 MPay 弹窗后销毁登录界面重建主窗口的那几秒。这段等待只
  37. # 轮询窗口,绝不重新启动进程——把「窗口暂时不在」当成「客户端没在运行」会拉起
  38. # 多余实例(单实例语义下用户正在用的那个会被顶掉),并把配置里的 handle 覆盖成新实例
  39. DESKTOP_WINDOW_READY_WAIT = 15
  40. DESKTOP_WINDOW_READY_POLL_INTERVAL = 0.5
  41. # 网易 MPay 账号登录弹窗的窗口类名。它是与游戏主窗口同 PID 的独立顶层窗口
  42. # (DirectUI 绘制,无子控件),不在游戏渲染面内,因此主窗口 BitBlt 截不到它,
  43. # 也无法用图像识别处理,只能按类名单独定位并注入消息。
  44. DESKTOP_LOGIN_POPUP_CLASS = 'MPAY_LOGIN'
  45. # 调整窗口尺寸时撞上客户端重建窗口的重试轮数与间隔(秒)。客户端确认登录弹窗后销毁
  46. # 登录界面、重建游戏主窗口,实测这段空窗期在几百毫秒到数秒之间,6 轮 × 1s 足够覆盖
  47. DESKTOP_RESIZE_ATTEMPTS = 6
  48. DESKTOP_RESIZE_RETRY_INTERVAL = 1.0
  49. # 关闭桌面客户端的强杀轮数。TerminateProcess 可能因权限被拒(实测本机出现过
  50. # (5, '拒绝访问。')),也可能进程正在退出但还没消失,因此杀完必须验证进程真的没了,
  51. # 没死就再杀一轮,而不是发完指令就当成功
  52. DESKTOP_KILL_ATTEMPTS = 3
  53. DESKTOP_KILL_POLL_INTERVAL = 0.5
  54. # DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2,SetThreadDpiAwarenessContext 的入参
  55. _PER_MONITOR_AWARE_V2 = ctypes.c_void_p(-4)
  56. # 桌面客户端运行期间强制保持显示器常亮:桌面模式截图走 BitBlt,依赖 DWM 合成,
  57. # 屏幕一旦因电源超时关闭,DWM 停止合成,BitBlt 只能返回静止黑帧,登录循环会因此
  58. # 死等 300s 超时。在客户端启动时开启、关闭时清除,只锁客户端生命周期,不影响
  59. # OAS 空闲时用户正常让屏幕休眠。
  60. ES_CONTINUOUS = 0x80000000
  61. ES_DISPLAY_REQUIRED = 0x00000002
  62. @contextmanager
  63. def dpi_awareness():
  64. """临时把当前线程切到 Per-Monitor V2 DPI 感知,退出时恢复原上下文。
  65. OAS 进程自身未声明 DPI 感知,GDI 调用默认被系统虚拟化成逻辑像素:125% 缩放下
  66. 物理 1280x720 的客户区只报 1024x576,BitBlt 也只能取到画面左上角那一块(右侧
  67. 侧边栏与底部菜单栏直接丢失)。桌面客户端进程是 Per-Monitor DPI 感知、按物理
  68. 像素原生渲染,因此桌面分支的窗口测量与截图必须在感知上下文里做才能拿到完整的
  69. 物理像素画面。用线程级而非进程级,是为了不影响模拟器直控路径既有的逻辑像素假设。
  70. """
  71. user32 = ctypes.windll.user32
  72. previous = None
  73. try:
  74. previous = user32.SetThreadDpiAwarenessContext(_PER_MONITOR_AWARE_V2)
  75. except AttributeError:
  76. # Windows 10 1607 以前没有该 API,退化为原有逻辑像素行为
  77. pass
  78. try:
  79. yield
  80. finally:
  81. if previous:
  82. user32.SetThreadDpiAwarenessContext(previous)
  83. def desktop_keep_screen_on(enable: bool) -> None:
  84. """按桌面客户端生命周期开关「强制保持显示器常亮」。
  85. SetThreadExecutionState 是线程级状态:ES_CONTINUOUS 保持该线程的请求,直到
  86. 再次调用清除。OAS worker 的任务在同一长驻线程内启停客户端,因此这里设置即可。
  87. 注意 ES_DISPLAY_REQUIRED 只「阻止未来关闭」,屏幕若已因电源超时熄灭,必须先用
  88. SC_MONITORPOWER(-1) 广播把显示器物理点亮,否则 BitBlt 仍返回黑帧。
  89. """
  90. if enable:
  91. # 物理点亮:SC_MONITORPOWER(-1) 单独发消息对部分显示器/驱动不触发硬件唤醒
  92. # (实测只发它屏幕仍黑),必须再模拟一次无害键盘输入与鼠标移动,产生真实
  93. # 输入事件才能真正点亮。VK_F15(0x7E) 无副作用,不会干扰游戏。
  94. try:
  95. # 必须用 SendMessageTimeoutW 而不是 SendMessageW:目标是
  96. # HWND_BROADCAST(0xFFFF),SendMessageW 会同步等系统里每一个顶层窗口
  97. # 处理完才返回,只要有一个窗口消息循环繁忙或无响应就永久阻塞调用线程
  98. # (实测 pytest 里这一行挂死 26 分钟不返回,生产上等于 worker 线程卡住)。
  99. # SMTO_ABORTIFHUNG(0x0002) 遇到无响应窗口直接放弃,1000ms 上限兜底。
  100. ctypes.windll.user32.SendMessageTimeoutW(
  101. 0xFFFF, 0x0111, 0xF170, -1, 0x0002, 1000, None)
  102. except Exception as e:
  103. logger.warning(f'SC_MONITORPOWER wake failed: {e}')
  104. try:
  105. user32 = ctypes.windll.user32
  106. user32.keybd_event(0x7E, 0, 0, 0)
  107. user32.keybd_event(0x7E, 0, 2, 0)
  108. user32.SetCursorPos(400, 300)
  109. except Exception as e:
  110. logger.warning(f'wake input failed: {e}')
  111. state = ES_CONTINUOUS | (ES_DISPLAY_REQUIRED if enable else 0)
  112. try:
  113. ctypes.windll.kernel32.SetThreadExecutionState(state)
  114. logger.info(f'Desktop screen keep-awake {"ON" if enable else "OFF"}')
  115. except Exception as e:
  116. logger.warning(f'SetThreadExecutionState({enable}) failed: {e}')
  117. def _window_total_size(width: int, height: int, style: int, ex_style: int) -> tuple:
  118. """用 user32.AdjustWindowRectEx 计算包含标题栏/边框的窗口总尺寸 (w, h)。
  119. pywin32 未导出 AdjustWindowRectEx,故用 ctypes 调用。
  120. """
  121. user32 = ctypes.windll.user32
  122. class RECT(Structure):
  123. _fields_ = [('left', c_long), ('top', c_long), ('right', c_long), ('bottom', c_long)]
  124. user32.AdjustWindowRectEx.argtypes = [POINTER(RECT), c_long, c_long, c_long]
  125. user32.AdjustWindowRectEx.restype = wintypes.BOOL
  126. rect = RECT(0, 0, width, height)
  127. user32.AdjustWindowRectEx(byref(rect), style, False, ex_style)
  128. return rect.right - rect.left, rect.bottom - rect.top
  129. def _desktop_process_image(pid) -> str:
  130. """返回进程 exe 完整路径;打开/查询失败(已退出、权限)返回空串。"""
  131. kernel32 = ctypes.windll.kernel32
  132. # PROCESS_QUERY_LIMITED_INFORMATION
  133. handle = kernel32.OpenProcess(0x1000, False, int(pid))
  134. if not handle:
  135. return ''
  136. try:
  137. buf = ctypes.create_unicode_buffer(520)
  138. size = ctypes.c_ulong(520)
  139. if kernel32.QueryFullProcessImageNameW(handle, 0, buf, ctypes.byref(size)):
  140. return buf.value
  141. return ''
  142. finally:
  143. kernel32.CloseHandle(handle)
  144. def _desktop_pid_under_root(pid, root) -> bool:
  145. """窗口归属进程的 exe 是否位于客户端安装目录之下。
  146. 自动启动绑定时用于排除同标题的模拟器窗口(MuMu 专版窗口标题也在
  147. DESKTOP_WINDOW_TITLES 内),保证绑到的一定是安装目录拉起的客户端进程。
  148. """
  149. exe = _desktop_process_image(pid)
  150. if not exe:
  151. return False
  152. root = os.path.normcase(os.path.normpath(root))
  153. exe = os.path.normcase(os.path.normpath(exe))
  154. return exe.startswith(root + os.sep)
  155. def list_desktop_windows() -> list:
  156. """枚举当前所有桌面客户端窗口。
  157. 返回 [{'pid': int, 'title': str, 'x': int, 'y': int}],按屏幕位置排序。
  158. 桌面客户端多开时窗口标题完全相同,只能靠 PID 区分,附带左上角坐标是为了
  159. 让用户在界面上按"窗口摆在哪"对号入座。按坐标排序保证同一组窗口每次枚举
  160. 顺序稳定(EnumWindows 的返回顺序随 Z 序变化)。
  161. """
  162. def enum_cb(hwnd, param):
  163. param.append(hwnd)
  164. return True
  165. handles = []
  166. EnumWindows(enum_cb, handles)
  167. result = []
  168. for hwnd in handles:
  169. if GetWindowText(hwnd) not in DESKTOP_WINDOW_TITLES:
  170. continue
  171. try:
  172. rect = GetWindowRect(hwnd)
  173. except Exception:
  174. # 窗口在枚举与取矩形之间被关闭,跳过即可
  175. continue
  176. result.append({
  177. 'pid': GetWindowThreadProcessId(hwnd)[1],
  178. 'title': GetWindowText(hwnd),
  179. 'hwnd': hwnd,
  180. 'x': rect[0],
  181. 'y': rect[1],
  182. })
  183. result.sort(key=lambda w: (w['x'], w['y'], w['pid']))
  184. return result
  185. def desktop_window_option(window: dict) -> str:
  186. """把窗口信息格式化成界面下拉项文本,形如 `27272 (154,38)`。
  187. 不显示窗口标题:桌面客户端多开时标题完全相同,且中文字样在英文界面里冗余。
  188. PID 放在最前,desktop_option2pid 只认第一段数字,坐标纯属给用户辨识用,
  189. 改动展示格式不会影响解析。
  190. """
  191. return f"{window['pid']} ({window['x']},{window['y']})"
  192. def desktop_option2pid(option: str) -> str:
  193. """从下拉项文本中取回纯 PID;取不到时返回空串。
  194. 界面回传的是展示文本,但落盘的 handle 必须是纯 PID(Handle 按数字消费),
  195. 因此写入配置前统一在这里剥掉标题与坐标。用户手工填的纯数字原样通过。
  196. """
  197. if not option:
  198. return ''
  199. matched = re.match(r'\s*(\d+)', str(option))
  200. return matched.group(1) if matched else ''
  201. class DesktopWindow:
  202. def find_desktop_window_by_pid(self, pid) -> int:
  203. """按 PID 查找桌面客户端窗口,返回窗口句柄;未找到抛 EmulatorNotRunningError。
  204. 「找不到窗口」记 warning 而非 error:本方法的调用方多为探测存在性
  205. (desktop_window_exists 判断是否需要重拉、_desktop_wait_closed 确认已关闭),
  206. 找不到是正常答案。真正的故障由上层在拿到 EmulatorNotRunningError 后判定,
  207. 这样真故障不会被淹没在每轮任务收尾都出现的噪音里。
  208. 同一 PID 下可能同时存在多个标题命中的顶层窗口(客户端多开共用同一标题;
  209. 新版 MuMu 内核客户端启动期还带着启动器残留窗口),取客户区最大者即可。
  210. 这里刻意**不设客户区面积下限**:窗口被最小化时客户区是 0x0,但客户端仍在
  211. 运行,还原交给 desktop_window_restore_if_minimized。用面积下限去宣布「未运行」
  212. 会把这个正常挂着的客户端判成掉线 → 触发误重拉并把配置 handle 覆盖成新实例
  213. (真机实测的循环就是这么起来的),而 BitBlt 截图前本来就会先把窗口还原。
  214. """
  215. try:
  216. pid_int = int(str(pid))
  217. except (TypeError, ValueError):
  218. logger.error(f'Invalid desktop PID: {pid}')
  219. raise EmulatorNotRunningError(f'Invalid desktop client PID: {pid}')
  220. def enum_cb(hwnd, param):
  221. param.append(hwnd)
  222. return True
  223. windows = []
  224. EnumWindows(enum_cb, windows)
  225. matches = []
  226. for hwnd in windows:
  227. if GetWindowText(hwnd) in DESKTOP_WINDOW_TITLES:
  228. _, win_pid = GetWindowThreadProcessId(hwnd)
  229. if win_pid == pid_int:
  230. matches.append(hwnd)
  231. # 同 PID 的多个候选里取客户区最大者:正常渲染窗口面积最大,启动器残留/
  232. # 最小化窗口(客户区 0x0)会排在后面。读不到客户区的(枚举与取值之间被销毁)
  233. # 直接跳过,全部读不到才算未找到
  234. best, best_area = 0, -1
  235. for hwnd in matches:
  236. try:
  237. cl, ct, cr, cb = GetClientRect(hwnd)
  238. area = (cr - cl) * (cb - ct)
  239. except Exception:
  240. continue
  241. if area > best_area:
  242. best, best_area = hwnd, area
  243. if best:
  244. return best
  245. logger.warning(f'Desktop client window not found, PID={pid}')
  246. raise EmulatorNotRunningError(f'Desktop client window not found, PID={pid}')
  247. def _desktop_best_window(self, pid, fallback: int = 0) -> int:
  248. """取指定 PID 下客户区最大的候选窗口;查不到时回退 fallback。
  249. 用于自动启动完成时的句柄确定:同一 PID 可能既带启动器残留窗口又带真渲染窗口,
  250. 取客户区最大者才不会把截图绑到残壳上。
  251. """
  252. try:
  253. return self.find_desktop_window_by_pid(pid)
  254. except EmulatorNotRunningError:
  255. return fallback
  256. def desktop_pid(self):
  257. """返回当前桌面客户端 PID(int);取不到返回 None。
  258. 优先用实例 root_handle(运行时自动启动绑定后的新 PID),未设置时回退配置里的
  259. handle。本会话的 PID 判断必须以实例状态为准,否则重新拉起后会误判。
  260. """
  261. pid = getattr(self, 'root_handle', None) or self.config.script.device.handle
  262. try:
  263. return int(str(pid))
  264. except (TypeError, ValueError):
  265. return None
  266. def find_desktop_login_popup(self) -> int:
  267. """按 PID + 类名查找 MPay 账号登录弹窗,返回句柄;没有则返回 0。
  268. 弹窗与游戏主窗口同 PID 但是独立顶层窗口(owner 为主窗口,非子窗口),
  269. 没有子控件可枚举,只能按窗口类名定位。
  270. 按 PID 过滤保证多开时各实例只处理自己客户端的弹窗。
  271. 主窗口 BitBlt 是否包含这个 owner 窗口受桌面合成状态影响,同一个弹窗可能在
  272. 不同错误截图中出现或消失,所以登录状态不能依赖截图判断。
  273. 改按「HWND 是否仍存活」判断而不再过滤 IsWindowVisible:真机验证过已登录的
  274. 客户端全系统枚举不到任何 MPAY_LOGIN 顶层窗口,说明客户端确认弹窗后是销毁它、
  275. 而非隐藏。因此 HWND 存活即代表尚未登录。
  276. """
  277. pid_int = self.desktop_pid()
  278. if pid_int is None:
  279. return 0
  280. def enum_cb(hwnd, param):
  281. param.append(hwnd)
  282. return True
  283. windows = []
  284. EnumWindows(enum_cb, windows)
  285. for hwnd in windows:
  286. try:
  287. if GetClassName(hwnd) != DESKTOP_LOGIN_POPUP_CLASS:
  288. continue
  289. if GetWindowThreadProcessId(hwnd)[1] == pid_int:
  290. return hwnd
  291. except Exception:
  292. # 窗口在枚举与取属性之间被关闭,跳过即可
  293. continue
  294. return 0
  295. def desktop_confirm_login_popup(self, wait: float = 15.0) -> bool:
  296. """向 MPay 登录弹窗发送回车,并确认对应 HWND 已真实消失。
  297. 弹窗是 DirectUI 独立顶层窗口,"进入游戏"只是绘制出来的像素、没有真实控件,
  298. 实测后台鼠标消息(WM_MOUSEMOVE/LBUTTONDOWN/LBUTTONUP,Post 与 Send 都试过)
  299. 完全无响应;同步与异步回车在无前台焦点时均可触发默认按钮。因此这里只发回车,
  300. 并在 wait 秒内轮询确认弹窗 HWND 真的消失。
  301. 返回 True 表示弹窗确实已关闭;False 表示没有弹窗,或超时后弹窗仍然存活。
  302. """
  303. if not self.find_desktop_login_popup():
  304. return False
  305. logger.info('Desktop MPay login popup found, press Enter to enter game')
  306. deadline = time.time() + wait
  307. while time.time() < deadline:
  308. hwnd = self.find_desktop_login_popup()
  309. if not hwnd:
  310. logger.info('Desktop MPay login popup confirmed closed')
  311. return True
  312. self._desktop_send_enter(hwnd)
  313. time.sleep(1)
  314. logger.warning(f'Desktop MPay login popup still present after {wait}s, Enter had no effect')
  315. return False
  316. def desktop_window_exists(self) -> bool:
  317. """桌面模式:目标 PID 对应窗口仍存在即视为客户端运行中。
  318. 只判「标题命中的顶层窗口在不在」,不看客户区尺寸——窗口被最小化或被遮挡时
  319. 客户端仍在运行,截图方法会先把窗口还原回来再取帧。
  320. 优先用实例 root_handle(运行时自动启动绑定后的新 PID),未设置时回退配置里的
  321. handle。本会话的窗口存在性判断必须以实例状态为准,否则重新拉起后会误判为未运行。
  322. """
  323. pid = getattr(self, 'root_handle', None) or self.config.script.device.handle
  324. try:
  325. self.find_desktop_window_by_pid(pid)
  326. return True
  327. except EmulatorNotRunningError:
  328. return False
  329. def _desktop_wait_window_ready(self, pid, wait: float = DESKTOP_WINDOW_READY_WAIT) -> bool:
  330. """在 wait 秒内等待指定 PID 的客户端窗口出现;超时返回 False。
  331. 用于「进程还活着、窗口暂时不可见」的空窗期。这段时间只能等,不能重新启动
  332. 客户端:真正在跑的那个实例会变成多开或被顶掉,配置里的 handle 也会被新实例
  333. 覆盖,从此再也绑不回原来的客户端。
  334. """
  335. deadline = time.time() + wait
  336. while True:
  337. try:
  338. self.find_desktop_window_by_pid(pid)
  339. return True
  340. except EmulatorNotRunningError:
  341. pass
  342. if time.time() >= deadline:
  343. logger.error(f'Desktop client process alive but window not ready in {wait}s, PID={pid}')
  344. return False
  345. time.sleep(DESKTOP_WINDOW_READY_POLL_INTERVAL)
  346. def desktop_client_offset(self) -> tuple:
  347. """返回客户区在窗口 DC 内的偏移 (x, y),用于 BitBlt 扣除标题栏/边框。"""
  348. with dpi_awareness():
  349. window_rect = GetWindowRect(self.screenshot_handle_num)
  350. client_origin = ClientToScreen(self.screenshot_handle_num, (0, 0))
  351. return client_origin[0] - window_rect[0], client_origin[1] - window_rect[1]
  352. def desktop_client_size(self) -> tuple:
  353. """返回桌面客户端窗口客户区的物理像素尺寸 (width, height)。"""
  354. with dpi_awareness():
  355. rect = GetClientRect(self.screenshot_handle_num)
  356. return rect[2] - rect[0], rect[3] - rect[1]
  357. def desktop_client_size_virtual(self) -> tuple:
  358. """返回客户区在 DPI 虚拟化空间下的尺寸 (width, height)。
  359. OAS 进程未声明 DPI 感知,PostMessage 的 lParam 会被系统按该空间解释,
  360. 因此后台输入的坐标必须换算到这里,而不是截图所用的物理空间。
  361. """
  362. rect = GetClientRect(self.screenshot_handle_num)
  363. return rect[2] - rect[0], rect[3] - rect[1]
  364. def _desktop_client_size(self, hwnd):
  365. """读窗口客户区物理尺寸,句柄已失效返回 None。
  366. 客户端从登录界面切到游戏主窗口时会销毁重建渲染窗口,因此调整窗口期间的任何
  367. 一次 Win32 调用都可能撞上失效句柄。GetClientRect 对废句柄抛
  368. (1400, '无效的窗口句柄'),不接住会直接崩掉整个脚本进程。
  369. """
  370. if not IsWindow(hwnd):
  371. return None
  372. try:
  373. rect = GetClientRect(hwnd)
  374. except Exception as e:
  375. logger.warning(f'GetClientRect failed (hwnd={hwnd}): {e}')
  376. return None
  377. return rect[2] - rect[0], rect[3] - rect[1]
  378. def _desktop_clear_handle_cache(self) -> None:
  379. """失效截图相关 cached_property,使其按当前 root_handle_num 重新求值。
  380. 桌面模式下 screenshot_handle_num 直接返回 root_handle_num,但它是
  381. cached_property:客户端重开后 root_handle_num 已换成新 hwnd,缓存仍指向
  382. 旧句柄,截图时 GetClientRect 会拿废句柄抛 (1400)。
  383. """
  384. for prop in ('screenshot_handle_num', 'screenshot_size'):
  385. if prop in self.__dict__:
  386. del_cached_property(self, prop)
  387. def _desktop_rebind_window(self) -> bool:
  388. """按 PID 重新查找客户端窗口并绑定新 hwnd,返回是否绑定成功。
  389. 用于两类句柄刷新:窗口重建(登录界面切游戏主窗口)后更换句柄,以及同一 PID
  390. 下换到客户区更大的那个候选窗口。进程还活着,不需要重拉客户端。
  391. """
  392. try:
  393. hwnd = self.find_desktop_window_by_pid(self.root_handle)
  394. except EmulatorNotRunningError:
  395. return False
  396. if hwnd != self.root_handle_num:
  397. logger.info(f'Desktop window handle changed, rebind hwnd {self.root_handle_num} -> {hwnd}')
  398. self.root_handle_num = hwnd
  399. self._desktop_clear_handle_cache()
  400. return True
  401. def desktop_window_set_size(self, width: int = 1280, height: int = 720) -> bool:
  402. """桌面模式:检测窗口客户区尺寸,非目标大小时用 SetWindowPos 调整到 width×height。
  403. 窗口位置保持不变;返回是否执行了调整。全过程在 DPI 感知上下文内完成,
  404. GetClientRect/SetWindowPos 处理的都是物理像素,因此目标尺寸无需按缩放比换算,
  405. 调整后客户区物理尺寸恰为 width×height,游戏画面与资产 1:1 对应。
  406. 客户端确认登录弹窗后会销毁登录界面、重建游戏主窗口,调整过程中旧 hwnd 随时可能
  407. 失效。此时不抛异常也不重拉客户端(进程还活着),而是按 PID 重新绑定重建后的
  408. 窗口再试,最多 DESKTOP_RESIZE_ATTEMPTS 轮。
  409. """
  410. if not getattr(self, 'is_desktop_window', False):
  411. return False
  412. for attempt in range(1, DESKTOP_RESIZE_ATTEMPTS + 1):
  413. result = self._desktop_try_set_size(width, height)
  414. if result is not None:
  415. return result
  416. if attempt >= DESKTOP_RESIZE_ATTEMPTS:
  417. break
  418. logger.info(f'Desktop window invalid, rebind and retry resize '
  419. f'({attempt}/{DESKTOP_RESIZE_ATTEMPTS})')
  420. time.sleep(DESKTOP_RESIZE_RETRY_INTERVAL)
  421. self._desktop_rebind_window()
  422. logger.warning(f'Desktop window resize gave up after {DESKTOP_RESIZE_ATTEMPTS} attempts, '
  423. f'window kept invalid')
  424. return False
  425. def _desktop_try_set_size(self, width: int, height: int):
  426. """单轮尝试调整窗口尺寸。
  427. 返回 True/False 表示本轮已得出结论(是否执行了调整);返回 None 表示句柄失效,
  428. 需由调用方重新绑定窗口后再试。三态的意义在于把「尺寸本来就对」(False)和
  429. 「窗口正在重建」(None)区分开,否则前者会白等重试。
  430. """
  431. hwnd = self.root_handle_num
  432. if not hwnd or not IsWindow(hwnd):
  433. logger.warning(f'Desktop window handle invalid (hwnd={hwnd})')
  434. return None
  435. with dpi_awareness():
  436. size = self._desktop_client_size(hwnd)
  437. if size is None:
  438. logger.warning(f'Desktop window vanished before resize (hwnd={hwnd})')
  439. return None
  440. client_w, client_h = size
  441. logger.info(f'Desktop client size: {client_w}x{client_h} (physical), target {width}x{height}')
  442. if client_w == width and client_h == height:
  443. logger.info('Desktop client size already matches target')
  444. return False
  445. # 用 AdjustWindowRectEx 精确计算含标题栏/边框的窗口总尺寸
  446. style = GetWindowLong(hwnd, GWL_STYLE)
  447. ex_style = GetWindowLong(hwnd, GWL_EXSTYLE)
  448. total_w, total_h = _window_total_size(width, height, style, ex_style)
  449. logger.info(f'Resize desktop window to {total_w}x{total_h} to get client {width}x{height}')
  450. try:
  451. SetWindowPos(hwnd, HWND_TOP, 0, 0, total_w, total_h, SWP_NOMOVE | SWP_SHOWWINDOW)
  452. except Exception as e:
  453. # 拒绝访问通常是目标窗口权限更高(游戏以管理员运行)或客户端锁定窗口大小
  454. logger.error(f'SetWindowPos failed: {e}. '
  455. f'请以管理员身份运行 OAS,或手动把游戏窗口设为 1280x720')
  456. return False
  457. # 校准:SetWindowPos 后的实际客户区可能与目标差几像素,按差值持续修正。
  458. # SetWindowPos 本身可能正好撞上客户端重建窗口,因此每轮都要重新确认句柄有效
  459. for _ in range(5):
  460. size = self._desktop_client_size(hwnd)
  461. if size is None:
  462. logger.warning(f'Desktop window vanished during resize (hwnd={hwnd}), '
  463. f'client is rebuilding its window')
  464. return None
  465. cw, ch = size
  466. if cw == width and ch == height:
  467. return True
  468. total_w += width - cw
  469. total_h += height - ch
  470. logger.info(f'Calibrate desktop window to {total_w}x{total_h}, current client {cw}x{ch}')
  471. try:
  472. SetWindowPos(hwnd, HWND_TOP, 0, 0, total_w, total_h, SWP_NOMOVE | SWP_SHOWWINDOW)
  473. except Exception as e:
  474. logger.warning(f'SetWindowPos failed during calibration (hwnd={hwnd}): {e}')
  475. return None
  476. return True
  477. # ------------------------------------------------------------------ 桌面客户端自动生命周期
  478. def desktop_resolve_install_root(self) -> str:
  479. """解析桌面客户端安装目录:优先 desktop_game_path 配置,其次自动发现。
  480. 只认含 bin\\onmyoji.exe(或根目录 Launch.exe)的安装目录,找不到返回空串。
  481. 仅桌面模式调用,不影响模拟器流程。
  482. """
  483. configured = getattr(self.config.script.device, 'desktop_game_path', '') or ''
  484. if configured:
  485. root = self._desktop_root_from_path(configured)
  486. if root is not None:
  487. return str(root)
  488. logger.warning(f'desktop_game_path 配置无效: {configured},尝试自动发现')
  489. root = self._desktop_discover_install_root()
  490. return str(root) if root else ''
  491. @staticmethod
  492. def _desktop_root_from_path(value: str):
  493. """把用户填的路径归一化成安装目录;无效返回 None。"""
  494. path = Path(value).expanduser()
  495. if path.is_file():
  496. # 允许直接填 bin\\onmyoji.exe 或 Launch.exe 的完整路径
  497. if path.name.lower() == 'onmyoji.exe' and path.parent.name.lower() == 'bin':
  498. path = path.parent.parent
  499. elif path.name.lower() == 'launch.exe':
  500. path = path.parent
  501. else:
  502. path = path.parent
  503. candidate = path / 'bin' / 'onmyoji.exe'
  504. if candidate.is_file():
  505. return path.resolve()
  506. return None
  507. @staticmethod
  508. def _desktop_discover_install_root():
  509. """按 %ProgramFiles%\\Onmyoji 与注册表 Uninstall 的 InstallLocation 自动发现安装目录。"""
  510. for env in ('ProgramFiles', 'ProgramFiles(x86)'):
  511. raw = os.environ.get(env)
  512. if raw and (Path(raw) / 'Onmyoji' / 'bin' / 'onmyoji.exe').is_file():
  513. return (Path(raw) / 'Onmyoji').resolve()
  514. try:
  515. import winreg
  516. roots = (
  517. (winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'),
  518. (winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall'),
  519. (winreg.HKEY_CURRENT_USER, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'),
  520. )
  521. for hive, key_path in roots:
  522. try:
  523. with winreg.OpenKey(hive, key_path) as parent:
  524. for index in range(winreg.QueryInfoKey(parent)[0]):
  525. try:
  526. with winreg.OpenKey(parent, winreg.EnumKey(parent, index)) as child:
  527. display, _ = winreg.QueryValueEx(child, 'DisplayName')
  528. if '阴阳师' not in str(display) and 'Onmyoji' not in str(display):
  529. continue
  530. location, _ = winreg.QueryValueEx(child, 'InstallLocation')
  531. if location and (Path(location) / 'bin' / 'onmyoji.exe').is_file():
  532. return Path(location).resolve()
  533. except OSError:
  534. continue
  535. except OSError:
  536. continue
  537. except Exception:
  538. pass
  539. return None
  540. @staticmethod
  541. def desktop_game_exe(root) -> str:
  542. """返回游戏可执行文件路径;找不到返回空串。
  543. 顺序即优先级:必须优先游戏本体 bin/onmyoji.exe。
  544. Launch.exe 是登录器,它会再拉起 bin/onmyoji.exe,
  545. 导致双开且 OAS 绑定到登录器 PID 上找不到游戏窗口。
  546. """
  547. root = Path(root)
  548. for name in ('bin/onmyoji.exe', 'Launch.exe'):
  549. exe = root / name
  550. if exe.is_file():
  551. return str(exe)
  552. return ''
  553. def launch_desktop_client(self, timeout: int = 90) -> bool:
  554. """自动启动桌面客户端并绑定新窗口的 PID/HWND,成功返回 True。
  555. 单轮 = 启动 exe → 等新窗口出现并稳定 → 绑定其 PID/HWND。到此启动即完成;
  556. MPay 登录弹窗与进游戏属登录流程,由 Restart 的 app_handle_login 负责。
  557. timeout 内没等到窗口说明客户端起歪了(卡加载、崩在启动期等),强杀本轮进程后
  558. 整轮重跑一次;第二轮仍失败则记 error 返回 False,由上层停下等人工,不无限重试。
  559. 安装目录/exe 找不到属配置问题,重试无意义,直接返回 False。
  560. """
  561. root = self.desktop_resolve_install_root()
  562. if not root:
  563. logger.error('未找到阴阳师桌面客户端安装目录,请在 设置-Script-设备 中填写 desktop_game_path')
  564. return False
  565. exe = self.desktop_game_exe(root)
  566. if not exe:
  567. logger.error(f'未找到游戏程序(bin\\onmyoji.exe 或 Launch.exe):{root}')
  568. return False
  569. for attempt in (1, 2):
  570. pids = self._desktop_launch_attempt(exe, root, timeout, attempt)
  571. if pids is None:
  572. # Popen 本身失败,重试也起不来
  573. return False
  574. bound_pid, spawned_pid = pids
  575. if bound_pid:
  576. # 启动成功也要记住本轮拉起的全部 PID:onmyoji.exe 是启动器,它会派生出
  577. # 真正的游戏窗口进程后自己继续存活(实测启动器 8932 派生窗口进程 6816,
  578. # 89 线程 42s CPU 却无窗口)。OAS 靠枚举窗口只绑到窗口进程,关闭时若只杀
  579. # 它,启动器就成了无主残留。这里留档,交给 desktop_stop_client 一并清理
  580. self._desktop_spawned_pids = set(spawned_pid)
  581. # 客户端已拉起,强制保持显示器常亮,防止电源超时关屏导致截图黑帧卡死
  582. desktop_keep_screen_on(True)
  583. return True
  584. if attempt == 1:
  585. # 只杀本轮确切启动的进程:绑定阶段就失败时 root_handle 仍是上一次的陈旧
  586. # PID,直接调 desktop_force_kill 会误杀(PID 可能已被系统复用)
  587. logger.warning('第 1 轮启动未就绪,清理本轮客户端后重试')
  588. self._desktop_kill_pids(spawned_pid)
  589. logger.error('桌面客户端连续 2 轮启动均未就绪,请检查客户端状态与机器负载')
  590. return False
  591. def _desktop_launch_attempt(self, exe: str, root: str, timeout: int, attempt: int):
  592. """启动客户端并绑定其窗口的单轮尝试。
  593. 返回 (bound_pid, spawned_pid):bound_pid 非 0 表示本轮成功;spawned_pid 是本轮
  594. Popen 出的进程与绑定到的窗口 PID 集合,供失败清理精确定位。Popen 失败返回 None。
  595. """
  596. before_pids = {w['pid'] for w in list_desktop_windows()}
  597. logger.info(f'自动启动桌面客户端(第 {attempt} 轮): {exe}')
  598. spawned = set()
  599. try:
  600. proc = subprocess.Popen([exe], cwd=root,
  601. creationflags=getattr(subprocess, 'CREATE_NEW_PROCESS_GROUP', 0))
  602. spawned.add(proc.pid)
  603. except Exception as e:
  604. logger.error(f'启动桌面客户端失败: {e}')
  605. return None
  606. deadline = time.time() + timeout
  607. stable_hwnd = 0
  608. stable_count = 0
  609. while time.time() < deadline:
  610. # 候选必须落在安装目录下的进程:客户端新旧版本窗口标题不同
  611. # ("阴阳师-网易游戏" / "阴阳师-MuMu模拟器专版"),启动等待期内任何
  612. # 匹配标题的新窗口都会成为候选,按 exe 归属收口,避免绑到别的进程
  613. candidates = [w for w in list_desktop_windows()
  614. if w['pid'] not in before_pids
  615. and _desktop_pid_under_root(w['pid'], root)]
  616. if candidates:
  617. candidate = candidates[0]
  618. if candidate['hwnd'] == stable_hwnd:
  619. stable_count += 1
  620. else:
  621. stable_hwnd = candidate['hwnd']
  622. stable_count = 1
  623. if stable_count >= 2:
  624. # 同一 PID 可能还带着启动器残留窗口(客户区极小),句柄统一取
  625. # 客户区最大者,否则截图会绑到残壳上(BitBlt 取不到画面)
  626. hwnd = self._desktop_best_window(candidate['pid'], candidate['hwnd'])
  627. self.desktop_bind_pid(candidate['pid'], hwnd)
  628. spawned.add(candidate['pid'])
  629. logger.info(f'桌面客户端已自动启动并绑定 PID={candidate["pid"]}')
  630. # 到这里启动就完成了:进程在跑、窗口句柄已绑定。
  631. # MPay 登录弹窗与进游戏属于登录流程,由 Restart 的 app_handle_login
  632. # 负责(登录循环每轮都复查弹窗,中途冒出来也能接住)。
  633. return candidate['pid'], spawned
  634. time.sleep(1)
  635. logger.warning(f'桌面客户端进程已启动,但 {timeout} 秒内未识别到游戏窗口')
  636. return 0, spawned
  637. def _desktop_kill_pids(self, pids) -> None:
  638. """强杀指定 PID 集合(本轮启动失败的清理),逐个容错并验证真的退出。"""
  639. kernel32 = ctypes.windll.kernel32
  640. wait = self._desktop_close_wait_seconds()
  641. for pid in pids:
  642. try:
  643. pid_int = int(pid)
  644. except (TypeError, ValueError):
  645. continue
  646. for attempt in range(1, DESKTOP_KILL_ATTEMPTS + 1):
  647. # PROCESS_TERMINATE(0x0001)
  648. handle = kernel32.OpenProcess(0x0001, False, pid_int)
  649. if not handle:
  650. # 进程已自行退出
  651. break
  652. try:
  653. kernel32.TerminateProcess(handle, 0)
  654. logger.info(f'清理桌面客户端 PID={pid_int}')
  655. finally:
  656. kernel32.CloseHandle(handle)
  657. # 杀完必须确认进程真的没了,被拒或正在退出都会让下一轮启动撞上残留
  658. if self._desktop_wait_pid_gone(pid_int, wait):
  659. break
  660. logger.warning(f'桌面客户端 PID={pid_int} 强杀后仍存活,重试 '
  661. f'({attempt}/{DESKTOP_KILL_ATTEMPTS})')
  662. else:
  663. logger.error(f'桌面客户端 PID={pid_int} 无法清理,可能需要手动结束进程')
  664. # 等窗口真的消失,避免残留窗口干扰下一轮的新窗口识别
  665. self._desktop_wait_closed(wait)
  666. def _desktop_wait_pid_gone(self, pid, wait: float) -> bool:
  667. """在 wait 秒内等待指定进程退出,返回是否已退出。"""
  668. deadline = time.time() + wait
  669. while True:
  670. if not self._desktop_pid_alive(pid):
  671. return True
  672. if time.time() >= deadline:
  673. return False
  674. time.sleep(DESKTOP_KILL_POLL_INTERVAL)
  675. def desktop_bind_pid(self, pid, hwnd=0) -> None:
  676. """把新 PID/HWND 绑定到实例,并尽量持久化到配置。"""
  677. self.root_handle = str(pid)
  678. if hwnd:
  679. self.root_handle_num = hwnd
  680. self.root_handle_title = DESKTOP_WINDOW_TITLES[0]
  681. self.is_desktop_window = True
  682. # 换了新 hwnd,截图句柄缓存必须同步失效,否则截图仍走上一个客户端的废句柄
  683. self._desktop_clear_handle_cache()
  684. # 新绑定的客户端刚启动,必然未登录,需先走 restart 登录流程
  685. self._desktop_login_done = False
  686. logger.info(f'Desktop client bound: PID={pid}, hwnd={hwnd}')
  687. try:
  688. self.config.script.device.handle = str(pid)
  689. self.config.save()
  690. except Exception as e:
  691. logger.warning(f'持久化桌面 PID 到配置失败: {e}')
  692. def _desktop_send_enter(self, hwnd) -> None:
  693. """向窗口发送回车键,用于确认 MPay 账号登录弹窗的默认按钮"进入游戏"。
  694. 窗口可能在两条消息之间被销毁(回车已生效),此时忽略异常即可。
  695. """
  696. try:
  697. SendMessage(hwnd, WM_KEYDOWN, VK_RETURN, 0)
  698. SendMessage(hwnd, WM_KEYUP, VK_RETURN, 0)
  699. except Exception as e:
  700. logger.info(f'Send Enter to window {hwnd} failed (window may be closed): {e}')
  701. def _desktop_pid_alive(self, pid) -> bool:
  702. """进程是否还活着。无法判定时按「还活着」返回,宁可多等一轮也不误报已关闭。
  703. 不能只看 OpenProcess 是否成功:进程已退出但仍有内核对象引用时 OpenProcess
  704. 照样返回句柄,必须再用 GetExitCodeProcess 看退出码是否还是 STILL_ACTIVE(259)。
  705. 窗口枚举不能替代这里——强杀被拒时窗口可能已销毁而进程还在,只验窗口会误判。
  706. """
  707. try:
  708. pid_int = int(str(pid))
  709. except (TypeError, ValueError):
  710. return False
  711. kernel32 = ctypes.windll.kernel32
  712. # PROCESS_QUERY_LIMITED_INFORMATION(0x1000),比 QUERY_INFORMATION 权限要求更低
  713. handle = kernel32.OpenProcess(0x1000, False, pid_int)
  714. if not handle:
  715. # 打不开通常就是进程已退出;权限不足时也走这里,交给窗口检查兜底
  716. return False
  717. try:
  718. code = ctypes.c_ulong()
  719. if not kernel32.GetExitCodeProcess(handle, ctypes.byref(code)):
  720. return True
  721. return code.value == 259 # STILL_ACTIVE
  722. finally:
  723. kernel32.CloseHandle(handle)
  724. def _desktop_wait_closed(self, wait: float) -> bool:
  725. """在 wait 秒内轮询等待桌面客户端窗口消失,返回是否已关闭。"""
  726. deadline = time.time() + wait
  727. while True:
  728. if not self.desktop_window_exists():
  729. return True
  730. if time.time() >= deadline:
  731. return False
  732. time.sleep(0.5)
  733. def _desktop_wait_released(self, pid, wait: float) -> bool:
  734. """在 wait 秒内等待客户端真正释放:窗口消失 **且** 进程退出。
  735. 两个条件都要,缺一个都可能是假关闭:
  736. - 只验窗口:强杀被拒时窗口已销毁但进程还在,会漏掉残留进程
  737. - 只验进程:进程刚退出时窗口可能还在被系统回收,下一轮新窗口识别会撞上
  738. """
  739. deadline = time.time() + wait
  740. while True:
  741. if not self.desktop_window_exists() and not self._desktop_pid_alive(pid):
  742. return True
  743. if time.time() >= deadline:
  744. return False
  745. time.sleep(DESKTOP_KILL_POLL_INTERVAL)
  746. def desktop_stop_client(self) -> bool:
  747. """关闭桌面客户端:强杀进程并验证真的释放,返回是否确认关闭。
  748. 客户端的退出确认框画在游戏窗口内部(不是独立顶层窗口),实测回车确认经常无效
  749. (进程不退出、主窗口只是被移到屏幕外),走 WM_CLOSE + 确认反而要多等几秒还未必
  750. 关得掉,因此这里不发任何窗口消息,直接强杀进程。
  751. 强杀不等于已关闭:TerminateProcess 可能因权限被拒(本机出现过 (5, '拒绝访问。')),
  752. 进程也可能正在退出还没消失。所以每轮杀完都验证「窗口消失 且 进程退出」,没释放
  753. 就再杀一轮,全部轮次用尽仍在则返回 False——调用方据此决定是重建还是交人工,
  754. 绝不能发完 kill 指令就当成功返回。
  755. 关闭后保留原 PID 在配置里;下次检测到该 PID 无效(客户端未运行)时,
  756. 由启动/重拉链路重启客户端并把配置更新为重启后的新 PID。
  757. """
  758. # 客户端关闭后必然未登录,下次启动需重新走登录流程
  759. self._desktop_login_done = False
  760. # PID 要在清理句柄前取,后面的验证全靠它
  761. pid = getattr(self, 'root_handle', None) or self.config.script.device.handle
  762. hwnd = self.root_handle_num
  763. if (not hwnd or not IsWindow(hwnd)) and not self._desktop_pid_alive(pid):
  764. logger.info('Desktop client not running, skip stop')
  765. # 客户端已不在,解除强制亮屏,允许系统恢复正常的显示器电源管理
  766. desktop_keep_screen_on(False)
  767. self._reset_desktop_handle_state()
  768. # 窗口进程已没了也要收启动器:它无窗口,只看窗口永远发现不了
  769. self._desktop_kill_spawned_leftovers(pid)
  770. return True
  771. wait = self._desktop_close_wait_seconds()
  772. released = False
  773. for attempt in range(1, DESKTOP_KILL_ATTEMPTS + 1):
  774. logger.info(f'Stopping desktop client: force kill '
  775. f'({attempt}/{DESKTOP_KILL_ATTEMPTS}, PID={pid})')
  776. self.desktop_force_kill()
  777. if self._desktop_wait_released(pid, wait):
  778. logger.info(f'Desktop client released (PID={pid})')
  779. # 客户端已确认关闭,解除强制亮屏,允许系统恢复正常的显示器电源管理
  780. desktop_keep_screen_on(False)
  781. released = True
  782. break
  783. logger.warning(f'Desktop client PID={pid} still present after {wait}s, retry kill')
  784. if not released:
  785. # 到这里客户端确实没关掉:句柄状态照常清零(它已不可信),但把失败如实报出去
  786. logger.error(f'Desktop client PID={pid} not released after '
  787. f'{DESKTOP_KILL_ATTEMPTS} force kill attempts, manual cleanup needed')
  788. self._reset_desktop_handle_state()
  789. # 无论窗口进程是否关掉,本轮自己拉起的启动器都要一并收掉
  790. leftovers_cleared = self._desktop_kill_spawned_leftovers(pid)
  791. return released and leftovers_cleared
  792. def _desktop_kill_spawned_leftovers(self, bound_pid) -> bool:
  793. """清理本次自己拉起、但没被绑定的客户端进程,返回是否已全部清掉。
  794. onmyoji.exe 是启动器:Popen 起来后它派生真正的游戏窗口进程,自己继续存活且
  795. 没有窗口(实测启动器 89 线程、42s CPU、主窗口句柄为 0)。OAS 靠枚举游戏窗口
  796. 绑定,只会绑到窗口进程,关闭时若只杀它,启动器就成了无主残留——既占内存,
  797. 也让下一轮启动的窗口识别多一个干扰源。这些 PID 由 launch_desktop_client
  798. 在启动成功时留档到 _desktop_spawned_pids。
  799. """
  800. spawned = getattr(self, '_desktop_spawned_pids', None)
  801. if not spawned:
  802. return True
  803. try:
  804. bound = int(str(bound_pid))
  805. except (TypeError, ValueError):
  806. bound = None
  807. # 已绑定的那个由主流程负责,这里只收剩下的
  808. leftovers = {p for p in spawned if p != bound and self._desktop_pid_alive(p)}
  809. self._desktop_spawned_pids = set()
  810. if not leftovers:
  811. return True
  812. logger.info(f'清理本次启动残留的客户端进程(启动器): {sorted(leftovers)}')
  813. self._desktop_kill_pids(leftovers)
  814. still = {p for p in leftovers if self._desktop_pid_alive(p)}
  815. if still:
  816. logger.error(f'客户端启动器进程无法清理: {sorted(still)},可能需要手动结束')
  817. return False
  818. return True
  819. def _reset_desktop_handle_state(self) -> None:
  820. """清零桌面窗口句柄与截图句柄缓存。
  821. 进程已杀,hwnd 随窗口销毁立即失效。必须清零,否则后续在同一个 device 对象
  822. 生命周期内被唤醒的任务(如配置变更触发的即时调度)会跳过 Handle.__init__,
  823. 直接拿这个废句柄去 GetClientRect,抛 (1400, '无效的窗口句柄') 搞崩整个进程。
  824. """
  825. self.root_handle_num = 0
  826. # 截图句柄缓存指向的也是刚被销毁的窗口,一并失效
  827. self._desktop_clear_handle_cache()
  828. def _desktop_close_wait_seconds(self) -> int:
  829. """关闭游戏等待时长(秒),读 config.script.optimization.close_game_wait_duration。"""
  830. try:
  831. t = self.config.script.optimization.close_game_wait_duration
  832. return t.hour * 3600 + t.minute * 60 + t.second
  833. except Exception:
  834. return 10
  835. def desktop_force_kill(self) -> None:
  836. """强杀桌面客户端进程(WM_CLOSE 超时未退出的兜底)。"""
  837. pid = getattr(self, 'root_handle', None) or self.config.script.device.handle
  838. try:
  839. pid_int = int(str(pid))
  840. except (TypeError, ValueError):
  841. logger.error(f'Invalid desktop PID: {pid}, skip force kill')
  842. return
  843. kernel32 = ctypes.windll.kernel32
  844. # PROCESS_TERMINATE(0x0001)
  845. handle = kernel32.OpenProcess(0x0001, False, pid_int)
  846. if not handle:
  847. # 进程已自行退出
  848. return
  849. try:
  850. kernel32.TerminateProcess(handle, 0)
  851. logger.info(f'Desktop client PID={pid_int} force terminated')
  852. finally:
  853. kernel32.CloseHandle(handle)
  854. def desktop_window_restore_if_minimized(self, wait: float = 3.0) -> bool:
  855. """桌面窗口被最小化(用户误操作)时还原并等待客户区恢复,返回是否发生过还原。
  856. 还原成功后若客户区尺寸偏离目标(1280x720),一并重校准,保证识别 1:1。
  857. """
  858. if not getattr(self, 'is_desktop_window', False):
  859. return False
  860. hwnd = self.root_handle_num
  861. if not hwnd or not IsIconic(hwnd):
  862. return False
  863. logger.warning('Desktop client window is minimized, restoring')
  864. ShowWindow(hwnd, SW_RESTORE)
  865. deadline = time.time() + wait
  866. restored = False
  867. while time.time() < deadline:
  868. with dpi_awareness():
  869. rect = GetClientRect(hwnd)
  870. if (rect[2] - rect[0]) > 0 and (rect[3] - rect[1]) > 0:
  871. restored = True
  872. break
  873. time.sleep(0.2)
  874. if restored:
  875. self.desktop_window_set_size()
  876. return restored