tabsTitleControl.ts 28.7 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, IUntitledResourceInput } 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
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 { 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';
32
import { IWindowService, IWindowsService } from 'vs/platform/windows/common/windows';
J
Johannes Rieken 已提交
33
import { TitleControl } from 'vs/workbench/browser/parts/editor/titleControl';
J
Johannes Rieken 已提交
34
import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen';
35
import { IDisposable, dispose, combinedDisposable } from 'vs/base/common/lifecycle';
J
Johannes Rieken 已提交
36 37 38
import { ScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
import { extractResources } from 'vs/base/browser/dnd';
39
import { getOrSet } from 'vs/base/common/map';
40 41
import { DelegatingWorkbenchEditorService } from 'vs/workbench/services/editor/browser/editorService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
B
Benjamin Pasero 已提交
42
import { IThemeService, registerThemingParticipant, ITheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService';
43
import { TAB_INACTIVE_BACKGROUND, TAB_ACTIVE_BACKGROUND, TAB_ACTIVE_FOREGROUND, TAB_INACTIVE_FOREGROUND, TAB_BORDER, EDITOR_DRAG_AND_DROP_BACKGROUND, TAB_UNFOCUSED_ACTIVE_FOREGROUND, TAB_UNFOCUSED_INACTIVE_FOREGROUND } from 'vs/workbench/common/theme';
44
import { activeContrastBorder, contrastBorder } from 'vs/platform/theme/common/colorRegistry';
B
Benjamin Pasero 已提交
45 46 47 48 49

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

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

	constructor(
		@IContextMenuService contextMenuService: IContextMenuService,
		@IInstantiationService instantiationService: IInstantiationService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IEditorGroupService editorGroupService: IEditorGroupService,
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
		@IQuickOpenService quickOpenService: IQuickOpenService,
73
		@IWindowService private windowService: IWindowService,
74
		@IWindowsService private windowsService: IWindowsService,
75
		@IThemeService themeService: IThemeService
B
wip  
Benjamin Pasero 已提交
76
	) {
77
		super(contextMenuService, instantiationService, editorService, editorGroupService, contextKeyService, keybindingService, telemetryService, messageService, menuService, quickOpenService, themeService);
B
wip  
Benjamin Pasero 已提交
78

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

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

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

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

103 104
			this.blockRevealActiveTab = true;

105 106 107
			return TPromise.as(void 0);
		});

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

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

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

117
	public create(parent: HTMLElement): void {
118
		super.create(parent);
119

120
		this.titleContainer = parent;
B
wip  
Benjamin Pasero 已提交
121

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

B
Benjamin Pasero 已提交
212 213
	private updateDropFeedback(element: HTMLElement, isDND: boolean, index?: number): void {
		const isTab = (typeof index === 'number');
214
		const isActiveTab = isTab && this.context && this.context.isActive(this.context.getEditor(index));
B
Benjamin Pasero 已提交
215 216

		// Background
B
Benjamin Pasero 已提交
217
		const noDNDBackgroundColor = isTab ? this.getColor(isActiveTab ? TAB_ACTIVE_BACKGROUND : TAB_INACTIVE_BACKGROUND) : null;
B
Benjamin Pasero 已提交
218 219 220
		element.style.backgroundColor = isDND ? this.getColor(EDITOR_DRAG_AND_DROP_BACKGROUND) : noDNDBackgroundColor;

		// Outline
221 222
		const activeContrastBorderColor = this.getColor(activeContrastBorder);
		if (activeContrastBorderColor && isDND) {
B
Benjamin Pasero 已提交
223 224
			element.style.outlineWidth = '2px';
			element.style.outlineStyle = 'dashed';
225
			element.style.outlineColor = activeContrastBorderColor;
B
Benjamin Pasero 已提交
226
			element.style.outlineOffset = isTab ? '-5px' : '-3px';
B
Benjamin Pasero 已提交
227 228 229
		} else {
			element.style.outlineWidth = null;
			element.style.outlineStyle = null;
230
			element.style.outlineColor = activeContrastBorderColor;
B
Benjamin Pasero 已提交
231
			element.style.outlineOffset = null;
B
Benjamin Pasero 已提交
232 233 234
		}
	}

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

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

		const group = this.context;

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

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

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

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

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

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

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

				// Active state
289
				if (isTabActive) {
290
					DOM.addClass(tabContainer, 'active');
291
					tabContainer.setAttribute('aria-selected', 'true');
B
Benjamin Pasero 已提交
292
					tabContainer.style.backgroundColor = this.getColor(TAB_ACTIVE_BACKGROUND);
293
					tabLabel.element.style.color = this.getColor(isGroupActive ? TAB_ACTIVE_FOREGROUND : TAB_UNFOCUSED_ACTIVE_FOREGROUND);
294

295 296 297
					this.activeTab = tabContainer;
				} else {
					DOM.removeClass(tabContainer, 'active');
298
					tabContainer.setAttribute('aria-selected', 'false');
B
Benjamin Pasero 已提交
299
					tabContainer.style.backgroundColor = this.getColor(TAB_INACTIVE_BACKGROUND);
300
					tabLabel.element.style.color = this.getColor(isGroupActive ? TAB_INACTIVE_FOREGROUND : TAB_UNFOCUSED_INACTIVE_FOREGROUND);
301 302 303 304 305 306 307 308 309 310
				}

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

312
		// Update Editor Actions Toolbar
313
		this.updateEditorActionsToolbar();
314

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

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

322 323
		const mapLabelToDuplicates = new Map<string, IEditorInputLabel[]>();
		const mapLabelAndDescriptionToDuplicates = new Map<string, IEditorInputLabel[]>();
B
Benjamin Pasero 已提交
324 325 326

		// Build labels and descriptions for each editor
		editors.forEach(editor => {
327
			const name = editor.getName();
B
Benjamin Pasero 已提交
328
			let description = editor.getDescription();
329 330 331 332
			if (mapLabelAndDescriptionToDuplicates.has(`${name}${description}`)) {
				description = editor.getDescription(true); // try verbose description if name+description already exists
			}

B
Benjamin Pasero 已提交
333
			const item: IEditorInputLabel = {
334
				name,
B
Benjamin Pasero 已提交
335
				description,
336
				title: editor.getTitle(Verbosity.LONG)
B
Benjamin Pasero 已提交
337 338 339
			};
			labels.push(item);

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

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

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

				if (duplicates.length > 1) {
357
					const shortenedDescriptions = shorten(duplicates.map(duplicate => duplicate.description));
B
Benjamin Pasero 已提交
358 359 360 361 362
					duplicates.forEach((duplicate, i) => {
						duplicate.description = shortenedDescriptions[i];
						duplicate.hasAmbiguousName = true;
					});
				}
B
Benjamin Pasero 已提交
363 364 365 366 367 368
			}
		});

		return labels;
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return tabContainer;
450 451 452 453 454 455 456
	}

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

457 458 459 460
		const visibleContainerWidth = this.tabsContainer.offsetWidth;
		const totalContainerWidth = this.tabsContainer.scrollWidth;

		// Update scrollbar
461
		this.scrollbar.setScrollDimensions({
462 463 464 465
			width: visibleContainerWidth,
			scrollWidth: totalContainerWidth
		});

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

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

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

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

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

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

512
			if (e.button === 1 /* Middle Button*/ && !this.isTabActionBar((e.target || e.srcElement) as HTMLElement)) {
513
				this.closeEditorAction.run(this.toTabContext(index)).done(null, errors.onUnexpectedError);
B
Benjamin Pasero 已提交
514
			}
B
Benjamin Pasero 已提交
515
		}));
B
Benjamin Pasero 已提交
516

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

647 648 649 650
	private isTabActionBar(element: HTMLElement): boolean {
		return !!DOM.findParentWithClass(element, 'monaco-action-bar', 'tab');
	}

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

B
Benjamin Pasero 已提交
663 664 665 666
		// Local DND
		const draggedEditor = TabsTitleControl.getDraggedEditor();
		if (draggedEditor) {
			DOM.EventHelper.stop(e, true);
667

B
Benjamin Pasero 已提交
668 669
			// Move editor to target position and index
			if (this.isMoveOperation(e, draggedEditor.group, group)) {
670
				this.editorGroupService.moveEditor(draggedEditor.editor, draggedEditor.group, group, { index: targetIndex });
B
Benjamin Pasero 已提交
671
			}
672

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

			this.onEditorDragEnd();
		}

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

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

690
		// Handle resources
691
		if (resources.length) {
B
Benjamin Pasero 已提交
692
			DOM.EventHelper.stop(e, true);
693

694 695 696
			// Add external ones to recently open list
			const externalResources = resources.filter(d => d.isExternal).map(d => d.resource);
			if (externalResources.length) {
697
				this.windowsService.addRecentlyOpened(externalResources.map(resource => resource.fsPath));
698 699 700 701
			}

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

class TabActionRunner extends ActionRunner {

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

B
Benjamin Pasero 已提交
726
	public run(action: IAction, context?: any): TPromise<void> {
B
Benjamin Pasero 已提交
727
		const group = this.group();
B
Benjamin Pasero 已提交
728 729 730
		if (!group) {
			return TPromise.as(void 0);
		}
B
Benjamin Pasero 已提交
731 732 733

		return super.run(action, { group, editor: group.getEditor(this.index) });
	}
B
Benjamin Pasero 已提交
734 735 736 737
}

registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {

B
Benjamin Pasero 已提交
738
	// Styling with Outline color (e.g. high contrast theme)
739 740
	const activeContrastBorderColor = theme.getColor(activeContrastBorder);
	if (activeContrastBorderColor) {
B
Benjamin Pasero 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
		collector.addRule(`
			.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.active,
			.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.active:hover  {
				outline: 1px solid;
				outline-offset: -5px;
			}

			.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab:hover  {
				outline: 1px dashed;
				outline-offset: -5px;
			}

			.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.active > .tab-close .action-label,
			.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.active:hover > .tab-close .action-label,
			.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.dirty > .tab-close .action-label,
			.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab:hover > .tab-close .action-label {
				opacity: 1 !important;
			}
		`);
	}
});