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 Option from "effect/Option";
5import * as Schema from "effect/Schema";
6
7import * as Electron from "electron";
8
9import { makeComponentLogger } from "../app/DesktopObservability.ts";
10import * as ElectronDialog from "../electron/ElectronDialog.ts";
11import * as ElectronMenu from "../electron/ElectronMenu.ts";
12import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
13import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
14import * as DesktopWindow from "./DesktopWindow.ts";
15
16export class DesktopApplicationMenuActionError extends Schema.TaggedError<DesktopApplicationMenuActionError>()(
17 "DesktopApplicationMenuActionError",
18 {
19 action: Schema.String,
20 cause: Schema.Defect(),
21 },
22) {
23 override get message(): string {
24 return `Desktop menu action "${this.action}" failed.`;
25 }
26}
27
28export class DesktopApplicationMenu extends Context.Service<
29 DesktopApplicationMenu,
30 {
31 readonly configure: Effect.Effect<void>;
32 }
33>()("@t3tools/desktop/window/DesktopApplicationMenu") {}
34
35type DesktopApplicationMenuRuntimeServices =
36 | DesktopUpdates.DesktopUpdates
37 | DesktopWindow.DesktopWindow
38 | ElectronDialog.ElectronDialog;
39
40const { logInfo: logUpdaterInfo } = makeComponentLogger("desktop-updater");
41
42const { logError: logMenuError } = makeComponentLogger("desktop-menu");
43
44const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function* (
45 action: string,
46): Effect.fn.Return<void, DesktopWindow.DesktopWindowError, DesktopWindow.DesktopWindow> {
47 const desktopWindow = yield* DesktopWindow.DesktopWindow;
48 yield* desktopWindow.dispatchMenuAction(action, {
49 reveal: action !== "paste-as-text",
50 });
51});
52
53const zoomMainWindow = Effect.fn("desktop.menu.zoomMainWindow")(function* (
54 direction: DesktopWindow.MainWindowZoomDirection,
55): Effect.fn.Return<void, never, DesktopWindow.DesktopWindow> {
56 const desktopWindow = yield* DesktopWindow.DesktopWindow;
57 yield* desktopWindow.zoomMain(direction);
58});
59
60const runMainContentsCommand = Effect.fn("desktop.menu.runMainContentsCommand")(function* (
61 command: DesktopWindow.MainWindowContentsCommand,
62): Effect.fn.Return<void, never, DesktopWindow.DesktopWindow> {
63 const desktopWindow = yield* DesktopWindow.DesktopWindow;
64 yield* desktopWindow.runMainContentsCommand(command);
65});
66
67const describeUpdate = (version: string | null) =>
68 version === null ? "A new version of T3 Code" : `T3 Code ${version}`;
69
70const checkForUpdatesFromMenu = Effect.gen(function* () {
71 const updates = yield* DesktopUpdates.DesktopUpdates;
72 const electronDialog = yield* ElectronDialog.ElectronDialog;
73 const result = yield* updates.check("menu");
74 const updateState = result.state;
75
76 if (updateState.status === "up-to-date") {
77 yield* electronDialog.showMessageBox({
78 type: "info",
79 title: "You're up to date!",
80 message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`,
81 buttons: ["OK"],
82 });
83 } else if (updateState.status === "available") {
84 const { response } = yield* electronDialog.showMessageBox({
85 type: "info",
86 title: "Update available",
87 message: `${describeUpdate(updateState.availableVersion)} is available.`,
88 detail: `You're running T3 Code ${updateState.currentVersion}.`,
89 buttons: ["Download", "Later"],
90 defaultId: 0,
91 cancelId: 1,
92 });
93 if (response === 0) yield* updates.download;
94 } else if (updateState.status === "downloading") {
95 yield* electronDialog.showMessageBox({
96 type: "info",
97 title: "Update downloading",
98 message: `${describeUpdate(updateState.availableVersion)} is already downloading.`,
99 buttons: ["OK"],
100 });
101 } else if (updateState.status === "downloaded") {
102 const { response } = yield* electronDialog.showMessageBox({
103 type: "info",
104 title: "Update ready",
105 message: `${describeUpdate(updateState.downloadedVersion ?? updateState.availableVersion)} is ready to install.`,
106 detail: "T3 Code will restart to install it. Any running tasks will be interrupted.",
107 buttons: ["Restart", "Later"],
108 defaultId: 0,
109 cancelId: 1,
110 });
111 if (response === 0) yield* updates.install;
112 } else if (updateState.status === "error") {
113 yield* electronDialog.showMessageBox({
114 type: "warning",
115 title: "Update check failed",
116 message: "Could not check for updates.",
117 detail: updateState.message ?? "An unknown error occurred. Please try again later.",
118 buttons: ["OK"],
119 });
120 }
121}).pipe(Effect.withSpan("desktop.menu.checkForUpdates"));
122
123const handleCheckForUpdatesMenuClick = Effect.gen(function* () {
124 const updates = yield* DesktopUpdates.DesktopUpdates;
125 const electronDialog = yield* ElectronDialog.ElectronDialog;
126 const disabledReason = yield* updates.disabledReason;
127 if (Option.isSome(disabledReason)) {
128 yield* logUpdaterInfo("manual update check requested, but updates are disabled", {
129 disabledReason: disabledReason.value,
130 });
131 yield* electronDialog.showMessageBox({
132 type: "info",
133 title: "Updates unavailable",
134 message: "Automatic updates are not available right now.",
135 detail: disabledReason.value,
136 buttons: ["OK"],
137 });
138 return;
139 }
140
141 // Opening a window before backend confirmation can strand it on failed auth bootstrap.
142 const desktopWindow = yield* DesktopWindow.DesktopWindow;
143 yield* desktopWindow.activate;
144 yield* checkForUpdatesFromMenu;
145}).pipe(Effect.withSpan("desktop.menu.handleCheckForUpdatesClick"));
146
147/** @public */
148export const make = Effect.gen(function* () {
149 const electronMenu = yield* ElectronMenu.ElectronMenu;
150 const environment = yield* DesktopEnvironment.DesktopEnvironment;
151 const context = yield* Effect.context<DesktopApplicationMenuRuntimeServices>();
152 const runPromise = Effect.runPromiseWith(context);
153
154 const runMenuEffect = <E>(
155 action: string,
156 effect: Effect.Effect<void, E, DesktopApplicationMenuRuntimeServices>,
157 ) => {
158 void runPromise(
159 effect.pipe(
160 Effect.annotateLogs({ action }),
161 Effect.withSpan("desktop.menu.action"),
162 Effect.catchCause((cause) => {
163 const error = new DesktopApplicationMenuActionError({ action, cause });
164 return logMenuError(error.message, { error });
165 }),
166 ),
167 );
168 };
169
170 const configure = Effect.gen(function* () {
171 const checkForUpdatesClick = () => {
172 runMenuEffect("check-for-updates", handleCheckForUpdatesMenuClick);
173 };
174 const settingsClick = () => {
175 runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
176 };
177 // Chromium and the renderer already handle this chord; injecting another paste duplicates text.
178 const pasteAsTextClick = (
179 _item: Electron.MenuItem,
180 _window: Electron.BaseWindow | undefined,
181 event: Electron.KeyboardEvent,
182 ) => {
183 if (event.triggeredByAccelerator === true) return;
184 runMenuEffect("paste-as-text", dispatchMenuAction("paste-as-text"));
185 };
186 const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => {
187 runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction));
188 };
189 const mainContentsClick = (command: DesktopWindow.MainWindowContentsCommand) => () => {
190 runMenuEffect(command, runMainContentsCommand(command));
191 };
192 const template: Electron.MenuItemConstructorOptions[] = [];
193
194 if (environment.platform === "darwin") {
195 template.push({
196 label: environment.displayName,
197 submenu: [
198 { role: "about", label: `About ${environment.displayName}` },
199 {
200 label: "Check for Updates...",
201 click: checkForUpdatesClick,
202 },
203 { type: "separator" },
204 {
205 label: "Settings...",
206 accelerator: "CmdOrCtrl+,",
207 click: settingsClick,
208 },
209 { type: "separator" },
210 { role: "services" },
211 { type: "separator" },
212 { role: "hide", label: `Hide ${environment.displayName}` },
213 { role: "hideOthers" },
214 { role: "unhide" },
215 { type: "separator" },
216 { role: "quit", label: `Quit ${environment.displayName}` },
217 ],
218 });
219 }
220
221 template.push(
222 {
223 label: "File",
224 submenu: [
225 ...(environment.platform === "darwin"
226 ? []
227 : [
228 {
229 label: "Settings...",
230 accelerator: "CmdOrCtrl+,",
231 click: settingsClick,
232 },
233 { type: "separator" as const },
234 ]),
235 {
236 label: "Close Developer Tools",
237 accelerator: "CmdOrCtrl+W",
238 visible: false,
239 click: () => {
240 Electron.webContents
241 .getAllWebContents()
242 .find((contents) => !contents.isDestroyed() && contents.isDevToolsFocused())
243 ?.closeDevTools();
244 },
245 },
246 // Cmd/Ctrl+W belongs to the renderer's tab close; it must never close the window.
247 environment.platform === "darwin"
248 ? { label: "Close Window", click: (_item, window) => window?.close() }
249 : { role: "quit" },
250 ],
251 },
252 {
253 label: "Edit",
254 submenu: [
255 { role: "undo" },
256 { role: "redo" },
257 { type: "separator" },
258 { role: "cut" },
259 { role: "copy" },
260 { role: "paste" },
261 {
262 label: "Paste as Text",
263 accelerator: "CmdOrCtrl+Shift+V",
264 click: pasteAsTextClick,
265 },
266 { role: "delete" },
267 { type: "separator" },
268 { role: "selectAll" },
269 ...(environment.platform === "darwin"
270 ? [
271 { type: "separator" as const },
272 {
273 label: "Speech",
274 submenu: [{ role: "startSpeaking" as const }, { role: "stopSpeaking" as const }],
275 },
276 ]
277 : []),
278 ],
279 },
280 {
281 label: "View",
282 submenu: [
283 /* Native reload/DevTools/zoom roles target focused guests; these commands must target the app. */
284 { label: "Reload", accelerator: "CmdOrCtrl+R", click: mainContentsClick("reload") },
285 {
286 label: "Force Reload",
287 accelerator: "Shift+CmdOrCtrl+R",
288 click: mainContentsClick("forceReload"),
289 },
290 {
291 label: "Toggle Developer Tools",
292 accelerator: environment.platform === "darwin" ? "Alt+Command+I" : "Ctrl+Shift+I",
293 click: mainContentsClick("toggleDevTools"),
294 },
295 { type: "separator" },
296 { label: "Actual Size", accelerator: "CmdOrCtrl+0", click: zoomClick("reset") },
297 { label: "Zoom In", accelerator: "CmdOrCtrl+=", click: zoomClick("in") },
298 {
299 label: "Zoom In",
300 accelerator: "CmdOrCtrl+Plus",
301 visible: false,
302 click: zoomClick("in"),
303 },
304 ...(environment.platform === "darwin"
305 ? [
306 {
307 label: "Zoom In",
308 accelerator: "CmdOrCtrl+Shift+=",
309 visible: false,
310 click: zoomClick("in"),
311 },
312 ]
313 : []),
314 { label: "Zoom Out", accelerator: "CmdOrCtrl+-", click: zoomClick("out") },
315 // Keypad codes do not match number-row accelerators.
316 {
317 label: "Actual Size",
318 accelerator: "CmdOrCtrl+num0",
319 visible: false,
320 click: zoomClick("reset"),
321 },
322 {
323 label: "Zoom In",
324 accelerator: "CmdOrCtrl+numadd",
325 visible: false,
326 click: zoomClick("in"),
327 },
328 {
329 label: "Zoom Out",
330 accelerator: "CmdOrCtrl+numsub",
331 visible: false,
332 click: zoomClick("out"),
333 },
334 { type: "separator" },
335 { role: "togglefullscreen" },
336 ],
337 },
338 {
339 // Electron's default Window submenu adds a Ctrl+W close role off macOS.
340 role: "windowMenu",
341 submenu: [
342 { role: "minimize" },
343 { role: "zoom" },
344 ...(environment.platform === "darwin"
345 ? [{ type: "separator" as const }, { role: "front" as const }]
346 : []),
347 ],
348 },
349 {
350 role: "help",
351 submenu: [
352 {
353 label: "Check for Updates...",
354 click: checkForUpdatesClick,
355 },
356 ],
357 },
358 );
359
360 yield* electronMenu.setApplicationMenu(template);
361 }).pipe(Effect.withSpan("desktop.menu.configure"));
362
363 return DesktopApplicationMenu.of({
364 configure,
365 });
366});
367
368export const layer = Layer.effect(DesktopApplicationMenu, make);