From c34ad43e64f49e9556865009ab52566152e17888 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 10 Apr 2024 00:09:03 +0000 Subject: [PATCH] Automated dotnet-format update --- .../Features/Commands/CommandsFeature.cs | 4 +- .../Patches/CommandLineFunctionalityPatch.cs | 42 +- .../ContinueSaveFileFeature.cs | 30 +- .../Patches/InformationManagerPatch.cs | 20 +- .../ContinueSaveFile/Patches/ModulePatch.cs | 36 +- .../Patches/SandBoxSubModulePatch.cs | 76 +-- .../ExceptionInterceptorFeature.cs | 54 +-- .../ExceptionInterceptor/FinalizerGlobal.cs | 28 +- .../ExceptionInterceptor/FinalizerSimple.cs | 14 +- .../Interceptor/InterceptorFeature.cs | 28 +- .../Interceptor/Patches/ModulePatch.cs | 42 +- .../Features/Xbox/Patches/ModulePatch.cs | 46 +- .../Features/Xbox/XboxFeature.cs | 8 +- .../Utils/CommandLineSplitter.cs | 134 +++--- src/Bannerlord.BLSE/Utils/GameUtils.cs | 14 +- src/Bannerlord.BLSE/Utils/TypeFinder.cs | 56 +-- .../Helpers/ConfigReader.cs | 68 +-- .../Helpers/Integrations.cs | 10 +- src/Bannerlord.LauncherEx/Helpers/UI/IRef.cs | 96 ++-- .../Helpers/UI/MixinManager.cs | 144 +++--- .../Helpers/UI/PrefabExtensionManager.cs | 228 ++++----- .../Mixins/LauncherVMMixin.cs | 436 +++++++++--------- .../Options/LauncherExData.cs | 46 +- .../Patches/LauncherConfirmStartVMPatch.cs | 16 +- .../Patches/LauncherModsVMPatch.cs | 22 +- .../Patches/LauncherUIPatch.cs | 68 +-- .../Patches/LauncherVMPatch.cs | 60 +-- .../Patches/ProgramPatch.cs | 24 +- .../Patches/UserDataManagerPatch.cs | 122 ++--- .../Patches/WidgetPrefabPatch.cs | 290 ++++++------ .../UILauncherPrefabExtension.ImportExport.cs | 4 +- .../UILauncherPrefabExtension.Minor.cs | 68 +-- .../UILauncherPrefabExtension.Mods.Saves.cs | 8 +- .../UILauncherPrefabExtension.Mods.cs | 4 +- .../UILauncherPrefabExtension.Options.cs | 32 +- .../GraphicsContextManager.cs | 74 +-- .../ResourceManagers/SpriteDataManager.cs | 270 +++++------ src/Bannerlord.LauncherEx/TPac/AssetItem.cs | 14 +- .../TPac/AssetPackage.cs | 136 +++--- .../TPac/ExternalData.cs | 14 +- .../TPac/ExternalLoader.cs | 106 ++--- .../TPac/TexturePixelData.cs | 104 ++--- .../TPac/TypedAssetFactory.cs | 48 +- .../TPac/TypedDataFactory.cs | 58 +-- src/Bannerlord.LauncherEx/TPac/Utils.cs | 30 +- .../ViewModels/BUTRLauncherMessageBoxVM.cs | 26 +- .../ViewModels/BUTRLauncherModuleVM.cs | 120 ++--- .../ViewModels/BUTRLauncherSaveVM.cs | 154 +++---- .../ViewModels/BUTRLauncherSavesVM.cs | 62 +-- .../ViewModels/SettingsPropertyVM.cs | 134 +++--- .../Widgets/LauncherSearchBoxWidget.cs | 30 +- .../Widgets/LauncherToggleButtonWidget.cs | 244 +++++----- 52 files changed, 2001 insertions(+), 2001 deletions(-) diff --git a/src/Bannerlord.BLSE/Features/Commands/CommandsFeature.cs b/src/Bannerlord.BLSE/Features/Commands/CommandsFeature.cs index c582b82..68debd4 100644 --- a/src/Bannerlord.BLSE/Features/Commands/CommandsFeature.cs +++ b/src/Bannerlord.BLSE/Features/Commands/CommandsFeature.cs @@ -18,6 +18,6 @@ public static class CommandsFeature public static void Enable(Harmony harmony) { - CommandLineFunctionalityPatch.Enable(harmony); - } + CommandLineFunctionalityPatch.Enable(harmony); + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Features/Commands/Patches/CommandLineFunctionalityPatch.cs b/src/Bannerlord.BLSE/Features/Commands/Patches/CommandLineFunctionalityPatch.cs index 49cadf3..e27a221 100644 --- a/src/Bannerlord.BLSE/Features/Commands/Patches/CommandLineFunctionalityPatch.cs +++ b/src/Bannerlord.BLSE/Features/Commands/Patches/CommandLineFunctionalityPatch.cs @@ -21,9 +21,9 @@ private readonly ref struct CommandLineFunctionHandle public static CommandLineFunctionHandle Create(Func, string> commandlinefunc) { - var commandLineFunction = CommandLineFunctionCtor?.Invoke(commandlinefunc); - return commandLineFunction is not null ? new(commandLineFunction) : default; - } + var commandLineFunction = CommandLineFunctionCtor?.Invoke(commandlinefunc); + return commandLineFunction is not null ? new(commandLineFunction) : default; + } public object Object { get; } @@ -34,29 +34,29 @@ public static CommandLineFunctionHandle Create(Func, string> comman public static bool Enable(Harmony harmony) { - _harmony = harmony; + _harmony = harmony; - return harmony.TryPatch( - AccessTools2.DeclaredMethod(typeof(CommandLineFunctionality), nameof(CommandLineFunctionality.CollectCommandLineFunctions)), - postfix: AccessTools2.DeclaredMethod(typeof(CommandLineFunctionalityPatch), nameof(CollectCommandLineFunctionsPostfix))); - } + return harmony.TryPatch( + AccessTools2.DeclaredMethod(typeof(CommandLineFunctionality), nameof(CommandLineFunctionality.CollectCommandLineFunctions)), + postfix: AccessTools2.DeclaredMethod(typeof(CommandLineFunctionalityPatch), nameof(CollectCommandLineFunctionsPostfix))); + } private static void CollectCommandLineFunctionsPostfix(IDictionary ___AllFunctions, ref List __result) { - try - { - foreach (var (name, function) in CommandsFeature.Functions) - { - if (CommandLineFunctionHandle.Create(function) is not { Object: { } cmdFuncObject }) continue; - ___AllFunctions.Add(name, cmdFuncObject); - __result.Add(name); - } - } - finally + try + { + foreach (var (name, function) in CommandsFeature.Functions) { - _harmony?.Unpatch( - AccessTools2.DeclaredMethod(typeof(CommandLineFunctionality), nameof(CommandLineFunctionality.CollectCommandLineFunctions)), - AccessTools2.DeclaredMethod(typeof(CommandLineFunctionalityPatch), nameof(CollectCommandLineFunctionsPostfix))); + if (CommandLineFunctionHandle.Create(function) is not { Object: { } cmdFuncObject }) continue; + ___AllFunctions.Add(name, cmdFuncObject); + __result.Add(name); } } + finally + { + _harmony?.Unpatch( + AccessTools2.DeclaredMethod(typeof(CommandLineFunctionality), nameof(CommandLineFunctionality.CollectCommandLineFunctions)), + AccessTools2.DeclaredMethod(typeof(CommandLineFunctionalityPatch), nameof(CollectCommandLineFunctionsPostfix))); + } + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Features/ContinueSaveFile/ContinueSaveFileFeature.cs b/src/Bannerlord.BLSE/Features/ContinueSaveFile/ContinueSaveFileFeature.cs index d67a4be..2b7daca 100644 --- a/src/Bannerlord.BLSE/Features/ContinueSaveFile/ContinueSaveFileFeature.cs +++ b/src/Bannerlord.BLSE/Features/ContinueSaveFile/ContinueSaveFileFeature.cs @@ -17,27 +17,27 @@ public static class ContinueSaveFileFeature public static void Enable(Harmony harmony) { - _harmony = harmony; - ModulePatch.OnSaveGameArgParsed += (_, saveFile) => _currentSaveFile = saveFile; - ModulePatch.Enable(harmony); + _harmony = harmony; + ModulePatch.OnSaveGameArgParsed += (_, saveFile) => _currentSaveFile = saveFile; + ModulePatch.Enable(harmony); - AppDomain.CurrentDomain.AssemblyLoad += CurrentDomainOnAssemblyLoad; - } + AppDomain.CurrentDomain.AssemblyLoad += CurrentDomainOnAssemblyLoad; + } private static void CurrentDomainOnAssemblyLoad(object? sender, AssemblyLoadEventArgs args) { - if (_harmony is null) return; - - if (args.LoadedAssembly.GetName().Name == "SandBox") - { - SandBoxSubModulePatch.GetSaveGameArg = GetSaveFile; - SandBoxSubModulePatch.Enable(_harmony); - InformationManagerPatch.Enable(_harmony); - } + if (_harmony is null) return; + + if (args.LoadedAssembly.GetName().Name == "SandBox") + { + SandBoxSubModulePatch.GetSaveGameArg = GetSaveFile; + SandBoxSubModulePatch.Enable(_harmony); + InformationManagerPatch.Enable(_harmony); } + } private static string? GetSaveFile(GameStartupInfo startupInfo) { - return _currentSaveFile; - } + return _currentSaveFile; + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Features/ContinueSaveFile/Patches/InformationManagerPatch.cs b/src/Bannerlord.BLSE/Features/ContinueSaveFile/Patches/InformationManagerPatch.cs index d3d6c76..dfb58fb 100644 --- a/src/Bannerlord.BLSE/Features/ContinueSaveFile/Patches/InformationManagerPatch.cs +++ b/src/Bannerlord.BLSE/Features/ContinueSaveFile/Patches/InformationManagerPatch.cs @@ -11,18 +11,18 @@ internal static class InformationManagerPatch public static bool Enable(Harmony harmony) { - return harmony.TryPatch( - original: AccessTools2.Method(typeof(InformationManager), "ShowInquiry"), - prefix: AccessTools2.Method(typeof(InformationManagerPatch), nameof(Prefix))); - } + return harmony.TryPatch( + original: AccessTools2.Method(typeof(InformationManager), "ShowInquiry"), + prefix: AccessTools2.Method(typeof(InformationManagerPatch), nameof(Prefix))); + } private static bool Prefix(InquiryData data) { - if (SkipChange) - { - data.AffirmativeAction?.Invoke(); - return false; - } - return true; + if (SkipChange) + { + data.AffirmativeAction?.Invoke(); + return false; } + return true; + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Features/ContinueSaveFile/Patches/ModulePatch.cs b/src/Bannerlord.BLSE/Features/ContinueSaveFile/Patches/ModulePatch.cs index 28ab098..e7d3dec 100644 --- a/src/Bannerlord.BLSE/Features/ContinueSaveFile/Patches/ModulePatch.cs +++ b/src/Bannerlord.BLSE/Features/ContinueSaveFile/Patches/ModulePatch.cs @@ -19,27 +19,27 @@ internal static class ModulePatch public static bool Enable(Harmony harmony) { - _harmony = harmony; + _harmony = harmony; - return harmony.TryPatch( - AccessTools2.DeclaredMethod(typeof(Module), "ProcessApplicationArguments"), - postfix: AccessTools2.DeclaredMethod(typeof(ModulePatch), nameof(ProcessApplicationArgumentsPostfix))); - } + return harmony.TryPatch( + AccessTools2.DeclaredMethod(typeof(Module), "ProcessApplicationArguments"), + postfix: AccessTools2.DeclaredMethod(typeof(ModulePatch), nameof(ProcessApplicationArgumentsPostfix))); + } private static void ProcessApplicationArgumentsPostfix(Module __instance) { - var cli = Utilities.GetFullCommandLineString(); - var array = CommandLineSplitter.SplitCommandLine(cli).ToArray(); - for (var i = 0; i < array.Length; i++) - { - if (!string.Equals(array[i], "/continuesave", StringComparison.OrdinalIgnoreCase)) continue; - if (array.Length <= i + 1) continue; - var saveGame = array[i + 1]; - OnSaveGameArgParsed?.Invoke(__instance.StartupInfo, saveGame); - } - - _harmony?.Unpatch( - AccessTools2.DeclaredMethod(typeof(Module), "ProcessApplicationArguments"), - AccessTools2.DeclaredMethod(typeof(ModulePatch), nameof(ProcessApplicationArgumentsPostfix))); + var cli = Utilities.GetFullCommandLineString(); + var array = CommandLineSplitter.SplitCommandLine(cli).ToArray(); + for (var i = 0; i < array.Length; i++) + { + if (!string.Equals(array[i], "/continuesave", StringComparison.OrdinalIgnoreCase)) continue; + if (array.Length <= i + 1) continue; + var saveGame = array[i + 1]; + OnSaveGameArgParsed?.Invoke(__instance.StartupInfo, saveGame); } + + _harmony?.Unpatch( + AccessTools2.DeclaredMethod(typeof(Module), "ProcessApplicationArguments"), + AccessTools2.DeclaredMethod(typeof(ModulePatch), nameof(ProcessApplicationArgumentsPostfix))); + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Features/ContinueSaveFile/Patches/SandBoxSubModulePatch.cs b/src/Bannerlord.BLSE/Features/ContinueSaveFile/Patches/SandBoxSubModulePatch.cs index ef2a485..94033ce 100644 --- a/src/Bannerlord.BLSE/Features/ContinueSaveFile/Patches/SandBoxSubModulePatch.cs +++ b/src/Bannerlord.BLSE/Features/ContinueSaveFile/Patches/SandBoxSubModulePatch.cs @@ -22,53 +22,53 @@ internal static class SandBoxSubModulePatch public static bool Enable(Harmony harmony) { - _harmony = harmony; + _harmony = harmony; - return harmony.TryPatch( - AccessTools2.DeclaredMethod("SandBox.SandBoxSubModule:OnInitialState"), - prefix: AccessTools2.DeclaredMethod(typeof(SandBoxSubModulePatch), nameof(OnInitialStatePrefix))); - } + return harmony.TryPatch( + AccessTools2.DeclaredMethod("SandBox.SandBoxSubModule:OnInitialState"), + prefix: AccessTools2.DeclaredMethod(typeof(SandBoxSubModulePatch), nameof(OnInitialStatePrefix))); + } private static bool OnInitialStatePrefix(MBSubModuleBase __instance) { - static void FailedToLoad(string message) - { - try - { - InformationManagerWrapper.ShowInquiry("Warning!", message); - } - catch (Exception) - { - MessageBoxDialog.Show(message, "Warning!"); - } - } - - if (AccessTools2.GetDelegate("SandBox.SandBoxSaveHelper:TryLoadSave") is not { } tryLoadSave) return true; - if (GetSaveGameArg?.Invoke(Module.CurrentModule.StartupInfo) is not { } saveFileName) return true; - if (saveFileName.EndsWith(".sav", StringComparison.OrdinalIgnoreCase)) saveFileName = saveFileName.Remove(saveFileName.Length - 4, 4); - if (MBSaveLoad.GetSaveFileWithName(saveFileName) is not { } saveFile) - { - FailedToLoad($"Failed to load Save!\nFailed to find save '{saveFileName}'!"); - return true; - } - if (AccessTools2.TypeByName("SandBox.SandBoxSubModule") is not { } sandBoxSubModuleType) + static void FailedToLoad(string message) + { + try { - FailedToLoad($"Failed to load Save!\nFailed to find 'SandBox' module!"); - return true; + InformationManagerWrapper.ShowInquiry("Warning!", message); } - if (AccessTools2.GetDelegate>(__instance, sandBoxSubModuleType, "StartGame") is not { } startGame) + catch (Exception) { - FailedToLoad($"Failed to load Save!\nUnexpected 'SandBox' issue! 'StartGame' method not found!"); - return true; + MessageBoxDialog.Show(message, "Warning!"); } + } + + if (AccessTools2.GetDelegate("SandBox.SandBoxSaveHelper:TryLoadSave") is not { } tryLoadSave) return true; + if (GetSaveGameArg?.Invoke(Module.CurrentModule.StartupInfo) is not { } saveFileName) return true; + if (saveFileName.EndsWith(".sav", StringComparison.OrdinalIgnoreCase)) saveFileName = saveFileName.Remove(saveFileName.Length - 4, 4); + if (MBSaveLoad.GetSaveFileWithName(saveFileName) is not { } saveFile) + { + FailedToLoad($"Failed to load Save!\nFailed to find save '{saveFileName}'!"); + return true; + } + if (AccessTools2.TypeByName("SandBox.SandBoxSubModule") is not { } sandBoxSubModuleType) + { + FailedToLoad($"Failed to load Save!\nFailed to find 'SandBox' module!"); + return true; + } + if (AccessTools2.GetDelegate>(__instance, sandBoxSubModuleType, "StartGame") is not { } startGame) + { + FailedToLoad($"Failed to load Save!\nUnexpected 'SandBox' issue! 'StartGame' method not found!"); + return true; + } - using (var _ = new InformationManagerConfirmInquiryHandler()) - tryLoadSave(saveFile, startGame); + using (var _ = new InformationManagerConfirmInquiryHandler()) + tryLoadSave(saveFile, startGame); - _harmony?.Unpatch( - AccessTools2.DeclaredMethod("SandBox.SandBoxSubModule:OnInitialState"), - AccessTools2.DeclaredMethod(typeof(SandBoxSubModulePatch), nameof(OnInitialStatePrefix))); + _harmony?.Unpatch( + AccessTools2.DeclaredMethod("SandBox.SandBoxSubModule:OnInitialState"), + AccessTools2.DeclaredMethod(typeof(SandBoxSubModulePatch), nameof(OnInitialStatePrefix))); - return false; - } + return false; + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Features/ExceptionInterceptor/ExceptionInterceptorFeature.cs b/src/Bannerlord.BLSE/Features/ExceptionInterceptor/ExceptionInterceptorFeature.cs index 6274ad4..a1d5f48 100644 --- a/src/Bannerlord.BLSE/Features/ExceptionInterceptor/ExceptionInterceptorFeature.cs +++ b/src/Bannerlord.BLSE/Features/ExceptionInterceptor/ExceptionInterceptorFeature.cs @@ -23,55 +23,55 @@ public static class ExceptionInterceptorFeature public static void Enable() { - AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException; - OnException += HandleException; - } + AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException; + OnException += HandleException; + } public static void EnableAutoGens() { - AppDomain.CurrentDomain.AssemblyLoad += CurrentDomainOnAssemblyLoad; - FinalizerGlobal.Enable(ExceptionHandler, FinalizerMethod); - } + AppDomain.CurrentDomain.AssemblyLoad += CurrentDomainOnAssemblyLoad; + FinalizerGlobal.Enable(ExceptionHandler, FinalizerMethod); + } public static void Disable() { - AppDomain.CurrentDomain.UnhandledException -= CurrentDomainOnUnhandledException; - OnException -= HandleException; - AppDomain.CurrentDomain.AssemblyLoad -= CurrentDomainOnAssemblyLoad; - ExceptionHandler.UnpatchAll(ExceptionHandler.Id); - } + AppDomain.CurrentDomain.UnhandledException -= CurrentDomainOnUnhandledException; + OnException -= HandleException; + AppDomain.CurrentDomain.AssemblyLoad -= CurrentDomainOnAssemblyLoad; + ExceptionHandler.UnpatchAll(ExceptionHandler.Id); + } private static void CurrentDomainOnAssemblyLoad(object sender, AssemblyLoadEventArgs args) { - var assembly = args.LoadedAssembly; - FinalizerGlobal.OnNewAssembly(ExceptionHandler, FinalizerMethod, assembly); - } + var assembly = args.LoadedAssembly; + FinalizerGlobal.OnNewAssembly(ExceptionHandler, FinalizerMethod, assembly); + } private static void Finalizer(Exception? __exception) { - if (__exception is not null) - HandleException(__exception); - } + if (__exception is not null) + HandleException(__exception); + } [HandleProcessCorruptedStateExceptions, SecurityCritical] private static void CurrentDomainOnUnhandledException(object? _, UnhandledExceptionEventArgs e) { - if (e.ExceptionObject is Exception exception) - OnException?.Invoke(exception); - } + if (e.ExceptionObject is Exception exception) + OnException?.Invoke(exception); + } private static void HandleException(Exception exception) { - try + try + { + foreach (var type in TypeFinder.GetInterceptorTypes(typeof(BLSEExceptionHandlerAttribute))) { - foreach (var type in TypeFinder.GetInterceptorTypes(typeof(BLSEExceptionHandlerAttribute))) + if (AccessTools2.GetDelegate(type, "OnException") is { } method) { - if (AccessTools2.GetDelegate(type, "OnException") is { } method) - { - method(exception); - } + method(exception); } } - catch (Exception) { /* ignore */ } } + catch (Exception) { /* ignore */ } + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Features/ExceptionInterceptor/FinalizerGlobal.cs b/src/Bannerlord.BLSE/Features/ExceptionInterceptor/FinalizerGlobal.cs index 78ec9a8..52f6c4d 100644 --- a/src/Bannerlord.BLSE/Features/ExceptionInterceptor/FinalizerGlobal.cs +++ b/src/Bannerlord.BLSE/Features/ExceptionInterceptor/FinalizerGlobal.cs @@ -35,21 +35,21 @@ internal static class FinalizerGlobal public static void Enable(Harmony harmony, MethodInfo finalizerMethod) { - var callbacksGeneratedTypes = AccessTools2.AllAssemblies().SelectMany(x => x.GetTypes().Where(y => y.Name.EndsWith("CallbacksGenerated"))); - var callbackGeneratedMethods = callbacksGeneratedTypes.SelectMany(AccessTools.GetDeclaredMethods) - .Where(x => !BlacklistedMethods.Contains(x.Name)) - .Where(x => !BlacklistedMethodStarts.Any(y => x.Name.StartsWith(y))); - foreach (var method in callbackGeneratedMethods.Where(x => x.GetCustomAttributesData().Any(y => y.AttributeType.Name == "MonoPInvokeCallbackAttribute"))) - harmony.Patch(method, finalizer: new HarmonyMethod(finalizerMethod)); - } + var callbacksGeneratedTypes = AccessTools2.AllAssemblies().SelectMany(x => x.GetTypes().Where(y => y.Name.EndsWith("CallbacksGenerated"))); + var callbackGeneratedMethods = callbacksGeneratedTypes.SelectMany(AccessTools.GetDeclaredMethods) + .Where(x => !BlacklistedMethods.Contains(x.Name)) + .Where(x => !BlacklistedMethodStarts.Any(y => x.Name.StartsWith(y))); + foreach (var method in callbackGeneratedMethods.Where(x => x.GetCustomAttributesData().Any(y => y.AttributeType.Name == "MonoPInvokeCallbackAttribute"))) + harmony.Patch(method, finalizer: new HarmonyMethod(finalizerMethod)); + } public static void OnNewAssembly(Harmony harmony, MethodInfo finalizerMethod, Assembly assembly) { - var callbacksGeneratedTypes = assembly.GetTypes().Where(y => y.Name.EndsWith("CallbacksGenerated")); - var callbackGeneratedMethods = callbacksGeneratedTypes.SelectMany(AccessTools.GetDeclaredMethods) - .Where(x => !BlacklistedMethods.Contains(x.Name)) - .Where(x => !BlacklistedMethodStarts.Any(y => x.Name.StartsWith(y))); - foreach (var method in callbackGeneratedMethods.Where(x => x.GetCustomAttributesData().Any(y => y.AttributeType.Name == "MonoPInvokeCallbackAttribute"))) - harmony.Patch(method, finalizer: new HarmonyMethod(finalizerMethod)); - } + var callbacksGeneratedTypes = assembly.GetTypes().Where(y => y.Name.EndsWith("CallbacksGenerated")); + var callbackGeneratedMethods = callbacksGeneratedTypes.SelectMany(AccessTools.GetDeclaredMethods) + .Where(x => !BlacklistedMethods.Contains(x.Name)) + .Where(x => !BlacklistedMethodStarts.Any(y => x.Name.StartsWith(y))); + foreach (var method in callbackGeneratedMethods.Where(x => x.GetCustomAttributesData().Any(y => y.AttributeType.Name == "MonoPInvokeCallbackAttribute"))) + harmony.Patch(method, finalizer: new HarmonyMethod(finalizerMethod)); + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Features/ExceptionInterceptor/FinalizerSimple.cs b/src/Bannerlord.BLSE/Features/ExceptionInterceptor/FinalizerSimple.cs index 59a9540..13bbe77 100644 --- a/src/Bannerlord.BLSE/Features/ExceptionInterceptor/FinalizerSimple.cs +++ b/src/Bannerlord.BLSE/Features/ExceptionInterceptor/FinalizerSimple.cs @@ -27,14 +27,14 @@ internal static class FinalizerSimple public static void Enable(Harmony harmony, MethodInfo finalizerMethod) { - harmony.Patch(ModuleInitializeMethod, finalizer: new HarmonyMethod(finalizerMethod)); + harmony.Patch(ModuleInitializeMethod, finalizer: new HarmonyMethod(finalizerMethod)); - harmony.Patch(ManagedApplicationTickMethod, finalizer: new HarmonyMethod(finalizerMethod)); + harmony.Patch(ManagedApplicationTickMethod, finalizer: new HarmonyMethod(finalizerMethod)); - harmony.Patch(ScreenManagerPreTickMethod, finalizer: new HarmonyMethod(finalizerMethod)); - harmony.Patch(ScreenManagerTickMethod, finalizer: new HarmonyMethod(finalizerMethod)); - harmony.Patch(ScreenManagerLateTickMethod, finalizer: new HarmonyMethod(finalizerMethod)); + harmony.Patch(ScreenManagerPreTickMethod, finalizer: new HarmonyMethod(finalizerMethod)); + harmony.Patch(ScreenManagerTickMethod, finalizer: new HarmonyMethod(finalizerMethod)); + harmony.Patch(ScreenManagerLateTickMethod, finalizer: new HarmonyMethod(finalizerMethod)); - harmony.Patch(ManagedScriptHolderTickComponentsMethod, finalizer: new HarmonyMethod(finalizerMethod)); - } + harmony.Patch(ManagedScriptHolderTickComponentsMethod, finalizer: new HarmonyMethod(finalizerMethod)); + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Features/Interceptor/InterceptorFeature.cs b/src/Bannerlord.BLSE/Features/Interceptor/InterceptorFeature.cs index 565c624..445d0dc 100644 --- a/src/Bannerlord.BLSE/Features/Interceptor/InterceptorFeature.cs +++ b/src/Bannerlord.BLSE/Features/Interceptor/InterceptorFeature.cs @@ -15,30 +15,30 @@ public static class InterceptorFeature public static void Enable(Harmony harmony) { - ModulePatch.OnInitializeSubModulesPrefix += OnInitializeSubModulesPrefix; - ModulePatch.OnLoadSubModulesPostfix += OnLoadSubModulesPostfix; - ModulePatch.Enable(harmony); - } + ModulePatch.OnInitializeSubModulesPrefix += OnInitializeSubModulesPrefix; + ModulePatch.OnLoadSubModulesPostfix += OnLoadSubModulesPostfix; + ModulePatch.Enable(harmony); + } private static void OnInitializeSubModulesPrefix() { - foreach (var type in TypeFinder.GetInterceptorTypes(typeof(BLSEInterceptorAttribute))) + foreach (var type in TypeFinder.GetInterceptorTypes(typeof(BLSEInterceptorAttribute))) + { + if (AccessTools2.GetDelegate(type, "OnInitializeSubModulesPrefix", logErrorInTrace: false) is { } method) { - if (AccessTools2.GetDelegate(type, "OnInitializeSubModulesPrefix", logErrorInTrace: false) is { } method) - { - method(); - } + method(); } } + } private static void OnLoadSubModulesPostfix() { - foreach (var type in TypeFinder.GetInterceptorTypes(typeof(BLSEInterceptorAttribute))) + foreach (var type in TypeFinder.GetInterceptorTypes(typeof(BLSEInterceptorAttribute))) + { + if (AccessTools2.GetDelegate(type, "OnLoadSubModulesPostfix", logErrorInTrace: false) is { } method) { - if (AccessTools2.GetDelegate(type, "OnLoadSubModulesPostfix", logErrorInTrace: false) is { } method) - { - method(); - } + method(); } } + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Features/Interceptor/Patches/ModulePatch.cs b/src/Bannerlord.BLSE/Features/Interceptor/Patches/ModulePatch.cs index 8f45917..a8a4e93 100644 --- a/src/Bannerlord.BLSE/Features/Interceptor/Patches/ModulePatch.cs +++ b/src/Bannerlord.BLSE/Features/Interceptor/Patches/ModulePatch.cs @@ -17,38 +17,38 @@ internal static class ModulePatch public static bool Enable(Harmony harmony) { - _harmony = harmony; + _harmony = harmony; - var res1 = harmony.TryPatch( - AccessTools2.Method(typeof(Module), "LoadSubModules"), - postfix: AccessTools2.Method(typeof(ModulePatch), nameof(LoadSubModulesPostfix))); - if (!res1) return false; + var res1 = harmony.TryPatch( + AccessTools2.Method(typeof(Module), "LoadSubModules"), + postfix: AccessTools2.Method(typeof(ModulePatch), nameof(LoadSubModulesPostfix))); + if (!res1) return false; - var res2 = harmony.TryPatch( - AccessTools2.Method(typeof(Module), "InitializeSubModules"), - prefix: AccessTools2.Method(typeof(ModulePatch), nameof(InitializeSubModulesPrefix))); - if (!res2) return false; + var res2 = harmony.TryPatch( + AccessTools2.Method(typeof(Module), "InitializeSubModules"), + prefix: AccessTools2.Method(typeof(ModulePatch), nameof(InitializeSubModulesPrefix))); + if (!res2) return false; - return true; - } + return true; + } [MethodImpl(MethodImplOptions.NoInlining)] private static void InitializeSubModulesPrefix() { - OnInitializeSubModulesPrefix?.Invoke(); + OnInitializeSubModulesPrefix?.Invoke(); - _harmony?.Unpatch( - AccessTools2.Method(typeof(Module), "InitializeSubModules"), - AccessTools2.Method(typeof(ModulePatch), nameof(InitializeSubModulesPrefix))); - } + _harmony?.Unpatch( + AccessTools2.Method(typeof(Module), "InitializeSubModules"), + AccessTools2.Method(typeof(ModulePatch), nameof(InitializeSubModulesPrefix))); + } [MethodImpl(MethodImplOptions.NoInlining)] private static void LoadSubModulesPostfix() { - OnLoadSubModulesPostfix?.Invoke(); + OnLoadSubModulesPostfix?.Invoke(); - _harmony?.Unpatch( - AccessTools2.Method(typeof(Module), "LoadSubModules"), - AccessTools2.Method(typeof(ModulePatch), nameof(LoadSubModulesPostfix))); - } + _harmony?.Unpatch( + AccessTools2.Method(typeof(Module), "LoadSubModules"), + AccessTools2.Method(typeof(ModulePatch), nameof(LoadSubModulesPostfix))); + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Features/Xbox/Patches/ModulePatch.cs b/src/Bannerlord.BLSE/Features/Xbox/Patches/ModulePatch.cs index 9ad7225..c7a5558 100644 --- a/src/Bannerlord.BLSE/Features/Xbox/Patches/ModulePatch.cs +++ b/src/Bannerlord.BLSE/Features/Xbox/Patches/ModulePatch.cs @@ -15,43 +15,43 @@ internal static class ModulePatch { public static bool Enable(Harmony harmony) { - var asm = Assembly.LoadFrom("TaleWorlds.MountAndBlade.Platform.GDK.dll"); - Trace.Assert(asm is not null); + var asm = Assembly.LoadFrom("TaleWorlds.MountAndBlade.Platform.GDK.dll"); + Trace.Assert(asm is not null); - var res1 = harmony.TryPatch( - AccessTools2.Constructor(typeof(Module)), - prefix: AccessTools2.Method(typeof(ModulePatch), nameof(ShowedLoginScreenPrefix))); - if (!res1) return false; + var res1 = harmony.TryPatch( + AccessTools2.Constructor(typeof(Module)), + prefix: AccessTools2.Method(typeof(ModulePatch), nameof(ShowedLoginScreenPrefix))); + if (!res1) return false; - var res2 = harmony.TryPatch( - AccessTools2.DeclaredMethod("TaleWorlds.MountAndBlade.Platform.GDK.PlatformGDKSubModule:OnSubModuleLoad"), - prefix: AccessTools2.Method(typeof(ModulePatch), nameof(OnSubModuleLoadPrefix))); - if (!res2) return false; + var res2 = harmony.TryPatch( + AccessTools2.DeclaredMethod("TaleWorlds.MountAndBlade.Platform.GDK.PlatformGDKSubModule:OnSubModuleLoad"), + prefix: AccessTools2.Method(typeof(ModulePatch), nameof(OnSubModuleLoadPrefix))); + if (!res2) return false; - var res3 = harmony.TryPatch( - AccessTools2.DeclaredMethod("TaleWorlds.MountAndBlade.Platform.GDK.PlatformGDKSubModule:OnApplicationTick"), - prefix: AccessTools2.Method(typeof(ModulePatch), nameof(OnApplicationTickPrefix))); - if (!res3) return false; + var res3 = harmony.TryPatch( + AccessTools2.DeclaredMethod("TaleWorlds.MountAndBlade.Platform.GDK.PlatformGDKSubModule:OnApplicationTick"), + prefix: AccessTools2.Method(typeof(ModulePatch), nameof(OnApplicationTickPrefix))); + if (!res3) return false; - return true; - } + return true; + } [MethodImpl(MethodImplOptions.NoInlining)] private static void ShowedLoginScreenPrefix(ref bool ___ShowedLoginScreen) { - ___ShowedLoginScreen = true; - } + ___ShowedLoginScreen = true; + } [MethodImpl(MethodImplOptions.NoInlining)] private static bool OnSubModuleLoadPrefix() { - Common.PlatformFileHelper = new PlatformFileHelperPC("Mount and Blade II Bannerlord"); - return false; - } + Common.PlatformFileHelper = new PlatformFileHelperPC("Mount and Blade II Bannerlord"); + return false; + } [MethodImpl(MethodImplOptions.NoInlining)] private static bool OnApplicationTickPrefix() { - return false; - } + return false; + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Features/Xbox/XboxFeature.cs b/src/Bannerlord.BLSE/Features/Xbox/XboxFeature.cs index acb6928..b4041d9 100644 --- a/src/Bannerlord.BLSE/Features/Xbox/XboxFeature.cs +++ b/src/Bannerlord.BLSE/Features/Xbox/XboxFeature.cs @@ -15,9 +15,9 @@ public static class XboxFeature public static void Enable(Harmony harmony) { - if (Path.GetFileName(Directory.GetCurrentDirectory()) != "Gaming.Desktop.x64_Shipping_Client") - return; + if (Path.GetFileName(Directory.GetCurrentDirectory()) != "Gaming.Desktop.x64_Shipping_Client") + return; - ModulePatch.Enable(harmony); - } + ModulePatch.Enable(harmony); + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Utils/CommandLineSplitter.cs b/src/Bannerlord.BLSE/Utils/CommandLineSplitter.cs index 7c91af7..e58bf81 100644 --- a/src/Bannerlord.BLSE/Utils/CommandLineSplitter.cs +++ b/src/Bannerlord.BLSE/Utils/CommandLineSplitter.cs @@ -14,97 +14,97 @@ private enum Boundary public static IEnumerable SplitCommandLine(string commandLine) { - var startTokenIndex = 0; + var startTokenIndex = 0; - var pos = 0; + var pos = 0; - var seeking = Boundary.TokenStart; - var seekingQuote = Boundary.QuoteStart; + var seeking = Boundary.TokenStart; + var seekingQuote = Boundary.QuoteStart; - while (pos < commandLine.Length) - { - var c = commandLine[pos]; + while (pos < commandLine.Length) + { + var c = commandLine[pos]; - if (char.IsWhiteSpace(c)) + if (char.IsWhiteSpace(c)) + { + if (seekingQuote == Boundary.QuoteStart) { - if (seekingQuote == Boundary.QuoteStart) + switch (seeking) { - switch (seeking) - { - case Boundary.WordEnd: - yield return CurrentToken(); - startTokenIndex = pos; - seeking = Boundary.TokenStart; - break; - - case Boundary.TokenStart: - startTokenIndex = pos; - break; - } + case Boundary.WordEnd: + yield return CurrentToken(); + startTokenIndex = pos; + seeking = Boundary.TokenStart; + break; + + case Boundary.TokenStart: + startTokenIndex = pos; + break; } } - else if (c == '\"') + } + else if (c == '\"') + { + if (seeking == Boundary.TokenStart) { - if (seeking == Boundary.TokenStart) - { - switch (seekingQuote) - { - case Boundary.QuoteEnd: - yield return CurrentToken(); - startTokenIndex = pos; - seekingQuote = Boundary.QuoteStart; - break; - - case Boundary.QuoteStart: - startTokenIndex = pos + 1; - seekingQuote = Boundary.QuoteEnd; - break; - } - } - else + switch (seekingQuote) { - switch (seekingQuote) - { - case Boundary.QuoteEnd: - seekingQuote = Boundary.QuoteStart; - break; - - case Boundary.QuoteStart: - seekingQuote = Boundary.QuoteEnd; - break; - } + case Boundary.QuoteEnd: + yield return CurrentToken(); + startTokenIndex = pos; + seekingQuote = Boundary.QuoteStart; + break; + + case Boundary.QuoteStart: + startTokenIndex = pos + 1; + seekingQuote = Boundary.QuoteEnd; + break; } } - else if (seeking == Boundary.TokenStart && seekingQuote == Boundary.QuoteStart) + else { - seeking = Boundary.WordEnd; - startTokenIndex = pos; - } - - Advance(); - - if (IsAtEndOfInput()) - { - switch (seeking) + switch (seekingQuote) { - case Boundary.TokenStart: + case Boundary.QuoteEnd: + seekingQuote = Boundary.QuoteStart; break; - default: - yield return CurrentToken(); + + case Boundary.QuoteStart: + seekingQuote = Boundary.QuoteEnd; break; } } } + else if (seeking == Boundary.TokenStart && seekingQuote == Boundary.QuoteStart) + { + seeking = Boundary.WordEnd; + startTokenIndex = pos; + } - void Advance() => pos++; + Advance(); - string CurrentToken() + if (IsAtEndOfInput()) { - return commandLine.Substring(startTokenIndex, IndexOfEndOfToken()).Replace("\"", ""); + switch (seeking) + { + case Boundary.TokenStart: + break; + default: + yield return CurrentToken(); + break; + } } + } - int IndexOfEndOfToken() => pos - startTokenIndex; + void Advance() => pos++; - bool IsAtEndOfInput() => pos == commandLine.Length; + string CurrentToken() + { + return commandLine.Substring(startTokenIndex, IndexOfEndOfToken()).Replace("\"", ""); } + + int IndexOfEndOfToken() => pos - startTokenIndex; + + bool IsAtEndOfInput() => pos == commandLine.Length; + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Utils/GameUtils.cs b/src/Bannerlord.BLSE/Utils/GameUtils.cs index bb652b3..f5f8723 100644 --- a/src/Bannerlord.BLSE/Utils/GameUtils.cs +++ b/src/Bannerlord.BLSE/Utils/GameUtils.cs @@ -17,11 +17,11 @@ internal static class GameUtils public static string[]? GetModulesNames() { - var iUtil = IUtilField.Value?.Invoke(); - // Don't use Trace, as this is used in critical code like AssemblyResolver. - // The less we trigger custom code, the better - // A custom Trace listener will break the resolver if it will trigger a recursive assembly resolution - var getModulesCode = AccessTools2.GetDelegate(iUtil, "GetModulesCode", logErrorInTrace: false); - return iUtil is not null && getModulesCode is not null ? getModulesCode(iUtil)?.Split('*') : null; - } + var iUtil = IUtilField.Value?.Invoke(); + // Don't use Trace, as this is used in critical code like AssemblyResolver. + // The less we trigger custom code, the better + // A custom Trace listener will break the resolver if it will trigger a recursive assembly resolution + var getModulesCode = AccessTools2.GetDelegate(iUtil, "GetModulesCode", logErrorInTrace: false); + return iUtil is not null && getModulesCode is not null ? getModulesCode(iUtil)?.Split('*') : null; + } } \ No newline at end of file diff --git a/src/Bannerlord.BLSE/Utils/TypeFinder.cs b/src/Bannerlord.BLSE/Utils/TypeFinder.cs index 394337b..6dddbaa 100644 --- a/src/Bannerlord.BLSE/Utils/TypeFinder.cs +++ b/src/Bannerlord.BLSE/Utils/TypeFinder.cs @@ -14,45 +14,45 @@ internal static class TypeFinder { public static IEnumerable GetInterceptorTypes(Type attributeType) { - bool CheckType(Type type) => type.GetCustomAttributes() - .Any(att => string.Equals(att.GetType().FullName, attributeType.FullName, StringComparison.Ordinal)); + bool CheckType(Type type) => type.GetCustomAttributes() + .Any(att => string.Equals(att.GetType().FullName, attributeType.FullName, StringComparison.Ordinal)); - var dlls = new HashSet(GetLoadedModulePaths()); - foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Where(x => !x.IsDynamic && dlls.Contains(x.Location))) + var dlls = new HashSet(GetLoadedModulePaths()); + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Where(x => !x.IsDynamic && dlls.Contains(x.Location))) + { + IEnumerable enumerable; + try { - IEnumerable enumerable; - try - { - enumerable = assembly.GetTypes().Where(CheckType).ToArray(); // Force type resolution - } - catch (TypeLoadException) - { - enumerable = Enumerable.Empty(); // ignore the incompatibility, not our problem - } - catch (ReflectionTypeLoadException) - { - enumerable = Enumerable.Empty(); // ignore the incompatibility, not our problem - } - foreach (var type in enumerable) - { - yield return type; - } + enumerable = assembly.GetTypes().Where(CheckType).ToArray(); // Force type resolution + } + catch (TypeLoadException) + { + enumerable = Enumerable.Empty(); // ignore the incompatibility, not our problem + } + catch (ReflectionTypeLoadException) + { + enumerable = Enumerable.Empty(); // ignore the incompatibility, not our problem + } + foreach (var type in enumerable) + { + yield return type; } } + } private static IEnumerable GetLoadedModulePaths() { - var configName = Common.ConfigName; + var configName = Common.ConfigName; - foreach (var moduleInfo in ModuleInfoHelper.GetLoadedModules()) + foreach (var moduleInfo in ModuleInfoHelper.GetLoadedModules()) + { + foreach (var subModule in moduleInfo.SubModules) { - foreach (var subModule in moduleInfo.SubModules) + if (ModuleInfoHelper.CheckIfSubModuleCanBeLoaded(subModule, ApplicationPlatform.CurrentPlatform, ApplicationPlatform.CurrentRuntimeLibrary, DedicatedServerType.None, false)) { - if (ModuleInfoHelper.CheckIfSubModuleCanBeLoaded(subModule, ApplicationPlatform.CurrentPlatform, ApplicationPlatform.CurrentRuntimeLibrary, DedicatedServerType.None, false)) - { - yield return System.IO.Path.GetFullPath(System.IO.Path.Combine(moduleInfo.Path, "bin", configName, subModule.DLLName)); - } + yield return System.IO.Path.GetFullPath(System.IO.Path.Combine(moduleInfo.Path, "bin", configName, subModule.DLLName)); } } } + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/Helpers/ConfigReader.cs b/src/Bannerlord.LauncherEx/Helpers/ConfigReader.cs index 668adfc..8251958 100644 --- a/src/Bannerlord.LauncherEx/Helpers/ConfigReader.cs +++ b/src/Bannerlord.LauncherEx/Helpers/ConfigReader.cs @@ -17,46 +17,46 @@ internal static class ConfigReader public static Dictionary GetGameOptions(Func readFileContent) { - var dict = new Dictionary(); - if (readFileContent(GameConfigPath) is not { } data) return dict; - try - { - var content = Encoding.UTF8.GetString(data); - if (content.StartsWith(BOMMarkUtf8, StringComparison.Ordinal)) - content = content.Remove(0, BOMMarkUtf8.Length); + var dict = new Dictionary(); + if (readFileContent(GameConfigPath) is not { } data) return dict; + try + { + var content = Encoding.UTF8.GetString(data); + if (content.StartsWith(BOMMarkUtf8, StringComparison.Ordinal)) + content = content.Remove(0, BOMMarkUtf8.Length); - foreach (var keyValue in content.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries)) - { - var split = keyValue.Split(new[] { "=" }, StringSplitOptions.RemoveEmptyEntries); - if (split.Length != 2) continue; - var key = split[0].Trim(); - var value = split[1].Trim(); - dict[key] = value; - } + foreach (var keyValue in content.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries)) + { + var split = keyValue.Split(new[] { "=" }, StringSplitOptions.RemoveEmptyEntries); + if (split.Length != 2) continue; + var key = split[0].Trim(); + var value = split[1].Trim(); + dict[key] = value; } - catch (Exception) { /* ignore */ } - return dict; } + catch (Exception) { /* ignore */ } + return dict; + } public static Dictionary GetEngineOptions(Func readFileContent) { - var dict = new Dictionary(); - if (readFileContent(EngineConfigPath) is not { } data) return dict; - try - { - var content = Encoding.UTF8.GetString(data); - if (content.StartsWith(BOMMarkUtf8, StringComparison.Ordinal)) - content = content.Remove(0, BOMMarkUtf8.Length); + var dict = new Dictionary(); + if (readFileContent(EngineConfigPath) is not { } data) return dict; + try + { + var content = Encoding.UTF8.GetString(data); + if (content.StartsWith(BOMMarkUtf8, StringComparison.Ordinal)) + content = content.Remove(0, BOMMarkUtf8.Length); - foreach (var keyValue in content.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries)) - { - var split = keyValue.Split(new[] { "=" }, StringSplitOptions.RemoveEmptyEntries); - if (split.Length != 2) continue; - var key = split[0].Trim(); - var value = split[1].Trim(); - dict[key] = value; - } + foreach (var keyValue in content.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries)) + { + var split = keyValue.Split(new[] { "=" }, StringSplitOptions.RemoveEmptyEntries); + if (split.Length != 2) continue; + var key = split[0].Trim(); + var value = split[1].Trim(); + dict[key] = value; } - catch (Exception) { /* ignore */ } - return dict; } + catch (Exception) { /* ignore */ } + return dict; + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/Helpers/Integrations.cs b/src/Bannerlord.LauncherEx/Helpers/Integrations.cs index 4ea86ef..3b37284 100644 --- a/src/Bannerlord.LauncherEx/Helpers/Integrations.cs +++ b/src/Bannerlord.LauncherEx/Helpers/Integrations.cs @@ -12,10 +12,10 @@ public static class Integrations static Integrations() { - if (Process.GetCurrentProcess().ParentProcess() is { MainModule.FileVersionInfo.OriginalFilename: "ModOrganizer.exe", MainModule.FileName: { } path }) - { - IsModOrganizer2 = true; - ModOrganizer2Path = Path.GetDirectoryName(path); - } + if (Process.GetCurrentProcess().ParentProcess() is { MainModule.FileVersionInfo.OriginalFilename: "ModOrganizer.exe", MainModule.FileName: { } path }) + { + IsModOrganizer2 = true; + ModOrganizer2Path = Path.GetDirectoryName(path); } + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/Helpers/UI/IRef.cs b/src/Bannerlord.LauncherEx/Helpers/UI/IRef.cs index 26f7df4..0f1416b 100644 --- a/src/Bannerlord.LauncherEx/Helpers/UI/IRef.cs +++ b/src/Bannerlord.LauncherEx/Helpers/UI/IRef.cs @@ -33,37 +33,37 @@ public object? Value get => PropertyInfo.GetValue(Instance); set { - if (PropertyInfo.CanWrite) - { - PropertyInfo.SetValue(Instance, value); - OnPropertyChanged(); - } + if (PropertyInfo.CanWrite) + { + PropertyInfo.SetValue(Instance, value); + OnPropertyChanged(); } + } } public PropertyRef(PropertyInfo propInfo, object instance) { - PropertyInfo = propInfo; - Instance = instance; - } + PropertyInfo = propInfo; + Instance = instance; + } private void OnPropertyChanged([CallerMemberName] string? propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); public bool Equals(PropertyRef? other) { - if (other is null) return false; - if (ReferenceEquals(this, other)) return true; - return PropertyInfo.Equals(other.PropertyInfo) && Instance.Equals(other.Instance); - } + if (other is null) return false; + if (ReferenceEquals(this, other)) return true; + return PropertyInfo.Equals(other.PropertyInfo) && Instance.Equals(other.Instance); + } /// public override bool Equals(object? obj) { - if (obj is null) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != GetType()) return false; - return Equals((PropertyRef) obj); - } + if (obj is null) return false; + if (ReferenceEquals(this, obj)) return true; + if (obj.GetType() != GetType()) return false; + return Equals((PropertyRef) obj); + } /// public override int GetHashCode() => PropertyInfo.GetHashCode() ^ Instance.GetHashCode(); public static bool operator ==(PropertyRef? left, PropertyRef? right) => Equals(left, right); @@ -82,19 +82,19 @@ public object? Value get => _value; set { - if (value is T val && !Equals(_value, val)) - { - _value = val; - OnPropertyChanged(); - } + if (value is T val && !Equals(_value, val)) + { + _value = val; + OnPropertyChanged(); } + } } public StorageRef(T? value) { - _value = value; - Type = value?.GetType() ?? typeof(T); - } + _value = value; + Type = value?.GetType() ?? typeof(T); + } private void OnPropertyChanged([CallerMemberName] string? propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); @@ -116,19 +116,19 @@ public object? Value get => _getter(); set { - if (_setter is not null && value is T val) - { - _setter(val); - OnPropertyChanged(); - } + if (_setter is not null && value is T val) + { + _setter(val); + OnPropertyChanged(); } + } } public ProxyRef(Func getter, Action? setter) { - _getter = getter ?? throw new ArgumentNullException(nameof(getter)); - _setter = setter; - } + _getter = getter ?? throw new ArgumentNullException(nameof(getter)); + _setter = setter; + } protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); @@ -136,27 +136,27 @@ protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName /// public bool Equals(ProxyRef? other) { - if (other is null) return false; - if (ReferenceEquals(this, other)) return true; - return _getter.Equals(other._getter) && Equals(_setter, other._setter); - } + if (other is null) return false; + if (ReferenceEquals(this, other)) return true; + return _getter.Equals(other._getter) && Equals(_setter, other._setter); + } /// public override bool Equals(object? obj) { - if (obj is null) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != GetType()) return false; - return Equals((ProxyRef) obj); - } + if (obj is null) return false; + if (ReferenceEquals(this, obj)) return true; + if (obj.GetType() != GetType()) return false; + return Equals((ProxyRef) obj); + } /// public override int GetHashCode() { - var hash = 269; - hash = (hash * 47) + _getter.GetHashCode(); - if (_setter is not null) - hash = (hash * 47) + _setter.GetHashCode(); - return hash; - } + var hash = 269; + hash = (hash * 47) + _getter.GetHashCode(); + if (_setter is not null) + hash = (hash * 47) + _setter.GetHashCode(); + return hash; + } public static bool operator ==(ProxyRef? left, ProxyRef? right) => Equals(left, right); public static bool operator !=(ProxyRef? left, ProxyRef? right) => !Equals(left, right); } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/Helpers/UI/MixinManager.cs b/src/Bannerlord.LauncherEx/Helpers/UI/MixinManager.cs index aaffb24..b5ebdc9 100644 --- a/src/Bannerlord.LauncherEx/Helpers/UI/MixinManager.cs +++ b/src/Bannerlord.LauncherEx/Helpers/UI/MixinManager.cs @@ -30,39 +30,39 @@ internal abstract class BUTRViewModel : ViewModel { protected BUTRViewModel() { - var properties = GetType().GetProperties(AccessTools.all); - foreach (var propertyInfo in properties) + var properties = GetType().GetProperties(AccessTools.all); + foreach (var propertyInfo in properties) + { + if (propertyInfo.GetCustomAttribute() is { } attribute) { - if (propertyInfo.GetCustomAttribute() is { } attribute) - { - if (propertyInfo.GetMethod?.IsPrivate == true || propertyInfo.SetMethod?.IsPrivate == true) throw new Exception(); + if (propertyInfo.GetMethod?.IsPrivate == true || propertyInfo.SetMethod?.IsPrivate == true) throw new Exception(); - this.AddProperty(attribute.OverrideName ?? propertyInfo.Name, propertyInfo); - } + this.AddProperty(attribute.OverrideName ?? propertyInfo.Name, propertyInfo); } + } - var methods = GetType().GetMethods(AccessTools.all); - foreach (var methodInfo in methods) + var methods = GetType().GetMethods(AccessTools.all); + foreach (var methodInfo in methods) + { + if (methodInfo.GetCustomAttribute() is { } attribute) { - if (methodInfo.GetCustomAttribute() is { } attribute) - { - if (methodInfo.IsPrivate) throw new Exception(); + if (methodInfo.IsPrivate) throw new Exception(); - this.AddMethod(attribute.OverrideName ?? methodInfo.Name, methodInfo); - } + this.AddMethod(attribute.OverrideName ?? methodInfo.Name, methodInfo); } } + } protected new bool SetField(ref T field, T value, [CallerMemberName] string? propertyName = null) { - if (EqualityComparer.Default.Equals(field, value)) - { - return false; - } - field = value; - OnPropertyChanged(propertyName); - return true; + if (EqualityComparer.Default.Equals(field, value)) + { + return false; } + field = value; + OnPropertyChanged(propertyName); + return true; + } } internal abstract class ViewModelMixin @@ -77,36 +77,36 @@ internal abstract class ViewModelMixin protected ViewModelMixin(TViewModel vm) { - _vm = new WeakReference(vm); + _vm = new WeakReference(vm); - SetVMProperty(nameof(Mixin), GetType().Name); - foreach (var propertyInfo in GetType().GetProperties(AccessTools.all)) + SetVMProperty(nameof(Mixin), GetType().Name); + foreach (var propertyInfo in GetType().GetProperties(AccessTools.all)) + { + if (propertyInfo.GetCustomAttribute() is { } attribute) { - if (propertyInfo.GetCustomAttribute() is { } attribute) - { - if (propertyInfo.GetMethod?.IsPrivate == true || propertyInfo.SetMethod?.IsPrivate == true) throw new Exception(); - - var wrappedPropertyInfo = new WrappedPropertyInfo(propertyInfo, this); - vm.AddProperty(attribute.OverrideName ?? propertyInfo.Name, wrappedPropertyInfo); - wrappedPropertyInfo.PropertyChanged += (_, e) => ViewModel?.OnPropertyChanged(e.PropertyName); - } + if (propertyInfo.GetMethod?.IsPrivate == true || propertyInfo.SetMethod?.IsPrivate == true) throw new Exception(); + + var wrappedPropertyInfo = new WrappedPropertyInfo(propertyInfo, this); + vm.AddProperty(attribute.OverrideName ?? propertyInfo.Name, wrappedPropertyInfo); + wrappedPropertyInfo.PropertyChanged += (_, e) => ViewModel?.OnPropertyChanged(e.PropertyName); } - foreach (var methodInfo in GetType().GetMethods(AccessTools.all)) + } + foreach (var methodInfo in GetType().GetMethods(AccessTools.all)) + { + if (methodInfo.GetCustomAttribute() is { } attribute) { - if (methodInfo.GetCustomAttribute() is { } attribute) - { - if (methodInfo.IsPrivate) throw new Exception(); + if (methodInfo.IsPrivate) throw new Exception(); - var wrappedMethodInfo = new WrappedMethodInfo(methodInfo, this); - vm.AddMethod(attribute.OverrideName ?? methodInfo.Name, wrappedMethodInfo); - } + var wrappedMethodInfo = new WrappedMethodInfo(methodInfo, this); + vm.AddMethod(attribute.OverrideName ?? methodInfo.Name, wrappedMethodInfo); } } + } protected void OnPropertyChanged([CallerMemberName] string? propertyName = null) { - ViewModel?.OnPropertyChanged(propertyName); - } + ViewModel?.OnPropertyChanged(propertyName); + } protected void OnPropertyChangedWithValue(T value, [CallerMemberName] string? propertyName = null) where T : class { @@ -120,27 +120,27 @@ protected void OnPropertyChangedWithValue(T value, [CallerMemberName] string? protected bool SetField(ref T field, T value, [CallerMemberName] string? propertyName = null) { - if (EqualityComparer.Default.Equals(field, value)) - { - return false; - } - field = value; - OnPropertyChanged(propertyName); - return true; + if (EqualityComparer.Default.Equals(field, value)) + { + return false; } + field = value; + OnPropertyChanged(propertyName); + return true; + } protected void SetVMProperty(string property, string? overrideName = null) { - var propertyInfo = new WrappedPropertyInfo(AccessTools2.Property(GetType(), property)!, this); - ViewModel?.AddProperty(overrideName ?? property, propertyInfo); - propertyInfo.PropertyChanged += (_, e) => ViewModel?.OnPropertyChanged(e.PropertyName); - } + var propertyInfo = new WrappedPropertyInfo(AccessTools2.Property(GetType(), property)!, this); + ViewModel?.AddProperty(overrideName ?? property, propertyInfo); + propertyInfo.PropertyChanged += (_, e) => ViewModel?.OnPropertyChanged(e.PropertyName); + } protected void SetVMMethod(string method, string? overrideName = null) { - var methodInfo = new WrappedMethodInfo(AccessTools2.Method(GetType(), method)!, this); - ViewModel?.AddMethod(overrideName ?? method, methodInfo); - } + var methodInfo = new WrappedMethodInfo(AccessTools2.Method(GetType(), method)!, this); + ViewModel?.AddMethod(overrideName ?? method, methodInfo); + } } internal static class MixinManager @@ -149,28 +149,28 @@ internal static class MixinManager private static void AddMixin(ViewModel viewModel, object mixin) { - if (Mixins.TryGetValue(viewModel, out var list)) - { - list.Add(mixin); - } - else - { - Mixins.Add(viewModel, new List { mixin }); - } + if (Mixins.TryGetValue(viewModel, out var list)) + { + list.Add(mixin); } + else + { + Mixins.Add(viewModel, new List { mixin }); + } + } public static LauncherVM AddMixins(LauncherVM launcherVM) { - AddMixin(launcherVM.News, new LauncherNewsVMMixin(launcherVM.News)); - AddMixin(launcherVM.ModsData, new LauncherModsVMMixin(launcherVM.ModsData)); - AddMixin(launcherVM.ConfirmStart, new LauncherConfirmStartVMMixin(launcherVM.ConfirmStart)); - AddMixin(launcherVM, new LauncherVMMixin(launcherVM)); - return launcherVM; - } + AddMixin(launcherVM.News, new LauncherNewsVMMixin(launcherVM.News)); + AddMixin(launcherVM.ModsData, new LauncherModsVMMixin(launcherVM.ModsData)); + AddMixin(launcherVM.ConfirmStart, new LauncherConfirmStartVMMixin(launcherVM.ConfirmStart)); + AddMixin(launcherVM, new LauncherVMMixin(launcherVM)); + return launcherVM; + } public static LauncherConfirmStartVM AddMixin(LauncherConfirmStartVM confirmStartVM) { - AddMixin(confirmStartVM, new LauncherConfirmStartVMMixin(confirmStartVM)); - return confirmStartVM; - } + AddMixin(confirmStartVM, new LauncherConfirmStartVMMixin(confirmStartVM)); + return confirmStartVM; + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/Helpers/UI/PrefabExtensionManager.cs b/src/Bannerlord.LauncherEx/Helpers/UI/PrefabExtensionManager.cs index abce6f8..751cc2d 100644 --- a/src/Bannerlord.LauncherEx/Helpers/UI/PrefabExtensionManager.cs +++ b/src/Bannerlord.LauncherEx/Helpers/UI/PrefabExtensionManager.cs @@ -62,167 +62,167 @@ internal static class PrefabExtensionManager public static void RegisterPatch(string movie, Action patcher) { - if (string.IsNullOrEmpty(movie)) - { - return; - } - - MoviePatches.GetOrAdd(movie, _ => new List>()).Add(patcher); + if (string.IsNullOrEmpty(movie)) + { + return; } + MoviePatches.GetOrAdd(movie, _ => new List>()).Add(patcher); + } + public static void RegisterPatch(string movie, string? xpath, Action patcher) { - RegisterPatch(movie, document => + RegisterPatch(movie, document => + { + var node = document.SelectSingleNode(xpath ?? string.Empty); + if (node is null) { - var node = document.SelectSingleNode(xpath ?? string.Empty); - if (node is null) - { - return; - } + return; + } - patcher(node); - }); - } + patcher(node); + }); + } public static void RegisterPatch(string movie, string? xpath, PrefabExtensionCustomPatch patcher) { - RegisterPatch(movie, document => + RegisterPatch(movie, document => + { + var node = document.SelectSingleNode(xpath ?? string.Empty); + if (node is null) { - var node = document.SelectSingleNode(xpath ?? string.Empty); - if (node is null) - { - return; - } + return; + } - patcher.Apply(node); - }); - } + patcher.Apply(node); + }); + } public static void RegisterPatch(string movie, string? xpath, PrefabExtensionSetAttributePatch patch) { - RegisterPatch(movie, xpath, node => + RegisterPatch(movie, xpath, node => + { + var ownerDocument = node as XmlDocument ?? node.OwnerDocument; + if (ownerDocument is null) { - var ownerDocument = node as XmlDocument ?? node.OwnerDocument; - if (ownerDocument is null) - { - return; - } + return; + } - if (node.NodeType != XmlNodeType.Element) - { - return; - } + if (node.NodeType != XmlNodeType.Element) + { + return; + } - if (node.Attributes![patch.Attribute] is null) - { - var attribute = ownerDocument.CreateAttribute(patch.Attribute); - node.Attributes.Append(attribute); - } + if (node.Attributes![patch.Attribute] is null) + { + var attribute = ownerDocument.CreateAttribute(patch.Attribute); + node.Attributes.Append(attribute); + } - node.Attributes![patch.Attribute].Value = patch.Value; - }); - } + node.Attributes![patch.Attribute].Value = patch.Value; + }); + } public static void RegisterPatch(string movie, string? xpath, PrefabExtensionSetAttributesPatch patch) { - RegisterPatch(movie, xpath, node => + RegisterPatch(movie, xpath, node => + { + var ownerDocument = node as XmlDocument ?? node.OwnerDocument; + if (ownerDocument is null) { - var ownerDocument = node as XmlDocument ?? node.OwnerDocument; - if (ownerDocument is null) - { - return; - } + return; + } - if (node.NodeType != XmlNodeType.Element) - { - return; - } + if (node.NodeType != XmlNodeType.Element) + { + return; + } - foreach (var (attribute, value) in patch.Attributes) + foreach (var (attribute, value) in patch.Attributes) + { + if (node.Attributes![attribute] is null) { - if (node.Attributes![attribute] is null) - { - var attr = ownerDocument.CreateAttribute(attribute); - node.Attributes.Append(attr); - } - - node.Attributes![attribute].Value = value; + var attr = ownerDocument.CreateAttribute(attribute); + node.Attributes.Append(attr); } - }); - } + + node.Attributes![attribute].Value = value; + } + }); + } public static void RegisterPatch(string movie, string? xpath, PrefabExtensionReplacePatch patch) { - RegisterPatch(movie, xpath, node => + RegisterPatch(movie, xpath, node => + { + var ownerDocument = node as XmlDocument ?? node.OwnerDocument; + if (ownerDocument is null) { - var ownerDocument = node as XmlDocument ?? node.OwnerDocument; - if (ownerDocument is null) - { - return; - } + return; + } - if (node.ParentNode is null) - { - return; - } + if (node.ParentNode is null) + { + return; + } - var extensionNode = patch.GetPrefabExtension().DocumentElement; - if (extensionNode is null) - { - return; - } + var extensionNode = patch.GetPrefabExtension().DocumentElement; + if (extensionNode is null) + { + return; + } - var importedExtensionNode = ownerDocument.ImportNode(extensionNode, true); + var importedExtensionNode = ownerDocument.ImportNode(extensionNode, true); - node.ParentNode.ReplaceChild(importedExtensionNode, node); - }); - } + node.ParentNode.ReplaceChild(importedExtensionNode, node); + }); + } public static void RegisterPatch(string movie, string? xpath, PrefabExtensionInsertAsSiblingPatch patch) { - RegisterPatch(movie, xpath, node => + RegisterPatch(movie, xpath, node => + { + var ownerDocument = node as XmlDocument ?? node.OwnerDocument; + if (ownerDocument is null) { - var ownerDocument = node as XmlDocument ?? node.OwnerDocument; - if (ownerDocument is null) - { - return; - } + return; + } - if (node.ParentNode is null) - { - return; - } + if (node.ParentNode is null) + { + return; + } - var extensionNode = patch.GetPrefabExtension().DocumentElement; - if (extensionNode is null) - { - return; - } + var extensionNode = patch.GetPrefabExtension().DocumentElement; + if (extensionNode is null) + { + return; + } - var importedExtensionNode = ownerDocument.ImportNode(extensionNode, true); + var importedExtensionNode = ownerDocument.ImportNode(extensionNode, true); - switch (patch.Type) - { - case PrefabExtensionInsertAsSiblingPatch.InsertType.Append: - node.ParentNode.InsertAfter(importedExtensionNode, node); - break; + switch (patch.Type) + { + case PrefabExtensionInsertAsSiblingPatch.InsertType.Append: + node.ParentNode.InsertAfter(importedExtensionNode, node); + break; - case PrefabExtensionInsertAsSiblingPatch.InsertType.Prepend: - node.ParentNode.InsertBefore(importedExtensionNode, node); - break; - } - }); - } + case PrefabExtensionInsertAsSiblingPatch.InsertType.Prepend: + node.ParentNode.InsertBefore(importedExtensionNode, node); + break; + } + }); + } public static void ProcessMovieIfNeeded(string movie, XmlDocument document) { - if (!MoviePatches.TryGetValue(movie, out var patches)) - return; + if (!MoviePatches.TryGetValue(movie, out var patches)) + return; - foreach (var patch in patches) - { - patch(document); - } + foreach (var patch in patches) + { + patch(document); } + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/Mixins/LauncherVMMixin.cs b/src/Bannerlord.LauncherEx/Mixins/LauncherVMMixin.cs index d6632b5..bfbe935 100644 --- a/src/Bannerlord.LauncherEx/Mixins/LauncherVMMixin.cs +++ b/src/Bannerlord.LauncherEx/Mixins/LauncherVMMixin.cs @@ -54,18 +54,18 @@ public bool IsSingleplayer2 get => _state == TopTabs.Singleplayer; set { - if (value && _state != TopTabs.Singleplayer && ViewModel is not null) + if (value && _state != TopTabs.Singleplayer && ViewModel is not null) + { + if (_state == TopTabs.Options) { - if (_state == TopTabs.Options) - { - SaveOptions(); - } + SaveOptions(); + } - _state = TopTabs.Singleplayer; + _state = TopTabs.Singleplayer; - SetState(); - } + SetState(); } + } } [BUTRDataSourceProperty] @@ -74,18 +74,18 @@ public bool IsMultiplayer2 get => _state == TopTabs.Multiplayer; set { - if (value && _state != TopTabs.Multiplayer && ViewModel is not null) + if (value && _state != TopTabs.Multiplayer && ViewModel is not null) + { + if (_state == TopTabs.Options) { - if (_state == TopTabs.Options) - { - SaveOptions(); - } + SaveOptions(); + } - _state = TopTabs.Multiplayer; + _state = TopTabs.Multiplayer; - SetState(); - } + SetState(); } + } } [BUTRDataSourceProperty] @@ -94,13 +94,13 @@ public bool IsOptions get => _state == TopTabs.Options; set { - if (value && _state != TopTabs.Options && ViewModel is not null) - { - _state = TopTabs.Options; + if (value && _state != TopTabs.Options && ViewModel is not null) + { + _state = TopTabs.Options; - SetState(); - } + SetState(); } + } } [BUTRDataSourceProperty] @@ -109,18 +109,18 @@ public bool IsDigitalCompanion2 get => _state == TopTabs.DigitalCompanion; set { - if (value && _state != TopTabs.DigitalCompanion && ViewModel is not null) + if (value && _state != TopTabs.DigitalCompanion && ViewModel is not null) + { + if (_state == TopTabs.Options) { - if (_state == TopTabs.Options) - { - SaveOptions(); - } + SaveOptions(); + } - _state = TopTabs.DigitalCompanion; + _state = TopTabs.DigitalCompanion; - SetState(); - } + SetState(); } + } } [BUTRDataSourceProperty] @@ -129,12 +129,12 @@ public bool IsModsDataSelected get => _isModsDataSelected; set { - if (SetField(ref _isModsDataSelected, value)) - { - OnPropertyChanged(nameof(ShowImportExport)); - OnPropertyChanged(nameof(ShowContinueSingleplayerButton)); - } + if (SetField(ref _isModsDataSelected, value)) + { + OnPropertyChanged(nameof(ShowImportExport)); + OnPropertyChanged(nameof(ShowContinueSingleplayerButton)); } + } } private bool _isModsDataSelected; @@ -144,13 +144,13 @@ public bool IsSavesDataSelected get => _isSavesDataSelected; set { - if (SetField(ref _isSavesDataSelected, value)) - { - OnPropertyChanged(nameof(ShowPlaySingleplayerButton)); - OnPropertyChanged(nameof(ShowContinueSingleplayerButton)); - OnPropertyChanged(nameof(ShowImportExport)); - } + if (SetField(ref _isSavesDataSelected, value)) + { + OnPropertyChanged(nameof(ShowPlaySingleplayerButton)); + OnPropertyChanged(nameof(ShowContinueSingleplayerButton)); + OnPropertyChanged(nameof(ShowImportExport)); } + } } private bool _isSavesDataSelected; @@ -278,263 +278,263 @@ public bool IsSavesDataSelected public LauncherVMMixin(LauncherVM launcherVM) : base(launcherVM) { - _launcherManagerHandler.RegisterStateProvider(() => new LauncherState(isSingleplayer: IsSingleplayer2)); + _launcherManagerHandler.RegisterStateProvider(() => new LauncherState(isSingleplayer: IsSingleplayer2)); - _userDataManager = UserDataManagerFieldRef?.Invoke(launcherVM); + _userDataManager = UserDataManagerFieldRef?.Invoke(launcherVM); - var blseMetadata = AccessTools2.TypeByName("Bannerlord.BLSE.BLSEInterceptorAttribute")?.Assembly.GetCustomAttributes(); - var launcherExMetadata = typeof(LauncherVMMixin).Assembly.GetCustomAttributes(); - _blseVersionText = $"BLSE v{blseMetadata?.FirstOrDefault(x => x.Key == "BLSEVersion")?.Value ?? "0.0.0.0"}"; - _butrLoaderVersionText = $"LauncherEx v{launcherExMetadata.FirstOrDefault(x => x.Key == "LauncherExVersion")?.Value ?? "0.0.0.0"}"; + var blseMetadata = AccessTools2.TypeByName("Bannerlord.BLSE.BLSEInterceptorAttribute")?.Assembly.GetCustomAttributes(); + var launcherExMetadata = typeof(LauncherVMMixin).Assembly.GetCustomAttributes(); + _blseVersionText = $"BLSE v{blseMetadata?.FirstOrDefault(x => x.Key == "BLSEVersion")?.Value ?? "0.0.0.0"}"; + _butrLoaderVersionText = $"LauncherEx v{launcherExMetadata.FirstOrDefault(x => x.Key == "LauncherExVersion")?.Value ?? "0.0.0.0"}"; - _optionsEngineData = new BUTRLauncherOptionsVM(OptionsType.Engine, SaveUserData, RefreshOptions); - _optionsGameData = new BUTRLauncherOptionsVM(OptionsType.Game, SaveUserData, RefreshOptions); - _optionsLauncherData = new BUTRLauncherOptionsVM(OptionsType.Launcher, SaveUserData, RefreshOptions); + _optionsEngineData = new BUTRLauncherOptionsVM(OptionsType.Engine, SaveUserData, RefreshOptions); + _optionsGameData = new BUTRLauncherOptionsVM(OptionsType.Game, SaveUserData, RefreshOptions); + _optionsLauncherData = new BUTRLauncherOptionsVM(OptionsType.Launcher, SaveUserData, RefreshOptions); - if (launcherVM.GetPropertyValue(nameof(LauncherVM.ModsData)) is LauncherModsVM lmvm && lmvm.GetMixin() is { } mixin) - { - _launcherModsVMMixin = mixin; + if (launcherVM.GetPropertyValue(nameof(LauncherVM.ModsData)) is LauncherModsVM lmvm && lmvm.GetMixin() is { } mixin) + { + _launcherModsVMMixin = mixin; - _savesData = new BUTRLauncherSavesVM(mixin.GetModuleById, mixin.GetModuleByName); - _savesData.PropertyChanged += (_, args) => + _savesData = new BUTRLauncherSavesVM(mixin.GetModuleById, mixin.GetModuleByName); + _savesData.PropertyChanged += (_, args) => + { + if (args.PropertyName == "SaveSelected") { - if (args.PropertyName == "SaveSelected") - { - OnPropertyChanged(nameof(ShowImportExport)); - OnPropertyChanged(nameof(ShowContinueSingleplayerButton)); - } - }; - } + OnPropertyChanged(nameof(ShowImportExport)); + OnPropertyChanged(nameof(ShowContinueSingleplayerButton)); + } + }; + } - ShowRandomImage = !LauncherSettings.HideRandomImage; - ContentTabControlMarginRight = LauncherSettings.HideRandomImage ? 5 : 114; - BackgroundHeight = LauncherSettings.BigMode ? 700 : 581; + ShowRandomImage = !LauncherSettings.HideRandomImage; + ContentTabControlMarginRight = LauncherSettings.HideRandomImage ? 5 : 114; + BackgroundHeight = LauncherSettings.BigMode ? 700 : 581; - IsDigitalCompanion2 = (bool?) launcherVM.GetPropertyValue("IsDigitalCompanion") ?? false; - IsMultiplayer2 = launcherVM.IsMultiplayer; - IsSingleplayer2 = launcherVM.IsSingleplayer; + IsDigitalCompanion2 = (bool?) launcherVM.GetPropertyValue("IsDigitalCompanion") ?? false; + IsMultiplayer2 = launcherVM.IsMultiplayer; + IsSingleplayer2 = launcherVM.IsSingleplayer; - Refresh?.Invoke(launcherVM); - } + Refresh?.Invoke(launcherVM); + } private void SetState() { - if (ViewModel is null) return; - - OnPropertyChanged(nameof(IsSingleplayer2)); - OnPropertyChanged(nameof(IsMultiplayer2)); - OnPropertyChanged(nameof(IsOptions)); - OnPropertyChanged(nameof(IsDigitalCompanion2)); - OnPropertyChanged(nameof(ShowBUTRLoaderVersionText)); - OnPropertyChanged(nameof(PlayButtonAlignment)); - OnPropertyChanged(nameof(ShowNews)); - OnPropertyChanged(nameof(ShowMods)); - OnPropertyChanged(nameof(ShowPlaySingleplayerButton)); - OnPropertyChanged(nameof(ShowContinueSingleplayerButton)); - - ViewModel.IsSingleplayer = IsSingleplayer2; - ViewModel.IsMultiplayer = IsMultiplayer2; - SetIsDigitalCompanion?.Invoke(ViewModel, IsDigitalCompanion2); - - RandomImageSwitch = !RandomImageSwitch; - - ViewModel.News.SetPropertyValue(nameof(LauncherNewsVMMixin.IsDisabled2), !ShowNews); - ViewModel.ModsData.SetPropertyValue(nameof(LauncherModsVMMixin.IsDisabled2), !ShowMods); - if (SavesData is not null) - SavesData.IsDisabled = !IsSingleplayer2; - OptionsLauncherData.IsDisabled = !IsOptions; - OptionsGameData.IsDisabled = !IsOptions; - OptionsEngineData.IsDisabled = !IsOptions; - if (IsOptions) - RefreshOptions(); - - ContentTabControlMarginBottom = IsOptions ? 65 : 114; - BUTRLoaderVersionMarginBottom = IsOptions ? 45 : 90; - BLSEVersionMarginBottom = IsOptions ? 25 : 70; - DividerMarginBottom = IsOptions ? 64 : 113; - } + if (ViewModel is null) return; + + OnPropertyChanged(nameof(IsSingleplayer2)); + OnPropertyChanged(nameof(IsMultiplayer2)); + OnPropertyChanged(nameof(IsOptions)); + OnPropertyChanged(nameof(IsDigitalCompanion2)); + OnPropertyChanged(nameof(ShowBUTRLoaderVersionText)); + OnPropertyChanged(nameof(PlayButtonAlignment)); + OnPropertyChanged(nameof(ShowNews)); + OnPropertyChanged(nameof(ShowMods)); + OnPropertyChanged(nameof(ShowPlaySingleplayerButton)); + OnPropertyChanged(nameof(ShowContinueSingleplayerButton)); + + ViewModel.IsSingleplayer = IsSingleplayer2; + ViewModel.IsMultiplayer = IsMultiplayer2; + SetIsDigitalCompanion?.Invoke(ViewModel, IsDigitalCompanion2); + + RandomImageSwitch = !RandomImageSwitch; + + ViewModel.News.SetPropertyValue(nameof(LauncherNewsVMMixin.IsDisabled2), !ShowNews); + ViewModel.ModsData.SetPropertyValue(nameof(LauncherModsVMMixin.IsDisabled2), !ShowMods); + if (SavesData is not null) + SavesData.IsDisabled = !IsSingleplayer2; + OptionsLauncherData.IsDisabled = !IsOptions; + OptionsGameData.IsDisabled = !IsOptions; + OptionsEngineData.IsDisabled = !IsOptions; + if (IsOptions) + RefreshOptions(); + + ContentTabControlMarginBottom = IsOptions ? 65 : 114; + BUTRLoaderVersionMarginBottom = IsOptions ? 45 : 90; + BLSEVersionMarginBottom = IsOptions ? 25 : 70; + DividerMarginBottom = IsOptions ? 64 : 113; + } public void RefreshOptions() { - OptionsLauncherData.Refresh(); - OptionsGameData.Refresh(); - OptionsEngineData.Refresh(); - } + OptionsLauncherData.Refresh(); + OptionsGameData.Refresh(); + OptionsEngineData.Refresh(); + } public void SaveUserData() { - if (ViewModel is null) return; + if (ViewModel is null) return; - ShowRandomImage = !LauncherSettings.HideRandomImage; - ContentTabControlMarginRight = LauncherSettings.HideRandomImage ? 5 : 114; - BackgroundHeight = LauncherSettings.BigMode ? 700 : 581; - UpdateAndSaveUserModsDataMethod?.Invoke(ViewModel, IsMultiplayer2); - } + ShowRandomImage = !LauncherSettings.HideRandomImage; + ContentTabControlMarginRight = LauncherSettings.HideRandomImage ? 5 : 114; + BackgroundHeight = LauncherSettings.BigMode ? 700 : 581; + UpdateAndSaveUserModsDataMethod?.Invoke(ViewModel, IsMultiplayer2); + } public void SaveOptions() { - OptionsLauncherData.Save(); - OptionsGameData.Save(); - OptionsEngineData.Save(); - } + OptionsLauncherData.Save(); + OptionsGameData.Save(); + OptionsEngineData.Save(); + } // Ensure save is triggered when launching the game [BUTRDataSourceMethod] public void ExecuteConfirmUnverifiedDLLStart() { - if (ViewModel is null) return; + if (ViewModel is null) return; - SaveUserData(); - ExecuteConfirmUnverifiedDLLStartOriginal?.Invoke(ViewModel); - } + SaveUserData(); + ExecuteConfirmUnverifiedDLLStartOriginal?.Invoke(ViewModel); + } [BUTRDataSourceMethod] public void ExecuteBeginHintImport() { - if (IsSingleplayer2 && IsModsDataSelected) - { - HintManager.ShowHint(new BUTRTextObject("{=Aws9irMU}Import Load Order")); - } - if (IsSingleplayer2 && IsSavesDataSelected) - { - HintManager.ShowHint(new BUTRTextObject("{=4wKr76gx}Import Save's Load Order")); - } + if (IsSingleplayer2 && IsModsDataSelected) + { + HintManager.ShowHint(new BUTRTextObject("{=Aws9irMU}Import Load Order")); + } + if (IsSingleplayer2 && IsSavesDataSelected) + { + HintManager.ShowHint(new BUTRTextObject("{=4wKr76gx}Import Save's Load Order")); } + } [BUTRDataSourceMethod] public void ExecuteBeginHintExport() { - if (IsSingleplayer2 && IsModsDataSelected) - { - HintManager.ShowHint(new BUTRTextObject("{=XdZGqnFW}Export Current Load Order")); - } - if (IsSingleplayer2 && IsSavesDataSelected) - { - HintManager.ShowHint(new BUTRTextObject("{=G55IdM6M}Export Save's Load Order")); - } + if (IsSingleplayer2 && IsModsDataSelected) + { + HintManager.ShowHint(new BUTRTextObject("{=XdZGqnFW}Export Current Load Order")); + } + if (IsSingleplayer2 && IsSavesDataSelected) + { + HintManager.ShowHint(new BUTRTextObject("{=G55IdM6M}Export Save's Load Order")); } + } [BUTRDataSourceMethod] public void ExecuteEndHint() { - HintManager.HideHint(); - } + HintManager.HideHint(); + } [BUTRDataSourceMethod] public void ExecuteImport() { - if (ViewModel is null || _launcherModsVMMixin is null || UpdateAndSaveUserModsDataMethod is null) return; + if (ViewModel is null || _launcherModsVMMixin is null || UpdateAndSaveUserModsDataMethod is null) return; - _currentModuleListHandler = new ModuleListHandler(_launcherManagerHandler); + _currentModuleListHandler = new ModuleListHandler(_launcherManagerHandler); - if (IsSingleplayer2 && IsModsDataSelected) + if (IsSingleplayer2 && IsModsDataSelected) + { + var thread = new Thread(() => { - var thread = new Thread(() => + _currentModuleListHandler.Import(result => { - _currentModuleListHandler.Import(result => - { - if (!result) return; - UpdateAndSaveUserModsDataMethod(ViewModel, false); - HintManager.ShowHint(new BUTRTextObject("{=eohqbvHU}Successfully imported list!")); - }); + if (!result) return; + UpdateAndSaveUserModsDataMethod(ViewModel, false); + HintManager.ShowHint(new BUTRTextObject("{=eohqbvHU}Successfully imported list!")); }); - thread.SetApartmentState(ApartmentState.STA); - thread.Start(); - thread.Join(); - } - if (IsSingleplayer2 && IsSavesDataSelected && SavesData?.Selected?.Name is { } saveName) + }); + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + thread.Join(); + } + if (IsSingleplayer2 && IsSavesDataSelected && SavesData?.Selected?.Name is { } saveName) + { + var thread = new Thread(() => { - var thread = new Thread(() => + _currentModuleListHandler.ImportSaveFile(saveName, result => { - _currentModuleListHandler.ImportSaveFile(saveName, result => - { - if (!result) return; - UpdateAndSaveUserModsDataMethod(ViewModel, false); - HintManager.ShowHint(new BUTRTextObject("{=eohqbvHU}Successfully imported list!")); - }); + if (!result) return; + UpdateAndSaveUserModsDataMethod(ViewModel, false); + HintManager.ShowHint(new BUTRTextObject("{=eohqbvHU}Successfully imported list!")); }); - thread.SetApartmentState(ApartmentState.STA); - thread.Start(); - thread.Join(); - } + }); + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + thread.Join(); } + } [BUTRDataSourceMethod] public void ExecuteExport() { - if (ViewModel is null || _launcherModsVMMixin is null) return; + if (ViewModel is null || _launcherModsVMMixin is null) return; - _currentModuleListHandler = new ModuleListHandler(_launcherManagerHandler); + _currentModuleListHandler = new ModuleListHandler(_launcherManagerHandler); - if (IsSingleplayer2 && IsModsDataSelected) + if (IsSingleplayer2 && IsModsDataSelected) + { + var thread = new Thread(() => { - var thread = new Thread(() => - { - _currentModuleListHandler.Export(); - }); - thread.SetApartmentState(ApartmentState.STA); - thread.Start(); - thread.Join(); - } - if (IsSingleplayer2 && IsSavesDataSelected && SavesData?.Selected?.Name is { } saveName) + _currentModuleListHandler.Export(); + }); + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + thread.Join(); + } + if (IsSingleplayer2 && IsSavesDataSelected && SavesData?.Selected?.Name is { } saveName) + { + var thread = new Thread(() => { - var thread = new Thread(() => - { - _currentModuleListHandler.ExportSaveFile(saveName); - }); - thread.SetApartmentState(ApartmentState.STA); - thread.Start(); - thread.Join(); - } + _currentModuleListHandler.ExportSaveFile(saveName); + }); + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + thread.Join(); } + } [BUTRDataSourceMethod(OverrideName = "ExecuteStartGame")] public void ExecuteStartGameOverride(int mode) { - if (ViewModel is null || ExecuteStartGame is null) return; + if (ViewModel is null || ExecuteStartGame is null) return; - if (IsSavesDataSelected && SavesData?.Selected is { } saveVM) + if (IsSavesDataSelected && SavesData?.Selected is { } saveVM) + { + _launcherManagerHandler.SetGameParameterSaveFile(saveVM.Name); + if (saveVM.HasWarning || saveVM.HasError) { - _launcherManagerHandler.SetGameParameterSaveFile(saveVM.Name); - if (saveVM.HasWarning || saveVM.HasError) + var description = new StringBuilder(); + if (saveVM.HasError) + { + description.Append(saveVM.ErrorHint?.Text ?? string.Empty); + } + + if (saveVM is { HasError: true, HasWarning: true }) { - var description = new StringBuilder(); - if (saveVM.HasError) - { - description.Append(saveVM.ErrorHint?.Text ?? string.Empty); - } - - if (saveVM is { HasError: true, HasWarning: true }) - { - description.Append("\n"); - } - - if (saveVM.HasWarning) - { - description.Append(saveVM.WarningHint?.Text ?? string.Empty); - } - - description.Append("\n\n"); - description.Append(new BUTRTextObject("{=MlYQ0uX7}An unstable experience could occur.")); description.Append("\n"); - description.Append(new BUTRTextObject("{=qvzptzrE}Do you wish to continue loading the save?")); + } - MessageBox?.Show(new BUTRTextObject("{=dDprK7Mz}WARNING").ToString(), description.ToString(), () => ExecuteStartGame(ViewModel, 0), null); - return; + if (saveVM.HasWarning) + { + description.Append(saveVM.WarningHint?.Text ?? string.Empty); } - ExecuteStartGame(ViewModel, 0); + description.Append("\n\n"); + description.Append(new BUTRTextObject("{=MlYQ0uX7}An unstable experience could occur.")); + description.Append("\n"); + description.Append(new BUTRTextObject("{=qvzptzrE}Do you wish to continue loading the save?")); + + MessageBox?.Show(new BUTRTextObject("{=dDprK7Mz}WARNING").ToString(), description.ToString(), () => ExecuteStartGame(ViewModel, 0), null); return; } - if (mode == 1) - { - _launcherManagerHandler.SetGameParameterContinueLastSaveFile(true); + ExecuteStartGame(ViewModel, 0); + return; + } - ExecuteStartGame(ViewModel, 1); - return; - } + if (mode == 1) + { + _launcherManagerHandler.SetGameParameterContinueLastSaveFile(true); - ExecuteStartGame(ViewModel, mode); + ExecuteStartGame(ViewModel, 1); + return; } + + ExecuteStartGame(ViewModel, mode); + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/Options/LauncherExData.cs b/src/Bannerlord.LauncherEx/Options/LauncherExData.cs index 6eac466..2c187af 100644 --- a/src/Bannerlord.LauncherEx/Options/LauncherExData.cs +++ b/src/Bannerlord.LauncherEx/Options/LauncherExData.cs @@ -9,18 +9,18 @@ public sealed class LauncherExData { public static LauncherExData? FromUserDataXml(string path) { - var xmlSerializer = new XmlSerializer(typeof(LauncherExData), new XmlRootAttribute("UserData")); - try - { - using var xmlReader = XmlReader.Create(path); - return (LauncherExData) xmlSerializer.Deserialize(xmlReader); - } - catch (Exception e) - { - Trace.WriteLine(e); - return null; - } + var xmlSerializer = new XmlSerializer(typeof(LauncherExData), new XmlRootAttribute("UserData")); + try + { + using var xmlReader = XmlReader.Create(path); + return (LauncherExData) xmlSerializer.Deserialize(xmlReader); } + catch (Exception e) + { + Trace.WriteLine(e); + return null; + } + } public bool AutomaticallyCheckForUpdates { get; set; } public bool FixCommonIssues { get; set; } @@ -48,16 +48,16 @@ public LauncherExData( bool disableCatchAutoGenExceptions, bool useVanillaCrashHandler) { - AutomaticallyCheckForUpdates = automaticallyCheckForUpdates; - FixCommonIssues = fixCommonIssues; - CompactModuleList = compactModuleList; - DisableBinaryCheck = disableBinaryCheck; - HideRandomImage = hideRandomImage; - BetaSorting = betaSorting; - BigMode = bigMode; - EnableDPIScaling = enableDPIScaling; - DisableCrashHandlerWhenDebuggerIsAttached = disableCrashHandlerWhenDebuggerIsAttached; - DisableCatchAutoGenExceptions = disableCatchAutoGenExceptions; - UseVanillaCrashHandler = useVanillaCrashHandler; - } + AutomaticallyCheckForUpdates = automaticallyCheckForUpdates; + FixCommonIssues = fixCommonIssues; + CompactModuleList = compactModuleList; + DisableBinaryCheck = disableBinaryCheck; + HideRandomImage = hideRandomImage; + BetaSorting = betaSorting; + BigMode = bigMode; + EnableDPIScaling = enableDPIScaling; + DisableCrashHandlerWhenDebuggerIsAttached = disableCrashHandlerWhenDebuggerIsAttached; + DisableCatchAutoGenExceptions = disableCatchAutoGenExceptions; + UseVanillaCrashHandler = useVanillaCrashHandler; + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/Patches/LauncherConfirmStartVMPatch.cs b/src/Bannerlord.LauncherEx/Patches/LauncherConfirmStartVMPatch.cs index 93042ee..854ebc4 100644 --- a/src/Bannerlord.LauncherEx/Patches/LauncherConfirmStartVMPatch.cs +++ b/src/Bannerlord.LauncherEx/Patches/LauncherConfirmStartVMPatch.cs @@ -11,16 +11,16 @@ internal static class LauncherConfirmStartVMPatch { public static bool Enable(Harmony harmony) { - var res1 = harmony.TryPatch( - AccessTools2.Method(typeof(LauncherConfirmStartVM), "EnableWith"), - prefix: AccessTools2.DeclaredMethod(typeof(LauncherConfirmStartVMPatch), nameof(EnableWithPrefix))); + var res1 = harmony.TryPatch( + AccessTools2.Method(typeof(LauncherConfirmStartVM), "EnableWith"), + prefix: AccessTools2.DeclaredMethod(typeof(LauncherConfirmStartVMPatch), nameof(EnableWithPrefix))); - return res1; - } + return res1; + } public static bool EnableWithPrefix(Action? ____onConfirm) { - ____onConfirm?.Invoke(); - return false; - } + ____onConfirm?.Invoke(); + return false; + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/Patches/LauncherModsVMPatch.cs b/src/Bannerlord.LauncherEx/Patches/LauncherModsVMPatch.cs index 792c10f..a80f66a 100644 --- a/src/Bannerlord.LauncherEx/Patches/LauncherModsVMPatch.cs +++ b/src/Bannerlord.LauncherEx/Patches/LauncherModsVMPatch.cs @@ -16,21 +16,21 @@ internal static class LauncherModsVMPatch public static bool Enable(Harmony harmony) { - var res1 = harmony.TryPatch( - AccessTools2.Method(typeof(LauncherModsVM), "LoadSubModules"), - prefix: AccessTools2.DeclaredMethod(typeof(LauncherModsVMPatch), nameof(LoadSubModulesPrefix))); + var res1 = harmony.TryPatch( + AccessTools2.Method(typeof(LauncherModsVM), "LoadSubModules"), + prefix: AccessTools2.DeclaredMethod(typeof(LauncherModsVMPatch), nameof(LoadSubModulesPrefix))); - return true; - } + return true; + } public static bool LoadSubModulesPrefix(LauncherModsVM __instance) { - if (_userData is null) - return true; + if (_userData is null) + return true; - if (__instance.GetMixin() is { } mixin) - mixin.Initialize(); + if (__instance.GetMixin() is { } mixin) + mixin.Initialize(); - return false; - } + return false; + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/Patches/LauncherUIPatch.cs b/src/Bannerlord.LauncherEx/Patches/LauncherUIPatch.cs index d3ee865..b70b34a 100644 --- a/src/Bannerlord.LauncherEx/Patches/LauncherUIPatch.cs +++ b/src/Bannerlord.LauncherEx/Patches/LauncherUIPatch.cs @@ -18,60 +18,60 @@ internal static class LauncherUIPatch { public static bool Enable(Harmony harmony) { - var res1 = harmony.TryPatch( - AccessTools2.DeclaredMethod(typeof(LauncherUI), "Initialize"), - postfix: AccessTools2.DeclaredMethod(typeof(LauncherUIPatch), nameof(InitializePostfix))); - if (!res1) return false; + var res1 = harmony.TryPatch( + AccessTools2.DeclaredMethod(typeof(LauncherUI), "Initialize"), + postfix: AccessTools2.DeclaredMethod(typeof(LauncherUIPatch), nameof(InitializePostfix))); + if (!res1) return false; - var res2 = harmony.TryPatch( - AccessTools2.DeclaredMethod(typeof(LauncherUI), "Update"), - postfix: AccessTools2.DeclaredMethod(typeof(LauncherUIPatch), nameof(UpdatePostfix))); - if (!res2) return false; + var res2 = harmony.TryPatch( + AccessTools2.DeclaredMethod(typeof(LauncherUI), "Update"), + postfix: AccessTools2.DeclaredMethod(typeof(LauncherUIPatch), nameof(UpdatePostfix))); + if (!res2) return false; - var res3 = harmony.TryPatch( - AccessTools2.DeclaredPropertyGetter(typeof(LauncherUI), "AdditionalArgs"), - postfix: AccessTools2.DeclaredMethod(typeof(LauncherUIPatch), nameof(AdditionalArgsPostfix))); - if (!res3) return false; + var res3 = harmony.TryPatch( + AccessTools2.DeclaredPropertyGetter(typeof(LauncherUI), "AdditionalArgs"), + postfix: AccessTools2.DeclaredMethod(typeof(LauncherUIPatch), nameof(AdditionalArgsPostfix))); + if (!res3) return false; - return true; - } + return true; + } [MethodImpl(MethodImplOptions.NoInlining)] private static void InitializePostfix(GauntletMovie ____movie, LauncherVM ____viewModel, UserDataManager ____userDataManager) { - BUTRLauncherManagerHandler.Initialize(____userDataManager); + BUTRLauncherManagerHandler.Initialize(____userDataManager); - // Add to the existing VM our own properties - MixinManager.AddMixins(____viewModel); - ____movie.RefreshDataSource(____viewModel); - } + // Add to the existing VM our own properties + MixinManager.AddMixins(____viewModel); + ____movie.RefreshDataSource(____viewModel); + } private static void UpdatePostfix(UIContext ____context) { - if (Input.InputManager is BUTRInputManager butrInputManager) + if (Input.InputManager is BUTRInputManager butrInputManager) + { + if (____context.EventManager?.FocusedWidget is { } focusedWidget) { - if (____context.EventManager?.FocusedWidget is { } focusedWidget) - { - butrInputManager.Update(); + butrInputManager.Update(); - focusedWidget.HandleInput(butrInputManager.ReleasedChars); - } - } - else - { - Input.Initialize(new BUTRInputManager(Input.InputManager), null); + focusedWidget.HandleInput(butrInputManager.ReleasedChars); } } + else + { + Input.Initialize(new BUTRInputManager(Input.InputManager), null); + } + } [MethodImpl(MethodImplOptions.NoInlining)] private static void AdditionalArgsPostfix() { - if (Input.InputManager is BUTRInputManager butrInputManager) - { - Input.Initialize(butrInputManager.InputManager, null); - butrInputManager.Dispose(); - } + if (Input.InputManager is BUTRInputManager butrInputManager) + { + Input.Initialize(butrInputManager.InputManager, null); + butrInputManager.Dispose(); } + } [MethodImpl(MethodImplOptions.NoInlining)] private static IEnumerable BlankTranspiler(IEnumerable instructions) => instructions; diff --git a/src/Bannerlord.LauncherEx/Patches/LauncherVMPatch.cs b/src/Bannerlord.LauncherEx/Patches/LauncherVMPatch.cs index abc6500..fbbbb73 100644 --- a/src/Bannerlord.LauncherEx/Patches/LauncherVMPatch.cs +++ b/src/Bannerlord.LauncherEx/Patches/LauncherVMPatch.cs @@ -17,29 +17,29 @@ internal static class LauncherVMPatch { public static bool Enable(Harmony harmony) { - var res1 = harmony.TryPatch( - AccessTools2.Method(typeof(LauncherVM), "ExecuteConfirmUnverifiedDLLStart"), - transpiler: AccessTools2.DeclaredMethod(typeof(LauncherVMPatch), nameof(BlankTranspiler))); - if (!res1) return false; - - var res2 = harmony.TryPatch( - AccessTools2.Method(typeof(LauncherVM), "GetApplicationVersionOfModule"), - prefix: AccessTools2.DeclaredMethod(typeof(LauncherVMPatch), nameof(GetApplicationVersionOfModulePrefix))); - if (!res2) return false; - - var res3 = harmony.TryPatch( - AccessTools2.Method(typeof(LauncherVM), "UpdateAndSaveUserModsData"), - prefix: AccessTools2.DeclaredMethod(typeof(LauncherVMPatch), nameof(UpdateAndSaveUserModsDataPrefix))); - if (!res3) return false; - - // Preventing inlining ExecuteConfirmUnverifiedDLLStart - harmony.TryPatch( - AccessTools2.Constructor(typeof(LauncherVM), new[] { typeof(UserDataManager), typeof(Action), typeof(Action) }), - transpiler: AccessTools2.DeclaredMethod(typeof(LauncherVMPatch), nameof(BlankTranspiler))); - // Preventing inlining ExecuteConfirmUnverifiedDLLStart - - return true; - } + var res1 = harmony.TryPatch( + AccessTools2.Method(typeof(LauncherVM), "ExecuteConfirmUnverifiedDLLStart"), + transpiler: AccessTools2.DeclaredMethod(typeof(LauncherVMPatch), nameof(BlankTranspiler))); + if (!res1) return false; + + var res2 = harmony.TryPatch( + AccessTools2.Method(typeof(LauncherVM), "GetApplicationVersionOfModule"), + prefix: AccessTools2.DeclaredMethod(typeof(LauncherVMPatch), nameof(GetApplicationVersionOfModulePrefix))); + if (!res2) return false; + + var res3 = harmony.TryPatch( + AccessTools2.Method(typeof(LauncherVM), "UpdateAndSaveUserModsData"), + prefix: AccessTools2.DeclaredMethod(typeof(LauncherVMPatch), nameof(UpdateAndSaveUserModsDataPrefix))); + if (!res3) return false; + + // Preventing inlining ExecuteConfirmUnverifiedDLLStart + harmony.TryPatch( + AccessTools2.Constructor(typeof(LauncherVM), new[] { typeof(UserDataManager), typeof(Action), typeof(Action) }), + transpiler: AccessTools2.DeclaredMethod(typeof(LauncherVMPatch), nameof(BlankTranspiler))); + // Preventing inlining ExecuteConfirmUnverifiedDLLStart + + return true; + } // Disable Vanilla's saving public static bool UpdateAndSaveUserModsDataPrefix() => false; @@ -47,15 +47,15 @@ public static bool Enable(Harmony harmony) [MethodImpl(MethodImplOptions.NoOptimization)] public static bool GetApplicationVersionOfModulePrefix(string id, ref ApplicationVersion __result) { - if (FeatureIds.LauncherFeatures.Contains(id)) - { - __result = ApplicationVersion.Empty; - return false; - } - - return true; + if (FeatureIds.LauncherFeatures.Contains(id)) + { + __result = ApplicationVersion.Empty; + return false; } + return true; + } + [MethodImpl(MethodImplOptions.NoInlining)] private static IEnumerable BlankTranspiler(IEnumerable instructions) => instructions; } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/Patches/ProgramPatch.cs b/src/Bannerlord.LauncherEx/Patches/ProgramPatch.cs index c1a6066..017a2a8 100644 --- a/src/Bannerlord.LauncherEx/Patches/ProgramPatch.cs +++ b/src/Bannerlord.LauncherEx/Patches/ProgramPatch.cs @@ -11,22 +11,22 @@ internal static class ProgramPatch { public static bool Enable(Harmony harmony) { - var res1 = harmony.TryPatch( - AccessTools2.Method(typeof(Program), "AuxFinalize"), - postfix: AccessTools2.DeclaredMethod(typeof(ProgramPatch), nameof(AuxFinalizePostfix))); - if (!res1) return false; + var res1 = harmony.TryPatch( + AccessTools2.Method(typeof(Program), "AuxFinalize"), + postfix: AccessTools2.DeclaredMethod(typeof(ProgramPatch), nameof(AuxFinalizePostfix))); + if (!res1) return false; - return true; - } + return true; + } private static void AuxFinalizePostfix() { - if (LauncherSettings.FixCommonIssues) - { - BUTRLauncherManagerHandler.Default.CheckForRootHarmony(); - } - - Manager.Disable(); + if (LauncherSettings.FixCommonIssues) + { + BUTRLauncherManagerHandler.Default.CheckForRootHarmony(); } + Manager.Disable(); + } + } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/Patches/UserDataManagerPatch.cs b/src/Bannerlord.LauncherEx/Patches/UserDataManagerPatch.cs index b610d6b..a98ef13 100644 --- a/src/Bannerlord.LauncherEx/Patches/UserDataManagerPatch.cs +++ b/src/Bannerlord.LauncherEx/Patches/UserDataManagerPatch.cs @@ -20,18 +20,18 @@ internal static class UserDataManagerPatch { public static bool Enable(Harmony harmony) { - var res1 = harmony.TryPatch( - AccessTools2.DeclaredMethod(typeof(UserDataManager), "LoadUserData"), - prefix: AccessTools2.DeclaredMethod(typeof(UserDataManagerPatch), nameof(LoadUserDataPrefix))); - if (!res1) return false; + var res1 = harmony.TryPatch( + AccessTools2.DeclaredMethod(typeof(UserDataManager), "LoadUserData"), + prefix: AccessTools2.DeclaredMethod(typeof(UserDataManagerPatch), nameof(LoadUserDataPrefix))); + if (!res1) return false; - var res2 = harmony.TryPatch( - AccessTools2.DeclaredMethod(typeof(UserDataManager), "SaveUserData"), - postfix: AccessTools2.DeclaredMethod(typeof(UserDataManagerPatch), nameof(SaveUserDataPostfix))); - if (!res2) return false; + var res2 = harmony.TryPatch( + AccessTools2.DeclaredMethod(typeof(UserDataManager), "SaveUserData"), + postfix: AccessTools2.DeclaredMethod(typeof(UserDataManagerPatch), nameof(SaveUserDataPostfix))); + if (!res2) return false; - return true; - } + return true; + } [SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "")] [SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "For Resharper")] @@ -40,27 +40,27 @@ public static bool Enable(Harmony harmony) [MethodImpl(MethodImplOptions.NoInlining)] private static bool LoadUserDataPrefix(string ____filePath) { - if (!File.Exists(____filePath)) - { - return true; - } - - var userDataOptions = LauncherExData.FromUserDataXml(____filePath) ?? new(); - LauncherSettings.AutomaticallyCheckForUpdates = userDataOptions.AutomaticallyCheckForUpdates; - LauncherSettings.FixCommonIssues = userDataOptions.FixCommonIssues; - LauncherSettings.CompactModuleList = userDataOptions.CompactModuleList; - LauncherSettings.HideRandomImage = userDataOptions.HideRandomImage; - LauncherSettings.DisableBinaryCheck = userDataOptions.DisableBinaryCheck; - LauncherSettings.BetaSorting = userDataOptions.BetaSorting; - LauncherSettings.BigMode = userDataOptions.BigMode; - LauncherSettings.EnableDPIScaling = userDataOptions.EnableDPIScaling; - LauncherSettings.DisableCrashHandlerWhenDebuggerIsAttached = userDataOptions.DisableCrashHandlerWhenDebuggerIsAttached; - LauncherSettings.DisableCatchAutoGenExceptions = userDataOptions.DisableCatchAutoGenExceptions; - LauncherSettings.UseVanillaCrashHandler = userDataOptions.UseVanillaCrashHandler; - + if (!File.Exists(____filePath)) + { return true; } + var userDataOptions = LauncherExData.FromUserDataXml(____filePath) ?? new(); + LauncherSettings.AutomaticallyCheckForUpdates = userDataOptions.AutomaticallyCheckForUpdates; + LauncherSettings.FixCommonIssues = userDataOptions.FixCommonIssues; + LauncherSettings.CompactModuleList = userDataOptions.CompactModuleList; + LauncherSettings.HideRandomImage = userDataOptions.HideRandomImage; + LauncherSettings.DisableBinaryCheck = userDataOptions.DisableBinaryCheck; + LauncherSettings.BetaSorting = userDataOptions.BetaSorting; + LauncherSettings.BigMode = userDataOptions.BigMode; + LauncherSettings.EnableDPIScaling = userDataOptions.EnableDPIScaling; + LauncherSettings.DisableCrashHandlerWhenDebuggerIsAttached = userDataOptions.DisableCrashHandlerWhenDebuggerIsAttached; + LauncherSettings.DisableCatchAutoGenExceptions = userDataOptions.DisableCatchAutoGenExceptions; + LauncherSettings.UseVanillaCrashHandler = userDataOptions.UseVanillaCrashHandler; + + return true; + } + [SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "")] [SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "For Resharper")] [SuppressMessage("ReSharper", "InconsistentNaming")] @@ -68,40 +68,40 @@ private static bool LoadUserDataPrefix(string ____filePath) [MethodImpl(MethodImplOptions.NoInlining)] private static void SaveUserDataPostfix(string ____filePath) { - var xDoc = new XmlDocument(); - xDoc.Load(____filePath); - var rootNode = xDoc.DocumentElement!; - - var xmlSerializer = new XmlSerializer(typeof(LauncherExData)); - using var xout = new StringWriter(); - using var writer = XmlWriter.Create(xout, new XmlWriterSettings { OmitXmlDeclaration = true }); - try - { - xmlSerializer.Serialize(writer, new LauncherExData( - LauncherSettings.AutomaticallyCheckForUpdates, - LauncherSettings.FixCommonIssues, - LauncherSettings.CompactModuleList, - LauncherSettings.HideRandomImage, - LauncherSettings.DisableBinaryCheck, - LauncherSettings.BetaSorting, - LauncherSettings.BigMode, - LauncherSettings.EnableDPIScaling, - LauncherSettings.DisableCrashHandlerWhenDebuggerIsAttached, - LauncherSettings.DisableCatchAutoGenExceptions, - LauncherSettings.UseVanillaCrashHandler)); - } - catch (Exception value) - { - Trace.WriteLine(value); - } + var xDoc = new XmlDocument(); + xDoc.Load(____filePath); + var rootNode = xDoc.DocumentElement!; - var xfrag = xDoc.CreateDocumentFragment(); - xfrag.InnerXml = xout.ToString(); - foreach (var element in xfrag.FirstChild.ChildNodes.OfType().ToList()) - { - rootNode.AppendChild(element); - } + var xmlSerializer = new XmlSerializer(typeof(LauncherExData)); + using var xout = new StringWriter(); + using var writer = XmlWriter.Create(xout, new XmlWriterSettings { OmitXmlDeclaration = true }); + try + { + xmlSerializer.Serialize(writer, new LauncherExData( + LauncherSettings.AutomaticallyCheckForUpdates, + LauncherSettings.FixCommonIssues, + LauncherSettings.CompactModuleList, + LauncherSettings.HideRandomImage, + LauncherSettings.DisableBinaryCheck, + LauncherSettings.BetaSorting, + LauncherSettings.BigMode, + LauncherSettings.EnableDPIScaling, + LauncherSettings.DisableCrashHandlerWhenDebuggerIsAttached, + LauncherSettings.DisableCatchAutoGenExceptions, + LauncherSettings.UseVanillaCrashHandler)); + } + catch (Exception value) + { + Trace.WriteLine(value); + } - xDoc.Save(____filePath); + var xfrag = xDoc.CreateDocumentFragment(); + xfrag.InnerXml = xout.ToString(); + foreach (var element in xfrag.FirstChild.ChildNodes.OfType().ToList()) + { + rootNode.AppendChild(element); } + + xDoc.Save(____filePath); + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/Patches/WidgetPrefabPatch.cs b/src/Bannerlord.LauncherEx/Patches/WidgetPrefabPatch.cs index 095bb03..1a0f5a6 100644 --- a/src/Bannerlord.LauncherEx/Patches/WidgetPrefabPatch.cs +++ b/src/Bannerlord.LauncherEx/Patches/WidgetPrefabPatch.cs @@ -21,181 +21,181 @@ internal static class WidgetPrefabPatch { public static bool Enable(Harmony harmony) { - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension31.Movie, UILauncherPrefabExtension31.XPath, new UILauncherPrefabExtension31()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension32.Movie, UILauncherPrefabExtension32.XPath, new UILauncherPrefabExtension32()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension34.Movie, UILauncherPrefabExtension34.XPath, new UILauncherPrefabExtension34()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension35.Movie, UILauncherPrefabExtension35.XPath, new UILauncherPrefabExtension35()); - - // Options - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension3.Movie, UILauncherPrefabExtension3.XPath, new UILauncherPrefabExtension3()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension4.Movie, UILauncherPrefabExtension4.XPath, new UILauncherPrefabExtension4()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension5.Movie, UILauncherPrefabExtension5.XPath, new UILauncherPrefabExtension5()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension6.Movie, UILauncherPrefabExtension6.XPath, new UILauncherPrefabExtension6()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension20.Movie, UILauncherPrefabExtension20.XPath, new UILauncherPrefabExtension20()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension21.Movie, UILauncherPrefabExtension21.XPath, new UILauncherPrefabExtension21()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension7.Movie, UILauncherPrefabExtension7.XPath, new UILauncherPrefabExtension7()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension22.Movie, UILauncherPrefabExtension22.XPath, new UILauncherPrefabExtension22()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension23.Movie, UILauncherPrefabExtension23.XPath, new UILauncherPrefabExtension23()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension10.Movie, UILauncherPrefabExtension10.XPath, new UILauncherPrefabExtension10()); - // Options - - // Saves - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension24.Movie, UILauncherPrefabExtension24.XPath, new UILauncherPrefabExtension24()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension25.Movie, UILauncherPrefabExtension25.XPath, new UILauncherPrefabExtension25()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension26.Movie, UILauncherPrefabExtension26.XPath, new UILauncherPrefabExtension26()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension33.Movie, UILauncherPrefabExtension33.XPath, new UILauncherPrefabExtension33()); - // Saves - - // News - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension8.Movie, UILauncherPrefabExtension8.XPath, new UILauncherPrefabExtension8()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension12.Movie, UILauncherPrefabExtension12.XPath, new UILauncherPrefabExtension12()); - // News - - // Mods - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension9.Movie, UILauncherPrefabExtension9.XPath, new UILauncherPrefabExtension9()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension13.Movie, UILauncherPrefabExtension13.XPath, new UILauncherPrefabExtension13()); - // Mods - - - // Import/Export - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension14.Movie, UILauncherPrefabExtension14.XPath, new UILauncherPrefabExtension14()); - // Import/Export - - // Minor - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension1.Movie, UILauncherPrefabExtension1.XPath, new UILauncherPrefabExtension1()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension2.Movie, UILauncherPrefabExtension2.XPath, new UILauncherPrefabExtension2()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension15.Movie, UILauncherPrefabExtension15.XPath, new UILauncherPrefabExtension15()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension16.Movie, UILauncherPrefabExtension16.XPath, new UILauncherPrefabExtension16()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension17.Movie, UILauncherPrefabExtension17.XPath, new UILauncherPrefabExtension17()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension18.Movie, UILauncherPrefabExtension18.XPath, new UILauncherPrefabExtension18()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension19.Movie, UILauncherPrefabExtension19.XPath, new UILauncherPrefabExtension19()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension28.Movie, UILauncherPrefabExtension28.XPath, new UILauncherPrefabExtension28()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension29.Movie, UILauncherPrefabExtension29.XPath, new UILauncherPrefabExtension29()); - PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension30.Movie, UILauncherPrefabExtension30.XPath, new UILauncherPrefabExtension30()); - // Minor - - // Compact - PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension4.Movie, ModuleTuplePrefabExtension4.XPath, new ModuleTuplePrefabExtension4()); - PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension6.Movie, ModuleTuplePrefabExtension6.XPath, new ModuleTuplePrefabExtension6()); - PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension7.Movie, ModuleTuplePrefabExtension7.XPath, new ModuleTuplePrefabExtension7()); - - PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension8.Movie, ModuleTuplePrefabExtension8.XPath, new ModuleTuplePrefabExtension8()); - PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension9.Movie, ModuleTuplePrefabExtension9.XPath, new ModuleTuplePrefabExtension9()); - PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension10.Movie, ModuleTuplePrefabExtension10.XPath, new ModuleTuplePrefabExtension10()); - PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension11.Movie, ModuleTuplePrefabExtension11.XPath, new ModuleTuplePrefabExtension11()); - PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension12.Movie, ModuleTuplePrefabExtension12.XPath, new ModuleTuplePrefabExtension12()); - PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension13.Movie, ModuleTuplePrefabExtension13.XPath, new ModuleTuplePrefabExtension13()); - PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension14.Movie, ModuleTuplePrefabExtension14.XPath, new ModuleTuplePrefabExtension14()); - // Compact - - var res1 = harmony.TryPatch( - AccessTools2.DeclaredMethod(typeof(WidgetPrefab), "LoadFrom"), - transpiler: AccessTools2.DeclaredMethod(typeof(WidgetPrefabPatch), nameof(WidgetPrefab_LoadFrom_Transpiler))); - if (!res1) return false; - - var res2 = harmony.TryCreateReversePatcher( - AccessTools2.DeclaredMethod(typeof(WidgetPrefab), "LoadFrom"), - AccessTools2.DeclaredMethod(typeof(WidgetPrefabPatch), nameof(LoadFromDocument))); - if (res2 is null) return false; - res2.Patch(); - - return true; - } + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension31.Movie, UILauncherPrefabExtension31.XPath, new UILauncherPrefabExtension31()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension32.Movie, UILauncherPrefabExtension32.XPath, new UILauncherPrefabExtension32()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension34.Movie, UILauncherPrefabExtension34.XPath, new UILauncherPrefabExtension34()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension35.Movie, UILauncherPrefabExtension35.XPath, new UILauncherPrefabExtension35()); + + // Options + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension3.Movie, UILauncherPrefabExtension3.XPath, new UILauncherPrefabExtension3()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension4.Movie, UILauncherPrefabExtension4.XPath, new UILauncherPrefabExtension4()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension5.Movie, UILauncherPrefabExtension5.XPath, new UILauncherPrefabExtension5()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension6.Movie, UILauncherPrefabExtension6.XPath, new UILauncherPrefabExtension6()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension20.Movie, UILauncherPrefabExtension20.XPath, new UILauncherPrefabExtension20()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension21.Movie, UILauncherPrefabExtension21.XPath, new UILauncherPrefabExtension21()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension7.Movie, UILauncherPrefabExtension7.XPath, new UILauncherPrefabExtension7()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension22.Movie, UILauncherPrefabExtension22.XPath, new UILauncherPrefabExtension22()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension23.Movie, UILauncherPrefabExtension23.XPath, new UILauncherPrefabExtension23()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension10.Movie, UILauncherPrefabExtension10.XPath, new UILauncherPrefabExtension10()); + // Options + + // Saves + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension24.Movie, UILauncherPrefabExtension24.XPath, new UILauncherPrefabExtension24()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension25.Movie, UILauncherPrefabExtension25.XPath, new UILauncherPrefabExtension25()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension26.Movie, UILauncherPrefabExtension26.XPath, new UILauncherPrefabExtension26()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension33.Movie, UILauncherPrefabExtension33.XPath, new UILauncherPrefabExtension33()); + // Saves + + // News + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension8.Movie, UILauncherPrefabExtension8.XPath, new UILauncherPrefabExtension8()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension12.Movie, UILauncherPrefabExtension12.XPath, new UILauncherPrefabExtension12()); + // News + + // Mods + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension9.Movie, UILauncherPrefabExtension9.XPath, new UILauncherPrefabExtension9()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension13.Movie, UILauncherPrefabExtension13.XPath, new UILauncherPrefabExtension13()); + // Mods + + + // Import/Export + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension14.Movie, UILauncherPrefabExtension14.XPath, new UILauncherPrefabExtension14()); + // Import/Export + + // Minor + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension1.Movie, UILauncherPrefabExtension1.XPath, new UILauncherPrefabExtension1()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension2.Movie, UILauncherPrefabExtension2.XPath, new UILauncherPrefabExtension2()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension15.Movie, UILauncherPrefabExtension15.XPath, new UILauncherPrefabExtension15()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension16.Movie, UILauncherPrefabExtension16.XPath, new UILauncherPrefabExtension16()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension17.Movie, UILauncherPrefabExtension17.XPath, new UILauncherPrefabExtension17()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension18.Movie, UILauncherPrefabExtension18.XPath, new UILauncherPrefabExtension18()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension19.Movie, UILauncherPrefabExtension19.XPath, new UILauncherPrefabExtension19()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension28.Movie, UILauncherPrefabExtension28.XPath, new UILauncherPrefabExtension28()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension29.Movie, UILauncherPrefabExtension29.XPath, new UILauncherPrefabExtension29()); + PrefabExtensionManager.RegisterPatch(UILauncherPrefabExtension30.Movie, UILauncherPrefabExtension30.XPath, new UILauncherPrefabExtension30()); + // Minor + + // Compact + PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension4.Movie, ModuleTuplePrefabExtension4.XPath, new ModuleTuplePrefabExtension4()); + PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension6.Movie, ModuleTuplePrefabExtension6.XPath, new ModuleTuplePrefabExtension6()); + PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension7.Movie, ModuleTuplePrefabExtension7.XPath, new ModuleTuplePrefabExtension7()); + + PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension8.Movie, ModuleTuplePrefabExtension8.XPath, new ModuleTuplePrefabExtension8()); + PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension9.Movie, ModuleTuplePrefabExtension9.XPath, new ModuleTuplePrefabExtension9()); + PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension10.Movie, ModuleTuplePrefabExtension10.XPath, new ModuleTuplePrefabExtension10()); + PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension11.Movie, ModuleTuplePrefabExtension11.XPath, new ModuleTuplePrefabExtension11()); + PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension12.Movie, ModuleTuplePrefabExtension12.XPath, new ModuleTuplePrefabExtension12()); + PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension13.Movie, ModuleTuplePrefabExtension13.XPath, new ModuleTuplePrefabExtension13()); + PrefabExtensionManager.RegisterPatch(ModuleTuplePrefabExtension14.Movie, ModuleTuplePrefabExtension14.XPath, new ModuleTuplePrefabExtension14()); + // Compact + + var res1 = harmony.TryPatch( + AccessTools2.DeclaredMethod(typeof(WidgetPrefab), "LoadFrom"), + transpiler: AccessTools2.DeclaredMethod(typeof(WidgetPrefabPatch), nameof(WidgetPrefab_LoadFrom_Transpiler))); + if (!res1) return false; + + var res2 = harmony.TryCreateReversePatcher( + AccessTools2.DeclaredMethod(typeof(WidgetPrefab), "LoadFrom"), + AccessTools2.DeclaredMethod(typeof(WidgetPrefabPatch), nameof(LoadFromDocument))); + if (res2 is null) return false; + res2.Patch(); + + return true; + } [MethodImpl(MethodImplOptions.NoInlining)] private static void ProcessMovie(string path, XmlDocument document) { - var movieName = Path.GetFileNameWithoutExtension(path); - PrefabExtensionManager.ProcessMovieIfNeeded(movieName, document); - } + var movieName = Path.GetFileNameWithoutExtension(path); + PrefabExtensionManager.ProcessMovieIfNeeded(movieName, document); + } private static int GetWidgetPrefabConstructorIndex(IList instructions, MethodBase originalMethod) { - var constructor = AccessTools2.DeclaredConstructor(typeof(WidgetPrefab)); + var constructor = AccessTools2.DeclaredConstructor(typeof(WidgetPrefab)); - var locals = originalMethod.GetMethodBody()?.LocalVariables; - var widgetPrefabLocal = locals?.FirstOrDefault(x => x.LocalType == typeof(WidgetPrefab)); + var locals = originalMethod.GetMethodBody()?.LocalVariables; + var widgetPrefabLocal = locals?.FirstOrDefault(x => x.LocalType == typeof(WidgetPrefab)); - if (widgetPrefabLocal is null) - return -1; + if (widgetPrefabLocal is null) + return -1; - var constructorIndex = -1; - for (var i = 0; i < instructions.Count - 2; i++) - { - if (instructions[i + 0].opcode != OpCodes.Newobj || !Equals(instructions[i + 0].operand, constructor)) - continue; + var constructorIndex = -1; + for (var i = 0; i < instructions.Count - 2; i++) + { + if (instructions[i + 0].opcode != OpCodes.Newobj || !Equals(instructions[i + 0].operand, constructor)) + continue; - if (!instructions[i + 1].IsStloc()) - continue; + if (!instructions[i + 1].IsStloc()) + continue; - constructorIndex = i; - break; - } - return constructorIndex; + constructorIndex = i; + break; } + return constructorIndex; + } [MethodImpl(MethodImplOptions.NoInlining)] private static IEnumerable WidgetPrefab_LoadFrom_Transpiler(IEnumerable instructions, MethodBase method) { - var instructionsList = instructions.ToList(); + var instructionsList = instructions.ToList(); - IEnumerable ReturnDefault() - { - return instructionsList.AsEnumerable(); - } + IEnumerable ReturnDefault() + { + return instructionsList.AsEnumerable(); + } - var widgetPrefabConstructorIndex = GetWidgetPrefabConstructorIndex(instructionsList, method); - if (widgetPrefabConstructorIndex == -1) - return ReturnDefault(); + var widgetPrefabConstructorIndex = GetWidgetPrefabConstructorIndex(instructionsList, method); + if (widgetPrefabConstructorIndex == -1) + return ReturnDefault(); - // ProcessMovie(path, xmlDocument); - instructionsList.InsertRange(widgetPrefabConstructorIndex + 1, new List + // ProcessMovie(path, xmlDocument); + instructionsList.InsertRange(widgetPrefabConstructorIndex + 1, new List { new (OpCodes.Ldarg_2), new (OpCodes.Ldloc_0), new (OpCodes.Call, AccessTools2.DeclaredMethod(typeof(WidgetPrefabPatch), nameof(ProcessMovie))) }); - return instructionsList.AsEnumerable(); - } + return instructionsList.AsEnumerable(); + } // We can call a slightly modified native game call this way [MethodImpl(MethodImplOptions.NoInlining)] public static WidgetPrefab? LoadFromDocument(PrefabExtensionContext prefabExtensionContext, WidgetAttributeContext widgetAttributeContext, string path, XmlDocument document) { - // Replaces reading XML from file with assigning it from the new local variable `XmlDocument document` - [MethodImpl(MethodImplOptions.NoInlining)] - static IEnumerable Transpiler(IEnumerable instructions) - { - var returnNull = new List + // Replaces reading XML from file with assigning it from the new local variable `XmlDocument document` + [MethodImpl(MethodImplOptions.NoInlining)] + static IEnumerable Transpiler(IEnumerable instructions) + { + var returnNull = new List { new (OpCodes.Ldnull), new (OpCodes.Ret) }.AsEnumerable(); - var instructionsList = instructions.ToList(); + var instructionsList = instructions.ToList(); - var method = AccessTools2.DeclaredMethod(typeof(WidgetPrefab), "LoadFrom"); - var locals = method?.GetMethodBody()?.LocalVariables; - var xmlDocumentLocal = locals?.FirstOrDefault(x => x.LocalType == typeof(XmlDocument)); + var method = AccessTools2.DeclaredMethod(typeof(WidgetPrefab), "LoadFrom"); + var locals = method?.GetMethodBody()?.LocalVariables; + var xmlDocumentLocal = locals?.FirstOrDefault(x => x.LocalType == typeof(XmlDocument)); - if (xmlDocumentLocal is null) - return returnNull; + if (xmlDocumentLocal is null) + return returnNull; - var widgetPrefabConstructorIndex = GetWidgetPrefabConstructorIndex(instructionsList, method!); - if (widgetPrefabConstructorIndex == -1) - return returnNull; + var widgetPrefabConstructorIndex = GetWidgetPrefabConstructorIndex(instructionsList, method!); + if (widgetPrefabConstructorIndex == -1) + return returnNull; - for (var i = 0; i < widgetPrefabConstructorIndex; i++) - { - instructionsList[i] = new CodeInstruction(OpCodes.Nop); - } + for (var i = 0; i < widgetPrefabConstructorIndex; i++) + { + instructionsList[i] = new CodeInstruction(OpCodes.Nop); + } - instructionsList[widgetPrefabConstructorIndex - 2] = new CodeInstruction(OpCodes.Ldarg_S, 3); - instructionsList[widgetPrefabConstructorIndex - 1] = new CodeInstruction(OpCodes.Stloc_S, xmlDocumentLocal.LocalIndex); + instructionsList[widgetPrefabConstructorIndex - 2] = new CodeInstruction(OpCodes.Ldarg_S, 3); + instructionsList[widgetPrefabConstructorIndex - 1] = new CodeInstruction(OpCodes.Stloc_S, xmlDocumentLocal.LocalIndex); - // ProcessMovie(path, xmlDocument); - instructionsList.InsertRange(widgetPrefabConstructorIndex + 1, new List + // ProcessMovie(path, xmlDocument); + instructionsList.InsertRange(widgetPrefabConstructorIndex + 1, new List { new (OpCodes.Ldarg_S, 2), new (OpCodes.Ldloc_S, xmlDocumentLocal.LocalIndex), @@ -203,19 +203,19 @@ static IEnumerable Transpiler(IEnumerable inst }); - return instructionsList.AsEnumerable(); - } + return instructionsList.AsEnumerable(); + } - // make compiler happy - _ = Transpiler(null!); + // make compiler happy + _ = Transpiler(null!); - // make analyzer happy - prefabExtensionContext.AddExtension(null); - widgetAttributeContext.RegisterKeyType(null); - path.Do(null); - document.Validate(null); + // make analyzer happy + prefabExtensionContext.AddExtension(null); + widgetAttributeContext.RegisterKeyType(null); + path.Do(null); + document.Validate(null); - // make compiler happy - return null!; - } + // make compiler happy + return null!; + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.ImportExport.cs b/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.ImportExport.cs index 07b7303..67f595b 100644 --- a/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.ImportExport.cs +++ b/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.ImportExport.cs @@ -14,7 +14,7 @@ internal sealed class UILauncherPrefabExtension14 : PrefabExtensionInsertAsSibli public UILauncherPrefabExtension14() { - XmlDocument.LoadXml(@" + XmlDocument.LoadXml(@" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Minor.cs b/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Minor.cs index b145e91..5388c51 100644 --- a/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Minor.cs +++ b/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Minor.cs @@ -22,10 +22,10 @@ internal sealed class UILauncherPrefabExtension1 : PrefabExtensionInsertAsSiblin public UILauncherPrefabExtension1() { - XmlDocument.LoadXml(@$" + XmlDocument.LoadXml(@$" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } @@ -42,10 +42,10 @@ internal sealed class UILauncherPrefabExtension2 : PrefabExtensionInsertAsSiblin public UILauncherPrefabExtension2() { - XmlDocument.LoadXml(@$" + XmlDocument.LoadXml(@$" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } @@ -129,20 +129,20 @@ internal sealed class UILauncherPrefabExtension19 : PrefabExtensionCustomPatch() ?? Enumerable.Empty()) + foreach (var selectNode in node.OwnerDocument?.SelectNodes("//*")?.OfType() ?? Enumerable.Empty()) + { + foreach (var attribute in selectNode.Attributes?.OfType() ?? Enumerable.Empty()) { - foreach (var attribute in selectNode.Attributes?.OfType() ?? Enumerable.Empty()) + attribute.Value = attribute.Value switch { - attribute.Value = attribute.Value switch - { - $"@{nameof(LauncherVM.IsSingleplayer)}" => $"@{nameof(LauncherVMMixin.IsSingleplayer2)}", - $"@{nameof(LauncherVM.IsMultiplayer)}" => $"@{nameof(LauncherVMMixin.IsMultiplayer2)}", - $"@{"IsDigitalCompanion"}" => $"@{nameof(LauncherVMMixin.IsDigitalCompanion2)}", - _ => attribute.Value - }; - } + $"@{nameof(LauncherVM.IsSingleplayer)}" => $"@{nameof(LauncherVMMixin.IsSingleplayer2)}", + $"@{nameof(LauncherVM.IsMultiplayer)}" => $"@{nameof(LauncherVMMixin.IsMultiplayer2)}", + $"@{"IsDigitalCompanion"}" => $"@{nameof(LauncherVMMixin.IsDigitalCompanion2)}", + _ => attribute.Value + }; } } + } } internal sealed class UILauncherPrefabExtension30 : PrefabExtensionSetAttributePatch @@ -161,19 +161,19 @@ internal sealed class UILauncherPrefabExtension31 : PrefabExtensionCustomPatch() ?? Enumerable.Empty()) + foreach (var selectNode in node.OwnerDocument?.SelectNodes("//*")?.OfType() ?? Enumerable.Empty()) + { + foreach (var attribute in selectNode.Attributes?.OfType() ?? Enumerable.Empty()) { - foreach (var attribute in selectNode.Attributes?.OfType() ?? Enumerable.Empty()) - { - if (attribute.Name != "Text") continue; - if (!attribute.Value.StartsWith("@")) continue; - if (!attribute.Value.EndsWith("Text")) continue; - if (attribute.Value == "@Text") continue; - if (attribute.Value == "@VersionText") continue; - attribute.Value = $"{attribute.Value}2"; - } + if (attribute.Name != "Text") continue; + if (!attribute.Value.StartsWith("@")) continue; + if (!attribute.Value.EndsWith("Text")) continue; + if (attribute.Value == "@Text") continue; + if (attribute.Value == "@VersionText") continue; + attribute.Value = $"{attribute.Value}2"; } } + } } internal sealed class UILauncherPrefabExtension34 : PrefabExtensionCustomPatch @@ -183,17 +183,17 @@ internal sealed class UILauncherPrefabExtension34 : PrefabExtensionCustomPatch() ?? Enumerable.Empty()) + foreach (var selectNode in node.OwnerDocument?.SelectNodes("//*")?.OfType() ?? Enumerable.Empty()) + { + foreach (var attribute in selectNode.Attributes?.OfType() ?? Enumerable.Empty()) { - foreach (var attribute in selectNode.Attributes?.OfType() ?? Enumerable.Empty()) - { - if (attribute.Name != "Brush") continue; - if (attribute.Value != "Launcher.PlayButton.Text") continue; - if (attribute.Value == "@VersionText") continue; - attribute.Value = "Launcher.Button.Text"; - } + if (attribute.Name != "Brush") continue; + if (attribute.Value != "Launcher.PlayButton.Text") continue; + if (attribute.Value == "@VersionText") continue; + attribute.Value = "Launcher.Button.Text"; } } + } } internal sealed class UILauncherPrefabExtension32 : PrefabExtensionInsertAsSiblingPatch @@ -205,10 +205,10 @@ internal sealed class UILauncherPrefabExtension32 : PrefabExtensionInsertAsSibli public UILauncherPrefabExtension32() { - XmlDocument.LoadXml(@" + XmlDocument.LoadXml(@" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } diff --git a/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Mods.Saves.cs b/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Mods.Saves.cs index 16832eb..717ff4e 100644 --- a/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Mods.Saves.cs +++ b/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Mods.Saves.cs @@ -15,14 +15,14 @@ internal sealed class UILauncherPrefabExtension24 : PrefabExtensionInsertAsSibli public UILauncherPrefabExtension24() { - XmlDocument.LoadXml(@" + XmlDocument.LoadXml(@" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } @@ -36,10 +36,10 @@ internal sealed class UILauncherPrefabExtension25 : PrefabExtensionInsertAsSibli public UILauncherPrefabExtension25() { - XmlDocument.LoadXml(@" + XmlDocument.LoadXml(@" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } diff --git a/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Mods.cs b/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Mods.cs index 159ad4d..facbbc8 100644 --- a/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Mods.cs +++ b/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Mods.cs @@ -33,10 +33,10 @@ internal sealed class UILauncherPrefabExtension13 : PrefabExtensionReplacePatch public UILauncherPrefabExtension13() { - XmlDocument.LoadXml(@" + XmlDocument.LoadXml(@" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Options.cs b/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Options.cs index 5f7ae1c..ff54eca 100644 --- a/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Options.cs +++ b/src/Bannerlord.LauncherEx/PrefabExtensions/UILauncherPrefabExtension.Options.cs @@ -17,14 +17,14 @@ internal sealed class UILauncherPrefabExtension3 : PrefabExtensionInsertAsSiblin public UILauncherPrefabExtension3() { - XmlDocument.LoadXml(@" + XmlDocument.LoadXml(@" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } @@ -54,10 +54,10 @@ internal sealed class UILauncherPrefabExtension5 : PrefabExtensionInsertAsSiblin public UILauncherPrefabExtension5() { - XmlDocument.LoadXml(@" + XmlDocument.LoadXml(@" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } @@ -75,14 +75,14 @@ internal sealed class UILauncherPrefabExtension6 : PrefabExtensionInsertAsSiblin public UILauncherPrefabExtension6() { - XmlDocument.LoadXml(@" + XmlDocument.LoadXml(@" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } @@ -96,14 +96,14 @@ internal sealed class UILauncherPrefabExtension20 : PrefabExtensionInsertAsSibli public UILauncherPrefabExtension20() { - XmlDocument.LoadXml(@" + XmlDocument.LoadXml(@" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } @@ -117,14 +117,14 @@ internal sealed class UILauncherPrefabExtension21 : PrefabExtensionInsertAsSibli public UILauncherPrefabExtension21() { - XmlDocument.LoadXml(@" + XmlDocument.LoadXml(@" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } @@ -142,10 +142,10 @@ internal sealed class UILauncherPrefabExtension7 : PrefabExtensionInsertAsSiblin public UILauncherPrefabExtension7() { - XmlDocument.LoadXml(@" + XmlDocument.LoadXml(@" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } @@ -159,10 +159,10 @@ internal sealed class UILauncherPrefabExtension22 : PrefabExtensionInsertAsSibli public UILauncherPrefabExtension22() { - XmlDocument.LoadXml(@" + XmlDocument.LoadXml(@" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } @@ -176,10 +176,10 @@ internal sealed class UILauncherPrefabExtension23 : PrefabExtensionInsertAsSibli public UILauncherPrefabExtension23() { - XmlDocument.LoadXml(@" + XmlDocument.LoadXml(@" "); - } + } public override XmlDocument GetPrefabExtension() => XmlDocument; } diff --git a/src/Bannerlord.LauncherEx/ResourceManagers/GraphicsContextManager.cs b/src/Bannerlord.LauncherEx/ResourceManagers/GraphicsContextManager.cs index de31cab..aaab672 100644 --- a/src/Bannerlord.LauncherEx/ResourceManagers/GraphicsContextManager.cs +++ b/src/Bannerlord.LauncherEx/ResourceManagers/GraphicsContextManager.cs @@ -21,66 +21,66 @@ internal static class GraphicsContextManager public static OpenGLTexture Create(string name, Stream stream) { - var texture = new OpenGLTexture(); - if (texture.LoadFromStream(name, stream)) - return texture; + var texture = new OpenGLTexture(); + if (texture.LoadFromStream(name, stream)) + return texture; - var path = Path.GetTempFileName(); - using (var fs = File.OpenWrite(path)) - stream.CopyTo(fs); - var openGLTexture = OpenGLTexture.FromFile(path); - File.Delete(path); + var path = Path.GetTempFileName(); + using (var fs = File.OpenWrite(path)) + stream.CopyTo(fs); + var openGLTexture = OpenGLTexture.FromFile(path); + File.Delete(path); - return openGLTexture; - } + return openGLTexture; + } private static OpenGLTexture CreateAssetTexture(string name, TPac.Texture assetTexture) { - var texture = new OpenGLTexture(); - texture.LoadFromAssetTexture(name, assetTexture); - return texture; - } + var texture = new OpenGLTexture(); + texture.LoadFromAssetTexture(name, assetTexture); + return texture; + } public static void Register(string name, Func func) => DeferredInitialization.Add(name, func); public static void CreateAndRegister(string name, Stream stream) => Register(name, () => Create(name, stream)); public static void CreateAssetTextureAndRegister(string name, TPac.Texture texture) => Register(name, () => CreateAssetTexture(name, texture)); public static void Clear() { - Textures.Clear(); - DeferredInitialization.Clear(); - Instance.SetTarget(null); - } + Textures.Clear(); + DeferredInitialization.Clear(); + Instance.SetTarget(null); + } internal static bool Enable(Harmony harmony) { - var res1 = harmony.TryPatch( - AccessTools2.DeclaredMethod(typeof(GraphicsContext), "GetTexture"), - prefix: AccessTools2.DeclaredMethod(typeof(GraphicsContextManager), nameof(GetTexturePrefix))); - if (!res1) return false; + var res1 = harmony.TryPatch( + AccessTools2.DeclaredMethod(typeof(GraphicsContext), "GetTexture"), + prefix: AccessTools2.DeclaredMethod(typeof(GraphicsContextManager), nameof(GetTexturePrefix))); + if (!res1) return false; - var res2 = harmony.TryPatch( - AccessTools2.DeclaredMethod(typeof(GraphicsContext), "CreateContext"), - postfix: AccessTools2.DeclaredMethod(typeof(GraphicsContextManager), nameof(CreateContextPostfix))); - if (!res2) return false; + var res2 = harmony.TryPatch( + AccessTools2.DeclaredMethod(typeof(GraphicsContext), "CreateContext"), + postfix: AccessTools2.DeclaredMethod(typeof(GraphicsContextManager), nameof(CreateContextPostfix))); + if (!res2) return false; - return true; - } + return true; + } private static bool GetTexturePrefix(string textureName, ref OpenGLTexture? __result) { - if (!Textures.TryGetValue(textureName, out __result)) - return true; - return false; - } + if (!Textures.TryGetValue(textureName, out __result)) + return true; + return false; + } private static void CreateContextPostfix(GraphicsContext __instance) { - Instance = new(__instance); + Instance = new(__instance); - foreach (var (name, func) in DeferredInitialization) - { - Textures[name] = func(); - } + foreach (var (name, func) in DeferredInitialization) + { + Textures[name] = func(); } + } private static IEnumerable BlankTranspiler(IEnumerable instructions) => instructions; } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/ResourceManagers/SpriteDataManager.cs b/src/Bannerlord.LauncherEx/ResourceManagers/SpriteDataManager.cs index 9f88b04..3e6de0a 100644 --- a/src/Bannerlord.LauncherEx/ResourceManagers/SpriteDataManager.cs +++ b/src/Bannerlord.LauncherEx/ResourceManagers/SpriteDataManager.cs @@ -21,22 +21,22 @@ private sealed class SpriteGenericFromTexture : SpriteGeneric private static SpritePart GetSpritePart(string name, Texture texture) { - var data = new SpriteData(name); - var category = new SpriteCategory(name, data, 0) - { - SpriteSheets = + var data = new SpriteData(name); + var category = new SpriteCategory(name, data, 0) + { + SpriteSheets = { texture }, - SpriteSheetCount = 1 - }; - SetIsLoaded?.Invoke(category, true); + SpriteSheetCount = 1 + }; + SetIsLoaded?.Invoke(category, true); - return new SpritePart(name, category, texture.Width, texture.Height) - { - SheetID = 1, - }; - } + return new SpritePart(name, category, texture.Width, texture.Height) + { + SheetID = 1, + }; + } public SpriteGenericFromTexture(string name, Texture texture) : base(name, GetSpritePart(name, texture)) { } } @@ -64,126 +64,126 @@ private sealed class SpriteFromTexture : Sprite public SpriteFromTexture(Texture texture) : this("Sprite", texture) { } public SpriteFromTexture(string name, Texture texture) : base(name, texture.Width, texture.Height) { - Texture = texture; - _vertices = new float[8]; - _uvs = new float[8]; - _indices = new uint[6]; - _indices[0] = 0U; - _indices[1] = 1U; - _indices[2] = 2U; - _indices[3] = 0U; - _indices[4] = 2U; - _indices[5] = 3U; - } + Texture = texture; + _vertices = new float[8]; + _uvs = new float[8]; + _indices = new uint[6]; + _indices[0] = 0U; + _indices[1] = 1U; + _indices[2] = 2U; + _indices[3] = 0U; + _indices[4] = 2U; + _indices[5] = 3U; + } public override float GetScaleToUse(float width, float height, float scale) => scale; protected override DrawObject2D GetArrays(SpriteDrawData spriteDrawData) { - if (CachedDrawObject is not null && CachedDrawData == spriteDrawData) - return CachedDrawObject; - - if (FieldMapX is null || FieldMapY is null || FieldWidth is null || FieldHeight is null || FieldHorizontalFlip is null || FieldVerticalFlip is null) - return null!; - - var mapX = FieldMapX(ref spriteDrawData); - var mapY = FieldMapY(ref spriteDrawData); - var width = FieldWidth(ref spriteDrawData); - var height = FieldHeight(ref spriteDrawData); - var horizontalFlip = FieldHorizontalFlip(ref spriteDrawData); - var verticalFlip = FieldVerticalFlip(ref spriteDrawData); - - //var vec2 = Vector2Constructor.Invoke(new object[] { width, height }); - //var quad1 = CreateQuad.Invoke(null, new object[]{ vec2 }) as DrawObject2D; - //return quad1; - //var quad = DrawObject2D.CreateQuad(new Vector2(width, height)); - //return quad; - - if (mapX == 0f && mapY == 0f) - { - PopulateVertices(Texture, mapX, mapY, _vertices, 0, 1f, width, height); - PopulateTextureCoordinates(_uvs, 0, horizontalFlip, verticalFlip); - var drawObject2D = new DrawObject2D(MeshTopology.Triangles, _vertices.ToArray(), _uvs.ToArray(), _indices.ToArray(), 6) - { - DrawObjectType = DrawObjectType.Quad, - Width = width, - Height = height, - MinU = 0f, - MaxU = 1f, - MinV = 0f, - MaxV = 1f - }; - if (horizontalFlip) - { - drawObject2D.MinU = 1f; - drawObject2D.MaxU = 0f; - } - if (verticalFlip) - { - drawObject2D.MinV = 1f; - drawObject2D.MaxV = 0f; - } - - CachedDrawData = spriteDrawData; - CachedDrawObject = drawObject2D; - return drawObject2D; - } - + if (CachedDrawObject is not null && CachedDrawData == spriteDrawData) + return CachedDrawObject; + + if (FieldMapX is null || FieldMapY is null || FieldWidth is null || FieldHeight is null || FieldHorizontalFlip is null || FieldVerticalFlip is null) + return null!; + + var mapX = FieldMapX(ref spriteDrawData); + var mapY = FieldMapY(ref spriteDrawData); + var width = FieldWidth(ref spriteDrawData); + var height = FieldHeight(ref spriteDrawData); + var horizontalFlip = FieldHorizontalFlip(ref spriteDrawData); + var verticalFlip = FieldVerticalFlip(ref spriteDrawData); + + //var vec2 = Vector2Constructor.Invoke(new object[] { width, height }); + //var quad1 = CreateQuad.Invoke(null, new object[]{ vec2 }) as DrawObject2D; + //return quad1; + //var quad = DrawObject2D.CreateQuad(new Vector2(width, height)); + //return quad; + + if (mapX == 0f && mapY == 0f) + { PopulateVertices(Texture, mapX, mapY, _vertices, 0, 1f, width, height); PopulateTextureCoordinates(_uvs, 0, horizontalFlip, verticalFlip); - var drawObject2D2 = new DrawObject2D(MeshTopology.Triangles, _vertices.ToArray(), _uvs.ToArray(), _indices.ToArray(), 6) + var drawObject2D = new DrawObject2D(MeshTopology.Triangles, _vertices.ToArray(), _uvs.ToArray(), _indices.ToArray(), 6) { - DrawObjectType = DrawObjectType.Mesh + DrawObjectType = DrawObjectType.Quad, + Width = width, + Height = height, + MinU = 0f, + MaxU = 1f, + MinV = 0f, + MaxV = 1f }; + if (horizontalFlip) + { + drawObject2D.MinU = 1f; + drawObject2D.MaxU = 0f; + } + if (verticalFlip) + { + drawObject2D.MinV = 1f; + drawObject2D.MaxV = 0f; + } CachedDrawData = spriteDrawData; - CachedDrawObject = drawObject2D2; - return drawObject2D2; + CachedDrawObject = drawObject2D; + return drawObject2D; } + PopulateVertices(Texture, mapX, mapY, _vertices, 0, 1f, width, height); + PopulateTextureCoordinates(_uvs, 0, horizontalFlip, verticalFlip); + var drawObject2D2 = new DrawObject2D(MeshTopology.Triangles, _vertices.ToArray(), _uvs.ToArray(), _indices.ToArray(), 6) + { + DrawObjectType = DrawObjectType.Mesh + }; + + CachedDrawData = spriteDrawData; + CachedDrawObject = drawObject2D2; + return drawObject2D2; + } + private static void PopulateVertices(Texture texture, float screenX, float screenY, float[] outVertices, int verticesStartIndex, float scale, float customWidth, float customHeight) { - var widthProp = customWidth / texture.Width; - var heightProp = customHeight / texture.Height; - var widthScaled = texture.Width * scale * widthProp; - var heightScaled = texture.Height * scale * heightProp; - - outVertices[verticesStartIndex] = screenX + 0f; - outVertices[verticesStartIndex + 1] = screenY + 0f; - outVertices[verticesStartIndex + 2] = screenX + 0f; - outVertices[verticesStartIndex + 3] = screenY + heightScaled; - outVertices[verticesStartIndex + 4] = screenX + widthScaled; - outVertices[verticesStartIndex + 5] = screenY + heightScaled; - outVertices[verticesStartIndex + 6] = screenX + widthScaled; - outVertices[verticesStartIndex + 7] = screenY + 0f; - } + var widthProp = customWidth / texture.Width; + var heightProp = customHeight / texture.Height; + var widthScaled = texture.Width * scale * widthProp; + var heightScaled = texture.Height * scale * heightProp; + + outVertices[verticesStartIndex] = screenX + 0f; + outVertices[verticesStartIndex + 1] = screenY + 0f; + outVertices[verticesStartIndex + 2] = screenX + 0f; + outVertices[verticesStartIndex + 3] = screenY + heightScaled; + outVertices[verticesStartIndex + 4] = screenX + widthScaled; + outVertices[verticesStartIndex + 5] = screenY + heightScaled; + outVertices[verticesStartIndex + 6] = screenX + widthScaled; + outVertices[verticesStartIndex + 7] = screenY + 0f; + } private static void PopulateTextureCoordinates(float[] outUVs, int uvsStartIndex, bool horizontalFlip, bool verticalFlip) { - var minU = 0f; - var maxU = 1f; - if (horizontalFlip) - { - minU = 1f; - maxU = 0f; - } - - var minV = 0f; - var maxV = 1f; - if (verticalFlip) - { - minV = 1f; - maxV = 0f; - } + var minU = 0f; + var maxU = 1f; + if (horizontalFlip) + { + minU = 1f; + maxU = 0f; + } - outUVs[uvsStartIndex] = minU; - outUVs[uvsStartIndex + 1] = minV; - outUVs[uvsStartIndex + 2] = minU; - outUVs[uvsStartIndex + 3] = maxV; - outUVs[uvsStartIndex + 4] = maxU; - outUVs[uvsStartIndex + 5] = maxV; - outUVs[uvsStartIndex + 6] = maxU; - outUVs[uvsStartIndex + 7] = minV; + var minV = 0f; + var maxV = 1f; + if (verticalFlip) + { + minV = 1f; + maxV = 0f; } + + outUVs[uvsStartIndex] = minU; + outUVs[uvsStartIndex + 1] = minV; + outUVs[uvsStartIndex + 2] = minU; + outUVs[uvsStartIndex + 3] = maxV; + outUVs[uvsStartIndex + 4] = maxU; + outUVs[uvsStartIndex + 5] = maxV; + outUVs[uvsStartIndex + 6] = maxU; + outUVs[uvsStartIndex + 7] = minV; + } } @@ -200,40 +200,40 @@ private static void PopulateTextureCoordinates(float[] outUVs, int uvsStartIndex public static void Clear() { - SpriteNames.Clear(); - DeferredInitialization.Clear(); - } + SpriteNames.Clear(); + DeferredInitialization.Clear(); + } internal static bool Enable(Harmony harmony) { - var res1 = harmony.TryPatch( - AccessTools2.Method(typeof(SpriteData), "GetSprite"), - prefix: AccessTools2.DeclaredMethod(typeof(SpriteDataManager), nameof(GetSpritePrefix))); - if (!res1) return false; + var res1 = harmony.TryPatch( + AccessTools2.Method(typeof(SpriteData), "GetSprite"), + prefix: AccessTools2.DeclaredMethod(typeof(SpriteDataManager), nameof(GetSpritePrefix))); + if (!res1) return false; - var res2 = harmony.TryPatch( - AccessTools2.Method(typeof(SpriteData), "Load"), - postfix: AccessTools2.DeclaredMethod(typeof(SpriteDataManager), nameof(LoadPostfix))); - if (!res2) return false; + var res2 = harmony.TryPatch( + AccessTools2.Method(typeof(SpriteData), "Load"), + postfix: AccessTools2.DeclaredMethod(typeof(SpriteDataManager), nameof(LoadPostfix))); + if (!res2) return false; - return true; - } + return true; + } private static bool GetSpritePrefix(string name, ref Sprite? __result) { - if (!SpriteNames.TryGetValue(name, out __result)) - return true; - return false; - } + if (!SpriteNames.TryGetValue(name, out __result)) + return true; + return false; + } private static void LoadPostfix() { - foreach (var func in DeferredInitialization) - { - var sprite = func(); - SpriteNames[sprite.Name] = sprite; - } + foreach (var func in DeferredInitialization) + { + var sprite = func(); + SpriteNames[sprite.Name] = sprite; } + } private static IEnumerable BlankTranspiler(IEnumerable instructions) => instructions; } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/TPac/AssetItem.cs b/src/Bannerlord.LauncherEx/TPac/AssetItem.cs index fcf02ca..8a244c0 100644 --- a/src/Bannerlord.LauncherEx/TPac/AssetItem.cs +++ b/src/Bannerlord.LauncherEx/TPac/AssetItem.cs @@ -15,16 +15,16 @@ internal class AssetItem public AssetItem(Guid type) { - Type = type; - Guid = Guid.Empty; - Name = string.Empty; - } + Type = type; + Guid = Guid.Empty; + Name = string.Empty; + } public virtual void ReadMetadata(BinaryReader stream, int totalSize) { - stream.BaseStream.Seek(totalSize, SeekOrigin.Current); - //_temp_metadata = stream.ReadBytes(totalSize); - } + stream.BaseStream.Seek(totalSize, SeekOrigin.Current); + //_temp_metadata = stream.ReadBytes(totalSize); + } public virtual void ConsumeDataSegments(AbstractExternalLoader[] externalData) { } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/TPac/AssetPackage.cs b/src/Bannerlord.LauncherEx/TPac/AssetPackage.cs index b978410..a40c213 100644 --- a/src/Bannerlord.LauncherEx/TPac/AssetPackage.cs +++ b/src/Bannerlord.LauncherEx/TPac/AssetPackage.cs @@ -18,88 +18,88 @@ internal class AssetPackage public AssetPackage(string filePath) { - File = new FileInfo(filePath); - } + File = new FileInfo(filePath); + } public Texture? GetTexture(string id) { - Load(); - return Items.OfType().FirstOrDefault(x => x.Name == id); - } + Load(); + return Items.OfType().FirstOrDefault(x => x.Name == id); + } public void Load() { - if (!HeaderLoaded) - { - using var stream = File.OpenBinaryReader(); - Load(stream); - } + if (!HeaderLoaded) + { + using var stream = File.OpenBinaryReader(); + Load(stream); } + } protected virtual void Load(BinaryReader stream) { - if (!stream.BaseStream.CanSeek) - throw new IOException("The base stream must support random access (seek)."); - HeaderLoaded = true; - - if (stream.ReadUInt32() != TPAC_MAGIC_NUMBER) - throw new IOException($"Not a Tpac file: {File.FullName}"); - var version = stream.ReadUInt32(); - switch (version) - { - case 1: // 1.0.0~1.4.2 - case 2: // since 1.4.3 - break; - default: - throw new Exception("Unsupported Tpac version: " + version); - } + if (!stream.BaseStream.CanSeek) + throw new IOException("The base stream must support random access (seek)."); + HeaderLoaded = true; + + if (stream.ReadUInt32() != TPAC_MAGIC_NUMBER) + throw new IOException($"Not a Tpac file: {File.FullName}"); + var version = stream.ReadUInt32(); + switch (version) + { + case 1: // 1.0.0~1.4.2 + case 2: // since 1.4.3 + break; + default: + throw new Exception("Unsupported Tpac version: " + version); + } + + stream.ReadGuid(); + + var resourceNum = stream.ReadUInt32(); + var dataOffset = stream.ReadUInt32(); + stream.ReadUInt32(); // skip reserve - stream.ReadGuid(); + for (var i = 0; i < resourceNum; i++) + { + var typeGuid = stream.ReadGuid(); + TypedAssetFactory.CreateTypedAsset(typeGuid, out var assetItem); + assetItem.Guid = stream.ReadGuid(); - var resourceNum = stream.ReadUInt32(); - var dataOffset = stream.ReadUInt32(); - stream.ReadUInt32(); // skip reserve + uint assetVersion = 0; + if (version > 1) assetVersion = stream.ReadUInt32(); + assetItem.Version = assetVersion; + assetItem.Name = stream.ReadSizedString(); - for (var i = 0; i < resourceNum; i++) + var metadataSize = stream.ReadUInt64(); + assetItem.ReadMetadata(stream, (int) metadataSize); + var unknownMetadataChecknum = stream.ReadInt64(); + + var dataSegmentNum = stream.ReadInt32(); + var segments = new AbstractExternalLoader[dataSegmentNum]; + for (var j = 0; j < dataSegmentNum; j++) { - var typeGuid = stream.ReadGuid(); - TypedAssetFactory.CreateTypedAsset(typeGuid, out var assetItem); - assetItem.Guid = stream.ReadGuid(); - - uint assetVersion = 0; - if (version > 1) assetVersion = stream.ReadUInt32(); - assetItem.Version = assetVersion; - assetItem.Name = stream.ReadSizedString(); - - var metadataSize = stream.ReadUInt64(); - assetItem.ReadMetadata(stream, (int) metadataSize); - var unknownMetadataChecknum = stream.ReadInt64(); - - var dataSegmentNum = stream.ReadInt32(); - var segments = new AbstractExternalLoader[dataSegmentNum]; - for (var j = 0; j < dataSegmentNum; j++) - { - var segOffset = stream.ReadUInt64(); - var segActualSize = stream.ReadUInt64(); - var segStorageSize = stream.ReadUInt64(); - var segGuid = stream.ReadGuid(); - var segTypeGuid = stream.ReadGuid(); - TypedDataFactory.CreateTypedLoader(segTypeGuid, File, out var result); - result._offset = segOffset; - result._actualSize = segActualSize; - result._storageSize = segStorageSize; - result.OwnerGuid = segGuid; - stream.ReadUInt64(); - stream.ReadUInt32(); - result._storageFormat = (AbstractExternalLoader.StorageFormat) stream.ReadByte(); - segments[j] = result; - } - - assetItem.ConsumeDataSegments(segments); - - var depNum = stream.ReadInt32(); - stream.BaseStream.Seek(depNum * 3 * Unsafe.SizeOf(), SeekOrigin.Current); - Items.Add(assetItem); + var segOffset = stream.ReadUInt64(); + var segActualSize = stream.ReadUInt64(); + var segStorageSize = stream.ReadUInt64(); + var segGuid = stream.ReadGuid(); + var segTypeGuid = stream.ReadGuid(); + TypedDataFactory.CreateTypedLoader(segTypeGuid, File, out var result); + result._offset = segOffset; + result._actualSize = segActualSize; + result._storageSize = segStorageSize; + result.OwnerGuid = segGuid; + stream.ReadUInt64(); + stream.ReadUInt32(); + result._storageFormat = (AbstractExternalLoader.StorageFormat) stream.ReadByte(); + segments[j] = result; } + + assetItem.ConsumeDataSegments(segments); + + var depNum = stream.ReadInt32(); + stream.BaseStream.Seek(depNum * 3 * Unsafe.SizeOf(), SeekOrigin.Current); + Items.Add(assetItem); } + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/TPac/ExternalData.cs b/src/Bannerlord.LauncherEx/TPac/ExternalData.cs index a7a73d5..10a8c86 100644 --- a/src/Bannerlord.LauncherEx/TPac/ExternalData.cs +++ b/src/Bannerlord.LauncherEx/TPac/ExternalData.cs @@ -10,17 +10,17 @@ internal class ExternalData public ExternalData() { - TypeGuid = Guid.Empty; - } + TypeGuid = Guid.Empty; + } public ExternalData(Guid typeGuid) { - TypeGuid = typeGuid; - } + TypeGuid = typeGuid; + } public virtual void ReadData(BinaryReader stream, IDictionary userdata, int totalSize) { - stream.BaseStream.Seek(totalSize, SeekOrigin.Current); - //_unknownRawData = stream.ReadBytes(totalSize); - } + stream.BaseStream.Seek(totalSize, SeekOrigin.Current); + //_unknownRawData = stream.ReadBytes(totalSize); + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/TPac/ExternalLoader.cs b/src/Bannerlord.LauncherEx/TPac/ExternalLoader.cs index f950542..be569d1 100644 --- a/src/Bannerlord.LauncherEx/TPac/ExternalLoader.cs +++ b/src/Bannerlord.LauncherEx/TPac/ExternalLoader.cs @@ -11,81 +11,81 @@ namespace Bannerlord.LauncherEx.TPac; internal ExternalLoader(FileInfo file) { - _file = file; - if (!_file.Exists) throw new FileNotFoundException("Cannot find file: " + _file.FullName); - OwnerGuid = Guid.Empty; - } + _file = file; + if (!_file.Exists) throw new FileNotFoundException("Cannot find file: " + _file.FullName); + OwnerGuid = Guid.Empty; + } public ExternalLoader() : this(new T()) { } public ExternalLoader(T data) { - _file = null; - //OwnerGuid = Guid.NewGuid(); // sz: don't assign a random guid for it makes no sense - OwnerGuid = Guid.Empty; - if (data.TypeGuid == Guid.Empty) - { - throw new ArgumentException("The data which were assigned to the loader must have a type guid."); - } - - TypeGuid = data.TypeGuid; + _file = null; + //OwnerGuid = Guid.NewGuid(); // sz: don't assign a random guid for it makes no sense + OwnerGuid = Guid.Empty; + if (data.TypeGuid == Guid.Empty) + { + throw new ArgumentException("The data which were assigned to the loader must have a type guid."); } + TypeGuid = data.TypeGuid; + } + private T ReadData() { - if (_file is null) throw new InvalidOperationException("Can't read data from file"); - using var stream = _file.OpenBinaryReader(); - return ReadData(stream); - } + if (_file is null) throw new InvalidOperationException("Can't read data from file"); + using var stream = _file.OpenBinaryReader(); + return ReadData(stream); + } private T ReadData(BinaryReader fullStream) { - var rawData = GetRawData(fullStream); - var data = new T(); - using (var stream = rawData.CreateBinaryReader()) - { - data.ReadData(stream, _userdata.IsValueCreated ? _userdata.Value : EMPTY_USERDATA, (int) _actualSize); - } + var rawData = GetRawData(fullStream); + var data = new T(); + using (var stream = rawData.CreateBinaryReader()) + { + data.ReadData(stream, _userdata.IsValueCreated ? _userdata.Value : EMPTY_USERDATA, (int) _actualSize); + } - if (rawData.Length > IMMEDIATELY_GC_THRESHOLD) - { - rawData = null; - GC.Collect(); - } + if (rawData.Length > IMMEDIATELY_GC_THRESHOLD) + { + rawData = null; + GC.Collect(); + } - data.TypeGuid = TypeGuid; + data.TypeGuid = TypeGuid; - return data; - } + return data; + } private byte[] GetRawData(BinaryReader stream) { - byte[]? rawData; - if (!stream.BaseStream.CanSeek) - throw new IOException("The base stream must support random access (seek)"); - stream.BaseStream.Seek((long) _offset, SeekOrigin.Begin); - switch (_storageFormat) + byte[]? rawData; + if (!stream.BaseStream.CanSeek) + throw new IOException("The base stream must support random access (seek)"); + stream.BaseStream.Seek((long) _offset, SeekOrigin.Begin); + switch (_storageFormat) + { + case StorageFormat.Uncompressed: { - case StorageFormat.Uncompressed: - { - rawData = stream.ReadBytes((int) _storageSize); - break; - } - case StorageFormat.LZ4HC: - { - rawData = stream.ReadBytes((int) _storageSize); - rawData = LZ4Decompress(rawData, (int) _actualSize); - if (rawData.Length > IMMEDIATELY_GC_THRESHOLD) - GC.Collect(); - break; - } - default: - throw new ArgumentException("Unsupported data storage format: " + _storageFormat); + rawData = stream.ReadBytes((int) _storageSize); + break; } - - return rawData; + case StorageFormat.LZ4HC: + { + rawData = stream.ReadBytes((int) _storageSize); + rawData = LZ4Decompress(rawData, (int) _actualSize); + if (rawData.Length > IMMEDIATELY_GC_THRESHOLD) + GC.Collect(); + break; + } + default: + throw new ArgumentException("Unsupported data storage format: " + _storageFormat); } + return rawData; + } + public T GetData() => ReadData(); private static byte[] LZ4Decompress(byte[] input, int outLength) => LZ4Codec.Decode(input, 0, input.Length, outLength); diff --git a/src/Bannerlord.LauncherEx/TPac/TexturePixelData.cs b/src/Bannerlord.LauncherEx/TPac/TexturePixelData.cs index 6f1bd7e..f7b0870 100644 --- a/src/Bannerlord.LauncherEx/TPac/TexturePixelData.cs +++ b/src/Bannerlord.LauncherEx/TPac/TexturePixelData.cs @@ -29,64 +29,64 @@ public TexturePixelData() : base(TYPE_GUID) { } public override void ReadData(BinaryReader stream, IDictionary userdata, int totalSize) { - int array = 1, mipmap = 1; - if (userdata.TryGetValue(KEY_ARRAY, out var arrayObj)) - { - array = (int) arrayObj; - } - - if (userdata.TryGetValue(KEY_MIPMAP, out var mipmapObj)) - { - mipmap = (int) mipmapObj; - } - - if (!userdata.TryGetValue(KEY_WIDTH, out var widthObj) || !userdata.TryGetValue(KEY_HEIGHT, out var heightObj) || !userdata.TryGetValue(KEY_FORMAT, out var formatObj)) - { - throw new ArgumentException("No enough user data for width, height and format"); - } + int array = 1, mipmap = 1; + if (userdata.TryGetValue(KEY_ARRAY, out var arrayObj)) + { + array = (int) arrayObj; + } - var width = (int) widthObj; - var height = (int) heightObj; - var format = (TextureFormat) formatObj; - var aligh = format.GetAlignSize(); - var pixelSize = format.GetBitsPerPixel(); + if (userdata.TryGetValue(KEY_MIPMAP, out var mipmapObj)) + { + mipmap = (int) mipmapObj; + } - //var raw = stream.ReadBytes(totalSize); + if (!userdata.TryGetValue(KEY_WIDTH, out var widthObj) || !userdata.TryGetValue(KEY_HEIGHT, out var heightObj) || !userdata.TryGetValue(KEY_FORMAT, out var formatObj)) + { + throw new ArgumentException("No enough user data for width, height and format"); + } - var raw = new byte[array][][]; - for (var a = 0; a < array; a++) + var width = (int) widthObj; + var height = (int) heightObj; + var format = (TextureFormat) formatObj; + var aligh = format.GetAlignSize(); + var pixelSize = format.GetBitsPerPixel(); + + //var raw = stream.ReadBytes(totalSize); + + var raw = new byte[array][][]; + for (var a = 0; a < array; a++) + { + raw[a] = new byte[mipmap][]; + var imageWidth = width; + var imageHeight = height; + for (var m = 0; m < mipmap; m++) { - raw[a] = new byte[mipmap][]; - var imageWidth = width; - var imageHeight = height; - for (var m = 0; m < mipmap; m++) + var alignedWidth = imageWidth; + var alignedHeight = imageHeight; + if (alignedWidth % aligh != 0) { - var alignedWidth = imageWidth; - var alignedHeight = imageHeight; - if (alignedWidth % aligh != 0) - { - alignedWidth += aligh - (alignedWidth % aligh); - } - - if (alignedHeight % aligh != 0) - { - alignedHeight += aligh - (alignedHeight % aligh); - } - - // prevent from overflow for mega textures or underflow for very small mipmap - // should be alignedWidth * alignedHeight * pixelSize / 8 - var readSize = alignedWidth * alignedHeight; - // if readSize & 7 != 0, then it cannot be divided exactly - if (readSize >= 8 && (readSize & 7) == 0) - readSize = readSize / 8 * pixelSize; - else - readSize = readSize * pixelSize / 8; - raw[a][m] = stream.ReadBytes(readSize); - imageWidth = Math.Max(imageWidth >> 1, 1); - imageHeight = Math.Max(imageHeight >> 1, 1); + alignedWidth += aligh - (alignedWidth % aligh); + } + + if (alignedHeight % aligh != 0) + { + alignedHeight += aligh - (alignedHeight % aligh); } - } - RawImage = raw; + // prevent from overflow for mega textures or underflow for very small mipmap + // should be alignedWidth * alignedHeight * pixelSize / 8 + var readSize = alignedWidth * alignedHeight; + // if readSize & 7 != 0, then it cannot be divided exactly + if (readSize >= 8 && (readSize & 7) == 0) + readSize = readSize / 8 * pixelSize; + else + readSize = readSize * pixelSize / 8; + raw[a][m] = stream.ReadBytes(readSize); + imageWidth = Math.Max(imageWidth >> 1, 1); + imageHeight = Math.Max(imageHeight >> 1, 1); + } } + + RawImage = raw; + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/TPac/TypedAssetFactory.cs b/src/Bannerlord.LauncherEx/TPac/TypedAssetFactory.cs index 19fff49..a78ad99 100644 --- a/src/Bannerlord.LauncherEx/TPac/TypedAssetFactory.cs +++ b/src/Bannerlord.LauncherEx/TPac/TypedAssetFactory.cs @@ -11,40 +11,40 @@ internal static class TypedAssetFactory static TypedAssetFactory() { - RegisterType(typeof(Texture)); - } + RegisterType(typeof(Texture)); + } public static void RegisterType(Type typeClass) { - var field = typeClass.GetField("TYPE_GUID", BindingFlags.Static | BindingFlags.Public) ?? throw new ArgumentException("Cannot find public static field \"TYPE_GUID\" from class " + typeClass.FullName); - if (field.FieldType != typeof(Guid)) throw new ArgumentException("\"TYPE_GUID\" must be Guid"); - var guid = (Guid) field.GetValue(null); - RegisterType(guid, typeClass); - } + var field = typeClass.GetField("TYPE_GUID", BindingFlags.Static | BindingFlags.Public) ?? throw new ArgumentException("Cannot find public static field \"TYPE_GUID\" from class " + typeClass.FullName); + if (field.FieldType != typeof(Guid)) throw new ArgumentException("\"TYPE_GUID\" must be Guid"); + var guid = (Guid) field.GetValue(null); + RegisterType(guid, typeClass); + } public static void RegisterType(Guid typeGuid, Type typeClass) { - if (!typeof(AssetItem).IsAssignableFrom(typeClass)) - throw new ArgumentException("Registered type must extend from AssetItem"); + if (!typeof(AssetItem).IsAssignableFrom(typeClass)) + throw new ArgumentException("Registered type must extend from AssetItem"); - var constructor = typeClass.GetConstructor(Type.EmptyTypes); - if (constructor == null) - throw new ArgumentException("Registered type must have a param-less constructor"); + var constructor = typeClass.GetConstructor(Type.EmptyTypes); + if (constructor == null) + throw new ArgumentException("Registered type must have a param-less constructor"); - classMap[typeGuid] = typeClass; - constructorMap[typeGuid] = constructor; - } + classMap[typeGuid] = typeClass; + constructorMap[typeGuid] = constructor; + } public static bool CreateTypedAsset(Guid typeGuid, out AssetItem result) { - if (classMap.ContainsKey(typeGuid)) - { - var constructor = constructorMap[typeGuid]; - result = (AssetItem) constructor.Invoke(null); - return true; - } - - result = new AssetItem(typeGuid); - return false; + if (classMap.ContainsKey(typeGuid)) + { + var constructor = constructorMap[typeGuid]; + result = (AssetItem) constructor.Invoke(null); + return true; } + + result = new AssetItem(typeGuid); + return false; + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/TPac/TypedDataFactory.cs b/src/Bannerlord.LauncherEx/TPac/TypedDataFactory.cs index c6d1a2b..26d42d5 100644 --- a/src/Bannerlord.LauncherEx/TPac/TypedDataFactory.cs +++ b/src/Bannerlord.LauncherEx/TPac/TypedDataFactory.cs @@ -12,45 +12,45 @@ internal static class TypedDataFactory static TypedDataFactory() { - RegisterType(typeof(TexturePixelData)); - } + RegisterType(typeof(TexturePixelData)); + } public static void RegisterType(Type typeClass) { - var field = typeClass.GetField("TYPE_GUID", BindingFlags.Static | BindingFlags.Public) ?? throw new ArgumentException("Cannot find public static field \"TYPE_GUID\" from class " + typeClass.FullName); - if (field.FieldType != typeof(Guid)) throw new ArgumentException("\"TYPE_GUID\" must be Guid"); - var guid = (Guid) field.GetValue(null); - RegisterType(guid, typeClass); - } + var field = typeClass.GetField("TYPE_GUID", BindingFlags.Static | BindingFlags.Public) ?? throw new ArgumentException("Cannot find public static field \"TYPE_GUID\" from class " + typeClass.FullName); + if (field.FieldType != typeof(Guid)) throw new ArgumentException("\"TYPE_GUID\" must be Guid"); + var guid = (Guid) field.GetValue(null); + RegisterType(guid, typeClass); + } public static void RegisterType(Guid typeGuid, Type typeClass) { - if (!typeof(ExternalData).IsAssignableFrom(typeClass)) - throw new ArgumentException("Registered type must extend from ExternalData"); + if (!typeof(ExternalData).IsAssignableFrom(typeClass)) + throw new ArgumentException("Registered type must extend from ExternalData"); - var constructor = typeClass.GetConstructor(Type.EmptyTypes); - if (constructor == null) throw new ArgumentException("Registered type must have a param-less constructor"); + var constructor = typeClass.GetConstructor(Type.EmptyTypes); + if (constructor == null) throw new ArgumentException("Registered type must have a param-less constructor"); - var loaderType = typeof(ExternalLoader<>).MakeGenericType(typeClass); - guidToLoaderTypeMap[typeGuid] = loaderType; - guidToLoaderConstructorMap[typeGuid] = loaderType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(FileInfo) }, null); - } + var loaderType = typeof(ExternalLoader<>).MakeGenericType(typeClass); + guidToLoaderTypeMap[typeGuid] = loaderType; + guidToLoaderConstructorMap[typeGuid] = loaderType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(FileInfo) }, null); + } public static bool CreateTypedLoader(Guid typeGuid, FileInfo file, out AbstractExternalLoader result) { - AbstractExternalLoader? loader = null; - var isFound = false; - if (guidToLoaderTypeMap.ContainsKey(typeGuid)) - { - var constructor = guidToLoaderConstructorMap[typeGuid]; - loader = (AbstractExternalLoader) constructor.Invoke(new object[] { file }); - isFound = true; - } - - loader ??= new ExternalLoader(file); - - loader.TypeGuid = typeGuid; - result = loader; - return isFound; + AbstractExternalLoader? loader = null; + var isFound = false; + if (guidToLoaderTypeMap.ContainsKey(typeGuid)) + { + var constructor = guidToLoaderConstructorMap[typeGuid]; + loader = (AbstractExternalLoader) constructor.Invoke(new object[] { file }); + isFound = true; } + + loader ??= new ExternalLoader(file); + + loader.TypeGuid = typeGuid; + result = loader; + return isFound; + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/TPac/Utils.cs b/src/Bannerlord.LauncherEx/TPac/Utils.cs index c167ca8..6bba3de 100644 --- a/src/Bannerlord.LauncherEx/TPac/Utils.cs +++ b/src/Bannerlord.LauncherEx/TPac/Utils.cs @@ -9,26 +9,26 @@ internal static class Utils { public static string ReadSizedString(this BinaryReader stream) { - var num = stream.ReadInt32(); - if (num == 0) - { - return string.Empty; - } - - var array = stream.ReadBytes(num); - return Encoding.UTF8.GetString(array); + var num = stream.ReadInt32(); + if (num == 0) + { + return string.Empty; } + var array = stream.ReadBytes(num); + return Encoding.UTF8.GetString(array); + } + public static List ReadStringList(this BinaryReader stream) { - var num = stream.ReadInt32(); - var list = new List(num); - for (var i = 0; i < num; i++) - { - list.Add(stream.ReadSizedString()); - } - return list; + var num = stream.ReadInt32(); + var list = new List(num); + for (var i = 0; i < num; i++) + { + list.Add(stream.ReadSizedString()); } + return list; + } public static Guid ReadGuid(this BinaryReader stream) => new Guid(stream.ReadBytes(16)); diff --git a/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherMessageBoxVM.cs b/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherMessageBoxVM.cs index 60c6d83..fc680a2 100644 --- a/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherMessageBoxVM.cs +++ b/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherMessageBoxVM.cs @@ -30,24 +30,24 @@ internal class BUTRLauncherMessageBoxVM : BUTRViewModel public void Show(string title, string description, Action? onConfirm, Action? onCancel) { - if (IsEnabled) return; + if (IsEnabled) return; - Title = title; - Description = description; - _onConfirm = onConfirm; - _onCancel = onCancel; - IsEnabled = true; - } + Title = title; + Description = description; + _onConfirm = onConfirm; + _onCancel = onCancel; + IsEnabled = true; + } private void ExecuteConfirm() { - _onConfirm?.Invoke(); - IsEnabled = false; - } + _onConfirm?.Invoke(); + IsEnabled = false; + } private void ExecuteCancel() { - _onCancel?.Invoke(); - IsEnabled = false; - } + _onCancel?.Invoke(); + IsEnabled = false; + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherModuleVM.cs b/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherModuleVM.cs index 288f257..57f7911 100644 --- a/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherModuleVM.cs +++ b/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherModuleVM.cs @@ -57,13 +57,13 @@ public bool IsDisabled get => _isDisabled; set { - if (value != _isDisabled) - { - _isDisabled = value; - OnPropertyChanged(); - OnPropertyChanged(nameof(IsNotSelectable)); - } + if (value != _isDisabled) + { + _isDisabled = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(IsNotSelectable)); } + } } private bool _isDisabled; @@ -77,14 +77,14 @@ public string IssuesText get => _issuesText; set { - if (value != _issuesText) - { - _issuesText = value; - OnPropertyChanged(); - OnPropertyChanged(nameof(IsNotSelectable)); - OnPropertyChanged(nameof(IsValid)); - } + if (value != _issuesText) + { + _issuesText = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(IsNotSelectable)); + OnPropertyChanged(nameof(IsValid)); } + } } private string _issuesText = string.Empty; @@ -101,70 +101,70 @@ public string IssuesText public BUTRLauncherModuleVM(ModuleInfoExtendedWithPath moduleInfoExtended, Action select, Func> validate) { - ModuleInfoExtended = moduleInfoExtended; - _select = select; - _validate = validate; + ModuleInfoExtended = moduleInfoExtended; + _select = select; + _validate = validate; - if (ModuleDependencyConstructor.GetDependencyHint(moduleInfoExtended) is { } str) - { - DependencyHint = new LauncherHintVM(str); - AnyDependencyAvailable = !string.IsNullOrEmpty(str); - } + if (ModuleDependencyConstructor.GetDependencyHint(moduleInfoExtended) is { } str) + { + DependencyHint = new LauncherHintVM(str); + AnyDependencyAvailable = !string.IsNullOrEmpty(str); + } - var dangerous = string.Empty; - if (ModuleChecker.IsInstalledInMainAndExternalModuleDirectory(moduleInfoExtended)) - { - dangerous += new BUTRTextObject("{=kfMQEOFS}The Module is installed in the game's /Modules folder and on Steam Workshop!{NL}The /Modules version will be used!").ToString(); - } - if (ModuleChecker.IsObfuscated(moduleInfoExtended)) - { - if (dangerous.Length != 0) dangerous += "\n"; - dangerous += new BUTRTextObject("{=aAYdk1zd}The DLL is obfuscated!{NL}There is no guarantee that the code is safe!{NL}The BUTR Team warns of consequences arising from running obfuscated code!").ToString(); - } - if (!string.IsNullOrEmpty(dangerous)) - { - IsDangerous = true; - DangerousHint = new LauncherHintVM(dangerous); - } - else - { - IsDangerous = false; - DangerousHint = new LauncherHintVM(dangerous); - } + var dangerous = string.Empty; + if (ModuleChecker.IsInstalledInMainAndExternalModuleDirectory(moduleInfoExtended)) + { + dangerous += new BUTRTextObject("{=kfMQEOFS}The Module is installed in the game's /Modules folder and on Steam Workshop!{NL}The /Modules version will be used!").ToString(); } + if (ModuleChecker.IsObfuscated(moduleInfoExtended)) + { + if (dangerous.Length != 0) dangerous += "\n"; + dangerous += new BUTRTextObject("{=aAYdk1zd}The DLL is obfuscated!{NL}There is no guarantee that the code is safe!{NL}The BUTR Team warns of consequences arising from running obfuscated code!").ToString(); + } + if (!string.IsNullOrEmpty(dangerous)) + { + IsDangerous = true; + DangerousHint = new LauncherHintVM(dangerous); + } + else + { + IsDangerous = false; + DangerousHint = new LauncherHintVM(dangerous); + } + } public void Validate() { - var validationIssues = _validate(this).ToList(); + var validationIssues = _validate(this).ToList(); - IssuesText = validationIssues.Count > 0 - ? string.Join("\n", validationIssues) - : string.Empty; - } + IssuesText = validationIssues.Count > 0 + ? string.Join("\n", validationIssues) + : string.Empty; + } [BUTRDataSourceMethod] public void ExecuteSelect() { - if (IsNotSelectable) - return; + if (IsNotSelectable) + return; - _select(this); - } + _select(this); + } [BUTRDataSourceMethod] public void ExecuteOpen() { - if (Integrations.IsModOrganizer2) - { - var explorer = Path.Combine(Integrations.ModOrganizer2Path!, "explorer++", "Explorer++.exe"); - if (!File.Exists(explorer)) return; - Process.Start(explorer, $"\"{ModuleInfoExtended.Path}\""); - return; - } - - if (!Directory.Exists(ModuleInfoExtended.Path)) return; - Process.Start(ModuleInfoExtended.Path); + if (Integrations.IsModOrganizer2) + { + var explorer = Path.Combine(Integrations.ModOrganizer2Path!, "explorer++", "Explorer++.exe"); + if (!File.Exists(explorer)) return; + Process.Start(explorer, $"\"{ModuleInfoExtended.Path}\""); + return; } + if (!Directory.Exists(ModuleInfoExtended.Path)) return; + Process.Start(ModuleInfoExtended.Path); + } + public override string ToString() => $"{ModuleInfoExtended}, IsSelected: {IsSelected}, IsValid: {IsValid}"; } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherSaveVM.cs b/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherSaveVM.cs index 45385cb..5b058d0 100644 --- a/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherSaveVM.cs +++ b/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherSaveVM.cs @@ -83,104 +83,104 @@ private record ModuleListEntry(string Name, ApplicationVersion Version); public BUTRLauncherSaveVM(SaveMetadata saveMetadata, Action select, Func getModuleById, Func getModuleByName) { - _saveMetadata = saveMetadata; - _select = select; - _getModuleById = getModuleById; - _getModuleByName = getModuleByName; - - _name = _saveMetadata.Name; - _version = _saveMetadata.TryGetValue("ApplicationVersion", out var appVersion) && !string.IsNullOrEmpty(appVersion) ? string.Join(".", appVersion.Split('.').Take(3)) : "Save Old"; - _characterName = _saveMetadata.TryGetValue("CharacterName", out var characterName) && !string.IsNullOrEmpty(characterName) ? characterName : "Save Old"; - _level = _saveMetadata.TryGetValue("MainHeroLevel", out var level) && !string.IsNullOrEmpty(level) ? level : "Save Old"; - _days = _saveMetadata.TryGetValue("DayLong", out var daysr) && !string.IsNullOrEmpty(daysr) && float.TryParse(daysr, out var days) ? days.ToString("0") : "Save Old"; - _createdAt = _saveMetadata.TryGetValue("CreationTime", out var ctr) && !string.IsNullOrEmpty(ctr) && long.TryParse(ctr, out var ticks) ? new DateTime(ticks).ToString("d") : "Save Old"; - - ValidateSave(); - } + _saveMetadata = saveMetadata; + _select = select; + _getModuleById = getModuleById; + _getModuleByName = getModuleByName; + + _name = _saveMetadata.Name; + _version = _saveMetadata.TryGetValue("ApplicationVersion", out var appVersion) && !string.IsNullOrEmpty(appVersion) ? string.Join(".", appVersion.Split('.').Take(3)) : "Save Old"; + _characterName = _saveMetadata.TryGetValue("CharacterName", out var characterName) && !string.IsNullOrEmpty(characterName) ? characterName : "Save Old"; + _level = _saveMetadata.TryGetValue("MainHeroLevel", out var level) && !string.IsNullOrEmpty(level) ? level : "Save Old"; + _days = _saveMetadata.TryGetValue("DayLong", out var daysr) && !string.IsNullOrEmpty(daysr) && float.TryParse(daysr, out var days) ? days.ToString("0") : "Save Old"; + _createdAt = _saveMetadata.TryGetValue("CreationTime", out var ctr) && !string.IsNullOrEmpty(ctr) && long.TryParse(ctr, out var ticks) ? new DateTime(ticks).ToString("d") : "Save Old"; + + ValidateSave(); + } private void ValidateSave() { - var changeset = _saveMetadata.GetChangeSet(); - var modules = _saveMetadata.GetModules().Select(x => - { - var version = _saveMetadata.GetModuleVersion(x); - if (version.ChangeSet == changeset) - version = new ApplicationVersion(version.ApplicationVersionType, version.Major, version.Minor, version.Revision, 0); - return new ModuleListEntry(x, version); - }).ToArray(); - - var existingModules = modules.Select(x => _getModuleByName(x.Name)).OfType().ToArray(); - var nameDuplicates = existingModules.Select(x => x.Name).GroupBy(i => i).Where(g => g.Count() > 1).Select(g => g.Key).ToList(); - if (nameDuplicates.Count > 0) - { - HasError = true; - ErrorHint = new LauncherHintVM(new BUTRTextObject("{=vCwH9226}Duplicate Module Names:{NL}{MODULENAMES}") - .SetTextVariable("MODULENAMES", string.Join("\n", nameDuplicates)).ToString()); - return; - } - var existingModulesByName = existingModules.ToDictionary(x => x.Name, x => x); + var changeset = _saveMetadata.GetChangeSet(); + var modules = _saveMetadata.GetModules().Select(x => + { + var version = _saveMetadata.GetModuleVersion(x); + if (version.ChangeSet == changeset) + version = new ApplicationVersion(version.ApplicationVersionType, version.Major, version.Minor, version.Revision, 0); + return new ModuleListEntry(x, version); + }).ToArray(); + + var existingModules = modules.Select(x => _getModuleByName(x.Name)).OfType().ToArray(); + var nameDuplicates = existingModules.Select(x => x.Name).GroupBy(i => i).Where(g => g.Count() > 1).Select(g => g.Key).ToList(); + if (nameDuplicates.Count > 0) + { + HasError = true; + ErrorHint = new LauncherHintVM(new BUTRTextObject("{=vCwH9226}Duplicate Module Names:{NL}{MODULENAMES}") + .SetTextVariable("MODULENAMES", string.Join("\n", nameDuplicates)).ToString()); + return; + } + var existingModulesByName = existingModules.ToDictionary(x => x.Name, x => x); - ModuleListCode = $"_MODULES_*{string.Join("*", existingModules.Select(x => x.Id))}*_MODULES_"; + ModuleListCode = $"_MODULES_*{string.Join("*", existingModules.Select(x => x.Id))}*_MODULES_"; - var missingNames = modules.Select(x => x.Name).Except(existingModulesByName.Keys).ToArray(); - var loadOrderIssues = LoadOrderChecker.IsLoadOrderCorrect(existingModules).ToList(); + var missingNames = modules.Select(x => x.Name).Except(existingModulesByName.Keys).ToArray(); + var loadOrderIssues = LoadOrderChecker.IsLoadOrderCorrect(existingModules).ToList(); - //LoadOrderHint = new LauncherHintVM($"Load Order:\n{string.Join("\n", existingModules.Select(x => x.Id))}\n\nUnknown Mod Names:{string.Join("\n", missingNames)}"); - LoadOrderHint = new LauncherHintVM(new BUTRTextObject("{=sd6M4KRd}Load Order:{NL}{LOADORDER}") - .SetTextVariable("LOADORDER", string.Join("\n", modules.Select(x => _getModuleByName(x.Name)?.Id ?? $"{x.Name} {new BUTRTextObject("{=kxqLbSqe}(Unknown ID)")}"))).ToString()); + //LoadOrderHint = new LauncherHintVM($"Load Order:\n{string.Join("\n", existingModules.Select(x => x.Id))}\n\nUnknown Mod Names:{string.Join("\n", missingNames)}"); + LoadOrderHint = new LauncherHintVM(new BUTRTextObject("{=sd6M4KRd}Load Order:{NL}{LOADORDER}") + .SetTextVariable("LOADORDER", string.Join("\n", modules.Select(x => _getModuleByName(x.Name)?.Id ?? $"{x.Name} {new BUTRTextObject("{=kxqLbSqe}(Unknown ID)")}"))).ToString()); - if (missingNames.Length > 0 || loadOrderIssues.Count > 0) + if (missingNames.Length > 0 || loadOrderIssues.Count > 0) + { + var text = string.Empty; + if (loadOrderIssues.Count > 0) { - var text = string.Empty; - if (loadOrderIssues.Count > 0) - { - text += new BUTRTextObject("{=HvvA78sZ}Load Order Issues:{NL}{LOADORDERISSUES}") - .SetTextVariable("LOADORDERISSUES", string.Join("\n\n", loadOrderIssues)); - text += missingNames.Length > 0 ? "\n\n\n" : string.Empty; - } - if (missingNames.Length > 0) - { - text += new BUTRTextObject("{=GtDRbC3m}Missing Modules:{NL}{MODULES}") - .SetTextVariable("MODULES", string.Join("\n", missingNames)).ToString(); - } - - HasError = true; - ErrorHint = new LauncherHintVM(text); - return; + text += new BUTRTextObject("{=HvvA78sZ}Load Order Issues:{NL}{LOADORDERISSUES}") + .SetTextVariable("LOADORDERISSUES", string.Join("\n\n", loadOrderIssues)); + text += missingNames.Length > 0 ? "\n\n\n" : string.Empty; } - - var issues = new List(); - foreach (var module in modules) + if (missingNames.Length > 0) { - var existingModule = existingModulesByName[module.Name]; - if (module.Version != existingModule.Version) - { - issues.Add(new BUTRTextObject("{=nYVWoomO}{MODULEID}. Required {REQUIREDVERSION}. Actual {ACTUALVERSION}") - .SetTextVariable("MODULEID", existingModule.Id) - .SetTextVariable("REQUIREDVERSION", module.Version.ToString()) - .SetTextVariable("ACTUALVERSION", existingModule.Version.ToString()).ToString()); - } + text += new BUTRTextObject("{=GtDRbC3m}Missing Modules:{NL}{MODULES}") + .SetTextVariable("MODULES", string.Join("\n", missingNames)).ToString(); } - if (issues.Count > 0) + + HasError = true; + ErrorHint = new LauncherHintVM(text); + return; + } + + var issues = new List(); + foreach (var module in modules) + { + var existingModule = existingModulesByName[module.Name]; + if (module.Version != existingModule.Version) { - HasWarning = true; - WarningHint = new LauncherHintVM(new BUTRTextObject("{=BuMom4Jt}Mismatched Module Versions:{NL}{MODULEVERSIONS}") - .SetTextVariable("MODULEVERSIONS", string.Join("\n\n", issues)).ToString()); + issues.Add(new BUTRTextObject("{=nYVWoomO}{MODULEID}. Required {REQUIREDVERSION}. Actual {ACTUALVERSION}") + .SetTextVariable("MODULEID", existingModule.Id) + .SetTextVariable("REQUIREDVERSION", module.Version.ToString()) + .SetTextVariable("ACTUALVERSION", existingModule.Version.ToString()).ToString()); } } + if (issues.Count > 0) + { + HasWarning = true; + WarningHint = new LauncherHintVM(new BUTRTextObject("{=BuMom4Jt}Mismatched Module Versions:{NL}{MODULEVERSIONS}") + .SetTextVariable("MODULEVERSIONS", string.Join("\n\n", issues)).ToString()); + } + } [BUTRDataSourceMethod] public void ExecuteSelect() { - _select(this); - } + _select(this); + } [BUTRDataSourceMethod] public void ExecuteOpen() { - var saveFilePath = _launcherManagerHandler.GetSaveFilePath(_saveMetadata.Name); - if (string.IsNullOrEmpty(saveFilePath) || !File.Exists(saveFilePath)) return; + var saveFilePath = _launcherManagerHandler.GetSaveFilePath(_saveMetadata.Name); + if (string.IsNullOrEmpty(saveFilePath) || !File.Exists(saveFilePath)) return; - Process.Start("explorer.exe", $"/select,\"{saveFilePath}\""); - } + Process.Start("explorer.exe", $"/select,\"{saveFilePath}\""); + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherSavesVM.cs b/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherSavesVM.cs index 64876b9..88456d0 100644 --- a/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherSavesVM.cs +++ b/src/Bannerlord.LauncherEx/ViewModels/BUTRLauncherSavesVM.cs @@ -53,11 +53,11 @@ public string SearchText get => _searchText; set { - if (SetField(ref _searchText, value)) - { - SearchTextChanged(); - } + if (SetField(ref _searchText, value)) + { + SearchTextChanged(); } + } } private string _searchText = string.Empty; @@ -65,48 +65,48 @@ public string SearchText public BUTRLauncherSavesVM(Func getModuleById, Func getModuleByName) { - _getModuleById = getModuleById; - _getModuleByName = getModuleByName; + _getModuleById = getModuleById; + _getModuleByName = getModuleByName; - ExecuteRefresh(); - } + ExecuteRefresh(); + } private void SelectSave(BUTRLauncherSaveVM saveVM) { - var previousState = saveVM.IsSelected; - foreach (var save in Saves) - { - save.IsSelected = false; - } - saveVM.IsSelected = !previousState; - OnPropertyChanged("SaveSelected"); + var previousState = saveVM.IsSelected; + foreach (var save in Saves) + { + save.IsSelected = false; } + saveVM.IsSelected = !previousState; + OnPropertyChanged("SaveSelected"); + } private void SearchTextChanged() { - var searchText = SearchText; - if (string.IsNullOrEmpty(searchText)) - { - foreach (var saveVM in Saves) - { - saveVM.IsVisible = true; - } - return; - } - + var searchText = SearchText; + if (string.IsNullOrEmpty(searchText)) + { foreach (var saveVM in Saves) { - saveVM.IsVisible = saveVM.Name.IndexOf(SearchText, StringComparison.OrdinalIgnoreCase) != -1; + saveVM.IsVisible = true; } + return; + } + + foreach (var saveVM in Saves) + { + saveVM.IsVisible = saveVM.Name.IndexOf(SearchText, StringComparison.OrdinalIgnoreCase) != -1; } + } [BUTRDataSourceMethod] public void ExecuteRefresh() { - Saves.Clear(); - foreach (var saveFile in _launcherManagerHandler.GetSaveFiles()) - { - Saves.Add(new BUTRLauncherSaveVM(saveFile, SelectSave, _getModuleById, _getModuleByName)); - } + Saves.Clear(); + foreach (var saveFile in _launcherManagerHandler.GetSaveFiles()) + { + Saves.Add(new BUTRLauncherSaveVM(saveFile, SelectSave, _getModuleById, _getModuleByName)); } + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/ViewModels/SettingsPropertyVM.cs b/src/Bannerlord.LauncherEx/ViewModels/SettingsPropertyVM.cs index 119d80e..6e89be5 100644 --- a/src/Bannerlord.LauncherEx/ViewModels/SettingsPropertyVM.cs +++ b/src/Bannerlord.LauncherEx/ViewModels/SettingsPropertyVM.cs @@ -34,13 +34,13 @@ public float FloatValue get => IsFloatVisible ? PropertyReference.Value is float val ? val : float.MinValue : 0f; set { - if (IsFloatVisible && FloatValue != value) - { - PropertyReference.Value = value; - OnPropertyChanged(); - OnPropertyChanged(nameof(TextBoxValue)); - } + if (IsFloatVisible && FloatValue != value) + { + PropertyReference.Value = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(TextBoxValue)); } + } } [BUTRDataSourceProperty] public int IntValue @@ -48,13 +48,13 @@ public int IntValue get => IsIntVisible ? PropertyReference.Value is int val ? val : int.MinValue : 0; set { - if (IsIntVisible && IntValue != value) - { - PropertyReference.Value = value; - OnPropertyChanged(); - OnPropertyChanged(nameof(TextBoxValue)); - } + if (IsIntVisible && IntValue != value) + { + PropertyReference.Value = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(TextBoxValue)); } + } } [BUTRDataSourceProperty] public bool BoolValue @@ -62,12 +62,12 @@ public bool BoolValue get => IsBoolVisible && PropertyReference.Value is bool val ? val : false; set { - if (IsBoolVisible && BoolValue != value) - { - PropertyReference.Value = value; - OnPropertyChanged(); - } + if (IsBoolVisible && BoolValue != value) + { + PropertyReference.Value = value; + OnPropertyChanged(); } + } } [BUTRDataSourceProperty] public string StringValue @@ -75,12 +75,12 @@ public string StringValue get => IsStringVisible ? PropertyReference.Value is string val ? val : "ERROR" : string.Empty; set { - if (IsStringVisible && StringValue != value) - { - PropertyReference.Value = value; - OnPropertyChanged(); - } + if (IsStringVisible && StringValue != value) + { + PropertyReference.Value = value; + OnPropertyChanged(); } + } } [BUTRDataSourceProperty] public string ButtonValue @@ -88,12 +88,12 @@ public string ButtonValue get => IsButtonVisible ? PropertyReference.Value is string val ? val : "ERROR" : string.Empty; set { - if (IsButtonVisible && ButtonValue != value) - { - PropertyReference.Value = value; - OnPropertyChanged(); - } + if (IsButtonVisible && ButtonValue != value) + { + PropertyReference.Value = value; + OnPropertyChanged(); } + } } [BUTRDataSourceProperty] @@ -120,73 +120,73 @@ public string ButtonValue public SettingsPropertyVM(ISettingsPropertyDefinition definition) { - SettingPropertyDefinition = definition; + SettingPropertyDefinition = definition; - // Moved to constructor - IsIntVisible = SettingType == SettingType.Int; - IsFloatVisible = SettingType == SettingType.Float; - IsBoolVisible = SettingType == SettingType.Bool; - IsStringVisible = SettingType == SettingType.String; - IsButtonVisible = SettingType == SettingType.Button; - // Moved to constructor + // Moved to constructor + IsIntVisible = SettingType == SettingType.Int; + IsFloatVisible = SettingType == SettingType.Float; + IsBoolVisible = SettingType == SettingType.Bool; + IsStringVisible = SettingType == SettingType.String; + IsButtonVisible = SettingType == SettingType.Button; + // Moved to constructor - PropertyReference.PropertyChanged += PropertyReference_OnPropertyChanged; + PropertyReference.PropertyChanged += PropertyReference_OnPropertyChanged; - RefreshValues(); - } + RefreshValues(); + } public override void OnFinalize() { - PropertyReference.PropertyChanged -= PropertyReference_OnPropertyChanged; + PropertyReference.PropertyChanged -= PropertyReference_OnPropertyChanged; - base.OnFinalize(); - } + base.OnFinalize(); + } private void PropertyReference_OnPropertyChanged(object? obj, PropertyChangedEventArgs args) { - RefreshValues(); - } + RefreshValues(); + } public override void RefreshValues() { - base.RefreshValues(); + base.RefreshValues(); - switch (SettingType) - { - case SettingType.Bool: - OnPropertyChanged(nameof(BoolValue)); - break; - case SettingType.Int: - OnPropertyChanged(nameof(IntValue)); - break; - case SettingType.Float: - OnPropertyChanged(nameof(FloatValue)); - break; - case SettingType.String: - OnPropertyChanged(nameof(StringValue)); - break; - } - OnPropertyChanged(nameof(TextBoxValue)); + switch (SettingType) + { + case SettingType.Bool: + OnPropertyChanged(nameof(BoolValue)); + break; + case SettingType.Int: + OnPropertyChanged(nameof(IntValue)); + break; + case SettingType.Float: + OnPropertyChanged(nameof(FloatValue)); + break; + case SettingType.String: + OnPropertyChanged(nameof(StringValue)); + break; } + OnPropertyChanged(nameof(TextBoxValue)); + } public override string ToString() => Name; [BUTRDataSourceMethod] public void OnHover() { - if (!string.IsNullOrEmpty(HintText)) - HintManager.ShowHint(HintText); - } + if (!string.IsNullOrEmpty(HintText)) + HintManager.ShowHint(HintText); + } [BUTRDataSourceMethod] public void OnHoverEnd() { - HintManager.HideHint(); - } + HintManager.HideHint(); + } [BUTRDataSourceMethod] public void OnValueClick() { - PropertyReference.Value = PropertyReference.Value; - } + PropertyReference.Value = PropertyReference.Value; + } } \ No newline at end of file diff --git a/src/Bannerlord.LauncherEx/Widgets/LauncherSearchBoxWidget.cs b/src/Bannerlord.LauncherEx/Widgets/LauncherSearchBoxWidget.cs index c8c81c5..f6b0121 100644 --- a/src/Bannerlord.LauncherEx/Widgets/LauncherSearchBoxWidget.cs +++ b/src/Bannerlord.LauncherEx/Widgets/LauncherSearchBoxWidget.cs @@ -12,22 +12,22 @@ public EditableTextWidget? EditableTextWidget get => _editableTextWidget; set { - if (this.SetField(ref _editableTextWidget, value)) - { - if (_editableTextWidget is not null) - _editableTextWidget.PropertyChanged -= SearchTextOnPropertyChanged; - - if (value is not null) - value.PropertyChanged += SearchTextOnPropertyChanged; - } + if (this.SetField(ref _editableTextWidget, value)) + { + if (_editableTextWidget is not null) + _editableTextWidget.PropertyChanged -= SearchTextOnPropertyChanged; + + if (value is not null) + value.PropertyChanged += SearchTextOnPropertyChanged; } + } } private void SearchTextOnPropertyChanged(PropertyOwnerObject propertyOwnerObject, string propertyName, object value) { - if (propertyName == nameof(TaleWorlds.GauntletUI.BaseTypes.EditableTextWidget.RealText) && value is string searchText) - SearchText = searchText; - } + if (propertyName == nameof(TaleWorlds.GauntletUI.BaseTypes.EditableTextWidget.RealText) && value is string searchText) + SearchText = searchText; + } private EditableTextWidget? _editableTextWidget; @@ -36,11 +36,11 @@ public string? SearchText get => _searchText; set { - if (this.SetField(ref _searchText, value) && EditableTextWidget is not null) - { - EditableTextWidget.RealText = value; - } + if (this.SetField(ref _searchText, value) && EditableTextWidget is not null) + { + EditableTextWidget.RealText = value; } + } } private string? _searchText; diff --git a/src/Bannerlord.LauncherEx/Widgets/LauncherToggleButtonWidget.cs b/src/Bannerlord.LauncherEx/Widgets/LauncherToggleButtonWidget.cs index c754f98..f61689d 100644 --- a/src/Bannerlord.LauncherEx/Widgets/LauncherToggleButtonWidget.cs +++ b/src/Bannerlord.LauncherEx/Widgets/LauncherToggleButtonWidget.cs @@ -23,12 +23,12 @@ public Widget? ToggleIndicator get => _toggleIndicator; set { - if (_toggleIndicator != value) - { - _toggleIndicator = value; - Refresh(); - } + if (_toggleIndicator != value) + { + _toggleIndicator = value; + Refresh(); } + } } private Widget? _toggleIndicator; @@ -38,14 +38,14 @@ public bool IsSelected get => _isSelected; set { - if (_isSelected != value) - { - _isSelected = value; - Refresh(); - RefreshState(); - OnPropertyChanged(value); - } + if (_isSelected != value) + { + _isSelected = value; + Refresh(); + RefreshState(); + OnPropertyChanged(value); } + } } private bool _isSelected; @@ -66,178 +66,178 @@ public bool IsSelected public LauncherToggleButtonWidget(UIContext context) : base(context) { - FrictionEnabled = true; - } + FrictionEnabled = true; + } protected override bool OnPreviewMousePressed() { - base.OnPreviewMousePressed(); - return true; - } + base.OnPreviewMousePressed(); + return true; + } protected override void RefreshState() { - base.RefreshState(); - if (!OverrideDefaultStateSwitchingEnabled) + base.RefreshState(); + if (!OverrideDefaultStateSwitchingEnabled) + { + if (IsDisabled) { - if (IsDisabled) - { - SetState("Disabled"); - } - else if (IsSelected && DominantSelectedState) - { - SetState("Selected"); - } - else if (IsPressed) - { - SetState("Pressed"); - } - else if (IsHovered) - { - SetState("Hovered"); - } - else if (IsSelected && !DominantSelectedState) - { - SetState("Selected"); - } - else - { - SetState("Default"); - } + SetState("Disabled"); + } + else if (IsSelected && DominantSelectedState) + { + SetState("Selected"); } + else if (IsPressed) + { + SetState("Pressed"); + } + else if (IsHovered) + { + SetState("Hovered"); + } + else if (IsSelected && !DominantSelectedState) + { + SetState("Selected"); + } + else + { + SetState("Default"); + } + } - if (UpdateChildrenStates) + if (UpdateChildrenStates) + { + for (var i = 0; i < ChildCount; i++) { - for (var i = 0; i < ChildCount; i++) + var child = GetChild(i); + if (child is not ImageWidget { OverrideDefaultStateSwitchingEnabled: true }) { - var child = GetChild(i); - if (child is not ImageWidget { OverrideDefaultStateSwitchingEnabled: true }) - { - child.SetState(CurrentState); - } + child.SetState(CurrentState); } } } + } private void Refresh() => ShowHideToggle(); private void ShowHideToggle() { - if (ToggleIndicator == null) return; + if (ToggleIndicator == null) return; - if (_isSelected) - { - ToggleIndicator.Show(); - return; - } - - ToggleIndicator.Hide(); + if (_isSelected) + { + ToggleIndicator.Show(); + return; } + ToggleIndicator.Hide(); + } + protected override void OnMousePressed() { - if (_clickState != ButtonClickState.None) return; + if (_clickState != ButtonClickState.None) return; - _clickState = ButtonClickState.HandlingClick; - this.SetIsPressed(true); - if (!DoNotPassEventsToChildren) + _clickState = ButtonClickState.HandlingClick; + this.SetIsPressed(true); + if (!DoNotPassEventsToChildren) + { + for (var i = 0; i < ChildCount; i++) { - for (var i = 0; i < ChildCount; i++) - { - var child = GetChild(i); - child?.SetIsPressed(true); - } + var child = GetChild(i); + child?.SetIsPressed(true); } } + } protected override void OnMouseReleased() { - if (_clickState != ButtonClickState.HandlingClick) return; + if (_clickState != ButtonClickState.HandlingClick) return; - _clickState = ButtonClickState.None; - this.SetIsPressed(false); - if (!DoNotPassEventsToChildren) + _clickState = ButtonClickState.None; + this.SetIsPressed(false); + if (!DoNotPassEventsToChildren) + { + for (var i = 0; i < ChildCount; i++) { - for (var i = 0; i < ChildCount; i++) - { - var child = GetChild(i); - child?.SetIsPressed(false); - } + var child = GetChild(i); + child?.SetIsPressed(false); } + } - if (IsPointInsideMeasuredAreaAndCheckIfVisible()) - { - HandleClick(); - } + if (IsPointInsideMeasuredAreaAndCheckIfVisible()) + { + HandleClick(); } + } private bool IsPointInsideMeasuredAreaAndCheckIfVisible() => this.IsPointInsideMeasuredArea() && IsRecursivelyVisible(); protected override void OnMouseAlternatePressed() { - if (_clickState != ButtonClickState.None) return; + if (_clickState != ButtonClickState.None) return; - _clickState = ButtonClickState.HandlingAlternateClick; - this.SetIsPressed(true); - if (!DoNotPassEventsToChildren) + _clickState = ButtonClickState.HandlingAlternateClick; + this.SetIsPressed(true); + if (!DoNotPassEventsToChildren) + { + for (var i = 0; i < ChildCount; i++) { - for (var i = 0; i < ChildCount; i++) - { - var child = GetChild(i); - child?.SetIsPressed(true); - } + var child = GetChild(i); + child?.SetIsPressed(true); } } + } protected override void OnMouseAlternateReleased() { - if (_clickState != ButtonClickState.HandlingAlternateClick) return; + if (_clickState != ButtonClickState.HandlingAlternateClick) return; - _clickState = ButtonClickState.None; - this.SetIsPressed(false); - if (!DoNotPassEventsToChildren) + _clickState = ButtonClickState.None; + this.SetIsPressed(false); + if (!DoNotPassEventsToChildren) + { + for (var i = 0; i < ChildCount; i++) { - for (var i = 0; i < ChildCount; i++) - { - var child = GetChild(i); - child?.SetIsPressed(false); - } + var child = GetChild(i); + child?.SetIsPressed(false); } + } - if (IsPointInsideMeasuredAreaAndCheckIfVisible()) - { - HandleAlternateClick(); - } + if (IsPointInsideMeasuredAreaAndCheckIfVisible()) + { + HandleAlternateClick(); } + } private void HandleClick() { - foreach (var action in ClickEventHandlers) - { - action(this); - } - - if (!ManualToggle) - { - IsSelected = !IsSelected; - } + foreach (var action in ClickEventHandlers) + { + action(this); + } - OnClick(); - EventFired("Click", Array.Empty()); - if (Context.EventManager.Time - _lastClickTime < _maxDoubleClickDeltaTimeInSeconds) - { - EventFired("DoubleClick", Array.Empty()); - return; - } + if (!ManualToggle) + { + IsSelected = !IsSelected; + } - _lastClickTime = Context.EventManager.Time; + OnClick(); + EventFired("Click", Array.Empty()); + if (Context.EventManager.Time - _lastClickTime < _maxDoubleClickDeltaTimeInSeconds) + { + EventFired("DoubleClick", Array.Empty()); + return; } + _lastClickTime = Context.EventManager.Time; + } + private void HandleAlternateClick() { - OnAlternateClick(); - EventFired("AlternateClick", Array.Empty()); - } + OnAlternateClick(); + EventFired("AlternateClick", Array.Empty()); + } private void OnClick() { } private void OnAlternateClick() { }