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 Service construction is part of the canonical Effect module API. */
131export const make = Effect.gen(function* () {
132 const platform = yield* HostProcess.Platform;
133 // The focus worker loads a native accessibility module. Start it on the first
134 // capture reveal so users who never capture pay nothing at launch.
135 let windowsForegroundFocus: ReturnType<typeof startWindowsForegroundFocusThread> | undefined;
136 const ensureWindowsForegroundFocus = () => {
137 windowsForegroundFocus ??= startWindowsForegroundFocusThread(
138 NodePath.join(__dirname, "electron", "WindowsForegroundFocusWorker.cjs"),
139 );
140 return windowsForegroundFocus;
141 };
142 // Tracks a capture reveal in flight. Ordinary reveals keep Electron's native path.
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
147 const listWindows = (includeOffscreen = false) =>
148 Effect.try({
149 // Streamed preview pages have native windows for their renderer lifetime,
150 // but must never be revealed or receive app broadcasts and appearance changes.
151 try: () =>
152 Electron.BrowserWindow.getAllWindows().filter(
153 (window) =>
154 includeOffscreen ||
155 window.isDestroyed() ||
156 window.webContents.getType() !== "offscreen",
157 ),
158 catch: (cause) =>
159 new ElectronWindowOperationError({
160 operation: "list-windows",
161 platform,
162 windowId: null,
163 channel: null,
164 cause,
165 }),
166 }).pipe(Effect.orDie);
167
168 const isWindowDestroyed = (window: Electron.BrowserWindow) =>
169 Effect.try({
170 try: () => window.isDestroyed(),
171 catch: (cause) =>
172 new ElectronWindowOperationError({
173 operation: "inspect-window",
174 platform,
175 windowId: window.id,
176 channel: null,
177 cause,
178 }),
179 }).pipe(Effect.orDie);
180
181 const liveMain = Effect.gen(function* () {
182 const main = yield* Ref.get(mainWindowRef);
183 if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
184 return Option.none<Electron.BrowserWindow>();
185 }
186 return main;
187 });
188
189 const currentMainOrFirst = Effect.gen(function* () {
190 const main = yield* liveMain;
191 if (Option.isSome(main)) {
192 return main;
193 }
194
195 const first = Option.fromNullishOr((yield* listWindows())[0] ?? null);
196 if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
197 return Option.none<Electron.BrowserWindow>();
198 }
199 return first;
200 });
201
202 const focusedMainOrFirst = Effect.gen(function* () {
203 const focused = yield* Effect.try({
204 try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
205 catch: (cause) =>
206 new ElectronWindowOperationError({
207 operation: "get-focused-window",
208 platform,
209 windowId: null,
210 channel: null,
211 cause,
212 }),
213 }).pipe(Effect.orDie);
214 if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
215 return focused;
216 }
217 return yield* currentMainOrFirst;
218 });
219
220 return ElectronWindow.of({
221 create: (options) => {
222 const webPreferences = options.webPreferences;
223 const diagnosticOptions = {
224 title: options.title ?? null,
225 width: options.width ?? null,
226 height: options.height ?? null,
227 minWidth: options.minWidth ?? null,
228 minHeight: options.minHeight ?? null,
229 show: options.show ?? null,
230 modal: options.modal ?? null,
231 frame: options.frame ?? null,
232 transparent: options.transparent ?? null,
233 backgroundColor: options.backgroundColor ?? null,
234 webPreferences: {
235 preload: webPreferences?.preload ?? null,
236 partition: webPreferences?.partition ?? null,
237 backgroundThrottling: webPreferences?.backgroundThrottling ?? null,
238 sandbox: webPreferences?.sandbox ?? null,
239 contextIsolation: webPreferences?.contextIsolation ?? null,
240 nodeIntegration: webPreferences?.nodeIntegration ?? null,
241 webviewTag: webPreferences?.webviewTag ?? null,
242 },
243 } satisfies typeof ElectronWindowCreateOptions.Type;
244
245 return Effect.try({
246 try: () => new Electron.BrowserWindow(options),
247 catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
248 });
249 },
250 main: liveMain,
251 currentMainOrFirst,
252 focusedMainOrFirst,
253 setMain: (window) => Ref.set(mainWindowRef, Option.some(window)),
254 clearMain: (window) =>
255 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 prepareReveal: (window) =>
265 Effect.promise(async () => {
266 if (platform !== "win32" || window.isDestroyed()) {
267 return false;
268 }
269 captureRevealWindows.add(window.id);
270 return ensureWindowsForegroundFocus()
271 .prepare(windowsForegroundFocusTarget(window))
272 .catch(() => false);
273 }),
274 reveal: (window) =>
275 Effect.tryPromise({
276 try: async () => {
277 if (window.isDestroyed()) {
278 return;
279 }
280
281 // Only a capture reveal fights another process for the foreground, which
282 // needs Win32 calls that load native modules. Everything else stays native.
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 sendAll: (channel, ...args) =>
340 Effect.gen(function* () {
341 for (const window of yield* listWindows()) {
342 if (yield* isWindowDestroyed(window)) {
343 continue;
344 }
345 yield* Effect.try({
346 try: () => window.webContents.send(channel, ...args),
347 catch: (cause) =>
348 new ElectronWindowOperationError({
349 operation: "send-window-message",
350 platform,
351 windowId: window.id,
352 channel,
353 cause,
354 }),
355 }).pipe(Effect.orDie);
356 }
357 }),
358 destroyAll: Effect.gen(function* () {
359 let firstFailure: Cause.Cause<never> | undefined;
360 for (const window of yield* listWindows(true)) {
361 const exit = yield* Effect.exit(
362 Effect.try({
363 try: () => window.destroy(),
364 catch: (cause) =>
365 new ElectronWindowOperationError({
366 operation: "destroy-window",
367 platform,
368 windowId: window.id,
369 channel: null,
370 cause,
371 }),
372 }).pipe(Effect.orDie),
373 );
374 if (Exit.isFailure(exit)) {
375 firstFailure ??= exit.cause;
376 }
377 }
378 if (firstFailure !== undefined) {
379 return yield* Effect.failCause(firstFailure);
380 }
381 }),
382 syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
383 sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
384 ) {
385 const windows = yield* listWindows();
386 for (const window of windows) {
387 if (yield* isWindowDestroyed(window)) {
388 continue;
389 }
390 yield* sync(window);
391 }
392 }),
393 });
394});
395
396export const layer = Layer.effect(ElectronWindow, make);