explorerViewer.ts 32.5 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

7
import {TPromise} from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
8 9 10 11 12 13 14 15 16 17
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import objects = require('vs/base/common/objects');
import DOM = require('vs/base/browser/dom');
import URI from 'vs/base/common/uri';
import {MIME_BINARY} from 'vs/base/common/mime';
import async = require('vs/base/common/async');
import paths = require('vs/base/common/paths');
import errors = require('vs/base/common/errors');
import {isString} from 'vs/base/common/types';
18
import {IAction, ActionRunner as BaseActionRunner, IActionRunner} from 'vs/base/common/actions';
E
Erich Gamma 已提交
19 20
import comparers = require('vs/base/common/comparers');
import {InputBox} from 'vs/base/browser/ui/inputbox/inputBox';
21
import {$, Builder} from 'vs/base/browser/builder';
E
Erich Gamma 已提交
22 23
import platform = require('vs/base/common/platform');
import glob = require('vs/base/common/glob');
24
import {IDisposable} from 'vs/base/common/lifecycle';
E
Erich Gamma 已提交
25
import {ContributableActionProvider} from 'vs/workbench/browser/actionBarRegistry';
26
import {LocalFileChangeEvent, IFilesConfiguration, ITextFileService} from 'vs/workbench/parts/files/common/files';
E
Erich Gamma 已提交
27
import {IFileOperationResult, FileOperationResult, IFileStat, IFileService} from 'vs/platform/files/common/files';
28
import {FileEditorInput} from 'vs/workbench/parts/files/common/editors/fileEditorInput';
E
Erich Gamma 已提交
29
import {DuplicateFileAction, ImportFileAction, PasteFileAction, keybindingForAction, IEditableData, IFileViewletState} from 'vs/workbench/parts/files/browser/fileActions';
B
Benjamin Pasero 已提交
30
import {IDataSource, ITree, IElementCallback, IAccessibilityProvider, IRenderer, ContextMenuEvent, ISorter, IFilter, IDragAndDrop, IDragAndDropData, IDragOverReaction, DRAG_OVER_ACCEPT_BUBBLE_DOWN, DRAG_OVER_ACCEPT_BUBBLE_DOWN_COPY, DRAG_OVER_ACCEPT_BUBBLE_UP, DRAG_OVER_ACCEPT_BUBBLE_UP_COPY, DRAG_OVER_REJECT} from 'vs/base/parts/tree/browser/tree';
E
Erich Gamma 已提交
31 32 33
import {DesktopDragAndDropData, ExternalElementsDragAndDropData} from 'vs/base/parts/tree/browser/treeDnd';
import {ClickBehavior, DefaultController} from 'vs/base/parts/tree/browser/treeDefaults';
import {ActionsRenderer} from 'vs/base/parts/tree/browser/actionsRenderer';
34
import {FileStat, NewStatPlaceholder} from 'vs/workbench/parts/files/common/explorerViewModel';
A
Alex Dima 已提交
35
import {DragMouseEvent, IMouseEvent} from 'vs/base/browser/mouseEvent';
36
import {IExtensionService} from 'vs/platform/extensions/common/extensions';
E
Erich Gamma 已提交
37 38
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
import {IPartService} from 'vs/workbench/services/part/common/partService';
39
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
E
Erich Gamma 已提交
40
import {IWorkspace} from 'vs/platform/workspace/common/workspace';
41
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
42
import {IContextKeyService} from 'vs/platform/contextkey/common/contextkey';
E
Erich Gamma 已提交
43 44
import {IContextViewService, IContextMenuService} from 'vs/platform/contextview/browser/contextView';
import {IEventService} from 'vs/platform/event/common/event';
45
import {IModeService} from 'vs/editor/common/services/modeService';
E
Erich Gamma 已提交
46 47 48 49 50
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IMessageService, IConfirmation, Severity} from 'vs/platform/message/common/message';
import {IProgressService} from 'vs/platform/progress/common/progress';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {Keybinding, CommonKeybindings} from 'vs/base/common/keyCodes';
A
Cleanup  
Alex Dima 已提交
51
import {IKeyboardEvent} from 'vs/base/browser/keyboardEvent';
52
import {IMenuService, IMenu, MenuId} from 'vs/platform/actions/common/actions';
53
import {fillInActions} from 'vs/platform/actions/browser/menuItemActionItem';
E
Erich Gamma 已提交
54

55
interface CSSEscapeSupport extends Window {
56 57 58 59 60
	CSS: {
		escape: (val: string) => string;
	};
}

B
Benjamin Pasero 已提交
61
export class FileDataSource implements IDataSource {
E
Erich Gamma 已提交
62 63 64 65 66 67 68 69 70 71 72 73
	private workspace: IWorkspace;

	constructor(
		@IProgressService private progressService: IProgressService,
		@IMessageService private messageService: IMessageService,
		@IFileService private fileService: IFileService,
		@IPartService private partService: IPartService,
		@IWorkspaceContextService contextService: IWorkspaceContextService
	) {
		this.workspace = contextService.getWorkspace();
	}

B
Benjamin Pasero 已提交
74
	public getId(tree: ITree, stat: FileStat): string {
E
Erich Gamma 已提交
75 76 77
		return stat.getId();
	}

B
Benjamin Pasero 已提交
78
	public hasChildren(tree: ITree, stat: FileStat): boolean {
E
Erich Gamma 已提交
79 80 81
		return stat.isDirectory;
	}

B
Benjamin Pasero 已提交
82
	public getChildren(tree: ITree, stat: FileStat): TPromise<FileStat[]> {
E
Erich Gamma 已提交
83 84 85

		// Return early if stat is already resolved
		if (stat.isDirectoryResolved) {
A
Alex Dima 已提交
86
			return TPromise.as(stat.children);
E
Erich Gamma 已提交
87 88 89 90 91 92 93 94 95 96 97
		}

		// Resolve children and add to fileStat for future lookup
		else {

			// Resolve
			let promise = this.fileService.resolveFile(stat.resource, { resolveSingleChildDescendants: true }).then((dirStat: IFileStat) => {

				// Convert to view model
				let modelDirStat = FileStat.create(dirStat);

98
				// Add children to folder
E
Erich Gamma 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111
				for (let i = 0; i < modelDirStat.children.length; i++) {
					stat.addChild(modelDirStat.children[i]);
				}

				stat.isDirectoryResolved = true;

				return stat.children;
			}, (e: any) => {
				this.messageService.show(Severity.Error, e);

				return []; // we could not resolve any children because of an error
			});

112
			this.progressService.showWhile(promise, this.partService.isCreated() ? 800 : 3200 /* less ugly initial startup */);
E
Erich Gamma 已提交
113 114 115 116 117

			return promise;
		}
	}

B
Benjamin Pasero 已提交
118
	public getParent(tree: ITree, stat: FileStat): TPromise<FileStat> {
E
Erich Gamma 已提交
119
		if (!stat) {
A
Alex Dima 已提交
120
			return TPromise.as(null); // can be null if nothing selected in the tree
E
Erich Gamma 已提交
121 122 123 124
		}

		// Return if root reached
		if (this.workspace && stat.resource.toString() === this.workspace.resource.toString()) {
A
Alex Dima 已提交
125
			return TPromise.as(null);
E
Erich Gamma 已提交
126 127 128 129
		}

		// Return if parent already resolved
		if (stat.parent) {
A
Alex Dima 已提交
130
			return TPromise.as(stat.parent);
E
Erich Gamma 已提交
131 132 133 134 135
		}

		// We never actually resolve the parent from the disk for performance reasons. It wouldnt make
		// any sense to resolve parent by parent with requests to walk up the chain. Instead, the explorer
		// makes sure to properly resolve a deep path to a specific file and merges the result with the model.
A
Alex Dima 已提交
136
		return TPromise.as(null);
E
Erich Gamma 已提交
137 138 139 140 141 142 143 144 145 146 147 148
	}
}

export class FileActionProvider extends ContributableActionProvider {
	private state: FileViewletState;

	constructor(state: any) {
		super();

		this.state = state;
	}

B
Benjamin Pasero 已提交
149
	public hasActions(tree: ITree, stat: FileStat): boolean {
E
Erich Gamma 已提交
150 151 152 153 154 155 156
		if (stat instanceof NewStatPlaceholder) {
			return false;
		}

		return super.hasActions(tree, stat);
	}

157
	public getActions(tree: ITree, stat: FileStat): TPromise<IAction[]> {
E
Erich Gamma 已提交
158
		if (stat instanceof NewStatPlaceholder) {
A
Alex Dima 已提交
159
			return TPromise.as([]);
E
Erich Gamma 已提交
160 161 162 163 164
		}

		return super.getActions(tree, stat);
	}

B
Benjamin Pasero 已提交
165
	public hasSecondaryActions(tree: ITree, stat: FileStat): boolean {
E
Erich Gamma 已提交
166 167 168 169 170 171 172
		if (stat instanceof NewStatPlaceholder) {
			return false;
		}

		return super.hasSecondaryActions(tree, stat);
	}

173
	public getSecondaryActions(tree: ITree, stat: FileStat): TPromise<IAction[]> {
E
Erich Gamma 已提交
174
		if (stat instanceof NewStatPlaceholder) {
A
Alex Dima 已提交
175
			return TPromise.as([]);
E
Erich Gamma 已提交
176 177 178 179 180
		}

		return super.getSecondaryActions(tree, stat);
	}

181
	public runAction(tree: ITree, stat: FileStat, action: IAction, context?: any): TPromise<any>;
182 183
	public runAction(tree: ITree, stat: FileStat, actionID: string, context?: any): TPromise<any>;
	public runAction(tree: ITree, stat: FileStat, arg: any, context: any = {}): TPromise<any> {
E
Erich Gamma 已提交
184 185 186 187 188 189
		context = objects.mixin({
			viewletState: this.state,
			stat: stat
		}, context);

		if (!isString(arg)) {
190
			let action = <IAction>arg;
E
Erich Gamma 已提交
191 192 193 194 195 196 197 198
			if (action.enabled) {
				return action.run(context);
			}

			return null;
		}

		let id = <string>arg;
A
Alex Dima 已提交
199
		let promise = this.hasActions(tree, stat) ? this.getActions(tree, stat) : TPromise.as([]);
E
Erich Gamma 已提交
200

201
		return promise.then((actions: IAction[]) => {
E
Erich Gamma 已提交
202 203 204 205 206 207
			for (let i = 0, len = actions.length; i < len; i++) {
				if (actions[i].id === id && actions[i].enabled) {
					return actions[i].run(context);
				}
			}

A
Alex Dima 已提交
208
			promise = this.hasSecondaryActions(tree, stat) ? this.getSecondaryActions(tree, stat) : TPromise.as([]);
E
Erich Gamma 已提交
209

210
			return promise.then((actions: IAction[]) => {
E
Erich Gamma 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
				for (let i = 0, len = actions.length; i < len; i++) {
					if (actions[i].id === id && actions[i].enabled) {
						return actions[i].run(context);
					}
				}

				return null;
			});
		});
	}
}

export class FileViewletState implements IFileViewletState {
	private _actionProvider: FileActionProvider;
	private editableStats: { [resource: string]: IEditableData; };

	constructor() {
		this._actionProvider = new FileActionProvider(this);
		this.editableStats = Object.create(null);
	}

	public get actionProvider(): FileActionProvider {
		return this._actionProvider;
	}

	public getEditableData(stat: FileStat): IEditableData {
		return this.editableStats[stat.resource && stat.resource.toString()];
	}

	public setEditable(stat: FileStat, editableData: IEditableData): void {
		if (editableData) {
			this.editableStats[stat.resource && stat.resource.toString()] = editableData;
		}
	}

	public clearEditable(stat: FileStat): void {
		delete this.editableStats[stat.resource && stat.resource.toString()];
	}
}

251
export class ActionRunner extends BaseActionRunner implements IActionRunner {
E
Erich Gamma 已提交
252 253 254 255 256 257 258 259
	private viewletState: FileViewletState;

	constructor(state: FileViewletState) {
		super();

		this.viewletState = state;
	}

260
	public run(action: IAction, context?: any): TPromise<any> {
E
Erich Gamma 已提交
261 262 263 264 265
		return super.run(action, { viewletState: this.viewletState });
	}
}

// Explorer Renderer
B
Benjamin Pasero 已提交
266
export class FileRenderer extends ActionsRenderer implements IRenderer {
267 268 269

	private static RESOURCE_PATH_KEY = '__resourcePath';

E
Erich Gamma 已提交
270
	private state: FileViewletState;
271
	private extensionsReady: boolean;
E
Erich Gamma 已提交
272 273 274

	constructor(
		state: FileViewletState,
275
		actionRunner: IActionRunner,
276
		private container: HTMLElement,
277
		@IContextViewService private contextViewService: IContextViewService,
278
		@IExtensionService private extensionService: IExtensionService,
279
		@IModeService private modeService: IModeService
E
Erich Gamma 已提交
280 281 282 283 284 285 286
	) {
		super({
			actionProvider: state.actionProvider,
			actionRunner: actionRunner
		});

		this.state = state;
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
		this.registerListeners();
	}

	private registerListeners(): void {

		// once the extension host is up we need to reapply our CSS classes for
		// icons because additional language associations might be present then
		this.extensionService.onReady().then(() => {
			this.extensionsReady = true;

			const fileItems = this.container.getElementsByClassName('explorer-item file-icon');

			for (let i = 0; i < fileItems.length; i++) {
				const fileItem = $(<HTMLElement>fileItems.item(i));
				const resourcePath = fileItem.getProperty(FileRenderer.RESOURCE_PATH_KEY);
				if (resourcePath) {
					fileItem.setClass(['explorer-item', ...this.fileIconClasses(resourcePath)].join(' '));
					fileItem.removeProperty(FileRenderer.RESOURCE_PATH_KEY);
				}
			}
		});
E
Erich Gamma 已提交
308 309
	}

B
Benjamin Pasero 已提交
310
	public getContentHeight(tree: ITree, element: any): number {
I
isidor 已提交
311
		return 22;
E
Erich Gamma 已提交
312 313
	}

B
Benjamin Pasero 已提交
314
	public renderContents(tree: ITree, stat: FileStat, domElement: HTMLElement, previousCleanupFn: IElementCallback): IElementCallback {
E
Erich Gamma 已提交
315
		let el = $(domElement).clearChildren();
316 317 318

		// Item Container
		let item = $('.explorer-item');
319
		if (stat.isDirectory || (stat instanceof NewStatPlaceholder && stat.isDirectoryPlaceholder())) {
320 321 322 323 324 325 326 327 328 329 330
			item.addClass('folder-icon');
		} else {
			item.addClass(...this.fileIconClasses(stat.resource.fsPath));

			// We need to re-apply the icon CSS classes once the extension host is ready
			if (!this.extensionsReady) {
				item.setProperty(FileRenderer.RESOURCE_PATH_KEY, stat.resource.fsPath);
			}
		}

		item.appendTo(el);
E
Erich Gamma 已提交
331 332 333 334

		// File/Folder label
		let editableData: IEditableData = this.state.getEditableData(stat);
		if (!editableData) {
335
			return this.renderFileFolderLabel(item, stat);
E
Erich Gamma 已提交
336 337
		}

338 339 340 341 342 343 344 345 346 347 348 349 350
		// Name Input
		return this.renderNameInput(item, tree, stat, editableData);
	}

	private renderFileFolderLabel(container: Builder, stat: IFileStat): IElementCallback {
		let label = $('.explorer-item-label').appendTo(container);
		$('a.plain').text(stat.name).title(stat.resource.fsPath).appendTo(label);

		return null;
	}

	private renderNameInput(container: Builder, tree: ITree, stat: FileStat, editableData: IEditableData): IElementCallback {

E
Erich Gamma 已提交
351
		// Input field (when creating a new file or folder or renaming)
352
		let inputBox = new InputBox(container.getHTMLElement(), this.contextViewService, {
J
Joao Moreno 已提交
353 354 355
			validationOptions: {
				validation: editableData.validator,
				showMessage: true
356 357
			},
			ariaLabel: nls.localize('fileInputAriaLabel', "Type file name. Press Enter to confirm or Escape to cancel.")
J
Joao Moreno 已提交
358
		});
E
Erich Gamma 已提交
359

J
Joao Moreno 已提交
360 361
		let value = stat.name || '';
		let lastDot = value.lastIndexOf('.');
E
Erich Gamma 已提交
362

J
Joao Moreno 已提交
363 364 365
		inputBox.value = value;
		inputBox.select({ start: 0, end: lastDot > 0 && !stat.isDirectory ? lastDot : value.length });
		inputBox.focus();
E
Erich Gamma 已提交
366

J
Joao Moreno 已提交
367
		let done = async.once(commit => {
J
Joao Moreno 已提交
368 369
			tree.clearHighlight();

J
Joao Moreno 已提交
370
			if (commit && inputBox.value) {
E
Erich Gamma 已提交
371
				this.state.actionProvider.runAction(tree, stat, editableData.action, { value: inputBox.value });
J
Joao Moreno 已提交
372
			}
E
Erich Gamma 已提交
373

J
Joao Moreno 已提交
374 375
			setTimeout(() => {
				tree.DOMFocus();
J
Joao Moreno 已提交
376
				lifecycle.dispose(toDispose);
J
Joao Moreno 已提交
377
			}, 0);
J
Joao Moreno 已提交
378
		});
E
Erich Gamma 已提交
379

B
Benjamin Pasero 已提交
380
		const toDispose = [
J
Joao Moreno 已提交
381
			inputBox,
A
Cleanup  
Alex Dima 已提交
382
			DOM.addStandardDisposableListener(inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: IKeyboardEvent) => {
J
Joao Moreno 已提交
383 384 385 386 387 388 389 390 391 392 393 394
				if (e.equals(CommonKeybindings.ENTER)) {
					if (inputBox.validate()) {
						done(true);
					}
				} else if (e.equals(CommonKeybindings.ESCAPE)) {
					done(false);
				}
			}),
			DOM.addDisposableListener(inputBox.inputElement, 'blur', () => {
				done(inputBox.isInputValid());
			})
		];
E
Erich Gamma 已提交
395

J
Joao Moreno 已提交
396
		return () => done(true);
E
Erich Gamma 已提交
397 398
	}

399 400 401
	private fileIconClasses(fsPath: string): string[] {
		const ext = paths.extname(fsPath);
		const basename = paths.basename(fsPath);
402
		const name = basename.substring(0, basename.length - ext.length);
403
		const langId = this.modeService.getModeIdByFilenameOrFirstLine(fsPath);
404 405

		const classes = ['file-icon'];
406
		const cssEscapeSupport = window as CSSEscapeSupport;
407 408

		if (ext && ext.length > 1) {
409
			classes.push(`${cssEscapeSupport.CSS.escape(ext.substr(1).toLowerCase())}-ext-file-icon`);
410 411 412
		}

		if (name) {
413
			classes.push(`${cssEscapeSupport.CSS.escape(name.toLowerCase())}-name-file-icon`);
414 415 416
		}

		if (langId) {
417
			classes.push(`${cssEscapeSupport.CSS.escape(langId)}-lang-file-icon`);
E
Erich Gamma 已提交
418 419
		}

420
		return classes;
E
Erich Gamma 已提交
421 422 423
	}
}

424
// Explorer Accessibility Provider
B
Benjamin Pasero 已提交
425
export class FileAccessibilityProvider implements IAccessibilityProvider {
426

B
Benjamin Pasero 已提交
427
	public getAriaLabel(tree: ITree, stat: FileStat): string {
428
		return nls.localize('filesExplorerViewerAriaLabel', "{0}, Files Explorer", stat.name);
429 430 431
	}
}

E
Erich Gamma 已提交
432 433 434 435 436
// Explorer Controller
export class FileController extends DefaultController {
	private didCatchEnterDown: boolean;
	private state: FileViewletState;

437
	private contributedContextMenu: IMenu;
438

E
Erich Gamma 已提交
439 440 441 442 443 444 445 446 447
	private workspace: IWorkspace;

	constructor(state: FileViewletState,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@ITextFileService private textFileService: ITextFileService,
		@IContextMenuService private contextMenuService: IContextMenuService,
		@IEventService private eventService: IEventService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@ITelemetryService private telemetryService: ITelemetryService,
448
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
449
		@IMenuService menuService: IMenuService,
450
		@IContextKeyService contextKeyService: IContextKeyService
E
Erich Gamma 已提交
451 452 453
	) {
		super({ clickBehavior: ClickBehavior.ON_MOUSE_DOWN });

454
		this.contributedContextMenu = menuService.createMenu(MenuId.ExplorerContext, contextKeyService);
455

E
Erich Gamma 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
		this.workspace = contextService.getWorkspace();

		this.didCatchEnterDown = false;

		this.downKeyBindingDispatcher.set(platform.isMacintosh ? CommonKeybindings.CTRLCMD_DOWN_ARROW : CommonKeybindings.ENTER, this.onEnterDown.bind(this));
		this.upKeyBindingDispatcher.set(platform.isMacintosh ? CommonKeybindings.CTRLCMD_DOWN_ARROW : CommonKeybindings.ENTER, this.onEnterUp.bind(this));
		if (platform.isMacintosh) {
			this.upKeyBindingDispatcher.set(CommonKeybindings.WINCTRL_ENTER, this.onModifierEnterUp.bind(this)); // Mac: somehow Cmd+Enter does not work
		} else {
			this.upKeyBindingDispatcher.set(CommonKeybindings.CTRLCMD_ENTER, this.onModifierEnterUp.bind(this)); // Mac: somehow Cmd+Enter does not work
		}
		this.downKeyBindingDispatcher.set(platform.isMacintosh ? CommonKeybindings.ENTER : CommonKeybindings.F2, this.onF2.bind(this));
		this.downKeyBindingDispatcher.set(CommonKeybindings.CTRLCMD_C, this.onCopy.bind(this));
		this.downKeyBindingDispatcher.set(CommonKeybindings.CTRLCMD_V, this.onPaste.bind(this));

		if (platform.isMacintosh) {
			this.downKeyBindingDispatcher.set(CommonKeybindings.CTRLCMD_UP_ARROW, this.onLeft.bind(this));
			this.downKeyBindingDispatcher.set(CommonKeybindings.CTRLCMD_BACKSPACE, this.onDelete.bind(this));
		} else {
			this.downKeyBindingDispatcher.set(CommonKeybindings.DELETE, this.onDelete.bind(this));
			this.downKeyBindingDispatcher.set(CommonKeybindings.SHIFT_DELETE, this.onDelete.bind(this));
		}

		this.state = state;
	}

A
Alex Dima 已提交
482
	/* protected */ public onLeftClick(tree: ITree, stat: FileStat, event: IMouseEvent, origin: string = 'mouse'): boolean {
E
Erich Gamma 已提交
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
		let payload = { origin: origin };
		let isDoubleClick = (origin === 'mouse' && event.detail === 2);

		// Handle Highlight Mode
		if (tree.getHighlight()) {

			// Cancel Event
			event.preventDefault();
			event.stopPropagation();

			tree.clearHighlight(payload);

			return false;
		}

		// Handle root
		if (this.workspace && stat.resource.toString() === this.workspace.resource.toString()) {
			tree.clearFocus(payload);
			tree.clearSelection(payload);

			return false;
		}

		// Cancel Event
		let isMouseDown = event && event.browserEvent && event.browserEvent.type === 'mousedown';
		if (!isMouseDown) {
			event.preventDefault(); // we cannot preventDefault onMouseDown because this would break DND otherwise
		}
		event.stopPropagation();

		// Set DOM focus
		tree.DOMFocus();

		// Expand / Collapse
		tree.toggleExpansion(stat);

		// Allow to unselect
		if (event.shiftKey && !(stat instanceof NewStatPlaceholder)) {
			let selection = tree.getSelection();
522
			if (selection && selection.length > 0 && selection[0] === stat) {
E
Erich Gamma 已提交
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
				tree.clearSelection(payload);
			}
		}

		// Select, Focus and open files
		else if (!(stat instanceof NewStatPlaceholder)) {
			let preserveFocus = !isDoubleClick;
			tree.setFocus(stat, payload);

			if (isDoubleClick) {
				event.preventDefault(); // focus moves to editor, we need to prevent default
			}

			if (!stat.isDirectory) {
				tree.setSelection([stat], payload);

539
				this.openEditor(stat, preserveFocus, event && (event.ctrlKey || event.metaKey), isDoubleClick);
E
Erich Gamma 已提交
540 541 542 543 544 545
			}
		}

		return true;
	}

B
Benjamin Pasero 已提交
546
	public onContextMenu(tree: ITree, stat: FileStat, event: ContextMenuEvent): boolean {
E
Erich Gamma 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
		if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') {
			return false;
		}

		event.preventDefault();
		event.stopPropagation();

		tree.setFocus(stat);

		if (!this.state.actionProvider.hasSecondaryActions(tree, stat)) {
			return true;
		}

		let anchor = { x: event.posx + 1, y: event.posy };
		this.contextMenuService.showContextMenu({
			getAnchor: () => anchor,
563 564
			getActions: () => {
				return this.state.actionProvider.getSecondaryActions(tree, stat).then(actions => {
565 566
					fillInActions(this.contributedContextMenu, actions);
					return actions;
567 568
				});
			},
E
Erich Gamma 已提交
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
			getActionItem: this.state.actionProvider.getActionItem.bind(this.state.actionProvider, tree, stat),
			getKeyBinding: (a): Keybinding => keybindingForAction(a.id),
			getActionsContext: () => {
				return {
					viewletState: this.state,
					stat: stat
				};
			},
			onHide: (wasCancelled?: boolean) => {
				if (wasCancelled) {
					tree.DOMFocus();
				}
			}
		});

		return true;
	}

A
Cleanup  
Alex Dima 已提交
587
	private onEnterDown(tree: ITree, event: IKeyboardEvent): boolean {
E
Erich Gamma 已提交
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
		if (tree.getHighlight()) {
			return false;
		}

		let payload = { origin: 'keyboard' };

		let stat: FileStat = tree.getFocus();
		if (stat) {

			// Directory: Toggle expansion
			if (stat.isDirectory) {
				tree.toggleExpansion(stat);
			}

			// File: Open
			else {
				tree.setFocus(stat, payload);
				this.openEditor(stat, false, false);
			}
		}

		this.didCatchEnterDown = true;

		return true;
	}

A
Cleanup  
Alex Dima 已提交
614
	private onEnterUp(tree: ITree, event: IKeyboardEvent): boolean {
E
Erich Gamma 已提交
615 616 617 618 619 620 621 622 623 624 625 626 627 628
		if (!this.didCatchEnterDown || tree.getHighlight()) {
			return false;
		}

		let stat: FileStat = tree.getFocus();
		if (stat && !stat.isDirectory) {
			this.openEditor(stat, false, false);
		}

		this.didCatchEnterDown = false;

		return true;
	}

A
Cleanup  
Alex Dima 已提交
629
	private onModifierEnterUp(tree: ITree, event: IKeyboardEvent): boolean {
E
Erich Gamma 已提交
630 631 632 633 634 635 636 637 638 639 640 641 642 643
		if (tree.getHighlight()) {
			return false;
		}

		let stat: FileStat = tree.getFocus();
		if (stat && !stat.isDirectory) {
			this.openEditor(stat, false, true);
		}

		this.didCatchEnterDown = false;

		return true;
	}

A
Cleanup  
Alex Dima 已提交
644
	private onCopy(tree: ITree, event: IKeyboardEvent): boolean {
E
Erich Gamma 已提交
645 646 647 648 649 650 651 652 653 654
		let stat: FileStat = tree.getFocus();
		if (stat) {
			this.runAction(tree, stat, 'workbench.files.action.copyFile').done();

			return true;
		}

		return false;
	}

A
Cleanup  
Alex Dima 已提交
655
	private onPaste(tree: ITree, event: IKeyboardEvent): boolean {
E
Erich Gamma 已提交
656 657 658 659 660 661 662 663 664 665 666 667 668
		let stat: FileStat = tree.getFocus() || tree.getInput() /* root */;
		if (stat) {
			let pasteAction = this.instantiationService.createInstance(PasteFileAction, tree, stat);
			if (pasteAction._isEnabled()) {
				pasteAction.run().done(null, errors.onUnexpectedError);

				return true;
			}
		}

		return false;
	}

669
	private openEditor(stat: FileStat, preserveFocus: boolean, sideBySide: boolean, pinned = false): void {
E
Erich Gamma 已提交
670 671 672
		if (stat && !stat.isDirectory) {
			this.telemetryService.publicLog('workbenchActionExecuted', { id: 'workbench.files.openFile', from: 'explorer' });

673 674
			const editorInput = this.instantiationService.createInstance(FileEditorInput, stat.resource, stat.mime, void 0);
			this.editorService.openEditor(editorInput, { preserveFocus, pinned }, sideBySide).done(null, errors.onUnexpectedError);
E
Erich Gamma 已提交
675 676 677
		}
	}

A
Cleanup  
Alex Dima 已提交
678
	private onF2(tree: ITree, event: IKeyboardEvent): boolean {
E
Erich Gamma 已提交
679 680 681 682 683 684 685 686 687 688 689
		let stat: FileStat = tree.getFocus();

		if (stat) {
			this.runAction(tree, stat, 'workbench.files.action.triggerRename').done();

			return true;
		}

		return false;
	}

A
Cleanup  
Alex Dima 已提交
690
	private onDelete(tree: ITree, event: IKeyboardEvent): boolean {
E
Erich Gamma 已提交
691 692 693 694 695 696 697 698 699 700 701
		let useTrash = !event.shiftKey;
		let stat: FileStat = tree.getFocus();
		if (stat) {
			this.runAction(tree, stat, useTrash ? 'workbench.files.action.moveFileToTrash' : 'workbench.files.action.deleteFile').done();

			return true;
		}

		return false;
	}

702
	private runAction(tree: ITree, stat: FileStat, id: string): TPromise<any> {
E
Erich Gamma 已提交
703 704 705 706 707
		return this.state.actionProvider.runAction(tree, stat, id);
	}
}

// Explorer Sorter
B
Benjamin Pasero 已提交
708
export class FileSorter implements ISorter {
E
Erich Gamma 已提交
709

B
Benjamin Pasero 已提交
710
	public compare(tree: ITree, statA: FileStat, statB: FileStat): number {
E
Erich Gamma 已提交
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
		if (statA.isDirectory && !statB.isDirectory) {
			return -1;
		}

		if (statB.isDirectory && !statA.isDirectory) {
			return 1;
		}

		if (statA.isDirectory && statB.isDirectory) {
			return statA.name.toLowerCase().localeCompare(statB.name.toLowerCase());
		}

		if (statA instanceof NewStatPlaceholder) {
			return -1;
		}

		if (statB instanceof NewStatPlaceholder) {
			return 1;
		}

		return comparers.compareFileNames(statA.name, statB.name);
	}
}

// Explorer Filter
B
Benjamin Pasero 已提交
736
export class FileFilter implements IFilter {
737 738 739

	private static MAX_SIBLINGS_FILTER_THRESHOLD = 2000;

E
Erich Gamma 已提交
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
	private hiddenExpression: glob.IExpression;

	constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
		this.hiddenExpression = Object.create(null);
	}

	public updateConfiguration(configuration: IFilesConfiguration): boolean {
		let excludesConfig = (configuration && configuration.files && configuration.files.exclude) || Object.create(null);
		let needsRefresh = !objects.equals(this.hiddenExpression, excludesConfig);

		this.hiddenExpression = objects.clone(excludesConfig); // do not keep the config, as it gets mutated under our hoods

		return needsRefresh;
	}

B
Benjamin Pasero 已提交
755
	public isVisible(tree: ITree, stat: FileStat): boolean {
E
Erich Gamma 已提交
756 757 758 759 760 761 762 763
		return this.doIsVisible(stat);
	}

	private doIsVisible(stat: FileStat): boolean {
		if (stat instanceof NewStatPlaceholder) {
			return true; // always visible
		}

764 765 766 767 768 769
		// Workaround for O(N^2) complexity (https://github.com/Microsoft/vscode/issues/9962)
		let siblings = stat.parent && stat.parent.children && stat.parent.children;
		if (siblings && siblings.length > FileFilter.MAX_SIBLINGS_FILTER_THRESHOLD) {
			siblings = void 0;
		}

E
Erich Gamma 已提交
770
		// Hide those that match Hidden Patterns
771
		const siblingsFn = () => siblings && siblings.map(c => c.name);
772
		if (glob.match(this.hiddenExpression, this.contextService.toWorkspaceRelativePath(stat.resource), siblingsFn)) {
E
Erich Gamma 已提交
773 774 775 776 777 778 779 780
			return false; // hidden through pattern
		}

		return true;
	}
}

// Explorer Drag And Drop Controller
B
Benjamin Pasero 已提交
781
export class FileDragAndDrop implements IDragAndDrop {
782 783
	private toDispose: IDisposable[];
	private dropEnabled: boolean;
E
Erich Gamma 已提交
784 785 786 787 788 789 790

	constructor(
		@IMessageService private messageService: IMessageService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
		@IEventService private eventService: IEventService,
		@IProgressService private progressService: IProgressService,
		@IFileService private fileService: IFileService,
791
		@IConfigurationService private configurationService: IConfigurationService,
E
Erich Gamma 已提交
792 793 794
		@IInstantiationService private instantiationService: IInstantiationService,
		@ITextFileService private textFileService: ITextFileService
	) {
795 796 797 798 799 800 801 802 803 804 805 806 807
		this.toDispose = [];

		this.onConfigurationUpdated(configurationService.getConfiguration<IFilesConfiguration>());

		this.registerListeners();
	}

	private registerListeners(): void {
		this.toDispose.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config)));
	}

	private onConfigurationUpdated(config: IFilesConfiguration): void {
		this.dropEnabled = config && config.explorer && config.explorer.enableDragAndDrop;
E
Erich Gamma 已提交
808 809
	}

B
Benjamin Pasero 已提交
810
	public getDragURI(tree: ITree, stat: FileStat): string {
E
Erich Gamma 已提交
811 812 813
		return stat.resource && stat.resource.toString();
	}

B
Benjamin Pasero 已提交
814
	public onDragStart(tree: ITree, data: IDragAndDropData, originalEvent: DragMouseEvent): void {
E
Erich Gamma 已提交
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
		let sources: FileStat[] = data.getData();
		let source: FileStat = null;
		if (sources.length > 0) {
			source = sources[0];
		}

		// When dragging folders, make sure to collapse them to free up some space
		if (source && source.isDirectory && tree.isExpanded(source)) {
			tree.collapse(source, false);
		}

		// Native only: when a DownloadURL attribute is defined on the data transfer it is possible to
		// drag a file from the browser to the desktop and have it downloaded there.
		if (!(data instanceof DesktopDragAndDropData)) {
			if (source && !source.isDirectory) {
				originalEvent.dataTransfer.setData('DownloadURL', [MIME_BINARY, source.name, source.resource.toString()].join(':'));
			}
		}
	}

B
Benjamin Pasero 已提交
835
	public onDragOver(tree: ITree, data: IDragAndDropData, target: FileStat, originalEvent: DragMouseEvent): IDragOverReaction {
836 837 838 839
		if (!this.dropEnabled) {
			return DRAG_OVER_REJECT;
		}

E
Erich Gamma 已提交
840 841 842 843 844 845 846 847 848 849 850 851 852 853
		let isCopy = originalEvent && ((originalEvent.ctrlKey && !platform.isMacintosh) || (originalEvent.altKey && platform.isMacintosh));
		let fromDesktop = data instanceof DesktopDragAndDropData;

		// Desktop DND
		if (fromDesktop) {
			let dragData = (<DesktopDragAndDropData>data).getData();

			let types = dragData.types;
			let typesArray: string[] = [];
			for (let i = 0; i < types.length; i++) {
				typesArray.push(types[i]);
			}

			if (typesArray.length === 0 || !typesArray.some((type) => { return type === 'Files'; })) {
B
Benjamin Pasero 已提交
854
				return DRAG_OVER_REJECT;
E
Erich Gamma 已提交
855 856 857 858 859
			}
		}

		// Other-Tree DND
		else if (data instanceof ExternalElementsDragAndDropData) {
B
Benjamin Pasero 已提交
860
			return DRAG_OVER_REJECT;
E
Erich Gamma 已提交
861 862 863 864 865 866
		}

		// In-Explorer DND
		else {
			let sources: FileStat[] = data.getData();
			if (!Array.isArray(sources)) {
B
Benjamin Pasero 已提交
867
				return DRAG_OVER_REJECT;
E
Erich Gamma 已提交
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
			}

			if (sources.some((source) => {
				if (source instanceof NewStatPlaceholder) {
					return true; // NewStatPlaceholders can not be moved
				}

				if (source.resource.toString() === target.resource.toString()) {
					return true; // Can not move anything onto itself
				}

				if (!isCopy && paths.dirname(source.resource.fsPath) === target.resource.fsPath) {
					return true; // Can not move a file to the same parent unless we copy
				}

				if (paths.isEqualOrParent(target.resource.fsPath, source.resource.fsPath)) {
					return true; // Can not move a parent folder into one of its children
				}

				return false;
			})) {
B
Benjamin Pasero 已提交
889
				return DRAG_OVER_REJECT;
E
Erich Gamma 已提交
890 891 892 893 894
			}
		}

		// All
		if (target.isDirectory) {
B
Benjamin Pasero 已提交
895
			return fromDesktop || isCopy ? DRAG_OVER_ACCEPT_BUBBLE_DOWN_COPY : DRAG_OVER_ACCEPT_BUBBLE_DOWN;
E
Erich Gamma 已提交
896 897 898
		}

		if (target.resource.toString() !== this.contextService.getWorkspace().resource.toString()) {
B
Benjamin Pasero 已提交
899
			return fromDesktop || isCopy ? DRAG_OVER_ACCEPT_BUBBLE_UP_COPY : DRAG_OVER_ACCEPT_BUBBLE_UP;
E
Erich Gamma 已提交
900 901
		}

B
Benjamin Pasero 已提交
902
		return DRAG_OVER_REJECT;
E
Erich Gamma 已提交
903 904
	}

B
Benjamin Pasero 已提交
905
	public drop(tree: ITree, data: IDragAndDropData, target: FileStat, originalEvent: DragMouseEvent): void {
906
		let promise: TPromise<void> = TPromise.as(null);
E
Erich Gamma 已提交
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930

		// Desktop DND (Import file)
		if (data instanceof DesktopDragAndDropData) {
			let importAction = this.instantiationService.createInstance(ImportFileAction, tree, target, null);
			promise = importAction.run({
				input: {
					files: <FileList>(<DesktopDragAndDropData>data).getData().files
				}
			});
		}

		// In-Explorer DND (Move/Copy file)
		else {
			let source: FileStat = data.getData()[0];
			let isCopy = (originalEvent.ctrlKey && !platform.isMacintosh) || (originalEvent.altKey && platform.isMacintosh);

			promise = tree.expand(target).then(() => {

				// Reuse action if user copies
				if (isCopy) {
					let copyAction = this.instantiationService.createInstance(DuplicateFileAction, tree, source, target);
					return copyAction.run();
				}

931 932 933 934
				// Handle dirty (in file or inside the folder if any)
				let revertPromise: TPromise<any> = TPromise.as(null);
				const dirty = this.textFileService.getDirty().filter(d => paths.isEqualOrParent(d.fsPath, source.resource.fsPath));
				if (dirty.length) {
935
					let message: string;
936 937 938 939 940 941 942 943
					if (source.isDirectory) {
						if (dirty.length === 1) {
							message = nls.localize('dirtyMessageFolderOne', "You are moving a folder with unsaved changes in 1 file. Do you want to continue?");
						} else {
							message = nls.localize('dirtyMessageFolder', "You are moving a folder with unsaved changes in {0} files. Do you want to continue?", dirty.length);
						}
					} else {
						message = nls.localize('dirtyMessageFile', "You are moving a file with unsaved changes. Do you want to continue?");
E
Erich Gamma 已提交
944 945
					}

946 947 948 949 950 951
					const res = this.messageService.confirm({
						message,
						type: 'warning',
						detail: nls.localize('dirtyWarning', "Your changes will be lost if you don't save them."),
						primaryButton: nls.localize({ key: 'moveLabel', comment: ['&& denotes a mnemonic'] }, "&&Move")
					});
E
Erich Gamma 已提交
952

953
					if (!res) {
A
Alex Dima 已提交
954
						return TPromise.as(null);
E
Erich Gamma 已提交
955 956
					}

957 958 959 960
					revertPromise = this.textFileService.revertAll(dirty);
				}

				return revertPromise.then(() => {
E
Erich Gamma 已提交
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
					let targetResource = URI.file(paths.join(target.resource.fsPath, source.name));
					let didHandleConflict = false;

					let onMove = (result: IFileStat) => {
						this.eventService.emit('files.internal:fileChanged', new LocalFileChangeEvent(source.clone(), result));
					};

					// Move File/Folder and emit event
					return this.fileService.moveFile(source.resource, targetResource).then(onMove, (error) => {

						// Conflict
						if ((<IFileOperationResult>error).fileOperationResult === FileOperationResult.FILE_MOVE_CONFLICT) {
							didHandleConflict = true;

							let confirm: IConfirmation = {
								message: nls.localize('confirmOverwriteMessage', "'{0}' already exists in the destination folder. Do you want to replace it?", source.name),
								detail: nls.localize('irreversible', "This action is irreversible!"),
B
Benjamin Pasero 已提交
978
								primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace")
E
Erich Gamma 已提交
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
							};

							if (this.messageService.confirm(confirm)) {
								return this.fileService.moveFile(source.resource, targetResource, true).then((result) => {
									let fakeTargetState = new FileStat(targetResource);
									this.eventService.emit('files.internal:fileChanged', new LocalFileChangeEvent(fakeTargetState, null));

									onMove(result);
								}, (error) => {
									this.messageService.show(Severity.Error, error);
								});
							}

							return;
						}

						this.messageService.show(Severity.Error, error);
					});
				});
			}, errors.onUnexpectedError);
		}

		this.progressService.showWhile(promise, 800);

		promise.done(null, errors.onUnexpectedError);
	}
}