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 type { DesktopUpdateChannel } from "@t3tools/contracts";
8import * as Electron from "electron";
9import { msg } from "gt-i18n";
10
11import { makeComponentLogger } from "../app/DesktopObservability.ts";
12import * as ElectronApp from "../electron/ElectronApp.ts";
13import * as ElectronDialog from "../electron/ElectronDialog.ts";
14import * as ElectronMenu from "../electron/ElectronMenu.ts";
15import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
16import { applyLanguage, m, onLocaleChange } from "../i18n/messages.ts";
17import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
18import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
19import * as DesktopWindow from "./DesktopWindow.ts";
20
21export class DesktopApplicationMenuActionError extends Schema.TaggedError<DesktopApplicationMenuActionError>()(
22 "DesktopApplicationMenuActionError",
23 {
24 action: Schema.String,
25 cause: Schema.Defect(),
26 },
27) {
28 override get message(): string {
29 return `Desktop menu action "${this.action}" failed.`;
30 }
31}
32
33export class DesktopApplicationMenu extends Context.Service<
34 DesktopApplicationMenu,
35 {
36 readonly configure: Effect.Effect<void>;
37 }
38>()("@t3tools/desktop/window/DesktopApplicationMenu") {}
39
40type DesktopApplicationMenuRuntimeServices =
41 | DesktopUpdates.DesktopUpdates
42 | DesktopWindow.DesktopWindow
43 | ElectronDialog.ElectronDialog;
44
45const { logInfo: logUpdaterInfo } = makeComponentLogger("desktop-updater");
46
47const { logError: logMenuError } = makeComponentLogger("desktop-menu");
48
49const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function* (
50 action: string,
51): Effect.fn.Return<void, DesktopWindow.DesktopWindowError, DesktopWindow.DesktopWindow> {
52 const desktopWindow = yield* DesktopWindow.DesktopWindow;
53 yield* desktopWindow.dispatchMenuAction(action, {
54 reveal: action !== "paste-as-text",
55 });
56});
57
58const zoomMainWindow = Effect.fn("desktop.menu.zoomMainWindow")(function* (
59 direction: DesktopWindow.MainWindowZoomDirection,
60): Effect.fn.Return<void, never, DesktopWindow.DesktopWindow> {
61 const desktopWindow = yield* DesktopWindow.DesktopWindow;
62 yield* desktopWindow.zoomMain(direction);
63});
64
65const runMainContentsCommand = Effect.fn("desktop.menu.runMainContentsCommand")(function* (
66 command: DesktopWindow.MainWindowContentsCommand,
67): Effect.fn.Return<void, never, DesktopWindow.DesktopWindow> {
68 const desktopWindow = yield* DesktopWindow.DesktopWindow;
69 yield* desktopWindow.runMainContentsCommand(command);
70});
71
72const trackLabel = (channel: DesktopUpdateChannel) =>
73 channel === "nightly"
74 ? m(msg("Nightly", { $context: "release track" }))
75 : m(msg("Stable", { $context: "release track" }));
76
77const checkForUpdatesFromMenu = Effect.gen(function* () {
78 const updates = yield* DesktopUpdates.DesktopUpdates;
79 const electronDialog = yield* ElectronDialog.ElectronDialog;
80 const result = yield* updates.check("menu");
81 const updateState = result.state;
82
83 if (updateState.status === "up-to-date") {
84 yield* electronDialog.showMessageBox({
85 type: "info",
86 title: m(msg("You're up to date!")),
87 message: m(msg("T3 Code {version} is currently the newest version available."), {
88 version: updateState.currentVersion,
89 }),
90 buttons: [m(msg("OK"))],
91 });
92 } else if (updateState.status === "available") {
93 const { response } = yield* electronDialog.showMessageBox({
94 type: "info",
95 title: m(msg("Update available")),
96 message:
97 updateState.availableVersion === null
98 ? m(msg("A new version of T3 Code is available."))
99 : m(msg("T3 Code {version} is available."), { version: updateState.availableVersion }),
100 detail: m(msg("You're running T3 Code {version}."), {
101 version: updateState.currentVersion,
102 }),
103 buttons: [
104 m(msg("Download", { $context: "button, downloads an app update" })),
105 m(msg("Later")),
106 ],
107 defaultId: 0,
108 cancelId: 1,
109 });
110 if (response === 0) yield* updates.download;
111 } else if (updateState.status === "downloading") {
112 yield* electronDialog.showMessageBox({
113 type: "info",
114 title: m(msg("Update downloading")),
115 message:
116 updateState.availableVersion === null
117 ? m(msg("A new version of T3 Code is already downloading."))
118 : m(msg("T3 Code {version} is already downloading."), {
119 version: updateState.availableVersion,
120 }),
121 buttons: [m(msg("OK"))],
122 });
123 } else if (updateState.status === "downloaded") {
124 const version = updateState.downloadedVersion ?? updateState.availableVersion;
125 const { response } = yield* electronDialog.showMessageBox({
126 type: "info",
127 title: m(msg("Update ready")),
128 message:
129 version === null
130 ? m(msg("A new version of T3 Code is ready to install."))
131 : m(msg("T3 Code {version} is ready to install."), { version }),
132 detail: m(msg("T3 Code will restart to install it. Any running tasks will be interrupted.")),
133 buttons: [m(msg("Restart", { $context: "button, restarts the app" })), m(msg("Later"))],
134 defaultId: 0,
135 cancelId: 1,
136 });
137 if (response === 0) yield* updates.install;
138 } else if (updateState.status === "error") {
139 yield* electronDialog.showMessageBox({
140 type: "warning",
141 title: m(msg("Update check failed")),
142 message: m(msg("Could not check for updates.")),
143 detail:
144 updateState.trackMismatch !== undefined
145 ? m(
146 msg(
147 "This {build} build can't update from the {saved} track on its own. Switch the update track back to {build}, or use Review beside Update track to retry the switch to {saved}.",
148 ),
149 {
150 build: trackLabel(updateState.trackMismatch.buildChannel),
151 saved: trackLabel(updateState.channel),
152 },
153 )
154 : (updateState.message ?? m(msg("An unknown error occurred. Please try again later."))),
155 buttons: [m(msg("OK"))],
156 });
157 }
158}).pipe(Effect.withSpan("desktop.menu.checkForUpdates"));
159
160const handleCheckForUpdatesMenuClick = Effect.gen(function* () {
161 const updates = yield* DesktopUpdates.DesktopUpdates;
162 const electronDialog = yield* ElectronDialog.ElectronDialog;
163 const disabledReason = yield* updates.disabledReason;
164 if (Option.isSome(disabledReason)) {
165 yield* logUpdaterInfo("manual update check requested, but updates are disabled", {
166 disabledReason: disabledReason.value,
167 });
168 yield* electronDialog.showMessageBox({
169 type: "info",
170 title: m(msg("Updates unavailable")),
171 message: m(msg("Automatic updates are not available right now.")),
172 detail: disabledReason.value,
173 buttons: [m(msg("OK"))],
174 });
175 return;
176 }
177
178 // Opening a window before backend confirmation can strand it on failed auth bootstrap.
179 const desktopWindow = yield* DesktopWindow.DesktopWindow;
180 yield* desktopWindow.activate;
181 yield* checkForUpdatesFromMenu;
182}).pipe(Effect.withSpan("desktop.menu.handleCheckForUpdatesClick"));
183
184/** @public */
185export const make = Effect.gen(function* () {
186 const electronMenu = yield* ElectronMenu.ElectronMenu;
187 const environment = yield* DesktopEnvironment.DesktopEnvironment;
188 const electronApp = yield* ElectronApp.ElectronApp;
189 const clientSettings = yield* Effect.serviceOption(DesktopClientSettings.DesktopClientSettings);
190 const context = yield* Effect.context<DesktopApplicationMenuRuntimeServices>();
191 const runPromise = Effect.runPromiseWith(context);
192 const runFork = Effect.runForkWith(context);
193 const runSync = Effect.runSyncWith(context);
194
195 const runMenuEffect = <E>(
196 action: string,
197 effect: Effect.Effect<void, E, DesktopApplicationMenuRuntimeServices>,
198 ) => {
199 void runPromise(
200 effect.pipe(
201 Effect.annotateLogs({ action }),
202 Effect.withSpan("desktop.menu.action"),
203 Effect.catchCause((cause) => {
204 const error = new DesktopApplicationMenuActionError({ action, cause });
205 return logMenuError(error.message, { error });
206 }),
207 ),
208 );
209 };
210
211 const configure = Effect.gen(function* () {
212 const checkForUpdatesClick = () => {
213 runMenuEffect("check-for-updates", handleCheckForUpdatesMenuClick);
214 };
215 const settingsClick = () => {
216 runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
217 };
218 const pasteAsTextClick = (
219 _item: Electron.MenuItem,
220 _window: Electron.BaseWindow | undefined,
221 event: Electron.KeyboardEvent,
222 ) => {
223 if (event.triggeredByAccelerator === true) {
224 // Chromium pastes this chord itself except on macOS. Paste synchronously there:
225 // a renderer round trip can land after the terminal's own clipboard read.
226 if (environment.platform === "darwin") {
227 runSync(electronMenu.pasteAndMatchStyle);
228 }
229 return;
230 }
231 runMenuEffect("paste-as-text", dispatchMenuAction("paste-as-text"));
232 };
233 const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => {
234 runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction));
235 };
236 const mainContentsClick = (command: DesktopWindow.MainWindowContentsCommand) => () => {
237 runMenuEffect(command, runMainContentsCommand(command));
238 };
239 const template: Electron.MenuItemConstructorOptions[] = [];
240
241 if (environment.platform === "darwin") {
242 template.push({
243 label: environment.displayName,
244 submenu: [
245 { role: "about", label: m(msg("About {appName}"), { appName: environment.displayName }) },
246 {
247 label: m(msg("Check for Updates...")),
248 click: checkForUpdatesClick,
249 },
250 { type: "separator" },
251 {
252 label: m(msg("Settings...")),
253 accelerator: "CmdOrCtrl+,",
254 click: settingsClick,
255 },
256 { type: "separator" },
257 { role: "services", label: m(msg("Services", { $context: "macOS app menu item" })) },
258 { type: "separator" },
259 { role: "hide", label: m(msg("Hide {appName}"), { appName: environment.displayName }) },
260 { role: "hideOthers", label: m(msg("Hide Others")) },
261 {
262 role: "unhide",
263 label: m(msg("Show All", { $context: "macOS app menu item, shows hidden apps" })),
264 },
265 { type: "separator" },
266 { role: "quit", label: m(msg("Quit {appName}"), { appName: environment.displayName }) },
267 ],
268 });
269 }
270
271 template.push(
272 {
273 label: m(msg("File", { $context: "menu bar title" })),
274 submenu: [
275 ...(environment.platform === "darwin"
276 ? []
277 : [
278 {
279 label: m(msg("Settings...")),
280 accelerator: "CmdOrCtrl+,",
281 click: settingsClick,
282 },
283 { type: "separator" as const },
284 ]),
285 {
286 label: m(msg("Close Developer Tools")),
287 accelerator: "CmdOrCtrl+W",
288 visible: false,
289 click: () => {
290 Electron.webContents
291 .getAllWebContents()
292 .find((contents) => !contents.isDestroyed() && contents.isDevToolsFocused())
293 ?.closeDevTools();
294 },
295 },
296 // Cmd/Ctrl+W belongs to the renderer's tab close; it must never close the window.
297 environment.platform === "darwin"
298 ? { label: m(msg("Close Window")), click: (_item, window) => window?.close() }
299 : {
300 role: "quit",
301 label:
302 environment.platform === "win32"
303 ? m(msg("Exit", { $context: "File menu item, quits the app" }))
304 : m(msg("Quit")),
305 },
306 ],
307 },
308 {
309 label: m(msg("Edit", { $context: "menu bar title" })),
310 submenu: [
311 { role: "undo", label: m(msg("Undo", { $context: "Edit menu item" })) },
312 { role: "redo", label: m(msg("Redo", { $context: "Edit menu item" })) },
313 { type: "separator" },
314 { role: "cut", label: m(msg("Cut", { $context: "Edit menu item" })) },
315 { role: "copy", label: m(msg("Copy", { $context: "Edit menu item" })) },
316 { role: "paste", label: m(msg("Paste", { $context: "Edit menu item" })) },
317 {
318 label: m(msg("Paste as Text")),
319 accelerator: "CmdOrCtrl+Shift+V",
320 click: pasteAsTextClick,
321 },
322 { role: "delete", label: m(msg("Delete", { $context: "Edit menu item" })) },
323 { type: "separator" },
324 { role: "selectAll", label: m(msg("Select All", { $context: "Edit menu item" })) },
325 ...(environment.platform === "darwin"
326 ? [
327 { type: "separator" as const },
328 {
329 label: m(msg("Speech", { $context: "menu, text-to-speech" })),
330 submenu: [
331 { role: "startSpeaking" as const, label: m(msg("Start Speaking")) },
332 { role: "stopSpeaking" as const, label: m(msg("Stop Speaking")) },
333 ],
334 },
335 ]
336 : []),
337 ],
338 },
339 {
340 label: m(msg("View", { $context: "menu bar title" })),
341 submenu: [
342 /* Native reload/DevTools/zoom roles target focused guests; these commands must target the app. */
343 {
344 label: m(msg("Reload")),
345 accelerator: "CmdOrCtrl+R",
346 click: mainContentsClick("reload"),
347 },
348 {
349 label: m(msg("Force Reload")),
350 accelerator: "Shift+CmdOrCtrl+R",
351 click: mainContentsClick("forceReload"),
352 },
353 {
354 label: m(msg("Toggle Developer Tools")),
355 accelerator: environment.platform === "darwin" ? "Alt+Command+I" : "Ctrl+Shift+I",
356 click: mainContentsClick("toggleDevTools"),
357 },
358 { type: "separator" },
359 { label: m(msg("Actual Size")), accelerator: "CmdOrCtrl+0", click: zoomClick("reset") },
360 { label: m(msg("Zoom In")), accelerator: "CmdOrCtrl+=", click: zoomClick("in") },
361 {
362 label: m(msg("Zoom In")),
363 accelerator: "CmdOrCtrl+Plus",
364 visible: false,
365 click: zoomClick("in"),
366 },
367 ...(environment.platform === "darwin"
368 ? [
369 {
370 label: m(msg("Zoom In")),
371 accelerator: "CmdOrCtrl+Shift+=",
372 visible: false,
373 click: zoomClick("in"),
374 },
375 ]
376 : []),
377 { label: m(msg("Zoom Out")), accelerator: "CmdOrCtrl+-", click: zoomClick("out") },
378 // Keypad codes do not match number-row accelerators.
379 {
380 label: m(msg("Actual Size")),
381 accelerator: "CmdOrCtrl+num0",
382 visible: false,
383 click: zoomClick("reset"),
384 },
385 {
386 label: m(msg("Zoom In")),
387 accelerator: "CmdOrCtrl+numadd",
388 visible: false,
389 click: zoomClick("in"),
390 },
391 {
392 label: m(msg("Zoom Out")),
393 accelerator: "CmdOrCtrl+numsub",
394 visible: false,
395 click: zoomClick("out"),
396 },
397 { type: "separator" },
398 { role: "togglefullscreen", label: m(msg("Toggle Full Screen")) },
399 ],
400 },
401 {
402 // Electron's default Window submenu adds a Ctrl+W close role off macOS.
403 role: "windowMenu",
404 label: m(msg("Window", { $context: "menu bar title" })),
405 submenu: [
406 { role: "minimize", label: m(msg("Minimize", { $context: "Window menu item" })) },
407 {
408 role: "zoom",
409 label: m(msg("Zoom", { $context: "Window menu item, resizes the window" })),
410 },
411 ...(environment.platform === "darwin"
412 ? [
413 { type: "separator" as const },
414 { role: "front" as const, label: m(msg("Bring All to Front")) },
415 ]
416 : []),
417 ],
418 },
419 {
420 role: "help",
421 label: m(msg("Help", { $context: "menu bar title" })),
422 submenu: [
423 {
424 label: m(msg("Check for Updates...")),
425 click: checkForUpdatesClick,
426 },
427 ],
428 },
429 );
430
431 yield* electronMenu.setApplicationMenu(template);
432 }).pipe(Effect.withSpan("desktop.menu.configure"));
433
434 // Load the saved language before the first build so the menu never starts in English.
435 const applySavedLanguage = Effect.gen(function* () {
436 if (Option.isNone(clientSettings)) return;
437 const saved = yield* clientSettings.value.get.pipe(Effect.orElseSucceed(() => Option.none()));
438 if (Option.isSome(saved)) {
439 yield* applyLanguage(saved.value.language).pipe(
440 Effect.provideService(ElectronApp.ElectronApp, electronApp),
441 );
442 }
443 });
444
445 let rebuildsOnLocaleChange = false;
446 return DesktopApplicationMenu.of({
447 configure: applySavedLanguage.pipe(
448 Effect.andThen(configure),
449 Effect.tap(() =>
450 Effect.sync(() => {
451 if (rebuildsOnLocaleChange) return;
452 rebuildsOnLocaleChange = true;
453 onLocaleChange(() => runFork(configure));
454 }),
455 ),
456 ),
457 });
458});
459
460export const layer = Layer.effect(DesktopApplicationMenu, make);