@theia/workspace 1.45.1 → 1.46.0-next.72

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 (118) hide show
  1. package/README.md +30 -30
  2. package/lib/browser/canonical-uri-service.d.ts +11 -11
  3. package/lib/browser/canonical-uri-service.js +59 -59
  4. package/lib/browser/diff-service.d.ts +10 -10
  5. package/lib/browser/diff-service.js +85 -85
  6. package/lib/browser/index.d.ts +7 -7
  7. package/lib/browser/index.js +34 -34
  8. package/lib/browser/quick-open-workspace.d.ts +25 -25
  9. package/lib/browser/quick-open-workspace.js +137 -137
  10. package/lib/browser/untitled-workspace-exit-dialog.d.ts +19 -19
  11. package/lib/browser/untitled-workspace-exit-dialog.js +74 -74
  12. package/lib/browser/workspace-breadcrumbs-contribution.d.ts +10 -10
  13. package/lib/browser/workspace-breadcrumbs-contribution.js +66 -66
  14. package/lib/browser/workspace-commands.d.ts +117 -117
  15. package/lib/browser/workspace-commands.js +601 -601
  16. package/lib/browser/workspace-commands.spec.d.ts +1 -1
  17. package/lib/browser/workspace-commands.spec.js +127 -127
  18. package/lib/browser/workspace-compare-handler.d.ts +26 -26
  19. package/lib/browser/workspace-compare-handler.js +66 -66
  20. package/lib/browser/workspace-delete-handler.d.ts +75 -75
  21. package/lib/browser/workspace-delete-handler.js +214 -214
  22. package/lib/browser/workspace-duplicate-handler.d.ts +30 -30
  23. package/lib/browser/workspace-duplicate-handler.js +86 -86
  24. package/lib/browser/workspace-frontend-contribution.d.ts +110 -110
  25. package/lib/browser/workspace-frontend-contribution.js +546 -546
  26. package/lib/browser/workspace-frontend-contribution.js.map +1 -1
  27. package/lib/browser/workspace-frontend-module.d.ts +3 -3
  28. package/lib/browser/workspace-frontend-module.js +91 -91
  29. package/lib/browser/workspace-input-dialog.d.ts +19 -19
  30. package/lib/browser/workspace-input-dialog.js +74 -74
  31. package/lib/browser/workspace-preferences.d.ts +11 -11
  32. package/lib/browser/workspace-preferences.js +46 -46
  33. package/lib/browser/workspace-schema-updater.d.ts +34 -34
  34. package/lib/browser/workspace-schema-updater.js +153 -153
  35. package/lib/browser/workspace-service.d.ts +184 -184
  36. package/lib/browser/workspace-service.js +739 -739
  37. package/lib/browser/workspace-storage-service.d.ts +15 -15
  38. package/lib/browser/workspace-storage-service.js +80 -80
  39. package/lib/browser/workspace-trust-preferences.d.ts +21 -21
  40. package/lib/browser/workspace-trust-preferences.js +65 -65
  41. package/lib/browser/workspace-trust-service.d.ts +27 -27
  42. package/lib/browser/workspace-trust-service.js +152 -152
  43. package/lib/browser/workspace-uri-contribution.d.ts +20 -20
  44. package/lib/browser/workspace-uri-contribution.js +113 -113
  45. package/lib/browser/workspace-uri-contribution.spec.d.ts +1 -1
  46. package/lib/browser/workspace-uri-contribution.spec.js +169 -169
  47. package/lib/browser/workspace-user-working-directory-provider.d.ts +12 -12
  48. package/lib/browser/workspace-user-working-directory-provider.js +62 -62
  49. package/lib/browser/workspace-utils.d.ts +15 -15
  50. package/lib/browser/workspace-utils.js +54 -54
  51. package/lib/browser/workspace-variable-contribution.d.ts +23 -23
  52. package/lib/browser/workspace-variable-contribution.js +237 -237
  53. package/lib/browser/workspace-window-title-updater.d.ts +7 -7
  54. package/lib/browser/workspace-window-title-updater.js +57 -57
  55. package/lib/browser-only/browser-only-workspace-server.d.ts +13 -0
  56. package/lib/browser-only/browser-only-workspace-server.d.ts.map +1 -0
  57. package/lib/browser-only/browser-only-workspace-server.js +81 -0
  58. package/lib/browser-only/browser-only-workspace-server.js.map +1 -0
  59. package/lib/browser-only/workspace-frontend-only-module.d.ts +4 -0
  60. package/lib/browser-only/workspace-frontend-only-module.d.ts.map +1 -0
  61. package/lib/browser-only/workspace-frontend-only-module.js +30 -0
  62. package/lib/browser-only/workspace-frontend-only-module.js.map +1 -0
  63. package/lib/common/index.d.ts +3 -3
  64. package/lib/common/index.js +30 -30
  65. package/lib/common/test/mock-workspace-server.d.ts +7 -7
  66. package/lib/common/test/mock-workspace-server.js +35 -35
  67. package/lib/common/untitled-workspace-service.d.ts +8 -8
  68. package/lib/common/untitled-workspace-service.js +60 -60
  69. package/lib/common/workspace-file-service.d.ts +26 -26
  70. package/lib/common/workspace-file-service.js +71 -71
  71. package/lib/common/workspace-protocol.d.ts +26 -26
  72. package/lib/common/workspace-protocol.js +23 -23
  73. package/lib/node/default-workspace-server.d.ts +65 -65
  74. package/lib/node/default-workspace-server.js +248 -248
  75. package/lib/node/default-workspace-server.spec.d.ts +1 -1
  76. package/lib/node/default-workspace-server.spec.js +85 -85
  77. package/lib/node/index.d.ts +2 -2
  78. package/lib/node/index.js +29 -29
  79. package/lib/node/workspace-backend-module.d.ts +3 -3
  80. package/lib/node/workspace-backend-module.js +33 -33
  81. package/package.json +9 -6
  82. package/src/browser/canonical-uri-service.ts +57 -57
  83. package/src/browser/diff-service.ts +62 -62
  84. package/src/browser/index.ts +23 -23
  85. package/src/browser/quick-open-workspace.ts +112 -112
  86. package/src/browser/untitled-workspace-exit-dialog.ts +70 -70
  87. package/src/browser/workspace-breadcrumbs-contribution.ts +56 -56
  88. package/src/browser/workspace-commands.spec.ts +153 -153
  89. package/src/browser/workspace-commands.ts +588 -588
  90. package/src/browser/workspace-compare-handler.ts +56 -56
  91. package/src/browser/workspace-delete-handler.ts +212 -212
  92. package/src/browser/workspace-duplicate-handler.ts +75 -75
  93. package/src/browser/workspace-frontend-contribution.ts +537 -537
  94. package/src/browser/workspace-frontend-module.ts +118 -118
  95. package/src/browser/workspace-input-dialog.ts +61 -61
  96. package/src/browser/workspace-preferences.ts +58 -58
  97. package/src/browser/workspace-schema-updater.ts +150 -150
  98. package/src/browser/workspace-service.ts +780 -780
  99. package/src/browser/workspace-storage-service.ts +67 -67
  100. package/src/browser/workspace-trust-preferences.ts +76 -76
  101. package/src/browser/workspace-trust-service.ts +147 -147
  102. package/src/browser/workspace-uri-contribution.spec.ts +191 -191
  103. package/src/browser/workspace-uri-contribution.ts +97 -97
  104. package/src/browser/workspace-user-working-directory-provider.ts +49 -49
  105. package/src/browser/workspace-utils.ts +45 -45
  106. package/src/browser/workspace-variable-contribution.ts +222 -222
  107. package/src/browser/workspace-window-title-updater.ts +45 -45
  108. package/src/browser-only/browser-only-workspace-server.ts +69 -0
  109. package/src/browser-only/workspace-frontend-only-module.ts +28 -0
  110. package/src/common/index.ts +19 -19
  111. package/src/common/test/mock-workspace-server.ts +29 -29
  112. package/src/common/untitled-workspace-service.ts +50 -50
  113. package/src/common/workspace-file-service.ts +72 -72
  114. package/src/common/workspace-protocol.ts +47 -47
  115. package/src/node/default-workspace-server.spec.ts +100 -100
  116. package/src/node/default-workspace-server.ts +244 -244
  117. package/src/node/index.ts +18 -18
  118. package/src/node/workspace-backend-module.ts +38 -38
@@ -1,588 +1,588 @@
1
- // *****************************************************************************
2
- // Copyright (C) 2017 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 { inject, injectable } from '@theia/core/shared/inversify';
18
- import URI from '@theia/core/lib/common/uri';
19
- import { SelectionService } from '@theia/core/lib/common/selection-service';
20
- import { Command, CommandContribution, CommandRegistry } from '@theia/core/lib/common/command';
21
- import { MenuContribution, MenuModelRegistry } from '@theia/core/lib/common/menu';
22
- import { CommonMenus } from '@theia/core/lib/browser/common-frontend-contribution';
23
- import { FileDialogService } from '@theia/filesystem/lib/browser';
24
- import { SingleTextInputDialog, ConfirmDialog, Dialog } from '@theia/core/lib/browser/dialogs';
25
- import { OpenerService, OpenHandler, open, FrontendApplication, LabelProvider, CommonCommands } from '@theia/core/lib/browser';
26
- import { UriCommandHandler, UriAwareCommandHandler } from '@theia/core/lib/common/uri-command-handler';
27
- import { WorkspaceService } from './workspace-service';
28
- import { MessageService } from '@theia/core/lib/common/message-service';
29
- import { WorkspacePreferences } from './workspace-preferences';
30
- import { WorkspaceDeleteHandler } from './workspace-delete-handler';
31
- import { WorkspaceDuplicateHandler } from './workspace-duplicate-handler';
32
- import { FileSystemUtils } from '@theia/filesystem/lib/common';
33
- import { WorkspaceCompareHandler } from './workspace-compare-handler';
34
- import { FileDownloadCommands } from '@theia/filesystem/lib/browser/download/file-download-command-contribution';
35
- import { FileSystemCommands } from '@theia/filesystem/lib/browser/filesystem-frontend-contribution';
36
- import { WorkspaceInputDialog } from './workspace-input-dialog';
37
- import { Emitter, EOL, Event, OS } from '@theia/core/lib/common';
38
- import { FileService } from '@theia/filesystem/lib/browser/file-service';
39
- import { FileStat } from '@theia/filesystem/lib/common/files';
40
- import { nls } from '@theia/core/lib/common/nls';
41
- import { ClipboardService } from '@theia/core/lib/browser/clipboard-service';
42
-
43
- const validFilename: (arg: string) => boolean = require('valid-filename');
44
-
45
- export namespace WorkspaceCommands {
46
-
47
- const WORKSPACE_CATEGORY = 'Workspaces';
48
- const FILE_CATEGORY = CommonCommands.FILE_CATEGORY;
49
-
50
- // On Linux and Windows, both files and folders cannot be opened at the same time in electron.
51
- // `OPEN_FILE` and `OPEN_FOLDER` must be available only on Linux and Windows in electron.
52
- // `OPEN` must *not* be available on Windows and Linux in electron.
53
- // VS Code does the same. See: https://github.com/eclipse-theia/theia/pull/3202#issuecomment-430585357
54
- export const OPEN: Command & { dialogLabel: string } = {
55
- ...Command.toDefaultLocalizedCommand({
56
- id: 'workspace:open',
57
- category: CommonCommands.FILE_CATEGORY,
58
- label: 'Open...'
59
- }),
60
- dialogLabel: nls.localizeByDefault('Open')
61
- };
62
- // No `label`. Otherwise, it shows up in the `Command Palette`.
63
- export const OPEN_FILE: Command & { dialogLabel: string } = {
64
- id: 'workspace:openFile',
65
- originalCategory: FILE_CATEGORY,
66
- category: nls.localizeByDefault(CommonCommands.FILE_CATEGORY),
67
- dialogLabel: nls.localizeByDefault('Open File')
68
- };
69
- export const OPEN_FOLDER: Command & { dialogLabel: string } = {
70
- id: 'workspace:openFolder',
71
- dialogLabel: nls.localizeByDefault('Open Folder') // No `label`. Otherwise, it shows up in the `Command Palette`.
72
- };
73
- export const OPEN_WORKSPACE: Command & { dialogLabel: string } = {
74
- ...Command.toDefaultLocalizedCommand({
75
- id: 'workspace:openWorkspace',
76
- category: CommonCommands.FILE_CATEGORY,
77
- label: 'Open Workspace from File...',
78
- }),
79
- dialogLabel: nls.localizeByDefault('Open Workspace from File')
80
- };
81
- export const OPEN_RECENT_WORKSPACE = Command.toLocalizedCommand({
82
- id: 'workspace:openRecent',
83
- category: FILE_CATEGORY,
84
- label: 'Open Recent Workspace...'
85
- }, 'theia/workspace/openRecentWorkspace', CommonCommands.FILE_CATEGORY_KEY);
86
- export const CLOSE = Command.toDefaultLocalizedCommand({
87
- id: 'workspace:close',
88
- category: WORKSPACE_CATEGORY,
89
- label: 'Close Workspace'
90
- });
91
- export const NEW_FILE = Command.toDefaultLocalizedCommand({
92
- id: 'file.newFile',
93
- category: FILE_CATEGORY,
94
- label: 'New File...'
95
- });
96
- export const NEW_FOLDER = Command.toDefaultLocalizedCommand({
97
- id: 'file.newFolder',
98
- category: FILE_CATEGORY,
99
- label: 'New Folder...'
100
- });
101
- export const FILE_OPEN_WITH = (opener: OpenHandler): Command => ({
102
- id: `file.openWith.${opener.id}`
103
- });
104
- export const FILE_RENAME = Command.toDefaultLocalizedCommand({
105
- id: 'file.rename',
106
- category: FILE_CATEGORY,
107
- label: 'Rename'
108
- });
109
- export const FILE_DELETE = Command.toDefaultLocalizedCommand({
110
- id: 'file.delete',
111
- category: FILE_CATEGORY,
112
- label: 'Delete'
113
- });
114
- export const FILE_DUPLICATE = Command.toLocalizedCommand({
115
- id: 'file.duplicate',
116
- category: FILE_CATEGORY,
117
- label: 'Duplicate'
118
- }, 'theia/workspace/duplicate', CommonCommands.FILE_CATEGORY_KEY);
119
- export const FILE_COMPARE = Command.toLocalizedCommand({
120
- id: 'file.compare',
121
- category: FILE_CATEGORY,
122
- label: 'Compare with Each Other'
123
- }, 'theia/workspace/compareWithEachOther', CommonCommands.FILE_CATEGORY_KEY);
124
- export const ADD_FOLDER = Command.toDefaultLocalizedCommand({
125
- id: 'workspace:addFolder',
126
- category: WORKSPACE_CATEGORY,
127
- label: 'Add Folder to Workspace...'
128
- });
129
- export const REMOVE_FOLDER = Command.toDefaultLocalizedCommand({
130
- id: 'workspace:removeFolder',
131
- category: WORKSPACE_CATEGORY,
132
- label: 'Remove Folder from Workspace'
133
- });
134
- export const SAVE_WORKSPACE_AS = Command.toDefaultLocalizedCommand({
135
- id: 'workspace:saveAs',
136
- category: WORKSPACE_CATEGORY,
137
- label: 'Save Workspace As...'
138
- });
139
- export const OPEN_WORKSPACE_FILE = Command.toDefaultLocalizedCommand({
140
- id: 'workspace:openConfigFile',
141
- category: WORKSPACE_CATEGORY,
142
- label: 'Open Workspace Configuration File'
143
- });
144
- /** @deprecated @since 1.24.0 Use `CommonCommands.SAVE_AS` instead */
145
- export const SAVE_AS = CommonCommands.SAVE_AS;
146
- export const COPY_RELATIVE_FILE_PATH = Command.toDefaultLocalizedCommand({
147
- id: 'navigator.copyRelativeFilePath',
148
- label: 'Copy Relative Path'
149
- });
150
- }
151
-
152
- @injectable()
153
- export class FileMenuContribution implements MenuContribution {
154
-
155
- registerMenus(registry: MenuModelRegistry): void {
156
- registry.registerMenuAction(CommonMenus.FILE_NEW_TEXT, {
157
- commandId: WorkspaceCommands.NEW_FOLDER.id,
158
- order: 'b'
159
- });
160
- const downloadUploadMenu = [...CommonMenus.FILE, '4_downloadupload'];
161
- registry.registerMenuAction(downloadUploadMenu, {
162
- commandId: FileSystemCommands.UPLOAD.id,
163
- order: 'a'
164
- });
165
- registry.registerMenuAction(downloadUploadMenu, {
166
- commandId: FileDownloadCommands.DOWNLOAD.id,
167
- order: 'b'
168
- });
169
- }
170
-
171
- }
172
-
173
- @injectable()
174
- export class EditMenuContribution implements MenuContribution {
175
-
176
- registerMenus(registry: MenuModelRegistry): void {
177
- registry.registerMenuAction(CommonMenus.EDIT_CLIPBOARD, {
178
- commandId: FileDownloadCommands.COPY_DOWNLOAD_LINK.id,
179
- order: '9999'
180
- });
181
- }
182
-
183
- }
184
-
185
- export interface DidCreateNewResourceEvent {
186
- uri: URI
187
- parent: URI
188
- }
189
-
190
- @injectable()
191
- export class WorkspaceCommandContribution implements CommandContribution {
192
-
193
- @inject(LabelProvider) protected readonly labelProvider: LabelProvider;
194
- @inject(FileService) protected readonly fileService: FileService;
195
- @inject(WorkspaceService) protected readonly workspaceService: WorkspaceService;
196
- @inject(SelectionService) protected readonly selectionService: SelectionService;
197
- @inject(OpenerService) protected readonly openerService: OpenerService;
198
- @inject(FrontendApplication) protected readonly app: FrontendApplication;
199
- @inject(MessageService) protected readonly messageService: MessageService;
200
- @inject(WorkspacePreferences) protected readonly preferences: WorkspacePreferences;
201
- @inject(FileDialogService) protected readonly fileDialogService: FileDialogService;
202
- @inject(WorkspaceDeleteHandler) protected readonly deleteHandler: WorkspaceDeleteHandler;
203
- @inject(WorkspaceDuplicateHandler) protected readonly duplicateHandler: WorkspaceDuplicateHandler;
204
- @inject(WorkspaceCompareHandler) protected readonly compareHandler: WorkspaceCompareHandler;
205
- @inject(ClipboardService) protected readonly clipboardService: ClipboardService;
206
-
207
- private readonly onDidCreateNewFileEmitter = new Emitter<DidCreateNewResourceEvent>();
208
- private readonly onDidCreateNewFolderEmitter = new Emitter<DidCreateNewResourceEvent>();
209
-
210
- get onDidCreateNewFile(): Event<DidCreateNewResourceEvent> {
211
- return this.onDidCreateNewFileEmitter.event;
212
- }
213
-
214
- get onDidCreateNewFolder(): Event<DidCreateNewResourceEvent> {
215
- return this.onDidCreateNewFolderEmitter.event;
216
- }
217
-
218
- protected fireCreateNewFile(uri: DidCreateNewResourceEvent): void {
219
- this.onDidCreateNewFileEmitter.fire(uri);
220
- }
221
-
222
- protected fireCreateNewFolder(uri: DidCreateNewResourceEvent): void {
223
- this.onDidCreateNewFolderEmitter.fire(uri);
224
- }
225
-
226
- registerCommands(registry: CommandRegistry): void {
227
- this.registerOpenWith(registry);
228
- registry.registerCommand(WorkspaceCommands.NEW_FILE, this.newWorkspaceRootUriAwareCommandHandler({
229
- execute: uri => this.getDirectory(uri).then(parent => {
230
- if (parent) {
231
- const parentUri = parent.resource;
232
- const { fileName, fileExtension } = this.getDefaultFileConfig();
233
- const targetUri = parentUri.resolve(fileName + fileExtension);
234
- const vacantChildUri = FileSystemUtils.generateUniqueResourceURI(parent, targetUri, false);
235
-
236
- const dialog = new WorkspaceInputDialog({
237
- title: nls.localizeByDefault('New File...'),
238
- maxWidth: 400,
239
- parentUri: parentUri,
240
- initialValue: vacantChildUri.path.base,
241
- placeholder: nls.localize('theia/workspace/newFilePlaceholder', 'File Name'),
242
- validate: name => this.validateFileName(name, parent, true)
243
- }, this.labelProvider);
244
-
245
- dialog.open().then(async name => {
246
- if (name) {
247
- const fileUri = parentUri.resolve(name);
248
- await this.fileService.create(fileUri);
249
- this.fireCreateNewFile({ parent: parentUri, uri: fileUri });
250
- open(this.openerService, fileUri);
251
- }
252
- });
253
- }
254
- })
255
- }));
256
- registry.registerCommand(WorkspaceCommands.NEW_FOLDER, this.newWorkspaceRootUriAwareCommandHandler({
257
- execute: uri => this.getDirectory(uri).then(parent => {
258
- if (parent) {
259
- const parentUri = parent.resource;
260
- const targetUri = parentUri.resolve('Untitled');
261
- const vacantChildUri = FileSystemUtils.generateUniqueResourceURI(parent, targetUri, true);
262
- const dialog = new WorkspaceInputDialog({
263
- title: nls.localizeByDefault('New Folder...'),
264
- maxWidth: 400,
265
- parentUri: parentUri,
266
- initialValue: vacantChildUri.path.base,
267
- placeholder: nls.localize('theia/workspace/newFolderPlaceholder', 'Folder Name'),
268
- validate: name => this.validateFileName(name, parent, true)
269
- }, this.labelProvider);
270
- dialog.open().then(async name => {
271
- if (name) {
272
- const folderUri = parentUri.resolve(name);
273
- await this.fileService.createFolder(folderUri);
274
- this.fireCreateNewFile({ parent: parentUri, uri: folderUri });
275
- }
276
- });
277
- }
278
- })
279
- }));
280
- registry.registerCommand(WorkspaceCommands.FILE_RENAME, this.newMultiUriAwareCommandHandler({
281
- isEnabled: uris => uris.some(uri => !this.isWorkspaceRoot(uri)) && uris.length === 1,
282
- isVisible: uris => uris.some(uri => !this.isWorkspaceRoot(uri)) && uris.length === 1,
283
- execute: async uris => {
284
- const uri = uris[0]; /* Since there is only one item in the array. */
285
- const parent = await this.getParent(uri);
286
- if (parent) {
287
- const oldName = uri.path.base;
288
- const dialog = new SingleTextInputDialog({
289
- title: nls.localizeByDefault('Rename'),
290
- maxWidth: 400,
291
- initialValue: oldName,
292
- initialSelectionRange: {
293
- start: 0,
294
- end: uri.path.name.length
295
- },
296
- validate: async (newName, mode) => {
297
- if (oldName === newName && mode === 'preview') {
298
- return false;
299
- }
300
- return this.validateFileRename(oldName, newName, parent);
301
- }
302
- });
303
- const fileName = await dialog.open();
304
- if (fileName) {
305
- const oldUri = uri;
306
- const newUri = uri.parent.resolve(fileName);
307
- return this.fileService.move(oldUri, newUri);
308
- }
309
- }
310
- }
311
- }));
312
- registry.registerCommand(WorkspaceCommands.FILE_DUPLICATE, this.newMultiUriAwareCommandHandler(this.duplicateHandler));
313
- registry.registerCommand(WorkspaceCommands.FILE_DELETE, this.newMultiUriAwareCommandHandler(this.deleteHandler));
314
- registry.registerCommand(WorkspaceCommands.FILE_COMPARE, this.newMultiUriAwareCommandHandler(this.compareHandler));
315
- registry.registerCommand(WorkspaceCommands.COPY_RELATIVE_FILE_PATH, UriAwareCommandHandler.MultiSelect(this.selectionService, {
316
- isEnabled: uris => !!uris.length,
317
- isVisible: uris => !!uris.length,
318
- execute: async uris => {
319
- const lineDelimiter = EOL;
320
- const text = uris.map((uri: URI) => {
321
- const workspaceRoot = this.workspaceService.getWorkspaceRootUri(uri);
322
- if (workspaceRoot) {
323
- return workspaceRoot.relative(uri)?.fsPath();
324
- } else {
325
- return uri.path.fsPath();
326
- }
327
- }).join(lineDelimiter);
328
- await this.clipboardService.writeText(text);
329
- }
330
- }));
331
- registry.registerCommand(WorkspaceCommands.ADD_FOLDER, {
332
- isEnabled: () => this.workspaceService.opened,
333
- isVisible: () => this.workspaceService.opened,
334
- execute: async () => {
335
- const selection = await this.fileDialogService.showOpenDialog({
336
- title: WorkspaceCommands.ADD_FOLDER.label!,
337
- canSelectFiles: false,
338
- canSelectFolders: true,
339
- canSelectMany: true,
340
- });
341
- if (!selection) {
342
- return;
343
- }
344
- const uris = Array.isArray(selection) ? selection : [selection];
345
- const workspaceSavedBeforeAdding = this.workspaceService.saved;
346
- await this.addFolderToWorkspace(...uris);
347
- if (!workspaceSavedBeforeAdding) {
348
- this.saveWorkspaceWithPrompt(registry);
349
- }
350
- }
351
- });
352
- registry.registerCommand(WorkspaceCommands.REMOVE_FOLDER, this.newMultiUriAwareCommandHandler({
353
- execute: uris => this.removeFolderFromWorkspace(uris),
354
- isEnabled: () => this.workspaceService.isMultiRootWorkspaceOpened,
355
- isVisible: uris => this.areWorkspaceRoots(uris) && this.workspaceService.saved
356
- }));
357
- }
358
-
359
- openers: OpenHandler[];
360
- protected async registerOpenWith(registry: CommandRegistry): Promise<void> {
361
- if (this.openerService.onDidChangeOpeners) {
362
- this.openerService.onDidChangeOpeners(async e => {
363
- this.openers = await this.openerService.getOpeners();
364
- });
365
- }
366
- this.openers = await this.openerService.getOpeners();
367
- for (const opener of this.openers) {
368
- const openWithCommand = WorkspaceCommands.FILE_OPEN_WITH(opener);
369
- registry.registerCommand(openWithCommand, this.newUriAwareCommandHandler({
370
- execute: uri => opener.open(uri),
371
- isEnabled: uri => opener.canHandle(uri) > 0,
372
- isVisible: uri => opener.canHandle(uri) > 0 && this.areMultipleOpenHandlersPresent(this.openers, uri)
373
- }));
374
- }
375
- }
376
-
377
- protected newUriAwareCommandHandler(handler: UriCommandHandler<URI>): UriAwareCommandHandler<URI> {
378
- return UriAwareCommandHandler.MonoSelect(this.selectionService, handler);
379
- }
380
-
381
- protected newMultiUriAwareCommandHandler(handler: UriCommandHandler<URI[]>): UriAwareCommandHandler<URI[]> {
382
- return UriAwareCommandHandler.MultiSelect(this.selectionService, handler);
383
- }
384
-
385
- protected newWorkspaceRootUriAwareCommandHandler(handler: UriCommandHandler<URI>): WorkspaceRootUriAwareCommandHandler {
386
- return new WorkspaceRootUriAwareCommandHandler(this.workspaceService, this.selectionService, handler);
387
- }
388
-
389
- protected async validateFileRename(oldName: string, newName: string, parent: FileStat): Promise<string> {
390
- if (OS.backend.isWindows && parent.resource.resolve(newName).isEqual(parent.resource.resolve(oldName), false)) {
391
- return '';
392
- }
393
- return this.validateFileName(newName, parent, false);
394
- }
395
-
396
- /**
397
- * Returns an error message if the file name is invalid. Otherwise, an empty string.
398
- *
399
- * @param name the simple file name of the file to validate.
400
- * @param parent the parent directory's file stat.
401
- * @param allowNested allow file or folder creation using recursive path
402
- */
403
- protected async validateFileName(name: string, parent: FileStat, allowNested: boolean = false): Promise<string> {
404
- if (!name) {
405
- return '';
406
- }
407
- // do not allow recursive rename
408
- if (!allowNested && !validFilename(name)) {
409
- return nls.localizeByDefault('The name **{0}** is not valid as a file or folder name. Please choose a different name.');
410
- }
411
- if (name.startsWith('/')) {
412
- return nls.localizeByDefault('A file or folder name cannot start with a slash.');
413
- } else if (name.startsWith(' ') || name.endsWith(' ')) {
414
- return nls.localizeByDefault('Leading or trailing whitespace detected in file or folder name.');
415
- }
416
- // check and validate each sub-paths
417
- if (name.split(/[\\/]/).some(file => !file || !validFilename(file) || /^\s+$/.test(file))) {
418
- return nls.localizeByDefault('\'{0}\' is not a valid file name', this.trimFileName(name));
419
- }
420
- const childUri = parent.resource.resolve(name);
421
- const exists = await this.fileService.exists(childUri);
422
- if (exists) {
423
- return nls.localizeByDefault('A file or folder **{0}** already exists at this location. Please choose a different name.', this.trimFileName(name));
424
- }
425
- return '';
426
- }
427
-
428
- protected trimFileName(name: string): string {
429
- if (name && name.length > 30) {
430
- return `${name.substring(0, 30)}...`;
431
- }
432
- return name;
433
- }
434
-
435
- protected async getDirectory(candidate: URI): Promise<FileStat | undefined> {
436
- let stat: FileStat | undefined;
437
- try {
438
- stat = await this.fileService.resolve(candidate);
439
- } catch { }
440
- if (stat && stat.isDirectory) {
441
- return stat;
442
- }
443
- return this.getParent(candidate);
444
- }
445
-
446
- protected async getParent(candidate: URI): Promise<FileStat | undefined> {
447
- try {
448
- return await this.fileService.resolve(candidate.parent);
449
- } catch {
450
- return undefined;
451
- }
452
- }
453
-
454
- protected async addFolderToWorkspace(...uris: URI[]): Promise<void> {
455
- if (uris.length) {
456
- const foldersToAdd = [];
457
- try {
458
- for (const uri of uris) {
459
- const stat = await this.fileService.resolve(uri);
460
- if (stat.isDirectory) {
461
- foldersToAdd.push(uri);
462
- }
463
- }
464
- await this.workspaceService.addRoot(foldersToAdd);
465
- } catch { }
466
- }
467
- }
468
-
469
- protected areWorkspaceRoots(uris: URI[]): boolean {
470
- return this.workspaceService.areWorkspaceRoots(uris);
471
- }
472
-
473
- protected isWorkspaceRoot(uri: URI): boolean {
474
- const rootUris = new Set(this.workspaceService.tryGetRoots().map(root => root.resource.toString()));
475
- return rootUris.has(uri.toString());
476
- }
477
-
478
- protected getDefaultFileConfig(): { fileName: string, fileExtension: string } {
479
- return {
480
- fileName: 'Untitled',
481
- fileExtension: '.txt'
482
- };
483
- }
484
-
485
- /**
486
- * Removes the list of folders from the workspace upon confirmation from the user.
487
- * @param uris the list of folder uris to remove.
488
- */
489
- protected async removeFolderFromWorkspace(uris: URI[]): Promise<void> {
490
- const roots = new Set(this.workspaceService.tryGetRoots().map(root => root.resource.toString()));
491
- const toRemove = uris.filter(uri => roots.has(uri.toString()));
492
- if (toRemove.length > 0) {
493
- const messageContainer = document.createElement('div');
494
- if (toRemove.length > 1) {
495
- messageContainer.textContent = nls.localize('theia/workspace/removeFolders',
496
- 'Are you sure you want to remove the following folders from the workspace?');
497
- } else {
498
- messageContainer.textContent = nls.localize('theia/workspace/removeFolder',
499
- 'Are you sure you want to remove the following folder from the workspace?');
500
- }
501
- messageContainer.title = nls.localize('theia/workspace/noErasure', 'Note: Nothing will be erased from disk');
502
- const list = document.createElement('div');
503
- list.classList.add('theia-dialog-node');
504
- toRemove.forEach(uri => {
505
- const listItem = document.createElement('div');
506
- listItem.classList.add('theia-dialog-node-content');
507
- const folderIcon = document.createElement('span');
508
- folderIcon.classList.add('codicon', 'codicon-root-folder', 'theia-dialog-icon');
509
- listItem.appendChild(folderIcon);
510
- listItem.title = this.labelProvider.getLongName(uri);
511
- const listContent = document.createElement('span');
512
- listContent.classList.add('theia-dialog-node-segment');
513
- listContent.appendChild(document.createTextNode(this.labelProvider.getName(uri)));
514
- listItem.appendChild(listContent);
515
- list.appendChild(listItem);
516
- });
517
- messageContainer.appendChild(list);
518
- const dialog = new ConfirmDialog({
519
- title: nls.localizeByDefault('Remove Folder from Workspace'),
520
- msg: messageContainer
521
- });
522
- if (await dialog.open()) {
523
- await this.workspaceService.removeRoots(toRemove);
524
- }
525
- }
526
- }
527
-
528
- async saveWorkspaceWithPrompt(registry: CommandRegistry): Promise<void> {
529
- const saveCommand = registry.getCommand(WorkspaceCommands.SAVE_WORKSPACE_AS.id);
530
- if (saveCommand && await new ConfirmDialog({
531
- title: nls.localize('theia/workspace/workspaceFolderAddedTitle', 'Folder added to Workspace'),
532
- msg: nls.localize('theia/workspace/workspaceFolderAdded',
533
- 'A workspace with multiple roots was created. Do you want to save your workspace configuration as a file?'),
534
- ok: Dialog.YES,
535
- cancel: Dialog.NO
536
- }).open()) {
537
- return registry.executeCommand(saveCommand.id);
538
- }
539
- }
540
-
541
- protected areMultipleOpenHandlersPresent(openers: OpenHandler[], uri: URI): boolean {
542
- let count = 0;
543
- for (const opener of openers) {
544
- if (opener.canHandle(uri) > 0) {
545
- count++;
546
- }
547
- if (count > 1) {
548
- return true;
549
- }
550
- }
551
- return false;
552
- }
553
- }
554
-
555
- export class WorkspaceRootUriAwareCommandHandler extends UriAwareCommandHandler<URI> {
556
-
557
- constructor(
558
- protected readonly workspaceService: WorkspaceService,
559
- selectionService: SelectionService,
560
- handler: UriCommandHandler<URI>
561
- ) {
562
- super(selectionService, handler);
563
- }
564
-
565
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
566
- public override isEnabled(...args: any[]): boolean {
567
- return super.isEnabled(...args) && !!this.workspaceService.tryGetRoots().length;
568
- }
569
-
570
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
571
- public override isVisible(...args: any[]): boolean {
572
- return super.isVisible(...args) && !!this.workspaceService.tryGetRoots().length;
573
- }
574
-
575
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
576
- protected override getUri(...args: any[]): URI | undefined {
577
- const uri = super.getUri(...args);
578
- // Return the `uri` immediately if the resource exists in any of the workspace roots and is of `file` scheme.
579
- if (uri && uri.scheme === 'file' && this.workspaceService.getWorkspaceRootUri(uri)) {
580
- return uri;
581
- }
582
- // Return the first root if available.
583
- if (!!this.workspaceService.tryGetRoots().length) {
584
- return this.workspaceService.tryGetRoots()[0].resource;
585
- }
586
- }
587
-
588
- }
1
+ // *****************************************************************************
2
+ // Copyright (C) 2017 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 { inject, injectable } from '@theia/core/shared/inversify';
18
+ import URI from '@theia/core/lib/common/uri';
19
+ import { SelectionService } from '@theia/core/lib/common/selection-service';
20
+ import { Command, CommandContribution, CommandRegistry } from '@theia/core/lib/common/command';
21
+ import { MenuContribution, MenuModelRegistry } from '@theia/core/lib/common/menu';
22
+ import { CommonMenus } from '@theia/core/lib/browser/common-frontend-contribution';
23
+ import { FileDialogService } from '@theia/filesystem/lib/browser';
24
+ import { SingleTextInputDialog, ConfirmDialog, Dialog } from '@theia/core/lib/browser/dialogs';
25
+ import { OpenerService, OpenHandler, open, FrontendApplication, LabelProvider, CommonCommands } from '@theia/core/lib/browser';
26
+ import { UriCommandHandler, UriAwareCommandHandler } from '@theia/core/lib/common/uri-command-handler';
27
+ import { WorkspaceService } from './workspace-service';
28
+ import { MessageService } from '@theia/core/lib/common/message-service';
29
+ import { WorkspacePreferences } from './workspace-preferences';
30
+ import { WorkspaceDeleteHandler } from './workspace-delete-handler';
31
+ import { WorkspaceDuplicateHandler } from './workspace-duplicate-handler';
32
+ import { FileSystemUtils } from '@theia/filesystem/lib/common';
33
+ import { WorkspaceCompareHandler } from './workspace-compare-handler';
34
+ import { FileDownloadCommands } from '@theia/filesystem/lib/browser/download/file-download-command-contribution';
35
+ import { FileSystemCommands } from '@theia/filesystem/lib/browser/filesystem-frontend-contribution';
36
+ import { WorkspaceInputDialog } from './workspace-input-dialog';
37
+ import { Emitter, EOL, Event, OS } from '@theia/core/lib/common';
38
+ import { FileService } from '@theia/filesystem/lib/browser/file-service';
39
+ import { FileStat } from '@theia/filesystem/lib/common/files';
40
+ import { nls } from '@theia/core/lib/common/nls';
41
+ import { ClipboardService } from '@theia/core/lib/browser/clipboard-service';
42
+
43
+ const validFilename: (arg: string) => boolean = require('valid-filename');
44
+
45
+ export namespace WorkspaceCommands {
46
+
47
+ const WORKSPACE_CATEGORY = 'Workspaces';
48
+ const FILE_CATEGORY = CommonCommands.FILE_CATEGORY;
49
+
50
+ // On Linux and Windows, both files and folders cannot be opened at the same time in electron.
51
+ // `OPEN_FILE` and `OPEN_FOLDER` must be available only on Linux and Windows in electron.
52
+ // `OPEN` must *not* be available on Windows and Linux in electron.
53
+ // VS Code does the same. See: https://github.com/eclipse-theia/theia/pull/3202#issuecomment-430585357
54
+ export const OPEN: Command & { dialogLabel: string } = {
55
+ ...Command.toDefaultLocalizedCommand({
56
+ id: 'workspace:open',
57
+ category: CommonCommands.FILE_CATEGORY,
58
+ label: 'Open...'
59
+ }),
60
+ dialogLabel: nls.localizeByDefault('Open')
61
+ };
62
+ // No `label`. Otherwise, it shows up in the `Command Palette`.
63
+ export const OPEN_FILE: Command & { dialogLabel: string } = {
64
+ id: 'workspace:openFile',
65
+ originalCategory: FILE_CATEGORY,
66
+ category: nls.localizeByDefault(CommonCommands.FILE_CATEGORY),
67
+ dialogLabel: nls.localizeByDefault('Open File')
68
+ };
69
+ export const OPEN_FOLDER: Command & { dialogLabel: string } = {
70
+ id: 'workspace:openFolder',
71
+ dialogLabel: nls.localizeByDefault('Open Folder') // No `label`. Otherwise, it shows up in the `Command Palette`.
72
+ };
73
+ export const OPEN_WORKSPACE: Command & { dialogLabel: string } = {
74
+ ...Command.toDefaultLocalizedCommand({
75
+ id: 'workspace:openWorkspace',
76
+ category: CommonCommands.FILE_CATEGORY,
77
+ label: 'Open Workspace from File...',
78
+ }),
79
+ dialogLabel: nls.localizeByDefault('Open Workspace from File')
80
+ };
81
+ export const OPEN_RECENT_WORKSPACE = Command.toLocalizedCommand({
82
+ id: 'workspace:openRecent',
83
+ category: FILE_CATEGORY,
84
+ label: 'Open Recent Workspace...'
85
+ }, 'theia/workspace/openRecentWorkspace', CommonCommands.FILE_CATEGORY_KEY);
86
+ export const CLOSE = Command.toDefaultLocalizedCommand({
87
+ id: 'workspace:close',
88
+ category: WORKSPACE_CATEGORY,
89
+ label: 'Close Workspace'
90
+ });
91
+ export const NEW_FILE = Command.toDefaultLocalizedCommand({
92
+ id: 'file.newFile',
93
+ category: FILE_CATEGORY,
94
+ label: 'New File...'
95
+ });
96
+ export const NEW_FOLDER = Command.toDefaultLocalizedCommand({
97
+ id: 'file.newFolder',
98
+ category: FILE_CATEGORY,
99
+ label: 'New Folder...'
100
+ });
101
+ export const FILE_OPEN_WITH = (opener: OpenHandler): Command => ({
102
+ id: `file.openWith.${opener.id}`
103
+ });
104
+ export const FILE_RENAME = Command.toDefaultLocalizedCommand({
105
+ id: 'file.rename',
106
+ category: FILE_CATEGORY,
107
+ label: 'Rename'
108
+ });
109
+ export const FILE_DELETE = Command.toDefaultLocalizedCommand({
110
+ id: 'file.delete',
111
+ category: FILE_CATEGORY,
112
+ label: 'Delete'
113
+ });
114
+ export const FILE_DUPLICATE = Command.toLocalizedCommand({
115
+ id: 'file.duplicate',
116
+ category: FILE_CATEGORY,
117
+ label: 'Duplicate'
118
+ }, 'theia/workspace/duplicate', CommonCommands.FILE_CATEGORY_KEY);
119
+ export const FILE_COMPARE = Command.toLocalizedCommand({
120
+ id: 'file.compare',
121
+ category: FILE_CATEGORY,
122
+ label: 'Compare with Each Other'
123
+ }, 'theia/workspace/compareWithEachOther', CommonCommands.FILE_CATEGORY_KEY);
124
+ export const ADD_FOLDER = Command.toDefaultLocalizedCommand({
125
+ id: 'workspace:addFolder',
126
+ category: WORKSPACE_CATEGORY,
127
+ label: 'Add Folder to Workspace...'
128
+ });
129
+ export const REMOVE_FOLDER = Command.toDefaultLocalizedCommand({
130
+ id: 'workspace:removeFolder',
131
+ category: WORKSPACE_CATEGORY,
132
+ label: 'Remove Folder from Workspace'
133
+ });
134
+ export const SAVE_WORKSPACE_AS = Command.toDefaultLocalizedCommand({
135
+ id: 'workspace:saveAs',
136
+ category: WORKSPACE_CATEGORY,
137
+ label: 'Save Workspace As...'
138
+ });
139
+ export const OPEN_WORKSPACE_FILE = Command.toDefaultLocalizedCommand({
140
+ id: 'workspace:openConfigFile',
141
+ category: WORKSPACE_CATEGORY,
142
+ label: 'Open Workspace Configuration File'
143
+ });
144
+ /** @deprecated @since 1.24.0 Use `CommonCommands.SAVE_AS` instead */
145
+ export const SAVE_AS = CommonCommands.SAVE_AS;
146
+ export const COPY_RELATIVE_FILE_PATH = Command.toDefaultLocalizedCommand({
147
+ id: 'navigator.copyRelativeFilePath',
148
+ label: 'Copy Relative Path'
149
+ });
150
+ }
151
+
152
+ @injectable()
153
+ export class FileMenuContribution implements MenuContribution {
154
+
155
+ registerMenus(registry: MenuModelRegistry): void {
156
+ registry.registerMenuAction(CommonMenus.FILE_NEW_TEXT, {
157
+ commandId: WorkspaceCommands.NEW_FOLDER.id,
158
+ order: 'b'
159
+ });
160
+ const downloadUploadMenu = [...CommonMenus.FILE, '4_downloadupload'];
161
+ registry.registerMenuAction(downloadUploadMenu, {
162
+ commandId: FileSystemCommands.UPLOAD.id,
163
+ order: 'a'
164
+ });
165
+ registry.registerMenuAction(downloadUploadMenu, {
166
+ commandId: FileDownloadCommands.DOWNLOAD.id,
167
+ order: 'b'
168
+ });
169
+ }
170
+
171
+ }
172
+
173
+ @injectable()
174
+ export class EditMenuContribution implements MenuContribution {
175
+
176
+ registerMenus(registry: MenuModelRegistry): void {
177
+ registry.registerMenuAction(CommonMenus.EDIT_CLIPBOARD, {
178
+ commandId: FileDownloadCommands.COPY_DOWNLOAD_LINK.id,
179
+ order: '9999'
180
+ });
181
+ }
182
+
183
+ }
184
+
185
+ export interface DidCreateNewResourceEvent {
186
+ uri: URI
187
+ parent: URI
188
+ }
189
+
190
+ @injectable()
191
+ export class WorkspaceCommandContribution implements CommandContribution {
192
+
193
+ @inject(LabelProvider) protected readonly labelProvider: LabelProvider;
194
+ @inject(FileService) protected readonly fileService: FileService;
195
+ @inject(WorkspaceService) protected readonly workspaceService: WorkspaceService;
196
+ @inject(SelectionService) protected readonly selectionService: SelectionService;
197
+ @inject(OpenerService) protected readonly openerService: OpenerService;
198
+ @inject(FrontendApplication) protected readonly app: FrontendApplication;
199
+ @inject(MessageService) protected readonly messageService: MessageService;
200
+ @inject(WorkspacePreferences) protected readonly preferences: WorkspacePreferences;
201
+ @inject(FileDialogService) protected readonly fileDialogService: FileDialogService;
202
+ @inject(WorkspaceDeleteHandler) protected readonly deleteHandler: WorkspaceDeleteHandler;
203
+ @inject(WorkspaceDuplicateHandler) protected readonly duplicateHandler: WorkspaceDuplicateHandler;
204
+ @inject(WorkspaceCompareHandler) protected readonly compareHandler: WorkspaceCompareHandler;
205
+ @inject(ClipboardService) protected readonly clipboardService: ClipboardService;
206
+
207
+ private readonly onDidCreateNewFileEmitter = new Emitter<DidCreateNewResourceEvent>();
208
+ private readonly onDidCreateNewFolderEmitter = new Emitter<DidCreateNewResourceEvent>();
209
+
210
+ get onDidCreateNewFile(): Event<DidCreateNewResourceEvent> {
211
+ return this.onDidCreateNewFileEmitter.event;
212
+ }
213
+
214
+ get onDidCreateNewFolder(): Event<DidCreateNewResourceEvent> {
215
+ return this.onDidCreateNewFolderEmitter.event;
216
+ }
217
+
218
+ protected fireCreateNewFile(uri: DidCreateNewResourceEvent): void {
219
+ this.onDidCreateNewFileEmitter.fire(uri);
220
+ }
221
+
222
+ protected fireCreateNewFolder(uri: DidCreateNewResourceEvent): void {
223
+ this.onDidCreateNewFolderEmitter.fire(uri);
224
+ }
225
+
226
+ registerCommands(registry: CommandRegistry): void {
227
+ this.registerOpenWith(registry);
228
+ registry.registerCommand(WorkspaceCommands.NEW_FILE, this.newWorkspaceRootUriAwareCommandHandler({
229
+ execute: uri => this.getDirectory(uri).then(parent => {
230
+ if (parent) {
231
+ const parentUri = parent.resource;
232
+ const { fileName, fileExtension } = this.getDefaultFileConfig();
233
+ const targetUri = parentUri.resolve(fileName + fileExtension);
234
+ const vacantChildUri = FileSystemUtils.generateUniqueResourceURI(parent, targetUri, false);
235
+
236
+ const dialog = new WorkspaceInputDialog({
237
+ title: nls.localizeByDefault('New File...'),
238
+ maxWidth: 400,
239
+ parentUri: parentUri,
240
+ initialValue: vacantChildUri.path.base,
241
+ placeholder: nls.localize('theia/workspace/newFilePlaceholder', 'File Name'),
242
+ validate: name => this.validateFileName(name, parent, true)
243
+ }, this.labelProvider);
244
+
245
+ dialog.open().then(async name => {
246
+ if (name) {
247
+ const fileUri = parentUri.resolve(name);
248
+ await this.fileService.create(fileUri);
249
+ this.fireCreateNewFile({ parent: parentUri, uri: fileUri });
250
+ open(this.openerService, fileUri);
251
+ }
252
+ });
253
+ }
254
+ })
255
+ }));
256
+ registry.registerCommand(WorkspaceCommands.NEW_FOLDER, this.newWorkspaceRootUriAwareCommandHandler({
257
+ execute: uri => this.getDirectory(uri).then(parent => {
258
+ if (parent) {
259
+ const parentUri = parent.resource;
260
+ const targetUri = parentUri.resolve('Untitled');
261
+ const vacantChildUri = FileSystemUtils.generateUniqueResourceURI(parent, targetUri, true);
262
+ const dialog = new WorkspaceInputDialog({
263
+ title: nls.localizeByDefault('New Folder...'),
264
+ maxWidth: 400,
265
+ parentUri: parentUri,
266
+ initialValue: vacantChildUri.path.base,
267
+ placeholder: nls.localize('theia/workspace/newFolderPlaceholder', 'Folder Name'),
268
+ validate: name => this.validateFileName(name, parent, true)
269
+ }, this.labelProvider);
270
+ dialog.open().then(async name => {
271
+ if (name) {
272
+ const folderUri = parentUri.resolve(name);
273
+ await this.fileService.createFolder(folderUri);
274
+ this.fireCreateNewFile({ parent: parentUri, uri: folderUri });
275
+ }
276
+ });
277
+ }
278
+ })
279
+ }));
280
+ registry.registerCommand(WorkspaceCommands.FILE_RENAME, this.newMultiUriAwareCommandHandler({
281
+ isEnabled: uris => uris.some(uri => !this.isWorkspaceRoot(uri)) && uris.length === 1,
282
+ isVisible: uris => uris.some(uri => !this.isWorkspaceRoot(uri)) && uris.length === 1,
283
+ execute: async uris => {
284
+ const uri = uris[0]; /* Since there is only one item in the array. */
285
+ const parent = await this.getParent(uri);
286
+ if (parent) {
287
+ const oldName = uri.path.base;
288
+ const dialog = new SingleTextInputDialog({
289
+ title: nls.localizeByDefault('Rename'),
290
+ maxWidth: 400,
291
+ initialValue: oldName,
292
+ initialSelectionRange: {
293
+ start: 0,
294
+ end: uri.path.name.length
295
+ },
296
+ validate: async (newName, mode) => {
297
+ if (oldName === newName && mode === 'preview') {
298
+ return false;
299
+ }
300
+ return this.validateFileRename(oldName, newName, parent);
301
+ }
302
+ });
303
+ const fileName = await dialog.open();
304
+ if (fileName) {
305
+ const oldUri = uri;
306
+ const newUri = uri.parent.resolve(fileName);
307
+ return this.fileService.move(oldUri, newUri);
308
+ }
309
+ }
310
+ }
311
+ }));
312
+ registry.registerCommand(WorkspaceCommands.FILE_DUPLICATE, this.newMultiUriAwareCommandHandler(this.duplicateHandler));
313
+ registry.registerCommand(WorkspaceCommands.FILE_DELETE, this.newMultiUriAwareCommandHandler(this.deleteHandler));
314
+ registry.registerCommand(WorkspaceCommands.FILE_COMPARE, this.newMultiUriAwareCommandHandler(this.compareHandler));
315
+ registry.registerCommand(WorkspaceCommands.COPY_RELATIVE_FILE_PATH, UriAwareCommandHandler.MultiSelect(this.selectionService, {
316
+ isEnabled: uris => !!uris.length,
317
+ isVisible: uris => !!uris.length,
318
+ execute: async uris => {
319
+ const lineDelimiter = EOL;
320
+ const text = uris.map((uri: URI) => {
321
+ const workspaceRoot = this.workspaceService.getWorkspaceRootUri(uri);
322
+ if (workspaceRoot) {
323
+ return workspaceRoot.relative(uri)?.fsPath();
324
+ } else {
325
+ return uri.path.fsPath();
326
+ }
327
+ }).join(lineDelimiter);
328
+ await this.clipboardService.writeText(text);
329
+ }
330
+ }));
331
+ registry.registerCommand(WorkspaceCommands.ADD_FOLDER, {
332
+ isEnabled: () => this.workspaceService.opened,
333
+ isVisible: () => this.workspaceService.opened,
334
+ execute: async () => {
335
+ const selection = await this.fileDialogService.showOpenDialog({
336
+ title: WorkspaceCommands.ADD_FOLDER.label!,
337
+ canSelectFiles: false,
338
+ canSelectFolders: true,
339
+ canSelectMany: true,
340
+ });
341
+ if (!selection) {
342
+ return;
343
+ }
344
+ const uris = Array.isArray(selection) ? selection : [selection];
345
+ const workspaceSavedBeforeAdding = this.workspaceService.saved;
346
+ await this.addFolderToWorkspace(...uris);
347
+ if (!workspaceSavedBeforeAdding) {
348
+ this.saveWorkspaceWithPrompt(registry);
349
+ }
350
+ }
351
+ });
352
+ registry.registerCommand(WorkspaceCommands.REMOVE_FOLDER, this.newMultiUriAwareCommandHandler({
353
+ execute: uris => this.removeFolderFromWorkspace(uris),
354
+ isEnabled: () => this.workspaceService.isMultiRootWorkspaceOpened,
355
+ isVisible: uris => this.areWorkspaceRoots(uris) && this.workspaceService.saved
356
+ }));
357
+ }
358
+
359
+ openers: OpenHandler[];
360
+ protected async registerOpenWith(registry: CommandRegistry): Promise<void> {
361
+ if (this.openerService.onDidChangeOpeners) {
362
+ this.openerService.onDidChangeOpeners(async e => {
363
+ this.openers = await this.openerService.getOpeners();
364
+ });
365
+ }
366
+ this.openers = await this.openerService.getOpeners();
367
+ for (const opener of this.openers) {
368
+ const openWithCommand = WorkspaceCommands.FILE_OPEN_WITH(opener);
369
+ registry.registerCommand(openWithCommand, this.newUriAwareCommandHandler({
370
+ execute: uri => opener.open(uri),
371
+ isEnabled: uri => opener.canHandle(uri) > 0,
372
+ isVisible: uri => opener.canHandle(uri) > 0 && this.areMultipleOpenHandlersPresent(this.openers, uri)
373
+ }));
374
+ }
375
+ }
376
+
377
+ protected newUriAwareCommandHandler(handler: UriCommandHandler<URI>): UriAwareCommandHandler<URI> {
378
+ return UriAwareCommandHandler.MonoSelect(this.selectionService, handler);
379
+ }
380
+
381
+ protected newMultiUriAwareCommandHandler(handler: UriCommandHandler<URI[]>): UriAwareCommandHandler<URI[]> {
382
+ return UriAwareCommandHandler.MultiSelect(this.selectionService, handler);
383
+ }
384
+
385
+ protected newWorkspaceRootUriAwareCommandHandler(handler: UriCommandHandler<URI>): WorkspaceRootUriAwareCommandHandler {
386
+ return new WorkspaceRootUriAwareCommandHandler(this.workspaceService, this.selectionService, handler);
387
+ }
388
+
389
+ protected async validateFileRename(oldName: string, newName: string, parent: FileStat): Promise<string> {
390
+ if (OS.backend.isWindows && parent.resource.resolve(newName).isEqual(parent.resource.resolve(oldName), false)) {
391
+ return '';
392
+ }
393
+ return this.validateFileName(newName, parent, false);
394
+ }
395
+
396
+ /**
397
+ * Returns an error message if the file name is invalid. Otherwise, an empty string.
398
+ *
399
+ * @param name the simple file name of the file to validate.
400
+ * @param parent the parent directory's file stat.
401
+ * @param allowNested allow file or folder creation using recursive path
402
+ */
403
+ protected async validateFileName(name: string, parent: FileStat, allowNested: boolean = false): Promise<string> {
404
+ if (!name) {
405
+ return '';
406
+ }
407
+ // do not allow recursive rename
408
+ if (!allowNested && !validFilename(name)) {
409
+ return nls.localizeByDefault('The name **{0}** is not valid as a file or folder name. Please choose a different name.');
410
+ }
411
+ if (name.startsWith('/')) {
412
+ return nls.localizeByDefault('A file or folder name cannot start with a slash.');
413
+ } else if (name.startsWith(' ') || name.endsWith(' ')) {
414
+ return nls.localizeByDefault('Leading or trailing whitespace detected in file or folder name.');
415
+ }
416
+ // check and validate each sub-paths
417
+ if (name.split(/[\\/]/).some(file => !file || !validFilename(file) || /^\s+$/.test(file))) {
418
+ return nls.localizeByDefault('\'{0}\' is not a valid file name', this.trimFileName(name));
419
+ }
420
+ const childUri = parent.resource.resolve(name);
421
+ const exists = await this.fileService.exists(childUri);
422
+ if (exists) {
423
+ return nls.localizeByDefault('A file or folder **{0}** already exists at this location. Please choose a different name.', this.trimFileName(name));
424
+ }
425
+ return '';
426
+ }
427
+
428
+ protected trimFileName(name: string): string {
429
+ if (name && name.length > 30) {
430
+ return `${name.substring(0, 30)}...`;
431
+ }
432
+ return name;
433
+ }
434
+
435
+ protected async getDirectory(candidate: URI): Promise<FileStat | undefined> {
436
+ let stat: FileStat | undefined;
437
+ try {
438
+ stat = await this.fileService.resolve(candidate);
439
+ } catch { }
440
+ if (stat && stat.isDirectory) {
441
+ return stat;
442
+ }
443
+ return this.getParent(candidate);
444
+ }
445
+
446
+ protected async getParent(candidate: URI): Promise<FileStat | undefined> {
447
+ try {
448
+ return await this.fileService.resolve(candidate.parent);
449
+ } catch {
450
+ return undefined;
451
+ }
452
+ }
453
+
454
+ protected async addFolderToWorkspace(...uris: URI[]): Promise<void> {
455
+ if (uris.length) {
456
+ const foldersToAdd = [];
457
+ try {
458
+ for (const uri of uris) {
459
+ const stat = await this.fileService.resolve(uri);
460
+ if (stat.isDirectory) {
461
+ foldersToAdd.push(uri);
462
+ }
463
+ }
464
+ await this.workspaceService.addRoot(foldersToAdd);
465
+ } catch { }
466
+ }
467
+ }
468
+
469
+ protected areWorkspaceRoots(uris: URI[]): boolean {
470
+ return this.workspaceService.areWorkspaceRoots(uris);
471
+ }
472
+
473
+ protected isWorkspaceRoot(uri: URI): boolean {
474
+ const rootUris = new Set(this.workspaceService.tryGetRoots().map(root => root.resource.toString()));
475
+ return rootUris.has(uri.toString());
476
+ }
477
+
478
+ protected getDefaultFileConfig(): { fileName: string, fileExtension: string } {
479
+ return {
480
+ fileName: 'Untitled',
481
+ fileExtension: '.txt'
482
+ };
483
+ }
484
+
485
+ /**
486
+ * Removes the list of folders from the workspace upon confirmation from the user.
487
+ * @param uris the list of folder uris to remove.
488
+ */
489
+ protected async removeFolderFromWorkspace(uris: URI[]): Promise<void> {
490
+ const roots = new Set(this.workspaceService.tryGetRoots().map(root => root.resource.toString()));
491
+ const toRemove = uris.filter(uri => roots.has(uri.toString()));
492
+ if (toRemove.length > 0) {
493
+ const messageContainer = document.createElement('div');
494
+ if (toRemove.length > 1) {
495
+ messageContainer.textContent = nls.localize('theia/workspace/removeFolders',
496
+ 'Are you sure you want to remove the following folders from the workspace?');
497
+ } else {
498
+ messageContainer.textContent = nls.localize('theia/workspace/removeFolder',
499
+ 'Are you sure you want to remove the following folder from the workspace?');
500
+ }
501
+ messageContainer.title = nls.localize('theia/workspace/noErasure', 'Note: Nothing will be erased from disk');
502
+ const list = document.createElement('div');
503
+ list.classList.add('theia-dialog-node');
504
+ toRemove.forEach(uri => {
505
+ const listItem = document.createElement('div');
506
+ listItem.classList.add('theia-dialog-node-content');
507
+ const folderIcon = document.createElement('span');
508
+ folderIcon.classList.add('codicon', 'codicon-root-folder', 'theia-dialog-icon');
509
+ listItem.appendChild(folderIcon);
510
+ listItem.title = this.labelProvider.getLongName(uri);
511
+ const listContent = document.createElement('span');
512
+ listContent.classList.add('theia-dialog-node-segment');
513
+ listContent.appendChild(document.createTextNode(this.labelProvider.getName(uri)));
514
+ listItem.appendChild(listContent);
515
+ list.appendChild(listItem);
516
+ });
517
+ messageContainer.appendChild(list);
518
+ const dialog = new ConfirmDialog({
519
+ title: nls.localizeByDefault('Remove Folder from Workspace'),
520
+ msg: messageContainer
521
+ });
522
+ if (await dialog.open()) {
523
+ await this.workspaceService.removeRoots(toRemove);
524
+ }
525
+ }
526
+ }
527
+
528
+ async saveWorkspaceWithPrompt(registry: CommandRegistry): Promise<void> {
529
+ const saveCommand = registry.getCommand(WorkspaceCommands.SAVE_WORKSPACE_AS.id);
530
+ if (saveCommand && await new ConfirmDialog({
531
+ title: nls.localize('theia/workspace/workspaceFolderAddedTitle', 'Folder added to Workspace'),
532
+ msg: nls.localize('theia/workspace/workspaceFolderAdded',
533
+ 'A workspace with multiple roots was created. Do you want to save your workspace configuration as a file?'),
534
+ ok: Dialog.YES,
535
+ cancel: Dialog.NO
536
+ }).open()) {
537
+ return registry.executeCommand(saveCommand.id);
538
+ }
539
+ }
540
+
541
+ protected areMultipleOpenHandlersPresent(openers: OpenHandler[], uri: URI): boolean {
542
+ let count = 0;
543
+ for (const opener of openers) {
544
+ if (opener.canHandle(uri) > 0) {
545
+ count++;
546
+ }
547
+ if (count > 1) {
548
+ return true;
549
+ }
550
+ }
551
+ return false;
552
+ }
553
+ }
554
+
555
+ export class WorkspaceRootUriAwareCommandHandler extends UriAwareCommandHandler<URI> {
556
+
557
+ constructor(
558
+ protected readonly workspaceService: WorkspaceService,
559
+ selectionService: SelectionService,
560
+ handler: UriCommandHandler<URI>
561
+ ) {
562
+ super(selectionService, handler);
563
+ }
564
+
565
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
566
+ public override isEnabled(...args: any[]): boolean {
567
+ return super.isEnabled(...args) && !!this.workspaceService.tryGetRoots().length;
568
+ }
569
+
570
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
571
+ public override isVisible(...args: any[]): boolean {
572
+ return super.isVisible(...args) && !!this.workspaceService.tryGetRoots().length;
573
+ }
574
+
575
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
576
+ protected override getUri(...args: any[]): URI | undefined {
577
+ const uri = super.getUri(...args);
578
+ // Return the `uri` immediately if the resource exists in any of the workspace roots and is of `file` scheme.
579
+ if (uri && uri.scheme === 'file' && this.workspaceService.getWorkspaceRootUri(uri)) {
580
+ return uri;
581
+ }
582
+ // Return the first root if available.
583
+ if (!!this.workspaceService.tryGetRoots().length) {
584
+ return this.workspaceService.tryGetRoots()[0].resource;
585
+ }
586
+ }
587
+
588
+ }