Debian Codegraph @

ivette/src/dome/main/menubar.ts

raw
1 /* ************************************************************************ */
2 /* */
3 /* This file is part of Frama-C. */
4 /* */
5 /* Copyright (C) 2007-2022 */
6 /* CEA (Commissariat à l'énergie atomique et aux énergies */
7 /* alternatives) */
8 /* */
9 /* you can redistribute it and/or modify it under the terms of the GNU */
10 /* Lesser General Public License as published by the Free Software */
11 /* Foundation, version 2.1. */
12 /* */
13 /* It is distributed in the hope that it will be useful, */
14 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
15 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
16 /* GNU Lesser General Public License for more details. */
17 /* */
18 /* See the GNU Lesser General Public License version 2.1 */
19 /* for more details (enclosed in the file licenses/LGPLv2.1). */
20 /* */
21 /* ************************************************************************ */
22
23 /* eslint-disable @typescript-eslint/explicit-function-return-type */
24 /* eslint-disable no-console */
25
26 // --------------------------------------------------------------------------
27 // --- Menus & MenuBar Management
28 // --------------------------------------------------------------------------
29
30 import {
31 app,
32 ipcMain,
33 BrowserWindow,
34 Menu,
35 MenuItem,
36 shell,
37 KeyboardEvent,
38 } from 'electron';
39 import * as System from 'dome/system';
40
41 // --------------------------------------------------------------------------
42 // --- Special Callbacks
43 // --------------------------------------------------------------------------
44
45 function reloadWindow() {
46 reset(); // declared below
47 BrowserWindow.getAllWindows().forEach((win) => {
48 if (win) {
49 try {
50 win.webContents.send('dome.ipc.closing');
51 win.reload();
52 } catch (err) {
53 console.warn('[Reload]', win.id, err);
54 }
55 }
56 });
57 }
58
59 function toggleFullScreen(
60 _item: MenuItem,
61 focusedWindow: BrowserWindow | undefined,
62 _evt: KeyboardEvent,
63 ) {
64 if (focusedWindow)
65 focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
66 }
67
68 function toggleDevTools(
69 _item: MenuItem,
70 focusedWindow: BrowserWindow | undefined,
71 _evt: KeyboardEvent,
72 ) {
73 if (focusedWindow)
74 focusedWindow.webContents.toggleDevTools();
75 }
76
77 function userFindInfo(
78 _item: MenuItem,
79 focusedWindow: BrowserWindow | undefined,
80 _evt: KeyboardEvent,
81 ) {
82 if (focusedWindow)
83 focusedWindow.webContents.send('dome.ipc.find');
84 }
85
86 // --------------------------------------------------------------------------
87 // --- Menu Utilities
88 // --------------------------------------------------------------------------
89
90 export type MenuItemSpec = Electron.MenuItemConstructorOptions;
91 export type MenuSpec = MenuItemSpec[];
92
93 const Separator: MenuItemSpec = { type: 'separator' };
94
95 function concatSep(...menus: MenuSpec[]): MenuSpec {
96 let menu: MenuItemSpec[] = [];
97 let needsep = false;
98 menus.forEach((items) => {
99 const n = items.length;
100 if (n > 0) {
101 if (needsep) menu.push(Separator);
102 menu = menu.concat(items);
103 needsep = (items[n - 1].type !== 'separator');
104 }
105 });
106 return menu;
107 }
108
109 // --------------------------------------------------------------------------
110 // --- MacOS Menu Items
111 // --------------------------------------------------------------------------
112
113 const macosAppMenuItems = (appName: string): MenuSpec => [
114 {
115 label: `About ${appName}`,
116 role: 'about',
117 },
118 Separator,
119 {
120 label: 'Preferences…',
121 accelerator: 'Command+,',
122 click: () => ipcMain.emit('dome.menu.settings'),
123 },
124 {
125 label: 'Restore Defaults',
126 click: () => ipcMain.emit('dome.menu.defaults'),
127 },
128 Separator,
129 {
130 label: 'Services',
131 submenu: [],
132 role: 'services',
133 },
134 Separator,
135 {
136 label: `Hide ${appName}`,
137 accelerator: 'Command+H',
138 role: 'hide',
139 }, {
140 label: 'Hide Others',
141 accelerator: 'Command+Alt+H',
142 role: 'hideOthers',
143 }, {
144 label: 'Show All',
145 role: 'unhide',
146 },
147 Separator,
148 {
149 label: 'Quit',
150 accelerator: 'Command+Q',
151 role: 'quit',
152 },
153 ];
154
155 // --------------------------------------------------------------------------
156 // --- File Menu Items (platform dependant)
157 // --------------------------------------------------------------------------
158
159 const fileMenuItemsCustom: MenuSpec = [];
160
161 const fileMenuItemsLinux: MenuSpec = [
162 {
163 label: 'Preferences…',
164 click: () => ipcMain.emit('dome.menu.settings'),
165 },
166 {
167 label: 'Restore Defaults',
168 click: () => ipcMain.emit('dome.menu.defaults'),
169 },
170 Separator,
171 {
172 label: 'Exit',
173 accelerator: 'Ctrl+Q',
174 role: 'quit',
175 },
176 ];
177
178 // --------------------------------------------------------------------------
179 // --- Edit Menu Items
180 // --------------------------------------------------------------------------
181
182 const editMenuItemsCustom: MenuSpec = [];
183
184 const editMenuItems: MenuSpec = [
185 {
186 label: 'Undo',
187 accelerator: 'CmdOrCtrl+Z',
188 role: 'undo',
189 }, {
190 label: 'Redo',
191 accelerator: 'Shift+CmdOrCtrl+Z',
192 role: 'redo',
193 },
194 Separator,
195 {
196 label: 'Cut',
197 accelerator: 'CmdOrCtrl+X',
198 role: 'cut',
199 }, {
200 label: 'Copy',
201 accelerator: 'CmdOrCtrl+C',
202 role: 'copy',
203 }, {
204 label: 'Paste',
205 accelerator: 'CmdOrCtrl+V',
206 role: 'paste',
207 }, {
208 label: 'Select All',
209 accelerator: 'CmdOrCtrl+A',
210 role: 'selectAll',
211 },
212 Separator,
213 {
214 label: 'Find',
215 accelerator: 'CmdOrCtrl+F',
216 click: userFindInfo,
217 },
218 ];
219
220 // --------------------------------------------------------------------------
221 // --- View Menu Items
222 // --------------------------------------------------------------------------
223
224 const viewMenuItemsCustom: MenuSpec = [];
225
226 const viewMenuItems = (osx: boolean): MenuSpec => [
227 {
228 label: 'Reload',
229 accelerator: 'CmdOrCtrl+R',
230 click: reloadWindow,
231 }, {
232 label: 'Toggle Full Screen',
233 accelerator: (osx ? 'Ctrl+Command+F' : 'F11'),
234 click: toggleFullScreen,
235 }, {
236 label: 'Toggle Developer Tools',
237 accelerator: (osx ? 'Alt+Command+I' : 'Ctrl+Shift+I'),
238 click: toggleDevTools,
239 },
240 ];
241
242 // --------------------------------------------------------------------------
243 // --- Window Menu Items
244 // --------------------------------------------------------------------------
245
246 const windowMenuItemsLinux: MenuSpec = [
247 {
248 label: 'Minimize',
249 accelerator: 'CmdOrCtrl+M',
250 role: 'minimize',
251 }, {
252 label: 'Close',
253 accelerator: 'CmdOrCtrl+W',
254 role: 'close',
255 },
256 Separator,
257 {
258 label: 'Reopen Window',
259 accelerator: 'CmdOrCtrl+Shift+T',
260 enabled: false,
261 click: () => { app.emit('activate'); },
262 },
263 ];
264
265 const windowMenuItemsMacos: MenuSpec = windowMenuItemsLinux.concat([
266 {
267 label: 'Bring All to Front',
268 role: 'front',
269 },
270 ]);
271
272 // --------------------------------------------------------------------------
273 // --- Help Menu Items
274 // --------------------------------------------------------------------------
275
276 let learnMoreLink = '';
277 ipcMain.handle('dome.ipc.updateLearnMore', (_, link) => {
278 if (typeof link === 'string') learnMoreLink = link;
279 });
280
281 const helpMenuItems: MenuSpec = [
282 {
283 label: 'Learn More',
284 click() { shell.openExternal(learnMoreLink); },
285 },
286 ];
287
288 // --------------------------------------------------------------------------
289 // --- Update MenuBar (async)
290 // --------------------------------------------------------------------------
291
292 let updateRequired = false;
293 let updateTriggered = false;
294
295 function requestUpdate() {
296 if (updateRequired && !updateTriggered) {
297 updateTriggered = true;
298 setImmediate(install);
299 }
300 }
301
302 // --------------------------------------------------------------------------
303 // --- CustomMenus
304 // --------------------------------------------------------------------------
305
306 interface CustomMenu extends Electron.MenuItemConstructorOptions {
307 label: string;
308 submenu: MenuSpec;
309 }
310
311 const customMenus: CustomMenu[] = [];
312
313 type ItemEntry = { spec: MenuItemSpec; item?: MenuItem };
314
315 const customItems = new Map<string, ItemEntry>();
316
317 function findMenu(label: string): MenuSpec | undefined {
318 switch (label) {
319 case 'File': return fileMenuItemsCustom;
320 case 'Edit': return editMenuItemsCustom;
321 case 'View': return viewMenuItemsCustom;
322 default: {
323 const cm = customMenus.find((m) => m.label === label);
324 return cm && cm.submenu;
325 }
326 }
327 }
328
329 export function addMenu(label: string) {
330 if (findMenu(label)) {
331 console.warn(`Already defined menu '${label}'`);
332 } else {
333 customMenus.push({ label, submenu: [] });
334 }
335 requestUpdate();
336 }
337
338 export interface CustomMenuItem extends MenuItemSpec {
339 menu: string;
340 id: string;
341 key?: string;
342 }
343
344 export interface SeparatorItem {
345 menu: string;
346 type: 'separator';
347 }
348
349 export type CustomMenuItemSpec = SeparatorItem | CustomMenuItem;
350
351 export function addMenuItem(custom: CustomMenuItemSpec) {
352 const menuSpec = findMenu(custom.menu);
353 if (!menuSpec) {
354 console.error('[Dome] Unknown menu', custom);
355 return;
356 }
357 if (custom.type === 'separator') {
358 menuSpec.push(Separator);
359 } else {
360 const { id, key, ...spec } = custom;
361 if (key) {
362 switch (System.platform) {
363 case 'macos':
364 if (key.startsWith('Cmd+'))
365 spec.accelerator = `Cmd+${key.substring(4)}`;
366 if (key.startsWith('Alt+'))
367 spec.accelerator = `Cmd+Alt+${key.substring(4)}`;
368 if (key.startsWith('Meta+'))
369 spec.accelerator = `Cmd+Shift+${key.substring(5)}`;
370 break;
371 case 'windows':
372 case 'linux':
373 default:
374 if (key.startsWith('Cmd+'))
375 spec.accelerator = `Ctrl+${key.substring(4)}`;
376 if (key.startsWith('Alt+'))
377 spec.accelerator = `Alt+${key.substring(4)}`;
378 if (key.startsWith('Meta+'))
379 spec.accelerator = `Ctrl+Alt+${key.substring(5)}`;
380 break;
381 }
382 }
383 const entry = customItems.get(id);
384 if (entry) {
385 if (!System.DEVEL) {
386 console.error('[Dome] Duplicate menu item:', custom);
387 return;
388 }
389 if (entry.spec) Object.assign(entry.spec, spec);
390 if (entry.item) Object.assign(entry.item, spec);
391 } else {
392 if (!spec.click && !spec.role)
393 spec.click = (
394 _item: MenuItem,
395 window: BrowserWindow | undefined,
396 _evt: KeyboardEvent,
397 ) => window?.webContents.send('dome.ipc.menu.clicked', id);
398 customItems.set(id, { spec });
399 menuSpec.push(spec);
400 }
401 }
402 requestUpdate();
403 }
404
405 export function setMenuItem({ id, ...options }: CustomMenuItem) {
406 const entry = customItems.get(id);
407 if (entry) {
408 if (entry.spec) Object.assign(entry.spec, options);
409 if (entry.item) Object.assign(entry.item, options);
410 requestUpdate ();
411 } else
412 console.warn(`[Dome] unknown menu item #${id}`);
413 }
414
415 // --------------------------------------------------------------------------
416 // --- Menu Bar Template
417 // --------------------------------------------------------------------------
418
419 function template(): CustomMenu[] {
420 switch (System.platform) {
421 case 'macos':
422 return ([] as CustomMenu[]).concat(
423 [
424 { label: app.name, submenu: macosAppMenuItems(app.name) },
425 {
426 label: 'File',
427 submenu: fileMenuItemsCustom,
428 },
429 {
430 label: 'Edit',
431 submenu: concatSep(editMenuItems, editMenuItemsCustom),
432 },
433 {
434 label: 'View',
435 submenu: concatSep(viewMenuItemsCustom, viewMenuItems(true)),
436 },
437 ],
438 customMenus,
439 [
440 {
441 label: 'Window',
442 role: 'window',
443 submenu: windowMenuItemsMacos,
444 },
445 {
446 label: 'Help',
447 role: 'help',
448 submenu: helpMenuItems,
449 },
450 ],
451 );
452 case 'windows':
453 case 'linux':
454 default:
455 return ([] as CustomMenu[]).concat(
456 [
457 {
458 label: 'File',
459 submenu: concatSep(fileMenuItemsCustom, fileMenuItemsLinux),
460 },
461 {
462 label: 'Edit',
463 submenu: concatSep(editMenuItems, editMenuItemsCustom),
464 },
465 {
466 label: 'View',
467 submenu: concatSep(viewMenuItemsCustom, viewMenuItems(false)),
468 },
469 ],
470 customMenus,
471 [
472 { label: 'Window', submenu: windowMenuItemsLinux },
473 { label: 'Help', submenu: helpMenuItems },
474 ],
475 );
476 }
477 }
478
479 // --------------------------------------------------------------------------
480 // --- MenuBar SetUp
481 // --------------------------------------------------------------------------
482
483 let menubar: Menu;
484
485 function registerCustomItems(menu: Menu) {
486 menu.items.forEach((item: MenuItem) => {
487 const entry = customItems.get(item.id);
488 if (entry) entry.item = item;
489 if (item.submenu) registerCustomItems(item.submenu);
490 });
491 }
492
493 // Initialize the menubar machinery
494 export function install() {
495 updateRequired = true;
496 updateTriggered = false;
497 menubar = Menu.buildFromTemplate(template());
498 registerCustomItems(menubar);
499 Menu.setApplicationMenu(menubar);
500 }
501
502 // Called by reload above
503 function reset() {
504 fileMenuItemsCustom.length = 0;
505 editMenuItemsCustom.length = 0;
506 viewMenuItemsCustom.length = 0;
507 customMenus.length = 0;
508 customItems.clear();
509 install();
510 }
511
512 // --------------------------------------------------------------------------
513 // --- Popup Menu Management
514 // --------------------------------------------------------------------------
515
516 interface PopupMenuItemProps {
517 /** Item label. */
518 label: string;
519 /** Optional menu identifier. */
520 id?: string;
521 /** Displayed item, default is `true`. */
522 display?: boolean;
523 /** Enabled item, default is `true`. */
524 enabled?: boolean;
525 /** Checked item, default is `false`. */
526 checked?: boolean;
527 }
528
529 type PopupMenuItem = PopupMenuItemProps | 'separator';
530
531 function handlePopupMenu(_: Event, items: PopupMenuItem[]): Promise<number> {
532 return new Promise((resolve) => {
533 const menu = new Menu();
534 let kid = 0;
535 let selected = (-1);
536 items.forEach((item, index) => {
537 if (item === 'separator')
538 menu.append(new MenuItem({ type: 'separator' }));
539 else if (item) {
540 const { display = true, enabled, checked } = item;
541 if (display) {
542 const label = item.label || `#${++kid}`;
543 const click = () => { selected = index; };
544 const type = checked !== undefined ? 'checkbox' : 'normal';
545 menu.append(new MenuItem({ label, enabled, type, checked, click }));
546 }
547 }
548 });
549 menu.popup({ callback: () => resolve(selected) });
550 });
551 }
552
553 ipcMain.handle('dome.popup', handlePopupMenu);
554
555 // --------------------------------------------------------------------------