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

J
João Moreno 已提交
6
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
7 8
import * as DOM from 'vs/base/browser/dom';
import * as glob from 'vs/base/common/glob';
I
isidor 已提交
9
import { IListVirtualDelegate, ListDragOverEffect } from 'vs/base/browser/ui/list/list';
10
import { IProgressService, ProgressLocation, IProgressStep, IProgress } from 'vs/platform/progress/common/progress';
I
isidor 已提交
11
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
12
import { IFileService, FileKind, FileOperationError, FileOperationResult, FileSystemProviderCapabilities, BinarySize } from 'vs/platform/files/common/files';
13
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
I
isidor 已提交
14
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
J
Joao Moreno 已提交
15
import { IDisposable, Disposable, dispose, toDisposable, DisposableStore } from 'vs/base/common/lifecycle';
16
import { KeyCode } from 'vs/base/common/keyCodes';
I
isidor 已提交
17
import { IFileLabelOptions, IResourceLabel, ResourceLabels } from 'vs/workbench/browser/labels';
J
Joao Moreno 已提交
18
import { ITreeNode, ITreeFilter, TreeVisibility, TreeFilterResult, IAsyncDataSource, ITreeSorter, ITreeDragAndDrop, ITreeDragOverReaction, TreeDragOverBubble } from 'vs/base/browser/ui/tree/tree';
I
isidor 已提交
19
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
B
Benjamin Pasero 已提交
20
import { IThemeService } from 'vs/platform/theme/common/themeService';
I
isidor 已提交
21
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
22
import { IFilesConfiguration, IExplorerService, VIEW_ID } from 'vs/workbench/contrib/files/common/files';
23
import { dirname, joinPath, isEqualOrParent, basename, distinctParents } from 'vs/base/common/resources';
I
isidor 已提交
24 25 26 27 28 29
import { InputBox, MessageType } from 'vs/base/browser/ui/inputbox/inputBox';
import { localize } from 'vs/nls';
import { attachInputBoxStyler } from 'vs/platform/theme/common/styler';
import { once } from 'vs/base/common/functional';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { equals, deepClone } from 'vs/base/common/objects';
30
import * as path from 'vs/base/common/path';
J
Joao Moreno 已提交
31
import { ExplorerItem, NewExplorerItem } from 'vs/workbench/contrib/files/common/explorerModel';
32
import { compareFileExtensionsNumeric, compareFileNamesNumeric } from 'vs/base/common/comparers';
33
import { fillResourceDataTransfers, CodeDataTransfers, extractResources, containsDragType } from 'vs/workbench/browser/dnd';
I
isidor 已提交
34 35 36
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IDragAndDropData, DataTransfers } from 'vs/base/browser/dnd';
import { Schemas } from 'vs/base/common/network';
I
isidor 已提交
37
import { DesktopDragAndDropData, ExternalElementsDragAndDropData, ElementsDragAndDropData } from 'vs/base/browser/ui/list/listView';
I
isidor 已提交
38
import { isMacintosh, isWeb } from 'vs/base/common/platform';
39
import { IDialogService, IConfirmation, getFileNamesMessage } from 'vs/platform/dialogs/common/dialogs';
40
import { IWorkingCopyFileService } from 'vs/workbench/services/workingCopy/common/workingCopyFileService';
41
import { IHostService } from 'vs/workbench/services/host/browser/host';
B
Benjamin Pasero 已提交
42
import { IWorkspaceEditingService } from 'vs/workbench/services/workspaces/common/workspaceEditing';
I
isidor 已提交
43 44 45 46
import { URI } from 'vs/base/common/uri';
import { ITask, sequence } from 'vs/base/common/async';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IWorkspaceFolderCreationData } from 'vs/platform/workspaces/common/workspaces';
47
import { findValidPasteFileTarget } from 'vs/workbench/contrib/files/browser/fileActions';
48
import { FuzzyScore, createMatches } from 'vs/base/common/filters';
J
Joao Moreno 已提交
49
import { Emitter, Event, EventMultiplexer } from 'vs/base/common/event';
J
Joao Moreno 已提交
50 51 52
import { ITreeCompressionDelegate } from 'vs/base/browser/ui/tree/asyncDataTree';
import { ICompressibleTreeRenderer } from 'vs/base/browser/ui/tree/objectTree';
import { ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel';
53
import { VSBuffer, newWriteableBufferStream } from 'vs/base/common/buffer';
54
import { ILabelService } from 'vs/platform/label/common/label';
J
Joao Moreno 已提交
55
import { isNumber } from 'vs/base/common/types';
56
import { domEvent } from 'vs/base/browser/event';
57
import { IEditableData } from 'vs/workbench/common/views';
58
import { IEditorInput } from 'vs/workbench/common/editor';
59
import { CancellationTokenSource, CancellationToken } from 'vs/base/common/cancellation';
I
isidor 已提交
60 61 62

export class ExplorerDelegate implements IListVirtualDelegate<ExplorerItem> {

I
isidor 已提交
63
	static readonly ITEM_HEIGHT = 22;
I
isidor 已提交
64 65 66 67 68 69 70 71 72 73

	getHeight(element: ExplorerItem): number {
		return ExplorerDelegate.ITEM_HEIGHT;
	}

	getTemplateId(element: ExplorerItem): string {
		return FilesRenderer.ID;
	}
}

I
isidor 已提交
74
export const explorerRootErrorEmitter = new Emitter<URI>();
75
export class ExplorerDataSource implements IAsyncDataSource<ExplorerItem | ExplorerItem[], ExplorerItem> {
E
Erich Gamma 已提交
76 77

	constructor(
78
		@IProgressService private readonly progressService: IProgressService,
79 80 81
		@INotificationService private readonly notificationService: INotificationService,
		@IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService,
		@IFileService private readonly fileService: IFileService,
82 83
		@IExplorerService private readonly explorerService: IExplorerService,
		@IWorkspaceContextService private readonly contextService: IWorkspaceContextService
84
	) { }
E
Erich Gamma 已提交
85

86 87
	hasChildren(element: ExplorerItem | ExplorerItem[]): boolean {
		return Array.isArray(element) || element.isDirectory;
E
Erich Gamma 已提交
88 89
	}

90 91 92
	getChildren(element: ExplorerItem | ExplorerItem[]): Promise<ExplorerItem[]> {
		if (Array.isArray(element)) {
			return Promise.resolve(element);
93
		}
E
Erich Gamma 已提交
94

95 96
		const sortOrder = this.explorerService.sortOrder;
		const promise = element.fetchChildren(sortOrder).then(undefined, e => {
97 98 99 100

			if (element instanceof ExplorerItem && element.isRoot) {
				if (this.contextService.getWorkbenchState() === WorkbenchState.FOLDER) {
					// Single folder create a dummy explorer item to show error
101
					const placeholder = new ExplorerItem(element.resource, this.fileService, undefined, false);
102 103
					placeholder.isError = true;
					return [placeholder];
I
isidor 已提交
104 105
				} else {
					explorerRootErrorEmitter.fire(element.resource);
106 107 108
				}
			} else {
				// Do not show error for roots since we already use an explorer decoration to notify user
109 110
				this.notificationService.error(e);
			}
E
Erich Gamma 已提交
111

112 113
			return []; // we could not resolve any children because of an error
		});
E
Erich Gamma 已提交
114

115 116 117 118 119
		this.progressService.withProgress({
			location: ProgressLocation.Explorer,
			delay: this.layoutService.isRestored() ? 800 : 1200 // less ugly initial startup
		}, _progress => promise);

120
		return promise;
E
Erich Gamma 已提交
121
	}
I
isidor 已提交
122
}
E
Erich Gamma 已提交
123

124 125
export interface ICompressedNavigationController {
	readonly current: ExplorerItem;
J
Joao Moreno 已提交
126
	readonly currentId: string;
127
	readonly items: ExplorerItem[];
128
	readonly labels: HTMLElement[];
129 130
	readonly index: number;
	readonly count: number;
J
Joao Moreno 已提交
131
	readonly onDidChange: Event<void>;
132 133
	previous(): void;
	next(): void;
134 135
	first(): void;
	last(): void;
J
Joao Moreno 已提交
136
	setIndex(index: number): void;
137 138
}

J
Joao Moreno 已提交
139 140 141
export class CompressedNavigationController implements ICompressedNavigationController, IDisposable {

	static ID = 0;
142 143

	private _index: number;
J
jeanp413 已提交
144 145
	private _labels!: HTMLElement[];
	private _updateLabelDisposable: IDisposable;
146 147 148 149

	get index(): number { return this._index; }
	get count(): number { return this.items.length; }
	get current(): ExplorerItem { return this.items[this._index]!; }
J
Joao Moreno 已提交
150
	get currentId(): string { return `${this.id}_${this.index}`; }
J
jeanp413 已提交
151
	get labels(): HTMLElement[] { return this._labels; }
J
Joao Moreno 已提交
152 153 154

	private _onDidChange = new Emitter<void>();
	readonly onDidChange = this._onDidChange.event;
155

J
Joao Moreno 已提交
156
	constructor(private id: string, readonly items: ExplorerItem[], templateData: IFileTemplateData) {
157
		this._index = items.length - 1;
J
Joao Moreno 已提交
158

J
jeanp413 已提交
159 160 161 162 163 164 165
		this.updateLabels(templateData);
		this._updateLabelDisposable = templateData.label.onDidRender(() => this.updateLabels(templateData));
	}

	private updateLabels(templateData: IFileTemplateData): void {
		this._labels = Array.from(templateData.container.querySelectorAll('.label-name')) as HTMLElement[];

I
isidor 已提交
166
		for (let i = 0; i < this.labels.length; i++) {
J
jeanp413 已提交
167
			this.labels[i].setAttribute('aria-label', this.items[i].name);
J
Joao Moreno 已提交
168 169
		}

I
isidor 已提交
170 171 172
		if (this._index < this.labels.length) {
			DOM.addClass(this.labels[this._index], 'active');
		}
173 174 175 176 177 178 179
	}

	previous(): void {
		if (this._index <= 0) {
			return;
		}

J
Joao Moreno 已提交
180
		this.setIndex(this._index - 1);
181 182 183 184 185 186 187
	}

	next(): void {
		if (this._index >= this.items.length - 1) {
			return;
		}

J
Joao Moreno 已提交
188
		this.setIndex(this._index + 1);
189
	}
190 191 192 193 194 195

	first(): void {
		if (this._index === 0) {
			return;
		}

J
Joao Moreno 已提交
196
		this.setIndex(0);
197 198 199 200 201 202 203
	}

	last(): void {
		if (this._index === this.items.length - 1) {
			return;
		}

J
Joao Moreno 已提交
204 205 206
		this.setIndex(this.items.length - 1);
	}

J
Joao Moreno 已提交
207 208 209 210 211
	setIndex(index: number): void {
		if (index < 0 || index >= this.items.length) {
			return;
		}

212
		DOM.removeClass(this.labels[this._index], 'active');
J
Joao Moreno 已提交
213
		this._index = index;
214
		DOM.addClass(this.labels[this._index], 'active');
J
Joao Moreno 已提交
215 216 217 218 219 220

		this._onDidChange.fire();
	}

	dispose(): void {
		this._onDidChange.dispose();
J
jeanp413 已提交
221
		this._updateLabelDisposable.dispose();
222
	}
223 224
}

I
isidor 已提交
225 226
export interface IFileTemplateData {
	elementDisposable: IDisposable;
B
Benjamin Pasero 已提交
227
	label: IResourceLabel;
I
isidor 已提交
228
	container: HTMLElement;
E
Erich Gamma 已提交
229 230
}

J
João Moreno 已提交
231
export class FilesRenderer implements ICompressibleTreeRenderer<ExplorerItem, FuzzyScore, IFileTemplateData>, IListAccessibilityProvider<ExplorerItem>, IDisposable {
I
isidor 已提交
232
	static readonly ID = 'file';
233

234 235
	private config: IFilesConfiguration;
	private configListener: IDisposable;
236
	private compressedNavigationControllers = new Map<ExplorerItem, CompressedNavigationController>();
E
Erich Gamma 已提交
237

J
Joao Moreno 已提交
238 239 240
	private _onDidChangeActiveDescendant = new EventMultiplexer<void>();
	readonly onDidChangeActiveDescendant = this._onDidChangeActiveDescendant.event;

E
Erich Gamma 已提交
241
	constructor(
B
Benjamin Pasero 已提交
242
		private labels: ResourceLabels,
J
Joao Moreno 已提交
243
		private updateWidth: (stat: ExplorerItem) => void,
244 245 246
		@IContextViewService private readonly contextViewService: IContextViewService,
		@IThemeService private readonly themeService: IThemeService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
247 248
		@IExplorerService private readonly explorerService: IExplorerService,
		@ILabelService private readonly labelService: ILabelService
E
Erich Gamma 已提交
249
	) {
250
		this.config = this.configurationService.getValue<IFilesConfiguration>();
251 252
		this.configListener = this.configurationService.onDidChangeConfiguration(e => {
			if (e.affectsConfiguration('explorer')) {
253
				this.config = this.configurationService.getValue();
254 255 256 257
			}
		});
	}

258 259 260 261
	getWidgetAriaLabel(): string {
		return localize('treeAriaLabel', "Files Explorer");
	}

I
isidor 已提交
262 263
	get templateId(): string {
		return FilesRenderer.ID;
264
	}
265

I
isidor 已提交
266
	renderTemplate(container: HTMLElement): IFileTemplateData {
J
Joao Moreno 已提交
267
		const elementDisposable = Disposable.None;
268
		const label = this.labels.create(container, { supportHighlights: true });
E
Erich Gamma 已提交
269

270
		return { elementDisposable, label, container };
271 272
	}

273
	renderElement(node: ITreeNode<ExplorerItem, FuzzyScore>, index: number, templateData: IFileTemplateData): void {
274
		templateData.elementDisposable.dispose();
275
		const stat = node.element;
276
		const editableData = this.explorerService.getEditableData(stat);
B
Benjamin Pasero 已提交
277

J
Joao Moreno 已提交
278 279
		DOM.removeClass(templateData.label.element, 'compressed');

280 281
		// File Label
		if (!editableData) {
282
			templateData.label.element.style.display = 'flex';
J
Joao Moreno 已提交
283
			templateData.elementDisposable = this.renderStat(stat, stat.name, undefined, node.filterData, templateData);
284
		}
285

286 287 288
		// Input Box
		else {
			templateData.label.element.style.display = 'none';
289
			templateData.elementDisposable = this.renderInputBox(templateData.container, stat, editableData);
290
		}
291 292
	}

J
Joao Moreno 已提交
293
	renderCompressedElements(node: ITreeNode<ICompressedTreeNode<ExplorerItem>, FuzzyScore>, index: number, templateData: IFileTemplateData, height: number | undefined): void {
J
Joao Moreno 已提交
294 295 296
		templateData.elementDisposable.dispose();

		const stat = node.element.elements[node.element.elements.length - 1];
I
isidor 已提交
297 298
		const editable = node.element.elements.filter(e => this.explorerService.isEditable(e));
		const editableData = editable.length === 0 ? undefined : this.explorerService.getEditableData(editable[0]);
J
Joao Moreno 已提交
299 300 301

		// File Label
		if (!editableData) {
J
Joao Moreno 已提交
302
			DOM.addClass(templateData.label.element, 'compressed');
J
Joao Moreno 已提交
303
			templateData.label.element.style.display = 'flex';
J
Joao Moreno 已提交
304 305

			const disposables = new DisposableStore();
J
Joao Moreno 已提交
306 307
			const id = `compressed-explorer_${CompressedNavigationController.ID++}`;

I
isidor 已提交
308
			const label = node.element.elements.map(e => e.name);
J
Joao Moreno 已提交
309
			disposables.add(this.renderStat(stat, label, id, node.filterData, templateData));
J
Joao Moreno 已提交
310

J
Joao Moreno 已提交
311 312
			const compressedNavigationController = new CompressedNavigationController(id, node.element.elements, templateData);
			disposables.add(compressedNavigationController);
313
			this.compressedNavigationControllers.set(stat, compressedNavigationController);
314

J
Joao Moreno 已提交
315 316 317
			// accessibility
			disposables.add(this._onDidChangeActiveDescendant.add(compressedNavigationController.onDidChange));

318 319 320 321 322 323 324 325
			domEvent(templateData.container, 'mousedown')(e => {
				const result = getIconLabelNameFromHTMLElement(e.target);

				if (result) {
					compressedNavigationController.setIndex(result.index);
				}
			}, undefined, disposables);

J
Joao Moreno 已提交
326
			disposables.add(toDisposable(() => this.compressedNavigationControllers.delete(stat)));
327

J
Joao Moreno 已提交
328
			templateData.elementDisposable = disposables;
J
Joao Moreno 已提交
329
		}
J
Joao Moreno 已提交
330

J
Joao Moreno 已提交
331 332
		// Input Box
		else {
J
Joao Moreno 已提交
333
			DOM.removeClass(templateData.label.element, 'compressed');
J
Joao Moreno 已提交
334
			templateData.label.element.style.display = 'none';
I
isidor 已提交
335
			templateData.elementDisposable = this.renderInputBox(templateData.container, editable[0], editableData);
J
Joao Moreno 已提交
336
		}
J
Joao Moreno 已提交
337 338
	}

J
Joao Moreno 已提交
339
	private renderStat(stat: ExplorerItem, label: string | string[], domId: string | undefined, filterData: FuzzyScore | undefined, templateData: IFileTemplateData): IDisposable {
J
Joao Moreno 已提交
340 341 342 343 344 345 346 347 348 349
		templateData.label.element.style.display = 'flex';
		const extraClasses = ['explorer-item'];
		if (this.explorerService.isCut(stat)) {
			extraClasses.push('cut');
		}

		templateData.label.setResource({ resource: stat.resource, name: label }, {
			fileKind: stat.isRoot ? FileKind.ROOT_FOLDER : stat.isDirectory ? FileKind.FOLDER : FileKind.FILE,
			extraClasses,
			fileDecorations: this.config.explorer.decorations,
350
			matches: createMatches(filterData),
J
Joao Moreno 已提交
351 352
			separator: this.labelService.getSeparator(stat.resource.scheme, stat.resource.authority),
			domId
J
Joao Moreno 已提交
353 354 355 356 357 358 359 360 361 362 363
		});

		return templateData.label.onDidRender(() => {
			try {
				this.updateWidth(stat);
			} catch (e) {
				// noop since the element might no longer be in the tree, no update of width necessery
			}
		});
	}

364
	private renderInputBox(container: HTMLElement, stat: ExplorerItem, editableData: IEditableData): IDisposable {
B
Benjamin Pasero 已提交
365

366
		// Use a file label only for the icon next to the input box
B
Benjamin Pasero 已提交
367
		const label = this.labels.create(container);
368
		const extraClasses = ['explorer-item', 'explorer-item-edited'];
I
isidor 已提交
369
		const fileKind = stat.isRoot ? FileKind.ROOT_FOLDER : stat.isDirectory ? FileKind.FOLDER : FileKind.FILE;
370
		const labelOptions: IFileLabelOptions = { hidePath: true, hideLabel: true, fileKind, extraClasses };
371

I
isidor 已提交
372
		const parent = stat.name ? dirname(stat.resource) : stat.resource;
373 374
		const value = stat.name || '';

I
isidor 已提交
375
		label.setFile(joinPath(parent, value || ' '), labelOptions); // Use icon for ' ' if name is empty.
376

J
Joao Moreno 已提交
377 378 379
		// hack: hide label
		(label.element.firstElementChild as HTMLElement).style.display = 'none';

380
		// Input field for name
381
		const inputBox = new InputBox(label.element, this.contextViewService, {
J
Joao Moreno 已提交
382
			validationOptions: {
383
				validation: (value) => {
384 385
					const message = editableData.validationMessage(value);
					if (!message || message.severity !== Severity.Error) {
386 387 388 389
						return null;
					}

					return {
390
						content: message.content,
391 392 393 394
						formatContent: true,
						type: MessageType.ERROR
					};
				}
395
			},
I
isidor 已提交
396
			ariaLabel: localize('fileInputAriaLabel', "Type file name. Press Enter to confirm or Escape to cancel.")
J
Joao Moreno 已提交
397
		});
B
Benjamin Pasero 已提交
398
		const styler = attachInputBoxStyler(inputBox, this.themeService);
E
Erich Gamma 已提交
399

400
		const lastDot = value.lastIndexOf('.');
E
Erich Gamma 已提交
401

J
Joao Moreno 已提交
402
		inputBox.value = value;
I
isidor 已提交
403 404
		inputBox.focus();
		inputBox.select({ start: 0, end: lastDot > 0 && !stat.isDirectory ? lastDot : value.length });
E
Erich Gamma 已提交
405

J
jeanp413 已提交
406
		const done = once((success: boolean, finishEditing: boolean) => {
T
Till Salinger 已提交
407
			label.element.style.display = 'none';
408
			const value = inputBox.value;
I
isidor 已提交
409
			dispose(toDispose);
O
orange4glace 已提交
410
			label.element.remove();
J
jeanp413 已提交
411 412 413
			if (finishEditing) {
				editableData.onFinish(value, success);
			}
J
Joao Moreno 已提交
414
		});
E
Erich Gamma 已提交
415

J
jeanp413 已提交
416
		const showInputBoxNotification = () => {
417 418
			if (inputBox.isInputValid()) {
				const message = editableData.validationMessage(inputBox.value);
J
jeanp413 已提交
419 420 421 422 423 424 425 426 427 428 429 430 431
				if (message) {
					inputBox.showMessage({
						content: message.content,
						formatContent: true,
						type: message.severity === Severity.Info ? MessageType.INFO : message.severity === Severity.Warning ? MessageType.WARNING : MessageType.ERROR
					});
				} else {
					inputBox.hideMessage();
				}
			}
		};
		showInputBoxNotification();

B
Benjamin Pasero 已提交
432
		const toDispose = [
J
Joao Moreno 已提交
433
			inputBox,
J
jeanp413 已提交
434 435 436
			inputBox.onDidChange(value => {
				label.setFile(joinPath(parent, value || ' '), labelOptions); // update label icon while typing!
			}),
A
Cleanup  
Alex Dima 已提交
437
			DOM.addStandardDisposableListener(inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: IKeyboardEvent) => {
A
Alexandru Dima 已提交
438
				if (e.equals(KeyCode.Enter)) {
J
Joao Moreno 已提交
439
					if (inputBox.validate()) {
J
jeanp413 已提交
440
						done(true, true);
J
Joao Moreno 已提交
441
					}
A
Alexandru Dima 已提交
442
				} else if (e.equals(KeyCode.Escape)) {
J
jeanp413 已提交
443
					done(false, true);
J
Joao Moreno 已提交
444 445
				}
			}),
J
jeanp413 已提交
446 447 448
			DOM.addStandardDisposableListener(inputBox.inputElement, DOM.EventType.KEY_UP, (e: IKeyboardEvent) => {
				showInputBoxNotification();
			}),
449 450 451
			DOM.addDisposableListener(inputBox.inputElement, DOM.EventType.BLUR, () => {
				done(inputBox.isInputValid(), true);
			}),
B
Benjamin Pasero 已提交
452 453
			label,
			styler
J
Joao Moreno 已提交
454
		];
455

I
isidor 已提交
456
		return toDisposable(() => {
J
jeanp413 已提交
457
			done(false, false);
I
isidor 已提交
458
		});
E
Erich Gamma 已提交
459 460
	}

461
	disposeElement(element: ITreeNode<ExplorerItem, FuzzyScore>, index: number, templateData: IFileTemplateData): void {
462
		templateData.elementDisposable.dispose();
E
Erich Gamma 已提交
463 464
	}

465
	disposeCompressedElements(node: ITreeNode<ICompressedTreeNode<ExplorerItem>, FuzzyScore>, index: number, templateData: IFileTemplateData): void {
466
		templateData.elementDisposable.dispose();
E
Erich Gamma 已提交
467 468
	}

I
isidor 已提交
469 470 471
	disposeTemplate(templateData: IFileTemplateData): void {
		templateData.elementDisposable.dispose();
		templateData.label.dispose();
E
Erich Gamma 已提交
472
	}
I
isidor 已提交
473

474 475 476 477
	getCompressedNavigationController(stat: ExplorerItem): ICompressedNavigationController | undefined {
		return this.compressedNavigationControllers.get(stat);
	}

J
Joao Moreno 已提交
478
	// IAccessibilityProvider
E
Erich Gamma 已提交
479

I
isidor 已提交
480 481
	getAriaLabel(element: ExplorerItem): string {
		return element.name;
B
Benjamin Pasero 已提交
482
	}
J
Joao Moreno 已提交
483 484 485 486 487 488 489 490 491

	getActiveDescendantId(stat: ExplorerItem): string | undefined {
		const compressedNavigationController = this.compressedNavigationControllers.get(stat);
		return compressedNavigationController?.currentId;
	}

	dispose(): void {
		this.configListener.dispose();
	}
E
Erich Gamma 已提交
492 493
}

494 495 496 497 498
interface CachedParsedExpression {
	original: glob.IExpression;
	parsed: glob.ParsedExpression;
}

499 500 501 502
/**
 * Respectes files.exclude setting in filtering out content from the explorer.
 * Makes sure that visible editors are always shown in the explorer even if they are filtered out by settings.
 */
503
export class FilesFilter implements ITreeFilter<ExplorerItem, FuzzyScore> {
504
	private hiddenExpressionPerRoot: Map<string, CachedParsedExpression>;
505 506 507 508
	private hiddenUris = new Set<URI>();
	private editorsAffectingFilter = new Set<IEditorInput>();
	private _onDidChange = new Emitter<void>();
	private toDispose: IDisposable[] = [];
E
Erich Gamma 已提交
509

I
isidor 已提交
510
	constructor(
I
isidor 已提交
511 512
		@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
513 514
		@IExplorerService private readonly explorerService: IExplorerService,
		@IEditorService private readonly editorService: IEditorService,
I
isidor 已提交
515
	) {
516
		this.hiddenExpressionPerRoot = new Map<string, CachedParsedExpression>();
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
		this.toDispose.push(this.contextService.onDidChangeWorkspaceFolders(() => this.updateConfiguration()));
		this.toDispose.push(this.configurationService.onDidChangeConfiguration((e) => {
			if (e.affectsConfiguration('files.exclude')) {
				this.updateConfiguration();
			}
		}));
		this.toDispose.push(this.editorService.onDidVisibleEditorsChange(() => {
			const editors = this.editorService.visibleEditors;
			let shouldFire = false;
			this.hiddenUris.forEach(u => {
				editors.forEach(e => {
					if (e.resource && isEqualOrParent(e.resource, u)) {
						// A filtered resource suddenly became visible since user opened an editor
						shouldFire = true;
					}
				});
			});

			this.editorsAffectingFilter.forEach(e => {
				if (editors.indexOf(e) === -1) {
					// Editor that was affecting filtering is no longer visible
					shouldFire = true;
				}
			});
			if (shouldFire) {
				this.editorsAffectingFilter.clear();
				this.hiddenUris.clear();
				this._onDidChange.fire();
			}
		}));
		this.updateConfiguration();
	}

	get onDidChange(): Event<void> {
		return this._onDidChange.event;
E
Erich Gamma 已提交
552 553
	}

554 555
	private updateConfiguration(): void {
		let shouldFire = false;
S
Sandeep Somavarapu 已提交
556
		this.contextService.getWorkspace().folders.forEach(folder => {
557
			const configuration = this.configurationService.getValue<IFilesConfiguration>({ resource: folder.uri });
B
Benjamin Pasero 已提交
558
			const excludesConfig: glob.IExpression = configuration?.files?.exclude || Object.create(null);
559

560
			if (!shouldFire) {
561
				const cached = this.hiddenExpressionPerRoot.get(folder.uri.toString());
562
				shouldFire = !cached || !equals(cached.original, excludesConfig);
563 564
			}

I
isidor 已提交
565
			const excludesConfigCopy = deepClone(excludesConfig); // do not keep the config, as it gets mutated under our hoods
566

567
			this.hiddenExpressionPerRoot.set(folder.uri.toString(), { original: excludesConfigCopy, parsed: glob.parse(excludesConfigCopy) });
I
isidor 已提交
568
		});
E
Erich Gamma 已提交
569

570 571 572 573 574
		if (shouldFire) {
			this.editorsAffectingFilter.clear();
			this.hiddenUris.clear();
			this._onDidChange.fire();
		}
E
Erich Gamma 已提交
575 576
	}

577
	filter(stat: ExplorerItem, parentVisibility: TreeVisibility): TreeFilterResult<FuzzyScore> {
578 579 580 581 582 583 584 585 586 587 588
		const isVisible = this.isVisible(stat, parentVisibility);
		if (isVisible) {
			this.hiddenUris.delete(stat.resource);
		} else {
			this.hiddenUris.add(stat.resource);
		}

		return isVisible;
	}

	private isVisible(stat: ExplorerItem, parentVisibility: TreeVisibility): boolean {
589
		stat.isExcluded = false;
I
isidor 已提交
590
		if (parentVisibility === TreeVisibility.Hidden) {
591
			stat.isExcluded = true;
I
isidor 已提交
592 593
			return false;
		}
I
isidor 已提交
594
		if (this.explorerService.getEditableData(stat) || stat.isRoot) {
E
Erich Gamma 已提交
595 596 597 598
			return true; // always visible
		}

		// Hide those that match Hidden Patterns
599
		const cached = this.hiddenExpressionPerRoot.get(stat.root.resource.toString());
I
isidor 已提交
600
		if ((cached && cached.parsed(path.relative(stat.root.resource.path, stat.resource.path), stat.name, name => !!(stat.parent && stat.parent.getChild(name)))) || stat.parent?.isExcluded) {
601
			stat.isExcluded = true;
602
			const editors = this.editorService.visibleEditors;
I
isidor 已提交
603
			const editor = editors.find(e => e.resource && isEqualOrParent(e.resource, stat.resource));
604 605 606 607 608
			if (editor) {
				this.editorsAffectingFilter.add(editor);
				return true; // Show all opened files and their parents
			}

E
Erich Gamma 已提交
609 610 611 612 613
			return false; // hidden through pattern
		}

		return true;
	}
B
Benjamin Pasero 已提交
614

615 616
	dispose(): void {
		dispose(this.toDispose);
B
Benjamin Pasero 已提交
617
	}
E
Erich Gamma 已提交
618 619
}

620
// Explorer Sorter
I
isidor 已提交
621
export class FileSorter implements ITreeSorter<ExplorerItem> {
I
isidor 已提交
622

I
isidor 已提交
623
	constructor(
I
isidor 已提交
624
		@IExplorerService private readonly explorerService: IExplorerService,
625
		@IWorkspaceContextService private readonly contextService: IWorkspaceContextService
I
isidor 已提交
626
	) { }
I
isidor 已提交
627

628
	compare(statA: ExplorerItem, statB: ExplorerItem): number {
I
isidor 已提交
629 630 631
		// Do not sort roots
		if (statA.isRoot) {
			if (statB.isRoot) {
I
isidor 已提交
632 633 634
				const workspaceA = this.contextService.getWorkspaceFolder(statA.resource);
				const workspaceB = this.contextService.getWorkspaceFolder(statB.resource);
				return workspaceA && workspaceB ? (workspaceA.index - workspaceB.index) : -1;
I
isidor 已提交
635
			}
I
isidor 已提交
636

I
isidor 已提交
637 638
			return -1;
		}
I
isidor 已提交
639

I
isidor 已提交
640 641 642
		if (statB.isRoot) {
			return 1;
		}
I
isidor 已提交
643

I
isidor 已提交
644
		const sortOrder = this.explorerService.sortOrder;
I
isidor 已提交
645

I
isidor 已提交
646 647 648 649 650 651
		// Sort Directories
		switch (sortOrder) {
			case 'type':
				if (statA.isDirectory && !statB.isDirectory) {
					return -1;
				}
I
isidor 已提交
652

I
isidor 已提交
653 654 655
				if (statB.isDirectory && !statA.isDirectory) {
					return 1;
				}
I
isidor 已提交
656

I
isidor 已提交
657
				if (statA.isDirectory && statB.isDirectory) {
658
					return compareFileNamesNumeric(statA.name, statB.name);
I
isidor 已提交
659
				}
I
isidor 已提交
660

I
isidor 已提交
661
				break;
I
isidor 已提交
662

I
isidor 已提交
663 664 665 666
			case 'filesFirst':
				if (statA.isDirectory && !statB.isDirectory) {
					return 1;
				}
I
isidor 已提交
667

I
isidor 已提交
668 669 670
				if (statB.isDirectory && !statA.isDirectory) {
					return -1;
				}
I
isidor 已提交
671

I
isidor 已提交
672
				break;
I
isidor 已提交
673

I
isidor 已提交
674 675
			case 'mixed':
				break; // not sorting when "mixed" is on
I
isidor 已提交
676

I
isidor 已提交
677 678 679 680
			default: /* 'default', 'modified' */
				if (statA.isDirectory && !statB.isDirectory) {
					return -1;
				}
I
isidor 已提交
681

I
isidor 已提交
682 683 684
				if (statB.isDirectory && !statA.isDirectory) {
					return 1;
				}
I
isidor 已提交
685

I
isidor 已提交
686 687
				break;
		}
I
isidor 已提交
688

I
isidor 已提交
689 690 691
		// Sort Files
		switch (sortOrder) {
			case 'type':
692
				return compareFileExtensionsNumeric(statA.name, statB.name);
I
isidor 已提交
693

I
isidor 已提交
694 695
			case 'modified':
				if (statA.mtime !== statB.mtime) {
I
isidor 已提交
696
					return (statA.mtime && statB.mtime && statA.mtime < statB.mtime) ? 1 : -1;
I
isidor 已提交
697
				}
I
isidor 已提交
698

699
				return compareFileNamesNumeric(statA.name, statB.name);
I
isidor 已提交
700

I
isidor 已提交
701
			default: /* 'default', 'mixed', 'filesFirst' */
702
				return compareFileNamesNumeric(statA.name, statB.name);
I
isidor 已提交
703 704 705
		}
	}
}
I
isidor 已提交
706

I
isidor 已提交
707
const getFileOverwriteConfirm = (name: string) => {
I
isidor 已提交
708 709 710 711 712 713
	return <IConfirmation>{
		message: localize('confirmOverwrite', "A file or folder with the name '{0}' already exists in the destination folder. Do you want to replace it?", name),
		detail: localize('irreversible', "This action is irreversible!"),
		primaryButton: localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
		type: 'warning'
	};
I
isidor 已提交
714 715
};

716 717 718 719 720 721 722 723 724
interface IWebkitDataTransfer {
	items: IWebkitDataTransferItem[];
}

interface IWebkitDataTransferItem {
	webkitGetAsEntry(): IWebkitDataTransferItemEntry;
}

interface IWebkitDataTransferItemEntry {
B
Benjamin Pasero 已提交
725
	name: string | undefined;
726 727 728 729 730 731 732 733 734 735 736
	isFile: boolean;
	isDirectory: boolean;

	file(resolve: (file: File) => void, reject: () => void): void;
	createReader(): IWebkitDataTransferItemEntryReader;
}

interface IWebkitDataTransferItemEntryReader {
	readEntries(resolve: (file: IWebkitDataTransferItemEntry[]) => void, reject: () => void): void
}

737 738 739 740 741 742 743 744
interface IUploadOperation {
	filesTotal: number;
	filesUploaded: number;

	startTime: number;
	bytesUploaded: number;
}

I
isidor 已提交
745 746 747
export class FileDragAndDrop implements ITreeDragAndDrop<ExplorerItem> {
	private static readonly CONFIRM_DND_SETTING_KEY = 'explorer.confirmDragAndDrop';

748 749 750
	private compressedDragOverElement: HTMLElement | undefined;
	private compressedDropTargetDisposable: IDisposable = Disposable.None;

I
isidor 已提交
751
	private toDispose: IDisposable[];
I
isidor 已提交
752
	private dropEnabled = false;
I
isidor 已提交
753 754 755 756 757 758 759 760 761 762

	constructor(
		@INotificationService private notificationService: INotificationService,
		@IExplorerService private explorerService: IExplorerService,
		@IEditorService private editorService: IEditorService,
		@IDialogService private dialogService: IDialogService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
		@IFileService private fileService: IFileService,
		@IConfigurationService private configurationService: IConfigurationService,
		@IInstantiationService private instantiationService: IInstantiationService,
763
		@IWorkingCopyFileService private workingCopyFileService: IWorkingCopyFileService,
764
		@IHostService private hostService: IHostService,
765 766
		@IWorkspaceEditingService private workspaceEditingService: IWorkspaceEditingService,
		@IProgressService private readonly progressService: IProgressService
I
isidor 已提交
767 768 769 770 771 772 773 774 775 776
	) {
		this.toDispose = [];

		const updateDropEnablement = () => {
			this.dropEnabled = this.configurationService.getValue('explorer.enableDragAndDrop');
		};
		updateDropEnablement();
		this.toDispose.push(this.configurationService.onDidChangeConfiguration((e) => updateDropEnablement()));
	}

I
isidor 已提交
777
	onDragOver(data: IDragAndDropData, target: ExplorerItem | undefined, targetIndex: number | undefined, originalEvent: DragEvent): boolean | ITreeDragOverReaction {
I
isidor 已提交
778 779 780 781
		if (!this.dropEnabled) {
			return false;
		}

782 783 784 785 786 787 788 789
		// Compressed folders
		if (target) {
			const compressedTarget = FileDragAndDrop.getCompressedStatFromDragEvent(target, originalEvent);

			if (compressedTarget) {
				const iconLabelName = getIconLabelNameFromHTMLElement(originalEvent.target);

				if (iconLabelName && iconLabelName.index < iconLabelName.count - 1) {
790
					const result = this.handleDragOver(data, compressedTarget, targetIndex, originalEvent);
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813

					if (result) {
						if (iconLabelName.element !== this.compressedDragOverElement) {
							this.compressedDragOverElement = iconLabelName.element;
							this.compressedDropTargetDisposable.dispose();
							this.compressedDropTargetDisposable = toDisposable(() => {
								DOM.removeClass(iconLabelName.element, 'drop-target');
								this.compressedDragOverElement = undefined;
							});

							DOM.addClass(iconLabelName.element, 'drop-target');
						}

						return typeof result === 'boolean' ? result : { ...result, feedback: [] };
					}

					this.compressedDropTargetDisposable.dispose();
					return false;
				}
			}
		}

		this.compressedDropTargetDisposable.dispose();
814
		return this.handleDragOver(data, target, targetIndex, originalEvent);
815 816
	}

817
	private handleDragOver(data: IDragAndDropData, target: ExplorerItem | undefined, targetIndex: number | undefined, originalEvent: DragEvent): boolean | ITreeDragOverReaction {
I
isidor 已提交
818 819
		const isCopy = originalEvent && ((originalEvent.ctrlKey && !isMacintosh) || (originalEvent.altKey && isMacintosh));
		const fromDesktop = data instanceof DesktopDragAndDropData;
I
isidor 已提交
820
		const effect = (fromDesktop || isCopy) ? ListDragOverEffect.Copy : ListDragOverEffect.Move;
I
isidor 已提交
821 822

		// Desktop DND
823 824
		if (fromDesktop) {
			if (!containsDragType(originalEvent, DataTransfers.FILES, CodeDataTransfers.FILES)) {
I
isidor 已提交
825 826 827 828 829 830 831 832 833 834 835
				return false;
			}
		}

		// Other-Tree DND
		else if (data instanceof ExternalElementsDragAndDropData) {
			return false;
		}

		// In-Explorer DND
		else {
J
Joao Moreno 已提交
836
			const items = FileDragAndDrop.getStatsFromDragAndDropData(data as ElementsDragAndDropData<ExplorerItem, ExplorerItem[]>);
I
isidor 已提交
837

I
isidor 已提交
838
			if (!target) {
H
Howard Hung 已提交
839
				// Dropping onto the empty area. Do not accept if items dragged are already
B
Benjamin Pasero 已提交
840
				// children of the root unless we are copying the file
841
				if (!isCopy && items.every(i => !!i.parent && i.parent.isRoot)) {
I
isidor 已提交
842 843 844
					return false;
				}

I
isidor 已提交
845
				return { accept: true, bubble: TreeDragOverBubble.Down, effect, autoExpand: false };
I
isidor 已提交
846 847
			}

I
isidor 已提交
848
			if (!Array.isArray(items)) {
I
isidor 已提交
849 850 851
				return false;
			}

I
isidor 已提交
852
			if (items.some((source) => {
I
isidor 已提交
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
				if (source.isRoot && target instanceof ExplorerItem && !target.isRoot) {
					return true; // Root folder can not be moved to a non root file stat.
				}

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

				if (source.isRoot && target instanceof ExplorerItem && target.isRoot) {
					// Disable moving workspace roots in one another
					return false;
				}

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

870
				if (isEqualOrParent(target.resource, source.resource)) {
I
isidor 已提交
871 872 873 874 875 876 877 878 879 880 881
					return true; // Can not move a parent folder into one of its children
				}

				return false;
			})) {
				return false;
			}
		}

		// All (target = model)
		if (!target) {
I
isidor 已提交
882
			return { accept: true, bubble: TreeDragOverBubble.Down, effect };
I
isidor 已提交
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
		}

		// All (target = file/folder)
		else {
			if (target.isDirectory) {
				if (target.isReadonly) {
					return false;
				}

				return { accept: true, bubble: TreeDragOverBubble.Down, effect, autoExpand: true };
			}

			if (this.contextService.getWorkspace().folders.every(folder => folder.uri.toString() !== target.resource.toString())) {
				return { accept: true, bubble: TreeDragOverBubble.Up, effect };
			}
		}

		return false;
	}

J
Joao Moreno 已提交
903
	getDragURI(element: ExplorerItem): string | null {
I
isidor 已提交
904
		if (this.explorerService.isEditable(element)) {
J
Joao Moreno 已提交
905 906 907
			return null;
		}

I
isidor 已提交
908 909 910
		return element.resource.toString();
	}

J
Joao Moreno 已提交
911 912 913 914
	getDragLabel(elements: ExplorerItem[], originalEvent: DragEvent): string | undefined {
		if (elements.length === 1) {
			const stat = FileDragAndDrop.getCompressedStatFromDragEvent(elements[0], originalEvent);
			return stat.name;
I
isidor 已提交
915 916
		}

J
Joao Moreno 已提交
917
		return String(elements.length);
I
isidor 已提交
918 919 920
	}

	onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void {
J
Joao Moreno 已提交
921
		const items = FileDragAndDrop.getStatsFromDragAndDropData(data as ElementsDragAndDropData<ExplorerItem, ExplorerItem[]>, originalEvent);
I
isidor 已提交
922
		if (items && items.length && originalEvent.dataTransfer) {
I
isidor 已提交
923
			// Apply some datatransfer types to allow for dragging the element outside of the application
924
			this.instantiationService.invokeFunction(fillResourceDataTransfers, items, undefined, originalEvent);
I
isidor 已提交
925 926 927

			// The only custom data transfer we set from the explorer is a file transfer
			// to be able to DND between multiple code file explorers across windows
I
isidor 已提交
928
			const fileResources = items.filter(s => !s.isDirectory && s.resource.scheme === Schemas.file).map(r => r.resource.fsPath);
I
isidor 已提交
929 930 931 932 933 934
			if (fileResources.length) {
				originalEvent.dataTransfer.setData(CodeDataTransfers.FILES, JSON.stringify(fileResources));
			}
		}
	}

I
isidor 已提交
935
	drop(data: IDragAndDropData, target: ExplorerItem | undefined, targetIndex: number | undefined, originalEvent: DragEvent): void {
936 937 938 939 940 941 942 943 944 945 946
		this.compressedDropTargetDisposable.dispose();

		// Find compressed target
		if (target) {
			const compressedTarget = FileDragAndDrop.getCompressedStatFromDragEvent(target, originalEvent);

			if (compressedTarget) {
				target = compressedTarget;
			}
		}

947 948 949 950
		// Find parent to add to
		if (!target) {
			target = this.explorerService.roots[this.explorerService.roots.length - 1];
		}
I
isidor 已提交
951
		if (!target.isDirectory && target.parent) {
952 953 954 955 956 957
			target = target.parent;
		}
		if (target.isReadonly) {
			return;
		}

I
isidor 已提交
958 959
		// Desktop DND (Import file)
		if (data instanceof DesktopDragAndDropData) {
J
Joao Moreno 已提交
960 961 962 963 964
			if (isWeb) {
				this.handleWebExternalDrop(data, target, originalEvent).then(undefined, e => this.notificationService.warn(e));
			} else {
				this.handleExternalDrop(data, target, originalEvent).then(undefined, e => this.notificationService.warn(e));
			}
I
isidor 已提交
965 966 967
		}
		// In-Explorer DND (Move/Copy file)
		else {
968
			this.handleExplorerDrop(data as ElementsDragAndDropData<ExplorerItem, ExplorerItem[]>, target, originalEvent).then(undefined, e => this.notificationService.warn(e));
I
isidor 已提交
969 970 971
		}
	}

J
Joao Moreno 已提交
972
	private async handleWebExternalDrop(data: DesktopDragAndDropData, target: ExplorerItem, originalEvent: DragEvent): Promise<void> {
973 974 975 976 977 978 979 980 981
		const items = (originalEvent.dataTransfer as unknown as IWebkitDataTransfer).items;

		// Somehow the items thing is being modified at random, maybe as a security
		// measure since this is a DND operation. As such, we copy the items into
		// an array we own as early as possible before using it.
		const entries: IWebkitDataTransferItemEntry[] = [];
		for (const item of items) {
			entries.push(item.webkitGetAsEntry());
		}
S
Steven Hermans 已提交
982

983
		const results: { isFile: boolean, resource: URI }[] = [];
984
		const cts = new CancellationTokenSource();
985
		const operation: IUploadOperation = { filesTotal: entries.length, filesUploaded: 0, startTime: Date.now(), bytesUploaded: 0 };
986 987 988 989 990 991 992 993 994

		// Start upload and report progress globally
		const uploadPromise = this.progressService.withProgress({
			location: ProgressLocation.Window,
			delay: 800,
			cancellable: true,
			title: localize('uploadingFiles', "Uploading")
		}, async progress => {
			for (let entry of entries) {
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006

				// Confirm overwrite as needed
				if (target && entry.name && target.getChild(entry.name)) {
					const { confirmed } = await this.dialogService.confirm(getFileOverwriteConfirm(entry.name));
					if (!confirmed) {
						continue;
					}

					await this.workingCopyFileService.delete(joinPath(target.resource, entry.name), { recursive: true });
				}

				// Upload entry
1007
				const result = await this.doUploadWebFileEntry(entry, target.resource, target, progress, operation, cts.token);
1008 1009 1010
				if (result) {
					results.push(result);
				}
S
Steven Hermans 已提交
1011
			}
1012 1013 1014 1015 1016 1017 1018
		}, () => cts.dispose(true));

		// Also indicate progress in the files view
		this.progressService.withProgress({ location: VIEW_ID, delay: 800 }, () => uploadPromise);

		// Wait until upload is done
		await uploadPromise;
1019 1020

		// Open uploaded file in editor only if we upload just one
1021
		if (!cts.token.isCancellationRequested && results.length === 1 && results[0].isFile) {
1022 1023
			await this.editorService.openEditor({ resource: results[0].resource, options: { pinned: true } });
		}
1024 1025
	}

1026
	private async doUploadWebFileEntry(entry: IWebkitDataTransferItemEntry, parentResource: URI, target: ExplorerItem | undefined, progress: IProgress<IProgressStep>, operation: IUploadOperation, token: CancellationToken): Promise<{ isFile: boolean, resource: URI } | undefined> {
1027
		if (token.isCancellationRequested || !entry.name || (!entry.isFile && !entry.isDirectory)) {
1028 1029 1030
			return undefined;
		}

1031
		// Report progress
1032
		let fileBytesUploaded = 0;
1033
		const reportProgress = (fileSize: number, bytesUploaded: number): void => {
1034 1035 1036 1037
			fileBytesUploaded += bytesUploaded;
			operation.bytesUploaded += bytesUploaded;

			const bytesUploadedPerSecond = operation.bytesUploaded / ((Date.now() - operation.startTime) / 1000);
1038 1039

			let message: string;
1040
			if (operation.filesTotal === 1 && entry.name) {
1041 1042
				message = entry.name;
			} else {
1043
				message = localize('uploadProgress', "{0} of {1} files ({2}/s)", operation.filesUploaded, operation.filesTotal, BinarySize.formatSize(bytesUploadedPerSecond));
1044 1045 1046
			}

			if (fileSize > BinarySize.MB) {
1047
				message = localize('uploadProgressDetail', "{0} ({1} of {2}, {3}/s)", message, BinarySize.formatSize(fileBytesUploaded), BinarySize.formatSize(fileSize), BinarySize.formatSize(bytesUploadedPerSecond));
1048 1049 1050 1051
			}

			progress.report({ message });
		};
1052
		operation.filesUploaded++;
1053
		reportProgress(0, 0);
1054

1055
		// Handle file upload
1056
		const resource = joinPath(parentResource, entry.name);
1057
		if (entry.isFile) {
S
Steven Hermans 已提交
1058
			const file = await new Promise<File>((resolve, reject) => entry.file(resolve, reject));
B
Benjamin Pasero 已提交
1059

1060 1061 1062
			if (token.isCancellationRequested) {
				return undefined;
			}
B
Benjamin Pasero 已提交
1063

1064 1065
			// Chrome/Edge/Firefox support stream method
			if (typeof file.stream === 'function') {
1066
				await this.doUploadWebFileEntryBuffered(resource, file, reportProgress, token);
1067 1068 1069 1070
			}

			// Fallback to unbuffered upload for other browsers
			else {
1071
				await this.doUploadWebFileEntryUnbuffered(resource, file, reportProgress);
1072
			}
1073 1074 1075 1076 1077 1078

			return { isFile: true, resource };
		}

		// Handle folder upload
		else {
1079 1080

			// Create target folder
1081 1082
			await this.fileService.createFolder(resource);

1083 1084 1085 1086
			if (token.isCancellationRequested) {
				return undefined;
			}

1087 1088
			// Recursive upload files in this directory
			const dirReader = entry.createReader();
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
			const childEntries: IWebkitDataTransferItemEntry[] = [];
			let done = false;
			do {
				const childEntriesChunk = await new Promise<IWebkitDataTransferItemEntry[]>((resolve, reject) => dirReader.readEntries(resolve, reject));
				if (childEntriesChunk.length > 0) {
					childEntries.push(...childEntriesChunk);
				} else {
					done = true; // an empty array is a signal that all entries have been read
				}
			} while (!done);
1099

1100
			// Update operation total based on new counts
1101
			operation.filesTotal += childEntries.length;
1102 1103

			// Upload all entries as files to target
1104
			const folderTarget = target && target.getChild(entry.name) || undefined;
S
Steven Hermans 已提交
1105
			for (let childEntry of childEntries) {
1106
				await this.doUploadWebFileEntry(childEntry, resource, folderTarget, progress, operation, token);
1107
			}
1108 1109

			return { isFile: false, resource };
1110
		}
J
Joao Moreno 已提交
1111
	}
I
isidor 已提交
1112

1113 1114 1115 1116 1117 1118 1119 1120
	private async doUploadWebFileEntryBuffered(resource: URI, file: File, progressReporter: (fileSize: number, bytesUploaded: number) => void, token: CancellationToken): Promise<void> {
		const writeableStream = newWriteableBufferStream({
			// Set a highWaterMark to prevent the stream
			// for file upload to produce large buffers
			// in-memory
			highWaterMark: 10
		});
		const writeFilePromise = this.fileService.writeFile(resource, writeableStream);
1121 1122

		// Read the file in chunks using File.stream() web APIs
1123 1124
		try {
			const reader: ReadableStreamDefaultReader<Uint8Array> = file.stream().getReader();
1125

1126 1127
			let res = await reader.read();
			while (!res.done) {
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
				if (token.isCancellationRequested) {
					return undefined;
				}

				// Write buffer into stream but make sure to wait
				// in case the highWaterMark is reached
				const buffer = VSBuffer.wrap(res.value);
				await writeableStream.write(buffer);

				if (token.isCancellationRequested) {
					return undefined;
				}

				// Report progress
				progressReporter(file.size, buffer.byteLength);
1143

1144
				res = await reader.read();
1145
			}
1146 1147 1148 1149
			writeableStream.end(res.value instanceof Uint8Array ? VSBuffer.wrap(res.value) : undefined);
		} catch (error) {
			writeableStream.end(error);
		}
1150

1151 1152 1153 1154
		if (token.isCancellationRequested) {
			return undefined;
		}

1155 1156
		// Wait for file being written to target
		await writeFilePromise;
1157 1158
	}

1159
	private doUploadWebFileEntryUnbuffered(resource: URI, file: File, progressReporter: (fileSize: number, bytesUploaded: number) => void): Promise<void> {
1160 1161 1162 1163 1164
		return new Promise<void>((resolve, reject) => {
			const reader = new FileReader();
			reader.onload = async event => {
				try {
					if (event.target?.result instanceof ArrayBuffer) {
1165 1166 1167 1168 1169
						const buffer = VSBuffer.wrap(new Uint8Array(event.target.result));
						await this.fileService.writeFile(resource, buffer);

						// Report progress
						progressReporter(file.size, buffer.byteLength);
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
					} else {
						throw new Error('Could not read from dropped file.');
					}

					resolve();
				} catch (error) {
					reject(error);
				}
			};

			// Start reading the file to trigger `onload`
			reader.readAsArrayBuffer(file);
		});
	}

J
Joao Moreno 已提交
1185
	private async handleExternalDrop(data: DesktopDragAndDropData, target: ExplorerItem, originalEvent: DragEvent): Promise<void> {
1186

I
isidor 已提交
1187
		// Check for dropped external files to be folders
1188
		const droppedResources = extractResources(originalEvent, true);
1189
		const result = await this.fileService.resolveAll(droppedResources.map(droppedResource => ({ resource: droppedResource.resource })));
I
isidor 已提交
1190

I
isidor 已提交
1191
		// Pass focus to window
1192
		this.hostService.focus();
I
isidor 已提交
1193

I
isidor 已提交
1194 1195 1196
		// Handle folders by adding to workspace if we are in workspace context
		const folders = result.filter(r => r.success && r.stat && r.stat.isDirectory).map(result => ({ uri: result.stat!.resource }));
		if (folders.length > 0) {
I
isidor 已提交
1197 1198 1199 1200
			const buttons = [
				folders.length > 1 ? localize('copyFolders', "&&Copy Folders") : localize('copyFolder', "&&Copy Folder"),
				localize('cancel', "Cancel")
			];
I
isidor 已提交
1201
			const workspaceFolderSchemas = this.contextService.getWorkspace().folders.map(f => f.uri.scheme);
I
isidor 已提交
1202 1203 1204 1205 1206 1207
			let message = folders.length > 1 ? localize('copyfolders', "Are you sure to want to copy folders?") : localize('copyfolder', "Are you sure to want to copy '{0}'?", basename(folders[0].uri));
			if (folders.some(f => workspaceFolderSchemas.indexOf(f.uri.scheme) >= 0)) {
				// We only allow to add a folder to the workspace if there is already a workspace folder with that scheme
				buttons.unshift(folders.length > 1 ? localize('addFolders', "&&Add Folders to Workspace") : localize('addFolder', "&&Add Folder to Workspace"));
				message = folders.length > 1 ? localize('dropFolders', "Do you want to copy the folders or add the folders to the workspace?")
					: localize('dropFolder', "Do you want to copy '{0}' or add '{0}' as a folder to the workspace?", basename(folders[0].uri));
I
isidor 已提交
1208
			}
I
isidor 已提交
1209

1210
			const { choice } = await this.dialogService.show(Severity.Info, message, buttons);
I
isidor 已提交
1211
			if (choice === buttons.length - 3) {
I
isidor 已提交
1212 1213
				return this.workspaceEditingService.addFolders(folders);
			}
I
isidor 已提交
1214
			if (choice === buttons.length - 2) {
I
isidor 已提交
1215 1216 1217 1218
				return this.addResources(target, droppedResources.map(res => res.resource));
			}

			return undefined;
I
isidor 已提交
1219 1220 1221 1222 1223 1224
		}

		// Handle dropped files (only support FileStat as target)
		else if (target instanceof ExplorerItem) {
			return this.addResources(target, droppedResources.map(res => res.resource));
		}
I
isidor 已提交
1225 1226
	}

I
isidor 已提交
1227
	private async addResources(target: ExplorerItem, resources: URI[]): Promise<void> {
I
isidor 已提交
1228 1229 1230
		if (resources && resources.length > 0) {

			// Resolve target to check for name collisions and ask user
I
isidor 已提交
1231 1232 1233 1234
			const targetStat = await this.fileService.resolve(target.resource);

			// Check for name collisions
			const targetNames = new Set<string>();
1235
			const caseSensitive = this.fileService.hasCapability(target.resource, FileSystemProviderCapabilities.PathCaseSensitive);
I
isidor 已提交
1236 1237
			if (targetStat.children) {
				targetStat.children.forEach(child => {
1238
					targetNames.add(caseSensitive ? child.name : child.name.toLowerCase());
I
isidor 已提交
1239 1240
				});
			}
I
isidor 已提交
1241

I
isidor 已提交
1242 1243
			// Run add in sequence
			const addPromisesFactory: ITask<Promise<void>>[] = [];
I
isidor 已提交
1244
			await Promise.all(resources.map(async resource => {
1245
				if (targetNames.has(caseSensitive ? basename(resource) : basename(resource).toLowerCase())) {
I
isidor 已提交
1246 1247 1248 1249 1250 1251
					const confirmationResult = await this.dialogService.confirm(getFileOverwriteConfirm(basename(resource)));
					if (!confirmationResult.confirmed) {
						return;
					}
				}

I
isidor 已提交
1252 1253 1254 1255
				addPromisesFactory.push(async () => {
					const sourceFile = resource;
					const targetFile = joinPath(target.resource, basename(sourceFile));

1256
					const stat = await this.workingCopyFileService.copy(sourceFile, targetFile, true);
I
isidor 已提交
1257 1258 1259 1260
					// if we only add one file, just open it directly
					if (resources.length === 1 && !stat.isDirectory) {
						this.editorService.openEditor({ resource: stat.resource, options: { pinned: true } });
					}
I
isidor 已提交
1261
				});
I
isidor 已提交
1262
			}));
I
isidor 已提交
1263

I
isidor 已提交
1264 1265
			await sequence(addPromisesFactory);
		}
I
isidor 已提交
1266 1267
	}

1268 1269
	private async handleExplorerDrop(data: ElementsDragAndDropData<ExplorerItem, ExplorerItem[]>, target: ExplorerItem, originalEvent: DragEvent): Promise<void> {
		const elementsData = FileDragAndDrop.getStatsFromDragAndDropData(data);
I
isidor 已提交
1270
		const items = distinctParents(elementsData, s => s.resource);
I
isidor 已提交
1271
		const isCopy = (originalEvent.ctrlKey && !isMacintosh) || (originalEvent.altKey && isMacintosh);
I
isidor 已提交
1272 1273

		// Handle confirm setting
I
isidor 已提交
1274
		const confirmDragAndDrop = !isCopy && this.configurationService.getValue<boolean>(FileDragAndDrop.CONFIRM_DND_SETTING_KEY);
I
isidor 已提交
1275
		if (confirmDragAndDrop) {
1276 1277 1278 1279 1280 1281
			const message = items.length > 1 && items.every(s => s.isRoot) ? localize('confirmRootsMove', "Are you sure you want to change the order of multiple root folders in your workspace?")
				: items.length > 1 ? localize('confirmMultiMove', "Are you sure you want to move the following {0} files into '{1}'?", items.length, target.name)
					: items[0].isRoot ? localize('confirmRootMove', "Are you sure you want to change the order of root folder '{0}' in your workspace?", items[0].name)
						: localize('confirmMove', "Are you sure you want to move '{0}' into '{1}'?", items[0].name, target.name);
			const detail = items.length > 1 && !items.every(s => s.isRoot) ? getFileNamesMessage(items.map(i => i.resource)) : undefined;

I
isidor 已提交
1282
			const confirmation = await this.dialogService.confirm({
1283 1284
				message,
				detail,
I
isidor 已提交
1285 1286 1287 1288 1289 1290 1291
				checkbox: {
					label: localize('doNotAskAgain', "Do not ask me again")
				},
				type: 'question',
				primaryButton: localize({ key: 'moveButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Move")
			});

I
isidor 已提交
1292 1293 1294
			if (!confirmation.confirmed) {
				return;
			}
I
isidor 已提交
1295 1296

			// Check for confirmation checkbox
I
isidor 已提交
1297 1298
			if (confirmation.checkboxChecked === true) {
				await this.configurationService.updateValue(FileDragAndDrop.CONFIRM_DND_SETTING_KEY, false, ConfigurationTarget.USER);
I
isidor 已提交
1299
			}
I
isidor 已提交
1300
		}
I
isidor 已提交
1301

I
isidor 已提交
1302 1303
		const rootDropPromise = this.doHandleRootDrop(items.filter(s => s.isRoot), target);
		await Promise.all(items.filter(s => !s.isRoot).map(source => this.doHandleExplorerDrop(source, target, isCopy)).concat(rootDropPromise));
I
isidor 已提交
1304 1305
	}

1306
	private doHandleRootDrop(roots: ExplorerItem[], target: ExplorerItem): Promise<void> {
I
isidor 已提交
1307 1308 1309 1310 1311
		if (roots.length === 0) {
			return Promise.resolve(undefined);
		}

		const folders = this.contextService.getWorkspace().folders;
1312
		let targetIndex: number | undefined;
I
isidor 已提交
1313 1314 1315 1316 1317
		const workspaceCreationData: IWorkspaceFolderCreationData[] = [];
		const rootsToMove: IWorkspaceFolderCreationData[] = [];

		for (let index = 0; index < folders.length; index++) {
			const data = {
I
isidor 已提交
1318 1319
				uri: folders[index].uri,
				name: folders[index].name
I
isidor 已提交
1320 1321
			};
			if (target instanceof ExplorerItem && folders[index].uri.toString() === target.resource.toString()) {
I
isidor 已提交
1322
				targetIndex = index;
I
isidor 已提交
1323 1324 1325 1326 1327 1328 1329 1330
			}

			if (roots.every(r => r.resource.toString() !== folders[index].uri.toString())) {
				workspaceCreationData.push(data);
			} else {
				rootsToMove.push(data);
			}
		}
I
isidor 已提交
1331
		if (targetIndex === undefined) {
I
isidor 已提交
1332 1333
			targetIndex = workspaceCreationData.length;
		}
I
isidor 已提交
1334 1335 1336 1337 1338

		workspaceCreationData.splice(targetIndex, 0, ...rootsToMove);
		return this.workspaceEditingService.updateFolders(0, workspaceCreationData.length, workspaceCreationData);
	}

I
isidor 已提交
1339
	private async doHandleExplorerDrop(source: ExplorerItem, target: ExplorerItem, isCopy: boolean): Promise<void> {
I
isidor 已提交
1340 1341
		// Reuse duplicate action if user copies
		if (isCopy) {
I
isidor 已提交
1342
			const incrementalNaming = this.configurationService.getValue<IFilesConfiguration>().explorer.incrementalNaming;
1343
			const stat = await this.workingCopyFileService.copy(source.resource, findValidPasteFileTarget(this.explorerService, target, { resource: source.resource, isDirectory: source.isDirectory, allowOverwrite: false }, incrementalNaming));
I
isidor 已提交
1344 1345 1346
			if (!stat.isDirectory) {
				await this.editorService.openEditor({ resource: stat.resource, options: { pinned: true } });
			}
I
isidor 已提交
1347

I
isidor 已提交
1348
			return;
I
isidor 已提交
1349 1350 1351 1352
		}

		// Otherwise move
		const targetResource = joinPath(target.resource, source.name);
I
isidor 已提交
1353 1354 1355 1356
		if (source.isReadonly) {
			// Do not allow moving readonly items
			return Promise.resolve();
		}
I
isidor 已提交
1357

I
isidor 已提交
1358
		try {
1359
			await this.workingCopyFileService.move(source.resource, targetResource);
I
isidor 已提交
1360
		} catch (error) {
I
isidor 已提交
1361 1362
			// Conflict
			if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_MOVE_CONFLICT) {
I
isidor 已提交
1363
				const confirm = getFileOverwriteConfirm(source.name);
I
isidor 已提交
1364
				// Move with overwrite if the user confirms
I
isidor 已提交
1365 1366 1367
				const { confirmed } = await this.dialogService.confirm(confirm);
				if (confirmed) {
					try {
1368
						await this.workingCopyFileService.move(source.resource, targetResource, true /* overwrite */);
I
isidor 已提交
1369 1370
					} catch (error) {
						this.notificationService.error(error);
I
isidor 已提交
1371
					}
I
isidor 已提交
1372
				}
I
isidor 已提交
1373 1374 1375 1376 1377
			}
			// Any other error
			else {
				this.notificationService.error(error);
			}
I
isidor 已提交
1378
		}
I
isidor 已提交
1379
	}
J
Joao Moreno 已提交
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394

	private static getStatsFromDragAndDropData(data: ElementsDragAndDropData<ExplorerItem, ExplorerItem[]>, dragStartEvent?: DragEvent): ExplorerItem[] {
		if (data.context) {
			return data.context;
		}

		// Detect compressed folder dragging
		if (dragStartEvent && data.elements.length === 1) {
			data.context = [FileDragAndDrop.getCompressedStatFromDragEvent(data.elements[0], dragStartEvent)];
			return data.context;
		}

		return data.elements;
	}

1395 1396
	private static getCompressedStatFromDragEvent(stat: ExplorerItem, dragEvent: DragEvent): ExplorerItem {
		const target = document.elementFromPoint(dragEvent.clientX, dragEvent.clientY);
J
Joao Moreno 已提交
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
		const iconLabelName = getIconLabelNameFromHTMLElement(target);

		if (iconLabelName) {
			const { count, index } = iconLabelName;

			let i = count - 1;
			while (i > index && stat.parent) {
				stat = stat.parent;
				i--;
			}

			return stat;
		}

		return stat;
	}
1413 1414 1415 1416

	onDragEnd(): void {
		this.compressedDropTargetDisposable.dispose();
	}
J
Joao Moreno 已提交
1417 1418
}

1419
function getIconLabelNameFromHTMLElement(target: HTMLElement | EventTarget | Element | null): { element: HTMLElement, count: number, index: number } | null {
J
Joao Moreno 已提交
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
	if (!(target instanceof HTMLElement)) {
		return null;
	}

	let element: HTMLElement | null = target;

	while (element && !DOM.hasClass(element, 'monaco-list-row')) {
		if (DOM.hasClass(element, 'label-name') && element.hasAttribute('data-icon-label-count')) {
			const count = Number(element.getAttribute('data-icon-label-count'));
			const index = Number(element.getAttribute('data-icon-label-index'));

			if (isNumber(count) && isNumber(index)) {
				return { element: element, count, index };
			}
		}

		element = element.parentElement;
	}

	return null;
I
isidor 已提交
1440
}
J
Joao Moreno 已提交
1441

J
Joao Moreno 已提交
1442 1443 1444 1445
export function isCompressedFolderName(target: HTMLElement | EventTarget | Element | null): boolean {
	return !!getIconLabelNameFromHTMLElement(target);
}

J
Joao Moreno 已提交
1446 1447
export class ExplorerCompressionDelegate implements ITreeCompressionDelegate<ExplorerItem> {

1448
	isIncompressible(stat: ExplorerItem): boolean {
J
Joao Moreno 已提交
1449
		return stat.isRoot || !stat.isDirectory || stat instanceof NewExplorerItem || (!stat.parent || stat.parent.isRoot);
J
Joao Moreno 已提交
1450 1451
	}
}