2022-08-05 12:07:19 +02:00
|
|
|
import { BrowserWindow, globalShortcut } from 'electron';
|
|
|
|
import * as Store from 'electron-store';
|
2022-08-09 16:10:08 +02:00
|
|
|
import { ShortcutRecord, shortcuts } from 'common/shortcuts';
|
2022-08-05 12:07:19 +02:00
|
|
|
const shortcutsStore = new Store({ name: 'shortcuts' });
|
|
|
|
const isDevelopment = process.env.NODE_ENV !== 'production';
|
2022-08-09 16:10:08 +02:00
|
|
|
const defaultShortcuts = shortcuts.filter(s => s.os.includes(process.platform));
|
2022-08-05 12:07:19 +02:00
|
|
|
|
|
|
|
export class ShortcutRegister {
|
2022-08-08 16:44:40 +02:00
|
|
|
private _shortcuts: ShortcutRecord[];
|
2022-08-05 12:07:19 +02:00
|
|
|
private _mainWindow: BrowserWindow;
|
|
|
|
|
|
|
|
constructor (args: { mainWindow: BrowserWindow }) {
|
|
|
|
this._mainWindow = args.mainWindow;
|
|
|
|
this.shortcuts = shortcutsStore.get('shortcuts', defaultShortcuts) as ShortcutRecord[];
|
|
|
|
}
|
|
|
|
|
2022-08-08 16:44:40 +02:00
|
|
|
get shortcuts () {
|
|
|
|
return this._shortcuts;
|
|
|
|
}
|
|
|
|
|
|
|
|
private set shortcuts (value: ShortcutRecord[]) {
|
|
|
|
this._shortcuts = value;
|
|
|
|
shortcutsStore.set('shortcuts', value);
|
|
|
|
}
|
|
|
|
|
2022-08-05 12:07:19 +02:00
|
|
|
init () {
|
|
|
|
for (const shortcut of this.shortcuts) {
|
|
|
|
if (shortcut.os.includes(process.platform)) {
|
|
|
|
for (const key of shortcut.keys) {
|
|
|
|
try {
|
|
|
|
globalShortcut.register(key, () => {
|
|
|
|
this._mainWindow.webContents.send(shortcut.event);
|
|
|
|
if (isDevelopment) console.log('EVENT:', shortcut);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
catch (error) {
|
|
|
|
this.restoreDefaults();
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
reload () {
|
|
|
|
this.unregister();
|
|
|
|
this.init();
|
|
|
|
}
|
|
|
|
|
|
|
|
updateShortcuts (shortcuts: ShortcutRecord[]) {
|
|
|
|
this.shortcuts = shortcuts;
|
2022-08-08 16:44:40 +02:00
|
|
|
this.reload();
|
2022-08-05 12:07:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
restoreDefaults () {
|
|
|
|
this.shortcuts = defaultShortcuts;
|
|
|
|
this.reload();
|
|
|
|
}
|
|
|
|
|
|
|
|
unregister () {
|
|
|
|
globalShortcut.unregisterAll();
|
|
|
|
}
|
|
|
|
}
|