@theia/filesystem 1.53.0-next.55 → 1.53.0-next.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +30 -30
  2. package/package.json +3 -3
  3. package/src/browser/breadcrumbs/filepath-breadcrumb.ts +43 -43
  4. package/src/browser/breadcrumbs/filepath-breadcrumbs-container.ts +65 -65
  5. package/src/browser/breadcrumbs/filepath-breadcrumbs-contribution.ts +129 -129
  6. package/src/browser/download/file-download-command-contribution.ts +83 -83
  7. package/src/browser/download/file-download-frontend-module.ts +25 -25
  8. package/src/browser/download/file-download-service.ts +179 -179
  9. package/src/browser/file-dialog/file-dialog-container.ts +67 -67
  10. package/src/browser/file-dialog/file-dialog-hidden-files-renderer.tsx +59 -59
  11. package/src/browser/file-dialog/file-dialog-model.ts +96 -96
  12. package/src/browser/file-dialog/file-dialog-module.ts +44 -44
  13. package/src/browser/file-dialog/file-dialog-service.ts +99 -99
  14. package/src/browser/file-dialog/file-dialog-tree-filters-renderer.tsx +100 -100
  15. package/src/browser/file-dialog/file-dialog-tree.ts +89 -89
  16. package/src/browser/file-dialog/file-dialog-widget.ts +75 -75
  17. package/src/browser/file-dialog/file-dialog.ts +434 -434
  18. package/src/browser/file-dialog/index.ts +20 -20
  19. package/src/browser/file-resource.spec.ts +255 -255
  20. package/src/browser/file-resource.ts +402 -402
  21. package/src/browser/file-selection.ts +44 -44
  22. package/src/browser/file-service.ts +1845 -1845
  23. package/src/browser/file-tree/file-tree-container.ts +36 -36
  24. package/src/browser/file-tree/file-tree-decorator-adapter.ts +159 -159
  25. package/src/browser/file-tree/file-tree-label-provider.ts +53 -53
  26. package/src/browser/file-tree/file-tree-model.ts +212 -212
  27. package/src/browser/file-tree/file-tree-widget.tsx +327 -327
  28. package/src/browser/file-tree/file-tree.ts +183 -183
  29. package/src/browser/file-tree/index.ts +22 -22
  30. package/src/browser/file-upload-service.ts +547 -547
  31. package/src/browser/filesystem-frontend-contribution.ts +396 -396
  32. package/src/browser/filesystem-frontend-module.ts +77 -77
  33. package/src/browser/filesystem-preferences.ts +139 -139
  34. package/src/browser/filesystem-saveable-service.ts +138 -138
  35. package/src/browser/filesystem-watcher-error-handler.ts +60 -60
  36. package/src/browser/index.ts +21 -21
  37. package/src/browser/location/index.ts +18 -18
  38. package/src/browser/location/location-renderer.tsx +406 -406
  39. package/src/browser/location/location-service.ts +22 -22
  40. package/src/browser/remote-file-service-contribution.ts +38 -38
  41. package/src/browser/style/file-dialog.css +208 -208
  42. package/src/browser/style/file-icons.css +64 -64
  43. package/src/browser/style/filepath-breadcrumbs.css +20 -20
  44. package/src/browser/style/index.css +36 -36
  45. package/src/browser-only/browser-only-filesystem-frontend-module.ts +38 -38
  46. package/src/browser-only/browser-only-filesystem-provider-server.ts +32 -32
  47. package/src/browser-only/browserfs-filesystem-initialization.ts +61 -61
  48. package/src/browser-only/browserfs-filesystem-provider.ts +462 -462
  49. package/src/common/delegating-file-system-provider.ts +226 -226
  50. package/src/common/download/README.md +30 -30
  51. package/src/common/download/file-download-data.ts +27 -27
  52. package/src/common/file-upload.ts +17 -17
  53. package/src/common/files.spec.ts +51 -51
  54. package/src/common/files.ts +997 -997
  55. package/src/common/filesystem-utils.spec.ts +411 -411
  56. package/src/common/filesystem-utils.ts +64 -64
  57. package/src/common/filesystem-watcher-protocol.ts +96 -96
  58. package/src/common/filesystem.ts +43 -43
  59. package/src/common/index.ts +18 -18
  60. package/src/common/io.ts +150 -150
  61. package/src/common/remote-file-system-provider.ts +549 -549
  62. package/src/electron-browser/file-dialog/electron-file-dialog-module.ts +24 -24
  63. package/src/electron-browser/file-dialog/electron-file-dialog-service.ts +165 -165
  64. package/src/electron-browser/preload.ts +31 -31
  65. package/src/electron-common/electron-api.ts +55 -55
  66. package/src/electron-main/electron-api-main.ts +78 -78
  67. package/src/electron-main/electron-main-module.ts +23 -23
  68. package/src/node/disk-file-system-provider.spec.ts +142 -142
  69. package/src/node/disk-file-system-provider.ts +915 -915
  70. package/src/node/download/directory-archiver.spec.ts +104 -104
  71. package/src/node/download/directory-archiver.ts +126 -126
  72. package/src/node/download/file-download-backend-module.ts +32 -32
  73. package/src/node/download/file-download-cache.ts +88 -88
  74. package/src/node/download/file-download-endpoint.ts +63 -63
  75. package/src/node/download/file-download-handler.ts +304 -304
  76. package/src/node/download/test/mock-directory-archiver.ts +30 -30
  77. package/src/node/file-change-collection.spec.ts +110 -110
  78. package/src/node/file-change-collection.ts +78 -78
  79. package/src/node/filesystem-backend-module.ts +140 -140
  80. package/src/node/filesystem-watcher-client.ts +72 -72
  81. package/src/node/filesystem-watcher-dispatcher.ts +82 -82
  82. package/src/node/node-file-upload-service.ts +80 -80
  83. package/src/node/nsfw-watcher/index.ts +45 -45
  84. package/src/node/nsfw-watcher/nsfw-filesystem-service.ts +481 -481
  85. package/src/node/nsfw-watcher/nsfw-filesystem-watcher.spec.ts +182 -182
  86. package/src/node/nsfw-watcher/nsfw-options.ts +23 -23
  87. package/src/typings/dom.webkit.d.ts +77 -77
  88. package/src/typings/mv/index.d.ts +21 -21
  89. package/src/typings/nsfw/index.d.ts +18 -18
  90. package/src/typings/trash/index.d.ts +20 -20
@@ -1,396 +1,396 @@
1
- // *****************************************************************************
2
- // Copyright (C) 2018 TypeFox and others.
3
- //
4
- // This program and the accompanying materials are made available under the
5
- // terms of the Eclipse Public License v. 2.0 which is available at
6
- // http://www.eclipse.org/legal/epl-2.0.
7
- //
8
- // This Source Code may also be made available under the following Secondary
9
- // Licenses when the conditions for such availability set forth in the Eclipse
10
- // Public License v. 2.0 are satisfied: GNU General Public License, version 2
11
- // with the GNU Classpath Exception which is available at
12
- // https://www.gnu.org/software/classpath/license.html.
13
- //
14
- // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
15
- // *****************************************************************************
16
-
17
- import { nls } from '@theia/core';
18
- import {
19
- ApplicationShell,
20
- CommonCommands,
21
- CorePreferences,
22
- ExpandableTreeNode,
23
- FrontendApplication,
24
- FrontendApplicationContribution,
25
- NavigatableWidget, NavigatableWidgetOptions,
26
- OpenerService,
27
- Saveable,
28
- StatefulWidget,
29
- WidgetManager,
30
- open
31
- } from '@theia/core/lib/browser';
32
- import { MimeService } from '@theia/core/lib/browser/mime-service';
33
- import { TreeWidgetSelection } from '@theia/core/lib/browser/tree/tree-widget-selection';
34
- import { Emitter, MaybePromise, SelectionService, isCancelled } from '@theia/core/lib/common';
35
- import { Command, CommandContribution, CommandRegistry } from '@theia/core/lib/common/command';
36
- import { Deferred } from '@theia/core/lib/common/promise-util';
37
- import URI from '@theia/core/lib/common/uri';
38
- import { environment } from '@theia/core/shared/@theia/application-package/lib/environment';
39
- import { inject, injectable } from '@theia/core/shared/inversify';
40
- import { UserWorkingDirectoryProvider } from '@theia/core/lib/browser/user-working-directory-provider';
41
- import { FileChangeType, FileChangesEvent, FileOperation } from '../common/files';
42
- import { FileDialogService, SaveFileDialogProps } from './file-dialog';
43
- import { FileSelection } from './file-selection';
44
- import { FileService, UserFileOperationEvent } from './file-service';
45
- import { FileUploadResult, FileUploadService } from './file-upload-service';
46
- import { FileSystemPreferences } from './filesystem-preferences';
47
-
48
- export namespace FileSystemCommands {
49
-
50
- export const UPLOAD = Command.toLocalizedCommand({
51
- id: 'file.upload',
52
- category: CommonCommands.FILE_CATEGORY,
53
- label: 'Upload Files...'
54
- }, 'theia/filesystem/uploadFiles', CommonCommands.FILE_CATEGORY_KEY);
55
-
56
- }
57
-
58
- export interface NavigatableWidgetMoveSnapshot {
59
- dirty?: object,
60
- view?: object
61
- }
62
-
63
- @injectable()
64
- export class FileSystemFrontendContribution implements FrontendApplicationContribution, CommandContribution {
65
-
66
- @inject(ApplicationShell)
67
- protected readonly shell: ApplicationShell;
68
-
69
- @inject(WidgetManager)
70
- protected readonly widgetManager: WidgetManager;
71
-
72
- @inject(MimeService)
73
- protected readonly mimeService: MimeService;
74
-
75
- @inject(FileSystemPreferences)
76
- protected readonly preferences: FileSystemPreferences;
77
-
78
- @inject(CorePreferences)
79
- protected readonly corePreferences: CorePreferences;
80
-
81
- @inject(SelectionService)
82
- protected readonly selectionService: SelectionService;
83
-
84
- @inject(FileUploadService)
85
- protected readonly uploadService: FileUploadService;
86
-
87
- @inject(FileService)
88
- protected readonly fileService: FileService;
89
-
90
- @inject(FileDialogService)
91
- protected readonly fileDialogService: FileDialogService;
92
-
93
- @inject(OpenerService)
94
- protected readonly openerService: OpenerService;
95
-
96
- @inject(UserWorkingDirectoryProvider)
97
- protected readonly workingDirectory: UserWorkingDirectoryProvider;
98
-
99
- protected onDidChangeEditorFileEmitter = new Emitter<{ editor: NavigatableWidget, type: FileChangeType }>();
100
- readonly onDidChangeEditorFile = this.onDidChangeEditorFileEmitter.event;
101
-
102
- protected readonly userOperations = new Map<number, Deferred<void>>();
103
- protected queueUserOperation(event: UserFileOperationEvent): void {
104
- const moveOperation = new Deferred<void>();
105
- this.userOperations.set(event.correlationId, moveOperation);
106
- this.run(() => moveOperation.promise);
107
- }
108
- protected resolveUserOperation(event: UserFileOperationEvent): void {
109
- const operation = this.userOperations.get(event.correlationId);
110
- if (operation) {
111
- this.userOperations.delete(event.correlationId);
112
- operation.resolve();
113
- }
114
- }
115
-
116
- initialize(): void {
117
- this.fileService.onDidFilesChange(event => this.run(() => this.updateWidgets(event)));
118
- this.fileService.onWillRunUserOperation(event => {
119
- this.queueUserOperation(event);
120
- event.waitUntil(this.runEach((uri, widget) => this.pushMove(uri, widget, event)));
121
- });
122
- this.fileService.onDidFailUserOperation(event => event.waitUntil((async () => {
123
- await this.runEach((uri, widget) => this.revertMove(uri, widget, event));
124
- this.resolveUserOperation(event);
125
- })()));
126
- this.fileService.onDidRunUserOperation(event => event.waitUntil((async () => {
127
- await this.runEach((uri, widget) => this.applyMove(uri, widget, event));
128
- this.resolveUserOperation(event);
129
- })()));
130
- this.uploadService.onDidUpload(files => {
131
- this.doHandleUpload(files);
132
- });
133
- }
134
-
135
- onStart?(app: FrontendApplication): MaybePromise<void> {
136
- this.updateAssociations();
137
- this.preferences.onPreferenceChanged(e => {
138
- if (e.preferenceName === 'files.associations') {
139
- this.updateAssociations();
140
- }
141
- });
142
- }
143
-
144
- registerCommands(commands: CommandRegistry): void {
145
- commands.registerCommand(FileSystemCommands.UPLOAD, {
146
- isEnabled: (...args: unknown[]) => {
147
- const selection = this.getSelection(...args);
148
- return !!selection && !environment.electron.is();
149
- },
150
- isVisible: () => !environment.electron.is(),
151
- execute: (...args: unknown[]) => {
152
- const selection = this.getSelection(...args);
153
- if (selection) {
154
- return this.upload(selection);
155
- }
156
- }
157
- });
158
- commands.registerCommand(CommonCommands.NEW_FILE, {
159
- execute: (...args: unknown[]) => {
160
- this.handleNewFileCommand(args);
161
- }
162
- });
163
- }
164
-
165
- protected async upload(selection: FileSelection): Promise<FileUploadResult | undefined> {
166
- try {
167
- const source = TreeWidgetSelection.getSource(this.selectionService.selection);
168
- const fileUploadResult = await this.uploadService.upload(selection.fileStat.isDirectory ? selection.fileStat.resource : selection.fileStat.resource.parent);
169
- if (ExpandableTreeNode.is(selection) && source) {
170
- await source.model.expandNode(selection);
171
- }
172
- return fileUploadResult;
173
- } catch (e) {
174
- if (!isCancelled(e)) {
175
- console.error(e);
176
- }
177
- }
178
- }
179
-
180
- protected async doHandleUpload(uploads: string[]): Promise<void> {
181
- // Only handle single file uploads
182
- if (uploads.length === 1) {
183
- const uri = new URI(uploads[0]);
184
- // Close all existing widgets for this URI
185
- const widgets = this.shell.widgets.filter(widget => NavigatableWidget.getUri(widget)?.isEqual(uri));
186
- await this.shell.closeMany(widgets, {
187
- // Don't ask to save the file if it's dirty
188
- // The user has already confirmed the file overwrite
189
- save: false
190
- });
191
- // Open a new editor for this URI
192
- open(this.openerService, uri);
193
- }
194
- }
195
-
196
- /**
197
- * Opens a save dialog to create a new file.
198
- *
199
- * @param args The first argument is the name of the new file. The second argument is the parent directory URI.
200
- */
201
- protected async handleNewFileCommand(args: unknown[]): Promise<void> {
202
- const fileName = (args !== undefined && typeof args[0] === 'string') ? args[0] : undefined;
203
- const title = nls.localizeByDefault('Create File');
204
- const props: SaveFileDialogProps = { title, saveLabel: title, inputValue: fileName };
205
-
206
- const dirUri = (args[1] instanceof URI) ? args[1] : await this.workingDirectory.getUserWorkingDir();
207
- const directory = await this.fileService.resolve(dirUri);
208
-
209
- const filePath = await this.fileDialogService.showSaveDialog(props, directory.isDirectory ? directory : undefined);
210
- if (filePath) {
211
- const file = await this.fileService.createFile(filePath);
212
- open(this.openerService, file.resource);
213
- }
214
- }
215
-
216
- protected getSelection(...args: unknown[]): FileSelection | undefined {
217
- const { selection } = this.selectionService;
218
- return this.toSelection(args[0]) ?? (Array.isArray(selection) ? selection.find(FileSelection.is) : this.toSelection(selection));
219
- };
220
-
221
- protected toSelection(arg: unknown): FileSelection | undefined {
222
- return FileSelection.is(arg) ? arg : undefined;
223
- }
224
-
225
- protected pendingOperation = Promise.resolve();
226
- protected run(operation: () => MaybePromise<void>): Promise<void> {
227
- return this.pendingOperation = this.pendingOperation.then(async () => {
228
- try {
229
- await operation();
230
- } catch (e) {
231
- console.error(e);
232
- }
233
- });
234
- }
235
-
236
- protected async runEach(participant: (resourceUri: URI, widget: NavigatableWidget) => Promise<void>): Promise<void> {
237
- const promises: Promise<void>[] = [];
238
- for (const [resourceUri, widget] of NavigatableWidget.get(this.shell.widgets)) {
239
- promises.push(participant(resourceUri, widget));
240
- }
241
- await Promise.all(promises);
242
- }
243
-
244
- protected readonly moveSnapshots = new Map<string, NavigatableWidgetMoveSnapshot>();
245
-
246
- protected popMoveSnapshot(resourceUri: URI): NavigatableWidgetMoveSnapshot | undefined {
247
- const snapshotKey = resourceUri.toString();
248
- const snapshot = this.moveSnapshots.get(snapshotKey);
249
- if (snapshot) {
250
- this.moveSnapshots.delete(snapshotKey);
251
- }
252
- return snapshot;
253
- }
254
-
255
- protected applyMoveSnapshot(widget: NavigatableWidget, snapshot: NavigatableWidgetMoveSnapshot | undefined): void {
256
- if (!snapshot) {
257
- return undefined;
258
- }
259
- if (snapshot.dirty) {
260
- const saveable = Saveable.get(widget);
261
- if (saveable && saveable.applySnapshot) {
262
- saveable.applySnapshot(snapshot.dirty);
263
- }
264
- }
265
- if (snapshot.view && StatefulWidget.is(widget)) {
266
- widget.restoreState(snapshot.view);
267
- }
268
- }
269
-
270
- protected async pushMove(resourceUri: URI, widget: NavigatableWidget, event: UserFileOperationEvent): Promise<void> {
271
- const newResourceUri = this.createMoveToUri(resourceUri, widget, event);
272
- if (!newResourceUri) {
273
- return;
274
- }
275
- const snapshot: NavigatableWidgetMoveSnapshot = {};
276
- const saveable = Saveable.get(widget);
277
- if (StatefulWidget.is(widget)) {
278
- snapshot.view = widget.storeState();
279
- }
280
- if (saveable && saveable.dirty) {
281
- if (saveable.createSnapshot) {
282
- snapshot.dirty = saveable.createSnapshot();
283
- }
284
- if (saveable.revert) {
285
- await saveable.revert({ soft: true });
286
- }
287
- }
288
- this.moveSnapshots.set(newResourceUri.toString(), snapshot);
289
- }
290
-
291
- protected async revertMove(resourceUri: URI, widget: NavigatableWidget, event: UserFileOperationEvent): Promise<void> {
292
- const newResourceUri = this.createMoveToUri(resourceUri, widget, event);
293
- if (!newResourceUri) {
294
- return;
295
- }
296
- const snapshot = this.popMoveSnapshot(newResourceUri);
297
- this.applyMoveSnapshot(widget, snapshot);
298
- }
299
-
300
- protected async applyMove(resourceUri: URI, widget: NavigatableWidget, event: UserFileOperationEvent): Promise<void> {
301
- const newResourceUri = this.createMoveToUri(resourceUri, widget, event);
302
- if (!newResourceUri) {
303
- return;
304
- }
305
-
306
- const snapshot = this.popMoveSnapshot(newResourceUri);
307
-
308
- const description = this.widgetManager.getDescription(widget);
309
- if (!description) {
310
- return;
311
- }
312
- const { factoryId, options } = description;
313
- if (!NavigatableWidgetOptions.is(options)) {
314
- return;
315
- }
316
-
317
- const newWidget = await this.widgetManager.getOrCreateWidget<NavigatableWidget>(factoryId, <NavigatableWidgetOptions>{
318
- ...options,
319
- uri: newResourceUri.toString()
320
- });
321
- this.applyMoveSnapshot(newWidget, snapshot);
322
- const area = this.shell.getAreaFor(widget) || 'main';
323
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
324
- const pending: Promise<any>[] = [this.shell.addWidget(newWidget, {
325
- area, ref: widget
326
- })];
327
- if (this.shell.activeWidget === widget) {
328
- pending.push(this.shell.activateWidget(newWidget.id));
329
- } else if (widget.isVisible) {
330
- pending.push(this.shell.revealWidget(newWidget.id));
331
- }
332
- pending.push(this.shell.closeWidget(widget.id, { save: false }));
333
- await Promise.all(pending);
334
- }
335
-
336
- protected createMoveToUri(resourceUri: URI, widget: NavigatableWidget, event: UserFileOperationEvent): URI | undefined {
337
- if (event.operation !== FileOperation.MOVE) {
338
- return undefined;
339
- }
340
- const path = event.source?.relative(resourceUri);
341
- const targetUri = path && event.target.resolve(path);
342
- return targetUri && widget.createMoveToUri(targetUri);
343
- }
344
-
345
- protected readonly deletedSuffix = `(${nls.localizeByDefault('Deleted')})`;
346
- protected async updateWidgets(event: FileChangesEvent): Promise<void> {
347
- if (!event.gotDeleted() && !event.gotAdded()) {
348
- return;
349
- }
350
- const dirty = new Set<string>();
351
- const toClose = new Map<string, NavigatableWidget[]>();
352
- for (const [uri, widget] of NavigatableWidget.get(this.shell.widgets)) {
353
- this.updateWidget(uri, widget, event, { dirty, toClose: toClose });
354
- }
355
- if (this.corePreferences['workbench.editor.closeOnFileDelete']) {
356
- const doClose = [];
357
- for (const [uri, widgets] of toClose.entries()) {
358
- if (!dirty.has(uri)) {
359
- doClose.push(...widgets);
360
- }
361
- }
362
- await this.shell.closeMany(doClose);
363
- }
364
- }
365
- protected updateWidget(uri: URI, widget: NavigatableWidget, event: FileChangesEvent, { dirty, toClose }: {
366
- dirty: Set<string>;
367
- toClose: Map<string, NavigatableWidget[]>
368
- }): void {
369
- const label = widget.title.label;
370
- const deleted = label.endsWith(this.deletedSuffix);
371
- if (event.contains(uri, FileChangeType.DELETED)) {
372
- const uriString = uri.toString();
373
- if (Saveable.isDirty(widget)) {
374
- dirty.add(uriString);
375
- }
376
- if (!deleted) {
377
- widget.title.label += this.deletedSuffix;
378
- this.onDidChangeEditorFileEmitter.fire({ editor: widget, type: FileChangeType.DELETED });
379
- }
380
- const widgets = toClose.get(uriString) || [];
381
- widgets.push(widget);
382
- toClose.set(uriString, widgets);
383
- } else if (event.contains(uri, FileChangeType.ADDED)) {
384
- if (deleted) {
385
- widget.title.label = widget.title.label.substring(0, label.length - this.deletedSuffix.length);
386
- this.onDidChangeEditorFileEmitter.fire({ editor: widget, type: FileChangeType.ADDED });
387
- }
388
- }
389
- }
390
-
391
- protected updateAssociations(): void {
392
- const fileAssociations = this.preferences['files.associations'];
393
- const mimeAssociations = Object.keys(fileAssociations).map(filepattern => ({ id: fileAssociations[filepattern], filepattern }));
394
- this.mimeService.setAssociations(mimeAssociations);
395
- }
396
- }
1
+ // *****************************************************************************
2
+ // Copyright (C) 2018 TypeFox and others.
3
+ //
4
+ // This program and the accompanying materials are made available under the
5
+ // terms of the Eclipse Public License v. 2.0 which is available at
6
+ // http://www.eclipse.org/legal/epl-2.0.
7
+ //
8
+ // This Source Code may also be made available under the following Secondary
9
+ // Licenses when the conditions for such availability set forth in the Eclipse
10
+ // Public License v. 2.0 are satisfied: GNU General Public License, version 2
11
+ // with the GNU Classpath Exception which is available at
12
+ // https://www.gnu.org/software/classpath/license.html.
13
+ //
14
+ // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
15
+ // *****************************************************************************
16
+
17
+ import { nls } from '@theia/core';
18
+ import {
19
+ ApplicationShell,
20
+ CommonCommands,
21
+ CorePreferences,
22
+ ExpandableTreeNode,
23
+ FrontendApplication,
24
+ FrontendApplicationContribution,
25
+ NavigatableWidget, NavigatableWidgetOptions,
26
+ OpenerService,
27
+ Saveable,
28
+ StatefulWidget,
29
+ WidgetManager,
30
+ open
31
+ } from '@theia/core/lib/browser';
32
+ import { MimeService } from '@theia/core/lib/browser/mime-service';
33
+ import { TreeWidgetSelection } from '@theia/core/lib/browser/tree/tree-widget-selection';
34
+ import { Emitter, MaybePromise, SelectionService, isCancelled } from '@theia/core/lib/common';
35
+ import { Command, CommandContribution, CommandRegistry } from '@theia/core/lib/common/command';
36
+ import { Deferred } from '@theia/core/lib/common/promise-util';
37
+ import URI from '@theia/core/lib/common/uri';
38
+ import { environment } from '@theia/core/shared/@theia/application-package/lib/environment';
39
+ import { inject, injectable } from '@theia/core/shared/inversify';
40
+ import { UserWorkingDirectoryProvider } from '@theia/core/lib/browser/user-working-directory-provider';
41
+ import { FileChangeType, FileChangesEvent, FileOperation } from '../common/files';
42
+ import { FileDialogService, SaveFileDialogProps } from './file-dialog';
43
+ import { FileSelection } from './file-selection';
44
+ import { FileService, UserFileOperationEvent } from './file-service';
45
+ import { FileUploadResult, FileUploadService } from './file-upload-service';
46
+ import { FileSystemPreferences } from './filesystem-preferences';
47
+
48
+ export namespace FileSystemCommands {
49
+
50
+ export const UPLOAD = Command.toLocalizedCommand({
51
+ id: 'file.upload',
52
+ category: CommonCommands.FILE_CATEGORY,
53
+ label: 'Upload Files...'
54
+ }, 'theia/filesystem/uploadFiles', CommonCommands.FILE_CATEGORY_KEY);
55
+
56
+ }
57
+
58
+ export interface NavigatableWidgetMoveSnapshot {
59
+ dirty?: object,
60
+ view?: object
61
+ }
62
+
63
+ @injectable()
64
+ export class FileSystemFrontendContribution implements FrontendApplicationContribution, CommandContribution {
65
+
66
+ @inject(ApplicationShell)
67
+ protected readonly shell: ApplicationShell;
68
+
69
+ @inject(WidgetManager)
70
+ protected readonly widgetManager: WidgetManager;
71
+
72
+ @inject(MimeService)
73
+ protected readonly mimeService: MimeService;
74
+
75
+ @inject(FileSystemPreferences)
76
+ protected readonly preferences: FileSystemPreferences;
77
+
78
+ @inject(CorePreferences)
79
+ protected readonly corePreferences: CorePreferences;
80
+
81
+ @inject(SelectionService)
82
+ protected readonly selectionService: SelectionService;
83
+
84
+ @inject(FileUploadService)
85
+ protected readonly uploadService: FileUploadService;
86
+
87
+ @inject(FileService)
88
+ protected readonly fileService: FileService;
89
+
90
+ @inject(FileDialogService)
91
+ protected readonly fileDialogService: FileDialogService;
92
+
93
+ @inject(OpenerService)
94
+ protected readonly openerService: OpenerService;
95
+
96
+ @inject(UserWorkingDirectoryProvider)
97
+ protected readonly workingDirectory: UserWorkingDirectoryProvider;
98
+
99
+ protected onDidChangeEditorFileEmitter = new Emitter<{ editor: NavigatableWidget, type: FileChangeType }>();
100
+ readonly onDidChangeEditorFile = this.onDidChangeEditorFileEmitter.event;
101
+
102
+ protected readonly userOperations = new Map<number, Deferred<void>>();
103
+ protected queueUserOperation(event: UserFileOperationEvent): void {
104
+ const moveOperation = new Deferred<void>();
105
+ this.userOperations.set(event.correlationId, moveOperation);
106
+ this.run(() => moveOperation.promise);
107
+ }
108
+ protected resolveUserOperation(event: UserFileOperationEvent): void {
109
+ const operation = this.userOperations.get(event.correlationId);
110
+ if (operation) {
111
+ this.userOperations.delete(event.correlationId);
112
+ operation.resolve();
113
+ }
114
+ }
115
+
116
+ initialize(): void {
117
+ this.fileService.onDidFilesChange(event => this.run(() => this.updateWidgets(event)));
118
+ this.fileService.onWillRunUserOperation(event => {
119
+ this.queueUserOperation(event);
120
+ event.waitUntil(this.runEach((uri, widget) => this.pushMove(uri, widget, event)));
121
+ });
122
+ this.fileService.onDidFailUserOperation(event => event.waitUntil((async () => {
123
+ await this.runEach((uri, widget) => this.revertMove(uri, widget, event));
124
+ this.resolveUserOperation(event);
125
+ })()));
126
+ this.fileService.onDidRunUserOperation(event => event.waitUntil((async () => {
127
+ await this.runEach((uri, widget) => this.applyMove(uri, widget, event));
128
+ this.resolveUserOperation(event);
129
+ })()));
130
+ this.uploadService.onDidUpload(files => {
131
+ this.doHandleUpload(files);
132
+ });
133
+ }
134
+
135
+ onStart?(app: FrontendApplication): MaybePromise<void> {
136
+ this.updateAssociations();
137
+ this.preferences.onPreferenceChanged(e => {
138
+ if (e.preferenceName === 'files.associations') {
139
+ this.updateAssociations();
140
+ }
141
+ });
142
+ }
143
+
144
+ registerCommands(commands: CommandRegistry): void {
145
+ commands.registerCommand(FileSystemCommands.UPLOAD, {
146
+ isEnabled: (...args: unknown[]) => {
147
+ const selection = this.getSelection(...args);
148
+ return !!selection && !environment.electron.is();
149
+ },
150
+ isVisible: () => !environment.electron.is(),
151
+ execute: (...args: unknown[]) => {
152
+ const selection = this.getSelection(...args);
153
+ if (selection) {
154
+ return this.upload(selection);
155
+ }
156
+ }
157
+ });
158
+ commands.registerCommand(CommonCommands.NEW_FILE, {
159
+ execute: (...args: unknown[]) => {
160
+ this.handleNewFileCommand(args);
161
+ }
162
+ });
163
+ }
164
+
165
+ protected async upload(selection: FileSelection): Promise<FileUploadResult | undefined> {
166
+ try {
167
+ const source = TreeWidgetSelection.getSource(this.selectionService.selection);
168
+ const fileUploadResult = await this.uploadService.upload(selection.fileStat.isDirectory ? selection.fileStat.resource : selection.fileStat.resource.parent);
169
+ if (ExpandableTreeNode.is(selection) && source) {
170
+ await source.model.expandNode(selection);
171
+ }
172
+ return fileUploadResult;
173
+ } catch (e) {
174
+ if (!isCancelled(e)) {
175
+ console.error(e);
176
+ }
177
+ }
178
+ }
179
+
180
+ protected async doHandleUpload(uploads: string[]): Promise<void> {
181
+ // Only handle single file uploads
182
+ if (uploads.length === 1) {
183
+ const uri = new URI(uploads[0]);
184
+ // Close all existing widgets for this URI
185
+ const widgets = this.shell.widgets.filter(widget => NavigatableWidget.getUri(widget)?.isEqual(uri));
186
+ await this.shell.closeMany(widgets, {
187
+ // Don't ask to save the file if it's dirty
188
+ // The user has already confirmed the file overwrite
189
+ save: false
190
+ });
191
+ // Open a new editor for this URI
192
+ open(this.openerService, uri);
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Opens a save dialog to create a new file.
198
+ *
199
+ * @param args The first argument is the name of the new file. The second argument is the parent directory URI.
200
+ */
201
+ protected async handleNewFileCommand(args: unknown[]): Promise<void> {
202
+ const fileName = (args !== undefined && typeof args[0] === 'string') ? args[0] : undefined;
203
+ const title = nls.localizeByDefault('Create File');
204
+ const props: SaveFileDialogProps = { title, saveLabel: title, inputValue: fileName };
205
+
206
+ const dirUri = (args[1] instanceof URI) ? args[1] : await this.workingDirectory.getUserWorkingDir();
207
+ const directory = await this.fileService.resolve(dirUri);
208
+
209
+ const filePath = await this.fileDialogService.showSaveDialog(props, directory.isDirectory ? directory : undefined);
210
+ if (filePath) {
211
+ const file = await this.fileService.createFile(filePath);
212
+ open(this.openerService, file.resource);
213
+ }
214
+ }
215
+
216
+ protected getSelection(...args: unknown[]): FileSelection | undefined {
217
+ const { selection } = this.selectionService;
218
+ return this.toSelection(args[0]) ?? (Array.isArray(selection) ? selection.find(FileSelection.is) : this.toSelection(selection));
219
+ };
220
+
221
+ protected toSelection(arg: unknown): FileSelection | undefined {
222
+ return FileSelection.is(arg) ? arg : undefined;
223
+ }
224
+
225
+ protected pendingOperation = Promise.resolve();
226
+ protected run(operation: () => MaybePromise<void>): Promise<void> {
227
+ return this.pendingOperation = this.pendingOperation.then(async () => {
228
+ try {
229
+ await operation();
230
+ } catch (e) {
231
+ console.error(e);
232
+ }
233
+ });
234
+ }
235
+
236
+ protected async runEach(participant: (resourceUri: URI, widget: NavigatableWidget) => Promise<void>): Promise<void> {
237
+ const promises: Promise<void>[] = [];
238
+ for (const [resourceUri, widget] of NavigatableWidget.get(this.shell.widgets)) {
239
+ promises.push(participant(resourceUri, widget));
240
+ }
241
+ await Promise.all(promises);
242
+ }
243
+
244
+ protected readonly moveSnapshots = new Map<string, NavigatableWidgetMoveSnapshot>();
245
+
246
+ protected popMoveSnapshot(resourceUri: URI): NavigatableWidgetMoveSnapshot | undefined {
247
+ const snapshotKey = resourceUri.toString();
248
+ const snapshot = this.moveSnapshots.get(snapshotKey);
249
+ if (snapshot) {
250
+ this.moveSnapshots.delete(snapshotKey);
251
+ }
252
+ return snapshot;
253
+ }
254
+
255
+ protected applyMoveSnapshot(widget: NavigatableWidget, snapshot: NavigatableWidgetMoveSnapshot | undefined): void {
256
+ if (!snapshot) {
257
+ return undefined;
258
+ }
259
+ if (snapshot.dirty) {
260
+ const saveable = Saveable.get(widget);
261
+ if (saveable && saveable.applySnapshot) {
262
+ saveable.applySnapshot(snapshot.dirty);
263
+ }
264
+ }
265
+ if (snapshot.view && StatefulWidget.is(widget)) {
266
+ widget.restoreState(snapshot.view);
267
+ }
268
+ }
269
+
270
+ protected async pushMove(resourceUri: URI, widget: NavigatableWidget, event: UserFileOperationEvent): Promise<void> {
271
+ const newResourceUri = this.createMoveToUri(resourceUri, widget, event);
272
+ if (!newResourceUri) {
273
+ return;
274
+ }
275
+ const snapshot: NavigatableWidgetMoveSnapshot = {};
276
+ const saveable = Saveable.get(widget);
277
+ if (StatefulWidget.is(widget)) {
278
+ snapshot.view = widget.storeState();
279
+ }
280
+ if (saveable && saveable.dirty) {
281
+ if (saveable.createSnapshot) {
282
+ snapshot.dirty = saveable.createSnapshot();
283
+ }
284
+ if (saveable.revert) {
285
+ await saveable.revert({ soft: true });
286
+ }
287
+ }
288
+ this.moveSnapshots.set(newResourceUri.toString(), snapshot);
289
+ }
290
+
291
+ protected async revertMove(resourceUri: URI, widget: NavigatableWidget, event: UserFileOperationEvent): Promise<void> {
292
+ const newResourceUri = this.createMoveToUri(resourceUri, widget, event);
293
+ if (!newResourceUri) {
294
+ return;
295
+ }
296
+ const snapshot = this.popMoveSnapshot(newResourceUri);
297
+ this.applyMoveSnapshot(widget, snapshot);
298
+ }
299
+
300
+ protected async applyMove(resourceUri: URI, widget: NavigatableWidget, event: UserFileOperationEvent): Promise<void> {
301
+ const newResourceUri = this.createMoveToUri(resourceUri, widget, event);
302
+ if (!newResourceUri) {
303
+ return;
304
+ }
305
+
306
+ const snapshot = this.popMoveSnapshot(newResourceUri);
307
+
308
+ const description = this.widgetManager.getDescription(widget);
309
+ if (!description) {
310
+ return;
311
+ }
312
+ const { factoryId, options } = description;
313
+ if (!NavigatableWidgetOptions.is(options)) {
314
+ return;
315
+ }
316
+
317
+ const newWidget = await this.widgetManager.getOrCreateWidget<NavigatableWidget>(factoryId, <NavigatableWidgetOptions>{
318
+ ...options,
319
+ uri: newResourceUri.toString()
320
+ });
321
+ this.applyMoveSnapshot(newWidget, snapshot);
322
+ const area = this.shell.getAreaFor(widget) || 'main';
323
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
324
+ const pending: Promise<any>[] = [this.shell.addWidget(newWidget, {
325
+ area, ref: widget
326
+ })];
327
+ if (this.shell.activeWidget === widget) {
328
+ pending.push(this.shell.activateWidget(newWidget.id));
329
+ } else if (widget.isVisible) {
330
+ pending.push(this.shell.revealWidget(newWidget.id));
331
+ }
332
+ pending.push(this.shell.closeWidget(widget.id, { save: false }));
333
+ await Promise.all(pending);
334
+ }
335
+
336
+ protected createMoveToUri(resourceUri: URI, widget: NavigatableWidget, event: UserFileOperationEvent): URI | undefined {
337
+ if (event.operation !== FileOperation.MOVE) {
338
+ return undefined;
339
+ }
340
+ const path = event.source?.relative(resourceUri);
341
+ const targetUri = path && event.target.resolve(path);
342
+ return targetUri && widget.createMoveToUri(targetUri);
343
+ }
344
+
345
+ protected readonly deletedSuffix = `(${nls.localizeByDefault('Deleted')})`;
346
+ protected async updateWidgets(event: FileChangesEvent): Promise<void> {
347
+ if (!event.gotDeleted() && !event.gotAdded()) {
348
+ return;
349
+ }
350
+ const dirty = new Set<string>();
351
+ const toClose = new Map<string, NavigatableWidget[]>();
352
+ for (const [uri, widget] of NavigatableWidget.get(this.shell.widgets)) {
353
+ this.updateWidget(uri, widget, event, { dirty, toClose: toClose });
354
+ }
355
+ if (this.corePreferences['workbench.editor.closeOnFileDelete']) {
356
+ const doClose = [];
357
+ for (const [uri, widgets] of toClose.entries()) {
358
+ if (!dirty.has(uri)) {
359
+ doClose.push(...widgets);
360
+ }
361
+ }
362
+ await this.shell.closeMany(doClose);
363
+ }
364
+ }
365
+ protected updateWidget(uri: URI, widget: NavigatableWidget, event: FileChangesEvent, { dirty, toClose }: {
366
+ dirty: Set<string>;
367
+ toClose: Map<string, NavigatableWidget[]>
368
+ }): void {
369
+ const label = widget.title.label;
370
+ const deleted = label.endsWith(this.deletedSuffix);
371
+ if (event.contains(uri, FileChangeType.DELETED)) {
372
+ const uriString = uri.toString();
373
+ if (Saveable.isDirty(widget)) {
374
+ dirty.add(uriString);
375
+ }
376
+ if (!deleted) {
377
+ widget.title.label += this.deletedSuffix;
378
+ this.onDidChangeEditorFileEmitter.fire({ editor: widget, type: FileChangeType.DELETED });
379
+ }
380
+ const widgets = toClose.get(uriString) || [];
381
+ widgets.push(widget);
382
+ toClose.set(uriString, widgets);
383
+ } else if (event.contains(uri, FileChangeType.ADDED)) {
384
+ if (deleted) {
385
+ widget.title.label = widget.title.label.substring(0, label.length - this.deletedSuffix.length);
386
+ this.onDidChangeEditorFileEmitter.fire({ editor: widget, type: FileChangeType.ADDED });
387
+ }
388
+ }
389
+ }
390
+
391
+ protected updateAssociations(): void {
392
+ const fileAssociations = this.preferences['files.associations'];
393
+ const mimeAssociations = Object.keys(fileAssociations).map(filepattern => ({ id: fileAssociations[filepattern], filepattern }));
394
+ this.mimeService.setAssociations(mimeAssociations);
395
+ }
396
+ }