titlebarPart.ts 12.9 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';
10
import { Builder, $ } from 'vs/base/browser/builder';
B
Benjamin Pasero 已提交
11
import * as paths from 'vs/base/common/paths';
B
Benjamin Pasero 已提交
12
import { Part } from 'vs/workbench/browser/part';
13
import { ITitleService, ITitleProperties } from 'vs/workbench/services/title/common/titleService';
B
Benjamin Pasero 已提交
14
import { getZoomFactor } from 'vs/base/browser/browser';
B
Benjamin Pasero 已提交
15 16 17 18 19
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';
20
import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
21
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
22
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
23
import * as nls from 'vs/nls';
24
import * as labels from 'vs/base/common/labels';
25
import { EditorInput, toResource, Verbosity } from 'vs/workbench/common/editor';
26
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
27
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
B
Benjamin Pasero 已提交
28
import { IThemeService } from 'vs/platform/theme/common/themeService';
29
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';
30
import { isMacintosh, isWindows } from 'vs/base/common/platform';
B
Benjamin Pasero 已提交
31
import URI from 'vs/base/common/uri';
B
Benjamin Pasero 已提交
32
import { trim } from 'vs/base/common/strings';
33
import { addDisposableListener, EventType, EventHelper, Dimension } from 'vs/base/browser/dom';
B
Benjamin Pasero 已提交
34 35 36 37 38

export class TitlebarPart extends Part implements ITitleService {

	public _serviceBrand: any;

39
	private static readonly NLS_UNSUPPORTED = nls.localize('patchedWindowTitle', "[Unsupported]");
40
	private static readonly NLS_USER_IS_ADMIN = isWindows ? nls.localize('userIsAdmin', "[Administrator]") : nls.localize('userIsSudo', "[Superuser]");
41 42 43
	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
44

B
Benjamin Pasero 已提交
45 46 47 48
	private titleContainer: Builder;
	private title: Builder;
	private pendingTitle: string;
	private initialTitleFontSize: number;
B
Benjamin Pasero 已提交
49
	private representedFileName: string;
B
Benjamin Pasero 已提交
50

B
Benjamin Pasero 已提交
51 52
	private isInactive: boolean;

53
	private properties: ITitleProperties;
54 55
	private activeEditorListeners: IDisposable[];

56 57
	constructor(
		id: string,
B
Benjamin Pasero 已提交
58 59
		@IContextMenuService private contextMenuService: IContextMenuService,
		@IWindowService private windowService: IWindowService,
60 61
		@IConfigurationService private configurationService: IConfigurationService,
		@IWindowsService private windowsService: IWindowsService,
62
		@IEditorService private editorService: IEditorService,
63
		@IEnvironmentService private environmentService: IEnvironmentService,
B
Benjamin Pasero 已提交
64
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
B
Benjamin Pasero 已提交
65
		@IThemeService themeService: IThemeService
66
	) {
B
Benjamin Pasero 已提交
67
		super(id, { hasTitle: false }, themeService);
68

69
		this.properties = { isPure: true, isAdmin: false };
70 71
		this.activeEditorListeners = [];

72 73 74 75
		this.registerListeners();
	}

	private registerListeners(): void {
76 77
		this.toUnbind.push(addDisposableListener(window, EventType.BLUR, () => this.onBlur()));
		this.toUnbind.push(addDisposableListener(window, EventType.FOCUS, () => this.onFocus()));
78
		this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChanged(e)));
79
		this.toUnbind.push(this.editorService.onDidActiveEditorChange(() => this.onActiveEditorChange()));
80 81 82
		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())));
83 84
	}

B
Benjamin Pasero 已提交
85 86 87 88 89 90 91 92 93 94
	private onBlur(): void {
		this.isInactive = true;
		this.updateStyles();
	}

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

95 96
	private onConfigurationChanged(event: IConfigurationChangeEvent): void {
		if (event.affectsConfiguration('window.title')) {
97 98 99 100
			this.setTitle(this.getWindowTitle());
		}
	}

101
	private onActiveEditorChange(): void {
102 103 104 105 106 107 108 109 110

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

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

		// Apply listener for dirty and label changes
111 112 113
		const activeEditor = this.editorService.activeEditor;
		if (activeEditor instanceof EditorInput) {
			this.activeEditorListeners.push(activeEditor.onDidChangeDirty(() => {
114 115 116
				this.setTitle(this.getWindowTitle());
			}));

117
			this.activeEditorListeners.push(activeEditor.onDidChangeLabel(() => {
118 119 120
				this.setTitle(this.getWindowTitle());
			}));
		}
B
Benjamin Pasero 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134

		// Represented File Name
		this.updateRepresentedFilename();
	}

	private updateRepresentedFilename(): void {
		const file = toResource(this.editorService.activeEditor, { supportSideBySide: true, filter: 'file' });
		const path = file ? file.fsPath : '';

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

		// Keep for context menu
		this.representedFileName = path;
135 136 137 138
	}

	private getWindowTitle(): string {
		let title = this.doGetWindowTitle();
B
Benjamin Pasero 已提交
139
		if (!trim(title)) {
140 141 142
			title = this.environmentService.appNameLong;
		}

143 144 145 146 147
		if (this.properties.isAdmin) {
			title = `${title} ${TitlebarPart.NLS_USER_IS_ADMIN}`;
		}

		if (!this.properties.isPure) {
148 149 150 151 152 153 154 155 156 157 158
			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;
	}

159 160 161 162 163 164 165 166 167 168 169 170
	public updateProperties(properties: ITitleProperties): void {
		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;

			this.setTitle(this.getWindowTitle());
		}
	}

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

B
Benjamin Pasero 已提交
189
		let root: URI;
190 191 192 193 194 195
		if (workspace.configuration) {
			root = workspace.configuration;
		} else if (workspace.folders.length) {
			root = workspace.folders[0].uri;
		}

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

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

214
		return labels.template(titleTemplate, {
B
Benjamin Pasero 已提交
215 216 217
			activeEditorShort,
			activeEditorLong,
			activeEditorMedium,
218 219
			rootName,
			rootPath,
220 221
			folderName,
			folderPath,
222 223 224 225 226 227
			dirty,
			appName,
			separator: { label: separator }
		});
	}

228
	public createContentArea(parent: HTMLElement): HTMLElement {
B
Benjamin Pasero 已提交
229 230 231 232 233 234 235 236
		this.titleContainer = $(parent);

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

237
		// Maximize/Restore on doubleclick
238 239
		this.titleContainer.on(EventType.DBLCLICK, (e) => {
			EventHelper.stop(e);
240 241 242 243

			this.onTitleDoubleclick();
		});

B
Benjamin Pasero 已提交
244
		// Context menu on title
245 246 247
		this.title.on([EventType.CONTEXT_MENU, EventType.MOUSE_DOWN], (e: MouseEvent) => {
			if (e.type === EventType.CONTEXT_MENU || e.metaKey) {
				EventHelper.stop(e);
B
Benjamin Pasero 已提交
248 249 250 251 252

				this.onContextMenu(e);
			}
		});

253 254
		// 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.
255
		this.titleContainer.on([EventType.MOUSE_DOWN], () => {
256 257 258 259 260 261 262 263
			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 */);

264
		return this.titleContainer.getHTMLElement();
B
Benjamin Pasero 已提交
265 266
	}

B
Benjamin Pasero 已提交
267 268 269 270
	protected updateStyles(): void {
		super.updateStyles();

		// Part container
271 272 273
		if (this.titleContainer) {
			this.titleContainer.style('color', this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_FOREGROUND : TITLE_BAR_ACTIVE_FOREGROUND));
			this.titleContainer.style('background-color', this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_BACKGROUND : TITLE_BAR_ACTIVE_BACKGROUND));
274 275

			const titleBorder = this.getColor(TITLE_BAR_BORDER);
276
			this.titleContainer.style('border-bottom', titleBorder ? `1px solid ${titleBorder}` : null);
277
		}
B
Benjamin Pasero 已提交
278 279
	}

280
	private onTitleDoubleclick(): void {
281
		this.windowService.onWindowTitleDoubleClick().then(null, errors.onUnexpectedError);
282 283
	}

B
Benjamin Pasero 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
	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--) {
307 308 309 310 311 312 313 314 315
				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 已提交
316
				let label: string;
317
				if (!isFile) {
B
Benjamin Pasero 已提交
318 319 320
					label = labels.getBaseLabel(paths.dirname(path));
				} else {
					label = labels.getBaseLabel(path);
321 322 323
				}

				actions.push(new ShowItemInFolderAction(path, label || paths.sep, this.windowsService));
B
Benjamin Pasero 已提交
324 325 326 327 328 329
			}
		}

		return actions;
	}

330
	public setTitle(title: string): void {
B
Benjamin Pasero 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

		// 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;
		}
	}

	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 已提交
353 354 355 356
}

class ShowItemInFolderAction extends Action {

357 358
	constructor(private path: string, label: string, private windowsService: IWindowsService) {
		super('showItemInFolder.action.id', label);
B
Benjamin Pasero 已提交
359 360 361 362 363
	}

	public run(): TPromise<void> {
		return this.windowsService.showItemInFolder(this.path);
	}
B
Benjamin Pasero 已提交
364
}