-
Notifications
You must be signed in to change notification settings - Fork 4
/
extension.js
1043 lines (874 loc) · 36.2 KB
/
extension.js
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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// modules
const vscode = require('vscode');
const fs = require("fs-extra");
const os = require("os");
const path = require("path");
const ext = require('./src/dsclient');
const debugServer = require('./src/websocket');
const localData = require("./src/local-data");
const connectToDroidScript = require("./src/commands/connect-to-droidscript");
const CONSTANTS = require("./src/CONSTANTS");
const { homePath, excludeFile, batchPromises, first, loadConfig } = require("./src/util");
const DocsTreeData = require("./src/DocsTreeView");
const ProjectsTreeData = require("./src/ProjectsTreeView");
const SamplesTreeData = require("./src/SamplesTreeView");
const createNewApp = require("./src/commands/create-app");
const deleteApp = require("./src/commands/delete-app");
const revealExplorer = require("./src/commands/revealExplorer");
const renameApp = require("./src/commands/rename-app");
const smartDeclare = require('./src/commands/smartDeclare');
const completionItemProvider = require("./src/providers/completionItemProvider");
const hoverProvider = require("./src/providers/hoverProvider");
const signatureHelpProvider = require("./src/providers/signatureHelperProvider");
const codeActionProvider = require("./src/providers/codeActionProvider");
// global variables
let PROJECT = "";
/** @type {DSCONFIG_T} */
let DSCONFIG;
/** @type {vscode.ExtensionContext} */
let GlobalContext;
/** @type {vscode.StatusBarItem?} */
let connectionStatusBarItem;
/** @type {vscode.StatusBarItem?} */
let projectName;
let closeSamplePlay = false;
/** @type {DocsTreeData.TreeDataProvider} */
let docsTreeDataProvider;
/** @type {ProjectsTreeData.TreeDataProvider} */
let projectsTreeDataProvider;
/** @type {SamplesTreeData.TreeDataProvider} */
let samplesTreeDataProvider;
/** @type {ReturnType<debugServer>} */
let dbgServ;
/** @type {vscode.StatusBarItem?} */
let syncButton;
/** @type {vscode.StatusBarItem?} */
let playButton;
/** @type {vscode.StatusBarItem?} */
let stopButton;
/** @type {vscode.Uri} */
let folderPath;
// subscriptions for registerCommands
let subscribe = null;
let startup = true;
// This method is called to activate the extension
/** @param {vscode.ExtensionContext} context */
async function activate(context) {
CONSTANTS.DEBUG = context.extensionMode == vscode.ExtensionMode.Development;
DSCONFIG = localData.load();
dbgServ = debugServer(onDebugServerStart, onDebugServerStop);
subscribe = (/** @type {string} */ cmd, /** @type {(...args: any[]) => any} */ fnc) => {
context.subscriptions.push(vscode.commands.registerCommand("droidscript-code." + cmd, fnc));
}
subscribe("connect", () => connectToDroidScript(dbgServ.start));
subscribe("disconnect", dbgServ.stop);
subscribe("loadFiles", loadFiles);
subscribe("extractAssets", extractAssets);
subscribe("stopApp", stop);
subscribe("refreshProjects", () => {
if (CONNECTED) projectsTreeDataProvider.refresh();
else showReloadPopup();
});
subscribe("openDroidScriptDocs", openDocs);
subscribe("learnToConnect", openConnectTutorial);
// projects
subscribe("play", play);
subscribe("stop", stop);
subscribe("runApp", (/** @type {ProjectsTreeData.ProjItem?} */ treeItem) => {
play(treeItem?.title || PROJECT)
});
subscribe("openApp", openProject);
subscribe("openAppInNewWindow", openProject);
subscribe("revealExplorer", (/** @type {ProjectsTreeData.ProjItem} */ treeItem) => {
revealExplorer(treeItem, projectsTreeDataProvider)
});
subscribe("addNewApp", createAppDialog);
subscribe("deleteApp", deleteAppDialog);
subscribe("renameApp", renameAppDialog);
subscribe("exec", execCommand);
subscribe("addTypes", addTypes);
subscribe("autoFormat", autoFormat);
subscribe("declareVars", smartDeclareVars);
// samples
subscribe("openSample", openSample);
subscribe("runSample", runSampleProgram);
const createFile = vscode.workspace.onDidCreateFiles(onCreateFile);
const deleteFile = vscode.workspace.onDidDeleteFiles(onDeleteFile);
const onSave = vscode.workspace.onDidSaveTextDocument(onDidSaveTextDocument);
const onRename = vscode.workspace.onDidRenameFiles(onRenameFile);
// autocompletion and intellisense
context.subscriptions.push(
onSave,
createFile,
deleteFile,
onRename,
completionItemProvider.register(),
codeActionProvider.register(),
hoverProvider.register(),
signatureHelpProvider.register()
);
GlobalContext = context;
// Create the TreeDataProvider for the new View
projectsTreeDataProvider = new ProjectsTreeData.TreeDataProvider();
let projectsTreeView = vscode.window.createTreeView('droidscript-projects', {
treeDataProvider: projectsTreeDataProvider,
showCollapseAll: false // Optional: Show a collapse all button in the new TreeView
});
docsTreeDataProvider = new DocsTreeData.TreeDataProvider();
let docsTreeView = vscode.window.createTreeView('droidscript-docs', {
treeDataProvider: docsTreeDataProvider,
showCollapseAll: false // Optional: Show a collapse all button in the new TreeView
});
samplesTreeDataProvider = new SamplesTreeData.TreeDataProvider();
let samplesTreeView = vscode.window.createTreeView('droidscript-samples', {
treeDataProvider: samplesTreeDataProvider,
showCollapseAll: false // Optional: Show a collapse all button in the new TreeView
});
prepareWorkspace();
const assetsExist = fs.existsSync(homePath(CONSTANTS.LOCALFOLDER))
if (CONSTANTS.VERSION > DSCONFIG.VERSION || !assetsExist || CONSTANTS.DEBUG) {
// extract assets
extractAssets();
// set the version
DSCONFIG.VERSION = CONSTANTS.VERSION;
localData.save(DSCONFIG);
if (!CONSTANTS.DEBUG) vscode.commands.executeCommand("markdown.showPreview", vscode.Uri.file(__dirname + "/Highlights.md"));
}
signatureHelpProvider.init();
completionItemProvider.init();
displayConnectionStatus();
}
// This method is called when extension is deactivated
function deactivate() {
dbgServ.stop();
vscode.commands.executeCommand('livePreview.end');
}
// Assets related functions
async function extractAssets() {
try {
// clear .droidscript folder first
fs.removeSync(homePath(CONSTANTS.LOCALFOLDER));
await createAssetFolder(CONSTANTS.LOCALFOLDER);
await createAssetFolder(CONSTANTS.SAMPLES);
await createAssetFolder(CONSTANTS.DEFINITIONS);
const defFolder = path.join(__dirname, "definitions");
fs.copySync(defFolder, homePath(CONSTANTS.DEFINITIONS), { overwrite: true });
} catch (e) {
catchError(e);
}
}
/** @param {string} paths */
async function createAssetFolder(paths) {
fs.mkdirSync(homePath(paths), { recursive: true });
}
async function prepareWorkspace() {
const uris = (vscode.workspace.workspaceFolders || []).map(ws => ws.uri)
.concat(vscode.window.visibleTextEditors.map(te => te.document.uri))
if (!uris.length) return;
displayConnectionStatus();
const reloadProj = localData.getProjectByName(DSCONFIG.reload || '');
const openProj = first(uris, uri => localData.getProjectByFile(uri.fsPath));
if (!openProj) return;
const proj = reloadProj || openProj;
// this is from DroidScript CLI
if (proj.reload) {
proj.reload = false;
delete DSCONFIG.reload;
localData.save(DSCONFIG);
}
else {
const selection = await vscode.window.showInformationMessage(proj.PROJECT + " is a DroidScript app.\nConnect to DroidScript?", "Proceed")
if (selection !== "Proceed") return;
}
setProjectName((reloadProj || proj).PROJECT);
vscode.commands.executeCommand("droidscript-code.connect");
}
/** @param {vscode.Uri} filePath */
async function openFile(filePath) {
try {
// Open the text document
const document = await vscode.workspace.openTextDocument(filePath);
// Show the document in the editor
await vscode.window.showTextDocument(document, vscode.ViewColumn.One);
} catch (error) {
vscode.window.showErrorMessage(`Error opening file: ${error.message}`);
}
}
/** @typedef {"dnlAll" | "uplAll" | "updLocal" | "updRemote" | "skip"} SyncAction */
/** @typedef {{ icon: string, text: string, desc: string }} SyncActionItem */
/** @type {{[x in SyncAction]: SyncActionItem}} */
const syncActions = {
updLocal: { icon: '$(chevron-down)', text: 'Update Local', desc: "downloads only remote files that already exists locally" },
dnlAll: { icon: '$(fold-down)', text: 'Download All', desc: "downloads all files from the remote" },
updRemote: { icon: '$(chevron-up)', text: 'Update Remote', desc: "uploads only files that already exist on the remote" },
uplAll: { icon: '$(fold-up)', text: 'Upload All', desc: "uploads all local files to the remote" },
skip: { icon: '$(blocked)', text: 'Skip', desc: "Do not sync" }
};
/** @type {SyncAction} */
let lastSyncAction = "updLocal";
// Load all files in the selected project
/** @param {SyncAction} [action] */
async function loadFiles(action) {
if (syncButton && syncButton.text.includes("$(sync~spin)")) return;
if (!action) {
/** @type {(vscode.QuickPickItem & { key: SyncAction })[]} */
const items = Object.entries(syncActions).map(([key, a]) => ({
label: a.icon + a.text,
detail: a.desc,
picked: key === lastSyncAction,
key: /** @type {SyncAction}*/ (key)
}));
const selection = await vscode.window.showQuickPick(items, {
title: `Select sync action for \`${PROJECT}\``,
ignoreFocusOut: true
});
if (!selection || selection.key == "skip") return;
action = lastSyncAction = selection.key;
displayControlButtons();
}
if (PROJECT) {
if (syncButton) syncButton.text = `$(sync~spin) ${syncActions[action].text}`
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: `${PROJECT}:${syncActions[action].text}...`,
cancellable: false
}, async (proc) => await getAllFiles(PROJECT, proc, action || lastSyncAction).catch(catchError));
if (syncButton) syncButton.text = "$(sync) Sync";
}
else {
vscode.window.showInformationMessage("Open an app in the DroidScript's 'PROJECT' section.");
}
}
/**
* @param {string} folder
* @param {ProjConfig} conf
* @param {vscode.Progress<{message?:string, increment?:number}>} [proc]
*/
async function indexFolder(folder, conf, proc, listFolder = ext.listFolder, root = folder) {
folder = folder || PROJECT;
if (!folder.startsWith('/')) root = folder += '/';
let data = await listFolder(folder);
proc?.report({ message: "indexing " + folder });
if (data.status !== "ok") throw Error(data.error);
if (!data.list.length) return [];
/** @type {string[]} */
const files = [];
for (var i = 0; i < data.list.length; i++) {
let file = data.list[i], path = folder + file;
// ignore hidden files
if (excludeFile(conf, path.replace(root, ''))) continue;
if (file.indexOf('.') > 0)
files.push(path);
else if (!excludeFile(conf, path.replace(root, '') + '/'))
files.push(...await indexFolder(path + '/', conf, proc, listFolder, root));
}
return files;
}
/**
* @param {string} folder
* @param {vscode.Progress<{message?:string, increment?:number}>} proc
* @param {SyncAction} action Update existing files. Default is download all
*/
async function getAllFiles(folder, proc, action) {
if (!CONNECTED) return showReloadPopup();
const proj = localData.getProjectByName(PROJECT);
if (!proj) return;
const conf = loadConfig(proj);
let remoteFiles = (await indexFolder(folder, conf, proc).catch(e => (catchError(e), [])))
.map(f => f.replace(PROJECT + '/', ''));
let localFiles = (await indexFolder(proj.path, conf, proc,
async p => ({ status: 'ok', list: fs.readdirSync(p) }))
.catch(e => (catchError(e), [])))
.map(f => f.replace(proj.path + '/', ''));
const update = action == "updLocal" || action == "updRemote";
if (update) {
localFiles = localFiles.filter(file => remoteFiles.includes(file));
remoteFiles = [...localFiles];
}
const download = action == "dnlAll" || action == "updLocal";
if (download) {
const folders = new Set(remoteFiles.map(p => path.dirname(p)));
for (const folder of folders)
if (folder != '.') createFolder(folder);
await batchPromises(remoteFiles, async (file) => {
proc.report({ message: file, increment: 100 / remoteFiles.length });
let response = await ext.loadFile(PROJECT + '/' + file);
if (response.status !== "ok") throw Error(`Error fetching ${file}:\n${response.error}\n${response.data || ''}`)
writeFile(file, response.data);
});
} else {
await batchPromises(localFiles, async (file) => {
proc.report({ message: file, increment: 100 / localFiles.length });
uploadFile(file);
});
}
}
async function showReloadPopup(auto = false) {
if (CONNECTED) return
const selection = auto || await vscode.window.showInformationMessage("You are currently disconnected!", "Reconnect");
if (auto || selection === "Reconnect") await vscode.commands.executeCommand("droidscript-code.connect");
}
/** @param {string} filePath */
function getLocalPath(filePath) {
if (!folderPath) throw Error("Something went wrong");
return path.resolve(folderPath.fsPath, filePath);
}
/** Write the file to the workspace
* @param {string} fileName
* @param {string | NodeJS.ArrayBufferView} content
*/
function writeFile(fileName, content) {
const filePath = getLocalPath(fileName);
fs.writeFileSync(filePath, content, { flag: 'w' });
}
/** Create a folder in the workspace
* @param {string} dirPath
*/
function createFolder(dirPath) {
const localPath = getLocalPath(dirPath);
fs.mkdirSync(localPath, { recursive: true });
}
/** Write the file to remote project
* @param {string} file
*/
async function uploadFile(file) {
const localPath = getLocalPath(file);
const dstDir = path.dirname(PROJECT + '/' + file);
await ext.uploadFile(localPath, dstDir, path.basename(file));
}
/**
* @param {string} filePath
* @param {LocalProject} [proj]
*/
function getRemotePath(filePath, proj) {
if (!proj) proj = getFileProject(filePath);
if (!proj) return null;
const conf = loadConfig(proj);
const dsFile = path.relative(proj.path, filePath);
if (excludeFile(conf, dsFile)) return null;
return proj.PROJECT + "/" + dsFile.replace(/\\/g, '/');
}
/**
* @param {string} filePath
*/
function getFileProject(filePath) {
return localData.getProjectByFile(filePath);
}
// Called when the document is save
/** @type {vscode.TextDocument[]} */
let documentsToSave = [];
/** @param {vscode.TextDocument} [doc] */
async function onDidSaveTextDocument(doc) {
if (doc && getFileProject(doc.uri.fsPath)) documentsToSave.push(doc);
if (!documentsToSave.length) return;
if (!CONNECTED) return showReloadPopup();
// prevent race conditions
const fileList = documentsToSave;
documentsToSave = [];
await batchPromises(fileList, async doc => {
const dsFile = getRemotePath(doc.uri.fsPath);
if (!dsFile) return;
await ext.uploadFile(doc.uri.fsPath, path.dirname(dsFile), path.basename(dsFile));
});
}
// Delete the file on the workspace
/** @type {vscode.Uri[]} */
let filesToDelete = [];
/** @param {vscode.FileDeleteEvent} [e] */
async function onDeleteFile(e) {
if (e) filesToDelete.push(...e.files.filter(f => getFileProject(f.fsPath)));
if (!filesToDelete.length) return;
if (!CONNECTED) return showReloadPopup();
// prevent race conditions
const fileList = filesToDelete;
filesToDelete = [];
await batchPromises(fileList, async file => {
const dsFile = getRemotePath(file.fsPath);
if (!dsFile) return;
await ext.deleteFile(dsFile).catch(catchError);
});
}
/** @type {(error: any) => DSServerResponse<{status:"bad"}>} */
const catchError = (error) => {
console.error(error.stack || error.message || error);
vscode.window.showErrorMessage(error.message || error);
return { status: "bad", error };
}
// Create files and folders on the workspace
/** @type {vscode.Uri[]} */
let filesToCreate = [];
/** @param {vscode.FileCreateEvent} [e] */
async function onCreateFile(e) {
if (e) filesToCreate.push(...e.files.filter(f => getFileProject(f.fsPath)));
if (!filesToCreate.length) return;
if (!CONNECTED) return showReloadPopup();
// prevent race conditions
const fileList = filesToCreate;
filesToCreate = [];
await batchPromises(fileList, async file => {
const dsFile = getRemotePath(file.fsPath);
if (!dsFile) return;
const stats = fs.statSync(file.fsPath);
if (stats.isFile()) {
const response = await ext.uploadFile(file.fsPath, path.dirname(dsFile), path.basename(dsFile));
if (response.status !== "ok")
vscode.window.showErrorMessage("An error occured while writing the file in DroidScript.");
}
else if (stats.isDirectory()) {
// folder
// const code = `app.MakeFolder("${filePath}")`;
// response = await ext.execute("usr", code);
// console.log( response );
}
});
}
// Rename a files in the workspace
/** @type {{oldUri: vscode.Uri, newUri: vscode.Uri}[]} */
let filesToRename = [];
/** @param {vscode.FileRenameEvent} [e] */
async function onRenameFile(e) {
if (e) filesToRename.push(...e.files.filter(f => getFileProject(f.oldUri.fsPath) && getFileProject(f.newUri.fsPath)));
if (!filesToRename.length) return;
if (!CONNECTED) return showReloadPopup();
// prevent race conditions
const fileList = filesToRename;
filesToRename = [];
await batchPromises(fileList, async file => {
const oldDsFile = getRemotePath(file.oldUri.fsPath);
const newDsFile = getRemotePath(file.newUri.fsPath);
if (!oldDsFile || !newDsFile) return;
await ext.renameFile(oldDsFile, newDsFile).catch(catchError);
});
}
// control buttons
function displayControlButtons() {
if (!PROJECT) return;
if (!syncButton) {
syncButton = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
syncButton.command = 'droidscript-code.loadFiles';
syncButton.text = '$(sync) Sync';
syncButton.tooltip = 'Sync ' + PROJECT;
GlobalContext.subscriptions.push(syncButton);
}
if (!playButton) {
playButton = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
playButton.command = 'droidscript-code.play';
playButton.text = '$(run) Run';
playButton.tooltip = 'DroidScript: Run';
GlobalContext.subscriptions.push(playButton);
}
if (!stopButton) {
stopButton = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
stopButton.command = 'droidscript-code.stop';
stopButton.text = '$(debug-stop) Stop';
stopButton.tooltip = 'DroidScript: Stop';
GlobalContext.subscriptions.push(stopButton);
}
syncButton.show();
playButton.show();
stopButton.show();
}
// connection status
function displayConnectionStatus() {
if (!connectionStatusBarItem) {
connectionStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right);
connectionStatusBarItem.tooltip = "DroidScript Connection Status";
connectionStatusBarItem.command = "droidscript-code.connect"; // Replace with your command ID or leave it empty
}
if (CONNECTED) connectionStatusBarItem.text = "$(radio-tower) Connected: " + DSCONFIG.serverIP; // Wi-Fi icon
else connectionStatusBarItem.text = "$(circle-slash) Connect to Droidscript"; // Wi-Fi icon
connectionStatusBarItem.show();
}
/**
* display project name
* @param {string} project
*/
function setProjectName(project = "") {
if (project) {
PROJECT = project;
ext.exec("!setprog " + PROJECT);
}
if (!projectName) projectName = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
projectName.text = "DroidScript";
if (PROJECT) projectName.text += ` (${PROJECT})`;
projectName.command = CONNECTED ? undefined : "droidscript-code.connect";
projectName.tooltip = CONNECTED ? PROJECT : "Connect";
projectName.show();
}
function showStatusBarItems() {
displayControlButtons();
displayConnectionStatus();
}
function hideStatusBarItems() {
syncButton?.hide();
playButton?.hide();
stopButton?.hide();
displayConnectionStatus();
}
/** @param {string} APPNAME */
async function play(APPNAME) {
if (!CONNECTED) return showReloadPopup(true);
const edt = vscode.window.activeTextEditor
await edt?.document.save()
if (!APPNAME && edt) {
const proj = localData.getProjectByFile(edt.document.uri.fsPath)
if (proj) setProjectName(proj.PROJECT);
}
if (!APPNAME && !PROJECT) return vscode.window.showWarningMessage("No Project Selected");
dbgServ.playApp(APPNAME || PROJECT, "app");
ext.play(APPNAME || PROJECT);
}
/** @param {SamplesTreeData.TreeItem} treeItem */
function runSampleProgram(treeItem) {
let title = (treeItem.label || '') + '';
let category = treeItem.category || '';
if (title.includes("♦")) {
return vscode.window.showWarningMessage("PREMIUM FEATURE. Please subscribe to 'DroidScript Premium' to run this sample.");
}
if (!CONNECTED) return showReloadPopup(true);
dbgServ.playApp(title, "sample")
ext.runSample(title, category);
}
function stop() {
if (!CONNECTED) return showReloadPopup(true);
dbgServ.stopApp();
ext.stop();
}
async function createAppDialog() {
if (!CONNECTED) return showReloadPopup();
const info = await createNewApp();
if (!info) return
if (projectsTreeDataProvider) projectsTreeDataProvider.refresh();
if (openProject) openProject(info);
}
/** @param {ProjectsTreeData.ProjItem} item */
async function deleteAppDialog(item) {
const appName = item?.title;
if (!appName) return vscode.window.showWarningMessage("Selec an app in DroidScript's PROJECTS section!");
const res = await deleteApp(item);
if (res?.status !== 'ok') return
projectsTreeDataProvider.refresh();
if (appName == PROJECT) {
dbgServ.stop();
setProjectName();
}
// remove the folder path in the localProjects array
let i = DSCONFIG.localProjects.findIndex(m => m.PROJECT == appName) || -1;
if (i >= 0) {
DSCONFIG.localProjects.splice(i, 1);
localData.save(DSCONFIG);
}
}
/** @param {ProjectsTreeData.ProjItem} item */
async function renameAppDialog(item) {
const appName = item?.title;
const proj = localData.getProjectByName(appName);
if (!appName || !proj) return vscode.window.showWarningMessage("Rename an app in DroidScript section under Projects view!");
const res = await renameApp(item);
if (res?.status === 'error') vscode.window.showErrorMessage('Failed to rename app: ' + res.error);
if (res?.status !== 'ok') return
projectsTreeDataProvider.refresh();
vscode.window.showInformationMessage(`${appName} successfully renamed to ${res.name}.`);
proj.reload = true;
DSCONFIG.reload = proj.PROJECT = res.name;
localData.save(DSCONFIG);
openProjectFolder(proj, false);
}
async function execCommand() {
if (!CONNECTED) return showReloadPopup();
/** @type {vscode.QuickPickItem[]} */
const items = [
{ label: '!savespk', description: 'Save SPK file to SPKs' },
{ label: '!addpackage [url]', description: 'Add a package with the specified URL' },
{ label: '!getperms', description: 'Get all detected permissions used by your app' },
{ label: '!addplugin [name]', description: 'Add a plugin with the specified name' },
{ label: '!addmodule [name]', description: 'Add a Node.js module with the specified name' },
{ label: '!remplugin [name]', description: 'Remove a plugin with the specified name' },
{ label: '!buildapk [pkgname] [ver] [obfus]', description: 'Build APK with the specified package name, version, and obfuscation options' },
{ label: '!clean', description: 'Clean .edit folder and other extracted DroidScript assets' },
{ label: '!reset [options]', description: 'Reset DroidScript to clean install but keeping all projects.', detail: 'Clears Plugins, Extensions and with \'full\' option even saved settings' },
{ label: '!exit', description: 'Exit DroidScript' },
{ label: '$netstat', description: 'Display network status from android shell' },
{ label: '$logcat', description: 'Display logcat from android shell' },
{ label: '[custom]', description: 'Enter a custom command' }
];
const cmd = await vscode.window.showQuickPick(items, { title: "Select IDE command" });
if (!cmd) return;
/** @type {string|undefined} */
let params = "";
if (cmd.label.includes("[")) {
params = await vscode.window.showInputBox({
title: "Enter Params",
prompt: cmd.label
});
}
if (params === undefined) return;
let command = cmd.label;
if (command == '[custom]') command = params;
else if (params) command += ' ' + params;
ext.exec(command);
}
/** @param {ProjectsTreeData.ProjItem} item */
async function addTypes(item) {
if (!item.path) return vscode.window.showWarningMessage("Types can be only enabled on local projects.");
const jsconfigPath = path.join(item.path, "jsconfig.json");
if (fs.existsSync(jsconfigPath)) return;
const res = await vscode.window.showInformationMessage("This will add jsconfig.json to your project. Proceed?", "Ok", "Cancel");
if (res !== "Ok") return;
try {
let jsconfig = fs.readFileSync(homePath(CONSTANTS.DEFINITIONS, "default_jsconfig.json"), "utf8");
jsconfig = replacePaths(jsconfig, true);
fs.writeFileSync(jsconfigPath, jsconfig);
} catch (e) {
catchError(e);
}
}
/** @param {ProjectsTreeData.ProjItem} item */
async function autoFormat(item) {
if (!item.path) return vscode.window.showWarningMessage("AutoFormat can be only enabled on local projects.");
const settingsPath = path.join(item.path, ".vscode", "settings.json");
if (fs.existsSync(settingsPath)) return;
const res = await vscode.window.showInformationMessage("This will add .vscode/settings.json to your project. Proceed?", "Ok", "Cancel");
if (res !== "Ok") return;
try {
fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
fs.copyFileSync(homePath(CONSTANTS.DEFINITIONS, "settings.json"), settingsPath);
} catch (e) {
catchError(e);
}
}
/** @param {ProjectsTreeData.ProjItem | vscode.Uri} [file] */
async function smartDeclareVars(file) {
let uri = file || vscode.window.activeTextEditor?.document.uri;
if (!uri) return;
if (!(uri instanceof vscode.Uri)) {
const info = await ext.getProjectInfo(uri.path || '', uri.title, async p => fs.existsSync(p));
if (!info) return vscode.window.showWarningMessage("No local project '" + uri.title + "' available.");
if (info.ext !== "js") return vscode.window.showWarningMessage(uri.title + " is not a JavaScript project.");
uri = vscode.Uri.file(info.file);
}
await smartDeclare(uri);
}
async function downloadDefinitions() {
let defPath, res;
for (defPath of CONSTANTS.defPaths) {
res = await ext.listFolder(defPath);
if (res.status === "ok" && res.list.length) break;
}
if (res?.status !== "ok" || !res.list.length) return;
for (const file of res.list) {
if (!file.endsWith(".d.ts")) continue;
await createAssetFolder(CONSTANTS.DEFINITIONS).catch(catchError);
console.log("fetching " + defPath + file);
const content = await ext.loadFile(defPath + file).catch(catchError);
if (content.status !== "ok") continue;
const defFile = homePath(CONSTANTS.DEFINITIONS, "ts", file);
fs.writeFileSync(defFile, content.data);
}
}
async function onDebugServerStart() {
downloadDefinitions();
samplesTreeDataProvider.refresh();
projectsTreeDataProvider.refresh();
// pluginsTreeDataProvider.refresh();
checkUnsavedChanges();
showStatusBarItems();
if (PROJECT) {
openProject({ title: PROJECT });
projectsTreeDataProvider.refresh();
}
}
async function checkUnsavedChanges() {
const changes = [
...documentsToSave.map(f => 'save ' + getRemotePath(f.uri.fsPath)),
...filesToDelete.map(f => 'delete ' + getRemotePath(f.fsPath)),
...filesToCreate.map(f => 'create ' + getRemotePath(f.fsPath)),
...filesToRename.map(f => `rename ${getRemotePath(f.oldUri.fsPath)} to ${getRemotePath(f.newUri.fsPath)}`),
];
if (!changes.length) return;
const selection = await vscode.window.showWarningMessage("Apply unsaved changes to remote project?", {
modal: true, detail: changes.join('\n')
}, "Save");
if (selection != "Save") return;
if (documentsToSave.length) await onDidSaveTextDocument();
if (filesToDelete.length) await onDeleteFile();
if (filesToCreate.length) await onCreateFile();
if (filesToRename.length) await onRenameFile();
}
async function onDebugServerStop() {
hideStatusBarItems();
setProjectName();
// pluginsTreeDataProvider.refresh();
samplesTreeDataProvider.refresh();
projectsTreeDataProvider.refresh();
const selection = await vscode.window.showWarningMessage("DroidScript disconnected.", "Reconnect");
if (selection === "Reconnect") vscode.commands.executeCommand("droidscript-code.connect");
}
// documentations
/** @type {vscode.WebviewPanel?} */
let docsPanel;
/** @param {DocsTreeData.TreeItem} [item] */
async function openDocs(item) {
if (!docsPanel) {
docsPanel = vscode.window.createWebviewPanel('dsDocs',
'Documentation', vscode.ViewColumn.Two,
{ enableScripts: true }
);
docsPanel.onDidDispose(e => {
docsPanel = null;
});
}
const url = DocsTreeData.getUrl(item ? item.contextValue : "Docs.htm");
console.log("Doc Page: " + url, item);
docsPanel.webview.html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>body,html,iframe {width:100%;height:100%;margin:0;padding:0;border:none}</style>
</head>
<body><iframe src=${JSON.stringify(url)}></body>
</html>`;
}
/**
* @param {ProjectsTreeData.ProjItem & vscode.TreeItem} item
*/
async function openProject(item) {
const SELECTED_PROJECT = item.contextValue || item.title;
let proj = localData.getProjectByName(SELECTED_PROJECT) || null;
if (proj && !fs.existsSync(proj.path)) proj = null;
// open existing local project
if (proj) {
proj.reload = true;
DSCONFIG.reload = proj.PROJECT;
localData.save(DSCONFIG);
openProjectFolder(proj);
return;
}
/** @type {"Other" | "Current" | undefined} */
let selection = "Other";
let folder = folderPath?.fsPath || DSCONFIG.localProjects[0]?.path || "";
if (folder) {
folder = path.resolve(folder, "..", SELECTED_PROJECT);
selection = await vscode.window.showInformationMessage("Open folder in current location",
{ modal: true, detail: folder }, "Current", "Other");
}
if (!selection) return;
if (selection === "Other") {
const folders = await vscode.window.showOpenDialog({
canSelectFiles: false,
canSelectFolders: true,
openLabel: "Choose Project Location",
title: "Choose Project Folder"
});
if (!folders || !folders.length) return;
folder = folders[0].fsPath;
}
else await fs.mkdir(folder).catch(catchError);
if (!fs.existsSync(folder)) return vscode.window.showInformationMessage("Selected folder does not exist.");
/** @type {LocalProject} */
const newProj = {
path: folder,
PROJECT: SELECTED_PROJECT,
created: Date.now(),
reload: true
}
DSCONFIG.localProjects.push(newProj);
localData.save(DSCONFIG);
openProjectFolder(newProj, "dnlAll");
projectsTreeDataProvider.refresh();
}
/**
* @param {LocalProject} proj
* @param {boolean | SyncAction} sync
*/
async function openProjectFolder(proj, sync = true) {
let info = await ext.getProjectInfo(proj.path, proj.PROJECT, async p => fs.existsSync(p));
const exists = info != null;
if (!exists && sync) {
folderPath = vscode.Uri.file(proj.path);
setProjectName(proj.PROJECT);
localData.save(DSCONFIG);
await loadFiles(sync !== true ? sync : undefined);
info = await ext.getProjectInfo(proj.path, proj.PROJECT, async p => fs.existsSync(p));
}
const isOpen = vscode.workspace.workspaceFolders?.find(ws => ws.uri.fsPath === proj.path);
if (!isOpen) {
const selection = await vscode.window.showInformationMessage(`Open '${proj.PROJECT}'?`, {
modal: true,
detail: `This will add '${proj.PROJECT}' to your workspace.`
}, "Open");
if (selection !== "Open") return;
folderPath = vscode.Uri.file(proj.path);
const n = vscode.workspace.workspaceFolders?.length || 0;
const success = vscode.workspace.updateWorkspaceFolders(n, 0, { uri: folderPath, name: proj.PROJECT });
if (!success) return vscode.window.showWarningMessage("Something went wrong: Invalid Workspace State");
}
folderPath = vscode.Uri.file(proj.path);
setProjectName(proj.PROJECT);
const projFile = getLocalPath('.dsproj');
if (!fs.existsSync(projFile)) fs.writeFileSync(projFile, '{}')
showStatusBarItems();
try {
if (!info) return vscode.window.showErrorMessage("Couldn't fetch project info.");
vscode.commands.executeCommand("workbench.explorer.fileView.focus");
await openFile(vscode.Uri.file(info.file));
if (startup) await openDocs();
startup = false;
} catch (e) {
catchError(e);
}
if (exists && sync) await loadFiles(sync !== true ? sync : undefined);
}
/** @param {string} string */
function replacePaths(string, unix = false) {
/** @type {{[x:string]:string}} */
const pathDict = {
userHome: os.homedir(),
};
if (folderPath) {
pathDict.projectFolder = folderPath.fsPath;
pathDict.projectName = PROJECT;
pathDict.WorkspaceFolder = path.dirname(folderPath.fsPath);
}
/** @param {string} p */
const norm = p => p.split(/[/\\]/).join(unix ? path.posix.sep : path.sep)
return string
.replace(/\$\{(\w+)\}/g, (m, v) => {
// @ts-ignore