-
Notifications
You must be signed in to change notification settings - Fork 29.8k
/
explorerViewer.ts
1539 lines (1262 loc) · 54.8 KB
/
explorerViewer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
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
482
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
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import * as DOM from 'vs/base/browser/dom';
import * as glob from 'vs/base/common/glob';
import { IListVirtualDelegate, ListDragOverEffect } from 'vs/base/browser/ui/list/list';
import { IProgressService, ProgressLocation, IProgressStep, IProgress } from 'vs/platform/progress/common/progress';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { IFileService, FileKind, FileOperationError, FileOperationResult, FileSystemProviderCapabilities, BinarySize } from 'vs/platform/files/common/files';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IDisposable, Disposable, dispose, toDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { KeyCode } from 'vs/base/common/keyCodes';
import { IFileLabelOptions, IResourceLabel, ResourceLabels } from 'vs/workbench/browser/labels';
import { ITreeNode, ITreeFilter, TreeVisibility, TreeFilterResult, IAsyncDataSource, ITreeSorter, ITreeDragAndDrop, ITreeDragOverReaction, TreeDragOverBubble } from 'vs/base/browser/ui/tree/tree';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
import { IFilesConfiguration, IExplorerService, VIEW_ID } from 'vs/workbench/contrib/files/common/files';
import { dirname, joinPath, basename, distinctParents } from 'vs/base/common/resources';
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';
import * as path from 'vs/base/common/path';
import { ExplorerItem, NewExplorerItem } from 'vs/workbench/contrib/files/common/explorerModel';
import { compareFileNamesDefault, compareFileExtensionsDefault } from 'vs/base/common/comparers';
import { fillResourceDataTransfers, CodeDataTransfers, extractResources, containsDragType } from 'vs/workbench/browser/dnd';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IDragAndDropData, DataTransfers } from 'vs/base/browser/dnd';
import { Schemas } from 'vs/base/common/network';
import { NativeDragAndDropData, ExternalElementsDragAndDropData, ElementsDragAndDropData } from 'vs/base/browser/ui/list/listView';
import { isMacintosh, isWeb } from 'vs/base/common/platform';
import { IDialogService, IConfirmation, getFileNamesMessage } from 'vs/platform/dialogs/common/dialogs';
import { IWorkingCopyFileService } from 'vs/workbench/services/workingCopy/common/workingCopyFileService';
import { IHostService } from 'vs/workbench/services/host/browser/host';
import { IWorkspaceEditingService } from 'vs/workbench/services/workspaces/common/workspaceEditing';
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';
import { findValidPasteFileTarget } from 'vs/workbench/contrib/files/browser/fileActions';
import { FuzzyScore, createMatches } from 'vs/base/common/filters';
import { Emitter, Event, EventMultiplexer } from 'vs/base/common/event';
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';
import { VSBuffer, newWriteableBufferStream } from 'vs/base/common/buffer';
import { ILabelService } from 'vs/platform/label/common/label';
import { isNumber } from 'vs/base/common/types';
import { domEvent } from 'vs/base/browser/event';
import { IEditableData } from 'vs/workbench/common/views';
import { IEditorInput } from 'vs/workbench/common/editor';
import { CancellationTokenSource, CancellationToken } from 'vs/base/common/cancellation';
import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity';
export class ExplorerDelegate implements IListVirtualDelegate<ExplorerItem> {
static readonly ITEM_HEIGHT = 22;
getHeight(element: ExplorerItem): number {
return ExplorerDelegate.ITEM_HEIGHT;
}
getTemplateId(element: ExplorerItem): string {
return FilesRenderer.ID;
}
}
export const explorerRootErrorEmitter = new Emitter<URI>();
export class ExplorerDataSource implements IAsyncDataSource<ExplorerItem | ExplorerItem[], ExplorerItem> {
constructor(
@IProgressService private readonly progressService: IProgressService,
@INotificationService private readonly notificationService: INotificationService,
@IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService,
@IFileService private readonly fileService: IFileService,
@IExplorerService private readonly explorerService: IExplorerService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService
) { }
hasChildren(element: ExplorerItem | ExplorerItem[]): boolean {
return Array.isArray(element) || element.isDirectory;
}
getChildren(element: ExplorerItem | ExplorerItem[]): Promise<ExplorerItem[]> {
if (Array.isArray(element)) {
return Promise.resolve(element);
}
const sortOrder = this.explorerService.sortOrder;
const promise = element.fetchChildren(sortOrder).then(undefined, e => {
if (element instanceof ExplorerItem && element.isRoot) {
if (this.contextService.getWorkbenchState() === WorkbenchState.FOLDER) {
// Single folder create a dummy explorer item to show error
const placeholder = new ExplorerItem(element.resource, this.fileService, undefined, false);
placeholder.isError = true;
return [placeholder];
} else {
explorerRootErrorEmitter.fire(element.resource);
}
} else {
// Do not show error for roots since we already use an explorer decoration to notify user
this.notificationService.error(e);
}
return []; // we could not resolve any children because of an error
});
this.progressService.withProgress({
location: ProgressLocation.Explorer,
delay: this.layoutService.isRestored() ? 800 : 1200 // less ugly initial startup
}, _progress => promise);
return promise;
}
}
export interface ICompressedNavigationController {
readonly current: ExplorerItem;
readonly currentId: string;
readonly items: ExplorerItem[];
readonly labels: HTMLElement[];
readonly index: number;
readonly count: number;
readonly onDidChange: Event<void>;
previous(): void;
next(): void;
first(): void;
last(): void;
setIndex(index: number): void;
updateCollapsed(collapsed: boolean): void;
}
export class CompressedNavigationController implements ICompressedNavigationController, IDisposable {
static ID = 0;
private _index: number;
private _labels!: HTMLElement[];
private _updateLabelDisposable: IDisposable;
get index(): number { return this._index; }
get count(): number { return this.items.length; }
get current(): ExplorerItem { return this.items[this._index]!; }
get currentId(): string { return `${this.id}_${this.index}`; }
get labels(): HTMLElement[] { return this._labels; }
private _onDidChange = new Emitter<void>();
readonly onDidChange = this._onDidChange.event;
constructor(private id: string, readonly items: ExplorerItem[], templateData: IFileTemplateData, private depth: number, private collapsed: boolean) {
this._index = items.length - 1;
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[];
let parents = '';
for (let i = 0; i < this.labels.length; i++) {
const ariaLabel = parents.length ? `${this.items[i].name}, compact, ${parents}` : this.items[i].name;
this.labels[i].setAttribute('aria-label', ariaLabel);
this.labels[i].setAttribute('aria-level', `${this.depth + i}`);
parents = parents.length ? `${this.items[i].name} ${parents}` : this.items[i].name;
}
this.updateCollapsed(this.collapsed);
if (this._index < this.labels.length) {
this.labels[this._index].classList.add('active');
}
}
previous(): void {
if (this._index <= 0) {
return;
}
this.setIndex(this._index - 1);
}
next(): void {
if (this._index >= this.items.length - 1) {
return;
}
this.setIndex(this._index + 1);
}
first(): void {
if (this._index === 0) {
return;
}
this.setIndex(0);
}
last(): void {
if (this._index === this.items.length - 1) {
return;
}
this.setIndex(this.items.length - 1);
}
setIndex(index: number): void {
if (index < 0 || index >= this.items.length) {
return;
}
this.labels[this._index].classList.remove('active');
this._index = index;
this.labels[this._index].classList.add('active');
this._onDidChange.fire();
}
updateCollapsed(collapsed: boolean): void {
this.collapsed = collapsed;
for (let i = 0; i < this.labels.length; i++) {
this.labels[i].setAttribute('aria-expanded', collapsed ? 'false' : 'true');
}
}
dispose(): void {
this._onDidChange.dispose();
this._updateLabelDisposable.dispose();
}
}
export interface IFileTemplateData {
elementDisposable: IDisposable;
label: IResourceLabel;
container: HTMLElement;
}
export class FilesRenderer implements ICompressibleTreeRenderer<ExplorerItem, FuzzyScore, IFileTemplateData>, IListAccessibilityProvider<ExplorerItem>, IDisposable {
static readonly ID = 'file';
private config: IFilesConfiguration;
private configListener: IDisposable;
private compressedNavigationControllers = new Map<ExplorerItem, CompressedNavigationController>();
private _onDidChangeActiveDescendant = new EventMultiplexer<void>();
readonly onDidChangeActiveDescendant = this._onDidChangeActiveDescendant.event;
constructor(
private labels: ResourceLabels,
private updateWidth: (stat: ExplorerItem) => void,
@IContextViewService private readonly contextViewService: IContextViewService,
@IThemeService private readonly themeService: IThemeService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IExplorerService private readonly explorerService: IExplorerService,
@ILabelService private readonly labelService: ILabelService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService
) {
this.config = this.configurationService.getValue<IFilesConfiguration>();
this.configListener = this.configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('explorer')) {
this.config = this.configurationService.getValue();
}
});
}
getWidgetAriaLabel(): string {
return localize('treeAriaLabel', "Files Explorer");
}
get templateId(): string {
return FilesRenderer.ID;
}
renderTemplate(container: HTMLElement): IFileTemplateData {
const elementDisposable = Disposable.None;
const label = this.labels.create(container, { supportHighlights: true });
return { elementDisposable, label, container };
}
renderElement(node: ITreeNode<ExplorerItem, FuzzyScore>, index: number, templateData: IFileTemplateData): void {
templateData.elementDisposable.dispose();
const stat = node.element;
const editableData = this.explorerService.getEditableData(stat);
templateData.label.element.classList.remove('compressed');
// File Label
if (!editableData) {
templateData.label.element.style.display = 'flex';
templateData.elementDisposable = this.renderStat(stat, stat.name, undefined, node.filterData, templateData);
}
// Input Box
else {
templateData.label.element.style.display = 'none';
templateData.elementDisposable = this.renderInputBox(templateData.container, stat, editableData);
}
}
renderCompressedElements(node: ITreeNode<ICompressedTreeNode<ExplorerItem>, FuzzyScore>, index: number, templateData: IFileTemplateData, height: number | undefined): void {
templateData.elementDisposable.dispose();
const stat = node.element.elements[node.element.elements.length - 1];
const editable = node.element.elements.filter(e => this.explorerService.isEditable(e));
const editableData = editable.length === 0 ? undefined : this.explorerService.getEditableData(editable[0]);
// File Label
if (!editableData) {
templateData.label.element.classList.add('compressed');
templateData.label.element.style.display = 'flex';
const disposables = new DisposableStore();
const id = `compressed-explorer_${CompressedNavigationController.ID++}`;
const label = node.element.elements.map(e => e.name);
disposables.add(this.renderStat(stat, label, id, node.filterData, templateData));
const compressedNavigationController = new CompressedNavigationController(id, node.element.elements, templateData, node.depth, node.collapsed);
disposables.add(compressedNavigationController);
this.compressedNavigationControllers.set(stat, compressedNavigationController);
// accessibility
disposables.add(this._onDidChangeActiveDescendant.add(compressedNavigationController.onDidChange));
domEvent(templateData.container, 'mousedown')(e => {
const result = getIconLabelNameFromHTMLElement(e.target);
if (result) {
compressedNavigationController.setIndex(result.index);
}
}, undefined, disposables);
disposables.add(toDisposable(() => this.compressedNavigationControllers.delete(stat)));
templateData.elementDisposable = disposables;
}
// Input Box
else {
templateData.label.element.classList.remove('compressed');
templateData.label.element.style.display = 'none';
templateData.elementDisposable = this.renderInputBox(templateData.container, editable[0], editableData);
}
}
private renderStat(stat: ExplorerItem, label: string | string[], domId: string | undefined, filterData: FuzzyScore | undefined, templateData: IFileTemplateData): IDisposable {
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,
matches: createMatches(filterData),
separator: this.labelService.getSeparator(stat.resource.scheme, stat.resource.authority),
domId
});
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
}
});
}
private renderInputBox(container: HTMLElement, stat: ExplorerItem, editableData: IEditableData): IDisposable {
// Use a file label only for the icon next to the input box
const label = this.labels.create(container);
const extraClasses = ['explorer-item', 'explorer-item-edited'];
const fileKind = stat.isRoot ? FileKind.ROOT_FOLDER : stat.isDirectory ? FileKind.FOLDER : FileKind.FILE;
const labelOptions: IFileLabelOptions = { hidePath: true, hideLabel: true, fileKind, extraClasses };
const parent = stat.name ? dirname(stat.resource) : stat.resource;
const value = stat.name || '';
label.setFile(joinPath(parent, value || ' '), labelOptions); // Use icon for ' ' if name is empty.
// hack: hide label
(label.element.firstElementChild as HTMLElement).style.display = 'none';
// Input field for name
const inputBox = new InputBox(label.element, this.contextViewService, {
validationOptions: {
validation: (value) => {
const message = editableData.validationMessage(value);
if (!message || message.severity !== Severity.Error) {
return null;
}
return {
content: message.content,
formatContent: true,
type: MessageType.ERROR
};
}
},
ariaLabel: localize('fileInputAriaLabel', "Type file name. Press Enter to confirm or Escape to cancel.")
});
const styler = attachInputBoxStyler(inputBox, this.themeService);
const lastDot = value.lastIndexOf('.');
inputBox.value = value;
inputBox.focus();
inputBox.select({ start: 0, end: lastDot > 0 && !stat.isDirectory ? lastDot : value.length });
const done = once((success: boolean, finishEditing: boolean) => {
label.element.style.display = 'none';
const value = inputBox.value;
dispose(toDispose);
label.element.remove();
if (finishEditing) {
editableData.onFinish(value, success);
}
});
const showInputBoxNotification = () => {
if (inputBox.isInputValid()) {
const message = editableData.validationMessage(inputBox.value);
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();
const toDispose = [
inputBox,
inputBox.onDidChange(value => {
label.setFile(joinPath(parent, value || ' '), labelOptions); // update label icon while typing!
}),
DOM.addStandardDisposableListener(inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: IKeyboardEvent) => {
if (e.equals(KeyCode.Enter)) {
if (inputBox.validate()) {
done(true, true);
}
} else if (e.equals(KeyCode.Escape)) {
done(false, true);
}
}),
DOM.addStandardDisposableListener(inputBox.inputElement, DOM.EventType.KEY_UP, (e: IKeyboardEvent) => {
showInputBoxNotification();
}),
DOM.addDisposableListener(inputBox.inputElement, DOM.EventType.BLUR, () => {
done(inputBox.isInputValid(), true);
}),
label,
styler
];
return toDisposable(() => {
done(false, false);
});
}
disposeElement(element: ITreeNode<ExplorerItem, FuzzyScore>, index: number, templateData: IFileTemplateData): void {
templateData.elementDisposable.dispose();
}
disposeCompressedElements(node: ITreeNode<ICompressedTreeNode<ExplorerItem>, FuzzyScore>, index: number, templateData: IFileTemplateData): void {
templateData.elementDisposable.dispose();
}
disposeTemplate(templateData: IFileTemplateData): void {
templateData.elementDisposable.dispose();
templateData.label.dispose();
}
getCompressedNavigationController(stat: ExplorerItem): ICompressedNavigationController | undefined {
return this.compressedNavigationControllers.get(stat);
}
// IAccessibilityProvider
getAriaLabel(element: ExplorerItem): string {
return element.name;
}
getAriaLevel(element: ExplorerItem): number {
// We need to comput aria level on our own since children of compact folders will otherwise have an incorrect level #107235
let depth = 0;
let parent = element.parent;
while (parent) {
parent = parent.parent;
depth++;
}
if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) {
depth = depth + 1;
}
return depth;
}
getActiveDescendantId(stat: ExplorerItem): string | undefined {
const compressedNavigationController = this.compressedNavigationControllers.get(stat);
return compressedNavigationController?.currentId;
}
dispose(): void {
this.configListener.dispose();
}
}
interface CachedParsedExpression {
original: glob.IExpression;
parsed: glob.ParsedExpression;
}
/**
* 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.
*/
export class FilesFilter implements ITreeFilter<ExplorerItem, FuzzyScore> {
private hiddenExpressionPerRoot: Map<string, CachedParsedExpression>;
private hiddenUris = new Set<URI>();
private editorsAffectingFilter = new Set<IEditorInput>();
private _onDidChange = new Emitter<void>();
private toDispose: IDisposable[] = [];
constructor(
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IExplorerService private readonly explorerService: IExplorerService,
@IEditorService private readonly editorService: IEditorService,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService
) {
this.hiddenExpressionPerRoot = new Map<string, CachedParsedExpression>();
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 && this.uriIdentityService.extUri.isEqualOrParent(e.resource, u)) {
// A filtered resource suddenly became visible since user opened an editor
shouldFire = true;
}
});
});
this.editorsAffectingFilter.forEach(e => {
if (!editors.includes(e)) {
// 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;
}
private updateConfiguration(): void {
let shouldFire = false;
this.contextService.getWorkspace().folders.forEach(folder => {
const configuration = this.configurationService.getValue<IFilesConfiguration>({ resource: folder.uri });
const excludesConfig: glob.IExpression = configuration?.files?.exclude || Object.create(null);
if (!shouldFire) {
const cached = this.hiddenExpressionPerRoot.get(folder.uri.toString());
shouldFire = !cached || !equals(cached.original, excludesConfig);
}
const excludesConfigCopy = deepClone(excludesConfig); // do not keep the config, as it gets mutated under our hoods
this.hiddenExpressionPerRoot.set(folder.uri.toString(), { original: excludesConfigCopy, parsed: glob.parse(excludesConfigCopy) });
});
if (shouldFire) {
this.editorsAffectingFilter.clear();
this.hiddenUris.clear();
this._onDidChange.fire();
}
}
filter(stat: ExplorerItem, parentVisibility: TreeVisibility): TreeFilterResult<FuzzyScore> {
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 {
stat.isExcluded = false;
if (parentVisibility === TreeVisibility.Hidden) {
stat.isExcluded = true;
return false;
}
if (this.explorerService.getEditableData(stat) || stat.isRoot) {
return true; // always visible
}
// Hide those that match Hidden Patterns
const cached = this.hiddenExpressionPerRoot.get(stat.root.resource.toString());
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) {
stat.isExcluded = true;
const editors = this.editorService.visibleEditors;
const editor = editors.find(e => e.resource && this.uriIdentityService.extUri.isEqualOrParent(e.resource, stat.resource));
if (editor) {
this.editorsAffectingFilter.add(editor);
return true; // Show all opened files and their parents
}
return false; // hidden through pattern
}
return true;
}
dispose(): void {
dispose(this.toDispose);
}
}
// Explorer Sorter
export class FileSorter implements ITreeSorter<ExplorerItem> {
constructor(
@IExplorerService private readonly explorerService: IExplorerService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService
) { }
compare(statA: ExplorerItem, statB: ExplorerItem): number {
// Do not sort roots
if (statA.isRoot) {
if (statB.isRoot) {
const workspaceA = this.contextService.getWorkspaceFolder(statA.resource);
const workspaceB = this.contextService.getWorkspaceFolder(statB.resource);
return workspaceA && workspaceB ? (workspaceA.index - workspaceB.index) : -1;
}
return -1;
}
if (statB.isRoot) {
return 1;
}
const sortOrder = this.explorerService.sortOrder;
// Sort Directories
switch (sortOrder) {
case 'type':
if (statA.isDirectory && !statB.isDirectory) {
return -1;
}
if (statB.isDirectory && !statA.isDirectory) {
return 1;
}
if (statA.isDirectory && statB.isDirectory) {
return compareFileNamesDefault(statA.name, statB.name);
}
break;
case 'filesFirst':
if (statA.isDirectory && !statB.isDirectory) {
return 1;
}
if (statB.isDirectory && !statA.isDirectory) {
return -1;
}
break;
case 'mixed':
break; // not sorting when "mixed" is on
default: /* 'default', 'modified' */
if (statA.isDirectory && !statB.isDirectory) {
return -1;
}
if (statB.isDirectory && !statA.isDirectory) {
return 1;
}
break;
}
// Sort Files
switch (sortOrder) {
case 'type':
return compareFileExtensionsDefault(statA.name, statB.name);
case 'modified':
if (statA.mtime !== statB.mtime) {
return (statA.mtime && statB.mtime && statA.mtime < statB.mtime) ? 1 : -1;
}
return compareFileNamesDefault(statA.name, statB.name);
default: /* 'default', 'mixed', 'filesFirst' */
return compareFileNamesDefault(statA.name, statB.name);
}
}
}
function getFileOverwriteConfirm(name: string): IConfirmation {
return {
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'
};
}
function getMultipleFilesOverwriteConfirm(files: URI[]): IConfirmation {
if (files.length > 1) {
return {
message: localize('confirmManyOverwrites', "The following {0} files and/or folders already exist in the destination folder. Do you want to replace them?", files.length),
detail: getFileNamesMessage(files) + '\n' + localize('irreversible', "This action is irreversible!"),
primaryButton: localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
type: 'warning'
};
}
return getFileOverwriteConfirm(basename(files[0]));
}
interface IWebkitDataTransfer {
items: IWebkitDataTransferItem[];
}
interface IWebkitDataTransferItem {
webkitGetAsEntry(): IWebkitDataTransferItemEntry;
}
interface IWebkitDataTransferItemEntry {
name: string | undefined;
isFile: boolean;
isDirectory: boolean;
file(resolve: (file: File) => void, reject: () => void): void;
createReader(): IWebkitDataTransferItemEntryReader;
}
interface IWebkitDataTransferItemEntryReader {
readEntries(resolve: (file: IWebkitDataTransferItemEntry[]) => void, reject: () => void): void
}
interface IUploadOperation {
filesTotal: number;
filesUploaded: number;
startTime: number;
bytesUploaded: number;
}
export class FileDragAndDrop implements ITreeDragAndDrop<ExplorerItem> {
private static readonly CONFIRM_DND_SETTING_KEY = 'explorer.confirmDragAndDrop';
private compressedDragOverElement: HTMLElement | undefined;
private compressedDropTargetDisposable: IDisposable = Disposable.None;
private toDispose: IDisposable[];
private dropEnabled = false;
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,
@IWorkingCopyFileService private workingCopyFileService: IWorkingCopyFileService,
@IHostService private hostService: IHostService,
@IWorkspaceEditingService private workspaceEditingService: IWorkspaceEditingService,
@IProgressService private readonly progressService: IProgressService,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService
) {
this.toDispose = [];
const updateDropEnablement = () => {
this.dropEnabled = this.configurationService.getValue('explorer.enableDragAndDrop');
};
updateDropEnablement();
this.toDispose.push(this.configurationService.onDidChangeConfiguration((e) => updateDropEnablement()));
}
onDragOver(data: IDragAndDropData, target: ExplorerItem | undefined, targetIndex: number | undefined, originalEvent: DragEvent): boolean | ITreeDragOverReaction {
if (!this.dropEnabled) {
return false;
}
// Compressed folders
if (target) {
const compressedTarget = FileDragAndDrop.getCompressedStatFromDragEvent(target, originalEvent);
if (compressedTarget) {
const iconLabelName = getIconLabelNameFromHTMLElement(originalEvent.target);
if (iconLabelName && iconLabelName.index < iconLabelName.count - 1) {
const result = this.handleDragOver(data, compressedTarget, targetIndex, originalEvent);
if (result) {
if (iconLabelName.element !== this.compressedDragOverElement) {
this.compressedDragOverElement = iconLabelName.element;
this.compressedDropTargetDisposable.dispose();
this.compressedDropTargetDisposable = toDisposable(() => {
iconLabelName.element.classList.remove('drop-target');
this.compressedDragOverElement = undefined;
});
iconLabelName.element.classList.add('drop-target');
}
return typeof result === 'boolean' ? result : { ...result, feedback: [] };
}
this.compressedDropTargetDisposable.dispose();
return false;
}
}
}
this.compressedDropTargetDisposable.dispose();
return this.handleDragOver(data, target, targetIndex, originalEvent);
}
private handleDragOver(data: IDragAndDropData, target: ExplorerItem | undefined, targetIndex: number | undefined, originalEvent: DragEvent): boolean | ITreeDragOverReaction {
const isCopy = originalEvent && ((originalEvent.ctrlKey && !isMacintosh) || (originalEvent.altKey && isMacintosh));
const isNative = data instanceof NativeDragAndDropData;
const effect = (isNative || isCopy) ? ListDragOverEffect.Copy : ListDragOverEffect.Move;
// Native DND
if (isNative) {
if (!containsDragType(originalEvent, DataTransfers.FILES, CodeDataTransfers.FILES)) {
return false;
}
}
// Other-Tree DND
else if (data instanceof ExternalElementsDragAndDropData) {
return false;
}
// In-Explorer DND
else {
const items = FileDragAndDrop.getStatsFromDragAndDropData(data as ElementsDragAndDropData<ExplorerItem, ExplorerItem[]>);
if (!target) {
// Dropping onto the empty area. Do not accept if items dragged are already
// children of the root unless we are copying the file
if (!isCopy && items.every(i => !!i.parent && i.parent.isRoot)) {
return false;
}
return { accept: true, bubble: TreeDragOverBubble.Down, effect, autoExpand: false };
}
if (!Array.isArray(items)) {
return false;
}
if (items.some((source) => {
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
}
if (this.uriIdentityService.extUri.isEqualOrParent(target.resource, source.resource)) {
return true; // Can not move a parent folder into one of its children
}
return false;
})) {
return false;
}
}
// All (target = model)
if (!target) {
return { accept: true, bubble: TreeDragOverBubble.Down, effect };
}
// 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;
}
getDragURI(element: ExplorerItem): string | null {
if (this.explorerService.isEditable(element)) {
return null;
}
return element.resource.toString();
}
getDragLabel(elements: ExplorerItem[], originalEvent: DragEvent): string | undefined {
if (elements.length === 1) {
const stat = FileDragAndDrop.getCompressedStatFromDragEvent(elements[0], originalEvent);
return stat.name;
}
return String(elements.length);
}
onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void {
const items = FileDragAndDrop.getStatsFromDragAndDropData(data as ElementsDragAndDropData<ExplorerItem, ExplorerItem[]>, originalEvent);
if (items && items.length && originalEvent.dataTransfer) {
// Apply some datatransfer types to allow for dragging the element outside of the application
this.instantiationService.invokeFunction(fillResourceDataTransfers, items, undefined, originalEvent);
// 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
const fileResources = items.filter(s => !s.isDirectory && s.resource.scheme === Schemas.file).map(r => r.resource.fsPath);
if (fileResources.length) {
originalEvent.dataTransfer.setData(CodeDataTransfers.FILES, JSON.stringify(fileResources));
}
}
}
drop(data: IDragAndDropData, target: ExplorerItem | undefined, targetIndex: number | undefined, originalEvent: DragEvent): void {
this.compressedDropTargetDisposable.dispose();
// Find compressed target
if (target) {
const compressedTarget = FileDragAndDrop.getCompressedStatFromDragEvent(target, originalEvent);
if (compressedTarget) {
target = compressedTarget;
}
}
// Find parent to add to
if (!target) {
target = this.explorerService.roots[this.explorerService.roots.length - 1];
}
if (!target.isDirectory && target.parent) {
target = target.parent;
}
if (target.isReadonly) {
return;