desktop_impl.py 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  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_prepare_profile`` /
  12. ``desktop_launch_instance`` / ``dpi_awareness`` 等)一并住在这里,外部调用方直接
  13. 从本模块导入,不经 handle.py 转出——避免"补丁打在转出别名上静默失效"。
  14. PID 生命周期约定:客户端进程 PID 每次重启都会变,因此它**不写配置**,只活在
  15. 运行时(实例 root_handle);配了档案目录时另在档案内写 oas_instance.json 状态
  16. 文件,供下次启动精确认领(多开必需,枚举无法区分多个同标题窗口的归属)。
  17. """
  18. import os
  19. import re
  20. import json
  21. import shutil
  22. import subprocess
  23. import time
  24. import ctypes
  25. from ctypes import c_long, byref, POINTER, Structure, wintypes
  26. from contextlib import contextmanager
  27. from pathlib import Path
  28. from win32api import SendMessage
  29. from win32process import GetWindowThreadProcessId
  30. from win32gui import (GetWindowText, EnumWindows, GetWindowRect, IsWindow,
  31. GetClientRect, ClientToScreen, GetWindowLong,
  32. SetWindowPos, GetClassName, IsIconic, ShowWindow,
  33. SetWindowText)
  34. from win32con import (WM_KEYDOWN, WM_KEYUP, VK_RETURN, GWL_STYLE, GWL_EXSTYLE,
  35. HWND_TOP, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, SWP_NOACTIVATE,
  36. SWP_SHOWWINDOW, SW_RESTORE)
  37. from module.base.decorator import del_cached_property
  38. from module.exception import EmulatorNotRunningError
  39. from module.logger import logger
  40. # 桌面客户端窗口标题(官方桌面版,多开共用同一标题)
  41. DESKTOP_WINDOW_TITLES = ('阴阳师-网易游戏', '阴阳师-MuMu模拟器专版')
  42. def desktop_window_titles(config=None) -> tuple:
  43. """本配置认可的窗口标题白名单:内置官方标题 + 自定义窗口标题。
  44. 自定义标题(script.desktop.window_title)非空时,OAS 绑定客户端时会把窗口
  45. 改名成它;此后**所有按标题找窗口的路径**都必须放行这个标题,否则改名后的
  46. 实例会被当成「窗口不存在」——desktop_window_exists 判掉线触发重拉、
  47. _desktop_locate_window 认领不到,多开直接乱套。
  48. """
  49. custom = ''
  50. if config is not None:
  51. try:
  52. custom = str(config.script.desktop.window_title or '').strip()
  53. except AttributeError:
  54. custom = ''
  55. return DESKTOP_WINDOW_TITLES + ((custom,) if custom else ())
  56. def desktop_rename_window(hwnd, config) -> bool:
  57. """把客户端窗口标题改成配置的自定义标题,返回是否实际改了名。
  58. 仅用于多开时在任务栏区分实例。客户端会在首次登录流程中自行重设一次标题,
  59. 故除绑定时的改名外,检测到 MPay 登录弹窗时补改一次;失败只记 warning,
  60. 标题不参与识别与点击。
  61. """
  62. if not hwnd:
  63. return False
  64. try:
  65. custom = str(config.script.desktop.window_title or '').strip()
  66. except AttributeError:
  67. return False
  68. if not custom:
  69. return False
  70. try:
  71. if GetWindowText(hwnd) == custom:
  72. return False
  73. SetWindowText(hwnd, custom)
  74. # 回读确认:win32gui.SetWindowText 对无效句柄不抛异常,不回读会把
  75. # 「没改成」记成「已改名」,排查时会被日志带偏
  76. if GetWindowText(hwnd) != custom:
  77. logger.warning(f'重命名桌面客户端窗口未生效(目标标题 {custom},不影响控制)')
  78. return False
  79. logger.info(f'Desktop window title renamed to: {custom}')
  80. return True
  81. except Exception as e:
  82. logger.warning(f'重命名桌面客户端窗口失败(不影响控制): {e}')
  83. return False
  84. # 「进程活着但窗口还没就绪」时的等待上限(秒)与轮询间隔。空窗期有两种:客户端
  85. # 启动期还没出窗口、确认 MPay 弹窗后销毁登录界面重建主窗口的那几秒。这段等待只
  86. # 轮询窗口,绝不重新启动进程——把「窗口暂时不在」当成「客户端没在运行」会拉起
  87. # 多余实例(单实例语义下用户正在用的那个会被顶掉),并把配置里的 handle 覆盖成新实例
  88. DESKTOP_WINDOW_READY_WAIT = 15
  89. DESKTOP_WINDOW_READY_POLL_INTERVAL = 0.5
  90. # 网易 MPay 账号登录弹窗的窗口类名。它是与游戏主窗口同 PID 的独立顶层窗口
  91. # (DirectUI 绘制,无子控件),不在游戏渲染面内,因此主窗口 BitBlt 截不到它,
  92. # 也无法用图像识别处理,只能按类名单独定位并注入消息。
  93. DESKTOP_LOGIN_POPUP_CLASS = 'MPAY_LOGIN'
  94. # 调整窗口尺寸时撞上客户端重建窗口的重试轮数与间隔(秒)。客户端确认登录弹窗后销毁
  95. # 登录界面、重建游戏主窗口,实测这段空窗期在几百毫秒到数秒之间,6 轮 × 1s 足够覆盖
  96. DESKTOP_RESIZE_ATTEMPTS = 6
  97. DESKTOP_RESIZE_RETRY_INTERVAL = 1.0
  98. # 关闭桌面客户端的强杀轮数。TerminateProcess 可能因权限被拒(实测本机出现过
  99. # (5, '拒绝访问。')),也可能进程正在退出但还没消失,因此杀完必须验证进程真的没了,
  100. # 没死就再杀一轮,而不是发完指令就当成功
  101. DESKTOP_KILL_ATTEMPTS = 3
  102. DESKTOP_KILL_POLL_INTERVAL = 0.5
  103. # ---- 多开档案(profile)隔离 ----
  104. # 档案内的只读大目录:junction 共享真实安装目录,不占空间、不重下资源
  105. DESKTOP_PROFILE_SHARED_DIRS = ('bin', 'bin_patch', 'res', 'thd', 'thdext1', 'zipres', '_check_preload_')
  106. # 档案内每实例独立的真实目录(Documents 内的子目录随后按 junction 共享)
  107. DESKTOP_PROFILE_ISOLATED_DIRS = ('Documents', 'cefLocalStorage')
  108. # 档案内「假用户主目录」子树。SDK 用 SHGetFolderPathW / SHGetSpecialFolderLocation 解析
  109. # %APPDATA%,这些 API 拿【进程环境的 USERPROFILE】展开注册表里的 REG_EXPAND_SZ
  110. # ("%USERPROFILE%\AppData\Roaming"),且目标目录必须真实存在,否则 API 直接失败
  111. DESKTOP_PROFILE_HOME_DIRS = (
  112. 'home/AppData/Roaming',
  113. 'home/AppData/Local',
  114. 'home/AppData/Local/Temp',
  115. 'home/AppData/LocalLow',
  116. 'home/Documents',
  117. )
  118. # QueryInformationJobObject 的 JobObjectBasicProcessIdList 信息类
  119. _JOB_OBJECT_BASIC_PROCESS_ID_LIST = 3
  120. # DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2,SetThreadDpiAwarenessContext 的入参
  121. _PER_MONITOR_AWARE_V2 = ctypes.c_void_p(-4)
  122. # 桌面客户端运行期间强制保持显示器常亮:桌面模式截图走 BitBlt,依赖 DWM 合成,
  123. # 屏幕一旦因电源超时关闭,DWM 停止合成,BitBlt 只能返回静止黑帧,登录循环会因此
  124. # 死等 300s 超时。在客户端启动时开启、关闭时清除,只锁客户端生命周期,不影响
  125. # OAS 空闲时用户正常让屏幕休眠。
  126. ES_CONTINUOUS = 0x80000000
  127. ES_DISPLAY_REQUIRED = 0x00000002
  128. @contextmanager
  129. def dpi_awareness():
  130. """临时把当前线程切到 Per-Monitor V2 DPI 感知,退出时恢复原上下文。
  131. OAS 进程自身未声明 DPI 感知,GDI 调用默认被系统虚拟化成逻辑像素:125% 缩放下
  132. 物理 1280x720 的客户区只报 1024x576,BitBlt 也只能取到画面左上角那一块(右侧
  133. 侧边栏与底部菜单栏直接丢失)。桌面客户端进程是 Per-Monitor DPI 感知、按物理
  134. 像素原生渲染,因此桌面分支的窗口测量与截图必须在感知上下文里做才能拿到完整的
  135. 物理像素画面。用线程级而非进程级,是为了不影响模拟器直控路径既有的逻辑像素假设。
  136. """
  137. user32 = ctypes.windll.user32
  138. previous = None
  139. try:
  140. previous = user32.SetThreadDpiAwarenessContext(_PER_MONITOR_AWARE_V2)
  141. except AttributeError:
  142. # Windows 10 1607 以前没有该 API,退化为原有逻辑像素行为
  143. pass
  144. try:
  145. yield
  146. finally:
  147. if previous:
  148. user32.SetThreadDpiAwarenessContext(previous)
  149. def desktop_keep_screen_on(enable: bool) -> None:
  150. """按桌面客户端生命周期开关「强制保持显示器常亮」。
  151. SetThreadExecutionState 是线程级状态:ES_CONTINUOUS 保持该线程的请求,直到
  152. 再次调用清除。OAS worker 的任务在同一长驻线程内启停客户端,因此这里设置即可。
  153. 注意 ES_DISPLAY_REQUIRED 只「阻止未来关闭」,屏幕若已因电源超时熄灭,必须先用
  154. SC_MONITORPOWER(-1) 广播把显示器物理点亮,否则 BitBlt 仍返回黑帧。
  155. """
  156. if enable:
  157. # 物理点亮:SC_MONITORPOWER(-1) 单独发消息对部分显示器/驱动不触发硬件唤醒
  158. # (实测只发它屏幕仍黑),必须再模拟一次无害键盘输入与鼠标移动,产生真实
  159. # 输入事件才能真正点亮。VK_F15(0x7E) 无副作用,不会干扰游戏。
  160. try:
  161. # 必须用 SendMessageTimeoutW 而不是 SendMessageW:目标是
  162. # HWND_BROADCAST(0xFFFF),SendMessageW 会同步等系统里每一个顶层窗口
  163. # 处理完才返回,只要有一个窗口消息循环繁忙或无响应就永久阻塞调用线程
  164. # (实测 pytest 里这一行挂死 26 分钟不返回,生产上等于 worker 线程卡住)。
  165. # SMTO_ABORTIFHUNG(0x0002) 遇到无响应窗口直接放弃,1000ms 上限兜底。
  166. ctypes.windll.user32.SendMessageTimeoutW(
  167. 0xFFFF, 0x0111, 0xF170, -1, 0x0002, 1000, None)
  168. except Exception as e:
  169. logger.warning(f'SC_MONITORPOWER wake failed: {e}')
  170. try:
  171. user32 = ctypes.windll.user32
  172. user32.keybd_event(0x7E, 0, 0, 0)
  173. user32.keybd_event(0x7E, 0, 2, 0)
  174. user32.SetCursorPos(400, 300)
  175. except Exception as e:
  176. logger.warning(f'wake input failed: {e}')
  177. state = ES_CONTINUOUS | (ES_DISPLAY_REQUIRED if enable else 0)
  178. try:
  179. ctypes.windll.kernel32.SetThreadExecutionState(state)
  180. logger.info(f'Desktop screen keep-awake {"ON" if enable else "OFF"}')
  181. except Exception as e:
  182. logger.warning(f'SetThreadExecutionState({enable}) failed: {e}')
  183. def _window_total_size(width: int, height: int, style: int, ex_style: int) -> tuple:
  184. """用 user32.AdjustWindowRectEx 计算包含标题栏/边框的窗口总尺寸 (w, h)。
  185. pywin32 未导出 AdjustWindowRectEx,故用 ctypes 调用。
  186. """
  187. user32 = ctypes.windll.user32
  188. class RECT(Structure):
  189. _fields_ = [('left', c_long), ('top', c_long), ('right', c_long), ('bottom', c_long)]
  190. user32.AdjustWindowRectEx.argtypes = [POINTER(RECT), c_long, c_long, c_long]
  191. user32.AdjustWindowRectEx.restype = wintypes.BOOL
  192. rect = RECT(0, 0, width, height)
  193. user32.AdjustWindowRectEx(byref(rect), style, False, ex_style)
  194. return rect.right - rect.left, rect.bottom - rect.top
  195. def _desktop_process_image(pid) -> str:
  196. """返回进程 exe 完整路径;打开/查询失败(已退出、权限)返回空串。"""
  197. kernel32 = ctypes.windll.kernel32
  198. # PROCESS_QUERY_LIMITED_INFORMATION
  199. handle = kernel32.OpenProcess(0x1000, False, int(pid))
  200. if not handle:
  201. return ''
  202. try:
  203. buf = ctypes.create_unicode_buffer(520)
  204. size = ctypes.c_ulong(520)
  205. if kernel32.QueryFullProcessImageNameW(handle, 0, buf, ctypes.byref(size)):
  206. return buf.value
  207. return ''
  208. finally:
  209. kernel32.CloseHandle(handle)
  210. def _desktop_pid_under_root(pid, root) -> bool:
  211. """窗口归属进程的 exe 是否位于客户端安装目录之下。
  212. 自动启动绑定时用于排除同标题的模拟器窗口(MuMu 专版窗口标题也在
  213. DESKTOP_WINDOW_TITLES 内),保证绑到的一定是安装目录拉起的客户端进程。
  214. """
  215. exe = _desktop_process_image(pid)
  216. if not exe:
  217. return False
  218. root = os.path.normcase(os.path.normpath(root))
  219. exe = os.path.normcase(os.path.normpath(exe))
  220. return exe.startswith(root + os.sep)
  221. def list_desktop_windows(titles=None) -> list:
  222. """枚举当前所有桌面客户端窗口。
  223. 返回 [{'pid': int, 'title': str, 'hwnd': int, 'x': int, 'y': int}],按屏幕位置
  224. 排序。桌面客户端多开时窗口标题完全相同,只能靠 PID 区分,附带左上角坐标是为了
  225. 按"窗口摆在哪"对号入座。按坐标排序保证同一组窗口每次枚举顺序稳定
  226. (EnumWindows 的返回顺序随 Z 序变化)。
  227. titles 为 None 时用 DESKTOP_WINDOW_TITLES;调用方按配置里的窗口标题
  228. (device.handle)过滤候选时传入自定义标题组。坐标在 DPI 感知上下文内读取,
  229. 是物理像素,与 desktop_window_pos 配置同一空间(OAS 进程自身未声明 DPI 感知,
  230. 上下文外读到的是虚拟化坐标)。
  231. """
  232. def enum_cb(hwnd, param):
  233. param.append(hwnd)
  234. return True
  235. wanted = tuple(titles) if titles else DESKTOP_WINDOW_TITLES
  236. handles = []
  237. EnumWindows(enum_cb, handles)
  238. result = []
  239. with dpi_awareness():
  240. for hwnd in handles:
  241. title = GetWindowText(hwnd)
  242. if title not in wanted:
  243. continue
  244. try:
  245. rect = GetWindowRect(hwnd)
  246. except Exception:
  247. # 窗口在枚举与取矩形之间被关闭,跳过即可
  248. continue
  249. result.append({
  250. 'pid': GetWindowThreadProcessId(hwnd)[1],
  251. 'title': title,
  252. 'hwnd': hwnd,
  253. 'x': rect[0],
  254. 'y': rect[1],
  255. })
  256. result.sort(key=lambda w: (w['x'], w['y'], w['pid']))
  257. return result
  258. # ---------------------------------------------------------------------- 多开档案隔离
  259. def desktop_make_junction(link: Path, target: Path) -> bool:
  260. """创建目录联接(junction 不需要管理员权限);已链接/目标缺失返回 False。
  261. junction 是 NTFS 重解析点,对程序透明且不占空间,用来让每个档案共享真实安装
  262. 目录里的只读大目录(bin/res/zipres 等),避免多开复制数个 GB。
  263. """
  264. if link.is_dir():
  265. # 真实目录或已建好的 junction 都命中(is_dir 会穿透到目标)
  266. return False
  267. if os.path.lexists(link):
  268. # 断裂的 junction:目标被删掉后 is_dir 为 False 但链接本身还在,摘掉重建
  269. try:
  270. os.rmdir(link)
  271. except OSError:
  272. return False
  273. if not target.is_dir():
  274. logger.warning(f'junction 目标不存在,跳过共享: {target}')
  275. return False
  276. link.parent.mkdir(parents=True, exist_ok=True)
  277. # 不走 text=True:mklink 的输出是中文 GBK,按 UTF-8 解码会在管道读取线程里
  278. # 炸 UnicodeDecodeError;bytes 接收,只在失败时容错解码后记日志
  279. result = subprocess.run(['cmd', '/c', 'mklink', '/J', str(link), str(target)],
  280. capture_output=True,
  281. creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
  282. if result.returncode != 0:
  283. stdout = result.stdout.decode('utf-8', errors='replace')
  284. stderr = result.stderr.decode('utf-8', errors='replace')
  285. logger.warning(f'mklink 失败: {link} <- {target}\\n{stdout}{stderr}')
  286. return False
  287. return True
  288. def desktop_prepare_profile(profile: Path, root: Path) -> None:
  289. """搭建多开实例档案目录(幂等,可重复执行)。
  290. 隔离结构:
  291. - 安装根与 Documents 下的大量子目录:junction 共享,0 额外占用;
  292. - Documents 根配置文件(clientconfig 等,实测合计仅几 MB):复制成独立文件;
  293. - home/:假用户主目录,SDK 账号库(Netease\\Mpay)按档案落盘。
  294. """
  295. profile.mkdir(parents=True, exist_ok=True)
  296. for name in DESKTOP_PROFILE_SHARED_DIRS:
  297. desktop_make_junction(profile / name, root / name)
  298. for name in DESKTOP_PROFILE_ISOLATED_DIRS:
  299. (profile / name).mkdir(exist_ok=True)
  300. for name in DESKTOP_PROFILE_HOME_DIRS:
  301. (profile / name).mkdir(parents=True, exist_ok=True)
  302. # 安装根小文件(neox.xml / client.ini / pkginfo.json 等,KB 级)。引擎在 cwd 下
  303. # 找 neox.xml,缺了起不来;cwd 即档案目录,所以这些文件必须各档案一份
  304. for item in root.iterdir():
  305. if item.is_dir():
  306. continue
  307. destination = profile / item.name
  308. if not destination.exists():
  309. shutil.copy2(item, destination)
  310. # Documents:根文件独立复制(账号记忆所在),子目录 junction 共享(8G 资源不复制)
  311. real_docs = root / 'Documents'
  312. if real_docs.is_dir():
  313. for sub in real_docs.iterdir():
  314. destination = profile / 'Documents' / sub.name
  315. if sub.is_dir():
  316. desktop_make_junction(destination, sub)
  317. elif not destination.exists():
  318. shutil.copy2(sub, destination)
  319. def desktop_profile_env(profile: Path) -> dict:
  320. """构造档案隔离的启动环境:USERPROFILE 指向档案内的假主目录。
  321. SDK 并不读 APPDATA 环境变量(走 Shell 已知文件夹 API + 注册表),真正起隔离
  322. 作用的是 USERPROFILE;APPDATA/LOCALAPPDATA/TEMP 一并设上,避免个别组件走
  323. 环境变量时写到全局用户目录。
  324. """
  325. home = profile / 'home'
  326. env = dict(os.environ)
  327. env['USERPROFILE'] = str(home)
  328. env['HOMEDRIVE'] = home.drive
  329. env['HOMEPATH'] = str(home)[len(home.drive):]
  330. env['APPDATA'] = str(home / 'AppData' / 'Roaming')
  331. env['LOCALAPPDATA'] = str(home / 'AppData' / 'Local')
  332. env['TEMP'] = str(home / 'AppData' / 'Local' / 'Temp')
  333. env['TMP'] = env['TEMP']
  334. return env
  335. def desktop_profile_path(configured: str):
  336. """把配置里的档案目录归一化成 Path;未配置返回 None(原行为,不隔离)。"""
  337. configured = (configured or '').strip()
  338. if not configured:
  339. return None
  340. path = Path(configured).expanduser()
  341. if not path.is_absolute():
  342. path = Path.cwd() / path
  343. return path
  344. def desktop_root_from_path(value: str):
  345. """把用户填的路径归一化成安装目录;无效返回 None。"""
  346. path = Path(value).expanduser()
  347. if path.is_file():
  348. # 允许直接填 bin\onmyoji.exe 或 Launch.exe 的完整路径
  349. if path.name.lower() == 'onmyoji.exe' and path.parent.name.lower() == 'bin':
  350. path = path.parent.parent
  351. elif path.name.lower() == 'launch.exe':
  352. path = path.parent
  353. else:
  354. path = path.parent
  355. candidate = path / 'bin' / 'onmyoji.exe'
  356. if candidate.is_file():
  357. return path.resolve()
  358. return None
  359. def desktop_discover_install_root():
  360. """按 %ProgramFiles%\Onmyoji 与注册表 Uninstall 的 InstallLocation 自动发现安装目录。"""
  361. for env in ('ProgramFiles', 'ProgramFiles(x86)'):
  362. raw = os.environ.get(env)
  363. if raw and (Path(raw) / 'Onmyoji' / 'bin' / 'onmyoji.exe').is_file():
  364. return (Path(raw) / 'Onmyoji').resolve()
  365. try:
  366. import winreg
  367. roots = (
  368. (winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'),
  369. (winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall'),
  370. (winreg.HKEY_CURRENT_USER, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'),
  371. )
  372. for hive, key_path in roots:
  373. try:
  374. with winreg.OpenKey(hive, key_path) as parent:
  375. for index in range(winreg.QueryInfoKey(parent)[0]):
  376. try:
  377. with winreg.OpenKey(parent, winreg.EnumKey(parent, index)) as child:
  378. display, _ = winreg.QueryValueEx(child, 'DisplayName')
  379. if '阴阳师' not in str(display) and 'Onmyoji' not in str(display):
  380. continue
  381. location, _ = winreg.QueryValueEx(child, 'InstallLocation')
  382. if location and (Path(location) / 'bin' / 'onmyoji.exe').is_file():
  383. return Path(location).resolve()
  384. except OSError:
  385. continue
  386. except OSError:
  387. continue
  388. except Exception:
  389. pass
  390. return None
  391. def desktop_install_root(game_path: str) -> str:
  392. """解析桌面客户端安装目录:优先配置的 game_path,其次自动发现。
  393. 只认含 bin\onmyoji.exe(或根目录 Launch.exe)的安装目录,找不到返回空串。
  394. """
  395. configured = (game_path or '').strip()
  396. if configured:
  397. root = desktop_root_from_path(configured)
  398. if root is not None:
  399. return str(root)
  400. logger.warning(f'游戏安装目录配置无效: {configured},尝试自动发现')
  401. root = desktop_discover_install_root()
  402. return str(root) if root else ''
  403. def desktop_instance_state_path(profile):
  404. """档案内运行时状态文件路径;未配档案返回 None。
  405. PID 不写配置(每次重启都会变),改记在档案里:OAS 下次启动凭它精确认领
  406. "这个档案的实例是哪个 PID",多开时枚举同标题窗口无法区分归属。
  407. """
  408. if profile is None:
  409. return None
  410. return Path(profile) / 'oas_instance.json'
  411. def desktop_read_instance_state(profile) -> dict:
  412. """读档案状态文件;不存在/损坏/未配档案返回空 dict。"""
  413. path = desktop_instance_state_path(profile)
  414. if path is None or not path.is_file():
  415. return {}
  416. try:
  417. data = json.loads(path.read_text(encoding='utf-8'))
  418. return data if isinstance(data, dict) else {}
  419. except Exception as e:
  420. logger.warning(f'读取桌面实例状态文件失败: {path}: {e}')
  421. return {}
  422. def desktop_write_instance_state(profile, pid) -> None:
  423. """把当前实例 PID 写进档案状态文件(tmp + replace 原子替换,防读写半截)。"""
  424. path = desktop_instance_state_path(profile)
  425. if path is None:
  426. return
  427. try:
  428. path.parent.mkdir(parents=True, exist_ok=True)
  429. tmp = path.with_suffix('.json.tmp')
  430. tmp.write_text(json.dumps({'pid': int(pid)}, ensure_ascii=False), encoding='utf-8')
  431. os.replace(tmp, path)
  432. except Exception as e:
  433. logger.warning(f'写入桌面实例状态文件失败: {path}: {e}')
  434. def desktop_clear_instance_state(profile) -> None:
  435. """清除档案状态文件(客户端已关闭/状态失效时)。"""
  436. path = desktop_instance_state_path(profile)
  437. if path is None:
  438. return
  439. try:
  440. path.unlink(missing_ok=True)
  441. except Exception as e:
  442. logger.warning(f'清除桌面实例状态文件失败: {path}: {e}')
  443. def desktop_prepare_profile_if_needed(profile: Path, root: str) -> None:
  444. """档案未就绪时搭建隔离目录;已就绪(含历史登录态)直接用。
  445. 以 home/AppData/Roaming 存在作为「已就绪」判据:prepare 的任何一步失败都
  446. 不允许带着半成品启动——那会悄悄退回全局账号库,登录到错误的账号。
  447. """
  448. if (profile / 'home' / 'AppData' / 'Roaming').is_dir():
  449. return
  450. logger.info(f'首次使用多开档案,正在准备隔离目录: {profile}')
  451. desktop_prepare_profile(profile, Path(root))
  452. logger.info(f'多开档案就绪: {profile}')
  453. def _desktop_job_api_ready() -> None:
  454. """给 kernel32 的 Job 相关导出声明指针尺寸的 argtypes/restype。
  455. ctypes 默认按 32 位 int 收发返回值,x64 上句柄高位会被截断。这几个导出只在
  456. 本模块的多开归属判定里使用,声明不影响文件内其他 kernel32 调用。
  457. """
  458. kernel32 = ctypes.windll.kernel32
  459. if kernel32.CreateJobObjectW.restype is wintypes.HANDLE:
  460. return
  461. kernel32.CreateJobObjectW.restype = wintypes.HANDLE
  462. kernel32.CreateJobObjectW.argtypes = [wintypes.LPVOID, wintypes.LPWSTR]
  463. kernel32.AssignProcessToJobObject.restype = wintypes.BOOL
  464. kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
  465. kernel32.QueryInformationJobObject.restype = wintypes.BOOL
  466. kernel32.QueryInformationJobObject.argtypes = [
  467. wintypes.HANDLE, wintypes.INT, wintypes.LPVOID, wintypes.DWORD, wintypes.PDWORD]
  468. def _desktop_job_member_pids(job) -> set:
  469. """查询 Job 当前成员进程 PID 集合;查询失败返回空集(调用方退回宽松匹配)。"""
  470. kernel32 = ctypes.windll.kernel32
  471. capacity = 2048
  472. pointer_size = ctypes.sizeof(ctypes.c_void_p)
  473. buffer = ctypes.create_string_buffer(8 + capacity * pointer_size)
  474. returned = wintypes.DWORD()
  475. if not kernel32.QueryInformationJobObject(
  476. wintypes.HANDLE(job), _JOB_OBJECT_BASIC_PROCESS_ID_LIST,
  477. buffer, len(buffer), ctypes.byref(returned)):
  478. return set()
  479. count = int.from_bytes(buffer.raw[4:8], 'little')
  480. pids = set()
  481. for index in range(min(count, capacity)):
  482. offset = 8 + index * pointer_size
  483. pids.add(int.from_bytes(buffer.raw[offset:offset + pointer_size], 'little'))
  484. return pids
  485. def _desktop_attach_job(pid) -> int:
  486. """把本轮 Popen 的启动器进程挂进新建的匿名 Job,返回 Job 句柄;失败返回 0。
  487. 多开时各实例同标题同 exe,并发启动会把别人刚出现的窗口当成自己的绑走;
  488. 窗口进程由启动器派生、自动加入同一 Job,成员名单即「本轮拉起的全部进程」。
  489. 刻意不设 JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE:OAS 退出不影响客户端继续运行,
  490. 句柄关闭也不会杀成员。
  491. """
  492. kernel32 = ctypes.windll.kernel32
  493. try:
  494. _desktop_job_api_ready()
  495. job = kernel32.CreateJobObjectW(None, None)
  496. if not job:
  497. logger.warning('CreateJobObjectW 失败,多开窗口归属退回宽松匹配')
  498. return 0
  499. # PROCESS_SET_QUOTA(0x0100) | PROCESS_TERMINATE(0x0001)
  500. handle = kernel32.OpenProcess(0x0101, False, int(pid))
  501. if not handle:
  502. kernel32.CloseHandle(job)
  503. logger.warning(f'OpenProcess 失败(PID={pid}),多开窗口归属退回宽松匹配')
  504. return 0
  505. try:
  506. if not kernel32.AssignProcessToJobObject(wintypes.HANDLE(job), wintypes.HANDLE(handle)):
  507. kernel32.CloseHandle(job)
  508. logger.warning('AssignProcessToJobObject 失败,多开窗口归属退回宽松匹配')
  509. return 0
  510. finally:
  511. kernel32.CloseHandle(handle)
  512. return int(job)
  513. except Exception as e:
  514. logger.warning(f'Job 归属初始化异常,退回宽松匹配: {e}')
  515. return 0
  516. def desktop_pid_alive(pid) -> bool:
  517. """进程是否还活着。无法判定时按「还活着」返回,宁可多等一轮也不误报已关闭。
  518. 不能只看 OpenProcess 是否成功:进程已退出但仍有内核对象引用时 OpenProcess
  519. 照样返回句柄,必须再用 GetExitCodeProcess 看退出码是否还是 STILL_ACTIVE(259)。
  520. 窗口枚举不能替代这里——强杀被拒时窗口可能已销毁而进程还在,只验窗口会误判。
  521. """
  522. try:
  523. pid_int = int(str(pid))
  524. except (TypeError, ValueError):
  525. return False
  526. kernel32 = ctypes.windll.kernel32
  527. # PROCESS_QUERY_LIMITED_INFORMATION(0x1000),比 QUERY_INFORMATION 权限要求更低
  528. handle = kernel32.OpenProcess(0x1000, False, pid_int)
  529. if not handle:
  530. # 打不开通常就是进程已退出;权限不足时也走这里,交给窗口检查兜底
  531. return False
  532. try:
  533. code = ctypes.c_ulong()
  534. if not kernel32.GetExitCodeProcess(handle, ctypes.byref(code)):
  535. return True
  536. return code.value == 259 # STILL_ACTIVE
  537. finally:
  538. kernel32.CloseHandle(handle)
  539. def desktop_game_exe(root) -> str:
  540. """返回游戏可执行文件路径;找不到返回空串。
  541. 顺序即优先级:必须优先游戏本体 bin/onmyoji.exe。
  542. Launch.exe 是登录器,它会再拉起 bin/onmyoji.exe,
  543. 导致双开且 OAS 绑定到登录器 PID 上找不到游戏窗口。
  544. """
  545. root = Path(root)
  546. for name in ('bin/onmyoji.exe', 'Launch.exe'):
  547. exe = root / name
  548. if exe.is_file():
  549. return str(exe)
  550. return ''
  551. def desktop_spawn_client(exe: str, root: str, profile=None, timeout: int = 90,
  552. attempt: int = 1, on_bound=None):
  553. """启动客户端并等其窗口就绪;返回 (bound_pid, spawned_pids),Popen 失败返回 None。
  554. profile 非空时按档案隔离启动:cwd=档案目录(游戏数据 <cwd>\Documents 独立),
  555. env 的 USERPROFILE 指向档案内假主目录(SDK 账号库 Netease\\Mpay 独立)。
  556. on_bound(pid, hwnd) 在窗口就绪时回调,供调用方绑定自己的实例状态。
  557. 多开窗口归属靠匿名 Job(见 _desktop_attach_job):没有它,并发启动的实例会把
  558. 别人刚出现的窗口绑走。档案隔离模式下 Job 不可用时只认可本次 Popen 的 PID,
  559. 不能把其他账号的新窗口当作自己的;未配置档案的单开仍允许原有的宽松匹配。
  560. """
  561. before_pids = {w['pid'] for w in list_desktop_windows()}
  562. logger.info(f'启动桌面客户端(第 {attempt} 轮): {exe}')
  563. spawned = set()
  564. # 档案隔离:cwd 决定游戏数据根,env 决定 SDK 账号库落点
  565. cwd = str(profile) if profile is not None else root
  566. env = desktop_profile_env(Path(profile)) if profile is not None else None
  567. if profile is not None:
  568. logger.info(f'多开档案隔离启动: cwd={cwd}, USERPROFILE={env["USERPROFILE"]}')
  569. try:
  570. proc = subprocess.Popen([exe], cwd=cwd, env=env,
  571. creationflags=getattr(subprocess, 'CREATE_NEW_PROCESS_GROUP', 0))
  572. spawned.add(proc.pid)
  573. except Exception as e:
  574. logger.error(f'启动桌面客户端失败: {e}')
  575. return None
  576. job = _desktop_attach_job(proc.pid)
  577. try:
  578. deadline = time.time() + timeout
  579. stable_hwnd = 0
  580. stable_count = 0
  581. while time.time() < deadline:
  582. # 候选必须落在安装目录下的进程:客户端新旧版本窗口标题不同
  583. # ("阴阳师-网易游戏" / "阴阳师-MuMu模拟器专版"),启动等待期内任何
  584. # 匹配标题的新窗口都会成为候选,按 exe 归属收口,避免绑到别的进程。
  585. # Job 可用时再按「本轮启动的进程树」精确收口(多开必需)
  586. job_pids = _desktop_job_member_pids(job) if job else set()
  587. spawned.update(job_pids)
  588. owned_pids = job_pids | {proc.pid}
  589. candidates = [w for w in list_desktop_windows()
  590. if _desktop_pid_under_root(w['pid'], root)
  591. and (w['pid'] in owned_pids if job or profile is not None
  592. else w['pid'] not in before_pids)]
  593. if candidates:
  594. candidate = candidates[0]
  595. if candidate['hwnd'] == stable_hwnd:
  596. stable_count += 1
  597. else:
  598. stable_hwnd = candidate['hwnd']
  599. stable_count = 1
  600. if stable_count >= 2:
  601. # 同一 PID 可能还带着启动器残留窗口(客户区极小),句柄统一取
  602. # 客户区最大者,否则截图会绑到残壳上(BitBlt 取不到画面)
  603. hwnd = _desktop_best_window(candidate['pid'], candidate['hwnd'])
  604. if on_bound is not None:
  605. on_bound(candidate['pid'], hwnd)
  606. spawned.add(candidate['pid'])
  607. logger.info(f'桌面客户端已启动并就绪 PID={candidate["pid"]}')
  608. # 到这里启动就完成了:进程在跑、窗口句柄已绑定。
  609. # MPay 登录弹窗与进游戏属于登录流程,由 Restart 的 app_handle_login
  610. # 负责(登录循环每轮都复查弹窗,中途冒出来也能接住)。
  611. return candidate['pid'], spawned
  612. time.sleep(1)
  613. logger.warning(f'桌面客户端进程已启动,但 {timeout} 秒内未识别到游戏窗口')
  614. return 0, spawned
  615. finally:
  616. # Job 只用于启动期的归属判定;关闭句柄不影响已加入的成员进程继续运行
  617. if job:
  618. ctypes.windll.kernel32.CloseHandle(wintypes.HANDLE(job))
  619. def desktop_launch_instance(config) -> bool:
  620. """「启动实例」按钮的落地动作:按 config.script.desktop 参数拉起一个客户端实例。
  621. 在 GUI/主进程里执行(script_set_arg 的副作用),不依赖 worker 的 Device 实例:
  622. 启动、Job 归属、档案状态文件都是模块级能力,worker 下次需要窗口时按状态文件
  623. 认领。已在运行(状态文件里的 PID 还活着)则跳过,避免多开出一个。
  624. """
  625. desktop = getattr(config.script, 'desktop', None)
  626. if desktop is None or not desktop.enable:
  627. logger.error('未启用桌面客户端模式(script.desktop.enable),已忽略启动请求')
  628. return False
  629. root = desktop_install_root(desktop.game_path)
  630. if not root:
  631. logger.error('未找到阴阳师桌面客户端安装目录,'
  632. '请在 设置-Script-桌面客户端 中填写 游戏安装目录')
  633. return False
  634. exe = desktop_game_exe(root)
  635. if not exe:
  636. logger.error(f'未找到游戏程序(bin\\onmyoji.exe 或 Launch.exe):{root}')
  637. return False
  638. profile = desktop_profile_path(desktop.profile_dir)
  639. if profile is not None:
  640. try:
  641. desktop_prepare_profile_if_needed(profile, root)
  642. except Exception as e:
  643. logger.error(f'准备多开档案失败,拒绝启动(避免登录到错误账号): {e}')
  644. return False
  645. state = desktop_read_instance_state(profile)
  646. state_pid = state.get('pid')
  647. if state_pid and desktop_pid_alive(state_pid):
  648. logger.info(f'客户端实例已在运行(PID={state_pid}),跳过启动')
  649. return True
  650. # 按钮路径不经过 Device.desktop_bind_pid,窗口标题改名在这里补上:
  651. # 绑定瞬间(on_bound)就改,与 Device 流程同一时机
  652. result = desktop_spawn_client(
  653. exe, root, profile,
  654. on_bound=lambda pid, hwnd: desktop_rename_window(hwnd, config))
  655. if result is None:
  656. return False
  657. bound_pid, spawned = result
  658. if not bound_pid:
  659. logger.error('客户端已启动但未识别到游戏窗口')
  660. return False
  661. # 状态文件供 worker 认领;PID 不写配置,只活在这里与运行时
  662. desktop_write_instance_state(profile, bound_pid)
  663. logger.info(f'已按按钮请求启动客户端实例 PID={bound_pid}')
  664. return True
  665. def find_desktop_window_by_pid(pid, titles=None) -> int:
  666. """按 PID 查找桌面客户端窗口,返回窗口句柄;未找到抛 EmulatorNotRunningError。
  667. 「找不到窗口」记 warning 而非 error:本方法的调用方多为探测存在性
  668. (desktop_window_exists 判断是否需要重拉、_desktop_wait_closed 确认已关闭),
  669. 找不到是正常答案。真正的故障由上层在拿到 EmulatorNotRunningError 后判定,
  670. 这样真故障不会被淹没在每轮任务收尾都出现的噪音里。
  671. 同一 PID 下可能同时存在多个标题命中的顶层窗口(客户端多开共用同一标题;
  672. 新版 MuMu 内核客户端启动期还带着启动器残留窗口),取客户区最大者即可。
  673. 这里刻意**不设客户区面积下限**:窗口被最小化时客户区是 0x0,但客户端仍在
  674. 运行,还原交给 desktop_window_restore_if_minimized。用面积下限去宣布「未运行」
  675. 会把这个正常挂着的客户端判成掉线 → 触发误重拉(真机实测的循环就是这么起来的),
  676. 而 BitBlt 截图前本来就会先把窗口还原。
  677. titles 为 None 时用 DESKTOP_WINDOW_TITLES;配置了自定义窗口标题
  678. (script.desktop.window_title)时必须传 desktop_window_titles(config),
  679. 否则改名后的实例会被当成「窗口不存在」。
  680. """
  681. try:
  682. pid_int = int(str(pid))
  683. except (TypeError, ValueError):
  684. logger.error(f'Invalid desktop PID: {pid}')
  685. raise EmulatorNotRunningError(f'Invalid desktop client PID: {pid}')
  686. wanted = tuple(titles) if titles else DESKTOP_WINDOW_TITLES
  687. def enum_cb(hwnd, param):
  688. param.append(hwnd)
  689. return True
  690. windows = []
  691. EnumWindows(enum_cb, windows)
  692. matches = []
  693. for hwnd in windows:
  694. if GetWindowText(hwnd) in wanted:
  695. _, win_pid = GetWindowThreadProcessId(hwnd)
  696. if win_pid == pid_int:
  697. matches.append(hwnd)
  698. # 同 PID 的多个候选里取客户区最大者:正常渲染窗口面积最大,启动器残留/
  699. # 最小化窗口(客户区 0x0)会排在后面。读不到客户区的(枚举与取值之间被销毁)
  700. # 直接跳过,全部读不到才算未找到
  701. best, best_area = 0, -1
  702. for hwnd in matches:
  703. try:
  704. cl, ct, cr, cb = GetClientRect(hwnd)
  705. area = (cr - cl) * (cb - ct)
  706. except Exception:
  707. continue
  708. if area > best_area:
  709. best, best_area = hwnd, area
  710. if best:
  711. return best
  712. logger.warning(f'Desktop client window not found, PID={pid}')
  713. raise EmulatorNotRunningError(f'Desktop client window not found, PID={pid}')
  714. def _desktop_best_window(pid, fallback: int = 0, titles=None) -> int:
  715. """取指定 PID 下客户区最大的候选窗口;查不到时回退 fallback。
  716. 用于自动启动完成时的句柄确定:同一 PID 可能既带启动器残留窗口又带真渲染窗口,
  717. 取客户区最大者才不会把截图绑到残壳上。titles 语义同 find_desktop_window_by_pid。
  718. """
  719. try:
  720. return find_desktop_window_by_pid(pid, titles)
  721. except EmulatorNotRunningError:
  722. return fallback
  723. class DesktopWindow:
  724. def desktop_pid(self):
  725. """返回当前桌面客户端 PID(int);取不到返回 None。
  726. 只用实例 root_handle:PID 每次重启都会变、不写配置,本会话的 PID 判断
  727. 必须以实例状态为准。为空的唯一场景是还没绑定过(尚未启动/认领)。
  728. """
  729. pid = getattr(self, 'root_handle', None)
  730. try:
  731. return int(str(pid))
  732. except (TypeError, ValueError):
  733. return None
  734. def find_desktop_login_popup(self) -> int:
  735. """按 PID + 类名查找 MPay 账号登录弹窗,返回句柄;没有则返回 0。
  736. 弹窗与游戏主窗口同 PID 但是独立顶层窗口(owner 为主窗口,非子窗口),
  737. 没有子控件可枚举,只能按窗口类名定位。
  738. 按 PID 过滤保证多开时各实例只处理自己客户端的弹窗。
  739. 主窗口 BitBlt 是否包含这个 owner 窗口受桌面合成状态影响,同一个弹窗可能在
  740. 不同错误截图中出现或消失,所以登录状态不能依赖截图判断。
  741. 改按「HWND 是否仍存活」判断而不再过滤 IsWindowVisible:真机验证过已登录的
  742. 客户端全系统枚举不到任何 MPAY_LOGIN 顶层窗口,说明客户端确认弹窗后是销毁它、
  743. 而非隐藏。因此 HWND 存活即代表尚未登录。
  744. """
  745. pid_int = self.desktop_pid()
  746. if pid_int is None:
  747. return 0
  748. def enum_cb(hwnd, param):
  749. param.append(hwnd)
  750. return True
  751. windows = []
  752. EnumWindows(enum_cb, windows)
  753. for hwnd in windows:
  754. try:
  755. if GetClassName(hwnd) != DESKTOP_LOGIN_POPUP_CLASS:
  756. continue
  757. if GetWindowThreadProcessId(hwnd)[1] == pid_int:
  758. return hwnd
  759. except Exception:
  760. # 窗口在枚举与取属性之间被关闭,跳过即可
  761. continue
  762. return 0
  763. def desktop_confirm_login_popup(self, wait: float = 15.0) -> bool:
  764. """向 MPay 登录弹窗发送回车,并确认对应 HWND 已真实消失。
  765. 弹窗是 DirectUI 独立顶层窗口,"进入游戏"只是绘制出来的像素、没有真实控件,
  766. 实测后台鼠标消息(WM_MOUSEMOVE/LBUTTONDOWN/LBUTTONUP,Post 与 Send 都试过)
  767. 完全无响应;同步与异步回车在无前台焦点时均可触发默认按钮。因此这里只发回车,
  768. 并在 wait 秒内轮询确认弹窗 HWND 真的消失。
  769. 返回 True 表示弹窗确实已关闭;False 表示没有弹窗,或超时后弹窗仍然存活。
  770. """
  771. if not self.find_desktop_login_popup():
  772. return False
  773. logger.info('Desktop MPay login popup found, press Enter to enter game')
  774. # 客户端在首次登录流程中会自行重设一次标题(绑定时的改名因此被覆盖),
  775. # 检测到弹窗时补改一次;标题已正确时仅是字符串比较
  776. desktop_rename_window(self.root_handle_num, self.config)
  777. deadline = time.time() + wait
  778. while time.time() < deadline:
  779. hwnd = self.find_desktop_login_popup()
  780. if not hwnd:
  781. logger.info('Desktop MPay login popup confirmed closed')
  782. return True
  783. self._desktop_send_enter(hwnd)
  784. time.sleep(1)
  785. logger.warning(f'Desktop MPay login popup still present after {wait}s, Enter had no effect')
  786. return False
  787. def desktop_window_is_own_launch(self) -> bool:
  788. """仅首次登录前豁免本轮新实例,避免刚启动就强杀重拉。"""
  789. if not getattr(self, '_desktop_just_launched', False):
  790. return False
  791. pid = self.desktop_pid()
  792. spawned = getattr(self, '_desktop_spawned_pids', None)
  793. if not spawned or pid is None:
  794. return False
  795. try:
  796. return int(str(pid)) in spawned
  797. except (TypeError, ValueError):
  798. return False
  799. def desktop_window_exists(self) -> bool:
  800. """桌面模式:目标 PID 对应窗口仍存在即视为客户端运行中。
  801. 只判「标题命中的顶层窗口在不在」,不看客户区尺寸——窗口被最小化或被遮挡时
  802. 客户端仍在运行,截图方法会先把窗口还原回来再取帧。
  803. 只用实例 root_handle:PID 不写配置,本会话的窗口存在性判断必须以实例状态
  804. 为准。root_handle 为空说明还没绑定过(未启动/未认领),按未运行处理。
  805. """
  806. pid = getattr(self, 'root_handle', None)
  807. if not pid:
  808. return False
  809. # 登录会重建同 PID 的窗口;存在性检查也要刷新截图与输入缓存。
  810. return self._desktop_rebind_window()
  811. def _desktop_wait_window_ready(self, pid, wait: float = DESKTOP_WINDOW_READY_WAIT) -> bool:
  812. """在 wait 秒内等待指定 PID 的客户端窗口出现;超时返回 False。
  813. 用于「进程还活着、窗口暂时不可见」的空窗期。这段时间只能等,不能重新启动
  814. 客户端:真正在跑的那个实例会变成多开或被顶掉,从此再也绑不回原来那个。
  815. """
  816. deadline = time.time() + wait
  817. while True:
  818. try:
  819. find_desktop_window_by_pid(pid, self._desktop_titles())
  820. return True
  821. except EmulatorNotRunningError:
  822. pass
  823. if time.time() >= deadline:
  824. logger.error(f'Desktop client process alive but window not ready in {wait}s, PID={pid}')
  825. return False
  826. time.sleep(DESKTOP_WINDOW_READY_POLL_INTERVAL)
  827. def desktop_client_offset(self) -> tuple:
  828. """返回客户区在窗口 DC 内的偏移 (x, y),用于 BitBlt 扣除标题栏/边框。"""
  829. with dpi_awareness():
  830. window_rect = GetWindowRect(self.screenshot_handle_num)
  831. client_origin = ClientToScreen(self.screenshot_handle_num, (0, 0))
  832. return client_origin[0] - window_rect[0], client_origin[1] - window_rect[1]
  833. def desktop_client_size(self) -> tuple:
  834. """返回桌面客户端窗口客户区的物理像素尺寸 (width, height)。"""
  835. with dpi_awareness():
  836. rect = GetClientRect(self.screenshot_handle_num)
  837. return rect[2] - rect[0], rect[3] - rect[1]
  838. def desktop_client_size_virtual(self) -> tuple:
  839. """返回客户区在 DPI 虚拟化空间下的尺寸 (width, height)。
  840. OAS 进程未声明 DPI 感知,PostMessage 的 lParam 会被系统按该空间解释,
  841. 因此后台输入的坐标必须换算到这里,而不是截图所用的物理空间。
  842. """
  843. rect = GetClientRect(self.screenshot_handle_num)
  844. return rect[2] - rect[0], rect[3] - rect[1]
  845. def _desktop_client_size(self, hwnd):
  846. """读窗口客户区物理尺寸,句柄已失效返回 None。
  847. 客户端从登录界面切到游戏主窗口时会销毁重建渲染窗口,因此调整窗口期间的任何
  848. 一次 Win32 调用都可能撞上失效句柄。GetClientRect 对废句柄抛
  849. (1400, '无效的窗口句柄'),不接住会直接崩掉整个脚本进程。
  850. """
  851. if not IsWindow(hwnd):
  852. return None
  853. try:
  854. rect = GetClientRect(hwnd)
  855. except Exception as e:
  856. logger.warning(f'GetClientRect failed (hwnd={hwnd}): {e}')
  857. return None
  858. return rect[2] - rect[0], rect[3] - rect[1]
  859. def _desktop_clear_handle_cache(self) -> None:
  860. """失效截图相关 cached_property,使其按当前 root_handle_num 重新求值。
  861. 桌面模式下 screenshot_handle_num 直接返回 root_handle_num,但它是
  862. cached_property:客户端重开后 root_handle_num 已换成新 hwnd,缓存仍指向
  863. 旧句柄,截图时 GetClientRect 会拿废句柄抛 (1400)。
  864. """
  865. for prop in ('screenshot_handle_num', 'screenshot_size', 'control_handle_list'):
  866. if prop in self.__dict__:
  867. del_cached_property(self, prop)
  868. def _desktop_rebind_window(self) -> bool:
  869. """按 PID 重新查找客户端窗口并绑定新 hwnd,返回是否绑定成功。
  870. 用于两类句柄刷新:窗口重建(登录界面切游戏主窗口)后更换句柄,以及同一 PID
  871. 下换到客户区更大的那个候选窗口。进程还活着,不需要重拉客户端。
  872. """
  873. try:
  874. hwnd = find_desktop_window_by_pid(self.root_handle, self._desktop_titles())
  875. except EmulatorNotRunningError:
  876. return False
  877. if hwnd != self.root_handle_num:
  878. logger.info(f'Desktop window handle changed, rebind hwnd {self.root_handle_num} -> {hwnd}')
  879. self.root_handle_num = hwnd
  880. self._desktop_clear_handle_cache()
  881. return True
  882. def desktop_window_set_size(self, width: int = 1280, height: int = 720) -> bool:
  883. """桌面模式:检测窗口客户区尺寸,非目标大小时用 SetWindowPos 调整到 width×height。
  884. 窗口位置保持不变;返回是否执行了调整。全过程在 DPI 感知上下文内完成,
  885. GetClientRect/SetWindowPos 处理的都是物理像素,因此目标尺寸无需按缩放比换算,
  886. 调整后客户区物理尺寸恰为 width×height,游戏画面与资产 1:1 对应。
  887. 客户端确认登录弹窗后会销毁登录界面、重建游戏主窗口,调整过程中旧 hwnd 随时可能
  888. 失效。此时不抛异常也不重拉客户端(进程还活着),而是按 PID 重新绑定重建后的
  889. 窗口再试,最多 DESKTOP_RESIZE_ATTEMPTS 轮。
  890. """
  891. if not getattr(self, 'is_desktop_window', False):
  892. return False
  893. for attempt in range(1, DESKTOP_RESIZE_ATTEMPTS + 1):
  894. result = self._desktop_try_set_size(width, height)
  895. if result is not None:
  896. return result
  897. if attempt >= DESKTOP_RESIZE_ATTEMPTS:
  898. break
  899. logger.info(f'Desktop window invalid, rebind and retry resize '
  900. f'({attempt}/{DESKTOP_RESIZE_ATTEMPTS})')
  901. time.sleep(DESKTOP_RESIZE_RETRY_INTERVAL)
  902. self._desktop_rebind_window()
  903. logger.warning(f'Desktop window resize gave up after {DESKTOP_RESIZE_ATTEMPTS} attempts, '
  904. f'window kept invalid')
  905. return False
  906. def _desktop_try_set_size(self, width: int, height: int):
  907. """单轮尝试调整窗口尺寸。
  908. 返回 True/False 表示本轮已得出结论(是否执行了调整);返回 None 表示句柄失效,
  909. 需由调用方重新绑定窗口后再试。三态的意义在于把「尺寸本来就对」(False)和
  910. 「窗口正在重建」(None)区分开,否则前者会白等重试。
  911. """
  912. hwnd = self.root_handle_num
  913. if not hwnd or not IsWindow(hwnd):
  914. logger.warning(f'Desktop window handle invalid (hwnd={hwnd})')
  915. return None
  916. with dpi_awareness():
  917. size = self._desktop_client_size(hwnd)
  918. if size is None:
  919. logger.warning(f'Desktop window vanished before resize (hwnd={hwnd})')
  920. return None
  921. client_w, client_h = size
  922. logger.info(f'Desktop client size: {client_w}x{client_h} (physical), target {width}x{height}')
  923. # 多开摆位与尺寸校准解耦:客户端启动后会自行把窗口挪回屏幕中央,
  924. # 摆位只挂在「尺寸不对」的分支上会被尺寸已正确的窗口整份跳过
  925. self._desktop_assert_window_pos(hwnd)
  926. if client_w == width and client_h == height:
  927. logger.info('Desktop client size already matches target')
  928. return False
  929. # 用 AdjustWindowRectEx 精确计算含标题栏/边框的窗口总尺寸
  930. style = GetWindowLong(hwnd, GWL_STYLE)
  931. ex_style = GetWindowLong(hwnd, GWL_EXSTYLE)
  932. total_w, total_h = _window_total_size(width, height, style, ex_style)
  933. logger.info(f'Resize desktop window to {total_w}x{total_h} to get client {width}x{height}')
  934. try:
  935. SetWindowPos(hwnd, HWND_TOP, 0, 0, total_w, total_h, SWP_NOMOVE | SWP_SHOWWINDOW)
  936. except Exception as e:
  937. # 拒绝访问通常是目标窗口权限更高(游戏以管理员运行)或客户端锁定窗口大小
  938. logger.error(f'SetWindowPos failed: {e}. '
  939. f'请以管理员身份运行 OAS,或手动把游戏窗口设为 1280x720')
  940. return False
  941. # 校准:SetWindowPos 后的实际客户区可能与目标差几像素,按差值持续修正。
  942. # SetWindowPos 本身可能正好撞上客户端重建窗口,因此每轮都要重新确认句柄有效
  943. for _ in range(5):
  944. size = self._desktop_client_size(hwnd)
  945. if size is None:
  946. logger.warning(f'Desktop window vanished during resize (hwnd={hwnd}), '
  947. f'client is rebuilding its window')
  948. return None
  949. cw, ch = size
  950. if cw == width and ch == height:
  951. return True
  952. total_w += width - cw
  953. total_h += height - ch
  954. logger.info(f'Calibrate desktop window to {total_w}x{total_h}, current client {cw}x{ch}')
  955. try:
  956. SetWindowPos(hwnd, HWND_TOP, 0, 0, total_w, total_h, SWP_NOMOVE | SWP_SHOWWINDOW)
  957. except Exception as e:
  958. logger.warning(f'SetWindowPos failed during calibration (hwnd={hwnd}): {e}')
  959. return None
  960. return True
  961. # ------------------------------------------------------------------ 桌面客户端自动生命周期
  962. def desktop_profile_dir(self):
  963. """返回多开档案目录(Path);未配置 script.desktop.profile_dir 时返回 None。"""
  964. return desktop_profile_path(getattr(self.config.script.desktop, 'profile_dir', ''))
  965. def desktop_window_pos(self):
  966. """返回配置的窗口摆位 (x, y);未配置返回 None。"""
  967. return self.desktop_window_pos_parsed(
  968. getattr(self.config.script.desktop, 'window_pos', ''))
  969. @staticmethod
  970. def desktop_window_pos_parsed(value: str):
  971. """解析窗口摆位配置("x,y");非法或留空返回 None。"""
  972. matched = re.fullmatch(r'\s*(-?\d+)\s*[,,]\s*(-?\d+)\s*', str(value or ''))
  973. if not matched:
  974. return None
  975. return int(matched.group(1)), int(matched.group(2))
  976. def desktop_resolve_install_root(self) -> str:
  977. """解析桌面客户端安装目录:优先 script.desktop.game_path 配置,其次自动发现。"""
  978. return desktop_install_root(getattr(self.config.script.desktop, 'game_path', ''))
  979. def launch_desktop_client(self, timeout: int = 90) -> bool:
  980. """自动启动桌面客户端并绑定新窗口的 PID/HWND,成功返回 True。
  981. 单轮 = 启动 exe → 等新窗口出现并稳定 → 绑定其 PID/HWND。到此启动即完成;
  982. MPay 登录弹窗与进游戏属登录流程,由 Restart 的 app_handle_login 负责。
  983. timeout 内没等到窗口说明客户端起歪了(卡加载、崩在启动期等),强杀本轮进程后
  984. 整轮重跑一次;第二轮仍失败则记 error 返回 False,由上层停下等人工,不无限重试。
  985. 安装目录/exe 找不到属配置问题,重试无意义,直接返回 False。
  986. 配置了档案目录(script.desktop.profile_dir)时按档案隔离启动:cwd 与
  987. USERPROFILE 都落在档案内,每个档案拥有独立的 Documents 与 SDK 账号库
  988. (多开账号隔离);未配置时行为不变。
  989. """
  990. root = self.desktop_resolve_install_root()
  991. if not root:
  992. logger.error('未找到阴阳师桌面客户端安装目录,'
  993. '请在 设置-Script-桌面客户端 中填写 游戏安装目录')
  994. return False
  995. exe = desktop_game_exe(root)
  996. if not exe:
  997. logger.error(f'未找到游戏程序(bin\\onmyoji.exe 或 Launch.exe):{root}')
  998. return False
  999. profile = self.desktop_profile_dir()
  1000. if profile is not None:
  1001. try:
  1002. desktop_prepare_profile_if_needed(profile, root)
  1003. except Exception as e:
  1004. logger.error(f'准备多开档案失败,拒绝启动(避免登录到错误账号): {e}')
  1005. return False
  1006. for attempt in (1, 2):
  1007. pids = desktop_spawn_client(exe, root, profile, timeout, attempt,
  1008. on_bound=self.desktop_bind_pid)
  1009. if pids is None:
  1010. # Popen 本身失败,重试也起不来
  1011. return False
  1012. bound_pid, spawned_pid = pids
  1013. if bound_pid:
  1014. # 启动成功也要记住本轮拉起的全部 PID:onmyoji.exe 是启动器,它会派生出
  1015. # 真正的游戏窗口进程后自己继续存活(实测启动器 8932 派生窗口进程 6816,
  1016. # 89 线程 42s CPU 却无窗口)。OAS 靠枚举窗口只绑到窗口进程,关闭时若只杀
  1017. # 它,启动器就成了无主残留。这里留档,交给 desktop_stop_client 一并清理
  1018. self._desktop_spawned_pids = set(spawned_pid)
  1019. return True
  1020. # 最后一轮失败也要清理;清不掉时停止,避免重复启动残留实例。
  1021. # 这里只处理本轮确认归属的 PID,不使用旧 root_handle。
  1022. logger.warning(f'第 {attempt} 轮启动未就绪,清理本轮客户端')
  1023. self._desktop_kill_pids(spawned_pid)
  1024. if any(desktop_pid_alive(pid) for pid in spawned_pid):
  1025. self._desktop_spawned_pids = set(spawned_pid)
  1026. logger.error('客户端残留进程未退出,停止重试')
  1027. return False
  1028. logger.error('桌面客户端连续 2 轮启动均未就绪,请检查客户端状态与机器负载')
  1029. return False
  1030. def _desktop_assert_window_pos(self, hwnd) -> None:
  1031. """按 script.desktop.window_pos 摆放窗口;未配置或已在位则什么都不做。
  1032. 客户端启动后会自行把窗口挪回屏幕中央,只在绑定时摆一次压不住,故在尺寸
  1033. 校准与截图路径上持续重断言。SWP_NOZORDER|SWP_NOACTIVATE:不抢焦点也不改
  1034. 层级——多开窗口互相遮挡是允许的(后台截图不受遮挡影响)。
  1035. """
  1036. position = self.desktop_window_pos()
  1037. if not position or not hwnd:
  1038. return
  1039. x, y = position
  1040. try:
  1041. with dpi_awareness():
  1042. rect = GetWindowRect(hwnd)
  1043. if (rect[0], rect[1]) == (x, y):
  1044. return
  1045. SetWindowPos(hwnd, HWND_TOP, x, y, 0, 0,
  1046. SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE)
  1047. logger.info(f'多开窗口已摆放到 ({x},{y}): hwnd={hwnd}')
  1048. except Exception as e:
  1049. logger.warning(f'摆放多开窗口失败 (hwnd={hwnd}): {e}')
  1050. def _desktop_kill_pids(self, pids) -> None:
  1051. """强杀指定 PID 集合(本轮启动失败的清理),逐个容错并验证真的退出。"""
  1052. kernel32 = ctypes.windll.kernel32
  1053. wait = self._desktop_close_wait_seconds()
  1054. for pid in pids:
  1055. try:
  1056. pid_int = int(pid)
  1057. except (TypeError, ValueError):
  1058. continue
  1059. for attempt in range(1, DESKTOP_KILL_ATTEMPTS + 1):
  1060. # PROCESS_TERMINATE(0x0001)
  1061. handle = kernel32.OpenProcess(0x0001, False, pid_int)
  1062. if not handle:
  1063. # 进程已自行退出
  1064. break
  1065. try:
  1066. kernel32.TerminateProcess(handle, 0)
  1067. logger.info(f'清理桌面客户端 PID={pid_int}')
  1068. finally:
  1069. kernel32.CloseHandle(handle)
  1070. # 杀完必须确认进程真的没了,被拒或正在退出都会让下一轮启动撞上残留
  1071. if self._desktop_wait_pid_gone(pid_int, wait):
  1072. break
  1073. logger.warning(f'桌面客户端 PID={pid_int} 强杀后仍存活,重试 '
  1074. f'({attempt}/{DESKTOP_KILL_ATTEMPTS})')
  1075. else:
  1076. logger.error(f'桌面客户端 PID={pid_int} 无法清理,可能需要手动结束进程')
  1077. # 等窗口真的消失,避免残留窗口干扰下一轮的新窗口识别
  1078. self._desktop_wait_closed(wait)
  1079. def _desktop_wait_pid_gone(self, pid, wait: float) -> bool:
  1080. """在 wait 秒内等待指定进程退出,返回是否已退出。"""
  1081. deadline = time.time() + wait
  1082. while True:
  1083. if not desktop_pid_alive(pid):
  1084. return True
  1085. if time.time() >= deadline:
  1086. return False
  1087. time.sleep(DESKTOP_KILL_POLL_INTERVAL)
  1088. def _desktop_titles(self) -> tuple:
  1089. """本配置认可的窗口标题白名单(内置官方标题 + 自定义窗口标题)。"""
  1090. return desktop_window_titles(getattr(self, 'config', None))
  1091. def _desktop_locate_window(self):
  1092. """定位本配置对应的已在运行的客户端窗口,返回 (pid, hwnd)。
  1093. pid 非空而 hwnd 为 0 表示进程活着但窗口还没就绪(启动期/登录后重建),
  1094. 由调用方等待;两者都空表示没有可归属的实例,应走启动流程。
  1095. 归属优先级:
  1096. 1. 档案内的运行时状态文件(oas_instance.json)——OAS 自己拉起的实例都记了
  1097. PID,多开重开后凭它精确认领,绝不会绑到别的账号实例上;
  1098. 2. 窗口枚举——仅未配档案的单实例场景用:按 device.handle(窗口标题)过滤,
  1099. 只剩一个候选时才认领。多开时各实例标题相同,枚举无法区分归属,
  1100. 宁可重拉一个自己的,也不能控制别人的客户端。
  1101. """
  1102. profile = self.desktop_profile_dir()
  1103. state = desktop_read_instance_state(profile)
  1104. state_pid = state.get('pid')
  1105. if state_pid:
  1106. if desktop_pid_alive(state_pid):
  1107. try:
  1108. return int(state_pid), find_desktop_window_by_pid(
  1109. state_pid, self._desktop_titles())
  1110. except EmulatorNotRunningError:
  1111. # 进程活着、窗口还没就绪:交调用方等,不能重拉(会多开)
  1112. return int(state_pid), 0
  1113. # PID 已死:状态失效,清掉免得下次误判
  1114. desktop_clear_instance_state(profile)
  1115. if profile is not None:
  1116. # 档案模式只认状态文件:枚举分不清多个同标题实例属于哪个账号
  1117. return None, 0
  1118. # 候选标题 = device.handle(原标题过滤)+ 自定义窗口标题(改名后的标题),
  1119. # 两个都可能命中正在跑的实例
  1120. title = str(getattr(self.config.script.device, 'handle', '') or '').strip()
  1121. custom = str(getattr(self.config.script.desktop, 'window_title', '') or '').strip()
  1122. wanted = tuple(t for t in (title, custom) if t)
  1123. candidates = list_desktop_windows(wanted or None)
  1124. if not candidates:
  1125. # 按标题没命中:窗口可能被自定义标题改过名,或客户端换了新标题,
  1126. # 退回内置官方标题再找一次,只剩一个候选时才认领(单实例场景)
  1127. fallback = list_desktop_windows()
  1128. if len(fallback) == 1:
  1129. candidates = fallback
  1130. elif len(fallback) > 1:
  1131. logger.warning(f'按标题过滤未命中,且检测到 {len(fallback)} 个桌面客户端窗口,'
  1132. f'无法区分归属,将重新拉起一个实例')
  1133. if len(candidates) == 1:
  1134. candidate = candidates[0]
  1135. return candidate['pid'], _desktop_best_window(
  1136. candidate['pid'], candidate['hwnd'], self._desktop_titles())
  1137. if len(candidates) > 1:
  1138. logger.warning(f'检测到 {len(candidates)} 个桌面客户端窗口且未配置档案目录,'
  1139. f'无法区分归属,将重新拉起一个实例')
  1140. return None, 0
  1141. def desktop_bind_pid(self, pid, hwnd=0, just_launched=True) -> None:
  1142. """把运行时 PID/HWND 绑定到实例;PID 不写配置,只进档案状态文件。
  1143. PID 每次重启都会变,落配置只会认领一个死进程;配了档案目录时写
  1144. oas_instance.json 供下次认领。同时强制显示器常亮,防止电源超时关屏导致
  1145. BitBlt 截图返回黑帧卡死登录循环。
  1146. just_launched=True 表示窗口是本轮新拉起的,必然未登录;
  1147. False 表示认领已存在的窗口,登录态由 find_desktop_login_popup() 实测判断。
  1148. """
  1149. self.root_handle = str(pid)
  1150. if hwnd:
  1151. self.root_handle_num = hwnd
  1152. if hwnd:
  1153. try:
  1154. title = GetWindowText(hwnd) or DESKTOP_WINDOW_TITLES[0]
  1155. except Exception:
  1156. title = DESKTOP_WINDOW_TITLES[0]
  1157. # 自定义窗口标题:绑定即改名,便于多开时在任务栏区分实例
  1158. desktop_rename_window(hwnd, self.config)
  1159. try:
  1160. title = GetWindowText(hwnd) or title
  1161. except Exception:
  1162. pass
  1163. else:
  1164. title = DESKTOP_WINDOW_TITLES[0]
  1165. self.root_handle_title = title
  1166. self.is_desktop_window = True
  1167. # 换了新 hwnd,截图句柄缓存必须同步失效,否则截图仍走上一个客户端的废句柄
  1168. self._desktop_clear_handle_cache()
  1169. self._desktop_just_launched = just_launched
  1170. if just_launched:
  1171. # 新拉起的客户端必然停在登录页
  1172. self._desktop_login_done = False
  1173. else:
  1174. # 认领已存在的窗口:可能早已登录。已登录的客户端全系统枚举不到
  1175. # MPAY_LOGIN 顶层窗口(见 find_desktop_login_popup),以此区分
  1176. self._desktop_login_done = not self.find_desktop_login_popup()
  1177. # 客户端已拉起,强制保持显示器常亮(线程级状态,随客户端关闭解除)
  1178. desktop_keep_screen_on(True)
  1179. # 档案状态文件:下次启动凭它认领「这个档案的实例是哪个 PID」
  1180. desktop_write_instance_state(self.desktop_profile_dir(), pid)
  1181. logger.info(f'Desktop client bound: PID={pid}, hwnd={hwnd}')
  1182. def _desktop_send_enter(self, hwnd) -> None:
  1183. """向窗口发送回车键,用于确认 MPay 账号登录弹窗的默认按钮"进入游戏"。
  1184. 窗口可能在两条消息之间被销毁(回车已生效),此时忽略异常即可。
  1185. """
  1186. try:
  1187. SendMessage(hwnd, WM_KEYDOWN, VK_RETURN, 0)
  1188. SendMessage(hwnd, WM_KEYUP, VK_RETURN, 0)
  1189. except Exception as e:
  1190. logger.info(f'Send Enter to window {hwnd} failed (window may be closed): {e}')
  1191. def _desktop_wait_closed(self, wait: float) -> bool:
  1192. """在 wait 秒内轮询等待桌面客户端窗口消失,返回是否已关闭。"""
  1193. deadline = time.time() + wait
  1194. while True:
  1195. if not self.desktop_window_exists():
  1196. return True
  1197. if time.time() >= deadline:
  1198. return False
  1199. time.sleep(0.5)
  1200. def _desktop_wait_released(self, pid, wait: float) -> bool:
  1201. """在 wait 秒内等待客户端真正释放:窗口消失 **且** 进程退出。
  1202. 两个条件都要,缺一个都可能是假关闭:
  1203. - 只验窗口:强杀被拒时窗口已销毁但进程还在,会漏掉残留进程
  1204. - 只验进程:进程刚退出时窗口可能还在被系统回收,下一轮新窗口识别会撞上
  1205. """
  1206. deadline = time.time() + wait
  1207. while True:
  1208. if not self.desktop_window_exists() and not desktop_pid_alive(pid):
  1209. return True
  1210. if time.time() >= deadline:
  1211. return False
  1212. time.sleep(DESKTOP_KILL_POLL_INTERVAL)
  1213. def desktop_stop_client(self) -> bool:
  1214. """关闭桌面客户端:强杀进程并验证真的释放,返回是否确认关闭。
  1215. 客户端的退出确认框画在游戏窗口内部(不是独立顶层窗口),实测回车确认经常无效
  1216. (进程不退出、主窗口只是被移到屏幕外),走 WM_CLOSE + 确认反而要多等几秒还未必
  1217. 关得掉,因此这里不发任何窗口消息,直接强杀进程。
  1218. 强杀不等于已关闭:TerminateProcess 可能因权限被拒(本机出现过 (5, '拒绝访问。')),
  1219. 进程也可能正在退出还没消失。所以每轮杀完都验证「窗口消失 且 进程退出」,没释放
  1220. 就再杀一轮,全部轮次用尽仍在则返回 False——调用方据此决定是重建还是交人工,
  1221. 绝不能发完 kill 指令就当成功返回。
  1222. PID 只活在运行时:关闭后清除档案状态文件,下次启动由启动/重拉链路重新拉起
  1223. 并绑定新 PID(不写配置)。
  1224. """
  1225. # 客户端关闭后必然未登录,下次启动需重新走登录流程
  1226. self._desktop_login_done = False
  1227. # PID 要在清理句柄前取,后面的验证全靠它
  1228. pid = getattr(self, 'root_handle', None)
  1229. hwnd = self.root_handle_num
  1230. if (not hwnd or not IsWindow(hwnd)) and not desktop_pid_alive(pid):
  1231. logger.info('Desktop client not running, skip stop')
  1232. # 客户端已不在,解除强制亮屏,允许系统恢复正常的显示器电源管理
  1233. desktop_keep_screen_on(False)
  1234. self._reset_desktop_handle_state()
  1235. desktop_clear_instance_state(self.desktop_profile_dir())
  1236. # 窗口进程已没了也要收启动器:它无窗口,只看窗口永远发现不了
  1237. return self._desktop_kill_spawned_leftovers(pid)
  1238. wait = self._desktop_close_wait_seconds()
  1239. released = False
  1240. for attempt in range(1, DESKTOP_KILL_ATTEMPTS + 1):
  1241. logger.info(f'Stopping desktop client: force kill '
  1242. f'({attempt}/{DESKTOP_KILL_ATTEMPTS}, PID={pid})')
  1243. self.desktop_force_kill()
  1244. if self._desktop_wait_released(pid, wait):
  1245. logger.info(f'Desktop client released (PID={pid})')
  1246. # 客户端已确认关闭,解除强制亮屏,允许系统恢复正常的显示器电源管理
  1247. desktop_keep_screen_on(False)
  1248. released = True
  1249. break
  1250. logger.warning(f'Desktop client PID={pid} still present after {wait}s, retry kill')
  1251. if not released:
  1252. # 到这里客户端确实没关掉:句柄状态照常清零(它已不可信),但把失败如实报出去
  1253. logger.error(f'Desktop client PID={pid} not released after '
  1254. f'{DESKTOP_KILL_ATTEMPTS} force kill attempts, manual cleanup needed')
  1255. self._reset_desktop_handle_state()
  1256. # 实例已终结(或杀而不死),档案状态文件不能再指着一个死 PID
  1257. desktop_clear_instance_state(self.desktop_profile_dir())
  1258. # 无论窗口进程是否关掉,本轮自己拉起的启动器都要一并收掉
  1259. leftovers_cleared = self._desktop_kill_spawned_leftovers(pid)
  1260. return released and leftovers_cleared
  1261. def _desktop_kill_spawned_leftovers(self, bound_pid) -> bool:
  1262. """清理本次自己拉起、但没被绑定的客户端进程,返回是否已全部清掉。
  1263. onmyoji.exe 是启动器:Popen 起来后它派生真正的游戏窗口进程,自己继续存活且
  1264. 没有窗口(实测启动器 89 线程、42s CPU、主窗口句柄为 0)。OAS 靠枚举游戏窗口
  1265. 绑定,只会绑到窗口进程,关闭时若只杀它,启动器就成了无主残留——既占内存,
  1266. 也让下一轮启动的窗口识别多一个干扰源。这些 PID 由 launch_desktop_client
  1267. 在启动成功时留档到 _desktop_spawned_pids。
  1268. """
  1269. spawned = getattr(self, '_desktop_spawned_pids', None)
  1270. if not spawned:
  1271. return True
  1272. try:
  1273. bound = int(str(bound_pid))
  1274. except (TypeError, ValueError):
  1275. bound = None
  1276. # 已绑定的那个由主流程负责,这里只收剩下的
  1277. leftovers = {p for p in spawned if p != bound and desktop_pid_alive(p)}
  1278. self._desktop_spawned_pids = set()
  1279. if not leftovers:
  1280. return True
  1281. logger.info(f'清理本次启动残留的客户端进程(启动器): {sorted(leftovers)}')
  1282. self._desktop_kill_pids(leftovers)
  1283. still = {p for p in leftovers if desktop_pid_alive(p)}
  1284. if still:
  1285. logger.error(f'客户端启动器进程无法清理: {sorted(still)},可能需要手动结束')
  1286. return False
  1287. return True
  1288. def _reset_desktop_handle_state(self) -> None:
  1289. """清零桌面窗口句柄与截图句柄缓存。
  1290. 进程已杀,hwnd 随窗口销毁立即失效。必须清零,否则后续在同一个 device 对象
  1291. 生命周期内被唤醒的任务(如配置变更触发的即时调度)会跳过 Handle.__init__,
  1292. 直接拿这个废句柄去 GetClientRect,抛 (1400, '无效的窗口句柄') 搞崩整个进程。
  1293. """
  1294. self.root_handle_num = 0
  1295. # 截图句柄缓存指向的也是刚被销毁的窗口,一并失效
  1296. self._desktop_clear_handle_cache()
  1297. def _desktop_close_wait_seconds(self) -> int:
  1298. """关闭游戏等待时长(秒),读 config.script.optimization.close_game_wait_duration。"""
  1299. try:
  1300. t = self.config.script.optimization.close_game_wait_duration
  1301. return t.hour * 3600 + t.minute * 60 + t.second
  1302. except Exception:
  1303. return 10
  1304. def desktop_force_kill(self) -> None:
  1305. """强杀桌面客户端进程(WM_CLOSE 超时未退出的兜底)。"""
  1306. pid = getattr(self, 'root_handle', None)
  1307. try:
  1308. pid_int = int(str(pid))
  1309. except (TypeError, ValueError):
  1310. logger.error(f'Invalid desktop PID: {pid}, skip force kill')
  1311. return
  1312. kernel32 = ctypes.windll.kernel32
  1313. # PROCESS_TERMINATE(0x0001)
  1314. handle = kernel32.OpenProcess(0x0001, False, pid_int)
  1315. if not handle:
  1316. # 进程已自行退出
  1317. return
  1318. try:
  1319. kernel32.TerminateProcess(handle, 0)
  1320. logger.info(f'Desktop client PID={pid_int} force terminated')
  1321. finally:
  1322. kernel32.CloseHandle(handle)
  1323. def desktop_window_restore_if_minimized(self, wait: float = 3.0) -> bool:
  1324. """桌面窗口被最小化(用户误操作)时还原并等待客户区恢复,返回是否发生过还原。
  1325. 还原成功后若客户区尺寸偏离目标(1280x720),一并重校准,保证识别 1:1。
  1326. """
  1327. if not getattr(self, 'is_desktop_window', False):
  1328. return False
  1329. hwnd = self.root_handle_num
  1330. if not hwnd or not IsIconic(hwnd):
  1331. return False
  1332. logger.warning('Desktop client window is minimized, restoring')
  1333. ShowWindow(hwnd, SW_RESTORE)
  1334. deadline = time.time() + wait
  1335. restored = False
  1336. while time.time() < deadline:
  1337. with dpi_awareness():
  1338. rect = GetClientRect(hwnd)
  1339. if (rect[2] - rect[0]) > 0 and (rect[3] - rect[1]) > 0:
  1340. restored = True
  1341. break
  1342. time.sleep(0.2)
  1343. if restored:
  1344. self.desktop_window_set_size()
  1345. return restored