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<void, never, DesktopShutdown.DesktopShutdown> {
77 const shutdown = yield* DesktopShutdown.DesktopShutdown;
78 yield* shutdown.request;
79 yield* shutdown.awaitComplete;
80 },
81);
82
83function handleBeforeQuit(
84 event: Electron.Event,
85 runEffect: <A, E>(effect: Effect.Effect<A, E, DesktopLifecycleRuntimeServices>) => Promise<A>,
86 allowQuit: () => boolean,
87 markQuitAllowed: () => void,
88): void {
89 if (allowQuit()) {
90 void runEffect(
91 Effect.gen(function* () {
92 const state = yield* DesktopState.DesktopState;
93 yield* Ref.set(state.quitting, true);
94 yield* logLifecycleInfo("before-quit received");
95 }).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")),
96 );
97 return;
98 }
99
100 event.preventDefault();
101 void runEffect(
102 Effect.gen(function* () {
103 const state = yield* DesktopState.DesktopState;
104 yield* Ref.set(state.quitting, true);
105 yield* logLifecycleInfo("before-quit received");
106 yield* requestDesktopShutdownAndWait();
107 }).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")),
108 ).finally(() => {
109 markQuitAllowed();
110 void runEffect(
111 Effect.gen(function* () {
112 const electronApp = yield* ElectronApp.ElectronApp;
113 yield* electronApp.quit;
114 }).pipe(Effect.withSpan("desktop.lifecycle.quitAfterShutdown")),
115 );
116 });
117}
118
119function quitFromSignal(
120 signal: "SIGINT" | "SIGTERM",
121 runEffect: <A, E>(effect: Effect.Effect<A, E, DesktopLifecycleRuntimeServices>) => Promise<A>,
122): void {
123 void runEffect(
124 Effect.gen(function* () {
125 yield* Effect.annotateCurrentSpan({ signal });
126 const electronApp = yield* ElectronApp.ElectronApp;
127 const state = yield* DesktopState.DesktopState;
128 const wasQuitting = yield* Ref.getAndSet(state.quitting, true);
129 if (wasQuitting) return;
130 yield* logLifecycleInfo("process signal received", { signal });
131 yield* requestDesktopShutdownAndWait();
132 yield* electronApp.quit;
133 }).pipe(Effect.withSpan("desktop.lifecycle.processSignal")),
134 );
135}
136
137export const make = DesktopLifecycle.of({
138 relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
139 const electronApp = yield* ElectronApp.ElectronApp;
140 const environment = yield* DesktopEnvironment.DesktopEnvironment;
141 const state = yield* DesktopState.DesktopState;
142 yield* logLifecycleInfo("desktop relaunch requested", { reason });
143 yield* Effect.gen(function* () {
144 yield* Effect.yieldNow;
145 yield* Ref.set(state.quitting, true);
146 yield* requestDesktopShutdownAndWait();
147 if (environment.isDevelopment) {
148 yield* electronApp.exit(75);
149 return;
150 }
151 yield* electronApp.relaunch({
152 execPath: process.execPath,
153 args: process.argv.slice(1),
154 });
155 yield* electronApp.exit(0);
156 }).pipe(
157 Effect.catchCause((cause) => {
158 const error = new DesktopLifecycleRelaunchError({ reason, cause });
159 return logLifecycleError(error.message, { error });
160 }),
161 Effect.forkDetach,
162 Effect.asVoid,
163 );
164 }),
165 register: Effect.gen(function* () {
166 const desktopWindow = yield* DesktopWindow.DesktopWindow;
167 const electronApp = yield* ElectronApp.ElectronApp;
168 const electronTheme = yield* ElectronTheme.ElectronTheme;
169 const environment = yield* DesktopEnvironment.DesktopEnvironment;
170 const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
171 const runEffect = Effect.runPromiseWith(context);
172 let quitAllowed = false;
173 yield* electronTheme.onUpdated(() => {
174 void runEffect(
175 desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
176 );
177 });
178 yield* electronApp.on("before-quit", (event: Electron.Event) => {
179 handleBeforeQuit(
180 event,
181 runEffect,
182 () => quitAllowed,
183 () => {
184 quitAllowed = true;
185 },
186 );
187 });
188 yield* electronApp.on("activate", () => {
189 void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
190 });
191 yield* electronApp.on("window-all-closed", () => {
192 void runEffect(
193 Effect.gen(function* () {
194 const app = yield* ElectronApp.ElectronApp;
195 const state = yield* DesktopState.DesktopState;
196 if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
197 yield* app.quit;
198 }
199 }).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
200 );
201 });
202
203 if (environment.platform !== "win32") {
204 yield* addScopedListener(process, "SIGINT", () => {
205 quitFromSignal("SIGINT", runEffect);
206 });
207 yield* addScopedListener(process, "SIGTERM", () => {
208 quitFromSignal("SIGTERM", runEffect);
209 });
210 }
211 }).pipe(Effect.withSpan("desktop.lifecycle.register")),
212});
213
214export const layer = Layer.succeed(DesktopLifecycle, make);