|
| 1 | +/* eslint no-undef:0 */ |
1 | 2 | /* globals Electron, process */
|
2 | 3 |
|
3 | 4 | interface MenuItemOptions extends Electron.MenuItemOptions {}
|
4 | 5 |
|
5 | 6 | import * as _ from "lodash";
|
6 | 7 | import * as assert from "assert";
|
7 |
| -import { globalShortcut, Menu } from "electron"; |
| 8 | +import { app, globalShortcut, Menu } from "electron"; |
8 | 9 | import * as shell from "./shell";
|
9 | 10 |
|
10 | 11 | const menuTemplate: MenuItemOptions[] = [];
|
11 | 12 |
|
12 | 13 | export const ERR_NOT_FOUND = "NOTFOUND";
|
13 | 14 |
|
| 15 | +app.on("browser-window-focus", function () { |
| 16 | + _refreshMenu(); |
| 17 | +}); |
| 18 | +app.on("browser-window-blur", function () { |
| 19 | + _refreshMenu(); |
| 20 | +}); |
| 21 | + |
| 22 | +function registerShortcuts(menuItem: MenuItemOptions) { |
| 23 | + if (menuItem.accelerator) { |
| 24 | + globalShortcut.register(menuItem.accelerator, menuItem.click as Function); |
| 25 | + } |
| 26 | + if (Array.isArray(menuItem.submenu)) { |
| 27 | + menuItem.submenu.forEach((i) => registerShortcuts(i)); |
| 28 | + } |
| 29 | +} |
| 30 | + |
14 | 31 | const __refreshMenu = _.debounce(function () {
|
15 | 32 | Menu.setApplicationMenu(Menu.buildFromTemplate(_.cloneDeep(menuTemplate)));
|
| 33 | + globalShortcut.unregisterAll(); |
| 34 | + const mainWindow = shell.getMainWindow(); |
| 35 | + if (mainWindow.isFocused()) { |
| 36 | + menuTemplate.forEach((menuItem) => registerShortcuts(menuItem)); |
| 37 | + } |
16 | 38 | }, 100);
|
17 | 39 |
|
18 |
| -function _refreshMenu(callback: () => void) { |
| 40 | +function _refreshMenu(callback?: () => void) { |
19 | 41 | __refreshMenu();
|
20 |
| - process.nextTick(callback); |
| 42 | + if (callback) { |
| 43 | + process.nextTick(callback); |
| 44 | + } |
21 | 45 | }
|
22 | 46 |
|
23 | 47 | function _findMenuItemPosition(
|
@@ -168,7 +192,6 @@ export function addMenuItem(
|
168 | 192 |
|
169 | 193 | if (key) {
|
170 | 194 | newObj.accelerator = key;
|
171 |
| - globalShortcut.register(newObj.accelerator, newObj.click as Function); |
172 | 195 | }
|
173 | 196 |
|
174 | 197 | const parentObj = _findMenuItemById(parentId);
|
@@ -255,11 +278,7 @@ export function setMenuItemShortcut(
|
255 | 278 | }
|
256 | 279 | if (shortcut) {
|
257 | 280 | obj.accelerator = shortcut;
|
258 |
| - globalShortcut.register(obj.accelerator, obj.click as Function); |
259 | 281 | } else {
|
260 |
| - if (obj.accelerator) { |
261 |
| - globalShortcut.unregister(obj.accelerator); |
262 |
| - } |
263 | 282 | delete obj.accelerator;
|
264 | 283 | }
|
265 | 284 | _refreshMenu(callback.bind(null, null));
|
|
0 commit comments