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 "t3/desktop/Shutdown",
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
64export class DesktopLifecycle extends Context.Service<DesktopLifecycle, DesktopLifecycleShape>()(
65 "t3/desktop/Lifecycle",
66) {}
67
68const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
69 DesktopObservability.makeComponentLogger("desktop-lifecycle");
70
71function addScopedListener<Args extends ReadonlyArray<unknown>>(
72 target: unknown,
73 eventName: string,
74 listener: (...args: Args) => void,
75): Effect.Effect<void, never, Scope.Scope> {
76 const eventTarget = target as {
77 on: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown;
78 removeListener: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown;
79 };
80 const untypedListener = listener as unknown as (...args: Array<unknown>) => void;
81 return Effect.acquireRelease(
82 Effect.sync(() => {
83 eventTarget.on(eventName, untypedListener);
84 }),
85 () =>
86 Effect.sync(() => {
87 eventTarget.removeListener(eventName, untypedListener);
88 }),
89 ).pipe(Effect.asVoid);
90}
91
92const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
93 function* (): Effect.fn.Return<void, never, DesktopShutdown> {
94 const shutdown = yield* DesktopShutdown;
95 yield* shutdown.request;
96 yield* shutdown.awaitComplete;
97 },
98);
99
100function handleBeforeQuit(
101 event: Electron.Event,
102 runEffect: <A, E>(effect: Effect.Effect<A, E, DesktopLifecycleRuntimeServices>) => Promise<A>,
103 allowQuit: () => boolean,
104 markQuitAllowed: () => void,
105): void {
106 if (allowQuit()) {
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 }).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")),
113 );
114 return;
115 }
116
117 event.preventDefault();
118 void runEffect(
119 Effect.gen(function* () {
120 const state = yield* DesktopState.DesktopState;
121 yield* Ref.set(state.quitting, true);
122 yield* logLifecycleInfo("before-quit received");
123 yield* requestDesktopShutdownAndWait();
124 }).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")),
125 ).finally(() => {
126 markQuitAllowed();
127 void runEffect(
128 Effect.gen(function* () {
129 const electronApp = yield* ElectronApp.ElectronApp;
130 yield* electronApp.quit;
131 }).pipe(Effect.withSpan("desktop.lifecycle.quitAfterShutdown")),
132 );
133 });
134}
135
136function quitFromSignal(
137 signal: "SIGINT" | "SIGTERM",
138 runEffect: <A, E>(effect: Effect.Effect<A, E, DesktopLifecycleRuntimeServices>) => Promise<A>,
139): void {
140 void runEffect(
141 Effect.gen(function* () {
142 yield* Effect.annotateCurrentSpan({ signal });
143 const electronApp = yield* ElectronApp.ElectronApp;
144 const state = yield* DesktopState.DesktopState;
145 const wasQuitting = yield* Ref.getAndSet(state.quitting, true);
146 if (wasQuitting) return;
147 yield* logLifecycleInfo("process signal received", { signal });
148 yield* requestDesktopShutdownAndWait();
149 yield* electronApp.quit;
150 }).pipe(Effect.withSpan("desktop.lifecycle.processSignal")),
151 );
152}
153
154export const layer = Layer.succeed(
155 DesktopLifecycle,
156 DesktopLifecycle.of({
157 relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
158 const electronApp = yield* ElectronApp.ElectronApp;
159 const environment = yield* DesktopEnvironment.DesktopEnvironment;
160 const state = yield* DesktopState.DesktopState;
161 yield* logLifecycleInfo("desktop relaunch requested", { reason });
162 yield* Effect.gen(function* () {
163 yield* Effect.yieldNow;
164 yield* Ref.set(state.quitting, true);
165 yield* requestDesktopShutdownAndWait();
166 if (environment.isDevelopment) {
167 yield* electronApp.exit(75);
168 return;
169 }
170 yield* electronApp.relaunch({
171 execPath: process.execPath,
172 args: process.argv.slice(1),
173 });
174 yield* electronApp.exit(0);
175 }).pipe(
176 Effect.catchCause((cause) =>
177 logLifecycleError("desktop relaunch failed", {
178 cause: Cause.pretty(cause),
179 }),
180 ),
181 Effect.forkDetach,
182 Effect.asVoid,
183 );
184 }),
185 register: Effect.gen(function* () {
186 const desktopWindow = yield* DesktopWindow.DesktopWindow;
187 const electronApp = yield* ElectronApp.ElectronApp;
188 const electronTheme = yield* ElectronTheme.ElectronTheme;
189 const environment = yield* DesktopEnvironment.DesktopEnvironment;
190 const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
191 const runEffect = Effect.runPromiseWith(context);
192 let quitAllowed = false;
193 yield* electronTheme.onUpdated(() => {
194 void runEffect(
195 desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
196 );
197 });
198 yield* electronApp.on("before-quit", (event: Electron.Event) => {
199 handleBeforeQuit(
200 event,
201 runEffect,
202 () => quitAllowed,
203 () => {
204 quitAllowed = true;
205 },
206 );
207 });
208 yield* electronApp.on("activate", () => {
209 void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
210 });
211 yield* electronApp.on("window-all-closed", () => {
212 void runEffect(
213 Effect.gen(function* () {
214 const app = yield* ElectronApp.ElectronApp;
215 const state = yield* DesktopState.DesktopState;
216 if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
217 yield* app.quit;
218 }
219 }).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
220 );
221 });
222
223 if (environment.platform !== "win32") {
224 yield* addScopedListener(process, "SIGINT", () => {
225 quitFromSignal("SIGINT", runEffect);
226 });
227 yield* addScopedListener(process, "SIGTERM", () => {
228 quitFromSignal("SIGTERM", runEffect);
229 });
230 }
231 }).pipe(Effect.withSpan("desktop.lifecycle.register")),
232 }),
233);