-
Notifications
You must be signed in to change notification settings - Fork 29.4k
/
explorerService.ts
573 lines (500 loc) · 22.3 KB
/
explorerService.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event } from '../../../../base/common/event.js';
import { IWorkspaceContextService } from '../../../../platform/workspace/common/workspace.js';
import { DisposableStore } from '../../../../base/common/lifecycle.js';
import { IFilesConfiguration, ISortOrderConfiguration, SortOrder, LexicographicOptions } from '../common/files.js';
import { ExplorerItem, ExplorerModel } from '../common/explorerModel.js';
import { URI } from '../../../../base/common/uri.js';
import { FileOperationEvent, FileOperation, IFileService, FileChangesEvent, FileChangeType, IResolveFileOptions } from '../../../../platform/files/common/files.js';
import { dirname, basename } from '../../../../base/common/resources.js';
import { IConfigurationService, IConfigurationChangeEvent } from '../../../../platform/configuration/common/configuration.js';
import { IClipboardService } from '../../../../platform/clipboard/common/clipboardService.js';
import { IEditorService } from '../../../services/editor/common/editorService.js';
import { IEditableData } from '../../../common/views.js';
import { IUriIdentityService } from '../../../../platform/uriIdentity/common/uriIdentity.js';
import { IBulkEditService, ResourceFileEdit } from '../../../../editor/browser/services/bulkEditService.js';
import { UndoRedoSource } from '../../../../platform/undoRedo/common/undoRedo.js';
import { IExplorerView, IExplorerService } from './files.js';
import { IProgressService, ProgressLocation, IProgressCompositeOptions, IProgressOptions } from '../../../../platform/progress/common/progress.js';
import { CancellationTokenSource } from '../../../../base/common/cancellation.js';
import { RunOnceScheduler } from '../../../../base/common/async.js';
import { IHostService } from '../../../services/host/browser/host.js';
import { IExpression } from '../../../../base/common/glob.js';
import { ResourceGlobMatcher } from '../../../common/resources.js';
import { IFilesConfigurationService } from '../../../services/filesConfiguration/common/filesConfigurationService.js';
import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js';
export const UNDO_REDO_SOURCE = new UndoRedoSource();
export class ExplorerService implements IExplorerService {
declare readonly _serviceBrand: undefined;
private static readonly EXPLORER_FILE_CHANGES_REACT_DELAY = 500; // delay in ms to react to file changes to give our internal events a chance to react first
private readonly disposables = new DisposableStore();
private editable: { stat: ExplorerItem; data: IEditableData } | undefined;
private config: IFilesConfiguration['explorer'];
private cutItems: ExplorerItem[] | undefined;
private view: IExplorerView | undefined;
private model: ExplorerModel;
private onFileChangesScheduler: RunOnceScheduler;
private fileChangeEvents: FileChangesEvent[] = [];
private revealExcludeMatcher: ResourceGlobMatcher;
constructor(
@IFileService private fileService: IFileService,
@IConfigurationService private configurationService: IConfigurationService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IClipboardService private clipboardService: IClipboardService,
@IEditorService private editorService: IEditorService,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService,
@IBulkEditService private readonly bulkEditService: IBulkEditService,
@IProgressService private readonly progressService: IProgressService,
@IHostService hostService: IHostService,
@IFilesConfigurationService private readonly filesConfigurationService: IFilesConfigurationService,
@ITelemetryService private readonly telemetryService: ITelemetryService
) {
this.config = this.configurationService.getValue('explorer');
this.model = new ExplorerModel(this.contextService, this.uriIdentityService, this.fileService, this.configurationService, this.filesConfigurationService);
this.disposables.add(this.model);
this.disposables.add(this.fileService.onDidRunOperation(e => this.onDidRunOperation(e)));
this.onFileChangesScheduler = new RunOnceScheduler(async () => {
const events = this.fileChangeEvents;
this.fileChangeEvents = [];
// Filter to the ones we care
const types = [FileChangeType.DELETED];
if (this.config.sortOrder === SortOrder.Modified) {
types.push(FileChangeType.UPDATED);
}
let shouldRefresh = false;
// For DELETED and UPDATED events go through the explorer model and check if any of the items got affected
this.roots.forEach(r => {
if (this.view && !shouldRefresh) {
shouldRefresh = doesFileEventAffect(r, this.view, events, types);
}
});
// For ADDED events we need to go through all the events and check if the explorer is already aware of some of them
// Or if they affect not yet resolved parts of the explorer. If that is the case we will not refresh.
events.forEach(e => {
if (!shouldRefresh) {
for (const resource of e.rawAdded) {
const parent = this.model.findClosest(dirname(resource));
// Parent of the added resource is resolved and the explorer model is not aware of the added resource - we need to refresh
if (parent && !parent.getChild(basename(resource))) {
shouldRefresh = true;
break;
}
}
}
});
if (shouldRefresh) {
await this.refresh(false);
}
}, ExplorerService.EXPLORER_FILE_CHANGES_REACT_DELAY);
this.disposables.add(this.fileService.onDidFilesChange(e => {
this.fileChangeEvents.push(e);
// Don't mess with the file tree while in the process of editing. #112293
if (this.editable) {
return;
}
if (!this.onFileChangesScheduler.isScheduled()) {
this.onFileChangesScheduler.schedule();
}
}));
this.disposables.add(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(e)));
this.disposables.add(Event.any<{ scheme: string }>(this.fileService.onDidChangeFileSystemProviderRegistrations, this.fileService.onDidChangeFileSystemProviderCapabilities)(async e => {
let affected = false;
this.model.roots.forEach(r => {
if (r.resource.scheme === e.scheme) {
affected = true;
r.forgetChildren();
}
});
if (affected) {
if (this.view) {
await this.view.setTreeInput();
}
}
}));
this.disposables.add(this.model.onDidChangeRoots(() => {
this.view?.setTreeInput();
}));
// Refresh explorer when window gets focus to compensate for missing file events #126817
this.disposables.add(hostService.onDidChangeFocus(hasFocus => {
if (hasFocus) {
this.refresh(false);
}
}));
this.revealExcludeMatcher = new ResourceGlobMatcher(
(uri) => getRevealExcludes(configurationService.getValue<IFilesConfiguration>({ resource: uri })),
(event) => event.affectsConfiguration('explorer.autoRevealExclude'),
contextService, configurationService);
this.disposables.add(this.revealExcludeMatcher);
}
get roots(): ExplorerItem[] {
return this.model.roots;
}
get sortOrderConfiguration(): ISortOrderConfiguration {
return {
sortOrder: this.config.sortOrder,
lexicographicOptions: this.config.sortOrderLexicographicOptions,
reverse: this.config.sortOrderReverse,
};
}
registerView(contextProvider: IExplorerView): void {
this.view = contextProvider;
}
getContext(respectMultiSelection: boolean, ignoreNestedChildren: boolean = false): ExplorerItem[] {
if (!this.view) {
return [];
}
const items = new Set<ExplorerItem>(this.view.getContext(respectMultiSelection));
items.forEach(item => {
try {
if (respectMultiSelection && !ignoreNestedChildren && this.view?.isItemCollapsed(item) && item.nestedChildren) {
for (const child of item.nestedChildren) {
items.add(child);
}
}
} catch {
// We will error out trying to resolve collapsed nodes that have not yet been resolved.
// So we catch and ignore them in the multiSelect context
return;
}
});
return [...items];
}
async applyBulkEdit(edit: ResourceFileEdit[], options: { undoLabel: string; progressLabel: string; confirmBeforeUndo?: boolean; progressLocation?: ProgressLocation.Explorer | ProgressLocation.Window }): Promise<void> {
const cancellationTokenSource = new CancellationTokenSource();
const location = options.progressLocation ?? ProgressLocation.Window;
let progressOptions;
if (location === ProgressLocation.Window) {
progressOptions = {
location: location,
title: options.progressLabel,
cancellable: edit.length > 1,
} satisfies IProgressOptions;
} else {
progressOptions = {
location: location,
title: options.progressLabel,
cancellable: edit.length > 1,
delay: 500,
} satisfies IProgressCompositeOptions;
}
const promise = this.progressService.withProgress(progressOptions, async progress => {
await this.bulkEditService.apply(edit, {
undoRedoSource: UNDO_REDO_SOURCE,
label: options.undoLabel,
code: 'undoredo.explorerOperation',
progress,
token: cancellationTokenSource.token,
confirmBeforeUndo: options.confirmBeforeUndo
});
}, () => cancellationTokenSource.cancel());
await this.progressService.withProgress({ location: ProgressLocation.Explorer, delay: 500 }, () => promise);
cancellationTokenSource.dispose();
}
hasViewFocus(): boolean {
return !!this.view && this.view.hasFocus();
}
// IExplorerService methods
findClosest(resource: URI): ExplorerItem | null {
return this.model.findClosest(resource);
}
findClosestRoot(resource: URI): ExplorerItem | null {
const parentRoots = this.model.roots.filter(r => this.uriIdentityService.extUri.isEqualOrParent(resource, r.resource))
.sort((first, second) => second.resource.path.length - first.resource.path.length);
return parentRoots.length ? parentRoots[0] : null;
}
async setEditable(stat: ExplorerItem, data: IEditableData | null): Promise<void> {
if (!this.view) {
return;
}
if (!data) {
this.editable = undefined;
} else {
this.editable = { stat, data };
}
const isEditing = this.isEditable(stat);
try {
await this.view.setEditable(stat, isEditing);
} catch {
const parent = stat.parent;
type ExplorerViewEditableErrorData = {
parentIsDirectory: boolean | undefined;
isDirectory: boolean | undefined;
isReadonly: boolean | undefined;
parentIsReadonly: boolean | undefined;
parentIsExcluded: boolean | undefined;
isExcluded: boolean | undefined;
parentIsRoot: boolean | undefined;
isRoot: boolean | undefined;
parentHasNests: boolean | undefined;
hasNests: boolean | undefined;
};
type ExplorerViewEditableErrorClassification = {
owner: 'lramos15';
comment: 'Helps gain a broard understanding of why users are unable to edit files in the explorer';
parentIsDirectory: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Whether the parent of the editable element is a directory' };
isDirectory: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Whether the editable element is a directory' };
isReadonly: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Whether the editable element is readonly' };
parentIsReadonly: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Whether the parent of the editable element is readonly' };
parentIsExcluded: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Whether the parent of the editable element is excluded from being shown in the explorer' };
isExcluded: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Whether the editable element is excluded from being shown in the explorer' };
parentIsRoot: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Whether the parent of the editable element is a root' };
isRoot: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Whether the editable element is a root' };
parentHasNests: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Whether the parent of the editable element has nested children' };
hasNests: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Whether the editable element has nested children' };
};
const errorData = {
parentIsDirectory: parent?.isDirectory,
isDirectory: stat.isDirectory,
isReadonly: !!stat.isReadonly,
parentIsReadonly: !!parent?.isReadonly,
parentIsExcluded: parent?.isExcluded,
isExcluded: stat.isExcluded,
parentIsRoot: parent?.isRoot,
isRoot: stat.isRoot,
parentHasNests: parent?.hasNests,
hasNests: stat.hasNests,
};
this.telemetryService.publicLogError2<ExplorerViewEditableErrorData, ExplorerViewEditableErrorClassification>('explorerView.setEditableError', errorData);
return;
}
if (!this.editable && this.fileChangeEvents.length && !this.onFileChangesScheduler.isScheduled()) {
this.onFileChangesScheduler.schedule();
}
}
async setToCopy(items: ExplorerItem[], cut: boolean): Promise<void> {
const previouslyCutItems = this.cutItems;
this.cutItems = cut ? items : undefined;
await this.clipboardService.writeResources(items.map(s => s.resource));
this.view?.itemsCopied(items, cut, previouslyCutItems);
}
isCut(item: ExplorerItem): boolean {
return !!this.cutItems && this.cutItems.some(i => this.uriIdentityService.extUri.isEqual(i.resource, item.resource));
}
getEditable(): { stat: ExplorerItem; data: IEditableData } | undefined {
return this.editable;
}
getEditableData(stat: ExplorerItem): IEditableData | undefined {
return this.editable && this.editable.stat === stat ? this.editable.data : undefined;
}
isEditable(stat: ExplorerItem | undefined): boolean {
return !!this.editable && (this.editable.stat === stat || !stat);
}
async select(resource: URI, reveal?: boolean | string): Promise<void> {
if (!this.view) {
return;
}
// If file or parent matches exclude patterns, do not reveal unless reveal argument is 'force'
const ignoreRevealExcludes = reveal === 'force';
const fileStat = this.findClosest(resource);
if (fileStat) {
if (!this.shouldAutoRevealItem(fileStat, ignoreRevealExcludes)) {
return;
}
await this.view.selectResource(fileStat.resource, reveal);
return Promise.resolve(undefined);
}
// Stat needs to be resolved first and then revealed
const options: IResolveFileOptions = { resolveTo: [resource], resolveMetadata: this.config.sortOrder === SortOrder.Modified };
const root = this.findClosestRoot(resource);
if (!root) {
return undefined;
}
try {
const stat = await this.fileService.resolve(root.resource, options);
// Convert to model
const modelStat = ExplorerItem.create(this.fileService, this.configurationService, this.filesConfigurationService, stat, undefined, options.resolveTo);
// Update Input with disk Stat
ExplorerItem.mergeLocalWithDisk(modelStat, root);
const item = root.find(resource);
await this.view.refresh(true, root);
// Once item is resolved, check again if folder should be expanded
if (item && !this.shouldAutoRevealItem(item, ignoreRevealExcludes)) {
return;
}
await this.view.selectResource(item ? item.resource : undefined, reveal);
} catch (error) {
root.error = error;
await this.view.refresh(false, root);
}
}
async refresh(reveal = true): Promise<void> {
// Do not refresh the tree when it is showing temporary nodes (phantom elements)
if (this.view?.hasPhantomElements()) {
return;
}
this.model.roots.forEach(r => r.forgetChildren());
if (this.view) {
await this.view.refresh(true);
const resource = this.editorService.activeEditor?.resource;
const autoReveal = this.configurationService.getValue<IFilesConfiguration>().explorer.autoReveal;
if (reveal && resource && autoReveal) {
// We did a top level refresh, reveal the active file #67118
this.select(resource, autoReveal);
}
}
}
// File events
private async onDidRunOperation(e: FileOperationEvent): Promise<void> {
// When nesting, changes to one file in a folder may impact the rendered structure
// of all the folder's immediate children, thus a recursive refresh is needed.
// Ideally the tree would be able to recusively refresh just one level but that does not yet exist.
const shouldDeepRefresh = this.config.fileNesting.enabled;
// Add
if (e.isOperation(FileOperation.CREATE) || e.isOperation(FileOperation.COPY)) {
const addedElement = e.target;
const parentResource = dirname(addedElement.resource)!;
const parents = this.model.findAll(parentResource);
if (parents.length) {
// Add the new file to its parent (Model)
await Promise.all(parents.map(async p => {
// We have to check if the parent is resolved #29177
const resolveMetadata = this.config.sortOrder === `modified`;
if (!p.isDirectoryResolved) {
const stat = await this.fileService.resolve(p.resource, { resolveMetadata });
if (stat) {
const modelStat = ExplorerItem.create(this.fileService, this.configurationService, this.filesConfigurationService, stat, p.parent);
ExplorerItem.mergeLocalWithDisk(modelStat, p);
}
}
const childElement = ExplorerItem.create(this.fileService, this.configurationService, this.filesConfigurationService, addedElement, p.parent);
// Make sure to remove any previous version of the file if any
p.removeChild(childElement);
p.addChild(childElement);
// Refresh the Parent (View)
await this.view?.refresh(shouldDeepRefresh, p);
}));
}
}
// Move (including Rename)
else if (e.isOperation(FileOperation.MOVE)) {
const oldResource = e.resource;
const newElement = e.target;
const oldParentResource = dirname(oldResource);
const newParentResource = dirname(newElement.resource);
const modelElements = this.model.findAll(oldResource);
const sameParentMove = modelElements.every(e => !e.nestedParent) && this.uriIdentityService.extUri.isEqual(oldParentResource, newParentResource);
// Handle Rename
if (sameParentMove) {
await Promise.all(modelElements.map(async modelElement => {
// Rename File (Model)
modelElement.rename(newElement);
await this.view?.refresh(shouldDeepRefresh, modelElement.parent);
}));
}
// Handle Move
else {
const newParents = this.model.findAll(newParentResource);
if (newParents.length && modelElements.length) {
// Move in Model
await Promise.all(modelElements.map(async (modelElement, index) => {
const oldParent = modelElement.parent;
const oldNestedParent = modelElement.nestedParent;
modelElement.move(newParents[index]);
if (oldNestedParent) {
await this.view?.refresh(false, oldNestedParent);
}
await this.view?.refresh(false, oldParent);
await this.view?.refresh(shouldDeepRefresh, newParents[index]);
}));
}
}
}
// Delete
else if (e.isOperation(FileOperation.DELETE)) {
const modelElements = this.model.findAll(e.resource);
await Promise.all(modelElements.map(async modelElement => {
if (modelElement.parent) {
// Remove Element from Parent (Model)
const parent = modelElement.parent;
parent.removeChild(modelElement);
this.view?.focusNext();
const oldNestedParent = modelElement.nestedParent;
if (oldNestedParent) {
oldNestedParent.removeChild(modelElement);
await this.view?.refresh(false, oldNestedParent);
}
// Refresh Parent (View)
await this.view?.refresh(shouldDeepRefresh, parent);
if (this.view?.getFocus().length === 0) {
this.view?.focusLast();
}
}
}));
}
}
// Check if an item matches a explorer.autoRevealExclude pattern
private shouldAutoRevealItem(item: ExplorerItem | undefined, ignore: boolean): boolean {
if (item === undefined || ignore) {
return true;
}
if (this.revealExcludeMatcher.matches(item.resource, name => !!(item.parent && item.parent.getChild(name)))) {
return false;
}
const root = item.root;
let currentItem = item.parent;
while (currentItem !== root) {
if (currentItem === undefined) {
return true;
}
if (this.revealExcludeMatcher.matches(currentItem.resource)) {
return false;
}
currentItem = currentItem.parent;
}
return true;
}
private async onConfigurationUpdated(event: IConfigurationChangeEvent): Promise<void> {
if (!event.affectsConfiguration('explorer')) {
return;
}
let shouldRefresh = false;
if (event.affectsConfiguration('explorer.fileNesting')) {
shouldRefresh = true;
}
const configuration = this.configurationService.getValue<IFilesConfiguration>();
const configSortOrder = configuration?.explorer?.sortOrder || SortOrder.Default;
if (this.config.sortOrder !== configSortOrder) {
shouldRefresh = this.config.sortOrder !== undefined;
}
const configLexicographicOptions = configuration?.explorer?.sortOrderLexicographicOptions || LexicographicOptions.Default;
if (this.config.sortOrderLexicographicOptions !== configLexicographicOptions) {
shouldRefresh = shouldRefresh || this.config.sortOrderLexicographicOptions !== undefined;
}
const sortOrderReverse = configuration?.explorer?.sortOrderReverse || false;
if (this.config.sortOrderReverse !== sortOrderReverse) {
shouldRefresh = shouldRefresh || this.config.sortOrderReverse !== undefined;
}
this.config = configuration.explorer;
if (shouldRefresh) {
await this.refresh();
}
}
dispose(): void {
this.disposables.dispose();
}
}
function doesFileEventAffect(item: ExplorerItem, view: IExplorerView, events: FileChangesEvent[], types: FileChangeType[]): boolean {
for (const [_name, child] of item.children) {
if (view.isItemVisible(child)) {
if (events.some(e => e.contains(child.resource, ...types))) {
return true;
}
if (child.isDirectory && child.isDirectoryResolved) {
if (doesFileEventAffect(child, view, events, types)) {
return true;
}
}
}
}
return false;
}
function getRevealExcludes(configuration: IFilesConfiguration): IExpression {
const revealExcludes = configuration && configuration.explorer && configuration.explorer.autoRevealExclude;
if (!revealExcludes) {
return {};
}
return revealExcludes;
}