/
commandsQuickAccess.ts
266 lines (227 loc) · 11.1 KB
/
commandsQuickAccess.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { ICommandQuickPick, CommandsHistory } from 'vs/platform/quickinput/browser/commandsQuickAccess';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IMenuService, MenuId, MenuItemAction, SubmenuItemAction, Action2 } from 'vs/platform/actions/common/actions';
// import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { CancellationToken } from 'vs/base/common/cancellation';
// import { timeout } from 'vs/base/common/async';
import { AbstractEditorCommandsQuickAccessProvider } from 'vs/editor/contrib/quickAccess/browser/commandsQuickAccess';
import { IEditor } from 'vs/editor/common/editorCommon';
import { Language } from 'vs/base/common/platform';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { DefaultQuickAccessFilterValue } from 'vs/platform/quickinput/common/quickAccess';
import { IConfigurationChangeEvent, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkbenchQuickAccessConfiguration } from 'vs/workbench/browser/quickaccess';
import { Codicon } from 'vs/base/common/codicons';
import { ThemeIcon } from 'vs/base/common/themables';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { TriggerAction } from 'vs/platform/quickinput/browser/pickerQuickAccess';
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
import { stripIcons } from 'vs/base/common/iconLabels';
import { isFirefox } from 'vs/base/browser/browser';
import { IProductService } from 'vs/platform/product/common/productService';
import { ISemanticSimilarityService } from 'vs/workbench/services/semanticSimilarity/common/semanticSimilarityService';
import { timeout } from 'vs/base/common/async';
export class CommandsQuickAccessProvider extends AbstractEditorCommandsQuickAccessProvider {
// TODO: bring this back once we have a chosen strategy for FastAndSlowPicks where Fast is also Promise based
// If extensions are not yet registered, we wait for a little moment to give them
// a chance to register so that the complete set of commands shows up as result
// We do not want to delay functionality beyond that time though to keep the commands
// functional.
// private readonly extensionRegistrationRace = Promise.race([
// timeout(800),
// this.extensionService.whenInstalledExtensionsRegistered()
// ]);
private useSemanticSimilarity = false;
protected get activeTextEditorControl(): IEditor | undefined { return this.editorService.activeTextEditorControl; }
get defaultFilterValue(): DefaultQuickAccessFilterValue | undefined {
if (this.configuration.preserveInput) {
return DefaultQuickAccessFilterValue.LAST;
}
return undefined;
}
constructor(
@IEditorService private readonly editorService: IEditorService,
@IMenuService private readonly menuService: IMenuService,
// @IExtensionService private readonly extensionService: IExtensionService,
@IInstantiationService instantiationService: IInstantiationService,
@IKeybindingService keybindingService: IKeybindingService,
@ICommandService commandService: ICommandService,
@ITelemetryService telemetryService: ITelemetryService,
@IDialogService dialogService: IDialogService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IEditorGroupsService private readonly editorGroupService: IEditorGroupsService,
@IPreferencesService private readonly preferencesService: IPreferencesService,
@IProductService private readonly productService: IProductService,
@ISemanticSimilarityService private readonly semanticSimilarityService: ISemanticSimilarityService,
) {
super({
showAlias: !Language.isDefaultVariant(),
noResultsPick: {
label: localize('noCommandResults', "No matching commands"),
commandId: ''
},
}, instantiationService, keybindingService, commandService, telemetryService, dialogService);
this._register(configurationService.onDidChangeConfiguration((e) => this.updateOptions(e)));
this.updateOptions();
}
private get configuration() {
const commandPaletteConfig = this.configurationService.getValue<IWorkbenchQuickAccessConfiguration>().workbench.commandPalette;
return {
preserveInput: commandPaletteConfig.preserveInput,
experimental: commandPaletteConfig.experimental
};
}
private updateOptions(e?: IConfigurationChangeEvent): void {
if (e && !e.affectsConfiguration('workbench.commandPalette.experimental')) {
return;
}
const config = this.configuration;
const suggestedCommandIds = config.experimental.suggestCommands && this.productService.commandPaletteSuggestedCommandIds?.length
? new Set(this.productService.commandPaletteSuggestedCommandIds)
: undefined;
this.options.suggestedCommandIds = suggestedCommandIds;
this.useSemanticSimilarity = config.experimental.useSemanticSimilarity;
}
protected getCommandPicks(token: CancellationToken): Array<ICommandQuickPick> {
// TODO: bring this back once we have a chosen strategy for FastAndSlowPicks where Fast is also Promise based
// wait for extensions registration or 800ms once
// await this.extensionRegistrationRace;
if (token.isCancellationRequested) {
return [];
}
return [
...this.getCodeEditorCommandPicks(),
...this.getGlobalCommandPicks()
].map(c => ({
...c,
buttons: [{
iconClass: ThemeIcon.asClassName(Codicon.gear),
tooltip: localize('configure keybinding', "Configure Keybinding"),
}],
trigger: (): TriggerAction => {
this.preferencesService.openGlobalKeybindingSettings(false, { query: `@command:${c.commandId}` });
return TriggerAction.CLOSE_PICKER;
},
}));
}
protected async getAdditionalCommandPicks(allPicks: ICommandQuickPick[], picksSoFar: ICommandQuickPick[], filter: string, token: CancellationToken): Promise<ICommandQuickPick[]> {
if (!this.useSemanticSimilarity || filter === '' || token.isCancellationRequested || !this.semanticSimilarityService.isEnabled()) {
return [];
}
const format = allPicks.map(p => p.commandId);
let scores: number[];
try {
await timeout(800, token);
scores = await this.semanticSimilarityService.getSimilarityScore(filter, format, token);
} catch (e) {
return [];
}
const sortedIndices = scores.map((_, i) => i).sort((a, b) => scores[b] - scores[a]);
const setOfPicksSoFar = new Set(picksSoFar.map(p => p.commandId));
const additionalPicks: ICommandQuickPick[] = [];
for (const i of sortedIndices) {
const score = scores[i];
if (score < 0.8) {
break;
}
const pick = allPicks[i];
if (!setOfPicksSoFar.has(pick.commandId)) {
additionalPicks.push(pick);
}
}
return additionalPicks;
}
private getGlobalCommandPicks(): ICommandQuickPick[] {
const globalCommandPicks: ICommandQuickPick[] = [];
const scopedContextKeyService = this.editorService.activeEditorPane?.scopedContextKeyService || this.editorGroupService.activeGroup.scopedContextKeyService;
const globalCommandsMenu = this.menuService.createMenu(MenuId.CommandPalette, scopedContextKeyService);
const globalCommandsMenuActions = globalCommandsMenu.getActions()
.reduce((r, [, actions]) => [...r, ...actions], <Array<MenuItemAction | SubmenuItemAction | string>>[])
.filter(action => action instanceof MenuItemAction && action.enabled) as MenuItemAction[];
for (const action of globalCommandsMenuActions) {
// Label
let label = (typeof action.item.title === 'string' ? action.item.title : action.item.title.value) || action.item.id;
// Category
const category = typeof action.item.category === 'string' ? action.item.category : action.item.category?.value;
if (category) {
label = localize('commandWithCategory', "{0}: {1}", category, label);
}
// Alias
const aliasLabel = typeof action.item.title !== 'string' ? action.item.title.original : undefined;
const aliasCategory = (category && action.item.category && typeof action.item.category !== 'string') ? action.item.category.original : undefined;
const commandAlias = (aliasLabel && category) ?
aliasCategory ? `${aliasCategory}: ${aliasLabel}` : `${category}: ${aliasLabel}` :
aliasLabel;
globalCommandPicks.push({
commandId: action.item.id,
commandAlias,
label: stripIcons(label)
});
}
// Cleanup
globalCommandsMenu.dispose();
return globalCommandPicks;
}
}
//#region Actions
export class ShowAllCommandsAction extends Action2 {
static readonly ID = 'workbench.action.showCommands';
constructor() {
super({
id: ShowAllCommandsAction.ID,
title: { value: localize('showTriggerActions', "Show All Commands"), original: 'Show All Commands' },
keybinding: {
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: !isFirefox ? (KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyP) : undefined,
secondary: [KeyCode.F1]
},
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
accessor.get(IQuickInputService).quickAccess.show(CommandsQuickAccessProvider.PREFIX);
}
}
export class ClearCommandHistoryAction extends Action2 {
constructor() {
super({
id: 'workbench.action.clearCommandHistory',
title: { value: localize('clearCommandHistory', "Clear Command History"), original: 'Clear Command History' },
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const configurationService = accessor.get(IConfigurationService);
const storageService = accessor.get(IStorageService);
const dialogService = accessor.get(IDialogService);
const commandHistoryLength = CommandsHistory.getConfiguredCommandHistoryLength(configurationService);
if (commandHistoryLength > 0) {
// Ask for confirmation
const { confirmed } = await dialogService.confirm({
type: 'warning',
message: localize('confirmClearMessage', "Do you want to clear the history of recently used commands?"),
detail: localize('confirmClearDetail', "This action is irreversible!"),
primaryButton: localize({ key: 'clearButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Clear")
});
if (!confirmed) {
return;
}
CommandsHistory.clearHistory(configurationService, storageService);
}
}
}
//#endregion