复核驱动输入与窗口补丁,修复接管互斥和异常清理

Browse Source
This commit is contained in:
yws
2026-10-22 06:52:39 +00:00
parent e2de126687
commit 46b5af01cd
10 changed files with 667 additions and 176 deletions
+26
View File
@@ -72,6 +72,32 @@ codex mcp add limbus --env PYTHONUTF8=1 -- D:\lc-mcp\vendor\aalc\.venv\Scripts\p
部分 Unity 界面仍读取系统指针位置,实测标题页按钮需使用 `window_move`。 部分 Unity 界面仍读取系统指针位置,实测标题页按钮需使用 `window_move`。
战斗按键有按下/释放间隔;隐藏启动后可用 `show_game_background` 恢复渲染。 战斗按键有按下/释放间隔;隐藏启动后可用 `show_game_background` 恢复渲染。
## 可选:任务流使用罗技驱动鼠标输入
驱动接入代码已随仓库提交:`lc_mcp/driver_input.py`、`lc_mcp/aalc_patches.py`、
`lc_mcp/aalc_task.py`,回归测试在 `tests/test_driver_input.py`。
**仓库不包含 `logitech.driver.dll`、罗技驱动安装包或 `logitech.test.py`。**
需要在 Windows 目标机安装配套驱动并提供 DLL;仅拉取本仓库不能启用这套输入。
在启动 MCP 服务的进程环境中设置(路径替换为本机实际位置):
```powershell
$env:LCP_DRIVER_INPUT = '1'
$env:LCP_LOGITECH_DLL = 'E:\罗技键鼠驱动\logitech.driver.dll'
# 可选,目录需已存在:
$env:LCP_DRIVER_TRACE = "$env:USERPROFILE\lc_mcp\driver-input.log"
```
`LCP_DRIVER_INPUT` 默认关闭,DLL 路径未设置时默认使用上面的 E 盘路径。
服务已经运行时,需要让服务以这些环境变量重新启动;只给 SSH bridge 设置无效。
任务子进程必须在物理 console 会话内,且关闭“提高指针精确度”。预检失败会记录原因,
继续使用原输入后端,不修改系统设置。驱动模式会移动真实系统光标并尝试激活游戏;
激活或坐标转换失败时拒绝本次点击。
接管范围是 `run_task` 的鼠标点击(含空白点击、`all` 和游戏重启后的点击)。
模拟器不接管;拖拽、滚动、键盘以及 MCP 的独立 `click` 工具仍使用原后端。
当前回归验证覆盖软件接线和异常处理,DLL、实际驱动及游戏响应需在 Windows 实机核验。
## 工具 ## 工具
| 工具 | 说明 | | 工具 | 说明 |
+33
View File
@@ -63,3 +63,36 @@ OCR 误读;已知读法集合只来自该账号历史观测,不是通用余
`state`;`errors` 表示本次日志出现过错误,不代表所有步骤都失败。新任务重新计算自己的结果。 `state`;`errors` 表示本次日志出现过错误,不代表所有步骤都失败。新任务重新计算自己的结果。
回归覆盖早期错误被大量日志挤出、错误条数上限、日志删除后的结果保留和下一轮状态清理。 回归覆盖早期错误被大量日志挤出、错误条数上限、日志删除后的结果保留和下一轮状态清理。
补充修复后的全套测试:377 项通过(18.235 秒);`git diff --check` 通过。 补充修复后的全套测试:377 项通过(18.235 秒);`git diff --check` 通过。
## 补充:远程驱动输入与窗口补丁复核
本次审查范围是远程新增的 `a6e987e`、`2902cf5`、`7eafbdd`、`e2de126`。
从 `e2de126` 开始修复;未修改 AALC 子模块或目标机配置。
| 优先级 | 已确认问题 | 修复 |
|---|---|---|
| P1 | 直接把 `auto.mouse_click` 绑到代理, 覆盖了真实 `Automation.init_input()` 后续安装的交互门和输入锁, 业务线程可能与监控线程同时点击 | 通过 `_run_business_interaction` 重建入口, 继续使用相同的门与锁 |
| P1 | `task=all` 提前进入 `script_task()` 跳过安装; 游戏异常重启后 `init_game()` 再次重建后端也会丢失代理 | 在任务作用域包装 `scheme.init_game`, 每次初始化结束后安装, 退出恢复原入口; 模拟器和未启用时保持原流程 |
| P1 | `mouse_click_blank` 仍绑定原后端; 物理点击未确认游戏焦点, 失败的坐标转换也被当作有效坐标 | 接管空白点击; 校验 console 会话、游戏焦点、Win32 查询结果; 失败拒绝点击, 保留暂停和 `move_back` 参数 |
| P1 | 驱动按下后异常没有保证抬起; 代理抬起时坐标查询失败也会跳过释放 | 将释放置于 `finally`; 任务中断继续向上抛出 |
| P1 | 前台补丁把 pywin32 `AttachThreadInput` 成功返回的 `None` 转为 `False`, 导致未解除线程绑定 | 无异常即记录已绑定, 前台设置成功或失败都解除绑定 |
| P2 | `GetForegroundWindow()!=0` 被误当作 console 会话依据, RDP 内也可能存在前台窗口; 查询失败被当作加速关闭或坐标 `(0,0)` | 比较进程会话 ID 与活动 console ID; 显式检查查询返回值, 设置指针宽度正确的 API 类型; 使用独立 DLL 绑定避免影响其他库 |
| P2 | 点击/拖动的窗口设置、激活、按下前等待位于清理范围之外; 鼠标释放失败也能跳过位置恢复 | 共用覆盖完整操作的窗口作用域, 透明度和已取得的原位置分别保证恢复 |
| P2 | 截图自检只对窗口 DC 执行 BitBlt, 与提交说明声称的 PrintWindow 路径不符; 位图仍选在 DC 内时尝试删除 | 窗口自检调用 PrintWindow(flags=3), 按客户区大小创建位图, 恢复旧对象后释放 GDI 资源; 屏幕 BitBlt 作为后备 |
| P3 | 新增测试直接导入 pyautogui 和 ctypes.windll, 在 Linux 上 399 项中有 2 项报错 | 隔离平台接口, 补充真实 AALC 接线、任务入口、故障清理和采集 API 的回归测试 |
会话判断依据 Microsoft 的 [GetForegroundWindow 文档](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getforegroundwindow)
和 [WTSGetActiveConsoleSessionId 文档](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-wtsgetactiveconsolesessionid)。
线程绑定接口核对了 [pywin32 源码](https://github.com/mhammond/pywin32/blob/main/win32/src/win32process.i)
及 [接口文档](https://mhammond.github.io/pywin32/win32process__AttachThreadInput_meth.html)。
文件核查:`lc_mcp/driver_input.py`、`lc_mcp/aalc_patches.py`、`lc_mcp/aalc_task.py`
和 `tests/test_driver_input.py` 已存在于远程 `e2de126`。仓库没有 `logitech.driver.dll`、
罗技驱动安装包或注释提到的 `logitech.test.py`。README 已补充外部依赖、环境变量和接管范围。
驱动只接管任务流点击, 不将拖拽、滚动、键盘或独立 MCP `click` 工具改为驱动输入。
验证:Linux / Python 3.12 全套 **417 项通过**(16.832 秒);随后将 Win32 类型声明改为
独立 DLL 绑定, 驱动相关 **29 项回归通过**。`git diff --check` 通过。
测试从 vendor AST 提取并执行真实的 `init_input`、交互门与监控点击方法, 不复制其接线逻辑;
实际 `aalc_task.run` 的 `all` / `daily` 入口也有覆盖。Windows DLL 和游戏未在本次环境执行。
PrintWindow 探测仅表示 API 调用成功, 不保证像素内容有效; 真机仍需检查画面、焦点和点击响应。
+29 -45
View File
@@ -8,6 +8,7 @@ import glob
import os import os
import sys import sys
import time import time
from contextlib import contextmanager
from .engine import Engine from .engine import Engine
@@ -228,42 +229,41 @@ class AalcEngine(Engine):
win32con.SWP_NOSIZE | win32con.SWP_NOZORDER | win32con.SWP_NOSIZE | win32con.SWP_NOZORDER |
win32con.SWP_NOACTIVATE) win32con.SWP_NOACTIVATE)
def click(self, x, y, times=1): @contextmanager
self._prepare_input() def _background_target(self, x, y):
if not self.cfg.simulator and self.cfg.win_input_type in ('background', 'window_move'):
import win32con
handler = self.auto.input_handler
self.auto.wait_pause()
for _ in range(int(times)):
position = None position = None
transparent = False transparent = self.cfg.win_input_type == 'window_move'
if self.cfg.win_input_type == 'window_move': try:
# 搬到光标下面时设成透明/点击穿透, 免得挡住用户的光标。 if transparent:
# ⛔ 必须在本次点击结束时就还原: 以前只有 background_screenshot
# 会把它恢复成 False, 于是"点击 -> 截图 -> 点击 -> 截图"这种
# 高频交替会让游戏窗口在不可见/可见之间反复切换 —— 肉眼看就是
# 画面一直抽搐。AALC 自己的 WindowMoveInput.mouse_click 根本不碰
# 透明度, 所以它只是"跳一下", 不会闪。
self.screen.handle.set_window_transparent(True) self.screen.handle.set_window_transparent(True)
transparent = True position = self.auto.input_handler._set_window_pos(int(x), int(y))
position = handler._set_window_pos(int(x), int(y)) self.auto.input_handler.set_active()
handler.set_active() yield position
self._background_mouse(win32con.WM_MOUSEMOVE, x, y) finally:
time.sleep(0.12) try:
self._background_mouse(win32con.WM_LBUTTONDOWN, x, y, held=True) if position is not None:
try: try:
time.sleep(0.12) time.sleep(0.12)
finally: finally:
# 嵌套 try/finally: 还原位置那步也可能抛错(比如任务被停),
# 但透明度**无论如何**都要还原, 否则窗口会一直隐形。
try:
self._background_mouse(win32con.WM_LBUTTONUP, x, y)
if position is not None:
time.sleep(0.12)
self._restore_background_position(position) self._restore_background_position(position)
finally: finally:
if transparent: if transparent:
self.screen.handle.set_window_transparent(False) self.screen.handle.set_window_transparent(False)
def click(self, x, y, times=1):
self._prepare_input()
if not self.cfg.simulator and self.cfg.win_input_type in ('background', 'window_move'):
import win32con
self.auto.wait_pause()
for _ in range(int(times)):
with self._background_target(x, y):
self._background_mouse(win32con.WM_MOUSEMOVE, x, y)
time.sleep(0.12)
try:
self._background_mouse(win32con.WM_LBUTTONDOWN, x, y, held=True)
time.sleep(0.12)
finally:
self._background_mouse(win32con.WM_LBUTTONUP, x, y)
# Let Unity consume the release before another target is selected. # Let Unity consume the release before another target is selected.
time.sleep(0.12) time.sleep(0.12)
elif not self.cfg.simulator and self.cfg.win_input_type == 'foreground': elif not self.cfg.simulator and self.cfg.win_input_type == 'foreground':
@@ -318,19 +318,12 @@ class AalcEngine(Engine):
if not self.cfg.simulator and self.cfg.win_input_type in ('background', 'window_move'): if not self.cfg.simulator and self.cfg.win_input_type in ('background', 'window_move'):
import win32con import win32con
self.auto.wait_pause() self.auto.wait_pause()
position = None with self._background_target(from_x, from_y) as position:
transparent = False
if self.cfg.win_input_type == 'window_move':
# 同 click(): 透明必须在本次拖动结束时就还原, 不能留给下一次截图
self.screen.handle.set_window_transparent(True)
transparent = True
position = self.auto.input_handler._set_window_pos(int(from_x), int(from_y))
self.auto.input_handler.set_active()
self._background_mouse(win32con.WM_MOUSEMOVE, from_x, from_y) self._background_mouse(win32con.WM_MOUSEMOVE, from_x, from_y)
time.sleep(0.12) time.sleep(0.12)
self._background_mouse(win32con.WM_LBUTTONDOWN, from_x, from_y, held=True)
last_x, last_y = from_x, from_y last_x, last_y = from_x, from_y
try: try:
self._background_mouse(win32con.WM_LBUTTONDOWN, from_x, from_y, held=True)
time.sleep(0.12) time.sleep(0.12)
steps = max(1, int(float(duration) / 0.02)) steps = max(1, int(float(duration) / 0.02))
for step in range(1, steps + 1): for step in range(1, steps + 1):
@@ -342,16 +335,7 @@ class AalcEngine(Engine):
time.sleep(float(duration) / steps) time.sleep(float(duration) / steps)
time.sleep(0.12) time.sleep(0.12)
finally: finally:
# 同 click(): 透明度必须在嵌套的 finally 里还原, 不能被还原位置那步的
# 异常跳过, 否则窗口会一直隐形。
try:
self._background_mouse(win32con.WM_LBUTTONUP, last_x, last_y) self._background_mouse(win32con.WM_LBUTTONUP, last_x, last_y)
if position is not None:
time.sleep(0.12)
self._restore_background_position(position)
finally:
if transparent:
self.screen.handle.set_window_transparent(False)
return return
if not self.cfg.simulator and self.cfg.win_input_type == 'foreground': if not self.cfg.simulator and self.cfg.win_input_type == 'foreground':
import pyautogui import pyautogui
+67 -23
View File
@@ -16,6 +16,7 @@ import os
import re import re
import threading import threading
import time import time
from contextlib import contextmanager
TEAM_TARGET = re.compile(r'(?:TEAMS|TFAMS|编队)#(\d+)', re.IGNORECASE) TEAM_TARGET = re.compile(r'(?:TEAMS|TFAMS|编队)#(\d+)', re.IGNORECASE)
@@ -98,10 +99,8 @@ class WindowGuard(threading.Thread):
# ---------------------------------------------------------------- 驱动级点击接管 # ---------------------------------------------------------------- 驱动级点击接管
# AALC 的 automation.py 在初始化时把这些名字绑成了别名 # 新版 AALC 的输入入口带交互门和锁, 重绑时必须保留这些包装。
# (self.mouse_click = self.input_handler.mouse_click 之类), 所以换掉 input_handler REBIND_NAMES = ('mouse_click', 'mouse_click_blank', 'mouse_down', 'mouse_up')
# 还不够, 必须把别名一起重绑, 否则任务流里调的还是老方法。
REBIND_NAMES = ('mouse_click', 'mouse_down', 'mouse_up')
class DriverClickProxy: class DriverClickProxy:
@@ -125,8 +124,15 @@ class DriverClickProxy:
# --- 接管 ------------------------------------------------------------- # --- 接管 -------------------------------------------------------------
def _screen_pos(self, x, y): def _screen_pos(self, x, y):
from .driver_input import client_to_screen from .driver_input import client_to_screen, foreground_window, is_console_session
hwnd = self._screen.handle.hwnd handle = self._screen.handle
hwnd = handle.hwnd
if not hwnd or handle.isMinimized or not is_console_session():
raise OSError('驱动点击需要 console 会话中可见的游戏窗口')
if foreground_window() != hwnd:
handle.setForeground()
if foreground_window() != hwnd:
raise OSError('无法激活游戏窗口, 未发送驱动输入')
return client_to_screen(hwnd, x, y) return client_to_screen(hwnd, x, y)
def _trace(self, msg): def _trace(self, msg):
@@ -140,34 +146,47 @@ class DriverClickProxy:
except OSError: except OSError:
pass pass
def mouse_click(self, x, y, times=1, *args, **kwargs): def mouse_click(self, x, y, times=1, move_back=False):
from .driver_input import get_cursor
self._handler.wait_pause()
self._trace('mouse_click(%s,%s,times=%s)' % (x, y, times)) self._trace('mouse_click(%s,%s,times=%s)' % (x, y, times))
original_pos = None
try: try:
sx, sy = self._screen_pos(x, y) sx, sy = self._screen_pos(x, y)
except Exception as e: if move_back:
self._trace('screen_pos 失败: %s: %s' % (type(e).__name__, e)) original_pos = get_cursor()
raise
if self._driver.click(sx, sy, times=times): if self._driver.click(sx, sy, times=times):
self.clicks += 1 self.clicks += 1
self.log('[driver] 点击客户区(%d,%d) -> 屏幕(%d,%d)' % (x, y, sx, sy)) self.log('[driver] 点击客户区(%d,%d) -> 屏幕(%d,%d)' % (x, y, sx, sy))
self._handler.wait_pause()
return True return True
except InterruptedError:
raise
except OSError as e:
self._trace('点击失败: %s' % e)
self.log('[driver] 点击失败: %s' % e)
finally:
if original_pos is not None:
self._driver.move_to(*original_pos)
self.refused += 1 self.refused += 1
self.log('[driver] 放弃点击客户区(%d,%d): 无法精确定位' % (x, y)) self.log('[driver] 放弃点击客户区(%d,%d): 无法激活或精确定位' % (x, y))
return False return False
def mouse_down(self, x=None, y=None, *args, **kwargs): def mouse_click_blank(self, coordinate=(1, 1), times=1, move_back=False):
if x is not None and y is not None: return self.mouse_click(*coordinate, times=times, move_back=move_back)
def mouse_down(self, x, y):
self._handler.wait_pause()
sx, sy = self._screen_pos(x, y) sx, sy = self._screen_pos(x, y)
if not self._driver.move_to(sx, sy): if not self._driver.move_to(sx, sy):
return False return False
self._driver.down(1) self._driver.down(1)
return True return True
def mouse_up(self, x=None, y=None, *args, **kwargs): def mouse_up(self, x, y):
if x is not None and y is not None: try:
sx, sy = self._screen_pos(x, y) sx, sy = self._screen_pos(x, y)
self._driver.move_to(sx, sy) self._driver.move_to(sx, sy)
finally:
self._driver.up(1) self._driver.up(1)
return True return True
@@ -180,7 +199,9 @@ def install_driver_click(auto, screen, driver=None, log=print):
""" """
from .driver_input import DriverInput from .driver_input import DriverInput
drv = driver or DriverInput(log=log) if isinstance(auto.input_handler, DriverClickProxy):
return auto.input_handler._driver
drv = driver if driver is not None else DriverInput(log=log)
ok, why = drv.preflight() ok, why = drv.preflight()
if not ok: if not ok:
log('[lc_mcp] 驱动级输入未启用: %s' % why) log('[lc_mcp] 驱动级输入未启用: %s' % why)
@@ -199,10 +220,31 @@ def install_driver_click(auto, screen, driver=None, log=print):
pass pass
auto.input_handler = proxy auto.input_handler = proxy
for name in REBIND_NAMES: for name in REBIND_NAMES:
if hasattr(proxy, name): gate = getattr(auto, '_run_business_interaction', None)
setattr(auto, name, getattr(proxy, name)) setattr(auto, name, gate(name) if callable(gate) else getattr(proxy, name))
log('[lc_mcp] patch: 鼠标点击已切到罗技驱动级输入') log('[lc_mcp] patch: 鼠标点击已切到罗技驱动级输入')
return drv return drv
@contextmanager
def driver_click_tasks(scheme, auto, screen, cfg, log=print):
"""每次游戏初始化完成后接管, 包括 all 任务和故障重启。"""
if cfg.simulator or os.environ.get('LCP_DRIVER_INPUT', '').strip() != '1':
yield
return
original = scheme.init_game
def init_game(*args, **kwargs):
result = original(*args, **kwargs)
install_driver_click(auto, screen, log=log)
return result
scheme.init_game = init_game
try:
yield
finally:
scheme.init_game = original
# ---------------------------------------------------------------- 前台窗口健壮化 # ---------------------------------------------------------------- 前台窗口健壮化
def install_robust_set_foreground(screen, log=print): def install_robust_set_foreground(screen, log=print):
@@ -214,8 +256,8 @@ def install_robust_set_foreground(screen, log=print):
失败时抛 pywintypes.error(0, 'SetForegroundWindow', ...) —— 这个异常在 失败时抛 pywintypes.error(0, 'SetForegroundWindow', ...) —— 这个异常在
set_win() 里没有捕获, 直接把任务带崩(观测: exit code 3 之前的 traceback)。 set_win() 里没有捕获, 直接把任务带崩(观测: exit code 3 之前的 traceback)。
兜底手法是 MSDN 认可的标准做法: 把自己的线程输入队列挂到当前前台窗口的 兜底尝试关联当前线程和前台线程的输入队列, 完成后解挂。
线程上, 借它的前台权限完成切换, 完成后解挂。 Windows 仍可能拒绝激活; 驱动输入在发送前另行检查游戏是否在前台。
""" """
handle = getattr(screen, 'handle', None) handle = getattr(screen, 'handle', None)
if handle is None or not hasattr(handle, 'setForeground'): if handle is None or not hasattr(handle, 'setForeground'):
@@ -243,13 +285,15 @@ def install_robust_set_foreground(screen, log=print):
thread_me = win32api.GetCurrentThreadId() thread_me = win32api.GetCurrentThreadId()
attached = False attached = False
if thread_fg and thread_fg != thread_me: if thread_fg and thread_fg != thread_me:
attached = bool(win32process.AttachThreadInput(thread_fg, thread_me, True)) # pywin32 成功时返回 None, 失败抛异常, 不能按真假判断。
win32process.AttachThreadInput(thread_me, thread_fg, True)
attached = True
try: try:
win32gui.BringWindowToTop(hwnd) win32gui.BringWindowToTop(hwnd)
win32gui.SetForegroundWindow(hwnd) win32gui.SetForegroundWindow(hwnd)
finally: finally:
if attached: if attached:
win32process.AttachThreadInput(thread_fg, thread_me, False) win32process.AttachThreadInput(thread_me, thread_fg, False)
except Exception as e: except Exception as e:
log('[lc_mcp] setForeground 兜底也失败: %s: %s' % (type(e).__name__, e)) log('[lc_mcp] setForeground 兜底也失败: %s: %s' % (type(e).__name__, e))
+2 -5
View File
@@ -11,7 +11,7 @@ import sys
from . import preflight from . import preflight
from .aalc_engine import bootstrap from .aalc_engine import bootstrap
from .aalc_patches import (WindowGuard, install_driver_click, install_exact_team_match, from .aalc_patches import (WindowGuard, driver_click_tasks, install_exact_team_match,
install_robust_set_foreground) install_robust_set_foreground)
# 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效 # 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效
@@ -88,16 +88,13 @@ def run(task, params):
guard.start() guard.start()
restore_path = os.environ.get(RESTORE_ENV) restore_path = os.environ.get(RESTORE_ENV)
originals = apply_overrides(cfg, task, params, restore_path) originals = apply_overrides(cfg, task, params, restore_path)
with driver_click_tasks(scheme, auto, screen, cfg, log=log):
try: try:
if task == 'all': if task == 'all':
scheme.script_task() scheme.script_task()
return 0 return 0
# 与 script_task() 相同的前置步骤 # 与 script_task() 相同的前置步骤
scheme.init_game() scheme.init_game()
# ⚠ 必须放在 init_game() 之后: 它会把 auto.input_handler 重建一次,
# 放在前面装好的代理会被覆盖掉(2026-10-22 实测: 日志有 patch 记录但代理从未被调用)。
if os.environ.get('LCP_DRIVER_INPUT', '').strip() == '1':
install_driver_click(auto, screen, log=log)
path_manager.initialize_paths() path_manager.initialize_paths()
auto.clear_img_cache() auto.clear_img_cache()
retry_monitor.start() retry_monitor.start()
+57 -17
View File
@@ -2,18 +2,18 @@
"""罗技驱动级输入(logitech.driver.dll)。 """罗技驱动级输入(logitech.driver.dll)。
为什么需要它: 用 SendInput/mouse_event 注入的点击, 游戏侧仍可能识别为"模拟"。 为什么需要它: 用 SendInput/mouse_event 注入的点击, 游戏侧仍可能识别为"模拟"。
这个 DLL 通过罗技驱动的虚拟 HID 设备发事件, 系统层面等同真鼠标。 这个 DLL 通过罗技驱动的虚拟 HID 设备发事件。
⛔ 两个必须知道的前提(2026-10-22 实测): ⛔ 两个必须知道的前提(2026-10-22 实测):
1. **会话必须是物理 console** 1. **会话必须是物理 console**
RDP 新建的是独立会话, 和物理桌面隔离。在 RDP 会话里调 `moveR` 光标纹丝不动 RDP 新建的是独立会话, 和物理桌面隔离。在 RDP 会话里调 `moveR` 光标纹丝不动
(实测 22 次采样全程 (1043,758) 不动), 切到 console 会话后立刻正常。 (实测 22 次采样全程 (1043,758) 不动), 切到 console 会话后立刻正常。
判断方法: `GetForegroundWindow()` 返回 0 就说明当前会话没有可接收输入的前台窗口。 比较当前进程会话与 WTSGetActiveConsoleSessionId; 前台窗口句柄不能判定会话类型。
2. **必须关掉指针加速** 2. **必须关掉指针加速**
加速开着时 counts→像素是非线性的(实测 +100/+200/+400 对应 -45/-3/-3 像素), 加速开着时 counts→像素是非线性的(实测 +100/+200/+400 对应 -45/-3/-3 像素),
关掉后严格 1 count = 1 像素(实测比值 1.0000)。没关的话本模块会报警并拒绝定位, 当时的速度设置下关闭后比值为 1.0000。没关的话本模块会报警并拒绝定位,
而不是给出一个不准的位置。 而不是给出一个不准的位置。
接口只用 `device_open / moveR / mouse_down / mouse_up / key_down / key_up / scroll`, 接口只用 `device_open / moveR / mouse_down / mouse_up / key_down / key_up / scroll`,
@@ -22,6 +22,8 @@
import ctypes import ctypes
import os import os
import time import time
from ctypes import wintypes
from functools import lru_cache
# win32 SPI 常量 # win32 SPI 常量
SPI_GETMOUSE = 0x0003 SPI_GETMOUSE = 0x0003
@@ -34,34 +36,61 @@ class Cursor(ctypes.Structure):
_fields_ = [('x', ctypes.c_long), ('y', ctypes.c_long)] _fields_ = [('x', ctypes.c_long), ('y', ctypes.c_long)]
@lru_cache(maxsize=None)
def _win_library(name):
# 使用独立绑定, 避免 argtypes 污染 AALC/pyautogui 共用的 ctypes.windll。
return ctypes.WinDLL(name, use_last_error=True)
def _api(library, name, result, args):
fn = getattr(_win_library(library), name)
fn.restype, fn.argtypes = result, args
return fn
def get_cursor(): def get_cursor():
c = Cursor() c = Cursor()
ctypes.windll.user32.GetCursorPos(ctypes.byref(c)) fn = _api('user32', 'GetCursorPos', wintypes.BOOL, [ctypes.POINTER(Cursor)])
if not fn(ctypes.byref(c)):
raise OSError('GetCursorPos 失败')
return (c.x, c.y) return (c.x, c.y)
def foreground_window(): def foreground_window():
return ctypes.windll.user32.GetForegroundWindow() return _api('user32', 'GetForegroundWindow', wintypes.HWND, [])()
def is_console_session():
current = wintypes.DWORD()
query = _api('kernel32', 'ProcessIdToSessionId', wintypes.BOOL,
[wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)])
if not query(os.getpid(), ctypes.byref(current)):
raise OSError('ProcessIdToSessionId 失败')
console = _api('kernel32', 'WTSGetActiveConsoleSessionId', wintypes.DWORD, [])()
return console != 0xFFFFFFFF and current.value == console
def has_foreground(): def has_foreground():
"""当前会话有没有可接收输入的前台窗口。 """当前是否存在前台窗口; 激活切换时也可能短暂为 0。"""
RDP 会话里常常是 0 —— 那种情况下所有注入(键盘尤其是)都不会生效。
"""
return bool(foreground_window()) return bool(foreground_window())
def acceleration_on(): def acceleration_on():
"""指针加速是否开着。开着就别指望 counts 和像素成线性。""" """指针加速是否开着。开着就别指望 counts 和像素成线性。"""
a = (ctypes.c_int * 3)() a = (ctypes.c_int * 3)()
ctypes.windll.user32.SystemParametersInfoA(SPI_GETMOUSE, 0, ctypes.byref(a), 0) fn = _api('user32', 'SystemParametersInfoA', wintypes.BOOL,
[wintypes.UINT, wintypes.UINT, ctypes.c_void_p, wintypes.UINT])
if not fn(SPI_GETMOUSE, 0, ctypes.byref(a), 0):
raise OSError('读取指针加速设置失败')
return bool(a[2]) return bool(a[2])
def mouse_speed(): def mouse_speed():
s = ctypes.c_int() s = ctypes.c_int()
ctypes.windll.user32.SystemParametersInfoA(SPI_GETMOUSESPEED, 0, ctypes.byref(s), 0) fn = _api('user32', 'SystemParametersInfoA', wintypes.BOOL,
[wintypes.UINT, wintypes.UINT, ctypes.c_void_p, wintypes.UINT])
if not fn(SPI_GETMOUSESPEED, 0, ctypes.byref(s), 0):
raise OSError('读取指针速度失败')
return s.value return s.value
@@ -88,8 +117,10 @@ class DriverInput:
return False return False
try: try:
self._dll = ctypes.CDLL(self.dll_path) self._dll = ctypes.CDLL(self.dll_path)
for name in ('device_open', 'moveR', 'mouse_down', 'mouse_up'):
getattr(self._dll, name)
ok = self._dll.device_open() == 1 ok = self._dll.device_open() == 1
except OSError as e: except (OSError, AttributeError) as e:
self.log('[driver] 加载 DLL 失败: %s' % e) self.log('[driver] 加载 DLL 失败: %s' % e)
self._dll = None self._dll = None
return False return False
@@ -106,13 +137,16 @@ class DriverInput:
"""返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。""" """返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。"""
if not self.open(): if not self.open():
return False, '罗技驱动不可用(device_open 失败)' return False, '罗技驱动不可用(device_open 失败)'
try:
if not is_console_session():
return False, '当前进程不在物理 console 会话, 不启用驱动输入'
if not has_foreground(): if not has_foreground():
return False, ('当前会话没有前台窗口(GetForegroundWindow=0) —— ' return False, '当前会话没有前台窗口(GetForegroundWindow=0), 暂不启用驱动输入'
'多半是 RDP 独立会话, 驱动级输入在这类会话里不生效, '
'需要物理 console 会话')
if acceleration_on(): if acceleration_on():
return False, ('指针加速开着, counts 与像素不成比例, 定位会不准 —— ' return False, ('指针加速开着, counts 与像素不成比例, 定位会不准 —— '
'关掉"提高指针精确度"后重试') '关掉"提高指针精确度"后重试')
except (OSError, AttributeError) as e:
return False, '无法确认输入环境: %s' % e
return True, 'ok' return True, 'ok'
# ---------------------------------------------------------------- 移动 # ---------------------------------------------------------------- 移动
@@ -160,8 +194,10 @@ class DriverInput:
% (sx, sy, cx, cy)) % (sx, sy, cx, cy))
return False return False
for _ in range(int(times)): for _ in range(int(times)):
try:
self._dll.mouse_down(1) self._dll.mouse_down(1)
time.sleep(0.03) time.sleep(0.03)
finally:
self._dll.mouse_up(1) self._dll.mouse_up(1)
return True return True
@@ -180,7 +216,11 @@ class DriverInput:
def client_to_screen(hwnd, x, y): def client_to_screen(hwnd, x, y):
"""游戏客户区坐标 -> 屏幕坐标。""" """游戏客户区坐标 -> 屏幕坐标。"""
from ctypes import wintypes if not hwnd:
raise OSError('没有游戏窗口句柄')
pt = wintypes.POINT(int(x), int(y)) pt = wintypes.POINT(int(x), int(y))
ctypes.windll.user32.ClientToScreen(hwnd, ctypes.byref(pt)) fn = _api('user32', 'ClientToScreen', wintypes.BOOL,
[wintypes.HWND, ctypes.POINTER(wintypes.POINT)])
if not fn(hwnd, ctypes.byref(pt)):
raise OSError('ClientToScreen 失败, 未发送输入')
return (pt.x, pt.y) return (pt.x, pt.y)
+61 -24
View File
@@ -110,41 +110,78 @@ def ensure_server(timeout_s=90):
# ---------------------------------------------------------------- 桌面渲染 # ---------------------------------------------------------------- 桌面渲染
def _blit_ok(hdc): def _blit_ok(hdc, hwnd=None):
"""从给定的 DC 拷一小块回来, 成功与否。""" """探测采集 API, 窗口走 AALC 的 PrintWindow(flags=3)。不验证画面内容。"""
from ctypes import windll if not hdc:
g = windll.gdi32 return False
mem = g.CreateCompatibleDC(hdc) import ctypes
bmp = g.CreateCompatibleBitmap(hdc, 64, 64) from ctypes import wintypes
g.SelectObject(mem, bmp) import win32gui
r = g.BitBlt(mem, 0, 0, 64, 64, hdc, 0, 0, 0x00CC0020) import win32ui
g.DeleteObject(bmp)
g.DeleteDC(mem) source = target = bitmap = old = bitmap_handle = None
return bool(r) try:
width, height = 64, 64
if hwnd:
left, top, right, bottom = win32gui.GetClientRect(hwnd)
width, height = right - left, bottom - top
if width <= 0 or height <= 0:
return False
source = win32ui.CreateDCFromHandle(hdc)
target = source.CreateCompatibleDC()
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(source, width, height)
bitmap_handle = bitmap.GetHandle()
old = target.SelectObject(bitmap)
if hwnd:
capture = ctypes.windll.user32.PrintWindow
capture.argtypes = [wintypes.HWND, wintypes.HDC, wintypes.UINT]
capture.restype = wintypes.BOOL
return bool(capture(hwnd, target.GetSafeHdc(), 3))
target.BitBlt((0, 0), (width, height), source, (0, 0), 0x00CC0020)
return True
except Exception:
return False
finally:
try:
if old is not None:
target.SelectObject(old)
finally:
try:
if target is not None:
target.DeleteDC()
finally:
if bitmap_handle is not None:
win32gui.DeleteObject(bitmap_handle)
# source 只包装调用者的 DC, 由调用者 ReleaseDC, 不能 DeleteDC。
def screen_blit_ok(): def screen_blit_ok():
"""抓**整个屏幕**能不能成功(GetDC(0))。""" import win32gui
from ctypes import windll hdc = None
u = windll.user32
hdc = u.GetDC(0)
try: try:
hdc = win32gui.GetDC(0)
return _blit_ok(hdc) return _blit_ok(hdc)
except Exception:
return False
finally: finally:
u.ReleaseDC(0, hdc) if hdc:
win32gui.ReleaseDC(0, hdc)
def window_blit_ok(hwnd): def window_blit_ok(hwnd):
"""从**游戏窗口**的 DC 拷一小块回来能不能成功(和 AALC 的采集走同一类路径)。""" import win32gui
from ctypes import windll hdc = None
u = windll.user32
hdc = u.GetWindowDC(hwnd)
if not hdc:
return False
try: try:
return _blit_ok(hdc) if win32gui.IsIconic(hwnd):
return False
hdc = win32gui.GetWindowDC(hwnd)
return _blit_ok(hdc, hwnd=hwnd)
except Exception:
return False
finally: finally:
u.ReleaseDC(hwnd, hdc) if hdc:
win32gui.ReleaseDC(hwnd, hdc)
def render_ok(): def render_ok():
+41 -2
View File
@@ -107,12 +107,51 @@ class BackgroundRestoreTest(unittest.TestCase):
engine.screen = mock.Mock() engine.screen = mock.Mock()
engine.auto.input_handler.pos_offset.return_value = (100, 200) engine.auto.input_handler.pos_offset.return_value = (100, 200)
engine._prepare_input = mock.Mock() engine._prepare_input = mock.Mock()
with mock.patch('pyautogui.moveTo'), mock.patch('pyautogui.mouseDown'), \ with mock.patch.dict(sys.modules, pyautogui=mock.Mock()), \
mock.patch('pyautogui.mouseUp'), \
mock.patch('lc_mcp.aalc_engine.time.sleep'): mock.patch('lc_mcp.aalc_engine.time.sleep'):
engine.click(100, 200) engine.click(100, 200)
engine.screen.handle.set_window_transparent.assert_not_called() engine.screen.handle.set_window_transparent.assert_not_called()
def test_window_cleanup_covers_setup_release_and_restore_failures(self):
constants = SimpleNamespace(WM_MOUSEMOVE=512, WM_LBUTTONDOWN=513, WM_LBUTTONUP=514)
for action in ('click', 'drag'):
for stage in ('move_window', 'activate', 'move_message', 'pre_press_sleep',
'release', 'restore'):
with self.subTest(action=action, stage=stage):
engine = AalcEngine.__new__(AalcEngine)
engine.cfg = SimpleNamespace(simulator=False, win_input_type='window_move')
engine.auto, engine.screen = mock.Mock(), mock.Mock()
engine.auto.input_handler._set_window_pos.return_value = (20, 30)
engine._grab = mock.Mock(return_value=SimpleNamespace(width=800, height=600))
engine._background_mouse = mock.Mock()
engine._restore_background_position = mock.Mock()
failure = RuntimeError(stage)
if stage == 'move_window':
engine.auto.input_handler._set_window_pos.side_effect = failure
elif stage == 'activate':
engine.auto.input_handler.set_active.side_effect = failure
elif stage == 'restore':
engine._restore_background_position.side_effect = failure
elif stage in ('move_message', 'release'):
message = 512 if stage == 'move_message' else 514
def send(kind, *args, **kwargs):
if kind == message:
raise failure
engine._background_mouse.side_effect = send
with mock.patch.dict(sys.modules, win32con=constants), \
mock.patch('lc_mcp.aalc_engine.time.sleep') as sleep:
if stage == 'pre_press_sleep':
sleep.side_effect = failure
with self.assertRaises(RuntimeError):
if action == 'click':
engine.click(100, 200)
else:
engine.drag(100, 100, 100, 300)
self.assertEqual(engine.screen.handle.set_window_transparent.call_args_list,
[mock.call(True), mock.call(False)])
if stage != 'move_window':
engine._restore_background_position.assert_called_once_with((20, 30))
def test_restore_uses_noactivate_and_preserves_foreground(self): def test_restore_uses_noactivate_and_preserves_foreground(self):
gui = mock.Mock() gui = mock.Mock()
gui.GetForegroundWindow.return_value = 123 gui.GetForegroundWindow.return_value = 123
+47
View File
@@ -703,6 +703,53 @@ class RenderCheckTest(QuietLogMixin, unittest.TestCase):
self.assertFalse(cm.render_ok()) self.assertFalse(cm.render_ok())
class CaptureApiTest(QuietLogMixin, unittest.TestCase):
def test_window_capture_uses_printwindow_and_releases_gdi_objects(self):
import ctypes
for outcome in (1, 0, OSError('capture failed')):
with self.subTest(outcome=outcome):
api, gui, ui = mock.Mock(), mock.Mock(), mock.Mock()
gui.GetClientRect.return_value = (0, 0, 1280, 720)
gui.IsIconic.return_value = False
source = ui.CreateDCFromHandle.return_value
target = source.CreateCompatibleDC.return_value
bitmap = ui.CreateBitmap.return_value
previous = target.SelectObject.return_value
if isinstance(outcome, Exception):
api.user32.PrintWindow.side_effect = outcome
else:
api.user32.PrintWindow.return_value = outcome
with mock.patch.dict(sys.modules, win32gui=gui, win32ui=ui), \
mock.patch.object(ctypes, 'windll', api, create=True):
self.assertEqual(cm.window_blit_ok(123), outcome == 1)
api.user32.PrintWindow.assert_called_once_with(123, target.GetSafeHdc(), 3)
target.BitBlt.assert_not_called()
bitmap.CreateCompatibleBitmap.assert_called_once_with(source, 1280, 720)
self.assertEqual(target.SelectObject.call_args_list,
[mock.call(bitmap), mock.call(previous)])
target.DeleteDC.assert_called_once()
gui.DeleteObject.assert_called_once_with(bitmap.GetHandle())
source.DeleteDC.assert_not_called()
gui.ReleaseDC.assert_called_once_with(123, gui.GetWindowDC())
def test_missing_dc_and_minimized_window_cannot_pass_capture(self):
gui = mock.Mock()
gui.IsIconic.return_value = True
with mock.patch.dict(sys.modules, win32gui=gui):
self.assertFalse(cm.window_blit_ok(123))
gui.GetWindowDC.assert_not_called()
self.assertFalse(cm._blit_ok(0))
def test_screen_fallback_uses_bitblt(self):
gui, ui = mock.Mock(), mock.Mock()
source = ui.CreateDCFromHandle.return_value
target = source.CreateCompatibleDC.return_value
with mock.patch.dict(sys.modules, win32gui=gui, win32ui=ui):
self.assertTrue(cm.screen_blit_ok())
target.BitBlt.assert_called_once_with((0, 0), (64, 64), source, (0, 0), 0x00CC0020)
gui.ReleaseDC.assert_called_once_with(0, gui.GetDC())
class SessionTableTest(QuietLogMixin, unittest.TestCase): class SessionTableTest(QuietLogMixin, unittest.TestCase):
"""解析 `query session` —— 用来区分"截不到图"到底是哪种情况。 """解析 `query session` —— 用来区分"截不到图"到底是哪种情况。
+252 -8
View File
@@ -5,14 +5,18 @@
而拒绝只是继续用原来的注入方式。所以测试重点放在 preflight 的各种拒绝条件上。 而拒绝只是继续用原来的注入方式。所以测试重点放在 preflight 的各种拒绝条件上。
背景(2026-10-22 实测): 背景(2026-10-22 实测):
* 在 RDP 独立会话里, 罗技驱动 moveR 完全不生效(22 次采样光标纹丝不动), * RDP 独立会话不能靠前台窗口判定, 必须核对进程与 console 会话 ID。
切到物理 console 会话后立刻正常 —— GetForegroundWindow()==0 是判据。
* 指针加速开着时 counts 和像素不成比例(+100/+200/+400 -> -45/-3/-3 像素), * 指针加速开着时 counts 和像素不成比例(+100/+200/+400 -> -45/-3/-3 像素),
关掉后严格 1:1。所以加速没关时不该给出"差不多"的位置。 关掉后严格 1:1。所以加速没关时不该给出"差不多"的位置。
""" """
import sys import sys
import os
import ast
import inspect
import threading
import unittest import unittest
from pathlib import Path from pathlib import Path
from types import SimpleNamespace
from unittest import mock from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1])) sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -23,11 +27,12 @@ from lc_mcp import aalc_patches as ap # noqa: E402
class PreflightTest(unittest.TestCase): class PreflightTest(unittest.TestCase):
"""能不能用, 必须说得清楚; 不能用时一条都不能含糊。""" """能不能用, 必须说得清楚; 不能用时一条都不能含糊。"""
def _drv(self, dll_ok=True, fg=True, accel=False): def _drv(self, dll_ok=True, fg=True, accel=False, console=True):
d = di.DriverInput(dll_path='X.dll', log=lambda m: None) d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
d._dll = mock.Mock() d._dll = mock.Mock()
d._open = dll_ok d._open = dll_ok
with mock.patch.object(di, 'has_foreground', lambda: fg), \ with mock.patch.object(di, 'has_foreground', lambda: fg), \
mock.patch.object(di, 'is_console_session', lambda: console), \
mock.patch.object(di, 'acceleration_on', lambda: accel): mock.patch.object(di, 'acceleration_on', lambda: accel):
return d.preflight() return d.preflight()
@@ -46,7 +51,11 @@ class PreflightTest(unittest.TestCase):
ok, why = self._drv(fg=False) ok, why = self._drv(fg=False)
self.assertFalse(ok) self.assertFalse(ok)
self.assertIn('前台窗口', why) self.assertIn('前台窗口', why)
self.assertIn('RDP', why)
def test_remote_session_is_rejected_even_with_foreground(self):
ok, why = self._drv(console=False, fg=True)
self.assertFalse(ok)
self.assertIn('console', why)
def test_refuses_when_acceleration_is_on(self): def test_refuses_when_acceleration_is_on(self):
ok, why = self._drv(accel=True) ok, why = self._drv(accel=True)
@@ -141,7 +150,7 @@ class InstallTest(unittest.TestCase):
"""接管 AALC 的点击: 条件不满足时**一个都不许改**。""" """接管 AALC 的点击: 条件不满足时**一个都不许改**。"""
def _auto(self): def _auto(self):
auto = mock.Mock() auto = SimpleNamespace()
auto.input_handler = mock.Mock() auto.input_handler = mock.Mock()
auto.mouse_click = auto.input_handler.mouse_click auto.mouse_click = auto.input_handler.mouse_click
return auto return auto
@@ -178,16 +187,251 @@ class InstallTest(unittest.TestCase):
class ClientToScreenTest(unittest.TestCase): class ClientToScreenTest(unittest.TestCase):
def test_uses_client_to_screen(self): def test_uses_client_to_screen(self):
pt = mock.Mock(x=0, y=0)
def fake(hwnd, byref_pt): def fake(hwnd, byref_pt):
ptr = byref_pt._obj ptr = byref_pt._obj
ptr.x, ptr.y = ptr.x + 100, ptr.y + 50 ptr.x, ptr.y = ptr.x + 100, ptr.y + 50
return 1 return 1
with mock.patch.object(di.ctypes.windll.user32, 'ClientToScreen', fake): api = mock.Mock()
api.user32.ClientToScreen.side_effect = fake
with mock.patch.object(di, '_win_library', side_effect=lambda name: getattr(api, name)):
self.assertEqual(di.client_to_screen(123, 7, 9), (107, 59)) self.assertEqual(di.client_to_screen(123, 7, 9), (107, 59))
def vendor_auto():
"""执行 vendor 的真实接线与交互门方法, 只隔离 Windows 输入后端。"""
root = Path(__file__).resolve().parents[1] / 'vendor/aalc/module/automation'
abstract = ast.parse((root / 'input_handlers/__init__.py').read_text())
abstract.body = [n for n in abstract.body if isinstance(n, ast.ClassDef)]
namespace = {'log': mock.Mock(), 'sleep': lambda _: None, 'time': lambda: 0}
exec(compile(abstract, str(root / 'input_handlers/__init__.py'), 'exec'), namespace)
base = namespace['AbstractInput']
class Handler(base):
def mouse_click(self, *args, **kwargs):
raise AssertionError('旧点击后端不应被调用')
def mouse_click_blank(self, *args, **kwargs):
raise AssertionError('空白点击不应回落到旧后端')
source = ast.parse((root / 'automation.py').read_text())
cls = next(n for n in source.body if isinstance(n, ast.ClassDef) and n.name == 'Automation')
keep = {'init_input', '_run_business_interaction', 'monitor_mouse_click',
'suspend_interactions', 'resume_interactions'}
cls.body = [n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name in keep]
cls.keywords = []
namespace = {'__name__': 'module.automation.automation', '__package__': 'module.automation',
'inspect': inspect, 'AbstractInput': base, 'log': mock.Mock(),
'cfg': SimpleNamespace(simulator=False, win_input_type='foreground',
memory_protection=False), 'GATE_WAIT_TIMEOUT': 30}
exec(compile(ast.Module(body=[cls], type_ignores=[]), str(root / 'automation.py'), 'exec'), namespace)
auto = namespace['Automation']()
auto.input_handler = None
auto._input_lock = threading.RLock()
auto._interaction_gate = threading.Event()
auto._interaction_gate.set()
with mock.patch.dict(sys.modules, {'module.automation.input_handlers.input':
SimpleNamespace(Input=Handler)}):
auto.init_input()
return auto, Handler
class DriverWiringTest(unittest.TestCase):
def test_real_business_gate_and_monitor_share_the_input_lock(self):
auto, _ = vendor_auto()
drv = mock.Mock()
drv.preflight.return_value = (True, 'ok')
locked = []
drv.click.side_effect = lambda *a, **k: locked.append(auto._input_lock._is_owned()) or True
ap.install_driver_click(auto, mock.Mock(), driver=drv, log=lambda _: None)
auto.suspend_interactions()
entered = threading.Event()
wait = auto._interaction_gate.wait
def waiting(*args, **kwargs):
entered.set()
return wait(*args, **kwargs)
with mock.patch.object(auto.input_handler, '_screen_pos', return_value=(10, 20)), \
mock.patch.object(auto._interaction_gate, 'wait', side_effect=waiting):
worker = threading.Thread(target=auto.mouse_click, args=(10, 20), daemon=True)
worker.start()
try:
self.assertTrue(entered.wait(1), '业务点击必须等待交互门')
drv.click.assert_not_called()
# 监控点击允许绕过门, 但仍必须持有同一把锁。
auto.monitor_mouse_click(10, 20)
finally:
auto.resume_interactions()
worker.join(2)
self.assertFalse(worker.is_alive())
self.assertEqual(locked, [True, True])
def test_blank_click_uses_driver_and_move_back_is_honored(self):
auto, _ = vendor_auto()
drv = mock.Mock()
drv.preflight.return_value = (True, 'ok')
ap.install_driver_click(auto, mock.Mock(), driver=drv, log=lambda _: None)
with mock.patch.object(auto.input_handler, '_screen_pos', return_value=(10, 20)), \
mock.patch.object(di, 'get_cursor', return_value=(90, 80)):
self.assertTrue(auto.mouse_click_blank((1, 2), times=2, move_back=True))
drv.click.assert_called_once_with(10, 20, times=2)
drv.move_to.assert_called_once_with(90, 80)
def test_all_task_and_reinitialization_reinstall_after_init(self):
auto, handler_type = vendor_auto()
scheme = SimpleNamespace(init_game=auto.init_input)
scheme.script_task = lambda: (scheme.init_game(), auto.mouse_click_blank())
original = scheme.init_game
drv = mock.Mock()
drv.preflight.return_value = (True, 'ok')
with mock.patch.dict(os.environ, LCP_DRIVER_INPUT='1'), \
mock.patch.dict(sys.modules, {'module.automation.input_handlers.input':
SimpleNamespace(Input=handler_type)}), \
mock.patch.object(di, 'DriverInput', return_value=drv), \
mock.patch.object(ap.DriverClickProxy, '_screen_pos', return_value=(10, 20)):
with ap.driver_click_tasks(scheme, auto, mock.Mock(),
SimpleNamespace(simulator=False), log=lambda _: None):
scheme.script_task()
first = auto.input_handler
scheme.script_task()
self.assertIsNot(auto.input_handler, first)
self.assertIsInstance(auto.input_handler, ap.DriverClickProxy)
self.assertEqual(drv.click.call_count, 2)
self.assertIs(scheme.init_game, original)
def test_actual_task_entry_enables_driver_for_all_and_daily(self):
from lc_mcp import aalc_task
for task in ('all', 'daily'):
with self.subTest(task=task):
auto, handler_type = vendor_auto()
auto.clear_img_cache = mock.Mock()
auto.click_element = mock.Mock(return_value=False)
cfg = SimpleNamespace(simulator=False)
scheme = SimpleNamespace(init_game=auto.init_input)
scheme.script_task = lambda: (scheme.init_game(), auto.mouse_click(10, 20))
scheme.Daily_task_wrapper = lambda **kw: lambda: auto.mouse_click(10, 20)
scheme.to_get_reward = scheme.Buy_enkephalin = scheme.Mirror_task = mock.Mock()
drv = mock.Mock()
drv.preflight.return_value = (True, 'ok')
modules = {
'module.automation': SimpleNamespace(auto=auto),
'module.automation.input_handlers.input': SimpleNamespace(Input=handler_type),
'module.config': SimpleNamespace(cfg=cfg),
'module.game_and_screen': SimpleNamespace(screen=mock.Mock()),
'tasks.base': SimpleNamespace(script_task_scheme=scheme),
'tasks.base.retry_monitor': SimpleNamespace(retry_monitor=mock.Mock()),
'tasks.battle': SimpleNamespace(battle=mock.Mock()),
'utils.path_manager': SimpleNamespace(path_manager=mock.Mock()),
}
with mock.patch.dict(sys.modules, modules), \
mock.patch.dict(os.environ, LCP_DRIVER_INPUT='1', LCP_RESTORE_FILE=''), \
mock.patch.object(aalc_task, 'bootstrap'), \
mock.patch.object(aalc_task, 'install_exact_team_match'), \
mock.patch.object(aalc_task, 'install_robust_set_foreground'), \
mock.patch.object(aalc_task, 'WindowGuard'), \
mock.patch.object(aalc_task, 'log'), \
mock.patch.object(aalc_task.preflight, 'collect', return_value={}), \
mock.patch.object(aalc_task.preflight, 'desktop_size', return_value=(1920, 1080)), \
mock.patch.object(aalc_task.preflight, 'check', return_value=[]), \
mock.patch.object(di, 'DriverInput', return_value=drv), \
mock.patch.object(ap.DriverClickProxy, '_screen_pos', return_value=(10, 20)):
self.assertEqual(aalc_task.run(task, {}), 0)
drv.click.assert_called_once_with(10, 20, times=1)
def test_disabled_and_simulator_leave_initialization_unchanged(self):
for enabled, simulator in [('0', False), ('1', True)]:
with self.subTest(enabled=enabled, simulator=simulator):
scheme = SimpleNamespace(init_game=mock.Mock())
original = scheme.init_game
with mock.patch.dict(os.environ, LCP_DRIVER_INPUT=enabled):
with ap.driver_click_tasks(scheme, mock.Mock(), mock.Mock(),
SimpleNamespace(simulator=simulator)):
self.assertIs(scheme.init_game, original)
class DriverFailureTest(unittest.TestCase):
def test_release_even_if_sleep_is_interrupted(self):
drv = di.DriverInput()
drv._open, drv._dll = True, mock.Mock()
with mock.patch.object(drv, 'move_to', return_value=True), \
mock.patch.object(di.time, 'sleep', side_effect=InterruptedError):
with self.assertRaises(InterruptedError):
drv.click(1, 2)
drv._dll.mouse_up.assert_called_once_with(1)
def test_release_even_if_coordinate_lookup_fails(self):
drv = mock.Mock()
proxy = ap.DriverClickProxy(mock.Mock(), drv, mock.Mock())
with mock.patch.object(proxy, '_screen_pos', side_effect=OSError('closed')):
with self.assertRaises(OSError):
proxy.mouse_up(1, 2)
drv.up.assert_called_once_with(1)
def test_no_physical_click_if_game_cannot_get_foreground(self):
drv = mock.Mock()
handle = SimpleNamespace(hwnd=123, isMinimized=False, setForeground=mock.Mock())
proxy = ap.DriverClickProxy(mock.Mock(), drv, SimpleNamespace(handle=handle), log=lambda _: None)
with mock.patch.object(di, 'is_console_session', return_value=True), \
mock.patch.object(di, 'foreground_window', return_value=999):
self.assertFalse(proxy.mouse_click(1, 2))
drv.click.assert_not_called()
handle.setForeground.assert_called_once()
def test_failed_windows_reads_do_not_become_zero_coordinates(self):
api = mock.Mock()
api.user32.ClientToScreen.return_value = 0
api.user32.GetCursorPos.return_value = 0
api.user32.SystemParametersInfoA.return_value = 0
with mock.patch.object(di, '_win_library', side_effect=lambda name: getattr(api, name)):
for fn, args in [(di.client_to_screen, (123, 1, 2)), (di.get_cursor, ()),
(di.acceleration_on, ())]:
with self.subTest(function=fn.__name__), self.assertRaises(OSError):
fn(*args)
def test_failed_environment_query_refuses_installation(self):
drv = di.DriverInput()
drv._open, drv._dll = True, mock.Mock()
with mock.patch.object(di, 'is_console_session', side_effect=OSError('session query failed')):
ok, reason = drv.preflight()
self.assertFalse(ok)
self.assertIn('session query failed', reason)
def test_dll_without_mouse_exports_is_rejected(self):
drv = di.DriverInput()
with mock.patch.object(di.os.path, 'exists', return_value=True), \
mock.patch.object(di.ctypes, 'CDLL', return_value=SimpleNamespace(device_open=lambda: 1)):
self.assertFalse(drv.open())
self.assertFalse(drv.ready)
def test_console_session_ids_are_compared(self):
api = mock.Mock()
def query(pid, sid):
sid._obj.value = 2
return 1
api.kernel32.ProcessIdToSessionId.side_effect = query
with mock.patch.object(di, '_win_library', side_effect=lambda name: getattr(api, name)):
for console, expected in [(2, True), (3, False), (0xFFFFFFFF, False)]:
api.kernel32.WTSGetActiveConsoleSessionId.return_value = console
self.assertEqual(di.is_console_session(), expected)
class ForegroundFallbackTest(unittest.TestCase):
def test_none_on_success_still_detaches_after_success_or_failure(self):
for failed in (False, True):
with self.subTest(failed=failed):
handle = SimpleNamespace(hwnd=123, setForeground=mock.Mock(side_effect=OSError))
gui = mock.Mock()
gui.GetForegroundWindow.return_value = 456
gui.SetForegroundWindow.side_effect = OSError if failed else None
process = mock.Mock()
process.GetWindowThreadProcessId.return_value = (11, 22)
process.AttachThreadInput.return_value = None
api = SimpleNamespace(GetCurrentThreadId=lambda: 33)
with mock.patch.dict(sys.modules, win32api=api, win32gui=gui, win32process=process):
ap.install_robust_set_foreground(SimpleNamespace(handle=handle), log=lambda _: None)
handle.setForeground()
self.assertEqual(process.AttachThreadInput.call_args_list,
[mock.call(33, 11, True), mock.call(33, 11, False)])
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()