Skip to content

Commit 68f1bc5

Browse files
fix(desktop): SnapShot shortcut rebinds after the desktop portal restarts (pingdotgg#35048)
1 parent cbc38a1 commit 68f1bc5

2 files changed

Lines changed: 83 additions & 20 deletions

File tree

‎apps/desktop/src/snapShot/PortalCaptureShortcut.test.ts‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ class FakeBus extends NodeEvents.EventEmitter {
3030
requestPath = "";
3131
boundId = "";
3232
foreignHandle = false;
33+
owner = ":1.2";
3334

3435
send(message: Message) {
3536
this.sends.push(message);
@@ -39,7 +40,7 @@ class FakeBus extends NodeEvents.EventEmitter {
3940
member: string,
4041
path: string,
4142
body: unknown[],
42-
sender = ":1.2",
43+
sender = this.owner,
4344
signature = "",
4445
) {
4546
this.emit(
@@ -71,7 +72,7 @@ class FakeBus extends NodeEvents.EventEmitter {
7172
]),
7273
});
7374
}
74-
activate(id = this.boundId, session = this.session, sender = ":1.2") {
75+
activate(id = this.boundId, session = this.session, sender = this.owner) {
7576
this.signal(portal, "Activated", root, [session, id, 1, {}], sender, "osta{sv}");
7677
}
7778
async call(message: Message) {
@@ -87,7 +88,7 @@ class FakeBus extends NodeEvents.EventEmitter {
8788
if (this.registryError) throw this.registryError;
8889
return reply();
8990
}
90-
if (message.member === "GetNameOwner") return reply([":1.2"]);
91+
if (message.member === "GetNameOwner") return reply([this.owner]);
9192
if (message.member === "Get") return reply([new Variant("u", this.version)]);
9293
if (message.member === "AddMatch" || message.member === "ConfigureShortcuts") return reply();
9394
const options = message.body.at(-1) as Record<string, Variant<string>>;
@@ -338,7 +339,30 @@ it("handles a disappearing portal without keeping a false registered state", asy
338339
);
339340
expect(client.state.shortcutRegistered).toBe(false);
340341
expect(client.state.shortcutMessage).toContain("restarted");
341-
expect(bus.disconnect).toHaveBeenCalledOnce();
342+
expect(client.hasSession).toBe(false);
343+
expect(bus.disconnect).not.toHaveBeenCalled();
344+
await vi.waitFor(() => expect(client.state.shortcutRegistered).toBe(true));
345+
expect(bus.calls.filter((call) => call.member === "CreateSession")).toHaveLength(2);
346+
});
347+
348+
it("binds a new session when the portal restarts", async () => {
349+
const { bus, client, capture } = start(new FakeBus(), chord, true);
350+
await client.ready;
351+
const ownerChanged = (from: string, to: string) =>
352+
bus.signal(
353+
"org.freedesktop.DBus",
354+
"NameOwnerChanged",
355+
"/org/freedesktop/DBus",
356+
["org.freedesktop.portal.Desktop", from, to],
357+
"org.freedesktop.DBus",
358+
);
359+
ownerChanged(":1.2", "");
360+
bus.owner = ":1.3";
361+
ownerChanged("", ":1.3");
362+
await vi.waitFor(() => expect(client.state.shortcutActionRegistered).toBe(true));
363+
expect(bus.calls.filter((call) => call.member === "CreateSession")).toHaveLength(2);
364+
bus.activate();
365+
expect(capture).toHaveBeenCalledOnce();
342366
});
343367

344368
it("accepts old portals without Registry but does not ignore permission denial", async () => {

‎apps/desktop/src/snapShot/PortalCaptureShortcut.ts‎

Lines changed: 55 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -67,15 +67,18 @@ export class PortalCaptureShortcut {
6767
};
6868
readonly ready: Promise<void>;
6969
private closed = false;
70+
private connection = 0;
7071
private owner = "";
7172
private namespace = "";
7273
private session = "";
7374
private shortcutId = "";
7475
private version = 0;
7576
private pending: { path: string; resolve: (body: unknown) => void } | undefined;
7677
private responses = new Map<string, unknown>();
77-
private readonly stopped: Promise<never>;
78+
private stopped!: Promise<never>;
7879
private rejectStopped!: (reason: Error) => void;
80+
private readonly appId: string;
81+
private readonly trigger: string;
7982
private readonly onCapture: () => void;
8083
private readonly onStateChanged: () => void;
8184
private readonly bus: MessageBus;
@@ -89,6 +92,8 @@ export class PortalCaptureShortcut {
8992
bus: MessageBus = sessionBus(),
9093
managedByHyprland = false,
9194
) {
95+
this.appId = appId;
96+
this.trigger = portalShortcutTrigger(shortcut);
9297
this.onCapture = onCapture;
9398
this.onStateChanged = onStateChanged;
9499
this.bus = bus;
@@ -99,13 +104,41 @@ export class PortalCaptureShortcut {
99104
shortcutPending: true,
100105
shortcutMessage: "Connecting to Hyprland shortcuts…",
101106
};
107+
this.resetStopped();
108+
bus.on("error", this.failed);
109+
bus.on("message", this.message);
110+
this.ready = this.connect(true);
111+
}
112+
113+
private resetStopped() {
102114
this.stopped = new Promise((_, reject) => {
103115
this.rejectStopped = reject;
104116
});
105117
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);
118+
}
119+
120+
private connect(first = false) {
121+
const connection = ++this.connection;
122+
return this.initialize(first).catch((error: unknown) => {
123+
if (connection === this.connection) this.failed(error);
124+
});
125+
}
126+
127+
private portalGone() {
128+
this.rejectStopped(new Error("The desktop shortcut service restarted."));
129+
this.resetStopped();
130+
this.owner = "";
131+
this.session = "";
132+
this.pending = undefined;
133+
this.responses.clear();
134+
this.update({
135+
shortcutRegistered: false,
136+
shortcutActionRegistered: false,
137+
shortcutPending: true,
138+
shortcutMessage: "The desktop shortcut service restarted. Reconnecting…",
139+
});
140+
// Register is sent to the well-known name, so it D-Bus-activates a portal that is not running.
141+
void this.connect();
109142
}
110143

111144
close = () => {
@@ -209,10 +242,9 @@ export class PortalCaptureShortcut {
209242
message.sender === "org.freedesktop.DBus" &&
210243
message.interface === DBUS &&
211244
message.member === "NameOwnerChanged" &&
212-
message.body[0] === PORTAL &&
213-
message.body[1] === this.owner
245+
message.body[0] === PORTAL
214246
) {
215-
this.failed(new Error("The desktop shortcut service restarted. Retry the shortcut request."));
247+
if (this.owner && message.body[1] === this.owner) this.portalGone();
216248
return;
217249
}
218250
if (!this.owner || message.sender !== this.owner) return;
@@ -270,7 +302,8 @@ export class PortalCaptureShortcut {
270302
const response = new Promise<unknown>((done) => {
271303
resolve = done;
272304
});
273-
this.pending = { path: expectedPath, resolve };
305+
const pending = { path: expectedPath, resolve };
306+
this.pending = pending;
274307
this.responses.clear();
275308
let completed = false;
276309
try {
@@ -284,7 +317,7 @@ export class PortalCaptureShortcut {
284317
});
285318
const handle = string(reply.body[0]);
286319
if (!handle.startsWith(this.namespace)) throw new Error("Invalid shortcut request handle.");
287-
this.pending.path = handle;
320+
pending.path = handle;
288321
if (this.responses.has(handle)) resolve(this.responses.get(handle));
289322
const [status, results] = decodeResponse(
290323
await this.wait(response, member === "BindShortcuts" ? 120_000 : 5_000),
@@ -306,9 +339,11 @@ export class PortalCaptureShortcut {
306339
}
307340
return results;
308341
} finally {
309-
if (!completed && !this.closed && this.pending) this.closeObject(this.pending.path, REQUEST);
310-
this.pending = undefined;
311-
this.responses.clear();
342+
if (this.pending === pending) {
343+
if (!completed && !this.closed) this.closeObject(pending.path, REQUEST);
344+
this.pending = undefined;
345+
this.responses.clear();
346+
}
312347
}
313348
}
314349

@@ -338,16 +373,16 @@ export class PortalCaptureShortcut {
338373
});
339374
}
340375

341-
private async initialize(appId: string, shortcut: SnapShotKeyChord) {
342-
const trigger = portalShortcutTrigger(shortcut);
376+
private async initialize(first: boolean) {
377+
const trigger = this.trigger;
343378
if (!process.env.FLATPAK_ID && !process.env.SNAP) {
344379
await this.call({
345380
destination: PORTAL,
346381
path: PATH,
347382
interface: "org.freedesktop.host.portal.Registry",
348383
member: "Register",
349384
signature: "sa{sv}",
350-
body: [appId, {}],
385+
body: [this.appId, {}],
351386
}).catch((error: unknown) => {
352387
if (
353388
!(
@@ -381,7 +416,11 @@ export class PortalCaptureShortcut {
381416
this.version = decodeVersion(version.body[0]).value;
382417
for (const rule of [
383418
`type='signal',sender='${this.owner}',path_namespace='${PATH}'`,
384-
`type='signal',sender='org.freedesktop.DBus',interface='${DBUS}',member='NameOwnerChanged',arg0='${PORTAL}'`,
419+
...(first
420+
? [
421+
`type='signal',sender='org.freedesktop.DBus',interface='${DBUS}',member='NameOwnerChanged',arg0='${PORTAL}'`,
422+
]
423+
: []),
385424
])
386425
await this.call({
387426
destination: DBUS,

0 commit comments

Comments
 (0)