Repository navigation
Expand file tree
/
Copy pathBuildOutputWindow.xaml.cs
More file actions
1504 lines (1339 loc) · 70.2 KB
/
Copy pathBuildOutputWindow.xaml.cs
File metadata and controls
1504 lines (1339 loc) · 70.2 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
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using Sm64DecompLevelViewer.Services;
namespace Sm64DecompLevelViewer
{
public partial class BuildOutputWindow : Window
{
private readonly string _projectRoot;
private readonly AppSettings? _settings;
private readonly string? _gitUrlToClone;
private readonly bool _isRevertMode = false;
private readonly List<string>? _bakFilesToRestore;
private readonly bool _runGitRevert = false;
private bool _isBuildSuccessful = false;
private bool _hasRetriedInstall = false;
public bool IsSuccessful => _isBuildSuccessful;
// Constructor for compilation mode
public BuildOutputWindow(string projectRoot, AppSettings settings)
{
InitializeComponent();
_projectRoot = projectRoot;
_settings = settings;
_gitUrlToClone = null;
Loaded += async (s, e) => await StartBuildAsync();
}
// Constructor for clean & clone mode
public BuildOutputWindow(string projectRoot, string gitUrlToClone)
{
InitializeComponent();
_projectRoot = projectRoot;
_settings = null;
_gitUrlToClone = gitUrlToClone;
Loaded += async (s, e) => await StartCleanAndCloneAsync();
}
// Constructor for revert mode
public BuildOutputWindow(string projectRoot, List<string>? bakFilesToRestore, bool runGitRevert)
{
InitializeComponent();
_projectRoot = projectRoot;
_settings = null;
_gitUrlToClone = null;
_isRevertMode = true;
_bakFilesToRestore = bakFilesToRestore;
_runGitRevert = runGitRevert;
Loaded += async (s, e) => await StartRevertSourceAsync();
}
// Constructor for revert mode (legacy fallback)
public BuildOutputWindow(string projectRoot, bool isRevertMode)
: this(projectRoot, null, true)
{
}
private void CloseButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
Close();
}
private async Task StartBuildAsync()
{
if (_settings == null)
{
LogTextBox.AppendText("> ERROR: No settings provided for building.\n");
return;
}
bool isPcPort = _settings.BuildTargetPlatform == "PC";
bool isMsys2 = isPcPort && _settings.BuildEnvironment == "MSYS2";
HeaderTitleText.Text = isMsys2 ? "BUILDING PROJECT (MSYS2)..." : "BUILDING PROJECT (WSL)...";
StatusText.Text = "Building...";
LogTextBox.AppendText($"> Building project in: {_projectRoot}\n");
// Scan repository to verify target platform correctness
string pcMainFilePath = Path.Combine(_projectRoot, "src", "pc", "pc_main.c");
bool hasPcSource = File.Exists(pcMainFilePath);
if (isPcPort && !hasPcSource)
{
LogTextBox.AppendText("> ERROR: Target platform is set to PC, but this repository does not support PC Port compilation (missing 'src/pc/pc_main.c').\n");
LogTextBox.AppendText("> Please change your Target Platform to N64 ROM, or select a repository that supports PC Port (like sm64ex or sm64-port).\n");
StatusText.Text = "Build Failed";
return;
}
if (!isPcPort && hasPcSource)
{
LogTextBox.AppendText("> ERROR: Target platform is set to N64, but this repository is a PC Port repository and does not support N64 compilation.\n");
LogTextBox.AppendText("> Please change your Target Platform to PC, or select a repository that supports N64 ROM builds (like vanilla sm64 decomp or HackerSM64).\n");
StatusText.Text = "Build Failed";
return;
}
var buildLogs = new System.Text.StringBuilder();
try
{
int jobs = _settings.BuildJobs <= 0 ? 8 : _settings.BuildJobs;
string version = _settings.BuildVersion;
string compiler = _settings.BuildCompiler;
string grucode = _settings.BuildGrucode;
int compareVal = _settings.BuildCompare ? 1 : 0;
int nonMatchingVal = _settings.BuildNonMatching ? 1 : 0;
// Verify compiler availability
bool compilerExists = true;
if (compiler == "clang" || compiler == "gcc")
{
string checkCmd = $"command -v {compiler}";
ProcessStartInfo checkInfo;
if (isMsys2)
{
string msysPath = _settings.MsysPath;
string bashPath = Path.Combine(msysPath, "usr", "bin", "bash.exe");
checkInfo = new ProcessStartInfo
{
FileName = bashPath,
Arguments = $"-c \"{checkCmd}\"",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
}
else // WSL
{
checkInfo = new ProcessStartInfo
{
FileName = "wsl.exe",
Arguments = $"bash -c \"{checkCmd}\"",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
}
try
{
using (var proc = Process.Start(checkInfo))
{
proc.WaitForExit();
if (proc.ExitCode != 0)
{
compilerExists = false;
}
}
}
catch
{
compilerExists = false;
}
}
if (!compilerExists)
{
bool installed = await TryAutoInstallCompilerAsync(compiler, isMsys2);
if (!installed)
{
StatusText.Text = "Build Failed";
return;
}
}
string uncompressedEnv = "";
if (isPcPort)
{
await PatchPcPortFilesAsync();
}
// Check if build platform or environment changed from the last build. If so, clean build subdirectory
bool envOrPlatformChanged = _settings.BuildEnvironment != _settings.LastBuildEnvironment ||
_settings.BuildTargetPlatform != _settings.LastBuildPlatform;
if (envOrPlatformChanged)
{
string buildSubdir = isPcPort ? $"{version}_pc" : version;
string buildSubdirPath = Path.Combine(_projectRoot, "build", buildSubdir);
if (Directory.Exists(buildSubdirPath))
{
LogTextBox.AppendText($"> Detected change in build platform or environment. Wiping build folder 'build/{buildSubdir}' to prevent Linux/Windows linking conflicts...\n");
try
{
await Task.Run(() => Directory.Delete(buildSubdirPath, true));
}
catch (Exception ex)
{
LogTextBox.AppendText($"> Warning: Failed to delete build subdirectory: {ex.Message}\n");
}
}
}
// Update settings tracking
_settings.LastBuildEnvironment = _settings.BuildEnvironment;
_settings.LastBuildPlatform = _settings.BuildTargetPlatform;
var settingsService = new Sm64DecompLevelViewer.Services.SettingsService();
settingsService.SaveSettings(_settings);
// Clean tools first only if build environment/platform changed (avoids rebuilding large tools like armips on every compile)
string cleanToolsPrefix = envOrPlatformChanged ? "make -C tools clean && " : "";
string makeArgs = isPcPort
? $"{cleanToolsPrefix}{uncompressedEnv}make -j{jobs} VERSION={version} TARGET_N64=0"
: $"{cleanToolsPrefix}{uncompressedEnv}make -j{jobs} VERSION={version} TARGET_N64=1 COMPILER={compiler} GRUCODE={grucode} COMPARE={compareVal} NON_MATCHING={nonMatchingVal}";
ProcessStartInfo startInfo;
if (isMsys2)
{
string msysPath = _settings.MsysPath;
string bashPath = Path.Combine(msysPath, "usr", "bin", "bash.exe");
if (!File.Exists(bashPath))
{
LogTextBox.AppendText($"> ERROR: MSYS2 bash.exe not found at: {bashPath}\n");
LogTextBox.AppendText("> Please check your MSYS2 Path configuration in Build Options.\n");
MainStatusBar.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(220, 53, 69)); // Red
StatusText.Text = "Build Error: MSYS2 Missing";
_isBuildSuccessful = false;
return;
}
string projectRootInMsys = _projectRoot.Replace("\\", "/");
if (projectRootInMsys.Length >= 2 && projectRootInMsys[1] == ':')
{
projectRootInMsys = "/" + char.ToLower(projectRootInMsys[0]) + projectRootInMsys.Substring(2);
}
string makeCmd = $"cd '{projectRootInMsys}' && {makeArgs}";
string bashArgs = $"-l -c \"{makeCmd}\"";
LogTextBox.AppendText($"> Running make command inside MSYS2 MinGW64: {makeCmd}\n\n");
startInfo = new ProcessStartInfo
{
FileName = bashPath,
Arguments = bashArgs,
WorkingDirectory = _projectRoot,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
startInfo.Environment["MSYSTEM"] = "MINGW64";
}
else
{
LogTextBox.AppendText($"> Running make command inside WSL: {makeArgs}\n\n");
startInfo = new ProcessStartInfo
{
FileName = "wsl",
Arguments = makeArgs,
WorkingDirectory = _projectRoot,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
}
using (var process = new Process { StartInfo = startInfo })
{
process.OutputDataReceived += (s, e) => {
if (e.Data != null) {
lock (buildLogs) { buildLogs.AppendLine(e.Data); }
}
AppendLog(e.Data);
};
process.ErrorDataReceived += (s, e) => {
if (e.Data != null) {
lock (buildLogs) { buildLogs.AppendLine(e.Data); }
}
AppendLog(e.Data);
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
await Task.Run(() => process.WaitForExit());
_isBuildSuccessful = process.ExitCode == 0;
if (_isBuildSuccessful)
{
if (RomExists())
{
MainStatusBar.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(40, 167, 69)); // Green
StatusText.Text = "Build Succeeded!";
LogTextBox.AppendText("\n> BUILD SUCCESSFUL!\n");
bool shouldAutoRun = _settings.AutoRunEmulator;
if (shouldAutoRun)
{
LogTextBox.AppendText($"> Launching game...\n");
LaunchEmulator();
}
else
{
LogTextBox.AppendText("> Auto-run skipped (disabled by user).\n");
}
}
else
{
_isBuildSuccessful = false;
MainStatusBar.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(220, 53, 69)); // Red
if (isPcPort)
{
StatusText.Text = "Build Error: Executable Not Found";
LogTextBox.AppendText($"\n> ERROR: make reported success, but no PC Port executable was found.\n");
}
else
{
StatusText.Text = "Build Error: ROM Not Found";
string expectedPath = Path.Combine("build", version, $"sm64.{version}.z64");
LogTextBox.AppendText($"\n> ERROR: make reported success, but no ROM file was found at {expectedPath}.\n");
}
}
}
else
{
if (isPcPort && !_hasRetriedInstall)
{
if (!isMsys2) // WSL automatic dependency retry
{
string logText = buildLogs.ToString();
if (logText.Contains("SDL2/SDL.h") || logText.Contains("pulseaudio.h") || logText.Contains("libusb.h"))
{
_hasRetriedInstall = true;
LogTextBox.AppendText("\n> DETECTED MISSING DEVELOPMENT LIBRARIES (SDL2/PulseAudio/libusb).\n");
LogTextBox.AppendText("> Attempting to install required packages automatically in WSL...\n");
StatusText.Text = "Installing WSL dependencies...";
bool installSuccess = await InstallWslDependenciesAsync();
if (installSuccess)
{
LogTextBox.AppendText("\n> WSL dependencies installed successfully! Retrying build...\n\n");
process.Dispose();
await StartBuildAsync();
return;
}
else
{
MainStatusBar.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(220, 53, 69)); // Red
StatusText.Text = "Build Failed";
LogTextBox.AppendText($"\n> BUILD FAILED with exit code {process.ExitCode}\n");
LogTextBox.AppendText("> ERROR: Failed to install packages automatically. Please run manually inside WSL:\n");
LogTextBox.AppendText("> sudo apt-get update && sudo apt-get install -y libsdl2-dev libpulse-dev libusb-1.0-0-dev\n\n");
}
}
else
{
MainStatusBar.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(220, 53, 69)); // Red
StatusText.Text = "Build Failed";
LogTextBox.AppendText($"\n> BUILD FAILED with exit code {process.ExitCode}\n");
}
}
else // MSYS2 advice
{
MainStatusBar.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(220, 53, 69)); // Red
StatusText.Text = "Build Failed";
LogTextBox.AppendText($"\n> BUILD FAILED with exit code {process.ExitCode}\n");
LogTextBox.AppendText("> Note: If you have missing dependencies, please open 'MSYS2 MinGW 64-bit' and run:\n");
LogTextBox.AppendText("> pacman -S git make python3 mingw-w64-x86_64-gcc\n\n");
}
}
else
{
MainStatusBar.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(220, 53, 69)); // Red
StatusText.Text = "Build Failed";
LogTextBox.AppendText($"\n> BUILD FAILED with exit code {process.ExitCode}\n");
}
}
}
}
catch (Exception ex)
{
MainStatusBar.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(220, 53, 69)); // Red
LogTextBox.AppendText($"\n> FATAL ERROR: {ex.Message}\n");
if (ex is System.ComponentModel.Win32Exception || ex.Message.Contains("wsl", StringComparison.OrdinalIgnoreCase))
{
LogTextBox.AppendText("\n> WSL (Windows Subsystem for Linux) might not be installed or configured on your system.\n");
LogTextBox.AppendText("> Please install WSL (e.g. Ubuntu 20.04 or newer from the Microsoft Store) to build the ROM.\n");
LogTextBox.AppendText("> To install WSL, run: 'wsl --install' in an administrator Command Prompt/PowerShell.\n");
}
StatusText.Text = "Execution Error";
}
finally
{
CloseButton.IsEnabled = true;
}
}
private async Task StartCleanAndCloneAsync()
{
if (string.IsNullOrEmpty(_gitUrlToClone))
{
LogTextBox.AppendText("> ERROR: No Git repository URL provided.\n");
return;
}
HeaderTitleText.Text = "CLEAN & RE-CLONE PROJECT (WSL)...";
StatusText.Text = "Cleaning project...";
LogTextBox.AppendText($"> Cleaning project directory: {_projectRoot}\n");
LogTextBox.AppendText($"> Git repository URL: {_gitUrlToClone}\n");
string tempBackupPath = Path.Combine(Path.GetTempPath(), "sm64_baserom_backup_" + Guid.NewGuid().ToString("N"));
bool hasBackup = false;
try
{
// Step 1: Find and backup baserom files
Directory.CreateDirectory(tempBackupPath);
LogTextBox.AppendText("> Backing up baserom files...\n");
string[] baseromFiles = Directory.GetFiles(_projectRoot, "baserom.*");
foreach (string file in baseromFiles)
{
string fileName = Path.GetFileName(file);
string destFile = Path.Combine(tempBackupPath, fileName);
File.Copy(file, destFile, true);
LogTextBox.AppendText($"> Backed up: {fileName}\n");
hasBackup = true;
}
if (!hasBackup)
{
LogTextBox.AppendText("> WARNING: No baserom files (baserom.*) found to back up.\n");
}
// Step 2: Delete everything in the project root
LogTextBox.AppendText("> Deleting existing files and directories...\n");
await Task.Run(() =>
{
foreach (string file in Directory.GetFiles(_projectRoot))
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(new Action(() => LogTextBox.AppendText($"> Warning deleting file {Path.GetFileName(file)}: {ex.Message}\n")));
}
}
foreach (string dir in Directory.GetDirectories(_projectRoot))
{
try
{
Directory.Delete(dir, true);
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(new Action(() => LogTextBox.AppendText($"> Warning deleting directory {Path.GetFileName(dir)}: {ex.Message}\n")));
}
}
});
// Step 3: Run git clone via WSL
LogTextBox.AppendText($"> Running 'git clone {_gitUrlToClone} .' inside WSL...\n");
StatusText.Text = "Cloning repository...";
var startInfo = new ProcessStartInfo
{
FileName = "wsl",
Arguments = $"git clone \"{_gitUrlToClone}\" .",
WorkingDirectory = _projectRoot,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
bool cloneSuccess = false;
using (var process = new Process { StartInfo = startInfo })
{
process.OutputDataReceived += (s, e) => AppendLog(e.Data);
process.ErrorDataReceived += (s, e) => AppendLog(e.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
await Task.Run(() => process.WaitForExit());
cloneSuccess = process.ExitCode == 0;
if (cloneSuccess)
{
LogTextBox.AppendText($"> Git clone completed successfully.\n");
}
else
{
LogTextBox.AppendText($"> ERROR: Git clone failed with exit code {process.ExitCode}\n");
}
}
if (!cloneSuccess)
{
throw new Exception("Git clone failed.");
}
// Step 4: Restore baserom files
if (hasBackup)
{
LogTextBox.AppendText("> Restoring baserom files...\n");
string[] backedFiles = Directory.GetFiles(tempBackupPath);
foreach (string file in backedFiles)
{
string fileName = Path.GetFileName(file);
string destFile = Path.Combine(_projectRoot, fileName);
File.Copy(file, destFile, true);
LogTextBox.AppendText($"> Restored: {fileName}\n");
}
}
MainStatusBar.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(40, 167, 69)); // Green
StatusText.Text = "Clean & Re-clone Succeeded!";
LogTextBox.AppendText("\n> FRESH START COMPLETE SUCCESSFULLY!\n");
_isBuildSuccessful = true;
}
catch (Exception ex)
{
MainStatusBar.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(220, 53, 69)); // Red
StatusText.Text = "Failed to Clean & Re-clone";
LogTextBox.AppendText($"\n> FATAL ERROR: {ex.Message}\n");
if (ex is System.ComponentModel.Win32Exception || ex.Message.Contains("wsl", StringComparison.OrdinalIgnoreCase))
{
LogTextBox.AppendText("\n> WSL (Windows Subsystem for Linux) might not be installed or configured on your system.\n");
LogTextBox.AppendText("> Please install WSL (e.g. Ubuntu 20.04 or newer from the Microsoft Store) to run build tools.\n");
LogTextBox.AppendText("> To install WSL, run: 'wsl --install' in an administrator Command Prompt/PowerShell.\n");
}
// CRITICAL safety fallback: try to restore baseroms even if clone failed
if (hasBackup)
{
LogTextBox.AppendText("> Attempting to restore original baserom files after failure...\n");
try
{
string[] backedFiles = Directory.GetFiles(tempBackupPath);
foreach (string file in backedFiles)
{
string fileName = Path.GetFileName(file);
string destFile = Path.Combine(_projectRoot, fileName);
File.Copy(file, destFile, true);
LogTextBox.AppendText($"> Restored: {fileName}\n");
}
}
catch (Exception restoreEx)
{
LogTextBox.AppendText($"> ERROR restoring baserom backup: {restoreEx.Message}\n");
}
}
}
finally
{
CloseButton.IsEnabled = true;
// Clean up backup directory
try
{
if (Directory.Exists(tempBackupPath))
{
Directory.Delete(tempBackupPath, true);
}
}
catch { }
}
}
private async Task StartRevertSourceAsync()
{
HeaderTitleText.Text = "REVERTING SOURCE CODE...";
StatusText.Text = "Reverting code...";
LogTextBox.AppendText($"> Reverting local changes in project: {_projectRoot}\n");
try
{
// Restore backup files
try
{
IEnumerable<string> bakFilesToProcess;
if (_bakFilesToRestore != null)
{
bakFilesToProcess = _bakFilesToRestore;
}
else
{
bakFilesToProcess = Directory.Exists(_projectRoot)
? Directory.GetFiles(_projectRoot, "*.bak", SearchOption.AllDirectories)
: Array.Empty<string>();
}
foreach (var bakFile in bakFilesToProcess)
{
if (File.Exists(bakFile))
{
string originalPath = bakFile.Substring(0, bakFile.Length - 4);
File.Copy(bakFile, originalPath, true);
File.SetLastWriteTime(originalPath, DateTime.Now);
File.Delete(bakFile);
LogTextBox.AppendText($"> Restored from backup: {Path.GetFileName(originalPath)}\n");
}
}
}
catch (Exception ex)
{
LogTextBox.AppendText($"> Warning restoring backups: {ex.Message}\n");
}
bool checkoutSuccess = true;
if (_runGitRevert)
{
// Run wsl git checkout -f
LogTextBox.AppendText("> Running 'git checkout -f' inside WSL...\n");
var startInfo = new ProcessStartInfo
{
FileName = "wsl",
Arguments = "sh -c \"git checkout -f && git clean -fd && python3 extract_assets.py us\"",
WorkingDirectory = _projectRoot,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
checkoutSuccess = false;
using (var process = new Process { StartInfo = startInfo })
{
process.OutputDataReceived += (s, e) => AppendLog(e.Data);
process.ErrorDataReceived += (s, e) => AppendLog(e.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
await Task.Run(() => process.WaitForExit());
checkoutSuccess = process.ExitCode == 0;
}
}
if (checkoutSuccess)
{
MainStatusBar.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(40, 167, 69)); // Green
StatusText.Text = "Revert Succeeded!";
LogTextBox.AppendText("\n> SOURCE REVERT COMPLETE SUCCESSFULLY!\n");
_isBuildSuccessful = true;
}
else
{
throw new Exception("Git checkout failed.");
}
}
catch (Exception ex)
{
MainStatusBar.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(220, 53, 69)); // Red
StatusText.Text = "Failed to Revert Changes";
LogTextBox.AppendText($"\n> FATAL ERROR: {ex.Message}\n");
if (ex is System.ComponentModel.Win32Exception || ex.Message.Contains("wsl", StringComparison.OrdinalIgnoreCase))
{
LogTextBox.AppendText("\n> WSL (Windows Subsystem for Linux) might not be installed or configured on your system.\n");
LogTextBox.AppendText("> Please install WSL (e.g. Ubuntu 20.04 or newer from the Microsoft Store) to run build tools.\n");
LogTextBox.AppendText("> To install WSL, run: 'wsl --install' in an administrator Command Prompt/PowerShell.\n");
}
}
finally
{
CloseButton.IsEnabled = true;
}
}
private async Task<bool> ExtendRomAsync(string version)
{
try
{
// Ensure setup_extend.sh script is present and compile sm64extend if it doesn't exist
string setupScriptPath = Path.Combine(_projectRoot, "tools", "sm64tools", "setup_extend.sh");
// Always write setup_extend.sh to keep it up-to-date and robust
string scriptContent = @"#!/bin/sh
set -e
CDIR=$(dirname ""$0"")
cd ""$CDIR""
# Patch libmio0.c if not already patched
python3 -c ""
import os
p = 'libmio0.c'
if os.path.exists(p):
data = open(p).read()
if 'gMio0Uncompressed' not in data:
print('> Patching libmio0.c...')
old_decl = 'unsigned int bytes_proc = 0;'
new_decl = old_decl + '\n int gMio0Uncompressed = 0;\n char *env_uncomp = getenv(\""MIO0_UNCOMPRESSED\"");\n if (env_uncomp != NULL && strcmp(env_uncomp, \""1\"") == 0) {\n gMio0Uncompressed = 1;\n }'
data = data.replace(old_decl, new_decl)
old_loop = 'while (bytes_proc < length) {'
new_loop = old_loop + '\n if (gMio0Uncompressed) {\n uncomp_buf[uncomp_idx] = in[bytes_proc];\n uncomp_idx++;\n PUT_BIT(bit_buf, bit_idx, 1);\n bytes_proc++;\n bit_idx++;\n continue;\n }'
data = data.replace(old_loop, new_loop)
open(p, 'w').write(data)
print('> Rebuilding mio0 tool...')
import subprocess
subprocess.run(['make', 'clean'])
subprocess.run(['make'])
""
# Fetch and patch libsm64.c to support version detection of custom/non-matching ROMs
if [ ! -f ./libsm64.c ]; then
echo ""sm64extend not found. Fetching source files...""
curl -L -o sm64extend.c https://raw.githubusercontent.com/queueRAM/sm64tools/master/sm64extend.c
curl -L -o libsm64.h https://raw.githubusercontent.com/queueRAM/sm64tools/master/libsm64.h
curl -L -o libsm64.c https://raw.githubusercontent.com/queueRAM/sm64tools/master/libsm64.c
echo ""Patching libsm64.c...""
sed -i 's/#include ""utils.h""/#include ""utils.h""\n#define INFO_HEX(a,b)/g' libsm64.c
fi
# Apply the version detection fallback patch using a robust heredoc
cat << 'EOF' > patch_libsm64.py
p = 'libsm64.c'
data = open(p).read()
if 'buf[0x3B]' not in data:
print('> Patching libsm64.c for custom ROM version detection...')
old_func = 'rom_version sm64_rom_version(unsigned char *buf)\n{'
new_func = old_func + '''
if (buf[0x3B] == 'N' && buf[0x3C] == 'S' && buf[0x3D] == 'M') {
switch (buf[0x3E]) {
case 'E': return VERSION_SM64_U;
case 'J': return VERSION_SM64_J;
case 'P': return VERSION_SM64_E;
case 'S': return VERSION_SM64_SHINDOU;
case 'C': return VERSION_SM64_IQUE;
}
}'''
data = data.replace(old_func, new_func)
# Patch the MIO0 header logic to always write fake headers for unmatched ASM references (command == 0)
if 'ptr_table[i].command != 0x18' not in data:
print('> Patching libsm64.c to enforce fake MIO0 headers on unmatched pointers...')
data = data.replace('if (ptr_table[i].command == 0x1A || ptr_table[i].command == 0xFF) {', 'if (ptr_table[i].command != 0x18) {')
open(p, 'w').write(data)
EOF
python3 patch_libsm64.py
rm patch_libsm64.py
echo ""Compiling sm64extend...""
gcc -I . sm64extend.c libsm64.c libmio0.c utils.c n64cksum.c -o sm64extend -lm
echo ""Compilation complete!""
";
string setupScriptDir = Path.GetDirectoryName(setupScriptPath);
if (!Directory.Exists(setupScriptDir))
{
Directory.CreateDirectory(setupScriptDir);
}
File.WriteAllText(setupScriptPath, scriptContent.Replace("\r\n", "\n"));
// Run setup script
var setupStartInfo = new ProcessStartInfo
{
FileName = "wsl",
Arguments = "sh -c \"chmod +x ./tools/sm64tools/setup_extend.sh && ./tools/sm64tools/setup_extend.sh\"",
WorkingDirectory = _projectRoot,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (var process = new Process { StartInfo = setupStartInfo })
{
process.OutputDataReceived += (s, e) => AppendLog(e.Data);
process.ErrorDataReceived += (s, e) => AppendLog(e.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
await Task.Run(() => process.WaitForExit());
}
string? absoluteInputPath = FindBuiltRomPath();
if (absoluteInputPath == null)
{
LogTextBox.AppendText("> ERROR: Cannot extend ROM because build output ROM was not found.\n");
return false;
}
string inputDir = Path.GetDirectoryName(absoluteInputPath);
string inputRomName = Path.GetFileName(absoluteInputPath);
string extRomName = Path.GetFileNameWithoutExtension(inputRomName) + ".ext" + Path.GetExtension(inputRomName);
string absoluteOutputPath = Path.Combine(inputDir, extRomName);
string inputRomPath = Path.GetRelativePath(_projectRoot, absoluteInputPath).Replace('\\', '/');
string outputRomPath = Path.GetRelativePath(_projectRoot, absoluteOutputPath).Replace('\\', '/');
// Run sm64extend tool compiled in WSL
// Command: ./tools/sm64tools/sm64extend -s 24 <input> <output>
string extendArgs = $"./tools/sm64tools/sm64extend -s 24 {inputRomPath} {outputRomPath}";
LogTextBox.AppendText($"> Running sm64extend command: wsl {extendArgs}\n");
var startInfo = new ProcessStartInfo
{
FileName = "wsl",
Arguments = extendArgs,
WorkingDirectory = _projectRoot,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (var process = new Process { StartInfo = startInfo })
{
process.OutputDataReceived += (s, e) => AppendLog(e.Data);
process.ErrorDataReceived += (s, e) => AppendLog(e.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
await Task.Run(() => process.WaitForExit());
if (process.ExitCode != 0)
{
LogTextBox.AppendText($"> ERROR: sm64extend failed with exit code {process.ExitCode}\n");
return false;
}
}
if (File.Exists(absoluteOutputPath))
{
try
{
File.Delete(absoluteInputPath);
File.Move(absoluteOutputPath, absoluteInputPath);
}
catch (IOException ioEx)
{
LogTextBox.AppendText($"\n> ERROR: Cannot replace '{inputRomName}' because it is locked by another process.\n");
LogTextBox.AppendText("> Please make sure your emulator (Project64/mupen64) is closed and try building again!\n");
LogTextBox.AppendText($"> Technical details: {ioEx.Message}\n");
return false;
}
LogTextBox.AppendText("> Successfully extended ROM and replaced build output with 24MB extended ROM!\n");
return true;
}
else
{
LogTextBox.AppendText($"> ERROR: Extended ROM file not found at {outputRomPath}\n");
return false;
}
}
catch (Exception ex)
{
LogTextBox.AppendText($"> ERROR during ROM extension: {ex.Message}\n");
if (ex is System.ComponentModel.Win32Exception || ex.Message.Contains("wsl", StringComparison.OrdinalIgnoreCase))
{
LogTextBox.AppendText("\n> WSL (Windows Subsystem for Linux) might not be installed or configured on your system.\n");
LogTextBox.AppendText("> Please install WSL (e.g. Ubuntu 20.04 or newer from the Microsoft Store) to run build tools.\n");
LogTextBox.AppendText("> To install WSL, run: 'wsl --install' in an administrator Command Prompt/PowerShell.\n");
}
return false;
}
}
private bool RomExists()
{
if (_settings == null) return false;
string version = _settings.BuildVersion;
if (_settings.BuildTargetPlatform == "PC")
{
string targetDir = Path.Combine(_projectRoot, "build", $"{version}_pc");
if (!Directory.Exists(targetDir)) return false;
if (_settings.BuildEnvironment == "MSYS2")
{
string[] exeFiles = Directory.GetFiles(targetDir, "sm64.*.exe");
return exeFiles.Length > 0;
}
else
{
string[] files = Directory.GetFiles(targetDir, "sm64.*");
foreach (var file in files)
{
if (!file.EndsWith(".z64") && !file.EndsWith(".png") && !file.EndsWith(".c") && !file.EndsWith(".o"))
{
return true;
}
}
return false;
}
}
else
{
return FindBuiltRomPath() != null;
}
}
private string? FindBuiltRomPath()
{
if (_settings == null) return null;
string version = _settings.BuildVersion;
// 1. Try exact standard path: build/{version}/sm64.{version}.z64
string standardPath = Path.Combine(_projectRoot, "build", version, $"sm64.{version}.z64");
if (File.Exists(standardPath))
{
return standardPath;
}
// 2. Scan build directory for any subdirectory containing a recently built .z64 file
string buildPath = Path.Combine(_projectRoot, "build");
if (Directory.Exists(buildPath))
{
try
{
// Find all *.z64 files in build/
string[] z64Files = Directory.GetFiles(buildPath, "*.z64", SearchOption.AllDirectories);
// Sort by write time descending to find the one we just compiled
var fileInfos = z64Files.Select(f => new FileInfo(f))
.OrderByDescending(fi => fi.LastWriteTime)
.ToList();
if (fileInfos.Count > 0)
{
// Check if it's in a subdirectory related to the current version
// (e.g. build/us_n64/sm64.z64 contains "us")
foreach (var fi in fileInfos)
{
string pathLower = fi.FullName.ToLower();
if (pathLower.Contains(version.ToLower()))
{
return fi.FullName;
}
}
// Fallback: return the newest .z64 file found anywhere under build/
return fileInfos[0].FullName;
}
}
catch { }
}
return null;
}
private void AppendLog(string? data)
{
if (data == null) return;
Dispatcher.BeginInvoke(new Action(() =>
{
LogTextBox.AppendText(data + "\n");
LogScrollViewer.ScrollToEnd();
}));
}
private void LaunchEmulator()
{
try
{
if (_settings == null) return;
string version = _settings.BuildVersion;
if (_settings.BuildTargetPlatform == "PC")
{
string targetDir = Path.Combine(_projectRoot, "build", $"{version}_pc");
if (!Directory.Exists(targetDir)) return;
if (_settings.BuildEnvironment == "MSYS2")
{
string[] exeFiles = Directory.GetFiles(targetDir, "sm64.*.exe");
if (exeFiles.Length > 0)
{
string exePath = exeFiles[0];
var runStartInfo = new ProcessStartInfo
{
FileName = exePath,
WorkingDirectory = Path.GetDirectoryName(exePath),
UseShellExecute = true
};
Process.Start(runStartInfo);
}
else