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

DesktopLifecycle.ts

266 lines9.5 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Ref from "effect/Ref";
5import * as Schema from "effect/Schema";
6import * as Scope from "effect/Scope";
7​
8import type * as Electron from "electron";
9​
10import * as DesktopEnvironment from "./DesktopEnvironment.ts";
11import { makeComponentLogger } from "./DesktopObservability.ts";
12import * as DesktopShutdown from "./DesktopShutdown.ts";
13import * as ElectronApp from "../electron/ElectronApp.ts";
14import * as ElectronTheme from "../electron/ElectronTheme.ts";
15import * as ElectronWindow from "../electron/ElectronWindow.ts";
16import * as DesktopState from "./DesktopState.ts";
17import * as DesktopWindow from "../window/DesktopWindow.ts";
18​
19export class DesktopLifecycleRelaunchError extends Schema.TaggedErrorClass<DesktopLifecycleRelaunchError>()(
20 "DesktopLifecycleRelaunchError",
21 {
22 reason: Schema.String,
23 cause: Schema.Defect(),
24 },
25) {
26 override get message(): string {
27 return `Desktop relaunch failed for reason "${this.reason}".`;
28 }
30​
31export type DesktopLifecycleRuntimeServices =
32 | DesktopEnvironment.DesktopEnvironment
33 | DesktopShutdown.DesktopShutdown
34 | DesktopState.DesktopState
35 | DesktopWindow.DesktopWindow
36 | ElectronApp.ElectronApp
37 | ElectronTheme.ElectronTheme;
38​
39type DesktopLifecycleRegistrationServices =
40 | DesktopLifecycleRuntimeServices
41 | ElectronWindow.ElectronWindow;
42​
43/**
44 * @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme | ElectronWindow
45 */
46export class DesktopLifecycle extends Context.Service<
47 DesktopLifecycle,
48 {
49 readonly relaunch: (
50 reason: string,
51 ) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
52 readonly register: Effect.Effect<
53 void,
54 never,
55 Scope.Scope | DesktopLifecycleRegistrationServices
56 >;
57 }
58>()("@t3tools/desktop/app/DesktopLifecycle") {}
59​
60const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
61 makeComponentLogger("desktop-lifecycle");
62​
63function addScopedListener<Args extends ReadonlyArray<unknown>>(
64 target: unknown,
65 eventName: string,
66 listener: (...args: Args) => void,
67): Effect.Effect<void, never, Scope.Scope> {
68 const eventTarget = target as {
69 on: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown;
70 removeListener: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown;
71 };
72 const untypedListener = listener as unknown as (...args: Array<unknown>) => void;
73 return Effect.acquireRelease(
74 Effect.sync(() => {
75 eventTarget.on(eventName, untypedListener);
76 }),
77 () =>
78 Effect.sync(() => {
79 eventTarget.removeListener(eventName, untypedListener);
80 }),
81 ).pipe(Effect.asVoid);
83​
84const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
85 function* (
86 afterBoundsFlush: Effect.Effect<void> = Effect.void,
87 ): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown | DesktopWindow.DesktopWindow> {
88 const shutdown = yield* DesktopShutdown.DesktopShutdown;
89 const desktopWindow = yield* DesktopWindow.DesktopWindow;
90 yield* desktopWindow.flushMainWindowBounds;
91 yield* afterBoundsFlush;
92 yield* shutdown.request;
93 yield* shutdown.awaitComplete;
94 },
95);
96​
97function handleBeforeQuit(
98 event: Electron.Event,
99 runEffect: <A, E>(
100 effect: Effect.Effect<A, E, DesktopLifecycleRegistrationServices>,
101 ) => Promise<A>,
102 allowQuit: () => boolean,
103 markQuitAllowed: () => void,
104): void {
105 if (allowQuit()) {
106 void runEffect(
107 Effect.gen(function* () {
108 const state = yield* DesktopState.DesktopState;
109 yield* Ref.set(state.quitting, true);
110 yield* logLifecycleInfo("before-quit received");
111 }).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")),
112 );
113 return;
114 }
115​
116 event.preventDefault();
117 void runEffect(
118 Effect.gen(function* () {
119 const state = yield* DesktopState.DesktopState;
120 const electronWindow = yield* ElectronWindow.ElectronWindow;
121 yield* Ref.set(state.quitting, true);
122 yield* logLifecycleInfo("before-quit received");
123 yield* requestDesktopShutdownAndWait(
124 electronWindow.destroyAll.pipe(
125 Effect.catchCause((cause) =>
126 logLifecycleError("failed to destroy windows before shutdown", { cause }),
127 ),
128 ),
129 );
130 }).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")),
131 ).finally(() => {
132 markQuitAllowed();
133 void runEffect(
134 Effect.gen(function* () {
135 const electronApp = yield* ElectronApp.ElectronApp;
136 yield* electronApp.quit;
137 }).pipe(Effect.withSpan("desktop.lifecycle.quitAfterShutdown")),
138 );
139 });
141​
142function quitFromSignal(
143 signal: "SIGINT" | "SIGTERM",
144 runEffect: <A, E>(
145 effect: Effect.Effect<A, E, DesktopLifecycleRegistrationServices>,
146 ) => Promise<A>,
147): void {
148 void runEffect(
149 Effect.gen(function* () {
150 yield* Effect.annotateCurrentSpan({ signal });
151 const electronApp = yield* ElectronApp.ElectronApp;
152 const state = yield* DesktopState.DesktopState;
153 const wasQuitting = yield* Ref.getAndSet(state.quitting, true);
154 if (wasQuitting) return;
155 yield* logLifecycleInfo("process signal received", { signal });
156 yield* requestDesktopShutdownAndWait();
157 yield* electronApp.quit;
158 }).pipe(Effect.withSpan("desktop.lifecycle.processSignal")),
159 );
161​
162export const make = DesktopLifecycle.of({
163 relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
164 const electronApp = yield* ElectronApp.ElectronApp;
165 const environment = yield* DesktopEnvironment.DesktopEnvironment;
166 const state = yield* DesktopState.DesktopState;
167 yield* logLifecycleInfo("desktop relaunch requested", { reason });
168 yield* Effect.gen(function* () {
169 yield* Effect.yieldNow;
170 yield* Ref.set(state.quitting, true);
171 yield* requestDesktopShutdownAndWait();
172 if (environment.isDevelopment) {
173 yield* electronApp.exit(75);
174 return;
175 }
176 yield* electronApp.relaunch({
177 execPath: process.execPath,
178 args: process.argv.slice(1),
179 });
180 yield* electronApp.exit(0);
181 }).pipe(
182 Effect.catchCause((cause) => {
183 const error = new DesktopLifecycleRelaunchError({ reason, cause });
184 return logLifecycleError(error.message, { error });
185 }),
186 Effect.forkDetach,
187 Effect.asVoid,
188 );
189 }),
190 register: Effect.gen(function* () {
191 const desktopWindow = yield* DesktopWindow.DesktopWindow;
192 const electronWindow = yield* ElectronWindow.ElectronWindow;
193 const electronApp = yield* ElectronApp.ElectronApp;
194 const electronTheme = yield* ElectronTheme.ElectronTheme;
195 const environment = yield* DesktopEnvironment.DesktopEnvironment;
196 const context = yield* Effect.context<DesktopLifecycleRegistrationServices>();
197 const runEffect = Effect.runPromiseWith(context);
198 let quitAllowed = false;
199 let updaterQuitAllowed = false;
200 yield* electronTheme.onUpdated(() => {
201 void runEffect(
202 desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
203 );
204 });
205 yield* electronApp.onBeforeQuitForUpdate(() => {
206 // Electron's updater owns the remaining quit/install/relaunch sequence.
207 // Cancelling the following app "before-quit" event breaks that sequence,
208 // most visibly on macOS where the native updater performs the relaunch.
209 updaterQuitAllowed = true;
210 // This event is synchronous and the updater's quit proceeds as soon as
211 // the listener returns, so a forked destroyAll would race the quit
212 // and windows could still be open when the process exits (visible on
213 // macOS). Destroy them inline.
214 Effect.runSyncWith(context)(
215 electronWindow.destroyAll.pipe(
216 Effect.andThen(logLifecycleInfo("allowing updater-controlled quit")),
217 Effect.catchCause((cause) =>
218 logLifecycleError("failed to destroy windows before updater quit", { cause }),
219 ),
220 Effect.withSpan("desktop.lifecycle.beforeQuitForUpdate"),
221 ),
222 );
223 });
224 yield* electronApp.on("before-quit", (event: Electron.Event) => {
225 handleBeforeQuit(
226 event,
227 runEffect,
228 () => quitAllowed || updaterQuitAllowed,
229 () => {
230 quitAllowed = true;
231 },
232 );
233 });
234 yield* electronApp.on("activate", () => {
235 void runEffect(
236 Effect.gen(function* () {
237 const state = yield* DesktopState.DesktopState;
238 if (yield* Ref.get(state.quitting)) return;
239 yield* desktopWindow.activate;
240 }).pipe(Effect.withSpan("desktop.lifecycle.activate")),
241 );
242 });
243 yield* electronApp.on("window-all-closed", () => {
244 void runEffect(
245 Effect.gen(function* () {
246 const app = yield* ElectronApp.ElectronApp;
247 const state = yield* DesktopState.DesktopState;
248 if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
249 yield* app.quit;
250 }
251 }).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
252 );
253 });
254​
255 if (environment.platform !== "win32") {
256 yield* addScopedListener(process, "SIGINT", () => {
257 quitFromSignal("SIGINT", runEffect);
258 });
259 yield* addScopedListener(process, "SIGTERM", () => {
260 quitFromSignal("SIGTERM", runEffect);
261 });
262 }
263 }).pipe(Effect.withSpan("desktop.lifecycle.register")),
264});
265​
266export const layer = Layer.succeed(DesktopLifecycle, make);