titlebarPart.ts 15.8 KB
Newer Older
B
Benjamin Pasero 已提交
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

import 'vs/css!./media/titlebarpart';
B
Benjamin Pasero 已提交
9
import { TPromise } from 'vs/base/common/winjs.base';
B
Benjamin Pasero 已提交
10
import { Builder, $, Dimension } from 'vs/base/browser/builder';
B
Benjamin Pasero 已提交
11 12
import * as DOM from 'vs/base/browser/dom';
import * as paths from 'vs/base/common/paths';
B
Benjamin Pasero 已提交
13 14 15
import { Part } from 'vs/workbench/browser/part';
import { ITitleService } from 'vs/workbench/services/title/common/titleService';
import { getZoomFactor } from 'vs/base/browser/browser';
B
Benjamin Pasero 已提交
16 17 18 19 20
import { IWindowService, IWindowsService } from 'vs/platform/windows/common/windows';
import * as errors from 'vs/base/common/errors';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { IAction, Action } from 'vs/base/common/actions';
21
import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
22 23 24 25 26 27
import { IIntegrityService } from 'vs/platform/integrity/common/integrity';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import nls = require('vs/nls');
import * as labels from 'vs/base/common/labels';
28
import { EditorInput, toResource } from 'vs/workbench/common/editor';
29
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
30
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
31
import { Verbosity } from 'vs/platform/editor/common/editor';
B
Benjamin Pasero 已提交
32
import { IThemeService } from 'vs/platform/theme/common/themeService';
33
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';
R
Ryan Adolf 已提交
34
import { isMacintosh, isWindows } from 'vs/base/common/platform';
B
Benjamin Pasero 已提交
35
import URI from 'vs/base/common/uri';
R
Ryan Adolf 已提交
36
import { Color } from 'vs/base/common/color';
37
import { ILifecycleService, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
B
Benjamin Pasero 已提交
38 39 40 41 42

export class TitlebarPart extends Part implements ITitleService {

	public _serviceBrand: any;

43 44 45 46
	private static readonly NLS_UNSUPPORTED = nls.localize('patchedWindowTitle', "[Unsupported]");
	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
47

B
Benjamin Pasero 已提交
48 49 50 51
	private titleContainer: Builder;
	private title: Builder;
	private pendingTitle: string;
	private initialTitleFontSize: number;
B
Benjamin Pasero 已提交
52
	private representedFileName: string;
B
Benjamin Pasero 已提交
53

B
Benjamin Pasero 已提交
54 55
	private isInactive: boolean;

56 57 58
	private isPure: boolean;
	private activeEditorListeners: IDisposable[];

59 60
	constructor(
		id: string,
B
Benjamin Pasero 已提交
61 62
		@IContextMenuService private contextMenuService: IContextMenuService,
		@IWindowService private windowService: IWindowService,
63 64 65 66 67 68
		@IConfigurationService private configurationService: IConfigurationService,
		@IWindowsService private windowsService: IWindowsService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IEditorGroupService private editorGroupService: IEditorGroupService,
		@IIntegrityService private integrityService: IIntegrityService,
		@IEnvironmentService private environmentService: IEnvironmentService,
B
Benjamin Pasero 已提交
69
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
70
		@IThemeService themeService: IThemeService,
71
		@ILifecycleService private lifecycleService: ILifecycleService
72
	) {
B
Benjamin Pasero 已提交
73
		super(id, { hasTitle: false }, themeService);
74

75 76 77 78 79
		this.isPure = true;
		this.activeEditorListeners = [];

		this.init();

80 81 82
		this.registerListeners();
	}

83 84
	private init(): void {

85
		// Initial window title when loading is done
86
		this.lifecycleService.when(LifecyclePhase.Running).then(() => this.setTitle(this.getWindowTitle()));
87 88 89 90 91 92 93 94 95 96

		// Integrity for window title
		this.integrityService.isPure().then(r => {
			if (!r.isPure) {
				this.isPure = false;
				this.setTitle(this.getWindowTitle());
			}
		});
	}

97
	private registerListeners(): void {
B
Benjamin Pasero 已提交
98 99
		this.toUnbind.push(DOM.addDisposableListener(window, DOM.EventType.BLUR, () => this.onBlur()));
		this.toUnbind.push(DOM.addDisposableListener(window, DOM.EventType.FOCUS, () => this.onFocus()));
100
		this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChanged(e)));
101
		this.toUnbind.push(this.editorGroupService.onEditorsChanged(() => this.onEditorsChanged()));
102 103 104
		this.toUnbind.push(this.contextService.onDidChangeWorkspaceFolders(() => this.setTitle(this.getWindowTitle())));
		this.toUnbind.push(this.contextService.onDidChangeWorkbenchState(() => this.setTitle(this.getWindowTitle())));
		this.toUnbind.push(this.contextService.onDidChangeWorkspaceName(() => this.setTitle(this.getWindowTitle())));
105 106
	}

B
Benjamin Pasero 已提交
107 108 109 110 111 112 113 114 115 116
	private onBlur(): void {
		this.isInactive = true;
		this.updateStyles();
	}

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

117 118
	private onConfigurationChanged(event: IConfigurationChangeEvent): void {
		if (event.affectsConfiguration('window.title')) {
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
			this.setTitle(this.getWindowTitle());
		}
	}

	private onEditorsChanged(): void {

		// Dispose old listeners
		dispose(this.activeEditorListeners);
		this.activeEditorListeners = [];

		const activeEditor = this.editorService.getActiveEditor();
		const activeInput = activeEditor ? activeEditor.input : void 0;

		// Calculate New Window Title
		this.setTitle(this.getWindowTitle());

		// Apply listener for dirty and label changes
		if (activeInput instanceof EditorInput) {
			this.activeEditorListeners.push(activeInput.onDidChangeDirty(() => {
				this.setTitle(this.getWindowTitle());
			}));

			this.activeEditorListeners.push(activeInput.onDidChangeLabel(() => {
				this.setTitle(this.getWindowTitle());
			}));
		}
	}

	private getWindowTitle(): string {
		let title = this.doGetWindowTitle();
		if (!title) {
			title = this.environmentService.appNameLong;
		}

		if (!this.isPure) {
			title = `${title} ${TitlebarPart.NLS_UNSUPPORTED}`;
		}

		// Extension Development Host gets a special title to identify itself
		if (this.environmentService.isExtensionDevelopment) {
			title = `${TitlebarPart.NLS_EXTENSION_HOST} - ${title}`;
		}

		return title;
	}

	/**
	 * Possible template values:
	 *
B
Benjamin Pasero 已提交
168 169 170
	 * {activeEditorLong}: e.g. /Users/Development/myProject/myFolder/myFile.txt
	 * {activeEditorMedium}: e.g. myFolder/myFile.txt
	 * {activeEditorShort}: e.g. myFile.txt
171
	 * {rootName}: e.g. myFolder1, myFolder2, myFolder3
172
	 * {rootPath}: e.g. /Users/Development/myProject
173 174
	 * {folderName}: e.g. myFolder
	 * {folderPath}: e.g. /Users/Development/myFolder
175 176 177 178 179 180
	 * {appName}: e.g. VS Code
	 * {dirty}: indiactor
	 * {separator}: conditional separator
	 */
	private doGetWindowTitle(): string {
		const input = this.editorService.getActiveEditorInput();
B
Benjamin Pasero 已提交
181
		const workspace = this.contextService.getWorkspace();
182

183
		let root: URI;
184
		if (workspace.configuration) {
185
			root = workspace.configuration;
186 187
		} else if (workspace.folders.length) {
			root = workspace.folders[0].uri;
188 189 190 191
		}

		// Compute folder resource
		// Single Root Workspace: always the root single workspace in this case
192
		// Otherwise: root folder of the currently active file if any
193
		let folder = this.contextService.getWorkbenchState() === WorkbenchState.FOLDER ? workspace.folders[0] : this.contextService.getWorkspaceFolder(toResource(input, { supportSideBySide: true }));
194

195
		// Variables
196 197 198
		const activeEditorShort = input ? input.getTitle(Verbosity.SHORT) : '';
		const activeEditorMedium = input ? input.getTitle(Verbosity.MEDIUM) : activeEditorShort;
		const activeEditorLong = input ? input.getTitle(Verbosity.LONG) : activeEditorMedium;
199
		const rootName = workspace.name;
200
		const rootPath = root ? labels.getPathLabel(root, void 0, this.environmentService) : '';
B
Benjamin Pasero 已提交
201
		const folderName = folder ? folder.name : '';
202
		const folderPath = folder ? labels.getPathLabel(folder.uri, void 0, this.environmentService) : '';
203 204 205
		const dirty = input && input.isDirty() ? TitlebarPart.TITLE_DIRTY : '';
		const appName = this.environmentService.appNameLong;
		const separator = TitlebarPart.TITLE_SEPARATOR;
206
		const titleTemplate = this.configurationService.getValue<string>('window.title');
207

208
		return labels.template(titleTemplate, {
B
Benjamin Pasero 已提交
209 210 211
			activeEditorShort,
			activeEditorLong,
			activeEditorMedium,
212 213
			rootName,
			rootPath,
214 215
			folderName,
			folderPath,
216 217 218 219 220 221
			dirty,
			appName,
			separator: { label: separator }
		});
	}

B
Benjamin Pasero 已提交
222
	public createContentArea(parent: Builder): Builder {
R
Ryan Adolf 已提交
223
		const SVGNS = 'http://www.w3.org/2000/svg';
B
Benjamin Pasero 已提交
224 225 226 227 228 229 230 231
		this.titleContainer = $(parent);

		// Title
		this.title = $(this.titleContainer).div({ class: 'window-title' });
		if (this.pendingTitle) {
			this.title.text(this.pendingTitle);
		}

232 233 234 235 236 237 238
		// Maximize/Restore on doubleclick
		this.titleContainer.on(DOM.EventType.DBLCLICK, (e) => {
			DOM.EventHelper.stop(e);

			this.onTitleDoubleclick();
		});

B
Benjamin Pasero 已提交
239 240 241 242 243 244 245 246 247
		// Context menu on title
		this.title.on([DOM.EventType.CONTEXT_MENU, DOM.EventType.MOUSE_DOWN], (e: MouseEvent) => {
			if (e.type === DOM.EventType.CONTEXT_MENU || e.metaKey) {
				DOM.EventHelper.stop(e);

				this.onContextMenu(e);
			}
		});

R
Ryan Adolf 已提交
248 249 250 251 252 253 254 255
		const $svg = (name: string, props: { [name: string]: any }) => {
			const el = document.createElementNS(SVGNS, name);
			Object.keys(props).forEach((prop) => {
				el.setAttribute(prop, props[prop]);
			});
			return el;
		};

256
		if (isWindows) {
257
			// The svgs and styles for the titlebar come from the electron-titlebar-windows package
258 259 260 261
			$(this.titleContainer).div({ class: 'window-icon' }, (builder) => {
				const svg = $svg('svg', { x: 0, y: 0, viewBox: '0 0 10 1' });
				svg.appendChild($svg('rect', { fill: 'currentColor', width: 10, height: 1 }));
				builder.getHTMLElement().appendChild(svg);
262
			}).on(DOM.EventType.CLICK, () => {
R
Ryan Adolf 已提交
263
				this.windowService.minimizeWindow().then(null, errors.onUnexpectedError);
264
			});
R
Ryan Adolf 已提交
265

266
			$(this.titleContainer).div({ class: 'window-icon' }, (builder) => {
267
				const svgf = $svg('svg', { class: 'window-maximize', x: 0, y: 0, viewBox: '0 0 10 10' });
268 269 270
				svgf.appendChild($svg('path', { fill: 'currentColor', d: 'M 0 0 L 0 10 L 10 10 L 10 0 L 0 0 z M 1 1 L 9 1 L 9 9 L 1 9 L 1 1 z' }));
				builder.getHTMLElement().appendChild(svgf);

271
				const svgm = $svg('svg', { class: 'window-unmaximize', x: 0, y: 0, viewBox: '0 0 10 10' });
272 273 274 275 276 277 278
				const mask = $svg('mask', { id: 'Mask' });
				mask.appendChild($svg('rect', { fill: '#fff', width: 10, height: 10 }));
				mask.appendChild($svg('path', { fill: '#000', d: 'M 3 1 L 9 1 L 9 7 L 8 7 L 8 2 L 3 2 L 3 1 z' }));
				mask.appendChild($svg('path', { fill: '#000', d: 'M 1 3 L 7 3 L 7 9 L 1 9 L 1 3 z' }));
				svgm.appendChild(mask);
				svgm.appendChild($svg('path', { fill: 'currentColor', d: 'M 2 0 L 10 0 L 10 8 L 8 8 L 8 10 L 0 10 L 0 2 L 2 2 L 2 0 z', mask: 'url(#Mask)' }));
				builder.getHTMLElement().appendChild(svgm);
279 280 281 282 283 284 285 286
			}).on(DOM.EventType.CLICK, () => {
				this.windowService.isMaximized().then((maximized) => {
					if (maximized) {
						return this.windowService.unmaximizeWindow();
					} else {
						return this.windowService.maximizeWindow();
					}
				}).then(null, errors.onUnexpectedError);
287
			});
R
Ryan Adolf 已提交
288

R
Ryan Adolf 已提交
289
			$(this.titleContainer).div({ class: 'window-icon window-close' }, (builder) => {
290 291 292
				const svg = $svg('svg', { x: '0', y: '0', viewBox: '0 0 10 10' });
				svg.appendChild($svg('polygon', { fill: 'currentColor', points: '10,1 9,0 5,4 1,0 0,1 4,5 0,9 1,10 5,6 9,10 10,9 6,5' }));
				builder.getHTMLElement().appendChild(svg);
293
			}).on(DOM.EventType.CLICK, () => {
R
Ryan Adolf 已提交
294
				this.windowService.closeWindow().then(null, errors.onUnexpectedError);
295
			});
296 297

			this.windowService.onDidChangeMaximize((mazimized) => {
R
Ryan Adolf 已提交
298 299
				($(this.titleContainer).getHTMLElement().querySelector('.window-maximize') as SVGElement).style.display = mazimized ? 'none' : 'inline';
				($(this.titleContainer).getHTMLElement().querySelector('.window-unmaximize') as SVGElement).style.display = mazimized ? 'inline' : 'none';
300
			}, this);
301
		}
R
Ryan Adolf 已提交
302

303 304 305 306 307 308 309 310 311 312 313
		// 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.
		this.titleContainer.on([DOM.EventType.MOUSE_DOWN], () => {
			const active = document.activeElement;
			setTimeout(() => {
				if (active instanceof HTMLElement) {
					active.focus();
				}
			}, 0 /* need a timeout because we are in capture phase */);
		}, void 0, true /* use capture to know the currently active element properly */);

B
Benjamin Pasero 已提交
314 315 316
		return this.titleContainer;
	}

B
Benjamin Pasero 已提交
317 318 319 320 321
	protected updateStyles(): void {
		super.updateStyles();

		// Part container
		const container = this.getContainer();
322
		if (container) {
R
Ryan Adolf 已提交
323
			const bgColor = this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_BACKGROUND : TITLE_BAR_ACTIVE_BACKGROUND);
324
			container.style('color', this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_FOREGROUND : TITLE_BAR_ACTIVE_FOREGROUND));
R
Ryan Adolf 已提交
325 326
			container.style('background-color', bgColor);
			container.getHTMLElement().classList.toggle('light', Color.fromHex(bgColor).isLighter());
327 328 329

			const titleBorder = this.getColor(TITLE_BAR_BORDER);
			container.style('border-bottom', titleBorder ? `1px solid ${titleBorder}` : null);
330
		}
B
Benjamin Pasero 已提交
331 332
	}

333
	private onTitleDoubleclick(): void {
334
		this.windowService.onWindowTitleDoubleClick().then(null, errors.onUnexpectedError);
335 336
	}

B
Benjamin Pasero 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
	private onContextMenu(e: MouseEvent): void {

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

		// Show menu
		const actions = this.getContextMenuActions();
		if (actions.length) {
			this.contextMenuService.showContextMenu({
				getAnchor: () => anchor,
				getActions: () => TPromise.as(actions),
				onHide: () => actions.forEach(a => a.dispose())
			});
		}
	}

	private getContextMenuActions(): IAction[] {
		const actions: IAction[] = [];

		if (this.representedFileName) {
			const segments = this.representedFileName.split(paths.sep);
			for (let i = segments.length; i > 0; i--) {
360 361 362 363 364 365 366 367 368
				const isFile = (i === segments.length);

				let pathOffset = i;
				if (!isFile) {
					pathOffset++; // for segments which are not the file name we want to open the folder
				}

				const path = segments.slice(0, pathOffset).join(paths.sep);

B
Benjamin Pasero 已提交
369
				let label: string;
370
				if (!isFile) {
B
Benjamin Pasero 已提交
371 372 373
					label = labels.getBaseLabel(paths.dirname(path));
				} else {
					label = labels.getBaseLabel(path);
374 375 376
				}

				actions.push(new ShowItemInFolderAction(path, label || paths.sep, this.windowsService));
B
Benjamin Pasero 已提交
377 378 379 380 381 382
			}
		}

		return actions;
	}

383
	public setTitle(title: string): void {
B
Benjamin Pasero 已提交
384 385 386 387 388 389 390 391 392 393 394 395

		// Always set the native window title to identify us properly to the OS
		window.document.title = title;

		// Apply if we can
		if (this.title) {
			this.title.text(title);
		} else {
			this.pendingTitle = title;
		}
	}

B
Benjamin Pasero 已提交
396 397 398 399 400 401 402 403 404
	public setRepresentedFilename(path: string): void {

		// Apply to window
		this.windowService.setRepresentedFilename(path);

		// Keep for context menu
		this.representedFileName = path;
	}

B
Benjamin Pasero 已提交
405 406 407 408 409 410 411 412 413 414
	public layout(dimension: Dimension): Dimension[] {

		// To prevent zooming we need to adjust the font size with the zoom factor
		if (typeof this.initialTitleFontSize !== 'number') {
			this.initialTitleFontSize = parseInt(this.titleContainer.getComputedStyle().fontSize, 10);
		}
		this.titleContainer.style({ fontSize: `${this.initialTitleFontSize / getZoomFactor()}px` });

		return super.layout(dimension);
	}
B
Benjamin Pasero 已提交
415 416 417 418
}

class ShowItemInFolderAction extends Action {

419 420
	constructor(private path: string, label: string, private windowsService: IWindowsService) {
		super('showItemInFolder.action.id', label);
B
Benjamin Pasero 已提交
421 422 423 424 425
	}

	public run(): TPromise<void> {
		return this.windowsService.showItemInFolder(this.path);
	}
R
Ryan Adolf 已提交
426
}