tabsTitleControl.ts 27.2 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';
43
import { IThemeService } from 'vs/platform/theme/common/themeService';
B
Benjamin Pasero 已提交
44 45
import { INACTIVE_TAB_BACKGROUND, ACTIVE_TAB_BACKGROUND, ACTIVE_TAB_ACTIVE_GROUP_FOREGROUND, ACTIVE_TAB_INACTIVE_GROUP_FOREGROUND, INACTIVE_TAB_ACTIVE_GROUP_FOREGROUND, INACTIVE_TAB_INACTIVE_GROUP_FOREGROUND, TAB_BORDER, EDITOR_DRAG_AND_DROP_BACKGROUND } from 'vs/workbench/common/theme';
import { highContrastOutline } from 'vs/platform/theme/common/colorRegistry';
B
Benjamin Pasero 已提交
46 47 48 49 50 51

interface IEditorInputLabel {
	editor: IEditorInput;
	name: string;
	hasAmbiguousName?: boolean;
	description?: string;
52
	title?: string;
B
Benjamin Pasero 已提交
53
}
B
wip  
Benjamin Pasero 已提交
54 55

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

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

B
Benjamin Pasero 已提交
81
		this.tabDisposeables = [];
82
		this.editorLabels = [];
B
wip  
Benjamin Pasero 已提交
83 84
	}

85 86 87 88 89 90 91
	protected initActions(services: IInstantiationService): void {
		super.initActions(this.createScopedInstantiationService());
	}

	private createScopedInstantiationService(): IInstantiationService {
		const stacks = this.editorGroupService.getStacksModel();
		const delegatingEditorService = this.instantiationService.createInstance(DelegatingWorkbenchEditorService);
92 93 94 95 96

		// 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.
97 98
		// 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.
99 100 101
		delegatingEditorService.setEditorCloseHandler((position, editor) => {
			const group = stacks.groupAt(position);
			if (group && stacks.isActive(group) && !group.isActive(editor)) {
102
				this.editorGroupService.focusGroup(group);
103 104
			}

105 106
			this.blockRevealActiveTab = true;

107 108 109
			return TPromise.as(void 0);
		});

110
		return this.instantiationService.createChild(new ServiceCollection([IWorkbenchEditorService, delegatingEditorService]));
111 112
	}

B
wip  
Benjamin Pasero 已提交
113 114 115
	public setContext(group: IEditorGroup): void {
		super.setContext(group);

116
		this.editorActionsToolbar.context = { group };
B
wip  
Benjamin Pasero 已提交
117 118
	}

119
	public create(parent: HTMLElement): void {
120
		super.create(parent);
121

122
		this.titleContainer = parent;
B
wip  
Benjamin Pasero 已提交
123

124
		// Tabs Container
B
Benjamin Pasero 已提交
125
		this.tabsContainer = document.createElement('div');
126
		this.tabsContainer.setAttribute('role', 'tablist');
B
Benjamin Pasero 已提交
127
		DOM.addClass(this.tabsContainer, 'tabs-container');
128

129
		// Forward scrolling inside the container to our custom scrollbar
130
		this.toUnbind.push(DOM.addDisposableListener(this.tabsContainer, DOM.EventType.SCROLL, e => {
B
Benjamin Pasero 已提交
131 132 133 134 135 136 137
			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
				});
			}
		}));

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

144
				const group = this.context;
B
Benjamin Pasero 已提交
145 146 147
				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
				}
148 149 150
			}
		}));

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
		// 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 已提交
166

B
Benjamin Pasero 已提交
167
		// Drag over
168
		this.toUnbind.push(DOM.addDisposableListener(this.tabsContainer, DOM.EventType.DRAG_OVER, (e: DragEvent) => {
B
Benjamin Pasero 已提交
169 170
			DOM.addClass(this.tabsContainer, 'scroll'); // enable support to scroll while dragging

B
Benjamin Pasero 已提交
171 172
			const target = e.target;
			if (target instanceof HTMLElement && target.className.indexOf('tabs-container') === 0) {
B
Benjamin Pasero 已提交
173
				this.updateDropFeedback(this.tabsContainer, true);
B
Benjamin Pasero 已提交
174 175 176 177
			}
		}));

		// Drag leave
178
		this.toUnbind.push(DOM.addDisposableListener(this.tabsContainer, DOM.EventType.DRAG_LEAVE, (e: DragEvent) => {
B
Benjamin Pasero 已提交
179
			this.updateDropFeedback(this.tabsContainer, false);
B
Benjamin Pasero 已提交
180
			DOM.removeClass(this.tabsContainer, 'scroll');
B
Benjamin Pasero 已提交
181 182 183
		}));

		// Drag end
184
		this.toUnbind.push(DOM.addDisposableListener(this.tabsContainer, DOM.EventType.DRAG_END, (e: DragEvent) => {
B
Benjamin Pasero 已提交
185
			this.updateDropFeedback(this.tabsContainer, false);
B
Benjamin Pasero 已提交
186
			DOM.removeClass(this.tabsContainer, 'scroll');
B
Benjamin Pasero 已提交
187 188
		}));

B
Benjamin Pasero 已提交
189
		// Drop onto tabs container
190
		this.toUnbind.push(DOM.addDisposableListener(this.tabsContainer, DOM.EventType.DROP, (e: DragEvent) => {
B
Benjamin Pasero 已提交
191
			this.updateDropFeedback(this.tabsContainer, false);
B
Benjamin Pasero 已提交
192
			DOM.removeClass(this.tabsContainer, 'scroll');
B
Benjamin Pasero 已提交
193

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

B
Benjamin Pasero 已提交
201
					this.onDrop(e, group, targetPosition, targetIndex);
B
Benjamin Pasero 已提交
202 203 204 205
				}
			}
		}));

206
		// Editor Actions Container
207 208 209
		const editorActionsContainer = document.createElement('div');
		DOM.addClass(editorActionsContainer, 'editor-actions');
		this.titleContainer.appendChild(editorActionsContainer);
210 211 212

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

B
Benjamin Pasero 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227
	private updateDropFeedback(element: HTMLElement, isDND: boolean, index?: number): void {
		const isTab = (typeof index === 'number');
		const isActiveTab = isTab && this.context.isActive(this.context.getEditor(index));

		// Background
		const noDNDBackgroundColor = isTab ? this.getColor(isActiveTab ? ACTIVE_TAB_BACKGROUND : INACTIVE_TAB_BACKGROUND) : null;
		element.style.backgroundColor = isDND ? this.getColor(EDITOR_DRAG_AND_DROP_BACKGROUND) : noDNDBackgroundColor;

		// Outline
		if (this.isHighContrastTheme && isDND) {
			element.style.outlineWidth = '2px';
			element.style.outlineStyle = 'dashed';
			element.style.outlineColor = this.getColor(highContrastOutline);
B
Benjamin Pasero 已提交
228
			(<any>element).style.outlineOffset = isTab ? '-5px' : '-3px'; // TS fail (gulp watch)
B
Benjamin Pasero 已提交
229 230 231 232
		} else {
			element.style.outlineWidth = null;
			element.style.outlineStyle = null;
			element.style.outlineColor = this.isHighContrastTheme ? this.getColor(highContrastOutline) : null;
B
Benjamin Pasero 已提交
233
			(<any>element).style.outlineOffset = null; // TS fail (gulp watch)
B
Benjamin Pasero 已提交
234 235 236
		}
	}

B
Benjamin Pasero 已提交
237 238 239 240
	public allowDragging(element: HTMLElement): boolean {
		return (element.className === 'tabs-container');
	}

241 242 243 244 245 246 247 248
	protected doUpdate(): void {
		if (!this.context) {
			return;
		}

		const group = this.context;

		// Tabs container activity state
249 250
		const isGroupActive = this.stacks.isActive(group);
		if (isGroupActive) {
251 252 253 254 255
			DOM.addClass(this.titleContainer, 'active');
		} else {
			DOM.removeClass(this.titleContainer, 'active');
		}

256 257
		// Compute labels and protect against duplicates
		const editorsOfGroup = this.context.getEditors();
B
Benjamin Pasero 已提交
258
		const labels = this.getUniqueTabLabels(editorsOfGroup);
259

260
		// Tab label and styles
261
		editorsOfGroup.forEach((editor, index) => {
262 263
			const tabContainer = this.tabsContainer.children[index];
			if (tabContainer instanceof HTMLElement) {
264
				const isPinned = group.isPinned(index);
265
				const isTabActive = group.isActive(editor);
266 267
				const isDirty = editor.isDirty();

268 269
				const label = labels[index];
				const name = label.name;
B
Benjamin Pasero 已提交
270
				const description = label.hasAmbiguousName && label.description ? label.description : '';
271
				const title = label.title || '';
272

273
				// Container
B
Benjamin Pasero 已提交
274
				tabContainer.setAttribute('aria-label', `${name}, tab`);
275
				tabContainer.title = title;
276 277
				tabContainer.style.borderLeftColor = (index !== 0) ? this.getColor(TAB_BORDER) : null;
				tabContainer.style.borderRightColor = (index === editorsOfGroup.length - 1) ? this.getColor(TAB_BORDER) : null;
B
Benjamin Pasero 已提交
278 279
				tabContainer.style.outlineColor = this.isHighContrastTheme ? this.getColor(highContrastOutline) : null;

280
				const tabOptions = this.editorGroupService.getTabOptions();
281
				['off', 'left'].forEach(option => {
282
					const domAction = tabOptions.tabCloseButton === option ? DOM.addClass : DOM.removeClass;
283 284
					domAction(tabContainer, `close-button-${option}`);
				});
285

286 287
				// Label
				const tabLabel = this.editorLabels[index];
288
				tabLabel.setLabel({ name, description, resource: toResource(editor, { supportSideBySide: true }) }, { extraClasses: ['tab-label'], italic: !isPinned });
289 290

				// Active state
291
				if (isTabActive) {
292
					DOM.addClass(tabContainer, 'active');
293
					tabContainer.setAttribute('aria-selected', 'true');
294
					tabContainer.style.backgroundColor = this.getColor(ACTIVE_TAB_BACKGROUND);
295 296
					tabLabel.element.style.color = this.getColor(isGroupActive ? ACTIVE_TAB_ACTIVE_GROUP_FOREGROUND : ACTIVE_TAB_INACTIVE_GROUP_FOREGROUND);

297 298 299
					this.activeTab = tabContainer;
				} else {
					DOM.removeClass(tabContainer, 'active');
300
					tabContainer.setAttribute('aria-selected', 'false');
301
					tabContainer.style.backgroundColor = this.getColor(INACTIVE_TAB_BACKGROUND);
302
					tabLabel.element.style.color = this.getColor(isGroupActive ? INACTIVE_TAB_ACTIVE_GROUP_FOREGROUND : INACTIVE_TAB_INACTIVE_GROUP_FOREGROUND);
303 304 305 306 307 308 309 310 311 312
				}

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

314
		// Update Editor Actions Toolbar
315
		this.updateEditorActionsToolbar();
316

B
Benjamin Pasero 已提交
317
		// Ensure the active tab is always revealed
318
		this.layout();
319 320
	}

B
Benjamin Pasero 已提交
321 322 323 324
	private getUniqueTabLabels(editors: IEditorInput[]): IEditorInputLabel[] {
		const labels: IEditorInputLabel[] = [];

		const mapLabelToDuplicates = new LinkedMap<string, IEditorInputLabel[]>();
B
Benjamin Pasero 已提交
325
		const mapLabelAndDescriptionToDuplicates = new LinkedMap<string, IEditorInputLabel[]>();
B
Benjamin Pasero 已提交
326 327 328 329 330 331 332 333

		// Build labels and descriptions for each editor
		editors.forEach(editor => {
			let description = editor.getDescription();
			const item: IEditorInputLabel = {
				editor,
				name: editor.getName(),
				description,
334
				title: editor.getTitle(Verbosity.LONG)
B
Benjamin Pasero 已提交
335 336 337 338
			};
			labels.push(item);

			mapLabelToDuplicates.getOrSet(item.name, []).push(item);
B
Benjamin Pasero 已提交
339 340 341 342

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

H
hun1ahpu 已提交
345
		// Mark duplicates and shorten their descriptions
B
Benjamin Pasero 已提交
346 347
		const labelDuplicates = mapLabelToDuplicates.values();
		labelDuplicates.forEach(duplicates => {
348
			if (duplicates.length > 1) {
B
Benjamin Pasero 已提交
349 350 351 352
				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 已提交
353
				});
B
Benjamin Pasero 已提交
354 355 356 357 358 359 360 361

				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 已提交
362 363 364 365 366 367
			}
		});

		return labels;
	}

368
	protected doRefresh(): void {
B
wip  
Benjamin Pasero 已提交
369
		const group = this.context;
370
		const editor = group && group.activeEditor;
B
wip  
Benjamin Pasero 已提交
371
		if (!editor) {
372 373
			this.clearTabs();

374
			this.clearEditorActionsToolbar();
B
wip  
Benjamin Pasero 已提交
375 376 377 378

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

B
Benjamin Pasero 已提交
379 380
		// Handle Tabs
		this.handleTabs(group.count);
381
		DOM.removeClass(this.titleContainer, 'empty');
382

383
		// Update Tabs
384
		this.doUpdate();
B
wip  
Benjamin Pasero 已提交
385 386
	}

387
	private clearTabs(): void {
B
Benjamin Pasero 已提交
388
		DOM.clearNode(this.tabsContainer);
389 390

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

393
		DOM.addClass(this.titleContainer, 'empty');
394 395
	}

B
Benjamin Pasero 已提交
396 397 398
	private handleTabs(tabsNeeded: number): void {
		const tabs = this.tabsContainer.children;
		const tabsCount = tabs.length;
B
Benjamin Pasero 已提交
399

B
Benjamin Pasero 已提交
400 401 402 403
		// Nothing to do if count did not change
		if (tabsCount === tabsNeeded) {
			return;
		}
B
Benjamin Pasero 已提交
404

B
Benjamin Pasero 已提交
405 406 407 408 409 410
		// We need more tabs: create new ones
		if (tabsCount < tabsNeeded) {
			for (let i = tabsCount; i < tabsNeeded; i++) {
				this.tabsContainer.appendChild(this.createTab(i));
			}
		}
411

B
Benjamin Pasero 已提交
412 413 414 415
		// 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();
416
				this.editorLabels.pop();
B
Benjamin Pasero 已提交
417
				this.tabDisposeables.pop().dispose();
418
			}
B
Benjamin Pasero 已提交
419 420
		}
	}
421

B
Benjamin Pasero 已提交
422
	private createTab(index: number): HTMLElement {
423

B
Benjamin Pasero 已提交
424 425 426 427 428
		// 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
429
		DOM.addClass(tabContainer, 'tab');
B
Benjamin Pasero 已提交
430

B
Benjamin Pasero 已提交
431 432 433
		// Tab Editor Label
		const editorLabel = this.instantiationService.createInstance(EditorLabel, tabContainer, void 0);
		this.editorLabels.push(editorLabel);
B
Benjamin Pasero 已提交
434

B
Benjamin Pasero 已提交
435 436 437 438
		// Tab Close
		const tabCloseContainer = document.createElement('div');
		DOM.addClass(tabCloseContainer, 'tab-close');
		tabContainer.appendChild(tabCloseContainer);
B
Benjamin Pasero 已提交
439

B
Benjamin Pasero 已提交
440 441
		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) });
442

B
Benjamin Pasero 已提交
443
		// Eventing
444 445 446
		const disposable = this.hookTabListeners(tabContainer, index);

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

		return tabContainer;
449 450 451 452 453 454 455
	}

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

456 457 458 459 460 461 462 463 464
		const visibleContainerWidth = this.tabsContainer.offsetWidth;
		const totalContainerWidth = this.tabsContainer.scrollWidth;

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

465 466 467 468 469 470 471
		// 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 已提交
472 473 474
		const containerScrollPosX = this.tabsContainer.scrollLeft;
		const activeTabPosX = this.activeTab.offsetLeft;
		const activeTabWidth = this.activeTab.offsetWidth;
475
		const activeTabFits = activeTabWidth <= visibleContainerWidth;
B
Benjamin Pasero 已提交
476 477

		// Tab is overflowing to the right: Scroll minimally until the element is fully visible to the right
478 479
		// 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) {
480 481 482
			this.scrollbar.updateState({
				scrollLeft: containerScrollPosX + ((activeTabPosX + activeTabWidth) /* right corner of tab */ - (containerScrollPosX + visibleContainerWidth) /* right corner of view port */)
			});
B
Benjamin Pasero 已提交
483 484
		}

485 486
		// Tab is overlflowng to the left or does not fit: Scroll it into view to the left
		else if (containerScrollPosX > activeTabPosX || !activeTabFits) {
487 488 489
			this.scrollbar.updateState({
				scrollLeft: this.activeTab.offsetLeft
			});
B
Benjamin Pasero 已提交
490
		}
B
Benjamin Pasero 已提交
491 492
	}

493
	private hookTabListeners(tab: HTMLElement, index: number): IDisposable {
B
Benjamin Pasero 已提交
494
		const disposables: IDisposable[] = [];
B
Benjamin Pasero 已提交
495 496

		// Open on Click
497
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.MOUSE_DOWN, (e: MouseEvent) => {
498 499
			tab.blur();

B
Benjamin Pasero 已提交
500
			const { editor, position } = this.toTabContext(index);
B
Benjamin Pasero 已提交
501
			if (e.button === 0 /* Left Button */ && !DOM.findParentWithClass((e.target || e.srcElement) as HTMLElement, 'monaco-action-bar', 'tab')) {
502 503 504 505 506
				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
507
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.MOUSE_UP, (e: MouseEvent) => {
508
			DOM.EventHelper.stop(e);
509
			tab.blur();
510 511

			if (e.button === 1 /* Middle Button */) {
512
				this.closeEditorAction.run(this.toTabContext(index)).done(null, errors.onUnexpectedError);
B
Benjamin Pasero 已提交
513
			}
B
Benjamin Pasero 已提交
514
		}));
B
Benjamin Pasero 已提交
515

516
		// Context menu on Shift+F10
517
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => {
518 519 520 521
			const event = new StandardKeyboardEvent(e);
			if (event.shiftKey && event.keyCode === KeyCode.F10) {
				DOM.EventHelper.stop(e);

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

				this.onContextMenu({ group, editor }, e, tab);
525 526 527
			}
		}));

B
Benjamin Pasero 已提交
528
		// Keyboard accessibility
529
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.KEY_UP, (e: KeyboardEvent) => {
B
Benjamin Pasero 已提交
530
			const event = new StandardKeyboardEvent(e);
B
Benjamin Pasero 已提交
531
			let handled = false;
B
Benjamin Pasero 已提交
532

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

B
Benjamin Pasero 已提交
535
			// Run action on Enter/Space
A
Alexandru Dima 已提交
536
			if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) {
B
Benjamin Pasero 已提交
537
				handled = true;
B
Benjamin Pasero 已提交
538
				this.editorService.openEditor(editor, null, position).done(null, errors.onUnexpectedError);
B
Benjamin Pasero 已提交
539 540
			}

B
Benjamin Pasero 已提交
541
			// Navigate in editors
A
Alexandru Dima 已提交
542
			else if ([KeyCode.LeftArrow, KeyCode.RightArrow, KeyCode.UpArrow, KeyCode.DownArrow, KeyCode.Home, KeyCode.End].some(kb => event.equals(kb))) {
B
Benjamin Pasero 已提交
543
				let targetIndex: number;
A
Alexandru Dima 已提交
544
				if (event.equals(KeyCode.LeftArrow) || event.equals(KeyCode.UpArrow)) {
B
Benjamin Pasero 已提交
545
					targetIndex = index - 1;
A
Alexandru Dima 已提交
546
				} else if (event.equals(KeyCode.RightArrow) || event.equals(KeyCode.DownArrow)) {
B
Benjamin Pasero 已提交
547
					targetIndex = index + 1;
A
Alexandru Dima 已提交
548
				} else if (event.equals(KeyCode.Home)) {
B
Benjamin Pasero 已提交
549 550 551 552 553
					targetIndex = 0;
				} else {
					targetIndex = group.count - 1;
				}

B
Benjamin Pasero 已提交
554 555 556
				const target = group.getEditor(targetIndex);
				if (target) {
					handled = true;
557
					this.editorService.openEditor(target, { preserveFocus: true }, position).done(null, errors.onUnexpectedError);
B
Benjamin Pasero 已提交
558 559 560
					(<HTMLElement>this.tabsContainer.childNodes[targetIndex]).focus();
				}
			}
B
Benjamin Pasero 已提交
561

B
Benjamin Pasero 已提交
562
			if (handled) {
563
				DOM.EventHelper.stop(e, true);
B
Benjamin Pasero 已提交
564
			}
565 566 567 568 569

			// 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 已提交
570 571
		}));

B
Benjamin Pasero 已提交
572
		// Pin on double click
573
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.DBLCLICK, (e: MouseEvent) => {
B
Benjamin Pasero 已提交
574 575
			DOM.EventHelper.stop(e);

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

578
			this.editorGroupService.pinEditor(group, editor);
B
Benjamin Pasero 已提交
579
		}));
B
Benjamin Pasero 已提交
580

B
Benjamin Pasero 已提交
581
		// Context menu
582
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.CONTEXT_MENU, (e: Event) => {
583
			DOM.EventHelper.stop(e, true);
B
Benjamin Pasero 已提交
584 585 586
			const { group, editor } = this.toTabContext(index);

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

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

593
			this.onEditorDragStart({ editor, group });
594
			e.dataTransfer.effectAllowed = 'copyMove';
B
Benjamin Pasero 已提交
595

B
Benjamin Pasero 已提交
596
			// Insert transfer accordingly
597 598 599
			const fileResource = toResource(editor, { supportSideBySide: true, filter: 'file' });
			if (fileResource) {
				const resource = fileResource.toString();
B
Benjamin Pasero 已提交
600 601
				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 已提交
602
			}
B
Benjamin Pasero 已提交
603 604
		}));

605 606 607 608 609 610
		// 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 已提交
611
		// Drag over
612
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.DRAG_ENTER, (e: DragEvent) => {
613
			counter++;
B
Benjamin Pasero 已提交
614
			this.updateDropFeedback(tab, true, index);
B
Benjamin Pasero 已提交
615 616 617
		}));

		// Drag leave
618
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.DRAG_LEAVE, (e: DragEvent) => {
619 620
			counter--;
			if (counter === 0) {
B
Benjamin Pasero 已提交
621
				this.updateDropFeedback(tab, false, index);
622
			}
B
Benjamin Pasero 已提交
623 624 625
		}));

		// Drag end
626
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.DRAG_END, (e: DragEvent) => {
627
			counter = 0;
B
Benjamin Pasero 已提交
628
			this.updateDropFeedback(tab, false, index);
B
Benjamin Pasero 已提交
629

630
			this.onEditorDragEnd();
B
Benjamin Pasero 已提交
631 632 633
		}));

		// Drop
634
		disposables.push(DOM.addDisposableListener(tab, DOM.EventType.DROP, (e: DragEvent) => {
635
			counter = 0;
B
Benjamin Pasero 已提交
636
			this.updateDropFeedback(tab, false, index);
B
Benjamin Pasero 已提交
637

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

B
Benjamin Pasero 已提交
640
			this.onDrop(e, group, position, index);
B
Benjamin Pasero 已提交
641
		}));
642 643

		return combinedDisposable(disposables);
B
Benjamin Pasero 已提交
644
	}
B
Benjamin Pasero 已提交
645

B
Benjamin Pasero 已提交
646 647 648 649 650 651 652 653
	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 已提交
654
	private onDrop(e: DragEvent, group: IEditorGroup, targetPosition: Position, targetIndex: number): void {
B
Benjamin Pasero 已提交
655
		this.updateDropFeedback(this.tabsContainer, false);
656
		DOM.removeClass(this.tabsContainer, 'scroll');
657

B
Benjamin Pasero 已提交
658 659 660 661
		// Local DND
		const draggedEditor = TabsTitleControl.getDraggedEditor();
		if (draggedEditor) {
			DOM.EventHelper.stop(e, true);
662

B
Benjamin Pasero 已提交
663 664
			// Move editor to target position and index
			if (this.isMoveOperation(e, draggedEditor.group, group)) {
665
				this.editorGroupService.moveEditor(draggedEditor.editor, draggedEditor.group, group, { index: targetIndex });
B
Benjamin Pasero 已提交
666
			}
667

B
Benjamin Pasero 已提交
668
			// Copy: just open editor at target index
669
			else {
B
Benjamin Pasero 已提交
670
				this.editorService.openEditor(draggedEditor.editor, { pinned: true, index: targetIndex }, targetPosition).done(null, errors.onUnexpectedError);
671
			}
B
Benjamin Pasero 已提交
672 673 674 675 676 677 678 679

			this.onEditorDragEnd();
		}

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

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

685
		// Handle resources
686
		if (resources.length) {
B
Benjamin Pasero 已提交
687
			DOM.EventHelper.stop(e, true);
688

689 690 691 692 693 694 695 696 697 698 699 700 701
			// 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 => {
702
				return {
703
					input: { resource: d.resource, options: { pinned: true, index: targetIndex } },
704 705
					position: targetPosition
				};
J
Joao Moreno 已提交
706
			})).then(() => {
707
				this.editorGroupService.focusGroup(targetPosition);
J
Joao Moreno 已提交
708 709
				return this.windowService.focusWindow();
			}).done(null, errors.onUnexpectedError);
710 711 712
		}
	}

713 714 715 716 717
	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 已提交
718
}
B
Benjamin Pasero 已提交
719 720 721 722 723 724 725 726 727

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 已提交
728 729 730
		if (!group) {
			return TPromise.as(void 0);
		}
B
Benjamin Pasero 已提交
731 732 733 734

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