Skip to content

Commit cd4401a

Browse files
committed
fixes #86
1 parent dd63a87 commit cd4401a

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed

app/appshell/app-menu.ts

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,47 @@
1+
/* eslint no-undef:0 */
12
/* globals Electron, process */
23

34
interface MenuItemOptions extends Electron.MenuItemOptions {}
45

56
import * as _ from "lodash";
67
import * as assert from "assert";
7-
import { globalShortcut, Menu } from "electron";
8+
import { app, globalShortcut, Menu } from "electron";
89
import * as shell from "./shell";
910

1011
const menuTemplate: MenuItemOptions[] = [];
1112

1213
export const ERR_NOT_FOUND = "NOTFOUND";
1314

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+
1431
const __refreshMenu = _.debounce(function () {
1532
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+
}
1638
}, 100);
1739

18-
function _refreshMenu(callback: () => void) {
40+
function _refreshMenu(callback?: () => void) {
1941
__refreshMenu();
20-
process.nextTick(callback);
42+
if (callback) {
43+
process.nextTick(callback);
44+
}
2145
}
2246

2347
function _findMenuItemPosition(
@@ -168,7 +192,6 @@ export function addMenuItem(
168192

169193
if (key) {
170194
newObj.accelerator = key;
171-
globalShortcut.register(newObj.accelerator, newObj.click as Function);
172195
}
173196

174197
const parentObj = _findMenuItemById(parentId);
@@ -255,11 +278,7 @@ export function setMenuItemShortcut(
255278
}
256279
if (shortcut) {
257280
obj.accelerator = shortcut;
258-
globalShortcut.register(obj.accelerator, obj.click as Function);
259281
} else {
260-
if (obj.accelerator) {
261-
globalShortcut.unregister(obj.accelerator);
262-
}
263282
delete obj.accelerator;
264283
}
265284
_refreshMenu(callback.bind(null, null));

0 commit comments

Comments
 (0)