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