Debian Codegraph @

ivette/src/dome/main/dome.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 ## Dome Application (Main Process)
28
29 This module manages the electron main-process of the application.
30 Your application will launch on `Dome.start()`:
31
32 @example
33 // src/main/index.js:
34 import * as Dome from 'dome' ;
35 Dome.start();
36
37 @packageDocumentation
38 @module dome(main)
39 */
40
41 import _ from 'lodash';
42 import fs from 'fs';
43 import path from 'path';
44 import {
45 app,
46 ipcMain,
47 BrowserWindow,
48 BrowserWindowConstructorOptions,
49 IpcMainEvent,
50 shell,
51 dialog,
52 nativeTheme,
53 } from 'electron';
54 import installExtension, { REACT_DEVELOPER_TOOLS } from 'dome/devtools';
55 import SYS, * as System from 'dome/system';
56
57 // --------------------------------------------------------------------------
58 // --- Main Window Web Navigation
59 // --------------------------------------------------------------------------
60
61 import { URL } from 'url';
62 import * as Menubar from './menubar';
63
64 // --------------------------------------------------------------------------
65 // --- System Helpers
66 // --------------------------------------------------------------------------
67
68 function fstat(p: string) {
69 try {
70 return fs.statSync(p);
71 } catch (_error) {
72 return undefined;
73 }
74 }
75
76 // --------------------------------------------------------------------------
77 // --- Helpers
78 // --------------------------------------------------------------------------
79
80 const LOCAL = process.env.DOME_LOCAL;
81
82 /** Development mode flag */
83 export const { DEVEL } = System;
84
85 /** System platform */
86 export const { platform } = System;
87
88 // --------------------------------------------------------------------------
89 // --- Native Theme
90 // --------------------------------------------------------------------------
91
92 ipcMain.handle('dome.ipc.theme', () => {
93 return nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
94 });
95
96 nativeTheme.on('updated', () => {
97 broadcast('dome.theme.updated');
98 });
99
100 function setNativeTheme(theme: string | undefined) {
101 switch (theme) {
102 case 'dark':
103 case 'light':
104 case 'system':
105 nativeTheme.themeSource = theme;
106 return;
107 default:
108 console.warn('[dome] unknown theme', theme);
109 }
110 }
111
112 // --------------------------------------------------------------------------
113 // --- Settings
114 // --------------------------------------------------------------------------
115
116 function loadSettings(file: string) {
117 try {
118 if (!fstat(file))
119 return {};
120 const text = fs.readFileSync(file, { encoding: 'utf8' });
121 return { ...JSON.parse(text) };
122 } catch (err) {
123 console.error('[Dome] Unable to load settings', file, err);
124 return {};
125 }
126 }
127
128 function saveSettings(file: string, data = {}) {
129 try {
130 const text = JSON.stringify(data, undefined, DEVEL ? 2 : 0);
131 fs.writeFileSync(file, text, { encoding: 'utf8' });
132 } catch (err) {
133 console.error('[Dome] Unable to save settings', file, err);
134 }
135 }
136
137 // --------------------------------------------------------------------------
138 // --- Global Settings
139 // --------------------------------------------------------------------------
140
141 let GlobalSettings = {}; // Current Dictionnary
142
143 const APP_DIR = app.getPath('userData');
144 const PATH_WINDOW_SETTINGS = path.join(APP_DIR, 'WindowSettings.json');
145 const PATH_GLOBAL_SETTINGS = path.join(APP_DIR, 'GlobalSettings.json');
146
147 function saveGlobalSettings() {
148 try {
149 if (!fstat(APP_DIR)) fs.mkdirSync(APP_DIR);
150 saveSettings(PATH_GLOBAL_SETTINGS, GlobalSettings);
151 } catch (err) {
152 console.error('[Dome] Unable to save global settings', err);
153 }
154 }
155
156 function obtainGlobalSettings() {
157 if (_.isEmpty(GlobalSettings)) {
158 GlobalSettings = loadSettings(PATH_GLOBAL_SETTINGS);
159 }
160 return GlobalSettings;
161 }
162
163 // --------------------------------------------------------------------------
164 // --- Window Settings & Frames
165 // --------------------------------------------------------------------------
166
167 type Store = { [key: string]: unknown };
168
169 interface Handle {
170 primary: boolean; // Primary window
171 window: BrowserWindow; // Also prevents Gc
172 frame: Electron.Rectangle; // Window frame
173 devtools: boolean; // Developper tools visible
174 reloaded: boolean; // Reloaded window
175 config: string; // Path to config file
176 settings: Store; // Current settings
177 storage: Store; // Local storage
178 }
179
180 const WindowHandles = new Map<number, Handle>(); // Indexed by *webContents* id
181
182 function saveWindowConfig(handle: Handle) {
183 const configData = {
184 frame: handle.frame,
185 settings: handle.settings,
186 storage: handle.storage,
187 devtools: handle.devtools,
188 };
189 saveSettings(handle.config, configData);
190 }
191
192 function windowSyncSettings(event: IpcMainEvent) {
193 const handle = WindowHandles.get(event.sender.id);
194 event.returnValue = {
195 globals: obtainGlobalSettings(),
196 storage: handle && handle.storage,
197 settings: handle && handle.settings,
198 };
199 }
200
201 ipcMain.on('dome.ipc.settings.sync', windowSyncSettings);
202
203 function applyThemeSettings(settings: Store) {
204 const theme = settings['dome-color-theme'];
205 if (typeof (theme) === 'string') setNativeTheme(theme);
206 }
207
208 // --------------------------------------------------------------------------
209 // --- Patching Settings
210 // --------------------------------------------------------------------------
211
212 type Patch = { key: string; value: unknown };
213
214 function applyPatches(data: Store, args: Patch[]) {
215 args.forEach(({ key, value }) => {
216 if (value === null) {
217 delete data[key];
218 } else {
219 data[key] = value;
220 }
221 });
222 }
223
224 function applyWindowSettings(event: IpcMainEvent, args: Patch[]) {
225 const handle = WindowHandles.get(event.sender.id);
226 if (handle) {
227 applyPatches(handle.settings, args);
228 if (DEVEL) saveWindowConfig(handle);
229 }
230 }
231
232 function applyStorageSettings(event: IpcMainEvent, args: Patch[]) {
233 const handle = WindowHandles.get(event.sender.id);
234 if (handle) {
235 applyPatches(handle.storage, args);
236 if (DEVEL) saveWindowConfig(handle);
237 }
238 }
239
240 function applyGlobalSettings(event: IpcMainEvent, args: Patch[]) {
241 const settings: Store = obtainGlobalSettings();
242 applyPatches(settings, args);
243 applyThemeSettings(settings);
244 BrowserWindow.getAllWindows().forEach((w: BrowserWindow) => {
245 const contents = w.webContents;
246 if (contents.id !== event.sender.id) {
247 contents.send('dome.ipc.settings.broadcast', args);
248 }
249 });
250 if (DEVEL) saveGlobalSettings();
251 }
252
253 ipcMain.on('dome.ipc.settings.window', applyWindowSettings);
254 ipcMain.on('dome.ipc.settings.global', applyGlobalSettings);
255 ipcMain.on('dome.ipc.settings.storage', applyStorageSettings);
256
257 // --------------------------------------------------------------------------
258 // --- Renderer-Process Communication
259 // --------------------------------------------------------------------------
260
261 function broadcast(event: string, ...args: unknown[]) {
262 BrowserWindow.getAllWindows().forEach((w) => {
263 w.webContents.send(event, ...args);
264 });
265 }
266
267 // --------------------------------------------------------------------------
268 // --- Window Activities
269 // --------------------------------------------------------------------------
270
271 let appName = 'Dome';
272 const MODIFIED = '(*) ';
273
274 /**
275 Sets application window name
276 */
277 export function setName(title: string) {
278 appName = title;
279 }
280
281 function setTitle(event: IpcMainEvent, title: string) {
282 const handle = WindowHandles.get(event.sender.id);
283 if (handle) handle.window.setTitle(title || appName);
284 }
285
286 function setModified(event: IpcMainEvent, modified: boolean) {
287 const handle = WindowHandles.get(event.sender.id);
288 if (handle) {
289 const w = handle.window;
290 if (platform === 'macos')
291 w.setDocumentEdited(modified);
292 else {
293 let title = w.getTitle();
294 if (title.startsWith(MODIFIED))
295 title = title.substring(MODIFIED.length);
296 if (modified)
297 title = MODIFIED + title;
298 w.setTitle(title);
299 }
300 }
301 }
302
303 ipcMain.on('dome.ipc.window.title', setTitle);
304 ipcMain.on('dome.ipc.window.modified', setModified);
305
306 function getURL() {
307 if (DEVEL)
308 return `http://localhost:${process.env.ELECTRON_WEBPACK_WDS_PORT}`;
309 if (LOCAL)
310 return `file://${path.join(__dirname, '../renderer/index.html')}`;
311 return `file://${__dirname}/index.html`;
312 }
313
314 function navigateURL(sender: Electron.WebContents) {
315 return (event: Electron.Event, url: string) => {
316 event.preventDefault();
317 const href = new URL(url);
318 const main = new URL(getURL());
319 if (href.origin === main.origin) {
320 sender.send('dome.ipc.href', url);
321 } else {
322 shell.openExternal(url);
323 }
324 };
325 }
326
327 // --------------------------------------------------------------------------
328 // --- Lookup for config file
329 // --------------------------------------------------------------------------
330
331 function lookupConfig(pwd = '.') {
332 const wdir = path.resolve(pwd);
333 let cwd = wdir;
334 const cfg = `.${appName.toLowerCase()}`;
335 for (; ;) {
336 const here = path.join(cwd, cfg);
337 if (fstat(here)) return here;
338 const up = path.dirname(cwd);
339 if (up === cwd) break;
340 cwd = up;
341 }
342 const home = path.resolve(app.getPath('home'));
343 const user = wdir.startsWith(home) ? wdir : home;
344 return path.join(user, cfg);
345 }
346
347 // --------------------------------------------------------------------------
348 // --- Browser Window SetUp
349 // --------------------------------------------------------------------------
350
351 function createBrowserWindow(
352 primary: boolean,
353 config: BrowserWindowConstructorOptions,
354 argv?: string[],
355 wdir?: string,
356 ) {
357
358 const isAppWindow = (argv !== undefined && wdir !== undefined);
359
360 const browserArguments = isAppWindow
361 ? SYS.WINDOW_APPLICATION_ARGV
362 : SYS.WINDOW_PREFERENCES_ARGV;
363
364 const options: BrowserWindowConstructorOptions = {
365 show: false,
366 backgroundColor: '#f0f0f0',
367 webPreferences: {
368 nodeIntegration: true,
369 contextIsolation: false,
370 additionalArguments: [browserArguments],
371 },
372 ...config,
373 };
374
375 const configFile = isAppWindow ? lookupConfig(wdir) : PATH_WINDOW_SETTINGS;
376 const configData = loadSettings(configFile);
377
378 const { frame, devtools, settings = {}, storage = {} } = configData;
379 if (frame) {
380 const getInt = <A>(v: A) => v && _.toSafeInteger(v);
381 options.x = getInt(frame.x);
382 options.y = getInt(frame.y);
383 options.width = getInt(frame.width);
384 options.height = getInt(frame.height);
385 }
386
387 const theWindow = new BrowserWindow(options);
388 const { webContents } = theWindow;
389 const wid = webContents.id;
390
391 const handle: Handle = {
392 primary,
393 window: theWindow,
394 config: configFile,
395 reloaded: false,
396 frame,
397 settings,
398 storage,
399 devtools,
400 };
401
402 // Keep the window reference (prevent garbage collection)
403 WindowHandles.set(wid, handle);
404
405 // Emitted when the window is closed.
406 theWindow.on('closed', () => {
407 saveWindowConfig(handle);
408 // Dereference the window object (allow garbage collection)
409 WindowHandles.delete(wid);
410 });
411
412 // Load the index.html of the app.
413 if (DEVEL || LOCAL)
414 process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';
415
416 theWindow.loadURL(getURL());
417
418 // Load Finished
419 theWindow.once('ready-to-show', () => {
420 if (DEVEL || LOCAL)
421 process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'false';
422 if (DEVEL && devtools) {
423 webContents.openDevTools();
424 }
425 theWindow.show();
426 });
427
428 // Focus Management
429 theWindow.on('focus', () => webContents.send('dome.ipc.focus', true));
430 theWindow.on('blur', () => webContents.send('dome.ipc.focus', false));
431
432 // URL Navigation
433 webContents.on('will-navigate', navigateURL(webContents));
434 webContents.on('did-navigate-in-page', navigateURL(webContents));
435
436 // Application Startup
437 webContents.on('did-finish-load', () => {
438 if (!handle.reloaded) {
439 handle.reloaded = true;
440 } else {
441 broadcast('dome.ipc.reload');
442 }
443 webContents.send('dome.ipc.command', argv, wdir);
444 });
445
446 // Emitted when the window want's to close.
447 theWindow.on('close', () => {
448 handle.frame = theWindow.getBounds();
449 handle.devtools = webContents.isDevToolsOpened();
450 webContents.send('dome.ipc.closing');
451 });
452
453 // Keep track of frame positions (in DEVEL)
454 if (DEVEL) {
455 const saveFrame = _.debounce(() => {
456 handle.frame = theWindow.getBounds();
457 handle.devtools = webContents.isDevToolsOpened();
458 saveWindowConfig(handle);
459 }, 300);
460 theWindow.on('resize', saveFrame);
461 theWindow.on('moved', saveFrame);
462 }
463
464 return theWindow;
465 }
466
467 // --------------------------------------------------------------------------
468 // --- Application Window(s) & Command Line
469 // --------------------------------------------------------------------------
470
471 function stripElectronArgv(argv: string[]) {
472 return argv.slice(DEVEL ? 3 : (LOCAL ? 2 : 1)).filter((p) => !!p);
473 }
474
475 function createPrimaryWindow() {
476 // Initialize Menubar
477 Menubar.install();
478
479 // React Developper Tools
480 if (DEVEL)
481 installExtension(REACT_DEVELOPER_TOOLS, true).catch((err) => {
482 console.error('[Dome] Enable to install React dev-tools', err);
483 });
484 const cwd = process.cwd();
485 const wdir = cwd === '/' ? app.getPath('home') : cwd;
486 const argv = stripElectronArgv(process.argv);
487
488 // Initialize Theme
489 const globals = obtainGlobalSettings();
490 applyThemeSettings(globals);
491
492 // Create Window
493 createBrowserWindow(true, { title: appName }, argv, wdir);
494 }
495
496 let appCount = 1;
497
498 function createSecondaryWindow(
499 _event: Electron.Event,
500 chromiumArgv: string[],
501 wdir: string,
502 ) {
503 const argStart = "--second-instance=";
504 let argString = chromiumArgv.find(a => a.startsWith(argStart));
505 if (argString) {
506 argString = argString.substring(argStart.length);
507 const electronArgv = JSON.parse(argString);
508 const argv = stripElectronArgv(electronArgv);
509 const title = `${appName} #${++appCount}`;
510 createBrowserWindow(false, { title }, argv, wdir);
511 }
512 }
513
514 function createDesktopWindow() {
515 const wdir = app.getPath('home');
516 const title = `${appName} #${++appCount}`;
517 createBrowserWindow(false, { title }, [], wdir);
518 }
519
520 // --------------------------------------------------------------------------
521 // --- Activate Windows (macOS)
522 // --------------------------------------------------------------------------
523
524 function activateWindows() {
525 let isFocused = false;
526 let toFocus: BrowserWindow | undefined;
527 BrowserWindow.getAllWindows().forEach((w) => {
528 w.show();
529 if (w.isFocused()) isFocused = true;
530 else if (!toFocus) toFocus = w;
531 });
532 if (!isFocused) {
533 if (toFocus) toFocus.focus();
534 else {
535 // No focusable nor focused window
536 createDesktopWindow();
537 }
538 }
539 }
540
541 // --------------------------------------------------------------------------
542 // --- Settings Window
543 // --------------------------------------------------------------------------
544
545 let PreferenceWindow: BrowserWindow | undefined;
546
547 function showSettingsWindow() {
548 if (!PreferenceWindow)
549 PreferenceWindow = createBrowserWindow(
550 false, {
551 title: `${appName} Settings`,
552 width: 256,
553 height: 248,
554 fullscreen: false,
555 maximizable: false,
556 minimizable: false,
557 });
558 PreferenceWindow.setMenuBarVisibility(false);
559 PreferenceWindow.show();
560 PreferenceWindow.on('closed', () => { PreferenceWindow = undefined; });
561 }
562
563 function restoreDefaultSettings() {
564 GlobalSettings = {};
565 nativeTheme.themeSource = 'system';
566 if (DEVEL) saveGlobalSettings();
567
568 WindowHandles.forEach((handle) => {
569 // Keep frame for user comfort
570 handle.settings = {};
571 handle.devtools = handle.window.webContents.isDevToolsOpened();
572 if (DEVEL) saveWindowConfig(handle);
573 });
574
575 broadcast('dome.ipc.settings.defaults');
576 }
577
578 ipcMain.on('dome.menu.settings', showSettingsWindow);
579 ipcMain.on('dome.menu.defaults', restoreDefaultSettings);
580 ipcMain.on('dome.app.paths', (event) => {
581 event.returnValue = {
582 'home': app.getPath('home'),
583 'desktop': app.getPath('desktop'),
584 'documents': app.getPath('documents'),
585 'downloads': app.getPath('downloads'),
586 'temp': app.getPath('temp'),
587 };
588 });
589
590 // --------------------------------------------------------------------------
591 // --- Main Application Starter
592 // --------------------------------------------------------------------------
593
594 /** Starts the main process. */
595 export function start() {
596
597 // Workaround to recover the original commandline of a second instance
598 // after chromium messes with the argument order.
599 // See https://github.com/electron/electron/issues/20322 for more details.
600 app.commandLine.appendSwitch("second-instance", JSON.stringify(process.argv));
601
602 // Ensures second instance triggers the main one
603 if (!app.requestSingleInstanceLock()) app.quit();
604
605 // Change default locale
606 app.commandLine.appendSwitch('lang', 'en');
607
608 // Listen to application events
609 app.on('ready', createPrimaryWindow); // Wait for Electron init
610 app.on('activate', activateWindows); // Mac OSX response to dock
611 app.on('second-instance', createSecondaryWindow);
612
613 // At-exit callbacks
614 app.on('will-quit', () => {
615 saveGlobalSettings();
616 System.doExit();
617 });
618
619 // On macOS the menu bar stays active until the user explicitly quits.
620 // On other systems, automatically quit when all windows are closed.
621 // Warning: when no event handler is registered, the app automatically
622 // quit when all windows are closed.
623 app.on('window-all-closed', () => {
624 if (System.platform !== 'macos') app.quit();
625 });
626
627 }
628
629 // --------------------------------------------------------------------------
630 // --- MenuBar Management
631 // --------------------------------------------------------------------------
632
633 /**
634 Define a custom main window menu.
635 */
636 export function addMenu(label: string) {
637 Menubar.addMenu(label);
638 }
639
640 /**
641 Define a custom menu item.
642 */
643 export function addMenuItem(spec: Menubar.CustomMenuItemSpec) {
644 Menubar.addMenuItem(spec);
645 }
646
647 /**
648 Update a menu item.
649 */
650 export function setMenuItem(spec: Menubar.CustomMenuItem) {
651 Menubar.setMenuItem(spec);
652 }
653
654 function isPrimary(evt: IpcMainEvent): boolean {
655 const h = WindowHandles.get(evt.sender.id);
656 return h ? h.primary : false;
657 }
658
659 ipcMain.on('dome.ipc.menu.addmenu', (evt, label) =>
660 isPrimary(evt) && Menubar.addMenu(label)
661 );
662 ipcMain.on('dome.ipc.menu.addmenuitem', (evt, spec) =>
663 isPrimary(evt) && Menubar.addMenuItem(spec)
664 );
665 ipcMain.on('dome.ipc.menu.setmenuitem', (_evt, spec) =>
666 // Always update menu items
667 Menubar.setMenuItem(spec)
668 );
669
670 // --------------------------------------------------------------------------
671 // --- Dialogs Management
672 // --------------------------------------------------------------------------
673
674 ipcMain.handle(
675 'dome.dialog.showMessageBox',
676 (_evt, props) => dialog.showMessageBox(props),
677 );
678
679 ipcMain.handle(
680 'dome.dialog.showOpenDialog',
681 (_evt, props) => dialog.showOpenDialog(props),
682 );
683
684 ipcMain.handle(
685 'dome.dialog.showSaveDialog',
686 (_evt, props) => dialog.showSaveDialog(props),
687 );
688
689 // --------------------------------------------------------------------------