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