-
-
Notifications
You must be signed in to change notification settings - Fork 440
/
Copy pathboards-quick-open-service.ts
309 lines (278 loc) · 12.5 KB
/
boards-quick-open-service.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
import * as fuzzy from 'fuzzy';
import { inject, injectable, postConstruct, named } from 'inversify';
import { ILogger } from '@theia/core/lib/common/logger';
import { CommandContribution, CommandRegistry, Command } from '@theia/core/lib/common/command';
import { KeybindingContribution, KeybindingRegistry } from '@theia/core/lib/browser/keybinding';
import { QuickOpenItem, QuickOpenModel, QuickOpenMode, QuickOpenGroupItem } from '@theia/core/lib/common/quick-open-model';
import {
QuickOpenService,
QuickOpenHandler,
QuickOpenOptions,
QuickOpenItemOptions,
QuickOpenContribution,
QuickOpenActionProvider,
QuickOpenHandlerRegistry,
QuickOpenGroupItemOptions
} from '@theia/core/lib/browser/quick-open';
import { naturalCompare } from '../../../common/utils';
import { BoardsService, Port, Board, ConfigOption, ConfigValue } from '../../../common/protocol';
import { BoardsDataStore } from '../boards-data-store';
import { BoardsServiceProvider, AvailableBoard } from '../boards-service-provider';
import { NotificationCenter } from '../../notification-center';
@injectable()
export class BoardsQuickOpenService implements QuickOpenContribution, QuickOpenModel, QuickOpenHandler, CommandContribution, KeybindingContribution, Command {
readonly id = 'arduino-boards-quick-open';
readonly prefix = '|';
readonly description = 'Configure Available Boards';
readonly label: 'Configure Available Boards';
@inject(ILogger)
@named('boards-quick-open')
protected readonly logger: ILogger;
@inject(QuickOpenService)
protected readonly quickOpenService: QuickOpenService;
@inject(BoardsService)
protected readonly boardsService: BoardsService;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClient: BoardsServiceProvider;
@inject(BoardsDataStore)
protected readonly boardsDataStore: BoardsDataStore;
@inject(NotificationCenter)
protected notificationCenter: NotificationCenter;
protected isOpen: boolean = false;
protected currentQuery: string = '';
// Attached boards plus the user's config.
protected availableBoards: AvailableBoard[] = [];
// Only for the `selected` one from the `availableBoards`. Note: the `port` of the `selected` is optional.
protected data: BoardsDataStore.Data = BoardsDataStore.Data.EMPTY;
protected allBoards: Board.Detailed[] = []
protected selectedBoard?: (AvailableBoard & { port: Port });
// `init` name is used by the `QuickOpenHandler`.
@postConstruct()
protected postConstruct(): void {
this.notificationCenter.onIndexUpdated(() => this.update(this.availableBoards));
this.boardsServiceClient.onAvailableBoardsChanged(availableBoards => this.update(availableBoards));
this.update(this.boardsServiceClient.availableBoards);
}
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(this, { execute: () => this.open() });
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({ command: this.id, keybinding: 'ctrlCmd+k ctrlCmd+b' });
}
registerQuickOpenHandlers(registry: QuickOpenHandlerRegistry): void {
registry.registerHandler(this);
}
getModel(): QuickOpenModel {
return this;
}
getOptions(): QuickOpenOptions {
let placeholder = '';
if (!this.selectedBoard) {
placeholder += 'No board selected.';
}
placeholder += 'Type to filter boards';
if (this.data.configOptions.length) {
placeholder += ' or use the ↓↑ keys to adjust the board settings...';
} else {
placeholder += '...';
}
return {
placeholder,
fuzzyMatchLabel: true,
onClose: () => this.isOpen = false
};
}
open(): void {
this.isOpen = true;
this.quickOpenService.open(this, this.getOptions());
}
onType(
lookFor: string,
acceptor: (items: QuickOpenItem<QuickOpenItemOptions>[], actionProvider?: QuickOpenActionProvider) => void): void {
this.currentQuery = lookFor;
const fuzzyFilter = this.fuzzyFilter(lookFor);
const availableBoards = this.availableBoards.filter(AvailableBoard.hasPort).filter(({ name }) => fuzzyFilter(name));
const toAccept: QuickOpenItem<QuickOpenItemOptions>[] = [];
// Show the selected attached in a different group.
if (this.selectedBoard && fuzzyFilter(this.selectedBoard.name)) {
toAccept.push(this.toQuickItem(this.selectedBoard, { groupLabel: 'Selected Board' }));
}
// Filter the selected from the attached ones.
toAccept.push(...availableBoards.filter(board => board !== this.selectedBoard).map((board, i) => {
let group: QuickOpenGroupItemOptions | undefined = undefined;
if (i === 0) {
// If no `selectedBoard`, then this item is the top one, no borders required.
group = { groupLabel: 'Attached Boards', showBorder: !!this.selectedBoard };
}
return this.toQuickItem(board, group);
}));
// Show the config only if the `input` is empty.
if (!lookFor.trim().length) {
toAccept.push(...this.data.configOptions.map((config, i) => {
let group: QuickOpenGroupItemOptions | undefined = undefined;
if (i === 0) {
group = { groupLabel: 'Board Settings', showBorder: true };
}
return this.toQuickItem(config, group);
}));
} else {
toAccept.push(...this.allBoards.filter(({ name }) => fuzzyFilter(name)).map((board, i) => {
let group: QuickOpenGroupItemOptions | undefined = undefined;
if (i === 0) {
group = { groupLabel: 'Boards', showBorder: true };
}
return this.toQuickItem(board, group);
}));
}
acceptor(toAccept);
}
private fuzzyFilter(lookFor: string): (inputString: string) => boolean {
const shouldFilter = !!lookFor.trim().length;
return (inputString: string) => shouldFilter ? fuzzy.test(lookFor.toLocaleLowerCase(), inputString.toLocaleLowerCase()) : true;
}
protected async update(availableBoards: AvailableBoard[]): Promise<void> {
// `selectedBoard` is not an attached board, we need to show the board settings for it (TODO: clarify!)
const selectedBoard = availableBoards.filter(AvailableBoard.hasPort).find(({ selected }) => selected);
const [data, boards] = await Promise.all([
selectedBoard && selectedBoard.fqbn ? this.boardsDataStore.getData(selectedBoard.fqbn) : Promise.resolve(BoardsDataStore.Data.EMPTY),
this.boardsService.allBoards({})
]);
this.allBoards = Board.decorateBoards(selectedBoard, boards)
.filter(board => !availableBoards.some(availableBoard => Board.sameAs(availableBoard, board)));
this.availableBoards = availableBoards;
this.data = data;
this.selectedBoard = selectedBoard;
if (this.isOpen) {
// Hack, to update the state without closing and reopening the quick open widget.
(this.quickOpenService as any).onType(this.currentQuery);
}
}
protected toQuickItem(item: BoardsQuickOpenService.Item, group?: QuickOpenGroupItemOptions): QuickOpenItem<QuickOpenItemOptions> {
let options: QuickOpenItemOptions;
if (AvailableBoard.is(item)) {
const description = `on ${Port.toString(item.port)}`
options = {
label: `${item.name}`,
description,
descriptionHighlights: [
{
start: 0,
end: description.length
}
],
run: this.toRun(() => this.boardsServiceClient.boardsConfig = ({ selectedBoard: item, selectedPort: item.port }))
};
} else if (ConfigOption.is(item)) {
const selected = item.values.find(({ selected }) => selected);
const value = selected ? selected.label : 'Not set';
const label = `${item.label}: ${value}`;
options = {
label,
// Intended to match the value part of a board setting.
// NOTE: this does not work, as `fuzzyMatchLabel: true` is set. Manual highlighting is ignored, apparently.
labelHighlights: [
{
start: label.length - value.length,
end: label.length
}
],
run: (mode) => {
if (mode === QuickOpenMode.OPEN) {
this.setConfig(item);
return false;
}
return true;
}
};
if (!selected) {
options.description = 'Not set';
};
} else {
options = {
label: `${item.name}`,
description: `${item.missing ? '' : `[installed with '${item.packageName}']`}`,
run: (mode) => {
if (mode === QuickOpenMode.OPEN) {
this.selectBoard(item);
return false;
}
return true;
}
};
}
if (group) {
return new QuickOpenGroupItem<QuickOpenGroupItemOptions>({ ...options, ...group });
} else {
return new QuickOpenItem<QuickOpenItemOptions>(options);
}
}
protected toRun(run: (() => void)): ((mode: QuickOpenMode) => boolean) {
return (mode) => {
if (mode !== QuickOpenMode.OPEN) {
return false;
}
run();
return true;
};
}
protected async selectBoard(board: Board): Promise<void> {
const allPorts = this.availableBoards.filter(AvailableBoard.hasPort).map(({ port }) => port).sort(Port.compare);
const toItem = (port: Port) => new QuickOpenItem<QuickOpenItemOptions>({
label: Port.toString(port, { useLabel: true }),
run: this.toRun(() => {
this.boardsServiceClient.boardsConfig = {
selectedBoard: board,
selectedPort: port
};
})
});
const options = {
placeholder: `Select a port for '${board.name}'. Press 'Enter' to confirm or 'Escape' to cancel.`,
fuzzyMatchLabel: true
}
this.quickOpenService.open({
onType: (lookFor, acceptor) => {
const fuzzyFilter = this.fuzzyFilter(lookFor);
acceptor(allPorts.filter(({ address }) => fuzzyFilter(address)).map(toItem));
}
}, options);
}
protected async setConfig(config: ConfigOption): Promise<void> {
const toItem = (value: ConfigValue) => new QuickOpenItem<QuickOpenItemOptions>({
label: value.label,
iconClass: value.selected ? 'fa fa-check' : '',
run: this.toRun(() => {
if (!this.selectedBoard) {
this.logger.warn(`Could not alter the boards settings. No board selected. ${JSON.stringify(config)}`);
return;
}
if (!this.selectedBoard.fqbn) {
this.logger.warn(`Could not alter the boards settings. The selected board does not have a FQBN. ${JSON.stringify(this.selectedBoard)}`);
return;
}
const { fqbn } = this.selectedBoard;
this.boardsDataStore.selectConfigOption({
fqbn,
option: config.option,
selectedValue: value.value
});
})
});
const options = {
placeholder: `Configure '${config.label}'. Press 'Enter' to confirm or 'Escape' to cancel.`,
fuzzyMatchLabel: true
}
this.quickOpenService.open({
onType: (lookFor, acceptor) => {
const fuzzyFilter = this.fuzzyFilter(lookFor);
acceptor(config.values
.filter(({ label }) => fuzzyFilter(label))
.sort((left, right) => naturalCompare(left.label, right.label))
.map(toItem));
}
}, options);
}
}
export namespace BoardsQuickOpenService {
export type Item = AvailableBoard & { port: Port } | Board.Detailed | ConfigOption;
}