tabsTitleControl.ts 25.0 KB
Newer Older
B
wip  
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/tabstitle';
B
Benjamin Pasero 已提交
9
import nls = require('vs/nls');
B
Benjamin Pasero 已提交
10
import { TPromise } from 'vs/base/common/winjs.base';
B
Benjamin Pasero 已提交
11 12
import errors = require('vs/base/common/errors');
import DOM = require('vs/base/browser/dom');
J
Johannes Rieken 已提交
13 14
import { isMacintosh } from 'vs/base/common/platform';
import { MIME_BINARY } from 'vs/base/common/mime';
B
Benjamin Pasero 已提交
15
import { shorten } from 'vs/base/common/labels';
B
Benjamin Pasero 已提交
16
import { ActionRunner, IAction } from 'vs/base/common/actions';
17
import { Position, IEditorInput, Verbosity } from 'vs/platform/editor/common/editor';
18
import { IEditorGroup, toResource } from 'vs/workbench/common/editor';
J
Johannes Rieken 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { EditorLabel } from 'vs/workbench/browser/labels';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { IMessageService } from 'vs/platform/message/common/message';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IMenuService } from 'vs/platform/actions/common/actions';
J
Joao Moreno 已提交
33
import { IWindowService } from 'vs/platform/windows/common/windows';
J
Johannes Rieken 已提交
34
import { TitleControl } from 'vs/workbench/browser/parts/editor/titleControl';
J
Johannes Rieken 已提交
35
import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen';
36
import { IDisposable, dispose, combinedDisposable } from 'vs/base/common/lifecycle';
J
Johannes Rieken 已提交
37 38 39 40
import { ScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
import { extractResources } from 'vs/base/browser/dnd';
import { LinkedMap } from 'vs/base/common/map';
41 42
import { DelegatingWorkbenchEditorService } from 'vs/workbench/services/editor/browser/editorService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
B
Benjamin Pasero 已提交
43 44 45 46 47 48

interface IEditorInputLabel {
	editor: IEditorInput;
	name: string;
	hasAmbiguousName?: boolean;
	description?: string;
49
	title?: string;
B
Benjamin Pasero 已提交
50
}
B
wip  
Benjamin Pasero 已提交
51 52

export class TabsTitleControl extends TitleControl {
B
Benjamin Pasero 已提交
53 54 55
	private titleContainer: HTMLElement;
	private tabsContainer: HTMLElement;
	private activeTab: HTMLElement;
56
	private editorLabels: EditorLabel[];
57
	private scrollbar: ScrollableElement;
58
	private tabDisposeables: IDisposable[];
59
	private blockRevealActiveTab: boolean;
B
wip  
Benjamin Pasero 已提交
60 61 62 63 64 65

	constructor(
		@IContextMenuService contextMenuService: IContextMenuService,
		@IInstantiationService instantiationService: IInstantiationService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IEditorGroupService editorGroupService: IEditorGroupService,
66
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
67
		@IContextKeyService contextKeyService: IContextKeyService,
68
		@IKeybindingService keybindingService: IKeybindingService,
B
wip  
Benjamin Pasero 已提交
69
		@ITelemetryService telemetryService: ITelemetryService,
70
		@IMessageService messageService: IMessageService,
71
		@IMenuService menuService: IMenuService,
J
Joao Moreno 已提交
72 73
		@IQuickOpenService quickOpenService: IQuickOpenService,
		@IWindowService private windowService: IWindowService
B
wip  
Benjamin Pasero 已提交
74
	) {
75
		super(contextMenuService, instantiationService, editorService, editorGroupService, contextKeyService, keybindingService, telemetryService, messageService, menuService, quickOpenService);
B
wip  
Benjamin Pasero 已提交
76

B
Benjamin Pasero 已提交
77
		this.tabDisposeables = [];
78
		this.editorLabels = [];
B
wip  
Benjamin Pasero 已提交
79 80
	}

81 82 83 84 85 86 87
	protected initActions(services: IInstantiationService): void {
		super.initActions(this.createScopedInstantiationService());
	}

	private createScopedInstantiationService(): IInstantiationService {
		const stacks = this.editorGroupService.getStacksModel();
		const delegatingEditorService = this.instantiationService.createInstance(DelegatingWorkbenchEditorService);
88 89 90 91 92

		// We create a scoped instantiation service to override the behaviour when closing an inactive editor
		// Specifically we want to move focus back to the editor when an inactive editor is closed from anywhere
		// in the tabs title control (e.g. mouse middle click, context menu on tab). This is only needed for
		// the inactive editors because closing the active one will always cause a tab switch that sets focus.
93 94
		// We also want to block the tabs container to reveal the currently active tab because that makes it very
		// hard to close multiple inactive tabs next to each other.
95 96 97
		delegatingEditorService.setEditorCloseHandler((position, editor) => {
			const group = stacks.groupAt(position);
			if (group && stacks.isActive(group) && !group.isActive(editor)) {
98
				this.editorGroupService.focusGroup(group);
99 100
			}

101 102
			this.blockRevealActiveTab = true;

103 104 105
			return TPromise.as(void 0);
		});

106
		return this.instantiationService.createChild(new ServiceCollection([IWorkbenchEditorService, delegatingEditorService]));
107 108
	}

B
wip  
Benjamin Pasero 已提交
109 110 111
	public setContext(group: IEditorGroup): void {
		super.setContext(group);

112
		this.editorActionsToolbar.context = { group };
B
wip  
Benjamin Pasero 已提交
113 114
	}

115
	public create(parent: HTMLElement): void {
116
		super.create(parent);
117

118
		this.titleContainer = parent;
B
wip  
Benjamin Pasero 已提交
119

120
		// Tabs Container
B
Benjamin Pasero 已提交
121
		this.tabsContainer = document.createElement('div');
122
		this.tabsContainer.setAttribute('role', 'tablist');
B
Benjamin Pasero 已提交
123
		DOM.addClass(this.tabsContainer, 'tabs-container');
124

125
		// Forward scrolling inside the container to our custom scrollbar
B
Benjamin Pasero 已提交
126 127 128 129 130 131 132 133
		this.toDispose.push(DOM.addDisposableListener(this.tabsContainer, DOM.EventType.SCROLL, e => {
			if (DOM.hasClass(this.tabsContainer, 'scroll')) {
				this.scrollbar.updateState({
					scrollLeft: this.tabsContainer.scrollLeft // during DND the  container gets scrolled so we need to update the custom scrollbar
				});
			}
		}));

134 135 136 137 138 139
		// New file when double clicking on tabs container (but not tabs)
		this.toDispose.push(DOM.addDisposableListener(this.tabsContainer, DOM.EventType.DBLCLICK, e => {
			const target = e.target;
			if (target instanceof HTMLElement && target.className.indexOf('tabs-container') === 0) {
				DOM.EventHelper.stop(e);

140
				const group = this.context;
B
Benjamin Pasero 已提交
141 142 143
				if (group) {
					this.editorService.openEditor(this.untitledEditorService.createOrGet(), { pinned: true, index: group.count /* always at the end */ }).done(null, errors.onUnexpectedError); // untitled are always pinned
				}
144 145 146
			}
		}));

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
		// Custom Scrollbar
		this.scrollbar = new ScrollableElement(this.tabsContainer, {
			horizontal: ScrollbarVisibility.Auto,
			vertical: ScrollbarVisibility.Hidden,
			scrollYToX: true,
			useShadows: false,
			canUseTranslate3d: true,
			horizontalScrollbarSize: 3
		});

		this.scrollbar.onScroll(e => {
			this.tabsContainer.scrollLeft = e.scrollLeft;
		});

		this.titleContainer.appendChild(this.scrollbar.getDomNode());
B
Benjamin Pasero 已提交
162

B
Benjamin Pasero 已提交
163 164
		// Drag over
		this.toDispose.push(DOM.addDisposableListener(this.tabsContainer, DOM.EventType.DRAG_OVER, (e: DragEvent) => {
B
Benjamin Pasero 已提交
165 166
			DOM.addClass(this.tabsContainer, 'scroll'); // enable support to scroll while dragging

B
Benjamin Pasero 已提交
167 168 169 170 171 172 173 174 175
			const target = e.target;
			if (target instanceof HTMLElement && target.className.indexOf('tabs-container') === 0) {
				DOM.addClass(this.tabsContainer, 'dropfeedback');
			}
		}));

		// Drag leave
		this.toDispose.push(DOM.addDisposableListener(this.tabsContainer, DOM.EventType.DRAG_LEAVE, (e: DragEvent) => {
			DOM.removeClass(this.tabsContainer, 'dropfeedback');
B
Benjamin Pasero 已提交
176
			DOM.removeClass(this.tabsContainer, 'scroll');
B
Benjamin Pasero 已提交
177 178 179 180 181
		}));

		// Drag end
		this.toDispose.push(DOM.addDisposableListener(this.tabsContainer, DOM.EventType.DRAG_END, (e: DragEvent) => {
			DOM.removeClass(this.tabsContainer, 'dropfeedback');
B
Benjamin Pasero 已提交
182
			DOM.removeClass(this.tabsContainer, 'scroll');
B
Benjamin Pasero 已提交
183 184
		}));

B
Benjamin Pasero 已提交
185 186
		// Drop onto tabs container
		this.toDispose.push(DOM.addDisposableListener(this.tabsContainer, DOM.EventType.DROP, (e: DragEvent) => {
B
Benjamin Pasero 已提交
187
			DOM.removeClass(this.tabsContainer, 'dropfeedback');
B
Benjamin Pasero 已提交
188
			DOM.removeClass(this.tabsContainer, 'scroll');
B
Benjamin Pasero 已提交
189

B
Benjamin Pasero 已提交
190
			const target = e.target;
B
Benjamin Pasero 已提交
191
			if (target instanceof HTMLElement && target.className.indexOf('tabs-container') === 0) {
B
Benjamin Pasero 已提交
192 193
				const group = this.context;
				if (group) {
194 195 196
					const targetPosition = this.stacks.positionOfGroup(group);
					const targetIndex = group.count;

B
Benjamin Pasero 已提交
197
					this.onDrop(e, group, targetPosition, targetIndex);
B
Benjamin Pasero 已提交
198 199 200 201
				}
			}
		}));

202
		// Editor Actions Container
203 204 205
		const editorActionsContainer = document.createElement('div');
		DOM.addClass(editorActionsContainer, 'editor-actions');
		this.titleContainer.appendChild(editorActionsContainer);
206 207 208

		// Editor Actions Toolbar
		this.createEditorActionsToolBar(editorActionsContainer);
B
wip  
Benjamin Pasero 已提交
209 210
	}

B
Benjamin Pasero 已提交
211 212 213 214
	public allowDragging(element: HTMLElement): boolean {
		return (element.className === 'tabs-container');
	}

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
	protected doUpdate(): void {
		if (!this.context) {
			return;
		}

		const group = this.context;

		// Tabs container activity state
		const isActive = this.stacks.isActive(group);
		if (isActive) {
			DOM.addClass(this.titleContainer, 'active');
		} else {
			DOM.removeClass(this.titleContainer, 'active');
		}

230 231
		// Compute labels and protect against duplicates
		const editorsOfGroup = this.context.getEditors();
B
Benjamin Pasero 已提交
232
		const labels = this.getUniqueTabLabels(editorsOfGroup);
233

234
		// Tab label and styles
235
		editorsOfGroup.forEach((editor, index) => {
236 237
			const tabContainer = this.tabsContainer.children[index];
			if (tabContainer instanceof HTMLElement) {
238
				const isPinned = group.isPinned(index);
239 240 241
				const isActive = group.isActive(editor);
				const isDirty = editor.isDirty();

242 243
				const label = labels[index];
				const name = label.name;
B
Benjamin Pasero 已提交
244
				const description = label.hasAmbiguousName && label.description ? label.description : '';
245
				const title = label.title || '';
246

247
				// Container
B
Benjamin Pasero 已提交
248
				tabContainer.setAttribute('aria-label', `${name}, tab`);
249
				tabContainer.title = title;
250
				const tabOptions = this.editorGroupService.getTabOptions();
251
				['off', 'left'].forEach(option => {
252
					const domAction = tabOptions.tabCloseButton === option ? DOM.addClass : DOM.removeClass;
253 254
					domAction(tabContainer, `close-button-${option}`);
				});
255

256 257
				// Label
				const tabLabel = this.editorLabels[index];
258
				tabLabel.setLabel({ name, description, resource: toResource(editor, { supportSideBySide: true }) }, { extraClasses: ['tab-label'], italic: !isPinned });
259 260 261 262

				// Active state
				if (isActive) {
					DOM.addClass(tabContainer, 'active');
263
					tabContainer.setAttribute('aria-selected', 'true');
264 265 266
					this.activeTab = tabContainer;
				} else {
					DOM.removeClass(tabContainer, 'active');
267
					tabContainer.setAttribute('aria-selected', 'false');
268 269 270 271 272 273 274 275 276 277
				}

				// Dirty State
				if (isDirty) {
					DOM.addClass(tabContainer, 'dirty');
				} else {
					DOM.removeClass(tabContainer, 'dirty');
				}
			}
		});
278

279
		// Update Editor Actions Toolbar
280
		this.updateEditorActionsToolbar();
281

B
Benjamin Pasero 已提交
282
		// Ensure the active tab is always revealed
283
		this.layout();
284 285
	}

B
Benjamin Pasero 已提交
286 287 288 289
	private getUniqueTabLabels(editors: IEditorInput[]): IEditorInputLabel[] {
		const labels: IEditorInputLabel[] = [];

		const mapLabelToDuplicates = new LinkedMap<string, IEditorInputLabel[]>();
B
Benjamin Pasero 已提交
290
		const mapLabelAndDescriptionToDuplicates = new LinkedMap<string, IEditorInputLabel[]>();
B
Benjamin Pasero 已提交
291 292 293 294 295 296 297 298

		// Build labels and descriptions for each editor
		editors.forEach(editor => {
			let description = editor.getDescription();
			const item: IEditorInputLabel = {
				editor,
				name: editor.getName(),
				description,
299
				title: editor.getTitle(Verbosity.LONG)
B
Benjamin Pasero 已提交
300 301 302 303
			};
			labels.push(item);

			mapLabelToDuplicates.getOrSet(item.name, []).push(item);
B
Benjamin Pasero 已提交
304 305 306 307

			if (typeof description === 'string') {
				mapLabelAndDescriptionToDuplicates.getOrSet(`${item.name}${item.description}`, []).push(item);
			}
B
Benjamin Pasero 已提交
308 309
		});

H
hun1ahpu 已提交
310
		// Mark duplicates and shorten their descriptions
B
Benjamin Pasero 已提交
311 312
		const labelDuplicates = mapLabelToDuplicates.values();
		labelDuplicates.forEach(duplicates => {
313
			if (duplicates.length > 1) {
B
Benjamin Pasero 已提交
314 315 316 317
				duplicates = duplicates.filter(d => {
					// we could have items with equal label and description. in that case it does not make much
					// sense to produce a shortened version of the label, so we ignore those kind of items
					return typeof d.description === 'string' && mapLabelAndDescriptionToDuplicates.get(`${d.name}${d.description}`).length === 1;
B
Benjamin Pasero 已提交
318
				});
B
Benjamin Pasero 已提交
319 320 321 322 323 324 325 326

				if (duplicates.length > 1) {
					const shortenedDescriptions = shorten(duplicates.map(duplicate => duplicate.editor.getDescription()));
					duplicates.forEach((duplicate, i) => {
						duplicate.description = shortenedDescriptions[i];
						duplicate.hasAmbiguousName = true;
					});
				}
B
Benjamin Pasero 已提交
327 328 329 330 331 332
			}
		});

		return labels;
	}

333
	protected doRefresh(): void {
B
wip  
Benjamin Pasero 已提交
334
		const group = this.context;
335
		const editor = group && group.activeEditor;
B
wip  
Benjamin Pasero 已提交
336
		if (!editor) {
337 338
			this.clearTabs();

339
			this.clearEditorActionsToolbar();
B
wip  
Benjamin Pasero 已提交
340 341 342 343

			return; // return early if we are being closed
		}

B
Benjamin Pasero 已提交
344 345 346
		// Handle Tabs
		this.handleTabs(group.count);
		DOM.addClass(this.titleContainer, 'shows-tabs');
347

348
		// Update Tabs
349
		this.doUpdate();
B
wip  
Benjamin Pasero 已提交
350 351
	}

352
	private clearTabs(): void {
B
Benjamin Pasero 已提交
353
		DOM.clearNode(this.tabsContainer);
354 355

		this.tabDisposeables = dispose(this.tabDisposeables);
356
		this.editorLabels = [];
B
Benjamin Pasero 已提交
357

358
		DOM.removeClass(this.titleContainer, 'shows-tabs');
359 360
	}

B
Benjamin Pasero 已提交
361 362 363
	private handleTabs(tabsNeeded: number): void {
		const tabs = this.tabsContainer.children;
		const tabsCount = tabs.length;
B
Benjamin Pasero 已提交
364

B
Benjamin Pasero 已提交
365 366 367 368
		// Nothing to do if count did not change
		if (tabsCount === tabsNeeded) {
			return;
		}
B
Benjamin Pasero 已提交
369

B
Benjamin Pasero 已提交
370 371 372 373 374 375
		// We need more tabs: create new ones
		if (tabsCount < tabsNeeded) {
			for (let i = tabsCount; i < tabsNeeded; i++) {
				this.tabsContainer.appendChild(this.createTab(i));
			}
		}
376

B
Benjamin Pasero 已提交
377 378 379 380
		// We need less tabs: delete the ones we do not need
		else {
			for (let i = 0; i < tabsCount - tabsNeeded; i++) {
				(this.tabsContainer.lastChild as HTMLElement).remove();
381
				this.editorLabels.pop();
B
Benjamin Pasero 已提交
382
				this.tabDisposeables.pop().dispose();
383
			}
B
Benjamin Pasero 已提交
384 385
		}
	}
386

B
Benjamin Pasero 已提交
387
	private createTab(index: number): HTMLElement {
388

B
Benjamin Pasero 已提交
389 390 391 392 393 394
		// Tab Container
		const tabContainer = document.createElement('div');
		tabContainer.draggable = true;
		tabContainer.tabIndex = 0;
		tabContainer.setAttribute('role', 'presentation'); // cannot use role "tab" here due to https://github.com/Microsoft/vscode/issues/8659
		DOM.addClass(tabContainer, 'tab monaco-editor-background');
B
Benjamin Pasero 已提交
395

B
Benjamin Pasero 已提交
396 397 398
		// Tab Editor Label
		const editorLabel = this.instantiationService.createInstance(EditorLabel, tabContainer, void 0);
		this.editorLabels.push(editorLabel);
B
Benjamin Pasero 已提交
399

B
Benjamin Pasero 已提交
400 401 402 403
		// Tab Close
		const tabCloseContainer = document.createElement('div');
		DOM.addClass(tabCloseContainer, 'tab-close');
		tabContainer.appendChild(tabCloseContainer);
B
Benjamin Pasero 已提交
404

B
Benjamin Pasero 已提交
405 406
		const bar = new ActionBar(tabCloseContainer, { ariaLabel: nls.localize('araLabelTabActions', "Tab actions"), actionRunner: new TabActionRunner(() => this.context, index) });
		bar.push(this.closeEditorAction, { icon: true, label: false, keybinding: this.getKeybindingLabel(this.closeEditorAction) });
407

B
Benjamin Pasero 已提交
408
		// Eventing
409 410 411
		const disposable = this.hookTabListeners(tabContainer, index);

		this.tabDisposeables.push(combinedDisposable([disposable, bar, editorLabel]));
B
Benjamin Pasero 已提交
412 413

		return tabContainer;
414 415 416 417 418 419 420
	}

	public layout(): void {
		if (!this.activeTab) {
			return;
		}

421 422 423 424 425 426 427 428 429
		const visibleContainerWidth = this.tabsContainer.offsetWidth;
		const totalContainerWidth = this.tabsContainer.scrollWidth;

		// Update scrollbar
		this.scrollbar.updateState({
			width: visibleContainerWidth,
			scrollWidth: totalContainerWidth
		});

430 431 432 433 434 435 436
		// Return now if we are blocked to reveal the active tab and clear flag
		if (this.blockRevealActiveTab) {
			this.blockRevealActiveTab = false;
			return;
		}

		// Reveal the active one
B
Benjamin Pasero 已提交
437 438 439
		const containerScrollPosX = this.tabsContainer.scrollLeft;
		const activeTabPosX = this.activeTab.offsetLeft;
		const activeTabWidth = this.activeTab.offsetWidth;
440
		const activeTabFits = activeTabWidth <= visibleContainerWidth;
B
Benjamin Pasero 已提交
441 442

		// Tab is overflowing to the right: Scroll minimally until the element is fully visible to the right
443 444
		// Note: only try to do this if we actually have enough width to give to show the tab fully!
		if (activeTabFits && containerScrollPosX + visibleContainerWidth < activeTabPosX + activeTabWidth) {
445 446 447
			this.scrollbar.updateState({
				scrollLeft: containerScrollPosX + ((activeTabPosX + activeTabWidth) /* right corner of tab */ - (containerScrollPosX + visibleContainerWidth) /* right corner of view port */)
			});
B
Benjamin Pasero 已提交
448 449
		}

450 451
		// Tab is overlflowng to the left or does not fit: Scroll it into view to the left
		else if (containerScrollPosX > activeTabPosX || !activeTabFits) {
452 453 454
			this.scrollbar.updateState({
				scrollLeft: this.activeTab.offsetLeft
			});
B
Benjamin Pasero 已提交
455
		}
B
Benjamin Pasero 已提交
456 457
	}

458
	private hookTabListeners(tab: HTMLElement, index: number): IDisposable {
B
Benjamin Pasero 已提交
459
		const disposables: IDisposable[] = [];
B
Benjamin Pasero 已提交
460 461

		// Open on Click
462
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.MOUSE_DOWN, (e: MouseEvent) => {
463 464
			tab.blur();

B
Benjamin Pasero 已提交
465
			const { editor, position } = this.toTabContext(index);
B
Benjamin Pasero 已提交
466
			if (e.button === 0 /* Left Button */ && !DOM.findParentWithClass((e.target || e.srcElement) as HTMLElement, 'monaco-action-bar', 'tab')) {
467 468 469 470 471
				setTimeout(() => this.editorService.openEditor(editor, null, position).done(null, errors.onUnexpectedError)); // timeout to keep focus in editor after mouse up
			}
		}));

		// Close on mouse middle click
472
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.MOUSE_UP, (e: MouseEvent) => {
473
			DOM.EventHelper.stop(e);
474
			tab.blur();
475 476

			if (e.button === 1 /* Middle Button */) {
477
				this.closeEditorAction.run(this.toTabContext(index)).done(null, errors.onUnexpectedError);
B
Benjamin Pasero 已提交
478
			}
B
Benjamin Pasero 已提交
479
		}));
B
Benjamin Pasero 已提交
480

481
		// Context menu on Shift+F10
482
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => {
483 484 485 486
			const event = new StandardKeyboardEvent(e);
			if (event.shiftKey && event.keyCode === KeyCode.F10) {
				DOM.EventHelper.stop(e);

B
Benjamin Pasero 已提交
487 488 489
				const { group, editor } = this.toTabContext(index);

				this.onContextMenu({ group, editor }, e, tab);
490 491 492
			}
		}));

B
Benjamin Pasero 已提交
493
		// Keyboard accessibility
494
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.KEY_UP, (e: KeyboardEvent) => {
B
Benjamin Pasero 已提交
495
			const event = new StandardKeyboardEvent(e);
B
Benjamin Pasero 已提交
496
			let handled = false;
B
Benjamin Pasero 已提交
497

B
Benjamin Pasero 已提交
498 499
			const { group, position, editor } = this.toTabContext(index);

B
Benjamin Pasero 已提交
500
			// Run action on Enter/Space
A
Alexandru Dima 已提交
501
			if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) {
B
Benjamin Pasero 已提交
502
				handled = true;
B
Benjamin Pasero 已提交
503
				this.editorService.openEditor(editor, null, position).done(null, errors.onUnexpectedError);
B
Benjamin Pasero 已提交
504 505
			}

B
Benjamin Pasero 已提交
506
			// Navigate in editors
A
Alexandru Dima 已提交
507
			else if ([KeyCode.LeftArrow, KeyCode.RightArrow, KeyCode.UpArrow, KeyCode.DownArrow, KeyCode.Home, KeyCode.End].some(kb => event.equals(kb))) {
B
Benjamin Pasero 已提交
508
				let targetIndex: number;
A
Alexandru Dima 已提交
509
				if (event.equals(KeyCode.LeftArrow) || event.equals(KeyCode.UpArrow)) {
B
Benjamin Pasero 已提交
510
					targetIndex = index - 1;
A
Alexandru Dima 已提交
511
				} else if (event.equals(KeyCode.RightArrow) || event.equals(KeyCode.DownArrow)) {
B
Benjamin Pasero 已提交
512
					targetIndex = index + 1;
A
Alexandru Dima 已提交
513
				} else if (event.equals(KeyCode.Home)) {
B
Benjamin Pasero 已提交
514 515 516 517 518
					targetIndex = 0;
				} else {
					targetIndex = group.count - 1;
				}

B
Benjamin Pasero 已提交
519 520 521
				const target = group.getEditor(targetIndex);
				if (target) {
					handled = true;
522
					this.editorService.openEditor(target, { preserveFocus: true }, position).done(null, errors.onUnexpectedError);
B
Benjamin Pasero 已提交
523 524 525
					(<HTMLElement>this.tabsContainer.childNodes[targetIndex]).focus();
				}
			}
B
Benjamin Pasero 已提交
526

B
Benjamin Pasero 已提交
527
			if (handled) {
528
				DOM.EventHelper.stop(e, true);
B
Benjamin Pasero 已提交
529
			}
530 531 532 533 534

			// moving in the tabs container can have an impact on scrolling position, so we need to update the custom scrollbar
			this.scrollbar.updateState({
				scrollLeft: this.tabsContainer.scrollLeft
			});
B
Benjamin Pasero 已提交
535 536
		}));

B
Benjamin Pasero 已提交
537
		// Pin on double click
538
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.DBLCLICK, (e: MouseEvent) => {
B
Benjamin Pasero 已提交
539 540
			DOM.EventHelper.stop(e);

B
Benjamin Pasero 已提交
541 542
			const { group, editor } = this.toTabContext(index);

543
			this.editorGroupService.pinEditor(group, editor);
B
Benjamin Pasero 已提交
544
		}));
B
Benjamin Pasero 已提交
545

B
Benjamin Pasero 已提交
546
		// Context menu
547
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.CONTEXT_MENU, (e: Event) => {
548
			DOM.EventHelper.stop(e, true);
B
Benjamin Pasero 已提交
549 550 551
			const { group, editor } = this.toTabContext(index);

			this.onContextMenu({ group, editor }, e, tab);
552
		}, true /* use capture to fix https://github.com/Microsoft/vscode/issues/19145 */));
B
Benjamin Pasero 已提交
553 554

		// Drag start
555
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.DRAG_START, (e: DragEvent) => {
B
Benjamin Pasero 已提交
556 557
			const { group, editor } = this.toTabContext(index);

558
			this.onEditorDragStart({ editor, group });
559
			e.dataTransfer.effectAllowed = 'copyMove';
B
Benjamin Pasero 已提交
560

B
Benjamin Pasero 已提交
561
			// Insert transfer accordingly
562 563 564
			const fileResource = toResource(editor, { supportSideBySide: true, filter: 'file' });
			if (fileResource) {
				const resource = fileResource.toString();
B
Benjamin Pasero 已提交
565 566
				e.dataTransfer.setData('URL', resource); // enables cross window DND of tabs
				e.dataTransfer.setData('DownloadURL', [MIME_BINARY, editor.getName(), resource].join(':')); // enables support to drag a tab as file to desktop
B
Benjamin Pasero 已提交
567
			}
B
Benjamin Pasero 已提交
568 569
		}));

570 571 572 573 574 575
		// We need to keep track of DRAG_ENTER and DRAG_LEAVE events because a tab is not just a div without children,
		// it contains a label and a close button. HTML gives us DRAG_ENTER and DRAG_LEAVE events when hovering over
		// these children and this can cause flicker of the drop feedback. The workaround is to count the events and only
		// remove the drop feedback when the counter is 0 (see https://github.com/Microsoft/vscode/issues/14470)
		let counter = 0;

B
Benjamin Pasero 已提交
576
		// Drag over
577
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.DRAG_ENTER, (e: DragEvent) => {
578
			counter++;
B
Benjamin Pasero 已提交
579 580 581 582
			DOM.addClass(tab, 'dropfeedback');
		}));

		// Drag leave
583
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.DRAG_LEAVE, (e: DragEvent) => {
584 585 586 587
			counter--;
			if (counter === 0) {
				DOM.removeClass(tab, 'dropfeedback');
			}
B
Benjamin Pasero 已提交
588 589 590
		}));

		// Drag end
591
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.DRAG_END, (e: DragEvent) => {
592
			counter = 0;
B
Benjamin Pasero 已提交
593
			DOM.removeClass(tab, 'dropfeedback');
B
Benjamin Pasero 已提交
594

595
			this.onEditorDragEnd();
B
Benjamin Pasero 已提交
596 597 598
		}));

		// Drop
599
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.DROP, (e: DragEvent) => {
600
			counter = 0;
B
Benjamin Pasero 已提交
601 602
			DOM.removeClass(tab, 'dropfeedback');

B
Benjamin Pasero 已提交
603
			const { group, position } = this.toTabContext(index);
604

B
Benjamin Pasero 已提交
605
			this.onDrop(e, group, position, index);
B
Benjamin Pasero 已提交
606
		}));
607 608

		return combinedDisposable(disposables);
B
Benjamin Pasero 已提交
609
	}
B
Benjamin Pasero 已提交
610

B
Benjamin Pasero 已提交
611 612 613 614 615 616 617 618
	private toTabContext(index: number): { group: IEditorGroup, position: Position, editor: IEditorInput } {
		const group = this.context;
		const position = this.stacks.positionOfGroup(group);
		const editor = group.getEditor(index);

		return { group, position, editor };
	}

B
Benjamin Pasero 已提交
619
	private onDrop(e: DragEvent, group: IEditorGroup, targetPosition: Position, targetIndex: number): void {
620 621
		DOM.removeClass(this.tabsContainer, 'dropfeedback');
		DOM.removeClass(this.tabsContainer, 'scroll');
622

B
Benjamin Pasero 已提交
623 624 625 626
		// Local DND
		const draggedEditor = TabsTitleControl.getDraggedEditor();
		if (draggedEditor) {
			DOM.EventHelper.stop(e, true);
627

B
Benjamin Pasero 已提交
628 629
			// Move editor to target position and index
			if (this.isMoveOperation(e, draggedEditor.group, group)) {
630
				this.editorGroupService.moveEditor(draggedEditor.editor, draggedEditor.group, group, { index: targetIndex });
B
Benjamin Pasero 已提交
631
			}
632

B
Benjamin Pasero 已提交
633
			// Copy: just open editor at target index
634
			else {
B
Benjamin Pasero 已提交
635
				this.editorService.openEditor(draggedEditor.editor, { pinned: true, index: targetIndex }, targetPosition).done(null, errors.onUnexpectedError);
636
			}
B
Benjamin Pasero 已提交
637 638 639 640 641 642 643 644

			this.onEditorDragEnd();
		}

		// External DND
		else {
			this.handleExternalDrop(e, targetPosition, targetIndex);
		}
B
Benjamin Pasero 已提交
645
	}
646

647
	private handleExternalDrop(e: DragEvent, targetPosition: Position, targetIndex: number): void {
648
		const resources = extractResources(e).filter(d => d.resource.scheme === 'file' || d.resource.scheme === 'untitled');
649

650
		// Handle resources
651
		if (resources.length) {
B
Benjamin Pasero 已提交
652
			DOM.EventHelper.stop(e, true);
653

654 655 656 657 658 659 660 661 662 663 664 665 666
			// Add external ones to recently open list
			const externalResources = resources.filter(d => d.isExternal).map(d => d.resource);
			if (externalResources.length) {
				this.windowService.addToRecentlyOpen(externalResources.map(resource => {
					return {
						path: resource.fsPath,
						isFile: true
					};
				}));
			}

			// Open in Editor
			this.editorService.openEditors(resources.map(d => {
667
				return {
668
					input: { resource: d.resource, options: { pinned: true, index: targetIndex } },
669 670
					position: targetPosition
				};
J
Joao Moreno 已提交
671
			})).then(() => {
672
				this.editorGroupService.focusGroup(targetPosition);
J
Joao Moreno 已提交
673 674
				return this.windowService.focusWindow();
			}).done(null, errors.onUnexpectedError);
675 676 677
		}
	}

678 679 680 681 682
	private isMoveOperation(e: DragEvent, source: IEditorGroup, target: IEditorGroup) {
		const isCopy = (e.ctrlKey && !isMacintosh) || (e.altKey && isMacintosh);

		return !isCopy || source.id === target.id;
	}
J
Johannes Rieken 已提交
683
}
B
Benjamin Pasero 已提交
684 685 686 687 688 689 690 691 692

class TabActionRunner extends ActionRunner {

	constructor(private group: () => IEditorGroup, private index: number) {
		super();
	}

	public run(action: IAction, context?: any): TPromise<any> {
		const group = this.group();
B
Benjamin Pasero 已提交
693 694 695
		if (!group) {
			return TPromise.as(void 0);
		}
B
Benjamin Pasero 已提交
696 697 698 699

		return super.run(action, { group, editor: group.getEditor(this.index) });
	}
}