Debian Codegraph @

ivette/src/dome/renderer/data/settings.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
25 // --------------------------------------------------------------------------
26 // --- States
27 // --------------------------------------------------------------------------
28
29 /**
30 Typed States & Settings
31 @packageDocumentation
32 @module dome/data/settings
33 */
34
35 import React from 'react';
36 import { ipcRenderer } from 'electron';
37 import { debounce } from 'lodash';
38 import isEqual from 'react-fast-compare';
39 import { emitter as SysEmitter } from 'dome/misc/system';
40 import * as JSON from './json';
41 import type { State } from './states';
42
43 // --------------------------------------------------------------------------
44 // --- Settings
45 // --------------------------------------------------------------------------
46
47 /** @internal */
48 interface Settings<A> {
49 decoder: JSON.Loose<A>;
50 encoder: JSON.Encoder<A>;
51 defaultValue: A;
52 }
53
54 /**
55 Global settings.
56 This utility class allows you to share accross several
57 components and windows the parameters associated to global settings.
58
59 However, it is important to note that global settings are uniquely identified
60 by their `name`. If you have multiple definitions of global settings class
61 with the same name, they will actually share the same value. Hence, if they
62 have different default values or decoders, this might leads to strange
63 results.
64 */
65 export class GlobalSettings<A> {
66 name: string;
67 decoder: JSON.Loose<A>;
68 encoder: JSON.Encoder<A>;
69 defaultValue: A;
70 constructor(
71 name: string,
72 decoder: JSON.Loose<A>,
73 encoder: JSON.Encoder<A>,
74 defaultValue: A,
75 ) {
76 this.name = name;
77 this.decoder = decoder;
78 this.encoder = encoder;
79 this.defaultValue = defaultValue;
80 }
81 }
82
83 // --------------------------------------------------------------------------
84 // --- Smart Constructors
85 // --------------------------------------------------------------------------
86
87 /** Boolean settings with `true` default. */
88 export class GTrue extends GlobalSettings<boolean> {
89 constructor(name: string) {
90 super(name, JSON.jBoolean, JSON.identity, true);
91 }
92 }
93
94 /** Boolean settings with `false` default. */
95 export class GFalse extends GlobalSettings<boolean> {
96 constructor(name: string) {
97 super(name, JSON.jBoolean, JSON.identity, false);
98 }
99 }
100
101 /** Numeric settings (default is zero unless specified). */
102 export class GNumber extends GlobalSettings<number> {
103 constructor(name: string, defaultValue = 0) {
104 super(name, JSON.jNumber, JSON.identity, defaultValue);
105 }
106 }
107
108 /** String settings (default is `""` unless specified). */
109 export class GString extends GlobalSettings<string> {
110 constructor(name: string, defaultValue = '') {
111 super(name, JSON.jString, JSON.identity, defaultValue);
112 }
113 }
114
115 /** Smart constructor for optional (JSON serializable) data. */
116 export class GOption<A extends JSON.json>
117 extends GlobalSettings<A | undefined>
118 {
119 constructor(name: string, encoder: JSON.Loose<A>, defaultValue?: A) {
120 super(name, encoder, JSON.identity, defaultValue);
121 }
122 }
123
124 /** Smart constructor for (JSON serializable) data with default. */
125 export class GDefault<A extends JSON.json> extends GlobalSettings<A> {
126 constructor(name: string, encoder: JSON.Loose<A>, defaultValue: A) {
127 super(name, encoder, JSON.identity, defaultValue);
128 }
129 }
130
131 /** Smart constructor for object (JSON serializable) data. */
132 export class GObject<A extends JSON.json> extends GlobalSettings<A> {
133 constructor(name: string, fields: JSON.Props<A>, defaultValue: A) {
134 super(name, JSON.jObject(fields), JSON.identity, defaultValue);
135 }
136 }
137
138 // --------------------------------------------------------------------------
139 // --- Generic Settings (private)
140 // --------------------------------------------------------------------------
141
142 type store = { [key: string]: JSON.json };
143 type patch = { key: string; value: JSON.json };
144 type driver = {
145 evt: string;
146 ipc: string;
147 globals: boolean; // Global Settings (all windows share the same)
148 defaults: boolean; // Restore defaults on demand
149 };
150
151 class Driver {
152
153 readonly evt: string; // Global Update Event
154 readonly store: Map<string, JSON.json> = new Map();
155 readonly diffs: Map<string, JSON.json> = new Map();
156 readonly commit: (() => void) & { flush: () => void; cancel: () => void };
157
158 constructor({ evt, ipc, defaults, globals }: driver) {
159 this.evt = evt;
160 // --- Update Events
161 this.commit = debounce(() => {
162 const m = this.diffs;
163 if (m.size > 0) {
164 const patches: patch[] = [];
165 m.forEach((value, key) => {
166 patches.push({ key, value });
167 });
168 m.clear();
169 ipcRenderer.send(ipc, patches);
170 }
171 }, 100);
172 // --- Restore Defaults Events
173 if (defaults) {
174 ipcRenderer.on('dome.ipc.settings.defaults', () => {
175 this.commit.cancel();
176 this.store.clear();
177 this.diffs.clear();
178 SysEmitter.emit(this.evt);
179 });
180 }
181 // --- Broadcast Events
182 if (globals) {
183 ipcRenderer.on(
184 'dome.ipc.settings.broadcast',
185 (_sender, updates: patch[]) => {
186 const m = this.store;
187 const d = this.diffs;
188 updates.forEach(({ key, value }) => {
189 // Don't cancel local updates
190 if (!d.has(key)) {
191 if (value === null)
192 m.delete(key);
193 else
194 m.set(key, value);
195 }
196 });
197 SysEmitter.emit(this.evt);
198 },
199 );
200 }
201 // --- Closing Events
202 ipcRenderer.on('dome.ipc.closing', () => {
203 this.commit();
204 this.commit.flush();
205 });
206 }
207
208 // --- Initial Data
209
210 sync(data: store) {
211 this.commit.cancel();
212 this.store.clear();
213 this.diffs.clear();
214 const m = this.store;
215 Object.keys(data).forEach((k) => { m.set(k, data[k]); });
216 SysEmitter.emit(this.evt);
217 }
218
219 // --- Load Data
220
221 load(key: string | undefined): JSON.json {
222 return key === undefined ? undefined : this.store.get(key);
223 }
224
225 // --- Save Data
226
227 save(key: string | undefined, data: JSON.json) {
228 if (key === undefined) return;
229 if (data === undefined) {
230 this.store.delete(key);
231 this.diffs.set(key, null);
232 } else {
233 this.store.set(key, data);
234 this.diffs.set(key, data);
235 }
236 SysEmitter.emit(this.evt);
237 this.commit();
238 }
239
240 }
241
242 // --------------------------------------------------------------------------
243 // --- Generic Settings Hook
244 // --------------------------------------------------------------------------
245
246 function useSettings<A>(
247 S: Settings<A>,
248 D: Driver,
249 K?: string,
250 ): State<A> {
251 // Local State
252 const [value, setValue] = React.useState<A>(() => (
253 JSON.jCatch(S.decoder, S.defaultValue)(D.load(K))
254 ));
255 // Foreign Settings Update
256 React.useEffect(() => {
257 const event = D.evt;
258 const onUpdate = () => {
259 const fromSettings = JSON.jCatch(S.decoder, undefined)(D.load(K));
260 if (fromSettings !== undefined)
261 setValue(fromSettings);
262 };
263 SysEmitter.on(event, onUpdate);
264 return () => { SysEmitter.off(event, onUpdate); };
265 });
266 // Hooked Settings Update
267 const updateValue = React.useCallback((newValue: A) => {
268 if (!isEqual(value, newValue)) {
269 setValue(newValue);
270 if (K) D.save(K, S.encoder(newValue));
271 }
272 }, [S, D, K, value]);
273 // Hook
274 return [value, updateValue];
275 }
276
277 // --------------------------------------------------------------------------
278 // --- Window Settings
279 // --------------------------------------------------------------------------
280
281 const WindowSettingsDriver = new Driver({
282 evt: 'dome.settings.window',
283 ipc: 'dome.ipc.settings.window',
284 globals: false,
285 defaults: true,
286 });
287
288 /**
289 Returns the current value of the settings (default for undefined key).
290 */
291 export function getWindowSettings<A>(
292 key: string | undefined,
293 decoder: JSON.Loose<A>,
294 defaultValue: A,
295 ): A {
296 return key ?
297 JSON.jCatch(decoder, defaultValue)(WindowSettingsDriver.load(key))
298 : defaultValue;
299 }
300
301 /**
302 Updates the current value of the settings (on defined key).
303 Most settings are subtypes of `JSON` and do not require any specific
304 encoder. If you have some, simply use it before updating the settings.
305 See [[useWindowSettings]] and [[useWindowSettingsData]].
306 */
307 export function setWindowSettings(
308 key: string | undefined,
309 value: JSON.json,
310 ) {
311 if (key) WindowSettingsDriver.save(key, value);
312 }
313
314 /**
315 Returns a local state that is saved back to the local window user settings.
316 Local window settings are stored in the `.<appName>` file of the working
317 directory, or in the closest one in parent directories, if any.
318 */
319 export function useWindowSettings<A>(
320 key: string | undefined,
321 decoder: JSON.Loose<A & JSON.json>,
322 defaultValue: A & JSON.json,
323 ) {
324 return useSettings({
325 decoder,
326 encoder: JSON.identity,
327 defaultValue,
328 }, WindowSettingsDriver, key);
329 }
330
331 /** Same as [[useWindowSettings]] with a specific encoder. */
332 export function useWindowSettingsData<A>(
333 key: string | undefined,
334 decoder: JSON.Loose<A>,
335 encoder: JSON.Encoder<A>,
336 defaultValue: A,
337 ) {
338 return useSettings({
339 decoder,
340 encoder,
341 defaultValue,
342 }, WindowSettingsDriver, key);
343 }
344
345 /** Call the callback function on window settings events. */
346 export function useWindowSettingsEvent(callback: () => void) {
347 React.useEffect(() => {
348 const { evt } = WindowSettingsDriver;
349 SysEmitter.on(evt, callback);
350 return () => { SysEmitter.off(evt, callback); };
351 });
352 }
353
354 /** @ignore DEPRECATED */
355 export function onWindowSettings(callback: () => void) {
356 const { evt } = WindowSettingsDriver;
357 SysEmitter.on(evt, callback);
358 }
359
360 /** @ignore DEPRECATED */
361 export function offWindowSettings(callback: () => void) {
362 const { evt } = WindowSettingsDriver;
363 SysEmitter.off(evt, callback);
364 }
365
366 // --------------------------------------------------------------------------
367 // --- Local Storage
368 // --------------------------------------------------------------------------
369
370 const LocalStorageDriver = new Driver({
371 evt: 'dome.settings.storage',
372 ipc: 'dome.ipc.settings.storage',
373 globals: false,
374 defaults: false,
375 });
376
377 /**
378 Returns the current value of the settings (default for undefined key).
379 */
380 export function getLocalStorage<A>(
381 key: string | undefined,
382 decoder: JSON.Loose<A>,
383 defaultValue: A,
384 ): A {
385 return key ?
386 JSON.jCatch(decoder, defaultValue)(LocalStorageDriver.load(key))
387 : defaultValue;
388 }
389
390 /**
391 Updates the current value of the settings (on defined key).
392 Most settings are subtypes of `JSON` and do not require any specific
393 encoder. If you have some, simply use it before updating the settings.
394 See [[useLocalStorage]] and [[useWindowSettingsData]].
395 */
396 export function setLocalStorage(
397 key: string | undefined,
398 value: JSON.json,
399 ) {
400 if (key) LocalStorageDriver.save(key, value);
401 }
402
403 export function useLocalStorage<A>(
404 key: string | undefined,
405 decoder: JSON.Loose<A & JSON.json>,
406 defaultValue: A & JSON.json,
407 ) {
408 return useSettings<A & JSON.json>({
409 decoder,
410 encoder: JSON.identity,
411 defaultValue,
412 }, LocalStorageDriver, key);
413 }
414
415 /** Same as [[useLocalStorage]] with a specific encoder. */
416 export function useLocalStorageData<A>(
417 key: string | undefined,
418 decoder: JSON.Loose<A>,
419 encoder: JSON.Encoder<A>,
420 defaultValue: A,
421 ) {
422 return useSettings({
423 decoder,
424 encoder,
425 defaultValue,
426 }, LocalStorageDriver, key);
427 }
428
429 /** Call the callback function on window settings events. */
430 export function useLocalStorageEvent(callback: () => void) {
431 React.useEffect(() => {
432 const { evt } = LocalStorageDriver;
433 SysEmitter.on(evt, callback);
434 return () => { SysEmitter.off(evt, callback); };
435 });
436 }
437
438 // --------------------------------------------------------------------------
439 // --- Global Settings
440 // --------------------------------------------------------------------------
441
442 const GlobalSettingsDriver = new Driver({
443 evt: 'dome.settings.global',
444 ipc: 'dome.ipc.settings.global',
445 globals: true,
446 defaults: true,
447 });
448
449 /**
450 Returns a global state, which is synchronized among all windows, and saved
451 back in the global user settings. The global user settings file is located in
452 the usual place for the application with respect to the underlying system.
453 */
454 export function useGlobalSettings<A>(S: GlobalSettings<A>) {
455 return useSettings(S, GlobalSettingsDriver, S.name);
456 }
457
458 /** Call the callback function on global settings events. */
459 export function useGlobalSettingsEvent(callback: () => void) {
460 React.useEffect(() => {
461 const { evt } = GlobalSettingsDriver;
462 SysEmitter.on(evt, callback);
463 return () => { SysEmitter.off(evt, callback); };
464 });
465 }
466
467 // --------------------------------------------------------------------------
468 // --- Settings Synchronization
469 // --------------------------------------------------------------------------
470
471 /* @ internal */
472 export const window = WindowSettingsDriver.evt;
473
474 /* @ internal */
475 export const global = GlobalSettingsDriver.evt;
476
477 /* @ internal */
478 export function synchronize() {
479 const data = ipcRenderer.sendSync('dome.ipc.settings.sync');
480 const storage: store = data.storage ?? {};
481 const globals: store = data.globals ?? {};
482 const settings: store = data.settings ?? {};
483 LocalStorageDriver.sync(storage);
484 GlobalSettingsDriver.sync(globals);
485 WindowSettingsDriver.sync(settings);
486 }
487
488 // --------------------------------------------------------------------------