-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
menus-contribution-handler.ts
367 lines (337 loc) · 18.2 KB
/
menus-contribution-handler.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
/********************************************************************************
* 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 WITH Classpath-exception-2.0
********************************************************************************/
// tslint:disable:no-any
import CodeUri from 'vscode-uri';
import { injectable, inject } from 'inversify';
import { MenuPath, ILogger, CommandRegistry, Command, Mutable, MenuAction, SelectionService, CommandHandler, Disposable, DisposableCollection } from '@theia/core';
import { EDITOR_CONTEXT_MENU, EditorWidget } from '@theia/editor/lib/browser';
import { MenuModelRegistry } from '@theia/core/lib/common';
import { Emitter } from '@theia/core/lib/common/event';
import { TabBarToolbarRegistry, TabBarToolbarItem } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import { NAVIGATOR_CONTEXT_MENU } from '@theia/navigator/lib/browser/navigator-contribution';
import { QuickCommandService } from '@theia/core/lib/browser/quick-open/quick-command-service';
import { VIEW_ITEM_CONTEXT_MENU, TreeViewWidget, VIEW_ITEM_INLINE_MNUE } from '../view/tree-view-widget';
import { PluginContribution, Menu, ScmCommandArg, TreeViewSelection } from '../../../common';
import { DebugStackFramesWidget } from '@theia/debug/lib/browser/view/debug-stack-frames-widget';
import { DebugThreadsWidget } from '@theia/debug/lib/browser/view/debug-threads-widget';
import { TreeWidgetSelection } from '@theia/core/lib/browser/tree/tree-widget-selection';
import { ScmWidget } from '@theia/scm/lib/browser/scm-widget';
import { ScmService } from '@theia/scm/lib/browser/scm-service';
import { ScmRepository } from '@theia/scm/lib/browser/scm-repository';
import { PluginScmProvider, PluginScmResourceGroup, PluginScmResource } from '../scm-main';
import { ResourceContextKey } from '@theia/core/lib/browser/resource-context-key';
import { PluginViewWidget } from '../view/plugin-view-widget';
import { ViewContextKeyService } from '../view/view-context-key-service';
import { WebviewWidget } from '../webview/webview';
import { Navigatable } from '@theia/core/lib/browser/navigatable';
import { ContextKeyService } from '@theia/core/lib/browser/context-key-service';
type CodeEditorWidget = EditorWidget | WebviewWidget;
export namespace CodeEditorWidget {
export function is(arg: any): arg is CodeEditorWidget {
return arg instanceof EditorWidget || arg instanceof WebviewWidget;
}
export function getResourceUri(editor: CodeEditorWidget): CodeUri | undefined {
const resourceUri = Navigatable.is(editor) && editor.getResourceUri();
return resourceUri ? resourceUri['codeUri'] : undefined;
}
}
@injectable()
export class MenusContributionPointHandler {
@inject(MenuModelRegistry)
protected readonly menuRegistry: MenuModelRegistry;
@inject(CommandRegistry)
protected readonly commands: CommandRegistry;
@inject(ILogger)
protected readonly logger: ILogger;
@inject(ScmService)
protected readonly scmService: ScmService;
@inject(QuickCommandService)
protected readonly quickCommandService: QuickCommandService;
@inject(TabBarToolbarRegistry)
protected readonly tabBarToolbar: TabBarToolbarRegistry;
@inject(SelectionService)
protected readonly selectionService: SelectionService;
@inject(ResourceContextKey)
protected readonly resourceContextKey: ResourceContextKey;
@inject(ViewContextKeyService)
protected readonly viewContextKeys: ViewContextKeyService;
@inject(ContextKeyService)
protected readonly contextKeyService: ContextKeyService;
handle(contributions: PluginContribution): Disposable {
const allMenus = contributions.menus;
if (!allMenus) {
return Disposable.NULL;
}
const toDispose = new DisposableCollection();
for (const location in allMenus) {
if (location === 'commandPalette') {
for (const menu of allMenus[location]) {
if (menu.when) {
toDispose.push(this.quickCommandService.pushCommandContext(menu.command, menu.when));
}
}
} else if (location === 'editor/title') {
for (const action of allMenus[location]) {
toDispose.push(this.registerTitleAction(location, action, {
execute: widget => CodeEditorWidget.is(widget) && this.commands.executeCommand(action.command, CodeEditorWidget.getResourceUri(widget)),
isEnabled: widget => CodeEditorWidget.is(widget) && this.commands.isEnabled(action.command, CodeEditorWidget.getResourceUri(widget)),
isVisible: widget => CodeEditorWidget.is(widget) && this.commands.isVisible(action.command, CodeEditorWidget.getResourceUri(widget))
}));
}
} else if (location === 'view/title') {
for (const action of allMenus[location]) {
toDispose.push(this.registerTitleAction(location, { ...action, when: undefined }, {
execute: widget => widget instanceof PluginViewWidget && this.commands.executeCommand(action.command),
isEnabled: widget => widget instanceof PluginViewWidget &&
this.viewContextKeys.with({ view: widget.options.viewId }, () =>
this.commands.isEnabled(action.command) && this.viewContextKeys.match(action.when)),
isVisible: widget => widget instanceof PluginViewWidget &&
this.viewContextKeys.with({ view: widget.options.viewId }, () =>
this.commands.isVisible(action.command) && this.viewContextKeys.match(action.when))
}));
}
} else if (location === 'view/item/context') {
for (const menu of allMenus[location]) {
const inline = menu.group && /^inline/.test(menu.group) || false;
const menuPath = inline ? VIEW_ITEM_INLINE_MNUE : VIEW_ITEM_CONTEXT_MENU;
toDispose.push(this.registerTreeMenuAction(menuPath, menu));
}
} else if (location === 'scm/title') {
for (const action of allMenus[location]) {
toDispose.push(this.registerScmTitleAction(location, action));
}
} else if (location === 'scm/resourceGroup/context') {
for (const menu of allMenus[location]) {
const inline = menu.group && /^inline/.test(menu.group) || false;
const menuPath = inline ? ScmWidget.RESOURCE_GROUP_INLINE_MENU : ScmWidget.RESOURCE_GROUP_CONTEXT_MENU;
toDispose.push(this.registerScmMenuAction(menuPath, menu));
}
} else if (location === 'scm/resourceState/context') {
for (const menu of allMenus[location]) {
const inline = menu.group && /^inline/.test(menu.group) || false;
const menuPath = inline ? ScmWidget.RESOURCE_INLINE_MENU : ScmWidget.RESOURCE_CONTEXT_MENU;
toDispose.push(this.registerScmMenuAction(menuPath, menu));
}
} else if (location === 'debug/callstack/context') {
for (const menu of allMenus[location]) {
for (const menuPath of [DebugStackFramesWidget.CONTEXT_MENU, DebugThreadsWidget.CONTEXT_MENU]) {
toDispose.push(this.registerMenuAction(menuPath, menu, command => ({
execute: (...args) => this.commands.executeCommand(command, args[0]),
isEnabled: (...args) => this.commands.isEnabled(command, args[0]),
isVisible: (...args) => this.commands.isVisible(command, args[0])
})));
}
}
} else if (allMenus.hasOwnProperty(location)) {
const menuPaths = MenusContributionPointHandler.parseMenuPaths(location);
if (!menuPaths.length) {
this.logger.warn(`Plugin contributes items to a menu with invalid identifier: ${location}`);
continue;
}
const menus = allMenus[location];
menus.forEach(menu => {
for (const menuPath of menuPaths) {
toDispose.push(this.registerGlobalMenuAction(menuPath, menu));
}
});
}
}
return toDispose;
}
protected static parseMenuPaths(value: string): MenuPath[] {
switch (value) {
case 'editor/context': return [EDITOR_CONTEXT_MENU];
case 'explorer/context': return [NAVIGATOR_CONTEXT_MENU];
}
return [];
}
protected registerTreeMenuAction(menuPath: MenuPath, menu: Menu): Disposable {
return this.registerMenuAction(menuPath, menu, command => ({
execute: (...args) => this.commands.executeCommand(command, ...this.toTreeArgs(...args)),
isEnabled: (...args) => this.commands.isEnabled(command, ...this.toTreeArgs(...args)),
isVisible: (...args) => this.commands.isVisible(command, ...this.toTreeArgs(...args))
}));
}
protected toTreeArgs(...args: any[]): any[] {
const treeArgs: any[] = [];
for (const arg of args) {
if (TreeViewSelection.is(arg)) {
treeArgs.push(arg);
}
}
return treeArgs;
}
protected registerTitleAction(location: string, action: Menu, handler: CommandHandler): Disposable {
const toDispose = new DisposableCollection();
const id = this.createSyntheticCommandId(action.command, { prefix: `__plugin.${location.replace('/', '.')}.action.` });
const command: Command = { id };
toDispose.push(this.commands.registerCommand(command, handler));
const { when } = action;
const whenKeys = when && this.contextKeyService.parseKeys(when);
let onDidChange;
if (whenKeys && whenKeys.size) {
const onDidChangeEmitter = new Emitter<void>();
toDispose.push(onDidChangeEmitter);
onDidChange = onDidChangeEmitter.event;
this.contextKeyService.onDidChange.maxListeners = this.contextKeyService.onDidChange.maxListeners + 1;
toDispose.push(this.contextKeyService.onDidChange(event => {
if (event.affects(whenKeys)) {
onDidChangeEmitter.fire(undefined);
}
}));
toDispose.push(Disposable.create(() => {
this.contextKeyService.onDidChange.maxListeners = this.contextKeyService.onDidChange.maxListeners - 1;
}));
}
// handle group and priority
// if group is empty or white space is will be set to navigation
// ' ' => ['navigation', 0]
// 'navigation@1' => ['navigation', 1]
// '1_rest-client@2' => ['1_rest-client', 2]
// if priority is not a number it will be set to 0
// navigation@test => ['navigation', 0]
const [group, sort] = (action.group || 'navigation').split('@');
const item: Mutable<TabBarToolbarItem> = { id, command: id, group: group.trim() || 'navigation', priority: ~~sort || undefined, when, onDidChange };
toDispose.push(this.tabBarToolbar.registerItem(item));
toDispose.push(this.onDidRegisterCommand(action.command, pluginCommand => {
command.category = pluginCommand.category;
item.tooltip = pluginCommand.label;
if (group === 'navigation') {
command.iconClass = pluginCommand.iconClass;
}
}));
return toDispose;
}
protected registerScmTitleAction(location: string, action: Menu): Disposable {
const selectedRepository = () => this.toScmArgs(this.scmService.selectedRepository);
return this.registerTitleAction(location, action, {
execute: widget => widget instanceof ScmWidget && this.commands.executeCommand(action.command, selectedRepository()),
isEnabled: widget => widget instanceof ScmWidget && this.commands.isEnabled(action.command, selectedRepository()),
isVisible: widget => widget instanceof ScmWidget && this.commands.isVisible(action.command, selectedRepository())
});
}
protected registerScmMenuAction(menuPath: MenuPath, menu: Menu): Disposable {
return this.registerMenuAction(menuPath, menu, command => ({
execute: (...args) => this.commands.executeCommand(command, ...this.toScmArgs(...args)),
isEnabled: (...args) => this.commands.isEnabled(command, ...this.toScmArgs(...args)),
isVisible: (...args) => this.commands.isVisible(command, ...this.toScmArgs(...args))
}));
}
protected toScmArgs(...args: any[]): any[] {
const scmArgs: any[] = [];
for (const arg of args) {
const scmArg = this.toScmArg(arg);
if (scmArg) {
scmArgs.push(scmArg);
}
}
return scmArgs;
}
protected toScmArg(arg: any): ScmCommandArg | undefined {
if (arg instanceof ScmRepository && arg.provider instanceof PluginScmProvider) {
return {
sourceControlHandle: arg.provider.handle
};
}
if (arg instanceof PluginScmResourceGroup) {
return {
sourceControlHandle: arg.provider.handle,
resourceGroupHandle: arg.handle
};
}
if (arg instanceof PluginScmResource) {
return {
sourceControlHandle: arg.group.provider.handle,
resourceGroupHandle: arg.group.handle,
resourceStateHandle: arg.handle
};
}
}
protected registerGlobalMenuAction(menuPath: MenuPath, menu: Menu): Disposable {
const selectedResource = () => {
const selection = this.selectionService.selection;
if (TreeWidgetSelection.is(selection) && selection.source instanceof TreeViewWidget && selection[0]) {
return selection.source.toTreeViewSelection(selection[0]);
}
const uri = this.resourceContextKey.get();
return uri ? uri['codeUri'] : undefined;
};
return this.registerMenuAction(menuPath, menu, command => ({
execute: () => this.commands.executeCommand(command, selectedResource()),
isEnabled: () => this.commands.isEnabled(command, selectedResource()),
isVisible: () => this.commands.isVisible(command, selectedResource())
}));
}
protected registerMenuAction(menuPath: MenuPath, menu: Menu, handler: (command: string) => CommandHandler): Disposable {
const toDispose = new DisposableCollection();
const commandId = this.createSyntheticCommandId(menu.command, { prefix: '__plugin.menu.action.' });
const command: Command = { id: commandId };
toDispose.push(this.commands.registerCommand(command, handler(menu.command)));
toDispose.push(this.quickCommandService.pushCommandContext(commandId, 'false'));
let altId: string | undefined;
if (menu.alt) {
altId = this.createSyntheticCommandId(menu.alt, { prefix: '__plugin.menu.action.' });
const alt: Command = { id: altId };
toDispose.push(this.commands.registerCommand(alt, handler(menu.alt)));
toDispose.push(this.quickCommandService.pushCommandContext(altId, 'false'));
toDispose.push(this.onDidRegisterCommand(menu.alt, pluginCommand => {
alt.category = pluginCommand.category;
alt.label = pluginCommand.label;
if (inline) {
alt.iconClass = pluginCommand.iconClass;
}
}));
}
const { when } = menu;
const [group = '', order = undefined] = (menu.group || '').split('@');
const action: MenuAction = { commandId, alt: altId, order, when };
const inline = /^inline/.test(group);
menuPath = inline ? menuPath : [...menuPath, group];
toDispose.push(this.menuRegistry.registerMenuAction(menuPath, action));
toDispose.push(this.onDidRegisterCommand(menu.command, pluginCommand => {
command.category = pluginCommand.category;
command.label = pluginCommand.label;
if (inline) {
command.iconClass = pluginCommand.iconClass;
}
}));
return toDispose;
}
protected createSyntheticCommandId(command: string, { prefix }: { prefix: string }): string {
let id = prefix + command;
let index = 0;
while (this.commands.getCommand(id)) {
id = prefix + command + ':' + index;
index++;
}
return id;
}
protected onDidRegisterCommand(id: string, cb: (command: Command) => void): Disposable {
const command = this.commands.getCommand(id);
if (command) {
cb(command);
return Disposable.NULL;
}
const toDispose = new DisposableCollection();
// Registering a menu action requires the related command to be already registered.
// But Theia plugin registers the commands dynamically via the Commands API.
// Let's wait for ~2 sec. It should be enough to finish registering all the contributed commands.
// FIXME: remove this workaround (timer) once the https://github.com/theia-ide/theia/issues/3344 is fixed
const handle = setTimeout(() => toDispose.push(this.onDidRegisterCommand(id, cb)), 2000);
toDispose.push(Disposable.create(() => clearTimeout(handle)));
return toDispose;
}
}