-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.js
More file actions
1082 lines (900 loc) · 44.1 KB
/
Copy pathextension.js
File metadata and controls
1082 lines (900 loc) · 44.1 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
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
const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const http = require('http');
const https = require('https');
const webModules = require('./src/webModules');
// Add a global terminal variable
let cargoTerminal = null;
function activate(context) {
// Add it to context so it's disposed properly
// Register a handler to reset terminal reference when it's closed
context.subscriptions.push(
vscode.window.onDidCloseTerminal(terminal => {
if (terminal === cargoTerminal) {
cargoTerminal = null;
}
})
);
// Register the "Show Rust Menu" command
let disposableShowMenu = vscode.commands.registerCommand('extension.showRustMenu', async () => {
const options = [
{ label: 'Create Rust GUIProject', command: 'extension.createRustProject' },
{ label: 'Create Rust Script Project', command: 'extension.createRustScriptProject' },
{ label: 'Run Program', command: 'extension.disposableCargoRun' },
...webModules.buildConfiguredWebModuleMenuOptions(),
{ label: 'Add Rust General Help File From The Web', command: 'extension.disposableReadMeHelp' },
{ label: 'Add Rust Advanced Help File From The Web', command: 'extension.disposableAdvancedHelp' },
{ label: 'Build: Linux Output', command: 'extension.disposableNativeOut' },
{ label: 'Build: Windows Output', command: 'extension.disposableWindowOut' },
{ label: 'Build: Web Output (Basic)', command: 'extension.disposableWebOutBasic' },
{ label: 'Build: Web Output (Advanced)', command: 'extension.disposableWebOut' },
{ label: 'Test: Run Web Server', command: 'extension.disposableWebRun' },
{ label: '⚙️ Plugin Settings', command: 'extension.manageWebModules' },
];
const selected = await vscode.window.showQuickPick(options, { placeHolder: 'Choose an option' });
if (selected) {
try {
await vscode.commands.executeCommand(selected.command, ...(selected.args || []));
} catch (error) {
const message = error && error.message ? error.message : String(error);
vscode.window.showErrorMessage(`Command failed: ${message}`);
}
}
// context.subscriptions.push(disposableShowMenu);
});
// Register the "Create Rust Project" command
let disposableCreateRust = vscode.commands.registerCommand('extension.createRustProject', async () => {
const folderPath = await requireFolderPath();
if (!folderPath) {
return;
}
if (hasSpaceInFolderName(folderPath)) {
vscode.window.showErrorMessage('Folder names with spaces are not supported for project creation. Rename the folder to remove spaces and try again.');
return;
}
const date = new Date().toISOString().split('T')[0]; // Format YYYY-MM-DD
const rustfmtMaxWidth = getRustfmtMaxWidth();
const defaultWindowWidth = getDefaultWindowWidth();
const defaultWindowHeight = getDefaultWindowHeight();
const defaultFullscreen = getDefaultFullscreen();
const defaultResizable = getDefaultResizable();
const maxWaitTime = getCargoInitTimeoutMs();
const autoCreateAssetsFolder = shouldAutoCreateAssetsFolder();
let terminal = getOrCreateTerminal();
terminal.show();
terminal.sendText("cargo init");
terminal.sendText("cargo add macroquad");
// Add a cross-platform approach to add features section to Cargo.toml
// Set up a polling interval to check when Cargo.toml is ready
let checkInterval;
const startTime = Date.now();
const checkAndUpdateCargoToml = () => {
try {
const cargoTomlPath = path.join(folderPath, 'Cargo.toml');
if (fs.existsSync(cargoTomlPath)) {
// Check if the file has the macroquad dependency
let content = fs.readFileSync(cargoTomlPath, 'utf8');
if (content.includes("macroquad") && !content.includes("[features]")) {
// Cargo.toml exists and has macroquad dependency but no features section yet
// Append the features section and wasm32-specific dependencies
//const additionalContent = '\n[features]\nscale = []\ndefault = []\n\n[target.\'cfg(target_arch = "wasm32")\'.dependencies]\nwasm-bindgen = "0.2"\n';
const additionalContent = '\n[features]\nscale = []\ndefault = []\n';
fs.appendFileSync(cargoTomlPath, additionalContent);
// console.log('Added features section to Cargo.toml');
// Stop checking
clearInterval(checkInterval);
} else if (Date.now() - startTime > maxWaitTime) {
// Time exceeded, stop checking
clearInterval(checkInterval);
console.warn('Timed out waiting for Cargo.toml to be updated with macroquad');
}
} else if (Date.now() - startTime > maxWaitTime) {
// Time exceeded, stop checking
clearInterval(checkInterval);
console.warn('Timed out waiting for Cargo.toml to be created');
}
} catch (error) {
console.error('Error checking/updating Cargo.toml:', error);
clearInterval(checkInterval);
}
};
// Check every second until the file is ready or timeout occurs
checkInterval = setInterval(checkAndUpdateCargoToml, 1000);
const fmtPath = path.join(folderPath, 'rustfmt.toml');
fs.writeFileSync(fmtPath, `max_width = ${rustfmtMaxWidth}\n`);
// showSuccessMessage(`Project initialized in ${folderPath}!`);
const srcFolder = path.join(folderPath, 'src');
if (!fs.existsSync(srcFolder)) {
fs.mkdirSync(srcFolder, { recursive: true });
}
if (autoCreateAssetsFolder) {
const assetsFolder = path.join(folderPath, 'assets');
if (!fs.existsSync(assetsFolder)) {
fs.mkdirSync(assetsFolder, { recursive: true });
}
}
const lastFolderName = path.basename(folderPath);
const mainRsPath = path.join(folderPath, 'src', 'main.rs');
const authorName = getAuthorName();
const mainRsContent = `/*
By: ${authorName}
Date: ${date}
Program Details: <Program Description Here>
*/
mod modules;
use macroquad::prelude::*;
/// Set up window settings before the app runs
fn window_conf() -> Conf {
Conf {
window_title: "${lastFolderName}".to_string(),
window_width: ${defaultWindowWidth},
window_height: ${defaultWindowHeight},
fullscreen: ${defaultFullscreen},
high_dpi: true,
window_resizable: ${defaultResizable},
sample_count: 4, // MSAA: makes shapes look smoother
..Default::default()
}
}
#[macroquad::main(window_conf)]
async fn main() {
loop {
clear_background(RED);
draw_line(40.0, 40.0, 100.0, 200.0, 15.0, BLUE);
draw_rectangle(screen_width() / 2.0 - 60.0, 100.0, 120.0, 60.0, GREEN);
next_frame().await;
}
}
`;
fs.writeFileSync(mainRsPath, mainRsContent);
const url = getRepositoryUrl() + 'mod.rs';
try {
await downloadToFolder('modules', 'mod.rs', url);
} catch (error) {
vscode.window.showErrorMessage(`Failed to download mod.rs: ${error.message}`);
return;
}
showSuccessMessage(`Creating Rust Project in: ${folderPath}`);
// You can add your logic to run cargo init here
});
// Register the "Create Rust Script Project" command (no macroquad)
let disposableCreateRustScriptProject = vscode.commands.registerCommand('extension.createRustScriptProject', async () => {
const folderPath = await requireFolderPath();
if (!folderPath) {
return;
}
if (hasSpaceInFolderName(folderPath)) {
vscode.window.showErrorMessage('Folder names with spaces are not supported for project creation. Rename the folder to remove spaces and try again.');
return;
}
const date = new Date().toISOString().split('T')[0]; // Format YYYY-MM-DD
const rustfmtMaxWidth = getRustfmtMaxWidth();
const autoCreateAssetsFolder = shouldAutoCreateAssetsFolder();
let terminal = getOrCreateTerminal();
terminal.show();
terminal.sendText("cargo init");
// No macroquad, just a plain Rust script project
const fmtPath = path.join(folderPath, 'rustfmt.toml');
fs.writeFileSync(fmtPath, `max_width = ${rustfmtMaxWidth}\n`);
// showSuccessMessage(`Project initialized in ${folderPath}!`);
const srcFolder = path.join(folderPath, 'src');
if (!fs.existsSync(srcFolder)) {
fs.mkdirSync(srcFolder, { recursive: true });
}
if (autoCreateAssetsFolder) {
const assetsFolder = path.join(folderPath, 'assets');
if (!fs.existsSync(assetsFolder)) {
fs.mkdirSync(assetsFolder, { recursive: true });
}
}
const lastFolderName = path.basename(folderPath);
const mainRsPath = path.join(folderPath, 'src', 'main.rs');
const authorName = getAuthorName();
const mainRsContent = `/*
By: ${authorName}
Date: ${date}
Program Details: <Program Description Here>
*/
fn main() {
println!("Hello ${lastFolderName}!");
}
`;
fs.writeFileSync(mainRsPath, mainRsContent);
showSuccessMessage(`Rust Script Project created in: ${folderPath}`);
});
// Register the "Add Web Support" command
let disposableAddWebSupport = vscode.commands.registerCommand('extension.addWebSupport', async () => {
const folderPath = await requireFolderPath();
if (!folderPath) {
return;
}
fs.writeFileSync(path.join(folderPath, 'index.html'), getBasicWebIndexHtml(path.basename(folderPath)));
// showSuccessMessage(`Adding Web Support in: ${folderPath}`);
});
let disposableWebOut = vscode.commands.registerCommand('extension.disposableWebOut', async () => {
const folderPath = await requireFolderPath();
if (!folderPath) {
return;
}
// Check if index.html exists, if not, automatically add web support
const indexHtmlPath = path.join(folderPath, 'index.html');
if (!fs.existsSync(indexHtmlPath)) {
// showSuccessMessage('Web support not found. Adding web support automatically...');
const lastFolderName = path.basename(folderPath);
fs.writeFileSync(indexHtmlPath, getAdvancedWebIndexHtml(lastFolderName));
// showSuccessMessage(`Web support added automatically to: ${folderPath}`);
}
let terminal = getOrCreateTerminal();
terminal.show();
// Define the command to build the project
const buildCommand = "cargo build --release --target wasm32-unknown-unknown";
// Run the build command and wait for it to complete
terminal.sendText(buildCommand);
try {
await waitForBuildOutput(folderPath, "wasm32-unknown-unknown", ".wasm");
} catch (error) {
vscode.window.showErrorMessage(`Build failed: ${error.message}`);
return;
}
const lastFolderName = path.basename(folderPath);
// Now that the build is complete, move the files
const pkgFolder = path.join(folderPath, "pkg");
const binaryName = path.basename(folderPath) + ".wasm";
const releaseBinary = path.join(folderPath, "target", "wasm32-unknown-unknown", "release", binaryName);
moveBuildOutput(pkgFolder, releaseBinary, binaryName, folderPath);
const wasmBindgenCommand = `wasm-bindgen "${path.join(folderPath, 'target', 'wasm32-unknown-unknown', 'release', lastFolderName + '.wasm')}" --out-dir pkg --target web --no-typescript --weak-refs`;
terminal.sendText(wasmBindgenCommand);
// Wait for wasm-bindgen to complete by checking for the generated files
try {
console.log('Waiting for wasm-bindgen to generate files...');
await waitForWasmBindgenOutput(folderPath, lastFolderName);
} catch (error) {
vscode.window.showErrorMessage(`wasm-bindgen failed: ${error.message}`);
return;
}
// Apply the patch to fix web compatibility issues
console.log('Applying patch to JavaScript file...');
const patchSuccess = patchFile(lastFolderName, folderPath);
if (patchSuccess) {
showSuccessMessage(`Web build completed successfully! Files are ready in the pkg folder.`);
terminal.sendText('echo "📁 Output files available in the pkg folder"');
} else {
vscode.window.showWarningMessage(`Web build completed but patching failed. Check the JavaScript file manually.`);
}
});
let disposableWebOutBasic = vscode.commands.registerCommand('extension.disposableWebOutBasic', async () => {
const folderPath = await requireFolderPath();
if (!folderPath) {
return;
}
const lastFolderName = path.basename(folderPath);
fs.writeFileSync(path.join(folderPath, 'index.html'), getBasicWebIndexHtml(lastFolderName));
let terminal = getOrCreateTerminal();
terminal.show();
// Define the command to build the project
const buildCommand = "cargo build --release --target wasm32-unknown-unknown";
// Run the build command and wait for it to complete
terminal.sendText(buildCommand);
try {
await waitForBuildOutput(folderPath, "wasm32-unknown-unknown", ".wasm");
} catch (error) {
vscode.window.showErrorMessage(`Build failed: ${error.message}`);
return;
}
// Now that the build is complete, move the files
const pkgFolder = path.join(folderPath, "pkg");
const binaryName = path.basename(folderPath) + ".wasm";
const releaseBinary = path.join(folderPath, "target", "wasm32-unknown-unknown", "release", binaryName);
moveBuildOutput(pkgFolder, releaseBinary, binaryName, folderPath);
showSuccessMessage(`Basic web build completed! Files are ready in the pkg folder.`);
terminal.sendText('echo "📁 Basic web output files available in the pkg folder"');
});
let disposableNativeOut = vscode.commands.registerCommand('extension.disposableNativeOut', async () => {
const folderPath = await requireFolderPath();
if (!folderPath) {
return;
}
let terminal = getOrCreateTerminal();
terminal.show();
// Define the command to build the project
const buildCommand = "cargo build --release --target x86_64-unknown-linux-gnu";
// Run the build command and wait for it to complete
terminal.sendText(buildCommand);
await waitForBuildOutput(folderPath, "x86_64-unknown-linux-gnu", "");
//showSuccessMessage('Build Completed!');
// Now that the build is complete, move the files
const pkgFolder = path.join(folderPath, "pkg");
const binaryName = path.basename(folderPath);
const releaseBinary = path.join(folderPath, "target", "x86_64-unknown-linux-gnu", "release", binaryName);
moveBuildOutput(pkgFolder, releaseBinary, binaryName, folderPath);
showSuccessMessage(`Linux Output Built.`);
// showSuccessMessage(`Windows Output Built and Moved.`);
});
let disposableWindowOut = vscode.commands.registerCommand('extension.disposableWindowOut', async () => {
const folderPath = await requireFolderPath();
if (!folderPath) {
return;
}
let terminal = getOrCreateTerminal();
terminal.show();
// Define the command to build the project
const buildCommand = "cargo build --release --target x86_64-pc-windows-gnu";
// Run the build command and wait for it to complete
terminal.sendText(buildCommand);
await waitForBuildOutput(folderPath, "x86_64-pc-windows-gnu", ".exe");
// showSuccessMessage('Build Completed!');
// Now that the build is complete, move the files
const pkgFolder = path.join(folderPath, "pkg");
const binaryName = path.basename(folderPath) + ".exe";
const releaseBinary = path.join(folderPath, "target", "x86_64-pc-windows-gnu", "release", binaryName);
moveBuildOutput(pkgFolder, releaseBinary, binaryName, folderPath);
showSuccessMessage(`Windows Output Built.`);
// showSuccessMessage(`Windows Output Built and Moved.`);
});
let disposableCargoRun = vscode.commands.registerCommand('extension.disposableCargoRun', async () => {
const folderPath = await requireFolderPath();
if (!folderPath) {
return;
}
let terminal = getOrCreateTerminal();
terminal.show();
terminal.sendText("cargo run");
showSuccessMessage(`Native Built.`);
});
let disposableWebRun = vscode.commands.registerCommand('extension.disposableWebRun', async () => {
const folderPath = await requireFolderPath();
if (!folderPath) {
return;
}
let terminal = getOrCreateTerminal();
terminal.show();
terminal.sendText("python3 -m http.server 8080 --bind 127.0.0.1");
showSuccessMessage(`Server Running.`);
});
let disposableReadMeHelp = registerWebFileCommand('extension.disposableReadMeHelp', 'RUST_HELP.md', 'Adding Rust Help File');
let disposableAdvancedHelp = registerWebFileCommand('extension.disposableAdvancedHelp', 'RUST_ADVANCED.md', 'Adding Rust Advanced Help File');
let disposableAddConfiguredWebModule = vscode.commands.registerCommand('extension.addConfiguredWebModule', async (moduleConfig) => {
let selectedConfig = webModules.normalizeCustomWebModuleConfig(moduleConfig);
if (!selectedConfig) {
const configuredModules = webModules.getConfiguredWebModules();
if (configuredModules.length === 0) {
vscode.window.showWarningMessage('No web modules configured. Update dusome-rust.customWebModules in Settings.');
return;
}
const picked = await vscode.window.showQuickPick(
configuredModules.map(item => ({
label: item.menuLabel,
detail: item.fileName,
item
})),
{ placeHolder: 'Choose a configured web module to add' }
);
if (!picked) {
return;
}
selectedConfig = picked.item;
}
const url = webModules.resolveConfiguredModuleUrl(selectedConfig);
try {
const folderPath = await downloadToFolder('modules', selectedConfig.fileName, url);
if (folderPath) {
showSuccessMessage(`${selectedConfig.successMessage} in: ${folderPath}`);
}
} catch (error) {
vscode.window.showErrorMessage(`Failed to download ${selectedConfig.fileName}: ${error.message}`);
}
});
// Register the "Set Repository URL" command
let disposableSetUrl = vscode.commands.registerCommand('extension.setRepositoryUrl', async () => {
const currentUrl = getRepositoryUrl();
const newUrl = await vscode.window.showInputBox({
prompt: 'Enter the base URL for Rust modules repository',
value: currentUrl,
validateInput: (value) => {
if (!value.trim()) {
return 'URL cannot be empty';
}
if (!value.trim().startsWith('http://') && !value.trim().startsWith('https://')) {
return 'URL must start with http:// or https://';
}
if (!value.trim().endsWith('/')) {
return 'URL must end with a forward slash (/)';
}
return null;
}
});
if (newUrl !== undefined) {
// Update the setting
await vscode.workspace.getConfiguration('dusome-rust').update('repositoryUrl', newUrl, vscode.ConfigurationTarget.Global);
showSuccessMessage(`Repository URL updated to: ${newUrl}`);
}
});
let disposableOpenSettings = vscode.commands.registerCommand('extension.openSettings', async () => {
await vscode.commands.executeCommand('workbench.action.openSettings', 'dusome-rust');
});
let disposableManageWebModules = vscode.commands.registerCommand('extension.manageWebModules', async () => {
const panel = vscode.window.createWebviewPanel(
'manageWebModules',
'Extension Settings & Web Modules',
vscode.ViewColumn.One,
{ enableScripts: true }
);
// Load current modules, defaults, and settings
const modules = webModules.getCustomWebModules();
const defaultModules = webModules.getDefaultWebModules();
const settings = {
repositoryUrl: getRepositoryUrl(),
rustfmtMaxWidth: getRustfmtMaxWidth(),
defaultWindowWidth: getDefaultWindowWidth(),
defaultWindowHeight: getDefaultWindowHeight(),
defaultFullscreen: getDefaultFullscreen(),
defaultResizable: getDefaultResizable(),
cargoInitTimeoutMs: getCargoInitTimeoutMs(),
showSuccessNotifications: shouldShowSuccessNotifications(),
terminalName: getTerminalName(),
autoCreateAssetsFolder: shouldAutoCreateAssetsFolder(),
authorName: getAuthorName()
};
panel.webview.html = webModules.getWebModulesWebviewContent(modules, defaultModules, settings);
// Handle messages from the webview
panel.webview.onDidReceiveMessage(async (message) => {
try {
if (message.command === 'save') {
// Update all settings
const config = vscode.workspace.getConfiguration('dusome-rust');
await config.update('repositoryUrl', message.settings.repositoryUrl, vscode.ConfigurationTarget.Global);
await config.update('rustfmtMaxWidth', message.settings.rustfmtMaxWidth, vscode.ConfigurationTarget.Global);
await config.update('defaultWindowWidth', message.settings.defaultWindowWidth, vscode.ConfigurationTarget.Global);
await config.update('defaultWindowHeight', message.settings.defaultWindowHeight, vscode.ConfigurationTarget.Global);
await config.update('defaultFullscreen', message.settings.defaultFullscreen, vscode.ConfigurationTarget.Global);
await config.update('defaultResizable', message.settings.defaultResizable, vscode.ConfigurationTarget.Global);
await config.update('cargoInitTimeoutMs', message.settings.cargoInitTimeoutMs, vscode.ConfigurationTarget.Global);
await config.update('showSuccessNotifications', message.settings.showSuccessNotifications, vscode.ConfigurationTarget.Global);
await config.update('terminalName', message.settings.terminalName, vscode.ConfigurationTarget.Global);
await config.update('autoCreateAssetsFolder', message.settings.autoCreateAssetsFolder, vscode.ConfigurationTarget.Global);
await config.update('authorName', message.settings.authorName, vscode.ConfigurationTarget.Global);
// Update the configuration with new modules list
await config.update(
'customWebModules',
message.modules,
vscode.ConfigurationTarget.Workspace
);
vscode.window.showInformationMessage('Settings and web modules updated successfully!');
panel.dispose();
} else if (message.command === 'cancel') {
panel.dispose();
} else if (message.command === 'reset') {
const config = vscode.workspace.getConfiguration('dusome-rust');
// Clear explicit values so VS Code falls back to defaults contributed in package.json.
await config.update('repositoryUrl', undefined, vscode.ConfigurationTarget.Global);
await config.update('repositoryUrl', undefined, vscode.ConfigurationTarget.Workspace);
await config.update('rustfmtMaxWidth', undefined, vscode.ConfigurationTarget.Global);
await config.update('rustfmtMaxWidth', undefined, vscode.ConfigurationTarget.Workspace);
await config.update('defaultWindowWidth', undefined, vscode.ConfigurationTarget.Global);
await config.update('defaultWindowWidth', undefined, vscode.ConfigurationTarget.Workspace);
await config.update('defaultWindowHeight', undefined, vscode.ConfigurationTarget.Global);
await config.update('defaultWindowHeight', undefined, vscode.ConfigurationTarget.Workspace);
await config.update('defaultFullscreen', undefined, vscode.ConfigurationTarget.Global);
await config.update('defaultFullscreen', undefined, vscode.ConfigurationTarget.Workspace);
await config.update('defaultResizable', undefined, vscode.ConfigurationTarget.Global);
await config.update('defaultResizable', undefined, vscode.ConfigurationTarget.Workspace);
await config.update('cargoInitTimeoutMs', undefined, vscode.ConfigurationTarget.Global);
await config.update('cargoInitTimeoutMs', undefined, vscode.ConfigurationTarget.Workspace);
await config.update('showSuccessNotifications', undefined, vscode.ConfigurationTarget.Global);
await config.update('showSuccessNotifications', undefined, vscode.ConfigurationTarget.Workspace);
await config.update('terminalName', undefined, vscode.ConfigurationTarget.Global);
await config.update('terminalName', undefined, vscode.ConfigurationTarget.Workspace);
await config.update('autoCreateAssetsFolder', undefined, vscode.ConfigurationTarget.Global);
await config.update('autoCreateAssetsFolder', undefined, vscode.ConfigurationTarget.Workspace);
await config.update('authorName', undefined, vscode.ConfigurationTarget.Global);
await config.update('authorName', undefined, vscode.ConfigurationTarget.Workspace);
await config.update('customWebModules', undefined, vscode.ConfigurationTarget.Global);
await config.update('customWebModules', undefined, vscode.ConfigurationTarget.Workspace);
vscode.window.showInformationMessage('Extension settings and web modules reset to defaults!');
panel.dispose();
}
} catch (error) {
vscode.window.showErrorMessage(`Error updating settings or modules: ${error.message}`);
}
});
});
// Add commands to the context subscriptions
context.subscriptions.push(
disposableShowMenu,
disposableCreateRust,
disposableCreateRustScriptProject,
disposableAddWebSupport,
disposableReadMeHelp,
disposableAdvancedHelp,
disposableWebOut,
disposableWebOutBasic,
disposableWebRun,
disposableCargoRun,
disposableNativeOut,
disposableWindowOut,
disposableAddConfiguredWebModule,
disposableSetUrl,
disposableOpenSettings,
disposableManageWebModules
);
}
function getExtensionConfig() {
return vscode.workspace.getConfiguration('dusome-rust');
}
function hasSpaceInFolderName(folderPath) {
return path.basename(folderPath).includes(' ');
}
// Function to get the repository URL from settings
function getRepositoryUrl() {
return getExtensionConfig().get('repositoryUrl');
}
function getRustfmtMaxWidth() {
const value = Number(getExtensionConfig().get('rustfmtMaxWidth', 150));
return Number.isFinite(value) && value >= 60 ? Math.floor(value) : 150;
}
function getDefaultWindowWidth() {
const value = Number(getExtensionConfig().get('defaultWindowWidth', 1024));
return Number.isFinite(value) && value >= 320 ? Math.floor(value) : 1024;
}
function getDefaultWindowHeight() {
const value = Number(getExtensionConfig().get('defaultWindowHeight', 768));
return Number.isFinite(value) && value >= 240 ? Math.floor(value) : 768;
}
function getDefaultFullscreen() {
return Boolean(getExtensionConfig().get('defaultFullscreen', false));
}
function getDefaultResizable() {
return Boolean(getExtensionConfig().get('defaultResizable', true));
}
function getCargoInitTimeoutMs() {
const value = Number(getExtensionConfig().get('cargoInitTimeoutMs', 90000));
return Number.isFinite(value) && value >= 5000 ? Math.floor(value) : 90000;
}
function shouldAutoCreateAssetsFolder() {
return Boolean(getExtensionConfig().get('autoCreateAssetsFolder', true));
}
function getAuthorName() {
return String(getExtensionConfig().get('authorName', '<Your Name Here>')).trim();
}
function shouldShowSuccessNotifications() {
return Boolean(getExtensionConfig().get('showSuccessNotifications', true));
}
function showSuccessMessage(message) {
if (shouldShowSuccessNotifications()) {
vscode.window.showInformationMessage(message);
}
}
function getTerminalName() {
const terminalName = getExtensionConfig().get('terminalName', 'Cargo Terminal');
if (typeof terminalName === 'string' && terminalName.trim().length > 0) {
return terminalName.trim();
}
return 'Cargo Terminal';
}
// Function to get the folder path (from workspace or active file)
async function getFolderPath() {
// Check if there's an open folder/workspace
const workspaceFolder = vscode.workspace.workspaceFolders ? vscode.workspace.workspaceFolders[0] : undefined;
if (workspaceFolder) {
return workspaceFolder.uri.fsPath; // Return the folder path of the open workspace
}
// If no workspace, check if there's an open file and get its directory path
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor && activeEditor.document.uri.scheme === 'file') {
return vscode.workspace.getWorkspaceFolder(activeEditor.document.uri)?.uri.fsPath;
}
return null; // Return null if no folder or file is open
}
async function requireFolderPath() {
const folderPath = await getFolderPath();
if (!folderPath) {
vscode.window.showErrorMessage('No folder is open. Please open a folder first.');
return null;
}
return folderPath;
}
function getWebIndexBaseStyle() {
return `
/* === MODE 1: Responsive fullscreen canvas (default) === */
html,body,canvas {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: black;
}
/* === MODE 2: Fixed-size centered canvas (uncomment to use) === */
/*
body {
margin: 0;
background: black;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
canvas {
width: 1024px;
height: 768px;
background: black;
}
html {
overflow: hidden;
}
*/`;
}
function getBasicWebIndexHtml(projectName) {
return `
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>${projectName}</title>
<style>${getWebIndexBaseStyle()}
</style>
</head>
<body>
<canvas id="glcanvas" tabindex='1'></canvas>
<script src="https://not-fl3.github.io/miniquad-samples/mq_js_bundle.js"></script>
<script>load("pkg/${projectName}.wasm");</script>
</body>
</html>
`;
}
function getAdvancedWebIndexHtml(projectName) {
return `
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>${projectName}</title>
<style>${getWebIndexBaseStyle()}
</style>
</head>
<body>
<canvas id="glcanvas" tabindex='1' hidden></canvas>
<script src="https://not-fl3.github.io/miniquad-samples/mq_js_bundle.js"></script>
<script type="module">
import init, { set_wasm } from "./pkg/${projectName}.js";
async function impl_run() {
let wbg = await init();
miniquad_add_plugin({
register_plugin: (a) => (a.wbg = wbg),
on_init: () => set_wasm(wasm_exports),
version: "0.0.1",
name: "wbg",
});
load("./pkg/${projectName}_bg.wasm");
}
// Auto-run when page loads
window.addEventListener('load', function() {
document.getElementById("glcanvas").removeAttribute("hidden");
document.getElementById("glcanvas").focus();
impl_run();
});
</script>
</body>
</html>
`;
}
function registerWebFileCommand(commandId, fileName, successLabel) {
return vscode.commands.registerCommand(commandId, async () => {
const folderPath = await requireFolderPath();
if (!folderPath) {
return;
}
const url = getRepositoryUrl() + fileName;
const filePath = path.join(folderPath, fileName);
try {
await downloadFile(url, filePath);
showSuccessMessage(`${successLabel} in: ${folderPath}`);
} catch (error) {
vscode.window.showErrorMessage(`Failed to add ${fileName}: ${error.message}`);
}
});
}
function downloadFile(url, targetPath) {
const client = url.startsWith('https://') ? https : http;
return new Promise((resolve, reject) => {
client.get(url, (response) => {
if (response.statusCode !== 200) {
response.resume();
reject(new Error(`Failed to download ${path.basename(targetPath)}: ${response.statusCode}`));
return;
}
const fileStream = fs.createWriteStream(targetPath);
response.pipe(fileStream);
fileStream.on('finish', () => {
fileStream.close();
resolve(targetPath);
});
fileStream.on('error', (err) => {
reject(new Error(`Write failed for ${path.basename(targetPath)}: ${err.message}`));
});
}).on('error', (err) => {
reject(new Error(`Download failed: ${err.message}`));
});
});
}
async function downloadToFolder(folderName, fileName, url) {
const folderPath = await requireFolderPath();
if (!folderPath) {
return null;
}
// Ensure the folder is inside `src`
const srcPath = path.join(folderPath, 'src', folderName);
if (!fs.existsSync(srcPath)) {
fs.mkdirSync(srcPath, { recursive: true });
}
const filePath = path.join(srcPath, fileName);
await downloadFile(url, filePath);
// Return the folder path so it can be used in the calling function
return folderPath;
}
function moveBuildOutput(pkgFolder, releaseBinary, binaryName, workspaceFolder) {
// Delete the pkg folder if it exists
if (fs.existsSync(pkgFolder)) {
fs.rmSync(pkgFolder, { recursive: true, force: true });
}
// Create the pkg folder if it doesn’t exist
if (!fs.existsSync(pkgFolder)) {
fs.mkdirSync(pkgFolder, { recursive: true });
}
// Move the binary
const destBinary = path.join(pkgFolder, binaryName);
if (fs.existsSync(releaseBinary)) {
fs.copyFileSync(releaseBinary, destBinary);
}
// Copy the assets folder
const assetsFolder = path.join(workspaceFolder, "assets");
const destAssets = path.join(pkgFolder, "assets");
if (fs.existsSync(assetsFolder)) {
fs.rmSync(destAssets, { recursive: true, force: true });
fs.cpSync(assetsFolder, destAssets, { recursive: true });
}
}
function waitForBuildOutput(folderPath, target, fileExtension) {
return new Promise((resolve, reject) => {
const releaseBinary = path.join(folderPath, "target", target, "release", path.basename(folderPath) + fileExtension);
const checkInterval = setInterval(() => {
if (fs.existsSync(releaseBinary)) {
clearInterval(checkInterval); // Stop checking
resolve(); // File found, proceed
}
}, 1000); // Check every second
// Timeout after 5 minutes (adjust as necessary)
setTimeout(() => {
clearInterval(checkInterval); // Stop checking after timeout
reject(new Error('Build process timed out waiting for the output file.'));
}, 300000); // 5 minutes
});
}
// Function to wait for wasm-bindgen output files in pkg directory
function waitForWasmBindgenOutput(folderPath, projectName) {
return new Promise((resolve, reject) => {
const pkgFolder = path.join(folderPath, "pkg");
const jsFilePath = path.join(pkgFolder, `${projectName}.js`);
const wasmBgFilePath = path.join(pkgFolder, `${projectName}_bg.wasm`);
let attempts = 0;
const maxAttempts = 30; // 30 seconds max wait time
console.log(`Waiting for wasm-bindgen files: ${jsFilePath} and ${wasmBgFilePath}`);
// Send status to terminal
let terminal = getOrCreateTerminal();
// terminal.sendText('echo "⏳ Waiting for wasm-bindgen to generate files..."');
const checkInterval = setInterval(() => {
attempts++;
// Check if both files exist and have content
const jsExists = fs.existsSync(jsFilePath);
const wasmBgExists = fs.existsSync(wasmBgFilePath);
if (jsExists && wasmBgExists) {
try {
const jsStats = fs.statSync(jsFilePath);
const wasmBgStats = fs.statSync(wasmBgFilePath);
// Both files exist and have reasonable content
if (jsStats.size > 1000 && wasmBgStats.size > 1000) {
clearInterval(checkInterval);
console.log(`wasm-bindgen files ready: JS(${jsStats.size}B), WASM(${wasmBgStats.size}B)`);
terminal.sendText('echo "✅ wasm-bindgen files ready"');
// Small delay to ensure files are fully written
setTimeout(() => {
resolve();
}, 200);
return;
}
} catch (error) {
// Files might be in process of being written, continue waiting
console.log(`File access error (continuing): ${error.message}`);
}
}
// Progress indicator every 5 seconds
if (attempts % 5 === 0 && attempts > 0) {
// Progress tracking - no terminal output
}
if (attempts >= maxAttempts) {
clearInterval(checkInterval);
const errorMsg = `Timeout waiting for wasm-bindgen files after ${maxAttempts}s`;
console.error(errorMsg);
vscode.window.showErrorMessage(`wasm-bindgen timeout: Files not generated after ${maxAttempts} seconds`);
reject(new Error(errorMsg));
}
}, 1000); // Check every second
});
}
// Helper function to get or create a terminal
function getOrCreateTerminal(name) {
const resolvedName = name || getTerminalName();
// If we already have a terminal, check if it still exists
if (cargoTerminal) {
const terminals = vscode.window.terminals;
const exists = terminals.some(t => t === cargoTerminal);
if (exists) {
return cargoTerminal;
}
}
// Create a new terminal if needed
cargoTerminal = vscode.window.createTerminal(resolvedName);
return cargoTerminal;