Skip to content

Commit

Permalink
more fixes for mods not loading settings properly
Browse files Browse the repository at this point in the history
  • Loading branch information
Jorixon committed Sep 15, 2023
1 parent 216ae75 commit 2a3a262
Show file tree
Hide file tree
Showing 9 changed files with 95 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ public interface ISkinManagerService : IDisposable
public string UnloadedModsFolderPath { get; }
public string ActiveModsFolderPath { get; }
public IReadOnlyCollection<ICharacterModList> CharacterModLists { get; }
public void ScanForMods();
public Task ScanForModsAsync();
public ICharacterModList GetCharacterModList(GenshinCharacter character);

public void Initialize(string activeModsFolderPath, string? unloadedModsFolderPath,
public Task Initialize(string activeModsFolderPath, string? unloadedModsFolderPath,
string? threeMigotoRootfolder = null);

/// <summary>
Expand All @@ -25,7 +25,7 @@ public void Initialize(string activeModsFolderPath, string? unloadedModsFolderPa
/// <summary>
/// This looks for mods in characters mod folder that are not tracked by the mod manager and adds them to the mod manager.
/// </summary>
public void RefreshMods(GenshinCharacter? refreshForCharacter = null);
public Task RefreshModsAsync(GenshinCharacter? refreshForCharacter = null);

public void TransferMods(ICharacterModList source, ICharacterModList destination, IEnumerable<Guid> modsEntryIds);

Expand Down
14 changes: 14 additions & 0 deletions src/GIMI-ModManager.Core/Entities/SkinMod.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ public SkinMod(DirectoryInfo modDirectory, string customName = "") : base(modDir
Init();
}

public static async Task<ISkinMod> CreateWithSettingsAsync(DirectoryInfo modDirectory,
CancellationToken cancellationToken = default)
{
var skinMod = new SkinMod(modDirectory);
if (skinMod.HasMergedInI)
await skinMod.ReadKeySwapConfiguration(cancellationToken: cancellationToken);
await skinMod.ReadSkinModSettings(cancellationToken: cancellationToken);
return skinMod;
}

private void Init()
{
var modFolderAttributes = File.GetAttributes(_modDirectory.FullName);
Expand Down Expand Up @@ -77,6 +87,10 @@ public async Task<IReadOnlyCollection<SkinModKeySwap>> ReadKeySwapConfiguration(
if (!HasMergedInI)
throw new InvalidOperationException("Mod has no merged.ini file.");


if (CachedKeySwaps is not null && !forceReload)
return CachedKeySwaps;

List<string> keySwapLines = new();
List<SkinModKeySwap> keySwaps = new();
var keySwapBlockStarted = false;
Expand Down
10 changes: 6 additions & 4 deletions src/GIMI-ModManager.Core/Services/SkinManagerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public SkinManagerService(IGenshinService genshinService, ILogger logger)

public bool UnloadingModsEnabled { get; private set; }

public void ScanForMods()
public Task ScanForModsAsync()
{
_activeModsFolder.Refresh();

Expand All @@ -56,9 +56,11 @@ public void ScanForMods()
characterModList.TrackMod(mod);
}
}

return Task.CompletedTask;
}

public void RefreshMods(GenshinCharacter? refreshForCharacter = null)
public async Task RefreshModsAsync(GenshinCharacter? refreshForCharacter = null)
{
foreach (var characterModList in _characterModLists)
{
Expand Down Expand Up @@ -341,7 +343,7 @@ public ICharacterModList GetCharacterModList(GenshinCharacter character)
}


public void Initialize(string activeModsFolderPath, string? unloadedModsFolderPath = null,
public async Task Initialize(string activeModsFolderPath, string? unloadedModsFolderPath = null,
string? threeMigotoRootfolder = null)
{
_logger.Debug(
Expand Down Expand Up @@ -371,7 +373,7 @@ public void Initialize(string activeModsFolderPath, string? unloadedModsFolderPa
_activeModsFolder = new DirectoryInfo(activeModsFolderPath);
_activeModsFolder.Create();
InitializeFolderStructure();
ScanForMods();
await ScanForModsAsync();
}

private void InitializeFolderStructure()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ protected override async Task HandleInternalAsync(LaunchActivatedEventArgs args)
var modManagerOptions =
await _localSettingsService.ReadSettingAsync<ModManagerOptions>(ModManagerOptions.Section);

_skinManagerService.Initialize(modManagerOptions!.ModsFolderPath!, null, modManagerOptions.GimiRootFolderPath);
await _skinManagerService.Initialize(modManagerOptions!.ModsFolderPath!, null, modManagerOptions.GimiRootFolderPath);
_navigationService.NavigateTo(typeof(CharactersViewModel).FullName!, args.Arguments, true);
}
}
4 changes: 4 additions & 0 deletions src/GIMI-ModManager.WinUI/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ public App()
var mt = new ExpressionTemplate(
"[{@t:yyyy-MM-dd'T'HH:mm:ss} {@l:u3} {Substring(SourceContext, LastIndexOf(SourceContext, '.') + 1)}] {@m}\n{@x}");
configuration.WriteTo.File(formatter: mt, "logs\\log.txt");
if (Debugger.IsAttached)
{
configuration.WriteTo.Debug();
}
})
.ConfigureServices((context, services) =>
{
Expand Down
21 changes: 17 additions & 4 deletions src/GIMI-ModManager.WinUI/Models/NewModModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ public partial class NewModModel : ObservableObject, IEquatable<NewModModel>
[ObservableProperty] private Uri _imagePath = PlaceholderImagePath;
[ObservableProperty] private string _author = string.Empty;

private static readonly Uri PlaceholderImagePath = new(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets\\ModPanePlaceholder.webp"));
private static readonly Uri PlaceholderImagePath =
new(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets\\ModPanePlaceholder.webp"));

public ObservableCollection<SkinModKeySwapModel> SkinModKeySwaps { get; set; } =
new ObservableCollection<SkinModKeySwapModel>();

Expand All @@ -49,24 +51,35 @@ public static NewModModel FromMod(CharacterSkinEntry modEntry)
name.StartsWith(CharacterModList.DISABLED_PREFIX) ? "DISABLED_" : "DISABLED", "");
}

return new NewModModel
var modModel = new NewModModel
{
Id = modEntry.Id,
Character = modEntry.ModList.Character,
Name = string.IsNullOrWhiteSpace(name) ? modEntry.Mod.CustomName : name,
FolderName = modEntry.Mod.Name,
IsEnabled = modEntry.IsEnabled
};

if (modEntry.Mod.CachedSkinModSettings is { } settings)
modModel.WithModSettings(settings);


if (modEntry.Mod.CachedKeySwaps is { } keySwaps)
modModel.SetKeySwaps(keySwaps);

return modModel;
}

public NewModModel WithModSettings(SkinModSettings settings)
{
if (!string.IsNullOrWhiteSpace(settings.CustomName))
Name = settings.CustomName;

ModUrl = settings.ModUrl ?? string.Empty;
ModVersion = settings.Version ?? string.Empty;
ImagePath = string.IsNullOrWhiteSpace(settings.ImagePath) ? PlaceholderImagePath : new Uri(settings.ImagePath, UriKind.Absolute);
ImagePath = string.IsNullOrWhiteSpace(settings.ImagePath)
? PlaceholderImagePath
: new Uri(settings.ImagePath, UriKind.Absolute);
Author = settings.Author ?? string.Empty;
return this;
}
Expand Down
47 changes: 34 additions & 13 deletions src/GIMI-ModManager.WinUI/ViewModels/CharacterDetailsViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text.Json;
using Windows.Storage;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
Expand Down Expand Up @@ -67,20 +69,19 @@ public CharacterDetailsViewModel(IGenshinService genshinService, ILogger logger,

private void ModListOnModsChanged(object? sender, ModFolderChangedArgs e)
{
App.MainWindow.DispatcherQueue.TryEnqueue(() =>
App.MainWindow.DispatcherQueue.TryEnqueue(async () =>
{
if (!IsAddingModFolder)
_notificationService.ShowNotification(
$"Folder Activity Detected in {ShownCharacter.DisplayName}'s Mod Folder",
"Files/Folders were changed in the characters mod folder and mods have been refreshed.",
TimeSpan.FromSeconds(5));
ModListVM.SetBackendMods(_modList.Mods.Select(mod =>
NewModModel.FromMod(mod).WithToggleModDelegate(ToggleMod)));
ModListVM.ResetContent();
await Task.Delay(TimeSpan.FromSeconds(1)); // Wait for file system to finish moving files
await _refreshMods().ConfigureAwait(false);
});
}

public void OnNavigatedTo(object parameter)
public async void OnNavigatedTo(object parameter)
{
if (parameter is not CharacterGridItemModel characterGridItemModel)
{
Expand All @@ -107,11 +108,19 @@ public void OnNavigatedTo(object parameter)
if (ShownCharacter.Id == _genshinService.OtherCharacterId)
ModListVM.DisableInfoBar = true;


ModListVM.SetBackendMods(_modList.Mods.Select(mod =>
NewModModel.FromMod(mod).WithToggleModDelegate(ToggleMod)));
_modList.ModsChanged += ModListOnModsChanged;
ModListVM.ResetContent();
try
{
await _refreshMods();
_modList.ModsChanged += ModListOnModsChanged;
}
catch (Exception e)
{
_logger.Error(e, "Error while refreshing mods.");
_notificationService.ShowNotification("Error while loading modes.",
$"An error occurred while loading the mods for this character.\n{e.Message}",
TimeSpan.FromSeconds(10));
_navigationService.GoBack();
}
}


Expand Down Expand Up @@ -203,14 +212,26 @@ private async Task RefreshMods()

private async Task _refreshMods()
{
await Task.Run(() => _skinManagerService.RefreshMods(ShownCharacter));
await Task.Run(() => _skinManagerService.RefreshModsAsync(ShownCharacter));
var modList = new List<NewModModel>();
foreach (var skinEntry in _modList.Mods)
{
var modSettings = await skinEntry.Mod.ReadSkinModSettings();
var newModModel = NewModModel.FromMod(skinEntry);
newModModel.WithToggleModDelegate(ToggleMod);
newModModel.WithModSettings(modSettings);
try
{
var modSettings = await skinEntry.Mod.ReadSkinModSettings();

newModModel.WithModSettings(modSettings);

}
catch (JsonException e)
{
_logger.Error(e, "Error while reading mod settings for {ModName}", skinEntry.Mod.Name);
_notificationService.ShowNotification("Error while reading mod settings.",
$"An error occurred while reading the mod settings for {skinEntry.Mod.Name}, See logs for details.\n{e.Message}",
TimeSpan.FromSeconds(10));
}
modList.Add(newModModel);
}

Expand Down
2 changes: 1 addition & 1 deletion src/GIMI-ModManager.WinUI/ViewModels/StartupViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ await _localSettingsService.SaveSettingAsync(ModManagerOptions.Section,
modManagerOptions);
_logger.Information("Saved startup settings: {@ModManagerOptions}", modManagerOptions);

_skinManagerService.Initialize(modManagerOptions.ModsFolderPath!, null, modManagerOptions.GimiRootFolderPath);
await _skinManagerService.Initialize(modManagerOptions.ModsFolderPath!, null, modManagerOptions.GimiRootFolderPath);

if (ReorganizeModsOnStartup)
{
Expand Down
18 changes: 15 additions & 3 deletions src/GIMI-ModManager.WinUI/ViewModels/SubVms/ModPaneVM.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.Text.Json;
using Windows.Storage.Pickers;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
Expand All @@ -18,6 +19,7 @@ public partial class ModPaneVM : ObservableRecipient
{
private readonly ISkinManagerService _skinManagerService;
private readonly NotificationManager _notificationManager;
private readonly ILogger _logger = Log.ForContext<ModPaneVM>();
private ISkinMod _selectedSkinMod = null!;
private ICharacterModList _modList = null!;

Expand Down Expand Up @@ -52,10 +54,20 @@ public async Task LoadMod(NewModModel modModel, CancellationToken cancellationTo

private async Task ReloadModSettings(CancellationToken cancellationToken = default)
{
var skinModSettings = await _selectedSkinMod.ReadSkinModSettings(cancellationToken: cancellationToken);
try
{
var skinModSettings = await _selectedSkinMod.ReadSkinModSettings(cancellationToken: cancellationToken);

_backendModModel.WithModSettings(skinModSettings);
SelectedModModel.WithModSettings(skinModSettings);
_backendModModel.WithModSettings(skinModSettings);
SelectedModModel.WithModSettings(skinModSettings);
}
catch (JsonException e)
{
_logger.Error(e, "Error while reading mod settings for {ModName}", _backendModModel.FolderName);
_notificationManager.ShowNotification("Error while reading mod settings.",
$"An error occurred while reading the mod settings for {_backendModModel.FolderName}, See logs for details.\n{e.Message}",
TimeSpan.FromSeconds(10));
}

Debug.Assert(_backendModModel.Equals(SelectedModModel));

Expand Down

0 comments on commit 2a3a262

Please sign in to comment.