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

DesktopWindow.ts

495 lines16.4 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Fiber from "effect/Fiber";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Ref from "effect/Ref";
7​
8import type * as Electron from "electron";
9​
10import * as DesktopAssets from "../app/DesktopAssets.ts";
11import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
12import { makeComponentLogger } from "../app/DesktopObservability.ts";
13import * as DesktopState from "../app/DesktopState.ts";
14import * as ElectronMenu from "../electron/ElectronMenu.ts";
15import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
16import * as ElectronShell from "../electron/ElectronShell.ts";
17import * as ElectronTheme from "../electron/ElectronTheme.ts";
18import * as ElectronWindow from "../electron/ElectronWindow.ts";
19import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
20import * as PreviewManager from "../preview/Manager.ts";
21​
22const TITLEBAR_HEIGHT = 40;
23const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
24const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
25const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
26const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
27const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
28 -2, // ERR_FAILED
29 -7, // ERR_TIMED_OUT
30 -9, // ERR_UNEXPECTED (custom protocol handler rejected)
31 -102, // ERR_CONNECTION_REFUSED
32 -105, // ERR_NAME_NOT_RESOLVED
33 -106, // ERR_INTERNET_DISCONNECTED
34 -118, // ERR_CONNECTION_TIMED_OUT
35]);
36​
37type WindowTitleBarOptions = Pick<
38 Electron.BrowserWindowConstructorOptions,
39 "titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
40>;
41​
42type DesktopWindowRuntimeServices =
43 | DesktopEnvironment.DesktopEnvironment
44 | DesktopAssets.DesktopAssets
45 | DesktopState.DesktopState
46 | ElectronMenu.ElectronMenu
47 | ElectronShell.ElectronShell
48 | ElectronTheme.ElectronTheme
49 | ElectronWindow.ElectronWindow
50 | PreviewManager.PreviewManager;
51​
52export type DesktopWindowError =
53 | ElectronWindow.ElectronWindowCreateError
54 | PreviewManager.PreviewManagerError;
55​
56export class DesktopWindow extends Context.Service<
57 DesktopWindow,
58 {
59 readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
60 readonly ensureMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
61 readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
62 readonly activate: Effect.Effect<void, DesktopWindowError>;
63 readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
64 readonly handleBackendReady: Effect.Effect<void, DesktopWindowError>;
65 readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
66 readonly syncAppearance: Effect.Effect<void>;
67 }
68>()("@t3tools/desktop/window/DesktopWindow") {}
69​
70const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
71 makeComponentLogger("desktop-window");
72​
73function getIconOption(
74 iconPaths: DesktopAssets.DesktopIconPaths,
75 platform: NodeJS.Platform,
76): { icon: string } | Record<string, never> {
77 if (platform === "darwin") return {}; // macOS uses .icns from app bundle
78 const ext = platform === "win32" ? "ico" : "png";
79 return Option.match(iconPaths[ext], {
80 onNone: () => ({}),
81 onSome: (icon) => ({ icon }),
82 });
84​
85function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
86 return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
88​
89export function isSameOriginRendererNavigation(input: {
90 readonly applicationUrl: string;
91 readonly navigationUrl: string;
92}): boolean {
93 try {
94 return new URL(input.applicationUrl).origin === new URL(input.navigationUrl).origin;
95 } catch {
96 return false;
97 }
99​
100export function isRetryableDevelopmentRendererLoadFailure(input: {
101 readonly applicationUrl: string;
102 readonly errorCode: number;
103 readonly isMainFrame: boolean;
104 readonly validatedUrl: string;
105}): boolean {
106 return (
107 input.isMainFrame &&
108 DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
109 isSameOriginRendererNavigation({
110 applicationUrl: input.applicationUrl,
111 navigationUrl: input.validatedUrl,
112 })
113 );
115​
116function getWindowTitleBarOptions(
117 shouldUseDarkColors: boolean,
118 platform: NodeJS.Platform,
119): WindowTitleBarOptions {
120 if (platform === "darwin") {
121 return {
122 titleBarStyle: "hiddenInset",
123 trafficLightPosition: { x: 16, y: 18 },
124 };
125 }
126​
127 return {
128 titleBarStyle: "hidden",
129 titleBarOverlay: {
130 color: TITLEBAR_COLOR,
131 height: TITLEBAR_HEIGHT,
132 symbolColor: shouldUseDarkColors ? TITLEBAR_DARK_SYMBOL_COLOR : TITLEBAR_LIGHT_SYMBOL_COLOR,
133 },
134 };
136​
137function syncWindowAppearance(
138 window: Electron.BrowserWindow,
139 shouldUseDarkColors: boolean,
140 platform: NodeJS.Platform,
141): Effect.Effect<void> {
142 return Effect.sync(() => {
143 if (window.isDestroyed()) {
144 return;
145 }
146​
147 window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
148 const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
149 if (typeof titleBarOverlay === "object") {
150 window.setTitleBarOverlay(titleBarOverlay);
151 }
152 });
154​
155type RevealSubscription = (listener: () => void) => void;
156​
157function bindFirstRevealTrigger(
158 subscribers: readonly RevealSubscription[],
159 reveal: () => void,
160): void {
161 let revealed = false;
162 const fire = () => {
163 if (revealed) return;
164 revealed = true;
165 reveal();
166 };
167 for (const subscribe of subscribers) {
168 subscribe(fire);
169 }
171​
172export const make = Effect.gen(function* () {
173 const environment = yield* DesktopEnvironment.DesktopEnvironment;
174 const assets = yield* DesktopAssets.DesktopAssets;
175 const electronMenu = yield* ElectronMenu.ElectronMenu;
176 const electronShell = yield* ElectronShell.ElectronShell;
177 const electronTheme = yield* ElectronTheme.ElectronTheme;
178 const electronWindow = yield* ElectronWindow.ElectronWindow;
179 const previewManager = yield* PreviewManager.PreviewManager;
180 const state = yield* DesktopState.DesktopState;
181 const context = yield* Effect.context<DesktopWindowRuntimeServices>();
182 const runFork = Effect.runForkWith(context);
183 const runPromise = Effect.runPromiseWith(context);
184​
185 const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
186 Electron.BrowserWindow,
187 DesktopWindowError
188 > {
189 yield* previewManager.getBrowserSession();
190 const applicationUrl = getDesktopUrl(environment.isDevelopment);
191 const iconPaths = yield* assets.iconPaths;
192 const iconOption = getIconOption(iconPaths, environment.platform);
193 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
194 const window = yield* electronWindow.create({
195 width: 1100,
196 height: 780,
197 minWidth: 840,
198 minHeight: 620,
199 show: false,
200 autoHideMenuBar: true,
201 ...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
202 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
203 ...iconOption,
204 title: environment.displayName,
205 ...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
206 webPreferences: {
207 preload: environment.preloadPath,
208 contextIsolation: true,
209 nodeIntegration: false,
210 sandbox: true,
211 webviewTag: true,
212 },
213 });
214​
215 if (environment.platform === "darwin") {
216 window.setAutoHideCursor(false);
217 }
218​
219 yield* previewManager.setMainWindow(window);
220 window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
221 if (
222 typeof params.partition !== "string" ||
223 !previewManager.isBrowserPartition(params.partition)
224 ) {
225 event.preventDefault();
226 return;
227 }
228 webPreferences.sandbox = true;
229 webPreferences.nodeIntegration = false;
230 webPreferences.nodeIntegrationInSubFrames = false;
231 webPreferences.contextIsolation = false;
232 });
233​
234 window.webContents.on("context-menu", (event, params) => {
235 event.preventDefault();
236​
237 const menuTemplate: Electron.MenuItemConstructorOptions[] = [];
238​
239 if (params.misspelledWord) {
240 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
241 menuTemplate.push({
242 label: suggestion,
243 click: () => window.webContents.replaceMisspelling(suggestion),
244 });
245 }
246 if (params.dictionarySuggestions.length === 0) {
247 menuTemplate.push({ label: "No suggestions", enabled: false });
248 }
249 menuTemplate.push({ type: "separator" });
250 }
251​
252 if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) {
253 menuTemplate.push(
254 {
255 label: "Copy Link",
256 click: () => {
257 void runPromise(electronShell.copyText(params.linkURL));
258 },
259 },
260 { type: "separator" },
261 );
262 }
263​
264 if (params.mediaType === "image") {
265 menuTemplate.push({
266 label: "Copy Image",
267 click: () => window.webContents.copyImageAt(params.x, params.y),
268 });
269 menuTemplate.push({ type: "separator" });
270 }
271​
272 menuTemplate.push(
273 { role: "cut", enabled: params.editFlags.canCut },
274 { role: "copy", enabled: params.editFlags.canCopy },
275 { role: "paste", enabled: params.editFlags.canPaste },
276 { role: "selectAll", enabled: params.editFlags.canSelectAll },
277 );
278​
279 void runPromise(electronMenu.popupTemplate({ window, template: menuTemplate }));
280 });
281​
282 window.webContents.setWindowOpenHandler(({ url }) => {
283 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
284 void runPromise(electronShell.openExternal(url));
285 }
286 return { action: "deny" };
287 });
288 window.webContents.on("will-navigate", (event, url) => {
289 if (
290 isSameOriginRendererNavigation({
291 applicationUrl,
292 navigationUrl: url,
293 })
294 ) {
295 return;
296 }
297​
298 event.preventDefault();
299 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
300 void runPromise(electronShell.openExternal(url));
301 }
302 });
303​
304 window.on("page-title-updated", (event) => {
305 event.preventDefault();
306 window.setTitle(environment.displayName);
307 });
308​
309 let developmentLoadRetryIndex = 0;
310 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
311 const clearDevelopmentLoadRetry = () => {
312 if (developmentLoadRetryFiber === undefined) {
313 return;
314 }
315 const retryFiber = developmentLoadRetryFiber;
316 developmentLoadRetryFiber = undefined;
317 runFork(Fiber.interrupt(retryFiber));
318 };
319 const loadApplication = () => {
320 if (window.isDestroyed()) {
321 return;
322 }
323 void window.loadURL(applicationUrl).catch(() => undefined);
324 };
325 const scheduleDevelopmentLoadRetry = () => {
326 if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
327 return undefined;
328 }
329​
330 const retryIndex = Math.min(
331 developmentLoadRetryIndex,
332 DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
333 );
334 const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
335 developmentLoadRetryIndex += 1;
336 developmentLoadRetryFiber = runFork(
337 Effect.sleep(retryInMs).pipe(
338 Effect.andThen(
339 Effect.sync(() => {
340 developmentLoadRetryFiber = undefined;
341 if (!window.isDestroyed()) {
342 loadApplication();
343 }
344 }),
345 ),
346 ),
347 );
348 return retryInMs;
349 };
350​
351 window.webContents.on("did-finish-load", () => {
352 if (
353 environment.isDevelopment &&
354 !isSameOriginRendererNavigation({
355 applicationUrl,
356 navigationUrl: window.webContents.getURL(),
357 })
358 ) {
359 return;
360 }
361 clearDevelopmentLoadRetry();
362 developmentLoadRetryIndex = 0;
363 window.setTitle(environment.displayName);
364 });
365 window.webContents.on(
366 "did-fail-load",
367 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
368 if (!isMainFrame) {
369 return;
370 }
371 const retryInMs =
372 environment.isDevelopment &&
373 isRetryableDevelopmentRendererLoadFailure({
374 applicationUrl,
375 errorCode,
376 isMainFrame,
377 validatedUrl: validatedURL,
378 })
379 ? scheduleDevelopmentLoadRetry()
380 : undefined;
381 void runPromise(
382 logWindowWarning("main window failed to load", {
383 errorCode,
384 errorDescription,
385 url: validatedURL,
386 ...(retryInMs === undefined ? {} : { retryInMs }),
387 }),
388 );
389 },
390 );
391 window.webContents.on("render-process-gone", (_event, details) => {
392 void runPromise(
393 logWindowWarning("main window render process gone", {
394 reason: details.reason,
395 exitCode: details.exitCode,
396 }),
397 );
398 });
399​
400 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
401 if (environment.platform === "linux") {
402 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
403 }
404 bindFirstRevealTrigger(revealSubscribers, () => {
405 void runPromise(electronWindow.reveal(window));
406 });
407​
408 loadApplication();
409 if (environment.isDevelopment) {
410 window.webContents.openDevTools({ mode: "detach" });
411 }
412​
413 window.on("closed", () => {
414 clearDevelopmentLoadRetry();
415 void runPromise(electronWindow.clearMain(Option.some(window)));
416 });
417​
418 return window;
419 });
420​
421 const createMain = Effect.gen(function* () {
422 const window = yield* createWindow();
423 yield* electronWindow.setMain(window);
424 yield* logWindowInfo("main window created");
425 return window;
426 }).pipe(Effect.withSpan("desktop.window.createMain"));
427​
428 const ensureMain = Effect.gen(function* () {
429 const existingWindow = yield* electronWindow.currentMainOrFirst;
430 if (Option.isSome(existingWindow)) {
431 return existingWindow.value;
432 }
433 return yield* createMain;
434 }).pipe(Effect.withSpan("desktop.window.ensureMain"));
435​
436 const revealOrCreateMain = Effect.gen(function* () {
437 const window = yield* ensureMain;
438 yield* electronWindow.reveal(window);
439 return window;
440 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
441​
442 const createMainIfBackendReady = Effect.gen(function* () {
443 const backendReady = yield* Ref.get(state.backendReady);
444 if (!backendReady) return;
445 const existingWindow = yield* electronWindow.currentMainOrFirst;
446 if (Option.isSome(existingWindow)) return;
447 yield* createMain;
448 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
449​
450 return DesktopWindow.of({
451 createMain,
452 ensureMain,
453 revealOrCreateMain,
454 activate: Effect.gen(function* () {
455 const existingWindow = yield* electronWindow.currentMainOrFirst;
456 if (Option.isSome(existingWindow)) {
457 yield* electronWindow.reveal(existingWindow.value);
458 } else {
459 yield* createMainIfBackendReady;
460 }
461 }).pipe(Effect.withSpan("desktop.window.activate")),
462 createMainIfBackendReady,
463 handleBackendReady: Effect.gen(function* () {
464 yield* Ref.set(state.backendReady, true);
465 yield* logWindowInfo("backend ready", { source: "http" });
466 yield* createMainIfBackendReady;
467 }).pipe(Effect.withSpan("desktop.window.handleBackendReady")),
468 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
469 yield* Effect.annotateCurrentSpan({ action });
470 const existingWindow = yield* electronWindow.focusedMainOrFirst;
471 const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* createMain;
472​
473 const send = () => {
474 if (targetWindow.isDestroyed()) return;
475 targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
476 void runPromise(electronWindow.reveal(targetWindow));
477 };
478​
479 if (targetWindow.webContents.isLoadingMainFrame()) {
480 targetWindow.webContents.once("did-finish-load", send);
481 return;
482 }
483​
484 send();
485 }),
486 syncAppearance: Effect.gen(function* () {
487 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
488 yield* electronWindow.syncAllAppearance((window) =>
489 syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
490 );
491 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
492 });
493});
494​
495export const layer = Layer.effect(DesktopWindow, make);