-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
plugin-vscode-commands-contribution.ts
executable file
·987 lines (926 loc) · 42 KB
/
plugin-vscode-commands-contribution.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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
// *****************************************************************************
// Copyright (C) 2018 Red Hat, Inc. 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-only WITH Classpath-exception-2.0
// *****************************************************************************
import { Command, CommandContribution, CommandRegistry, environment, isOSX, CancellationTokenSource, MessageService } from '@theia/core';
import {
ApplicationShell,
CommonCommands,
NavigatableWidget,
OpenerService, OpenHandler,
QuickInputService,
Saveable,
TabBar,
Title,
Widget
} from '@theia/core/lib/browser';
import { ContextKeyService } from '@theia/core/lib/browser/context-key-service';
import { ApplicationShellMouseTracker } from '@theia/core/lib/browser/shell/application-shell-mouse-tracker';
import { CommandService } from '@theia/core/lib/common/command';
import TheiaURI from '@theia/core/lib/common/uri';
import { EditorManager, EditorCommands } from '@theia/editor/lib/browser';
import {
TextDocumentShowOptions,
Location,
CallHierarchyItem,
CallHierarchyIncomingCall,
CallHierarchyOutgoingCall,
TypeHierarchyItem,
Hover,
TextEdit,
FormattingOptions,
DocumentHighlight
} from '@theia/plugin-ext/lib/common/plugin-api-rpc-model';
import { DocumentsMainImpl } from '@theia/plugin-ext/lib/main/browser/documents-main';
import { isUriComponents, toMergedSymbol, toPosition } from '@theia/plugin-ext/lib/plugin/type-converters';
import { ViewColumn } from '@theia/plugin-ext/lib/plugin/types-impl';
import { WorkspaceCommands } from '@theia/workspace/lib/browser';
import { WorkspaceService, WorkspaceInput } from '@theia/workspace/lib/browser/workspace-service';
import { DiffService } from '@theia/workspace/lib/browser/diff-service';
import { inject, injectable, optional } from '@theia/core/shared/inversify';
import { Position } from '@theia/plugin-ext/lib/common/plugin-api-rpc';
import { URI } from '@theia/core/shared/vscode-uri';
import { PluginServer } from '@theia/plugin-ext/lib/common/plugin-protocol';
import { TerminalFrontendContribution } from '@theia/terminal/lib/browser/terminal-frontend-contribution';
import { QuickOpenWorkspace } from '@theia/workspace/lib/browser/quick-open-workspace';
import { TerminalService } from '@theia/terminal/lib/browser/base/terminal-service';
import {
FileNavigatorCommands,
FILE_NAVIGATOR_TOGGLE_COMMAND_ID
} from '@theia/navigator/lib/browser/navigator-contribution';
import { FILE_NAVIGATOR_ID, FileNavigatorWidget } from '@theia/navigator/lib/browser';
import { SelectableTreeNode } from '@theia/core/lib/browser/tree/tree-selection';
import { UriComponents } from '@theia/plugin-ext/lib/common/uri-components';
import { FileService } from '@theia/filesystem/lib/browser/file-service';
import { CallHierarchyServiceProvider, CallHierarchyService } from '@theia/callhierarchy/lib/browser';
import { TypeHierarchyServiceProvider, TypeHierarchyService } from '@theia/typehierarchy/lib/browser';
import { MonacoTextModelService } from '@theia/monaco/lib/browser/monaco-text-model-service';
import {
fromCallHierarchyCalleeToModelCallHierarchyOutgoingCall,
fromCallHierarchyCallerToModelCallHierarchyIncomingCall,
fromItemHierarchyDefinition,
toItemHierarchyDefinition
} from '@theia/plugin-ext/lib/main/browser/hierarchy/hierarchy-types-converters';
import { CustomEditorOpener } from '@theia/plugin-ext/lib/main/browser/custom-editors/custom-editor-opener';
import { nls } from '@theia/core/lib/common/nls';
import { WindowService } from '@theia/core/lib/browser/window/window-service';
import * as monaco from '@theia/monaco-editor-core';
import { VSCodeExtensionUri } from '../common/plugin-vscode-uri';
import { CodeEditorWidgetUtil } from '@theia/plugin-ext/lib/main/browser/menus/vscode-theia-menu-mappings';
import { OutlineViewContribution } from '@theia/outline-view/lib/browser/outline-view-contribution';
import { Range } from '@theia/plugin';
import { MonacoLanguages } from '@theia/monaco/lib/browser/monaco-languages';
export namespace VscodeCommands {
export const GET_CODE_EXCHANGE_ENDPOINTS: Command = {
id: 'workbench.getCodeExchangeProxyEndpoints' // this command is used in the github auth built-in
// see: https://github.com/microsoft/vscode/blob/191be39e5ac872e03f9d79cc859d9917f40ad935/extensions/github-authentication/src/githubServer.ts#L60
};
export const OPEN: Command = {
id: 'vscode.open'
};
export const OPEN_WITH: Command = {
id: 'vscode.openWith'
};
export const OPEN_FOLDER: Command = {
id: 'vscode.openFolder'
};
export const DIFF: Command = {
id: 'vscode.diff'
};
export const INSTALL_FROM_VSIX: Command = {
id: 'workbench.extensions.installExtension'
};
}
// https://wicg.github.io/webusb/
export interface UsbDeviceData {
readonly deviceClass: number;
readonly deviceProtocol: number;
readonly deviceSubclass: number;
readonly deviceVersionMajor: number;
readonly deviceVersionMinor: number;
readonly deviceVersionSubminor: number;
readonly manufacturerName?: string;
readonly productId: number;
readonly productName?: string;
readonly serialNumber?: string;
readonly usbVersionMajor: number;
readonly usbVersionMinor: number;
readonly usbVersionSubminor: number;
readonly vendorId: number;
}
// https://wicg.github.io/serial/
export interface SerialPortData {
readonly usbVendorId?: number | undefined;
readonly usbProductId?: number | undefined;
}
// https://wicg.github.io/webhid/
export interface HidDeviceData {
readonly opened: boolean;
readonly vendorId: number;
readonly productId: number;
readonly productName: string;
readonly collections: [];
}
@injectable()
export class PluginVscodeCommandsContribution implements CommandContribution {
@inject(CommandService)
protected readonly commandService: CommandService;
@inject(ContextKeyService)
protected readonly contextKeyService: ContextKeyService;
@inject(EditorManager)
protected readonly editorManager: EditorManager;
@inject(ApplicationShell)
protected readonly shell: ApplicationShell;
@inject(DiffService)
protected readonly diffService: DiffService;
@inject(OpenerService)
protected readonly openerService: OpenerService;
@inject(ApplicationShellMouseTracker)
protected readonly mouseTracker: ApplicationShellMouseTracker;
@inject(QuickInputService) @optional()
protected readonly quickInput: QuickInputService;
@inject(WorkspaceService)
protected readonly workspaceService: WorkspaceService;
@inject(TerminalFrontendContribution)
protected readonly terminalContribution: TerminalFrontendContribution;
@inject(QuickOpenWorkspace)
protected readonly quickOpenWorkspace: QuickOpenWorkspace;
@inject(TerminalService)
protected readonly terminalService: TerminalService;
@inject(CodeEditorWidgetUtil)
protected readonly codeEditorWidgetUtil: CodeEditorWidgetUtil;
@inject(PluginServer)
protected readonly pluginServer: PluginServer;
@inject(FileService)
protected readonly fileService: FileService;
@inject(CallHierarchyServiceProvider)
protected readonly callHierarchyProvider: CallHierarchyServiceProvider;
@inject(TypeHierarchyServiceProvider)
protected readonly typeHierarchyProvider: TypeHierarchyServiceProvider;
@inject(MonacoTextModelService)
protected readonly textModelService: MonacoTextModelService;
@inject(WindowService)
protected readonly windowService: WindowService;
@inject(MessageService)
protected readonly messageService: MessageService;
@inject(OutlineViewContribution)
protected outlineViewContribution: OutlineViewContribution;
@inject(MonacoLanguages)
protected monacoLanguages: MonacoLanguages;
private async openWith(commandId: string, resource: URI, columnOrOptions?: ViewColumn | TextDocumentShowOptions, openerId?: string): Promise<boolean> {
if (!resource) {
throw new Error(`${commandId} command requires at least URI argument.`);
}
if (!URI.isUri(resource)) {
throw new Error(`Invalid argument for ${commandId} command with URI argument. Found ${resource}`);
}
let options: TextDocumentShowOptions | undefined;
if (typeof columnOrOptions === 'number') {
options = {
viewColumn: columnOrOptions
};
} else if (columnOrOptions) {
options = {
...columnOrOptions
};
}
const uri = new TheiaURI(resource);
const editorOptions = DocumentsMainImpl.toEditorOpenerOptions(this.shell, options);
let openHandler: OpenHandler | undefined;
if (typeof openerId === 'string') {
const lowerViewType = openerId.toLowerCase();
const openers = await this.openerService.getOpeners();
for (const opener of openers) {
const idLowerCase = opener.id.toLowerCase();
if (lowerViewType === idLowerCase) {
openHandler = opener;
break;
}
}
} else {
openHandler = await this.openerService.getOpener(uri, editorOptions);
}
if (openHandler) {
await openHandler.open(uri, editorOptions);
return true;
}
return false;
}
registerCommands(commands: CommandRegistry): void {
commands.registerCommand(VscodeCommands.GET_CODE_EXCHANGE_ENDPOINTS, {
execute: () => undefined // this is a dummy implementation: only used in the case of web apps, which is not supported yet.
});
commands.registerCommand(VscodeCommands.OPEN, {
isVisible: () => false,
execute: async (resource: URI | string, columnOrOptions?: ViewColumn | TextDocumentShowOptions) => {
if (typeof resource === 'string') {
resource = URI.parse(resource);
}
try {
await this.openWith(VscodeCommands.OPEN.id, resource, columnOrOptions);
} catch (error) {
const message = nls.localizeByDefault("Unable to open '{0}'", resource.path);
const reason = nls.localizeByDefault('Error: {0}', error.message);
this.messageService.error(`${message}\n${reason}`);
console.warn(error);
}
}
});
commands.registerCommand(VscodeCommands.OPEN_WITH, {
isVisible: () => false,
execute: async (resource: URI, viewType: string, columnOrOptions?: ViewColumn | TextDocumentShowOptions) => {
if (!viewType) {
throw new Error(`Running the contributed command: ${VscodeCommands.OPEN_WITH} failed.`);
}
if (viewType.toLowerCase() === 'default') {
return commands.executeCommand(VscodeCommands.OPEN.id, resource, columnOrOptions);
}
let result = await this.openWith(VscodeCommands.OPEN_WITH.id, resource, columnOrOptions, viewType);
if (!result) {
result = await this.openWith(VscodeCommands.OPEN_WITH.id, resource, columnOrOptions, CustomEditorOpener.toCustomEditorId(viewType));
}
if (!result) {
throw new Error(`Could not find an editor for '${viewType}'`);
}
}
});
interface IOpenFolderAPICommandOptions {
forceNewWindow?: boolean;
forceReuseWindow?: boolean;
noRecentEntry?: boolean;
}
commands.registerCommand(VscodeCommands.OPEN_FOLDER, {
isVisible: () => false,
execute: async (resource?: URI, arg: boolean | IOpenFolderAPICommandOptions = {}) => {
if (!resource) {
return commands.executeCommand(WorkspaceCommands.OPEN_WORKSPACE.id);
}
if (!URI.isUri(resource)) {
throw new Error(`Invalid argument for ${VscodeCommands.OPEN_FOLDER.id} command with URI argument. Found ${resource}`);
}
let options: WorkspaceInput | undefined;
if (typeof arg === 'boolean') {
options = { preserveWindow: !arg };
} else {
options = { preserveWindow: !arg.forceNewWindow };
}
this.workspaceService.open(new TheiaURI(resource), options);
}
});
commands.registerCommand(VscodeCommands.DIFF, {
isVisible: () => false,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
execute: async (left: URI, right: URI, label?: string, options?: TextDocumentShowOptions) => {
if (!left || !right) {
throw new Error(`${VscodeCommands.DIFF} command requires at least two URI arguments. Found left=${left}, right=${right} as arguments`);
}
if (!URI.isUri(left)) {
throw new Error(`Invalid argument for ${VscodeCommands.DIFF.id} command with left argument. Expecting URI left type but found ${left}`);
}
if (!URI.isUri(right)) {
throw new Error(`Invalid argument for ${VscodeCommands.DIFF.id} command with right argument. Expecting URI right type but found ${right}`);
}
const leftURI = new TheiaURI(left);
const editorOptions = DocumentsMainImpl.toEditorOpenerOptions(this.shell, options);
await this.diffService.openDiffEditor(leftURI, new TheiaURI(right), label, editorOptions);
}
});
// https://code.visualstudio.com/docs/getstarted/keybindings#_navigation
/*
* internally, in VS Code, any widget opened in the main area is represented as an editor
* operations below apply to them, but not to side-bar widgets, like the explorer
*
* in Theia, there are not such difference and any widget can be put in any area
* because of it we filter out editors from views based on `NavigatableWidget.is`
* and apply actions only to them
*/
if (!environment.electron.is() || isOSX) {
commands.registerCommand({ id: 'workbench.action.files.openFileFolder' }, {
execute: () => commands.executeCommand(WorkspaceCommands.OPEN.id)
});
}
commands.registerCommand({ id: 'workbench.action.files.openFile' }, {
execute: () => commands.executeCommand(WorkspaceCommands.OPEN_FILE.id)
});
commands.registerCommand({ id: 'workbench.action.files.openFolder' }, {
execute: () => commands.executeCommand(WorkspaceCommands.OPEN_FOLDER.id)
});
commands.registerCommand({ id: 'workbench.action.addRootFolder' }, {
execute: () => commands.executeCommand(WorkspaceCommands.ADD_FOLDER.id)
});
commands.registerCommand({ id: 'workbench.action.saveWorkspaceAs' }, {
execute: () => commands.executeCommand(WorkspaceCommands.SAVE_WORKSPACE_AS.id)
});
commands.registerCommand({ id: 'workbench.action.gotoLine' }, {
execute: () => commands.executeCommand(EditorCommands.GOTO_LINE_COLUMN.id)
});
commands.registerCommand({ id: 'workbench.action.quickOpen' }, {
execute: (prefix?: unknown) => this.quickInput.open(typeof prefix === 'string' ? prefix : '')
});
commands.registerCommand({ id: 'workbench.action.openSettings' }, {
execute: (query?: string) => commands.executeCommand(CommonCommands.OPEN_PREFERENCES.id, query)
});
commands.registerCommand({ id: 'workbench.action.openWorkspaceConfigFile' }, {
execute: () => commands.executeCommand(WorkspaceCommands.OPEN_WORKSPACE_FILE.id)
});
commands.registerCommand({ id: 'workbench.files.action.refreshFilesExplorer' }, {
execute: () => commands.executeCommand(FileNavigatorCommands.REFRESH_NAVIGATOR.id)
});
commands.registerCommand({ id: VscodeCommands.INSTALL_FROM_VSIX.id }, {
execute: async (vsixUriOrExtensionId: TheiaURI | UriComponents | string) => {
if (typeof vsixUriOrExtensionId === 'string') {
await this.pluginServer.deploy(VSCodeExtensionUri.fromId(vsixUriOrExtensionId).toString());
} else {
const uriPath = isUriComponents(vsixUriOrExtensionId) ? URI.revive(vsixUriOrExtensionId).fsPath : await this.fileService.fsPath(vsixUriOrExtensionId);
await this.pluginServer.deploy(`local-file:${uriPath}`);
}
}
});
commands.registerCommand({ id: 'workbench.action.files.save', }, {
execute: (uri?: monaco.Uri) => {
if (uri) {
const uriString = uri.toString();
const widget = this.shell.widgets.find(w => {
const resourceUri = Saveable.is(w) && NavigatableWidget.is(w) && w.getResourceUri();
return (resourceUri && resourceUri.toString()) === uriString;
});
if (Saveable.is(widget)) {
Saveable.save(widget);
}
} else {
this.shell.save();
}
}
});
commands.registerCommand({ id: 'workbench.action.files.saveAll', }, {
execute: () => this.shell.saveAll()
});
commands.registerCommand({ id: 'workbench.action.closeActiveEditor' }, {
execute: () => commands.executeCommand(CommonCommands.CLOSE_MAIN_TAB.id)
});
commands.registerCommand({ id: 'workbench.action.closeOtherEditors' }, {
execute: async (uri?: monaco.Uri) => {
let editor = this.editorManager.currentEditor || this.shell.currentWidget;
if (uri) {
const uriString = uri.toString();
editor = this.editorManager.all.find(e => {
const resourceUri = e.getResourceUri();
return (resourceUri && resourceUri.toString()) === uriString;
});
}
const toClose = this.shell.widgets.filter(widget => widget !== editor && this.codeEditorWidgetUtil.is(widget));
await this.shell.closeMany(toClose);
}
});
const performActionOnGroup = (
cb: (
tabBarOrArea: TabBar<Widget> | ApplicationShell.Area,
filter?: ((title: Title<Widget>, index: number) => boolean) | undefined
) => void,
uri?: monaco.Uri
): void => {
let editor = this.editorManager.currentEditor || this.shell.currentWidget;
if (uri) {
const uriString = uri.toString();
editor = this.editorManager.all.find(e => {
const resourceUri = e.getResourceUri();
return (resourceUri && resourceUri.toString()) === uriString;
});
}
if (editor) {
const tabBar = this.shell.getTabBarFor(editor);
if (tabBar) {
cb(tabBar, ({ owner }) => this.codeEditorWidgetUtil.is(owner));
}
}
};
commands.registerCommand({
id: 'workbench.action.closeEditorsInGroup',
label: nls.localizeByDefault('Close All Editors in Group')
}, {
execute: (uri?: monaco.Uri) => performActionOnGroup(this.shell.closeTabs, uri)
});
commands.registerCommand({
id: 'workbench.files.saveAllInGroup',
label: nls.localizeByDefault('Save All in Group')
}, {
execute: (uri?: monaco.Uri) => performActionOnGroup(this.shell.saveTabs, uri)
});
commands.registerCommand({ id: 'workbench.action.closeEditorsInOtherGroups' }, {
execute: () => {
const editor = this.editorManager.currentEditor || this.shell.currentWidget;
if (editor) {
const editorTabBar = this.shell.getTabBarFor(editor);
for (const tabBar of this.shell.allTabBars) {
if (tabBar !== editorTabBar) {
this.shell.closeTabs(tabBar,
({ owner }) => this.codeEditorWidgetUtil.is(owner)
);
}
}
}
}
});
commands.registerCommand({ id: 'workbench.action.closeEditorsToTheLeft' }, {
execute: () => {
const editor = this.editorManager.currentEditor || this.shell.currentWidget;
if (editor) {
const tabBar = this.shell.getTabBarFor(editor);
if (tabBar) {
let left = true;
this.shell.closeTabs(tabBar,
({ owner }) => {
if (owner === editor) {
left = false;
return false;
}
return left && this.codeEditorWidgetUtil.is(owner);
}
);
}
}
}
});
commands.registerCommand({ id: 'workbench.action.closeEditorsToTheRight' }, {
execute: () => {
const editor = this.editorManager.currentEditor || this.shell.currentWidget;
if (editor) {
const tabBar = this.shell.getTabBarFor(editor);
if (tabBar) {
let left = true;
this.shell.closeTabs(tabBar,
({ owner }) => {
if (owner === editor) {
left = false;
return false;
}
return !left && this.codeEditorWidgetUtil.is(owner);
}
);
}
}
}
});
commands.registerCommand({ id: 'workbench.action.closeAllEditors' }, {
execute: async () => {
const toClose = this.shell.widgets.filter(widget => this.codeEditorWidgetUtil.is(widget));
await this.shell.closeMany(toClose);
}
});
commands.registerCommand({ id: 'workbench.action.nextEditor' }, {
execute: () => this.shell.activateNextTab()
});
commands.registerCommand({ id: 'workbench.action.previousEditor' }, {
execute: () => this.shell.activatePreviousTab()
});
commands.registerCommand({ id: 'workbench.action.navigateBack' }, {
execute: () => commands.executeCommand(EditorCommands.GO_BACK.id)
});
commands.registerCommand({ id: 'workbench.action.navigateForward' }, {
execute: () => commands.executeCommand(EditorCommands.GO_FORWARD.id)
});
commands.registerCommand({ id: 'workbench.action.navigateToLastEditLocation' }, {
execute: () => commands.executeCommand(EditorCommands.GO_LAST_EDIT.id)
});
commands.registerCommand({ id: 'openInTerminal' }, {
execute: (resource: URI) => this.terminalContribution.openInTerminal(new TheiaURI(resource.toString()))
});
commands.registerCommand({ id: 'workbench.action.reloadWindow' }, {
execute: () => {
this.windowService.reload();
}
});
/**
* TODO:
* Open Next: workbench.action.openNextRecentlyUsedEditorInGroup
* Open Previous: workbench.action.openPreviousRecentlyUsedEditorInGroup
* Copy Path of Active File: workbench.action.files.copyPathOfActiveFile
* Reveal Active File in Windows: workbench.action.files.revealActiveFileInWindows
* Show Opened File in New Window: workbench.action.files.showOpenedFileInNewWindow
* Compare Opened File With: workbench.files.action.compareFileWith
*/
// Register built-in language service commands
// see https://code.visualstudio.com/api/references/commands
/* eslint-disable @typescript-eslint/no-explicit-any */
// TODO register other `vscode.execute...` commands.
// see https://github.com/microsoft/vscode/blob/master/src/vs/workbench/api/common/extHostApiCommands.ts
commands.registerCommand(
{
id: 'vscode.executeDefinitionProvider'
},
{
execute: ((resource: URI, position: Position) =>
commands.executeCommand<Location[]>('_executeDefinitionProvider', monaco.Uri.from(resource), position))
}
);
commands.registerCommand(
{
id: 'vscode.executeDeclarationProvider'
},
{
execute: ((resource: URI, position: Position) =>
commands.executeCommand<Location[]>('_executeDeclarationProvider', monaco.Uri.from(resource), position))
}
);
commands.registerCommand(
{
id: 'vscode.executeTypeDefinitionProvider'
},
{
execute: ((resource: URI, position: Position) =>
commands.executeCommand<Location[]>('_executeTypeDefinitionProvider', monaco.Uri.from(resource), position))
}
);
commands.registerCommand(
{
id: 'vscode.executeImplementationProvider'
},
{
execute: ((resource: URI, position: Position) =>
commands.executeCommand<Location[]>('_executeImplementationProvider', monaco.Uri.from(resource), position))
}
);
commands.registerCommand(
{
id: 'vscode.executeHoverProvider'
},
{
execute: ((resource: URI, position: Position) =>
commands.executeCommand<Hover[]>('_executeHoverProvider', monaco.Uri.from(resource), position))
}
);
commands.registerCommand(
{
id: 'vscode.executeDocumentHighlights'
},
{
execute: ((resource: URI, position: Position) =>
commands.executeCommand<DocumentHighlight[]>('_executeDocumentHighlights', monaco.Uri.from(resource), position))
}
);
commands.registerCommand(
{
id: 'vscode.executeReferenceProvider'
},
{
execute: ((resource: URI, position: Position) => commands.executeCommand<Location[]>('_executeReferenceProvider', monaco.Uri.from(resource), position))
}
);
commands.registerCommand(
{
id: 'vscode.executeDocumentSymbolProvider'
},
{
execute: (resource: URI) => commands.executeCommand('_executeDocumentSymbolProvider',
monaco.Uri.parse(resource.toString())
).then((value: any) => { // eslint-disable-line @typescript-eslint/no-explicit-any
if (!Array.isArray(value) || value === undefined) {
return undefined;
}
return value.map(loc => toMergedSymbol(resource, loc));
})
}
);
commands.registerCommand(
{
id: 'vscode.executeFormatDocumentProvider'
},
{
execute: ((resource: URI, options: FormattingOptions) =>
commands.executeCommand<TextEdit[]>('_executeFormatDocumentProvider', monaco.Uri.from(resource), options))
}
);
commands.registerCommand(
{
id: 'vscode.executeFormatRangeProvider'
},
{
execute: ((resource: URI, range: Range, options: FormattingOptions) =>
commands.executeCommand<TextEdit[]>('_executeFormatRangeProvider', monaco.Uri.from(resource), range, options))
}
);
commands.registerCommand(
{
id: 'vscode.executeFormatOnTypeProvider'
},
{
execute: ((resource: URI, position: Position, ch: string, options: FormattingOptions) =>
commands.executeCommand<TextEdit[]>('_executeFormatOnTypeProvider', monaco.Uri.from(resource), position, ch, options))
}
);
commands.registerCommand(
{
id: 'vscode.executeFoldingRangeProvider'
},
{
execute: ((resource: URI, position: Position) =>
commands.executeCommand<TextEdit[]>('_executeFoldingRangeProvider', monaco.Uri.from(resource), position))
}
);
commands.registerCommand(
{
id: 'vscode.executeCodeActionProvider'
},
{
execute: ((resource: URI, range: Range, kind?: string, itemResolveCount?: number) =>
commands.executeCommand<TextEdit[]>('_executeCodeActionProvider', monaco.Uri.from(resource), range, kind, itemResolveCount))
}
);
commands.registerCommand(
{
id: 'vscode.executeWorkspaceSymbolProvider'
},
{
execute: async (queryString: string) =>
(await Promise.all(
this.monacoLanguages.workspaceSymbolProviders
.map(async provider => provider.provideWorkspaceSymbols({ query: queryString }, new CancellationTokenSource().token))))
.flatMap(symbols => symbols)
.filter(symbols => !!symbols)
}
);
commands.registerCommand(
{
id: 'vscode.prepareCallHierarchy'
},
{
execute: async (resource: URI, position: Position): Promise<CallHierarchyItem[]> => {
const provider = await this.getCallHierarchyServiceForUri(resource);
const definition = await provider?.getRootDefinition(
resource.path,
toPosition(position),
new CancellationTokenSource().token
);
if (definition) {
return definition.items.map(item => fromItemHierarchyDefinition(item));
};
return [];
}
}
);
commands.registerCommand(
{
id: 'vscode.provideIncomingCalls'
},
{
execute: async (item: CallHierarchyItem): Promise<CallHierarchyIncomingCall[]> => {
const resource = URI.from(item.uri);
const provider = await this.getCallHierarchyServiceForUri(resource);
const incomingCalls = await provider?.getCallers(
toItemHierarchyDefinition(item),
new CancellationTokenSource().token,
);
if (incomingCalls) {
return incomingCalls.map(fromCallHierarchyCallerToModelCallHierarchyIncomingCall);
}
return [];
},
},
);
commands.registerCommand(
{
id: 'vscode.provideOutgoingCalls'
},
{
execute: async (item: CallHierarchyItem): Promise<CallHierarchyOutgoingCall[]> => {
const resource = URI.from(item.uri);
const provider = await this.getCallHierarchyServiceForUri(resource);
const outgoingCalls = await provider?.getCallees?.(
toItemHierarchyDefinition(item),
new CancellationTokenSource().token,
);
if (outgoingCalls) {
return outgoingCalls.map(fromCallHierarchyCalleeToModelCallHierarchyOutgoingCall);
}
return [];
}
}
);
commands.registerCommand(
{
id: 'vscode.prepareTypeHierarchy'
},
{
execute: async (resource: URI, position: Position): Promise<TypeHierarchyItem[]> => {
const provider = await this.getTypeHierarchyServiceForUri(resource);
const session = await provider?.prepareSession(
resource.path,
toPosition(position),
new CancellationTokenSource().token
);
return session ? session.items.map(item => fromItemHierarchyDefinition(item)) : [];
}
}
);
commands.registerCommand(
{
id: 'vscode.provideSupertypes'
},
{
execute: async (item: TypeHierarchyItem): Promise<TypeHierarchyItem[]> => {
if (!item._sessionId || !item._itemId) {
return [];
}
const resource = URI.from(item.uri);
const provider = await this.getTypeHierarchyServiceForUri(resource);
const items = await provider?.provideSuperTypes(
item._sessionId,
item._itemId,
new CancellationTokenSource().token
);
return (items ? items : []).map(typeItem => fromItemHierarchyDefinition(typeItem));
}
}
);
commands.registerCommand(
{
id: 'vscode.provideSubtypes'
},
{
execute: async (item: TypeHierarchyItem): Promise<TypeHierarchyItem[]> => {
if (!item._sessionId || !item._itemId) {
return [];
}
const resource = URI.from(item.uri);
const provider = await this.getTypeHierarchyServiceForUri(resource);
const items = await provider?.provideSubTypes(
item._sessionId, item._itemId,
new CancellationTokenSource().token
);
return (items ? items : []).map(typeItem => fromItemHierarchyDefinition(typeItem));
}
}
);
commands.registerCommand({
id: 'workbench.action.openRecent'
}, {
execute: () => this.quickOpenWorkspace.select()
});
commands.registerCommand({
id: 'explorer.newFolder'
}, {
execute: () => commands.executeCommand(WorkspaceCommands.NEW_FOLDER.id)
});
commands.registerCommand({
id: 'workbench.action.terminal.sendSequence'
}, {
execute: (args?: { text?: string }) => {
if (args === undefined || args.text === undefined) {
return;
}
const currentTerminal = this.terminalService.currentTerminal;
if (currentTerminal === undefined) {
return;
}
currentTerminal.sendText(args.text);
}
});
commands.registerCommand({
id: 'workbench.action.terminal.kill'
}, {
execute: () => {
const currentTerminal = this.terminalService.currentTerminal;
if (currentTerminal === undefined) {
return;
}
currentTerminal.dispose();
}
});
commands.registerCommand({
id: 'workbench.view.explorer'
}, {
execute: () => commands.executeCommand(FileNavigatorCommands.FOCUS.id)
});
commands.registerCommand({
id: 'copyFilePath'
}, {
execute: () => commands.executeCommand(CommonCommands.COPY_PATH.id)
});
commands.registerCommand({
id: 'copyRelativeFilePath'
}, {
execute: () => commands.executeCommand(WorkspaceCommands.COPY_RELATIVE_FILE_PATH.id)
});
commands.registerCommand({
id: 'revealInExplorer'
}, {
execute: async (resource: URI | object) => {
if (!URI.isUri(resource)) {
return;
}
let navigator = await this.shell.revealWidget(FILE_NAVIGATOR_ID);
if (!navigator) {
await this.commandService.executeCommand(FILE_NAVIGATOR_TOGGLE_COMMAND_ID);
navigator = await this.shell.revealWidget(FILE_NAVIGATOR_ID);
}
if (navigator instanceof FileNavigatorWidget) {
const model = navigator.model;
const node = await model.revealFile(new TheiaURI(resource));
if (SelectableTreeNode.is(node)) {
model.selectNode(node);
}
}
}
});
commands.registerCommand({
id: 'workbench.experimental.requestUsbDevice'
}, {
execute: async (options?: { filters?: unknown[] }): Promise<UsbDeviceData | undefined> => {
const usb = (navigator as any).usb;
if (!usb) {
return undefined;
}
const device = await usb.requestDevice({ filters: options?.filters ?? [] });
if (!device) {
return undefined;
}
return {
deviceClass: device.deviceClass,
deviceProtocol: device.deviceProtocol,
deviceSubclass: device.deviceSubclass,
deviceVersionMajor: device.deviceVersionMajor,
deviceVersionMinor: device.deviceVersionMinor,
deviceVersionSubminor: device.deviceVersionSubminor,
manufacturerName: device.manufacturerName,
productId: device.productId,
productName: device.productName,
serialNumber: device.serialNumber,
usbVersionMajor: device.usbVersionMajor,
usbVersionMinor: device.usbVersionMinor,
usbVersionSubminor: device.usbVersionSubminor,
vendorId: device.vendorId,
};
}
});
commands.registerCommand({
id: 'workbench.experimental.requestSerialPort'
}, {
execute: async (options?: { filters?: unknown[] }): Promise<SerialPortData | undefined> => {
const serial = (navigator as any).serial;
if (!serial) {
return undefined;
}
const port = await serial.requestPort({ filters: options?.filters ?? [] });
if (!port) {
return undefined;
}
const info = port.getInfo();
return {
usbVendorId: info.usbVendorId,
usbProductId: info.usbProductId
};
}
});
commands.registerCommand({
id: 'workbench.experimental.requestHidDevice'
}, {
execute: async (options?: { filters?: unknown[] }): Promise<HidDeviceData | undefined> => {
const hid = (navigator as any).hid;
if (!hid) {
return undefined;
}
const devices = await hid.requestDevice({ filters: options?.filters ?? [] });
if (!devices.length) {
return undefined;
}
const device = devices[0];
return {
opened: device.opened,
vendorId: device.vendorId,
productId: device.productId,
productName: device.productName,
collections: device.collections
};
}
});
// required by Jupyter for the show table of contents action
commands.registerCommand({ id: 'outline.focus' }, {
execute: () => this.outlineViewContribution.openView({ activate: true })
});
}
private async resolveLanguageId(resource: URI): Promise<string> {
const reference = await this.textModelService.createModelReference(resource);
const languageId = reference.object.languageId;
reference.dispose();
return languageId;
}
protected async getCallHierarchyServiceForUri(resource: URI): Promise<CallHierarchyService | undefined> {
const languageId = await this.resolveLanguageId(resource);
return this.callHierarchyProvider.get(languageId, new TheiaURI(resource));
}
protected async getTypeHierarchyServiceForUri(resource: URI): Promise<TypeHierarchyService | undefined> {
const languageId = await this.resolveLanguageId(resource);
return this.typeHierarchyProvider.get(languageId, new TheiaURI(resource));
}
}