Files
lc-mcp/backends/xdotool_linux.py
T

56 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""Linux X11 输入后端:xdotool(X 事件注入,xdotool 需已安装)。
物理化升级路径: uinput 后端(虚拟内核 evdev 设备)。
"""
import shutil
import subprocess
from ._util import parse_combo
# 内部键名 -> X keysym
KEYSYM = {'enter': 'Return', 'esc': 'Escape', 'space': 'space', 'tab': 'Tab',
'backspace': 'BackSpace', 'alt': 'Alt_L', 'ralt': 'Alt_R', 'ctrl': 'Control_L',
'rctrl': 'Control_R', 'shift': 'Shift_L', 'lshift': 'Shift_L', 'rshift': 'Shift_R',
'lwin': 'Super_L', 'up': 'Up', 'down': 'Down', 'left': 'Left', 'right': 'Right',
'home': 'Home', 'end': 'End', 'pageup': 'Prior', 'pagedown': 'Next',
'insert': 'Insert', 'delete': 'Delete'}
KEYSYM.update({'f%d' % i: 'F%d' % i for i in range(1, 13)})
def _run(args):
r = subprocess.run(args, capture_output=True, text=True, timeout=30)
if r.returncode != 0:
raise RuntimeError('%s failed: %s' % (' '.join(args[:2]), (r.stderr or '').strip()[-200:]))
return r
class XdotoolBackend:
def __init__(self):
if not shutil.which('xdotool'):
raise RuntimeError('xdotool not found (apt install xdotool)')
def move(self, x, y):
_run(['xdotool', 'mousemove', '--sync', str(int(x)), str(int(y))])
return {'ok': True, 'backend': 'xdotool'}
def click(self, x, y, button='left', clicks=1):
btn = {'left': '1', 'right': '3', 'middle': '2'}.get(button, '1')
_run(['xdotool', 'mousemove', '--sync', str(int(x)), str(int(y)),
'click', '--repeat', str(max(1, int(clicks))), '--delay', '60', btn])
return {'ok': True, 'clicked': [int(x), int(y)], 'backend': 'xdotool'}
def keypress(self, key):
try:
parts = parse_combo(key)
except ValueError as e:
return {'ok': False, 'error': str(e)}
combo = '+'.join(KEYSYM.get(p, p) for p in parts)
_run(['xdotool', 'key', '--', combo])
return {'ok': True, 'key': str(key), 'backend': 'xdotool'}
def type_text(self, text):
# '--' 防止以 '-' 开头的文本被当成选项
_run(['xdotool', 'type', '--delay', '60', '--', str(text)])
return {'ok': True, 'typed': str(text), 'backend': 'xdotool'}