diff --git a/lc_mcp/aalc_patches.py b/lc_mcp/aalc_patches.py index 57d8e5a..e23e9ce 100644 --- a/lc_mcp/aalc_patches.py +++ b/lc_mcp/aalc_patches.py @@ -94,3 +94,85 @@ class WindowGuard(threading.Thread): def stop(self): self.stopped.set() + +# ---------------------------------------------------------------- 驱动级点击接管 + +# AALC 的 automation.py 在初始化时把这些名字绑成了别名 +# (self.mouse_click = self.input_handler.mouse_click 之类), 所以换掉 input_handler +# 还不够, 必须把别名一起重绑, 否则任务流里调的还是老方法。 +REBIND_NAMES = ('mouse_click', 'mouse_down', 'mouse_up') + + +class DriverClickProxy: + """把鼠标点击转发到罗技驱动, 其余一律透传给原 handler。 + + ⛔ 只接管**点击类**操作。拖拽/滑动/滚轮仍走 AALC 原逻辑 —— 那些在镜牢和日常 + 里用得少, 而各自的行为差异(惯性、多点)不好用相对位移复现, 接了反而更容易出错。 + """ + + def __init__(self, handler, driver, screen, log=print): + self._handler = handler + self._driver = driver + self._screen = screen + self.log = log + self.clicks = 0 + self.refused = 0 + + # --- 透传 ------------------------------------------------------------- + def __getattr__(self, name): + return getattr(self._handler, name) + + # --- 接管 ------------------------------------------------------------- + def _screen_pos(self, x, y): + from .driver_input import client_to_screen + hwnd = self._screen.handle.hwnd + return client_to_screen(hwnd, x, y) + + def mouse_click(self, x, y, times=1, *args, **kwargs): + sx, sy = self._screen_pos(x, y) + if self._driver.click(sx, sy, times=times): + self.clicks += 1 + self.log('[driver] 点击客户区(%d,%d) -> 屏幕(%d,%d)' % (x, y, sx, sy)) + self._handler.wait_pause() + return True + self.refused += 1 + self.log('[driver] 放弃点击客户区(%d,%d): 无法精确定位' % (x, y)) + return False + + def mouse_down(self, x=None, y=None, *args, **kwargs): + if x is not None and y is not None: + sx, sy = self._screen_pos(x, y) + if not self._driver.move_to(sx, sy): + return False + self._driver.down(1) + return True + + def mouse_up(self, x=None, y=None, *args, **kwargs): + if x is not None and y is not None: + sx, sy = self._screen_pos(x, y) + self._driver.move_to(sx, sy) + self._driver.up(1) + return True + + +def install_driver_click(auto, screen, driver=None, log=print): + """如果环境满足, 把 AALC 的鼠标点击切到罗技驱动级输入。 + + 返回驱动实例(成功) 或 None(条件不满足, AALC 保持原样)。 + 条件不满足时**不改任何东西** —— 宁可继续用原来的注入方式, 也不要半吊子接管。 + """ + from .driver_input import DriverInput + + drv = driver or DriverInput(log=log) + ok, why = drv.preflight() + if not ok: + log('[lc_mcp] 驱动级输入未启用: %s' % why) + return None + + proxy = DriverClickProxy(auto.input_handler, drv, screen, log=log) + auto.input_handler = proxy + for name in REBIND_NAMES: + if hasattr(proxy, name): + setattr(auto, name, getattr(proxy, name)) + log('[lc_mcp] patch: 鼠标点击已切到罗技驱动级输入') + return drv \ No newline at end of file diff --git a/lc_mcp/aalc_task.py b/lc_mcp/aalc_task.py index c05b7e8..2ebec16 100644 --- a/lc_mcp/aalc_task.py +++ b/lc_mcp/aalc_task.py @@ -11,7 +11,7 @@ import sys from . import preflight from .aalc_engine import bootstrap -from .aalc_patches import WindowGuard, install_exact_team_match +from .aalc_patches import WindowGuard, install_driver_click, install_exact_team_match # 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效 TASKS = { @@ -82,6 +82,10 @@ def run(task, params): return PREFLIGHT_EXIT install_exact_team_match(auto, log) + # 驱动级鼠标点击: 默认关闭, 设 LCP_DRIVER_INPUT=1 才启用。 + # 条件不满足(非物理会话 / 指针加速没关 / 驱动没装)时什么都不改, 保持原样。 + if os.environ.get('LCP_DRIVER_INPUT', '').strip() == '1': + install_driver_click(auto, screen, log=log) guard = WindowGuard(screen, cfg, log=log) guard.start() restore_path = os.environ.get(RESTORE_ENV) diff --git a/lc_mcp/driver_input.py b/lc_mcp/driver_input.py new file mode 100644 index 0000000..43639e4 --- /dev/null +++ b/lc_mcp/driver_input.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +"""罗技驱动级输入(logitech.driver.dll)。 + +为什么需要它: 用 SendInput/mouse_event 注入的点击, 游戏侧仍可能识别为"模拟"。 +这个 DLL 通过罗技驱动的虚拟 HID 设备发事件, 系统层面等同真鼠标。 + +⛔ 两个必须知道的前提(2026-10-22 实测): + +1. **会话必须是物理 console** + RDP 新建的是独立会话, 和物理桌面隔离。在 RDP 会话里调 `moveR` 光标纹丝不动 + (实测 22 次采样全程 (1043,758) 不动), 切到 console 会话后立刻正常。 + 判断方法: `GetForegroundWindow()` 返回 0 就说明当前会话没有可接收输入的前台窗口。 + +2. **必须关掉指针加速** + 加速开着时 counts→像素是非线性的(实测 +100/+200/+400 对应 -45/-3/-3 像素), + 关掉后严格 1 count = 1 像素(实测比值 1.0000)。没关的话本模块会报警并拒绝定位, + 而不是给出一个不准的位置。 + +接口只用 `device_open / moveR / mouse_down / mouse_up / key_down / key_up / scroll`, +这是 logitech.test.py 里验证过的那几个。 +""" +import ctypes +import os +import time + +# win32 SPI 常量 +SPI_GETMOUSE = 0x0003 +SPI_GETMOUSESPEED = 0x0070 + +DEFAULT_DLL = r'E:\罗技键鼠驱动\logitech.driver.dll' + + +class Cursor(ctypes.Structure): + _fields_ = [('x', ctypes.c_long), ('y', ctypes.c_long)] + + +def get_cursor(): + c = Cursor() + ctypes.windll.user32.GetCursorPos(ctypes.byref(c)) + return (c.x, c.y) + + +def foreground_window(): + return ctypes.windll.user32.GetForegroundWindow() + + +def has_foreground(): + """当前会话有没有可接收输入的前台窗口。 + + RDP 会话里常常是 0 —— 那种情况下所有注入(键盘尤其是)都不会生效。 + """ + return bool(foreground_window()) + + +def acceleration_on(): + """指针加速是否开着。开着就别指望 counts 和像素成线性。""" + a = (ctypes.c_int * 3)() + ctypes.windll.user32.SystemParametersInfoA(SPI_GETMOUSE, 0, ctypes.byref(a), 0) + return bool(a[2]) + + +def mouse_speed(): + s = ctypes.c_int() + ctypes.windll.user32.SystemParametersInfoA(SPI_GETMOUSESPEED, 0, ctypes.byref(s), 0) + return s.value + + +class DriverInput: + """罗技驱动级鼠标/键盘。 + + 定位采用**闭环**: 发相对位移 -> 读回实际位置 -> 不够就再发, 直到误差 <= tol。 + 这样不依赖任何标定常数, 也能对抗偶发的坐标跳变。 + """ + + def __init__(self, dll_path=None, log=print): + self.dll_path = dll_path or os.environ.get('LCP_LOGITECH_DLL') or DEFAULT_DLL + self.log = log + self._dll = None + self._open = False + + # ---------------------------------------------------------------- 生命周期 + + def open(self): + if self._open: + return True + if not os.path.exists(self.dll_path): + self.log('[driver] 找不到 %s' % self.dll_path) + return False + try: + self._dll = ctypes.CDLL(self.dll_path) + ok = self._dll.device_open() == 1 + except OSError as e: + self.log('[driver] 加载 DLL 失败: %s' % e) + self._dll = None + return False + self._open = bool(ok) + if not ok: + self.log('[driver] device_open() != 1, 罗技驱动未就绪') + return self._open + + @property + def ready(self): + return self._open and self._dll is not None + + def preflight(self): + """返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。""" + if not self.open(): + return False, '罗技驱动不可用(device_open 失败)' + if not has_foreground(): + return False, ('当前会话没有前台窗口(GetForegroundWindow=0) —— ' + '多半是 RDP 独立会话, 驱动级输入在这类会话里不生效, ' + '需要物理 console 会话') + if acceleration_on(): + return False, ('指针加速开着, counts 与像素不成比例, 定位会不准 —— ' + '关掉"提高指针精确度"后重试') + return True, 'ok' + + # ---------------------------------------------------------------- 移动 + + def move_relative(self, dx, dy): + if not self.ready: + return False + if dx == 0 and dy == 0: + return True + self._dll.moveR(int(dx), int(dy), True) + return True + + def move_to(self, sx, sy, tol=1, iters=10, settle=0.03): + """把光标精确移到屏幕坐标 (sx, sy)。返回是否到位。""" + if not self.ready: + return False + for _ in range(iters): + cx, cy = get_cursor() + dx, dy = int(sx) - cx, int(sy) - cy + if abs(dx) <= tol and abs(dy) <= tol: + return True + if self.move_relative(dx, dy) is False: + return False + time.sleep(settle) + cx, cy = get_cursor() + return abs(int(sx) - cx) <= tol and abs(int(sy) - cy) <= tol + + # ---------------------------------------------------------------- 按键 + + def down(self, button=1): + if self.ready: + self._dll.mouse_down(int(button)) + + def up(self, button=1): + if self.ready: + self._dll.mouse_up(int(button)) + + def click(self, sx, sy, times=1, tol=1): + """先确认到位置, 再按下抬起。没到位就不点, 免得点错地方。""" + if not self.ready: + return False + if not self.move_to(sx, sy, tol=tol): + cx, cy = get_cursor() + self.log('[driver] 定位失败: 目标(%d,%d) 实际(%d,%d), 不点击' + % (sx, sy, cx, cy)) + return False + for _ in range(int(times)): + self._dll.mouse_down(1) + time.sleep(0.03) + self._dll.mouse_up(1) + return True + + def key_down(self, key): + if self.ready: + self._dll.key_down(key) + + def key_up(self, key): + if self.ready: + self._dll.key_up(key) + + def scroll(self, amount): + if self.ready: + self._dll.scroll(int(amount)) + + +def client_to_screen(hwnd, x, y): + """游戏客户区坐标 -> 屏幕坐标。""" + from ctypes import wintypes + pt = wintypes.POINT(int(x), int(y)) + ctypes.windll.user32.ClientToScreen(hwnd, ctypes.byref(pt)) + return (pt.x, pt.y) diff --git a/tests/test_driver_input.py b/tests/test_driver_input.py new file mode 100644 index 0000000..14ec125 --- /dev/null +++ b/tests/test_driver_input.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +"""驱动级输入接管。 + +⛔ 这个模块的每一条"拒绝"都比"接管"更重要: 接管错了会让任务点错地方, +而拒绝只是继续用原来的注入方式。所以测试重点放在 preflight 的各种拒绝条件上。 + +背景(2026-10-22 实测): + * 在 RDP 独立会话里, 罗技驱动 moveR 完全不生效(22 次采样光标纹丝不动), + 切到物理 console 会话后立刻正常 —— GetForegroundWindow()==0 是判据。 + * 指针加速开着时 counts 和像素不成比例(+100/+200/+400 -> -45/-3/-3 像素), + 关掉后严格 1:1。所以加速没关时不该给出"差不多"的位置。 +""" +import sys +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from lc_mcp import driver_input as di # noqa: E402 +from lc_mcp import aalc_patches as ap # noqa: E402 + + +class PreflightTest(unittest.TestCase): + """能不能用, 必须说得清楚; 不能用时一条都不能含糊。""" + + def _drv(self, dll_ok=True, fg=True, accel=False): + d = di.DriverInput(dll_path='X.dll', log=lambda m: None) + d._dll = mock.Mock() + d._open = dll_ok + with mock.patch.object(di, 'has_foreground', lambda: fg), \ + mock.patch.object(di, 'acceleration_on', lambda: accel): + return d.preflight() + + def test_ok_when_everything_is_right(self): + ok, why = self._drv() + self.assertTrue(ok) + self.assertEqual(why, 'ok') + + def test_refuses_without_driver(self): + ok, why = self._drv(dll_ok=False) + self.assertFalse(ok) + self.assertIn('device_open', why) + + def test_refuses_in_a_session_without_foreground(self): + """RDP 独立会话的典型特征 —— 这种会话里驱动级输入无效。""" + ok, why = self._drv(fg=False) + self.assertFalse(ok) + self.assertIn('前台窗口', why) + self.assertIn('RDP', why) + + def test_refuses_when_acceleration_is_on(self): + ok, why = self._drv(accel=True) + self.assertFalse(ok) + self.assertIn('加速', why) + + def test_refuses_missing_dll_file(self): + d = di.DriverInput(dll_path=r'Z:\nope\nope.dll', log=lambda m: None) + self.assertFalse(d.open()) + self.assertFalse(d.ready) + + +class MoveToTest(unittest.TestCase): + """定位必须是闭环: 发位移 -> 读回 -> 不够再发。不依赖标定常数。""" + + def test_converges_when_moves_are_exact(self): + pos = {'v': (0, 0)} + d = di.DriverInput(dll_path='X.dll', log=lambda m: None) + d._dll = mock.Mock() + d._open = True + + def moveR(dx, dy, _): + pos['v'] = (pos['v'][0] + dx, pos['v'][1] + dy) + + d._dll.moveR.side_effect = moveR + with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \ + mock.patch.object(di.time, 'sleep', lambda s: None): + self.assertTrue(d.move_to(300, 200)) + self.assertEqual(pos['v'], (300, 200)) + + def test_gives_up_when_moves_do_nothing(self): + """驱动不理人时不能假称到位 —— 那样会点错地方。""" + d = di.DriverInput(dll_path='X.dll', log=lambda m: None) + d._dll = mock.Mock() + d._open = True + with mock.patch.object(di, 'get_cursor', lambda: (0, 0)), \ + mock.patch.object(di.time, 'sleep', lambda s: None): + self.assertFalse(d.move_to(300, 200, iters=4)) + + def test_tolerance_is_respected(self): + """已经在容差内就不该再发位移 —— 白折腾还容易引入抖动。""" + d = di.DriverInput(dll_path='X.dll', log=lambda m: None) + d._dll = mock.Mock() + d._open = True + with mock.patch.object(di, 'get_cursor', lambda: (100, 100)), \ + mock.patch.object(di.time, 'sleep', lambda s: None): + self.assertTrue(d.move_to(101, 101, tol=1)) + self.assertEqual(d._dll.moveR.call_count, 0, '容差内不该发位移') + + def test_out_of_tolerance_does_move(self): + """超出容差就必须尝试移动, 只是驱动不动时要如实返回失败。""" + d = di.DriverInput(dll_path='X.dll', log=lambda m: None) + d._dll = mock.Mock() + d._open = True + with mock.patch.object(di, 'get_cursor', lambda: (100, 100)), \ + mock.patch.object(di.time, 'sleep', lambda s: None): + self.assertFalse(d.move_to(105, 105, tol=1, iters=3)) + self.assertGreater(d._dll.moveR.call_count, 0) + + +class ClickTest(unittest.TestCase): + """没到位置就绝不点。""" + + def _drv(self, reachable): + d = di.DriverInput(dll_path='X.dll', log=lambda m: None) + d._dll = mock.Mock() + d._open = True + return d + + def test_clicks_only_after_positioning(self): + pos = {'v': (0, 0)} + d = self._drv(True) + d._dll.moveR.side_effect = lambda dx, dy, _: pos.update( + {'v': (pos['v'][0] + dx, pos['v'][1] + dy)}) + with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \ + mock.patch.object(di.time, 'sleep', lambda s: None): + self.assertTrue(d.click(500, 400)) + self.assertEqual(pos['v'], (500, 400)) + d._dll.mouse_down.assert_called_once_with(1) + d._dll.mouse_up.assert_called_once_with(1) + + def test_never_clicks_when_positioning_fails(self): + d = self._drv(False) + with mock.patch.object(di, 'get_cursor', lambda: (0, 0)), \ + mock.patch.object(di.time, 'sleep', lambda s: None): + self.assertFalse(d.click(500, 400)) + d._dll.mouse_down.assert_not_called() + d._dll.mouse_up.assert_not_called() + + +class InstallTest(unittest.TestCase): + """接管 AALC 的点击: 条件不满足时**一个都不许改**。""" + + def _auto(self): + auto = mock.Mock() + auto.input_handler = mock.Mock() + auto.mouse_click = auto.input_handler.mouse_click + return auto + + def test_refuses_quietly_when_preflight_fails(self): + auto = self._auto() + before = auto.input_handler + drv = mock.Mock() + drv.preflight.return_value = (False, '不是物理会话') + got = ap.install_driver_click(auto, mock.Mock(), driver=drv, log=lambda m: None) + self.assertIsNone(got) + self.assertIs(auto.input_handler, before, '条件不满足就不该换 handler') + + def test_rebinds_the_aliases_captured_at_init(self): + """automation.py 初始化时把方法绑成了别名, 光换 handler 影响不到那些别名。""" + auto = self._auto() + old_click = auto.mouse_click + drv = mock.Mock() + drv.preflight.return_value = (True, 'ok') + got = ap.install_driver_click(auto, mock.Mock(), driver=drv, log=lambda m: None) + self.assertIs(got, drv) + self.assertIsNot(auto.mouse_click, old_click, '别名必须重绑') + + def test_proxy_other_methods_fall_through(self): + """拖拽/滑动/滚轮等仍走 AALC 原逻辑, 不能被吞掉。""" + handler = mock.Mock() + proxy = ap.DriverClickProxy(handler, mock.Mock(), mock.Mock(), log=lambda m: None) + proxy.mouse_drag(10, 20, 0.5, 0, 100, True) + handler.mouse_drag.assert_called_once() + proxy.wait_pause() + handler.wait_pause.assert_called_once() + + +class ClientToScreenTest(unittest.TestCase): + + def test_uses_client_to_screen(self): + pt = mock.Mock(x=0, y=0) + + def fake(hwnd, byref_pt): + ptr = byref_pt._obj + ptr.x, ptr.y = ptr.x + 100, ptr.y + 50 + return 1 + + with mock.patch.object(di.ctypes.windll.user32, 'ClientToScreen', fake): + self.assertEqual(di.client_to_screen(123, 7, 9), (107, 59)) + + +if __name__ == '__main__': + unittest.main()