Open History to see the last commit
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 DesktopState from "./DesktopState.ts";
16import * as DesktopWindow from "../window/DesktopWindow.ts";
17
18export class DesktopLifecycleRelaunchError extends Schema.TaggedErrorClass<DesktopLifecycleRelaunchError>()(
19 "DesktopLifecycleRelaunchError",
20 {
21 reason: Schema.String,
22 cause: Schema.Defect(),
23 },
24) {
25 override get message(): string {
26 return `Desktop relaunch failed for reason "${this.reason}".`;
27 }
28}
29
30export type DesktopLifecycleRuntimeServices =
31 | DesktopEnvironment.DesktopEnvironment
32 | DesktopShutdown.DesktopShutdown
33 | DesktopState.DesktopState
34 | DesktopWindow.DesktopWindow
35 | ElectronApp.ElectronApp
36 | ElectronTheme.ElectronTheme;
37
38/**
39 * @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme
40 */
41export class DesktopLifecycle extends Context.Service<
42 DesktopLifecycle,
43 {
44 readonly relaunch: (
45 reason: string,
46 ) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
47 readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
48 }
49>()("@t3tools/desktop/app/DesktopLifecycle") {}
50
51const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
52 makeComponentLogger("desktop-lifecycle");
53
54function addScopedListener<Args extends ReadonlyArray<unknown>>(
55 target: unknown,
56 eventName: string,
57 listener: (...args: Args) => void,
58): Effect.Effect<void, never, Scope.Scope> {
59 const eventTarget = target as {
60 on: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown;
61 removeListener: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown;
62 };
63 const untypedListener = listener as unknown as (...args: Array<unknown>) => void;
64 return Effect.acquireRelease(
65 Effect.sync(() => {
66 eventTarget.on(eventName, untypedListener);
67 }),
68 () =>
69 Effect.sync(() => {
70 eventTarget.removeListener(eventName, untypedListener);
71 }),
72 ).pipe(Effect.asVoid);
73}
74
75const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
76 function* (): Effect.fn.Return<
77 void,
78 never,
79 DesktopShutdown.DesktopShutdown | DesktopWindow.DesktopWindow
80 > {
81 const shutdown = yield* DesktopShutdown.DesktopShutdown;
82 const desktopWindow = yield* DesktopWindow.DesktopWindow;
83 yield* desktopWindow.flushMainWindowBounds;
84 yield* shutdown.request;
85 yield* shutdown.awaitComplete;
86 },
87);
88
89function handleBeforeQuit(
90 event: Electron.Event,
91 runEffect: <A, E>(effect: Effect.Effect<A, E, DesktopLifecycleRuntimeServices>) => Promise<A>,
92 allowQuit: () => boolean,
93 markQuitAllowed: () => void,
94): void {
95 if (allowQuit()) {
96 void runEffect(
97 Effect.gen(function* () {
98 const state = yield* DesktopState.DesktopState;
99 yield* Ref.set(state.quitting, true);
100 yield* logLifecycleInfo("before-quit received");
101 }).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")),
102 );
103 return;
104 }
105
106 event.preventDefault();
107 void runEffect(
108 Effect.gen(function* () {
109 const state = yield* DesktopState.DesktopState;
110 yield* Ref.set(state.quitting, true);
111 yield* logLifecycleInfo("before-quit received");
112 yield* requestDesktopShutdownAndWait();
113 }).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")),
114 ).finally(() => {
115 markQuitAllowed();
116 void runEffect(
117 Effect.gen(function* () {
118 const electronApp = yield* ElectronApp.ElectronApp;
119 yield* electronApp.quit;
120 }).pipe(Effect.withSpan("desktop.lifecycle.quitAfterShutdown")),
121 );
122 });
123}
124
125function quitFromSignal(
126 signal: "SIGINT" | "SIGTERM",
127 runEffect: <A, E>(effect: Effect.Effect<A, E, DesktopLifecycleRuntimeServices>) => Promise<A>,
128): void {
129 void runEffect(
130 Effect.gen(function* () {
131 yield* Effect.annotateCurrentSpan({ signal });
132 const electronApp = yield* ElectronApp.ElectronApp;
133 const state = yield* DesktopState.DesktopState;
134 const wasQuitting = yield* Ref.getAndSet(state.quitting, true);
135 if (wasQuitting) return;
136 yield* logLifecycleInfo("process signal received", { signal });
137 yield* requestDesktopShutdownAndWait();
138 yield* electronApp.quit;
139 }).pipe(Effect.withSpan("desktop.lifecycle.processSignal")),
140 );
141}
142
143export const make = DesktopLifecycle.of({
144 relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
145 const electronApp = yield* ElectronApp.ElectronApp;
146 const environment = yield* DesktopEnvironment.DesktopEnvironment;
147 const state = yield* DesktopState.DesktopState;
148 yield* logLifecycleInfo("desktop relaunch requested", { reason });
149 yield* Effect.gen(function* () {
150 yield* Effect.yieldNow;
151 yield* Ref.set(state.quitting, true);
152 yield* requestDesktopShutdownAndWait();
153 if (environment.isDevelopment) {
154 yield* electronApp.exit(75);
155 return;
156 }
157 yield* electronApp.relaunch({
158 execPath: process.execPath,
159 args: process.argv.slice(1),
160 });
161 yield* electronApp.exit(0);
162 }).pipe(
163 Effect.catchCause((cause) => {
164 const error = new DesktopLifecycleRelaunchError({ reason, cause });
165 return logLifecycleError(error.message, { error });
166 }),
167 Effect.forkDetach,
168 Effect.asVoid,
169 );
170 }),
171 register: Effect.gen(function* () {
172 const desktopWindow = yield* DesktopWindow.DesktopWindow;
173 const electronApp = yield* ElectronApp.ElectronApp;
174 const electronTheme = yield* ElectronTheme.ElectronTheme;
175 const environment = yield* DesktopEnvironment.DesktopEnvironment;
176 const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
177 const runEffect = Effect.runPromiseWith(context);
178 let quitAllowed = false;
179 yield* electronTheme.onUpdated(() => {
180 void runEffect(
181 desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
182 );
183 });
184 yield* electronApp.on("before-quit", (event: Electron.Event) => {
185 handleBeforeQuit(
186 event,
187 runEffect,
188 () => quitAllowed,
189 () => {
190 quitAllowed = true;
191 },
192 );
193 });
194 yield* electronApp.on("activate", () => {
195 void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
196 });
197 yield* electronApp.on("window-all-closed", () => {
198 void runEffect(
199 Effect.gen(function* () {
200 const app = yield* ElectronApp.ElectronApp;
201 const state = yield* DesktopState.DesktopState;
202 if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
203 yield* app.quit;
204 }
205 }).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
206 );
207 });
208
209 if (environment.platform !== "win32") {
210 yield* addScopedListener(process, "SIGINT", () => {
211 quitFromSignal("SIGINT", runEffect);
212 });
213 yield* addScopedListener(process, "SIGTERM", () => {
214 quitFromSignal("SIGTERM", runEffect);
215 });
216 }
217 }).pipe(Effect.withSpan("desktop.lifecycle.register")),
218});
219
220export const layer = Layer.succeed(DesktopLifecycle, make);