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