forked from wulkano/Kap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglobal-accelerators.js
92 lines (80 loc) · 2.52 KB
/
global-accelerators.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
'use strict';
const {globalShortcut} = require('electron');
const {ipcMain: ipc} = require('electron-better-ipc');
const shortcutToAccelerator = require('./utils/shortcut-to-accelerator');
const store = require('./common/settings');
const {openCropperWindow, isCropperOpen} = require('./cropper');
const openCropper = () => {
if (!isCropperOpen()) {
openCropperWindow();
}
};
// All settings that should be loaded and handled as global accelerators
const handlers = new Map([
['cropperShortcut', openCropper]
]);
// If no action is passed, it resets
const setCropperShortcutAction = (action = openCropper) => {
if (store.get('recordKeyboardShortcut') && store.has('cropperShortcut')) {
handlers.set('cropperShortcut', action);
const shortcut = shortcutToAccelerator(store.get('cropperShortcut'));
if (globalShortcut.isRegistered(shortcut)) {
globalShortcut.unregister(shortcut);
}
globalShortcut.register(shortcut, action);
}
};
const registerShortcut = (shortcut, action) => {
try {
const shortcutAccelerator = shortcutToAccelerator(shortcut);
globalShortcut.register(shortcutAccelerator, action);
} catch (error) {
console.error('Error registering shortcut', shortcut, action, error);
}
};
const registrerFromStore = () => {
if (store.get('recordKeyboardShortcut')) {
for (const [setting, action] of handlers.entries()) {
const shortcut = store.get(setting);
if (shortcut) {
registerShortcut(shortcut, action);
}
}
} else {
globalShortcut.unregisterAll();
}
};
const initializeGlobalAccelerators = () => {
ipc.answerRenderer('update-shortcut', ({setting, shortcut}) => {
try {
if (store.has(setting)) {
const oldShortcut = store.get(setting);
const shortcutAccelerator = shortcutToAccelerator(oldShortcut);
if (globalShortcut.isRegistered(shortcutAccelerator)) {
globalShortcut.unregister(shortcutAccelerator);
}
}
} catch (error) {
console.error('Error unregestering old shortcutAccelerator', error);
}
if (shortcut) {
store.set(setting, shortcut);
registerShortcut(shortcut, handlers.get(setting));
} else {
store.delete(setting);
}
});
ipc.answerRenderer('toggle-shortcuts', ({enabled}) => {
if (enabled) {
registrerFromStore();
} else {
globalShortcut.unregisterAll();
}
});
// Register keyboard shortcuts from store
registrerFromStore();
};
module.exports = {
initializeGlobalAccelerators,
setCropperShortcutAction
};