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

ElectronWindow.ts

384 lines13.3 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 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 const captureRevealWindows = new Set<number>();
143 yield* Effect.addFinalizer(() => Effect.sync(() => windowsForegroundFocus?.close()));
144 const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
145​
146 const listWindows = Effect.try({
147 try: () => Electron.BrowserWindow.getAllWindows(),
148 catch: (cause) =>
149 new ElectronWindowOperationError({
150 operation: "list-windows",
151 platform,
152 windowId: null,
153 channel: null,
154 cause,
155 }),
156 }).pipe(Effect.orDie);
157​
158 const isWindowDestroyed = (window: Electron.BrowserWindow) =>
159 Effect.try({
160 try: () => window.isDestroyed(),
161 catch: (cause) =>
162 new ElectronWindowOperationError({
163 operation: "inspect-window",
164 platform,
165 windowId: window.id,
166 channel: null,
167 cause,
168 }),
169 }).pipe(Effect.orDie);
170​
171 const liveMain = Effect.gen(function* () {
172 const main = yield* Ref.get(mainWindowRef);
173 if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
174 return Option.none<Electron.BrowserWindow>();
175 }
176 return main;
177 });
178​
179 const currentMainOrFirst = Effect.gen(function* () {
180 const main = yield* liveMain;
181 if (Option.isSome(main)) {
182 return main;
183 }
184​
185 const first = Option.fromNullishOr((yield* listWindows)[0] ?? null);
186 if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
187 return Option.none<Electron.BrowserWindow>();
188 }
189 return first;
190 });
191​
192 const focusedMainOrFirst = Effect.gen(function* () {
193 const focused = yield* Effect.try({
194 try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
195 catch: (cause) =>
196 new ElectronWindowOperationError({
197 operation: "get-focused-window",
198 platform,
199 windowId: null,
200 channel: null,
201 cause,
202 }),
203 }).pipe(Effect.orDie);
204 if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
205 return focused;
206 }
207 return yield* currentMainOrFirst;
208 });
209​
210 return ElectronWindow.of({
211 create: (options) => {
212 const webPreferences = options.webPreferences;
213 const diagnosticOptions = {
214 title: options.title ?? null,
215 width: options.width ?? null,
216 height: options.height ?? null,
217 minWidth: options.minWidth ?? null,
218 minHeight: options.minHeight ?? null,
219 show: options.show ?? null,
220 modal: options.modal ?? null,
221 frame: options.frame ?? null,
222 transparent: options.transparent ?? null,
223 backgroundColor: options.backgroundColor ?? null,
224 webPreferences: {
225 preload: webPreferences?.preload ?? null,
226 partition: webPreferences?.partition ?? null,
227 backgroundThrottling: webPreferences?.backgroundThrottling ?? null,
228 sandbox: webPreferences?.sandbox ?? null,
229 contextIsolation: webPreferences?.contextIsolation ?? null,
230 nodeIntegration: webPreferences?.nodeIntegration ?? null,
231 webviewTag: webPreferences?.webviewTag ?? null,
232 },
233 } satisfies typeof ElectronWindowCreateOptions.Type;
234​
235 return Effect.try({
236 try: () => new Electron.BrowserWindow(options),
237 catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
238 });
239 },
240 main: liveMain,
241 currentMainOrFirst,
242 focusedMainOrFirst,
243 setMain: (window) => Ref.set(mainWindowRef, Option.some(window)),
244 clearMain: (window) =>
245 Ref.update(mainWindowRef, (current) => {
246 if (Option.isNone(current)) {
247 return current;
248 }
249 if (Option.isSome(window) && current.value !== window.value) {
250 return current;
251 }
252 return Option.none();
253 }),
254 prepareReveal: (window) =>
255 Effect.promise(async () => {
256 if (platform !== "win32" || window.isDestroyed()) {
257 return false;
258 }
259 captureRevealWindows.add(window.id);
260 return ensureWindowsForegroundFocus()
261 .prepare(windowsForegroundFocusTarget(window))
262 .catch(() => false);
263 }),
264 reveal: (window) =>
265 Effect.tryPromise({
266 try: async () => {
267 if (window.isDestroyed()) {
268 return;
269 }
270​
271 const captureReveal = platform === "win32" && captureRevealWindows.delete(window.id);
272 const shellHostedForeground =
273 captureReveal && (await isWindowsShellHostedForeground().catch(() => false));
274​
275 if (window.isMinimized()) {
276 window.restore();
277 }
278​
279 if (captureReveal) {
280 Electron.app.focus();
281 }
282​
283 if (captureReveal || !window.isVisible()) {
284 window.show();
285 }
286​
287 if (captureReveal) {
288 window.moveTop();
289 }
290​
291 if (platform === "darwin") {
292 Electron.app.focus({ steal: true });
293 }
294​
295 window.focus();
296​
297 if (captureReveal) {
298 if (shellHostedForeground) {
299 await windowsForegroundFocus
300 ?.focus(windowsForegroundFocusTarget(window))
301 .catch(() => false);
302 }
303 try {
304 await activateWindowsForeground(window.getNativeWindowHandle());
305 } catch {
306 const needsFocus = !(await isWindowsBrowserWindowForeground(window));
307 if (needsFocus && !window.isDestroyed()) {
308 await windowsForegroundFocus
309 ?.focus(windowsForegroundFocusTarget(window))
310 .catch(() => false);
311 }
312 if (!window.isDestroyed()) {
313 await activateWindowsForeground(window.getNativeWindowHandle());
314 }
315 }
316 }
317 },
318 catch: (cause) =>
319 new ElectronWindowOperationError({
320 operation: "reveal-window",
321 platform,
322 windowId: window.id,
323 channel: null,
324 cause,
325 }),
326 }).pipe(Effect.orDie),
327 sendAll: (channel, ...args) =>
328 Effect.gen(function* () {
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);