-
Notifications
You must be signed in to change notification settings - Fork 30k
/
Copy pathexplorerService.ts
398 lines (336 loc) · 13.8 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
/*---------------------------------------------------------------------------------------------
* 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 'vs/base/common/event';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { IExplorerService, IFilesConfiguration, SortOrder, IExplorerView } from 'vs/workbench/contrib/files/common/files';
import { ExplorerItem, ExplorerModel } from 'vs/workbench/contrib/files/common/explorerModel';
import { URI } from 'vs/base/common/uri';
import { FileOperationEvent, FileOperation, IFileService, FileChangesEvent, FILES_EXCLUDE_CONFIG, FileChangeType, IResolveFileOptions } from 'vs/platform/files/common/files';
import { dirname } from 'vs/base/common/resources';
import { memoize } from 'vs/base/common/decorators';
import { ResourceGlobMatcher } from 'vs/workbench/common/resources';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
import { IExpression } from 'vs/base/common/glob';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IEditableData } from 'vs/workbench/common/views';
import { EditorResourceAccessor } from 'vs/workbench/common/editor';
function getFileEventsExcludes(configurationService: IConfigurationService, root?: URI): IExpression {
const scope = root ? { resource: root } : undefined;
const configuration = scope ? configurationService.getValue<IFilesConfiguration>(scope) : configurationService.getValue<IFilesConfiguration>();
return configuration?.files?.exclude || Object.create(null);
}
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 _sortOrder: SortOrder;
private cutItems: ExplorerItem[] | undefined;
private view: IExplorerView | undefined;
private model: ExplorerModel;
constructor(
@IFileService private fileService: IFileService,
@IInstantiationService private instantiationService: IInstantiationService,
@IConfigurationService private configurationService: IConfigurationService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IClipboardService private clipboardService: IClipboardService,
@IEditorService private editorService: IEditorService,
) {
this._sortOrder = this.configurationService.getValue('explorer.sortOrder');
this.model = new ExplorerModel(this.contextService, this.fileService);
this.disposables.add(this.model);
this.disposables.add(this.fileService.onDidRunOperation(e => this.onDidRunOperation(e)));
this.disposables.add(this.fileService.onDidFilesChange(e => this.onDidFilesChange(e)));
this.disposables.add(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(this.configurationService.getValue<IFilesConfiguration>())));
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.refresh(true);
}
}
}));
this.disposables.add(this.model.onDidChangeRoots(() => {
if (this.view) {
this.view.setTreeInput();
}
}));
}
get roots(): ExplorerItem[] {
return this.model.roots;
}
get sortOrder(): SortOrder {
return this._sortOrder;
}
registerView(contextProvider: IExplorerView): void {
this.view = contextProvider;
}
getContext(respectMultiSelection: boolean): ExplorerItem[] {
if (!this.view) {
return [];
}
return this.view.getContext(respectMultiSelection);
}
// Memoized locals
@memoize private get fileEventsFilter(): ResourceGlobMatcher {
const fileEventsFilter = this.instantiationService.createInstance(
ResourceGlobMatcher,
(root?: URI) => getFileEventsExcludes(this.configurationService, root),
(event: IConfigurationChangeEvent) => event.affectsConfiguration(FILES_EXCLUDE_CONFIG)
);
this.disposables.add(fileEventsFilter);
return fileEventsFilter;
}
// IExplorerService methods
findClosest(resource: URI): ExplorerItem | null {
return this.model.findClosest(resource);
}
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);
await this.view.setEditable(stat, isEditing);
}
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.indexOf(item) >= 0;
}
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;
}
const fileStat = this.findClosest(resource);
if (fileStat) {
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.sortOrder === SortOrder.Modified };
const workspaceFolder = this.contextService.getWorkspaceFolder(resource);
if (workspaceFolder === null) {
return Promise.resolve(undefined);
}
const rootUri = workspaceFolder.uri;
const root = this.roots.find(r => r.resource.toString() === rootUri.toString())!;
try {
const stat = await this.fileService.resolve(rootUri, options);
// Convert to model
const modelStat = ExplorerItem.create(this.fileService, stat, undefined, options.resolveTo);
// Update Input with disk Stat
ExplorerItem.mergeLocalWithDisk(modelStat, root);
const item = root.find(resource);
await this.view.refresh(true, root);
// Select and Reveal
await this.view.selectResource(item ? item.resource : undefined, reveal);
} catch (error) {
root.isError = true;
await this.view.refresh(false, root);
}
}
async refresh(reveal = true): Promise<void> {
this.model.roots.forEach(r => r.forgetChildren());
if (this.view) {
await this.view.refresh(true);
const resource = EditorResourceAccessor.getOriginalUri(this.editorService.activeEditor);
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> {
// 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)
parents.forEach(async p => {
// We have to check if the parent is resolved #29177
const resolveMetadata = this.sortOrder === `modified`;
if (!p.isDirectoryResolved) {
const stat = await this.fileService.resolve(p.resource, { resolveMetadata });
if (stat) {
const modelStat = ExplorerItem.create(this.fileService, stat, p.parent);
ExplorerItem.mergeLocalWithDisk(modelStat, p);
}
}
const childElement = ExplorerItem.create(this.fileService, 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(false, 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);
// Handle Rename
if (oldParentResource.toString() === newParentResource.toString()) {
const modelElements = this.model.findAll(oldResource);
modelElements.forEach(async modelElement => {
// Rename File (Model)
modelElement.rename(newElement);
await this.view?.refresh(false, modelElement.parent);
});
}
// Handle Move
else {
const newParents = this.model.findAll(newParentResource);
const modelElements = this.model.findAll(oldResource);
if (newParents.length && modelElements.length) {
// Move in Model
modelElements.forEach(async (modelElement, index) => {
const oldParent = modelElement.parent;
modelElement.move(newParents[index]);
await this.view?.refresh(false, oldParent);
await this.view?.refresh(false, newParents[index]);
});
}
}
}
// Delete
else if (e.isOperation(FileOperation.DELETE)) {
const modelElements = this.model.findAll(e.resource);
modelElements.forEach(async element => {
if (element.parent) {
const parent = element.parent;
// Remove Element from Parent (Model)
parent.removeChild(element);
this.view?.focusNeighbourIfItemFocused(element);
// Refresh Parent (View)
await this.view?.refresh(false, parent);
}
});
}
}
private onDidFilesChange(e: FileChangesEvent): void {
// Check if an explorer refresh is necessary (delayed to give internal events a chance to react first)
// Note: there is no guarantee when the internal events are fired vs real ones. Code has to deal with the fact that one might
// be fired first over the other or not at all.
setTimeout(async () => {
// Filter to the ones we care
const shouldRefresh = () => {
e = this.filterToViewRelevantEvents(e);
// Handle added files/folders
const added = e.getAdded();
if (added.length) {
// Check added: Refresh if added file/folder is not part of resolved root and parent is part of it
const ignoredPaths: Set<string> = new Set();
for (let i = 0; i < added.length; i++) {
const change = added[i];
// Find parent
const parent = dirname(change.resource);
// Continue if parent was already determined as to be ignored
if (ignoredPaths.has(parent.toString())) {
continue;
}
// Compute if parent is visible and added file not yet part of it
const parentStat = this.model.findClosest(parent);
if (parentStat && parentStat.isDirectoryResolved && !this.model.findClosest(change.resource)) {
return true;
}
// Keep track of path that can be ignored for faster lookup
if (!parentStat || !parentStat.isDirectoryResolved) {
ignoredPaths.add(parent.toString());
}
}
}
// Handle deleted files/folders
const deleted = e.getDeleted();
if (deleted.length) {
// Check deleted: Refresh if deleted file/folder part of resolved root
for (let j = 0; j < deleted.length; j++) {
const del = deleted[j];
const item = this.model.findClosest(del.resource);
if (item && item.parent) {
return true;
}
}
}
// Handle updated files/folders if we sort by modified
if (this._sortOrder === SortOrder.Modified) {
const updated = e.getUpdated();
// Check updated: Refresh if updated file/folder part of resolved root
for (let j = 0; j < updated.length; j++) {
const upd = updated[j];
const item = this.model.findClosest(upd.resource);
if (item && item.parent) {
return true;
}
}
}
return false;
};
if (shouldRefresh()) {
await this.refresh(false);
}
}, ExplorerService.EXPLORER_FILE_CHANGES_REACT_DELAY);
}
private filterToViewRelevantEvents(e: FileChangesEvent): FileChangesEvent {
return e.filter(change => {
if (change.type === FileChangeType.UPDATED && this._sortOrder !== SortOrder.Modified) {
return false; // we only are about updated if we sort by modified time
}
if (!this.contextService.isInsideWorkspace(change.resource)) {
return false; // exclude changes for resources outside of workspace
}
if (this.fileEventsFilter.matches(change.resource)) {
return false; // excluded via files.exclude setting
}
return true;
});
}
private async onConfigurationUpdated(configuration: IFilesConfiguration, event?: IConfigurationChangeEvent): Promise<void> {
const configSortOrder = configuration?.explorer?.sortOrder || 'default';
if (this._sortOrder !== configSortOrder) {
const shouldRefresh = this._sortOrder !== undefined;
this._sortOrder = configSortOrder;
if (shouldRefresh) {
await this.refresh();
}
}
}
dispose(): void {
this.disposables.dispose();
}
}