Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopApplicationMenu.ts

447 lines17.1 KB

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