Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- This desktop-only service resolves its bundled helper beside the Electron entrypoint.
2
3import * as NodePath from "node:path";
4
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import type * as Cause from "effect/Cause";
7import * as Context from "effect/Context";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Ref from "effect/Ref";
13import * as Schema from "effect/Schema";
14
15import * as Electron from "electron";
16
17import {
18 activateWindowsForeground,
19 isWindowsShellHostedForeground,
20 loadWindowsForegroundApi,
21} from "./WindowsForeground.ts";
22import { startWindowsForegroundFocusThread } from "./WindowsForegroundFocusThread.ts";
23
24function windowsForegroundFocusTarget(window: Electron.BrowserWindow) {
25 return {
26 windowId: window.id,
27 processId: process.pid,
28 title: window.getTitle(),
29 bounds: window.getBounds(),
30 contentBounds: window.getContentBounds(),
31 };
32}
33
34async function isWindowsBrowserWindowForeground(window: Electron.BrowserWindow): Promise<boolean> {
35 const foreground = await loadWindowsForegroundApi()
36 .then((api) => api.getForegroundWindow())
37 .catch(() => undefined);
38 if (window.isDestroyed() || foreground === undefined || foreground === 0n) return false;
39 const handle = window.getNativeWindowHandle();
40 const hwnd = handle.length === 8 ? handle.readBigUInt64LE() : BigInt(handle.readUInt32LE());
41 return foreground === hwnd;
42}
43
44const ElectronWindowCreateOptions = Schema.Struct({
45 title: Schema.NullOr(Schema.String),
46 width: Schema.NullOr(Schema.Number),
47 height: Schema.NullOr(Schema.Number),
48 minWidth: Schema.NullOr(Schema.Number),
49 minHeight: Schema.NullOr(Schema.Number),
50 show: Schema.NullOr(Schema.Boolean),
51 modal: Schema.NullOr(Schema.Boolean),
52 frame: Schema.NullOr(Schema.Boolean),
53 transparent: Schema.NullOr(Schema.Boolean),
54 backgroundColor: Schema.NullOr(Schema.String),
55 webPreferences: Schema.Struct({
56 preload: Schema.NullOr(Schema.String),
57 partition: Schema.NullOr(Schema.String),
58 backgroundThrottling: Schema.NullOr(Schema.Boolean),
59 sandbox: Schema.NullOr(Schema.Boolean),
60 contextIsolation: Schema.NullOr(Schema.Boolean),
61 nodeIntegration: Schema.NullOr(Schema.Boolean),
62 webviewTag: Schema.NullOr(Schema.Boolean),
63 }),
64});
65
66const ElectronWindowOperation = Schema.Literals([
67 "list-windows",
68 "get-focused-window",
69 "inspect-window",
70 "reveal-window",
71 "send-window-message",
72 "destroy-window",
73]);
74
75export class ElectronWindowCreateError extends Schema.TaggedError<ElectronWindowCreateError>()(
76 "ElectronWindowCreateError",
77 {
78 options: ElectronWindowCreateOptions,
79 cause: Schema.Defect(),
80 },
81) {
82 override get message(): string {
83 const title = this.options.title === null ? "" : ` "${this.options.title}"`;
84 const dimensions =
85 this.options.width === null || this.options.height === null
86 ? ""
87 : ` (${this.options.width}x${this.options.height})`;
88 return `Failed to create Electron BrowserWindow${title}${dimensions}.`;
89 }
90}
91
92export class ElectronWindowOperationError extends Schema.TaggedError<ElectronWindowOperationError>()(
93 "ElectronWindowOperationError",
94 {
95 operation: ElectronWindowOperation,
96 platform: Schema.String,
97 windowId: Schema.NullOr(Schema.Number),
98 channel: Schema.NullOr(Schema.String),
99 cause: Schema.Defect(),
100 },
101) {
102 override get message(): string {
103 const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
104 const channel = this.channel === null ? "" : ` on channel ${JSON.stringify(this.channel)}`;
105 return `Electron window operation ${JSON.stringify(this.operation)} failed${window}${channel} on ${this.platform}.`;
106 }
107}
108
109export class ElectronWindow extends Context.Service<
110 ElectronWindow,
111 {
112 /** Auxiliary windows are never returned as the main-or-first fallback. */
113 readonly create: (
114 options: Electron.BrowserWindowConstructorOptions,
115 behavior?: { readonly auxiliary?: boolean },
116 ) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
117 readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
118 readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
119 readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
120 readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
121 readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
122 readonly prepareReveal: (window: Electron.BrowserWindow) => Effect.Effect<boolean>;
123 readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
124 readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
125 readonly destroyAll: Effect.Effect<void>;
126 readonly syncAllAppearance: <E, R>(
127 sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
128 ) => Effect.Effect<void, E, R>;
129 }
130>()("@t3tools/desktop/electron/ElectronWindow") {}
131
132/** @public */
133export const make = Effect.gen(function* () {
134 const platform = yield* HostProcess.Platform;
135 // Lazy-load native accessibility on capture reveal to avoid startup cost for other users.
136 let windowsForegroundFocus: ReturnType<typeof startWindowsForegroundFocusThread> | undefined;
137 const ensureWindowsForegroundFocus = () => {
138 windowsForegroundFocus ??= startWindowsForegroundFocusThread(
139 NodePath.join(__dirname, "electron", "WindowsForegroundFocusWorker.cjs"),
140 );
141 return windowsForegroundFocus;
142 };
143 const captureRevealWindows = new Set<number>();
144 yield* Effect.addFinalizer(() => Effect.sync(() => windowsForegroundFocus?.close()));
145 const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
146 const auxiliaryWindows = new WeakSet<Electron.BrowserWindow>();
147
148 const listWindows = Effect.try({
149 try: () => Electron.BrowserWindow.getAllWindows(),
150 catch: (cause) =>
151 new ElectronWindowOperationError({
152 operation: "list-windows",
153 platform,
154 windowId: null,
155 channel: null,
156 cause,
157 }),
158 }).pipe(Effect.orDie);
159
160 const isWindowDestroyed = (window: Electron.BrowserWindow) =>
161 Effect.try({
162 try: () => window.isDestroyed(),
163 catch: (cause) =>
164 new ElectronWindowOperationError({
165 operation: "inspect-window",
166 platform,
167 windowId: window.id,
168 channel: null,
169 cause,
170 }),
171 }).pipe(Effect.orDie);
172
173 const liveMain = Effect.gen(function* () {
174 const main = yield* Ref.get(mainWindowRef);
175 if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
176 return Option.none<Electron.BrowserWindow>();
177 }
178 return main;
179 });
180
181 const currentMainOrFirst = Effect.gen(function* () {
182 const main = yield* liveMain;
183 if (Option.isSome(main)) {
184 return main;
185 }
186
187 const first = Option.fromNullishOr(
188 (yield* listWindows).find((window) => !auxiliaryWindows.has(window)) ?? null,
189 );
190 if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
191 return Option.none<Electron.BrowserWindow>();
192 }
193 return first;
194 });
195
196 const focusedMainOrFirst = Effect.gen(function* () {
197 const focused = yield* Effect.try({
198 try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
199 catch: (cause) =>
200 new ElectronWindowOperationError({
201 operation: "get-focused-window",
202 platform,
203 windowId: null,
204 channel: null,
205 cause,
206 }),
207 }).pipe(Effect.orDie);
208 if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
209 return focused;
210 }
211 return yield* currentMainOrFirst;
212 });
213
214 return ElectronWindow.of({
215 create: Effect.fn("ElectronWindow.create")(function (options, behavior) {
216 const webPreferences = options.webPreferences;
217 const diagnosticOptions = {
218 title: options.title ?? null,
219 width: options.width ?? null,
220 height: options.height ?? null,
221 minWidth: options.minWidth ?? null,
222 minHeight: options.minHeight ?? null,
223 show: options.show ?? null,
224 modal: options.modal ?? null,
225 frame: options.frame ?? null,
226 transparent: options.transparent ?? null,
227 backgroundColor: options.backgroundColor ?? null,
228 webPreferences: {
229 preload: webPreferences?.preload ?? null,
230 partition: webPreferences?.partition ?? null,
231 backgroundThrottling: webPreferences?.backgroundThrottling ?? null,
232 sandbox: webPreferences?.sandbox ?? null,
233 contextIsolation: webPreferences?.contextIsolation ?? null,
234 nodeIntegration: webPreferences?.nodeIntegration ?? null,
235 webviewTag: webPreferences?.webviewTag ?? null,
236 },
237 } satisfies typeof ElectronWindowCreateOptions.Type;
238
239 return Effect.try({
240 try: () => {
241 const window = new Electron.BrowserWindow(options);
242 if (behavior?.auxiliary === true) auxiliaryWindows.add(window);
243 return window;
244 },
245 catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
246 });
247 }),
248 main: liveMain,
249 currentMainOrFirst,
250 focusedMainOrFirst,
251 setMain: Effect.fn("ElectronWindow.setMain")(function (window) {
252 return Ref.set(mainWindowRef, Option.some(window));
253 }),
254 clearMain: Effect.fn("ElectronWindow.clearMain")(function (window) {
255 return Ref.update(mainWindowRef, (current) => {
256 if (Option.isNone(current)) {
257 return current;
258 }
259 if (Option.isSome(window) && current.value !== window.value) {
260 return current;
261 }
262 return Option.none();
263 });
264 }),
265 prepareReveal: Effect.fn("ElectronWindow.prepareReveal")(function (window) {
266 return Effect.promise(async () => {
267 if (platform !== "win32" || window.isDestroyed()) {
268 return false;
269 }
270 captureRevealWindows.add(window.id);
271 return ensureWindowsForegroundFocus()
272 .prepare(windowsForegroundFocusTarget(window))
273 .catch(() => false);
274 });
275 }),
276 reveal: Effect.fn("ElectronWindow.reveal")(function (window) {
277 return Effect.tryPromise({
278 try: async () => {
279 if (window.isDestroyed()) {
280 return;
281 }
282
283 const captureReveal = platform === "win32" && captureRevealWindows.delete(window.id);
284 const shellHostedForeground =
285 captureReveal && (await isWindowsShellHostedForeground().catch(() => false));
286
287 if (window.isMinimized()) {
288 window.restore();
289 }
290
291 if (captureReveal) {
292 Electron.app.focus();
293 }
294
295 if (captureReveal || !window.isVisible()) {
296 window.show();
297 }
298
299 if (captureReveal) {
300 window.moveTop();
301 }
302
303 if (platform === "darwin") {
304 Electron.app.focus({ steal: true });
305 }
306
307 window.focus();
308
309 if (captureReveal) {
310 if (shellHostedForeground) {
311 await windowsForegroundFocus
312 ?.focus(windowsForegroundFocusTarget(window))
313 .catch(() => false);
314 }
315 try {
316 await activateWindowsForeground(window.getNativeWindowHandle());
317 } catch {
318 const needsFocus = !(await isWindowsBrowserWindowForeground(window));
319 if (needsFocus && !window.isDestroyed()) {
320 await windowsForegroundFocus
321 ?.focus(windowsForegroundFocusTarget(window))
322 .catch(() => false);
323 }
324 if (!window.isDestroyed()) {
325 await activateWindowsForeground(window.getNativeWindowHandle());
326 }
327 }
328 }
329 },
330 catch: (cause) =>
331 new ElectronWindowOperationError({
332 operation: "reveal-window",
333 platform,
334 windowId: window.id,
335 channel: null,
336 cause,
337 }),
338 }).pipe(Effect.orDie);
339 }),
340 sendAll:
341 /* Window broadcasts run for streamed updates; avoid a span per broadcast. */
342 Effect.fnUntraced(function* (channel, ...args) {
343 for (const window of yield* listWindows) {
344 if (yield* isWindowDestroyed(window)) {
345 continue;
346 }
347 yield* Effect.try({
348 try: () => window.webContents.send(channel, ...args),
349 catch: (cause) =>
350 new ElectronWindowOperationError({
351 operation: "send-window-message",
352 platform,
353 windowId: window.id,
354 channel,
355 cause,
356 }),
357 }).pipe(Effect.orDie);
358 }
359 }),
360 destroyAll: Effect.gen(function* () {
361 let firstFailure: Cause.Cause<never> | undefined;
362 for (const window of yield* listWindows) {
363 const exit = yield* Effect.exit(
364 Effect.try({
365 try: () => window.destroy(),
366 catch: (cause) =>
367 new ElectronWindowOperationError({
368 operation: "destroy-window",
369 platform,
370 windowId: window.id,
371 channel: null,
372 cause,
373 }),
374 }).pipe(Effect.orDie),
375 );
376 if (Exit.isFailure(exit)) {
377 firstFailure ??= exit.cause;
378 }
379 }
380 if (firstFailure !== undefined) {
381 return yield* Effect.failCause(firstFailure);
382 }
383 }),
384 syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
385 sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
386 ) {
387 const windows = yield* listWindows;
388 for (const window of windows) {
389 if (yield* isWindowDestroyed(window)) {
390 continue;
391 }
392 yield* sync(window);
393 }
394 }),
395 });
396});
397
398export const layer = Layer.effect(ElectronWindow, make);