Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ElectronWindow.ts

389 lines13.5 KB

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 };
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;
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 }
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 }
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: Effect.fn("ElectronWindow.create")(function (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: Effect.fn("ElectronWindow.setMain")(function (window) {
243 return Ref.set(mainWindowRef, Option.some(window));
244 }),
245 clearMain: Effect.fn("ElectronWindow.clearMain")(function (window) {
246 return Ref.update(mainWindowRef, (current) => {
247 if (Option.isNone(current)) {
248 return current;
249 }
250 if (Option.isSome(window) && current.value !== window.value) {
251 return current;
252 }
253 return Option.none();
254 });
255 }),
256 prepareReveal: Effect.fn("ElectronWindow.prepareReveal")(function (window) {
257 return Effect.promise(async () => {
258 if (platform !== "win32" || window.isDestroyed()) {
259 return false;
260 }
261 captureRevealWindows.add(window.id);
262 return ensureWindowsForegroundFocus()
263 .prepare(windowsForegroundFocusTarget(window))
264 .catch(() => false);
265 });
266 }),
267 reveal: Effect.fn("ElectronWindow.reveal")(function (window) {
268 return Effect.tryPromise({
269 try: async () => {
270 if (window.isDestroyed()) {
271 return;
272 }
273​
274 const captureReveal = platform === "win32" && captureRevealWindows.delete(window.id);
275 const shellHostedForeground =
276 captureReveal && (await isWindowsShellHostedForeground().catch(() => false));
277​
278 if (window.isMinimized()) {
279 window.restore();
280 }
281​
282 if (captureReveal) {
283 Electron.app.focus();
284 }
285​
286 if (captureReveal || !window.isVisible()) {
287 window.show();
288 }
289​
290 if (captureReveal) {
291 window.moveTop();
292 }
293​
294 if (platform === "darwin") {
295 Electron.app.focus({ steal: true });
296 }
297​
298 window.focus();
299​
300 if (captureReveal) {
301 if (shellHostedForeground) {
302 await windowsForegroundFocus
303 ?.focus(windowsForegroundFocusTarget(window))
304 .catch(() => false);
305 }
306 try {
307 await activateWindowsForeground(window.getNativeWindowHandle());
308 } catch {
309 const needsFocus = !(await isWindowsBrowserWindowForeground(window));
310 if (needsFocus && !window.isDestroyed()) {
311 await windowsForegroundFocus
312 ?.focus(windowsForegroundFocusTarget(window))
313 .catch(() => false);
314 }
315 if (!window.isDestroyed()) {
316 await activateWindowsForeground(window.getNativeWindowHandle());
317 }
318 }
319 }
320 },
321 catch: (cause) =>
322 new ElectronWindowOperationError({
323 operation: "reveal-window",
324 platform,
325 windowId: window.id,
326 channel: null,
327 cause,
328 }),
329 }).pipe(Effect.orDie);
330 }),
331 sendAll:
332 /* Window broadcasts run for streamed updates; avoid a span per broadcast. */
333 Effect.fnUntraced(function* (channel, ...args) {
334 for (const window of yield* listWindows) {
335 if (yield* isWindowDestroyed(window)) {
336 continue;
337 }
338 yield* Effect.try({
339 try: () => window.webContents.send(channel, ...args),
340 catch: (cause) =>
341 new ElectronWindowOperationError({
342 operation: "send-window-message",
343 platform,
344 windowId: window.id,
345 channel,
346 cause,
347 }),
348 }).pipe(Effect.orDie);
349 }
350 }),
351 destroyAll: Effect.gen(function* () {
352 let firstFailure: Cause.Cause<never> | undefined;
353 for (const window of yield* listWindows) {
354 const exit = yield* Effect.exit(
355 Effect.try({
356 try: () => window.destroy(),
357 catch: (cause) =>
358 new ElectronWindowOperationError({
359 operation: "destroy-window",
360 platform,
361 windowId: window.id,
362 channel: null,
363 cause,
364 }),
365 }).pipe(Effect.orDie),
366 );
367 if (Exit.isFailure(exit)) {
368 firstFailure ??= exit.cause;
369 }
370 }
371 if (firstFailure !== undefined) {
372 return yield* Effect.failCause(firstFailure);
373 }
374 }),
375 syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
376 sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
377 ) {
378 const windows = yield* listWindows;
379 for (const window of windows) {
380 if (yield* isWindowDestroyed(window)) {
381 continue;
382 }
383 yield* sync(window);
384 }
385 }),
386 });
387});
388​
389export const layer = Layer.effect(ElectronWindow, make);