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

DesktopWindow.ts

1,007 lines38.0 KB

1import * as Clock from "effect/Clock";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Ref from "effect/Ref";
8​
9import * as Electron from "electron";
10​
11import { type DesktopSnapShotEvent, DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts";
12​
13import * as DesktopAssets from "../app/DesktopAssets.ts";
14import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
15import { makeComponentLogger } from "../app/DesktopObservability.ts";
16import * as ElectronMenu from "../electron/ElectronMenu.ts";
17import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
18import * as ElectronShell from "../electron/ElectronShell.ts";
19import * as ElectronTheme from "../electron/ElectronTheme.ts";
20import * as ElectronWindow from "../electron/ElectronWindow.ts";
21import {
22 MENU_ACTION_CHANNEL,
23 QUIT_SHORTCUT_CHANNEL,
24 SNAP_SHOT_EVENT_CHANNEL,
25 TRACKPAD_SCROLL_END_CHANNEL,
26 WINDOW_FULLSCREEN_STATE_CHANNEL,
27} from "../ipc/channels.ts";
28import { PASSKEY_BRIDGE_ARGUMENT } from "../preview/GuestProtocol.ts";
29import * as PreviewManager from "../preview/Manager.ts";
30import * as PreviewPasskeys from "../preview/Passkeys.ts";
31import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
32import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
33import * as ElectronApp from "../electron/ElectronApp.ts";
34import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts";
35import { makeQuitShortcutHandler } from "./QuitHold.ts";
36import { copyContextMenuImage } from "./ContextMenuImage.ts";
37​
38const TITLEBAR_HEIGHT = 40;
39// Matches --workspace-topbar-height in apps/web/src/index.css. Native macOS
40// buttons are 14 points tall and do not scale with the renderer's zoom.
41const MACOS_WORKSPACE_TOPBAR_HEIGHT = 52;
42const MACOS_WINDOW_BUTTON_RADIUS = 7;
43​
44function syncMacosWindowButtons(window: Electron.BrowserWindow): void {
45 if (window.isDestroyed() || window.isFullScreen()) return;
46 window.setWindowButtonPosition({
47 x: 16,
48 y: Math.round(
49 (MACOS_WORKSPACE_TOPBAR_HEIGHT * window.webContents.getZoomFactor()) / 2 -
50 MACOS_WINDOW_BUTTON_RADIUS,
51 ),
52 });
54​
55const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
56const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
57const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
58const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
59const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
60const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500;
61const RENDERER_RECOVERY_MAX_ATTEMPTS = 3;
62const RENDERER_RECOVERY_WINDOW_MS = 60_000;
63const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([-2, -7, -9, -102, -105, -106, -118]);
64​
65type WindowTitleBarOptions = Pick<
66 Electron.BrowserWindowConstructorOptions,
67 "titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
68>;
69​
70type DesktopWindowRuntimeServices =
71 | DesktopEnvironment.DesktopEnvironment
72 | DesktopAssets.DesktopAssets
73 | DesktopAppSettings.DesktopAppSettings
74 | DesktopClientSettings.DesktopClientSettings
75 | ElectronApp.ElectronApp
76 | ElectronMenu.ElectronMenu
77 | ElectronShell.ElectronShell
78 | ElectronTheme.ElectronTheme
79 | ElectronWindow.ElectronWindow
80 | DesktopRendererHistory.DesktopRendererHistory
81 | PreviewManager.PreviewManager;
82​
83export type DesktopWindowError =
84 | ElectronWindow.ElectronWindowCreateError
85 | PreviewManager.PreviewManagerError;
86​
87export type MainWindowZoomDirection = "in" | "out" | "reset";
88export type MainWindowContentsCommand = "reload" | "forceReload" | "toggleDevTools";
89​
90export class DesktopWindow extends Context.Service<
91 DesktopWindow,
92 {
93 readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
94 readonly ensureMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
95 readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
96 readonly activate: Effect.Effect<void, DesktopWindowError>;
97 readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
98 readonly showConnectingSplash: Effect.Effect<void>;
99 readonly handleBackendReady: (httpBaseUrl: URL) => Effect.Effect<void, DesktopWindowError>;
100 readonly handleBackendNotReady: Effect.Effect<void>;
101 readonly flushMainWindowBounds: Effect.Effect<void>;
102 readonly prepareCaptureReveal: Effect.Effect<void>;
103 readonly dispatchMenuAction: (
104 action: string,
105 options?: { readonly reveal?: boolean },
106 ) => Effect.Effect<void, DesktopWindowError>;
107 readonly dispatchSnapShotEvent: (
108 event: DesktopSnapShotEvent,
109 ) => Effect.Effect<void, DesktopWindowError>;
110 // The Electron `zoomIn`/`zoomOut` menu roles act on whichever webContents
111 // has keyboard focus, so with an embedded preview WebContentsView (or
112 // DevTools) focused they zoom the guest page instead of the app UI.
113 readonly zoomMain: (direction: MainWindowZoomDirection) => Effect.Effect<void>;
114 readonly runMainContentsCommand: (command: MainWindowContentsCommand) => Effect.Effect<void>;
115 readonly syncAppearance: Effect.Effect<void>;
116 }
117>()("@t3tools/desktop/window/DesktopWindow") {}
118​
119const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
120 makeComponentLogger("desktop-window");
121​
122function getIconOption(
123 iconPaths: DesktopAssets.DesktopIconPaths,
124 platform: NodeJS.Platform,
125): { icon: string } | Record<string, never> {
126 if (platform === "darwin") return {};
127 const ext = platform === "win32" ? "ico" : "png";
128 return Option.match(iconPaths[ext], {
129 onNone: () => ({}),
130 onSome: (icon) => ({ icon }),
131 });
133​
134function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
135 return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
137​
138type DisplayBounds = Pick<Electron.Rectangle, "x" | "y" | "width" | "height">;
139​
140function windowFitsWithinDisplay(
141 windowBounds: DesktopAppSettings.DesktopWindowBounds,
142 displayBounds: DisplayBounds,
143): boolean {
144 return (
145 windowBounds.x >= displayBounds.x &&
146 windowBounds.y >= displayBounds.y &&
147 windowBounds.x + windowBounds.width <= displayBounds.x + displayBounds.width &&
148 windowBounds.y + windowBounds.height <= displayBounds.y + displayBounds.height
149 );
151​
152function windowBoundsEqual(
153 left: DesktopAppSettings.DesktopWindowBounds,
154 right: DesktopAppSettings.DesktopWindowBounds,
155): boolean {
156 return (
157 left.x === right.x &&
158 left.y === right.y &&
159 left.width === right.width &&
160 left.height === right.height
161 );
163​
164export function resolveInitialMainWindowBounds(
165 persistedBounds: DesktopAppSettings.DesktopWindowBounds | null,
166 displays: readonly DisplayBounds[],
167): DesktopAppSettings.DesktopWindowBounds | typeof DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE {
168 if (
169 persistedBounds !== null &&
170 displays.some((display) => windowFitsWithinDisplay(persistedBounds, display))
171 ) {
172 return persistedBounds;
173 }
174 return DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE;
176​
177function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string {
178 const background = getInitialWindowBackgroundColor(shouldUseDarkColors);
179 const label = shouldUseDarkColors ? "#9ca3af" : "#6b7280";
180 const accent = shouldUseDarkColors ? "#f8fafc" : "#1f2937";
181 const track = shouldUseDarkColors ? "rgba(248,250,252,0.18)" : "rgba(31,41,55,0.18)";
182 const html = `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><style>html,body{margin:0;height:100%}body{background:${background};color:${label};font-family:system-ui,-apple-system,'Segoe UI',sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;-webkit-user-select:none;user-select:none;-webkit-app-region:drag}.spinner{width:26px;height:26px;border:3px solid ${track};border-top-color:${accent};border-radius:50%;animation:spin .8s linear infinite}.label{font-size:13px}@keyframes spin{to{transform:rotate(360deg)}}</style></head><body><div class="spinner"></div><div class="label">Connecting to WSL…</div></body></html>`;
183 return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
185​
186export function isSameOriginRendererNavigation(input: {
187 readonly applicationUrl: string;
188 readonly navigationUrl: string;
189}): boolean {
190 try {
191 return new URL(input.applicationUrl).origin === new URL(input.navigationUrl).origin;
192 } catch {
193 return false;
194 }
196​
197export function isRetryableDevelopmentRendererLoadFailure(input: {
198 readonly applicationUrl: string;
199 readonly errorCode: number;
200 readonly isMainFrame: boolean;
201 readonly validatedUrl: string;
202}): boolean {
203 return (
204 input.isMainFrame &&
205 DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
206 isSameOriginRendererNavigation({
207 applicationUrl: input.applicationUrl,
208 navigationUrl: input.validatedUrl,
209 })
210 );
212​
213export function concealPendingQuitWindow(
214 window: Pick<
215 Electron.BrowserWindow,
216 "isDestroyed" | "isFullScreen" | "setFullScreen" | "setOpacity"
217 >,
218): void {
219 if (window.isDestroyed()) return;
220 if (window.isFullScreen()) {
221 window.setFullScreen(false);
222 }
223 // Electron implements window opacity on macOS and Windows. Linux keeps the
224 // release-gated quit behavior but cannot make the pending window disappear.
225 window.setOpacity(0);
227​
228function getWindowTitleBarOptions(
229 shouldUseDarkColors: boolean,
230 platform: NodeJS.Platform,
231): WindowTitleBarOptions {
232 if (platform === "darwin") {
233 return {
234 titleBarStyle: "hiddenInset",
235 trafficLightPosition: {
236 x: 16,
237 y: MACOS_WORKSPACE_TOPBAR_HEIGHT / 2 - MACOS_WINDOW_BUTTON_RADIUS,
238 },
239 };
240 }
241​
242 return {
243 titleBarStyle: "hidden",
244 titleBarOverlay: {
245 color: TITLEBAR_COLOR,
246 height: TITLEBAR_HEIGHT,
247 symbolColor: shouldUseDarkColors ? TITLEBAR_DARK_SYMBOL_COLOR : TITLEBAR_LIGHT_SYMBOL_COLOR,
248 },
249 };
251​
252function syncWindowAppearance(
253 window: Electron.BrowserWindow,
254 shouldUseDarkColors: boolean,
255 platform: NodeJS.Platform,
256): Effect.Effect<void> {
257 return Effect.sync(() => {
258 if (window.isDestroyed()) {
259 return;
260 }
261​
262 window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
263 const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
264 if (typeof titleBarOverlay === "object") {
265 window.setTitleBarOverlay(titleBarOverlay);
266 }
267 });
269​
270type RevealSubscription = (listener: () => void) => void;
271​
272function bindFirstRevealTrigger(
273 subscribers: readonly RevealSubscription[],
274 reveal: () => void,
275): void {
276 let revealed = false;
277 const fire = () => {
278 if (revealed) return;
279 revealed = true;
280 reveal();
281 };
282 for (const subscribe of subscribers) {
283 subscribe(fire);
284 }
286​
287/** @public Service construction is part of the canonical Effect module API. */
288export const make = Effect.gen(function* () {
289 const environment = yield* DesktopEnvironment.DesktopEnvironment;
290 const assets = yield* DesktopAssets.DesktopAssets;
291 const electronMenu = yield* ElectronMenu.ElectronMenu;
292 const electronShell = yield* ElectronShell.ElectronShell;
293 const electronTheme = yield* ElectronTheme.ElectronTheme;
294 const electronWindow = yield* ElectronWindow.ElectronWindow;
295 const previewManager = yield* PreviewManager.PreviewManager;
296 const previewPasskeys = yield* PreviewPasskeys.PreviewPasskeys;
297 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
298 const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
299 const electronApp = yield* ElectronApp.ElectronApp;
300 const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory;
301 const backendReadyRef = yield* Ref.make(false);
302 const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
303 const context = yield* Effect.context<DesktopWindowRuntimeServices>();
304 const runFork = Effect.runForkWith(context);
305 const runPromise = Effect.runPromiseWith(context);
306 let flushMainWindowBounds: Effect.Effect<void> = Effect.void;
307​
308 const dismissConnectingSplash = Effect.gen(function* () {
309 const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
310 if (Option.isSome(splash) && !splash.value.isDestroyed()) {
311 splash.value.close();
312 }
313 });
314​
315 // currentMainOrFirst / focusedMainOrFirst fall back to "any first window",
316 // which during WSL-only boot is the connecting splash. The splash is never
317 // registered via setMain, so it must be treated as "no real main window" --
318 // otherwise ensureMain/activate/dispatchMenuAction latch onto it and never
319 // open (or retry) the real main.
320 const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
321 Ref.get(splashWindowRef).pipe(
322 Effect.map((splash) =>
323 Option.isSome(splash) && Option.isSome(window) && window.value === splash.value
324 ? Option.none<Electron.BrowserWindow>()
325 : window,
326 ),
327 );
328​
329 const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
330 const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
331​
332 const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
333 Electron.BrowserWindow,
334 DesktopWindowError
335 > {
336 yield* previewManager.getBrowserSession();
337 const applicationUrl = getDesktopUrl(environment.isDevelopment);
338 const iconPaths = yield* assets.iconPaths;
339 const iconOption = getIconOption(iconPaths, environment.platform);
340 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
341 const persistedSettings = yield* desktopSettings.get;
342 const persistedBounds = persistedSettings.mainWindowBounds;
343 const displayBoundsResult = yield* Effect.sync(() => {
344 try {
345 return {
346 _tag: "Success" as const,
347 bounds: Electron.screen.getAllDisplays().map((display) => display.bounds),
348 };
349 } catch (cause) {
350 return { _tag: "Failure" as const, cause };
351 }
352 });
353 const displayBounds =
354 displayBoundsResult._tag === "Success"
355 ? displayBoundsResult.bounds
356 : yield* logWindowWarning("failed to read connected displays; using defaults", {
357 cause: displayBoundsResult.cause,
358 }).pipe(Effect.as<readonly Electron.Rectangle[]>([]));
359 const initialBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds);
360 const restoredPersistedBounds = persistedBounds !== null && initialBounds === persistedBounds;
361 if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) {
362 yield* logWindowWarning("saved main window bounds could not be restored; using defaults");
363 }
364 const window = yield* electronWindow.create({
365 ...initialBounds,
366 minWidth: 840,
367 minHeight: 620,
368 show: false,
369 autoHideMenuBar: true,
370 ...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
371 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
372 ...iconOption,
373 title: environment.displayName,
374 ...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
375 webPreferences: {
376 preload: environment.preloadPath,
377 // Chromium throttles hidden renderers: timers coalesce and rAF stops,
378 // which stalls first paint. Boot unthrottled; the first-reveal trigger
379 // re-enables throttling so a hidden or minimized window goes back to
380 // being cheap after it has been shown once.
381 backgroundThrottling: false,
382 contextIsolation: true,
383 nodeIntegration: false,
384 sandbox: true,
385 webviewTag: true,
386 // A preview guest's fullscreen request is mirrored onto this embedder,
387 // which would otherwise put the whole window into OS fullscreen. With
388 // both sides opted out the page fills its webview and the window stays.
389 disableHtmlFullscreenWindowResize: true,
390 },
391 });
392​
393 yield* rendererHistory.register(window.webContents, { surface: "main" });
394 if (environment.platform === "darwin") {
395 window.setAutoHideCursor(false);
396 }
397 let boundsPersistFiber: Fiber.Fiber<void, never> | undefined;
398 let pendingBoundsPersistFiber: Fiber.Fiber<void, never> | undefined;
399 let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds;
400 const readPersistableBounds = (): DesktopAppSettings.DesktopWindowBounds | null => {
401 if (window.isDestroyed()) {
402 return null;
403 }
404 const bounds =
405 window.isFullScreen() || window.isMaximized() || window.isMinimized()
406 ? window.getNormalBounds()
407 : window.getBounds();
408 return DesktopAppSettings.normalizeMainWindowBounds({
409 x: Math.round(bounds.x),
410 y: Math.round(bounds.y),
411 width: Math.round(bounds.width),
412 height: Math.round(bounds.height),
413 });
414 };
415 const fallbackWindowBounds = boundsPersistenceEnabled ? null : readPersistableBounds();
416 const fallbackWindowMaximized = persistedSettings.mainWindowMaximized;
417 const persistCurrentBounds = (): Fiber.Fiber<void, never> | undefined => {
418 if (!boundsPersistenceEnabled) {
419 return pendingBoundsPersistFiber;
420 }
421 const bounds = readPersistableBounds();
422 if (bounds === null) {
423 return pendingBoundsPersistFiber;
424 }
425 pendingBoundsPersistFiber = runFork(
426 desktopSettings.setMainWindowBounds(bounds, window.isMaximized()).pipe(
427 Effect.asVoid,
428 Effect.catch((error) =>
429 logWindowWarning("failed to persist main window bounds", {
430 message: error.message,
431 }),
432 ),
433 ),
434 );
435 return pendingBoundsPersistFiber;
436 };
437 const scheduleBoundsPersist = () => {
438 if (!boundsPersistenceEnabled) {
439 const currentBounds = readPersistableBounds();
440 if (
441 currentBounds === null ||
442 (fallbackWindowBounds !== null &&
443 windowBoundsEqual(currentBounds, fallbackWindowBounds) &&
444 window.isMaximized() === fallbackWindowMaximized)
445 ) {
446 return;
447 }
448 }
449 boundsPersistenceEnabled = true;
450 if (boundsPersistFiber !== undefined) {
451 const fiber = boundsPersistFiber;
452 boundsPersistFiber = undefined;
453 runFork(Fiber.interrupt(fiber));
454 }
455 boundsPersistFiber = runFork(
456 Effect.sleep(MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS).pipe(
457 Effect.andThen(
458 Effect.sync(() => {
459 boundsPersistFiber = undefined;
460 void persistCurrentBounds();
461 }),
462 ),
463 ),
464 );
465 };
466 const clearBoundsPersist = () => {
467 if (boundsPersistFiber === undefined) {
468 return;
469 }
470 const fiber = boundsPersistFiber;
471 boundsPersistFiber = undefined;
472 runFork(Fiber.interrupt(fiber));
473 };
474 const flushBoundsPersist = Effect.sync(() => {
475 clearBoundsPersist();
476 return persistCurrentBounds();
477 }).pipe(
478 Effect.flatMap((fiber) =>
479 fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid),
480 ),
481 );
482 flushMainWindowBounds = flushBoundsPersist;
483​
484 yield* previewManager.setMainWindow(window);
485 window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
486 if (
487 typeof params.partition !== "string" ||
488 !previewManager.isBrowserPartition(params.partition)
489 ) {
490 event.preventDefault();
491 return;
492 }
493 webPreferences.sandbox = true;
494 webPreferences.nodeIntegration = false;
495 webPreferences.nodeIntegrationInSubFrames = false;
496 webPreferences.contextIsolation = false;
497 webPreferences.disableHtmlFullscreenWindowResize = true;
498 if (previewPasskeys.bridgeEnabled) {
499 webPreferences.additionalArguments = [
500 ...(webPreferences.additionalArguments ?? []),
501 PASSKEY_BRIDGE_ARGUMENT,
502 ];
503 }
504 });
505​
506 const contextMenuContents = new WeakSet<Electron.WebContents>();
507 const installContextMenu = (
508 ownerWindow: Electron.BrowserWindow,
509 contents: Electron.WebContents,
510 ): void => {
511 if (contextMenuContents.has(contents)) return;
512 contextMenuContents.add(contents);
513 contents.on("context-menu", (event, params) => {
514 event.preventDefault();
515 if (contents.isDestroyed() || ownerWindow.isDestroyed()) return;
516 // Native editing roles act on the focused contents, which may still be
517 // the host renderer when the user right-clicks inside a browser guest.
518 contents.focus();
519​
520 const menuTemplate: Electron.MenuItemConstructorOptions[] = [];
521​
522 if (params.misspelledWord) {
523 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
524 menuTemplate.push({
525 label: suggestion,
526 click: () => {
527 if (!contents.isDestroyed()) contents.replaceMisspelling(suggestion);
528 },
529 });
530 }
531 if (params.dictionarySuggestions.length === 0) {
532 menuTemplate.push({ label: "No suggestions", enabled: false });
533 }
534 menuTemplate.push({ type: "separator" });
535 }
536​
537 if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) {
538 menuTemplate.push(
539 {
540 label: "Copy Link",
541 click: () => {
542 void runPromise(electronShell.copyText(params.linkURL));
543 },
544 },
545 { type: "separator" },
546 );
547 }
548​
549 if (params.mediaType === "image") {
550 menuTemplate.push({
551 label: "Copy Image",
552 click: () => {
553 void runPromise(
554 Effect.tryPromise(() => copyContextMenuImage(contents, params)).pipe(
555 Effect.catch(() => logWindowWarning("failed to copy context-menu image")),
556 ),
557 );
558 },
559 });
560 menuTemplate.push({ type: "separator" });
561 }
562​
563 menuTemplate.push(
564 { role: "cut", enabled: params.editFlags.canCut },
565 { role: "copy", enabled: params.editFlags.canCopy },
566 { role: "paste", enabled: params.editFlags.canPaste },
567 { role: "selectAll", enabled: params.editFlags.canSelectAll },
568 );
569​
570 void runPromise(
571 electronMenu.popupTemplate({
572 window: ownerWindow,
573 template: menuTemplate,
574 ...(params.frame ? { frame: params.frame } : {}),
575 }),
576 );
577 });
578 contents.on("did-create-window", (popup) => {
579 installContextMenu(popup, popup.webContents);
580 });
581 };
582 installContextMenu(window, window.webContents);
583 window.webContents.on("did-attach-webview", (_event, contents) => {
584 installContextMenu(window, contents);
585 void runPromise(previewManager.prepareWebview(contents));
586 });
587​
588 window.webContents.setWindowOpenHandler(({ url }) => {
589 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
590 void runPromise(electronShell.openExternal(url));
591 }
592 return { action: "deny" };
593 });
594 window.webContents.on("will-navigate", (event, url) => {
595 if (
596 isSameOriginRendererNavigation({
597 applicationUrl,
598 navigationUrl: url,
599 })
600 ) {
601 return;
602 }
603​
604 event.preventDefault();
605 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
606 void runPromise(electronShell.openExternal(url));
607 }
608 });
609​
610 // Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
611 // close-terminal shortcut can outlive the terminal that handled its first
612 // press, so reject repeats before they reach the native window accelerator.
613 const quitShortcutHandler = makeQuitShortcutHandler({
614 platform: environment.platform,
615 getMode: () =>
616 runPromise(
617 Effect.map(
618 clientSettings.get,
619 Option.match({
620 onNone: () => DEFAULT_CLIENT_SETTINGS.confirmQuit,
621 onSome: (settings) => settings.confirmQuit,
622 }),
623 ),
624 ),
625 notify: (hint) => {
626 if (!window.isDestroyed()) {
627 window.webContents.send(QUIT_SHORTCUT_CHANNEL, hint);
628 }
629 },
630 // Keep the transparent window focused until the physical shortcut is
631 // released so its remaining repeats cannot reach the next app.
632 concealWindow: () => concealPendingQuitWindow(window),
633 quit: () => {
634 void runPromise(electronApp.quit);
635 },
636 });
637 window.webContents.on("before-input-event", (event, input) => {
638 quitShortcutHandler(event, input);
639 if (input.type !== "keyDown" || !input.isAutoRepeat) return;
640 const modifier = environment.platform === "darwin" ? input.meta : input.control;
641 if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
642 event.preventDefault();
643 }
644 });
645 window.webContents.on("input-event", (_event, input) => {
646 if (input.type === "gestureScrollEnd") window.webContents.send(TRACKPAD_SCROLL_END_CHANNEL);
647 });
648​
649 window.on("page-title-updated", (event) => {
650 event.preventDefault();
651 window.setTitle(environment.displayName);
652 });
653 window.on("resize", scheduleBoundsPersist);
654 window.on("move", scheduleBoundsPersist);
655 window.on("maximize", scheduleBoundsPersist);
656 window.on("unmaximize", scheduleBoundsPersist);
657 window.on("close", () => {
658 runFork(flushBoundsPersist);
659 });
660​
661 if (environment.platform === "darwin") {
662 window.on("enter-full-screen", () => {
663 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
664 });
665 window.on("leave-full-screen", () => {
666 syncMacosWindowButtons(window);
667 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
668 });
669 }
670​
671 let developmentLoadRetryIndex = 0;
672 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
673 let rendererRecoveryTimestamps: number[] = [];
674 const clearDevelopmentLoadRetry = () => {
675 if (developmentLoadRetryFiber === undefined) {
676 return;
677 }
678 const retryFiber = developmentLoadRetryFiber;
679 developmentLoadRetryFiber = undefined;
680 runFork(Fiber.interrupt(retryFiber));
681 };
682 const loadApplication = () => {
683 if (window.isDestroyed()) {
684 return;
685 }
686 void window.loadURL(applicationUrl).catch(() => undefined);
687 };
688 const scheduleDevelopmentLoadRetry = () => {
689 if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
690 return undefined;
691 }
692​
693 const retryIndex = Math.min(
694 developmentLoadRetryIndex,
695 DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
696 );
697 const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
698 developmentLoadRetryIndex += 1;
699 developmentLoadRetryFiber = runFork(
700 Effect.sleep(retryInMs).pipe(
701 Effect.andThen(
702 Effect.sync(() => {
703 developmentLoadRetryFiber = undefined;
704 if (!window.isDestroyed()) {
705 loadApplication();
706 }
707 }),
708 ),
709 ),
710 );
711 return retryInMs;
712 };
713​
714 window.webContents.on("did-finish-load", () => {
715 if (
716 environment.isDevelopment &&
717 !isSameOriginRendererNavigation({
718 applicationUrl,
719 navigationUrl: window.webContents.getURL(),
720 })
721 ) {
722 return;
723 }
724 clearDevelopmentLoadRetry();
725 developmentLoadRetryIndex = 0;
726 window.setTitle(environment.displayName);
727 if (environment.platform === "darwin") syncMacosWindowButtons(window);
728 });
729 window.webContents.on(
730 "did-fail-load",
731 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
732 if (!isMainFrame) {
733 return;
734 }
735 const retryInMs =
736 environment.isDevelopment &&
737 isRetryableDevelopmentRendererLoadFailure({
738 applicationUrl,
739 errorCode,
740 isMainFrame,
741 validatedUrl: validatedURL,
742 })
743 ? scheduleDevelopmentLoadRetry()
744 : undefined;
745 void runPromise(
746 logWindowWarning("main window failed to load", {
747 errorCode,
748 errorDescription,
749 url: validatedURL,
750 ...(retryInMs === undefined ? {} : { retryInMs }),
751 }),
752 );
753 },
754 );
755 window.webContents.on("render-process-gone", (_event, details) => {
756 const recoverable =
757 details.reason === "crashed" ||
758 details.reason === "oom" ||
759 details.reason === "abnormal-exit";
760 // Recovery attempts are bounded so a renderer that dies immediately on
761 // boot cannot reload-loop forever.
762 runFork(
763 Effect.gen(function* () {
764 const now = yield* Clock.currentTimeMillis;
765 rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
766 (timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
767 );
768 const shouldRecover =
769 recoverable &&
770 !window.isDestroyed() &&
771 rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
772 yield* logWindowWarning("main window render process gone", {
773 reason: details.reason,
774 exitCode: details.exitCode,
775 recovering: shouldRecover,
776 });
777 if (!shouldRecover) {
778 return;
779 }
780 rendererRecoveryTimestamps.push(now);
781 yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
782 if (!window.isDestroyed()) {
783 loadApplication();
784 }
785 }),
786 );
787 });
788​
789 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
790 if (environment.platform === "linux") {
791 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
792 }
793 bindFirstRevealTrigger(revealSubscribers, () => {
794 if (!window.isDestroyed()) {
795 window.webContents.setBackgroundThrottling(true);
796 }
797 if (persistedSettings.mainWindowMaximized) {
798 window.maximize();
799 }
800 void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
801 });
802​
803 loadApplication();
804 if (environment.isDevelopment) {
805 window.webContents.openDevTools({ mode: "detach" });
806 }
807​
808 window.on("closed", () => {
809 clearDevelopmentLoadRetry();
810 clearBoundsPersist();
811 void runPromise(electronWindow.clearMain(Option.some(window)));
812 });
813​
814 return window;
815 });
816​
817 const createMain = Effect.gen(function* () {
818 const window = yield* createWindow();
819 yield* electronWindow.setMain(window);
820 yield* logWindowInfo("main window created");
821 return window;
822 }).pipe(Effect.withSpan("desktop.window.createMain"));
823​
824 const ensureMain = Effect.gen(function* () {
825 const existingWindow = yield* currentMainWindow;
826 if (Option.isSome(existingWindow)) {
827 return existingWindow.value;
828 }
829 return yield* createMain;
830 }).pipe(Effect.withSpan("desktop.window.ensureMain"));
831​
832 const revealOrCreateMain = Effect.gen(function* () {
833 const window = yield* ensureMain;
834 yield* electronWindow.reveal(window);
835 return window;
836 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
837​
838 const waitingForBackend = Effect.gen(function* () {
839 if (yield* Ref.get(backendReadyRef)) return false;
840 return (yield* desktopSettings.get).localEnvironmentEnabled;
841 });
842​
843 const createMainIfBackendReady = Effect.gen(function* () {
844 if (yield* waitingForBackend) return;
845 const existingWindow = yield* currentMainWindow;
846 if (Option.isSome(existingWindow)) return;
847 yield* createMain;
848 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
849​
850 const showConnectingSplash = Effect.gen(function* () {
851 const existingSplash = yield* Ref.get(splashWindowRef);
852 if (Option.isSome(existingSplash)) return;
853 const existingWindow = yield* electronWindow.currentMainOrFirst;
854 if (Option.isSome(existingWindow)) return;
855​
856 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
857 const splash = yield* electronWindow.create({
858 width: 360,
859 height: 220,
860 resizable: false,
861 minimizable: false,
862 maximizable: false,
863 fullscreenable: false,
864 frame: false,
865 center: true,
866 show: false,
867 skipTaskbar: false,
868 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
869 title: environment.displayName,
870 webPreferences: {
871 contextIsolation: true,
872 nodeIntegration: false,
873 sandbox: true,
874 },
875 });
876 yield* rendererHistory.register(splash.webContents, { surface: "splash" });
877 yield* Ref.set(splashWindowRef, Option.some(splash));
878 splash.once("closed", () => {
879 void runPromise(Ref.set(splashWindowRef, Option.none()));
880 });
881 splash.once("ready-to-show", () => {
882 if (!splash.isDestroyed()) {
883 splash.show();
884 }
885 });
886 void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
887 yield* logWindowInfo("connecting splash shown");
888 }).pipe(
889 Effect.catch((error) =>
890 logWindowWarning("failed to show connecting splash", { message: error.message }),
891 ),
892 Effect.withSpan("desktop.window.showConnectingSplash"),
893 );
894​
895 const dispatchRendererEvent = Effect.fn("desktop.window.dispatchRendererEvent")(function* (
896 channel: string,
897 payload: unknown,
898 { reveal = true }: { readonly reveal?: boolean } = {},
899 ) {
900 const existingWindow = yield* reveal ? focusedMainWindow : electronWindow.main;
901 if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) return;
902 const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
903 if (targetWindow.isDestroyed()) return;
904 const send = Effect.sync(() => {
905 if (!targetWindow.isDestroyed()) targetWindow.webContents.send(channel, payload);
906 });
907 // The renderer must learn about the event even when another process refuses to
908 // yield the foreground, so send first and treat the reveal as best effort.
909 const dispatch = reveal
910 ? send.pipe(Effect.andThen(electronWindow.reveal(targetWindow).pipe(Effect.ignoreCause)))
911 : send;
912 if (targetWindow.webContents.isLoadingMainFrame()) {
913 targetWindow.webContents.once("did-finish-load", () => void runPromise(dispatch));
914 return;
915 }
916 yield* dispatch;
917 });
918​
919 return DesktopWindow.of({
920 createMain,
921 ensureMain,
922 revealOrCreateMain,
923 prepareCaptureReveal: Effect.gen(function* () {
924 const existingWindow = yield* currentMainWindow;
925 if (Option.isSome(existingWindow)) {
926 yield* electronWindow.prepareReveal(existingWindow.value);
927 }
928 }),
929 activate: Effect.gen(function* () {
930 const existingWindow = yield* currentMainWindow;
931 if (Option.isSome(existingWindow)) {
932 yield* electronWindow.reveal(existingWindow.value);
933 return;
934 }
935 const backendReady = yield* Ref.get(backendReadyRef);
936 if (!backendReady) {
937 const splash = yield* Ref.get(splashWindowRef);
938 if (Option.isSome(splash)) {
939 yield* electronWindow.reveal(splash.value);
940 return;
941 }
942 }
943 yield* createMainIfBackendReady;
944 }).pipe(Effect.withSpan("desktop.window.activate")),
945 createMainIfBackendReady,
946 showConnectingSplash,
947 handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
948 yield* Ref.set(backendReadyRef, true);
949 yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
950 yield* createMainIfBackendReady;
951 }),
952 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
953 Effect.withSpan("desktop.window.handleBackendNotReady"),
954 ),
955 flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
956 Effect.withSpan("desktop.window.flushMainWindowBounds"),
957 ),
958 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action, options) {
959 yield* Effect.annotateCurrentSpan({ action });
960 yield* dispatchRendererEvent(MENU_ACTION_CHANNEL, action, options);
961 }),
962 dispatchSnapShotEvent: Effect.fn("desktop.window.dispatchSnapShotEvent")(function* (event) {
963 yield* Effect.annotateCurrentSpan({
964 event: event.type,
965 captureId: "id" in event ? (event.id ?? null) : null,
966 });
967 yield* dispatchRendererEvent(SNAP_SHOT_EVENT_CHANNEL, event, {
968 reveal: event.type === "started",
969 });
970 }),
971 zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
972 yield* Effect.annotateCurrentSpan({ direction });
973 const window = yield* focusedMainWindow;
974 if (Option.isNone(window) || window.value.isDestroyed()) {
975 return;
976 }
977 const webContents = window.value.webContents;
978 webContents.setZoomLevel(
979 direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
980 );
981 if (environment.platform === "darwin") syncMacosWindowButtons(window.value);
982 // Chromium pushes the new level down to embedded guests, which would zoom
983 // the previewed page along with the app UI. The preview browser keeps its
984 // own zoom, so put each guest back where the preview left it.
985 yield* previewManager.reapplyZoom();
986 }),
987 runMainContentsCommand: Effect.fn("desktop.window.runMainContentsCommand")(function* (command) {
988 yield* Effect.annotateCurrentSpan({ command });
989 // The registered main window, never the focused one: with an OAuth popup
990 // focused, Reload would otherwise reload the popup mid sign-in.
991 const window = yield* electronWindow.main;
992 if (Option.isNone(window) || window.value.isDestroyed()) return;
993 const webContents = window.value.webContents;
994 if (command === "reload") webContents.reload();
995 else if (command === "forceReload") webContents.reloadIgnoringCache();
996 else webContents.toggleDevTools();
997 }),
998 syncAppearance: Effect.gen(function* () {
999 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
1000 yield* electronWindow.syncAllAppearance((window) =>
1001 syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
1002 );
1003 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
1004 });
1005});
1006​
1007export const layer = Layer.effect(DesktopWindow, make);