electron/lib/browser/api/menu.js

286 lines
8.8 KiB
JavaScript
Raw Normal View History

2020-03-20 20:28:31 +00:00
'use strict';
2020-03-20 20:28:31 +00:00
const { TopLevelWindow, MenuItem, webContents } = require('electron');
const { sortMenuItems } = require('@electron/internal/browser/api/menu-utils');
const EventEmitter = require('events').EventEmitter;
const v8Util = process.electronBinding('v8_util');
const bindings = process.electronBinding('menu');
2016-01-12 02:40:23 +00:00
2020-03-20 20:28:31 +00:00
const { Menu } = bindings;
let applicationMenu = null;
let groupIdIndex = 0;
2017-10-23 18:47:47 +00:00
/* Instance Methods */
2017-10-23 22:35:16 +00:00
Menu.prototype._init = function () {
2020-03-20 20:28:31 +00:00
this.commandsMap = {};
this.groupsMap = {};
this.items = [];
2020-04-02 23:07:56 +00:00
};
Menu.prototype._isCommandIdChecked = function (id) {
return this.commandsMap[id] ? this.commandsMap[id].checked : undefined;
};
Menu.prototype._isCommandIdEnabled = function (id) {
return this.commandsMap[id] ? this.commandsMap[id].enabled : undefined;
};
Menu.prototype._shouldCommandIdWorkWhenHidden = function (id) {
return this.commandsMap[id] ? this.commandsMap[id].acceleratorWorksWhenHidden : undefined;
};
Menu.prototype._isCommandIdVisible = function (id) {
return this.commandsMap[id] ? this.commandsMap[id].visible : undefined;
};
Menu.prototype._getAcceleratorForCommandId = function (id, useDefaultAccelerator) {
const command = this.commandsMap[id];
if (!command) return;
if (command.accelerator != null) return command.accelerator;
if (useDefaultAccelerator) return command.getDefaultRoleAccelerator();
};
Menu.prototype._shouldRegisterAcceleratorForCommandId = function (id) {
return this.commandsMap[id] ? this.commandsMap[id].registerAccelerator : undefined;
};
Menu.prototype._executeCommand = function (event, id) {
const command = this.commandsMap[id];
if (!command) return;
command.click(event, TopLevelWindow.getFocusedWindow(), webContents.getFocusedWebContents());
};
Menu.prototype._menuWillShow = function () {
// Ensure radio groups have at least one menu item selected
for (const id of Object.keys(this.groupsMap)) {
const found = this.groupsMap[id].find(item => item.checked) || null;
if (!found) v8Util.setHiddenValue(this.groupsMap[id][0], 'checked', true);
}
2020-03-20 20:28:31 +00:00
};
2017-10-23 18:47:47 +00:00
Menu.prototype.popup = function (options = {}) {
if (options == null || typeof options !== 'object') {
2020-03-20 20:28:31 +00:00
throw new TypeError('Options must be an object');
}
2020-03-20 20:28:31 +00:00
let { window, x, y, positioningItem, callback } = options;
2017-10-23 22:35:16 +00:00
2018-02-20 01:59:27 +00:00
// no callback passed
2020-03-20 20:28:31 +00:00
if (!callback || typeof callback !== 'function') callback = () => {};
2017-10-23 22:35:16 +00:00
// set defaults
2020-03-20 20:28:31 +00:00
if (typeof x !== 'number') x = -1;
if (typeof y !== 'number') y = -1;
if (typeof positioningItem !== 'number') positioningItem = -1;
2018-02-20 01:59:27 +00:00
// find which window to use
2020-03-20 20:28:31 +00:00
const wins = TopLevelWindow.getAllWindows();
if (!wins || wins.indexOf(window) === -1) {
2020-03-20 20:28:31 +00:00
window = TopLevelWindow.getFocusedWindow();
if (!window && wins && wins.length > 0) {
2020-03-20 20:28:31 +00:00
window = wins[0];
}
if (!window) {
2020-03-20 20:28:31 +00:00
throw new Error('Cannot open Menu without a TopLevelWindow present');
}
}
2017-10-23 22:35:16 +00:00
2020-03-20 20:28:31 +00:00
this.popupAt(window, x, y, positioningItem, callback);
return { browserWindow: window, x, y, position: positioningItem };
};
Menu.prototype.closePopup = function (window) {
2018-04-17 08:14:49 +00:00
if (window instanceof TopLevelWindow) {
2020-03-20 20:28:31 +00:00
this.closePopupAt(window.id);
2017-12-21 06:26:32 +00:00
} else {
// Passing -1 (invalid) would make closePopupAt close the all menu runners
// belong to this menu.
2020-03-20 20:28:31 +00:00
this.closePopupAt(-1);
}
2020-03-20 20:28:31 +00:00
};
Menu.prototype.getMenuItemById = function (id) {
2020-03-20 20:28:31 +00:00
const items = this.items;
2020-03-20 20:28:31 +00:00
let found = items.find(item => item.id === id) || null;
for (let i = 0; !found && i < items.length; i++) {
if (items[i].submenu) {
2020-03-20 20:28:31 +00:00
found = items[i].submenu.getMenuItemById(id);
}
}
2020-03-20 20:28:31 +00:00
return found;
};
2017-10-23 22:35:16 +00:00
Menu.prototype.append = function (item) {
2020-03-20 20:28:31 +00:00
return this.insert(this.getItemCount(), item);
};
2017-10-23 22:35:16 +00:00
Menu.prototype.insert = function (pos, item) {
if ((item ? item.constructor : undefined) !== MenuItem) {
2020-03-20 20:28:31 +00:00
throw new TypeError('Invalid item');
2017-10-23 18:47:47 +00:00
}
if (pos < 0) {
2020-03-20 20:28:31 +00:00
throw new RangeError(`Position ${pos} cannot be less than 0`);
} else if (pos > this.getItemCount()) {
2020-03-20 20:28:31 +00:00
throw new RangeError(`Position ${pos} cannot be greater than the total MenuItem count`);
}
// insert item depending on its type
2020-03-20 20:28:31 +00:00
insertItemByType.call(this, item, pos);
// set item properties
2020-03-20 20:28:31 +00:00
if (item.sublabel) this.setSublabel(pos, item.sublabel);
if (item.toolTip) this.setToolTip(pos, item.toolTip);
if (item.icon) this.setIcon(pos, item.icon);
if (item.role) this.setRole(pos, item.role);
// Make menu accessable to items.
2020-03-20 20:28:31 +00:00
item.overrideReadOnlyProperty('menu', this);
2016-01-12 02:40:23 +00:00
// Remember the items.
2020-03-20 20:28:31 +00:00
this.items.splice(pos, 0, item);
this.commandsMap[item.commandId] = item;
};
2017-10-23 18:47:47 +00:00
2017-10-23 22:35:16 +00:00
Menu.prototype._callMenuWillShow = function () {
2020-03-20 20:28:31 +00:00
if (this.delegate) this.delegate.menuWillShow(this);
2017-10-23 22:35:16 +00:00
this.items.forEach(item => {
2020-03-20 20:28:31 +00:00
if (item.submenu) item.submenu._callMenuWillShow();
});
};
2017-10-23 22:35:16 +00:00
/* Static Methods */
2020-03-20 20:28:31 +00:00
Menu.getApplicationMenu = () => applicationMenu;
2020-03-20 20:28:31 +00:00
Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder;
// set application menu with a preexisting menu
2017-10-23 22:35:16 +00:00
Menu.setApplicationMenu = function (menu) {
if (menu && menu.constructor !== Menu) {
2020-03-20 20:28:31 +00:00
throw new TypeError('Invalid menu');
2017-10-23 22:35:16 +00:00
}
2017-10-23 18:47:47 +00:00
2020-03-20 20:28:31 +00:00
applicationMenu = menu;
v8Util.setHiddenValue(global, 'applicationMenuSet', true);
2017-10-23 18:47:47 +00:00
if (process.platform === 'darwin') {
2020-03-20 20:28:31 +00:00
if (!menu) return;
menu._callMenuWillShow();
bindings.setApplicationMenu(menu);
2017-10-23 18:47:47 +00:00
} else {
2020-03-20 20:28:31 +00:00
const windows = TopLevelWindow.getAllWindows();
return windows.map(w => w.setMenu(menu));
2016-01-12 02:40:23 +00:00
}
2020-03-20 20:28:31 +00:00
};
2016-01-12 02:40:23 +00:00
2017-10-23 22:35:16 +00:00
Menu.buildFromTemplate = function (template) {
if (!Array.isArray(template)) {
2020-03-20 20:28:31 +00:00
throw new TypeError('Invalid template for Menu: Menu template must be an array');
2017-10-23 22:35:16 +00:00
}
if (!areValidTemplateItems(template)) {
2020-03-20 20:28:31 +00:00
throw new TypeError('Invalid template for MenuItem: must have at least one of label, role or type');
}
2020-03-20 20:28:31 +00:00
const filtered = removeExtraSeparators(template);
const sorted = sortTemplate(filtered);
2020-03-20 20:28:31 +00:00
const menu = new Menu();
sorted.forEach(item => {
if (item instanceof MenuItem) {
2020-03-20 20:28:31 +00:00
menu.append(item);
} else {
2020-03-20 20:28:31 +00:00
menu.append(new MenuItem(item));
}
2020-03-20 20:28:31 +00:00
});
2017-10-23 22:35:16 +00:00
2020-03-20 20:28:31 +00:00
return menu;
};
2016-01-12 02:40:23 +00:00
/* Helper Functions */
2017-10-23 18:47:47 +00:00
// validate the template against having the wrong attribute
function areValidTemplateItems (template) {
return template.every(item =>
item != null &&
typeof item === 'object' &&
(Object.prototype.hasOwnProperty.call(item, 'label') ||
Object.prototype.hasOwnProperty.call(item, 'role') ||
2020-03-20 20:28:31 +00:00
item.type === 'separator'));
}
function sortTemplate (template) {
2020-03-20 20:28:31 +00:00
const sorted = sortMenuItems(template);
for (const item of sorted) {
if (Array.isArray(item.submenu)) {
2020-03-20 20:28:31 +00:00
item.submenu = sortTemplate(item.submenu);
}
}
2020-03-20 20:28:31 +00:00
return sorted;
}
// Search between separators to find a radio menu item and return its group id
function generateGroupId (items, pos) {
2017-10-23 22:35:16 +00:00
if (pos > 0) {
for (let idx = pos - 1; idx >= 0; idx--) {
2020-03-20 20:28:31 +00:00
if (items[idx].type === 'radio') return items[idx].groupId;
if (items[idx].type === 'separator') break;
2017-10-23 22:35:16 +00:00
}
} else if (pos < items.length) {
for (let idx = pos; idx <= items.length - 1; idx++) {
2020-03-20 20:28:31 +00:00
if (items[idx].type === 'radio') return items[idx].groupId;
if (items[idx].type === 'separator') break;
2017-10-23 03:57:23 +00:00
}
2017-10-23 18:47:47 +00:00
}
2020-03-20 20:28:31 +00:00
groupIdIndex += 1;
return groupIdIndex;
2017-10-23 22:35:16 +00:00
}
2017-10-23 18:47:47 +00:00
function removeExtraSeparators (items) {
// fold adjacent separators together
let ret = items.filter((e, idx, arr) => {
2020-03-20 20:28:31 +00:00
if (e.visible === false) return true;
return e.type !== 'separator' || idx === 0 || arr[idx - 1].type !== 'separator';
});
// remove edge separators
ret = ret.filter((e, idx, arr) => {
2020-03-20 20:28:31 +00:00
if (e.visible === false) return true;
return e.type !== 'separator' || (idx !== 0 && idx !== arr.length - 1);
});
2020-03-20 20:28:31 +00:00
return ret;
}
function insertItemByType (item, pos) {
const types = {
2017-10-25 14:17:41 +00:00
normal: () => this.insertItem(pos, item.commandId, item.label),
checkbox: () => this.insertCheckItem(pos, item.commandId, item.label),
separator: () => this.insertSeparator(pos),
submenu: () => this.insertSubMenu(pos, item.commandId, item.label, item.submenu),
radio: () => {
// Grouping radio menu items
2020-03-20 20:28:31 +00:00
item.overrideReadOnlyProperty('groupId', generateGroupId(this.items, pos));
if (this.groupsMap[item.groupId] == null) {
2020-03-20 20:28:31 +00:00
this.groupsMap[item.groupId] = [];
}
2020-03-20 20:28:31 +00:00
this.groupsMap[item.groupId].push(item);
// Setting a radio menu item should flip other items in the group.
2020-03-20 20:28:31 +00:00
v8Util.setHiddenValue(item, 'checked', item.checked);
Object.defineProperty(item, 'checked', {
enumerable: true,
get: () => v8Util.getHiddenValue(item, 'checked'),
set: () => {
this.groupsMap[item.groupId].forEach(other => {
2020-03-20 20:28:31 +00:00
if (other !== item) v8Util.setHiddenValue(other, 'checked', false);
});
v8Util.setHiddenValue(item, 'checked', true);
}
2020-03-20 20:28:31 +00:00
});
this.insertRadioItem(pos, item.commandId, item.label, item.groupId);
}
2020-03-20 20:28:31 +00:00
};
types[item.type]();
}
2020-03-20 20:28:31 +00:00
module.exports = Menu;