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 readonly create: (
113 options: Electron.BrowserWindowConstructorOptions,
114 ) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
115 readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
116 readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
117 readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
118 readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
119 readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
120 readonly prepareReveal: (window: Electron.BrowserWindow) => Effect.Effect<boolean>;
121 readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
122 readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
123 readonly destroyAll: Effect.Effect<void>;
124 readonly syncAllAppearance: <E, R>(
125 sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
126 ) => Effect.Effect<void, E, R>;
127 }
128>()("@t3tools/desktop/electron/ElectronWindow") {}
129
130/** @public */
131export const make = Effect.gen(function* () {
132 const platform = yield* HostProcess.Platform;
133 // Lazy-load native accessibility on capture reveal to avoid startup cost for other users.
134 let windowsForegroundFocus: ReturnType<typeof startWindowsForegroundFocusThread> | undefined;
135 const ensureWindowsForegroundFocus = () => {
136 windowsForegroundFocus ??= startWindowsForegroundFocusThread(
137 NodePath.join(__dirname, "electron", "WindowsForegroundFocusWorker.cjs"),
138 );
139 return windowsForegroundFocus;
140 };
141 const captureRevealWindows = new Set<number>();
142 yield* Effect.addFinalizer(() => Effect.sync(() => windowsForegroundFocus?.close()));
143 const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
144
145 const listWindows = Effect.try({
146 try: () => Electron.BrowserWindow.getAllWindows(),
147 catch: (cause) =>
148 new ElectronWindowOperationError({
149 operation: "list-windows",
150 platform,
151 windowId: null,
152 channel: null,
153 cause,
154 }),
155 }).pipe(Effect.orDie);
156
157 const isWindowDestroyed = (window: Electron.BrowserWindow) =>
158 Effect.try({
159 try: () => window.isDestroyed(),
160 catch: (cause) =>
161 new ElectronWindowOperationError({
162 operation: "inspect-window",
163 platform,
164 windowId: window.id,
165 channel: null,
166 cause,
167 }),
168 }).pipe(Effect.orDie);
169
170 const liveMain = Effect.gen(function* () {
171 const main = yield* Ref.get(mainWindowRef);
172 if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
173 return Option.none<Electron.BrowserWindow>();
174 }
175 return main;
176 });
177
178 const currentMainOrFirst = Effect.gen(function* () {
179 const main = yield* liveMain;
180 if (Option.isSome(main)) {
181 return main;
182 }
183
184 const first = Option.fromNullishOr((yield* listWindows)[0] ?? null);
185 if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
186 return Option.none<Electron.BrowserWindow>();
187 }
188 return first;
189 });
190
191 const focusedMainOrFirst = Effect.gen(function* () {
192 const focused = yield* Effect.try({
193 try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
194 catch: (cause) =>
195 new ElectronWindowOperationError({
196 operation: "get-focused-window",
197 platform,
198 windowId: null,
199 channel: null,
200 cause,
201 }),
202 }).pipe(Effect.orDie);
203 if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
204 return focused;
205 }
206 return yield* currentMainOrFirst;
207 });
208
209 return ElectronWindow.of({
210 create: (options) => {
211 const webPreferences = options.webPreferences;
212 const diagnosticOptions = {
213 title: options.title ?? null,
214 width: options.width ?? null,
215 height: options.height ?? null,
216 minWidth: options.minWidth ?? null,
217 minHeight: options.minHeight ?? null,
218 show: options.show ?? null,
219 modal: options.modal ?? null,
220 frame: options.frame ?? null,
221 transparent: options.transparent ?? null,
222 backgroundColor: options.backgroundColor ?? null,
223 webPreferences: {
224 preload: webPreferences?.preload ?? null,
225 partition: webPreferences?.partition ?? null,
226 backgroundThrottling: webPreferences?.backgroundThrottling ?? null,
227 sandbox: webPreferences?.sandbox ?? null,
228 contextIsolation: webPreferences?.contextIsolation ?? null,
229 nodeIntegration: webPreferences?.nodeIntegration ?? null,
230 webviewTag: webPreferences?.webviewTag ?? null,
231 },
232 } satisfies typeof ElectronWindowCreateOptions.Type;
233
234 return Effect.try({
235 try: () => new Electron.BrowserWindow(options),
236 catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
237 });
238 },
239 main: liveMain,
240 currentMainOrFirst,
241 focusedMainOrFirst,
242 setMain: (window) => Ref.set(mainWindowRef, Option.some(window)),
243 clearMain: (window) =>
244 Ref.update(mainWindowRef, (current) => {
245 if (Option.isNone(current)) {
246 return current;
247 }
248 if (Option.isSome(window) && current.value !== window.value) {
249 return current;
250 }
251 return Option.none();
252 }),
253 prepareReveal: (window) =>
254 Effect.promise(async () => {
255 if (platform !== "win32" || window.isDestroyed()) {
256 return false;
257 }
258 captureRevealWindows.add(window.id);
259 return ensureWindowsForegroundFocus()
260 .prepare(windowsForegroundFocusTarget(window))
261 .catch(() => false);
262 }),
263 reveal: (window) =>
264 Effect.tryPromise({
265 try: async () => {
266 if (window.isDestroyed()) {
267 return;
268 }
269
270 const captureReveal = platform === "win32" && captureRevealWindows.delete(window.id);
271 const shellHostedForeground =
272 captureReveal && (await isWindowsShellHostedForeground().catch(() => false));
273
274 if (window.isMinimized()) {
275 window.restore();
276 }
277
278 if (captureReveal) {
279 Electron.app.focus();
280 }
281
282 if (captureReveal || !window.isVisible()) {
283 window.show();
284 }
285
286 if (captureReveal) {
287 window.moveTop();
288 }
289
290 if (platform === "darwin") {
291 Electron.app.focus({ steal: true });
292 }
293
294 window.focus();
295
296 if (captureReveal) {
297 if (shellHostedForeground) {
298 await windowsForegroundFocus
299 ?.focus(windowsForegroundFocusTarget(window))
300 .catch(() => false);
301 }
302 try {
303 await activateWindowsForeground(window.getNativeWindowHandle());
304 } catch {
305 const needsFocus = !(await isWindowsBrowserWindowForeground(window));
306 if (needsFocus && !window.isDestroyed()) {
307 await windowsForegroundFocus
308 ?.focus(windowsForegroundFocusTarget(window))
309 .catch(() => false);
310 }
311 if (!window.isDestroyed()) {
312 await activateWindowsForeground(window.getNativeWindowHandle());
313 }
314 }
315 }
316 },
317 catch: (cause) =>
318 new ElectronWindowOperationError({
319 operation: "reveal-window",
320 platform,
321 windowId: window.id,
322 channel: null,
323 cause,
324 }),
325 }).pipe(Effect.orDie),
326 sendAll:
327 /* Window broadcasts run for streamed updates; avoid a span per broadcast. */
328 Effect.fnUntraced(function* (channel, ...args) {
329 for (const window of yield* listWindows) {
330 if (yield* isWindowDestroyed(window)) {
331 continue;
332 }
333 yield* Effect.try({
334 try: () => window.webContents.send(channel, ...args),
335 catch: (cause) =>
336 new ElectronWindowOperationError({
337 operation: "send-window-message",
338 platform,
339 windowId: window.id,
340 channel,
341 cause,
342 }),
343 }).pipe(Effect.orDie);
344 }
345 }),
346 destroyAll: Effect.gen(function* () {
347 let firstFailure: Cause.Cause<never> | undefined;
348 for (const window of yield* listWindows) {
349 const exit = yield* Effect.exit(
350 Effect.try({
351 try: () => window.destroy(),
352 catch: (cause) =>
353 new ElectronWindowOperationError({
354 operation: "destroy-window",
355 platform,
356 windowId: window.id,
357 channel: null,
358 cause,
359 }),
360 }).pipe(Effect.orDie),
361 );
362 if (Exit.isFailure(exit)) {
363 firstFailure ??= exit.cause;
364 }
365 }
366 if (firstFailure !== undefined) {
367 return yield* Effect.failCause(firstFailure);
368 }
369 }),
370 syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
371 sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
372 ) {
373 const windows = yield* listWindows;
374 for (const window of windows) {
375 if (yield* isWindowDestroyed(window)) {
376 continue;
377 }
378 yield* sync(window);
379 }
380 }),
381 });
382});
383
384export const layer = Layer.effect(ElectronWindow, make);