Files
lc-mcp/backends/interception_win.py
T

240 lines
9.2 KiB
Python

# -*- coding: utf-8 -*-
"""Interception 物理输入后端(Windows + Interception 驱动)。
输入在驱动层转为真实 HID 事件(对应用透明,非 SendInput 虚拟输入)。
需要: install-interception.exe /install 后重启系统,且本 dll 与驱动共存。
API 以 oblitum/Interception interception.h 为准:
设备号 1..10 = 键盘, 11..20 = 鼠标; 没有 open_device 之类的函数。
interception_send(ctx, device, stroke*, nstroke) 第 4 个参数是 stroke 个数, 不是字节数。
"""
import ctypes
import time
from ._util import parse_combo, win_dpi_aware
# ---- Interception 常量 ----
MOUSE_LEFTBUTTON_DOWN = 0x001
MOUSE_LEFTBUTTON_UP = 0x002
MOUSE_RIGHTBUTTON_DOWN = 0x004
MOUSE_RIGHTBUTTON_UP = 0x008
MOUSE_MIDDLEBUTTON_DOWN = 0x010
MOUSE_MIDDLEBUTTON_UP = 0x020
MOUSE_MOVE_RELATIVE = 0x000
MOUSE_MOVE_ABSOLUTE = 0x001
MOUSE_VIRTUAL_DESKTOP = 0x002
KEY_DOWN = 0x00
KEY_UP = 0x01
KEY_E0 = 0x02
MAX_KEYBOARD = 10
MAX_MOUSE = 10
KEYBOARD_DEVS = range(1, MAX_KEYBOARD + 1)
MOUSE_DEVS = range(MAX_KEYBOARD + 1, MAX_KEYBOARD + MAX_MOUSE + 1)
# ---- Set 1 扫描码 ----
SCAN = {
'a': 0x1E, 'b': 0x30, 'c': 0x2E, 'd': 0x20, 'e': 0x12, 'f': 0x21,
'g': 0x22, 'h': 0x23, 'i': 0x17, 'j': 0x24, 'k': 0x25, 'l': 0x26,
'm': 0x32, 'n': 0x31, 'o': 0x18, 'p': 0x19, 'q': 0x10, 'r': 0x13,
's': 0x1F, 't': 0x14, 'u': 0x16, 'v': 0x2F, 'w': 0x11, 'x': 0x2D,
'y': 0x15, 'z': 0x2C,
'1': 0x02, '2': 0x03, '3': 0x04, '4': 0x05, '5': 0x06,
'6': 0x07, '7': 0x08, '8': 0x09, '9': 0x0A, '0': 0x0B,
'enter': 0x1C, 'esc': 0x01, 'space': 0x39, 'tab': 0x0F, 'backspace': 0x0E,
'ctrl': 0x1D, 'alt': 0x38, 'lshift': 0x2A, 'rshift': 0x36, 'shift': 0x2A,
'f1': 0x3B, 'f2': 0x3C, 'f3': 0x3D, 'f4': 0x3E, 'f5': 0x3F, 'f6': 0x40,
'f7': 0x41, 'f8': 0x42, 'f9': 0x43, 'f10': 0x44, 'f11': 0x57, 'f12': 0x58,
',': 0x33, '.': 0x34, '/': 0x35, ';': 0x27, "'": 0x28, '[': 0x1A,
']': 0x1B, '-': 0x0C, '=': 0x0D, '`': 0x29, '\\': 0x2B,
}
# 扩展键: 扫描码同小键盘, 需带 E0 前缀
SCAN_E0 = {
'up': 0x48, 'down': 0x50, 'left': 0x4B, 'right': 0x4D,
'home': 0x47, 'end': 0x4F, 'pageup': 0x49, 'pagedown': 0x51,
'insert': 0x52, 'delete': 0x53, 'rctrl': 0x1D, 'ralt': 0x38, 'lwin': 0x5B,
}
UPPER_SCAN = { # 需按住 Shift 的符号
'!': 0x02, '@': 0x03, '#': 0x04, '$': 0x05, '%': 0x06, '^': 0x07,
'&': 0x08, '*': 0x09, '(': 0x0A, ')': 0x0B, '_': 0x0C, '+': 0x0D,
'{': 0x1A, '}': 0x1B, ':': 0x27, '"': 0x28, '<': 0x33, '>': 0x34,
'?': 0x35, '~': 0x29, '|': 0x2B,
}
class MouseStroke(ctypes.Structure):
# interception.h: unsigned short state, flags; short rolling; int x, y; unsigned int information
_fields_ = [("state", ctypes.c_ushort), ("flags", ctypes.c_ushort),
("rolling", ctypes.c_short), ("x", ctypes.c_int),
("y", ctypes.c_int), ("information", ctypes.c_uint)]
class KeyStroke(ctypes.Structure):
_fields_ = [("code", ctypes.c_ushort), ("state", ctypes.c_ushort),
("information", ctypes.c_uint)]
def key_strokes(key):
"""键名 -> (scancode, e0) ; 未知返回 None。"""
if key in SCAN:
return SCAN[key], False
if key in SCAN_E0:
return SCAN_E0[key], True
return None
def to_absolute(v, size):
"""像素 -> Interception 绝对坐标 0..65535 (主屏)。"""
if size <= 1:
return 0
v = min(max(int(v), 0), size - 1)
return int(round(v * 65535.0 / (size - 1)))
class InterceptionBackend:
def __init__(self, dll_path=None, keyboard=None, mouse=None):
if dll_path is None:
dll_path = r'C:\Program Files\Interception\interception.dll'
try:
self.dll = ctypes.CDLL(dll_path)
except OSError:
# 兜底:尝试系统 PATH / 常见目录
self.dll = ctypes.CDLL('interception.dll')
self._api()
self._user32 = ctypes.WinDLL('user32', use_last_error=True)
win_dpi_aware(self._user32)
self.ctx = self.dll.interception_create_context()
if not self.ctx:
raise RuntimeError('interception_create_context failed (驱动未安装/未重启?)')
# 只往一个设备发: 广播到所有键盘会让同一个键被按多次
self.kbd = keyboard or self._first_present(KEYBOARD_DEVS)
self.mou = mouse or self._first_present(MOUSE_DEVS)
self._scr_w = self._user32.GetSystemMetrics(0)
self._scr_h = self._user32.GetSystemMetrics(1)
def __del__(self):
try:
if getattr(self, 'ctx', None):
self.dll.interception_destroy_context(self.ctx)
self.ctx = None
except Exception:
pass
def _api(self):
d = self.dll
d.interception_create_context.restype = ctypes.c_void_p
d.interception_create_context.argtypes = []
d.interception_destroy_context.restype = None
d.interception_destroy_context.argtypes = [ctypes.c_void_p]
d.interception_get_hardware_id.restype = ctypes.c_uint
d.interception_get_hardware_id.argtypes = [ctypes.c_void_p, ctypes.c_int,
ctypes.c_void_p, ctypes.c_uint]
d.interception_send.restype = ctypes.c_int
d.interception_send.argtypes = [ctypes.c_void_p, ctypes.c_int,
ctypes.c_void_p, ctypes.c_uint]
def hardware_id(self, dev):
buf = ctypes.create_string_buffer(512)
n = self.dll.interception_get_hardware_id(self.ctx, dev, buf, ctypes.sizeof(buf))
if not n or n > ctypes.sizeof(buf):
return ''
# 驱动返回 UTF-16 (REG_MULTI_SZ), 取第一个
return buf.raw[:n].decode('utf-16-le', 'replace').split('\x00')[0]
def _first_present(self, devs):
for dev in devs:
if self.hardware_id(dev):
return dev
return devs[0]
def set_screen(self, w, h):
"""以截图尺寸为准(会话 0 / DPI 虚拟化下 GetSystemMetrics 不可信)。"""
self._scr_w, self._scr_h = int(w), int(h)
# ---- 底层发送 ----
def _send(self, dev, stroke):
n = self.dll.interception_send(self.ctx, dev, ctypes.byref(stroke), 1)
if n != 1:
raise RuntimeError('interception_send(dev=%d) returned %d' % (dev, n))
def _kbd_stroke(self, code, state, e0=False):
ks = KeyStroke(code=code, state=state | (KEY_E0 if e0 else 0))
self._send(self.kbd, ks)
def _mouse_stroke(self, state=0, flags=0, x=0, y=0):
self._send(self.mou, MouseStroke(state=state, flags=flags, x=int(x), y=int(y)))
def _tap(self, code, e0=False, hold=0.04):
self._kbd_stroke(code, KEY_DOWN, e0)
time.sleep(hold)
self._kbd_stroke(code, KEY_UP, e0)
# ---- 公开动作 ----
def move(self, x, y):
nx = to_absolute(x, self._scr_w)
ny = to_absolute(y, self._scr_h)
self._mouse_stroke(state=0, flags=MOUSE_MOVE_ABSOLUTE, x=nx, y=ny)
time.sleep(0.03)
return {'ok': True, 'backend': 'interception'}
def click(self, x, y, button='left', clicks=1):
self.move(x, y)
time.sleep(0.05)
if button == 'left':
down, up = MOUSE_LEFTBUTTON_DOWN, MOUSE_LEFTBUTTON_UP
else:
down, up = MOUSE_RIGHTBUTTON_DOWN, MOUSE_RIGHTBUTTON_UP
for _ in range(max(1, int(clicks))):
self._mouse_stroke(state=down)
time.sleep(0.06)
self._mouse_stroke(state=up)
time.sleep(0.06)
return {'ok': True, 'clicked': [int(x), int(y)], 'backend': 'interception'}
def keypress(self, key):
try:
parts = parse_combo(key)
except ValueError as e:
return {'ok': False, 'error': str(e)}
strokes = [key_strokes(p) for p in parts]
if None in strokes:
return {'ok': False, 'error': 'unknown key %s' % key}
for code, e0 in strokes[:-1]: # 修饰键按下
self._kbd_stroke(code, KEY_DOWN, e0)
time.sleep(0.03)
self._tap(*strokes[-1])
for code, e0 in reversed(strokes[:-1]):
time.sleep(0.03)
self._kbd_stroke(code, KEY_UP, e0)
return {'ok': True, 'key': str(key), 'backend': 'interception'}
def type_text(self, text):
text = str(text)
plan = []
for ch in text:
low = ch.lower()
if ch == ' ':
plan.append((SCAN['space'], False))
elif ch == '\n':
plan.append((SCAN['enter'], False))
elif low in SCAN and len(low) == 1:
plan.append((SCAN[low], ch.isupper()))
elif ch in UPPER_SCAN:
plan.append((UPPER_SCAN[ch], True))
else:
# 扫描码只能打 US 布局 ASCII; 中文请用 sendinput 后端(KEYEVENTF_UNICODE)
return {'ok': False, 'error': 'untypable char %r (interception 只支持 ASCII)' % ch}
for code, shift in plan:
if shift:
self._kbd_stroke(SCAN['shift'], KEY_DOWN)
time.sleep(0.02)
self._tap(code, hold=0.03)
if shift:
time.sleep(0.02)
self._kbd_stroke(SCAN['shift'], KEY_UP)
time.sleep(0.03)
return {'ok': True, 'typed': text, 'backend': 'interception'}