| 1 | |
| 2 | """Private IBus bridge. Text is transient and is never logged or persisted.""" |
| 3 | import json |
| 4 | import os |
| 5 | from pathlib import Path |
| 6 | import re |
| 7 | import socket |
| 8 | import sys |
| 9 | |
| 10 | directory = (Path('/run/cage-phone-desktop/input') if os.environ.get('CAGE_PHONE_DESKTOP_INPUT') == '1' |
| 11 | else Path.home() / '.cache' / 'cage-input') |
| 12 | socket_path = directory / 'input.sock' |
| 13 | limit = 32768 |
| 14 | |
| 15 | |
| 16 | def request(): |
| 17 | data = sys.stdin.buffer.readline(limit + 1) |
| 18 | if not data: |
| 19 | raise EOFError |
| 20 | if len(data) > limit or not data.endswith(b'\n'): |
| 21 | raise ValueError('Invalid input request') |
| 22 | with socket.socket(socket.AF_UNIX) as client: |
| 23 | client.settimeout(3) |
| 24 | client.connect(str(socket_path)) |
| 25 | client.sendall(data) |
| 26 | result = client.makefile('rb').readline(limit + 1) |
| 27 | if len(result) > limit or not result.endswith(b'\n'): |
| 28 | raise ValueError('Invalid input response') |
| 29 | sys.stdout.buffer.write(result) |
| 30 | sys.stdout.buffer.flush() |
| 31 | |
| 32 | |
| 33 | if __name__ == '__main__' and sys.argv[1:] == ['--request']: |
| 34 | try: |
| 35 | request() |
| 36 | except (OSError, ValueError, EOFError): |
| 37 | print('{"available":false}') |
| 38 | sys.exit(0) |
| 39 | |
| 40 | if __name__ == '__main__' and sys.argv[1:] == ['--relay']: |
| 41 | |
| 42 | |
| 43 | while True: |
| 44 | try: |
| 45 | request() |
| 46 | except EOFError: |
| 47 | break |
| 48 | except OSError: |
| 49 | print('{"available":false}', flush=True) |
| 50 | except ValueError: |
| 51 | |
| 52 | sys.exit(1) |
| 53 | sys.exit(0) |
| 54 | |
| 55 | import gi |
| 56 | import secrets |
| 57 | import socketserver |
| 58 | import subprocess |
| 59 | import threading |
| 60 | import time |
| 61 | |
| 62 | gi.require_version('IBus', '1.0') |
| 63 | from gi.repository import IBus, GLib |
| 64 | |
| 65 | IBus.init() |
| 66 | active = None |
| 67 | engines = [] |
| 68 | probe_key = 0xffd5 |
| 69 | |
| 70 | |
| 71 | def prepare_probe(): |
| 72 | |
| 73 | |
| 74 | |
| 75 | try: |
| 76 | mapping = subprocess.check_output(['xmodmap', '-pke'], text=True) |
| 77 | empty = [] |
| 78 | for line in mapping.splitlines(): |
| 79 | match = re.fullmatch(r'keycode\s+(\d+)\s*=\s*(.*)', line) |
| 80 | if not match: |
| 81 | continue |
| 82 | symbols = match[2].split() |
| 83 | if symbols and symbols[0] == 'F24': |
| 84 | return True |
| 85 | if int(match[1]) >= 128 and not symbols: |
| 86 | empty.append(int(match[1])) |
| 87 | if not empty: |
| 88 | return False |
| 89 | subprocess.run(['xmodmap', '-e', f'keycode {max(empty)} = F24'], |
| 90 | check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 91 | return True |
| 92 | except (OSError, subprocess.SubprocessError): |
| 93 | return False |
| 94 | |
| 95 | |
| 96 | probe_ready = prepare_probe() |
| 97 | |
| 98 | |
| 99 | class Engine(IBus.Engine): |
| 100 | __gtype_name__ = 'CageInputEngine' |
| 101 | |
| 102 | def __init__(self, **args): |
| 103 | super().__init__(**args) |
| 104 | self.context = '' |
| 105 | self.session = '' |
| 106 | self.sequence = -1 |
| 107 | self.rect = None |
| 108 | self.purpose = 0 |
| 109 | self.probing = False |
| 110 | self.probe_seen = False |
| 111 | self.reachable = False |
| 112 | self.updated = 0 |
| 113 | |
| 114 | def clear(self): |
| 115 | self.update_preedit_text(IBus.Text.new_from_string(''), 0, False) |
| 116 | self.session = '' |
| 117 | self.sequence = -1 |
| 118 | |
| 119 | def do_focus_in(self): |
| 120 | global active |
| 121 | if active is not self: |
| 122 | self.context = secrets.token_hex(16) |
| 123 | self.rect = None |
| 124 | self.reachable = False |
| 125 | active = self |
| 126 | |
| 127 | def do_focus_in_id(self, path, client): |
| 128 | |
| 129 | global active |
| 130 | if self.context_path != str(path): |
| 131 | self.clear() |
| 132 | self.context = secrets.token_hex(16) |
| 133 | self.rect = None |
| 134 | self.context_path = str(path) |
| 135 | self.do_focus_in() |
| 136 | |
| 137 | context_path = '' |
| 138 | |
| 139 | def do_focus_out(self): |
| 140 | global active |
| 141 | self.clear() |
| 142 | self.rect = None |
| 143 | self.probing = False |
| 144 | self.reachable = False |
| 145 | if active is self: |
| 146 | active = None |
| 147 | |
| 148 | def do_focus_out_id(self, path): |
| 149 | self.do_focus_out() |
| 150 | |
| 151 | def do_reset(self): |
| 152 | self.clear() |
| 153 | self.context = secrets.token_hex(16) |
| 154 | self.reachable = False |
| 155 | |
| 156 | def do_set_cursor_location(self, x, y, width, height): |
| 157 | self.rect = [x, y, width, height] |
| 158 | |
| 159 | def do_set_content_type(self, purpose, hints): |
| 160 | self.purpose = int(purpose) |
| 161 | |
| 162 | def do_process_key_event(self, keyval, keycode, state): |
| 163 | if self.probing and keyval == probe_key: |
| 164 | self.probe_seen = True |
| 165 | self.reachable = True |
| 166 | return True |
| 167 | return False |
| 168 | |
| 169 | |
| 170 | bus = IBus.Bus() |
| 171 | if not bus.is_connected(): |
| 172 | raise RuntimeError('Private input bus unavailable') |
| 173 | |
| 174 | |
| 175 | class Factory(IBus.Factory): |
| 176 | def do_create_engine(self, name): |
| 177 | options = dict(connection=bus.get_connection(), |
| 178 | object_path='/org/freedesktop/IBus/Cage/' + str(len(engines))) |
| 179 | |
| 180 | |
| 181 | if IBus.Engine.find_property('has-focus-id') is not None: |
| 182 | options['has_focus_id'] = True |
| 183 | engine = Engine(**options) |
| 184 | engines.append(engine) |
| 185 | return engine |
| 186 | |
| 187 | |
| 188 | factory = Factory(connection=bus.get_connection(), object_path=IBus.PATH_FACTORY) |
| 189 | component = IBus.Component(name='org.freedesktop.IBus.Cage', description='Cage host input', |
| 190 | version='1', license='MIT', author='Cage', homepage='', |
| 191 | command_line='', textdomain='') |
| 192 | component.add_engine(IBus.EngineDesc(name='cage-host', longname='Cage Host Input', |
| 193 | description='Host input transport', language='en', |
| 194 | license='MIT', author='Cage', icon='', layout='us')) |
| 195 | if not bus.register_component(component): |
| 196 | raise RuntimeError('Private input engine unavailable') |
| 197 | |
| 198 | |
| 199 | def snapshot(engine): |
| 200 | if engine is None or engine is not active or not engine.reachable or engine.purpose in (8, 9): |
| 201 | return {'available': False} |
| 202 | return {'available': True, 'context': engine.context, 'rect': engine.rect} |
| 203 | |
| 204 | |
| 205 | def utf16_index(text, offset): |
| 206 | if type(offset) is not int or offset < 0: |
| 207 | raise ValueError('Invalid input range') |
| 208 | data = text.encode('utf-16-le') |
| 209 | if offset * 2 > len(data): |
| 210 | raise ValueError('Invalid input range') |
| 211 | return len(data[:offset * 2].decode('utf-16-le')) |
| 212 | |
| 213 | |
| 214 | def apply(value): |
| 215 | engine = active |
| 216 | mode = value.get('mode') |
| 217 | if mode in ('phone-status', 'phone-text', 'phone-char') and os.environ.get('CAGE_PHONE_DESKTOP_INPUT') == '1': |
| 218 | if engine is None or not engine.reachable or not engine.context: |
| 219 | return {'available': False} |
| 220 | password = engine.purpose in (8, 9) |
| 221 | if mode == 'phone-status': |
| 222 | return {'available': True, 'context': engine.context, 'password': password} |
| 223 | text = value.get('text', '') |
| 224 | if engine.context != value.get('context') or not isinstance(text, str) or not text: |
| 225 | return {'available': False} |
| 226 | if mode == 'phone-text' and (password or len(text.encode()) > 8192): |
| 227 | return {'available': False} |
| 228 | if mode == 'phone-char' and (len(text) != 1 or not (' ' <= text <= '~')): |
| 229 | return {'available': False} |
| 230 | engine.commit_text(IBus.Text.new_from_string(text)) |
| 231 | return {'available': True} |
| 232 | if mode == 'status': |
| 233 | if engine is not None and engine.session and value.get('session') == engine.session: |
| 234 | engine.updated = time.monotonic() |
| 235 | return snapshot(engine) |
| 236 | session = value.get('session', '') |
| 237 | sequence = value.get('sequence') |
| 238 | if not isinstance(session, str) or not re.fullmatch('[a-f0-9]{32}', session): |
| 239 | raise ValueError('Invalid input session') |
| 240 | if type(sequence) is not int or sequence < 0: |
| 241 | raise ValueError('Invalid input sequence') |
| 242 | if mode == 'cancel': |
| 243 | |
| 244 | for old in engines: |
| 245 | if old.session == session and sequence > old.sequence: |
| 246 | old.clear() |
| 247 | return {'available': False} |
| 248 | if not snapshot(engine)['available']: |
| 249 | return {'available': False} |
| 250 | if mode == 'begin': |
| 251 | if value.get('context') != engine.context: |
| 252 | raise ValueError('Input target changed') |
| 253 | engine.clear() |
| 254 | engine.session = session |
| 255 | engine.sequence = sequence |
| 256 | engine.updated = time.monotonic() |
| 257 | return snapshot(engine) |
| 258 | if engine.session != session or sequence <= engine.sequence: |
| 259 | raise ValueError('Input session expired') |
| 260 | text = value.get('text', '') |
| 261 | if not isinstance(text, str) or len(text.encode('utf-8')) > 8192: |
| 262 | raise ValueError('Input text too large') |
| 263 | if mode == 'update': |
| 264 | start = utf16_index(text, value.get('selectionStart', 0)) |
| 265 | end = utf16_index(text, value.get('selectionEnd', 0)) |
| 266 | if end < start: |
| 267 | raise ValueError('Invalid input range') |
| 268 | preedit = IBus.Text.new_from_string(text) |
| 269 | preedit.append_attribute(IBus.AttrType.UNDERLINE, IBus.AttrUnderline.SINGLE, 0, len(text)) |
| 270 | if end > start: |
| 271 | preedit.append_attribute(IBus.AttrType.BACKGROUND, 0x3584e4, start, end) |
| 272 | preedit.append_attribute(IBus.AttrType.FOREGROUND, 0xffffff, start, end) |
| 273 | engine.update_preedit_text_with_mode(preedit, end, bool(text), IBus.PreeditFocusMode.CLEAR) |
| 274 | engine.sequence = sequence |
| 275 | engine.updated = time.monotonic() |
| 276 | elif mode == 'commit': |
| 277 | engine.clear() |
| 278 | if text: |
| 279 | engine.commit_text(IBus.Text.new_from_string(text)) |
| 280 | else: |
| 281 | raise ValueError('Invalid input mode') |
| 282 | return snapshot(engine) |
| 283 | |
| 284 | |
| 285 | class Handler(socketserver.StreamRequestHandler): |
| 286 | def handle(self): |
| 287 | self.connection.settimeout(3) |
| 288 | try: |
| 289 | line = self.rfile.readline(limit + 1) |
| 290 | if len(line) > limit or not line.endswith(b'\n'): |
| 291 | raise ValueError('Invalid input request') |
| 292 | value = json.loads(line) |
| 293 | if not isinstance(value, dict): |
| 294 | raise ValueError('Invalid input request') |
| 295 | done = threading.Event() |
| 296 | result = {} |
| 297 | |
| 298 | def dispatch(): |
| 299 | try: |
| 300 | result.update(apply(value)) |
| 301 | except UnicodeError: |
| 302 | result.update(error='Invalid input range') |
| 303 | except ValueError as error: |
| 304 | |
| 305 | |
| 306 | result.update(error=str(error)) |
| 307 | finally: |
| 308 | done.set() |
| 309 | return False |
| 310 | |
| 311 | def probe(): |
| 312 | engine = active |
| 313 | desktop_probe = (os.environ.get('CAGE_PHONE_DESKTOP_INPUT') == '1' and |
| 314 | value.get('mode') in ('phone-status', 'phone-text', 'phone-char')) |
| 315 | ordinary_probe = value.get('mode') in ('status', 'begin') and engine is not None and engine.purpose not in (8, 9) |
| 316 | if probe_ready and engine is not None and (desktop_probe or ordinary_probe): |
| 317 | engine.probing = True |
| 318 | engine.probe_seen = False |
| 319 | subprocess.Popen(['xdotool', 'key', '--delay', '0', 'F24'], |
| 320 | stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 321 | |
| 322 | def finish(): |
| 323 | engine.probing = False |
| 324 | engine.reachable = engine.probe_seen and engine is active |
| 325 | return dispatch() |
| 326 | GLib.timeout_add(45, finish) |
| 327 | else: |
| 328 | dispatch() |
| 329 | return False |
| 330 | |
| 331 | GLib.idle_add(probe) |
| 332 | if not done.wait(2): |
| 333 | result = {'error': 'Input bridge timed out'} |
| 334 | self.wfile.write((json.dumps(result, separators=(',', ':')) + '\n').encode()) |
| 335 | except (OSError, ValueError): |
| 336 | pass |
| 337 | |
| 338 | |
| 339 | class Server(socketserver.ThreadingUnixStreamServer): |
| 340 | daemon_threads = True |
| 341 | |
| 342 | |
| 343 | directory.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 344 | os.chmod(directory, 0o700) |
| 345 | socket_path.unlink(missing_ok=True) |
| 346 | server = Server(str(socket_path), Handler) |
| 347 | os.chmod(socket_path, 0o600) |
| 348 | threading.Thread(target=server.serve_forever, daemon=True).start() |
| 349 | |
| 350 | |
| 351 | def activate(): |
| 352 | def finish(source, result): |
| 353 | if source.set_global_engine_async_finish(result): |
| 354 | (directory / 'ready').touch(mode=0o600) |
| 355 | bus.set_global_engine_async('cage-host', 10000, None, finish) |
| 356 | return False |
| 357 | |
| 358 | |
| 359 | def expire(): |
| 360 | for engine in engines: |
| 361 | if engine.session and time.monotonic() - engine.updated > 10: |
| 362 | engine.clear() |
| 363 | return True |
| 364 | |
| 365 | |
| 366 | GLib.timeout_add(200, activate) |
| 367 | GLib.timeout_add_seconds(1, expire) |
| 368 | GLib.MainLoop().run() |