Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- Stable shortcut IDs and unique portal request tokens.
2// @effect-diagnostics globalTimers:off -- Bounded D-Bus calls and user-consent requests at the native boundary.
3import * as NodeCrypto from "node:crypto";
4import {
5 DBusError,
6 Message,
7 MessageFlag,
8 MessageType,
9 Variant,
10 sessionBus,
11 type MessageBus,
12 type MessageLike,
13} from "dbus-next";
14import * as Schema from "effect/Schema";
15import type { SnapShotKeyChord } from "@t3tools/contracts";
16import { HYPRLAND_CAPTURE_ACTION, portalShortcutTrigger } from "./linuxCaptureSession.ts";
17export { portalShortcutTrigger } from "./linuxCaptureSession.ts";
18
19const PORTAL = "org.freedesktop.portal.Desktop";
20const PATH = "/org/freedesktop/portal/desktop";
21const SHORTCUTS = "org.freedesktop.portal.GlobalShortcuts";
22const REQUEST = "org.freedesktop.portal.Request";
23const SESSION = "org.freedesktop.portal.Session";
24const DBUS = "org.freedesktop.DBus";
25const string = Schema.decodeUnknownSync(Schema.String);
26const StringVariant = Schema.Struct({ signature: Schema.Literal("s"), value: Schema.String });
27const Shortcuts = Schema.Array(
28 Schema.Tuple([
29 Schema.String,
30 Schema.Struct({
31 description: Schema.optional(StringVariant),
32 trigger_description: Schema.optional(StringVariant),
33 }),
34 ]),
35);
36const decodeShortcuts = Schema.decodeUnknownSync(Shortcuts);
37const decodeShortcutsResult = Schema.decodeUnknownSync(
38 Schema.Struct({
39 shortcuts: Schema.Struct({ signature: Schema.Literal("a(sa{sv})"), value: Shortcuts }),
40 }),
41);
42const decodeSession = Schema.decodeUnknownSync(Schema.Struct({ session_handle: StringVariant }));
43const decodeResponse = Schema.decodeUnknownSync(
44 Schema.Tuple([Schema.Int, Schema.Record(Schema.String, Schema.Unknown)]),
45);
46const decodeVersion = Schema.decodeUnknownSync(
47 Schema.Struct({
48 signature: Schema.Literal("u"),
49 value: Schema.Int,
50 }),
51);
52
53export interface PortalShortcutState {
54 readonly shortcutActionRegistered?: boolean;
55 readonly shortcutRegistered: boolean;
56 readonly shortcutPending: boolean;
57 readonly shortcutCanRetry?: boolean;
58 readonly shortcutLabel?: string;
59 readonly shortcutMessage: string | null;
60}
61
62export class PortalCaptureShortcut {
63 state: PortalShortcutState = {
64 shortcutRegistered: false,
65 shortcutPending: true,
66 shortcutMessage: "Waiting for shortcut permission. Approve the desktop prompt if one appears.",
67 };
68 readonly ready: Promise<void>;
69 private closed = false;
70 private owner = "";
71 private namespace = "";
72 private session = "";
73 private shortcutId = "";
74 private version = 0;
75 private pending: { path: string; resolve: (body: unknown) => void } | undefined;
76 private responses = new Map<string, unknown>();
77 private readonly stopped: Promise<never>;
78 private rejectStopped!: (reason: Error) => void;
79 private readonly onCapture: () => void;
80 private readonly onStateChanged: () => void;
81 private readonly bus: MessageBus;
82 private readonly managedByHyprland: boolean;
83
84 constructor(
85 appId: string,
86 shortcut: SnapShotKeyChord,
87 onCapture: () => void,
88 onStateChanged: () => void,
89 bus: MessageBus = sessionBus(),
90 managedByHyprland = false,
91 ) {
92 this.onCapture = onCapture;
93 this.onStateChanged = onStateChanged;
94 this.bus = bus;
95 this.managedByHyprland = managedByHyprland;
96 if (managedByHyprland)
97 this.state = {
98 shortcutRegistered: false,
99 shortcutPending: true,
100 shortcutMessage: "Connecting to Hyprland shortcuts…",
101 };
102 this.stopped = new Promise((_, reject) => {
103 this.rejectStopped = reject;
104 });
105 void this.stopped.catch(() => undefined);
106 bus.on("error", this.failed);
107 bus.on("message", this.message);
108 this.ready = this.initialize(appId, shortcut).catch(this.failed);
109 }
110
111 close = () => {
112 if (this.closed) return;
113 this.closed = true;
114 this.rejectStopped(new Error("Capture shortcut registration closed."));
115 try {
116 if (this.pending) this.closeObject(this.pending.path, REQUEST);
117 if (this.session) this.closeObject(this.session, SESSION);
118 } catch {}
119 this.bus.removeListener("message", this.message);
120 this.responses.clear();
121 this.bus.disconnect();
122 };
123
124 get hasSession() {
125 return !this.closed && Boolean(this.session);
126 }
127
128 async configure() {
129 if (this.managedByHyprland)
130 throw new Error("Change the capture binding in your Hyprland config, then save it.");
131 if (!this.hasSession || this.version < 2)
132 throw new Error(
133 "Open your desktop's shortcut settings and allow T3 Code's capture shortcut.",
134 );
135 await this.call({
136 destination: this.owner,
137 path: PATH,
138 interface: SHORTCUTS,
139 member: "ConfigureShortcuts",
140 signature: "osa{sv}",
141 body: [this.session, "", {}],
142 });
143 }
144
145 private update(state: PortalShortcutState) {
146 if (this.closed) return;
147 this.state = {
148 shortcutCanRetry: !this.managedByHyprland && (!this.hasSession || this.version >= 2),
149 ...state,
150 };
151 this.onStateChanged();
152 }
153
154 private failed = (error: unknown) => {
155 if (this.closed) return;
156 this.update({
157 shortcutRegistered: false,
158 shortcutPending: false,
159 shortcutCanRetry: !this.managedByHyprland,
160 shortcutMessage: this.managedByHyprland
161 ? "Couldn't connect to Hyprland shortcuts. Make sure xdg-desktop-portal-hyprland is running, then restart T3 Code."
162 : error instanceof Error
163 ? error.message
164 : "Could not register the capture shortcut.",
165 });
166 this.close();
167 };
168
169 private async wait<T>(promise: Promise<T>, timeoutMs = 5_000): Promise<T> {
170 let timer: ReturnType<typeof setTimeout> | undefined;
171 try {
172 return await Promise.race([
173 promise,
174 this.stopped,
175 new Promise<never>((_, reject) => {
176 timer = setTimeout(
177 () => reject(new Error("Shortcut permission request timed out. Try again.")),
178 timeoutMs,
179 );
180 }),
181 ]);
182 } finally {
183 clearTimeout(timer);
184 }
185 }
186
187 private async call(message: MessageLike) {
188 if (this.closed) throw new Error("Capture shortcut registration closed.");
189 const reply = await this.wait(this.bus.call(new Message(message)));
190 if (!reply) throw new Error("Missing shortcut portal reply.");
191 return reply;
192 }
193
194 private closeObject(path: string, iface: string) {
195 this.bus.send(
196 new Message({
197 destination: this.owner,
198 path,
199 interface: iface,
200 member: "Close",
201 flags: MessageFlag.NO_REPLY_EXPECTED,
202 }),
203 );
204 }
205
206 private message = (message: Message) => {
207 if (this.closed || message.type !== MessageType.SIGNAL) return;
208 if (
209 message.sender === "org.freedesktop.DBus" &&
210 message.interface === DBUS &&
211 message.member === "NameOwnerChanged" &&
212 message.body[0] === PORTAL &&
213 message.body[1] === this.owner
214 ) {
215 this.failed(new Error("The desktop shortcut service restarted. Retry the shortcut request."));
216 return;
217 }
218 if (!this.owner || message.sender !== this.owner) return;
219 if (
220 message.interface === REQUEST &&
221 message.member === "Response" &&
222 message.path.startsWith(this.namespace)
223 ) {
224 if (message.path === this.pending?.path) this.pending.resolve(message.body);
225 else if (this.responses.size < 8) this.responses.set(message.path, message.body);
226 return;
227 }
228 if (
229 this.session &&
230 message.path === this.session &&
231 message.interface === SESSION &&
232 message.member === "Closed"
233 ) {
234 this.failed(
235 new Error("Your desktop closed the capture shortcut. Retry the shortcut request."),
236 );
237 return;
238 }
239 if (
240 message.path !== PATH ||
241 message.interface !== SHORTCUTS ||
242 message.body[0] !== this.session
243 )
244 return;
245 if (
246 message.member === "Activated" &&
247 message.signature === "osta{sv}" &&
248 message.body[1] === this.shortcutId &&
249 (this.state.shortcutRegistered || this.state.shortcutActionRegistered)
250 )
251 this.onCapture();
252 if (message.member === "ShortcutsChanged") {
253 try {
254 this.bound(decodeShortcuts(message.body[1]));
255 } catch (error) {
256 this.failed(error);
257 }
258 }
259 };
260
261 private async request(
262 member: string,
263 signature: string,
264 body: unknown[],
265 options: Record<string, Variant<unknown>> = {},
266 ) {
267 const token = `t3_${NodeCrypto.randomUUID().replaceAll("-", "")}`;
268 const expectedPath = this.namespace + token;
269 let resolve!: (body: unknown) => void;
270 const response = new Promise<unknown>((done) => {
271 resolve = done;
272 });
273 this.pending = { path: expectedPath, resolve };
274 this.responses.clear();
275 let completed = false;
276 try {
277 const reply = await this.call({
278 destination: this.owner,
279 path: PATH,
280 interface: SHORTCUTS,
281 member,
282 signature: signature + "a{sv}",
283 body: [...body, { ...options, handle_token: new Variant("s", token) }],
284 });
285 const handle = string(reply.body[0]);
286 if (!handle.startsWith(this.namespace)) throw new Error("Invalid shortcut request handle.");
287 this.pending.path = handle;
288 if (this.responses.has(handle)) resolve(this.responses.get(handle));
289 const [status, results] = decodeResponse(
290 await this.wait(response, member === "BindShortcuts" ? 120_000 : 5_000),
291 );
292 completed = true;
293 if (status !== 0) {
294 if (member === "BindShortcuts") {
295 this.update({
296 shortcutRegistered: false,
297 shortcutPending: false,
298 shortcutMessage:
299 this.version >= 2
300 ? "Shortcut permission wasn't granted. Open shortcut permissions to allow it."
301 : "Shortcut permission wasn't granted. Allow T3 Code in your desktop's shortcut settings.",
302 });
303 return undefined;
304 }
305 throw new Error("Your desktop could not create a capture shortcut session.");
306 }
307 return results;
308 } finally {
309 if (!completed && !this.closed && this.pending) this.closeObject(this.pending.path, REQUEST);
310 this.pending = undefined;
311 this.responses.clear();
312 }
313 }
314
315 private bound(shortcuts: typeof Shortcuts.Type) {
316 const shortcut = shortcuts.find(([id]) => id === this.shortcutId);
317 if (this.managedByHyprland) {
318 this.update({
319 shortcutRegistered: false,
320 shortcutActionRegistered: Boolean(shortcut),
321 shortcutPending: false,
322 shortcutMessage: shortcut
323 ? "Managed by Hyprland. Add the binding to your config and save it."
324 : "Hyprland did not register the capture action. Check that xdg-desktop-portal-hyprland is running, then restart T3 Code.",
325 });
326 return;
327 }
328 const label = shortcut?.[1].trigger_description?.value.trim();
329 this.update({
330 shortcutRegistered: Boolean(shortcut && label),
331 shortcutPending: false,
332 ...(label ? { shortcutLabel: label } : {}),
333 shortcutMessage: label
334 ? `Desktop shortcut: ${label}`
335 : this.version >= 2
336 ? "No shortcut is assigned. Open shortcut permissions to choose one."
337 : "No shortcut is assigned. Choose one in your desktop's shortcut settings.",
338 });
339 }
340
341 private async initialize(appId: string, shortcut: SnapShotKeyChord) {
342 const trigger = portalShortcutTrigger(shortcut);
343 if (!process.env.FLATPAK_ID && !process.env.SNAP) {
344 await this.call({
345 destination: PORTAL,
346 path: PATH,
347 interface: "org.freedesktop.host.portal.Registry",
348 member: "Register",
349 signature: "sa{sv}",
350 body: [appId, {}],
351 }).catch((error: unknown) => {
352 if (
353 !(
354 error instanceof DBusError &&
355 ["UnknownMethod", "UnknownInterface"].some(
356 (name) => error.type === `${DBUS}.Error.${name}`,
357 )
358 )
359 )
360 throw error;
361 });
362 }
363 const owner = await this.call({
364 destination: DBUS,
365 path: "/org/freedesktop/DBus",
366 interface: DBUS,
367 member: "GetNameOwner",
368 signature: "s",
369 body: [PORTAL],
370 });
371 this.owner = string(owner.body[0]);
372 this.namespace = `${PATH}/request/${owner.destination.slice(1).replaceAll(".", "_")}/`;
373 const version = await this.call({
374 destination: this.owner,
375 path: PATH,
376 interface: "org.freedesktop.DBus.Properties",
377 member: "Get",
378 signature: "ss",
379 body: [SHORTCUTS, "version"],
380 });
381 this.version = decodeVersion(version.body[0]).value;
382 for (const rule of [
383 `type='signal',sender='${this.owner}',path_namespace='${PATH}'`,
384 `type='signal',sender='org.freedesktop.DBus',interface='${DBUS}',member='NameOwnerChanged',arg0='${PORTAL}'`,
385 ])
386 await this.call({
387 destination: DBUS,
388 path: "/org/freedesktop/DBus",
389 interface: DBUS,
390 member: "AddMatch",
391 signature: "s",
392 body: [rule],
393 });
394 const created = await this.request("CreateSession", "", [], {
395 session_handle_token: new Variant(
396 "s",
397 `t3_capture_${NodeCrypto.randomUUID().replaceAll("-", "")}`,
398 ),
399 });
400 const session = decodeSession(created).session_handle.value;
401 const sessionNamespace = this.namespace.replace("/request/", "/session/");
402 if (!session.startsWith(sessionNamespace)) throw new Error("Invalid shortcut session handle.");
403 this.session = session;
404 this.shortcutId = this.managedByHyprland
405 ? HYPRLAND_CAPTURE_ACTION
406 : `t3-snap-shot-${NodeCrypto.createHash("sha256").update(trigger).digest("hex").slice(0, 16)}`;
407 // Every session must bind, even when the desktop remembers this shortcut's approval.
408 const bound = await this.request("BindShortcuts", "oa(sa{sv})s", [
409 this.session,
410 [
411 [
412 this.shortcutId,
413 {
414 description: new Variant("s", "Capture a window"),
415 ...(!this.managedByHyprland ? { preferred_trigger: new Variant("s", trigger) } : {}),
416 },
417 ],
418 ],
419 "",
420 ]);
421 if (bound) this.bound(decodeShortcutsResult(bound).shortcuts.value);
422 }
423}