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

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
+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))