menubar.ts 29.9 KB
Newer Older
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import * as nls from 'vs/nls';
7
import { isMacintosh, language } from 'vs/base/common/platform';
8
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
9
import { app, shell, Menu, MenuItem, BrowserWindow } from 'electron';
B
Benjamin Pasero 已提交
10
import { OpenContext, IRunActionInWindowRequest, getTitleBarStyle } from 'vs/platform/windows/common/windows';
11
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
12 13 14 15 16
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IUpdateService, StateType } from 'vs/platform/update/common/update';
import product from 'vs/platform/node/product';
import { RunOnceScheduler } from 'vs/base/common/async';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
I
isidor 已提交
17
import { mnemonicMenuLabel as baseMnemonicLabel, unmnemonicLabel } from 'vs/base/common/labels';
18 19
import { IWindowsMainService, IWindowsCountChangedEvent } from 'vs/platform/windows/electron-main/windows';
import { IHistoryMainService } from 'vs/platform/history/common/history';
20
import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier, isWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
21
import { IMenubarData, IMenubarKeybinding, MenubarMenuItem, isMenubarMenuItemSeparator, isMenubarMenuItemSubmenu, isMenubarMenuItemAction, IMenubarMenu } from 'vs/platform/menubar/common/menubar';
22
import { URI } from 'vs/base/common/uri';
I
isidor 已提交
23
import { ILabelService } from 'vs/platform/label/common/label';
24
import { IStateService } from 'vs/platform/state/common/state';
25 26 27

const telemetryFrom = 'menu';

28 29 30 31 32
interface IMenuItemClickHandler {
	inDevTools: (contents: Electron.WebContents) => void;
	inNoWindow: () => void;
}

33 34 35
export class Menubar {

	private static readonly MAX_MENU_RECENT_ENTRIES = 10;
36
	private static readonly lastKnownMenubarStorageKey = 'lastKnownMenubarData';
37

38 39
	private isQuitting: boolean;
	private appMenuInstalled: boolean;
40
	private closedLastWindow: boolean;
41 42

	private menuUpdater: RunOnceScheduler;
43 44 45 46 47
	private menuGC: RunOnceScheduler;

	// Array to keep menus around so that GC doesn't cause crash as explained in #55347
	// TODO@sbatten Remove this when fixed upstream by Electron
	private oldMenus: Menu[];
48

49
	private menubarMenus: { [id: string]: IMenubarMenu };
50

S
SteVen Batten 已提交
51
	private keybindings: { [commandId: string]: IMenubarKeybinding };
S
SteVen Batten 已提交
52

53 54
	private fallbackMenuHandlers: { [id: string]: (menuItem: MenuItem, browserWindow: BrowserWindow, event: Electron.Event) => void } = {};

55 56 57 58 59 60 61
	constructor(
		@IUpdateService private updateService: IUpdateService,
		@IInstantiationService instantiationService: IInstantiationService,
		@IConfigurationService private configurationService: IConfigurationService,
		@IWindowsMainService private windowsMainService: IWindowsMainService,
		@IEnvironmentService private environmentService: IEnvironmentService,
		@ITelemetryService private telemetryService: ITelemetryService,
I
isidor 已提交
62
		@IHistoryMainService private historyMainService: IHistoryMainService,
63 64
		@ILabelService private labelService: ILabelService,
		@IStateService private stateService: IStateService
65 66
	) {
		this.menuUpdater = new RunOnceScheduler(() => this.doUpdateMenu(), 0);
S
SteVen Batten 已提交
67

68 69
		this.menuGC = new RunOnceScheduler(() => { this.oldMenus = []; }, 10000);

70 71
		this.menubarMenus = Object.create(null);
		this.keybindings = Object.create(null);
72

B
Benjamin Pasero 已提交
73
		if (isMacintosh || getTitleBarStyle(this.configurationService, this.environmentService) === 'native') {
74 75
			this.restoreCachedMenubarData();
		}
76 77

		this.addFallbackHandlers();
78

79 80
		this.closedLastWindow = false;

81 82
		this.oldMenus = [];

83 84 85 86 87
		this.install();

		this.registerListeners();
	}

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
	private restoreCachedMenubarData() {
		// TODO@sbatten remove this at some point down the road
		const outdatedKeys = ['lastKnownAdditionalKeybindings', 'lastKnownKeybindings', 'lastKnownMenubar'];
		outdatedKeys.forEach(key => this.stateService.removeItem(key));

		const menubarData = this.stateService.getItem<IMenubarData>(Menubar.lastKnownMenubarStorageKey);
		if (menubarData) {
			if (menubarData.menus) {
				this.menubarMenus = menubarData.menus;
			}

			if (menubarData.keybindings) {
				this.keybindings = menubarData.keybindings;
			}
		}
	}

105 106 107 108 109 110 111 112 113 114 115 116
	private addFallbackHandlers(): void {
		// File Menu Items
		this.fallbackMenuHandlers['workbench.action.files.newUntitledFile'] = () => this.windowsMainService.openNewWindow(OpenContext.MENU);
		this.fallbackMenuHandlers['workbench.action.newWindow'] = () => this.windowsMainService.openNewWindow(OpenContext.MENU);
		this.fallbackMenuHandlers['workbench.action.files.openFileFolder'] = (menuItem, win, event) => this.windowsMainService.pickFileFolderAndOpen({ forceNewWindow: this.isOptionClick(event), telemetryExtraData: { from: telemetryFrom } });
		this.fallbackMenuHandlers['workbench.action.openWorkspace'] = (menuItem, win, event) => this.windowsMainService.pickWorkspaceAndOpen({ forceNewWindow: this.isOptionClick(event), telemetryExtraData: { from: telemetryFrom } });

		// Recent Menu Items
		this.fallbackMenuHandlers['workbench.action.clearRecentFiles'] = () => this.historyMainService.clearRecentlyOpened();

		// Help Menu Items
		if (product.twitterUrl) {
S
SteVen Batten 已提交
117
			this.fallbackMenuHandlers['workbench.action.openTwitterUrl'] = () => this.openUrl(product.twitterUrl, 'openTwitterUrl');
118 119 120 121 122 123 124 125 126 127 128
		}

		if (product.requestFeatureUrl) {
			this.fallbackMenuHandlers['workbench.action.openRequestFeatureUrl'] = () => this.openUrl(product.requestFeatureUrl, 'openUserVoiceUrl');
		}

		if (product.reportIssueUrl) {
			this.fallbackMenuHandlers['workbench.action.openIssueReporter'] = () => this.openUrl(product.reportIssueUrl, 'openReportIssues');
		}

		if (product.licenseUrl) {
S
SteVen Batten 已提交
129
			this.fallbackMenuHandlers['workbench.action.openLicenseUrl'] = () => {
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
				if (language) {
					const queryArgChar = product.licenseUrl.indexOf('?') > 0 ? '&' : '?';
					this.openUrl(`${product.licenseUrl}${queryArgChar}lang=${language}`, 'openLicenseUrl');
				} else {
					this.openUrl(product.licenseUrl, 'openLicenseUrl');
				}
			};
		}

		if (product.privacyStatementUrl) {
			this.fallbackMenuHandlers['workbench.action.openPrivacyStatementUrl'] = () => {
				if (language) {
					const queryArgChar = product.licenseUrl.indexOf('?') > 0 ? '&' : '?';
					this.openUrl(`${product.privacyStatementUrl}${queryArgChar}lang=${language}`, 'openPrivacyStatement');
				} else {
					this.openUrl(product.privacyStatementUrl, 'openPrivacyStatement');
				}
			};
		}
	}

151 152 153 154 155 156 157 158
	private registerListeners(): void {

		// Keep flag when app quits
		app.on('will-quit', () => {
			this.isQuitting = true;
		});

		// // Listen to some events from window service to update menu
S
SteVen Batten 已提交
159
		this.historyMainService.onRecentlyOpenedChange(() => this.scheduleUpdateMenu());
160
		this.windowsMainService.onWindowsCountChanged(e => this.onWindowsCountChanged(e));
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
		// this.windowsMainService.onActiveWindowChanged(() => this.updateWorkspaceMenuItems());
		// this.windowsMainService.onWindowReady(() => this.updateWorkspaceMenuItems());
		// this.windowsMainService.onWindowClose(() => this.updateWorkspaceMenuItems());

		// Update when auto save config changes
		// this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(e));

		// Listen to update service
		// this.updateService.onStateChange(() => this.updateMenu());
	}

	private get currentEnableMenuBarMnemonics(): boolean {
		let enableMenuBarMnemonics = this.configurationService.getValue<boolean>('window.enableMenuBarMnemonics');
		if (typeof enableMenuBarMnemonics !== 'boolean') {
			enableMenuBarMnemonics = true;
		}
177

178 179 180 181
		return enableMenuBarMnemonics;
	}

	private get currentEnableNativeTabs(): boolean {
S
SteVen Batten 已提交
182 183 184 185
		if (!isMacintosh) {
			return false;
		}

186 187 188 189 190 191 192
		let enableNativeTabs = this.configurationService.getValue<boolean>('window.nativeTabs');
		if (typeof enableNativeTabs !== 'boolean') {
			enableNativeTabs = false;
		}
		return enableNativeTabs;
	}

193 194 195
	updateMenu(menubarData: IMenubarData, windowId: number) {
		this.menubarMenus = menubarData.menus;
		this.keybindings = menubarData.keybindings;
S
SteVen Batten 已提交
196

197
		// Save off new menu and keybindings
198
		this.stateService.setItem(Menubar.lastKnownMenubarStorageKey, menubarData);
199

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
		this.scheduleUpdateMenu();
	}


	private scheduleUpdateMenu(): void {
		this.menuUpdater.schedule(); // buffer multiple attempts to update the menu
	}

	private doUpdateMenu(): void {

		// Due to limitations in Electron, it is not possible to update menu items dynamically. The suggested
		// workaround from Electron is to set the application menu again.
		// See also https://github.com/electron/electron/issues/846
		//
		// Run delayed to prevent updating menu while it is open
		if (!this.isQuitting) {
			setTimeout(() => {
				if (!this.isQuitting) {
					this.install();
				}
			}, 10 /* delay this because there is an issue with updating a menu when it is open */);
		}
	}

224 225 226 227 228 229 230
	private onWindowsCountChanged(e: IWindowsCountChangedEvent): void {
		if (!isMacintosh) {
			return;
		}

		// Update menu if window count goes from N > 0 or 0 > N to update menu item enablement
		if ((e.oldCount === 0 && e.newCount > 0) || (e.oldCount > 0 && e.newCount === 0)) {
231
			this.closedLastWindow = e.newCount === 0;
232 233 234
			this.scheduleUpdateMenu();
		}
	}
235 236

	private install(): void {
237 238 239 240 241 242
		// Store old menu in our array to avoid GC to collect the menu and crash. See #55347
		// TODO@sbatten Remove this when fixed upstream by Electron
		const oldMenu = Menu.getApplicationMenu();
		if (oldMenu) {
			this.oldMenus.push(oldMenu);
		}
243

244 245 246 247 248 249 250
		// If we don't have a menu yet, set it to null to avoid the electron menu.
		// This should only happen on the first launch ever
		if (Object.keys(this.menubarMenus).length === 0) {
			Menu.setApplicationMenu(isMacintosh ? new Menu() : null);
			return;
		}

251 252 253 254 255 256 257 258 259
		// Menus
		const menubar = new Menu();

		// Mac: Application
		let macApplicationMenuItem: Electron.MenuItem;
		if (isMacintosh) {
			const applicationMenu = new Menu();
			macApplicationMenuItem = new MenuItem({ label: product.nameShort, submenu: applicationMenu });
			this.setMacApplicationMenu(applicationMenu);
260
			menubar.append(macApplicationMenuItem);
261 262
		}

263
		// Mac: Dock
264 265 266 267 268 269 270 271 272
		if (isMacintosh && !this.appMenuInstalled) {
			this.appMenuInstalled = true;

			const dockMenu = new Menu();
			dockMenu.append(new MenuItem({ label: this.mnemonicLabel(nls.localize({ key: 'miNewWindow', comment: ['&& denotes a mnemonic'] }, "New &&Window")), click: () => this.windowsMainService.openNewWindow(OpenContext.DOCK) }));

			app.dock.setMenu(dockMenu);
		}

273 274 275 276
		// File
		const fileMenu = new Menu();
		const fileMenuItem = new MenuItem({ label: this.mnemonicLabel(nls.localize({ key: 'mFile', comment: ['&& denotes a mnemonic'] }, "&&File")), submenu: fileMenu });

277 278
		this.setMenuById(fileMenu, 'File');
		menubar.append(fileMenuItem);
279

280 281 282 283
		// Edit
		const editMenu = new Menu();
		const editMenuItem = new MenuItem({ label: this.mnemonicLabel(nls.localize({ key: 'mEdit', comment: ['&& denotes a mnemonic'] }, "&&Edit")), submenu: editMenu });

284 285
		this.setMenuById(editMenu, 'Edit');
		menubar.append(editMenuItem);
286 287 288 289

		// Selection
		const selectionMenu = new Menu();
		const selectionMenuItem = new MenuItem({ label: this.mnemonicLabel(nls.localize({ key: 'mSelection', comment: ['&& denotes a mnemonic'] }, "&&Selection")), submenu: selectionMenu });
290

291 292
		this.setMenuById(selectionMenu, 'Selection');
		menubar.append(selectionMenuItem);
293 294

		// View
295 296 297
		const viewMenu = new Menu();
		const viewMenuItem = new MenuItem({ label: this.mnemonicLabel(nls.localize({ key: 'mView', comment: ['&& denotes a mnemonic'] }, "&&View")), submenu: viewMenu });

298 299
		this.setMenuById(viewMenu, 'View');
		menubar.append(viewMenuItem);
300

301
		// Go
302 303
		const gotoMenu = new Menu();
		const gotoMenuItem = new MenuItem({ label: this.mnemonicLabel(nls.localize({ key: 'mGoto', comment: ['&& denotes a mnemonic'] }, "&&Go")), submenu: gotoMenu });
304

305 306
		this.setMenuById(gotoMenu, 'Go');
		menubar.append(gotoMenuItem);
307

308 309 310 311
		// Debug
		const debugMenu = new Menu();
		const debugMenuItem = new MenuItem({ label: this.mnemonicLabel(nls.localize({ key: 'mDebug', comment: ['&& denotes a mnemonic'] }, "&&Debug")), submenu: debugMenu });

312 313
		this.setMenuById(debugMenu, 'Debug');
		menubar.append(debugMenuItem);
314

315 316 317
		// Terminal
		const terminalMenu = new Menu();
		const terminalMenuItem = new MenuItem({ label: this.mnemonicLabel(nls.localize({ key: 'mTerminal', comment: ['&& denotes a mnemonic'] }, "&&Terminal")), submenu: terminalMenu });
318

319 320
		this.setMenuById(terminalMenu, 'Terminal');
		menubar.append(terminalMenuItem);
321

322 323
		// Mac: Window
		let macWindowMenuItem: Electron.MenuItem;
S
SteVen Batten 已提交
324
		if (this.shouldDrawMenu('Window')) {
325 326 327 328
			const windowMenu = new Menu();
			macWindowMenuItem = new MenuItem({ label: this.mnemonicLabel(nls.localize('mWindow', "Window")), submenu: windowMenu, role: 'window' });
			this.setMacWindowMenu(windowMenu);
		}
329 330 331 332 333

		if (macWindowMenuItem) {
			menubar.append(macWindowMenuItem);
		}

334 335 336 337
		// Help
		const helpMenu = new Menu();
		const helpMenuItem = new MenuItem({ label: this.mnemonicLabel(nls.localize({ key: 'mHelp', comment: ['&& denotes a mnemonic'] }, "&&Help")), submenu: helpMenu, role: 'help' });

338 339
		this.setMenuById(helpMenu, 'Help');
		menubar.append(helpMenuItem);
340

S
SteVen Batten 已提交
341 342 343 344 345
		if (menubar.items && menubar.items.length > 0) {
			Menu.setApplicationMenu(menubar);
		} else {
			Menu.setApplicationMenu(null);
		}
346 347 348

		// Dispose of older menus after some time
		this.menuGC.schedule();
349 350 351 352 353
	}

	private setMacApplicationMenu(macApplicationMenu: Electron.Menu): void {
		const about = new MenuItem({ label: nls.localize('mAbout', "About {0}", product.nameLong), role: 'about' });
		const checkForUpdates = this.getUpdateMenuItems();
S
SteVen Batten 已提交
354 355 356 357 358 359 360 361

		let preferences;
		if (this.shouldDrawMenu('Preferences')) {
			const preferencesMenu = new Menu();
			this.setMenuById(preferencesMenu, 'Preferences');
			preferences = new MenuItem({ label: this.mnemonicLabel(nls.localize({ key: 'miPreferences', comment: ['&& denotes a mnemonic'] }, "&&Preferences")), submenu: preferencesMenu });
		}

362 363 364 365 366 367 368
		const servicesMenu = new Menu();
		const services = new MenuItem({ label: nls.localize('mServices', "Services"), role: 'services', submenu: servicesMenu });
		const hide = new MenuItem({ label: nls.localize('mHide', "Hide {0}", product.nameLong), role: 'hide', accelerator: 'Command+H' });
		const hideOthers = new MenuItem({ label: nls.localize('mHideOthers', "Hide Others"), role: 'hideothers', accelerator: 'Command+Alt+H' });
		const showAll = new MenuItem({ label: nls.localize('mShowAll', "Show All"), role: 'unhide' });
		const quit = new MenuItem(this.likeAction('workbench.action.quit', {
			label: nls.localize('miQuit', "Quit {0}", product.nameLong), click: () => {
B
Benjamin Pasero 已提交
369 370 371 372 373 374
				if (
					this.windowsMainService.getWindowCount() === 0 || 			// allow to quit when no more windows are open
					!!this.windowsMainService.getFocusedWindow() ||				// allow to quit when window has focus (fix for https://github.com/Microsoft/vscode/issues/39191)
					this.windowsMainService.getLastActiveWindow().isMinimized()	// allow to quit when window has no focus but is minimized (https://github.com/Microsoft/vscode/issues/63000)
				) {
					this.windowsMainService.quit();
375 376 377 378 379 380
				}
			}
		}));

		const actions = [about];
		actions.push(...checkForUpdates);
S
SteVen Batten 已提交
381 382 383 384 385 386 387 388

		if (preferences) {
			actions.push(...[
				__separator__(),
				preferences
			]);
		}

389 390 391 392 393 394 395 396 397 398 399 400 401 402
		actions.push(...[
			__separator__(),
			services,
			__separator__(),
			hide,
			hideOthers,
			showAll,
			__separator__(),
			quit
		]);

		actions.forEach(i => macApplicationMenu.append(i));
	}

403
	private shouldDrawMenu(menuId: string): boolean {
S
SteVen Batten 已提交
404
		// We need to draw an empty menu to override the electron default
B
Benjamin Pasero 已提交
405
		if (!isMacintosh && getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') {
S
SteVen Batten 已提交
406 407 408
			return false;
		}

409 410 411
		switch (menuId) {
			case 'File':
			case 'Help':
S
SteVen Batten 已提交
412
				if (isMacintosh) {
413 414
					return (this.windowsMainService.getWindowCount() === 0 && this.closedLastWindow) || (!!this.menubarMenus && !!this.menubarMenus[menuId]);
				}
S
SteVen Batten 已提交
415

416 417 418
			case 'Window':
				if (isMacintosh) {
					return (this.windowsMainService.getWindowCount() === 0 && this.closedLastWindow) || !!this.menubarMenus;
S
SteVen Batten 已提交
419
				}
S
SteVen Batten 已提交
420

421
			default:
422
				return this.windowsMainService.getWindowCount() > 0 && (!!this.menubarMenus && !!this.menubarMenus[menuId]);
423 424 425 426
		}
	}


427 428 429
	private setMenu(menu: Electron.Menu, items: Array<MenubarMenuItem>) {
		items.forEach((item: MenubarMenuItem) => {
			if (isMenubarMenuItemSeparator(item)) {
430
				menu.append(__separator__());
431 432 433 434 435 436 437 438
			} else if (isMenubarMenuItemSubmenu(item)) {
				const submenu = new Menu();
				const submenuItem = new MenuItem({ label: this.mnemonicLabel(item.label), submenu: submenu });
				this.setMenu(submenu, item.submenu.items);
				menu.append(submenuItem);
			} else if (isMenubarMenuItemAction(item)) {
				if (item.id === 'workbench.action.openRecent') {
					this.insertRecentMenuItems(menu);
S
SteVen Batten 已提交
439 440
				} else if (item.id === 'workbench.action.showAboutDialog') {
					this.insertCheckForUpdatesItems(menu);
441 442
				}

443 444 445 446 447 448 449 450 451
				if (isMacintosh) {
					if (this.windowsMainService.getWindowCount() === 0 && this.closedLastWindow) {
						// In the fallback scenario, we are either disabled or using a fallback handler
						if (this.fallbackMenuHandlers[item.id]) {
							menu.append(new MenuItem(this.likeAction(item.id, { label: this.mnemonicLabel(item.label), click: this.fallbackMenuHandlers[item.id] })));
						} else {
							menu.append(this.createMenuItem(item.label, item.id, false, item.checked));
						}
					} else {
452
						menu.append(this.createMenuItem(item.label, item.id, item.enabled === false ? false : true, !!item.checked));
453 454
					}
				} else {
455
					menu.append(this.createMenuItem(item.label, item.id, item.enabled === false ? false : true, !!item.checked));
456
				}
457
			}
458 459 460
		});
	}

461
	private setMenuById(menu: Electron.Menu, menuId: string): void {
462
		if (this.menubarMenus && this.menubarMenus[menuId]) {
S
SteVen Batten 已提交
463 464
			this.setMenu(menu, this.menubarMenus[menuId].items);
		}
465 466
	}

S
SteVen Batten 已提交
467 468 469 470 471 472 473 474
	private insertCheckForUpdatesItems(menu: Electron.Menu) {
		const updateItems = this.getUpdateMenuItems();
		if (updateItems.length) {
			updateItems.forEach(i => menu.append(i));
			menu.append(__separator__());
		}
	}

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
	private insertRecentMenuItems(menu: Electron.Menu) {
		const { workspaces, files } = this.historyMainService.getRecentlyOpened();

		// Workspaces
		if (workspaces.length > 0) {
			for (let i = 0; i < Menubar.MAX_MENU_RECENT_ENTRIES && i < workspaces.length; i++) {
				menu.append(this.createOpenRecentMenuItem(workspaces[i], 'openRecentWorkspace', false));
			}

			menu.append(__separator__());
		}

		// Files
		if (files.length > 0) {
			for (let i = 0; i < Menubar.MAX_MENU_RECENT_ENTRIES && i < files.length; i++) {
				menu.append(this.createOpenRecentMenuItem(files[i], 'openRecentFile', true));
			}

			menu.append(__separator__());
		}
	}

497
	private createOpenRecentMenuItem(workspaceOrFile: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | URI, commandId: string, isFile: boolean): Electron.MenuItem {
498
		let label: string;
499
		let uri: URI;
500
		if (isSingleFolderWorkspaceIdentifier(workspaceOrFile) && !isFile) {
I
isidor 已提交
501
			label = unmnemonicLabel(this.labelService.getWorkspaceLabel(workspaceOrFile, { verbose: true }));
502 503
			uri = workspaceOrFile;
		} else if (isWorkspaceIdentifier(workspaceOrFile)) {
I
isidor 已提交
504
			label = this.labelService.getWorkspaceLabel(workspaceOrFile, { verbose: true });
505
			uri = URI.file(workspaceOrFile.configPath);
506
		} else {
I
isidor 已提交
507
			label = unmnemonicLabel(this.labelService.getUriLabel(workspaceOrFile));
508
			uri = workspaceOrFile;
509 510 511 512 513 514 515 516 517
		}

		return new MenuItem(this.likeAction(commandId, {
			label,
			click: (menuItem, win, event) => {
				const openInNewWindow = this.isOptionClick(event);
				const success = this.windowsMainService.open({
					context: OpenContext.MENU,
					cli: this.environmentService.args,
S
Sandeep Somavarapu 已提交
518
					urisToOpen: [uri],
519
					forceNewWindow: openInNewWindow,
520 521 522 523
					forceOpenWorkspaceAsFile: isFile
				}).length > 0;

				if (!success) {
524
					this.historyMainService.removeFromRecentlyOpened([workspaceOrFile]);
525 526 527 528 529 530 531 532 533
				}
			}
		}, false));
	}

	private isOptionClick(event: Electron.Event): boolean {
		return event && ((!isMacintosh && (event.ctrlKey || event.shiftKey)) || (isMacintosh && (event.metaKey || event.altKey)));
	}

534 535 536 537 538 539 540 541 542 543
	private createRoleMenuItem(label: string, commandId: string, role: any): Electron.MenuItem {
		const options: Electron.MenuItemConstructorOptions = {
			label: this.mnemonicLabel(label),
			role,
			enabled: true
		};

		return new MenuItem(this.withKeybinding(commandId, options));
	}

544 545 546 547 548 549 550 551
	private setMacWindowMenu(macWindowMenu: Electron.Menu): void {
		const minimize = new MenuItem({ label: nls.localize('mMinimize', "Minimize"), role: 'minimize', accelerator: 'Command+M', enabled: this.windowsMainService.getWindowCount() > 0 });
		const zoom = new MenuItem({ label: nls.localize('mZoom', "Zoom"), role: 'zoom', enabled: this.windowsMainService.getWindowCount() > 0 });
		const bringAllToFront = new MenuItem({ label: nls.localize('mBringToFront', "Bring All to Front"), role: 'front', enabled: this.windowsMainService.getWindowCount() > 0 });
		const switchWindow = this.createMenuItem(nls.localize({ key: 'miSwitchWindow', comment: ['&& denotes a mnemonic'] }, "Switch &&Window..."), 'workbench.action.switchWindow');

		const nativeTabMenuItems: Electron.MenuItem[] = [];
		if (this.currentEnableNativeTabs) {
552 553
			nativeTabMenuItems.push(__separator__());

B
Benjamin Pasero 已提交
554
			nativeTabMenuItems.push(this.createMenuItem(nls.localize('mNewTab', "New Tab"), 'workbench.action.newWindowTab'));
555

B
Benjamin Pasero 已提交
556 557 558 559
			nativeTabMenuItems.push(this.createRoleMenuItem(nls.localize('mShowPreviousTab', "Show Previous Tab"), 'workbench.action.showPreviousWindowTab', 'selectPreviousTab'));
			nativeTabMenuItems.push(this.createRoleMenuItem(nls.localize('mShowNextTab', "Show Next Tab"), 'workbench.action.showNextWindowTab', 'selectNextTab'));
			nativeTabMenuItems.push(this.createRoleMenuItem(nls.localize('mMoveTabToNewWindow', "Move Tab to New Window"), 'workbench.action.moveWindowTabToNewWindow', 'moveTabToNewWindow'));
			nativeTabMenuItems.push(this.createRoleMenuItem(nls.localize('mMergeAllWindows', "Merge All Windows"), 'workbench.action.mergeAllWindowTabs', 'mergeAllWindows'));
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
		}

		[
			minimize,
			zoom,
			switchWindow,
			...nativeTabMenuItems,
			__separator__(),
			bringAllToFront
		].forEach(item => macWindowMenu.append(item));
	}

	private getUpdateMenuItems(): Electron.MenuItem[] {
		const state = this.updateService.state;

		switch (state.type) {
			case StateType.Uninitialized:
				return [];

			case StateType.Idle:
				return [new MenuItem({
S
SteVen Batten 已提交
581
					label: this.mnemonicLabel(nls.localize('miCheckForUpdates', "Check for &&Updates...")), click: () => setTimeout(() => {
582 583 584 585 586 587 588 589 590 591 592 593 594
						this.reportMenuActionTelemetry('CheckForUpdate');

						const focusedWindow = this.windowsMainService.getFocusedWindow();
						const context = focusedWindow ? { windowId: focusedWindow.id } : null;
						this.updateService.checkForUpdates(context);
					}, 0)
				})];

			case StateType.CheckingForUpdates:
				return [new MenuItem({ label: nls.localize('miCheckingForUpdates', "Checking For Updates..."), enabled: false })];

			case StateType.AvailableForDownload:
				return [new MenuItem({
S
SteVen Batten 已提交
595
					label: this.mnemonicLabel(nls.localize('miDownloadUpdate', "D&&ownload Available Update")), click: () => {
596 597 598 599 600 601 602 603 604
						this.updateService.downloadUpdate();
					}
				})];

			case StateType.Downloading:
				return [new MenuItem({ label: nls.localize('miDownloadingUpdate', "Downloading Update..."), enabled: false })];

			case StateType.Downloaded:
				return [new MenuItem({
S
SteVen Batten 已提交
605
					label: this.mnemonicLabel(nls.localize('miInstallUpdate', "Install &&Update...")), click: () => {
606 607 608 609 610 611 612 613 614 615
						this.reportMenuActionTelemetry('InstallUpdate');
						this.updateService.applyUpdate();
					}
				})];

			case StateType.Updating:
				return [new MenuItem({ label: nls.localize('miInstallingUpdate', "Installing Update..."), enabled: false })];

			case StateType.Ready:
				return [new MenuItem({
S
SteVen Batten 已提交
616
					label: this.mnemonicLabel(nls.localize('miRestartToUpdate', "Restart to &&Update...")), click: () => {
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
						this.reportMenuActionTelemetry('RestartToUpdate');
						this.updateService.quitAndInstall();
					}
				})];
		}
	}

	private createMenuItem(label: string, commandId: string | string[], enabled?: boolean, checked?: boolean): Electron.MenuItem;
	private createMenuItem(label: string, click: () => void, enabled?: boolean, checked?: boolean): Electron.MenuItem;
	private createMenuItem(arg1: string, arg2: any, arg3?: boolean, arg4?: boolean): Electron.MenuItem {
		const label = this.mnemonicLabel(arg1);
		const click: () => void = (typeof arg2 === 'function') ? arg2 : (menuItem: Electron.MenuItem, win: Electron.BrowserWindow, event: Electron.Event) => {
			let commandId = arg2;
			if (Array.isArray(arg2)) {
				commandId = this.isOptionClick(event) ? arg2[1] : arg2[0]; // support alternative action if we got multiple action Ids and the option key was pressed while invoking
			}

			this.runActionInRenderer(commandId);
		};
		const enabled = typeof arg3 === 'boolean' ? arg3 : this.windowsMainService.getWindowCount() > 0;
		const checked = typeof arg4 === 'boolean' ? arg4 : false;

		const options: Electron.MenuItemConstructorOptions = {
			label,
			click,
			enabled
		};

		if (checked) {
			options['type'] = 'checkbox';
			options['checked'] = checked;
		}

		let commandId: string;
		if (typeof arg2 === 'string') {
			commandId = arg2;
		} else if (Array.isArray(arg2)) {
			commandId = arg2[0];
		}

S
SteVen Batten 已提交
657
		if (isMacintosh) {
658
			// Add role for special case menu items
S
SteVen Batten 已提交
659 660 661 662 663 664 665
			if (commandId === 'editor.action.clipboardCutAction') {
				options['role'] = 'cut';
			} else if (commandId === 'editor.action.clipboardCopyAction') {
				options['role'] = 'copy';
			} else if (commandId === 'editor.action.clipboardPasteAction') {
				options['role'] = 'paste';
			}
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683

			// Add context aware click handlers for special case menu items
			if (commandId === 'undo') {
				options.click = this.makeContextAwareClickHandler(click, {
					inDevTools: devTools => devTools.undo(),
					inNoWindow: () => Menu.sendActionToFirstResponder('undo:')
				});
			} else if (commandId === 'redo') {
				options.click = this.makeContextAwareClickHandler(click, {
					inDevTools: devTools => devTools.redo(),
					inNoWindow: () => Menu.sendActionToFirstResponder('redo:')
				});
			} else if (commandId === 'editor.action.selectAll') {
				options.click = this.makeContextAwareClickHandler(click, {
					inDevTools: devTools => devTools.selectAll(),
					inNoWindow: () => Menu.sendActionToFirstResponder('selectAll:')
				});
			}
S
SteVen Batten 已提交
684 685
		}

686 687 688
		return new MenuItem(this.withKeybinding(commandId, options));
	}

689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
	private makeContextAwareClickHandler(click: () => void, contextSpecificHandlers: IMenuItemClickHandler): () => void {
		return () => {
			// No Active Window
			const activeWindow = this.windowsMainService.getFocusedWindow();
			if (!activeWindow) {
				return contextSpecificHandlers.inNoWindow();
			}

			// DevTools focused
			if (activeWindow.win.webContents.isDevToolsFocused()) {
				return contextSpecificHandlers.inDevTools(activeWindow.win.webContents.devToolsWebContents);
			}

			// Finally execute command in Window
			click();
		};
	}

707 708 709 710
	private runActionInRenderer(id: string): void {
		// We make sure to not run actions when the window has no focus, this helps
		// for https://github.com/Microsoft/vscode/issues/25907 and specifically for
		// https://github.com/Microsoft/vscode/issues/11928
B
Benjamin Pasero 已提交
711 712 713 714 715 716 717 718 719 720
		// Still allow to run when the last active window is minimized though for
		// https://github.com/Microsoft/vscode/issues/63000
		let activeWindow = this.windowsMainService.getFocusedWindow();
		if (!activeWindow) {
			const lastActiveWindow = this.windowsMainService.getLastActiveWindow();
			if (lastActiveWindow.isMinimized()) {
				activeWindow = lastActiveWindow;
			}
		}

721 722 723 724 725 726
		if (activeWindow) {
			this.windowsMainService.sendToFocused('vscode:runAction', { id, from: 'menu' } as IRunActionInWindowRequest);
		}
	}

	private withKeybinding(commandId: string, options: Electron.MenuItemConstructorOptions): Electron.MenuItemConstructorOptions {
S
SteVen Batten 已提交
727
		const binding = this.keybindings[commandId];
728 729 730 731 732

		// Apply binding if there is one
		if (binding && binding.label) {

			// if the binding is native, we can just apply it
733
			if (binding.isNative !== false) {
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
				options.accelerator = binding.label;
			}

			// the keybinding is not native so we cannot show it as part of the accelerator of
			// the menu item. we fallback to a different strategy so that we always display it
			else {
				const bindingIndex = options.label.indexOf('[');
				if (bindingIndex >= 0) {
					options.label = `${options.label.substr(0, bindingIndex)} [${binding.label}]`;
				} else {
					options.label = `${options.label} [${binding.label}]`;
				}
			}
		}

		// Unset bindings if there is none
		else {
			options.accelerator = void 0;
		}

		return options;
	}

	private likeAction(commandId: string, options: Electron.MenuItemConstructorOptions, setAccelerator = !options.accelerator): Electron.MenuItemConstructorOptions {
		if (setAccelerator) {
			options = this.withKeybinding(commandId, options);
		}

		const originalClick = options.click;
		options.click = (item, window, event) => {
			this.reportMenuActionTelemetry(commandId);
			if (originalClick) {
				originalClick(item, window, event);
			}
		};

		return options;
	}

	private openUrl(url: string, id: string): void {
		shell.openExternal(url);
		this.reportMenuActionTelemetry(id);
	}

	private reportMenuActionTelemetry(id: string): void {
		/* __GDPR__
			"workbenchActionExecuted" : {
				"id" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
				"from": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
			}
		*/
		this.telemetryService.publicLog('workbenchActionExecuted', { id, from: telemetryFrom });
	}

	private mnemonicLabel(label: string): string {
		return baseMnemonicLabel(label, !this.currentEnableMenuBarMnemonics);
	}
}

function __separator__(): Electron.MenuItem {
	return new MenuItem({ type: 'separator' });
}