Files
electron/lib/browser/api/desktop-capturer.ts
T
Shelley Vohr 37d0d2b4ce feat: allow restoring a desktopCapturer source across launches on Wayland (#54550)
* chore: patch webrtc to keep the ScreenCast persist mode with the restore token

Carries https://webrtc-review.googlesource.com/c/src/+/505860 until it
rolls. RestoreTokenManager stores the portal persist mode next to each
restore token and BaseCapturerPipeWire::Start() requests that mode when
restoring, so a persistent token stays persistent. Existing callers
default to transient and behave as before.

* feat: allow restoring a desktopCapturer source across launches on Wayland

On Wayland desktopCapturer.getSources() shows the xdg-desktop-portal
picker on every call, so a screen-capture app has to ask the user again
on every launch even though ScreenCast v4 can persist the grant.

Add `persistMode` ('transient' | 'persistent') and `restoreToken`
options to getSources(), a `restoreToken` property on the returned
sources, and desktopCapturer.getRestoreToken(sourceId) to read the
token again after it rotates when a stream starts. With a stored
persistent token the picker is skipped; a revoked or stale token falls
back to the picker. Electron does not store tokens; the docs show how
an app can. Other platforms ignore the options and return an empty
restoreToken.

* docs: say when persistMode is needed with a token and add API history

* chore: update the carried webrtc patch to the latest upstream revision

The persist mode enum moved to modules/portal/screencast_persist_mode.h
upstream, so use it from there instead of including screencast_portal.h.

* docs: say how a restored window is matched and handle a cancelled picker

GNOME and KDE save a window as its app id and title and restore the open
window of that app with the closest title, so a token does not always bring
back the window the user picked. The sample now denies the request when the
user closes the picker.

* docs: format the restore token sample

* fix: forward restore tokens from xdg-desktop-portal 1.22.1

Only tokens that parse as a UUID were passed to the portal. Since 1.22.1 it
issues 22 character base64 tokens, and accepts those and UUIDs, so every
token from a new portal was dropped and the picker came back. Forward what
the portal itself accepts.

* chore: drop the webrtc patch that has rolled in

https://webrtc-review.googlesource.com/c/src/+/505860 is part of the WebRTC
that Chromium 157.0.8085.0 pins.

* fix: only look up and seed restore tokens for picker sessions

Also covers an empty source list and a second request in the docs sample, and adds a round-trip spec.

* fix: pass restore tokens through unchecked and require persistMode with them

The portal's token grammar changed once already (1.22.1) and copying it here
silently dropped valid tokens, so the token now goes to the portal as given: a
value it did not issue makes getSources() reject, which the docs and the sample
handle. restoreToken without persistMode restored a persistent grant as
transient and ended it, so that combination is now an invalid option.
2026-10-19 19:46:12 +02:00

111 lines
3.7 KiB
TypeScript

import { BaseWindow } from 'electron/main';
const { createDesktopCapturer, isDisplayMediaSystemPickerAvailable, getRestoreToken } = process._linkedBinding(
'electron_browser_desktop_capturer'
);
const deepEqual = (a: ElectronInternal.GetSourcesOptions, b: ElectronInternal.GetSourcesOptions) =>
JSON.stringify(a) === JSON.stringify(b);
let currentlyRunning: {
options: ElectronInternal.GetSourcesOptions;
getSources: Promise<ElectronInternal.GetSourcesResult[]>;
}[] = [];
const persistModes = new Set(['transient', 'persistent']);
function isValid(options: Electron.SourcesOptions) {
if (!Array.isArray(options?.types)) return false;
if (options.persistMode != null && !persistModes.has(options.persistMode)) return false;
if (options.restoreToken != null && typeof options.restoreToken !== 'string') return false;
return !options.restoreToken || options.persistMode != null;
}
export { isDisplayMediaSystemPickerAvailable, getRestoreToken };
export async function getSources(args: Electron.SourcesOptions) {
if (!isValid(args)) throw new Error('Invalid options');
const resizableValues = new Map<number, boolean>();
if (process.platform === 'darwin') {
// Fix for bug in ScreenCaptureKit that modifies a window's styleMask the first time
// it captures a non-resizable window. We record each non-resizable window's styleMask,
// and we restore modified styleMasks later, after the screen capture.
for (const win of BaseWindow.getAllWindows()) {
resizableValues.set(win.id, win.resizable);
}
}
const captureWindow = args.types.includes('window');
const captureScreen = args.types.includes('screen');
const { thumbnailSize = { width: 150, height: 150 } } = args;
const { fetchWindowIcons = false } = args;
const persistent = args.persistMode === 'persistent';
const restoreToken = args.restoreToken ?? '';
const options = {
captureWindow,
captureScreen,
thumbnailSize,
fetchWindowIcons,
persistent,
restoreToken
};
for (const running of currentlyRunning) {
if (deepEqual(running.options, options)) {
// If a request is currently running for the same options
// return that promise
return running.getSources;
}
}
let resolveGetSources!: (value: ElectronInternal.GetSourcesResult[]) => void;
let rejectGetSources!: (reason?: any) => void;
const getSources = new Promise<ElectronInternal.GetSourcesResult[]>((resolve, reject) => {
resolveGetSources = resolve;
rejectGetSources = reject;
});
// Register in currentlyRunning BEFORE startHandling so that synchronous
// completion (e.g. when no capturers are created) can properly clean up.
currentlyRunning.push({ options, getSources });
let capturer: ElectronInternal.DesktopCapturer | null = createDesktopCapturer();
const stopRunning = () => {
if (capturer) {
delete capturer._onerror;
delete capturer._onfinished;
capturer = null;
if (process.platform === 'darwin') {
for (const win of BaseWindow.getAllWindows()) {
const resizable = resizableValues.get(win.id);
if (resizable !== undefined && win.resizable !== resizable) {
win.resizable = resizable;
}
}
}
}
// Remove from currentlyRunning once we resolve or reject
currentlyRunning = currentlyRunning.filter((running) => running.options !== options);
};
capturer._onerror = (error: string) => {
stopRunning();
rejectGetSources(error);
};
capturer._onfinished = (sources: Electron.DesktopCapturerSource[]) => {
stopRunning();
resolveGetSources(sources);
};
capturer.startHandling(captureWindow, captureScreen, thumbnailSize, fetchWindowIcons, persistent, restoreToken);
return getSources;
}