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

DesktopWindow.ts

1,023 lines38.6 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 zoomWindow = Effect.fn("desktop.window.zoomWindow")(function* (
333 window: Electron.BrowserWindow,
334 direction: MainWindowZoomDirection,
335 ) {
336 const webContents = window.webContents;
337 webContents.setZoomLevel(
338 direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
339 );
340 if (environment.platform === "darwin") syncMacosWindowButtons(window);
341 // Chromium pushes the new level down to embedded guests, which would zoom
342 // the previewed page along with the app UI. The preview browser keeps its
343 // own zoom, so put each guest back where the preview left it.
344 yield* previewManager.reapplyZoom();
345 });
346​
347 const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
348 Electron.BrowserWindow,
349 DesktopWindowError
350 > {
351 yield* previewManager.getBrowserSession();
352 const applicationUrl = getDesktopUrl(environment.isDevelopment);
353 const iconPaths = yield* assets.iconPaths;
354 const iconOption = getIconOption(iconPaths, environment.platform);
355 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
356 const persistedSettings = yield* desktopSettings.get;
357 const persistedBounds = persistedSettings.mainWindowBounds;
358 const displayBoundsResult = yield* Effect.sync(() => {
359 try {
360 return {
361 _tag: "Success" as const,
362 bounds: Electron.screen.getAllDisplays().map((display) => display.bounds),
363 };
364 } catch (cause) {
365 return { _tag: "Failure" as const, cause };
366 }
367 });
368 const displayBounds =
369 displayBoundsResult._tag === "Success"
370 ? displayBoundsResult.bounds
371 : yield* logWindowWarning("failed to read connected displays; using defaults", {
372 cause: displayBoundsResult.cause,
373 }).pipe(Effect.as<readonly Electron.Rectangle[]>([]));
374 const initialBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds);
375 const restoredPersistedBounds = persistedBounds !== null && initialBounds === persistedBounds;
376 if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) {
377 yield* logWindowWarning("saved main window bounds could not be restored; using defaults");
378 }
379 const window = yield* electronWindow.create({
380 ...initialBounds,
381 minWidth: 840,
382 minHeight: 620,
383 show: false,
384 autoHideMenuBar: true,
385 ...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
386 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
387 ...iconOption,
388 title: environment.displayName,
389 ...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
390 webPreferences: {
391 preload: environment.preloadPath,
392 // Chromium throttles hidden renderers: timers coalesce and rAF stops,
393 // which stalls first paint. Boot unthrottled; the first-reveal trigger
394 // re-enables throttling so a hidden or minimized window goes back to
395 // being cheap after it has been shown once.
396 backgroundThrottling: false,
397 contextIsolation: true,
398 nodeIntegration: false,
399 sandbox: true,
400 webviewTag: true,
401 // A preview guest's fullscreen request is mirrored onto this embedder,
402 // which would otherwise put the whole window into OS fullscreen. With
403 // both sides opted out the page fills its webview and the window stays.
404 disableHtmlFullscreenWindowResize: true,
405 },
406 });
407​
408 yield* rendererHistory.register(window.webContents, { surface: "main" });
409 if (environment.platform === "darwin") {
410 window.setAutoHideCursor(false);
411 }
412 let boundsPersistFiber: Fiber.Fiber<void, never> | undefined;
413 let pendingBoundsPersistFiber: Fiber.Fiber<void, never> | undefined;
414 let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds;
415 const readPersistableBounds = (): DesktopAppSettings.DesktopWindowBounds | null => {
416 if (window.isDestroyed()) {
417 return null;
418 }
419 const bounds =
420 window.isFullScreen() || window.isMaximized() || window.isMinimized()
421 ? window.getNormalBounds()
422 : window.getBounds();
423 return DesktopAppSettings.normalizeMainWindowBounds({
424 x: Math.round(bounds.x),
425 y: Math.round(bounds.y),
426 width: Math.round(bounds.width),
427 height: Math.round(bounds.height),
428 });
429 };
430 const fallbackWindowBounds = boundsPersistenceEnabled ? null : readPersistableBounds();
431 const fallbackWindowMaximized = persistedSettings.mainWindowMaximized;
432 const persistCurrentBounds = (): Fiber.Fiber<void, never> | undefined => {
433 if (!boundsPersistenceEnabled) {
434 return pendingBoundsPersistFiber;
435 }
436 const bounds = readPersistableBounds();
437 if (bounds === null) {
438 return pendingBoundsPersistFiber;
439 }
440 pendingBoundsPersistFiber = runFork(
441 desktopSettings.setMainWindowBounds(bounds, window.isMaximized()).pipe(
442 Effect.asVoid,
443 Effect.catch((error) =>
444 logWindowWarning("failed to persist main window bounds", {
445 message: error.message,
446 }),
447 ),
448 ),
449 );
450 return pendingBoundsPersistFiber;
451 };
452 const scheduleBoundsPersist = () => {
453 if (!boundsPersistenceEnabled) {
454 const currentBounds = readPersistableBounds();
455 if (
456 currentBounds === null ||
457 (fallbackWindowBounds !== null &&
458 windowBoundsEqual(currentBounds, fallbackWindowBounds) &&
459 window.isMaximized() === fallbackWindowMaximized)
460 ) {
461 return;
462 }
463 }
464 boundsPersistenceEnabled = true;
465 if (boundsPersistFiber !== undefined) {
466 const fiber = boundsPersistFiber;
467 boundsPersistFiber = undefined;
468 runFork(Fiber.interrupt(fiber));
469 }
470 boundsPersistFiber = runFork(
471 Effect.sleep(MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS).pipe(
472 Effect.andThen(
473 Effect.sync(() => {
474 boundsPersistFiber = undefined;
475 void persistCurrentBounds();
476 }),
477 ),
478 ),
479 );
480 };
481 const clearBoundsPersist = () => {
482 if (boundsPersistFiber === undefined) {
483 return;
484 }
485 const fiber = boundsPersistFiber;
486 boundsPersistFiber = undefined;
487 runFork(Fiber.interrupt(fiber));
488 };
489 const flushBoundsPersist = Effect.sync(() => {
490 clearBoundsPersist();
491 return persistCurrentBounds();
492 }).pipe(
493 Effect.flatMap((fiber) =>
494 fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid),
495 ),
496 );
497 flushMainWindowBounds = flushBoundsPersist;
498​
499 yield* previewManager.setMainWindow(window);
500 window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
501 if (
502 typeof params.partition !== "string" ||
503 !previewManager.isBrowserPartition(params.partition)
504 ) {
505 event.preventDefault();
506 return;
507 }
508 webPreferences.sandbox = true;
509 webPreferences.nodeIntegration = false;
510 webPreferences.nodeIntegrationInSubFrames = false;
511 webPreferences.contextIsolation = false;
512 webPreferences.disableHtmlFullscreenWindowResize = true;
513 if (previewPasskeys.bridgeEnabled) {
514 webPreferences.additionalArguments = [
515 ...(webPreferences.additionalArguments ?? []),
516 PASSKEY_BRIDGE_ARGUMENT,
517 ];
518 }
519 });
520​
521 const contextMenuContents = new WeakSet<Electron.WebContents>();
522 const installContextMenu = (
523 ownerWindow: Electron.BrowserWindow,
524 contents: Electron.WebContents,
525 ): void => {
526 if (contextMenuContents.has(contents)) return;
527 contextMenuContents.add(contents);
528 contents.on("context-menu", (event, params) => {
529 event.preventDefault();
530 if (contents.isDestroyed() || ownerWindow.isDestroyed()) return;
531 // Native editing roles act on the focused contents, which may still be
532 // the host renderer when the user right-clicks inside a browser guest.
533 contents.focus();
534​
535 const menuTemplate: Electron.MenuItemConstructorOptions[] = [];
536​
537 if (params.misspelledWord) {
538 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
539 menuTemplate.push({
540 label: suggestion,
541 click: () => {
542 if (!contents.isDestroyed()) contents.replaceMisspelling(suggestion);
543 },
544 });
545 }
546 if (params.dictionarySuggestions.length === 0) {
547 menuTemplate.push({ label: "No suggestions", enabled: false });
548 }
549 menuTemplate.push({ type: "separator" });
550 }
551​
552 if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) {
553 menuTemplate.push(
554 {
555 label: "Copy Link",
556 click: () => {
557 void runPromise(electronShell.copyText(params.linkURL));
558 },
559 },
560 { type: "separator" },
561 );
562 }
563​
564 if (params.mediaType === "image") {
565 menuTemplate.push({
566 label: "Copy Image",
567 click: () => {
568 void runPromise(
569 Effect.tryPromise(() => copyContextMenuImage(contents, params)).pipe(
570 Effect.catch(() => logWindowWarning("failed to copy context-menu image")),
571 ),
572 );
573 },
574 });
575 menuTemplate.push({ type: "separator" });
576 }
577​
578 menuTemplate.push(
579 { role: "cut", enabled: params.editFlags.canCut },
580 { role: "copy", enabled: params.editFlags.canCopy },
581 { role: "paste", enabled: params.editFlags.canPaste },
582 { role: "selectAll", enabled: params.editFlags.canSelectAll },
583 );
584​
585 void runPromise(
586 electronMenu.popupTemplate({
587 window: ownerWindow,
588 template: menuTemplate,
589 ...(params.frame ? { frame: params.frame } : {}),
590 }),
591 );
592 });
593 contents.on("did-create-window", (popup) => {
594 installContextMenu(popup, popup.webContents);
595 });
596 };
597 installContextMenu(window, window.webContents);
598 window.webContents.on("did-attach-webview", (_event, contents) => {
599 installContextMenu(window, contents);
600 void runPromise(previewManager.prepareWebview(contents));
601 });
602​
603 window.webContents.setWindowOpenHandler(({ url }) => {
604 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
605 void runPromise(electronShell.openExternal(url));
606 }
607 return { action: "deny" };
608 });
609 window.webContents.on("will-navigate", (event, url) => {
610 if (
611 isSameOriginRendererNavigation({
612 applicationUrl,
613 navigationUrl: url,
614 })
615 ) {
616 return;
617 }
618​
619 event.preventDefault();
620 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
621 void runPromise(electronShell.openExternal(url));
622 }
623 });
624​
625 // Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
626 // close-terminal shortcut can outlive the terminal that handled its first
627 // press, so reject repeats before they reach the native window accelerator.
628 const quitShortcutHandler = makeQuitShortcutHandler({
629 platform: environment.platform,
630 getMode: () =>
631 runPromise(
632 Effect.map(
633 clientSettings.get,
634 Option.match({
635 onNone: () => DEFAULT_CLIENT_SETTINGS.confirmQuit,
636 onSome: (settings) => settings.confirmQuit,
637 }),
638 ),
639 ),
640 notify: (hint) => {
641 if (!window.isDestroyed()) {
642 window.webContents.send(QUIT_SHORTCUT_CHANNEL, hint);
643 }
644 },
645 // Keep the transparent window focused until the physical shortcut is
646 // released so its remaining repeats cannot reach the next app.
647 concealWindow: () => concealPendingQuitWindow(window),
648 quit: () => {
649 void runPromise(electronApp.quit);
650 },
651 });
652 window.webContents.on("before-input-event", (event, input) => {
653 quitShortcutHandler(event, input);
654 if (input.type !== "keyDown" || !input.isAutoRepeat) return;
655 const modifier = environment.platform === "darwin" ? input.meta : input.control;
656 if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
657 event.preventDefault();
658 }
659 });
660 window.webContents.on("input-event", (_event, input) => {
661 if (input.type === "gestureScrollEnd") window.webContents.send(TRACKPAD_SCROLL_END_CHANNEL);
662 });
663 // Ctrl+wheel never reaches the menu accelerators: Chromium reports it here
664 // and leaves applying the zoom to the app. A preview guest under the
665 // pointer emits this on its own webContents and keeps its own zoom.
666 window.webContents.on("zoom-changed", (_event, direction) => {
667 if (window.isDestroyed()) return;
668 runFork(zoomWindow(window, direction));
669 });
670​
671 window.on("page-title-updated", (event) => {
672 event.preventDefault();
673 window.setTitle(environment.displayName);
674 });
675 window.on("resize", scheduleBoundsPersist);
676 window.on("move", scheduleBoundsPersist);
677 window.on("maximize", scheduleBoundsPersist);
678 window.on("unmaximize", scheduleBoundsPersist);
679 window.on("close", () => {
680 runFork(flushBoundsPersist);
681 });
682​
683 if (environment.platform === "darwin") {
684 window.on("enter-full-screen", () => {
685 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
686 });
687 window.on("leave-full-screen", () => {
688 syncMacosWindowButtons(window);
689 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
690 });
691 }
692​
693 let developmentLoadRetryIndex = 0;
694 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
695 let rendererRecoveryTimestamps: number[] = [];
696 const clearDevelopmentLoadRetry = () => {
697 if (developmentLoadRetryFiber === undefined) {
698 return;
699 }
700 const retryFiber = developmentLoadRetryFiber;
701 developmentLoadRetryFiber = undefined;
702 runFork(Fiber.interrupt(retryFiber));
703 };
704 const loadApplication = () => {
705 if (window.isDestroyed()) {
706 return;
707 }
708 void window.loadURL(applicationUrl).catch(() => undefined);
709 };
710 const scheduleDevelopmentLoadRetry = () => {
711 if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
712 return undefined;
713 }
714​
715 const retryIndex = Math.min(
716 developmentLoadRetryIndex,
717 DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
718 );
719 const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
720 developmentLoadRetryIndex += 1;
721 developmentLoadRetryFiber = runFork(
722 Effect.sleep(retryInMs).pipe(
723 Effect.andThen(
724 Effect.sync(() => {
725 developmentLoadRetryFiber = undefined;
726 if (!window.isDestroyed()) {
727 loadApplication();
728 }
729 }),
730 ),
731 ),
732 );
733 return retryInMs;
734 };
735​
736 window.webContents.on("did-finish-load", () => {
737 if (
738 environment.isDevelopment &&
739 !isSameOriginRendererNavigation({
740 applicationUrl,
741 navigationUrl: window.webContents.getURL(),
742 })
743 ) {
744 return;
745 }
746 clearDevelopmentLoadRetry();
747 developmentLoadRetryIndex = 0;
748 window.setTitle(environment.displayName);
749 if (environment.platform === "darwin") syncMacosWindowButtons(window);
750 });
751 window.webContents.on(
752 "did-fail-load",
753 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
754 if (!isMainFrame) {
755 return;
756 }
757 const retryInMs =
758 environment.isDevelopment &&
759 isRetryableDevelopmentRendererLoadFailure({
760 applicationUrl,
761 errorCode,
762 isMainFrame,
763 validatedUrl: validatedURL,
764 })
765 ? scheduleDevelopmentLoadRetry()
766 : undefined;
767 void runPromise(
768 logWindowWarning("main window failed to load", {
769 errorCode,
770 errorDescription,
771 url: validatedURL,
772 ...(retryInMs === undefined ? {} : { retryInMs }),
773 }),
774 );
775 },
776 );
777 window.webContents.on("render-process-gone", (_event, details) => {
778 const recoverable =
779 details.reason === "crashed" ||
780 details.reason === "oom" ||
781 details.reason === "killed" ||
782 details.reason === "abnormal-exit";
783 // Recovery attempts are bounded so a renderer that dies immediately on
784 // boot cannot reload-loop forever.
785​
786 runFork(
787 Effect.gen(function* () {
788 const now = yield* Clock.currentTimeMillis;
789 rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
790 (timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
791 );
792 const shouldRecover =
793 recoverable &&
794 !window.isDestroyed() &&
795 rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
796 yield* logWindowWarning("main window render process gone", {
797 reason: details.reason,
798 exitCode: details.exitCode,
799 recovering: shouldRecover,
800 });
801 if (!shouldRecover) {
802 return;
803 }
804 rendererRecoveryTimestamps.push(now);
805 yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
806 if (!window.isDestroyed()) {
807 loadApplication();
808 }
809 }),
810 );
811 });
812​
813 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
814 if (environment.platform === "linux") {
815 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
816 }
817 bindFirstRevealTrigger(revealSubscribers, () => {
818 if (!window.isDestroyed()) {
819 window.webContents.setBackgroundThrottling(true);
820 }
821 if (persistedSettings.mainWindowMaximized) {
822 window.maximize();
823 }
824 void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
825 });
826​
827 loadApplication();
828 if (environment.isDevelopment) {
829 window.webContents.openDevTools({ mode: "detach" });
830 }
831​
832 window.on("closed", () => {
833 clearDevelopmentLoadRetry();
834 clearBoundsPersist();
835 void runPromise(electronWindow.clearMain(Option.some(window)));
836 });
837​
838 return window;
839 });
840​
841 const createMain = Effect.gen(function* () {
842 const window = yield* createWindow();
843 yield* electronWindow.setMain(window);
844 yield* logWindowInfo("main window created");
845 return window;
846 }).pipe(Effect.withSpan("desktop.window.createMain"));
847​
848 const ensureMain = Effect.gen(function* () {
849 const existingWindow = yield* currentMainWindow;
850 if (Option.isSome(existingWindow)) {
851 return existingWindow.value;
852 }
853 return yield* createMain;
854 }).pipe(Effect.withSpan("desktop.window.ensureMain"));
855​
856 const revealOrCreateMain = Effect.gen(function* () {
857 const window = yield* ensureMain;
858 yield* electronWindow.reveal(window);
859 return window;
860 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
861​
862 const waitingForBackend = Effect.gen(function* () {
863 if (yield* Ref.get(backendReadyRef)) return false;
864 return (yield* desktopSettings.get).localEnvironmentEnabled;
865 });
866​
867 const createMainIfBackendReady = Effect.gen(function* () {
868 if (yield* waitingForBackend) return;
869 const existingWindow = yield* currentMainWindow;
870 if (Option.isSome(existingWindow)) return;
871 yield* createMain;
872 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
873​
874 const showConnectingSplash = Effect.gen(function* () {
875 const existingSplash = yield* Ref.get(splashWindowRef);
876 if (Option.isSome(existingSplash)) return;
877 const existingWindow = yield* electronWindow.currentMainOrFirst;
878 if (Option.isSome(existingWindow)) return;
879​
880 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
881 const splash = yield* electronWindow.create({
882 width: 360,
883 height: 220,
884 resizable: false,
885 minimizable: false,
886 maximizable: false,
887 fullscreenable: false,
888 frame: false,
889 center: true,
890 show: false,
891 skipTaskbar: false,
892 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
893 title: environment.displayName,
894 webPreferences: {
895 contextIsolation: true,
896 nodeIntegration: false,
897 sandbox: true,
898 },
899 });
900 yield* rendererHistory.register(splash.webContents, { surface: "splash" });
901 yield* Ref.set(splashWindowRef, Option.some(splash));
902 splash.once("closed", () => {
903 void runPromise(Ref.set(splashWindowRef, Option.none()));
904 });
905 splash.once("ready-to-show", () => {
906 if (!splash.isDestroyed()) {
907 splash.show();
908 }
909 });
910 void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
911 yield* logWindowInfo("connecting splash shown");
912 }).pipe(
913 Effect.catch((error) =>
914 logWindowWarning("failed to show connecting splash", { message: error.message }),
915 ),
916 Effect.withSpan("desktop.window.showConnectingSplash"),
917 );
918​
919 const dispatchRendererEvent = Effect.fn("desktop.window.dispatchRendererEvent")(function* (
920 channel: string,
921 payload: unknown,
922 { reveal = true }: { readonly reveal?: boolean } = {},
923 ) {
924 const existingWindow = yield* reveal ? focusedMainWindow : electronWindow.main;
925 if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) return;
926 const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
927 if (targetWindow.isDestroyed()) return;
928 const send = Effect.sync(() => {
929 if (!targetWindow.isDestroyed()) targetWindow.webContents.send(channel, payload);
930 });
931 // The renderer must learn about the event even when another process refuses to
932 // yield the foreground, so send first and treat the reveal as best effort.
933 const dispatch = reveal
934 ? send.pipe(Effect.andThen(electronWindow.reveal(targetWindow).pipe(Effect.ignoreCause)))
935 : send;
936 if (targetWindow.webContents.isLoadingMainFrame()) {
937 targetWindow.webContents.once("did-finish-load", () => void runPromise(dispatch));
938 return;
939 }
940 yield* dispatch;
941 });
942​
943 return DesktopWindow.of({
944 createMain,
945 ensureMain,
946 revealOrCreateMain,
947 prepareCaptureReveal: Effect.gen(function* () {
948 const existingWindow = yield* currentMainWindow;
949 if (Option.isSome(existingWindow)) {
950 yield* electronWindow.prepareReveal(existingWindow.value);
951 }
952 }),
953 activate: Effect.gen(function* () {
954 const existingWindow = yield* currentMainWindow;
955 if (Option.isSome(existingWindow)) {
956 yield* electronWindow.reveal(existingWindow.value);
957 return;
958 }
959 const backendReady = yield* Ref.get(backendReadyRef);
960 if (!backendReady) {
961 const splash = yield* Ref.get(splashWindowRef);
962 if (Option.isSome(splash)) {
963 yield* electronWindow.reveal(splash.value);
964 return;
965 }
966 }
967 yield* createMainIfBackendReady;
968 }).pipe(Effect.withSpan("desktop.window.activate")),
969 createMainIfBackendReady,
970 showConnectingSplash,
971 handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
972 yield* Ref.set(backendReadyRef, true);
973 yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
974 yield* createMainIfBackendReady;
975 }),
976 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
977 Effect.withSpan("desktop.window.handleBackendNotReady"),
978 ),
979 flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
980 Effect.withSpan("desktop.window.flushMainWindowBounds"),
981 ),
982 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action, options) {
983 yield* Effect.annotateCurrentSpan({ action });
984 yield* dispatchRendererEvent(MENU_ACTION_CHANNEL, action, options);
985 }),
986 dispatchSnapShotEvent: Effect.fn("desktop.window.dispatchSnapShotEvent")(function* (event) {
987 yield* Effect.annotateCurrentSpan({
988 event: event.type,
989 captureId: "id" in event ? (event.id ?? null) : null,
990 });
991 yield* dispatchRendererEvent(SNAP_SHOT_EVENT_CHANNEL, event, {
992 reveal: event.type === "started",
993 });
994 }),
995 zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
996 yield* Effect.annotateCurrentSpan({ direction });
997 const window = yield* focusedMainWindow;
998 if (Option.isNone(window) || window.value.isDestroyed()) {
999 return;
1001 yield* zoomWindow(window.value, direction);
1002 }),
1003 runMainContentsCommand: Effect.fn("desktop.window.runMainContentsCommand")(function* (command) {
1004 yield* Effect.annotateCurrentSpan({ command });
1005 // The registered main window, never the focused one: with an OAuth popup
1006 // focused, Reload would otherwise reload the popup mid sign-in.
1007 const window = yield* electronWindow.main;
1008 if (Option.isNone(window) || window.value.isDestroyed()) return;
1009 const webContents = window.value.webContents;
1010 if (command === "reload") webContents.reload();
1011 else if (command === "forceReload") webContents.reloadIgnoringCache();
1012 else webContents.toggleDevTools();
1013 }),
1014 syncAppearance: Effect.gen(function* () {
1015 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
1016 yield* electronWindow.syncAllAppearance((window) =>
1017 syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
1018 );
1019 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
1020 });
1021});
1022​
1023export const layer = Layer.effect(DesktopWindow, make);