| 1 | |
| 2 | """Window-only capture and shared input for the existing Claude Desktop.""" |
| 3 | import base64 |
| 4 | import fcntl |
| 5 | import hashlib |
| 6 | import io |
| 7 | import json |
| 8 | import math |
| 9 | import os |
| 10 | from pathlib import Path |
| 11 | import secrets |
| 12 | import signal |
| 13 | import socket |
| 14 | import socketserver |
| 15 | import subprocess |
| 16 | import sys |
| 17 | import time |
| 18 | |
| 19 | from PIL import Image |
| 20 | from Xlib import X, XK, Xutil, display, error |
| 21 | from Xlib.ext import composite, xtest |
| 22 | |
| 23 | |
| 24 | class Failure(Exception): |
| 25 | def __init__(self, status): |
| 26 | self.status = status |
| 27 | |
| 28 | |
| 29 | def run(*args): |
| 30 | return subprocess.check_output(args, stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=3).decode() |
| 31 | |
| 32 | |
| 33 | layout_file = Path('/run/cage-phone-desktop/layout.json') |
| 34 | |
| 35 | |
| 36 | def display_scale(): |
| 37 | path = Path('/run/cage-desktop/display-scale') |
| 38 | value = float(path.read_text()) if path.exists() else 2 |
| 39 | |
| 40 | if not math.isfinite(value) or not .75 <= value <= 8: |
| 41 | raise Failure(503) |
| 42 | return value |
| 43 | |
| 44 | |
| 45 | def set_display_scale(value): |
| 46 | dpi = round(value * 96 * 1024) |
| 47 | config = Path('/run/cage-desktop/xsettings.conf') |
| 48 | temporary = config.with_suffix('.new') |
| 49 | temporary.write_text(f'Xft/DPI {dpi}\nGdk/WindowScalingFactor 1\nGdk/UnscaledDPI {dpi}\nGtk/DecorationLayout ":"\n') |
| 50 | temporary.replace(config) |
| 51 | pid = int(Path('/run/cage-desktop/xsettings.pid').read_text()) |
| 52 | if Path(f'/proc/{pid}/comm').read_text().strip() != 'xsettingsd': |
| 53 | raise Failure(503) |
| 54 | os.kill(pid, signal.SIGHUP) |
| 55 | Path('/run/cage-desktop/display-scale').write_text(str(value) + '\n') |
| 56 | |
| 57 | |
| 58 | def encode_frame(image): |
| 59 | |
| 60 | |
| 61 | while True: |
| 62 | for quality in (92, 82, 68, 50): |
| 63 | buffer = io.BytesIO() |
| 64 | image.save(buffer, format='JPEG', quality=quality, subsampling=0) |
| 65 | if buffer.tell() <= 1900000: |
| 66 | return buffer.getvalue(), image.size |
| 67 | ratio = min(.85, math.sqrt(1900000 / buffer.tell()) * .95) |
| 68 | image = image.resize((max(1, round(image.width * ratio)), max(1, round(image.height * ratio))), |
| 69 | Image.Resampling.LANCZOS) |
| 70 | |
| 71 | |
| 72 | def save_layout(layout): |
| 73 | temporary = layout_file.with_suffix('.new') |
| 74 | temporary.write_text(json.dumps(layout)) |
| 75 | temporary.replace(layout_file) |
| 76 | |
| 77 | |
| 78 | def display_size(width, height): |
| 79 | name = f'cage-phone-{width}x{height}' |
| 80 | modes = run('xrandr', '--query') |
| 81 | if name not in modes: |
| 82 | run('xrandr', '--newmode', name, f'{(width+32)*(height+8)*60/1000000:.3f}', |
| 83 | *[str(v) for v in (width, width+8, width+16, width+32, height, height+1, height+2, height+8)], '+HSync', '-VSync') |
| 84 | run('xrandr', '--addmode', 'VNC-0', name) |
| 85 | run('xrandr', '--output', 'VNC-0', '--mode', name) |
| 86 | for line in modes.splitlines(): |
| 87 | fields = line.split() |
| 88 | if fields and fields[0].startswith('cage-phone-') and fields[0] != name: |
| 89 | run('xrandr', '--delmode', 'VNC-0', fields[0]) |
| 90 | run('xrandr', '--rmmode', fields[0]) |
| 91 | |
| 92 | |
| 93 | def restore_layout(): |
| 94 | if not layout_file.exists(): |
| 95 | return |
| 96 | with open('/run/cage-desktop/resize.lock', 'a') as lock: |
| 97 | fcntl.flock(lock, fcntl.LOCK_EX) |
| 98 | layout = json.loads(layout_file.read_text()) |
| 99 | |
| 100 | pending = Path('/run/cage-desktop/desktop-size') |
| 101 | latest = pending.read_text().split() if pending.exists() else [] |
| 102 | if len(latest) > 2: |
| 103 | layout['scale'] = float(latest[2]) |
| 104 | if 'scale' in layout and Path('/run/cage-desktop/xsettings.pid').exists(): |
| 105 | set_display_scale(layout['scale']) |
| 106 | conn = display.Display() |
| 107 | for wid, saved in layout['minimums'].items(): |
| 108 | try: |
| 109 | win = conn.create_resource_object('window', int(wid)) |
| 110 | pid = win.get_full_property(conn.intern_atom('_NET_WM_PID'), X.AnyPropertyType) |
| 111 | hints = win.get_wm_normal_hints() |
| 112 | if pid is not None and list(pid.value) == [saved['pid']] and hints: |
| 113 | values = dict(hints._data) |
| 114 | values.update(min_width=saved['width'], min_height=saved['height']) |
| 115 | win.set_wm_normal_hints(**values) |
| 116 | except error.XError: |
| 117 | |
| 118 | continue |
| 119 | conn.sync() |
| 120 | width, height = layout['width'], layout['height'] |
| 121 | if len(latest) > 1: |
| 122 | width, height = int(latest[0]), int(latest[1]) |
| 123 | display_size(width, height) |
| 124 | layout_file.unlink() |
| 125 | conn.close() |
| 126 | |
| 127 | |
| 128 | def fitted_window(size, window): |
| 129 | """Phone CSS rectangle actually occupied by the remote window.""" |
| 130 | ratio = min(size[0] / window.width, size[1] / window.height) |
| 131 | return ratio, (size[0] - window.width * ratio) / 2, (size[1] - window.height * ratio) / 2 |
| 132 | |
| 133 | |
| 134 | def native_input(payload): |
| 135 | with socket.socket(socket.AF_UNIX) as conn: |
| 136 | conn.settimeout(2) |
| 137 | conn.connect(str(Path.home() / '.cache/cage-input/input.sock')) |
| 138 | conn.sendall(json.dumps(payload).encode() + b'\n') |
| 139 | return json.loads(conn.makefile('rb').readline(32769)) |
| 140 | |
| 141 | |
| 142 | def token(*parts): |
| 143 | return hashlib.sha256(json.dumps(parts, separators=(',', ':')).encode()).hexdigest() |
| 144 | |
| 145 | |
| 146 | class View: |
| 147 | def __init__(self): |
| 148 | self.conn = display.Display() |
| 149 | self.root = self.conn.screen().root |
| 150 | self.id = os.environ['CAGE_PHONE_ID'] |
| 151 | self.generation = secrets.token_hex(16) |
| 152 | self.redirected = set() |
| 153 | self.size = None |
| 154 | self.pixels = None |
| 155 | self.scale = display_scale() |
| 156 | self.dynamic_scale = Path('/run/cage-desktop/xsettings.pid').exists() |
| 157 | self.requested_scale = self.scale |
| 158 | self.scale_ready = 0 |
| 159 | self.resize(int(os.environ['CAGE_PHONE_WIDTH']), int(os.environ['CAGE_PHONE_HEIGHT']), |
| 160 | float(os.environ.get('CAGE_PHONE_PIXEL_RATIO', '0'))) |
| 161 | self.last = time.monotonic() |
| 162 | |
| 163 | def resize(self, w, h, pixel_ratio=0): |
| 164 | if type(w) is not int or type(h) is not int or not (240 <= w <= 1440 and 160 <= h <= 1600): |
| 165 | raise Failure(400) |
| 166 | self.size = (w, h) |
| 167 | if type(pixel_ratio) not in (int, float) or not math.isfinite(pixel_ratio) or (pixel_ratio != 0 and not 1 <= pixel_ratio <= 8): |
| 168 | raise Failure(400) |
| 169 | if pixel_ratio: |
| 170 | self.requested_scale = pixel_ratio |
| 171 | self.fit_display() |
| 172 | |
| 173 | def fit_display(self): |
| 174 | with open('/run/cage-desktop/resize.lock', 'a') as lock: |
| 175 | fcntl.flock(lock, fcntl.LOCK_EX) |
| 176 | geometry = self.root.get_geometry() |
| 177 | current = (geometry.width, geometry.height) |
| 178 | if layout_file.exists(): |
| 179 | layout = json.loads(layout_file.read_text()) |
| 180 | |
| 181 | |
| 182 | if self.pixels is not None and current != self.pixels: |
| 183 | layout.update(width=current[0], height=current[1]) |
| 184 | save_layout(layout) |
| 185 | else: |
| 186 | minimums = {} |
| 187 | for wid in self.values(self.root, '_NET_CLIENT_LIST'): |
| 188 | win = self.window(wid) |
| 189 | if self.role(win) != 'desktop': |
| 190 | continue |
| 191 | hints = win.get_wm_normal_hints() |
| 192 | if hints and hints.flags & Xutil.PMinSize: |
| 193 | minimums[str(win.id)] = {'width':hints.min_width, 'height':hints.min_height, |
| 194 | 'pid':int(self.values(win, '_NET_WM_PID')[0])} |
| 195 | save_layout({'width':current[0], 'height':current[1], 'scale':self.scale, 'minimums':minimums}) |
| 196 | scale = min(self.requested_scale, 8192 / max(self.size)) if self.dynamic_scale else self.scale |
| 197 | if scale != self.scale: |
| 198 | set_display_scale(scale) |
| 199 | self.scale = scale |
| 200 | self.scale_ready = time.monotonic() + .2 |
| 201 | pixels = tuple(round(value * self.scale) for value in self.size) |
| 202 | if current != pixels: |
| 203 | display_size(*pixels) |
| 204 | self.pixels = pixels |
| 205 | |
| 206 | def fit_window(self, win, geometry): |
| 207 | width, height = self.pixels |
| 208 | if geometry.width <= width and geometry.height <= height: |
| 209 | return |
| 210 | hints = win.get_wm_normal_hints() |
| 211 | if not hints or not hints.flags & Xutil.PMinSize or win.get_wm_transient_for(): |
| 212 | return |
| 213 | if hints.min_width <= width and hints.min_height <= height: |
| 214 | return |
| 215 | layout = json.loads(layout_file.read_text()) |
| 216 | wid = str(win.id) |
| 217 | if wid not in layout['minimums']: |
| 218 | layout['minimums'][wid] = {'width':hints.min_width, 'height':hints.min_height, |
| 219 | 'pid':int(self.values(win, '_NET_WM_PID')[0])} |
| 220 | save_layout(layout) |
| 221 | values = dict(hints._data) |
| 222 | values.update(min_width=min(width, hints.min_width), min_height=min(height, hints.min_height)) |
| 223 | win.set_wm_normal_hints(**values) |
| 224 | self.conn.sync() |
| 225 | raise Failure(409) |
| 226 | |
| 227 | def values(self, win, name): |
| 228 | result = win.get_full_property(self.conn.intern_atom(name), X.AnyPropertyType) |
| 229 | return result.value if result is not None else [] |
| 230 | |
| 231 | def window(self, wid): |
| 232 | return self.conn.create_resource_object('window', int(wid)) |
| 233 | |
| 234 | def role(self, win): |
| 235 | pid = self.values(win, '_NET_WM_PID') |
| 236 | if len(pid) != 1 or win.get_attributes().map_state != X.IsViewable: |
| 237 | return '' |
| 238 | process = Path('/proc') / str(int(pid[0])) |
| 239 | try: |
| 240 | if process.stat().st_uid != os.getuid(): |
| 241 | return '' |
| 242 | exe = os.readlink(process / 'exe') |
| 243 | except OSError: |
| 244 | return '' |
| 245 | klass = {s.lower() for s in (win.get_wm_class() or ())} |
| 246 | if klass & {'com.anthropic.claude','claude','claude-desktop'}: |
| 247 | if exe == '/usr/lib/claude-desktop/claude-desktop': |
| 248 | return 'desktop' |
| 249 | return '' |
| 250 | |
| 251 | def active(self): |
| 252 | ids = self.values(self.root, '_NET_ACTIVE_WINDOW') |
| 253 | if not len(ids) or not ids[0]: |
| 254 | raise Failure(409) |
| 255 | win = self.window(ids[0]) |
| 256 | role = self.role(win) |
| 257 | if not role: |
| 258 | raise Failure(409) |
| 259 | g = win.get_geometry() |
| 260 | self.fit_window(win, g) |
| 261 | document = token(self.generation, win.id, role, *self.size, g.width, g.height) |
| 262 | return win, role, g, document |
| 263 | |
| 264 | def focus(self, win, role): |
| 265 | try: |
| 266 | value = native_input({'mode': 'status'}) |
| 267 | except (OSError, ValueError): |
| 268 | value = {} |
| 269 | ctx = value.get('context', '') |
| 270 | if not value.get('available') or not ctx: |
| 271 | return '', False, '' |
| 272 | return token(self.generation, win.id, ctx), False, ctx |
| 273 | |
| 274 | def snapshot(self): |
| 275 | self.fit_display() |
| 276 | if time.monotonic() < self.scale_ready: |
| 277 | raise Failure(409) |
| 278 | win, role, g, document = self.active() |
| 279 | if not (0 < g.width <= 8192 and 0 < g.height <= 8192): |
| 280 | raise Failure(409) |
| 281 | |
| 282 | |
| 283 | if win.id not in self.redirected: |
| 284 | win.composite_redirect_window(composite.RedirectAutomatic) |
| 285 | self.redirected.add(win.id) |
| 286 | self.conn.sync() |
| 287 | pixmap = win.composite_name_window_pixmap() |
| 288 | try: |
| 289 | raw = pixmap.get_image(0, 0, g.width, g.height, X.ZPixmap, 0xffffffff) |
| 290 | if raw.depth not in (24, 32): |
| 291 | raise Failure(503) |
| 292 | image = Image.frombytes('RGB', (g.width, g.height), raw.data, 'raw', 'BGRX') |
| 293 | finally: |
| 294 | pixmap.free() |
| 295 | ratio, left, top = fitted_window(self.size, g) |
| 296 | density = min(self.scale, 1 / ratio) |
| 297 | canvas = Image.new('RGB', (max(1, round(self.size[0] * density)), |
| 298 | max(1, round(self.size[1] * density))), '#181818') |
| 299 | image.thumbnail((max(1, round(g.width * ratio * density)), max(1, round(g.height * ratio * density))), |
| 300 | Image.Resampling.LANCZOS) |
| 301 | canvas.paste(image, (round(left * density), round(top * density))) |
| 302 | encoded, encoded_size = encode_frame(canvas) |
| 303 | focus, password, _ = self.focus(win, role) |
| 304 | if document != self.active()[3]: |
| 305 | raise Failure(409) |
| 306 | return {'id': self.id, 'width': self.size[0], 'height': self.size[1], 'document': document, |
| 307 | 'image': base64.b64encode(encoded).decode(), 'focus': focus, 'password': password, |
| 308 | 'pixel_width':encoded_size[0], 'pixel_height':encoded_size[1], |
| 309 | 'pixel_ratio':self.scale, 'requested_pixel_ratio':self.requested_scale, |
| 310 | 'pixel_ratio_control':self.dynamic_scale, |
| 311 | 'window': role, 'title': 'Claude Desktop', 'shared': True} |
| 312 | |
| 313 | def switch(self, role): |
| 314 | for wid in reversed(self.values(self.root, '_NET_CLIENT_LIST_STACKING')): |
| 315 | if self.role(self.window(wid)) == role: |
| 316 | run('xdotool', 'windowactivate', '--sync', str(int(wid))) |
| 317 | return |
| 318 | raise Failure(409) |
| 319 | |
| 320 | def action(self, req): |
| 321 | kind = req.get('type') |
| 322 | if kind == 'resize': |
| 323 | self.resize(req.get('width'), req.get('height'), req.get('pixel_ratio', 0)) |
| 324 | return |
| 325 | win, role, geometry, document = self.active() |
| 326 | if document != req.get('document'): |
| 327 | raise Failure(409) |
| 328 | if kind in ('desktop', 'login'): |
| 329 | self.switch(kind) |
| 330 | return |
| 331 | key = req.get('key', '') |
| 332 | ctx = None |
| 333 | if kind == 'text' or (kind == 'key' and (req.get('focus') or key == 'Enter' or len(key) == 1)): |
| 334 | focus, password, ctx = self.focus(win, role) |
| 335 | if not focus or req.get('focus') != focus or (password and kind == 'text'): |
| 336 | raise Failure(409) |
| 337 | if kind == 'text' or (kind == 'key' and len(key) == 1): |
| 338 | value = req.get('text') if kind == 'text' else key |
| 339 | if not isinstance(value, str) or not value or len(value.encode()) > 8192: |
| 340 | raise Failure(400) |
| 341 | if kind == 'key' and (role != 'login' or not (' ' <= key <= '~')): |
| 342 | raise Failure(400) |
| 343 | if document != self.active()[3]: |
| 344 | raise Failure(409) |
| 345 | session = secrets.token_hex(16) |
| 346 | result = native_input({'mode': 'begin', 'context': ctx, 'session': session, 'sequence': 0}) |
| 347 | if result.get('available'): |
| 348 | result = native_input({'mode': 'commit', 'session': session, 'sequence': 1, 'text': value}) |
| 349 | if not result.get('available'): |
| 350 | raise Failure(409) |
| 351 | return |
| 352 | |
| 353 | |
| 354 | self.conn.grab_server() |
| 355 | try: |
| 356 | if document != self.active()[3]: |
| 357 | raise Failure(409) |
| 358 | if kind == 'key': |
| 359 | names = {'Enter':'Return', 'Tab':'Tab', 'Escape':'Escape', 'Backspace':'BackSpace', 'Delete':'Delete', |
| 360 | 'ArrowLeft':'Left', 'ArrowRight':'Right', 'ArrowUp':'Up', 'ArrowDown':'Down'} |
| 361 | if key not in names: |
| 362 | raise Failure(400) |
| 363 | code = self.conn.keysym_to_keycode(XK.string_to_keysym(names[key])) |
| 364 | if not code: |
| 365 | raise Failure(400) |
| 366 | xtest.fake_input(self.conn, X.KeyPress, code) |
| 367 | xtest.fake_input(self.conn, X.KeyRelease, code) |
| 368 | return |
| 369 | if kind not in ('tap', 'scroll'): |
| 370 | raise Failure(400) |
| 371 | x, y = req.get('x'), req.get('y') |
| 372 | if not all(type(n) in (int, float) and math.isfinite(n) and 0 <= n < bound for n, bound in zip((x,y), self.size)): |
| 373 | raise Failure(400) |
| 374 | ratio, left, top = fitted_window(self.size, geometry) |
| 375 | wx, wy = (x - left) / ratio, (y - top) / ratio |
| 376 | if not (0 <= wx < geometry.width and 0 <= wy < geometry.height): |
| 377 | raise Failure(409) |
| 378 | p = self.root.translate_coords(win, int(wx), int(wy)) |
| 379 | xtest.fake_input(self.conn, X.MotionNotify, x=p.x, y=p.y) |
| 380 | current = self.root |
| 381 | while current.id != win.id: |
| 382 | current = current.query_pointer().child |
| 383 | if not current: |
| 384 | raise Failure(409) |
| 385 | buttons = [1] |
| 386 | if kind == 'scroll': |
| 387 | dx, dy = req.get('dx'), req.get('dy') |
| 388 | if not all(type(n) in (int, float) and math.isfinite(n) and abs(n) <= 3200 for n in (dx,dy)): |
| 389 | raise Failure(400) |
| 390 | buttons = [] |
| 391 | for delta, neg, pos in [(dx,6,7), (dy,4,5)]: |
| 392 | if delta: |
| 393 | buttons.extend([neg if delta < 0 else pos] * min(20, max(1, round(abs(delta)/50)))) |
| 394 | for button in buttons: |
| 395 | xtest.fake_input(self.conn, X.ButtonPress, button) |
| 396 | xtest.fake_input(self.conn, X.ButtonRelease, button) |
| 397 | finally: |
| 398 | self.conn.ungrab_server() |
| 399 | self.conn.sync() |
| 400 | |
| 401 | |
| 402 | class Handler(socketserver.StreamRequestHandler): |
| 403 | def handle(self): |
| 404 | self.request.settimeout(7) |
| 405 | try: |
| 406 | req = json.loads(self.rfile.readline(65537)) |
| 407 | if req.get('id') != view.id: |
| 408 | raise Failure(410) |
| 409 | view.last = time.monotonic() |
| 410 | if req.get('op') == 'frame': |
| 411 | result = view.snapshot() |
| 412 | elif req.get('op') == 'action': |
| 413 | view.action(req) |
| 414 | result = {'id': view.id} |
| 415 | else: |
| 416 | raise Failure(400) |
| 417 | except Failure as error: |
| 418 | result = {'status': error.status} |
| 419 | except Exception: |
| 420 | result = {'status': 409} |
| 421 | self.wfile.write(json.dumps(result, separators=(',', ':')).encode() + b'\n') |
| 422 | |
| 423 | |
| 424 | if __name__ == '__main__': |
| 425 | if sys.argv[1:] == ['--restore']: |
| 426 | restore_layout() |
| 427 | sys.exit(0) |
| 428 | view = View() |
| 429 | with socketserver.UnixStreamServer(str(Path(os.environ['XDG_RUNTIME_DIR'])/'view.sock'), Handler) as server: |
| 430 | server.timeout = 3 |
| 431 | while time.monotonic() - view.last < 120: |
| 432 | server.handle_request() |