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

'use strict';

B
Benjamin Pasero 已提交
8
import 'vs/css!./media/titlecontrol';
B
Benjamin Pasero 已提交
9
import nls = require('vs/nls');
10 11 12
import { Registry } from 'vs/platform/platform';
import { Scope, IActionBarRegistry, Extensions, prepareActions } from 'vs/workbench/browser/actionBarRegistry';
import { IAction, Action } from 'vs/base/common/actions';
B
Benjamin Pasero 已提交
13
import errors = require('vs/base/common/errors');
B
Benjamin Pasero 已提交
14
import DOM = require('vs/base/browser/dom');
15 16 17 18
import { TPromise } from 'vs/base/common/winjs.base';
import { BaseEditor, IEditorInputActionContext } from 'vs/workbench/browser/parts/editor/baseEditor';
import { RunOnceScheduler } from 'vs/base/common/async';
import { isCommonCodeEditor, isCommonDiffEditor } from 'vs/editor/common/editorCommon';
19
import arrays = require('vs/base/common/arrays');
I
isidor 已提交
20
import { IEditorStacksModel, IEditorGroup, IEditorIdentifier, EditorInput, IStacksModelChangeEvent, toResource } from 'vs/workbench/common/editor';
21 22 23 24 25
import { EventType as BaseEventType } from 'vs/base/common/events';
import { IActionItem, ActionsOrientation, Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
26
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
27 28 29 30
import { IMessageService, Severity } from 'vs/platform/message/common/message';
import { StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
J
Johannes Rieken 已提交
31
import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen';
32
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
33
import { ResolvedKeybinding } from 'vs/base/common/keyCodes';
34
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
B
Benjamin Pasero 已提交
35
import { CloseEditorsInGroupAction, SplitEditorAction, CloseEditorAction, KeepEditorAction, CloseOtherEditorsInGroupAction, CloseRightEditorsInGroupAction, ShowEditorsInGroupAction } from 'vs/workbench/browser/parts/editor/editorActions';
36 37
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { createActionItem, fillInActions } from 'vs/platform/actions/browser/menuItemActionItem';
38
import { IMenuService, MenuId, IMenu, ExecuteCommandAction } from 'vs/platform/actions/common/actions';
J
Johannes Rieken 已提交
39
import { ResourceContextKey } from 'vs/workbench/common/resourceContextKey';
40
import { IThemeService } from 'vs/platform/theme/common/themeService';
B
Benjamin Pasero 已提交
41
import { Themable } from 'vs/workbench/common/theme';
B
Benjamin Pasero 已提交
42 43 44 45 46 47 48 49

export interface IToolbarActions {
	primary: IAction[];
	secondary: IAction[];
}

export interface ITitleAreaControl {
	setContext(group: IEditorGroup): void;
50
	hasContext(): boolean;
B
Benjamin Pasero 已提交
51
	allowDragging(element: HTMLElement): boolean;
52
	setDragged(dragged: boolean): void;
53
	create(parent: HTMLElement): void;
54
	getContainer(): HTMLElement;
55 56
	refresh(instant?: boolean): void;
	update(instant?: boolean): void;
57
	layout(): void;
B
Benjamin Pasero 已提交
58 59 60
	dispose(): void;
}

B
Benjamin Pasero 已提交
61
export abstract class TitleControl extends Themable implements ITitleAreaControl {
62 63 64

	private static draggedEditor: IEditorIdentifier;

B
Benjamin Pasero 已提交
65 66 67
	protected stacks: IEditorStacksModel;
	protected context: IEditorGroup;

68 69
	protected dragged: boolean;

B
Benjamin Pasero 已提交
70
	protected closeEditorAction: CloseEditorAction;
B
Benjamin Pasero 已提交
71
	protected pinEditorAction: KeepEditorAction;
B
Benjamin Pasero 已提交
72
	protected closeOtherEditorsAction: CloseOtherEditorsInGroupAction;
B
Benjamin Pasero 已提交
73
	protected closeRightEditorsAction: CloseRightEditorsInGroupAction;
B
Benjamin Pasero 已提交
74 75
	protected closeEditorsInGroupAction: CloseEditorsInGroupAction;
	protected splitEditorAction: SplitEditorAction;
B
Benjamin Pasero 已提交
76
	protected showEditorsInGroupAction: ShowEditorsInGroupAction;
B
Benjamin Pasero 已提交
77

78 79
	private parent: HTMLElement;

80 81 82 83
	private currentPrimaryEditorActionIds: string[] = [];
	private currentSecondaryEditorActionIds: string[] = [];
	protected editorActionsToolbar: ToolBar;

B
Benjamin Pasero 已提交
84 85
	private mapActionsToEditors: { [editorId: string]: IToolbarActions; };
	private scheduler: RunOnceScheduler;
86
	private refreshScheduled: boolean;
B
Benjamin Pasero 已提交
87

88
	private resourceContext: ResourceContextKey;
89
	private disposeOnEditorActions: IDisposable[] = [];
90

B
Benjamin Pasero 已提交
91 92
	private contextMenu: IMenu;

B
Benjamin Pasero 已提交
93 94 95 96 97
	constructor(
		@IContextMenuService protected contextMenuService: IContextMenuService,
		@IInstantiationService protected instantiationService: IInstantiationService,
		@IWorkbenchEditorService protected editorService: IWorkbenchEditorService,
		@IEditorGroupService protected editorGroupService: IEditorGroupService,
98
		@IContextKeyService protected contextKeyService: IContextKeyService,
99
		@IKeybindingService protected keybindingService: IKeybindingService,
B
Benjamin Pasero 已提交
100
		@ITelemetryService protected telemetryService: ITelemetryService,
101
		@IMessageService protected messageService: IMessageService,
102
		@IMenuService protected menuService: IMenuService,
103 104
		@IQuickOpenService protected quickOpenService: IQuickOpenService,
		@IThemeService protected themeService: IThemeService
B
Benjamin Pasero 已提交
105
	) {
B
Benjamin Pasero 已提交
106
		super(themeService);
107

B
Benjamin Pasero 已提交
108 109 110
		this.stacks = editorGroupService.getStacksModel();
		this.mapActionsToEditors = Object.create(null);

111
		this.scheduler = new RunOnceScheduler(() => this.onSchedule(), 0);
112
		this.toUnbind.push(this.scheduler);
B
Benjamin Pasero 已提交
113

114 115
		this.resourceContext = instantiationService.createInstance(ResourceContextKey);

116
		this.contextMenu = this.menuService.createMenu(MenuId.EditorTitleContext, this.contextKeyService);
117
		this.toUnbind.push(this.contextMenu);
B
Benjamin Pasero 已提交
118

119
		this.initActions(this.instantiationService);
120 121 122
		this.registerListeners();
	}

123 124 125 126
	public static getDraggedEditor(): IEditorIdentifier {
		return TitleControl.draggedEditor;
	}

127 128 129 130
	public setDragged(dragged: boolean): void {
		this.dragged = dragged;
	}

131 132 133 134 135 136 137 138
	protected onEditorDragStart(editor: IEditorIdentifier): void {
		TitleControl.draggedEditor = editor;
	}

	protected onEditorDragEnd(): void {
		TitleControl.draggedEditor = void 0;
	}

139
	private registerListeners(): void {
140
		this.toUnbind.push(this.stacks.onModelChanged(e => this.onStacksChanged(e)));
B
Benjamin Pasero 已提交
141 142 143 144 145 146
	}

	private onStacksChanged(e: IStacksModelChangeEvent): void {
		if (e.structural) {
			this.updateSplitActionEnablement();
		}
147 148
	}

B
Benjamin Pasero 已提交
149
	private updateSplitActionEnablement(): void {
150 151 152 153 154 155 156 157 158 159
		if (!this.context) {
			return;
		}

		const groupCount = this.stacks.groups.length;

		// Split editor
		this.splitEditorAction.enabled = groupCount < 3;
	}

160
	protected updateStyles(): void {
161 162
		super.updateStyles();

163 164 165
		this.update(true); // run an update when the theme changes to new styles
	}

166 167 168 169 170 171 172 173 174 175
	private onSchedule(): void {
		if (this.refreshScheduled) {
			this.doRefresh();
		} else {
			this.doUpdate();
		}

		this.refreshScheduled = false;
	}

B
Benjamin Pasero 已提交
176 177
	public setContext(group: IEditorGroup): void {
		this.context = group;
178 179
	}

180 181 182 183
	public hasContext(): boolean {
		return !!this.context;
	}

184 185 186 187 188 189 190 191
	public update(instant?: boolean): void {
		if (instant) {
			this.scheduler.cancel();
			this.onSchedule();
		} else {
			this.scheduler.schedule();
		}
	}
B
Benjamin Pasero 已提交
192

193 194 195 196 197 198 199 200 201
	public refresh(instant?: boolean) {
		this.refreshScheduled = true;

		if (instant) {
			this.scheduler.cancel();
			this.onSchedule();
		} else {
			this.scheduler.schedule();
		}
B
Benjamin Pasero 已提交
202 203
	}

204 205 206 207 208 209 210
	public create(parent: HTMLElement): void {
		this.parent = parent;
	}

	public getContainer(): HTMLElement {
		return this.parent;
	}
211

212 213 214 215 216
	protected abstract doRefresh(): void;

	protected doUpdate(): void {
		this.doRefresh();
	}
B
Benjamin Pasero 已提交
217

218 219 220 221
	public layout(): void {
		// Subclasses can opt in to react on layout
	}

B
Benjamin Pasero 已提交
222
	public allowDragging(element: HTMLElement): boolean {
B
Benjamin Pasero 已提交
223
		return !DOM.findParentWithClass(element, 'monaco-action-bar', 'one-editor-silo');
B
Benjamin Pasero 已提交
224 225
	}

226 227 228 229 230 231 232 233
	protected initActions(services: IInstantiationService): void {
		this.closeEditorAction = services.createInstance(CloseEditorAction, CloseEditorAction.ID, nls.localize('close', "Close"));
		this.closeOtherEditorsAction = services.createInstance(CloseOtherEditorsInGroupAction, CloseOtherEditorsInGroupAction.ID, nls.localize('closeOthers', "Close Others"));
		this.closeRightEditorsAction = services.createInstance(CloseRightEditorsInGroupAction, CloseRightEditorsInGroupAction.ID, nls.localize('closeRight', "Close to the Right"));
		this.closeEditorsInGroupAction = services.createInstance(CloseEditorsInGroupAction, CloseEditorsInGroupAction.ID, nls.localize('closeAll', "Close All"));
		this.pinEditorAction = services.createInstance(KeepEditorAction, KeepEditorAction.ID, nls.localize('keepOpen', "Keep Open"));
		this.showEditorsInGroupAction = services.createInstance(ShowEditorsInGroupAction, ShowEditorsInGroupAction.ID, nls.localize('showOpenedEditors', "Show Opened Editors"));
		this.splitEditorAction = services.createInstance(SplitEditorAction, SplitEditorAction.ID, SplitEditorAction.LABEL);
B
Benjamin Pasero 已提交
234 235
	}

236 237
	protected createEditorActionsToolBar(container: HTMLElement): void {
		this.editorActionsToolbar = new ToolBar(container, this.contextMenuService, {
B
Benjamin Pasero 已提交
238 239 240
			actionItemProvider: (action: Action) => this.actionItemProvider(action),
			orientation: ActionsOrientation.HORIZONTAL,
			ariaLabel: nls.localize('araLabelEditorActions', "Editor actions"),
241
			getKeyBinding: (action) => this.getKeybinding(action)
B
Benjamin Pasero 已提交
242 243 244
		});

		// Action Run Handling
A
Alex Dima 已提交
245
		this.toUnbind.push(this.editorActionsToolbar.actionRunner.addListener(BaseEventType.RUN, (e: any) => {
B
Benjamin Pasero 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

			// Check for Error
			if (e.error && !errors.isPromiseCanceledError(e.error)) {
				this.messageService.show(Severity.Error, e.error);
			}

			// Log in telemetry
			if (this.telemetryService) {
				this.telemetryService.publicLog('workbenchActionExecuted', { id: e.action.id, from: 'editorPart' });
			}
		}));
	}

	protected actionItemProvider(action: Action): IActionItem {
		if (!this.context) {
			return null;
		}

		const group = this.context;
		const position = this.stacks.positionOfGroup(group);
		const editor = this.editorService.getVisibleEditors()[position];

		let actionItem: IActionItem;

		// Check Active Editor
		if (editor instanceof BaseEditor) {
			actionItem = editor.getActionItem(action);
		}

		// Check Registry
		if (!actionItem) {
277
			const actionBarRegistry = Registry.as<IActionBarRegistry>(Extensions.Actionbar);
B
Benjamin Pasero 已提交
278 279 280
			actionItem = actionBarRegistry.getActionItemForContext(Scope.EDITOR, { input: editor && editor.input, editor, position }, action);
		}

281 282
		// Check extensions
		if (!actionItem) {
283
			actionItem = createActionItem(action, this.keybindingService, this.messageService);
284 285
		}

B
Benjamin Pasero 已提交
286 287 288
		return actionItem;
	}

289
	protected getEditorActions(identifier: IEditorIdentifier): IToolbarActions {
B
Benjamin Pasero 已提交
290 291 292
		const primary: IAction[] = [];
		const secondary: IAction[] = [];

293
		const { group } = identifier;
294 295
		const position = this.stacks.positionOfGroup(group);

296
		// Update the resource context
297
		this.resourceContext.set(group && toResource(group.activeEditor, { supportSideBySide: true }));
298

299 300
		// Editor actions require the editor control to be there, so we retrieve it via service
		const control = this.editorService.getVisibleEditors()[position];
301
		if (control instanceof BaseEditor && control.input && typeof control.position === 'number') {
302 303 304

			// Editor Control Actions
			let editorActions = this.mapActionsToEditors[control.getId()];
B
Benjamin Pasero 已提交
305
			if (!editorActions) {
306 307
				editorActions = this.getEditorActionsForContext(control);
				this.mapActionsToEditors[control.getId()] = editorActions;
B
Benjamin Pasero 已提交
308 309 310 311
			}
			primary.push(...editorActions.primary);
			secondary.push(...editorActions.secondary);

312 313
			// Editor Input Actions
			const editorInputActions = this.getEditorActionsForContext({ input: control.input, editor: control, position: control.position });
B
Benjamin Pasero 已提交
314 315
			primary.push(...editorInputActions.primary);
			secondary.push(...editorInputActions.secondary);
316 317

			// MenuItems
318 319 320 321 322 323 324 325 326 327
			// TODO This isn't very proper but needed as we have failed to
			// use the correct context key service per editor only once. Don't
			// take this code as sample of how to work with menus
			this.disposeOnEditorActions = dispose(this.disposeOnEditorActions);
			const widget = control.getControl();
			const codeEditor = isCommonCodeEditor(widget) && widget || isCommonDiffEditor(widget) && widget.getModifiedEditor();
			const scopedContextKeyService = codeEditor && codeEditor.invokeWithinContext(accessor => accessor.get(IContextKeyService)) || this.contextKeyService;
			const titleBarMenu = this.menuService.createMenu(MenuId.EditorTitle, scopedContextKeyService);
			this.disposeOnEditorActions.push(titleBarMenu, titleBarMenu.onDidChange(_ => this.update()));

328
			fillInActions(titleBarMenu, { arg: this.resourceContext.get() }, { primary, secondary });
B
Benjamin Pasero 已提交
329 330 331 332 333
		}

		return { primary, secondary };
	}

J
Johannes Rieken 已提交
334
	private getEditorActionsForContext(context: BaseEditor | IEditorInputActionContext): IToolbarActions {
335 336
		const primaryActions: IAction[] = [];
		const secondaryActions: IAction[] = [];
B
Benjamin Pasero 已提交
337 338 339 340 341 342 343 344

		// From Editor
		if (context instanceof BaseEditor) {
			primaryActions.push(...(<BaseEditor>context).getActions());
			secondaryActions.push(...(<BaseEditor>context).getSecondaryActions());
		}

		// From Contributions
345 346 347 348 349
		else {
			const actionBarRegistry = Registry.as<IActionBarRegistry>(Extensions.Actionbar);
			primaryActions.push(...actionBarRegistry.getActionBarActionsForContext(Scope.EDITOR, context));
			secondaryActions.push(...actionBarRegistry.getSecondaryActionBarActionsForContext(Scope.EDITOR, context));
		}
B
Benjamin Pasero 已提交
350 351 352 353 354 355 356

		return {
			primary: primaryActions,
			secondary: secondaryActions
		};
	}

357 358 359 360 361
	protected updateEditorActionsToolbar(): void {
		const group = this.context;
		if (!group) {
			return;
		}
B
Benjamin Pasero 已提交
362

363 364 365 366 367 368 369 370 371 372
		const editor = group && group.activeEditor;
		const isActive = this.stacks.isActive(group);

		// Update Editor Actions Toolbar
		let primaryEditorActions: IAction[] = [];
		let secondaryEditorActions: IAction[] = [];
		if (isActive) {
			const editorActions = this.getEditorActions({ group, editor });
			primaryEditorActions = prepareActions(editorActions.primary);
			if (isActive && editor instanceof EditorInput && editor.supportsSplitEditor()) {
373
				this.updateSplitActionEnablement();
374 375 376 377
				primaryEditorActions.push(this.splitEditorAction);
			}
			secondaryEditorActions = prepareActions(editorActions.secondary);
		}
378

379 380
		const tabOptions = this.editorGroupService.getTabOptions();
		if (tabOptions.showTabs) {
381 382
			if (secondaryEditorActions.length > 0) {
				secondaryEditorActions.push(new Separator());
383
			}
384
			secondaryEditorActions.push(this.showEditorsInGroupAction);
385 386
			secondaryEditorActions.push(new Separator());
			secondaryEditorActions.push(this.closeEditorsInGroupAction);
B
Benjamin Pasero 已提交
387 388
		}

389
		const primaryEditorActionIds = primaryEditorActions.map(a => a.id);
390
		if (!tabOptions.showTabs) {
391
			primaryEditorActionIds.push(this.closeEditorAction.id); // always show "Close" when tabs are disabled
B
Benjamin Pasero 已提交
392 393
		}

394
		const secondaryEditorActionIds = secondaryEditorActions.map(a => a.id);
B
Benjamin Pasero 已提交
395

396 397 398 399 400 401
		if (
			!arrays.equals(primaryEditorActionIds, this.currentPrimaryEditorActionIds) ||
			!arrays.equals(secondaryEditorActionIds, this.currentSecondaryEditorActionIds) ||
			primaryEditorActions.some(action => action instanceof ExecuteCommandAction) || // execute command actions can have the same ID but different arguments
			secondaryEditorActions.some(action => action instanceof ExecuteCommandAction)  // see also https://github.com/Microsoft/vscode/issues/16298
		) {
402 403
			this.editorActionsToolbar.setActions(primaryEditorActions, secondaryEditorActions)();

404
			if (!tabOptions.showTabs) {
405 406 407 408 409 410 411 412 413 414 415 416 417
				this.editorActionsToolbar.addPrimaryAction(this.closeEditorAction)();
			}

			this.currentPrimaryEditorActionIds = primaryEditorActionIds;
			this.currentSecondaryEditorActionIds = secondaryEditorActionIds;
		}
	}

	protected clearEditorActionsToolbar(): void {
		this.editorActionsToolbar.setActions([], [])();

		this.currentPrimaryEditorActionIds = [];
		this.currentSecondaryEditorActionIds = [];
B
Benjamin Pasero 已提交
418 419
	}

420
	protected onContextMenu(identifier: IEditorIdentifier, e: Event, node: HTMLElement): void {
421 422 423

		// Update the resource context
		const currentContext = this.resourceContext.get();
424
		this.resourceContext.set(toResource(identifier.editor, { supportSideBySide: true }));
425 426

		// Find target anchor
427 428 429 430 431 432 433 434 435 436
		let anchor: HTMLElement | { x: number, y: number } = node;
		if (e instanceof MouseEvent) {
			const event = new StandardMouseEvent(e);
			anchor = { x: event.posx, y: event.posy };
		}

		this.contextMenuService.showContextMenu({
			getAnchor: () => anchor,
			getActions: () => TPromise.as(this.getContextMenuActions(identifier)),
			getActionsContext: () => identifier,
B
Benjamin Pasero 已提交
437 438
			getKeyBinding: (action) => this.getKeybinding(action),
			onHide: (cancel) => this.resourceContext.set(currentContext) // restore previous context
439 440 441
		});
	}

442
	protected getKeybinding(action: IAction): ResolvedKeybinding {
443
		return this.keybindingService.lookupKeybinding(action.id);
B
Benjamin Pasero 已提交
444 445 446 447 448
	}

	protected getKeybindingLabel(action: IAction): string {
		const keybinding = this.getKeybinding(action);

449
		return keybinding ? keybinding.getLabel() : void 0;
B
Benjamin Pasero 已提交
450 451
	}

452
	protected getContextMenuActions(identifier: IEditorIdentifier): IAction[] {
453
		const { editor, group } = identifier;
454 455 456 457 458 459 460 461 462 463 464

		// Enablement
		this.closeOtherEditorsAction.enabled = group.count > 1;
		this.pinEditorAction.enabled = !group.isPinned(editor);
		this.closeRightEditorsAction.enabled = group.indexOf(editor) !== group.count - 1;

		// Actions: For all editors
		const actions: IAction[] = [
			this.closeEditorAction,
			this.closeOtherEditorsAction
		];
465
		const tabOptions = this.editorGroupService.getTabOptions();
466

467
		if (tabOptions.showTabs) {
468 469 470 471 472
			actions.push(this.closeRightEditorsAction);
		}

		actions.push(this.closeEditorsInGroupAction);

473
		if (tabOptions.previewEditors) {
474 475 476
			actions.push(new Separator(), this.pinEditorAction);
		}

B
Benjamin Pasero 已提交
477
		// Fill in contributed actions
478
		fillInActions(this.contextMenu, { arg: this.resourceContext.get() }, actions);
479

480 481 482
		return actions;
	}

B
Benjamin Pasero 已提交
483
	public dispose(): void {
484
		super.dispose();
B
Benjamin Pasero 已提交
485 486 487 488

		// Actions
		[
			this.splitEditorAction,
B
Benjamin Pasero 已提交
489
			this.showEditorsInGroupAction,
B
Benjamin Pasero 已提交
490
			this.closeEditorAction,
B
Benjamin Pasero 已提交
491
			this.closeRightEditorsAction,
B
Benjamin Pasero 已提交
492
			this.closeOtherEditorsAction,
B
Benjamin Pasero 已提交
493 494
			this.closeEditorsInGroupAction,
			this.pinEditorAction
B
Benjamin Pasero 已提交
495 496 497
		].forEach((action) => {
			action.dispose();
		});
498 499 500

		// Toolbar
		this.editorActionsToolbar.dispose();
B
Benjamin Pasero 已提交
501
	}
J
Johannes Rieken 已提交
502
}