Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PortalCaptureShortcut.test.ts

368 lines12.3 KB

1// @effect-diagnostics nodeBuiltinImport:off -- Event-driven fake of the portal transport.
2import * as NodeEvents from "node:events";
3import { DBusError, Message, MessageType, Variant, type MessageBus } from "dbus-next";
4import { afterEach, expect, it, vi } from "vite-plus/test";
5import { PortalCaptureShortcut, portalShortcutTrigger } from "./PortalCaptureShortcut.ts";
6​
7const chord = {
8 key: "2",
9 modKey: true,
10 ctrlKey: false,
11 altKey: false,
12 shiftKey: true,
13 metaKey: false,
14};
15const root = "/org/freedesktop/portal/desktop";
16const portal = "org.freedesktop.portal.GlobalShortcuts";
17const clients: PortalCaptureShortcut[] = [];
18type Shortcut = [string, { description?: Variant<string>; trigger_description?: Variant<string> }];
19​
20class FakeBus extends NodeEvents.EventEmitter {
21 calls: Message[] = [];
22 sends: Message[] = [];
23 disconnect = vi.fn();
24 registryError: Error | undefined;
25 version = 2;
26 autoBind = true;
27 actualLabel = "Ctrl+Shift+2";
28 bindStatus = 0;
29 session = "";
30 requestPath = "";
31 boundId = "";
32 foreignHandle = false;
33​
34 send(message: Message) {
35 this.sends.push(message);
36 }
37 signal(
38 iface: string,
39 member: string,
40 path: string,
41 body: unknown[],
42 sender = ":1.2",
43 signature = "",
44 ) {
45 this.emit(
46 "message",
47 new Message({
48 type: MessageType.SIGNAL,
49 sender,
50 interface: iface,
51 member,
52 path,
53 body,
54 signature,
55 }),
56 );
57 }
58 response(path: string, status: number, results: Record<string, Variant<unknown>>) {
59 this.signal("org.freedesktop.portal.Request", "Response", path, [status, results]);
60 }
61 respondBind(status = this.bindStatus) {
62 this.response(this.requestPath, status, {
63 shortcuts: new Variant("a(sa{sv})", [
64 [
65 this.boundId,
66 {
67 description: new Variant("s", "Capture a window"),
68 trigger_description: new Variant("s", this.actualLabel),
69 },
70 ],
71 ]),
72 });
73 }
74 activate(id = this.boundId, session = this.session, sender = ":1.2") {
75 this.signal(portal, "Activated", root, [session, id, 1, {}], sender, "osta{sv}");
76 }
77 async call(message: Message) {
78 this.calls.push(message);
79 const reply = (body: unknown[] = []) =>
80 new Message({
81 type: MessageType.METHOD_RETURN,
82 replySerial: "1",
83 destination: ":1.23",
84 body,
85 });
86 if (message.member === "Register") {
87 if (this.registryError) throw this.registryError;
88 return reply();
89 }
90 if (message.member === "GetNameOwner") return reply([":1.2"]);
91 if (message.member === "Get") return reply([new Variant("u", this.version)]);
92 if (message.member === "AddMatch" || message.member === "ConfigureShortcuts") return reply();
93 const options = message.body.at(-1) as Record<string, Variant<string>>;
94 const path = `${root}/request/1_23/${options.handle_token!.value}`;
95 if (message.member === "CreateSession") {
96 this.session = `${root}/session/1_23/${options.session_handle_token!.value}`;
97 this.response(path, 0, {
98 session_handle: new Variant(
99 "s",
100 this.foreignHandle ? `${root}/session/9_9/other` : this.session,
101 ),
102 });
103 } else if (message.member === "BindShortcuts") {
104 this.boundId = (message.body[1] as Shortcut[])[0]![0];
105 this.requestPath = path;
106 this.emit("bind");
107 if (this.autoBind) this.respondBind();
108 } else throw new Error(`Unexpected call: ${message.member}`);
109 return reply([path]);
110 }
112​
113function start(bus = new FakeBus(), shortcut = chord, managedByHyprland = false) {
114 const capture = vi.fn();
115 const changed = vi.fn();
116 const client = new PortalCaptureShortcut(
117 "com.t3tools.T3Code",
118 shortcut,
119 capture,
120 changed,
121 bus as unknown as MessageBus,
122 managedByHyprland,
123 );
124 clients.push(client);
125 return { bus, client, capture, changed };
127​
128afterEach(() => {
129 for (const client of clients.splice(0)) client.close();
130 vi.useRealTimers();
131 vi.unstubAllEnvs();
132});
133​
134it("accepts Hyprland's action-only binding without claiming the keys are reserved", async () => {
135 const bus = new FakeBus();
136 bus.actualLabel = "";
137 const { client, capture } = start(bus, chord, true);
138 await client.ready;
139 expect(client.state).toMatchObject({
140 shortcutRegistered: false,
141 shortcutActionRegistered: true,
142 shortcutPending: false,
143 shortcutCanRetry: false,
144 });
145 expect(bus.boundId).toBe("capture-window");
146 expect(bus.calls.find((call) => call.member === "BindShortcuts")?.body[1]).toEqual([
147 ["capture-window", { description: new Variant("s", "Capture a window") }],
148 ]);
149 bus.activate("wrong");
150 bus.activate(bus.boundId, bus.session, ":1.999");
151 expect(capture).not.toHaveBeenCalled();
152 bus.activate();
153 expect(capture).toHaveBeenCalledOnce();
154 await expect(client.configure()).rejects.toThrow("Hyprland config");
155 bus.signal(portal, "ShortcutsChanged", root, [bus.session, []]);
156 bus.activate();
157 expect(capture).toHaveBeenCalledOnce();
158 expect(client.state.shortcutActionRegistered).toBe(false);
159});
160​
161it.each([
162 ["2", "CTRL+SHIFT+2"],
163 ["f12", "CTRL+SHIFT+F12"],
164 ["pageup", "CTRL+SHIFT+Page_Up"],
165 ["+", "CTRL+SHIFT+plus"],
166 ["arrowleft", "CTRL+SHIFT+Left"],
167 [" ", "CTRL+SHIFT+space"],
168])("encodes %s as an XDG shortcut", (key, expected) => {
169 expect(portalShortcutTrigger({ ...chord, key })).toBe(expected);
170});
171it("normalizes Ctrl/Mod and rejects unsupported keys before requesting access", () => {
172 expect(portalShortcutTrigger({ ...chord, ctrlKey: true, metaKey: true })).toBe(
173 "CTRL+SHIFT+LOGO+2",
174 );
175 expect(() => portalShortcutTrigger({ ...chord, key: "unknown-key" })).toThrow("isn't supported");
176});
177​
178it("does not call submission approval, then reads the actual assigned shortcut", async () => {
179 const bus = new FakeBus();
180 bus.autoBind = false;
181 bus.actualLabel = "Ctrl+Shift+7";
182 const binding = NodeEvents.EventEmitter.once(bus, "bind");
183 const { client } = start(bus);
184 await binding;
185 expect(client.state.shortcutRegistered).toBe(false);
186 expect(client.state.shortcutPending).toBe(true);
187 bus.respondBind();
188 await client.ready;
189 expect(client.state).toMatchObject({
190 shortcutRegistered: true,
191 shortcutPending: false,
192 shortcutLabel: "Ctrl+Shift+7",
193 });
194});
195​
196it("binds only the requested shortcut with a stable ID across sessions", async () => {
197 const first = start();
198 await first.client.ready;
199 first.client.close();
200 const { bus, client, capture } = start();
201 await client.ready;
202 expect(bus.boundId).toBe(first.bus.boundId);
203 const binds = bus.calls.filter((call) => call.member === "BindShortcuts");
204 expect(binds).toHaveLength(1);
205 expect(binds[0]!.body[1]).toEqual([
206 [
207 bus.boundId,
208 {
209 description: new Variant("s", "Capture a window"),
210 preferred_trigger: new Variant("s", "CTRL+SHIFT+2"),
211 },
212 ],
213 ]);
214 bus.activate();
215 expect(capture).toHaveBeenCalledOnce();
216 expect(bus.calls[0]?.member).toBe("Register");
217});
218​
219it("ignores other shortcuts, sessions, and forged activations", async () => {
220 const { bus, client, capture } = start();
221 await client.ready;
222 bus.activate("stale-shortcut");
223 bus.activate(bus.boundId, `${root}/session/9_9/other`);
224 bus.activate(bus.boundId, bus.session, ":1.999");
225 expect(capture).not.toHaveBeenCalled();
226 bus.activate();
227 expect(capture).toHaveBeenCalledOnce();
228});
229​
230it("replaces a binding without restarting the application and stops the old callback", async () => {
231 const first = start();
232 await first.client.ready;
233 first.client.close();
234 const next = start(new FakeBus(), { ...chord, key: "8" });
235 await next.client.ready;
236 expect(next.bus.boundId).not.toBe(first.bus.boundId);
237 expect(next.bus.calls.find((call) => call.member === "BindShortcuts")?.body[1]).toEqual([
238 [
239 next.bus.boundId,
240 {
241 description: new Variant("s", "Capture a window"),
242 preferred_trigger: new Variant("s", "CTRL+SHIFT+8"),
243 },
244 ],
245 ]);
246 first.bus.activate();
247 next.bus.activate();
248 expect(first.capture).not.toHaveBeenCalled();
249 expect(next.capture).toHaveBeenCalledOnce();
250 expect(
251 first.bus.sends.some(
252 (message) =>
253 message.interface === "org.freedesktop.portal.Session" && message.member === "Close",
254 ),
255 ).toBe(true);
256});
257​
258it.each([1, 2])(
259 "reports denied/cancelled response %s and offers the desktop permissions UI",
260 async (status) => {
261 const bus = new FakeBus();
262 bus.bindStatus = status;
263 const { client, capture } = start(bus);
264 await client.ready;
265 expect(client.state.shortcutRegistered).toBe(false);
266 expect(client.state.shortcutPending).toBe(false);
267 expect(client.state.shortcutCanRetry).toBe(true);
268 expect(client.state.shortcutMessage).toContain("wasn't granted");
269 bus.activate();
270 expect(capture).not.toHaveBeenCalled();
271 await client.configure();
272 expect(bus.calls.at(-1)?.member).toBe("ConfigureShortcuts");
273 },
274);
275​
276it("treats a remembered empty binding as unassigned, then observes desktop-side edits", async () => {
277 const bus = new FakeBus();
278 bus.actualLabel = "";
279 const { client, capture } = start(bus);
280 await client.ready;
281 expect(client.state.shortcutRegistered).toBe(false);
282 bus.activate();
283 expect(capture).not.toHaveBeenCalled();
284 bus.signal(portal, "ShortcutsChanged", root, [
285 bus.session,
286 [[bus.boundId, { trigger_description: new Variant("s", "Meta+F12") }]],
287 ]);
288 expect(client.state.shortcutLabel).toBe("Meta+F12");
289 expect(client.state.shortcutRegistered).toBe(true);
290 bus.activate();
291 expect(capture).toHaveBeenCalledOnce();
292});
293​
294it("captures on older portals without offering an unsupported permission dialog", async () => {
295 const bus = new FakeBus();
296 bus.version = 1;
297 const { client, capture } = start(bus);
298 await client.ready;
299 expect(client.state).toMatchObject({ shortcutRegistered: true, shortcutCanRetry: false });
300 bus.activate();
301 expect(capture).toHaveBeenCalledOnce();
302 bus.signal(portal, "ShortcutsChanged", root, [bus.session, []]);
303 expect(client.state).toMatchObject({
304 shortcutRegistered: false,
305 shortcutCanRetry: false,
306 shortcutMessage: "No shortcut is assigned. Choose one in your desktop's shortcut settings.",
307 });
308 bus.signal("org.freedesktop.portal.Session", "Closed", bus.session, []);
309 expect(client.hasSession).toBe(false);
310 expect(client.state.shortcutCanRetry).toBe(true);
311});
312​
313it("closes an outstanding consent request and ignores its late response", async () => {
314 const bus = new FakeBus();
315 bus.autoBind = false;
316 const binding = NodeEvents.EventEmitter.once(bus, "bind");
317 const { client, capture, changed } = start(bus);
318 await binding;
319 client.close();
320 bus.respondBind();
321 await client.ready;
322 bus.activate();
323 expect(capture).not.toHaveBeenCalled();
324 expect(changed).not.toHaveBeenCalled();
325 expect(bus.sends.filter((message) => message.member === "Close")).toHaveLength(2);
326 expect(bus.disconnect).toHaveBeenCalledOnce();
327});
328​
329it("handles a disappearing portal without keeping a false registered state", async () => {
330 const { bus, client } = start();
331 await client.ready;
332 bus.signal(
333 "org.freedesktop.DBus",
334 "NameOwnerChanged",
335 "/org/freedesktop/DBus",
336 ["org.freedesktop.portal.Desktop", ":1.2", ""],
337 "org.freedesktop.DBus",
338 );
339 expect(client.state.shortcutRegistered).toBe(false);
340 expect(client.state.shortcutMessage).toContain("restarted");
341 expect(bus.disconnect).toHaveBeenCalledOnce();
342});
343​
344it("accepts old portals without Registry but does not ignore permission denial", async () => {
345 const bus = new FakeBus();
346 bus.registryError = new DBusError("org.freedesktop.DBus.Error.UnknownMethod", "Old portal");
347 const first = start(bus);
348 await first.client.ready;
349 expect(first.client.state.shortcutRegistered).toBe(true);
350 const denied = new FakeBus();
351 denied.registryError = new DBusError(
352 "org.freedesktop.portal.Error.NotAllowed",
353 "App is not allowed",
354 );
355 const second = start(denied);
356 await second.client.ready;
357 expect(second.client.state.shortcutRegistered).toBe(false);
358 expect(denied.calls.some((call) => call.member === "CreateSession")).toBe(false);
359});
360​
361it("rejects a foreign session without trying to close someone else's session", async () => {
362 const bus = new FakeBus();
363 bus.foreignHandle = true;
364 const { client } = start(bus);
365 await client.ready;
366 expect(client.state.shortcutRegistered).toBe(false);
367 expect(bus.sends.some((message) => message.path.includes("9_9"))).toBe(false);
368});