titlebarPart.ts 12.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 22 23 24 25 26 27
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
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';
B
Benjamin Pasero 已提交
34
import { IPartService } from 'vs/workbench/services/part/common/partService';
35
import { isMacintosh } from 'vs/base/common/platform';
B
Benjamin Pasero 已提交
36 37 38 39 40

export class TitlebarPart extends Part implements ITitleService {

	public _serviceBrand: any;

41 42 43
	private static NLS_UNSUPPORTED = nls.localize('patchedWindowTitle', "[Unsupported]");
	private static NLS_EXTENSION_HOST = nls.localize('devExtensionWindowTitlePrefix', "[Extension Development Host]");
	private static TITLE_DIRTY = '\u25cf ';
44
	private static TITLE_SEPARATOR = isMacintosh ? ' - ' : ' - '; // macOS uses special - separator
45

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

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

54 55 56 57
	private titleTemplate: string;
	private isPure: boolean;
	private activeEditorListeners: IDisposable[];

58 59
	constructor(
		id: string,
B
Benjamin Pasero 已提交
60 61
		@IContextMenuService private contextMenuService: IContextMenuService,
		@IWindowService private windowService: IWindowService,
62 63 64 65 66 67
		@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 已提交
68
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
69 70
		@IThemeService themeService: IThemeService,
		@IPartService private partService: IPartService
71
	) {
B
Benjamin Pasero 已提交
72
		super(id, { hasTitle: false }, themeService);
73

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

		this.init();

79 80 81
		this.registerListeners();
	}

82 83 84 85 86
	private init(): void {

		// Read initial config
		this.onConfigurationChanged();

87 88
		// Initial window title when loading is done
		this.partService.joinCreation().done(() => this.setTitle(this.getWindowTitle()));
89 90 91 92 93 94 95 96 97 98

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

99
	private registerListeners(): void {
B
Benjamin Pasero 已提交
100 101
		this.toUnbind.push(DOM.addDisposableListener(window, DOM.EventType.BLUR, () => this.onBlur()));
		this.toUnbind.push(DOM.addDisposableListener(window, DOM.EventType.FOCUS, () => this.onFocus()));
102 103
		this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(() => this.onConfigurationChanged(true)));
		this.toUnbind.push(this.editorGroupService.onEditorsChanged(() => this.onEditorsChanged()));
104 105 106
		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())));
107 108
	}

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

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

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 168 169 170 171 172
	private onConfigurationChanged(update?: boolean): void {
		const currentTitleTemplate = this.titleTemplate;
		this.titleTemplate = this.configurationService.lookup<string>('window.title').value;

		if (update && currentTitleTemplate !== this.titleTemplate) {
			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 已提交
173 174 175
	 * {activeEditorLong}: e.g. /Users/Development/myProject/myFolder/myFile.txt
	 * {activeEditorMedium}: e.g. myFolder/myFile.txt
	 * {activeEditorShort}: e.g. myFile.txt
176
	 * {rootName}: e.g. myFolder1, myFolder2, myFolder3
177
	 * {rootPath}: e.g. /Users/Development/myProject
178 179
	 * {folderName}: e.g. myFolder
	 * {folderPath}: e.g. /Users/Development/myFolder
180 181 182 183 184 185
	 * {appName}: e.g. VS Code
	 * {dirty}: indiactor
	 * {separator}: conditional separator
	 */
	private doGetWindowTitle(): string {
		const input = this.editorService.getActiveEditorInput();
B
Benjamin Pasero 已提交
186
		const workspace = this.contextService.getWorkspace();
187

188 189 190 191 192 193 194
		let root;
		if (workspace.configuration) {
			root = workspace.configuration;
		} else if (workspace.folders.length) {
			root = workspace.folders[0].uri;
		}

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

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

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

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

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

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

			this.onTitleDoubleclick();
		});

B
Benjamin Pasero 已提交
242 243 244 245 246 247 248 249 250
		// 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);
			}
		});

251 252 253 254 255 256 257 258 259 260 261
		// 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 已提交
262 263 264
		return this.titleContainer;
	}

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

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

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

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

B
Benjamin Pasero 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
	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--) {
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
				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);

				let label = paths.basename(path);
				if (!isFile) {
					label = paths.basename(paths.dirname(path));
				}

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

		return actions;
	}

327
	public setTitle(title: string): void {
B
Benjamin Pasero 已提交
328 329 330 331 332 333 334 335 336 337 338 339

		// 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 已提交
340 341 342 343 344 345 346 347 348
	public setRepresentedFilename(path: string): void {

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

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

B
Benjamin Pasero 已提交
349 350 351 352 353 354 355 356 357 358
	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 已提交
359 360 361 362
}

class ShowItemInFolderAction extends Action {

363 364
	constructor(private path: string, label: string, private windowsService: IWindowsService) {
		super('showItemInFolder.action.id', label);
B
Benjamin Pasero 已提交
365 366 367 368 369
	}

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