@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 420 lines 14.3 KB
Raw
1 // @effect-diagnostics globalTimers:off -- D-Bus deadlines run at a native async boundary.
2 // @effect-diagnostics nodeBuiltinImport:off -- Read the portal file through one bounded file descriptor at the native adapter boundary.
3
4 import * as NodeCrypto from "node:crypto";
5 import {
6 DBusError,
7 Message,
8 MessageFlag,
9 MessageType,
10 NameFlag,
11 RequestNameReply,
12 Variant,
13 sessionBus,
14 type MessageBus,
15 type MessageLike,
16 } from "dbus-next";
17 import * as Schema from "effect/Schema";
18 import { isKdeCaptureSession, type KdeCapturePaths } from "./KdeSnapShot.ts";
19 import { isGnomeCaptureSession, readPortalPng, resizeLinuxCapture } from "./linuxCaptureSession.ts";
20 export { readPortalPng } from "./linuxCaptureSession.ts";
21 import { isHyprlandCaptureSession, type HyprlandCapturePaths } from "./HyprlandSnapShot.ts";
22
23 const PORTAL = "org.freedesktop.portal.Desktop";
24 const PORTAL_PATH = "/org/freedesktop/portal/desktop";
25 const SCREENSHOT = "org.freedesktop.portal.Screenshot";
26 const REQUEST = "org.freedesktop.portal.Request";
27 const EXTENSION = "org.gnome.Shell.Extensions.T3SnapShot";
28 const EXTENSION_PATH = "/org/gnome/Shell/Extensions/T3SnapShot";
29 const DBUS = "org.freedesktop.DBus";
30 const DBUS_PATH = "/org/freedesktop/DBus";
31 const UInt = Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 0xffff_ffff }));
32 const UIntVariant = Schema.Struct({ signature: Schema.Literal("u"), value: UInt });
33 const StringVariant = Schema.Struct({ signature: Schema.Literal("s"), value: Schema.String });
34 const PortalProperties = Schema.Struct({
35 version: UIntVariant,
36 AvailableTargets: Schema.optional(UIntVariant),
37 });
38 const WindowMetadata = Schema.Struct({
39 title: Schema.String,
40 appName: Schema.String,
41 appIdentifier: Schema.String,
42 processId: UInt,
43 bounds: Schema.Struct({
44 x: Schema.Int,
45 y: Schema.Int,
46 width: Schema.Int.check(Schema.isGreaterThan(0)),
47 height: Schema.Int.check(Schema.isGreaterThan(0)),
48 }),
49 });
50 export type LinuxWindowMetadata = typeof WindowMetadata.Type & {
51 readonly clientBounds?: typeof WindowMetadata.Type.bounds;
52 readonly accessibilityBoundsReliable?: boolean;
53 };
54 const decodeProperties = Schema.decodeUnknownSync(PortalProperties);
55 const decodeExtension = Schema.decodeUnknownSync(Schema.Struct({ Version: UIntVariant }));
56 const decodeKde = Schema.decodeUnknownSync(Schema.Struct({ Version: UIntVariant }));
57 const decodeString = Schema.decodeUnknownSync(Schema.String);
58 const decodeBoolean = Schema.decodeUnknownSync(Schema.Boolean);
59 const decodeResponse = Schema.decodeUnknownSync(
60 Schema.Tuple([UInt, Schema.Record(Schema.String, Schema.Unknown)]),
61 );
62 const decodeUri = Schema.decodeUnknownSync(StringVariant);
63 const decodeWindow = Schema.decodeUnknownSync(Schema.fromJsonString(WindowMetadata));
64 export type LinuxCaptureBackend =
65 | "screenshot-portal"
66 | "gnome-extension"
67 | "niri"
68 | "kde"
69 | "hyprland"
70 | "picker";
71 export type LinuxWindowSnapshot = {
72 readonly png: Buffer;
73 readonly window?: LinuxWindowMetadata;
74 readonly feedback?: LinuxCaptureFeedback;
75 };
76
77 export type LinuxCaptureFeedback = {
78 readonly animationStarted: boolean;
79 readonly activate: (title: string) => Promise<void>;
80 readonly animateTo: (frame: {
81 x: number;
82 y: number;
83 width: number;
84 height: number;
85 }) => Promise<void>;
86 readonly complete: () => Promise<void>;
87 readonly close: () => void;
88 };
89 type FeedbackOptions = { readonly flash: boolean; readonly animate: boolean };
90
91 function unavailable(error: unknown): boolean {
92 return (
93 error instanceof DBusError &&
94 ["ServiceUnknown", "NameHasNoOwner", "UnknownObject", "UnknownInterface", "UnknownMethod"].some(
95 (name) => error.type === `${DBUS}.Error.${name}`,
96 )
97 );
98 }
99
100 /** One connection per operation: portal registration and request ownership stay together. */
101 class LinuxCaptureConnection {
102 private readonly bus: MessageBus;
103 private readonly disconnected: Promise<never>;
104 private uniqueName = "";
105 private extensionVersion = 0;
106 private closed = false;
107 private feedbackTimer: ReturnType<typeof setTimeout> | undefined;
108
109 get feedbackAvailable() {
110 return this.extensionVersion === 2;
111 }
112
113 constructor(bus = sessionBus()) {
114 this.bus = bus;
115 this.disconnected = new Promise((_, reject) => {
116 bus.on("error", reject);
117 });
118 // A disconnect between calls must not become an unhandled rejection.
119 void this.disconnected.catch(() => undefined);
120 }
121
122 close() {
123 if (this.closed) return;
124 this.closed = true;
125 clearTimeout(this.feedbackTimer);
126 this.bus.disconnect();
127 }
128
129 private async wait<T>(pending: Promise<T>, timeoutMs = 5_000): Promise<T> {
130 let timer: ReturnType<typeof setTimeout> | undefined;
131 try {
132 return await Promise.race([
133 pending,
134 this.disconnected,
135 new Promise<never>((_, reject) => {
136 timer = setTimeout(() => reject(new Error("Snapshot timed out.")), timeoutMs);
137 }),
138 ]);
139 } finally {
140 clearTimeout(timer);
141 }
142 }
143
144 private async call(message: MessageLike) {
145 const reply = await this.wait(this.bus.call(new Message(message)));
146 if (!reply) throw new Error("Missing D-Bus reply.");
147 this.uniqueName = reply.destination;
148 return reply;
149 }
150
151 private async properties(destination: string, path: string, iface: string) {
152 const reply = await this.call({
153 destination,
154 path,
155 interface: "org.freedesktop.DBus.Properties",
156 member: "GetAll",
157 signature: "s",
158 body: [iface],
159 });
160 return reply.body[0] as unknown;
161 }
162
163 async backend(appId: string): Promise<LinuxCaptureBackend> {
164 if (isKdeCaptureSession()) {
165 const kde = await this.properties(
166 "org.kde.KWin.ScreenShot2",
167 "/org/kde/KWin/ScreenShot2",
168 "org.kde.KWin.ScreenShot2",
169 ).catch((error: unknown) => {
170 if (!unavailable(error)) throw error;
171 return undefined;
172 });
173 if (kde !== undefined && decodeKde(kde).Version.value >= 2) return "kde";
174 }
175 if (!process.env.FLATPAK_ID && !process.env.SNAP) {
176 await this.call({
177 destination: PORTAL,
178 path: PORTAL_PATH,
179 interface: "org.freedesktop.host.portal.Registry",
180 member: "Register",
181 signature: "sa{sv}",
182 body: [appId, {}],
183 }).catch((error: unknown) => {
184 if (!unavailable(error)) throw error;
185 });
186 }
187 const properties = await this.properties(PORTAL, PORTAL_PATH, SCREENSHOT).catch(
188 (error: unknown) => {
189 if (!unavailable(error)) throw error;
190 return undefined;
191 },
192 );
193 if (properties !== undefined) {
194 const parsed = decodeProperties(properties);
195 if (parsed.version.value >= 3 && ((parsed.AvailableTargets?.value ?? 0) & 8) !== 0) {
196 return "screenshot-portal";
197 }
198 }
199 if (!isGnomeCaptureSession(process.env)) return "picker";
200 const extension = await this.properties(EXTENSION, EXTENSION_PATH, EXTENSION).catch(
201 (error: unknown) => {
202 if (!unavailable(error)) throw error;
203 return undefined;
204 },
205 );
206 if (extension !== undefined) {
207 const parsed = decodeExtension(extension);
208 this.extensionVersion = parsed.Version.value;
209 if (this.extensionVersion === 1 || this.extensionVersion === 2) return "gnome-extension";
210 }
211 return "picker";
212 }
213
214 async capturePortal(): Promise<LinuxWindowSnapshot> {
215 const owner = await this.call({
216 destination: DBUS,
217 path: DBUS_PATH,
218 interface: DBUS,
219 member: "GetNameOwner",
220 signature: "s",
221 body: [PORTAL],
222 });
223 const sender = decodeString(owner.body[0]);
224 const token = `t3_${NodeCrypto.randomUUID().replaceAll("-", "")}`;
225 const namespace = `${PORTAL_PATH}/request/${this.uniqueName.slice(1).replaceAll(".", "_")}/`;
226 let handle = namespace + token;
227 let completed = false;
228 // Subscribe before Screenshot: the response may precede its method reply.
229 const responses = new Map<string, unknown>();
230 let deliver: ((body: unknown) => void) | undefined;
231 const listener = (message: Message) => {
232 if (
233 message.type !== MessageType.SIGNAL ||
234 message.sender !== sender ||
235 message.interface !== REQUEST ||
236 message.member !== "Response" ||
237 !message.path.startsWith(namespace)
238 )
239 return;
240 if (deliver && message.path === handle) deliver(message.body);
241 else if (responses.size < 8) responses.set(message.path, message.body);
242 };
243 this.bus.on("message", listener);
244 try {
245 await this.call({
246 destination: DBUS,
247 path: DBUS_PATH,
248 interface: DBUS,
249 member: "AddMatch",
250 signature: "s",
251 body: [
252 `type='signal',sender='${sender}',interface='${REQUEST}',member='Response',path_namespace='${namespace.slice(0, -1)}'`,
253 ],
254 });
255 const reply = await this.call({
256 destination: sender,
257 path: PORTAL_PATH,
258 interface: SCREENSHOT,
259 member: "Screenshot",
260 signature: "sa{sv}",
261 body: [
262 "",
263 {
264 handle_token: new Variant("s", token),
265 interactive: new Variant("b", false),
266 modal: new Variant("b", false),
267 target: new Variant("u", 8),
268 },
269 ],
270 });
271 handle = decodeString(reply.body[0]);
272 if (!handle.startsWith(namespace)) throw new Error("Invalid screenshot request handle.");
273 const body = await this.wait(
274 new Promise<unknown>((resolve) => {
275 deliver = resolve;
276 if (responses.has(handle)) resolve(responses.get(handle));
277 }),
278 120_000,
279 );
280 const [status, results] = decodeResponse(body);
281 completed = true;
282 if (status === 1) throw new Error("Snapshot was cancelled.");
283 if (status !== 0) throw new Error("Your desktop did not allow the snapshot.");
284 const uri = decodeUri(results.uri).value;
285 return { png: await readPortalPng(uri) };
286 } finally {
287 this.bus.removeListener("message", listener);
288 if (!completed) {
289 this.bus.send(
290 new Message({
291 destination: sender,
292 path: handle,
293 interface: REQUEST,
294 member: "Close",
295 flags: MessageFlag.NO_REPLY_EXPECTED,
296 }),
297 );
298 }
299 }
300 }
301
302 async captureExtension(appId: string, options?: FeedbackOptions): Promise<LinuxWindowSnapshot> {
303 const result = await this.wait(
304 this.bus.requestName(`${appId}.SnapShot`, NameFlag.DO_NOT_QUEUE),
305 );
306 if (result !== RequestNameReply.PRIMARY_OWNER) {
307 throw new Error("Another T3 Code instance is capturing a window. Try again.");
308 }
309 const withFeedback = this.feedbackAvailable && options !== undefined;
310 const reply = await this.call({
311 destination: EXTENSION,
312 path: EXTENSION_PATH,
313 interface: EXTENSION,
314 member: withFeedback ? "CaptureWithFeedback" : "Capture",
315 ...(withFeedback ? { signature: "bb", body: [options.flash, options.animate] } : {}),
316 });
317 const bytes: unknown = reply.body[0];
318 if (!(bytes instanceof Uint8Array)) throw new Error("Invalid extension screenshot.");
319 const window = decodeWindow(reply.body[1]);
320 const png = resizeLinuxCapture(Buffer.from(bytes));
321 if (!withFeedback) return { png, window };
322 const animationStarted = decodeBoolean(reply.body[2]);
323 // Keep the same authenticated sender alive through activation and the compositor flight.
324 this.feedbackTimer = setTimeout(() => this.close(), 15_000);
325 let flight: Promise<void> | undefined;
326 const feedback: LinuxCaptureFeedback = {
327 animationStarted,
328 activate: async (title) => {
329 await this.feedbackCall("Activate", "s", [title]);
330 },
331 animateTo: (frame) => {
332 flight ??= this.feedbackCall("Animate", "dddd", [
333 frame.x,
334 frame.y,
335 frame.width,
336 frame.height,
337 ]);
338 return flight;
339 },
340 complete: async () => {
341 try {
342 await flight;
343 } finally {
344 this.close();
345 }
346 },
347 close: () => this.close(),
348 };
349 return { png, window, feedback };
350 }
351
352 private async feedbackCall(member: string, signature: string, body: unknown[]): Promise<void> {
353 if (this.closed) return;
354 await this.call({
355 destination: EXTENSION,
356 path: EXTENSION_PATH,
357 interface: EXTENSION,
358 member,
359 signature,
360 body,
361 });
362 }
363 }
364
365 export async function getLinuxCaptureSupport(appId: string) {
366 if (isHyprlandCaptureSession())
367 return { linuxBackend: "hyprland" as const, linuxFeedbackAvailable: false };
368 const { niriSocketPath, checkNiriCaptureSupport } = await import("./NiriSnapShot.ts");
369 const niri = niriSocketPath();
370 if (niri) {
371 await checkNiriCaptureSupport(niri);
372 return { linuxBackend: "niri" as const, linuxFeedbackAvailable: false };
373 }
374 const connection = new LinuxCaptureConnection();
375 try {
376 const linuxBackend = await connection.backend(appId);
377 return { linuxBackend, linuxFeedbackAvailable: connection.feedbackAvailable };
378 } finally {
379 connection.close();
380 }
381 }
382
383 /** Undefined means capability missing, not denied: only that case may open the picker. */
384 export async function captureLinuxWindow(
385 appId: string,
386 options?: FeedbackOptions,
387 kdePaths?: KdeCapturePaths,
388 hyprlandPaths?: HyprlandCapturePaths,
389 ): Promise<LinuxWindowSnapshot | undefined> {
390 if (isHyprlandCaptureSession()) {
391 if (!hyprlandPaths) throw new Error("Hyprland capture setup is unavailable in this build.");
392 const { captureHyprlandWindow } = await import("./HyprlandSnapShot.ts");
393 return captureHyprlandWindow(hyprlandPaths, options);
394 }
395 const { niriSocketPath, captureNiriWindow } = await import("./NiriSnapShot.ts");
396 const niri = niriSocketPath();
397 if (niri) return captureNiriWindow(niri);
398 const connection = new LinuxCaptureConnection();
399 let retained = false;
400 try {
401 switch (await connection.backend(appId)) {
402 case "kde": {
403 if (!kdePaths) throw new Error("KDE capture setup is unavailable in this build.");
404 const { captureKdeWindow } = await import("./KdeSnapShot.ts");
405 return await captureKdeWindow(kdePaths, options);
406 }
407 case "screenshot-portal":
408 return await connection.capturePortal();
409 case "gnome-extension": {
410 const snapshot = await connection.captureExtension(appId, options);
411 retained = snapshot.feedback !== undefined;
412 return snapshot;
413 }
414 case "picker":
415 return undefined;
416 }
417 } finally {
418 if (!retained) connection.close();
419 }
420 }