titleControl.ts 17.2 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 10
import nls = require('vs/nls');
import {Registry} from 'vs/platform/platform';
11
import {Scope, IActionBarRegistry, Extensions, prepareActions} from 'vs/workbench/browser/actionBarRegistry';
B
Benjamin Pasero 已提交
12 13
import {IAction, Action} from 'vs/base/common/actions';
import errors = require('vs/base/common/errors');
B
Benjamin Pasero 已提交
14
import DOM = require('vs/base/browser/dom');
15
import {TPromise} from 'vs/base/common/winjs.base';
B
Benjamin Pasero 已提交
16 17
import {BaseEditor, IEditorInputActionContext} from 'vs/workbench/browser/parts/editor/baseEditor';
import {RunOnceScheduler} from 'vs/base/common/async';
18
import {isCommonCodeEditor, isCommonDiffEditor} from 'vs/editor/common/editorCommon';
19
import arrays = require('vs/base/common/arrays');
20
import {IEditorStacksModel, IEditorGroup, IEditorIdentifier, EditorInput, IWorkbenchEditorConfiguration, IStacksModelChangeEvent, getResource} from 'vs/workbench/common/editor';
B
Benjamin Pasero 已提交
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 {IConfigurationService} from 'vs/platform/configuration/common/configuration';
B
Benjamin Pasero 已提交
27 28
import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService';
import {IMessageService, Severity} from 'vs/platform/message/common/message';
29
import {StandardMouseEvent} from 'vs/base/browser/mouseEvent';
B
Benjamin Pasero 已提交
30 31
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
32
import {IQuickOpenService} from 'vs/workbench/services/quickopen/common/quickOpenService';
33
import {IKeybindingService} from 'vs/platform/keybinding/common/keybinding';
34
import {IContextKeyService} from 'vs/platform/contextkey/common/contextkey';
35
import {CloseEditorsInGroupAction, SplitEditorAction, CloseEditorAction, KeepEditorAction, CloseOtherEditorsInGroupAction, CloseRightEditorsInGroupAction, ShowEditorsInGroupAction} from 'vs/workbench/browser/parts/editor/editorActions';
B
Benjamin Pasero 已提交
36
import {IDisposable, dispose} from 'vs/base/common/lifecycle';
37
import {createActionItem, fillInActions} from 'vs/platform/actions/browser/menuItemActionItem';
38
import {IMenuService, MenuId} from 'vs/platform/actions/common/actions';
39
import {ResourceContextKey} from 'vs/platform/actions/common/resourceContextKey';
B
Benjamin Pasero 已提交
40 41 42 43 44 45 46 47

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

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

58
export abstract class TitleControl implements ITitleAreaControl {
59 60 61

	private static draggedEditor: IEditorIdentifier;

B
Benjamin Pasero 已提交
62 63
	protected stacks: IEditorStacksModel;
	protected context: IEditorGroup;
64
	protected toDispose: IDisposable[];
B
Benjamin Pasero 已提交
65

66 67
	protected dragged: boolean;

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

76 77
	private parent: HTMLElement;

78 79 80
	private previewEditors: boolean;
	private showTabs: boolean;

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

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

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

B
Benjamin Pasero 已提交
92 93 94
	constructor(
		@IContextMenuService protected contextMenuService: IContextMenuService,
		@IInstantiationService protected instantiationService: IInstantiationService,
95
		@IConfigurationService protected configurationService: IConfigurationService,
B
Benjamin Pasero 已提交
96 97
		@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 103
		@IMenuService protected menuService: IMenuService,
		@IQuickOpenService protected quickOpenService: IQuickOpenService
B
Benjamin Pasero 已提交
104 105 106 107 108
	) {
		this.toDispose = [];
		this.stacks = editorGroupService.getStacksModel();
		this.mapActionsToEditors = Object.create(null);

109 110
		this.onConfigurationUpdated(configurationService.getConfiguration<IWorkbenchEditorConfiguration>());

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

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

B
Benjamin Pasero 已提交
116
		this.initActions();
117 118 119
		this.registerListeners();
	}

120 121 122 123
	public static getDraggedEditor(): IEditorIdentifier {
		return TitleControl.draggedEditor;
	}

124 125 126 127
	public setDragged(dragged: boolean): void {
		this.dragged = dragged;
	}

128 129 130 131 132 133 134 135
	protected onEditorDragStart(editor: IEditorIdentifier): void {
		TitleControl.draggedEditor = editor;
	}

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

136 137
	private registerListeners(): void {
		this.toDispose.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config)));
B
Benjamin Pasero 已提交
138 139 140 141 142 143 144
		this.toDispose.push(this.stacks.onModelChanged(e => this.onStacksChanged(e)));
	}

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

	private onConfigurationUpdated(config: IWorkbenchEditorConfiguration): void {
148 149
		this.previewEditors = config.workbench.editor.enablePreview;
		this.showTabs = config.workbench.editor.showTabs;
B
Benjamin Pasero 已提交
150 151
	}

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

		const groupCount = this.stacks.groups.length;

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

163 164 165 166 167 168 169 170 171 172
	private onSchedule(): void {
		if (this.refreshScheduled) {
			this.doRefresh();
		} else {
			this.doUpdate();
		}

		this.refreshScheduled = false;
	}

B
Benjamin Pasero 已提交
173 174
	public setContext(group: IEditorGroup): void {
		this.context = group;
175 176 177 178 179 180 181 182 183 184
	}

	public update(instant?: boolean): void {
		if (instant) {
			this.scheduler.cancel();
			this.onSchedule();
		} else {
			this.scheduler.schedule();
		}
	}
B
Benjamin Pasero 已提交
185

186 187 188 189 190 191 192 193 194
	public refresh(instant?: boolean) {
		this.refreshScheduled = true;

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

197 198 199 200 201 202 203
	public create(parent: HTMLElement): void {
		this.parent = parent;
	}

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

205 206 207 208 209
	protected abstract doRefresh(): void;

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

211 212 213 214
	public layout(): void {
		// Subclasses can opt in to react on layout
	}

B
Benjamin Pasero 已提交
215
	public allowDragging(element: HTMLElement): boolean {
B
Benjamin Pasero 已提交
216
		return !DOM.findParentWithClass(element, 'monaco-action-bar', 'one-editor-silo');
B
Benjamin Pasero 已提交
217 218
	}

B
Benjamin Pasero 已提交
219 220
	private initActions(): void {
		this.closeEditorAction = this.instantiationService.createInstance(CloseEditorAction, CloseEditorAction.ID, nls.localize('close', "Close"));
B
Benjamin Pasero 已提交
221
		this.closeOtherEditorsAction = this.instantiationService.createInstance(CloseOtherEditorsInGroupAction, CloseOtherEditorsInGroupAction.ID, nls.localize('closeOthers', "Close Others"));
B
Benjamin Pasero 已提交
222 223
		this.closeRightEditorsAction = this.instantiationService.createInstance(CloseRightEditorsInGroupAction, CloseRightEditorsInGroupAction.ID, nls.localize('closeRight', "Close to the Right"));
		this.closeEditorsInGroupAction = this.instantiationService.createInstance(CloseEditorsInGroupAction, CloseEditorsInGroupAction.ID, nls.localize('closeAll', "Close All"));
224
		this.pinEditorAction = this.instantiationService.createInstance(KeepEditorAction, KeepEditorAction.ID, nls.localize('keepOpen', "Keep Open"));
225
		this.showEditorsInGroupAction = this.instantiationService.createInstance(ShowEditorsInGroupAction, ShowEditorsInGroupAction.ID, nls.localize('showOpenedEditors', "Show Opened Editors"));
B
Benjamin Pasero 已提交
226 227 228
		this.splitEditorAction = this.instantiationService.createInstance(SplitEditorAction, SplitEditorAction.ID, SplitEditorAction.LABEL);
	}

229 230
	protected createEditorActionsToolBar(container: HTMLElement): void {
		this.editorActionsToolbar = new ToolBar(container, this.contextMenuService, {
B
Benjamin Pasero 已提交
231 232 233 234
			actionItemProvider: (action: Action) => this.actionItemProvider(action),
			orientation: ActionsOrientation.HORIZONTAL,
			ariaLabel: nls.localize('araLabelEditorActions', "Editor actions"),
			getKeyBinding: (action) => {
235
				const opts = this.keybindingService.lookupKeybindings(action.id);
B
Benjamin Pasero 已提交
236 237 238 239 240 241 242 243 244
				if (opts.length > 0) {
					return opts[0]; // only take the first one
				}

				return null;
			}
		});

		// Action Run Handling
245
		this.toDispose.push(this.editorActionsToolbar.actionRunner.addListener2(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 294 295
		const {group} = identifier;
		const position = this.stacks.positionOfGroup(group);

296 297 298
		// Update the resource context
		this.resourceContext.set(group && getResource(group.activeEditor));

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 328
			// 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()));

			fillInActions(titleBarMenu, { 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
		if (this.showTabs) {
380 381
			if (secondaryEditorActions.length > 0) {
				secondaryEditorActions.push(new Separator());
382
			}
383
			secondaryEditorActions.push(this.showEditorsInGroupAction);
384 385
			secondaryEditorActions.push(new Separator());
			secondaryEditorActions.push(this.closeEditorsInGroupAction);
B
Benjamin Pasero 已提交
386 387
		}

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

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

395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
		if (!arrays.equals(primaryEditorActionIds, this.currentPrimaryEditorActionIds) || !arrays.equals(secondaryEditorActionIds, this.currentSecondaryEditorActionIds)) {
			this.editorActionsToolbar.setActions(primaryEditorActions, secondaryEditorActions)();

			if (!this.showTabs) {
				this.editorActionsToolbar.addPrimaryAction(this.closeEditorAction)();
			}

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

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

		this.currentPrimaryEditorActionIds = [];
		this.currentSecondaryEditorActionIds = [];
B
Benjamin Pasero 已提交
412 413
	}

414 415 416 417 418 419 420 421 422 423 424 425
	protected onContextMenu(identifier: IEditorIdentifier, e: Event, node: HTMLElement): void {
		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,
			getKeyBinding: (action) => {
426
				const opts = this.keybindingService.lookupKeybindings(action.id);
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
				if (opts.length > 0) {
					return opts[0]; // only take the first one
				}

				return null;
			}
		});
	}

	protected getContextMenuActions(identifier: IEditorIdentifier): IAction[] {
		const {editor, group} = identifier;

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

		if (this.showTabs) {
			actions.push(this.closeRightEditorsAction);
		}

		actions.push(this.closeEditorsInGroupAction);

		if (this.previewEditors) {
			actions.push(new Separator(), this.pinEditorAction);
		}

		return actions;
	}

B
Benjamin Pasero 已提交
463 464 465 466 467 468
	public dispose(): void {
		dispose(this.toDispose);

		// Actions
		[
			this.splitEditorAction,
B
Benjamin Pasero 已提交
469
			this.showEditorsInGroupAction,
B
Benjamin Pasero 已提交
470
			this.closeEditorAction,
B
Benjamin Pasero 已提交
471
			this.closeRightEditorsAction,
B
Benjamin Pasero 已提交
472
			this.closeOtherEditorsAction,
B
Benjamin Pasero 已提交
473 474
			this.closeEditorsInGroupAction,
			this.pinEditorAction
B
Benjamin Pasero 已提交
475 476 477
		].forEach((action) => {
			action.dispose();
		});
478 479 480

		// Toolbar
		this.editorActionsToolbar.dispose();
B
Benjamin Pasero 已提交
481 482
	}
}