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