titlebarPart.ts 23.7 KB
Newer Older
B
Benjamin Pasero 已提交
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 'vs/css!./media/titlebarpart';
7
import * as resources from 'vs/base/common/resources';
B
Benjamin Pasero 已提交
8
import { Part } from 'vs/workbench/browser/part';
9
import { ITitleService, ITitleProperties } from 'vs/workbench/services/title/common/titleService';
B
Benjamin Pasero 已提交
10
import { getZoomFactor } from 'vs/base/browser/browser';
11
import { MenuBarVisibility, getTitleBarStyle, IWindowService } from 'vs/platform/windows/common/windows';
B
Benjamin Pasero 已提交
12 13
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { StandardMouseEvent } from 'vs/base/browser/mouseEvent';
14
import { IAction } from 'vs/base/common/actions';
15
import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
B
Benjamin Pasero 已提交
16
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
17
import { DisposableStore, dispose } from 'vs/base/common/lifecycle';
18
import * as nls from 'vs/nls';
B
Benjamin Pasero 已提交
19
import { EditorInput, toResource, Verbosity, SideBySideEditor } from 'vs/workbench/common/editor';
20
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
21
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
S
SteVen Batten 已提交
22
import { IThemeService, registerThemingParticipant, ITheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService';
23
import { TITLE_BAR_ACTIVE_BACKGROUND, TITLE_BAR_ACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_BACKGROUND, TITLE_BAR_BORDER } from 'vs/workbench/common/theme';
24
import { isMacintosh, isWindows, isLinux, isWeb } from 'vs/base/common/platform';
25
import { URI } from 'vs/base/common/uri';
R
Ryan Adolf 已提交
26
import { Color } from 'vs/base/common/color';
B
Benjamin Pasero 已提交
27
import { trim } from 'vs/base/common/strings';
S
SteVen Batten 已提交
28
import { EventType, EventHelper, Dimension, isAncestor, hide, show, removeClass, addClass, append, $, addDisposableListener, runAtThisOrScheduleAtNextAnimationFrame, removeNode } from 'vs/base/browser/dom';
29
import { CustomMenubarControl } from 'vs/workbench/browser/parts/titlebar/menubarControl';
30
import { IInstantiationService, optional } from 'vs/platform/instantiation/common/instantiation';
31
import { template } from 'vs/base/common/labels';
I
isidor 已提交
32
import { ILabelService } from 'vs/platform/label/common/label';
33
import { Event, Emitter } from 'vs/base/common/event';
B
Benjamin Pasero 已提交
34
import { IStorageService } from 'vs/platform/storage/common/storage';
35
import { Parts, IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
36
import { RunOnceScheduler } from 'vs/base/common/async';
37
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
38 39 40
import { createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { IMenuService, IMenu, MenuId } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
41
import { IHostService } from 'vs/workbench/services/host/browser/host';
B
Benjamin Pasero 已提交
42

43 44 45
// TODO@sbatten https://github.com/microsoft/vscode/issues/81360
// tslint:disable-next-line: import-patterns layering
import { IElectronService } from 'vs/platform/electron/node/electron';
46
// tslint:disable-next-line: import-patterns layering
47
import { IElectronEnvironmentService } from 'vs/workbench/services/electron/electron-browser/electronEnvironmentService';
48

49
export class TitlebarPart extends Part implements ITitleService {
B
Benjamin Pasero 已提交
50

51
	private static readonly NLS_UNSUPPORTED = nls.localize('patchedWindowTitle', "[Unsupported]");
52
	private static readonly NLS_USER_IS_ADMIN = isWindows ? nls.localize('userIsAdmin', "[Administrator]") : nls.localize('userIsSudo', "[Superuser]");
53 54 55
	private static readonly NLS_EXTENSION_HOST = nls.localize('devExtensionWindowTitlePrefix', "[Extension Development Host]");
	private static readonly TITLE_DIRTY = '\u25cf ';
	private static readonly TITLE_SEPARATOR = isMacintosh ? '' : ' - '; // macOS uses special - separator
56

57
	//#region IView
58

B
Benjamin Pasero 已提交
59 60
	readonly minimumWidth: number = 0;
	readonly maximumWidth: number = Number.POSITIVE_INFINITY;
S
SteVen Batten 已提交
61 62
	get minimumHeight(): number { return isMacintosh && !isWeb ? 22 / getZoomFactor() : (30 / (this.currentMenubarVisibility === 'hidden' ? getZoomFactor() : 1)); }
	get maximumHeight(): number { return isMacintosh && !isWeb ? 22 / getZoomFactor() : (30 / (this.currentMenubarVisibility === 'hidden' ? getZoomFactor() : 1)); }
B
Benjamin Pasero 已提交
63

64
	//#endregion
65

66
	private _onMenubarVisibilityChange = this._register(new Emitter<boolean>());
67
	readonly onMenubarVisibilityChange: Event<boolean> = this._onMenubarVisibilityChange.event;
68

69
	_serviceBrand: undefined;
B
Benjamin Pasero 已提交
70

71 72 73 74 75
	private title: HTMLElement;
	private dragRegion: HTMLElement;
	private windowControls: HTMLElement;
	private maxRestoreControl: HTMLElement;
	private appIcon: HTMLElement;
76
	private customMenubar: CustomMenubarControl | undefined;
S
SteVen Batten 已提交
77
	private menubar?: HTMLElement;
78
	private resizer: HTMLElement;
S
SteVen Batten 已提交
79
	private lastLayoutDimensions: Dimension;
B
Benjamin Pasero 已提交
80

B
Benjamin Pasero 已提交
81
	private pendingTitle: string;
82

B
Benjamin Pasero 已提交
83 84
	private isInactive: boolean;

85 86
	private readonly properties: ITitleProperties = { isPure: true, isAdmin: false };
	private readonly activeEditorListeners = this._register(new DisposableStore());
87

88 89
	private titleUpdater: RunOnceScheduler = this._register(new RunOnceScheduler(() => this.doUpdateTitle(), 0));

90 91
	private contextMenu: IMenu;

92
	constructor(
93 94 95
		@IContextMenuService private readonly contextMenuService: IContextMenuService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@IEditorService private readonly editorService: IEditorService,
96
		@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
97 98
		@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
		@IInstantiationService private readonly instantiationService: IInstantiationService,
I
isidor 已提交
99
		@IThemeService themeService: IThemeService,
100
		@ILabelService private readonly labelService: ILabelService,
101
		@IStorageService storageService: IStorageService,
102 103
		@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
		@IMenuService menuService: IMenuService,
104
		@IContextKeyService contextKeyService: IContextKeyService,
105
		@IHostService private readonly hostService: IHostService,
106
		@IWindowService windowService: IWindowService,
107 108
		@optional(IElectronService) private electronService: IElectronService,
		@optional(IElectronEnvironmentService) private readonly electronEnvironmentService: IElectronEnvironmentService
109
	) {
110
		super(Parts.TITLEBAR_PART, { hasTitle: false }, themeService, storageService, layoutService);
111

112 113
		this.contextMenu = this._register(menuService.createMenu(MenuId.TitleBarContext, contextKeyService));

114 115 116 117
		this.registerListeners();
	}

	private registerListeners(): void {
118
		this._register(this.hostService.onDidChangeFocus(focused => focused ? this.onFocus() : this.onBlur()));
B
Benjamin Pasero 已提交
119 120
		this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChanged(e)));
		this._register(this.editorService.onDidActiveEditorChange(() => this.onActiveEditorChange()));
121 122 123 124
		this._register(this.contextService.onDidChangeWorkspaceFolders(() => this.titleUpdater.schedule()));
		this._register(this.contextService.onDidChangeWorkbenchState(() => this.titleUpdater.schedule()));
		this._register(this.contextService.onDidChangeWorkspaceName(() => this.titleUpdater.schedule()));
		this._register(this.labelService.onDidChangeFormatters(() => this.titleUpdater.schedule()));
125 126
	}

B
Benjamin Pasero 已提交
127 128 129 130 131 132 133 134 135 136
	private onBlur(): void {
		this.isInactive = true;
		this.updateStyles();
	}

	private onFocus(): void {
		this.isInactive = false;
		this.updateStyles();
	}

137 138
	private onConfigurationChanged(event: IConfigurationChangeEvent): void {
		if (event.affectsConfiguration('window.title')) {
139
			this.titleUpdater.schedule();
140
		}
S
SteVen Batten 已提交
141

S
SteVen Batten 已提交
142 143 144 145 146 147 148 149
		if (event.affectsConfiguration('window.menuBarVisibility')) {
			if (this.currentMenubarVisibility === 'compact') {
				this.uninstallMenubar();
			} else {
				this.installMenubar();
			}
		}

S
SteVen Batten 已提交
150 151 152 153 154
		if (event.affectsConfiguration('window.doubleClickIconToClose')) {
			if (this.appIcon) {
				this.onUpdateAppIconDragBehavior();
			}
		}
155 156
	}

S
SteVen Batten 已提交
157
	private onMenubarVisibilityChanged(visible: boolean) {
158
		if (isWeb || isWindows || isLinux) {
S
SteVen Batten 已提交
159
			// Hide title when toggling menu bar
S
SteVen Batten 已提交
160
			if (!isWeb && this.currentMenubarVisibility === 'toggle' && visible) {
S
SteVen Batten 已提交
161
				// Hack to fix issue #52522 with layered webkit-app-region elements appearing under cursor
162 163
				hide(this.dragRegion);
				setTimeout(() => show(this.dragRegion), 50);
S
SteVen Batten 已提交
164
			}
S
SteVen Batten 已提交
165 166

			this.adjustTitleMarginToCenter();
167 168

			this._onMenubarVisibilityChange.fire(visible);
S
SteVen Batten 已提交
169
		}
170 171
	}

S
SteVen Batten 已提交
172
	private onMenubarFocusChanged(focused: boolean) {
S
SteVen Batten 已提交
173
		if (!isWeb && (isWindows || isLinux) && this.currentMenubarVisibility === 'compact') {
S
SteVen Batten 已提交
174 175 176 177 178 179 180 181
			if (focused) {
				hide(this.dragRegion);
			} else {
				show(this.dragRegion);
			}
		}
	}

B
Benjamin Pasero 已提交
182
	private onActiveEditorChange(): void {
183 184

		// Dispose old listeners
185
		this.activeEditorListeners.clear();
186 187

		// Calculate New Window Title
188
		this.titleUpdater.schedule();
189 190

		// Apply listener for dirty and label changes
B
Benjamin Pasero 已提交
191 192
		const activeEditor = this.editorService.activeEditor;
		if (activeEditor instanceof EditorInput) {
193 194
			this.activeEditorListeners.add(activeEditor.onDidChangeDirty(() => this.titleUpdater.schedule()));
			this.activeEditorListeners.add(activeEditor.onDidChangeLabel(() => this.titleUpdater.schedule()));
195 196 197
		}
	}

B
Benjamin Pasero 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
	private doUpdateTitle(): void {
		const title = this.getWindowTitle();

		// Always set the native window title to identify us properly to the OS
		let nativeTitle = title;
		if (!trim(nativeTitle)) {
			nativeTitle = this.environmentService.appNameLong;
		}
		window.document.title = nativeTitle;

		// Apply custom title if we can
		if (this.title) {
			this.title.innerText = title;
		} else {
			this.pendingTitle = title;
		}
S
SteVen Batten 已提交
214

215
		if ((isWeb || isWindows || isLinux) && this.title) {
S
SteVen Batten 已提交
216 217 218
			if (this.lastLayoutDimensions) {
				this.updateLayout(this.lastLayoutDimensions);
			}
219
		}
B
Benjamin Pasero 已提交
220 221
	}

222 223 224
	private getWindowTitle(): string {
		let title = this.doGetWindowTitle();

225
		if (this.properties.isAdmin) {
B
Benjamin Pasero 已提交
226
			title = `${title || this.environmentService.appNameLong} ${TitlebarPart.NLS_USER_IS_ADMIN}`;
227 228 229
		}

		if (!this.properties.isPure) {
B
Benjamin Pasero 已提交
230
			title = `${title || this.environmentService.appNameLong} ${TitlebarPart.NLS_UNSUPPORTED}`;
231 232 233
		}

		if (this.environmentService.isExtensionDevelopment) {
B
Benjamin Pasero 已提交
234
			title = `${TitlebarPart.NLS_EXTENSION_HOST} - ${title || this.environmentService.appNameLong}`;
235 236 237 238 239
		}

		return title;
	}

B
Benjamin Pasero 已提交
240
	updateProperties(properties: ITitleProperties): void {
241 242 243 244 245 246 247
		const isAdmin = typeof properties.isAdmin === 'boolean' ? properties.isAdmin : this.properties.isAdmin;
		const isPure = typeof properties.isPure === 'boolean' ? properties.isPure : this.properties.isPure;

		if (isAdmin !== this.properties.isAdmin || isPure !== this.properties.isPure) {
			this.properties.isAdmin = isAdmin;
			this.properties.isPure = isPure;

248
			this.titleUpdater.schedule();
249 250 251
		}
	}

252 253 254
	/**
	 * Possible template values:
	 *
255 256
	 * {activeEditorLong}: e.g. /Users/Development/myFolder/myFileFolder/myFile.txt
	 * {activeEditorMedium}: e.g. myFolder/myFileFolder/myFile.txt
B
Benjamin Pasero 已提交
257
	 * {activeEditorShort}: e.g. myFile.txt
258 259 260
	 * {activeFolderLong}: e.g. /Users/Development/myFolder/myFileFolder
	 * {activeFolderMedium}: e.g. myFolder/myFileFolder
	 * {activeFolderShort}: e.g. myFileFolder
261
	 * {rootName}: e.g. myFolder1, myFolder2, myFolder3
262
	 * {rootPath}: e.g. /Users/Development
263 264
	 * {folderName}: e.g. myFolder
	 * {folderPath}: e.g. /Users/Development/myFolder
265
	 * {appName}: e.g. VS Code
266
	 * {remoteName}: e.g. SSH
267
	 * {dirty}: indicator
268 269 270
	 * {separator}: conditional separator
	 */
	private doGetWindowTitle(): string {
B
Benjamin Pasero 已提交
271
		const editor = this.editorService.activeEditor;
B
Benjamin Pasero 已提交
272
		const workspace = this.contextService.getWorkspace();
273

B
Benjamin Pasero 已提交
274
		// Compute root
275
		let root: URI | undefined;
276
		if (workspace.configuration) {
277
			root = workspace.configuration;
278 279
		} else if (workspace.folders.length) {
			root = workspace.folders[0].uri;
280 281
		}

B
Benjamin Pasero 已提交
282 283 284 285 286 287 288
		// Compute active editor folder
		const editorResource = editor ? toResource(editor) : undefined;
		let editorFolderResource = editorResource ? resources.dirname(editorResource) : undefined;
		if (editorFolderResource && editorFolderResource.path === '.') {
			editorFolderResource = undefined;
		}

289 290
		// Compute folder resource
		// Single Root Workspace: always the root single workspace in this case
291
		// Otherwise: root folder of the currently active file if any
B
Benjamin Pasero 已提交
292
		const folder = this.contextService.getWorkbenchState() === WorkbenchState.FOLDER ? workspace.folders[0] : this.contextService.getWorkspaceFolder(toResource(editor, { supportSideBySide: SideBySideEditor.MASTER })!);
293

294
		// Variables
B
Benjamin Pasero 已提交
295 296 297
		const activeEditorShort = editor ? editor.getTitle(Verbosity.SHORT) : '';
		const activeEditorMedium = editor ? editor.getTitle(Verbosity.MEDIUM) : activeEditorShort;
		const activeEditorLong = editor ? editor.getTitle(Verbosity.LONG) : activeEditorMedium;
B
Benjamin Pasero 已提交
298 299 300
		const activeFolderShort = editorFolderResource ? resources.basename(editorFolderResource) : '';
		const activeFolderMedium = editorFolderResource ? this.labelService.getUriLabel(editorFolderResource, { relative: true }) : '';
		const activeFolderLong = editorFolderResource ? this.labelService.getUriLabel(editorFolderResource) : '';
I
isidor 已提交
301
		const rootName = this.labelService.getWorkspaceLabel(workspace);
I
isidor 已提交
302
		const rootPath = root ? this.labelService.getUriLabel(root) : '';
B
Benjamin Pasero 已提交
303
		const folderName = folder ? folder.name : '';
I
isidor 已提交
304
		const folderPath = folder ? this.labelService.getUriLabel(folder.uri) : '';
B
Benjamin Pasero 已提交
305
		const dirty = editor && editor.isDirty() ? TitlebarPart.TITLE_DIRTY : '';
306
		const appName = this.environmentService.appNameLong;
307
		const remoteName = this.environmentService.configuration.remoteAuthority;
308
		const separator = TitlebarPart.TITLE_SEPARATOR;
309
		const titleTemplate = this.configurationService.getValue<string>('window.title');
310

I
isidor 已提交
311
		return template(titleTemplate, {
B
Benjamin Pasero 已提交
312 313 314
			activeEditorShort,
			activeEditorLong,
			activeEditorMedium,
315 316 317
			activeFolderShort,
			activeFolderMedium,
			activeFolderLong,
318 319
			rootName,
			rootPath,
320 321
			folderName,
			folderPath,
322 323
			dirty,
			appName,
324
			remoteName,
325 326 327 328
			separator: { label: separator }
		});
	}

S
SteVen Batten 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
	private uninstallMenubar(): void {
		if (this.customMenubar) {
			this.customMenubar.dispose();
			this.customMenubar = undefined;
		}

		if (this.menubar) {
			removeNode(this.menubar);
			this.menubar = undefined;
		}
	}

	private installMenubar(): void {
		this.customMenubar = this._register(this.instantiationService.createInstance(CustomMenubarControl));

		this.menubar = this.element.insertBefore($('div.menubar'), this.title);

		this.menubar.setAttribute('role', 'menubar');

		this.customMenubar.create(this.menubar);

		this._register(this.customMenubar.onVisibilityChange(e => this.onMenubarVisibilityChanged(e)));
		this._register(this.customMenubar.onFocusStateChange(e => this.onMenubarFocusChanged(e)));
	}

B
Benjamin Pasero 已提交
354
	createContentArea(parent: HTMLElement): HTMLElement {
355
		this.element = parent;
B
Benjamin Pasero 已提交
356

357
		// Draggable region that we can manipulate for #52522
358 359 360
		if (!isWeb) {
			this.dragRegion = append(this.element, $('div.titlebar-drag-region'));
		}
361

362 363
		// App Icon (Native Windows/Linux)
		if (!isMacintosh && !isWeb) {
364
			this.appIcon = append(this.element, $('div.window-appicon'));
S
SteVen Batten 已提交
365 366 367
			this.onUpdateAppIconDragBehavior();

			this._register(addDisposableListener(this.appIcon, EventType.DBLCLICK, (e => {
368
				this.electronService.closeWindow();
S
SteVen Batten 已提交
369
			})));
370
		}
S
SteVen Batten 已提交
371

372
		// Menubar: install a custom menu bar depending on configuration
S
SteVen Batten 已提交
373 374 375 376 377
		// and when not in activity bar
		if (getTitleBarStyle(this.configurationService, this.environmentService) !== 'native'
			&& (!isMacintosh || isWeb)
			&& this.currentMenubarVisibility !== 'compact') {
			this.installMenubar();
S
SteVen Batten 已提交
378 379
		}

B
Benjamin Pasero 已提交
380
		// Title
381
		this.title = append(this.element, $('div.window-title'));
B
Benjamin Pasero 已提交
382
		if (this.pendingTitle) {
383
			this.title.innerText = this.pendingTitle;
B
Benjamin Pasero 已提交
384
		} else {
385
			this.titleUpdater.schedule();
B
Benjamin Pasero 已提交
386 387
		}

B
Benjamin Pasero 已提交
388
		// Context menu on title
389 390 391 392
		[EventType.CONTEXT_MENU, EventType.MOUSE_DOWN].forEach(event => {
			this._register(addDisposableListener(this.title, event, e => {
				if (e.type === EventType.CONTEXT_MENU || e.metaKey) {
					EventHelper.stop(e);
B
Benjamin Pasero 已提交
393

394 395 396
					this.onContextMenu(e);
				}
			}));
B
Benjamin Pasero 已提交
397 398
		});

399 400
		// Window Controls (Native Windows/Linux)
		if (!isMacintosh && !isWeb) {
401
			this.windowControls = append(this.element, $('div.window-controls-container'));
402

B
Benjamin Pasero 已提交
403
			// Minimize
404 405 406 407
			const minimizeIconContainer = append(this.windowControls, $('div.window-icon-bg'));
			const minimizeIcon = append(minimizeIconContainer, $('div.window-icon'));
			addClass(minimizeIcon, 'window-minimize');
			this._register(addDisposableListener(minimizeIcon, EventType.CLICK, e => {
408
				this.electronService.minimizeWindow();
409
			}));
R
Ryan Adolf 已提交
410

B
Benjamin Pasero 已提交
411
			// Restore
412 413 414
			const restoreIconContainer = append(this.windowControls, $('div.window-icon-bg'));
			this.maxRestoreControl = append(restoreIconContainer, $('div.window-icon'));
			addClass(this.maxRestoreControl, 'window-max-restore');
415
			this._register(addDisposableListener(this.maxRestoreControl, EventType.CLICK, async e => {
416
				const maximized = await this.electronService.isMaximized();
417
				if (maximized) {
418
					return this.electronService.unmaximizeWindow();
419 420
				}

421
				return this.electronService.maximizeWindow();
422
			}));
R
Ryan Adolf 已提交
423

B
Benjamin Pasero 已提交
424
			// Close
425 426 427 428 429
			const closeIconContainer = append(this.windowControls, $('div.window-icon-bg'));
			addClass(closeIconContainer, 'window-close-bg');
			const closeIcon = append(closeIconContainer, $('div.window-icon'));
			addClass(closeIcon, 'window-close');
			this._register(addDisposableListener(closeIcon, EventType.CLICK, e => {
430
				this.electronService.closeWindow();
431
			}));
432

S
SteVen Batten 已提交
433
			// Resizer
434
			this.resizer = append(this.element, $('div.resizer'));
S
SteVen Batten 已提交
435

436
			const isMaximized = this.environmentService.configuration.maximized ? true : false;
437
			this.onDidChangeMaximized(isMaximized);
438 439

			this._register(Event.any(
440 441
				Event.map(Event.filter(this.electronService.onWindowMaximize, id => id === this.electronEnvironmentService.windowId), _ => true),
				Event.map(Event.filter(this.electronService.onWindowUnmaximize, id => id === this.electronEnvironmentService.windowId), _ => false)
442
			)(e => this.onDidChangeMaximized(e)));
443
		}
R
Ryan Adolf 已提交
444

445 446
		// Since the title area is used to drag the window, we do not want to steal focus from the
		// currently active element. So we restore focus after a timeout back to where it was.
447
		this._register(addDisposableListener(this.element, EventType.MOUSE_DOWN, e => {
S
SteVen Batten 已提交
448
			if (e.target && this.menubar && isAncestor(e.target as HTMLElement, this.menubar)) {
S
SteVen Batten 已提交
449 450 451
				return;
			}

452 453 454 455 456 457
			const active = document.activeElement;
			setTimeout(() => {
				if (active instanceof HTMLElement) {
					active.focus();
				}
			}, 0 /* need a timeout because we are in capture phase */);
458
		}, true /* use capture to know the currently active element properly */));
459

S
SteVen Batten 已提交
460 461
		this.updateStyles();

462
		return this.element;
B
Benjamin Pasero 已提交
463 464
	}

465
	private onDidChangeMaximized(maximized: boolean) {
S
SteVen Batten 已提交
466 467
		if (this.maxRestoreControl) {
			if (maximized) {
468 469
				removeClass(this.maxRestoreControl, 'window-maximize');
				addClass(this.maxRestoreControl, 'window-unmaximize');
S
SteVen Batten 已提交
470
			} else {
471 472
				removeClass(this.maxRestoreControl, 'window-unmaximize');
				addClass(this.maxRestoreControl, 'window-maximize');
S
SteVen Batten 已提交
473
			}
S
SteVen Batten 已提交
474
		}
S
SteVen Batten 已提交
475

S
SteVen Batten 已提交
476 477
		if (this.resizer) {
			if (maximized) {
478
				hide(this.resizer);
S
SteVen Batten 已提交
479
			} else {
480
				show(this.resizer);
S
SteVen Batten 已提交
481
			}
S
SteVen Batten 已提交
482
		}
S
SteVen Batten 已提交
483 484

		this.adjustTitleMarginToCenter();
485 486
	}

487
	updateStyles(): void {
B
Benjamin Pasero 已提交
488 489 490
		super.updateStyles();

		// Part container
491
		if (this.element) {
S
SteVen Batten 已提交
492
			if (this.isInactive) {
493
				addClass(this.element, 'inactive');
S
SteVen Batten 已提交
494
			} else {
495
				removeClass(this.element, 'inactive');
S
SteVen Batten 已提交
496 497
			}

B
Benjamin Pasero 已提交
498
			const titleBackground = this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_BACKGROUND : TITLE_BAR_ACTIVE_BACKGROUND);
499
			this.element.style.backgroundColor = titleBackground;
M
Matt Bierner 已提交
500
			if (titleBackground && Color.fromHex(titleBackground).isLighter()) {
501
				addClass(this.element, 'light');
S
SteVen Batten 已提交
502
			} else {
503
				removeClass(this.element, 'light');
S
SteVen Batten 已提交
504
			}
505

B
Benjamin Pasero 已提交
506
			const titleForeground = this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_FOREGROUND : TITLE_BAR_ACTIVE_FOREGROUND);
507
			this.element.style.color = titleForeground;
B
Benjamin Pasero 已提交
508

509
			const titleBorder = this.getColor(TITLE_BAR_BORDER);
510
			this.element.style.borderBottom = titleBorder ? `1px solid ${titleBorder}` : null;
511
		}
B
Benjamin Pasero 已提交
512 513
	}

S
SteVen Batten 已提交
514 515 516
	private onUpdateAppIconDragBehavior() {
		const setting = this.configurationService.getValue('window.doubleClickIconToClose');
		if (setting) {
S
SteVen Batten 已提交
517
			(this.appIcon.style as any)['-webkit-app-region'] = 'no-drag';
518
		} else {
S
SteVen Batten 已提交
519
			(this.appIcon.style as any)['-webkit-app-region'] = 'drag';
S
SteVen Batten 已提交
520 521 522
		}
	}

B
Benjamin Pasero 已提交
523 524 525 526 527 528
	private onContextMenu(e: MouseEvent): void {

		// Find target anchor
		const event = new StandardMouseEvent(e);
		const anchor = { x: event.posx, y: event.posy };

529
		// Fill in contributed actions
B
Benjamin Pasero 已提交
530
		const actions: IAction[] = [];
531
		const actionsDisposable = createAndFillInContextMenuActions(this.contextMenu, undefined, actions, this.contextMenuService);
B
Benjamin Pasero 已提交
532

533 534 535 536 537 538
		// Show it
		this.contextMenuService.showContextMenu({
			getAnchor: () => anchor,
			getActions: () => actions,
			onHide: () => dispose(actionsDisposable)
		});
B
Benjamin Pasero 已提交
539 540
	}

S
SteVen Batten 已提交
541
	private adjustTitleMarginToCenter(): void {
S
SteVen Batten 已提交
542
		if (this.customMenubar && this.menubar) {
543 544 545 546 547 548 549 550 551
			const leftMarker = (this.appIcon ? this.appIcon.clientWidth : 0) + this.menubar.clientWidth + 10;
			const rightMarker = this.element.clientWidth - (this.windowControls ? this.windowControls.clientWidth : 0) - 10;

			// Not enough space to center the titlebar within window,
			// Center between menu and window controls
			if (leftMarker > (this.element.clientWidth - this.title.clientWidth) / 2 ||
				rightMarker < (this.element.clientWidth + this.title.clientWidth) / 2) {
				this.title.style.position = null;
				this.title.style.left = null;
M
Matt Bierner 已提交
552
				this.title.style.transform = '';
553 554
				return;
			}
S
SteVen Batten 已提交
555
		}
556 557 558 559

		this.title.style.position = 'absolute';
		this.title.style.left = '50%';
		this.title.style.transform = 'translate(-50%, 0)';
S
SteVen Batten 已提交
560 561
	}

S
SteVen Batten 已提交
562 563 564 565
	private get currentMenubarVisibility(): MenuBarVisibility {
		return this.configurationService.getValue<MenuBarVisibility>('window.menuBarVisibility');
	}

566
	updateLayout(dimension: Dimension): void {
S
SteVen Batten 已提交
567 568
		this.lastLayoutDimensions = dimension;

B
Benjamin Pasero 已提交
569
		if (getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') {
570
			// Only prevent zooming behavior on macOS or when the menubar is not visible
S
SteVen Batten 已提交
571
			if ((!isWeb && isMacintosh) || this.currentMenubarVisibility === 'hidden') {
572
				this.title.style.zoom = `${1 / getZoomFactor()}`;
573
				if (!isWeb && (isWindows || isLinux)) {
574 575
					this.appIcon.style.zoom = `${1 / getZoomFactor()}`;
					this.windowControls.style.zoom = `${1 / getZoomFactor()}`;
S
SteVen Batten 已提交
576
				}
577 578
			} else {
				this.title.style.zoom = null;
579
				if (!isWeb && (isWindows || isLinux)) {
580 581
					this.appIcon.style.zoom = null;
					this.windowControls.style.zoom = null;
S
SteVen Batten 已提交
582
				}
583 584
			}

S
SteVen Batten 已提交
585
			runAtThisOrScheduleAtNextAnimationFrame(() => this.adjustTitleMarginToCenter());
586

587
			if (this.customMenubar) {
M
Matt Bierner 已提交
588
				const menubarDimension = new Dimension(0, dimension.height);
589
				this.customMenubar.layout(menubarDimension);
590
			}
591
		}
592 593
	}

B
Benjamin Pasero 已提交
594 595
	layout(width: number, height: number): void {
		this.updateLayout(new Dimension(width, height));
596

B
Benjamin Pasero 已提交
597
		super.layoutContents(width, height);
598
	}
B
Benjamin Pasero 已提交
599

600 601 602 603
	toJSON(): object {
		return {
			type: Parts.TITLEBAR_PART
		};
B
Benjamin Pasero 已提交
604
	}
B
Benjamin Pasero 已提交
605 606
}

S
SteVen Batten 已提交
607 608 609 610
registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
	const titlebarActiveFg = theme.getColor(TITLE_BAR_ACTIVE_FOREGROUND);
	if (titlebarActiveFg) {
		collector.addRule(`
611
		.monaco-workbench .part.titlebar > .window-controls-container .window-icon {
S
SteVen Batten 已提交
612 613 614 615 616 617 618 619
			background-color: ${titlebarActiveFg};
		}
		`);
	}

	const titlebarInactiveFg = theme.getColor(TITLE_BAR_INACTIVE_FOREGROUND);
	if (titlebarInactiveFg) {
		collector.addRule(`
620
		.monaco-workbench .part.titlebar.inactive > .window-controls-container .window-icon {
S
SteVen Batten 已提交
621 622 623 624 625
				background-color: ${titlebarInactiveFg};
			}
		`);
	}
});
626

627
registerSingleton(ITitleService, TitlebarPart);