dsh-plugin-linux-computer-use 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,523 @@
1
+ """Display geometry and screen capture for the Linux desktop MCP server.
2
+
3
+ Screenshots on a Wayland GNOME session cannot come from ``org.gnome.Shell``
4
+ (its Screenshot interface answers AccessDenied to every external client), so
5
+ the portal is the only legal source. Two portal paths live here:
6
+
7
+ * ``org.freedesktop.portal.Screenshot`` — one request, one PNG back in roughly
8
+ half a second. GNOME remembers the answer, so after the first approval it
9
+ never asks again. This is what the server uses by default.
10
+ * ``org.freedesktop.portal.ScreenCast`` — a persistent PipeWire session whose
11
+ ``restore_token`` is stored under ``~/.cache/dsh-linux-cu``. Frames are read
12
+ with ``pipewiresrc`` and encoded by ``pngenc``. Kept as a fallback: on GNOME
13
+ 46/Mutter the stream delivers its first frames during preroll and then stays
14
+ silent while the screen is static, so a one-shot capture can time out.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import random
22
+ import struct
23
+ import time
24
+ from dataclasses import dataclass, field
25
+
26
+ import gi
27
+
28
+ gi.require_version("Gio", "2.0")
29
+ gi.require_version("GLib", "2.0")
30
+ from gi.repository import Gio, GLib # noqa: E402
31
+
32
+ PORTAL_DEST = "org.freedesktop.portal.Desktop"
33
+ PORTAL_PATH = "/org/freedesktop/portal/desktop"
34
+ REQUEST_IFACE = "org.freedesktop.portal.Request"
35
+ SCREENCAST_IFACE = "org.freedesktop.portal.ScreenCast"
36
+ SCREENSHOT_IFACE = "org.freedesktop.portal.Screenshot"
37
+ DISPLAYCONFIG_DEST = "org.gnome.Mutter.DisplayConfig"
38
+ DISPLAYCONFIG_PATH = "/org/gnome/Mutter/DisplayConfig"
39
+ DISPLAYCONFIG_IFACE = "org.gnome.Mutter.DisplayConfig"
40
+
41
+ CACHE_DIR = os.path.join(os.path.expanduser("~"), ".cache", "dsh-linux-cu")
42
+ TOKEN_FILE = os.path.join(CACHE_DIR, "screencast.json")
43
+ SHOT_DIR = os.path.join(CACHE_DIR, "shots")
44
+
45
+ SOURCE_MONITOR = 1
46
+ SOURCE_WINDOW = 2
47
+ CURSOR_HIDDEN, CURSOR_EMBEDDED, CURSOR_METADATA = 0, 1, 2
48
+
49
+
50
+ class PortalError(RuntimeError):
51
+ """Portal call failed, was cancelled, or timed out."""
52
+
53
+
54
+ def _ensure_dirs() -> None:
55
+ os.makedirs(CACHE_DIR, exist_ok=True)
56
+ os.makedirs(SHOT_DIR, exist_ok=True)
57
+
58
+
59
+ # --------------------------------------------------------------------------- #
60
+ # display geometry
61
+ # --------------------------------------------------------------------------- #
62
+ @dataclass
63
+ class Monitor:
64
+ connector: str
65
+ vendor: str
66
+ product: str
67
+ x: int = 0
68
+ y: int = 0
69
+ width: int = 0
70
+ height: int = 0
71
+ scale: float = 1.0
72
+ primary: bool = False
73
+ refresh: float = 0.0
74
+
75
+
76
+ @dataclass
77
+ class Layout:
78
+ """Logical desktop extent plus per-monitor geometry."""
79
+
80
+ x: int
81
+ y: int
82
+ width: int
83
+ height: int
84
+ monitors: list[Monitor] = field(default_factory=list)
85
+ serial: int = 0
86
+
87
+ def to_absolute(self, x: float, y: float) -> tuple[int, int]:
88
+ """Map logical desktop coordinates to the pointer's 0..32767 range."""
89
+ x = max(self.x, min(self.x + self.width - 1, float(x)))
90
+ y = max(self.y, min(self.y + self.height - 1, float(y)))
91
+ span_x = max(1, self.width - 1)
92
+ span_y = max(1, self.height - 1)
93
+ return (round((x - self.x) * 32767 / span_x), round((y - self.y) * 32767 / span_y))
94
+
95
+ def describe(self) -> dict:
96
+ return {
97
+ "logical": {"x": self.x, "y": self.y, "width": self.width, "height": self.height},
98
+ "monitors": [
99
+ {
100
+ "connector": m.connector,
101
+ "x": m.x,
102
+ "y": m.y,
103
+ "width": m.width,
104
+ "height": m.height,
105
+ "scale": m.scale,
106
+ "primary": m.primary,
107
+ "refresh": round(m.refresh, 3),
108
+ }
109
+ for m in self.monitors
110
+ ],
111
+ }
112
+
113
+
114
+ def _session_bus() -> Gio.DBusConnection:
115
+ return Gio.bus_get_sync(Gio.BusType.SESSION, None)
116
+
117
+
118
+ def read_layout(timeout_ms: int = 4000) -> Layout:
119
+ """Read the live layout from Mutter's DisplayConfig D-Bus interface."""
120
+ connection = _session_bus()
121
+ try:
122
+ reply = connection.call_sync(
123
+ DISPLAYCONFIG_DEST,
124
+ DISPLAYCONFIG_PATH,
125
+ DISPLAYCONFIG_IFACE,
126
+ "GetCurrentState",
127
+ None,
128
+ None,
129
+ Gio.DBusCallFlags.NONE,
130
+ timeout_ms,
131
+ None,
132
+ )
133
+ serial, monitors, logical, _props = reply.unpack()
134
+ except GLib.Error as error:
135
+ raise PortalError(
136
+ f"cannot read the display layout from Mutter DisplayConfig: {error.message}"
137
+ ) from error
138
+
139
+ # connector -> (current width, height, refresh)
140
+ current: dict[str, tuple[int, int, float]] = {}
141
+ for entry in monitors:
142
+ spec, modes, _enabled = entry
143
+ connector = spec[0]
144
+ for mode in modes:
145
+ mode_id, width, height, refresh = mode[0], mode[1], mode[2], mode[3]
146
+ mode_props = mode[6] if len(mode) > 6 else {}
147
+ if mode_props.get("is-current"):
148
+ current[connector] = (width, height, refresh)
149
+ break
150
+ del mode_id
151
+
152
+ result: list[Monitor] = []
153
+ for entry in logical:
154
+ x, y, scale, _transform, primary, attached, _props = entry
155
+ attached = attached or []
156
+ for spec in attached:
157
+ connector, vendor, product = spec[0], spec[1], spec[2]
158
+ width, height, refresh = current.get(connector, (0, 0, 0.0))
159
+ logical_width = round(width / scale) if width and scale else 0
160
+ logical_height = round(height / scale) if height and scale else 0
161
+ result.append(
162
+ Monitor(
163
+ connector=connector,
164
+ vendor=vendor,
165
+ product=product,
166
+ x=int(x),
167
+ y=int(y),
168
+ width=logical_width,
169
+ height=logical_height,
170
+ scale=float(scale),
171
+ primary=bool(primary),
172
+ refresh=float(refresh or 0.0),
173
+ )
174
+ )
175
+
176
+ if not result:
177
+ # Extremely defensive: assume a single 1080p monitor at the origin.
178
+ result = [Monitor("unknown", "", "", 0, 0, 1920, 1080, 1.0, True)]
179
+
180
+ min_x = min(m.x for m in result)
181
+ min_y = min(m.y for m in result)
182
+ max_x = max(m.x + m.width for m in result)
183
+ max_y = max(m.y + m.height for m in result)
184
+ return Layout(x=min_x, y=min_y, width=max_x - min_x, height=max_y - min_y,
185
+ monitors=result, serial=int(serial))
186
+
187
+
188
+ def png_size(path: str) -> tuple[int, int]:
189
+ """Read width and height from a PNG header without decoding the image."""
190
+ try:
191
+ with open(path, "rb") as handle:
192
+ header = handle.read(24)
193
+ except OSError:
194
+ return (0, 0)
195
+ if len(header) < 24 or header[:8] != b"\x89PNG\r\n\x1a\n":
196
+ return (0, 0)
197
+ width, height = struct.unpack(">II", header[16:24])
198
+ return (int(width), int(height))
199
+
200
+
201
+ # --------------------------------------------------------------------------- #
202
+ # portal plumbing
203
+ # --------------------------------------------------------------------------- #
204
+ def _token() -> str:
205
+ return f"dsh_cu_{random.randrange(1 << 32):08x}"
206
+
207
+
208
+ def _request_path(connection: Gio.DBusConnection, handle_token: str) -> str:
209
+ sender = connection.get_unique_name().lstrip(":").replace(".", "_")
210
+ return f"{PORTAL_PATH}/request/{sender}/{handle_token}"
211
+
212
+
213
+ def _options_token(parameters: GLib.Variant) -> str | None:
214
+ """Read the handle_token out of whichever a{sv} argument carries it.
215
+
216
+ Every caller already puts a handle_token in its options dict, and the
217
+ Request object path must match exactly that token - so this only reads it.
218
+ Unpacking and re-packing the whole tuple would demote the variant values to
219
+ plain Python objects, and 'v' arguments require GLib.Variant instances.
220
+ """
221
+ for index in range(parameters.n_children()):
222
+ child = parameters.get_child_value(index)
223
+ if not child.get_type_string().endswith("v}"):
224
+ continue
225
+ token = child.lookup_value("handle_token", GLib.VariantType.new("s"))
226
+ if token is not None:
227
+ return token.get_string()
228
+ return None
229
+
230
+
231
+ def _call_request(connection: Gio.DBusConnection, interface: str, method: str,
232
+ parameters: GLib.Variant, timeout_s: float = 90.0) -> dict:
233
+ """Call a portal method that answers with a Request Response signal."""
234
+ handle_token = _options_token(parameters)
235
+ if not handle_token:
236
+ raise PortalError(f"{interface}.{method} was called without a handle_token")
237
+ path = _request_path(connection, handle_token)
238
+
239
+ loop = GLib.MainLoop()
240
+ outcome: dict = {}
241
+
242
+ def on_response(_conn, _sender, _path, _iface, _signal, payload):
243
+ response, results = payload.unpack()
244
+ outcome["response"] = int(response)
245
+ outcome["results"] = results
246
+ loop.quit()
247
+
248
+ subscription = connection.signal_subscribe(
249
+ PORTAL_DEST, REQUEST_IFACE, "Response", path, None,
250
+ Gio.DBusSignalFlags.NONE, on_response,
251
+ )
252
+ try:
253
+ connection.call_sync(
254
+ PORTAL_DEST, PORTAL_PATH, interface, method, parameters, None,
255
+ Gio.DBusCallFlags.NONE, int(timeout_s * 1000), None,
256
+ )
257
+ timeout = GLib.timeout_add(int(timeout_s * 1000), lambda: (loop.quit(), False)[1])
258
+ try:
259
+ loop.run()
260
+ finally:
261
+ GLib.source_remove(timeout)
262
+ except GLib.Error as error:
263
+ raise PortalError(f"{interface}.{method} failed: {error.message}") from error
264
+ finally:
265
+ connection.signal_unsubscribe(subscription)
266
+
267
+ if "response" not in outcome:
268
+ raise PortalError(f"{interface}.{method} produced no response within {timeout_s:.0f}s")
269
+ if outcome["response"] != 0:
270
+ reason = "cancelled by the user" if outcome["response"] == 1 else "closed by the user"
271
+ raise PortalError(f"{interface}.{method} was {reason}")
272
+ return outcome["results"]
273
+
274
+
275
+ # --------------------------------------------------------------------------- #
276
+ # screencast session
277
+ # --------------------------------------------------------------------------- #
278
+ class ScreencastSession:
279
+ """A persistent ScreenCast portal session feeding frames over PipeWire."""
280
+
281
+ _instance: "ScreencastSession | None" = None
282
+
283
+ def __init__(self) -> None:
284
+ self.connection: Gio.DBusConnection | None = None
285
+ self.session_handle: str | None = None
286
+ self.node_id: int | None = None
287
+ self.fd: int | None = None
288
+ self.stream_size: tuple[int, int] = (0, 0)
289
+ self.restore_token: str | None = None
290
+ self._gst_ready = False
291
+
292
+ # -- token persistence ------------------------------------------------- #
293
+ @staticmethod
294
+ def load_token() -> str | None:
295
+ try:
296
+ with open(TOKEN_FILE, "r", encoding="utf-8") as handle:
297
+ return json.load(handle).get("restore_token")
298
+ except (OSError, ValueError):
299
+ return None
300
+
301
+ @staticmethod
302
+ def save_token(token: str | None) -> None:
303
+ _ensure_dirs()
304
+ try:
305
+ with open(TOKEN_FILE, "w", encoding="utf-8") as handle:
306
+ json.dump({"restore_token": token, "saved_at": time.time()}, handle)
307
+ os.chmod(TOKEN_FILE, 0o600)
308
+ except OSError:
309
+ pass
310
+
311
+ # -- lifecycle --------------------------------------------------------- #
312
+ @classmethod
313
+ def shared(cls) -> "ScreencastSession":
314
+ if cls._instance is None:
315
+ cls._instance = cls()
316
+ return cls._instance
317
+
318
+ def ensure(self, timeout_s: float = 120.0) -> "ScreencastSession":
319
+ """Open the portal session if needed; may show the share dialog once."""
320
+ if self.fd is not None and self.node_id is not None:
321
+ return self
322
+ _ensure_dirs()
323
+ connection = self.connection or _session_bus()
324
+ self.connection = connection
325
+ self.restore_token = self.restore_token or self.load_token()
326
+
327
+ create = GLib.Variant(
328
+ "(a{sv})",
329
+ ({"handle_token": GLib.Variant("s", _token()),
330
+ "session_handle_token": GLib.Variant("s", _token())},),
331
+ )
332
+ reply = _call_request(connection, SCREENCAST_IFACE, "CreateSession", create, 30)
333
+ # xdg-desktop-portal answers a request with a{sv} results dict, while the
334
+ # documented signature is (o). Accept both shapes.
335
+ handle = reply.get("session_handle") if isinstance(reply, dict) else reply
336
+ if isinstance(handle, tuple):
337
+ handle = handle[0]
338
+ if not isinstance(handle, str):
339
+ raise PortalError(f"unexpected CreateSession reply: {reply!r}")
340
+ self.session_handle = handle
341
+
342
+ options: dict[str, GLib.Variant] = {
343
+ "types": GLib.Variant("u", SOURCE_MONITOR),
344
+ "multiple": GLib.Variant("b", False),
345
+ "cursor_mode": GLib.Variant("u", CURSOR_EMBEDDED),
346
+ "persist_mode": GLib.Variant("u", 2),
347
+ }
348
+ if self.restore_token:
349
+ options["restore_token"] = GLib.Variant("s", self.restore_token)
350
+ select = GLib.Variant(
351
+ "(oa{sv})",
352
+ (self.session_handle,
353
+ {"handle_token": GLib.Variant("s", _token()), **options}),
354
+ )
355
+ _call_request(connection, SCREENCAST_IFACE, "SelectSources", select, timeout_s)
356
+
357
+ start = GLib.Variant(
358
+ "(osa{sv})",
359
+ (self.session_handle, "",
360
+ {"handle_token": GLib.Variant("s", _token())}),
361
+ )
362
+ results = _call_request(connection, SCREENCAST_IFACE, "Start", start, timeout_s)
363
+ streams = results.get("streams") or []
364
+ if not streams:
365
+ raise PortalError("the ScreenCast portal returned no streams")
366
+ node_id, props = streams[0]
367
+ self.node_id = int(node_id)
368
+ size = props.get("size") if isinstance(props, dict) else None
369
+ if size and len(size) == 2:
370
+ self.stream_size = (int(size[0]), int(size[1]))
371
+ token = results.get("restore_token")
372
+ if token:
373
+ self.restore_token = token
374
+ self.save_token(token)
375
+
376
+ reply, fd_list = connection.call_with_unix_fd_list_sync(
377
+ PORTAL_DEST, PORTAL_PATH, SCREENCAST_IFACE, "OpenPipeWireRemote",
378
+ GLib.Variant("(oa{sv})", (self.session_handle, {})),
379
+ GLib.VariantType.new("(h)"), Gio.DBusCallFlags.NONE, 20000, None, None,
380
+ )
381
+ del reply
382
+ self.fd = fd_list.get(0)
383
+ return self
384
+
385
+ def close(self) -> None:
386
+ if self.fd is not None:
387
+ try:
388
+ os.close(self.fd)
389
+ except OSError:
390
+ pass
391
+ self.fd = None
392
+ self.node_id = None
393
+ self.session_handle = None
394
+
395
+
396
+ # --------------------------------------------------------------------------- #
397
+ # frame capture
398
+ # --------------------------------------------------------------------------- #
399
+ def _init_gst():
400
+ gi.require_version("Gst", "1.0")
401
+ from gi.repository import Gst # local import keeps startup light
402
+
403
+ if not Gst.is_initialized():
404
+ Gst.init(None)
405
+ return Gst
406
+
407
+
408
+ def capture_frame(session: ScreencastSession, path: str, timeout_s: float = 10.0) -> tuple[int, int]:
409
+ """Grab one frame from the screencast session and write it as PNG."""
410
+ Gst = _init_gst()
411
+ _ensure_dirs()
412
+ os.makedirs(os.path.dirname(path) or SHOT_DIR, exist_ok=True)
413
+
414
+ pipeline = Gst.Pipeline.new("dsh-capture")
415
+ source = Gst.ElementFactory.make("pipewiresrc", "src")
416
+ convert = Gst.ElementFactory.make("videoconvert", "convert")
417
+ encode = Gst.ElementFactory.make("pngenc", "encode")
418
+ sink = Gst.ElementFactory.make("appsink", "sink")
419
+ for element in (source, convert, encode, sink):
420
+ if element is None:
421
+ raise PortalError("GStreamer is missing an element required for capture "
422
+ "(pipewiresrc/videoconvert/pngenc/appsink)")
423
+ source.set_property("path", str(session.node_id))
424
+ source.set_property("fd", int(session.fd))
425
+ source.set_property("do-timestamp", True)
426
+ encode.set_property("snapshot", True)
427
+ sink.set_property("max-buffers", 1)
428
+ sink.set_property("drop", True)
429
+ sink.set_property("sync", False)
430
+
431
+ pipeline.add(source)
432
+ pipeline.add(convert)
433
+ pipeline.add(encode)
434
+ pipeline.add(sink)
435
+ if not (source.link(convert) and convert.link(encode) and encode.link(sink)):
436
+ raise PortalError("cannot link the capture pipeline")
437
+
438
+ loop = GLib.MainLoop()
439
+ state: dict = {"ok": False, "error": None}
440
+
441
+ def on_sample(_sink):
442
+ sample = _sink.emit("pull-sample")
443
+ if sample is None:
444
+ return Gst.FlowReturn.ERROR
445
+ buffer = sample.get_buffer()
446
+ success, mapinfo = buffer.map(Gst.MapFlags.READ)
447
+ if not success:
448
+ state["error"] = "cannot map the captured buffer"
449
+ loop.quit()
450
+ return Gst.FlowReturn.ERROR
451
+ try:
452
+ with open(path, "wb") as handle:
453
+ handle.write(bytes(mapinfo.data))
454
+ state["ok"] = True
455
+ finally:
456
+ buffer.unmap(mapinfo)
457
+ loop.quit()
458
+ return Gst.FlowReturn.OK
459
+
460
+ sink.connect("new-sample", on_sample)
461
+ pipeline.set_state(Gst.State.PLAYING)
462
+ timeout = GLib.timeout_add(int(timeout_s * 1000), lambda: (loop.quit(), False)[1])
463
+ try:
464
+ loop.run()
465
+ finally:
466
+ GLib.source_remove(timeout)
467
+ pipeline.set_state(Gst.State.NULL)
468
+
469
+ if not state["ok"]:
470
+ raise PortalError(state["error"] or f"no frame arrived within {timeout_s:.0f}s")
471
+ width, height = png_size(path)
472
+ if width and height:
473
+ session.stream_size = (width, height)
474
+ return (width, height)
475
+
476
+
477
+ def portal_screenshot(path: str, timeout_s: float = 120.0) -> tuple[int, int]:
478
+ """One-shot fallback: portal Screenshot (shows a dialog every call)."""
479
+ connection = _session_bus()
480
+ options = {
481
+ "handle_token": GLib.Variant("s", _token()),
482
+ "interactive": GLib.Variant("b", False),
483
+ "modal": GLib.Variant("b", True),
484
+ }
485
+ results = _call_request(
486
+ connection, SCREENSHOT_IFACE, "Screenshot",
487
+ GLib.Variant("(sa{sv})", ("", options)), timeout_s,
488
+ )
489
+ uri = results.get("uri")
490
+ if not uri:
491
+ raise PortalError("the Screenshot portal returned no uri")
492
+ source_path = uri[len("file://"):] if uri.startswith("file://") else uri
493
+ source_path = GLib.filename_from_uri(uri)[0] if uri.startswith("file://") else source_path
494
+ _ensure_dirs()
495
+ os.makedirs(os.path.dirname(path) or SHOT_DIR, exist_ok=True)
496
+ with open(source_path, "rb") as src, open(path, "wb") as dst:
497
+ dst.write(src.read())
498
+ return png_size(path)
499
+
500
+
501
+ # --------------------------------------------------------------------------- #
502
+ # image scaling
503
+ # --------------------------------------------------------------------------- #
504
+ def downscale(path: str, max_width: int) -> tuple[int, int]:
505
+ """Shrink a PNG in place when wider than ``max_width`` (vision economy)."""
506
+ if max_width <= 0:
507
+ return png_size(path)
508
+ width, height = png_size(path)
509
+ if not width or width <= max_width:
510
+ return (width, height)
511
+ try:
512
+ gi.require_version("GdkPixbuf", "2.0")
513
+ from gi.repository import GdkPixbuf
514
+
515
+ pixbuf = GdkPixbuf.Pixbuf.new_from_file(path)
516
+ target_height = max(1, round(height * max_width / width))
517
+ scaled = pixbuf.scale_simple(max_width, target_height, GdkPixbuf.InterpType.BILINEAR)
518
+ if scaled is None:
519
+ return (width, height)
520
+ scaled.savev(path, "png", [], [])
521
+ return png_size(path)
522
+ except Exception: # noqa: BLE001 - scaling is best effort
523
+ return (width, height)