Browse Source

feat(DesktopClient): Device 层桌面生命周期(DesktopDevice mixin)

- 新增 DesktopDevice(与 DesktopWindow 对称):_desktop_ensure_launched 先看进程
  再看窗口,避免把“窗口被最小化”当成“客户端未运行”而反复拉起并覆盖 handle
- device.py 接入:__init__ 桌面分支、screenshot 窗口守卫、app_start/app_stop
- 顺带修两处漂移:__init__ 重试次数还原基线语义;is_desktop 不再静默兜底成 False
User 1 tháng trước cách đây
mục cha
commit
0e7edcc8e5
2 tập tin đã thay đổi với 107 bổ sung và 1 xóa
  1. 70 0
      module/device/desktop_device.py
  2. 37 1
      module/device/device.py

+ 70 - 0
module/device/desktop_device.py

@@ -0,0 +1,70 @@
+# This Python file uses the following encoding: utf-8
+"""桌面客户端(serial='desktop')在 Device 层的生命周期策略。
+
+窗口/进程的实现细节在 module/device/method/desktop_impl.py 的 DesktopWindow,
+这里只管「什么时候把客户端拉起来、什么时候算它在运行」。
+"""
+from module.logger import logger
+
+
+class DesktopDevice:
+    # 登录态:OAS 自动启动的客户端停在 MPay 登录页时为 False,登录流程成功后
+    # 置 True,运行期发现弹窗置回 False。默认 True 表示假设已在游戏中。
+    _desktop_login_done = True
+
+    def _desktop_ensure_launched(self) -> bool:
+        """确保客户端可用:进程已死才拉起,进程活着只等窗口就绪。
+
+        判定顺序是关键——先看进程再看窗口。把「窗口不在」当成「客户端没在运行」
+        会拉起多余实例,并把配置里的 handle 覆盖成新实例的 PID,从此再也绑不回
+        原来那个。窗口被最小化不算没运行,截图方法会先还原再取帧。
+        """
+        pid = self.desktop_pid()
+        if pid is None or not self._desktop_pid_alive(pid):
+            return self.launch_desktop_client()
+        if self.desktop_window_exists():
+            return True
+        return self._desktop_wait_window_ready(pid)
+
+    def app_lost_login(self) -> bool:
+        """客户端是否掉回了未登录态。
+
+        MPay 登录窗存活时游戏画面上的一切页面标志都无效,发现即复位登录标记,
+        使 app_is_running() 与任务前置检查能拦住后续流程。模拟器模式恒为 False。
+        """
+        if not self.is_desktop or not self.find_desktop_login_popup():
+            return False
+        logger.warning('Desktop MPay login popup present, client is not logged in')
+        self.desktop_mark_logged_out()
+        return True
+
+    def desktop_mark_logged_in(self) -> None:
+        """标记客户端已完成登录(Restart 的登录流程成功后调用)。"""
+        self._desktop_login_done = True
+
+    def desktop_mark_logged_out(self) -> None:
+        """标记客户端处于未登录态。"""
+        self._desktop_login_done = False
+
+    def _init_desktop(self) -> None:
+        """桌面客户端模式初始化:跳过模拟器健康检查/full_recovery。"""
+        logger.info('Desktop client mode: skip emulator health check and full recovery')
+        if self.config.script.device.screenshot_method == 'auto':
+            self.config.script.device.screenshot_method = 'window_background'
+        if self.config.script.device.control_method != 'window_message':
+            logger.warning(
+                f'Desktop mode requires control_method=window_message, '
+                f'current={self.config.script.device.control_method}, overriding'
+            )
+            self.config.script.device.control_method = 'window_message'
+        self.config.save()
+        self.screenshot_interval_set()
+        # 桌面客户端的渲染经过 DPI 缩放重采样,相对模板截图环境(模拟器原生
+        # 1280x720)存在约 1px 的相位差;仓库里约 1/3 的模板 roi 与模板等宽,
+        # matchTemplate 结果只剩 1 列、横向无法平移补偿,这点相位差就足以把
+        # 「元素存在」判成「不存在」。这里统一外扩 2px 吸收之,模拟器模式保持 0。
+        from module.atom.image import DESKTOP_ROI_MATCH_PAD, set_roi_match_padding
+        set_roi_match_padding(DESKTOP_ROI_MATCH_PAD)
+        # 客户区校准到 1280x720 保证识别 1:1。窗口存在性已由 __init__ 的
+        # _desktop_ensure_launched 保证,运行期掉了由 Restart 负责重拉
+        self.desktop_window_set_size()

+ 37 - 1
module/device/device.py

@@ -12,6 +12,7 @@ from module.base.timer import Timer
 from module.config.utils import get_server_next_update
 from module.device.app_control import AppControl
 from module.device.control import Control
+from module.device.desktop_device import DesktopDevice
 from module.device.platform2 import Platform
 from module.device.screenshot import Screenshot
 from module.exception import (GameNotRunningError,
@@ -22,7 +23,7 @@ from module.exception import (GameNotRunningError,
 from module.logger import logger
 
 
-class Device(Platform, Screenshot, Control, AppControl):
+class Device(DesktopDevice, Platform, Screenshot, Control, AppControl):
     _screen_size_checked = False
     detect_record = set()
     click_record = deque(maxlen=15)
@@ -36,6 +37,13 @@ class Device(Platform, Screenshot, Control, AppControl):
                 super().__init__(*args, **kwargs)
                 break
             except EmulatorNotRunningError:
+                # 桌面客户端没有模拟器可拉:确保客户端在,再重跑一次基类完成窗口绑定
+                if self.is_desktop:
+                    if trial >= 1 or not self._desktop_ensure_launched():
+                        logger.critical('Desktop client not found and auto-launch failed, '
+                                        'please start the game and bind PID first')
+                        raise RequestHumanTakeover from None
+                    continue
                 if trial >= 3:
                     logger.critical('Failed to start emulator after 3 trial')
                     raise RequestHumanTakeover
@@ -49,6 +57,11 @@ class Device(Platform, Screenshot, Control, AppControl):
                     )
                     raise RequestHumanTakeover
 
+        # 桌面客户端模式:无模拟器生命周期
+        if self.is_desktop:
+            self._init_desktop()
+            return
+
         # Auto-fill emulator info
         if IS_WINDOWS and self.config.script.device.emulatorinfo_type == 'auto':
             _ = self.emulator_instance
@@ -104,6 +117,12 @@ class Device(Platform, Screenshot, Control, AppControl):
         """
         self.stuck_record_check()
 
+        # 桌面模式:窗口缺失说明客户端当前不可用(启动期未出窗口,或客户端崩了)。
+        # 直接截图会抛 (1400, '无效的窗口句柄') 搞崩整个进程,必须先拦下;拉客户端
+        # 是 Restart 的职责。最小化不算窗口缺失——BitBlt 截图前会先还原窗口。
+        if self.is_desktop and not self.desktop_window_exists():
+            raise GameNotRunningError('Desktop client window not found')
+
         try:
             super().screenshot()
         except RequestHumanTakeover as e:
@@ -227,6 +246,17 @@ class Device(Platform, Screenshot, Control, AppControl):
         self.stuck_record_check = empty_function
 
     def app_start(self):
+        # 桌面模式:窗口缺失时自动启动客户端并绑定 PID(空闲关闭后由 Restart 重新拉起)
+        if self.is_desktop:
+            if not self._desktop_ensure_launched():
+                logger.error('Desktop client not running and auto-launch failed, '
+                             'please start the game manually or check desktop_game_path')
+                raise GameNotRunningError('Desktop client auto-launch failed')
+            # 这里必然早于 app_handle_login,且是拉起客户端的唯一入口:客户区没校准到
+            # 1280x720 的话登录 OCR 与点击坐标全错。运行期重拉时 Device 对象是复用的,
+            # _init_desktop 不会再跑,所以校准不能只挂在初始化路径上
+            self.desktop_window_set_size()
+            return
         if not self.config.script.error.handle_error:
             logger.critical('No app stop/start, because HandleError disabled')
             logger.critical('Please enable Alas.Error.HandleError or manually login to AzurLane')
@@ -236,6 +266,12 @@ class Device(Platform, Screenshot, Control, AppControl):
         self.click_record_clear()
 
     def app_stop(self):
+        # 桌面模式:关闭客户端。desktop_stop_client 内部已做「窗口消失 且 进程退出」
+        # 验证并多轮重杀,关不掉时它已记 ERROR,这里只把结论透出
+        if self.is_desktop:
+            if not self.desktop_stop_client():
+                logger.warning('Desktop client not released, residual process may remain')
+            return
         if not self.config.script.error.handle_error:
             logger.critical('No app stop/start, because HandleError disabled')
             logger.critical('Please enable Alas.Error.HandleError or manually login to AzurLane')