-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathMainWindowViewModel.cs
More file actions
1032 lines (934 loc) · 37 KB
/
MainWindowViewModel.cs
File metadata and controls
1032 lines (934 loc) · 37 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 Avalonia;
using Avalonia.Controls;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using HedgeModManager.CoreLib;
using HedgeModManager.Foundation;
using HedgeModManager.IO;
using HedgeModManager.UI.CLI;
using HedgeModManager.UI.Config;
using HedgeModManager.UI.Controls;
using HedgeModManager.UI.Controls.Modals;
using HedgeModManager.UI.Input;
using HedgeModManager.UI.Languages;
using HedgeModManager.UI.Models;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using static HedgeModManager.UI.Languages.Language;
using static HedgeModManager.UI.Models.Download;
namespace HedgeModManager.UI.ViewModels;
public partial class MainWindowViewModel : ViewModelBase
{
public string AppVersion => Program.ApplicationVersion;
public ObservableCollection<UIGame> Games { get; set; } = [];
public ObservableCollection<Download> Downloads { get; set; } = [];
public ObservableCollection<LanguageEntry> Languages { get; set; } = [];
public ProgramConfig Config { get; set; } = new();
public int ServerStatus { get; set; } = 1;
public CancellationTokenSource ServerCancellationTokenSource { get; set; } = new();
public bool IsFullscreen => WindowState == WindowState.FullScreen;
public bool IsGamescope { get; set; }
public Action<Buttons>? CurrentInputPressedHandler { get; set; }
private ModProfile _lastSelectedProfile = ModProfile.Default;
[ObservableProperty] private UIGame? _selectedGame;
[ObservableProperty] private ModProfile _selectedProfile = ModProfile.Default;
[ObservableProperty] private int _selectedTabIndex;
[ObservableProperty] private UILogger? _loggerInstance;
[ObservableProperty] private string _lastLog = "";
[ObservableProperty] private string _message = "";
[ObservableProperty] private TabInfo? _currentTabInfo;
[ObservableProperty] private TabInfo[] _tabInfos =
[new ("Loading"), new("Setup"), new("Mods"), new("Codes"), new("Settings"), new("About"), new("Test")];
[ObservableProperty] private ObservableCollection<Modal> _modals = [];
[ObservableProperty] private ObservableCollection<IMod> _mods = [];
[ObservableProperty] private ObservableCollection<ICode> _codes = [];
[ObservableProperty] private ObservableCollection<ModProfile> _profiles = [];
[ObservableProperty] private bool _isBusy = true;
[ObservableProperty] private double _overallProgress = 0d;
[ObservableProperty] private double _overallProgressMax = 0d;
[ObservableProperty] private bool _showProgressBar = false;
[ObservableProperty] private bool _progressIndeterminate = false;
[ObservableProperty] private LanguageEntry? _selectedLanguage = null;
[ObservableProperty] private WindowState _windowState = WindowState.Normal;
[ObservableProperty] private ICode _selectedCode = Controls.Codes.Codes.NoCode.Instance;
[ObservableProperty] private GameConfig? _selectedGameConfig = null;
// Preview only
public MainWindowViewModel() { }
public MainWindowViewModel(UILogger logger, List<LanguageEntry> languages)
{
// Setup languages
LanguageEntry.TotalLineCount = languages.Max(x => x.Lines);
Languages = new ObservableCollection<LanguageEntry>(languages);
// Setup logger
_loggerInstance = logger;
_ = new Logger(logger);
logger.Logs.CollectionChanged += (sender, args) =>
{
if (logger.Logs.Count == 0)
return;
var lastLog = logger.Logs.LastOrDefault(x => x.Type != LogType.Debug);
LastLog = lastLog == null ? "" : lastLog.Message;
};
Logger.Information($"Starting HedgeModManager {AppVersion}...");
Logger.Information($"Startup Date: {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} (UTC)");
string os = "Unknown";
if (OperatingSystem.IsWindows())
os = "Windows";
else if (OperatingSystem.IsLinux())
os = "Linux"; // Excludes Android
else if (OperatingSystem.IsMacOS())
os = "macOS";
Logger.Debug($"OS: {os}");
Logger.Debug($"RID: {RuntimeInformation.RuntimeIdentifier}");
Logger.Debug($"FlatpakID: \"{Program.FlatpakID}\" ({!string.IsNullOrEmpty(Program.FlatpakID)})");
Logger.Debug($"InstallLocation: {Program.InstallLocation}");
Logger.Debug($"IsDebugBuild: {Program.IsDebugBuild}");
}
public async Task OnStartUpAsync()
{
if (Config.LastUpdateCheck.AddMinutes(20) < DateTime.Now &&
!Design.IsDesignMode && !Program.IsDebugBuild)
{
#if !COMMITBUILD
if (OperatingSystem.IsWindows())
await CheckForManagerUpdatesAsync();
#endif
try
{
Config.LastUpdateCheck = DateTime.Now;
await Config.SaveAsync();
}
catch { }
}
}
public async Task CheckForManagerUpdatesAsync()
{
await new Download(Localize("Download.Text.CheckManagerUpdate"), true)
.OnRun(async (d, c) =>
{
d.CreateProgress().ReportMax(-1);
var (update, status) = await Updater.CheckForUpdates();
if (update == null)
{
if (status == Updater.UpdateCheckStatus.NoUpdate)
{
Logger.Information("No release found");
} else
{
OpenErrorMessage("Modal.Title.UpdateError", "Modal.Message.UpdateCheckError",
"Failed to check for updates", null);
}
d.Destroy();
return;
}
d.Destroy();
string message = $"Update found:\n{update.Title} - {update.Version}";
Logger.Information(message);
var messageBox = new MessageBoxModal("Modal.Title.UpdateManager", message);
messageBox.AddButton("Common.Button.Cancel", (s, e) => messageBox.Close());
messageBox.AddButton("Common.Button.Install", async (s, e) =>
{
Logger.Information("Install clicked for update");
messageBox.Close();
if (Program.FlatpakID != null)
{
MessageBoxModal.CreateOK("Modal.Title.UpdateManager", "Modal.Message.PkgUpdate");
return;
}
await Updater.BeginUpdate(update, this);
});
//messageBox.AddButton("Test", async (s, e) =>
//{
// messageBox.Close();
// await Updater.UpdateFromPackage("../update.zip", this);
//});
messageBox.Open(this);
}).OnError((d, e) =>
{
Logger.Error(e);
Logger.Error($"Unexpected error while checking for updates");
d.Destroy();
return Task.CompletedTask;
}).RunAsync(this);
}
public async Task CheckForModLoaderUpdatesAsync()
{
await new Download(Localize("Download.Text.CheckLoaderUpdate"), true)
.OnRun(async (d, c) =>
{
d.ReportMax(-1);
var game = GetModdableGameGeneric();
if (game == null)
{
Logger.Debug("Mod loader updates are only supported on ModdableGameGeneric");
return;
}
if (game.ModLoader == null)
{
Logger.Debug("Game does not use an external mod loader");
return;
}
// TODO: Show changelog
bool installed = game.ModLoader.IsInstalled();
bool hasUpdate = await game.ModLoader.CheckForUpdatesAsync();
if (hasUpdate && installed)
await game.ModLoader.InstallAsync(false);
}).OnError((d, e) =>
{
OpenErrorMessage("Modal.Title.UpdateError", "Modal.Message.UpdateCheckError",
"Failed to check for mod loader updates", e);
return Task.CompletedTask;
}).OnFinally((d) =>
{
d.Destroy();
return Task.CompletedTask;
}).RunAsync(this);
}
public async Task CheckForAllModUpdatesAsync()
{
if (SelectedGame == null)
return;
await new Download(Localize("Download.Text.CheckModUpdate", 0, 0), true)
.OnRun(async (d, c) =>
{
var updatableMods = SelectedGame.Game.ModDatabase.Mods
.Where(x => x.Updater != null)
.ToList();
var progress = d.CreateProgress();
progress.ReportMax(updatableMods.Count);
Logger.Debug($"Checking {updatableMods.Count} mod updates");
foreach (var mod in updatableMods)
{
if (c.IsCancellationRequested)
break;
await CheckForModUpdatesAsync(mod, false, c);
progress.ReportAdd(1);
d.Name = Localize("Download.Text.CheckModUpdates", progress.Progress, progress.ProgressMax);
}
d.Destroy();
}).OnError((d, e) =>
{
Logger.Error(e);
Logger.Error($"Unexpected error while checking for mod updates");
d.Destroy();
return Task.CompletedTask;
}).RunAsync(this);
}
public async Task<UpdateInfo?> CheckForModUpdatesAsync(IMod mod, bool promptUpdate = false, CancellationToken c = default)
{
IsBusy = true;
var download = new Download(Localize("Download.Text.CheckModUpdate"), true, -1);
download.Run(this);
try
{
if (await mod.Updater!.CheckForUpdatesAsync(c) == true)
{
var info = await mod.Updater.GetUpdateInfoAsync(c);
download.Destroy();
IsBusy = false;
if (info == null)
{
Logger.Debug($"Got null update info for \"{mod.Title}\" while true for the update check");
return null;
}
Logger.Debug($"Update found for {mod.Title}");
Logger.Debug($" Current: {mod.Version}");
Logger.Debug($" Latest: {info.Version}");
if (promptUpdate)
{
var message = Localize("Modal.Message.UpdateMod", mod.Title, mod.Version, info.Version);
if (!string.IsNullOrEmpty(info.Changelog))
{
message += "\n\n" + info.Changelog;
}
var messageBox = new MessageBoxModal(Localize("Modal.Title.UpdateMod"), message);
messageBox.AddButton("Common.Button.Cancel", (s, e) => messageBox.Close());
messageBox.AddButton("Common.Button.Update", async (s, e) =>
{
// TODO: Look into threading issues
await Dispatcher.UIThread.InvokeAsync(async () =>
{
Modals.Where(x => x.Control is ModInfoModal).ToList().ForEach(x => x.Close());
Logger.Information($"Update clicked for {mod.Title}");
messageBox.Close();
await CreateSimpleDownload(Localize("Download.Text.UpdateMod", mod.Title),
"Failed to update mod", "Modal.Title.UpdateError", Localize("Modal.Message.UpdateModError", mod.Title),
async (d, p, c) =>
{
await mod.Updater.PerformUpdateAsync(p, c);
}).RunAsync(this);
Modals.Where(x => x.Control is ModInfoModal).ToList().ForEach(x => x.Close());
RefreshGame();
});
});
messageBox.Open(this);
}
return info;
}
}
catch (Exception e)
{
Logger.Error($"Failed to check for updates for {mod.Title}");
Logger.Error(e);
}
download.Destroy();
IsBusy = false;
return null;
}
public async Task LoadGameAsync()
{
try
{
if (SelectedGame == null || SelectedGame.Game == null)
return;
var game = SelectedGame.Game;
Logger.Debug($"Selected game:");
Logger.Debug($" ID: {game.ID}");
Logger.Debug($" Name: {game.Name}");
Logger.Debug($" Plat: {game.Platform}");
Logger.Debug($" Root: {game.Root}");
Logger.Debug($" Exec: {game.Executable}");
Logger.Debug($" N OS: {game.NativeOS}");
Logger.Debug($" PFX: {game.PrefixRoot}");
Logger.Debug($" Type: {game.GetType().Name}");
await game.InitializeAsync();
Logger.Debug($"Initialised game");
if (game is ModdableGameGeneric gameGeneric)
{
if (gameGeneric.ModLoader != null)
{
Logger.Debug($"ModLoader.IsInstalled: {gameGeneric.ModLoader.IsInstalled()}");
Logger.Debug($"ModLoader.GetInstalledVersion: {gameGeneric.ModLoader.GetInstalledVersion() ?? "null"}");
}
}
Logger.Debug($"Loading profiles...");
_lastSelectedProfile = ModProfile.Default;
if (game.ModLoaderConfiguration is ModLoaderConfiguration config)
{
Profiles = new(await LoadProfilesAsync(game) ?? []);
_lastSelectedProfile = Profiles
.FirstOrDefault(x => Path.GetFileName(config.DatabasePath) == x.ModDBPath) ?? _lastSelectedProfile;
}
SelectedProfile = _lastSelectedProfile;
Logger.Debug($"Loaded {Profiles.Count} profile(s)");
Config.LastSelectedPath = Path.Combine(game.Root, game.Executable ?? "");
SelectedGameConfig = new GameConfig(game);
Logger.Debug("Loading game config...");
await SelectedGameConfig.LoadAsync();
Logger.Debug("Updating UI");
_ = Dispatcher.UIThread.InvokeAsync(async () =>
{
await UpdateCodesAsync(false, true);
await CheckForModLoaderUpdatesAsync();
});
RefreshUI();
}
catch (Exception e)
{
OpenErrorMessage("Modal.Title.LoadError", "Modal.Message.GameLoadError",
"Failed to load game/mod data", e);
}
}
public async Task InstallModLoaderAsync(bool? install = null)
{
IsBusy = true;
await CreateSimpleDownload("Download.Text.InstallModLoader", "Failed to install modloader",
async (d, p, c) =>
{
if (SelectedGame == null)
return;
if (install != null)
{
var gameGeneric = GetModdableGameGeneric();
if (gameGeneric == null || gameGeneric.ModLoader == null)
return;
if (install == true)
_ = await gameGeneric.ModLoader.InstallAsync();
else
_ = await gameGeneric.ModLoader.UninstallAsync();
}
else
{
_ = await SelectedGame.Game.InstallModLoaderAsync();
}
IsBusy = false;
Dispatcher.UIThread.Invoke(RefreshUI);
}).OnError((d, e) =>
{
OpenErrorMessage("Modal.Title.InstallError", "Modal.Message.ModLoaderInstallError", "Failed to install modloader", e);
return Task.CompletedTask;
}).RunAsync(this);
}
/// <summary>
/// Loads all the mod configurations for the current selected profile.
/// It is important to have the selected game already initialised.
/// </summary>
public async Task SwitchProfileAsync()
{
var lastProfile = _lastSelectedProfile;
var currentProfile = SelectedProfile;
var moddableGameGeneric = GetModdableGameGeneric();
var database = moddableGameGeneric?.ModDatabase;
// No need to reload the same profile
if (currentProfile == lastProfile)
return;
if (SelectedProfile == null)
{
Logger.Debug("Attempted to load a null profile");
return;
}
if (moddableGameGeneric == null || database == null)
{
Logger.Warning("Profile switching is only supported on ModdableGameGeneric");
return;
}
IsBusy = true;
await CreateSimpleDownload("Download.Text.SwitchProfileSave", "Failed to switch profiles",
async (d, p, c) =>
{
var backupProgress = d.CreateProgress();
var restoreProgress = d.CreateProgress();
await lastProfile.BackupModConfigAsync(moddableGameGeneric.ModDatabase, backupProgress);
d.Name = Localize("Download.Text.SwitchProfileLoad");
await currentProfile.RestoreModConfigAsync(moddableGameGeneric.ModDatabase, restoreProgress);
}).RunAsync(this);
Logger.Debug($"Switched profile {_lastSelectedProfile.Name} -> {SelectedProfile.Name}");
_lastSelectedProfile = SelectedProfile;
if (moddableGameGeneric.ModLoaderConfiguration is ModLoaderConfiguration config)
{
config.DatabasePath = Path.Combine(Path.GetDirectoryName(config.DatabasePath)!, SelectedProfile.ModDBPath);
await config.Save(Path.Combine(moddableGameGeneric.Root, "cpkredir.ini"));
moddableGameGeneric.ModDatabase.LoadDatabase(config.DatabasePath);
RefreshUI();
}
await SaveAsync(false);
IsBusy = false;
}
public async Task<List<ModProfile>?> LoadProfilesAsync(IModdableGame game)
{
string filePath = Path.Combine(game.Root, "profiles.json");
// Profiles are only supported for ModDatabaseGeneric
if (SelectedGame?.Game.ModDatabase is not ModDatabaseGeneric modsDB)
return null;
if (!File.Exists(filePath))
return [ModProfile.Default];
string json = await File.ReadAllTextAsync(filePath);
var profiles = JsonSerializer.Deserialize<List<ModProfile>>(json);
// Remove missing profiles
if (profiles != null)
profiles = profiles.Where(x => File.Exists(Path.Combine(modsDB.Root, x.ModDBPath))).ToList();
if (profiles?.Count == 0)
return [ModProfile.Default];
return profiles ?? [ModProfile.Default];
}
public async Task SaveProfilesAsync(IModdableGame game)
{
string filePath = Path.Combine(game.Root, "profiles.json");
// Profiles are only supported for ModDatabaseGeneric
if (SelectedGame?.Game.ModDatabase is not ModDatabaseGeneric)
return;
string json = JsonSerializer.Serialize(Profiles, Program.JsonSerializerOptions);
await File.WriteAllTextAsync(filePath, json);
}
public async Task SaveAsync(bool setBusy = true)
{
if (setBusy)
IsBusy = true;
try
{
Logger.Debug("Saving program config...");
await Config.SaveAsync();
if (SelectedGameConfig != null)
{
Logger.Debug("Saving game config...");
await SelectedGameConfig.SaveAsync();
}
if (SelectedGame != null)
{
try
{
// Resolve mod dependencies
CheckAndInstallModDependencies();
// Ensure enabled mods are on top of disabled mods
// TODO: Find a method to reorder without full update
if (SelectedGame.Game.ModDatabase is ModDatabaseGeneric modsDB)
{
Mods = new(modsDB.Mods = new(modsDB.Mods.OrderBy(x => !x.Enabled)));
var report = await modsDB.SaveWithReport();
if (report.HasErrors)
{
Logger.Warning("Code compilation failed");
var reportViewer = new ReportViewerModal(report);
reportViewer.Open(this, "Modal.Title.CodeCompileError");
}
else
{
Logger.Information("Compiled codes");
}
}
else
{
await SelectedGame.Game.ModDatabase.Save();
}
if (SelectedGame.Game.ModLoaderConfiguration is ModLoaderConfiguration config)
await config.Save(Path.Combine(SelectedGame.Game.Root, "cpkredir.ini"));
}
catch (UnauthorizedAccessException e)
{
OpenErrorMessage("Modal.Title.SaveError", "Modal.Message.GameNoAccess",
"Failed to save mod database and config", e);
IsBusy = false;
return;
}
if (!SelectedGame.Game.IsModLoaderInstalled())
await SelectedGame.Game.InstallModLoaderAsync();
else
Logger.Information("Saved");
}
}
catch (Exception e)
{
OpenErrorMessage("Modal.Title.SaveError", "Modal.Message.UnknownSaveError", "Failed to save", e);
}
if (setBusy)
IsBusy = false;
}
public async Task RunGameAsync()
{
if (SelectedGame != null)
{
try
{
if (IsGamescope)
MessageBoxModal.CreateOK("Modal.Title.Information", "Modal.Message.GamescopeError").Open(this);
await SelectedGame.Game.Run(null, true);
await Task.Delay(5000);
}
catch (Exception e)
{
OpenErrorMessage("Modal.Title.RunError", "Modal.Message.UnknownRunError",
"Failed to run game", e);
}
}
}
public async Task SaveAndRunAsync()
{
IsBusy = true;
await SaveAsync(false);
await RunGameAsync();
IsBusy = false;
}
/// <summary>
/// Closes the application by calling the close event on the main window
/// </summary>
public void Close()
{
(Application.Current as App)?.MainWindow?.Close();
}
public void StartSetup()
{
Logger.Debug("Entered setup");
Config.IsSetupCompleted = false;
SelectedTabIndex = 1;
}
public void CheckAndInstallModDependencies()
{
if (SelectedGame == null)
return;
var game = SelectedGame.Game;
var database = game.ModDatabase;
var dependencies = new List<ModDependency>();
var missing = new List<ModDependency>();
foreach (var mod in database.Mods.Where(x => x.Enabled))
{
var report = ModDependencyReport.GenerateReport(database, mod);
dependencies.AddRange(report.Dependencies);
missing.AddRange(report.MissingDependencies);
}
if (missing.Count == 0)
{
if (dependencies.Count == 0)
return;
Logger.Debug($"Found {dependencies.Count} dependencies");
foreach (var dependency in dependencies)
{
var mod = database.Mods.FirstOrDefault(x => x.ID == dependency.ID);
if (mod == null)
{
Logger.Debug($" Missing {dependency.Title}!");
continue;
}
if (!mod.Enabled)
{
Logger.Debug($" Enabling {mod.Title}...");
mod.Enabled = true;
}
}
UpdateModsList();
}
else
{
Logger.Debug($"Found {missing.Count} dependencies");
foreach (var dependency in missing)
Logger.Debug($" {dependency.Title}");
// TODO: Automate installation of missing dependencies
string modListStr = string.Join(Environment.NewLine, missing.Select(x => $"- {x.Title} | {x.Version}")); ;
var messageBox = new MessageBoxModal("Modal.Title.MissingDependency", Localize("Modal.Message.MissingDependency", modListStr));
messageBox.AddButton("Common.Button.OK", (s, e) => messageBox.Close());
messageBox.Open(this);
}
}
public async Task UpdateCodesAsync(bool force, bool append)
{
if (SelectedGame != null && SelectedGame.Game is ModdableGameGeneric gameGeneric &&
gameGeneric.ModLoaderConfiguration is ModLoaderConfiguration config)
{
string modsRoot = PathEx.GetDirectoryName(config.DatabasePath).ToString();
string mainCodesPath = Path.Combine(modsRoot, ModDatabaseGeneric.MainCodesFileName);
if (force || !File.Exists(mainCodesPath))
{
await CreateSimpleDownload("Download.Text.DownloadCodes", "Failed to download community codes",
async (d, p, c) =>
{
var diff = await gameGeneric.UpdateCodes();
var blocks = diff.ToList();
// Print to logger for now
Logger.Debug($"Updated codes with {blocks.Count} blocks:");
foreach (var block in blocks)
Logger.Debug($" {block.Type} {block.Description}");
if (append)
gameGeneric.ModDatabase.LoadSingleCodeFile(mainCodesPath);
else
await gameGeneric.InitializeAsync();
Dispatcher.UIThread.Invoke(RefreshUI);
}).RunAsync(this);
}
}
}
public void RefreshGame()
{
if (SelectedGame is not UIGame game)
return;
OnPropertyChanged(nameof(SelectedGame));
}
public void RefreshUI()
{
if (SelectedGame is not UIGame game)
return;
UpdateModsList();
UpdateCodesList();
Logger.Information($"Found {game.Game.ModDatabase.Mods.Count} mods");
}
public void UpdateModsList()
{
if (SelectedGame == null)
{
Logger.Error("Updating mods from null game!");
Codes.Clear();
return;
}
Mods = new(SelectedGame.Game.ModDatabase.Mods);
}
public void UpdateCodesList()
{
if (SelectedGame == null)
{
Logger.Error("Updating codes from null game!");
Codes.Clear();
return;
}
Codes = new(SelectedGame.Game.ModDatabase.Codes);
}
public void OpenErrorMessage(string title, string message, string logMessage, Exception? exception = null)
{
if (exception != null)
Logger.Error(exception);
Logger.Error(logMessage);
var messageBox = new MessageBoxModal(title, message);
messageBox.AddButton("Common.Button.OK", (s, e) => messageBox.Close());
messageBox.AddButton("Modal.Button.ExportLog", async (s, e) =>
{
await ExportLogAsync(messageBox);
messageBox.Close();
});
messageBox.SetDanger();
messageBox.Open(this);
}
public ModdableGameGeneric? GetModdableGameGeneric()
{
return SelectedGame?.Game as ModdableGameGeneric;
}
public int GetTabIndex(string name)
{
return Array.FindIndex(TabInfos, x => x.Name == name);
}
public async Task OnInputDownAsync(Buttons button)
{
if (button == Buttons.None)
return;
if (Modals.Count > 0)
{
// TODO: Handle inputs
return;
}
if (button == Buttons.Start)
{
await RunGameAsync();
return;
}
if (button == Buttons.LB)
{
if (SelectedTabIndex > 2)
SelectedTabIndex--;
else
SelectedTabIndex = Config.TestModeEnabled ? 6 : 5;
return;
}
if (button == Buttons.RB)
{
if (SelectedTabIndex < (Config.TestModeEnabled ? 6 : 5))
SelectedTabIndex++;
else
SelectedTabIndex = 2;
return;
}
CurrentInputPressedHandler?.Invoke(button);
}
public static async Task ExportLogAsync(Visual visual)
{
string log = UILogger.Export();
var topLevel = TopLevel.GetTopLevel(visual);
if (topLevel == null)
return;
var file = await topLevel.StorageProvider.SaveFilePickerAsync(new()
{
Title = "Save Log File",
SuggestedFileName = "HedgeModManager.log",
DefaultExtension = ".log",
FileTypeChoices =
[
new("Log Files")
{
Patterns = ["*.log"],
MimeTypes = ["text/plain"]
}
]
});
if (file != null)
{
using var stream = await file.OpenWriteAsync();
await stream.WriteAsync(Encoding.Default.GetBytes(log));
}
}
public async Task InstallModAsync(Visual visual, UIGame? game)
{
var topLevel = TopLevel.GetTopLevel(visual);
if (topLevel == null)
return;
var files = await topLevel.StorageProvider.OpenFilePickerAsync(new()
{
Title = "Select Mod...",
AllowMultiple = true,
FileTypeFilter =
[
new("Archive Files")
{
Patterns = ["*.zip", "*.7z", "*.rar"],
MimeTypes =
[
"application/zip",
"application/x-rar-compressed",
"application/x-7z-compressed"
]
}
]
});
if (files == null)
return;
foreach (var file in files)
InstallMod(file.Name, Utils.ConvertToPath(file.Path), game);
}
public void InstallMod(string name, string path, UIGame? game)
{
game ??= SelectedGame;
if (game?.Game.ModDatabase is not ModDatabaseGeneric modsDB)
{
OpenErrorMessage("Modal.Title.InstallError", "Modal.Message.InstallError",
"Only ModDatabaseGeneric is supported for installing mods");
return;
}
new Download(name).OnRun(async (d, c) =>
{
var installProgress = d.CreateProgress();
installProgress.ReportMax(1);
await modsDB.InstallModFromArchive(path, installProgress);
Logger.Information($"Finished installing {name}");
if (game == SelectedGame)
{
await Dispatcher.UIThread.Invoke(async () =>
{
await SelectedGame.Game.InitializeAsync();
RefreshUI();
});
}
}).OnError((d, e) =>
{
OpenErrorMessage("Modal.Title.InstallError", "Modal.Message.InstallError",
$"Failed to install {name}");
return Task.CompletedTask;
}).OnFinally((d) =>
{
d.Destroy();
return Task.CompletedTask;
})
.Run(this);
}
public void UpdateDownload()
{
double progress = 0;
double progressMax = -1;
for (int i = 0; i < Downloads.Count; i++)
{
if (Downloads[i].Destroyed)
{
Downloads.RemoveAt(i);
i--;
continue;
}
if (Downloads[i].ProgressMax != -1)
{
progress += Downloads[i].Progress;
progressMax += Downloads[i].ProgressMax;
}
}
if (Downloads.Count > 0)
{
OverallProgress = progress;
OverallProgressMax = progressMax;
if (Downloads.Count == 1)
Message = Downloads[0].CustomTitle ?
Downloads[0].Name : Localize("Download.Text.InstallMod", Downloads[0].Name);
else
Message = Localize("Download.Text.InstallModMultiple", Downloads.Count);
}
ShowProgressBar = Downloads.Count > 0;
ProgressIndeterminate = progressMax == -1;
}
public void AddDownload(Download download)
{
download.PropertyChanged += (s, e) => Dispatcher.UIThread.Invoke(UpdateDownload);
Downloads.Add(download);
Dispatcher.UIThread.Invoke(UpdateDownload);
}
public static Download CreateSimpleDownload(string name, string errorMessage, string? errorTitle, string? errorBody, Func<Download, DownloadProgress, CancellationToken, Task> callback)
{
return new Download(Localize(name), true)
.OnRun(async (d, c) =>
{
var progress = d.CreateProgress();
progress.ReportMax(-1);
await callback(d, progress, c);
d.Destroy();
}).OnError((d, e) =>
{
if (errorTitle != null && errorBody != null && d.MainViewModel != null)
d.MainViewModel.OpenErrorMessage(errorTitle, errorBody, errorMessage, e);
else
{
Logger.Error(e);
Logger.Error(errorMessage);
}
return Task.CompletedTask;
}).OnFinally((d) =>
{
d.Destroy();
return Task.CompletedTask;
});
}
public static Download CreateSimpleDownload(string name, string errorMessage, Func<Download, DownloadProgress, CancellationToken, Task> callback)
{
return CreateSimpleDownload(name, errorMessage, null, null, callback);
}
public async Task ProcessCommandsAsync(List<ICliCommand> commands)
{
Logger.Debug($"Processing {commands.Count} command(s)");
foreach (var command in commands)
{
Logger.Debug($" Processing command: {command.GetType().Name}");
await command.ExecuteUI(this);
}
}
public async Task StartServerAsync()
{
try
{
var c = ServerCancellationTokenSource.Token;
Logger.Debug("Starting server");
ServerStatus = 1;
while (ServerStatus == 1)
{
if (c.IsCancellationRequested)
break;
using var server = new NamedPipeServerStream(Program.PipeName, PipeDirection.In,
NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
Logger.Debug("Waiting for connection");
await server.WaitForConnectionAsync(c);
if (c.IsCancellationRequested)
break;
Logger.Debug("Opening stream...");
using var reader = new StreamReader(server);
string message = await reader.ReadToEndAsync(c);
Logger.Debug("Message read");
var argsStr = JsonSerializer.Deserialize<string[]>(message);
if (argsStr == null)
continue;
Logger.Debug("Message deserialised");
_ = Dispatcher.UIThread.InvokeAsync(async () =>
{
try
{
var args = CommandLine.ParseArguments(argsStr);
var (continueStartup, commands) = CommandLine.ExecuteArguments(args);
await ProcessCommandsAsync(commands);
Logger.Debug("Message processed");
}
catch (Exception e)
{
OpenErrorMessage("Modal.Title.UnknownError", "Modal.Message.UnknownError",
"Failed to process message", e);
}
});