forked from microsoft/devicescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate.ts
More file actions
957 lines (868 loc) · 31.4 KB
/
Copy pathstate.ts
File metadata and controls
957 lines (868 loc) · 31.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
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
import type {
DeviceConfig,
ServerInfo,
ServerInfoFile,
} from "@devicescript/interop"
import { normalizeDeviceConfig, parseAnyInt } from "@devicescript/interop"
import {
CHANGE,
ControlReg,
delay,
DEVICE_CHANGE,
JDBus,
JDEventSource,
JDService,
randomDeviceId,
shortDeviceId,
SRV_DEVICE_SCRIPT_MANAGER,
CONNECTION_STATE,
ConnectionState,
JDDevice,
DEVICE_ANNOUNCE,
} from "jacdac-ts"
import * as vscode from "vscode"
import { Utils } from "vscode-uri"
import {
AddResponse,
SideAddNpmReq,
SideAddNpmResp,
SideAddServiceReq,
SideAddServiceResp,
SideAddSettingsReq,
SideAddSettingsResp,
SideAddSimReq,
SideAddSimResp,
SideAddTestReq,
SideAddTestResp,
SideConnectReq,
SideStartVmReq,
SideStopVmReq,
SideTransportEvent,
TransportStatus,
} from "../../cli/src/sideprotocol"
import { openDocUri, showInformationMessageWithHelp } from "./commands"
import { CONNECTION_RESOURCE_GROUP, MESSAGE_PREFIX } from "./constants"
import { prepareForDeploy, readRuntimeVersion } from "./deploy"
import { DeveloperToolsManager } from "./devtoolsserver"
import { checkFileExists, openFileEditor, writeFile } from "./fs"
import { sideRequest, subSideEvent } from "./jacdac"
import { JDomDeviceTreeItem } from "./JDomTreeDataProvider"
import { showConfirmBox, TaggedQuickPickItem } from "./pickers"
import { SimulatorsWebView } from "./simulatorWebView"
import { showErrorMessage } from "./telemetry"
import _serverInfo from "./server-info.json"
import { resolvePythonEnvironment } from "./python"
const serverInfo = _serverInfo as ServerInfoFile
const STATE_WATCHES_KEY = "views.watches.3"
const STATE_CURRENT_DEVICE = "devices.current"
const STATE_SIMULATOR_DEVICE = "devices.simulator"
type DeviceQuickItem = TaggedQuickPickItem<string>
export interface NodeWatch {
id: string
label: string
icon: string
}
export type ServerQuickPickItem = TaggedQuickPickItem<{
command: "test" | "settings" | "search" | "server" | "sim" | "npm"
info?: ServerInfo
}>
export class DeviceScriptExtensionState extends JDEventSource {
readonly devtools: DeveloperToolsManager
readonly simulators: SimulatorsWebView
private _transport: TransportStatus = {
transports: [],
}
constructor(
readonly context: vscode.ExtensionContext,
readonly bus: JDBus
) {
super()
this.devtools = new DeveloperToolsManager(this)
this.simulators = new SimulatorsWebView(this)
if (!this.simulatorScriptManagerId) {
this.state.update(STATE_SIMULATOR_DEVICE, randomDeviceId())
}
this.bus.on([DEVICE_CHANGE, CONNECTION_STATE], () => {
this.emit(CHANGE)
})
this.bus.on(DEVICE_ANNOUNCE, this.handleDeviceAnnounce.bind(this))
this.devtools.on(CHANGE, () => this.emit(CHANGE))
subSideEvent<SideTransportEvent>("transport", msg => {
const _transport = msg.data
if (
JSON.stringify(_transport) !== JSON.stringify(this._transport)
) {
this._transport = _transport
this.emit(CHANGE)
}
})
}
get state() {
return this.context.workspaceState
}
get transport() {
return this._transport
}
get watches(): NodeWatch[] {
return this.state.get(STATE_WATCHES_KEY) || []
}
async updateWatches(watches: NodeWatch[]) {
await this.state.update(STATE_WATCHES_KEY, watches || [])
this.emit(CHANGE)
}
get simulatorScriptManagerId() {
const id = this.state.get(STATE_SIMULATOR_DEVICE) as string
return id
}
get deviceScriptManager() {
const id = this.state.get(STATE_CURRENT_DEVICE) as string
const current = this.bus.device(id, true)
const srv = current?.services({
serviceClass: SRV_DEVICE_SCRIPT_MANAGER,
})[0]
return srv?.disposed ? undefined : srv
}
get projectFolder() {
return this.devtools.projectFolder
}
async setProjectFolder(folder: vscode.Uri) {
await this.devtools.setProjectFolder(folder)
}
public async updateCurrentDeviceScriptManagerId(id: string) {
const oldid = this.state.get(STATE_CURRENT_DEVICE) as string
if (oldid !== id) {
await this.state.update(STATE_CURRENT_DEVICE, id)
if (id !== this.simulatorScriptManagerId) await this.stopSimulator()
this.emit(CHANGE)
}
}
async resolveDeviceScriptManager(options?: {
autoStartSimulator?: boolean
skipUpdate?: boolean
}): Promise<JDService> {
return this.deviceScriptManager || this.pickDeviceScriptManager(options)
}
async addTest() {
const resp = await sideRequest<SideAddTestReq, SideAddTestResp>({
req: "addTest",
data: {},
})
await this.handleAddResponse(resp.data)
}
async addSim() {
const resp = await sideRequest<SideAddSimReq, SideAddSimResp>({
req: "addSim",
data: {},
})
await this.handleAddResponse(resp.data)
}
async addNpm() {
const resp = await sideRequest<SideAddNpmReq, SideAddNpmResp>({
req: "addNpm",
data: {},
})
await this.handleAddResponse(resp.data)
}
async addSettings() {
const resp = await sideRequest<SideAddSettingsReq, SideAddSettingsResp>(
{
req: "addSettings",
data: {},
}
)
await this.handleAddResponse(resp.data)
}
private async handleAddResponse(data: AddResponse) {
const dir = this.devtools.projectFolder
const { files = [] } = data || {}
for (const file of files) {
await openFileEditor(dir, file)
}
}
async addService() {
const name = await vscode.window.showInputBox({
title: "Pick a service name",
})
if (!name) return
const resp = await sideRequest<SideAddServiceReq, SideAddServiceResp>({
req: "addService",
data: { name },
})
await this.handleAddResponse(resp.data)
}
async addBoard() {
await this.devtools.start()
if (!this.devtools.connected) return
await this.devtools.refreshSpecs()
const { boards } = this.devtools
if (!boards?.length) return
const base = await vscode.window.showQuickPick<
TaggedQuickPickItem<DeviceConfig>
>(
boards.map(board => ({
data: board,
label: board.devName,
description: board.archId,
detail: board.id,
})),
{
title: "Pick a board base.",
}
)
if (base === undefined) return
const name = await vscode.window.showInputBox({
placeHolder: "Pick a name for the new board.",
value: base.data.devName,
validateInput: value => {
if (value.length < 4)
return "Name must be at least 4 characters long."
if (value.length > 64)
return "Name must be at most 64 characters long."
if (boards.find(b => b.devName === value))
return "Board name already exists."
return undefined
},
})
if (name === undefined) return
const normalize = (v: string) =>
v
.toLowerCase()
.replace(/[^a-z0-9]+/g, " ")
.trim()
.replace(/\s+/g, "_")
const board = await vscode.window.showInputBox({
placeHolder: "Pick a board identifier.",
value: base.data.id,
prompt: `Alphanumeric characters or _ allowed. Base is ${base.data.id}.`,
validateInput: async value => {
const nvalue = normalize(value)
if (nvalue.length < 4)
return `Identifier (${nvalue}) must be at least 4 characters long.`
if (nvalue.length > 64)
return `Identifier (${nvalue}) must be at most 64 characters long.`
if (boards.find(b => b.id === nvalue))
return `Identifier (${nvalue}) already used.`
const fp = `./boards/${nvalue}.json`
const exists = await checkFileExists(
this.devtools.projectFolder,
fp
)
if (exists) return `Board file ${fp} already exists.`
return undefined
},
})
if (board === undefined) return
const newBoard = normalizeDeviceConfig(base.data, {
ignoreFirmwareUrl: true,
ignoreId: true,
})
newBoard.devName = name
newBoard.productId = this.bus.deviceCatalog.uniqueFirmwareId()
const content = JSON.stringify(newBoard, null, 4)
await writeFile(
this.devtools.projectFolder,
`./boards/${normalize(board)}.board.json`,
content,
{ open: true }
)
}
async showQuickPickBoard(
title: string,
options?: { useUniqueDevice?: boolean }
): Promise<DeviceConfig> {
const { useUniqueDevice } = options || {}
const { boards } = this.devtools
// find device on the board
const devices = this.bus.devices({
serviceClass: SRV_DEVICE_SCRIPT_MANAGER,
lost: false,
})
const deviceItems = devices
.map(device => ({
device,
board: boards.find(
b => parseAnyInt(b.productId) === device.productIdentifier
),
}))
.filter(({ board }) => !!board)
.map(({ device, board }) => ({
data: { board },
description: board.devName,
label: device.shortId,
detail: "connected",
}))
if (deviceItems.length === 1 && useUniqueDevice)
return deviceItems[0].data.board
const res = await vscode.window.showQuickPick(
<TaggedQuickPickItem<{ board?: DeviceConfig }>[]>[
...deviceItems,
deviceItems && {
kind: vscode.QuickPickItemKind.Separator,
},
{
label: "Help me choose...",
detail: "Identify your board or find where to get one.",
},
...boards.map(board => ({
data: { board },
label: board.devName,
description: board.id,
detail: board.$description,
})),
].filter(i => !!i),
{
title,
canPickMany: false,
matchOnDetail: true,
matchOnDescription: true,
}
)
if (!res) return undefined // user escaped
if (!res.data?.board) {
openDocUri("devices")
return undefined
}
return res.data.board
}
async configureHardware(editor: vscode.TextEditor) {
await this.devtools.start()
if (!this.devtools.connected) return
await this.devtools.refreshSpecs()
const { boards } = this.devtools
const document = editor.document
const { boardimport } =
/from "@dsboard\/(?<boardimport>[^"]+)/.exec(document.getText())
?.groups || {}
let board = boards.find(b => b.id === boardimport)
if (!board) {
board = await this.showQuickPickBoard(
"What kind of device are you programming?",
{ useUniqueDevice: true }
)
if (!board) return
// insert missing import
await editor.edit(editBuilder => {
editBuilder.insert(
document.positionAt(0),
`import { pins, board } from "@dsboard/${board.id}"\n`
)
})
showInformationMessageWithHelp(
`Imported ${board.devName} configuration`,
"developer/board-configuration"
)
return
}
await this.showQuickAddFeatureOrDriver(editor)
}
private async handleDeviceAnnounce(dev: JDDevice) {
// ignore simulator
if (dev.deviceId === this.simulatorScriptManagerId) return
// only handle devices that have a script manager
if (!dev.hasService(SRV_DEVICE_SCRIPT_MANAGER)) return
// check if a simulator is running
if (!this.bus.device(this.simulatorScriptManagerId, true)) return
// stop simulator and let other manager take over
await this.stopSimulator()
}
private async showQuickAddFeatureOrDriver(editor: vscode.TextEditor) {
const server = await vscode.window.showQuickPick(
[
{
label: "Drivers",
kind: vscode.QuickPickItemKind.Separator,
},
...serverInfo.servers.map(
e =>
<ServerQuickPickItem>{
label: e.label,
description: e.startName,
detail: e.detail,
data: { info: e, command: "server" },
}
),
<ServerQuickPickItem>{
label: "Search...",
description: "npmjs.com",
detail: "Search for packages on npmjs.com with the `devicescript` keyword.",
data: { command: "search" },
},
{
label: "Features",
kind: vscode.QuickPickItemKind.Separator,
},
<ServerQuickPickItem>{
label: "Add settings and secrets",
detail: "Add .env.default and .env.local files to store configuration settings and secrets.",
data: { command: "settings" },
},
<ServerQuickPickItem>{
label: "Add tests",
detail: "Add a test file to run tests on your device.",
data: { command: "test" },
},
<ServerQuickPickItem>{
label: "Convert to NPM package",
detail: "Update package.json to support publishing as a library on npm.js.",
data: { command: "npm" },
},
],
{
title: `Configure project`,
matchOnDescription: true,
matchOnDetail: true,
canPickMany: false,
}
)
if (server === undefined) return
const { command, info } = server.data
if (command === "server") await this.addStartServer(editor, info)
else if (command === "search")
await vscode.env.openExternal(
vscode.Uri.parse(
"https://www.npmjs.com/search?q=keywords%3Adevicescript"
)
)
else if (command === "test") await this.addTest()
else if (command === "settings") await this.addSettings()
else if (command === "sim") await this.addSim()
else if (command === "npm") await this.addNpm()
}
// find first line that is not an import, comment or empty
private async addStartServer(
editor: vscode.TextEditor,
server: ServerInfo
) {
for (const [symName, modName] of Object.entries(server.imports)) {
await this.addImport(editor, symName, modName)
}
const document = editor.document
let line: vscode.TextLine
let i = 0
for (let i = 0; i < document.lineCount; ++i) {
line = document.lineAt(i)
if (
!line.isEmptyOrWhitespace &&
!/^\s*(\/\/|import\s+)/m.test(line.text)
)
break
}
const position = line?.rangeIncludingLineBreak?.start
await editor.insertSnippet(
new vscode.SnippetString(server.snippet),
position
)
}
private async addImport(
editor: vscode.TextEditor,
symName: string,
modName: string
) {
let idx = -1
let lastImport = 0
let add = ""
const text = editor.document.getText()
text.replace(
/^(\s*import\s*\{)([^\}]*)(\}\s*from\s*"([^"]+)")/gm,
(
full: string,
pref: string,
imports: string,
suff: string,
mod: string
) => {
if (idx == -1 && mod == modName) {
if (
imports
.split(/,/)
.map(e => e.trim())
.includes(symName)
) {
idx = 0
add = ""
} else {
imports = imports.replace(/\s*$/, "")
idx = text.indexOf(full) + pref.length + imports.length
if (!imports.endsWith(",")) add += ","
add += " " + symName + " "
}
}
lastImport = text.indexOf(full) + full.length
return full
}
)
if (idx == -1) {
idx = lastImport
add = `\nimport { ${symName} } from "${modName}"`
}
await editor.edit(editBuilder => {
editBuilder.insert(editor.document.positionAt(idx), add)
})
}
private async resolveBoardDefinition(device?: JDDevice) {
await this.devtools.start()
if (!this.devtools.connected) return undefined
await this.devtools.refreshSpecs()
const { boards } = this.devtools
if (!boards?.length) return undefined
const productIdentifier = await device?.resolveProductIdentifier()
let board: DeviceConfig =
productIdentifier &&
boards.find(
board => parseAnyInt(board.productId) === productIdentifier
)
if (!board) {
board = await this.showQuickPickBoard(
"What kind of device are you flashing?",
{ useUniqueDevice: true }
)
if (!board) return undefined
}
return board
}
async cleanFirmware(device?: JDDevice) {
const board = await this.resolveBoardDefinition(device)
if (!board) return
if (
!(await showConfirmBox(
`The entire flash on ${board.devName} will be erased. There is NO undo. Confirm?`
))
)
return
// force disconnect
await this.disconnect()
const { id } = board
const args = ["flash", "--board", id, "--install", "--clean"]
const python = await resolvePythonEnvironment()
if (python) args.push("--python", python.path)
const t = await this.devtools.createCliTerminal({
title: "DeviceScript Flasher",
progress: "Starting flashing tools...",
useShell: true,
args,
diagnostics: false,
})
t.show()
}
async flashFirmware(device?: JDDevice) {
const board = await this.resolveBoardDefinition(device)
if (!board) return
if (
!(await showConfirmBox(
`DeviceScript runtime will be flashed on your ${board.devName}. There is NO undo. Confirm?`
))
)
return
// force disconnect
await this.disconnect()
const { id } = board
const args = ["flash", "--board", id, "--refresh", "--install"]
const python = await resolvePythonEnvironment()
if (python) args.push("--python", python.path)
const t = await this.devtools.createCliTerminal({
title: "DeviceScript Flasher",
progress: "Starting flashing tools...",
useShell: true,
args,
diagnostics: false,
})
t.show()
}
private async disconnect() {
if (!this.devtools.connected) return
await sideRequest<SideConnectReq>({
req: "connect",
data: {
transport: "none",
background: true,
resourceGroupId: CONNECTION_RESOURCE_GROUP,
},
})
}
async connect() {
const { simulatorScriptManagerId } = this
const { extensionKind } = this.context.extension
const isWorkspace = extensionKind === vscode.ExtensionKind.Workspace
if (isWorkspace) {
showErrorMessage(
"connection.remote",
"Connection to a hardware device (serial, usb, ...) is not supported in remote workspaces."
)
return
}
await this.devtools.start()
if (!this.devtools.connected) return
const { transports } = this.transport
const connecteds = transports.filter(
tr => tr.connectionState === ConnectionState.Connected
)
const serial = transports.find(t => t.type === "serial")
const usb = transports.find(t => t.type === "usb")
const sim = !!this.bus.device(this.simulatorScriptManagerId, true)
const items: (vscode.QuickPickItem & { transport?: string })[] = [
{
label: "Hardware Connections",
kind: vscode.QuickPickItemKind.Separator,
},
{
transport: "serial",
label: "Serial",
detail: "ESP32, RP2040, ...",
description: serial
? `${serial.description || ""}(${serial.connectionState})`
: "",
},
/*{
transport: "usb",
label: "USB",
detail: "micro:bit",
description: usb
? `${usb.description || ""}(${usb.connectionState})`
: "",
},*/
!!connecteds.length && {
transport: "none",
label: "Disconnect",
detail: `Disconnect from ${connecteds
.map(tr => tr.type)
.join(", ")}`,
},
!sim && {
label: "Simulator",
kind: vscode.QuickPickItemKind.Separator,
},
!sim && {
label: shortDeviceId(simulatorScriptManagerId),
description: `Simulator`,
detail: `A virtual DeviceScript interpreter running in a separate process.`,
transport: simulatorScriptManagerId,
},
{
label: "Firmware Tools",
kind: vscode.QuickPickItemKind.Separator,
},
{
label: "Flash Firmware...",
transport: "flash",
detail: "Flash the DeviceScript runtime on new devices.",
},
{
label: "Clean Flash...",
transport: "clean",
detail: "Erase the entire flash.",
},
].filter(m => !!m)
const res = await vscode.window.showQuickPick(items, {
title: "Pick a DeviceScript connection",
})
if (res === undefined || !res.transport) return
if (res.transport === "flash") await this.flashFirmware()
else if (res.transport === "clean") await this.cleanFirmware()
else if (res.transport === simulatorScriptManagerId)
await this.startSimulator()
else
await sideRequest<SideConnectReq>({
req: "connect",
data: {
transport: res.transport,
background: false,
resourceGroupId: CONNECTION_RESOURCE_GROUP,
},
})
}
async startSimulator(clearFlash?: boolean) {
const did = this.simulatorScriptManagerId
await this.devtools.start()
if (!this.devtools.connected) return
if (this.bus.device(did, true)) return // already running
const config = vscode.workspace.getConfiguration(
"devicescript.simulator"
)
const nativePath = config.get("runNative")
? (config.get("nativePath") as string) || undefined
: undefined
await sideRequest<SideStartVmReq>({
req: "startVM",
data: {
nativePath,
deviceId: did,
clearFlash: !!clearFlash,
},
})
// wait for it to enumerate
let max = 20
while (max-- > 0 && !this.bus.device(did, true)) await delay(200)
}
async stopSimulator() {
if (this.devtools.connectionState === ConnectionState.Connected)
await sideRequest<SideStopVmReq>({
req: "stopVM",
data: {},
})
}
async clearSimulatorFlash() {
await this.stopSimulator()
await this.startSimulator(true)
}
async pickDeviceScriptFile(
options?: vscode.QuickPickOptions & {
fileSearchPattern?: string
forcePick?: boolean
}
): Promise<vscode.Uri> {
const { fileSearchPattern = "src/main*.ts", forcePick } = options || {}
const { projectFolder: folder } = this.devtools
if (!folder) return undefined
// find file marker
const configs = await vscode.workspace.findFiles(
new vscode.RelativePattern(folder, "**/devsconfig.json"),
"**/node_modules/**"
)
// get all typescript files next to config file
let files = (
await Promise.all(
configs
.filter(cfg => !/\/node_modules\//.test(cfg.fsPath))
.map(async cfg => {
const d = Utils.dirname(cfg).fsPath
const res = await vscode.workspace.findFiles(
new vscode.RelativePattern(d, fileSearchPattern),
"**/node_modules/**"
)
return res
})
)
).flat()
// ignore .devicescript files
files = files.filter(f => !/\/\.devicescript\//.test(f.fsPath))
// sort
files.sort((l, r) => l.path.localeCompare(r.path))
// unique
files = [...new Set(files)]
if (!files.length) {
showErrorMessage("pickfile.notfound", "Could not find any file.")
return undefined
}
// only 1 file
if (files.length === 1 && !forcePick) return files[0]
// ask user
const res = await vscode.window.showQuickPick(
files.map(
file =>
<TaggedQuickPickItem<vscode.Uri>>{
data: file,
label: Utils.basename(file),
description: Utils.dirname(file).fsPath,
}
),
{
...options,
canPickMany: false,
}
)
return res?.data
}
async configure() {
const project = await this.devtools.showQuickPickProjects()
if (project === undefined) return
await this.devtools.setProjectFolder(project)
await this.devtools.start()
}
async build(file: vscode.Uri) {
const status = await this.devtools.buildFile(file)
if (!status?.success)
vscode.commands.executeCommand("workbench.action.problems.focus")
}
async pickDeviceScriptManager(options?: {
autoStartSimulator?: boolean
skipUpdate?: boolean
}): Promise<JDService> {
const { simulatorScriptManagerId } = this
const { skipUpdate, autoStartSimulator } = options || {}
const cid = this.state.get(STATE_CURRENT_DEVICE) as string
await this.devtools.start()
if (!this.devtools.connected) return
let startVM = false
let did: string
const services = this.bus.services({
serviceClass: SRV_DEVICE_SCRIPT_MANAGER,
lost: false,
})
if (!services.length && autoStartSimulator) {
did = simulatorScriptManagerId
startVM = true
} else if (services.length === 1) {
did = services[0].device.deviceId
} else {
const detail = async (srv: JDService) => {
const runtimeVersion = await readRuntimeVersion(srv)
const description = srv.device
.service(0)
.register(ControlReg.DeviceDescription)
await description.refresh(true)
return `${description.stringValue || ""} (${
runtimeVersion || "?"
})`
}
const items: DeviceQuickItem[] = await Promise.all(
services.map(
async srv =>
<DeviceQuickItem>{
label: `$(${JDomDeviceTreeItem.ICON}) ${srv.device.friendlyName}`,
description: srv.device.deviceId,
detail: await detail(srv),
data: srv.device.deviceId,
picked: srv.device.deviceId === cid,
}
)
)
if (!items.find(({ data }) => data === simulatorScriptManagerId)) {
startVM = true
items.push(<DeviceQuickItem>{
label: shortDeviceId(simulatorScriptManagerId),
description: `Simulator`,
detail: `A virtual DeviceScript interpreter running in a separate process.`,
data: simulatorScriptManagerId,
})
}
const res = await vscode.window.showQuickPick(items, {
title: `Pick a DeviceScript device`,
matchOnDescription: true,
matchOnDetail: true,
canPickMany: false,
})
did = res?.data
if (!did) return undefined
}
if (startVM && did == simulatorScriptManagerId) {
await this.startSimulator()
} else {
startVM = false
}
const service = this.bus.device(did, true)?.services({
serviceClass: SRV_DEVICE_SCRIPT_MANAGER,
})?.[0]
if (service) await prepareForDeploy(this, service)
if (service && !skipUpdate)
await this.updateCurrentDeviceScriptManagerId(
service.device.deviceId
)
return service
}
async runFile(file: vscode.Uri, options?: { debug?: boolean }) {
if (!file) return
const folder = vscode.workspace.getWorkspaceFolder(file)
if (!folder) return
const { debug } = options || {}
await vscode.debug.startDebugging(folder, {
type: "devicescript",
request: "launch",
name: "DeviceScript: Run File",
stopOnEntry: false,
noDebug: !debug,
program: file.path,
} as vscode.DebugConfiguration)
if (!debug)
vscode.commands.executeCommand("extension.devicescript.jdom.focus")
}
}