-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmanage-solution-webview-main.ts
More file actions
497 lines (438 loc) · 20.4 KB
/
manage-solution-webview-main.ts
File metadata and controls
497 lines (438 loc) · 20.4 KB
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
/**
* Copyright 2024-2026 Arm Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import path, { dirname } from 'path';
import * as vscode from 'vscode';
import { ExtensionContext } from 'vscode';
import { URI } from 'vscode-uri';
import { ETextFileResult } from '../../generic/text-file';
import * as manifest from '../../manifest';
import { IOpenFileExternal } from '../../open-file-external-if';
import { SolutionLoadStateChangeEvent, SolutionManager } from '../../solutions/solution-manager';
import { backToForwardSlashes } from '../../utils/path-utils';
import { CommandsProvider } from '../../vscode-api/commands-provider';
import { ConfigurationProvider } from '../../vscode-api/configuration-provider';
import { WebviewManager, WebviewManagerOptions } from '../webview-manager';
import { ManageSolutionController } from './manage-solution-controller';
import { IncomingMessage, OutgoingMessage } from './messages';
import { SolutionData } from './view/state/manage-solution-state';
import { initialState } from './view/state/reducer';
import debounce from 'lodash.debounce';
import { CsolutionService } from '../../json-rpc/csolution-rpc-client';
import { isDeepStrictEqual } from 'util';
import { FileSelectorOptionsType } from './types';
export const MANAGE_SOLUTION_WEBVIEW_OPTIONS: Readonly<WebviewManagerOptions> = {
title: 'Manage Solution',
scriptPath: path.join('dist', 'views', 'manageSolution.js'),
viewType: 'cmsis.manageSolution',
commandId: undefined,
iconName: {
dark: 'gear-dark.svg',
light: 'gear-light.svg',
},
enableSerializer: false,
};
export class ManageSolutionWebviewMain {
private readonly HELP_URL = path.join(manifest.GUIDE_FOLDER, 'manage_settings.html#active-target');
private readonly webviewManager: WebviewManager<IncomingMessage, OutgoingMessage>;
private readonly onEdit?: (label: string, before: SolutionData, after: SolutionData) => void;
protected _controller?: ManageSolutionController;
private wasDirty: boolean = false;
constructor(
context: ExtensionContext,
protected readonly solutionManager: SolutionManager, // solutionManager is only used for didChange events. Other calls to csolution must be done using the csolution getter/setter
private readonly commandsProvider: CommandsProvider,
private readonly openFileExternal: IOpenFileExternal,
private readonly configurationProvider: ConfigurationProvider,
private readonly csolutionService: CsolutionService,
onEdit?: (label: string, before: SolutionData, after: SolutionData) => void,
webviewManager?: WebviewManager<IncomingMessage, OutgoingMessage>,
) {
this.webviewManager = webviewManager || new WebviewManager(context, MANAGE_SOLUTION_WEBVIEW_OPTIONS, commandsProvider);
this.onEdit = onEdit;
context.subscriptions.push(
this.webviewManager.onDidCreate(() => {
debounce(() => this.setBusyState(!this.solutionManager.loadState.solutionPath), 500)();
}),
this.solutionManager.onDidChangeLoadState(this.handleSolutionLoadChange, this),
);
this.configurationProvider.onChangeConfiguration(() => {
if (this._controller) {
this._controller.customDebugAdapterDefaults = this.configurationProvider.getConfigVariableOrDefault('debug-adapters', {});
this._controller.csolutionService = this.csolutionService;
}
}, 'debug-adapters');
}
private async handleSolutionLoadChange(e: SolutionLoadStateChangeEvent): Promise<void> {
const { solutionPath: newPath, converted: newConverted, loaded: newLoaded } = e.newState;
const { solutionPath: prevPath, converted: prevConverted, loaded: prevLoaded } = e.previousState;
if (!this.webviewManager.isPanelActive || (newPath === prevPath && newConverted !== prevConverted)) {
return;
}
this.setBusyState(true);
if (newPath !== prevPath) {
if (newPath) {
await this.sendContextData();
} else if (prevPath) {
await this.clearContext();
this.webviewManager.disposePanel();
}
} else if (newLoaded !== prevLoaded) {
await this.sendContextData();
}
this.setBusyState(false);
}
private get isDirty(): boolean {
return (
this.controller?.cmsisJsonFile.isModified()
|| this.controller?.csolutionYml.isModified()
|| false);
}
get controller() {
if (!this._controller) {
this._controller = this.createController();
}
return this._controller;
}
protected createController(): ManageSolutionController {
const controller = new ManageSolutionController();
controller.customDebugAdapterDefaults = this.configurationProvider.getConfigVariableOrDefault('debug-adapters', {});
controller.csolutionService = this.csolutionService;
return controller;
}
public async activate(context: ExtensionContext): Promise<void> {
context.subscriptions.push(
this.webviewManager.onDidReceiveMessage(this.handleMessage, this),
);
// get notified about updates on the value of autoDebugLaunch and update the UI
this.configurationProvider.onChangeConfiguration(async () => {
const autoUpdate = this.configurationProvider.getConfigVariableOrDefault(manifest.CONFIG_AUTO_DEBUG_LAUNCH, true);
await this.webviewManager.sendMessage({ type: 'AUTO_UPDATE', data: autoUpdate });
}, manifest.CONFIG_AUTO_DEBUG_LAUNCH);
await this.webviewManager.activate(context);
}
private async setBusyState(busy: boolean): Promise<void> {
await this.webviewManager.sendMessage({ type: 'IS_BUSY', data: busy });
}
private getSolutionDir(): string {
return dirname(this.controller?.solutionPath ?? '');
}
private getSolutionBasename(): string {
return path.basename(this.controller?.solutionPath ?? '') || 'the solution';
}
public attachToPanel(panel: vscode.WebviewPanel): void {
this.webviewManager.attachPanel(panel);
}
public async applySnapshot(snapshot: SolutionData): Promise<void> {
this.controller.solutionData = this.cloneSolutionData(snapshot);
await this.broadcastState();
}
public getSolutionSnapshot(): SolutionData {
return this.cloneSolutionData(this.controller.solutionData);
}
private cloneSolutionData(data: SolutionData): SolutionData {
return structuredClone(data) as SolutionData;
}
private async withEdit(label: string, action: () => Promise<void>): Promise<void> {
const before = this.cloneSolutionData(this.controller.solutionData);
await action();
const after = this.cloneSolutionData(this.controller.solutionData);
if (this.onEdit && !isDeepStrictEqual(before, after)) {
this.onEdit(label, before, after);
}
await this.calculateDirtyState();
}
private async broadcastState(): Promise<void> {
await this.controller.refreshDebugAdapters();
const debugAdapters = await this.controller.debugAdapters;
const activeDebugger = this.controller.activeDebugger;
await Promise.all([
this.webviewManager.sendMessage({ type: 'DATA_CONTEXT_SELECTION', data: this.controller.solutionData }),
this.webviewManager.sendMessage({ type: 'DEBUGGER', data: this.controller.activeDebuggerName }),
this.webviewManager.sendMessage({ type: 'IS_DIRTY', data: this.isDirty }),
this.webviewManager.sendMessage({ type: 'AUTO_UPDATE', data: this.configurationProvider.getConfigVariableOrDefault(manifest.CONFIG_AUTO_DEBUG_LAUNCH, true) }),
this.webviewManager.sendMessage({ type: 'DEBUG_ADAPTERS', data: debugAdapters, sectionsInUse: activeDebugger?.sectionNames ?? [] }),
]);
}
private async openFile(path: string, openExternal?: boolean): Promise<void> {
if (openExternal) {
this.openFileExternal.openFile(path);
} else {
await this.commandsProvider.executeCommand('vscode.open', vscode.Uri.file(path));
}
}
private async handleMessage(message: OutgoingMessage): Promise<void> {
switch (message.type) {
case 'GET_CONTEXT_SELECTION_DATA':
await this.sendContextData();
break;
case 'OPEN_FILE':
await this.openFile(message.path, false);
break;
case 'SET_SELECTED_CONTEXTS':
await this.setSelectedContexts(message.data);
break;
case 'SET_SELECTED_TARGET':
await this.setSelectedTarget(message.target, message.set);
break;
case 'GET_DEBUG_ADAPTERS':
await this.sendDebugAdapters();
break;
case 'SET_DEBUGGER':
await this.setSelectedDebugger(message.name);
break;
case 'ADD_NEW_CONTEXT':
// not implemented yet
break;
case 'ADD_NEW_PROJECT':
await this.addNewProject();
break;
case 'ADD_NEW_IMAGE':
await this.addNewImage();
break;
case 'UNLINK_IMAGE':
await this.unlinkImage(message.image);
break;
case 'SET_START_PROCESSOR':
await this.updateStartProcessor(message.value);
break;
case 'SAVE_CONTEXT_SELECTION':
await this.commandsProvider.executeCommand('workbench.action.files.save');
break;
case 'OPEN_HELP':
await this.openFile(this.HELP_URL, true);
break;
case 'SET_DEBUG_ADAPTER_PROPERTY':
await this.updateDebuggerParameter(message.service, message.key, message.value, message.pname);
break;
case 'SELECT_FILE':
await this.selectFileDialog(message.targetElementId, message.options);
break;
case 'SET_AUTO_UPDATE':
await this.configurationProvider.setConfigVariable(manifest.CONFIG_AUTO_DEBUG_LAUNCH, message.value, undefined, true);
await this.webviewManager.sendMessage({ type: 'AUTO_UPDATE', data: message.value });
break;
case 'TOGGLE_DEBUGGER':
await this.toggleDebugger(message.value);
break;
case 'TOGGLE_DEBUG_ADAPTER_SECTION':
await this.toggleDebugAdapterSection(message.section);
break;
}
}
private async setSelectedTarget(target: string, set: string | undefined): Promise<void> {
await this.withEdit('SET_SELECTED_TARGET', async () => {
if (this.controller.setActiveTargetSet(target, set || undefined)) {
await this.sendContextData();
}
});
};
private async toggleDebugAdapterSection(section: string): Promise<void> {
await this.withEdit('TOGGLE_DEBUG_ADAPTER_SECTION', async () => {
await this.controller.toggleDebugAdapterSection(section);
await this.sendDebugAdapters();
});
}
private async toggleDebugger(enabled: boolean): Promise<void> {
await this.withEdit('TOGGLE_DEBUGGER', async () => {
this.controller.enableDebugger(enabled);
await this.sendContextData();
});
}
private async updateDebuggerParameter(service: string | undefined, param: string, value: string | number, pname?: string) {
await this.withEdit('UPDATE_DEBUGGER_PARAMETER', async () => {
if (service && !this.controller.isDebuggerSectionEnabled(service)) {
await this.controller.toggleDebugAdapterSection(service);
}
if ((pname === undefined || pname === null) || this.controller.availableCoreNames.length <= 1) {
this.controller.setDebuggerParameter(service, param, value.toString());
} else {
this.controller.setDebuggerParameterWithPname(service, pname, param, value.toString());
}
await this.sendContextData();
});
}
private async updateStartProcessor(name: string) {
await this.updateDebuggerParameter('', 'start-pname', name);
}
public async saveChanges(): Promise<void> {
if (!this.isDirty) {
return;
}
await this.setBusyState(true);
await this.controller.saveSolution(this.solutionManager);
this.wasDirty = false;
await this.setBusyState(false);
await this.sendContextData();
}
public async revertToDisk(): Promise<void> {
this._controller = this.createController();
this.wasDirty = false;
await this.sendContextData();
}
private async setSelectedContexts(selectedContextState: SolutionData): Promise<void> {
await this.withEdit('SET_SELECTED_CONTEXTS', async () => {
this.controller.solutionData = selectedContextState;
await this.sendContextData();
});
}
protected async querySaveModified(): Promise<void> {
if (!this.isDirty) {
return;
}
// for now only yes/no answers are supported, cancel can be only triggered externally when changing solution
// todo: query all modifications from this and component views
const result = await vscode.window.showWarningMessage(
`Manage Solution: You have unsaved changes in ${this.getSolutionBasename()}. Do you want to save them?`,
{ modal: true },
'Yes',
'No'
);
if (result === 'Yes') {
await this.saveChanges();
}
}
/**
* Loads csolution.ym file for editing
* @returns true if solution file is successfully loaded
*/
protected async loadSolution(): Promise<ETextFileResult> {
const globalSolution = this.solutionManager.getCsolution(); // get global csolution
if (this.controller.solutionPath !== globalSolution?.solutionPath) {
// await this.querySaveModified();
this._controller = this.createController(); // todo: use clear instead
}
if (!globalSolution) { // no solution is loaded in workspace
return ETextFileResult.NotExists;
}
const defaultDebugAdapterName = await globalSolution.getDefaultDebugAdapterName();
return this.controller.loadSolution(globalSolution.solutionPath, defaultDebugAdapterName);
}
private async clearContext(): Promise<void> {
this._controller = undefined;
this.wasDirty = false;
await Promise.all([
this.webviewManager.sendMessage({ type: 'DATA_CONTEXT_SELECTION', data: initialState.solutionData }),
this.webviewManager.sendMessage({ type: 'DEBUG_ADAPTERS', data: [], sectionsInUse: [] }),
this.webviewManager.sendMessage({ type: 'DEBUGGER', data: '' }),
this.webviewManager.sendMessage({ type: 'IS_DIRTY', data: false }),
this.webviewManager.sendMessage({ type: 'AUTO_UPDATE', data: false }),
]);
}
public async sendContextData(): Promise<void> {
const result = await this.loadSolution();
if (result === ETextFileResult.Error || result === ETextFileResult.NotExists) {
await this.setBusyState(false);
return;
}
const controller = this.controller;
await controller.getAvailableCoreNames();
await Promise.all([
this.sendDebugAdapters(),
this.webviewManager.sendMessage({ type: 'DATA_CONTEXT_SELECTION', data: controller.solutionData }),
this.webviewManager.sendMessage({ type: 'DEBUGGER', data: controller.activeDebuggerName }),
this.webviewManager.sendMessage({ type: 'IS_DIRTY', data: this.isDirty }),
this.webviewManager.sendMessage({ type: 'AUTO_UPDATE', data: this.configurationProvider.getConfigVariableOrDefault(manifest.CONFIG_AUTO_DEBUG_LAUNCH, true) }),
this.setBusyState(false),
]);
}
private async sendDebugAdapters(): Promise<void> {
await this.controller.refreshDebugAdapters();
const debugAdaters = await this.controller.debugAdapters;
const activeDebugger = this.controller.activeDebugger;
return this.webviewManager.sendMessage({
type: 'DEBUG_ADAPTERS',
data: debugAdaters,
sectionsInUse: activeDebugger?.sectionNames ?? []
});
}
private async addNewProject(): Promise<void> {
await vscode.window.showWarningMessage('Not implemented');
};
private async unlinkImage(image: string): Promise<void> {
await this.withEdit('UNLINK_IMAGE', async () => {
await this.setBusyState(true);
try {
this.controller.activeTargetSetWrap.getImage(image)?.remove();
await this.sendContextData();
} finally {
await this.setBusyState(false);
}
});
}
private async selectFileDialog(targetElementId: string, options?: FileSelectorOptionsType): Promise<void> {
const solutionDir = this.getSolutionDir();
if (options?.defaultUri) {
options.defaultUri = URI.file(dirname(options.defaultUri)).toString();
}
const localOptions: vscode.OpenDialogOptions = {
canSelectMany: options?.canSelectMany || false,
openLabel: options?.openLabel || 'Select File',
title: options?.title || 'Select File',
filters: options?.filters || { 'All Files': ['*'] },
defaultUri: options?.defaultUri ? URI.parse(options.defaultUri) : URI.file(solutionDir),
};
const fileUri = await vscode.window.showOpenDialog(localOptions);
if (fileUri && fileUri[0]) {
const paths = fileUri.map(u =>
backToForwardSlashes(options?.pathType === 'absolute'
? u.fsPath
: path.relative(solutionDir, u.fsPath)
)
);
await this.webviewManager.sendMessage({ type: 'FILE_SELECTED', data: paths, for: targetElementId });
}
}
private async addNewImage() {
await this.withEdit('ADD_IMAGE', async () => {
await this.setBusyState(true);
try {
const solutionDir = this.getSolutionDir();
const options: vscode.OpenDialogOptions = {
canSelectMany: false,
openLabel: 'Select File',
filters: {
'All Files': ['*'],
'All Image Files': ['axf', 'elf', 'hex', 'bin'],
'Executable in ELF format': ['axf', 'elf'],
'Intel HEX file in HEX-386 format': ['hex'],
'Binary Image': ['bin'],
},
defaultUri: URI.file(solutionDir),
};
const fileUri = await vscode.window.showOpenDialog(options);
if (fileUri?.[0]) {
const filePath = backToForwardSlashes(path.relative(solutionDir, fileUri[0].fsPath));
this.controller.activeTargetSetWrap.addImage(filePath);
await this.sendContextData();
}
} finally {
await this.setBusyState(false);
}
});
}
private async setSelectedDebugger(name: string): Promise<void> {
await this.withEdit('SET_DEBUGGER', async () => {
this.controller.setSelectedDebugger(name);
await this.sendContextData();
});
}
private async calculateDirtyState(): Promise<void> {
if (this.wasDirty !== this.isDirty) {
await this.webviewManager.sendMessage({ type: 'IS_DIRTY', data: this.isDirty });
}
this.wasDirty = this.isDirty;
};
}