From 3da9d60faf6e526155367eb4c05870b5893843fc Mon Sep 17 00:00:00 2001 From: cheese3660 Date: Fri, 22 Dec 2023 12:09:36 -0500 Subject: [PATCH 01/82] Update release_nuget.yml Add permissions correctly I think? --- .github/workflows/release_nuget.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release_nuget.yml b/.github/workflows/release_nuget.yml index a88f85a..5d7df16 100644 --- a/.github/workflows/release_nuget.yml +++ b/.github/workflows/release_nuget.yml @@ -7,7 +7,7 @@ on: jobs: publish: runs-on: ubuntu-latest - + permissions: write-all steps: - name: Check out repository uses: actions/checkout@v3 From efe1807138b6cfa541aa2a04973e061ad0ea251e Mon Sep 17 00:00:00 2001 From: MBoutray Date: Sun, 24 Dec 2023 19:10:12 +0100 Subject: [PATCH 02/82] add french localization --- .../space_warp_localizations.csv | 92 +++++++++---------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/plugin_template/BepInEx/plugins/SpaceWarp/localizations/space_warp_localizations.csv b/plugin_template/BepInEx/plugins/SpaceWarp/localizations/space_warp_localizations.csv index 92936cf..66aa773 100644 --- a/plugin_template/BepInEx/plugins/SpaceWarp/localizations/space_warp_localizations.csv +++ b/plugin_template/BepInEx/plugins/SpaceWarp/localizations/space_warp_localizations.csv @@ -1,46 +1,46 @@ -Key,Type,Description,English,Portuguese BR -SpaceWarp/ModList/EnableAll,Text,,Enable All,Ativar todos -SpaceWarp/ModList/DisableAll,Text,,Disable All,Desativar todos -SpaceWarp/ModList/RevertChanges,Text,,Revert Changes,Reverter alterações -SpaceWarp/ModList/multipleChangesDetected,Text,,"{0} changes detected, please restart to apply them","{0} alterações detetadas, porfavor reinicie o jogo" -SpaceWarp/ModList/singleChangeDetected,Text,,"1 change detected, please restart to apply it","1 alteração detectada, reinicie para aplicá-la" -SpaceWarp/ModList/Header,Text,,spacewarp.modlist,spacewarp.modlist -SpaceWarp/ModList/EnabledMods,Text,,Enabled Mods,Mods ativos -SpaceWarp/ModList/ErroredMods,Text,,Errored Mods,Mods com erros -SpaceWarp/ModList/DisabledMods,Text,,Disabled Mods,Mods desativados -SpaceWarp/ModList/Version,Text,,Version,Versão -SpaceWarp/ModList/Author,Text,,Author,Autor -SpaceWarp/ModList/Source,Text,,Source,Fonte -SpaceWarp/ModList/Description,Text,,Description,Descrição -SpaceWarp/ModList/KSP2Version,Text,,KSP2 Version,Versão do jogo -SpaceWarp/ModList/Dependencies,Text,,Dependencies,Dependências -SpaceWarp/ModList/outdated,Text,,outdated,desatualizado -SpaceWarp/ModList/unsupported,Text,,unsupported,não suportado -SpaceWarp/ModList/disabled,Text,,disabled,desativado -SpaceWarp/ModList/OpenConfigurationManager,Text,,Open Configuration Manager,Abrir gestor de configurações -SpaceWarp/ModList/OpenModsFolder,Text,,Open Mods Folder,Abrir pasta de mods -SpaceWarp/ModList/mismatched,Text,,Mismatched,Não corresponde com o swinfo -SpaceWarp/ModList/baddirectory,Text,,Bad Directory,Problemas no diretorio -SpaceWarp/ModList/missingswinfo,Text,,Missing SW Info,Não possui um swinfo -SpaceWarp/ModList/MissingDependency,Text,,Dependency is missing,Esta dependência não está presente -SpaceWarp/ModList/ErroredDependency,Text,,Dependency had an error while loading,Esta dependência teve um erro durante o loading -SpaceWarp/ModList/DisabledDependency,Text,,Dependency is disabled,Esta dependência esta desativada -SpaceWarp/ModList/UnspecifiedDependency,Text,,Dependency was not specified in SW info,Esta dependência não está presente no swinfo -SpaceWarp/ModList/UnsupportedDependency,Text,,Dependency is of an unsupported version,Esta dependência é de uma versão nao suportada -SpaceWarp/ModList/Conflicts,Text,,Conflicts,Incompatibilidades -SpaceWarp/ModList/Details,Text,,Details,Detalhes -SpaceWarp/Mods,Text,,Mods,Mods -SpaceWarp/Mods/Outdated,Text,,Mods ⚠,Mods ⚠ -SpaceWarp/Mods/Errored,Text,,Mods ⚠,Mods ⚠ -SpaceWarp,Text,,Space Warp,Space Warp -SpaceWarp/VersionChecking,Text,,Allow Space Warp to check versions for mods over the network?,Deixar SpaceWarp verificar a versão dos mods na internet? -SpaceWarp/Yes,Text,,Yes,Sim -SpaceWarp/No,Text,,No,Não -SpaceWarp/Console/Header,Text,,SPACE WARP - Console, SPACE WARP - Consola -SpaceWarp/Console/Clear,Text,,Clear,Limpar -SpaceWarp/Console/AutoScroll,Text,,Auto Scroll,Scroll automatico -SpaceWarp/Console/On,Text,,On,On -SpaceWarp/Console/Off,Text,,Off,Off -SpaceWarp/AvcDialog/Title,Text,,spacewarp.avc,spacewarp.avc -SpaceWarp/AvcDialog/MainText,Text,,Allow SpaceWarp to automatically check for mod updates online?,Allow SpaceWarp to automatically check for mod updates online? -SpaceWarp/AvcDialog/MinorText,Text,,*You can change this later in the settings menu.,*You can change this later in the settings menu. \ No newline at end of file +Key,Type,Description,English,Portuguese BR,French +SpaceWarp/ModList/EnableAll,Text,,Enable All,Ativar todos,Activer tous +SpaceWarp/ModList/DisableAll,Text,,Disable All,Desativar todos,Désactiver tous +SpaceWarp/ModList/RevertChanges,Text,,Revert Changes,Reverter alterações,Rétablir les changements +SpaceWarp/ModList/multipleChangesDetected,Text,,"{0} changes detected, please restart to apply them","{0} alterações detetadas, porfavor reinicie o jogo","{0} changements détectés, veuillez redémarrer pour les appliquer" +SpaceWarp/ModList/singleChangeDetected,Text,,"1 change detected, please restart to apply it","1 alteração detectada, reinicie para aplicá-la","{0} changement détecté, veuillez redémarrer pour l'appliquer" +SpaceWarp/ModList/Header,Text,,spacewarp.modlist,spacewarp.modlist,spacewarp.modlist +SpaceWarp/ModList/EnabledMods,Text,,Enabled Mods,Mods ativos,Mods activés +SpaceWarp/ModList/ErroredMods,Text,,Errored Mods,Mods com erros,Mods avec des erreurs +SpaceWarp/ModList/DisabledMods,Text,,Disabled Mods,Mods desativados,Mods désactivés +SpaceWarp/ModList/Version,Text,,Version,Versão,Version +SpaceWarp/ModList/Author,Text,,Author,Autor,Auteur +SpaceWarp/ModList/Source,Text,,Source,Fonte,Source +SpaceWarp/ModList/Description,Text,,Description,Descrição,Description +SpaceWarp/ModList/KSP2Version,Text,,KSP2 Version,Versão do jogo,Version de KSP2 +SpaceWarp/ModList/Dependencies,Text,,Dependencies,Dependências,Dépendances +SpaceWarp/ModList/outdated,Text,,outdated,desatualizado,obsolète +SpaceWarp/ModList/unsupported,Text,,unsupported,não suportado,non pris en charge +SpaceWarp/ModList/disabled,Text,,disabled,desativado,désactivé +SpaceWarp/ModList/OpenConfigurationManager,Text,,Open Configuration Manager,Abrir gestor de configurações,Ouvrir le gestionnaire de configuration +SpaceWarp/ModList/OpenModsFolder,Text,,Open Mods Folder,Abrir pasta de mods,Ouvrir le dossier des mods +SpaceWarp/ModList/mismatched,Text,,Mismatched,Não corresponde com o swinfo,Non concordant +SpaceWarp/ModList/baddirectory,Text,,Bad Directory,Problemas no diretorio,Mauvais dossier +SpaceWarp/ModList/missingswinfo,Text,,Missing SW Info,Não possui um swinfo,SW Info manquant +SpaceWarp/ModList/MissingDependency,Text,,Dependency is missing,Esta dependência não está presente,Cette dépendance est manquante +SpaceWarp/ModList/ErroredDependency,Text,,Dependency had an error while loading,Esta dependência teve um erro durante o loading,Une erreur s'est produite lors du chargement de cette dépendance +SpaceWarp/ModList/DisabledDependency,Text,,Dependency is disabled,Esta dependência esta desativada,Cette dépendance est manquante +SpaceWarp/ModList/UnspecifiedDependency,Text,,Dependency was not specified in SW info,Esta dependência não está presente no swinfo,Cette dépendance n'a pas été spécifiée dans SW Info +SpaceWarp/ModList/UnsupportedDependency,Text,,Dependency is of an unsupported version,Esta dependência é de uma versão nao suportada,Cette dépendance est d'une version non supportée +SpaceWarp/ModList/Conflicts,Text,,Conflicts,Incompatibilidades,Conflits +SpaceWarp/ModList/Details,Text,,Details,Detalhes,Détails +SpaceWarp/Mods,Text,,Mods,Mods,Mods +SpaceWarp/Mods/Outdated,Text,,Mods ⚠,Mods ⚠,Mods ⚠ +SpaceWarp/Mods/Errored,Text,,Mods ⚠,Mods ⚠,Mods ⚠ +SpaceWarp,Text,,Space Warp,Space Warp,Space Warp +SpaceWarp/VersionChecking,Text,,Allow Space Warp to check versions for mods over the network?,Deixar SpaceWarp verificar a versão dos mods na internet?,Autoriser Space Warp à vérifier les versions des mods sur le réseau ? +SpaceWarp/Yes,Text,,Yes,Sim,Oui +SpaceWarp/No,Text,,No,Não,Non +SpaceWarp/Console/Header,Text,,SPACE WARP - Console,SPACE WARP - Consola,SPACE WARP - Console +SpaceWarp/Console/Clear,Text,,Clear,Limpar,Effacer +SpaceWarp/Console/AutoScroll,Text,,Auto Scroll,Scroll automatico,Défilement automatique +SpaceWarp/Console/On,Text,,On,On,On +SpaceWarp/Console/Off,Text,,Off,Off,Off +SpaceWarp/AvcDialog/Title,Text,,spacewarp.avc,spacewarp.avc,spacewarp.avc +SpaceWarp/AvcDialog/MainText,Text,,Allow SpaceWarp to automatically check for mod updates online?,Allow SpaceWarp to automatically check for mod updates online?,Autoriser SpaceWarp à vérifier automatiquement les mises à jour de mods en ligne ? +SpaceWarp/AvcDialog/MinorText,Text,,*You can change this later in the settings menu.,*You can change this later in the settings menu.,*Vous pouvez modifier plus tard dans le menu des réglages. \ No newline at end of file From 4c07ff525d56cdfb6a3254967d69f7ffb446e474 Mon Sep 17 00:00:00 2001 From: MBoutray Date: Sun, 24 Dec 2023 19:16:52 +0100 Subject: [PATCH 03/82] translated AvcDialog/MainText and AvcDialog/MinorText for portuguese I used DeepL translator so the translation might be wrong --- .../SpaceWarp/localizations/space_warp_localizations.csv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugin_template/BepInEx/plugins/SpaceWarp/localizations/space_warp_localizations.csv b/plugin_template/BepInEx/plugins/SpaceWarp/localizations/space_warp_localizations.csv index 66aa773..5600bf3 100644 --- a/plugin_template/BepInEx/plugins/SpaceWarp/localizations/space_warp_localizations.csv +++ b/plugin_template/BepInEx/plugins/SpaceWarp/localizations/space_warp_localizations.csv @@ -42,5 +42,5 @@ SpaceWarp/Console/AutoScroll,Text,,Auto Scroll,Scroll automatico,Défilement aut SpaceWarp/Console/On,Text,,On,On,On SpaceWarp/Console/Off,Text,,Off,Off,Off SpaceWarp/AvcDialog/Title,Text,,spacewarp.avc,spacewarp.avc,spacewarp.avc -SpaceWarp/AvcDialog/MainText,Text,,Allow SpaceWarp to automatically check for mod updates online?,Allow SpaceWarp to automatically check for mod updates online?,Autoriser SpaceWarp à vérifier automatiquement les mises à jour de mods en ligne ? -SpaceWarp/AvcDialog/MinorText,Text,,*You can change this later in the settings menu.,*You can change this later in the settings menu.,*Vous pouvez modifier plus tard dans le menu des réglages. \ No newline at end of file +SpaceWarp/AvcDialog/MainText,Text,,Allow SpaceWarp to automatically check for mod updates online?,Permitir que o SpaceWarp verifique automaticamente se há atualizações de mods online?,Autoriser SpaceWarp à vérifier automatiquement les mises à jour de mods en ligne ? +SpaceWarp/AvcDialog/MinorText,Text,,*You can change this later in the settings menu.,*Pode alterá-lo mais tarde no menu de definições.,*Vous pouvez modifier plus tard dans le menu des réglages. \ No newline at end of file From a66026075c64d25a0a4ececa1d630c5bb7012f3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Sun, 24 Dec 2023 19:28:58 +0100 Subject: [PATCH 04/82] Changed variable to literal "1" in singleChangeDetected loc string --- .../SpaceWarp/localizations/space_warp_localizations.csv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin_template/BepInEx/plugins/SpaceWarp/localizations/space_warp_localizations.csv b/plugin_template/BepInEx/plugins/SpaceWarp/localizations/space_warp_localizations.csv index 5600bf3..aba70e3 100644 --- a/plugin_template/BepInEx/plugins/SpaceWarp/localizations/space_warp_localizations.csv +++ b/plugin_template/BepInEx/plugins/SpaceWarp/localizations/space_warp_localizations.csv @@ -3,7 +3,7 @@ SpaceWarp/ModList/EnableAll,Text,,Enable All,Ativar todos,Activer tous SpaceWarp/ModList/DisableAll,Text,,Disable All,Desativar todos,Désactiver tous SpaceWarp/ModList/RevertChanges,Text,,Revert Changes,Reverter alterações,Rétablir les changements SpaceWarp/ModList/multipleChangesDetected,Text,,"{0} changes detected, please restart to apply them","{0} alterações detetadas, porfavor reinicie o jogo","{0} changements détectés, veuillez redémarrer pour les appliquer" -SpaceWarp/ModList/singleChangeDetected,Text,,"1 change detected, please restart to apply it","1 alteração detectada, reinicie para aplicá-la","{0} changement détecté, veuillez redémarrer pour l'appliquer" +SpaceWarp/ModList/singleChangeDetected,Text,,"1 change detected, please restart to apply it","1 alteração detectada, reinicie para aplicá-la","1 changement détecté, veuillez redémarrer pour l'appliquer" SpaceWarp/ModList/Header,Text,,spacewarp.modlist,spacewarp.modlist,spacewarp.modlist SpaceWarp/ModList/EnabledMods,Text,,Enabled Mods,Mods ativos,Mods activés SpaceWarp/ModList/ErroredMods,Text,,Errored Mods,Mods com erros,Mods avec des erreurs From 94723627095d5ea7fb794d9e3fabbaa22de6ad15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 25 Dec 2023 19:41:26 +0100 Subject: [PATCH 05/82] Plugin constants now use values from swinfo.json --- Directory.Build.props | 6 +++--- src/SpaceWarp.Core/SpaceWarpPlugin.cs | 9 ++++----- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 0fe657a..9433b81 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -56,9 +56,9 @@ @(Swinfo -> '%(description)') git @(Swinfo -> '%(source)') - $(ModId) - $(Product) - $(Version) + $(ModId) + $(Product) + $(Version) diff --git a/src/SpaceWarp.Core/SpaceWarpPlugin.cs b/src/SpaceWarp.Core/SpaceWarpPlugin.cs index 8718633..cb66ee9 100644 --- a/src/SpaceWarp.Core/SpaceWarpPlugin.cs +++ b/src/SpaceWarp.Core/SpaceWarpPlugin.cs @@ -29,11 +29,10 @@ public sealed class SpaceWarpPlugin : BaseSpaceWarpPlugin { public static SpaceWarpPlugin Instance; - [PublicAPI] public const string ModGuid = "com.github.x606.spacewarp"; - [PublicAPI] public const string ModName = "Space Warp"; - [PublicAPI] public const string ModVer = MyPluginInfo.PLUGIN_VERSION; // TODO: Don't hard code this, but I don't know much msbuild stuff so @munix wil have to do that, - // and @munix is really lazy to do it right now but he definitely will at some point :P - + [PublicAPI] public const string ModGuid = MyPluginInfo.PLUGIN_GUID; + [PublicAPI] public const string ModName = MyPluginInfo.PLUGIN_NAME; + [PublicAPI] public const string ModVer = MyPluginInfo.PLUGIN_VERSION; + internal ScriptEnvironment GlobalLuaState; internal new static ManualLogSource Logger; From 8fb94a1a86f61ccc2085a96a3fd63a51b4521eba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Tue, 26 Dec 2023 21:58:51 +0100 Subject: [PATCH 06/82] Start of fixing all SpaceWarp warnings, removes all unused imports and adds doc comments to SpaceWarp.Core.API.Assets, SpaceWarp.Core.API.Configuration, SpaceWarp.Core.API.Loading and SpaceWarp.Core.API.Lua namespaces --- src/SpaceWarp.Core/API/Assets/AssetManager.cs | 8 ++-- .../API/Configuration/BepInExConfigEntry.cs | 32 +++++++++++-- .../API/Configuration/BepInExConfigFile.cs | 37 ++++++++++++-- .../API/Configuration/ConfigValue.cs | 29 ++++++++--- .../API/Configuration/EmptyConfigFile.cs | 34 +++++++++++-- .../API/Configuration/IConfigEntry.cs | 39 +++++++++++++-- .../API/Configuration/IConfigFile.cs | 34 +++++++++++-- .../API/Configuration/IValueConstraint.cs | 13 +++++ .../API/Configuration/JsonConfigEntry.cs | 40 +++++++++++++--- .../API/Configuration/JsonConfigFile.cs | 26 ++++++++-- .../API/Configuration/ListConstraint.cs | 28 ++++++++--- .../API/Configuration/RangeConstraint.cs | 29 ++++++++--- .../API/Configuration/ValueConstraint.cs | 17 +++++++ src/SpaceWarp.Core/API/Loading/Loading.cs | 10 ++-- src/SpaceWarp.Core/API/Loading/SaveLoad.cs | 48 ++++++++++--------- src/SpaceWarp.Core/API/Lua/LuaMod.cs | 41 ++++++++++------ .../API/Lua/SpaceWarpLuaAPIAttribute.cs | 14 +++++- .../API/Mods/GlobalModDefines.cs | 3 +- .../JSON/Converters/SpecVersionConverter.cs | 3 +- src/SpaceWarp.Core/API/Mods/JSON/ModInfo.cs | 4 +- .../API/Mods/JSON/SpecVersion.cs | 3 +- .../API/Mods/JSON/VersionCheckType.cs | 3 +- src/SpaceWarp.Core/API/Mods/PluginList.cs | 6 +-- .../API/Mods/SpaceWarpErrorDescription.cs | 4 +- .../API/Mods/SpaceWarpPluginDescriptor.cs | 3 +- src/SpaceWarp.Core/API/Parts/Colors.cs | 4 +- .../API/SaveGameManager/ModSaves.cs | 2 - .../API/Versions/SemanticVersion.cs | 3 +- .../API/Versions/VersionUtility.cs | 3 +- .../Backend/Modding/Ksp2ModInfo.cs | 3 +- .../Backend/Modding/PluginRegister.cs | 6 +-- .../Backend/SaveGameManager/PluginSaveData.cs | 4 +- .../SpaceWarpSerializedSavedGame.cs | 6 +-- .../InternalUtilities/AssetHelpers.cs | 1 - .../InternalUtilities/InternalExtensions.cs | 1 - .../InternalUtilities/PathHelpers.cs | 5 +- src/SpaceWarp.Core/Modules/ModuleManager.cs | 5 +- src/SpaceWarp.Core/Modules/SpaceWarpModule.cs | 3 +- src/SpaceWarp.Core/Patching/BootstrapPatch.cs | 1 - src/SpaceWarp.Core/Patching/ColorsPatch.cs | 3 +- src/SpaceWarp.Core/Patching/FixGetTypes.cs | 1 - .../LoadingActions/AddressableAction.cs | 4 +- .../LoadingActions/DescriptorLoadingAction.cs | 3 +- .../FunctionalLoadingActions.cs | 5 +- .../LoadingActions/InitializeModAction.cs | 1 - .../LoadingActions/LoadAddressablesAction.cs | 4 +- .../LoadingActions/LoadLocalizationAction.cs | 4 +- .../Patching/LoadingActions/LoadLuaAction.cs | 4 +- .../LoadingAddressablesLocalizationsAction.cs | 4 +- .../LoadingActions/ModLoadingAction.cs | 3 +- .../LoadingActions/PostInitializeModAction.cs | 3 +- .../LoadingActions/PreInitializeModAction.cs | 1 - .../ResolvingPatchOrderAction.cs | 3 +- src/SpaceWarp.Core/Patching/ModLoaderPatch.cs | 5 +- .../SaveGameManager/SaveGamePatches.cs | 1 - .../Patching/SequentialFlowLoadersPatcher.cs | 4 +- .../Patching/SettingsManagerPatcher.cs | 3 +- src/SpaceWarp.Core/SpaceWarpPlugin.cs | 2 - .../Game/Extensions/PartProviderExtensions.cs | 4 +- .../API/Game/Messages/StateChanges.cs | 3 +- .../API/Game/Messages/StateLoadings.cs | 3 +- .../API/Messaging/MessageBus.cs | 5 +- .../API/Messaging/MessageBusBase.cs | 4 +- .../API/Messaging/MessageBusManager.cs | 5 +- src/SpaceWarp.Sound/API/Sound/Soundbank.cs | 3 +- .../API/Sound/SoundbankManager.cs | 1 - src/SpaceWarp.Sound/Modules/Sound.cs | 5 +- src/SpaceWarp.UI/API/Lua/AppBarInterop.cs | 3 +- src/SpaceWarp.UI/API/UI/Appbar/Appbar.cs | 2 - src/SpaceWarp.UI/API/UI/Appbar/AppbarMenu.cs | 1 - src/SpaceWarp.UI/API/UI/MainMenu.cs | 4 +- src/SpaceWarp.UI/API/UI/ModList.cs | 4 +- .../API/UI/Settings/ModsPropertyDrawers.cs | 5 +- src/SpaceWarp.UI/API/UI/Skins.cs | 3 +- .../Backend/UI/Appbar/AppbarBackend.cs | 1 - .../UI/Loading/LoadingScreenManager.cs | 5 +- ...tomSettingsElementDescriptionController.cs | 3 +- src/SpaceWarp.UI/Modules/UI.cs | 10 +--- src/SpaceWarp.UI/Patching/CurtainPatch.cs | 5 +- src/SpaceWarp.UI/Patching/LoadingFlowPatch.cs | 4 +- .../LoadingScreenDeserializationPatch.cs | 3 +- src/SpaceWarp.UI/Patching/MainMenuPatcher.cs | 3 +- src/SpaceWarp.UI/UI/Console/LogEntry.cs | 3 +- .../UI/Console/SpaceWarpConsoleLogListener.cs | 4 +- .../UI/ModList/ModListController.cs | 5 +- .../UI/ModList/ModListItemController.cs | 4 +- src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs | 6 +-- src/SpaceWarpPatcher/AssemblyCSharpPatcher.cs | 4 +- src/SpaceWarpPatcher/Patcher.cs | 7 +-- src/SpaceWarpPatcher/PathsGenerator.cs | 5 +- src/SpaceWarpPatcher/SwinfoTransformer.cs | 4 +- 91 files changed, 441 insertions(+), 303 deletions(-) diff --git a/src/SpaceWarp.Core/API/Assets/AssetManager.cs b/src/SpaceWarp.Core/API/Assets/AssetManager.cs index d1d956b..5219788 100644 --- a/src/SpaceWarp.Core/API/Assets/AssetManager.cs +++ b/src/SpaceWarp.Core/API/Assets/AssetManager.cs @@ -1,13 +1,13 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using JetBrains.Annotations; +using JetBrains.Annotations; using SpaceWarp.API.Lua; using UnityEngine; using Logger = BepInEx.Logging.Logger; namespace SpaceWarp.API.Assets; +/// +/// Manages all mod assets loaded by SpaceWarp +/// [SpaceWarpLuaAPI("Assets")] [PublicAPI] public static class AssetManager diff --git a/src/SpaceWarp.Core/API/Configuration/BepInExConfigEntry.cs b/src/SpaceWarp.Core/API/Configuration/BepInExConfigEntry.cs index 1901d90..2375c9d 100644 --- a/src/SpaceWarp.Core/API/Configuration/BepInExConfigEntry.cs +++ b/src/SpaceWarp.Core/API/Configuration/BepInExConfigEntry.cs @@ -1,20 +1,38 @@ -using System; -using BepInEx.Configuration; +using BepInEx.Configuration; using JetBrains.Annotations; namespace SpaceWarp.API.Configuration; +/// +/// A wrapper around a BepInEx to make it compatible with the +/// interface. +/// [PublicAPI] public class BepInExConfigEntry : IConfigEntry { + /// + /// The underlying that this class wraps. + /// public readonly ConfigEntryBase EntryBase; - public event Action Callbacks; + + /// + /// The callbacks that are invoked when the value of this entry changes. + /// + public event Action Callbacks; + + /// + /// Creates a new from the given and optional + /// . + /// + /// The to wrap. + /// The to use. public BepInExConfigEntry(ConfigEntryBase entryBase, IValueConstraint constraint = null) { EntryBase = entryBase; Constraint = constraint; } + /// public object Value { get => EntryBase.BoxedValue; @@ -25,8 +43,10 @@ public object Value } } + /// public Type ValueType => EntryBase.SettingType; + /// public T Get() where T : class { if (!typeof(T).IsAssignableFrom(ValueType)) @@ -37,6 +57,7 @@ public T Get() where T : class return Value as T; } + /// public void Set(T value) { if (!ValueType.IsAssignableFrom(typeof(T))) @@ -52,8 +73,13 @@ public void Set(T value) EntryBase.BoxedValue = Convert.ChangeType(value, ValueType); } + /// public string Description => EntryBase.Description.Description; + + /// public IValueConstraint Constraint { get; } + + /// public void RegisterCallback(Action valueChangedCallback) { Callbacks += valueChangedCallback; diff --git a/src/SpaceWarp.Core/API/Configuration/BepInExConfigFile.cs b/src/SpaceWarp.Core/API/Configuration/BepInExConfigFile.cs index a1a5c60..d43cc5b 100644 --- a/src/SpaceWarp.Core/API/Configuration/BepInExConfigFile.cs +++ b/src/SpaceWarp.Core/API/Configuration/BepInExConfigFile.cs @@ -1,40 +1,69 @@ -using System.Collections.Generic; -using BepInEx.Configuration; +using BepInEx.Configuration; using JetBrains.Annotations; namespace SpaceWarp.API.Configuration; +/// +/// A wrapper around BepInEx's to make it implement . +/// [PublicAPI] public class BepInExConfigFile : IConfigFile { - + /// + /// The underlying instance. + /// public readonly ConfigFile AdaptedConfigFile; + /// + /// Creates a new instance. + /// + /// The instance to wrap. public BepInExConfigFile(ConfigFile adaptedConfigFile) { AdaptedConfigFile = adaptedConfigFile; } + /// public void Save() { AdaptedConfigFile.Save(); } + /// public IConfigEntry this[string section, string key] => new BepInExConfigEntry(AdaptedConfigFile[section, key]); + /// public IConfigEntry Bind(string section, string key, T defaultValue = default, string description = "") { return new BepInExConfigEntry(AdaptedConfigFile.Bind(section, key, defaultValue, description)); } - public IConfigEntry Bind(string section, string key, T defaultValue, string description, IValueConstraint valueConstraint) + /// + /// Binds a new config entry to the given section and key with the given default value and description. + /// + /// Section to bind the entry to. + /// Key to bind the entry to. + /// Default value of the entry. + /// Description of the entry. + /// Value constraint of the entry. + /// Type of the entry. + /// The newly bound config entry. + public IConfigEntry Bind( + string section, + string key, + T defaultValue, + string description, + IValueConstraint valueConstraint + ) { return new BepInExConfigEntry(AdaptedConfigFile.Bind(new ConfigDefinition(section, key), defaultValue, new ConfigDescription(description, valueConstraint.ToAcceptableValueBase()))); } + /// public IReadOnlyList Sections => AdaptedConfigFile.Keys.Select(x => x.Section).Distinct().ToList(); + /// public IReadOnlyList this[string section] => AdaptedConfigFile.Keys.Where(x => x.Section == section) .Select(x => x.Key).ToList(); } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Configuration/ConfigValue.cs b/src/SpaceWarp.Core/API/Configuration/ConfigValue.cs index b4a5427..670b197 100644 --- a/src/SpaceWarp.Core/API/Configuration/ConfigValue.cs +++ b/src/SpaceWarp.Core/API/Configuration/ConfigValue.cs @@ -1,13 +1,26 @@ -using System; -using JetBrains.Annotations; +using JetBrains.Annotations; namespace SpaceWarp.API.Configuration; +/// +/// A wrapper around that provides type safety. +/// +/// The type of the value. [PublicAPI] public class ConfigValue { + /// + /// The underlying . + /// public IConfigEntry Entry; + /// + /// Creates a new from an . + /// + /// The entry to wrap. + /// + /// If the type of does not match . + /// public ConfigValue(IConfigEntry entry) { Entry = entry; @@ -17,15 +30,19 @@ public ConfigValue(IConfigEntry entry) } } + /// + /// The value of the entry. + /// public T Value { get => (T)Entry.Value; - set - { - Entry.Value = value; - } + set => Entry.Value = value; } + /// + /// Registers a callback that will be invoked when the value changes. + /// + /// The callback to invoke. public void RegisterCallback(Action callback) { // Callbacks += callback; diff --git a/src/SpaceWarp.Core/API/Configuration/EmptyConfigFile.cs b/src/SpaceWarp.Core/API/Configuration/EmptyConfigFile.cs index 503d891..85cd3bb 100644 --- a/src/SpaceWarp.Core/API/Configuration/EmptyConfigFile.cs +++ b/src/SpaceWarp.Core/API/Configuration/EmptyConfigFile.cs @@ -1,28 +1,52 @@ -using System.Collections.Generic; -using JetBrains.Annotations; +using JetBrains.Annotations; namespace SpaceWarp.API.Configuration; +/// +/// An empty config file that does not save anything. +/// [PublicAPI] public class EmptyConfigFile : IConfigFile { + /// public void Save() { } + /// public IConfigEntry this[string section, string key] => throw new KeyNotFoundException($"{section}/{key}"); + /// public IConfigEntry Bind(string section, string key, T defaultValue = default, string description = "") { - throw new System.NotImplementedException(); + throw new NotImplementedException(); } - public IConfigEntry Bind(string section, string key, T defaultValue, string description, IValueConstraint valueConstraint) + /// + /// Binds a config entry to a section and key. + /// + /// Section to bind to. + /// Key to bind to. + /// Default value to use if no value is found. + /// Description of the config entry. + /// Constraint to use for the value. + /// Type of the value. + /// The config entry. + /// Always thrown. + public IConfigEntry Bind( + string section, + string key, + T defaultValue, + string description, + IValueConstraint valueConstraint + ) { - throw new System.NotImplementedException(); + throw new NotImplementedException(); } + /// public IReadOnlyList Sections => new List(); + /// public IReadOnlyList this[string section] => throw new KeyNotFoundException($"{section}"); } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Configuration/IConfigEntry.cs b/src/SpaceWarp.Core/API/Configuration/IConfigEntry.cs index f5f062a..0506ede 100644 --- a/src/SpaceWarp.Core/API/Configuration/IConfigEntry.cs +++ b/src/SpaceWarp.Core/API/Configuration/IConfigEntry.cs @@ -1,23 +1,52 @@ -using System; -using JetBrains.Annotations; +using JetBrains.Annotations; namespace SpaceWarp.API.Configuration; +/// +/// Represents a config entry +/// [PublicAPI] public interface IConfigEntry { + /// + /// The value of the config entry + /// public object Value { get; set; } + + /// + /// The type of the value of the config entry + /// public Type ValueType { get; } + + /// + /// Gets the value of the config entry as a specific type + /// + /// The type to cast to + /// The value as the specified type public T Get() where T : class; + + /// + /// Sets the value of the config entry + /// + /// The value to set + /// The type of the value public void Set(T value); + /// + /// The description of the config entry + /// public string Description { get; } + /// + /// The value constraint of the config entry + /// public IValueConstraint Constraint { get; } - + /// - /// Called when setting the value on a config file + /// Registers a callback to be called when setting the value on a config file /// - /// An action that takes te old value and the new value and calls a callback + /// + /// An action that takes the old value and the new value and calls a callback + /// public void RegisterCallback(Action valueChangedCallback); } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Configuration/IConfigFile.cs b/src/SpaceWarp.Core/API/Configuration/IConfigFile.cs index 87aedf2..2b271e5 100644 --- a/src/SpaceWarp.Core/API/Configuration/IConfigFile.cs +++ b/src/SpaceWarp.Core/API/Configuration/IConfigFile.cs @@ -1,18 +1,44 @@ -using System; -using System.Collections.Generic; -using JetBrains.Annotations; +using JetBrains.Annotations; namespace SpaceWarp.API.Configuration; +/// +/// Represents a configuration file. +/// [PublicAPI] public interface IConfigFile { + /// + /// Saves the configuration file. + /// public void Save(); + /// + /// Gets the with the specified section and key. + /// + /// Section of the entry. + /// Key of the entry. public IConfigEntry this[string section, string key] { get; } + /// + /// Binds a new to the specified section and key. + /// + /// Section of the entry. + /// Key of the entry. + /// Default value of the entry. + /// Description of the entry. + /// Type of the entry. + /// The bound . public IConfigEntry Bind(string section, string key, T defaultValue = default, string description = ""); - + + /// + /// A list of all sections in the configuration file. + /// public IReadOnlyList Sections { get; } + + /// + /// A list of all keys in the specified section. + /// + /// public IReadOnlyList this[string section] { get; } } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Configuration/IValueConstraint.cs b/src/SpaceWarp.Core/API/Configuration/IValueConstraint.cs index 4256ceb..8325078 100644 --- a/src/SpaceWarp.Core/API/Configuration/IValueConstraint.cs +++ b/src/SpaceWarp.Core/API/Configuration/IValueConstraint.cs @@ -2,8 +2,21 @@ namespace SpaceWarp.API.Configuration; +/// +/// A constraint that can be applied to a to limit the values it can take. +/// public interface IValueConstraint { + /// + /// Checks if the given object is constrained by this constraint. + /// + /// Object to check. + /// True if the object is constrained, false otherwise. public bool IsConstrained(object o); + + /// + /// Converts this constraint to an . + /// + /// An representing this constraint. public AcceptableValueBase ToAcceptableValueBase(); } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Configuration/JsonConfigEntry.cs b/src/SpaceWarp.Core/API/Configuration/JsonConfigEntry.cs index 977f910..e43b17a 100644 --- a/src/SpaceWarp.Core/API/Configuration/JsonConfigEntry.cs +++ b/src/SpaceWarp.Core/API/Configuration/JsonConfigEntry.cs @@ -1,17 +1,36 @@ -using System; -using JetBrains.Annotations; +using JetBrains.Annotations; namespace SpaceWarp.API.Configuration; +/// +/// A config entry that is stored in a JSON file. +/// [PublicAPI] public class JsonConfigEntry : IConfigEntry { private readonly JsonConfigFile _configFile; private object _value; - public event Action Callbacks; - - public JsonConfigEntry(JsonConfigFile configFile, Type type, string description, object value, IValueConstraint constraint = null) + /// + /// The callbacks that are invoked when the value of this entry changes. + /// + public event Action Callbacks; + + /// + /// Creates a new config entry. + /// + /// Config file that this entry belongs to. + /// Type of the value. + /// Description of the value. + /// Value of the entry. + /// Constraint of the value. + public JsonConfigEntry( + JsonConfigFile configFile, + Type type, + string description, + object value, + IValueConstraint constraint = null + ) { _configFile = configFile; _value = value; @@ -20,7 +39,7 @@ public JsonConfigEntry(JsonConfigFile configFile, Type type, string description, ValueType = type; } - + /// public object Value { get => _value; @@ -32,7 +51,10 @@ public object Value } } + /// public Type ValueType { get; } + + /// public T Get() where T : class { if (!typeof(T).IsAssignableFrom(ValueType)) @@ -43,6 +65,7 @@ public T Get() where T : class return Value as T; } + /// public void Set(T value) { if (!ValueType.IsAssignableFrom(typeof(T))) @@ -56,8 +79,13 @@ public void Set(T value) Value = Convert.ChangeType(value, ValueType); } + /// public string Description { get; } + + /// public IValueConstraint Constraint { get; } + + /// public void RegisterCallback(Action valueChangedCallback) { Callbacks += valueChangedCallback; diff --git a/src/SpaceWarp.Core/API/Configuration/JsonConfigFile.cs b/src/SpaceWarp.Core/API/Configuration/JsonConfigFile.cs index aafbfc8..90d3886 100644 --- a/src/SpaceWarp.Core/API/Configuration/JsonConfigFile.cs +++ b/src/SpaceWarp.Core/API/Configuration/JsonConfigFile.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; +using System.Text; using JetBrains.Annotations; using KSP.IO; using Newtonsoft.Json; @@ -11,6 +8,9 @@ namespace SpaceWarp.API.Configuration; +/// +/// A config file that uses JSON to store its data. +/// [PublicAPI] public class JsonConfigFile : IConfigFile { @@ -19,6 +19,10 @@ public class JsonConfigFile : IConfigFile internal Dictionary> CurrentEntries = new(); private readonly string _file; + /// + /// Creates a new JSON config file object. + /// + /// The file path to use. public JsonConfigFile(string file) { // Use .cfg as this is going to have comments and that will be an issue @@ -38,6 +42,7 @@ public JsonConfigFile(string file) _file = file; } + /// public void Save() { if (!CurrentEntries.Any(value => value.Value.Count > 0)) return; @@ -72,6 +77,9 @@ private static bool DumpSection(bool hadPreviousSection, StringBuilder result, K private static List _defaultConverters; + /// + /// The default converters to use when serializing/deserializing JSON. + /// public static List DefaultConverters { get @@ -86,7 +94,11 @@ public static List DefaultConverters } } - private static bool DumpEntry(StringBuilder result, bool hadPreviousKey, KeyValuePair entry) + private static bool DumpEntry( + StringBuilder result, + bool hadPreviousKey, + KeyValuePair entry + ) { if (hadPreviousKey) { @@ -128,8 +140,10 @@ private static bool DumpEntry(StringBuilder result, bool hadPreviousKey, KeyValu return true; } + /// public IConfigEntry this[string section, string key] => CurrentEntries[section][key]; + /// public IConfigEntry Bind(string section, string key, T defaultValue = default, string description = "") { // So now we have to check if its already bound, and/or if the previous config object has it @@ -173,7 +187,9 @@ public IConfigEntry Bind(string section, string key, T defaultValue = default return previousSection[key]; } + /// public IReadOnlyList Sections => CurrentEntries.Keys.ToList(); + /// public IReadOnlyList this[string section] => CurrentEntries[section].Keys.ToList(); } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Configuration/ListConstraint.cs b/src/SpaceWarp.Core/API/Configuration/ListConstraint.cs index b9610ee..af5dd4b 100644 --- a/src/SpaceWarp.Core/API/Configuration/ListConstraint.cs +++ b/src/SpaceWarp.Core/API/Configuration/ListConstraint.cs @@ -1,32 +1,48 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Text; using BepInEx.Configuration; using JetBrains.Annotations; namespace SpaceWarp.API.Configuration; +/// +/// A constraint that checks if the value is in a list of acceptable values. +/// +/// The type of the value. public class ListConstraint : ValueConstraint where T : IEquatable { - [PublicAPI] - public List AcceptableValues; - + /// + /// The list of acceptable values. + /// + [PublicAPI] public List AcceptableValues; + + /// + /// Creates a new list constraint. + /// + /// The list of acceptable values. public ListConstraint(IEnumerable acceptableValues) { AcceptableValues = acceptableValues.ToList(); } + /// + /// Creates a new list constraint. + /// + /// The array of acceptable values. public ListConstraint(params T[] acceptableValues) { AcceptableValues = acceptableValues.ToList(); } + /// public override bool IsValid(T o) => AcceptableValues.Any(x => x.Equals(o)); + + /// public override AcceptableValueBase ToAcceptableValueBase() { return new AcceptableValueList(AcceptableValues.ToArray()); } + /// public override string ToString() { StringBuilder sb = new(); diff --git a/src/SpaceWarp.Core/API/Configuration/RangeConstraint.cs b/src/SpaceWarp.Core/API/Configuration/RangeConstraint.cs index 00fbc08..18e0a4c 100644 --- a/src/SpaceWarp.Core/API/Configuration/RangeConstraint.cs +++ b/src/SpaceWarp.Core/API/Configuration/RangeConstraint.cs @@ -1,28 +1,45 @@ -using System; -using BepInEx.Configuration; +using BepInEx.Configuration; using JetBrains.Annotations; namespace SpaceWarp.API.Configuration; +/// +/// A constraint that checks if a value is within a range. +/// +/// The type of the value. public class RangeConstraint : ValueConstraint where T : IComparable, IComparable { - [PublicAPI] - public T Minimum; - [PublicAPI] - public T Maximum; + /// + /// The minimum value. + /// + [PublicAPI] public T Minimum; + /// + /// The maximum value. + /// + [PublicAPI] public T Maximum; + + /// + /// Creates a new range constraint. + /// + /// The minimum value. + /// The maximum value. public RangeConstraint(T minimum, T maximum) { Minimum = minimum; Maximum = maximum; } + /// public override bool IsValid(T o) => Minimum.CompareTo(o) <= 0 && Maximum.CompareTo(o) >= 0; + + /// public override AcceptableValueBase ToAcceptableValueBase() { return new AcceptableValueRange(Minimum, Maximum); } + /// public override string ToString() { return $"{Minimum} - {Maximum}"; diff --git a/src/SpaceWarp.Core/API/Configuration/ValueConstraint.cs b/src/SpaceWarp.Core/API/Configuration/ValueConstraint.cs index ddabf76..4ba8da0 100644 --- a/src/SpaceWarp.Core/API/Configuration/ValueConstraint.cs +++ b/src/SpaceWarp.Core/API/Configuration/ValueConstraint.cs @@ -2,18 +2,35 @@ namespace SpaceWarp.API.Configuration; +/// +/// Base class for value constraints. +/// +/// Type of the value. public abstract class ValueConstraint : IValueConstraint { + /// + /// Returns true if the given value is valid for this constraint. + /// + /// Value to check. + /// True if the value is valid, false otherwise. public abstract bool IsValid(T o); + + /// + /// Returns true if the given value is valid for this constraint. + /// + /// Value to check. + /// True if the value is valid, false otherwise. public bool IsValid(object o) { return IsValid((T)o); } + /// public bool IsConstrained(object o) { return IsValid((T)o); } + /// public abstract AcceptableValueBase ToAcceptableValueBase(); } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Loading/Loading.cs b/src/SpaceWarp.Core/API/Loading/Loading.cs index e9a0a82..e73588a 100644 --- a/src/SpaceWarp.Core/API/Loading/Loading.cs +++ b/src/SpaceWarp.Core/API/Loading/Loading.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.IO; -using JetBrains.Annotations; +using JetBrains.Annotations; using KSP.Game.Flow; using SpaceWarp.API.Assets; using SpaceWarp.API.Mods; @@ -10,6 +7,9 @@ namespace SpaceWarp.API.Loading; +/// +/// API for mods to register their actions for the loading of assets. +/// [PublicAPI] public static class Loading { @@ -20,7 +20,7 @@ public static class Loading internal static List> GeneralLoadingActions = new(); /// - /// Registers an asset loading function for space warp, will load assets from the subfolder. Should be added either on Awake() or Start(). + /// Registers an asset loading function for SpaceWarp, will load assets from the subfolder. Should be added either on Awake() or Start(). /// /// The subfolder under "assets" that this loader matches /// The name to be displayed for this loader, it gets displayed like the following "Mod Name: [name]" diff --git a/src/SpaceWarp.Core/API/Loading/SaveLoad.cs b/src/SpaceWarp.Core/API/Loading/SaveLoad.cs index cd617ef..53c8779 100644 --- a/src/SpaceWarp.Core/API/Loading/SaveLoad.cs +++ b/src/SpaceWarp.Core/API/Loading/SaveLoad.cs @@ -1,17 +1,19 @@ -using System; -using JetBrains.Annotations; +using JetBrains.Annotations; using KSP.Game.Flow; using SpaceWarp.Patching; namespace SpaceWarp.API.Loading; +/// +/// An API to register flow actions to be run during loading and saving. +/// [PublicAPI] public static class SaveLoad { /// /// Construct and add a FlowAction to the Game's load sequence. /// - /// FlowActionType must have a public constructor that takes either no arguments, + /// TFlowActionType must have a public constructor that takes either no arguments, /// or a single GameManager. /// /// The action will be run after the first FlowAction with a name equal to referenceAction. @@ -34,12 +36,12 @@ public static class SaveLoad /// /// /// - /// The type of FlowAction to insert - /// The name of the action to insert a FlowActionType after. Use null to insert it at the start. - /// Thrown if FlowActionType does not have a valid Constructor - public static void AddFlowActionToGameLoadAfter(string referenceAction) where FlowActionType : FlowAction + /// The type of FlowAction to insert + /// The name of the action to insert a TFlowActionType after. Use null to insert it at the start. + /// Thrown if TFlowActionType does not have a valid Constructor + public static void AddFlowActionToGameLoadAfter(string referenceAction) where TFlowActionType : FlowAction { - SequentialFlowLoadersPatcher.AddConstructor(referenceAction, typeof(FlowActionType), SequentialFlowLoadersPatcher.FlowMethodStartgame); + SequentialFlowLoadersPatcher.AddConstructor(referenceAction, typeof(TFlowActionType), SequentialFlowLoadersPatcher.FlowMethodStartgame); } /// @@ -66,17 +68,17 @@ public static void AddFlowActionToGameLoadAfter(string reference /// /// /// The FlowAction to insert - /// The name of the action to insert a FlowActionType after. Use null to insert it at the start. + /// The name of the action to insert a TFlowActionType after. Use null to insert it at the start. public static void AddFlowActionToGameLoadAfter(FlowAction flowAction, string referenceAction) { SequentialFlowLoadersPatcher.AddFlowAction(referenceAction, flowAction, SequentialFlowLoadersPatcher.FlowMethodStartgame); } /// - /// Add a FlowAction to the save file loading sequence. A new FlowActionType is constructed every load. + /// Add a FlowAction to the save file loading sequence. A new TFlowActionType is constructed every load. /// /// - /// FlowActionType must have a public constructor that at most one of each of the following types: + /// TFlowActionType must have a public constructor that at most one of each of the following types: /// /// SaveLoadManager /// LoadOrSaveCampaignTicket @@ -145,12 +147,12 @@ public static void AddFlowActionToGameLoadAfter(FlowAction flowAction, string re /// /// /// - /// The type of FlowAction to insert - /// The name of the action to insert a FlowActionType after. Use null to insert it at the start. - /// Thrown if FlowActionType does not have a valid Constructor - public static void AddFlowActionToCampaignLoadAfter(string referenceAction) where FlowActionType : FlowAction + /// The type of FlowAction to insert + /// The name of the action to insert a TFlowActionType after. Use null to insert it at the start. + /// Thrown if TFlowActionType does not have a valid Constructor + public static void AddFlowActionToCampaignLoadAfter(string referenceAction) where TFlowActionType : FlowAction { - SequentialFlowLoadersPatcher.AddConstructor(referenceAction, typeof(FlowActionType), SequentialFlowLoadersPatcher.FlowMethodPrivateloadcommon); + SequentialFlowLoadersPatcher.AddConstructor(referenceAction, typeof(TFlowActionType), SequentialFlowLoadersPatcher.FlowMethodPrivateloadcommon); } /// @@ -225,10 +227,10 @@ public static void AddFlowActionToCampaignLoadAfter(FlowAction flowAction, strin } /// - /// Add a FlowAction to the save file writing sequence. A new FlowActionType is constructed every load. + /// Add a FlowAction to the save file writing sequence. A new TFlowActionType is constructed every load. /// /// - /// FlowActionType must have a public constructor that at most one of each of the following types: + /// TFlowActionType must have a public constructor that at most one of each of the following types: /// /// SaveLoadManager /// LoadOrSaveCampaignTicket @@ -258,12 +260,12 @@ public static void AddFlowActionToCampaignLoadAfter(FlowAction flowAction, strin /// /// /// - /// The type of FlowAction to insert - /// The name of the action to insert a FlowActionType after. Use null to insert it at the start. - /// Thrown if FlowActionType does not have a valid Constructor - public static void AddFlowActionToCampaignSaveAfter(string referenceAction) where FlowActionType : FlowAction + /// The type of FlowAction to insert + /// The name of the action to insert a TFlowActionType after. Use null to insert it at the start. + /// Thrown if TFlowActionType does not have a valid Constructor + public static void AddFlowActionToCampaignSaveAfter(string referenceAction) where TFlowActionType : FlowAction { - SequentialFlowLoadersPatcher.AddConstructor(referenceAction, typeof(FlowActionType), SequentialFlowLoadersPatcher.FlowMethodPrivatesavecommon); + SequentialFlowLoadersPatcher.AddConstructor(referenceAction, typeof(TFlowActionType), SequentialFlowLoadersPatcher.FlowMethodPrivatesavecommon); } /// diff --git a/src/SpaceWarp.Core/API/Lua/LuaMod.cs b/src/SpaceWarp.Core/API/Lua/LuaMod.cs index 1496019..8ce38ac 100644 --- a/src/SpaceWarp.Core/API/Lua/LuaMod.cs +++ b/src/SpaceWarp.Core/API/Lua/LuaMod.cs @@ -1,15 +1,20 @@ -using System; -using BepInEx.Logging; +using BepInEx.Logging; using JetBrains.Annotations; using KSP.Game; using MoonSharp.Interpreter; namespace SpaceWarp.API.Lua; +/// +/// A Lua mod, this is the base class for all mods that are written in Lua. +/// [MoonSharpUserData] [PublicAPI] public class LuaMod : KerbalMonoBehaviour { + /// + /// The table that contains the mod's functions. + /// public Table ModTable; // TODO: Add more than just this to the behaviour but for now @@ -33,9 +38,15 @@ public class LuaMod : KerbalMonoBehaviour private Closure _reset; #endregion + /// + /// The logger for this mod. + /// public ManualLogSource Logger; - // First a pass through to the wrapped table + /// + /// A pass through to the wrapped table + /// + /// The index of the name. public DynValue this[DynValue idx] { get => ModTable.Get(idx); @@ -55,17 +66,17 @@ private void TryCallMethod(Closure closure, params object[] args) } #region Message Handlers - private void TryRegister(string name, out Closure method) + private void TryRegister(string methodName, out Closure method) { - if (ModTable.Get(name) != null && ModTable.Get(name).Type == DataType.Function) + if (ModTable.Get(methodName) != null && ModTable.Get(methodName).Type == DataType.Function) { - method = ModTable.Get(name).Function; + method = ModTable.Get(methodName).Function; return; } method = null; } - public void Awake() + private void Awake() { if (ModTable.Get("Awake") != null && ModTable.Get("Awake").Type == DataType.Function) { @@ -92,7 +103,7 @@ public void Awake() } // Start - public void Start() + private void Start() { if (_start != null) { @@ -102,7 +113,7 @@ public void Start() // Update Functions - public void Update() + private void Update() { if (_update != null) { @@ -110,7 +121,7 @@ public void Update() } } - public void FixedUpdate() + private void FixedUpdate() { if (_fixedUpdate != null) { @@ -118,7 +129,7 @@ public void FixedUpdate() } } - public void LateUpdate() + private void LateUpdate() { if (_lateUpdate != null) { @@ -128,7 +139,7 @@ public void LateUpdate() // Enable/Disable - public void OnEnable() + private void OnEnable() { if (_onEnable != null) { @@ -136,7 +147,7 @@ public void OnEnable() } } - public void OnDisable() + private void OnDisable() { if (_onDisable != null) { @@ -146,7 +157,7 @@ public void OnDisable() // Destruction - public void OnDestroy() + private void OnDestroy() { if (_onDestroy != null) { @@ -155,7 +166,7 @@ public void OnDestroy() } // Reset - public void Reset() + private void Reset() { if (_reset != null) { diff --git a/src/SpaceWarp.Core/API/Lua/SpaceWarpLuaAPIAttribute.cs b/src/SpaceWarp.Core/API/Lua/SpaceWarpLuaAPIAttribute.cs index 91fc288..7c346fa 100644 --- a/src/SpaceWarp.Core/API/Lua/SpaceWarpLuaAPIAttribute.cs +++ b/src/SpaceWarp.Core/API/Lua/SpaceWarpLuaAPIAttribute.cs @@ -1,13 +1,23 @@ -using System; -using JetBrains.Annotations; +using JetBrains.Annotations; namespace SpaceWarp.API.Lua; +/// +/// Marks a class as a Lua API class, allowing it to be used in Lua. +/// [AttributeUsage(AttributeTargets.Class)] [MeansImplicitUse] public class SpaceWarpLuaAPIAttribute : Attribute { + /// + /// The name of the class in Lua. + /// public string LuaName; + + /// + /// Marks a class as a Lua API class, allowing it to be used in Lua. + /// + /// public SpaceWarpLuaAPIAttribute(string luaName) { LuaName = luaName; diff --git a/src/SpaceWarp.Core/API/Mods/GlobalModDefines.cs b/src/SpaceWarp.Core/API/Mods/GlobalModDefines.cs index 4c36ad8..16f660f 100644 --- a/src/SpaceWarp.Core/API/Mods/GlobalModDefines.cs +++ b/src/SpaceWarp.Core/API/Mods/GlobalModDefines.cs @@ -1,5 +1,4 @@ -using System.IO; -using JetBrains.Annotations; +using JetBrains.Annotations; namespace SpaceWarp.API.Mods; diff --git a/src/SpaceWarp.Core/API/Mods/JSON/Converters/SpecVersionConverter.cs b/src/SpaceWarp.Core/API/Mods/JSON/Converters/SpecVersionConverter.cs index 0b74286..ac65866 100644 --- a/src/SpaceWarp.Core/API/Mods/JSON/Converters/SpecVersionConverter.cs +++ b/src/SpaceWarp.Core/API/Mods/JSON/Converters/SpecVersionConverter.cs @@ -1,5 +1,4 @@ -using System; -using Newtonsoft.Json; +using Newtonsoft.Json; namespace SpaceWarp.API.Mods.JSON.Converters; diff --git a/src/SpaceWarp.Core/API/Mods/JSON/ModInfo.cs b/src/SpaceWarp.Core/API/Mods/JSON/ModInfo.cs index 9a97192..78fe129 100644 --- a/src/SpaceWarp.Core/API/Mods/JSON/ModInfo.cs +++ b/src/SpaceWarp.Core/API/Mods/JSON/ModInfo.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using JetBrains.Annotations; +using JetBrains.Annotations; using Newtonsoft.Json; namespace SpaceWarp.API.Mods.JSON; diff --git a/src/SpaceWarp.Core/API/Mods/JSON/SpecVersion.cs b/src/SpaceWarp.Core/API/Mods/JSON/SpecVersion.cs index aa4c00d..bc73289 100644 --- a/src/SpaceWarp.Core/API/Mods/JSON/SpecVersion.cs +++ b/src/SpaceWarp.Core/API/Mods/JSON/SpecVersion.cs @@ -1,5 +1,4 @@ -using System; -using JetBrains.Annotations; +using JetBrains.Annotations; using Newtonsoft.Json; using SpaceWarp.API.Mods.JSON.Converters; diff --git a/src/SpaceWarp.Core/API/Mods/JSON/VersionCheckType.cs b/src/SpaceWarp.Core/API/Mods/JSON/VersionCheckType.cs index bfa1b6d..d6c0bb4 100644 --- a/src/SpaceWarp.Core/API/Mods/JSON/VersionCheckType.cs +++ b/src/SpaceWarp.Core/API/Mods/JSON/VersionCheckType.cs @@ -1,5 +1,4 @@ -using System; -using System.Runtime.Serialization; +using System.Runtime.Serialization; using JetBrains.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Converters; diff --git a/src/SpaceWarp.Core/API/Mods/PluginList.cs b/src/SpaceWarp.Core/API/Mods/PluginList.cs index 73c7f22..b5c994a 100644 --- a/src/SpaceWarp.Core/API/Mods/PluginList.cs +++ b/src/SpaceWarp.Core/API/Mods/PluginList.cs @@ -1,13 +1,9 @@ -using System; -using System.Collections.Generic; -using BepInEx; +using BepInEx; using BepInEx.Bootstrap; using JetBrains.Annotations; using SpaceWarp.API.Mods.JSON; using SpaceWarp.API.Versions; using SpaceWarpPatcher; -using UnityEngine.InputSystem; -using UnityEngine.InputSystem.Switch.LowLevel; // Disable obsolete warning for Chainloader.Plugins #pragma warning disable CS0618 diff --git a/src/SpaceWarp.Core/API/Mods/SpaceWarpErrorDescription.cs b/src/SpaceWarp.Core/API/Mods/SpaceWarpErrorDescription.cs index 22456c0..6afadc3 100644 --- a/src/SpaceWarp.Core/API/Mods/SpaceWarpErrorDescription.cs +++ b/src/SpaceWarp.Core/API/Mods/SpaceWarpErrorDescription.cs @@ -1,8 +1,6 @@ -using System.Collections.Generic; -using BepInEx; +using BepInEx; using JetBrains.Annotations; using SpaceWarp.Patching; -using UnityEngine; namespace SpaceWarp.API.Mods; diff --git a/src/SpaceWarp.Core/API/Mods/SpaceWarpPluginDescriptor.cs b/src/SpaceWarp.Core/API/Mods/SpaceWarpPluginDescriptor.cs index fdf7edf..1f2eca8 100644 --- a/src/SpaceWarp.Core/API/Mods/SpaceWarpPluginDescriptor.cs +++ b/src/SpaceWarp.Core/API/Mods/SpaceWarpPluginDescriptor.cs @@ -1,5 +1,4 @@ -using System.IO; -using JetBrains.Annotations; +using JetBrains.Annotations; using SpaceWarp.API.Configuration; using SpaceWarp.API.Mods.JSON; diff --git a/src/SpaceWarp.Core/API/Parts/Colors.cs b/src/SpaceWarp.Core/API/Parts/Colors.cs index 752bb84..8bfa17e 100644 --- a/src/SpaceWarp.Core/API/Parts/Colors.cs +++ b/src/SpaceWarp.Core/API/Parts/Colors.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using JetBrains.Annotations; +using JetBrains.Annotations; using SpaceWarp.API.Lua; using SpaceWarp.Patching; using UnityEngine; diff --git a/src/SpaceWarp.Core/API/SaveGameManager/ModSaves.cs b/src/SpaceWarp.Core/API/SaveGameManager/ModSaves.cs index 792d0ee..432a134 100644 --- a/src/SpaceWarp.Core/API/SaveGameManager/ModSaves.cs +++ b/src/SpaceWarp.Core/API/SaveGameManager/ModSaves.cs @@ -1,7 +1,5 @@ using JetBrains.Annotations; using SpaceWarp.Backend.SaveGameManager; -using System; -using System.Collections.Generic; using SpaceWarp.API.Logging; namespace SpaceWarp.API.SaveGameManager; diff --git a/src/SpaceWarp.Core/API/Versions/SemanticVersion.cs b/src/SpaceWarp.Core/API/Versions/SemanticVersion.cs index ea45be7..bb51a7e 100644 --- a/src/SpaceWarp.Core/API/Versions/SemanticVersion.cs +++ b/src/SpaceWarp.Core/API/Versions/SemanticVersion.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; + // Disable warnings for missing Equals and GetHashCode implementations #pragma warning disable CS0660, CS0661 diff --git a/src/SpaceWarp.Core/API/Versions/VersionUtility.cs b/src/SpaceWarp.Core/API/Versions/VersionUtility.cs index b6f9b2a..dc0b092 100644 --- a/src/SpaceWarp.Core/API/Versions/VersionUtility.cs +++ b/src/SpaceWarp.Core/API/Versions/VersionUtility.cs @@ -1,5 +1,4 @@ -using System; -using System.Text.RegularExpressions; +using System.Text.RegularExpressions; using JetBrains.Annotations; namespace SpaceWarp.API.Versions; diff --git a/src/SpaceWarp.Core/Backend/Modding/Ksp2ModInfo.cs b/src/SpaceWarp.Core/Backend/Modding/Ksp2ModInfo.cs index d8615dd..fd1732d 100644 --- a/src/SpaceWarp.Core/Backend/Modding/Ksp2ModInfo.cs +++ b/src/SpaceWarp.Core/Backend/Modding/Ksp2ModInfo.cs @@ -1,5 +1,4 @@ -using System; -using Newtonsoft.Json; +using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace SpaceWarp.Backend.Modding; diff --git a/src/SpaceWarp.Core/Backend/Modding/PluginRegister.cs b/src/SpaceWarp.Core/Backend/Modding/PluginRegister.cs index 88d24c1..6b1b2aa 100644 --- a/src/SpaceWarp.Core/Backend/Modding/PluginRegister.cs +++ b/src/SpaceWarp.Core/Backend/Modding/PluginRegister.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text.RegularExpressions; -using BepInEx; +using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using Newtonsoft.Json; diff --git a/src/SpaceWarp.Core/Backend/SaveGameManager/PluginSaveData.cs b/src/SpaceWarp.Core/Backend/SaveGameManager/PluginSaveData.cs index 768e5bf..a439d08 100644 --- a/src/SpaceWarp.Core/Backend/SaveGameManager/PluginSaveData.cs +++ b/src/SpaceWarp.Core/Backend/SaveGameManager/PluginSaveData.cs @@ -1,6 +1,4 @@ -using System; - -namespace SpaceWarp.Backend.SaveGameManager; +namespace SpaceWarp.Backend.SaveGameManager; internal delegate void SaveGameCallbackFunctionDelegate(object data); diff --git a/src/SpaceWarp.Core/Backend/SaveGameManager/SpaceWarpSerializedSavedGame.cs b/src/SpaceWarp.Core/Backend/SaveGameManager/SpaceWarpSerializedSavedGame.cs index a777997..e5501d7 100644 --- a/src/SpaceWarp.Core/Backend/SaveGameManager/SpaceWarpSerializedSavedGame.cs +++ b/src/SpaceWarp.Core/Backend/SaveGameManager/SpaceWarpSerializedSavedGame.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using UnityEngine.Serialization; - -namespace SpaceWarp.Backend.SaveGameManager; +namespace SpaceWarp.Backend.SaveGameManager; /// /// Extension of game's save/load data class diff --git a/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs b/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs index 5eeeaac..5d36524 100644 --- a/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs +++ b/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs @@ -1,4 +1,3 @@ -using System.IO; using I2.Loc; using KSP.Game; using UnityEngine.AddressableAssets; diff --git a/src/SpaceWarp.Core/InternalUtilities/InternalExtensions.cs b/src/SpaceWarp.Core/InternalUtilities/InternalExtensions.cs index 55accc7..e6aeb81 100644 --- a/src/SpaceWarp.Core/InternalUtilities/InternalExtensions.cs +++ b/src/SpaceWarp.Core/InternalUtilities/InternalExtensions.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System; using UnityEngine; using System.Collections; diff --git a/src/SpaceWarp.Core/InternalUtilities/PathHelpers.cs b/src/SpaceWarp.Core/InternalUtilities/PathHelpers.cs index 49eb5e8..1f69801 100644 --- a/src/SpaceWarp.Core/InternalUtilities/PathHelpers.cs +++ b/src/SpaceWarp.Core/InternalUtilities/PathHelpers.cs @@ -1,7 +1,4 @@ -using System; -using System.IO; - -namespace SpaceWarp.InternalUtilities; +namespace SpaceWarp.InternalUtilities; internal static class PathHelpers { diff --git a/src/SpaceWarp.Core/Modules/ModuleManager.cs b/src/SpaceWarp.Core/Modules/ModuleManager.cs index 29876cc..0b7a843 100644 --- a/src/SpaceWarp.Core/Modules/ModuleManager.cs +++ b/src/SpaceWarp.Core/Modules/ModuleManager.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; +using System.Reflection; using HarmonyLib; using SpaceWarp.API.Configuration; using SpaceWarp.API.Logging; diff --git a/src/SpaceWarp.Core/Modules/SpaceWarpModule.cs b/src/SpaceWarp.Core/Modules/SpaceWarpModule.cs index d2f89bd..9f08d28 100644 --- a/src/SpaceWarp.Core/Modules/SpaceWarpModule.cs +++ b/src/SpaceWarp.Core/Modules/SpaceWarpModule.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using SpaceWarp.API.Configuration; +using SpaceWarp.API.Configuration; using SpaceWarp.API.Logging; namespace SpaceWarp.Modules; diff --git a/src/SpaceWarp.Core/Patching/BootstrapPatch.cs b/src/SpaceWarp.Core/Patching/BootstrapPatch.cs index 29a080f..39219b3 100644 --- a/src/SpaceWarp.Core/Patching/BootstrapPatch.cs +++ b/src/SpaceWarp.Core/Patching/BootstrapPatch.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using HarmonyLib; using KSP.Game; using KSP.Game.Flow; diff --git a/src/SpaceWarp.Core/Patching/ColorsPatch.cs b/src/SpaceWarp.Core/Patching/ColorsPatch.cs index c2d8b52..1c7bb4a 100644 --- a/src/SpaceWarp.Core/Patching/ColorsPatch.cs +++ b/src/SpaceWarp.Core/Patching/ColorsPatch.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using System.Reflection; +using System.Reflection; using BepInEx.Logging; using Castle.Core.Internal; using HarmonyLib; diff --git a/src/SpaceWarp.Core/Patching/FixGetTypes.cs b/src/SpaceWarp.Core/Patching/FixGetTypes.cs index 19ddcf9..0ebee94 100644 --- a/src/SpaceWarp.Core/Patching/FixGetTypes.cs +++ b/src/SpaceWarp.Core/Patching/FixGetTypes.cs @@ -1,4 +1,3 @@ -using System; using System.Reflection; using BepInEx.Logging; using HarmonyLib; diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/AddressableAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/AddressableAction.cs index cfb2dbc..cd588b5 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/AddressableAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/AddressableAction.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using JetBrains.Annotations; +using JetBrains.Annotations; using KSP.Game; using KSP.Game.Flow; using UnityEngine; diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/DescriptorLoadingAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/DescriptorLoadingAction.cs index b1ab21d..e7c7958 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/DescriptorLoadingAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/DescriptorLoadingAction.cs @@ -1,5 +1,4 @@ -using System; -using JetBrains.Annotations; +using JetBrains.Annotations; using KSP.Game.Flow; using SpaceWarp.API.Mods; diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/FunctionalLoadingActions.cs b/src/SpaceWarp.Core/Patching/LoadingActions/FunctionalLoadingActions.cs index 59e6896..bb98a70 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/FunctionalLoadingActions.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/FunctionalLoadingActions.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.IO; -using UnityEngine; +using UnityEngine; namespace SpaceWarp.Patching.LoadingActions; diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/InitializeModAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/InitializeModAction.cs index 04ad68e..25ab834 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/InitializeModAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/InitializeModAction.cs @@ -1,4 +1,3 @@ -using System; using KSP.Game.Flow; using SpaceWarp.API.Mods; diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/LoadAddressablesAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/LoadAddressablesAction.cs index 3e7376b..b4c50e9 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/LoadAddressablesAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/LoadAddressablesAction.cs @@ -1,6 +1,4 @@ -using System; -using System.IO; -using BepInEx.Logging; +using BepInEx.Logging; using KSP.Game.Flow; using SpaceWarp.API.Mods; using SpaceWarp.InternalUtilities; diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/LoadLocalizationAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/LoadLocalizationAction.cs index 6964691..bf00eba 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/LoadLocalizationAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/LoadLocalizationAction.cs @@ -1,6 +1,4 @@ -using System; -using System.IO; -using KSP.Game.Flow; +using KSP.Game.Flow; using SpaceWarp.API.Mods; using SpaceWarp.InternalUtilities; diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/LoadLuaAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/LoadLuaAction.cs index 0403bc0..bd8f096 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/LoadLuaAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/LoadLuaAction.cs @@ -1,6 +1,4 @@ -using System; -using System.IO; -using KSP.Game.Flow; +using KSP.Game.Flow; using SpaceWarp.API.Mods; namespace SpaceWarp.Patching.LoadingActions; diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/LoadingAddressablesLocalizationsAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/LoadingAddressablesLocalizationsAction.cs index dc0e075..cecd044 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/LoadingAddressablesLocalizationsAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/LoadingAddressablesLocalizationsAction.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using I2.Loc; +using I2.Loc; using KSP.Game; using KSP.Game.Flow; using UnityEngine; diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs index e595db7..d9ec2d4 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs @@ -1,5 +1,4 @@ -using System; -using JetBrains.Annotations; +using JetBrains.Annotations; using KSP.Game.Flow; using SpaceWarp.API.Mods; diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/PostInitializeModAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/PostInitializeModAction.cs index e8c5894..d582183 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/PostInitializeModAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/PostInitializeModAction.cs @@ -1,5 +1,4 @@ -using System; -using KSP.Game.Flow; +using KSP.Game.Flow; using SpaceWarp.API.Mods; namespace SpaceWarp.Patching.LoadingActions; diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/PreInitializeModAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/PreInitializeModAction.cs index a8aac19..ae5d97e 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/PreInitializeModAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/PreInitializeModAction.cs @@ -1,4 +1,3 @@ -using System; using KSP.Game.Flow; using SpaceWarp.API.Mods; diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/ResolvingPatchOrderAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/ResolvingPatchOrderAction.cs index 76926cd..acd2375 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/ResolvingPatchOrderAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/ResolvingPatchOrderAction.cs @@ -1,5 +1,4 @@ -using System; -using KSP.Game.Flow; +using KSP.Game.Flow; namespace SpaceWarp.Patching.LoadingActions; diff --git a/src/SpaceWarp.Core/Patching/ModLoaderPatch.cs b/src/SpaceWarp.Core/Patching/ModLoaderPatch.cs index 98d10a6..eed6820 100644 --- a/src/SpaceWarp.Core/Patching/ModLoaderPatch.cs +++ b/src/SpaceWarp.Core/Patching/ModLoaderPatch.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; +using System.Reflection; using HarmonyLib; using KSP.Modding; using Newtonsoft.Json; diff --git a/src/SpaceWarp.Core/Patching/SaveGameManager/SaveGamePatches.cs b/src/SpaceWarp.Core/Patching/SaveGameManager/SaveGamePatches.cs index 5dad181..ff85ffa 100644 --- a/src/SpaceWarp.Core/Patching/SaveGameManager/SaveGamePatches.cs +++ b/src/SpaceWarp.Core/Patching/SaveGameManager/SaveGamePatches.cs @@ -5,7 +5,6 @@ using SpaceWarp.API.SaveGameManager; using SpaceWarp.Backend.SaveGameManager; using SpaceWarp.InternalUtilities; -using System; namespace SpaceWarp.Patching.SaveGameManager; diff --git a/src/SpaceWarp.Core/Patching/SequentialFlowLoadersPatcher.cs b/src/SpaceWarp.Core/Patching/SequentialFlowLoadersPatcher.cs index e84a706..34864b4 100644 --- a/src/SpaceWarp.Core/Patching/SequentialFlowLoadersPatcher.cs +++ b/src/SpaceWarp.Core/Patching/SequentialFlowLoadersPatcher.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Reflection; +using System.Reflection; using System.Reflection.Emit; using BepInEx.Logging; using HarmonyLib; diff --git a/src/SpaceWarp.Core/Patching/SettingsManagerPatcher.cs b/src/SpaceWarp.Core/Patching/SettingsManagerPatcher.cs index 93864fe..5ff50e8 100644 --- a/src/SpaceWarp.Core/Patching/SettingsManagerPatcher.cs +++ b/src/SpaceWarp.Core/Patching/SettingsManagerPatcher.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using HarmonyLib; +using HarmonyLib; using KSP.UI; namespace SpaceWarp.Patching; diff --git a/src/SpaceWarp.Core/SpaceWarpPlugin.cs b/src/SpaceWarp.Core/SpaceWarpPlugin.cs index cb66ee9..8fd340d 100644 --- a/src/SpaceWarp.Core/SpaceWarpPlugin.cs +++ b/src/SpaceWarp.Core/SpaceWarpPlugin.cs @@ -1,7 +1,5 @@ global using UnityObject = UnityEngine.Object; global using System.Linq; -using System; -using System.IO; using System.Reflection; using BepInEx; using BepInEx.Logging; diff --git a/src/SpaceWarp.Game/API/Game/Extensions/PartProviderExtensions.cs b/src/SpaceWarp.Game/API/Game/Extensions/PartProviderExtensions.cs index d77af41..e939bf7 100644 --- a/src/SpaceWarp.Game/API/Game/Extensions/PartProviderExtensions.cs +++ b/src/SpaceWarp.Game/API/Game/Extensions/PartProviderExtensions.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; -using System.Linq; -using JetBrains.Annotations; +using JetBrains.Annotations; using KSP.Game; using KSP.Sim.Definitions; diff --git a/src/SpaceWarp.Game/API/Game/Messages/StateChanges.cs b/src/SpaceWarp.Game/API/Game/Messages/StateChanges.cs index c0f5768..308268e 100644 --- a/src/SpaceWarp.Game/API/Game/Messages/StateChanges.cs +++ b/src/SpaceWarp.Game/API/Game/Messages/StateChanges.cs @@ -1,5 +1,4 @@ -using System; -using JetBrains.Annotations; +using JetBrains.Annotations; using KSP.Game; using KSP.Messages; diff --git a/src/SpaceWarp.Game/API/Game/Messages/StateLoadings.cs b/src/SpaceWarp.Game/API/Game/Messages/StateLoadings.cs index 94df110..2ea1ce1 100644 --- a/src/SpaceWarp.Game/API/Game/Messages/StateLoadings.cs +++ b/src/SpaceWarp.Game/API/Game/Messages/StateLoadings.cs @@ -1,5 +1,4 @@ -using System; -using JetBrains.Annotations; +using JetBrains.Annotations; using KSP.Messages; namespace SpaceWarp.API.Game.Messages; diff --git a/src/SpaceWarp.Messaging/API/Messaging/MessageBus.cs b/src/SpaceWarp.Messaging/API/Messaging/MessageBus.cs index dc220ba..2a5b426 100644 --- a/src/SpaceWarp.Messaging/API/Messaging/MessageBus.cs +++ b/src/SpaceWarp.Messaging/API/Messaging/MessageBus.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using JetBrains.Annotations; -using UnityEngine; +using JetBrains.Annotations; namespace SpaceWarp.API.Messaging; diff --git a/src/SpaceWarp.Messaging/API/Messaging/MessageBusBase.cs b/src/SpaceWarp.Messaging/API/Messaging/MessageBusBase.cs index f8ae278..0fe45c2 100644 --- a/src/SpaceWarp.Messaging/API/Messaging/MessageBusBase.cs +++ b/src/SpaceWarp.Messaging/API/Messaging/MessageBusBase.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using JetBrains.Annotations; +using JetBrains.Annotations; namespace SpaceWarp.API.Messaging; diff --git a/src/SpaceWarp.Messaging/API/Messaging/MessageBusManager.cs b/src/SpaceWarp.Messaging/API/Messaging/MessageBusManager.cs index 8b256e9..cc68732 100644 --- a/src/SpaceWarp.Messaging/API/Messaging/MessageBusManager.cs +++ b/src/SpaceWarp.Messaging/API/Messaging/MessageBusManager.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using JetBrains.Annotations; -using UnityEngine; +using JetBrains.Annotations; namespace SpaceWarp.API.Messaging; diff --git a/src/SpaceWarp.Sound/API/Sound/Soundbank.cs b/src/SpaceWarp.Sound/API/Sound/Soundbank.cs index 50a4065..d95e376 100644 --- a/src/SpaceWarp.Sound/API/Sound/Soundbank.cs +++ b/src/SpaceWarp.Sound/API/Sound/Soundbank.cs @@ -1,5 +1,4 @@ -using System; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; using JetBrains.Annotations; namespace SpaceWarp.API.Sound; diff --git a/src/SpaceWarp.Sound/API/Sound/SoundbankManager.cs b/src/SpaceWarp.Sound/API/Sound/SoundbankManager.cs index 7e1466f..0f3ea60 100644 --- a/src/SpaceWarp.Sound/API/Sound/SoundbankManager.cs +++ b/src/SpaceWarp.Sound/API/Sound/SoundbankManager.cs @@ -1,5 +1,4 @@ using JetBrains.Annotations; -using System.Collections.Generic; namespace SpaceWarp.API.Sound; diff --git a/src/SpaceWarp.Sound/Modules/Sound.cs b/src/SpaceWarp.Sound/Modules/Sound.cs index 1497d6a..6d4b3b6 100644 --- a/src/SpaceWarp.Sound/Modules/Sound.cs +++ b/src/SpaceWarp.Sound/Modules/Sound.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.IO; -using JetBrains.Annotations; +using JetBrains.Annotations; using SpaceWarp.API.Loading; using SpaceWarp.API.Sound; using UnityObject = UnityEngine.Object; diff --git a/src/SpaceWarp.UI/API/Lua/AppBarInterop.cs b/src/SpaceWarp.UI/API/Lua/AppBarInterop.cs index 6fe42aa..b830a3b 100644 --- a/src/SpaceWarp.UI/API/Lua/AppBarInterop.cs +++ b/src/SpaceWarp.UI/API/Lua/AppBarInterop.cs @@ -1,5 +1,4 @@ -using System; -using JetBrains.Annotations; +using JetBrains.Annotations; using MoonSharp.Interpreter; using SpaceWarp.API.Assets; using SpaceWarp.API.UI.Appbar; diff --git a/src/SpaceWarp.UI/API/UI/Appbar/Appbar.cs b/src/SpaceWarp.UI/API/UI/Appbar/Appbar.cs index af009f9..cc441bf 100644 --- a/src/SpaceWarp.UI/API/UI/Appbar/Appbar.cs +++ b/src/SpaceWarp.UI/API/UI/Appbar/Appbar.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using BepInEx.Bootstrap; using JetBrains.Annotations; using KSP.UI.Binding; diff --git a/src/SpaceWarp.UI/API/UI/Appbar/AppbarMenu.cs b/src/SpaceWarp.UI/API/UI/Appbar/AppbarMenu.cs index 2e130c1..081b76b 100644 --- a/src/SpaceWarp.UI/API/UI/Appbar/AppbarMenu.cs +++ b/src/SpaceWarp.UI/API/UI/Appbar/AppbarMenu.cs @@ -1,4 +1,3 @@ -using System; using JetBrains.Annotations; using KSP.Game; using KSP.Sim.impl; diff --git a/src/SpaceWarp.UI/API/UI/MainMenu.cs b/src/SpaceWarp.UI/API/UI/MainMenu.cs index 5667fd4..9e72d6f 100644 --- a/src/SpaceWarp.UI/API/UI/MainMenu.cs +++ b/src/SpaceWarp.UI/API/UI/MainMenu.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using JetBrains.Annotations; +using JetBrains.Annotations; namespace SpaceWarp.API.UI; diff --git a/src/SpaceWarp.UI/API/UI/ModList.cs b/src/SpaceWarp.UI/API/UI/ModList.cs index 884652b..46c5d49 100644 --- a/src/SpaceWarp.UI/API/UI/ModList.cs +++ b/src/SpaceWarp.UI/API/UI/ModList.cs @@ -1,6 +1,4 @@ -using System; -using JetBrains.Annotations; -using SpaceWarp.UI.ModList; +using JetBrains.Annotations; using UnityEngine.UIElements; namespace SpaceWarp.API.UI; diff --git a/src/SpaceWarp.UI/API/UI/Settings/ModsPropertyDrawers.cs b/src/SpaceWarp.UI/API/UI/Settings/ModsPropertyDrawers.cs index e78c279..b1058ff 100644 --- a/src/SpaceWarp.UI/API/UI/Settings/ModsPropertyDrawers.cs +++ b/src/SpaceWarp.UI/API/UI/Settings/ModsPropertyDrawers.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; +using System.ComponentModel; using System.Reflection; using BepInEx.Configuration; using I2.Loc; diff --git a/src/SpaceWarp.UI/API/UI/Skins.cs b/src/SpaceWarp.UI/API/UI/Skins.cs index b281628..f8b35bb 100644 --- a/src/SpaceWarp.UI/API/UI/Skins.cs +++ b/src/SpaceWarp.UI/API/UI/Skins.cs @@ -1,5 +1,4 @@ -using System; -using JetBrains.Annotations; +using JetBrains.Annotations; using SpaceWarp.API.Assets; using UnityEngine; diff --git a/src/SpaceWarp.UI/Backend/UI/Appbar/AppbarBackend.cs b/src/SpaceWarp.UI/Backend/UI/Appbar/AppbarBackend.cs index abdd99c..495f1fd 100644 --- a/src/SpaceWarp.UI/Backend/UI/Appbar/AppbarBackend.cs +++ b/src/SpaceWarp.UI/Backend/UI/Appbar/AppbarBackend.cs @@ -1,7 +1,6 @@ // Attribution Notice To Lawrence/HatBat of https://github.com/Halbann/LazyOrbit // This file is licensed under https://creativecommons.org/licenses/by-sa/4.0/ -using System; using System.Collections; using System.Reflection; using BepInEx.Logging; diff --git a/src/SpaceWarp.UI/Backend/UI/Loading/LoadingScreenManager.cs b/src/SpaceWarp.UI/Backend/UI/Loading/LoadingScreenManager.cs index f317850..22c0118 100644 --- a/src/SpaceWarp.UI/Backend/UI/Loading/LoadingScreenManager.cs +++ b/src/SpaceWarp.UI/Backend/UI/Loading/LoadingScreenManager.cs @@ -1,7 +1,4 @@ -using System.Collections.Generic; -using System.IO; -using KSP.Game; -using SpaceWarp.API.Mods; +using SpaceWarp.API.Mods; using UnityEngine; using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets.ResourceLocators; diff --git a/src/SpaceWarp.UI/Backend/UI/Settings/CustomSettingsElementDescriptionController.cs b/src/SpaceWarp.UI/Backend/UI/Settings/CustomSettingsElementDescriptionController.cs index 347f74f..709f0bd 100644 --- a/src/SpaceWarp.UI/Backend/UI/Settings/CustomSettingsElementDescriptionController.cs +++ b/src/SpaceWarp.UI/Backend/UI/Settings/CustomSettingsElementDescriptionController.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using KSP.Game; +using KSP.Game; using UnityEngine.EventSystems; using DG.Tweening; diff --git a/src/SpaceWarp.UI/Modules/UI.cs b/src/SpaceWarp.UI/Modules/UI.cs index 9ec81c5..b2f2e71 100644 --- a/src/SpaceWarp.UI/Modules/UI.cs +++ b/src/SpaceWarp.UI/Modules/UI.cs @@ -1,17 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using BepInEx.Bootstrap; +using BepInEx.Bootstrap; using JetBrains.Annotations; -using KSP.Assets; -using KSP.Game; -using KSP.Game.Flow; using SpaceWarp.API.Assets; using SpaceWarp.API.Configuration; -using SpaceWarp.API.Loading; using SpaceWarp.API.UI.Appbar; using SpaceWarp.Backend.UI.Appbar; -using SpaceWarp.Backend.UI.Loading; using SpaceWarp.InternalUtilities; using SpaceWarp.UI.AvcDialog; using SpaceWarp.UI.Console; diff --git a/src/SpaceWarp.UI/Patching/CurtainPatch.cs b/src/SpaceWarp.UI/Patching/CurtainPatch.cs index 853abef..eb1f8ff 100644 --- a/src/SpaceWarp.UI/Patching/CurtainPatch.cs +++ b/src/SpaceWarp.UI/Patching/CurtainPatch.cs @@ -1,8 +1,5 @@ -using System; -using HarmonyLib; -using KSP.Networking.MP.Utils; +using HarmonyLib; using SpaceWarp.Backend.UI.Loading; -using UnityEngine; namespace SpaceWarp.Patching; diff --git a/src/SpaceWarp.UI/Patching/LoadingFlowPatch.cs b/src/SpaceWarp.UI/Patching/LoadingFlowPatch.cs index 15cbe4f..9549fdf 100644 --- a/src/SpaceWarp.UI/Patching/LoadingFlowPatch.cs +++ b/src/SpaceWarp.UI/Patching/LoadingFlowPatch.cs @@ -1,9 +1,7 @@ -using System; -using HarmonyLib; +using HarmonyLib; using KSP.Game; using KSP.Game.Flow; using KSP.Startup; -using UnityEngine; namespace SpaceWarp.Patching; diff --git a/src/SpaceWarp.UI/Patching/LoadingScreenDeserializationPatch.cs b/src/SpaceWarp.UI/Patching/LoadingScreenDeserializationPatch.cs index 5a75d46..9adf711 100644 --- a/src/SpaceWarp.UI/Patching/LoadingScreenDeserializationPatch.cs +++ b/src/SpaceWarp.UI/Patching/LoadingScreenDeserializationPatch.cs @@ -1,5 +1,4 @@ -using System.Linq; -using HarmonyLib; +using HarmonyLib; using KSP.Game; using KSP.Game.StartupFlow; diff --git a/src/SpaceWarp.UI/Patching/MainMenuPatcher.cs b/src/SpaceWarp.UI/Patching/MainMenuPatcher.cs index 5826158..7a17a52 100644 --- a/src/SpaceWarp.UI/Patching/MainMenuPatcher.cs +++ b/src/SpaceWarp.UI/Patching/MainMenuPatcher.cs @@ -1,5 +1,4 @@ -using System; -using HarmonyLib; +using HarmonyLib; using I2.Loc; using KSP.Api.CoreTypes; using KSP.Game.StartupFlow; diff --git a/src/SpaceWarp.UI/UI/Console/LogEntry.cs b/src/SpaceWarp.UI/UI/Console/LogEntry.cs index 5239a4d..64a18bd 100644 --- a/src/SpaceWarp.UI/UI/Console/LogEntry.cs +++ b/src/SpaceWarp.UI/UI/Console/LogEntry.cs @@ -1,5 +1,4 @@ -using System; -using BepInEx.Logging; +using BepInEx.Logging; using UnityEngine; using UnityEngine.UIElements; using static SpaceWarp.UI.Console.SpaceWarpConsoleLogListener; diff --git a/src/SpaceWarp.UI/UI/Console/SpaceWarpConsoleLogListener.cs b/src/SpaceWarp.UI/UI/Console/SpaceWarpConsoleLogListener.cs index 4fc09ca..eaaab50 100644 --- a/src/SpaceWarp.UI/UI/Console/SpaceWarpConsoleLogListener.cs +++ b/src/SpaceWarp.UI/UI/Console/SpaceWarpConsoleLogListener.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using BepInEx.Logging; +using BepInEx.Logging; namespace SpaceWarp.UI.Console; diff --git a/src/SpaceWarp.UI/UI/ModList/ModListController.cs b/src/SpaceWarp.UI/UI/ModList/ModListController.cs index c57f5a7..6dd2c85 100644 --- a/src/SpaceWarp.UI/UI/ModList/ModListController.cs +++ b/src/SpaceWarp.UI/UI/ModList/ModListController.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; +using System.Diagnostics; using BepInEx; using I2.Loc; using SpaceWarp.API.Assets; diff --git a/src/SpaceWarp.UI/UI/ModList/ModListItemController.cs b/src/SpaceWarp.UI/UI/ModList/ModListItemController.cs index d3703d6..baa19fc 100644 --- a/src/SpaceWarp.UI/UI/ModList/ModListItemController.cs +++ b/src/SpaceWarp.UI/UI/ModList/ModListItemController.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using SpaceWarp.API.Mods; +using SpaceWarp.API.Mods; using UnityEngine.UIElements; namespace SpaceWarp.UI.ModList; diff --git a/src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs b/src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs index 392fcac..c9d2cbb 100644 --- a/src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs +++ b/src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using BepInEx; -using BepInEx.Configuration; +using BepInEx.Configuration; using KSP.UI; using SpaceWarp.API.Configuration; using SpaceWarp.API.Mods; diff --git a/src/SpaceWarpPatcher/AssemblyCSharpPatcher.cs b/src/SpaceWarpPatcher/AssemblyCSharpPatcher.cs index 91318da..40a9b14 100644 --- a/src/SpaceWarpPatcher/AssemblyCSharpPatcher.cs +++ b/src/SpaceWarpPatcher/AssemblyCSharpPatcher.cs @@ -1,6 +1,4 @@ -using BepInEx; -using BepInEx.Logging; -using JetBrains.Annotations; +using JetBrains.Annotations; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; diff --git a/src/SpaceWarpPatcher/Patcher.cs b/src/SpaceWarpPatcher/Patcher.cs index 5579713..7685ae5 100644 --- a/src/SpaceWarpPatcher/Patcher.cs +++ b/src/SpaceWarpPatcher/Patcher.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using BepInEx; @@ -15,7 +11,6 @@ using Mono.Cecil; using Mono.Cecil.Cil; using MonoMod.Cil; -using Newtonsoft.Json.Linq; [assembly: InternalsVisibleTo("SpaceWarp.Core")] diff --git a/src/SpaceWarpPatcher/PathsGenerator.cs b/src/SpaceWarpPatcher/PathsGenerator.cs index 465b232..b248c27 100644 --- a/src/SpaceWarpPatcher/PathsGenerator.cs +++ b/src/SpaceWarpPatcher/PathsGenerator.cs @@ -1,7 +1,4 @@ -using System; -using System.IO; -using System.Linq; -using System.Reflection; +using System.Reflection; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Logging; diff --git a/src/SpaceWarpPatcher/SwinfoTransformer.cs b/src/SpaceWarpPatcher/SwinfoTransformer.cs index 2df4b07..f765bf7 100644 --- a/src/SpaceWarpPatcher/SwinfoTransformer.cs +++ b/src/SpaceWarpPatcher/SwinfoTransformer.cs @@ -1,6 +1,4 @@ -using System.IO; -using System.Linq; -using System.Security.Cryptography; +using System.Security.Cryptography; using System.Text; using BepInEx; using Newtonsoft.Json.Linq; From 7a1d323e0c2a8d0e38f3817adb7e81e5a70cd41a Mon Sep 17 00:00:00 2001 From: Lexi Date: Thu, 28 Dec 2023 09:12:07 -0500 Subject: [PATCH 07/82] Possible fix for both callbacks and the threading issue --- .../API/UI/Settings/SettingsMenu.cs | 23 ++++ .../UI/Console/SpaceWarpConsole.cs | 22 +++- src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs | 105 ++++++++++++------ 3 files changed, 112 insertions(+), 38 deletions(-) create mode 100644 src/SpaceWarp.UI/API/UI/Settings/SettingsMenu.cs diff --git a/src/SpaceWarp.UI/API/UI/Settings/SettingsMenu.cs b/src/SpaceWarp.UI/API/UI/Settings/SettingsMenu.cs new file mode 100644 index 0000000..49f59a8 --- /dev/null +++ b/src/SpaceWarp.UI/API/UI/Settings/SettingsMenu.cs @@ -0,0 +1,23 @@ +using JetBrains.Annotations; +using SpaceWarp.API.Configuration; + +namespace SpaceWarp.UI.API.UI.Settings; + +[PublicAPI] +public static class SettingsMenu +{ + /// + /// Contains a list of all the registered config files + /// + public static Dictionary RegisteredConfigFiles = new(); + + /// + /// Register a manually created config file for the settings menu + /// + /// The section name for the config file + /// The file itself + public static void RegisterConfigFile(string section, IConfigFile file) + { + RegisteredConfigFiles[section] = file; + } +} \ No newline at end of file diff --git a/src/SpaceWarp.UI/UI/Console/SpaceWarpConsole.cs b/src/SpaceWarp.UI/UI/Console/SpaceWarpConsole.cs index a78dd6b..f98fd0b 100644 --- a/src/SpaceWarp.UI/UI/Console/SpaceWarpConsole.cs +++ b/src/SpaceWarp.UI/UI/Console/SpaceWarpConsole.cs @@ -1,4 +1,5 @@ using System.Collections; +using System.Collections.Concurrent; using BepInEx.Logging; using KSP.Game; using UitkForKsp2.API; @@ -39,7 +40,7 @@ private void Start() CreateNewLogEntry(logMessage); } // Binds the OnNewMessageReceived function to the OnNewMessage event - OnNewLog += CreateNewLogEntry; + OnNewLog += AddToQueue; } @@ -98,6 +99,13 @@ private void Update() { HideWindow(); } + + if (!_isWindowVisible) return; + + while (Queue.TryDequeue(out var info)) + { + CreateNewLogEntry(info); + } } private void SetupDocument() @@ -298,4 +306,16 @@ private void HideWindow() UnbindFunctions(); } + private ConcurrentQueue Queue = new(); + + + private void AddToQueue(LogInfo info) + { + Queue.Enqueue(info); + while (Queue.Count > + Modules.UI.Instance.ConfigDebugMessageLimit.Value && Queue.TryDequeue(out _)) + { + // Do nothing + } + } } \ No newline at end of file diff --git a/src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs b/src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs index c9d2cbb..18e60b9 100644 --- a/src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs +++ b/src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs @@ -4,7 +4,9 @@ using SpaceWarp.API.Mods; using SpaceWarp.API.UI.Settings; using SpaceWarp.Backend.Modding; +using SpaceWarp.Backend.UI.Settings; using SpaceWarp.Modules; +using SpaceWarp.UI.API.UI.Settings; using UnityEngine; namespace SpaceWarp.UI.Settings; @@ -32,46 +34,12 @@ public void Start() } // Now here is where we go through every single mod -#pragma warning disable CS0618 - foreach (var mod in BepInEx.Bootstrap.Chainloader.Plugins.Where(mod => - mod.Config.Count > 0 && mod is not ConfigurationManager.ConfigurationManager)) - { - // This is where do a "Add Name" function - GenerateTitle(mod.Info.Metadata.Name).transform.SetParent(transform); - GenerateDivider().transform.SetParent(transform); - Dictionary> modConfigCategories = new(); - foreach (var config in mod.Config) - { - var section = config.Key.Section; - var conf = config.Value; - if (modConfigCategories.TryGetValue(section, out var list)) - { - list.Add(conf); - } - else - { - modConfigCategories[section] = new List { conf }; - } - } - foreach (var config in modConfigCategories) - { - var header = GenerateSectionHeader(config.Key); - header.transform.SetParent(transform); - foreach (var drawer in config.Value.Select(ModsPropertyDrawers.Drawer).Where(drawer => drawer != null)) - { - drawer.transform.SetParent(header.transform); - } - - GenerateDivider().transform.SetParent(transform); - } - } foreach (var mod in PluginList.AllEnabledAndActivePlugins.Where(mod => mod.ConfigFile != null && mod.ConfigFile.Sections.Count > 0 && mod.ConfigFile.Sections.Any(x => - mod.ConfigFile[x].Count > 0) && mod.Plugin is not BepInExModAdapter && - mod.Plugin is not BaseSpaceWarpPlugin && mod.Plugin != null)) + mod.ConfigFile[x].Count > 0) && mod.Plugin != null)) { GenerateTitle(mod.Name).transform.SetParent(transform); GenerateDivider().transform.SetParent(transform); @@ -96,7 +64,7 @@ public void Start() GenerateDivider().transform.SetParent(transform); } } - + foreach (var module in ModuleManager.AllSpaceWarpModules.Where( mod => mod.ModuleConfiguration.Sections.Count > 0 )) @@ -126,7 +94,70 @@ public void Start() GenerateDivider().transform.SetParent(transform); } } - + + foreach (var (section, entries) in SettingsMenu.RegisteredConfigFiles) + { + GenerateTitle(section).transform.SetParent(transform); + GenerateDivider().transform.SetParent(transform); + Dictionary> modConfigCategories = new(); + foreach (var sect in entries.Sections) + { + if (entries[section].Count <= 0) continue; + var list = modConfigCategories[section] = new List<(string name, IConfigEntry entry)>(); + list.AddRange(entries[section].Select( + entry => (entry, entries[section, entry]) + )); + } + + foreach (var config in modConfigCategories) + { + var header = GenerateSectionHeader(config.Key); + header.transform.SetParent(transform); + foreach (var drawer in config.Value.Select(x => ModsPropertyDrawers.Drawer(x.name, x.entry)) + .Where(drawer => drawer != null)) + { + drawer.transform.SetParent(header.transform); + } + + GenerateDivider().transform.SetParent(transform); + } + } +#pragma warning disable CS0618 + foreach (var mod in BepInEx.Bootstrap.Chainloader.Plugins.Where(mod => + (mod is not BaseSpaceWarpPlugin || (mod is BaseSpaceWarpPlugin baseSpaceWarpPlugin && + baseSpaceWarpPlugin.SWConfiguration.Sections.Count == 0)) && + mod.Config.Count > 0 && mod is not ConfigurationManager.ConfigurationManager)) + { + // This is where do a "Add Name" function + GenerateTitle(mod.Info.Metadata.Name).transform.SetParent(transform); + GenerateDivider().transform.SetParent(transform); + Dictionary> modConfigCategories = new(); + foreach (var config in mod.Config) + { + var section = config.Key.Section; + var conf = config.Value; + if (modConfigCategories.TryGetValue(section, out var list)) + { + list.Add(conf); + } + else + { + modConfigCategories[section] = new List { conf }; + } + } + + foreach (var config in modConfigCategories) + { + var header = GenerateSectionHeader(config.Key); + header.transform.SetParent(transform); + foreach (var drawer in config.Value.Select(ModsPropertyDrawers.Drawer).Where(drawer => drawer != null)) + { + drawer.transform.SetParent(header.transform); + } + + GenerateDivider().transform.SetParent(transform); + } + } } public override void OnShow() From 9a7648217518b02123101b371a554fe854642441 Mon Sep 17 00:00:00 2001 From: Lexi Date: Thu, 28 Dec 2023 09:17:00 -0500 Subject: [PATCH 08/82] Make sure to remove the right delegate --- src/SpaceWarp.UI/UI/Console/SpaceWarpConsole.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/SpaceWarp.UI/UI/Console/SpaceWarpConsole.cs b/src/SpaceWarp.UI/UI/Console/SpaceWarpConsole.cs index f98fd0b..8e6743c 100644 --- a/src/SpaceWarp.UI/UI/Console/SpaceWarpConsole.cs +++ b/src/SpaceWarp.UI/UI/Console/SpaceWarpConsole.cs @@ -47,7 +47,7 @@ private void Start() private void OnDestroy() { // Unbinds the OnNewMessageReceived function to the OnNewMessage event when destroyed - OnNewLog -= CreateNewLogEntry; + OnNewLog -= AddToQueue; } From 62c3de42a176017d6f03b6202705203500143a1d Mon Sep 17 00:00:00 2001 From: Lexi Date: Thu, 28 Dec 2023 11:22:55 -0500 Subject: [PATCH 09/82] first bit of C# 12 code :3 --- src/SpaceWarp.Core/API/Configuration/BepInExConfigEntry.cs | 1 - src/SpaceWarp.Core/SpaceWarpPlugin.cs | 3 +++ src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/SpaceWarp.Core/API/Configuration/BepInExConfigEntry.cs b/src/SpaceWarp.Core/API/Configuration/BepInExConfigEntry.cs index 2375c9d..d49ab90 100644 --- a/src/SpaceWarp.Core/API/Configuration/BepInExConfigEntry.cs +++ b/src/SpaceWarp.Core/API/Configuration/BepInExConfigEntry.cs @@ -69,7 +69,6 @@ public void Set(T value) { if (!Constraint.IsConstrained(value)) return; } - Callbacks?.Invoke(EntryBase.BoxedValue, value); EntryBase.BoxedValue = Convert.ChangeType(value, ValueType); } diff --git a/src/SpaceWarp.Core/SpaceWarpPlugin.cs b/src/SpaceWarp.Core/SpaceWarpPlugin.cs index 8fd340d..222b6f3 100644 --- a/src/SpaceWarp.Core/SpaceWarpPlugin.cs +++ b/src/SpaceWarp.Core/SpaceWarpPlugin.cs @@ -9,6 +9,7 @@ using KSP.ScriptInterop.impl.moonsharp; using MoonSharp.Interpreter; using MoonSharp.Interpreter.Interop; +using SpaceWarp.API.Configuration; using SpaceWarp.API.Loading; using SpaceWarp.API.Lua; using SpaceWarp.API.Mods; @@ -37,6 +38,8 @@ public sealed class SpaceWarpPlugin : BaseSpaceWarpPlugin public SpaceWarpPlugin() { + + // Load the type forwarders Assembly.LoadFile( $"{new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName}\\SpaceWarp.dll"); diff --git a/src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs b/src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs index 18e60b9..a2078c9 100644 --- a/src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs +++ b/src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs @@ -142,7 +142,7 @@ public void Start() } else { - modConfigCategories[section] = new List { conf }; + modConfigCategories[section] = [conf]; } } From f7218f8a6f0c2c75ea02c14b0b8fc0e91d8070bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Sat, 30 Dec 2023 01:08:03 +0100 Subject: [PATCH 10/82] Search for localizations in subfolders --- src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs b/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs index 5d36524..38309dc 100644 --- a/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs +++ b/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs @@ -36,14 +36,14 @@ internal static void LoadLocalizationFromFolder(string folder) } var info = new DirectoryInfo(folder); - foreach (var csvFile in info.GetFiles("*.csv")) + foreach (var csvFile in info.GetFiles("*.csv", SearchOption.AllDirectories)) { languageSourceData ??= new LanguageSourceData(); var csvData = File.ReadAllText(csvFile.FullName).Replace("\r\n", "\n"); languageSourceData.Import_CSV("", csvData, eSpreadsheetUpdateMode.AddNewTerms); } - foreach (var i2CsvFile in info.GetFiles("*.i2csv")) + foreach (var i2CsvFile in info.GetFiles("*.i2csv", SearchOption.AllDirectories)) { languageSourceData ??= new LanguageSourceData(); var i2CsvData = File.ReadAllText(i2CsvFile.FullName).Replace("\r\n", "\n"); From 8cea3a6956b3218769cb2c0c14c5b52e926ece10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Sat, 30 Dec 2023 01:08:29 +0100 Subject: [PATCH 11/82] Reload the language dropdown in Settings in OnInitialized --- src/SpaceWarp.Core/SpaceWarpPlugin.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/SpaceWarp.Core/SpaceWarpPlugin.cs b/src/SpaceWarp.Core/SpaceWarpPlugin.cs index 8fd340d..aa50e7b 100644 --- a/src/SpaceWarp.Core/SpaceWarpPlugin.cs +++ b/src/SpaceWarp.Core/SpaceWarpPlugin.cs @@ -93,6 +93,11 @@ private void SetupLuaState() } } + private void UpdateLanguagesDropdown() + { + Game.SettingsMenuManager._generalSettings.InitializeLanguageDropdown(); + } + public override void OnPreInitialized() { // Persist all game objects so I don't need to stomp on config @@ -103,6 +108,7 @@ public override void OnInitialized() { ModuleManager.InitializeAllModules(); SetupLuaState(); + UpdateLanguagesDropdown(); } public override void OnPostInitialized() From 9349cabf70449a730b8cb84c4d25314ee48e09b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Sat, 30 Dec 2023 16:41:44 +0100 Subject: [PATCH 12/82] Allow mods to override existing localizations --- .../InternalUtilities/AssetHelpers.cs | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs b/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs index 38309dc..b339aed 100644 --- a/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs +++ b/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs @@ -54,11 +54,33 @@ internal static void LoadLocalizationFromFolder(string folder) { languageSourceData.OnMissingTranslation = LanguageSourceData.MissingTranslationAction.Fallback; SpaceWarpPlugin.Instance.SWLogger.LogInfo($"Loaded localizations from {folder}"); - LocalizationManager.AddSource(languageSourceData); + + AddSource(languageSourceData); } else { SpaceWarpPlugin.Instance.SWLogger.LogInfo($"No localizations found in {folder}"); } } + + private static void AddSource(LanguageSourceData source) + { + if (LocalizationManager.Sources.Contains(source)) + { + return; + } + + LocalizationManager.Sources.Insert(0, source); + foreach (var language in source.mLanguages) + { + language.SetLoaded(true); + } + + if (source.mDictionary.Count != 0) + { + return; + } + + source.UpdateDictionary(true); + } } \ No newline at end of file From 44fdffd06fa5b2503e2a159c4a5c76efaf584384 Mon Sep 17 00:00:00 2001 From: Lexi Date: Sat, 30 Dec 2023 13:26:02 -0500 Subject: [PATCH 13/82] Constrain the mod saving API to only allow reference types (as non reference types will cause an error) --- src/SpaceWarp.Core/API/SaveGameManager/ModSaves.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/SpaceWarp.Core/API/SaveGameManager/ModSaves.cs b/src/SpaceWarp.Core/API/SaveGameManager/ModSaves.cs index 432a134..d1204c2 100644 --- a/src/SpaceWarp.Core/API/SaveGameManager/ModSaves.cs +++ b/src/SpaceWarp.Core/API/SaveGameManager/ModSaves.cs @@ -20,7 +20,7 @@ public static class ModSaves /// Function that will execute when a LOAD event is triggered. Defaults to null or no callback. /// Your object that will be saved to a save file during a save event and that will be updated when a load event pulls new data. Ensure that a new instance of this object is NOT created after registration. /// T saveData object you passed as a parameter, or a default instance of object T if you didn't pass anything - public static T RegisterSaveLoadGameData(string modGuid, Action onSave = null, Action onLoad = null, T saveData = default) + public static T RegisterSaveLoadGameData(string modGuid, Action onSave = null, Action onLoad = null, T saveData = default) where T : class { // Check if this GUID is already registered if (InternalPluginSaveData.Find(p => p.ModGuid == modGuid) != null) @@ -73,7 +73,7 @@ public static void UnRegisterSaveLoadGameData(string modGuid) /// Function that will execute when a LOAD event is triggered. Defaults to null or no callback. /// Your object that will be saved to a save file during a save event and that will be updated when a load event pulls new data. Ensure that a new instance of this object is NOT created after registration. /// T saveData object you passed as a parameter, or a default instance of object T if you didn't pass anything - public static T ReregisterSaveLoadGameData(string modGuid, Action onSave = null, Action onLoad = null, T saveData = default(T)) + public static T ReregisterSaveLoadGameData(string modGuid, Action onSave = null, Action onLoad = null, T saveData = default(T)) where T : class { UnRegisterSaveLoadGameData(modGuid); return RegisterSaveLoadGameData(modGuid, onSave, onLoad, saveData); From f759c5be2b0c2292e2b4b4ebcc0e6b060c715018 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Sat, 30 Dec 2023 20:17:29 +0100 Subject: [PATCH 14/82] Removed unneeded imports --- src/SpaceWarp.Core/Patching/ColorsPatch.cs | 3 +-- src/SpaceWarp.Core/SpaceWarpPlugin.cs | 3 --- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/SpaceWarp.Core/Patching/ColorsPatch.cs b/src/SpaceWarp.Core/Patching/ColorsPatch.cs index 1c7bb4a..b65991f 100644 --- a/src/SpaceWarp.Core/Patching/ColorsPatch.cs +++ b/src/SpaceWarp.Core/Patching/ColorsPatch.cs @@ -1,6 +1,5 @@ using System.Reflection; using BepInEx.Logging; -using Castle.Core.Internal; using HarmonyLib; using KSP.Game; using KSP.Modules; @@ -321,7 +320,7 @@ internal static void Prefix() internal static void Postfix(Module_Color __instance) { var partName = __instance.OABPart is not null ? __instance.OABPart.PartName : __instance.part.Name; - if (partName.IsNullOrEmpty()) return; + if (string.IsNullOrEmpty(partName)) return; var trimmedPartName = TrimPartName(partName); if (DeclaredParts.Count <= 0 || !_allParts.Contains(trimmedPartName)) return; diff --git a/src/SpaceWarp.Core/SpaceWarpPlugin.cs b/src/SpaceWarp.Core/SpaceWarpPlugin.cs index 51d0266..aa50e7b 100644 --- a/src/SpaceWarp.Core/SpaceWarpPlugin.cs +++ b/src/SpaceWarp.Core/SpaceWarpPlugin.cs @@ -9,7 +9,6 @@ using KSP.ScriptInterop.impl.moonsharp; using MoonSharp.Interpreter; using MoonSharp.Interpreter.Interop; -using SpaceWarp.API.Configuration; using SpaceWarp.API.Loading; using SpaceWarp.API.Lua; using SpaceWarp.API.Mods; @@ -38,8 +37,6 @@ public sealed class SpaceWarpPlugin : BaseSpaceWarpPlugin public SpaceWarpPlugin() { - - // Load the type forwarders Assembly.LoadFile( $"{new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName}\\SpaceWarp.dll"); From 77f305e87554a87edcd568ebea508ac9228c3cd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Sat, 30 Dec 2023 20:19:06 +0100 Subject: [PATCH 15/82] Patch for localization fallbacks --- .../Patching/LocalizationPatch.cs | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/SpaceWarp.Core/Patching/LocalizationPatch.cs diff --git a/src/SpaceWarp.Core/Patching/LocalizationPatch.cs b/src/SpaceWarp.Core/Patching/LocalizationPatch.cs new file mode 100644 index 0000000..113fad5 --- /dev/null +++ b/src/SpaceWarp.Core/Patching/LocalizationPatch.cs @@ -0,0 +1,49 @@ +using HarmonyLib; +using I2.Loc; + +namespace SpaceWarp.Patching; + +/// +/// Patches the localization system so that localization sources that don't contain the current language +/// are not skipped when looking for a fallback translation. +/// +[HarmonyPatch] +public class LocalizationPatch +{ + [HarmonyPatch(typeof(LanguageSourceData), nameof(LanguageSourceData.TryGetTranslation))] + [HarmonyPostfix] + private static void TryGetTranslationPatch( + // ReSharper disable once InconsistentNaming + LanguageSourceData __instance, + // ReSharper disable once InconsistentNaming + ref bool __result, + string term, + // ReSharper disable once InconsistentNaming + ref string Translation, + string overrideLanguage = null, + string overrideSpecialization = null, + bool skipDisabled = false, + bool allowCategoryMistmatch = false) + { + if (__result && !string.IsNullOrEmpty(Translation) && !Translation.Equals(term)) + { + return; + } + + var termData = __instance.GetTermData(term, allowCategoryMistmatch); + if (__instance.OnMissingTranslation != LanguageSourceData.MissingTranslationAction.Fallback || + termData == null) + { + return; + } + + if (!__instance.TryGetFallbackTranslation(termData, out var translation, -1, + overrideSpecialization, skipDisabled)) + { + return; + } + + Translation = translation; + __result = true; + } +} \ No newline at end of file From 6ee244309076421408673a1cae1cc56ad1d7c24b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Sun, 31 Dec 2023 22:59:49 +0100 Subject: [PATCH 16/82] https://youtu.be/0xyxtzD54rM --- .../Patching/LocalizationPatch.cs | 79 ++++++++++++++++++- 1 file changed, 76 insertions(+), 3 deletions(-) diff --git a/src/SpaceWarp.Core/Patching/LocalizationPatch.cs b/src/SpaceWarp.Core/Patching/LocalizationPatch.cs index 113fad5..be30406 100644 --- a/src/SpaceWarp.Core/Patching/LocalizationPatch.cs +++ b/src/SpaceWarp.Core/Patching/LocalizationPatch.cs @@ -8,7 +8,7 @@ namespace SpaceWarp.Patching; /// are not skipped when looking for a fallback translation. /// [HarmonyPatch] -public class LocalizationPatch +public static class LocalizationPatch { [HarmonyPatch(typeof(LanguageSourceData), nameof(LanguageSourceData.TryGetTranslation))] [HarmonyPostfix] @@ -37,8 +37,13 @@ private static void TryGetTranslationPatch( return; } - if (!__instance.TryGetFallbackTranslation(termData, out var translation, -1, - overrideSpecialization, skipDisabled)) + if (!__instance.TryGetFallbackTranslation( + termData, + out var translation, + -1, + overrideSpecialization, + skipDisabled) + ) { return; } @@ -46,4 +51,72 @@ private static void TryGetTranslationPatch( Translation = translation; __result = true; } + + [HarmonyPatch(typeof(LanguageSourceData), nameof(LanguageSourceData.TryGetFallbackTranslation))] + [HarmonyPrefix] + private static bool TryGetFallbackTranslation( + // ReSharper disable once InconsistentNaming + LanguageSourceData __instance, + // ReSharper disable once InconsistentNaming + ref bool __result, + TermData termData, + // ReSharper disable once InconsistentNaming + out string Translation, + int langIndex, + string overrideSpecialization = null, + bool skipDisabled = false) + { + var str = langIndex != -1 && __instance.mLanguages.Count > langIndex + ? __instance.mLanguages[langIndex].Code + : null; + if (!string.IsNullOrEmpty(str)) + { + if (str.Contains('-')) + { + str = str[..str.IndexOf('-')]; + } + + for (var index = 0; index < __instance.mLanguages.Count; ++index) + { + if (index == langIndex || + !__instance.mLanguages[index].Code.StartsWith(str, StringComparison.Ordinal) || + (skipDisabled && !__instance.mLanguages[index].IsEnabled())) + { + continue; + } + + Translation = termData.GetTranslation(index, overrideSpecialization, true); + if (string.IsNullOrEmpty(Translation)) + { + continue; + } + + __result = true; + return false; + } + } + + for (var index = 0; index < __instance.mLanguages.Count; ++index) + { + if (index == langIndex || + (skipDisabled && !__instance.mLanguages[index].IsEnabled()) || + (str != null && __instance.mLanguages[index].Code.StartsWith(str, StringComparison.Ordinal))) + { + continue; + } + + Translation = termData.GetTranslation(index, overrideSpecialization, true); + if (string.IsNullOrEmpty(Translation)) + { + continue; + } + + __result = true; + return false; + } + + Translation = null; + __result = false; + return false; + } } \ No newline at end of file From c08c5d53c104177a689ece0b5fb138f05304aaee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 14:22:55 +0100 Subject: [PATCH 17/82] Fixed localization patch --- .../Patching/LocalizationPatch.cs | 274 +++++++++++++----- 1 file changed, 201 insertions(+), 73 deletions(-) diff --git a/src/SpaceWarp.Core/Patching/LocalizationPatch.cs b/src/SpaceWarp.Core/Patching/LocalizationPatch.cs index be30406..581ab9f 100644 --- a/src/SpaceWarp.Core/Patching/LocalizationPatch.cs +++ b/src/SpaceWarp.Core/Patching/LocalizationPatch.cs @@ -1,122 +1,250 @@ using HarmonyLib; using I2.Loc; +using UnityEngine; namespace SpaceWarp.Patching; /// -/// Patches the localization system so that localization sources that don't contain the current language -/// are not skipped when looking for a fallback translation. +/// Patches the localization system to properly find fallback translations. /// [HarmonyPatch] -public static class LocalizationPatch +internal static class LocalizationPatch { - [HarmonyPatch(typeof(LanguageSourceData), nameof(LanguageSourceData.TryGetTranslation))] - [HarmonyPostfix] - private static void TryGetTranslationPatch( - // ReSharper disable once InconsistentNaming - LanguageSourceData __instance, - // ReSharper disable once InconsistentNaming + [HarmonyPatch( + typeof(LocalizationManager), + nameof(LocalizationManager.TryGetTranslation), + [ + typeof(string), typeof(string), typeof(bool), typeof(int), typeof(bool), typeof(bool), + typeof(GameObject), typeof(string), typeof(bool), typeof(string) + ], + [ + ArgumentType.Normal, ArgumentType.Out, ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Normal, + ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Normal + ] + )] + [HarmonyPrefix] + // ReSharper disable InconsistentNaming + private static bool LocalizationManagerTryGetTranslationPrefix( ref bool __result, - string term, - // ReSharper disable once InconsistentNaming - ref string Translation, + string Term, + out string Translation, + bool FixForRTL = true, + int maxLineLengthForRTL = 0, + bool ignoreRTLnumbers = true, + bool applyParameters = false, + GameObject localParametersRoot = null, string overrideLanguage = null, - string overrideSpecialization = null, - bool skipDisabled = false, - bool allowCategoryMistmatch = false) + bool allowLocalizedParameters = true, + string overrideSpecialization = null + ) + { + // ReSharper restore InconsistentNaming + __result = TryGetTranslation( + Term, + out Translation, + FixForRTL, + maxLineLengthForRTL, + ignoreRTLnumbers, + applyParameters, + localParametersRoot, + overrideLanguage, + allowLocalizedParameters, + overrideSpecialization + ); + + return false; + } + + private static bool TryGetTranslation( + string term, + out string translation, + bool fixForRtl, + int maxLineLengthForRtl, + bool ignoreRtlNumbers, + bool applyParameters, + GameObject localParametersRoot, + string overrideLanguage, + bool allowLocalizedParameters, + string overrideSpecialization + ) { - if (__result && !string.IsNullOrEmpty(Translation) && !Translation.Equals(term)) + translation = null; + if (string.IsNullOrEmpty(term)) { - return; + return false; } - var termData = __instance.GetTermData(term, allowCategoryMistmatch); - if (__instance.OnMissingTranslation != LanguageSourceData.MissingTranslationAction.Fallback || - termData == null) + if (LocalizationManager.DebugLocalizationIsOn) { - return; + translation = term; + return true; } - if (!__instance.TryGetFallbackTranslation( - termData, - out var translation, - -1, - overrideSpecialization, - skipDisabled) - ) + LocalizationManager.InitializeIfNeeded(); + + foreach (var source in LocalizationManager.Sources) { - return; + if (!TryGetTranslationFromSource( + source, + term, + out translation, + overrideLanguage, + overrideSpecialization + )) + { + continue; + } + + if (applyParameters) + { + LocalizationManager.ApplyLocalizationParams( + ref translation, + localParametersRoot, + allowLocalizedParameters + ); + } + + if (LocalizationManager.IsRight2Left & fixForRtl) + { + translation = LocalizationManager.ApplyRTLfix(translation, maxLineLengthForRtl, ignoreRtlNumbers); + } + + return true; } - Translation = translation; - __result = true; + return TryGetFallback( + term, + ref translation, + fixForRtl, + maxLineLengthForRtl, + ignoreRtlNumbers, + applyParameters, + localParametersRoot, + allowLocalizedParameters, + overrideSpecialization + ); } - [HarmonyPatch(typeof(LanguageSourceData), nameof(LanguageSourceData.TryGetFallbackTranslation))] - [HarmonyPrefix] - private static bool TryGetFallbackTranslation( - // ReSharper disable once InconsistentNaming - LanguageSourceData __instance, - // ReSharper disable once InconsistentNaming - ref bool __result, - TermData termData, - // ReSharper disable once InconsistentNaming - out string Translation, - int langIndex, + private static bool TryGetTranslationFromSource( + LanguageSourceData source, + string term, + out string translation, + string overrideLanguage = null, string overrideSpecialization = null, - bool skipDisabled = false) + bool skipDisabled = false, + bool allowCategoryMistmatch = false + ) { - var str = langIndex != -1 && __instance.mLanguages.Count > langIndex - ? __instance.mLanguages[langIndex].Code - : null; - if (!string.IsNullOrEmpty(str)) - { - if (str.Contains('-')) - { - str = str[..str.IndexOf('-')]; - } + var languageIndex = source.GetLanguageIndex( + overrideLanguage ?? LocalizationManager.CurrentLanguage, + SkipDisabled: false + ); - for (var index = 0; index < __instance.mLanguages.Count; ++index) + if (languageIndex >= 0 && (!skipDisabled || source.mLanguages[languageIndex].IsEnabled())) + { + var termData = source.GetTermData(term, allowCategoryMistmatch); + if (termData != null) { - if (index == langIndex || - !__instance.mLanguages[index].Code.StartsWith(str, StringComparison.Ordinal) || - (skipDisabled && !__instance.mLanguages[index].IsEnabled())) + translation = termData.GetTranslation(languageIndex, overrideSpecialization, true); + if (translation == "---") { - continue; + translation = string.Empty; + return true; } - Translation = termData.GetTranslation(index, overrideSpecialization, true); - if (string.IsNullOrEmpty(Translation)) + if (!string.IsNullOrEmpty(translation)) { - continue; + return true; } - - __result = true; - return false; } } - for (var index = 0; index < __instance.mLanguages.Count; ++index) + translation = null; + return false; + } + + private static bool TryGetFallback( + string term, + ref string translation, + bool fixForRtl, + int maxLineLengthForRtl, + bool ignoreRtlNumbers, + bool applyParameters, + GameObject localParametersRoot, + bool allowLocalizedParameters, + string overrideSpecialization + ) + { + if (!string.IsNullOrEmpty(translation) && !translation.Equals(term)) + { + return true; + } + + foreach (var source in LocalizationManager.Sources) { - if (index == langIndex || - (skipDisabled && !__instance.mLanguages[index].IsEnabled()) || - (str != null && __instance.mLanguages[index].Code.StartsWith(str, StringComparison.Ordinal))) + switch (source.OnMissingTranslation) + { + case LanguageSourceData.MissingTranslationAction.ShowWarning: + translation = ""; + return true; + case LanguageSourceData.MissingTranslationAction.Empty: + translation = string.Empty; + return true; + case LanguageSourceData.MissingTranslationAction.ShowTerm: + translation = term; + return true; + } + + if (!TryGetFallbackFromSource(source, term, out var fallback, overrideSpecialization)) { continue; } - Translation = termData.GetTranslation(index, overrideSpecialization, true); - if (string.IsNullOrEmpty(Translation)) + if (applyParameters) + { + LocalizationManager.ApplyLocalizationParams( + ref fallback, + localParametersRoot, + allowLocalizedParameters + ); + } + + if (LocalizationManager.IsRight2Left & fixForRtl) + { + fallback = LocalizationManager.ApplyRTLfix(fallback, maxLineLengthForRtl, ignoreRtlNumbers); + } + + translation = fallback; + return true; + } + + return false; + } + + private static bool TryGetFallbackFromSource( + LanguageSourceData source, + string term, + out string translation, + string overrideSpecialization + ) + { + translation = null; + + for (var index = 0; index < source.mLanguages.Count; ++index) + { + var termData = source.GetTermData(term); + if (termData == null) { continue; } - __result = true; - return false; + translation = termData.GetTranslation(index, overrideSpecialization, true); + if (!string.IsNullOrEmpty(translation)) + { + return true; + } } - Translation = null; - __result = false; return false; } } \ No newline at end of file From 5533fba15592c14b72e23b378ff7cd11e2667c8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 14:40:29 +0100 Subject: [PATCH 18/82] Fixed loading of localization overrides --- .../InternalUtilities/AssetHelpers.cs | 31 +++++++++---------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs b/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs index b339aed..8ad7481 100644 --- a/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs +++ b/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs @@ -28,39 +28,36 @@ public static void LoadAddressable(string catalog) internal static void LoadLocalizationFromFolder(string folder) { SpaceWarpPlugin.Instance.SWLogger.LogInfo($"Attempting to load localizations from {folder}"); - LanguageSourceData languageSourceData = null; if (!Directory.Exists(folder)) { SpaceWarpPlugin.Instance.SWLogger.LogInfo($"{folder} does not exist, not loading localizations."); return; } + int loadedCount = 0; + var info = new DirectoryInfo(folder); foreach (var csvFile in info.GetFiles("*.csv", SearchOption.AllDirectories)) { - languageSourceData ??= new LanguageSourceData(); + var csvSource = new LanguageSourceData(); var csvData = File.ReadAllText(csvFile.FullName).Replace("\r\n", "\n"); - languageSourceData.Import_CSV("", csvData, eSpreadsheetUpdateMode.AddNewTerms); + csvSource.Import_CSV("", csvData, eSpreadsheetUpdateMode.AddNewTerms); + loadedCount++; + AddSource(csvSource); } foreach (var i2CsvFile in info.GetFiles("*.i2csv", SearchOption.AllDirectories)) { - languageSourceData ??= new LanguageSourceData(); + var i2CsvSource = new LanguageSourceData(); var i2CsvData = File.ReadAllText(i2CsvFile.FullName).Replace("\r\n", "\n"); - languageSourceData.Import_I2CSV("", i2CsvData, eSpreadsheetUpdateMode.AddNewTerms); + i2CsvSource.Import_I2CSV("", i2CsvData, eSpreadsheetUpdateMode.AddNewTerms); + loadedCount++; + AddSource(i2CsvSource); } - if (languageSourceData != null) - { - languageSourceData.OnMissingTranslation = LanguageSourceData.MissingTranslationAction.Fallback; - SpaceWarpPlugin.Instance.SWLogger.LogInfo($"Loaded localizations from {folder}"); - - AddSource(languageSourceData); - } - else - { - SpaceWarpPlugin.Instance.SWLogger.LogInfo($"No localizations found in {folder}"); - } + SpaceWarpPlugin.Instance.SWLogger.LogInfo( + loadedCount > 0 ? $"Loaded localizations from {folder}" : $"No localizations found in {folder}" + ); } private static void AddSource(LanguageSourceData source) @@ -70,6 +67,8 @@ private static void AddSource(LanguageSourceData source) return; } + source.OnMissingTranslation = LanguageSourceData.MissingTranslationAction.Fallback; + LocalizationManager.Sources.Insert(0, source); foreach (var language in source.mLanguages) { From 81556db1af86f7ed45d67566f9c6bdafc1193cc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 14:42:52 +0100 Subject: [PATCH 19/82] Fix non-localized main menu buttons changing to "Single Player" after switching languages --- src/SpaceWarp.UI/Patching/MainMenuPatcher.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/SpaceWarp.UI/Patching/MainMenuPatcher.cs b/src/SpaceWarp.UI/Patching/MainMenuPatcher.cs index 7a17a52..afaed3e 100644 --- a/src/SpaceWarp.UI/Patching/MainMenuPatcher.cs +++ b/src/SpaceWarp.UI/Patching/MainMenuPatcher.cs @@ -37,6 +37,8 @@ public static void Postfix(LandingHUD __instance) var tmp = newButton.GetComponentInChildren(); tmp.SetText(menuButtonToBeAdded.name); + + LocalizationManager.OnLocalizeEvent += () => tmp.SetText(menuButtonToBeAdded.name); } foreach (var localizedMenuButtonToBeAddded in MainMenu.LocalizedMenuButtonsToBeAdded) From afe424238c7a615b6e3025405f557787ff13b889 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 15:56:25 +0100 Subject: [PATCH 20/82] Fixed SpaceWarp.API.Loading warnings --- src/SpaceWarp.Core/API/Loading/Loading.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/SpaceWarp.Core/API/Loading/Loading.cs b/src/SpaceWarp.Core/API/Loading/Loading.cs index e73588a..0a3cc7a 100644 --- a/src/SpaceWarp.Core/API/Loading/Loading.cs +++ b/src/SpaceWarp.Core/API/Loading/Loading.cs @@ -5,6 +5,8 @@ using SpaceWarp.InternalUtilities; using SpaceWarp.Patching.LoadingActions; +#pragma warning disable CS0618 // Type or member is obsolete + namespace SpaceWarp.API.Loading; /// From da9e1d1a3fe22242c50d151800e7ff5d890090bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 15:56:58 +0100 Subject: [PATCH 21/82] Remove LogNone and LogAll methods --- src/SpaceWarp.Core/API/Logging/BaseLogger.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/SpaceWarp.Core/API/Logging/BaseLogger.cs b/src/SpaceWarp.Core/API/Logging/BaseLogger.cs index 7835d5b..a830775 100644 --- a/src/SpaceWarp.Core/API/Logging/BaseLogger.cs +++ b/src/SpaceWarp.Core/API/Logging/BaseLogger.cs @@ -6,7 +6,6 @@ namespace SpaceWarp.API.Logging; public abstract class BaseLogger : ILogger { public abstract void Log(LogLevel level, object x); - public void LogNone(object x) => Log(LogLevel.None, x); public void LogFatal(object x) => Log(LogLevel.Fatal, x); @@ -19,6 +18,4 @@ public abstract class BaseLogger : ILogger public void LogInfo(object x) => Log(LogLevel.Info, x); public void LogDebug(object x) => Log(LogLevel.Debug, x); - - public void LogAll(object x) => Log(LogLevel.All, x); } \ No newline at end of file From 19bd97e6ca6877dea7b89e73f7d43b9448cce6e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 15:57:17 +0100 Subject: [PATCH 22/82] Fixed SpaceWarp.API.Logging warnings --- src/SpaceWarp.Core/API/Logging/BaseLogger.cs | 10 +++++ .../API/Logging/BepInExLogger.cs | 13 +++++++ src/SpaceWarp.Core/API/Logging/ILogger.cs | 39 ++++++++++++++++++- src/SpaceWarp.Core/API/Logging/LogLevel.cs | 27 +++++++++++++ .../API/Logging/UnityLogSource.cs | 11 ++++++ 5 files changed, 98 insertions(+), 2 deletions(-) diff --git a/src/SpaceWarp.Core/API/Logging/BaseLogger.cs b/src/SpaceWarp.Core/API/Logging/BaseLogger.cs index a830775..c260e32 100644 --- a/src/SpaceWarp.Core/API/Logging/BaseLogger.cs +++ b/src/SpaceWarp.Core/API/Logging/BaseLogger.cs @@ -2,20 +2,30 @@ namespace SpaceWarp.API.Logging; +/// +/// Base class for loggers. +/// [PublicAPI] public abstract class BaseLogger : ILogger { + /// public abstract void Log(LogLevel level, object x); + /// public void LogFatal(object x) => Log(LogLevel.Fatal, x); + /// public void LogError(object x) => Log(LogLevel.Error, x); + /// public void LogWarning(object x) => Log(LogLevel.Warning, x); + /// public void LogMessage(object x) => Log(LogLevel.Message, x); + /// public void LogInfo(object x) => Log(LogLevel.Info, x); + /// public void LogDebug(object x) => Log(LogLevel.Debug, x); } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Logging/BepInExLogger.cs b/src/SpaceWarp.Core/API/Logging/BepInExLogger.cs index 662f73a..0789790 100644 --- a/src/SpaceWarp.Core/API/Logging/BepInExLogger.cs +++ b/src/SpaceWarp.Core/API/Logging/BepInExLogger.cs @@ -3,20 +3,33 @@ namespace SpaceWarp.API.Logging; +/// +/// A logger that uses BepInEx's logging system. +/// [PublicAPI] public class BepInExLogger : BaseLogger { private ManualLogSource _log; + /// + /// Creates a new instance of . + /// + /// The to use. public BepInExLogger(ManualLogSource log) { _log = log; } + /// public override void Log(LogLevel level, object x) { _log.Log((BepInEx.Logging.LogLevel)level, x); } + /// + /// Implicitly converts a to a . + /// + /// The to convert. + /// The converted . public static implicit operator BepInExLogger(ManualLogSource log) => new(log); } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Logging/ILogger.cs b/src/SpaceWarp.Core/API/Logging/ILogger.cs index a77e76e..f84cfa9 100644 --- a/src/SpaceWarp.Core/API/Logging/ILogger.cs +++ b/src/SpaceWarp.Core/API/Logging/ILogger.cs @@ -2,17 +2,52 @@ namespace SpaceWarp.API.Logging; +/// +/// Interface for loggers. +/// [PublicAPI] public interface ILogger { + /// + /// Logs the given object with the given log level. + /// + /// Log level. + /// Object to log. public void Log(LogLevel level, object x); - public void LogNone(object x); + /// + /// Logs the given object with the log level . + /// + /// Object to log. public void LogFatal(object x); + + /// + /// Logs the given object with the log level . + /// + /// Object to log. public void LogError(object x); + + /// + /// Logs the given object with the log level . + /// + /// Object to log. public void LogWarning(object x); + + /// + /// Logs the given object with the log level . + /// + /// Object to log. public void LogMessage(object x); + + /// + /// Logs the given object with the log level . + /// + /// Object to log. public void LogInfo(object x); + + /// + /// Logs the given object with the log level . + /// + /// Object to log. public void LogDebug(object x); - public void LogAll(object x); } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Logging/LogLevel.cs b/src/SpaceWarp.Core/API/Logging/LogLevel.cs index 2ef7977..2c26fdd 100644 --- a/src/SpaceWarp.Core/API/Logging/LogLevel.cs +++ b/src/SpaceWarp.Core/API/Logging/LogLevel.cs @@ -2,15 +2,42 @@ namespace SpaceWarp.API.Logging; +/// +/// The log level. +/// [PublicAPI] public enum LogLevel { + /// + /// No logging. + /// None = 0, + /// + /// Fatal errors. + /// Fatal = 1, + /// + /// Errors. + /// Error = 2, + /// + /// Warnings. + /// Warning = 4, + /// + /// Messages. + /// Message = 8, + /// + /// Information. + /// Info = 16, + /// + /// Debug information. + /// Debug = 32, + /// + /// All logging. + /// All = Debug | Info | Message | Warning | Error | Fatal } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Logging/UnityLogSource.cs b/src/SpaceWarp.Core/API/Logging/UnityLogSource.cs index 654cb06..8abbb90 100644 --- a/src/SpaceWarp.Core/API/Logging/UnityLogSource.cs +++ b/src/SpaceWarp.Core/API/Logging/UnityLogSource.cs @@ -3,16 +3,27 @@ namespace SpaceWarp.API.Logging; +/// +/// A logger that logs to Unity's built-in logging system. +/// [PublicAPI] public class UnityLogSource : BaseLogger { + /// + /// The name of the logger. + /// public string Name; + /// + /// Creates a new with the given name. + /// + /// The name of the logger. public UnityLogSource(string name) { Name = name; } + /// public override void Log(LogLevel level, object x) { switch (level) From af66f9a8831d109ec820c2bd412831d8a27b1bc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 15:58:22 +0100 Subject: [PATCH 23/82] Fixed SpaceWarp.API.Lua warnings --- .../API/Lua/SpaceWarpInterop.cs | 9 + src/SpaceWarp.Core/API/Lua/UI/LuaUITK.cs | 383 +++++++++++++++++- 2 files changed, 376 insertions(+), 16 deletions(-) diff --git a/src/SpaceWarp.Core/API/Lua/SpaceWarpInterop.cs b/src/SpaceWarp.Core/API/Lua/SpaceWarpInterop.cs index 96b762a..97d7ac6 100644 --- a/src/SpaceWarp.Core/API/Lua/SpaceWarpInterop.cs +++ b/src/SpaceWarp.Core/API/Lua/SpaceWarpInterop.cs @@ -7,10 +7,19 @@ namespace SpaceWarp.API.Lua; +/// +/// SpaceWarp interop class for Lua API. +/// [SpaceWarpLuaAPI("SpaceWarp")] [PublicAPI] public static class SpaceWarpInterop { + /// + /// Registers a Lua mod. + /// + /// Name of the mod. + /// Table containing the mod's functions. + /// The created instance. public static LuaMod RegisterMod(string name, Table modTable) { var go = new GameObject(name); diff --git a/src/SpaceWarp.Core/API/Lua/UI/LuaUITK.cs b/src/SpaceWarp.Core/API/Lua/UI/LuaUITK.cs index 34ae01f..c8df04a 100644 --- a/src/SpaceWarp.Core/API/Lua/UI/LuaUITK.cs +++ b/src/SpaceWarp.Core/API/Lua/UI/LuaUITK.cs @@ -1,50 +1,96 @@ using JetBrains.Annotations; using MoonSharp.Interpreter; using SpaceWarp.API.Assets; +using UitkForKsp2.API; using UnityEngine.UIElements; namespace SpaceWarp.API.Lua.UI; +/// +/// Lua API for UITK +/// [SpaceWarpLuaAPI("UI")] [PublicAPI] +// ReSharper disable once InconsistentNaming public static class LuaUITK { #region Creation + /// + /// Creates a new window from a UXML file. + /// + /// Mod to create the window for + /// ID of the window + /// Path to the UXML file + /// Created window public static UIDocument Window(LuaMod mod, string id, string documentPath) { return Window(mod, id, AssetManager.GetAsset(documentPath)); } + /// + /// Creates a new window from a VisualTreeAsset. + /// + /// Mod to create the window for + /// ID of the window + /// VisualTreeAsset to create the window from + /// Created window public static UIDocument Window(LuaMod mod, string id, VisualTreeAsset uxml) { - var parent = mod.transform; - return UitkForKsp2.API.Window.CreateFromUxml(uxml, id, parent, true); + var windowOptions = WindowOptions.Default; + windowOptions.Parent = mod.transform; + windowOptions.WindowId = id; + return UitkForKsp2.API.Window.Create(windowOptions, uxml); } + /// + /// Creates a new window with an empty root element. + /// + /// Mod to create the window for + /// ID of the window + /// Created window public static UIDocument Window(LuaMod mod, string id) { - var parent = mod.transform; - return UitkForKsp2.API.Window.Create(out _, id, parent, true); + var windowOptions = WindowOptions.Default; + windowOptions.Parent = mod.transform; + windowOptions.WindowId = id; + return UitkForKsp2.API.Window.Create(windowOptions); } #region Element Creation + /// + /// Creates a new VisualElement. + /// + /// Created VisualElement public static VisualElement VisualElement() { return new VisualElement(); } + /// + /// Creates a new ScrollView. + /// + /// Created ScrollView public static ScrollView ScrollView() { return new ScrollView(); } + /// + /// Creates a new ListView. + /// + /// Created ListView public static ListView ListView() { return new ListView(); } + /// + /// Creates a new Toggle. + /// + /// Text of the Toggle + /// Created Toggle public static Toggle Toggle(string text = "") { return new Toggle @@ -53,6 +99,11 @@ public static Toggle Toggle(string text = "") }; } + /// + /// Creates a new Label. + /// + /// Text of the Label + /// Created Label public static Label Label(string text = "") { return new Label @@ -61,6 +112,11 @@ public static Label Label(string text = "") }; } + /// + /// Creates a new Button. + /// + /// Text of the Button + /// Created Button public static Button Button(string text = "") { return new Button @@ -69,11 +125,20 @@ public static Button Button(string text = "") }; } + /// + /// Creates a new Scroller. + /// + /// Created Scroller public static Scroller Scroller() { return new Scroller(); } + /// + /// Creates a new TextField. + /// + /// Text of the TextField + /// Created TextField public static TextField TextField(string text = "") { return new TextField @@ -82,11 +147,22 @@ public static TextField TextField(string text = "") }; } + /// + /// Creates a new Foldout. + /// + /// Created Foldout public static Foldout Foldout() { return new Foldout(); } + /// + /// Creates a new Slider. + /// + /// Value of the Slider + /// Minimum value of the Slider + /// Maximum value of the Slider + /// Created Slider public static Slider Slider(float value = 0.0f, float minValue = 0.0f, float maxValue = 1.0f) { return new Slider @@ -97,6 +173,13 @@ public static Slider Slider(float value = 0.0f, float minValue = 0.0f, float max }; } + /// + /// Creates a new SliderInt. + /// + /// Value of the SliderInt + /// Minimum value of the SliderInt + /// Maximum value of the SliderInt + /// public static SliderInt SliderInt(int value = 0, int minValue = 0, int maxValue = 100) { return new SliderInt @@ -107,8 +190,20 @@ public static SliderInt SliderInt(int value = 0, int minValue = 0, int maxValue }; } - public static MinMaxSlider MinMaxSlider(float minValue = 0.0f, float maxValue = 1.0f, float minLimit = 0.0f, - float maxLimit = 1.0f) + /// + /// Creates a new MinMaxSlider. + /// + /// Minimum value of the MinMaxSlider + /// Maximum value of the MinMaxSlider + /// Minimum limit of the MinMaxSlider + /// Maximum limit of the MinMaxSlider + /// + public static MinMaxSlider MinMaxSlider( + float minValue = 0.0f, + float maxValue = 1.0f, + float minLimit = 0.0f, + float maxLimit = 1.0f + ) { return new MinMaxSlider { @@ -125,6 +220,12 @@ public static MinMaxSlider MinMaxSlider(float minValue = 0.0f, float maxValue = #region Callbacks + /// + /// Adds a callback to a button from Lua + /// + /// Button to add the callback to + /// Callback to add + /// Self parameter for the callback public static void AddCallback(Button button, Closure callback, [CanBeNull] DynValue self = null) { if (self != null) @@ -138,13 +239,13 @@ public static void AddCallback(Button button, Closure callback, [CanBeNull] DynV } /// - /// Registers a value changed callback from lua - /// The lua functions parameters should be like function(self?,previous,new) + /// Registers a value changed callback from Lua + /// The Lua functions parameters should be like function(self?,previous,new) /// - /// - /// - /// - /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Type of the value public static void RegisterValueChangedCallback( INotifyValueChanged element, Closure callback, @@ -170,19 +271,30 @@ private static void RegisterGenericCallback( { if (self != null) { - element.RegisterCallback(evt => callback.Call(self, evt), - trickleDown ? TrickleDown.TrickleDown : TrickleDown.NoTrickleDown); + element.RegisterCallback( + evt => callback.Call(self, evt), + trickleDown ? TrickleDown.TrickleDown : TrickleDown.NoTrickleDown + ); } else { - element.RegisterCallback(evt => callback.Call(evt), - trickleDown ? TrickleDown.TrickleDown : TrickleDown.NoTrickleDown); + element.RegisterCallback( + evt => callback.Call(evt), + trickleDown ? TrickleDown.TrickleDown : TrickleDown.NoTrickleDown + ); } } #region Capture Events + /// + /// Registers a mouse capture callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterMouseCaptureCallback( VisualElement element, Closure callback, @@ -190,6 +302,13 @@ public static void RegisterMouseCaptureCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a mouse capture out callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterMouseCaptureOutCallback( VisualElement element, Closure callback, @@ -197,6 +316,13 @@ public static void RegisterMouseCaptureOutCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a pointer capture callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterPointerCaptureCallback( VisualElement element, Closure callback, @@ -204,6 +330,13 @@ public static void RegisterPointerCaptureCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a pointer capture out callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterPointerCaptureOutCallback( VisualElement element, Closure callback, @@ -215,6 +348,13 @@ public static void RegisterPointerCaptureOutCallback( #region Change Events + /// + /// Registers a boolean value change event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterChangeBoolCallback( VisualElement element, Closure callback, @@ -222,6 +362,13 @@ public static void RegisterChangeBoolCallback( bool trickleDown = false ) => RegisterGenericCallback>(element, callback, self, trickleDown); + /// + /// Registers an integer value change event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterChangeIntCallback( VisualElement element, Closure callback, @@ -229,6 +376,13 @@ public static void RegisterChangeIntCallback( bool trickleDown = false ) => RegisterGenericCallback>(element, callback, self, trickleDown); + /// + /// Registers a float value change event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterChangeFloatCallback( VisualElement element, Closure callback, @@ -236,6 +390,13 @@ public static void RegisterChangeFloatCallback( bool trickleDown = false ) => RegisterGenericCallback>(element, callback, self, trickleDown); + /// + /// Registers a string value change event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterChangeStringCallback( VisualElement element, Closure callback, @@ -247,6 +408,13 @@ public static void RegisterChangeStringCallback( #region Click Events + /// + /// Registers a click event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterClickCallback( VisualElement element, Closure callback, @@ -258,6 +426,13 @@ public static void RegisterClickCallback( #region Focus Events + /// + /// Registers a focus out event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterFocusOutCallback( VisualElement element, Closure callback, @@ -265,6 +440,13 @@ public static void RegisterFocusOutCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a focus in event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterFocusInCallback( VisualElement element, Closure callback, @@ -272,6 +454,13 @@ public static void RegisterFocusInCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a blur event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterBlurCallback( VisualElement element, Closure callback, @@ -279,6 +468,13 @@ public static void RegisterBlurCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a focus event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterFocusCallback( VisualElement element, Closure callback, @@ -290,6 +486,13 @@ public static void RegisterFocusCallback( #region Input Events + /// + /// Registers an input event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterInputCallback( VisualElement element, Closure callback, @@ -301,6 +504,13 @@ public static void RegisterInputCallback( #region Layout Events + /// + /// Registers a geometry changed event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterGeometryChangedCallback( VisualElement element, Closure callback, @@ -312,6 +522,13 @@ public static void RegisterGeometryChangedCallback( #region Mouse Events + /// + /// Registers a mouse down event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterMouseDownCallback( VisualElement element, Closure callback, @@ -319,6 +536,14 @@ public static void RegisterMouseDownCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + + /// + /// Registers a mouse up event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterMouseUpCallback( VisualElement element, Closure callback, @@ -326,6 +551,13 @@ public static void RegisterMouseUpCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a mouse move event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterMouseMoveCallback( VisualElement element, Closure callback, @@ -333,6 +565,13 @@ public static void RegisterMouseMoveCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a mouse wheel event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterWheelCallback( VisualElement element, Closure callback, @@ -340,6 +579,13 @@ public static void RegisterWheelCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a mouse enter window event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterMouseEnterWindowCallback( VisualElement element, Closure callback, @@ -347,6 +593,13 @@ public static void RegisterMouseEnterWindowCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a mouse leave window event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterMouseLeaveWindowCallback( VisualElement element, Closure callback, @@ -354,6 +607,13 @@ public static void RegisterMouseLeaveWindowCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a mouse enter event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterMouseEnterCallback( VisualElement element, Closure callback, @@ -361,6 +621,13 @@ public static void RegisterMouseEnterCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a mouse leave event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterMouseLeaveCallback( VisualElement element, Closure callback, @@ -368,6 +635,13 @@ public static void RegisterMouseLeaveCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a mouse over event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterMouseOverCallback( VisualElement element, Closure callback, @@ -375,6 +649,13 @@ public static void RegisterMouseOverCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a mouse out event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterMouseOutCallback( VisualElement element, Closure callback, @@ -386,6 +667,13 @@ public static void RegisterMouseOutCallback( #region Pointer Events + /// + /// Registers a pointer down event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterPointerDownCallback( VisualElement element, Closure callback, @@ -393,6 +681,13 @@ public static void RegisterPointerDownCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a pointer up event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterPointerUpCallback( VisualElement element, Closure callback, @@ -400,6 +695,13 @@ public static void RegisterPointerUpCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a pointer move event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterPointerMoveCallback( VisualElement element, Closure callback, @@ -407,6 +709,13 @@ public static void RegisterPointerMoveCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a pointer enter event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterPointerEnterCallback( VisualElement element, Closure callback, @@ -414,6 +723,13 @@ public static void RegisterPointerEnterCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a pointer leave event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterPointerLeaveCallback( VisualElement element, Closure callback, @@ -421,6 +737,13 @@ public static void RegisterPointerLeaveCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a pointer over event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterPointerOverCallback( VisualElement element, Closure callback, @@ -428,6 +751,13 @@ public static void RegisterPointerOverCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a pointer out event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterPointerOutCallback( VisualElement element, Closure callback, @@ -439,6 +769,13 @@ public static void RegisterPointerOutCallback( #region Panel Events + /// + /// Registers an attach to panel event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterAttachToPanelCallback( VisualElement element, Closure callback, @@ -446,6 +783,13 @@ public static void RegisterAttachToPanelCallback( bool trickleDown = false ) => RegisterGenericCallback(element, callback, self, trickleDown); + /// + /// Registers a detach from panel event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterDetachFromPanelCallback( VisualElement element, Closure callback, @@ -457,6 +801,13 @@ public static void RegisterDetachFromPanelCallback( #region Tooltip Events + /// + /// Registers a tooltip event callback from Lua + /// + /// Element to register the callback for + /// Callback to register + /// Self parameter for the callback + /// Whether the event should trickle down public static void RegisterTooltipCallback( VisualElement element, Closure callback, From 2c91322467276539c1a96d7a6bc07df2a594cdf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 16:12:33 +0100 Subject: [PATCH 24/82] Reorganized BaseSpaceWarpPlugin, replaced uses of internal ModLogger with SWLogger --- src/SpaceWarp.Core/API/Loading/Loading.cs | 4 +- .../API/Mods/BaseSpaceWarpPlugin.cs | 65 ++++++++++++------- .../LoadingActions/ModLoadingAction.cs | 2 +- 3 files changed, 44 insertions(+), 27 deletions(-) diff --git a/src/SpaceWarp.Core/API/Loading/Loading.cs b/src/SpaceWarp.Core/API/Loading/Loading.cs index 0a3cc7a..858840d 100644 --- a/src/SpaceWarp.Core/API/Loading/Loading.cs +++ b/src/SpaceWarp.Core/API/Loading/Loading.cs @@ -100,7 +100,7 @@ private static Action CreateAssetLoadingActionWithExtension } catch (Exception e) { - plugin.ModLogger.LogError(e.ToString()); + plugin.SWLogger.LogError(e.ToString()); } } } @@ -197,7 +197,7 @@ private static Action CreateAssetLoadingActionWithoutExtens } catch (Exception e) { - plugin.ModLogger.LogError(e.ToString()); + plugin.SWLogger.LogError(e.ToString()); } } }; diff --git a/src/SpaceWarp.Core/API/Mods/BaseSpaceWarpPlugin.cs b/src/SpaceWarp.Core/API/Mods/BaseSpaceWarpPlugin.cs index 2f7551f..caa5d4f 100644 --- a/src/SpaceWarp.Core/API/Mods/BaseSpaceWarpPlugin.cs +++ b/src/SpaceWarp.Core/API/Mods/BaseSpaceWarpPlugin.cs @@ -1,5 +1,4 @@ using BepInEx; -using BepInEx.Logging; using JetBrains.Annotations; using KSP.Game; using KSP.Messages; @@ -11,60 +10,78 @@ namespace SpaceWarp.API.Mods; /// -/// Represents a KSP2 Mod, you should inherit from this and do your manager processing. +/// Represents a SpaceWarp mod based on BepInEx. /// [PublicAPI] public abstract class BaseSpaceWarpPlugin : BaseUnityPlugin, ISpaceWarpMod { - #region KspBehaviour things + #region KerbalMonoBehaviour properties + /// + /// The current game instance, this is null if the game is not yet initialized or shutting down. + /// protected static GameInstance Game => GameManager.Instance == null ? null : GameManager.Instance.Game; + /// + /// The message center for the current game instance. + /// protected MessageCenter Messages => Game.Messages; - // ReSharper disable Unity.NoNullPropagation - // fine because its null checked by Game properly + /// + /// The current game instance, this is null if the game is not yet initialized or shutting down. + /// + // ReSharper disable Unity.NoNullPropagation - fine because it's null checked by Game properly + // ReSharper disable once InconsistentNaming protected ContextualFxSystem CFXSystem => Game?.GraphicsManager?.ContextualFxSystem; + /// + /// Whether the game is shutting down. + /// protected bool IsGameShuttingDown => Game == null; #endregion + private BepInExLogger _logger; + private BepInExConfigFile _configFile; + + /// + /// The mod info for this mod. + /// public ModInfo SpaceWarpMetadata { get; internal set; } - internal ManualLogSource ModLogger => Logger; - public string PluginFolderPath { get; internal set; } - public string IdBySpec => GetGuidBySpec(Info, SpaceWarpMetadata); + /// + /// The path to the folder containing the plugin. + /// + public string PluginFolderPath { get; internal set; } /// - /// 1st stage initialization - /// This is called before any of the game is actually loaded, it is called as early as possible in the games bootstrap - /// process. + /// The correct ID of the mod based on its spec version. /// + public string IdBySpec => GetGuidBySpec(Info, SpaceWarpMetadata); + + /// + public ILogger SWLogger => _logger ??= new BepInExLogger(Logger); + + /// + public IConfigFile SWConfiguration => _configFile ??= new BepInExConfigFile(Config); + + /// + public SpaceWarpPluginDescriptor SWMetadata { get; set; } + + /// public virtual void OnPreInitialized() { } - /// - /// 2nd stage initialization - /// This is called after the game is loaded, and after your mods assets are loaded. - /// + /// public virtual void OnInitialized() { } - /// - /// 3rd stage initialization - /// This is called after all mods have done first stage initialization - /// + /// public virtual void OnPostInitialized() { } - private BepInExLogger _logger; - public ILogger SWLogger => _logger ??= new BepInExLogger(Logger); - private BepInExConfigFile _configFile; - public IConfigFile SWConfiguration => _configFile ??= new BepInExConfigFile(Config); - public SpaceWarpPluginDescriptor SWMetadata { get; set; } internal static string GetGuidBySpec(PluginInfo pluginInfo, ModInfo modInfo) { diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs index d9ec2d4..5b9483f 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs @@ -31,7 +31,7 @@ public override void DoAction(Action resolve, Action reject) } catch (Exception e) { - Plugin.ModLogger.LogError(e.ToString()); + Plugin.SWLogger.LogError(e.ToString()); reject(null); } } From cce1b205be7fc770855619b4f952b6d31a217e69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 16:28:26 +0100 Subject: [PATCH 25/82] Mark obsolete members of BaseSpaceWarpPlugin --- src/SpaceWarp.Core/API/Mods/BaseSpaceWarpPlugin.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/SpaceWarp.Core/API/Mods/BaseSpaceWarpPlugin.cs b/src/SpaceWarp.Core/API/Mods/BaseSpaceWarpPlugin.cs index caa5d4f..6c22d6d 100644 --- a/src/SpaceWarp.Core/API/Mods/BaseSpaceWarpPlugin.cs +++ b/src/SpaceWarp.Core/API/Mods/BaseSpaceWarpPlugin.cs @@ -47,16 +47,19 @@ public abstract class BaseSpaceWarpPlugin : BaseUnityPlugin, ISpaceWarpMod /// /// The mod info for this mod. /// + [Obsolete("This will be removed in 2.0.0. Use SWMetadata instead.")] public ModInfo SpaceWarpMetadata { get; internal set; } /// /// The path to the folder containing the plugin. /// + [Obsolete("This will be removed in 2.0.0. Use SWMetadata.Folder instead.")] public string PluginFolderPath { get; internal set; } /// /// The correct ID of the mod based on its spec version. /// + [Obsolete("This will be removed in 2.0.0. Use SWMetadata.Guid instead.")] public string IdBySpec => GetGuidBySpec(Info, SpaceWarpMetadata); /// @@ -83,6 +86,7 @@ public virtual void OnPostInitialized() { } + [Obsolete("To be removed in 2.0.0.")] internal static string GetGuidBySpec(PluginInfo pluginInfo, ModInfo modInfo) { return modInfo.Spec >= SpecVersion.V1_2 From aa9d7129517537d57f3ad27d38c63532dd18272d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 16:56:01 +0100 Subject: [PATCH 26/82] PluginList updates for member visibility and more --- src/SpaceWarp.Core/API/Mods/PluginList.cs | 111 ++++++++++++++-------- 1 file changed, 70 insertions(+), 41 deletions(-) diff --git a/src/SpaceWarp.Core/API/Mods/PluginList.cs b/src/SpaceWarp.Core/API/Mods/PluginList.cs index b5c994a..3e94847 100644 --- a/src/SpaceWarp.Core/API/Mods/PluginList.cs +++ b/src/SpaceWarp.Core/API/Mods/PluginList.cs @@ -33,7 +33,8 @@ public static class PluginList /// Contains information about all currently disabled plugins. The key is the BepInEx GUID of the plugin. /// public static Dictionary DisabledPluginInfos { get; } = ChainloaderPatch - .DisabledPluginGuids.Zip(ChainloaderPatch.DisabledPlugins, (guid, info) => new { guid, info }) + .DisabledPluginGuids + .Zip(ChainloaderPatch.DisabledPlugins, (guid, info) => new { guid, info }) .ToDictionary(item => item.guid, item => item.info); /// @@ -71,12 +72,9 @@ public static int CompareVersion(string guid, Version version) /// of the plugin or null if not found public static ModInfo TryGetSwinfo(string guid) { - var swModInfo = AllEnabledAndActivePlugins - .FirstOrDefault(item => item.Guid == guid); - - if (swModInfo != null) + if (TryGetDescriptor(guid) is { SWInfo: var swInfo }) { - return swModInfo.SWInfo; + return swInfo; } var disabledModInfo = AllDisabledPlugins @@ -95,8 +93,7 @@ public static ModInfo TryGetSwinfo(string guid) /// of the plugin or null if not found public static SpaceWarpPluginDescriptor TryGetDescriptor(string guid) { - return AllEnabledAndActivePlugins - .FirstOrDefault(item => item.Guid == guid); + return AllEnabledAndActivePlugins.FirstOrDefault(item => item.Guid == guid); } /// @@ -119,27 +116,33 @@ public static T TryGetPlugin(string guid) where T : BaseUnityPlugin => #region Registering Plugins - private static List _allEnabledAndActivePlugins = new(); + private static List _allEnabledAndActivePlugins = []; + private static List _allDisabledPlugins = []; + private static List _allErroredPlugins = []; /// - /// All plugins that are enabled, and active (not errored) + /// All plugins that are enabled and active (not errored) /// public static IReadOnlyList AllEnabledAndActivePlugins => _allEnabledAndActivePlugins; - private static List _allDisabledPlugins = new(); - /// /// All disabled plugins /// public static IReadOnlyList AllDisabledPlugins => _allDisabledPlugins; - private static List _allErroredPlugins = new(); + /// + /// All errored plugins + /// public static IReadOnlyList AllErroredPlugins => _allErroredPlugins; + /// + /// All plugins, including disabled and errored + /// public static IEnumerable AllPlugins => _allEnabledAndActivePlugins - .Concat(_allDisabledPlugins).Concat(_allErroredPlugins.Select(x => x.Plugin)); + .Concat(_allDisabledPlugins) + .Concat(_allErroredPlugins.Select(x => x.Plugin)); - public static void RegisterPlugin(SpaceWarpPluginDescriptor plugin) + internal static void RegisterPlugin(SpaceWarpPluginDescriptor plugin) { if (AllPlugins.Any(x => x.Guid == plugin.Guid)) { @@ -150,10 +153,16 @@ public static void RegisterPlugin(SpaceWarpPluginDescriptor plugin) _allEnabledAndActivePlugins.Add(plugin); } - public static void Disable(string guid) + internal static void Disable(string guid) { - var descriptor = _allEnabledAndActivePlugins.FirstOrDefault(x => - string.Equals(x.Guid, guid, StringComparison.InvariantCultureIgnoreCase)); + var descriptor = _allEnabledAndActivePlugins.FirstOrDefault( + x => string.Equals( + x.Guid, + guid, + StringComparison.InvariantCultureIgnoreCase + ) + ); + if (descriptor != null) { _allEnabledAndActivePlugins.Remove(descriptor); @@ -161,9 +170,8 @@ public static void Disable(string guid) } } - public static SpaceWarpErrorDescription GetErrorDescriptor(SpaceWarpPluginDescriptor plugin) + internal static SpaceWarpErrorDescription GetErrorDescriptor(SpaceWarpPluginDescriptor plugin) { - if (_allErroredPlugins.Any(x => x.Plugin == plugin)) { return _allErroredPlugins.First(x => x.Plugin == plugin); @@ -179,31 +187,31 @@ public static SpaceWarpErrorDescription GetErrorDescriptor(SpaceWarpPluginDescri return newError; } - public static void NoteMissingSwinfoError(SpaceWarpPluginDescriptor plugin) + internal static void NoteMissingSwinfoError(SpaceWarpPluginDescriptor plugin) { var errorDescriptor = GetErrorDescriptor(plugin); errorDescriptor.MissingSwinfo = true; } - public static void NoteBadDirectoryError(SpaceWarpPluginDescriptor plugin) + internal static void NoteBadDirectoryError(SpaceWarpPluginDescriptor plugin) { var errorDescriptor = GetErrorDescriptor(plugin); errorDescriptor.BadDirectory = true; } - public static void NoteBadIDError(SpaceWarpPluginDescriptor plugin) + internal static void NoteBadIDError(SpaceWarpPluginDescriptor plugin) { var errorDescriptor = GetErrorDescriptor(plugin); errorDescriptor.BadID = true; } - public static void NoteMismatchedVersionError(SpaceWarpPluginDescriptor plugin) + internal static void NoteMismatchedVersionError(SpaceWarpPluginDescriptor plugin) { var errorDescriptor = GetErrorDescriptor(plugin); errorDescriptor.MismatchedVersion = true; } - public static void NoteUnspecifiedDependencyError(SpaceWarpPluginDescriptor plugin, string dependency) + internal static void NoteUnspecifiedDependencyError(SpaceWarpPluginDescriptor plugin, string dependency) { var errorDescriptor = GetErrorDescriptor(plugin); errorDescriptor.UnspecifiedDependencies.Add(dependency); @@ -212,7 +220,7 @@ public static void NoteUnspecifiedDependencyError(SpaceWarpPluginDescriptor plug private static SemanticVersion PadVersion(string version) { var length = version.Split('.').Length; - for (var i = 0; i < 3-length; i++) + for (var i = 0; i < 3 - length; i++) { version += ".0"; } @@ -227,7 +235,7 @@ private static bool IsSupportedSemver(string version, string min, string max) var maxVersion = PadVersion(max.Replace("*", $"{int.MaxValue}")); return basicVersion >= minVersion && basicVersion <= maxVersion; } - + private static bool DependencyResolved( SpaceWarpPluginDescriptor descriptor, List resolvedPlugins @@ -235,10 +243,12 @@ List resolvedPlugins { if (descriptor.SWInfo.Spec < SpecVersion.V1_3) return true; return !(from dependency in descriptor.SWInfo.Dependencies - let info = resolvedPlugins.FirstOrDefault(x => string.Equals( - x.Guid, - dependency.ID, - StringComparison.InvariantCultureIgnoreCase) + let info = resolvedPlugins.FirstOrDefault( + x => string.Equals( + x.Guid, + dependency.ID, + StringComparison.InvariantCultureIgnoreCase + ) ) where info == null || !IsSupportedSemver( info.SWInfo.Version, @@ -269,8 +279,11 @@ private static void GetLoadOrder() var info = _allEnabledAndActivePlugins[i]; SpaceWarpPlugin.Logger.LogError($"Missing dependency for mod: {info.Name}, this mod will not be loaded"); var error = GetErrorDescriptor(info); - error.MissingDependencies = info.SWInfo.Dependencies.Select(x => x.ID).Where(x => - !newOrder.Any(y => string.Equals(x, y.Guid, StringComparison.InvariantCultureIgnoreCase))).ToList(); + error.MissingDependencies = info.SWInfo + .Dependencies + .Select(x => x.ID) + .Where(x => !newOrder.Any(y => string.Equals(x, y.Guid, StringComparison.InvariantCultureIgnoreCase))) + .ToList(); } _allEnabledAndActivePlugins = newOrder; @@ -278,8 +291,9 @@ private static void GetLoadOrder() private static void GetDependencyErrors() { - foreach (var erroredPlugin in _allErroredPlugins.Where(erroredPlugin => - erroredPlugin.MissingDependencies.Count != 0)) + foreach (var erroredPlugin in _allErroredPlugins.Where( + erroredPlugin => erroredPlugin.MissingDependencies.Count != 0 + )) { for (var i = erroredPlugin.MissingDependencies.Count - 1; i >= 0; i--) { @@ -308,19 +322,30 @@ private static void GetDependencyErrors() private static void CheckCompatibility() { - var incompatibilities = _allEnabledAndActivePlugins.Select(x => (Key: x.Guid, Value: new HashSet())) + var incompatibilities = _allEnabledAndActivePlugins + .Select(x => (Key: x.Guid, Value: new HashSet())) .ToDictionary(x => x.Key, x => x.Value); - var versionLookup = _allEnabledAndActivePlugins.Select(x => (Key: x.Guid, Value: x.SWInfo.Version)) + var versionLookup = _allEnabledAndActivePlugins + .Select(x => (Key: x.Guid, Value: x.SWInfo.Version)) .ToDictionary(x => x.Key, x => x.Value); - var pluginDictionary = _allEnabledAndActivePlugins.ToDictionary(x => x.Guid, x => x); + var pluginDictionary = _allEnabledAndActivePlugins + .ToDictionary(x => x.Guid, x => x); foreach (var mod in _allEnabledAndActivePlugins) { var swinfo = mod.SWInfo; - if (swinfo.Spec < SpecVersion.V2_0) continue; + if (swinfo.Spec < SpecVersion.V2_0) + { + continue; + } + foreach (var conflict in swinfo.Conflicts) { if (!versionLookup.TryGetValue(conflict.ID, out var conflictingVersion) || - !IsSupportedSemver(conflictingVersion, conflict.Version.Min, conflict.Version.Max)) continue; + !IsSupportedSemver(conflictingVersion, conflict.Version.Min, conflict.Version.Max)) + { + continue; + } + incompatibilities[mod.Guid].Add(conflict.ID); incompatibilities[conflict.ID].Add(mod.Guid); } @@ -328,7 +353,11 @@ private static void CheckCompatibility() foreach (var incompatibility in incompatibilities) { - if (incompatibility.Value.Count <= 0) continue; + if (incompatibility.Value.Count <= 0) + { + continue; + } + var descriptor = GetErrorDescriptor(pluginDictionary[incompatibility.Key]); descriptor.Incompatibilities.AddRange(incompatibility.Value); } From 5092319be29b42f31883180a7e189c597a502531 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 17:00:05 +0100 Subject: [PATCH 27/82] Fixed SpaceWarp.API.Mods warnings --- .../API/Mods/BaseKspLoaderSpaceWarpMod.cs | 18 +++--- .../API/Mods/GlobalModDefines.cs | 9 +++ src/SpaceWarp.Core/API/Mods/ISpaceWarpMod.cs | 25 ++++++++ .../API/Mods/JSON/DependencyInfo.cs | 6 ++ src/SpaceWarp.Core/API/Mods/JSON/ModInfo.cs | 58 ++++++++++++++++--- .../API/Mods/JSON/SpecVersion.cs | 52 ++++++++++++++++- .../API/Mods/JSON/SupportedVersionsInfo.cs | 22 +++++++ .../API/Mods/JSON/VersionCheckType.cs | 9 +++ .../API/Mods/SpaceWarpErrorDescription.cs | 50 +++++++++++++++- .../API/Mods/SpaceWarpPluginDescriptor.cs | 53 ++++++++++++++++- 10 files changed, 281 insertions(+), 21 deletions(-) diff --git a/src/SpaceWarp.Core/API/Mods/BaseKspLoaderSpaceWarpMod.cs b/src/SpaceWarp.Core/API/Mods/BaseKspLoaderSpaceWarpMod.cs index 0127632..0cf5ecc 100644 --- a/src/SpaceWarp.Core/API/Mods/BaseKspLoaderSpaceWarpMod.cs +++ b/src/SpaceWarp.Core/API/Mods/BaseKspLoaderSpaceWarpMod.cs @@ -5,31 +5,33 @@ namespace SpaceWarp.API.Mods; +/// +/// Base class for mods that are loaded by the KSP2 internal loader +/// [PublicAPI] public abstract class BaseKspLoaderSpaceWarpMod : Mod, ISpaceWarpMod { + /// public virtual void OnPreInitialized() { - } + /// public virtual void OnInitialized() { } + /// public virtual void OnPostInitialized() { } - /// - /// Gets set automatically, before awake is called - /// + /// public ILogger SWLogger { get; set; } - public IConfigFile SWConfiguration { - get; - internal set; - } + /// + public IConfigFile SWConfiguration { get; internal set; } + /// public SpaceWarpPluginDescriptor SWMetadata { get; set; } } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Mods/GlobalModDefines.cs b/src/SpaceWarp.Core/API/Mods/GlobalModDefines.cs index 16f660f..fc1a8aa 100644 --- a/src/SpaceWarp.Core/API/Mods/GlobalModDefines.cs +++ b/src/SpaceWarp.Core/API/Mods/GlobalModDefines.cs @@ -2,9 +2,18 @@ namespace SpaceWarp.API.Mods; +/// +/// Global definitions for all SpaceWarp mods. +/// [PublicAPI] public static class GlobalModDefines { + /// + /// Relative path to the folder containing the mod's asset bundles. + /// public static readonly string AssetBundlesFolder = Path.Combine("assets", "bundles"); + /// + /// Relative path to the folder containing the mod's images. + /// public static readonly string ImageAssetsFolder = Path.Combine("assets", "images"); } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Mods/ISpaceWarpMod.cs b/src/SpaceWarp.Core/API/Mods/ISpaceWarpMod.cs index c2f9d44..7335189 100644 --- a/src/SpaceWarp.Core/API/Mods/ISpaceWarpMod.cs +++ b/src/SpaceWarp.Core/API/Mods/ISpaceWarpMod.cs @@ -4,18 +4,43 @@ namespace SpaceWarp.API.Mods; +/// +/// Interface for all SpaceWarp mods +/// [PublicAPI] public interface ISpaceWarpMod { + /// + /// 1st stage initialization. + /// This is called before any of the game is actually loaded, it is called as early as possible in the game's + /// bootstrap process. + /// public void OnPreInitialized(); + /// + /// 2nd stage initialization. + /// This is called after the game is loaded, and after your mods assets are loaded. + /// public void OnInitialized(); + /// + /// 3rd stage initialization. + /// This is called after all mods have done 2nd stage initialization. + /// public void OnPostInitialized(); + /// + /// Gets the logger for this mod + /// public ILogger SWLogger { get; } + /// + /// Gets the configuration file for this mod + /// public IConfigFile SWConfiguration { get; } + /// + /// Gets the metadata for this mod + /// public SpaceWarpPluginDescriptor SWMetadata { get; set; } } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Mods/JSON/DependencyInfo.cs b/src/SpaceWarp.Core/API/Mods/JSON/DependencyInfo.cs index f862fcd..dd4e595 100644 --- a/src/SpaceWarp.Core/API/Mods/JSON/DependencyInfo.cs +++ b/src/SpaceWarp.Core/API/Mods/JSON/DependencyInfo.cs @@ -11,7 +11,13 @@ namespace SpaceWarp.API.Mods.JSON; [PublicAPI] public sealed class DependencyInfo { + /// + /// The ID of the dependency. + /// [JsonProperty("id")] public string ID { get; internal set; } + /// + /// The version of the dependency. + /// [JsonProperty("version")] public SupportedVersionsInfo Version { get; internal set; } } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Mods/JSON/ModInfo.cs b/src/SpaceWarp.Core/API/Mods/JSON/ModInfo.cs index 78fe129..49b94b3 100644 --- a/src/SpaceWarp.Core/API/Mods/JSON/ModInfo.cs +++ b/src/SpaceWarp.Core/API/Mods/JSON/ModInfo.cs @@ -10,10 +10,19 @@ namespace SpaceWarp.API.Mods.JSON; [PublicAPI] public sealed class ModInfo { - [JsonProperty("spec", Required = Required.DisallowNull)] public SpecVersion Spec { get; internal set; } = new(); + /// + /// The spec version of the mod info file. + /// + [JsonProperty("spec", Required = Required.DisallowNull)] + public SpecVersion Spec { get; internal set; } = new(); - [JsonProperty("mod_id", Required = Required.DisallowNull)] private string _modID = ""; + [JsonProperty("mod_id", Required = Required.DisallowNull)] + private string _modID = ""; + /// + /// The mod ID of the mod. + /// + /// Thrown when the spec version is 1.2. public string ModID { get @@ -22,31 +31,57 @@ public string ModID { throw new DeprecatedSwinfoPropertyException(nameof(ModID), SpecVersion.V1_2); } + return _modID; } internal set => _modID = value; } - [JsonProperty("name")] private string _name; + + /// + /// The name of the mod. + /// public string Name { get => _name ?? _modID; internal set => _name = value; } + /// + /// The author of the mod. + /// [JsonProperty("author", Required = Required.DisallowNull)] public string Author { get; internal set; } = ""; - [JsonProperty("description", Required = Required.DisallowNull)] public string Description { get; internal set; } = ""; + /// + /// The description of the mod. + /// + [JsonProperty("description", Required = Required.DisallowNull)] + public string Description { get; internal set; } = ""; - [JsonProperty("source", Required = Required.DisallowNull)] public string Source { get; internal set; } = ""; + /// + /// The URL of the source code of the mod. + /// + [JsonProperty("source", Required = Required.DisallowNull)] + public string Source { get; internal set; } = ""; - [JsonProperty("version", Required = Required.Always)] public string Version { get; internal set; } + /// + /// The version of the mod. + /// + [JsonProperty("version", Required = Required.Always)] + public string Version { get; internal set; } - [JsonProperty("dependencies", Required = Required.DisallowNull)] public List Dependencies { get; internal set; } = new(); + /// + /// The dependencies of the mod. + /// + [JsonProperty("dependencies", Required = Required.DisallowNull)] + public List Dependencies { get; internal set; } = new(); + /// + /// The KSP2 versions supported by the mod. + /// [JsonProperty("ksp2_version", Required = Required.DisallowNull)] public SupportedVersionsInfo SupportedKsp2Versions { get; internal set; } = new() { @@ -54,14 +89,23 @@ public string Name Max = "*" }; + /// + /// The URL for the version checking of the mod. + /// [JsonProperty("version_check")] [CanBeNull] public string VersionCheck { get; internal set; } + /// + /// The type of version checking of the mod. + /// [JsonProperty("version_check_type")] [Obsolete("Only swinfo.json version checking will be allowed in 2.0.0.")] public VersionCheckType VersionCheckType { get; internal set; } = VersionCheckType.SwInfo; + /// + /// The conflicts of the mod. + /// [JsonProperty("conflicts", Required = Required.DisallowNull)] public List Conflicts { get; internal set; } = new(); } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Mods/JSON/SpecVersion.cs b/src/SpaceWarp.Core/API/Mods/JSON/SpecVersion.cs index bc73289..0deb260 100644 --- a/src/SpaceWarp.Core/API/Mods/JSON/SpecVersion.cs +++ b/src/SpaceWarp.Core/API/Mods/JSON/SpecVersion.cs @@ -14,7 +14,14 @@ public sealed record SpecVersion private const int DefaultMajor = 1; private const int DefaultMinor = 0; + /// + /// Major version number. + /// public int Major { get; } = DefaultMajor; + + /// + /// Minor version number. + /// public int Minor { get; } = DefaultMinor; // ReSharper disable InconsistentNaming @@ -78,14 +85,44 @@ public SpecVersion(string version = null) Minor = minor; } + /// + /// Returns the string representation of the version in the format "major.minor". + /// + /// public override string ToString() => $"{Major}.{Minor}"; + /// + /// Returns true if the first version is less than the second version. + /// + /// First version + /// Second version + /// True if the first version is less than the second version public static bool operator <(SpecVersion a, SpecVersion b) => Compare(a, b) < 0; + + /// + /// Returns true if the first version is greater than the second version. + /// + /// First version + /// Second version + /// True if the first version is greater than the second version public static bool operator >(SpecVersion a, SpecVersion b) => Compare(a, b) > 0; + + /// + /// Returns true if the first version is less than or equal to the second version. + /// + /// First version + /// Second version + /// True if the first version is less than or equal to the second version public static bool operator <=(SpecVersion a, SpecVersion b) => Compare(a, b) <= 0; + + /// + /// Returns true if the first version is greater than or equal to the second version. + /// + /// First version + /// Second version + /// True if the first version is greater than or equal to the second version public static bool operator >=(SpecVersion a, SpecVersion b) => Compare(a, b) >= 0; - private static int Compare(SpecVersion a, SpecVersion b) { if (a.Major != b.Major) @@ -103,6 +140,10 @@ private static int Compare(SpecVersion a, SpecVersion b) [PublicAPI] public sealed class InvalidSpecVersionException : Exception { + /// + /// Creates a new InvalidSpecVersionException. + /// + /// Invalid version string public InvalidSpecVersionException(string version) : base($"Invalid spec version: {version}. The correct format is \"major.minor\".") { @@ -115,8 +156,15 @@ public InvalidSpecVersionException(string version) : [PublicAPI] public sealed class DeprecatedSwinfoPropertyException : Exception { + /// + /// Creates a new DeprecatedSwinfoPropertyException. + /// + /// Deprecated property name + /// Specification version in which the property was deprecated public DeprecatedSwinfoPropertyException(string property, SpecVersion deprecationVersion) : - base($"The swinfo.json property \"{property}\" is deprecated in the spec version {deprecationVersion} and will be removed completely in the future.") + base( + $"The swinfo.json property \"{property}\" is deprecated in the spec version {deprecationVersion} and will be removed completely in the future." + ) { } } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Mods/JSON/SupportedVersionsInfo.cs b/src/SpaceWarp.Core/API/Mods/JSON/SupportedVersionsInfo.cs index fb4e311..faca578 100644 --- a/src/SpaceWarp.Core/API/Mods/JSON/SupportedVersionsInfo.cs +++ b/src/SpaceWarp.Core/API/Mods/JSON/SupportedVersionsInfo.cs @@ -11,18 +11,40 @@ namespace SpaceWarp.API.Mods.JSON; [PublicAPI] public sealed class SupportedVersionsInfo { + /// + /// The default minimum version. + /// public const string DefaultMin = "0.0.0"; + + /// + /// The default maximum version. + /// public const string DefaultMax = "*"; + /// + /// The minimum supported version of KSP2. + /// [JsonProperty("min")] public string Min { get; internal set; } = DefaultMin; + /// + /// The maximum supported version of KSP2. + /// [JsonProperty("max")] public string Max { get; internal set; } = DefaultMax; + /// + /// Checks if the given version is supported by this mod. + /// + /// The version to check. + /// public bool IsSupported(string toCheck) { return VersionUtility.IsSupported(toCheck, Min, Max); } + /// + /// Returns a string representation of the version range. + /// + /// The string representation of the version range. public override string ToString() { return $"{Min} - {Max}"; diff --git a/src/SpaceWarp.Core/API/Mods/JSON/VersionCheckType.cs b/src/SpaceWarp.Core/API/Mods/JSON/VersionCheckType.cs index d6c0bb4..521287f 100644 --- a/src/SpaceWarp.Core/API/Mods/JSON/VersionCheckType.cs +++ b/src/SpaceWarp.Core/API/Mods/JSON/VersionCheckType.cs @@ -5,13 +5,22 @@ namespace SpaceWarp.API.Mods.JSON; +/// +/// The type of version checking to use. +/// [JsonConverter(typeof(StringEnumConverter))] [Obsolete("Only swinfo.json version checking will be allowed in 2.0.0.")] [PublicAPI] public enum VersionCheckType { + /// + /// Use the swinfo.json file to check for updates. + /// [EnumMember(Value = "swinfo")] SwInfo, + /// + /// Use the .csproj file to check for updates. + /// [EnumMember(Value = "csproj")] Csproj } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Mods/SpaceWarpErrorDescription.cs b/src/SpaceWarp.Core/API/Mods/SpaceWarpErrorDescription.cs index 6afadc3..eb5f425 100644 --- a/src/SpaceWarp.Core/API/Mods/SpaceWarpErrorDescription.cs +++ b/src/SpaceWarp.Core/API/Mods/SpaceWarpErrorDescription.cs @@ -4,22 +4,71 @@ namespace SpaceWarp.API.Mods; +/// +/// This class is used to describe the errors that occur when loading a plugin +/// [PublicAPI] public class SpaceWarpErrorDescription { + /// + /// The plugin that errored + /// public SpaceWarpPluginDescriptor Plugin; + + /// + /// Whether the plugin is missing a swinfo file + /// public bool MissingSwinfo; + + /// + /// Whether the plugin is in the wrong directory + /// public bool BadDirectory; + + /// + /// Whether the plugin has a bad ID + /// public bool BadID; + + /// + /// Whether there's a version mismatch between the swinfo and the plugin + /// public bool MismatchedVersion; + /// + /// List of dependencies that are disabled + /// public List DisabledDependencies = new(); + + /// + /// List of dependencies that errored + /// public List ErroredDependencies = new(); + + /// + /// List of dependencies that are missing + /// public List MissingDependencies = new(); + + /// + /// List of dependencies that are unsupported + /// public List UnsupportedDependencies = new(); + + /// + /// List of dependencies that are unspecified + /// public List UnspecifiedDependencies = new(); + + /// + /// List of incompatibilities + /// public List Incompatibilities = new(); + /// + /// Creates a new error description for a plugin + /// + /// The plugin that errored public SpaceWarpErrorDescription(SpaceWarpPluginDescriptor plugin) { Plugin = plugin; @@ -41,5 +90,4 @@ public SpaceWarpErrorDescription(SpaceWarpPluginDescriptor plugin) } plugin.Plugin = null; } - } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Mods/SpaceWarpPluginDescriptor.cs b/src/SpaceWarp.Core/API/Mods/SpaceWarpPluginDescriptor.cs index 1f2eca8..31e6b2e 100644 --- a/src/SpaceWarp.Core/API/Mods/SpaceWarpPluginDescriptor.cs +++ b/src/SpaceWarp.Core/API/Mods/SpaceWarpPluginDescriptor.cs @@ -4,9 +4,22 @@ namespace SpaceWarp.API.Mods; +/// +/// A descriptor for a SpaceWarp plugin. +/// [PublicAPI] public class SpaceWarpPluginDescriptor { + /// + /// Creates a new plugin descriptor. + /// + /// The plugin instance. + /// The plugin's GUID. + /// The plugin's name. + /// The plugin's swinfo. + /// The plugin's folder. + /// Whether or not to do loading actions. + /// The plugin's config file. public SpaceWarpPluginDescriptor( [CanBeNull] ISpaceWarpMod plugin, string guid, @@ -26,19 +39,53 @@ public SpaceWarpPluginDescriptor( ConfigFile = configFile; } + /// + /// The plugin instance. + /// [CanBeNull] public ISpaceWarpMod Plugin; + + /// + /// The plugin's GUID. + /// public readonly string Guid; + + /// + /// The plugin's name. + /// public readonly string Name; + + /// + /// The plugin's swinfo. + /// public readonly ModInfo SWInfo; + + /// + /// The plugin's folder. + /// public readonly DirectoryInfo Folder; + + /// + /// Whether or not to do loading actions. + /// public bool DoLoadingActions; + + /// + /// The plugin's config file. + /// [CanBeNull] public IConfigFile ConfigFile; - // Set by the version checking system + /// + /// Whether or not the plugin is outdated. Set by the version checking system. + /// public bool Outdated; - public bool Unsupported = false; + /// + /// Whether or not the plugin is unsupported. + /// + public bool Unsupported; - // Used to check for mods that have not been pre-initialized + /// + /// Whether or not the plugin has been pre-initialized yet. + /// public bool LatePreInitialize; } \ No newline at end of file From d4b3e0d56de200c644aee84632ccf28a91c85fa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 18:16:40 +0100 Subject: [PATCH 28/82] Fixed some more SpaceWarp.Core warnings --- src/SpaceWarp.Core/API/Parts/Colors.cs | 39 ++++++++++--------- .../API/Versions/VersionUtility.cs | 39 ++++++++++++------- 2 files changed, 46 insertions(+), 32 deletions(-) diff --git a/src/SpaceWarp.Core/API/Parts/Colors.cs b/src/SpaceWarp.Core/API/Parts/Colors.cs index 8bfa17e..7ad752e 100644 --- a/src/SpaceWarp.Core/API/Parts/Colors.cs +++ b/src/SpaceWarp.Core/API/Parts/Colors.cs @@ -5,45 +5,48 @@ namespace SpaceWarp.API.Parts; +/// +/// API for allowing modded parts to be colored. +/// [SpaceWarpLuaAPI("Colors")] [PublicAPI] public static class Colors { /// - /// Key is ModGUID. - /// Value is list of strings containing the partNames. - /// Only parts in this list will be modified. + /// Key is ModGUID. + /// Value is list of strings containing the partNames. + /// Only parts in this list will be modified. /// - [Obsolete("Use the shader \"KSP2/Parts/Paintable\" or \"Parts Replace\" instead")] + [Obsolete("Use the shader \"KSP2/Parts/Paintable\" or \"Parts Replace\" instead. Will be removed in 2.0.0.")] public static Dictionary DeclaredParts => new(); /// - /// Adds to internal parts list under - /// allowing them to have the patch applied. + /// Adds to internal parts list under + /// allowing them to have the patch applied. /// /// guid of the mod that owns the parts. /// - /// Collection of partNames. Names that end in XS, S, M, L or XL will be counted as the same - /// part, - /// Example: partNameS, partNameM, partNameL, partNameXL are all treated as partName + /// Collection of partNames. Names that end in XS, S, M, L or XL will be counted as the same + /// part, + /// Example: partNameS, partNameM, partNameL, partNameXL are all treated as partName /// - [Obsolete("Use the shader \"KSP2/Parts/Paintable\" or \"Parts Replace\" instead")] + [Obsolete("Use the shader \"KSP2/Parts/Paintable\" or \"Parts Replace\" instead. Will be removed in 2.0.0.")] public static void DeclareParts(string modGuid, params string[] partNameList) { ColorsPatch.DeclareParts(modGuid, partNameList); } /// - /// Adds to internal parts list under - /// allowing them to have the patch applied. + /// Adds to internal parts list under + /// allowing them to have the patch applied. /// /// guid of the mod that owns the parts. /// - /// Collection of partNames. Names that end in XS, S, M, L or XL will be counted as the same - /// part. - /// Example: partNameS, partNameM, partNameL, partNameXL are all treated as partName + /// Collection of partNames. Names that end in XS, S, M, L or XL will be counted as the same + /// part. + /// Example: partNameS, partNameM, partNameL, partNameXL are all treated as partName /// - [Obsolete("Use the shader \"KSP2/Parts/Paintable\" or \"Parts Replace\" instead")] + [Obsolete("Use the shader \"KSP2/Parts/Paintable\" or \"Parts Replace\" instead. Will be removed in 2.0.0.")] public static void DeclareParts(string modGuid, IEnumerable partNameList) { ColorsPatch.DeclareParts(modGuid, partNameList); @@ -52,7 +55,7 @@ public static void DeclareParts(string modGuid, IEnumerable partNameList /// Retrieves all the texture list from your part. Textures not set will be null. /// /// Name of the part as described in the .json. - /// - [Obsolete("Use the shader \"KSP2/Parts/Paintable\" or \"Parts Replace\" instead")] + /// Array of textures. + [Obsolete("Use the shader \"KSP2/Parts/Paintable\" or \"Parts Replace\" instead. Will be removed in 2.0.0.")] public static Texture[] GetTextures(string partName) => Array.Empty(); } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/Versions/VersionUtility.cs b/src/SpaceWarp.Core/API/Versions/VersionUtility.cs index dc0b092..dfe0e77 100644 --- a/src/SpaceWarp.Core/API/Versions/VersionUtility.cs +++ b/src/SpaceWarp.Core/API/Versions/VersionUtility.cs @@ -3,6 +3,9 @@ namespace SpaceWarp.API.Versions; +/// +/// Utility class for comparing semantic versions +/// [PublicAPI] public static class VersionUtility { @@ -28,6 +31,13 @@ public static bool IsOlderThan(string version1, string version2) return CompareSemanticVersionStrings(version1, version2) < 0; } + /// + /// Checks if a semantic version is supported by a range of versions + /// + /// The version to check + /// The minimum version + /// The maximum version + /// public static bool IsSupported(string version, string min, string max) { return !IsOlderThan(version, min) && !IsNewerThan(version, max); @@ -119,7 +129,7 @@ private static int ComparePrereleaseSemanticVersions(string version1, string ver alphaVersionNumber1 = int.Parse(number.Value); alphaVersionName1 = name.Value; } - + if (_prereleaseVersion.IsMatch(alphaVersion2)) { var match = _prereleaseVersion.Match(alphaVersion2); @@ -130,20 +140,21 @@ private static int ComparePrereleaseSemanticVersions(string version1, string ver } var comparison = string.CompareOrdinal(alphaVersionName1, alphaVersionName2); - if (comparison == 0) + if (comparison != 0) { - if (alphaVersionNumber1 > alphaVersionNumber2) - { - return 1; - } else if (alphaVersionNumber1 == alphaVersionNumber2) - { - return 0; - } - else - { - return -1; - } + return comparison; } - return comparison; + + if (alphaVersionNumber1 > alphaVersionNumber2) + { + return 1; + } + + if (alphaVersionNumber1 == alphaVersionNumber2) + { + return 0; + } + + return -1; } } \ No newline at end of file From 3ce2765cdb1e9850c6b8d29b62cdd9d360deb10f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 18:17:40 +0100 Subject: [PATCH 29/82] Fixed SpaceWarp.Backend warnings --- .../Backend/Modding/BepInExModAdapter.cs | 4 ++- .../Backend/Modding/Ksp2ModInfo.cs | 36 +++++++++++-------- .../Backend/SaveGameManager/PluginSaveData.cs | 15 +++++++- .../SpaceWarpSerializedSavedGame.cs | 4 +++ 4 files changed, 42 insertions(+), 17 deletions(-) diff --git a/src/SpaceWarp.Core/Backend/Modding/BepInExModAdapter.cs b/src/SpaceWarp.Core/Backend/Modding/BepInExModAdapter.cs index 84f61bd..4411763 100644 --- a/src/SpaceWarp.Core/Backend/Modding/BepInExModAdapter.cs +++ b/src/SpaceWarp.Core/Backend/Modding/BepInExModAdapter.cs @@ -5,14 +5,16 @@ namespace SpaceWarp.Backend.Modding; -public class BepInExModAdapter : ISpaceWarpMod +internal class BepInExModAdapter : ISpaceWarpMod { public readonly BaseUnityPlugin Plugin; + /// public void OnPreInitialized() { } + /// public void OnInitialized() { } diff --git a/src/SpaceWarp.Core/Backend/Modding/Ksp2ModInfo.cs b/src/SpaceWarp.Core/Backend/Modding/Ksp2ModInfo.cs index fd1732d..25610c2 100644 --- a/src/SpaceWarp.Core/Backend/Modding/Ksp2ModInfo.cs +++ b/src/SpaceWarp.Core/Backend/Modding/Ksp2ModInfo.cs @@ -3,40 +3,46 @@ namespace SpaceWarp.Backend.Modding; +/// +/// Represents the KSP2 mod info file used by the internal loader. +/// public class Ksp2ModInfo { + /// + /// The API version of the mod. + /// [JsonConverter(typeof(VersionConverter))] [JsonProperty] public Version APIVersion { get; private set; } - // Token: 0x17001C93 RID: 7315 - // (get) Token: 0x06008070 RID: 32880 RVA: 0x001EE0B9 File Offset: 0x001EC2B9 - // (set) Token: 0x06008071 RID: 32881 RVA: 0x001EE0C1 File Offset: 0x001EC2C1 + /// + /// The version of the mod. + /// [JsonConverter(typeof(VersionConverter))] [JsonProperty] public Version ModVersion { get; private set; } - // Token: 0x17001C94 RID: 7316 - // (get) Token: 0x06008072 RID: 32882 RVA: 0x001EE0CA File Offset: 0x001EC2CA - // (set) Token: 0x06008073 RID: 32883 RVA: 0x001EE0D2 File Offset: 0x001EC2D2 + /// + /// The name of the mod. + /// [JsonProperty] public string ModName { get; private set; } - // Token: 0x17001C95 RID: 7317 - // (get) Token: 0x06008074 RID: 32884 RVA: 0x001EE0DB File Offset: 0x001EC2DB - // (set) Token: 0x06008075 RID: 32885 RVA: 0x001EE0E3 File Offset: 0x001EC2E3 + /// + /// The author of the mod. + /// [JsonProperty] public string ModAuthor { get; private set; } - // Token: 0x17001C96 RID: 7318 - // (get) Token: 0x06008076 RID: 32886 RVA: 0x001EE0EC File Offset: 0x001EC2EC - // (set) Token: 0x06008077 RID: 32887 RVA: 0x001EE0F4 File Offset: 0x001EC2F4 + /// + /// The description of the mod. + /// [JsonProperty] public string ModDescription { get; private set; } - // Token: 0x17001C97 RID: 7319 - // (get) Token: 0x06008078 RID: 32888 RVA: 0x001EE0FD File Offset: 0x001EC2FD - // (set) Token: 0x06008079 RID: 32889 RVA: 0x001EE105 File Offset: 0x001EC305 + /// + /// The addressables catalog file of the mod. + /// [JsonProperty] public string Catalog { get; private set; } } \ No newline at end of file diff --git a/src/SpaceWarp.Core/Backend/SaveGameManager/PluginSaveData.cs b/src/SpaceWarp.Core/Backend/SaveGameManager/PluginSaveData.cs index a439d08..42796b3 100644 --- a/src/SpaceWarp.Core/Backend/SaveGameManager/PluginSaveData.cs +++ b/src/SpaceWarp.Core/Backend/SaveGameManager/PluginSaveData.cs @@ -1,11 +1,24 @@ namespace SpaceWarp.Backend.SaveGameManager; -internal delegate void SaveGameCallbackFunctionDelegate(object data); +/// +/// The delegate type that will be called when a save or load event is triggered. +/// +public delegate void SaveGameCallbackFunctionDelegate(object data); +/// +/// This class is used to store your mod data for saving and loading. +/// [Serializable] public class PluginSaveData { + /// + /// The GUID of your mod + /// public string ModGuid { get; set; } + + /// + /// The data that will be saved + /// public object SaveData { get; set; } [NonSerialized] diff --git a/src/SpaceWarp.Core/Backend/SaveGameManager/SpaceWarpSerializedSavedGame.cs b/src/SpaceWarp.Core/Backend/SaveGameManager/SpaceWarpSerializedSavedGame.cs index e5501d7..5315f77 100644 --- a/src/SpaceWarp.Core/Backend/SaveGameManager/SpaceWarpSerializedSavedGame.cs +++ b/src/SpaceWarp.Core/Backend/SaveGameManager/SpaceWarpSerializedSavedGame.cs @@ -6,5 +6,9 @@ [Serializable] public class SpaceWarpSerializedSavedGame : KSP.Sim.SerializedSavedGame { + /// + /// List of serialized plugin save data + /// + // ReSharper disable once InconsistentNaming public List serializedPluginSaveData = new(); } From 151ccb707e5ab5aafcc89a8773169aaeef03cb95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 18:18:17 +0100 Subject: [PATCH 30/82] Fixed SpaceWarpPlugin warnings --- src/SpaceWarp.Core/SpaceWarpPlugin.cs | 48 ++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/src/SpaceWarp.Core/SpaceWarpPlugin.cs b/src/SpaceWarp.Core/SpaceWarpPlugin.cs index aa50e7b..43bf28b 100644 --- a/src/SpaceWarp.Core/SpaceWarpPlugin.cs +++ b/src/SpaceWarp.Core/SpaceWarpPlugin.cs @@ -19,27 +19,48 @@ namespace SpaceWarp; +/// +/// The main SpaceWarp plugin class. +/// [BepInDependency("com.bepis.bepinex.configurationmanager", "17.1")] [BepInDependency(UitkForKsp2Plugin.ModGuid, UitkForKsp2Plugin.ModVer)] [BepInIncompatibility("com.shadow.quantum")] [BepInPlugin(ModGuid, ModName, ModVer)] public sealed class SpaceWarpPlugin : BaseSpaceWarpPlugin { + /// + /// SpaceWarp plugin instance. + /// public static SpaceWarpPlugin Instance; + /// + /// The GUID of the SpaceWarp plugin. + /// [PublicAPI] public const string ModGuid = MyPluginInfo.PLUGIN_GUID; + + /// + /// The name of the SpaceWarp plugin. + /// [PublicAPI] public const string ModName = MyPluginInfo.PLUGIN_NAME; + + /// + /// The version of the SpaceWarp plugin. + /// [PublicAPI] public const string ModVer = MyPluginInfo.PLUGIN_VERSION; internal ScriptEnvironment GlobalLuaState; internal new static ManualLogSource Logger; + /// + /// Initializes a new instance of the class. + /// public SpaceWarpPlugin() { // Load the type forwarders Assembly.LoadFile( - $"{new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName}\\SpaceWarp.dll"); + $"{new FileInfo(Assembly.GetExecutingAssembly().Location).Directory!.FullName}\\SpaceWarp.dll" + ); Logger = base.Logger; Instance = this; } @@ -54,7 +75,8 @@ private static void OnLanguageSourceAssetLoaded(LanguageSourceAsset asset) asset.mSource.owner = asset; LocalizationManager.AddSource(asset.mSource); } - public void Awake() + + private void Awake() { BepInEx.Bootstrap.Chainloader.ManagerObject.Persist(); // IOProvider.Init(); @@ -62,9 +84,22 @@ public void Awake() Harmony.CreateAndPatchAll(typeof(SpaceWarpPlugin).Assembly, ModGuid); ModuleManager.LoadAllModules(); - Loading.AddAssetLoadingAction("bundles", "loading asset bundles", FunctionalLoadingActions.AssetBundleLoadingAction, "bundle"); - Loading.AddAssetLoadingAction("images", "loading images", FunctionalLoadingActions.ImageLoadingAction); - Loading.AddAddressablesLoadingAction("localization","language_source",OnLanguageSourceAssetLoaded); + Loading.AddAssetLoadingAction( + "bundles", + "loading asset bundles", + FunctionalLoadingActions.AssetBundleLoadingAction, + "bundle" + ); + Loading.AddAssetLoadingAction( + "images", + "loading images", + FunctionalLoadingActions.ImageLoadingAction + ); + Loading.AddAddressablesLoadingAction( + "localization", + "language_source", + OnLanguageSourceAssetLoaded + ); } private void SetupLuaState() @@ -98,12 +133,14 @@ private void UpdateLanguagesDropdown() Game.SettingsMenuManager._generalSettings.InitializeLanguageDropdown(); } + /// public override void OnPreInitialized() { // Persist all game objects so I don't need to stomp on config ModuleManager.PreInitializeAllModules(); } + /// public override void OnInitialized() { ModuleManager.InitializeAllModules(); @@ -111,6 +148,7 @@ public override void OnInitialized() UpdateLanguagesDropdown(); } + /// public override void OnPostInitialized() { ModuleManager.PostInitializeAllModules(); From c13d602b59db276bd2cbaae136e663348d2e2190 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 18:18:43 +0100 Subject: [PATCH 31/82] PluginRegister refactoring --- .../Backend/Modding/PluginRegister.cs | 148 +++++++++++++----- 1 file changed, 106 insertions(+), 42 deletions(-) diff --git a/src/SpaceWarp.Core/Backend/Modding/PluginRegister.cs b/src/SpaceWarp.Core/Backend/Modding/PluginRegister.cs index 6b1b2aa..d85533c 100644 --- a/src/SpaceWarp.Core/Backend/Modding/PluginRegister.cs +++ b/src/SpaceWarp.Core/Backend/Modding/PluginRegister.cs @@ -23,7 +23,7 @@ public static void RegisterAllMods() DisableMods(); } - private static ILogger Logger = (BepInExLogger)SpaceWarpPlugin.Logger; + private static readonly ILogger Logger = (BepInExLogger)SpaceWarpPlugin.Logger; private static ModInfo BepInExToSWInfo(PluginInfo plugin) { @@ -51,7 +51,6 @@ private static ModInfo BepInExToSWInfo(PluginInfo plugin) Max = "*" }, VersionCheck = null, - VersionCheckType = VersionCheckType.SwInfo, Conflicts = plugin.Incompatibilities.Select(x => new DependencyInfo { ID = x.IncompatibilityGUID, @@ -70,7 +69,9 @@ private static bool AssertFolderPath(BaseSpaceWarpPlugin plugin, string folderPa if (Path.GetFileName(folderPath) != "plugins") return true; Logger.LogError( - $"Found Space Warp mod {plugin.Info.Metadata.Name} in the BepInEx/plugins directory. This mod will not be initialized."); + $"Found Space Warp mod {plugin.Info.Metadata.Name} in the BepInEx/plugins directory. This mod will " + + $"not be initialized." + ); var descriptor = new SpaceWarpPluginDescriptor( plugin, @@ -82,25 +83,38 @@ private static bool AssertFolderPath(BaseSpaceWarpPlugin plugin, string folderPa new BepInExConfigFile(plugin.Config) ); PluginList.NoteBadDirectoryError(descriptor); + return false; } private static bool AssertModInfoExistence(BaseSpaceWarpPlugin plugin, string modInfoPath, string folderPath) { - if (File.Exists(modInfoPath)) return true; + if (File.Exists(modInfoPath)) + { + return true; + } Logger.LogError( - $"Found Space Warp plugin {plugin.Info.Metadata.Name} without a swinfo.json next to it. This mod will not be initialized."); + $"Found Space Warp plugin {plugin.Info.Metadata.Name} without a swinfo.json in its folder. This mod " + + $"will not be initialized." + ); + PluginList.NoteMissingSwinfoError(new SpaceWarpPluginDescriptor(plugin, plugin.Info.Metadata.GUID, plugin.Info.Metadata.Name, BepInExToSWInfo(plugin.Info), - new DirectoryInfo(folderPath))); + new DirectoryInfo(folderPath)) + ); + return false; } - private static bool TryReadModInfo(BaseUnityPlugin plugin, - string modInfoPath, string folderPath, out ModInfo metadata) + private static bool TryReadModInfo( + BaseUnityPlugin plugin, + string modInfoPath, + string folderPath, + out ModInfo metadata + ) { try { @@ -127,22 +141,19 @@ private static bool TryReadModInfo(BaseUnityPlugin plugin, private static bool AssertSpecificationCompliance( SpaceWarpPluginDescriptor descriptor, BaseUnityPlugin plugin, - ModInfo metadata, - string folderPath + ModInfo metadata ) => metadata.Spec < SpecVersion.V1_3 || AssertSpecVersion13Compliance( descriptor, plugin, - metadata, - folderPath + metadata ); private static bool AssertSpecVersion13Compliance( SpaceWarpPluginDescriptor descriptor, BaseUnityPlugin plugin, - ModInfo metadata, - string folderPath - ) => AssertMatchingModID(descriptor, plugin, metadata, folderPath) && - AssertMatchingVersions(descriptor, plugin, metadata, folderPath) && + ModInfo metadata + ) => AssertMatchingModID(descriptor, plugin, metadata) && + AssertMatchingVersions(descriptor, plugin, metadata) && AssertAllDependenciesAreSpecified(descriptor, plugin, metadata); private static bool AssertAllDependenciesAreSpecified( @@ -161,12 +172,19 @@ private static bool AssertDependencyIsSpecified( ModInfo metadata ) { - if (metadata.Dependencies.Any( - x => string.Equals(x.ID, dep.DependencyGUID, StringComparison.InvariantCultureIgnoreCase)) - ) return true; + if (metadata.Dependencies.Any(x => string.Equals( + x.ID, + dep.DependencyGUID, + StringComparison.InvariantCultureIgnoreCase + ))) + { + return true; + } Logger.LogError( - $"Found Space Warp Plugin {plugin.Info.Metadata.Name} that has an unspecified swinfo dependency found in its BepInDependencies: {dep.DependencyGUID}"); + $"Found Space Warp Plugin {plugin.Info.Metadata.Name} that has an unspecified swinfo dependency found " + + $"in its BepInDependencies: {dep.DependencyGUID}" + ); PluginList.NoteUnspecifiedDependencyError(descriptor, dep.DependencyGUID); metadata.Dependencies.Add(new DependencyInfo { @@ -183,21 +201,22 @@ ModInfo metadata private static string ClearPrerelease(string version) { var semver = new SemanticVersion(version); - return - $"{semver.Major}.{semver.Minor}.{semver.Patch}{(semver.VersionNumbers.Count > 3 ? $".{semver.VersionNumbers[3]}" : "")}"; + return $"{semver.Major}.{semver.Minor}.{semver.Patch}" + + $"{(semver.VersionNumbers.Count > 3 ? $".{semver.VersionNumbers[3]}" : "")}"; } private static bool AssertMatchingVersions( SpaceWarpPluginDescriptor descriptor, BaseUnityPlugin plugin, - ModInfo metadata, - string folderPath + ModInfo metadata ) { if (new Version(ClearPrerelease(metadata.Version)) == plugin.Info.Metadata.Version) return true; Logger.LogError( - $"Found Space Warp plugin {plugin.Info.Metadata.Name} that's swinfo version ({metadata.Version}) does not match the plugin version ({plugin.Info.Metadata.Version}), this mod will not be initialized"); + $"Found Space Warp plugin {plugin.Info.Metadata.Name} that's swinfo version ({metadata.Version}) does " + + $"not match the plugin version ({plugin.Info.Metadata.Version}), this mod will not be initialized" + ); PluginList.NoteMismatchedVersionError(descriptor); return false; } @@ -205,15 +224,16 @@ string folderPath private static bool AssertMatchingModID( SpaceWarpPluginDescriptor descriptor, BaseUnityPlugin plugin, - ModInfo metadata, - string folderPath + ModInfo metadata ) { var modID = metadata.ModID; if (modID == plugin.Info.Metadata.GUID) return true; Logger.LogError( - $"Found Space Warp plugin {plugin.Info.Metadata.Name} that has an swinfo.json w/ spec version >= 1.3 that's ModID is not the same as the plugins GUID, This mod will not be initialized."); + $"Found SpaceWarp plugin {plugin.Info.Metadata.Name} that has a swinfo.json file with spec version >=" + + $" 1.3 whose ModID is not the same as the plugin's GUID. This mod will not be initialized." + ); PluginList.NoteBadIDError(descriptor); return false; } @@ -221,16 +241,34 @@ string folderPath private static void RegisterSingleSpaceWarpPlugin(BaseSpaceWarpPlugin plugin) { var folderPath = Path.GetDirectoryName(plugin.Info.Location); + +#pragma warning disable CS0618 // Type or member is obsolete + // TODO: Remove this in 2.0 plugin.PluginFolderPath = folderPath; - if (!AssertFolderPath(plugin, folderPath)) return; +#pragma warning restore CS0618 // Type or member is obsolete + + if (!AssertFolderPath(plugin, folderPath)) + { + return; + } var modInfoPath = Path.Combine(folderPath!, "swinfo.json"); - if (!AssertModInfoExistence(plugin, modInfoPath, folderPath)) return; + if (!AssertModInfoExistence(plugin, modInfoPath, folderPath)) + { + return; + } - if (!TryReadModInfo(plugin, modInfoPath, folderPath, out var metadata)) return; + if (!TryReadModInfo(plugin, modInfoPath, folderPath, out var metadata)) + { + return; + } +#pragma warning disable CS0618 // Type or member is obsolete + // TODO: Remove this in 2.0 plugin.SpaceWarpMetadata = metadata; +#pragma warning restore CS0618 // Type or member is obsolete + var directoryInfo = new FileInfo(modInfoPath).Directory; var descriptor = new SpaceWarpPluginDescriptor( plugin, @@ -242,7 +280,10 @@ private static void RegisterSingleSpaceWarpPlugin(BaseSpaceWarpPlugin plugin) new BepInExConfigFile(plugin.Config) ); descriptor.Plugin!.SWMetadata = descriptor; - if (!AssertSpecificationCompliance(descriptor, plugin, metadata, folderPath)) return; + if (!AssertSpecificationCompliance(descriptor, plugin, metadata)) + { + return; + } PluginList.RegisterPlugin(descriptor); } @@ -259,7 +300,11 @@ private static void RegisterSingleBepInExPlugin(BaseUnityPlugin plugin) var directoryInfo = new DirectoryInfo(Path.GetDirectoryName(plugin.Info.Location)!); if (File.Exists(modInfoPath)) { - if (!TryReadModInfo(plugin, modInfoPath, folderPath, out var metadata)) return; + if (!TryReadModInfo(plugin, modInfoPath, folderPath, out var metadata)) + { + return; + } + var descriptor = new SpaceWarpPluginDescriptor( new BepInExModAdapter(plugin), metadata.Spec != SpecVersion.V1_2 ? metadata.ModID : plugin.Info.Metadata.GUID, @@ -270,8 +315,11 @@ private static void RegisterSingleBepInExPlugin(BaseUnityPlugin plugin) new BepInExConfigFile(plugin.Config) ); descriptor.Plugin!.SWMetadata = descriptor; - if (!AssertSpecificationCompliance(descriptor, plugin, metadata, folderPath)) + if (!AssertSpecificationCompliance(descriptor, plugin, metadata)) + { return; + } + PluginList.RegisterPlugin(descriptor); } else @@ -293,6 +341,7 @@ private static SpaceWarpPluginDescriptor GetBepInExDescriptor(BaseUnityPlugin pl new BepInExConfigFile(plugin.Config) ); pluginAdapter.SWMetadata = descriptor; + return descriptor; } @@ -342,7 +391,9 @@ private static void RegisterAllCodelessMods() if (swinfoData.Spec < SpecVersion.V1_3) { Logger.LogWarning( - $"Found swinfo information for: {swinfoData.Name}, but its spec is less than v1.3, if this describes a \"codeless\" mod, it will be ignored"); + $"Found swinfo information for: {swinfoData.Name}, but its spec is less than 1.3, if this " + + $"describes a \"codeless\" mod, it will be ignored" + ); continue; } @@ -360,7 +411,10 @@ private static void RegisterAllCodelessMods() if (PluginList.AllPlugins.Any( x => string.Equals(x.Guid, swinfoData.ModID, StringComparison.InvariantCultureIgnoreCase) - )) continue; + )) + { + continue; + } // Now we can just add it to our plugin list PluginList.RegisterPlugin(descriptor); @@ -390,8 +444,7 @@ private static ModInfo KspToSwinfo(Ksp2ModInfo mod) Min = "*", Max = "*" }, - VersionCheck = null, - VersionCheckType = VersionCheckType.SwInfo + VersionCheck = null }; return newInfo; } @@ -412,7 +465,10 @@ private static void RegisterSingleKspMod(DirectoryInfo folder) ); metadata = KspToSwinfo(modinfo); } - else return; + else + { + return; + } // This descriptor *will* be modified later var descriptor = new SpaceWarpPluginDescriptor( @@ -432,9 +488,14 @@ private static void RegisterSingleKspMod(DirectoryInfo folder) private static void RegisterAllKspMods() { var pluginPath = new DirectoryInfo(Path.Combine(Paths.GameRootPath, "GameData", "Mods")); - if (!pluginPath.Exists) return; + if (!pluginPath.Exists) + { + return; + } + Logger.LogInfo($"KSP Loaded mods path: {pluginPath.FullName}"); - // Lets quickly register every KSP loader loaded mod into the load order before anything, with late pre-initialize + // Let's quickly register every mod loaded with the internal loader into the load order before anything else, + // with late pre-initialize foreach (var plugin in pluginPath.EnumerateDirectories()) { Logger.LogInfo($"Attempting to register KSP loaded mod at {pluginPath.FullName}"); @@ -461,7 +522,10 @@ private static void RegisterAllErroredMods() (x.Plugin is BaseUnityPlugin baseUnityPlugin && string.Equals( baseUnityPlugin.Info.Metadata.GUID, info.Metadata.GUID, StringComparison.InvariantCultureIgnoreCase)) - )) continue; + )) + { + continue; + } var descriptor = new SpaceWarpPluginDescriptor( null, From 48a389bb18d2d307f7a2e09b4fa7b4d12009516a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 18:29:54 +0100 Subject: [PATCH 32/82] SpaceWarp.API refactoring --- .../API/Parts/PartComponentModuleOverride.cs | 20 +++-- .../API/SaveGameManager/ModSaves.cs | 87 ++++++++++++++----- 2 files changed, 78 insertions(+), 29 deletions(-) diff --git a/src/SpaceWarp.Core/API/Parts/PartComponentModuleOverride.cs b/src/SpaceWarp.Core/API/Parts/PartComponentModuleOverride.cs index 5cfb02d..8011535 100644 --- a/src/SpaceWarp.Core/API/Parts/PartComponentModuleOverride.cs +++ b/src/SpaceWarp.Core/API/Parts/PartComponentModuleOverride.cs @@ -1,14 +1,14 @@ using JetBrains.Annotations; using KSP.Sim.impl; -using SpaceWarp.API.Logging; namespace SpaceWarp.API.Parts; +/// +/// This class allows you to register your custom PartComponentModule for background resource processing. +/// [PublicAPI] public static class PartComponentModuleOverride { - private static readonly ILogger _LOGGER = new UnityLogSource("SpaceWarp.PartComponentModuleOverride"); - internal static List RegisteredPartComponentOverrides = new(); /// @@ -22,11 +22,14 @@ public static void RegisterModuleForBackgroundResourceProcessing() where T : // Check if this Module is already registered if (RegisteredPartComponentOverrides.Contains(typeof(T))) { - throw new ArgumentException($"Module '{moduleName}' is already registered. Skipping.", nameof(T)); + throw new ArgumentException( + $"Background resource processing for module '{moduleName}' is already registered. Skipping.", + nameof(T) + ); } RegisteredPartComponentOverrides.Add(typeof(T)); - _LOGGER.LogInfo($"Registered '{moduleName}' for background resources processing."); + SpaceWarpPlugin.Logger.LogInfo($"Registered '{moduleName}' for background resources processing."); } /// @@ -35,9 +38,12 @@ public static void RegisterModuleForBackgroundResourceProcessing() where T : /// Your Custom Module class that inherits from PartComponentModule public static void UnRegisterModuleForBackgroundResourceProcessing() where T : PartComponentModule { - if (!RegisteredPartComponentOverrides.Contains(typeof(T))) return; + if (!RegisteredPartComponentOverrides.Contains(typeof(T))) + { + return; + } RegisteredPartComponentOverrides.Remove(typeof(T)); - _LOGGER.LogInfo($"Unregistered '{typeof(T).Name}' from background resources processing."); + SpaceWarpPlugin.Logger.LogInfo($"Unregistered '{typeof(T).Name}' from background resources processing."); } } \ No newline at end of file diff --git a/src/SpaceWarp.Core/API/SaveGameManager/ModSaves.cs b/src/SpaceWarp.Core/API/SaveGameManager/ModSaves.cs index d1204c2..ddcbace 100644 --- a/src/SpaceWarp.Core/API/SaveGameManager/ModSaves.cs +++ b/src/SpaceWarp.Core/API/SaveGameManager/ModSaves.cs @@ -1,26 +1,43 @@ using JetBrains.Annotations; using SpaceWarp.Backend.SaveGameManager; -using SpaceWarp.API.Logging; namespace SpaceWarp.API.SaveGameManager; +/// +/// This class allows you to register your mod data for the game's save file system . +/// [PublicAPI] public static class ModSaves { - private static readonly ILogger Logger = new UnityLogSource("SpaceWarp.ModSaves"); - internal static List InternalPluginSaveData = new(); /// /// Registers your mod data for saving and loading events. /// /// Any object - /// Your mod GUID. Or, technically, any kind of string can be passed here, but what is mandatory is that it's unique compared to what other mods will use. - /// Function that will execute when a SAVE event is triggered. Defaults to null or no callback. - /// Function that will execute when a LOAD event is triggered. Defaults to null or no callback. - /// Your object that will be saved to a save file during a save event and that will be updated when a load event pulls new data. Ensure that a new instance of this object is NOT created after registration. - /// T saveData object you passed as a parameter, or a default instance of object T if you didn't pass anything - public static T RegisterSaveLoadGameData(string modGuid, Action onSave = null, Action onLoad = null, T saveData = default) where T : class + /// + /// Your mod GUID. Or, technically, any kind of string can be passed here, but what is mandatory is that it's unique + /// compared to what other mods will use. + /// + /// + /// Function that will execute when a SAVE event is triggered. Defaults to null or no callback. + /// + /// + /// Function that will execute when a LOAD event is triggered. Defaults to null or no callback. + /// + /// + /// Your object that will be saved to a save file during a save event and that will be updated when a load event + /// pulls new data. Ensure that a new instance of this object is NOT created after registration. + /// + /// + /// T saveData object you passed as a parameter, or a default instance of object T if you didn't pass anything + /// + public static T RegisterSaveLoadGameData( + string modGuid, + Action onSave = null, + Action onLoad = null, + T saveData = default + ) where T : class { // Check if this GUID is already registered if (InternalPluginSaveData.Find(p => p.ModGuid == modGuid) != null) @@ -30,10 +47,18 @@ public static T RegisterSaveLoadGameData(string modGuid, Action onSave = n saveData ??= Activator.CreateInstance(); - InternalPluginSaveData.Add(new PluginSaveData { ModGuid = modGuid, SaveEventCallback = SaveCallbackAdapter, LoadEventCallback = LoadCallbackAdapter, SaveData = saveData }); - Logger.LogInfo($"Registered '{modGuid}' for save/load events."); + InternalPluginSaveData.Add(new PluginSaveData + { + ModGuid = modGuid, + SaveEventCallback = SaveCallbackAdapter, + LoadEventCallback = LoadCallbackAdapter, + SaveData = saveData + }); + SpaceWarpPlugin.Logger.LogInfo($"Registered '{modGuid}' for save/load events."); return saveData; + // Create adapter functions to convert Action to CallbackFunctionDelegate + void LoadCallbackAdapter(object dataToBeLoaded) { if (onLoad != null && dataToBeLoaded is T data) @@ -42,7 +67,6 @@ void LoadCallbackAdapter(object dataToBeLoaded) } } - // Create adapter functions to convert Action to CallbackFunctionDelegate void SaveCallbackAdapter(object dataToBeSaved) { if (onSave != null && dataToBeSaved is T data) @@ -53,7 +77,8 @@ void SaveCallbackAdapter(object dataToBeSaved) } /// - /// Unregister your previously registered mod data for saving and loading. Use this if you no longer need your data to be saved and loaded. + /// Unregister your previously registered mod data for saving and loading. Use this if you no longer need your data + /// to be saved and loaded. /// /// Your mod GUID you used when registering. public static void UnRegisterSaveLoadGameData(string modGuid) @@ -61,21 +86,39 @@ public static void UnRegisterSaveLoadGameData(string modGuid) var toRemove = InternalPluginSaveData.Find(p => p.ModGuid == modGuid); if (toRemove == null) return; InternalPluginSaveData.Remove(toRemove); - Logger.LogInfo($"Unregistered '{modGuid}' for save/load events."); + SpaceWarpPlugin.Logger.LogInfo($"Unregistered '{modGuid}' for save/load events."); } /// /// Unregisters then again registers your mod data for saving and loading events /// - /// Any object - /// Your mod GUID. Or, technically, any kind of string can be passed here, but what is mandatory is that it's unique compared to what other mods will use. - /// Function that will execute when a SAVE event is triggered. Defaults to null or no callback. - /// Function that will execute when a LOAD event is triggered. Defaults to null or no callback. - /// Your object that will be saved to a save file during a save event and that will be updated when a load event pulls new data. Ensure that a new instance of this object is NOT created after registration. - /// T saveData object you passed as a parameter, or a default instance of object T if you didn't pass anything - public static T ReregisterSaveLoadGameData(string modGuid, Action onSave = null, Action onLoad = null, T saveData = default(T)) where T : class + /// The type of your save data + /// + /// Your mod GUID. Or, technically, any kind of string can be passed here, but what is mandatory is that it's unique + /// compared to what other mods will use. + /// + /// + /// Function that will execute when a SAVE event is triggered. Defaults to null or no callback. + /// + /// + /// Function that will execute when a LOAD event is triggered. Defaults to null or no callback. + /// + /// + /// Your object that will be saved to a save file during a save event and that will be + /// updated when a load event pulls new data. Ensure that a new instance of this object is NOT created after + /// registration. + /// + /// + /// T saveData object you passed as a parameter, or a default instance of object T if you didn't pass anything + /// + public static T ReregisterSaveLoadGameData( + string modGuid, + Action onSave = null, + Action onLoad = null, + T saveData = default + ) where T : class { UnRegisterSaveLoadGameData(modGuid); return RegisterSaveLoadGameData(modGuid, onSave, onLoad, saveData); } -} +} \ No newline at end of file From 1e1bcfcbf5b9f3817fddaf664894bd656ffec085 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 18:36:31 +0100 Subject: [PATCH 33/82] Fixed SpaceWarp.Modules warnings --- src/SpaceWarp.Core/Modules/ModuleManager.cs | 9 ++++ src/SpaceWarp.Core/Modules/SpaceWarpModule.cs | 44 +++++++++++++++---- 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/src/SpaceWarp.Core/Modules/ModuleManager.cs b/src/SpaceWarp.Core/Modules/ModuleManager.cs index 0b7a843..0bd8564 100644 --- a/src/SpaceWarp.Core/Modules/ModuleManager.cs +++ b/src/SpaceWarp.Core/Modules/ModuleManager.cs @@ -6,11 +6,20 @@ namespace SpaceWarp.Modules; +/// +/// Manager of SpaceWarp modules. +/// public static class ModuleManager { internal static List AllSpaceWarpModules = new(); private static readonly ILogger ModuleManagerLogSource = new UnityLogSource("SpaceWarp.ModuleManager"); + /// + /// Gets a SpaceWarp module instance by name. + /// + /// Name of the module. + /// The module instance. + /// True if the module was found, false otherwise. public static bool TryGetModule(string name, out SpaceWarpModule module) { module = AllSpaceWarpModules.FirstOrDefault(x => x.Name == name); diff --git a/src/SpaceWarp.Core/Modules/SpaceWarpModule.cs b/src/SpaceWarp.Core/Modules/SpaceWarpModule.cs index 9f08d28..9e72094 100644 --- a/src/SpaceWarp.Core/Modules/SpaceWarpModule.cs +++ b/src/SpaceWarp.Core/Modules/SpaceWarpModule.cs @@ -3,20 +3,48 @@ namespace SpaceWarp.Modules; +/// +/// Base class for SpaceWarp modules. +/// public abstract class SpaceWarpModule { + /// + /// The logger for the module. + /// public ILogger ModuleLogger; + + /// + /// The configuration file for the module. + /// public IConfigFile ModuleConfiguration; + /// + /// The name of the module. + /// public abstract string Name { get; } - public abstract void LoadModule(); - - public abstract void PreInitializeModule(); - - public abstract void InitializeModule(); - - public abstract void PostInitializeModule(); - + /// + /// Loads the module. Called in plugin's Awake method. + /// + public virtual void LoadModule() {} + + /// + /// 1st stage of module initialization. Called in plugin's OnPreInitialized method. + /// + public virtual void PreInitializeModule() {} + + /// + /// 2nd stage of module initialization. Called in plugin's OnInitialized method. + /// + public virtual void InitializeModule() {} + + /// + /// 3rd stage of module initialization. Called in plugin's OnPostInitialized method. + /// + public virtual void PostInitializeModule() {} + + /// + /// Names of modules that this module depends on. + /// public virtual List Prerequisites => new(); } \ No newline at end of file From c40e336cf439ce465c61276059a74120b591c1a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 19:34:53 +0100 Subject: [PATCH 34/82] SpaceWarp.Patching refactoring --- src/SpaceWarp.Core/API/Loading/SaveLoad.cs | 2 +- .../API/Mods/SpaceWarpErrorDescription.cs | 2 +- src/SpaceWarp.Core/API/Parts/Colors.cs | 2 +- .../Patching/CodeGenerationUtilities.cs | 2 +- .../Patching/{ => Flow}/BootstrapPatch.cs | 12 ++- .../SequentialFlowLoadersPatcher.cs | 99 +++++++++++-------- .../LoadingActions/AddressableAction.cs | 16 +-- .../LoadingActions/DescriptorLoadingAction.cs | 2 + .../FunctionalLoadingActions.cs | 3 +- .../LoadingActions/InitializeModAction.cs | 6 +- .../LoadingActions/LoadAddressablesAction.cs | 7 +- .../LoadingActions/LoadLocalizationAction.cs | 5 + .../Patching/LoadingActions/LoadLuaAction.cs | 9 ++ .../LoadingAddressablesLocalizationsAction.cs | 50 ---------- .../LoadingActions/ModLoadingAction.cs | 15 +-- .../LoadingActions/PostInitializeModAction.cs | 5 +- .../LoadingActions/PreInitializeModAction.cs | 1 + .../ResolvingPatchOrderAction.cs | 15 --- .../{ => Localization}/LocalizationPatch.cs | 2 +- .../Patching/{ => Mods}/ModLoaderPatch.cs | 39 +++++--- .../Patching/PartOwnerComponentConstructor.cs | 32 ------ .../Patching/{ => Parts}/ColorsPatch.cs | 37 +++++-- .../Parts/PartOwnerComponentConstructor.cs | 36 +++++++ .../SaveGameManager/SaveGamePatches.cs | 59 +++++++---- .../Settings/ConfigurationManagerPatch.cs} | 11 ++- .../{ => Settings}/SettingsManagerPatcher.cs | 9 +- .../Patching/{ => System}/FixGetTypes.cs | 5 +- src/SpaceWarp.Core/SpaceWarp.Core.csproj | 3 + .../{ => LoadingScreen}/CurtainPatch.cs | 9 +- .../{ => LoadingScreen}/LoadingFlowPatch.cs | 9 +- .../LoadingScreenDeserializationPatch.cs | 6 +- .../{ => Settings}/MainMenuPatcher.cs | 5 +- .../UI/Settings/SettingsMenuController.cs | 6 +- 33 files changed, 283 insertions(+), 238 deletions(-) rename src/SpaceWarp.Core/Patching/{ => Flow}/BootstrapPatch.cs (94%) rename src/SpaceWarp.Core/Patching/{ => Flow}/SequentialFlowLoadersPatcher.cs (73%) delete mode 100644 src/SpaceWarp.Core/Patching/LoadingActions/LoadingAddressablesLocalizationsAction.cs delete mode 100644 src/SpaceWarp.Core/Patching/LoadingActions/ResolvingPatchOrderAction.cs rename src/SpaceWarp.Core/Patching/{ => Localization}/LocalizationPatch.cs (99%) rename src/SpaceWarp.Core/Patching/{ => Mods}/ModLoaderPatch.cs (90%) delete mode 100644 src/SpaceWarp.Core/Patching/PartOwnerComponentConstructor.cs rename src/SpaceWarp.Core/Patching/{ => Parts}/ColorsPatch.cs (96%) create mode 100644 src/SpaceWarp.Core/Patching/Parts/PartOwnerComponentConstructor.cs rename src/{SpaceWarp.UI/Patching/ConfigurationPatch.cs => SpaceWarp.Core/Patching/Settings/ConfigurationManagerPatch.cs} (54%) rename src/SpaceWarp.Core/Patching/{ => Settings}/SettingsManagerPatcher.cs (57%) rename src/SpaceWarp.Core/Patching/{ => System}/FixGetTypes.cs (96%) rename src/SpaceWarp.UI/Patching/{ => LoadingScreen}/CurtainPatch.cs (81%) rename src/SpaceWarp.UI/Patching/{ => LoadingScreen}/LoadingFlowPatch.cs (85%) rename src/SpaceWarp.UI/Patching/{ => LoadingScreen}/LoadingScreenDeserializationPatch.cs (76%) rename src/SpaceWarp.UI/Patching/{ => Settings}/MainMenuPatcher.cs (96%) diff --git a/src/SpaceWarp.Core/API/Loading/SaveLoad.cs b/src/SpaceWarp.Core/API/Loading/SaveLoad.cs index 53c8779..8808ff9 100644 --- a/src/SpaceWarp.Core/API/Loading/SaveLoad.cs +++ b/src/SpaceWarp.Core/API/Loading/SaveLoad.cs @@ -1,6 +1,6 @@ using JetBrains.Annotations; using KSP.Game.Flow; -using SpaceWarp.Patching; +using SpaceWarp.Patching.Flow; namespace SpaceWarp.API.Loading; diff --git a/src/SpaceWarp.Core/API/Mods/SpaceWarpErrorDescription.cs b/src/SpaceWarp.Core/API/Mods/SpaceWarpErrorDescription.cs index eb5f425..5670ff8 100644 --- a/src/SpaceWarp.Core/API/Mods/SpaceWarpErrorDescription.cs +++ b/src/SpaceWarp.Core/API/Mods/SpaceWarpErrorDescription.cs @@ -1,6 +1,6 @@ using BepInEx; using JetBrains.Annotations; -using SpaceWarp.Patching; +using SpaceWarp.Patching.Flow; namespace SpaceWarp.API.Mods; diff --git a/src/SpaceWarp.Core/API/Parts/Colors.cs b/src/SpaceWarp.Core/API/Parts/Colors.cs index 7ad752e..6ef376a 100644 --- a/src/SpaceWarp.Core/API/Parts/Colors.cs +++ b/src/SpaceWarp.Core/API/Parts/Colors.cs @@ -1,6 +1,6 @@ using JetBrains.Annotations; using SpaceWarp.API.Lua; -using SpaceWarp.Patching; +using SpaceWarp.Patching.Parts; using UnityEngine; namespace SpaceWarp.API.Parts; diff --git a/src/SpaceWarp.Core/Patching/CodeGenerationUtilities.cs b/src/SpaceWarp.Core/Patching/CodeGenerationUtilities.cs index 60fcee9..b67bc18 100644 --- a/src/SpaceWarp.Core/Patching/CodeGenerationUtilities.cs +++ b/src/SpaceWarp.Core/Patching/CodeGenerationUtilities.cs @@ -6,7 +6,7 @@ namespace SpaceWarp.Patching; internal static class CodeGenerationUtilities { /// - /// Creates a CodeInstruction that pushed an integer to the stack. + /// Creates a CodeInstruction that pushed an integer to the stack. /// /// The integer to push /// An new CodeInstruction to push i diff --git a/src/SpaceWarp.Core/Patching/BootstrapPatch.cs b/src/SpaceWarp.Core/Patching/Flow/BootstrapPatch.cs similarity index 94% rename from src/SpaceWarp.Core/Patching/BootstrapPatch.cs rename to src/SpaceWarp.Core/Patching/Flow/BootstrapPatch.cs index 39219b3..b10b1c2 100644 --- a/src/SpaceWarp.Core/Patching/BootstrapPatch.cs +++ b/src/SpaceWarp.Core/Patching/Flow/BootstrapPatch.cs @@ -7,7 +7,7 @@ using SpaceWarp.Backend.Modding; using SpaceWarp.Patching.LoadingActions; -namespace SpaceWarp.Patching; +namespace SpaceWarp.Patching.Flow; [HarmonyPatch] internal static class BootstrapPatch @@ -23,8 +23,8 @@ private static void GetAllMods() PluginList.ResolveDependenciesAndLoadOrder(); } - [HarmonyILManipulator] [HarmonyPatch(typeof(GameManager), nameof(GameManager.StartBootstrap))] + [HarmonyILManipulator] private static void PatchInitializationsIL(ILContext ilContext, ILLabel endLabel) { ILCursor ilCursor = new(ilContext); @@ -108,9 +108,9 @@ private static IList GetAllPlugins() IList allPlugins; if (ForceSpaceWarpLoadDueToError) { - var l = new List { ErroredSWPluginDescriptor }; - l.AddRange(PluginList.AllEnabledAndActivePlugins); - allPlugins = l; + var list = new List { ErroredSWPluginDescriptor }; + list.AddRange(PluginList.AllEnabledAndActivePlugins); + allPlugins = list; } else { @@ -130,7 +130,9 @@ private static void InjectBeforeGameLoadMethods() foreach (var plugin in PluginList.AllEnabledAndActivePlugins) { if (plugin.Plugin != null && !plugin.LatePreInitialize) + { GameManager.Instance.LoadingFlow.AddAction(new PreInitializeModAction(plugin)); + } } } } \ No newline at end of file diff --git a/src/SpaceWarp.Core/Patching/SequentialFlowLoadersPatcher.cs b/src/SpaceWarp.Core/Patching/Flow/SequentialFlowLoadersPatcher.cs similarity index 73% rename from src/SpaceWarp.Core/Patching/SequentialFlowLoadersPatcher.cs rename to src/SpaceWarp.Core/Patching/Flow/SequentialFlowLoadersPatcher.cs index 34864b4..3379ecc 100644 --- a/src/SpaceWarp.Core/Patching/SequentialFlowLoadersPatcher.cs +++ b/src/SpaceWarp.Core/Patching/Flow/SequentialFlowLoadersPatcher.cs @@ -5,7 +5,7 @@ using KSP.Game; using KSP.Game.Flow; -namespace SpaceWarp.Patching; +namespace SpaceWarp.Patching.Flow; [HarmonyPatch] internal static class SequentialFlowLoadersPatcher @@ -14,28 +14,29 @@ internal static class SequentialFlowLoadersPatcher internal const int FlowMethodPrivateloadcommon = 1; internal const int FlowMethodPrivatesavecommon = 2; - private static SequentialFlowAdditions[] _sequentialFlowAdditions = + private static readonly SequentialFlowAdditions[] SequentialFlowAdditionMethods = { - new(typeof(GameManager).GetMethod("StartGame")), // Must be index FLOW_METHOD_STARTGAME - new(AccessTools.Method( - "KSP.Game.SaveLoadManager:PrivateLoadCommon")), // Must be index FLOW_METHOD_PRIVATELOADCOMMON - new(AccessTools.Method( - "KSP.Game.SaveLoadManager:PrivateSaveCommon")), // Must be index FLOW_METHOD_PRIVATESAVECOMMON + // Must be index FlowMethodStartgame + new(typeof(GameManager).GetMethod("StartGame")), + // Must be index FlowMethodPrivateloadcommon + new(AccessTools.Method("KSP.Game.SaveLoadManager:PrivateLoadCommon")), + // Must be index FlowMethodPrivatesavecommon + new(AccessTools.Method("KSP.Game.SaveLoadManager:PrivateSaveCommon")) }; internal static void AddConstructor(string after, Type flowAction, int methodIndex) { - _sequentialFlowAdditions[methodIndex].AddConstructor(after, flowAction); + SequentialFlowAdditionMethods[methodIndex].AddConstructor(after, flowAction); } internal static void AddFlowAction(string after, FlowAction flowAction, int methodIndex) { - _sequentialFlowAdditions[methodIndex].AddAction(after, flowAction); + SequentialFlowAdditionMethods[methodIndex].AddAction(after, flowAction); } public static SequentialFlow Apply(SequentialFlow flow, object[] methodArguments, int methodIndex) { - _sequentialFlowAdditions[methodIndex].ApplyTo(flow, methodArguments); + SequentialFlowAdditionMethods[methodIndex].ApplyTo(flow, methodArguments); return flow; } @@ -55,8 +56,9 @@ int methodIndex // Get list of relevant arguments to pass to FlowAction constructors. // `parameterCount` has a `+ 1` because `GetParameters()` doesn't include the instance parameter (this). - var parameters = _sequentialFlowAdditions[methodIndex].method.GetParameters() - .Where(parameter => !parameter.ParameterType.IsValueType).ToArray(); + var parameters = SequentialFlowAdditionMethods[methodIndex].Method.GetParameters() + .Where(parameter => !parameter.ParameterType.IsValueType) + .ToArray(); var parameterCount = parameters.Length + 1; // Creation of argument `methodArguments` to `Apply()`: @@ -97,19 +99,17 @@ int methodIndex } } - [HarmonyPatch(typeof(GameManager))] - [HarmonyPatch("StartGame")] + [HarmonyPatch(typeof(GameManager), nameof(GameManager.StartGame))] [HarmonyPrefix] public static void PrefixGameManagerStartGame(GameManager __instance) { - _sequentialFlowAdditions[FlowMethodStartgame].ApplyTo( + SequentialFlowAdditionMethods[FlowMethodStartgame].ApplyTo( __instance.LoadingFlow, new object[] { __instance } ); } - [HarmonyPatch(typeof(SaveLoadManager))] - [HarmonyPatch("PrivateLoadCommon")] + [HarmonyPatch(typeof(SaveLoadManager), nameof(SaveLoadManager.PrivateLoadCommon))] [HarmonyTranspiler] public static IEnumerable TranspileSaveLoadManagerPrivateLoadCommon( IEnumerable instructions) @@ -117,8 +117,7 @@ public static IEnumerable TranspileSaveLoadManagerPrivateLoadCo return TranspileSequentialFlowBuilderMethod(instructions, FlowMethodPrivateloadcommon); } - [HarmonyPatch(typeof(SaveLoadManager))] - [HarmonyPatch("PrivateSaveCommon")] + [HarmonyPatch(typeof(SaveLoadManager), nameof(SaveLoadManager.PrivateSaveCommon))] [HarmonyTranspiler] public static IEnumerable TranspileSaveLoadManagerPrivateSaveCommon( IEnumerable instructions) @@ -128,29 +127,35 @@ public static IEnumerable TranspileSaveLoadManagerPrivateSaveCo private class SequentialFlowAdditions { - private readonly HashSet availableTypes; - private readonly List> insertAfter = new(); - internal readonly MethodInfo method; + private readonly HashSet _availableTypes; + private readonly List> _insertAfter = new(); + + internal readonly MethodInfo Method; internal SequentialFlowAdditions(MethodInfo method) { - availableTypes = - new HashSet(method.GetParameters().Select(parameter => parameter.ParameterType) - .Where(type => !type.IsValueType)) { method.DeclaringType }; - this.method = method; + _availableTypes = + [ + ..method.GetParameters() + .Select(parameter => parameter.ParameterType) + .Where(type => !type.IsValueType), + method.DeclaringType + ]; + Method = method; } internal void AddConstructor(string after, Type flowAction) { // Determine the correct constructor to use. var constructor = flowAction.GetConstructors() - .OrderByDescending(constructor => constructor.GetParameters().Length).Where(constructor => + .OrderByDescending(constructor => constructor.GetParameters().Length) + .Where(constructor => { HashSet seen = new(); foreach (var parameter in constructor.GetParameters()) { - if (!availableTypes.Contains(parameter.ParameterType)) + if (!_availableTypes.Contains(parameter.ParameterType)) return false; if (!seen.Add(parameter.GetType())) @@ -158,15 +163,18 @@ internal void AddConstructor(string after, Type flowAction) } return true; - }).FirstOrDefault() ?? throw new InvalidOperationException( - $"Flow action type {flowAction.Name} does not have a public constructor that has parameters compatible with {method.DeclaringType.Name}.{method.Name}"); + }) + .FirstOrDefault() ?? throw new InvalidOperationException( + $"Flow action type {flowAction.Name} does not have a public constructor that has " + + $"parameters compatible with {Method.DeclaringType.Name}.{Method.Name}" + ); - insertAfter.Add(new KeyValuePair(after, constructor)); + _insertAfter.Add(new KeyValuePair(after, constructor)); } internal void AddAction(string after, FlowAction action) { - insertAfter.Add(new KeyValuePair(after, action)); + _insertAfter.Add(new KeyValuePair(after, action)); } private static FlowAction Construct(ConstructorInfo constructor, object[] methodArguments) @@ -199,11 +207,11 @@ private void AddActionsAfter(string name, List actions, bool[] added if (added[i]) continue; - if (insertAfter[i].Key != name) continue; + if (_insertAfter[i].Key != name) continue; added[i] = true; - var action = insertAfter[i].Value switch + var action = _insertAfter[i].Value switch { ConstructorInfo constructor => Construct(constructor, methodArguments), FlowAction flowAction => flowAction, @@ -214,7 +222,7 @@ private void AddActionsAfter(string name, List actions, bool[] added // There could be actions set to run after the newly inserted action, // so this needs to be called again. - AddActionsAfter(action.Name, actions, added, methodArguments); + AddActionsAfter(action!.Name, actions, added, methodArguments); } } @@ -240,7 +248,7 @@ internal void ApplyTo(SequentialFlow flow, object[] methodArguments) // Has each action been added already? // Used to prevent duplicates, and warn about unused actions. - var added = new bool[insertAfter.Count()]; + var added = new bool[_insertAfter.Count()]; // `null` is sued to signify the start of the action list. AddActionsAfter(null, actions, added, methodArguments); @@ -259,20 +267,27 @@ internal void ApplyTo(SequentialFlow flow, object[] methodArguments) // Warn about any actions that were not used. for (int i = 0; i < added.Length; i++) { - if (added[i]) continue; + if (added[i]) + { + continue; + } - if (insertAfter[i].Value is ConstructorInfo constructor) + if (_insertAfter[i].Value is ConstructorInfo constructor) { var actionType = constructor.DeclaringType; - var logger = Logger.CreateLogSource($"{actionType.Assembly.GetName().Name}/{actionType.Name}"); + var logger = Logger.CreateLogSource($"{actionType!.Assembly.GetName().Name}/{actionType.Name}"); logger.LogWarning( - $"Flow action {actionType.Name} was set to be inserted after \"{insertAfter[i].Key}\" in {method.Name}, however that action does not exist in that flow"); + $"Flow action {actionType.Name} was set to be inserted after \"{_insertAfter[i].Key}\" " + + $"in {Method.Name}, however that action does not exist in that flow" + ); } - else if (insertAfter[i].Value is FlowAction action) + else if (_insertAfter[i].Value is FlowAction action) { var logger = Logger.CreateLogSource("SequentialFlow"); logger.LogWarning( - $"Flow action \"{action.Name}\" was set to be inserted after \"{insertAfter[i].Key}\" in {method.Name}, however that action does not exist in that flow"); + $"Flow action \"{action.Name}\" was set to be inserted after \"{_insertAfter[i].Key}\" " + + $"in {Method.Name}, however that action does not exist in that flow" + ); } } } diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/AddressableAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/AddressableAction.cs index cd588b5..b3ae450 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/AddressableAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/AddressableAction.cs @@ -6,17 +6,19 @@ namespace SpaceWarp.Patching.LoadingActions; +// TODO: Move this to SpaceWarp.API.Loading in 2.0.0 + [Obsolete("This will be moved to SpaceWarp.API.Loading in 2.0.0")] [PublicAPI] public class AddressableAction : FlowAction where T : UnityObject { - private string Label; - private Action Action; + private string _label; + private Action _action; public AddressableAction(string name, string label, Action action) : base(name) { - Label = label; - Action = action; + _label = label; + _action = action; } private bool DoesLabelExist(object label) @@ -27,16 +29,16 @@ private bool DoesLabelExist(object label) public override void DoAction(Action resolve, Action reject) { - if (!DoesLabelExist(Label)) + if (!DoesLabelExist(_label)) { - Debug.Log($"[Space Warp] Skipping loading addressables for {Label} which does not exist."); + Debug.Log($"[Space Warp] Skipping loading addressables for {_label} which does not exist."); resolve(); return; } try { - GameManager.Instance.Assets.LoadByLabel(Label,Action,delegate(IList assetLocations) + GameManager.Instance.Assets.LoadByLabel(_label,_action,delegate(IList assetLocations) { if (assetLocations != null) { diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/DescriptorLoadingAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/DescriptorLoadingAction.cs index e7c7958..0b88306 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/DescriptorLoadingAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/DescriptorLoadingAction.cs @@ -4,6 +4,8 @@ namespace SpaceWarp.Patching.LoadingActions; +// TODO: Move this to SpaceWarp.API.Loading in 2.0.0 + [Obsolete("This will be moved to SpaceWarp.API.Loading in 2.0.0")] [PublicAPI] public class DescriptorLoadingAction : FlowAction diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/FunctionalLoadingActions.cs b/src/SpaceWarp.Core/Patching/LoadingActions/FunctionalLoadingActions.cs index bb98a70..4e9cec4 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/FunctionalLoadingActions.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/FunctionalLoadingActions.cs @@ -12,8 +12,7 @@ string filename var assetBundle = AssetBundle.LoadFromFile(filename); if (assetBundle == null) { - throw new Exception( - $"Failed to load AssetBundle {internalPath} ({filename})"); + throw new Exception($"Failed to load AssetBundle {internalPath} ({filename})"); } internalPath = internalPath.Replace(".bundle", ""); diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/InitializeModAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/InitializeModAction.cs index 25ab834..8c49c2d 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/InitializeModAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/InitializeModAction.cs @@ -7,8 +7,7 @@ internal sealed class InitializeModAction : FlowAction { private readonly SpaceWarpPluginDescriptor _plugin; - public InitializeModAction(SpaceWarpPluginDescriptor plugin) : base( - $"Initialization for plugin {plugin.Name}") + public InitializeModAction(SpaceWarpPluginDescriptor plugin) : base($"Initialization for plugin {plugin.Name}") { _plugin = plugin; } @@ -18,7 +17,10 @@ public override void DoAction(Action resolve, Action reject) try { if (_plugin.DoLoadingActions) + { _plugin.Plugin.OnInitialized(); + } + resolve(); } catch (Exception e) diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/LoadAddressablesAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/LoadAddressablesAction.cs index b4c50e9..a66819a 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/LoadAddressablesAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/LoadAddressablesAction.cs @@ -38,9 +38,14 @@ public override void DoAction(Action resolve, Action reject) catch (Exception e) { if (_plugin.Plugin != null) + { _plugin.Plugin.SWLogger.LogError(e.ToString()); + } else - SpaceWarpPlugin.Logger.LogError(_plugin.SWInfo.Name + ": " + e); + { + SpaceWarpPlugin.Logger.LogError(_plugin.SWInfo.Name + ": " + e); + } + reject(null); } } diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/LoadLocalizationAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/LoadLocalizationAction.cs index bf00eba..f9b5cf9 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/LoadLocalizationAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/LoadLocalizationAction.cs @@ -25,9 +25,14 @@ public override void DoAction(Action resolve, Action reject) catch (Exception e) { if (_plugin.Plugin != null) + { _plugin.Plugin.SWLogger.LogError(e.ToString()); + } else + { SpaceWarpPlugin.Logger.LogError(_plugin.SWInfo.Name + ": " + e); + } + reject(null); } } diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/LoadLuaAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/LoadLuaAction.cs index bd8f096..761ec3e 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/LoadLuaAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/LoadLuaAction.cs @@ -30,9 +30,13 @@ public override void DoAction(Action resolve, Action reject) catch (Exception e) { if (_plugin.Plugin != null) + { _plugin.Plugin.SWLogger.LogError(e.ToString()); + } else + { SpaceWarpPlugin.Logger.LogError(_plugin.SWInfo.Name + ": " + e); + } } } @@ -41,9 +45,14 @@ public override void DoAction(Action resolve, Action reject) catch (Exception e) { if (_plugin.Plugin != null) + { _plugin.Plugin.SWLogger.LogError(e.ToString()); + } else + { SpaceWarpPlugin.Logger.LogError(_plugin.SWInfo.Name + ": " + e); + } + reject(null); } } diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/LoadingAddressablesLocalizationsAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/LoadingAddressablesLocalizationsAction.cs deleted file mode 100644 index cecd044..0000000 --- a/src/SpaceWarp.Core/Patching/LoadingActions/LoadingAddressablesLocalizationsAction.cs +++ /dev/null @@ -1,50 +0,0 @@ -using I2.Loc; -using KSP.Game; -using KSP.Game.Flow; -using UnityEngine; -using UnityEngine.AddressableAssets; - -namespace SpaceWarp.Patching.LoadingActions; - -internal sealed class LoadAddressablesLocalizationsAction : FlowAction -{ - public LoadAddressablesLocalizationsAction() : base("Loading localizations from Addressables") - { - } - - public override void DoAction(Action resolve, Action reject) - { - try - { - GameManager.Instance.Assets.LoadByLabel( - "language_source", - OnLanguageSourceAssetLoaded, - delegate(IList languageAssetLocations) - { - if (languageAssetLocations != null) - { - Addressables.Release(languageAssetLocations); - } - - resolve(); - } - ); - } - catch (Exception e) - { - Debug.LogError(e.ToString()); - reject(null); - } - } - - private static void OnLanguageSourceAssetLoaded(LanguageSourceAsset asset) - { - if (!asset || LocalizationManager.Sources.Contains(asset.mSource)) - { - return; - } - - asset.mSource.owner = asset; - LocalizationManager.AddSource(asset.mSource); - } -} \ No newline at end of file diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs index 5b9483f..08e917f 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs @@ -4,13 +4,14 @@ namespace SpaceWarp.Patching.LoadingActions; +// TODO: Move this to SpaceWarp.API.Loading in 2.0.0 + [Obsolete("This will be moved to SpaceWarp.API.Loading in 2.0.0")] [PublicAPI] public class ModLoadingAction : FlowAction { - private Action Action; - private BaseSpaceWarpPlugin Plugin; - + private Action _action; + private BaseSpaceWarpPlugin _plugin; public ModLoadingAction( string actionName, @@ -18,20 +19,20 @@ public ModLoadingAction( BaseSpaceWarpPlugin plugin ) : base($"{plugin.SpaceWarpMetadata.Name}:{actionName}") { - Action = action; - Plugin = plugin; + _action = action; + _plugin = plugin; } public override void DoAction(Action resolve, Action reject) { try { - Action(Plugin); + _action(_plugin); resolve(); } catch (Exception e) { - Plugin.SWLogger.LogError(e.ToString()); + _plugin.SWLogger.LogError(e.ToString()); reject(null); } } diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/PostInitializeModAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/PostInitializeModAction.cs index d582183..80831b5 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/PostInitializeModAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/PostInitializeModAction.cs @@ -18,7 +18,10 @@ public override void DoAction(Action resolve, Action reject) try { if (_plugin.DoLoadingActions) - _plugin.Plugin.OnPostInitialized(); + { + _plugin.Plugin!.OnPostInitialized(); + } + resolve(); } catch (Exception e) diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/PreInitializeModAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/PreInitializeModAction.cs index ae5d97e..81eefe4 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/PreInitializeModAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/PreInitializeModAction.cs @@ -27,6 +27,7 @@ public override void DoAction(Action resolve, Action reject) { SpaceWarpPlugin.Logger.LogInfo("NO!!"); } + resolve(); } catch (Exception e) diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/ResolvingPatchOrderAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/ResolvingPatchOrderAction.cs deleted file mode 100644 index acd2375..0000000 --- a/src/SpaceWarp.Core/Patching/LoadingActions/ResolvingPatchOrderAction.cs +++ /dev/null @@ -1,15 +0,0 @@ -using KSP.Game.Flow; - -namespace SpaceWarp.Patching.LoadingActions; - -internal class ResolvingPatchOrderAction : FlowAction -{ - public ResolvingPatchOrderAction(string name) : base(name) - { - } - - public override void DoAction(Action resolve, Action reject) - { - throw new NotImplementedException(); - } -} \ No newline at end of file diff --git a/src/SpaceWarp.Core/Patching/LocalizationPatch.cs b/src/SpaceWarp.Core/Patching/Localization/LocalizationPatch.cs similarity index 99% rename from src/SpaceWarp.Core/Patching/LocalizationPatch.cs rename to src/SpaceWarp.Core/Patching/Localization/LocalizationPatch.cs index 581ab9f..37330d9 100644 --- a/src/SpaceWarp.Core/Patching/LocalizationPatch.cs +++ b/src/SpaceWarp.Core/Patching/Localization/LocalizationPatch.cs @@ -2,7 +2,7 @@ using I2.Loc; using UnityEngine; -namespace SpaceWarp.Patching; +namespace SpaceWarp.Patching.Localization; /// /// Patches the localization system to properly find fallback translations. diff --git a/src/SpaceWarp.Core/Patching/ModLoaderPatch.cs b/src/SpaceWarp.Core/Patching/Mods/ModLoaderPatch.cs similarity index 90% rename from src/SpaceWarp.Core/Patching/ModLoaderPatch.cs rename to src/SpaceWarp.Core/Patching/Mods/ModLoaderPatch.cs index eed6820..eb59403 100644 --- a/src/SpaceWarp.Core/Patching/ModLoaderPatch.cs +++ b/src/SpaceWarp.Core/Patching/Mods/ModLoaderPatch.cs @@ -12,12 +12,12 @@ using UnityEngine; using File = System.IO.File; -namespace SpaceWarp.Patching; +namespace SpaceWarp.Patching.Mods; [HarmonyPatch(typeof(KSP2Mod))] -public static class ModLoaderPatch +internal static class ModLoaderPatch { - private static ModInfo KSPToSwinfo(KSP2Mod mod) + private static ModInfo KspToSwinfo(KSP2Mod mod) { var newInfo = new ModInfo { @@ -34,8 +34,7 @@ private static ModInfo KSPToSwinfo(KSP2Mod mod) Min = "*", Max = "*" }, - VersionCheck = null, - VersionCheckType = VersionCheckType.SwInfo + VersionCheck = null }; return newInfo; } @@ -48,7 +47,7 @@ private static bool LoadPre(KSP2Mod __instance, ref bool __result, out bool __st var path = __instance.ModRootPath; var info = File.Exists(Path.Combine(path, "swinfo.json")) ? JsonConvert.DeserializeObject(File.ReadAllText(path)) - : KSPToSwinfo(__instance); + : KspToSwinfo(__instance); var disabled = ChainloaderPatch.DisabledPluginGuids.Contains(info.ModID); __state = disabled; return !disabled; @@ -63,7 +62,7 @@ private static void LoadPost(KSP2Mod __instance, ref bool __result, ref bool __s var path = __instance.ModRootPath; var info = File.Exists(Path.Combine(path, "swinfo.json")) ? JsonConvert.DeserializeObject(File.ReadAllText(path)) - : KSPToSwinfo(__instance); + : KspToSwinfo(__instance); var descriptor = PluginList.AllPlugins.FirstOrDefault(x => string.Equals(x.Guid, info.ModID, StringComparison.InvariantCultureIgnoreCase)); @@ -74,7 +73,10 @@ private static void LoadPost(KSP2Mod __instance, ref bool __result, ref bool __s if (__instance.EntryPoint != null) { if (LoadCodeBasedMod(__instance, ref __result, go, ref descriptor.Plugin, ref addAdapter, - ref descriptor.ConfigFile, ref descriptor.DoLoadingActions)) return; + ref descriptor.ConfigFile, ref descriptor.DoLoadingActions)) + { + return; + } } else { @@ -112,11 +114,17 @@ ref bool isSWMod if (__instance.EntryPoint.EndsWith(".dll")) { if (LoadModWithDLLEntryPoint(__instance, ref __result, go, ref swMod, ref addAdapter, ref configFile, - ref isSWMod)) return true; + ref isSWMod)) + { + return true; + } } else if (__instance.EntryPoint.EndsWith(".lua")) { - if (LoadModWithLuaEntryPoint(__instance, ref __result)) return true; + if (LoadModWithLuaEntryPoint(__instance, ref __result)) + { + return true; + } } } else @@ -169,9 +177,16 @@ ref bool isSWMod __instance.modType = KSP2ModType.CSharp; foreach (var type in asm.GetTypes()) { - if (!typeof(Mod).IsAssignableFrom(type) || type.IsAbstract) continue; + if (!typeof(Mod).IsAssignableFrom(type) || type.IsAbstract) + { + continue; + } + var comp = go.AddComponent(type); - if (comp is not BaseKspLoaderSpaceWarpMod baseKspLoaderSpaceWarpMod) continue; + if (comp is not BaseKspLoaderSpaceWarpMod baseKspLoaderSpaceWarpMod) + { + continue; + } SpaceWarpPlugin.Logger.LogInfo($"Loading mod: {comp}"); isSWMod = true; diff --git a/src/SpaceWarp.Core/Patching/PartOwnerComponentConstructor.cs b/src/SpaceWarp.Core/Patching/PartOwnerComponentConstructor.cs deleted file mode 100644 index f9c7da1..0000000 --- a/src/SpaceWarp.Core/Patching/PartOwnerComponentConstructor.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Reflection; -using HarmonyLib; -using JetBrains.Annotations; -using KSP.Sim.impl; -using SpaceWarp.API.Parts; - -namespace SpaceWarp.Patching; - - -[HarmonyPatch(typeof(PartOwnerComponent))] -public static class PartOwnerComponentConstructor -{ - private static FieldInfo AddedField = - typeof(PartOwnerComponent).GetField("HasRegisteredPartComponentsForFixedUpdate"); - - [HarmonyPatch(MethodType.Constructor)] - public static void SetFalse(PartOwnerComponent __instance) - { - - AddedField.SetValue(__instance, false); - } - - [HarmonyPatch(nameof(PartOwnerComponent.Add)), HarmonyPrefix, UsedImplicitly] - public static void CheckForModule(PartOwnerComponent __instance, PartComponent part) - { - var currentValue = (Boolean)AddedField.GetValue(__instance); - if (currentValue) return; - var hasModule = PartComponentModuleOverride.RegisteredPartComponentOverrides.Any(type => part.TryGetModule(type, out _)); - - AddedField.SetValue(__instance, hasModule); - } -} \ No newline at end of file diff --git a/src/SpaceWarp.Core/Patching/ColorsPatch.cs b/src/SpaceWarp.Core/Patching/Parts/ColorsPatch.cs similarity index 96% rename from src/SpaceWarp.Core/Patching/ColorsPatch.cs rename to src/SpaceWarp.Core/Patching/Parts/ColorsPatch.cs index b65991f..b9f6a5f 100644 --- a/src/SpaceWarp.Core/Patching/ColorsPatch.cs +++ b/src/SpaceWarp.Core/Patching/Parts/ColorsPatch.cs @@ -8,7 +8,7 @@ using SpaceWarp.API.Assets; using UnityEngine; -namespace SpaceWarp.Patching; +namespace SpaceWarp.Patching.Parts; /// /// This patch is meant to give modders a way to use the new colors system on KSP2. @@ -20,9 +20,9 @@ namespace SpaceWarp.Patching; [HarmonyPatch] internal class ColorsPatch { + #region Colors patch + private const string Ksp2OpaquePath = "KSP2/Scenery/Standard (Opaque)"; - private const string Ksp2TransparentPath = "KSP2/Scenery/Standard (Transparent)"; - private const string UnityStandard = "Standard"; [HarmonyPatch(typeof(ObjectAssemblyPartTracker), nameof(ObjectAssemblyPartTracker.OnPartPrefabLoaded))] public static void Prefix(IObjectAssemblyAvailablePart obj, ref GameObject prefab) @@ -30,7 +30,11 @@ public static void Prefix(IObjectAssemblyAvailablePart obj, ref GameObject prefa foreach (var renderer in prefab.GetComponentsInChildren()) { var shaderName = renderer.material.shader.name; - if (shaderName is not ("Parts Replace" or "KSP2/Parts/Paintable")) continue; + if (shaderName is not ("Parts Replace" or "KSP2/Parts/Paintable")) + { + continue; + } + Material material; var mat = new Material(Shader.Find(Ksp2OpaquePath)) { @@ -48,7 +52,11 @@ public static void UpdateColorsInFlight(GameObject instance) foreach (var renderer in instance.GetComponentsInChildren()) { var shaderName = renderer.material.shader.name; - if (shaderName is not ("Parts Replace" or "KSP2/Parts/Paintable")) continue; + if (shaderName is not ("Parts Replace" or "KSP2/Parts/Paintable")) + { + continue; + } + Material material; var mat = new Material(Shader.Find(Ksp2OpaquePath)) { @@ -59,7 +67,17 @@ public static void UpdateColorsInFlight(GameObject instance) } } - //Everything below this point will be removed in the next patch + #endregion + + // TODO: Remove everything below this comment in 2.0. + + #region To be removed + + // ReSharper disable all + + private const string Ksp2TransparentPath = "KSP2/Scenery/Standard (Transparent)"; + private const string UnityStandard = "Standard"; + private const int Diffuse = 0; private const int Metallic = 1; private const int Bump = 2; @@ -100,7 +118,6 @@ public static void UpdateColorsInFlight(GameObject instance) private static Shader _unityStandard; internal static ManualLogSource Logger; - ///TODO: Implement false behaviour public static Dictionary DeclaredParts { get; } = new(); [HarmonyPrepare] @@ -128,7 +145,7 @@ private static bool Init(MethodBase original) Logger = BepInEx.Logging.Logger.CreateLogSource(DisplayName); - return true; // TODO: add config to enable/disable this patch, if disabled return false. + return true; } /// @@ -312,7 +329,7 @@ private static string TrimPartName(string partName) nameof(GameManager.OnLoadingFinished))] internal static void Prefix() { - LoadDeclaredParts(); // TODO: Move this to a more apropriate call, like the one loading parts or something like that. + LoadDeclaredParts(); } [HarmonyPatch(typeof(Module_Color), @@ -363,4 +380,6 @@ private static void LogError(object data) { Logger.LogError($"{data}"); } + + #endregion } \ No newline at end of file diff --git a/src/SpaceWarp.Core/Patching/Parts/PartOwnerComponentConstructor.cs b/src/SpaceWarp.Core/Patching/Parts/PartOwnerComponentConstructor.cs new file mode 100644 index 0000000..38eab41 --- /dev/null +++ b/src/SpaceWarp.Core/Patching/Parts/PartOwnerComponentConstructor.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using HarmonyLib; +using KSP.Sim.impl; +using SpaceWarp.API.Parts; + +namespace SpaceWarp.Patching.Parts; + +[HarmonyPatch(typeof(PartOwnerComponent))] +internal static class PartOwnerComponentConstructor +{ + private static readonly FieldInfo AddedField = + typeof(PartOwnerComponent).GetField("HasRegisteredPartComponentsForFixedUpdate"); + + [HarmonyPatch(MethodType.Constructor)] + private static void SetFalse(PartOwnerComponent __instance) + { + AddedField.SetValue(__instance, false); + } + + [HarmonyPatch(nameof(PartOwnerComponent.Add))] + [HarmonyPrefix] + private static void CheckForModule(PartOwnerComponent __instance, PartComponent part) + { + var currentValue = (bool)AddedField.GetValue(__instance); + if (currentValue) + { + return; + } + + var hasModule = PartComponentModuleOverride.RegisteredPartComponentOverrides.Any( + type => part.TryGetModule(type, out _) + ); + + AddedField.SetValue(__instance, hasModule); + } +} \ No newline at end of file diff --git a/src/SpaceWarp.Core/Patching/SaveGameManager/SaveGamePatches.cs b/src/SpaceWarp.Core/Patching/SaveGameManager/SaveGamePatches.cs index ff85ffa..e067723 100644 --- a/src/SpaceWarp.Core/Patching/SaveGameManager/SaveGamePatches.cs +++ b/src/SpaceWarp.Core/Patching/SaveGameManager/SaveGamePatches.cs @@ -1,7 +1,6 @@ using HarmonyLib; using KSP.Game.Load; using KSP.IO; -using SpaceWarp.API.Logging; using SpaceWarp.API.SaveGameManager; using SpaceWarp.Backend.SaveGameManager; using SpaceWarp.InternalUtilities; @@ -11,17 +10,22 @@ namespace SpaceWarp.Patching.SaveGameManager; [HarmonyPatch] internal class SaveLoadPatches { - private static readonly ILogger _logger = new UnityLogSource("SpaceWarp.SaveLoadPatches"); + #region Saving - /// SAVING /// - - [HarmonyPatch(typeof(SerializeGameDataFlowAction), MethodType.Constructor), HarmonyPostfix] - [HarmonyPatch(new Type[] { typeof(string), typeof(LoadGameData) })] - private static void InjectPluginSaveGameData(string filename, LoadGameData data, SerializeGameDataFlowAction __instance) + [HarmonyPatch(typeof(SerializeGameDataFlowAction), MethodType.Constructor, [typeof(string), typeof(LoadGameData)])] + [HarmonyPostfix] + private static void InjectPluginSaveGameData( + string filename, + LoadGameData data, + // ReSharper disable once InconsistentNaming + SerializeGameDataFlowAction __instance + ) { // Skip plugin data injection if there are no mods that have registered for save/load actions if (ModSaves.InternalPluginSaveData.Count == 0) + { return; + } // Take the game's LoadGameData, extend it with our own class and copy plugin save data to it SpaceWarpSerializedSavedGame modSaveData = new(); @@ -36,21 +40,30 @@ private static void InjectPluginSaveGameData(string filename, LoadGameData data, } } - /// LOADING /// + #endregion + + #region Loading - [HarmonyPatch(typeof(DeserializeContentsFlowAction), "DoAction"), HarmonyPrefix] - private static bool DeserializeLoadedPluginData(Action resolve, Action reject, DeserializeContentsFlowAction __instance) + [HarmonyPatch(typeof(DeserializeContentsFlowAction), "DoAction")] + [HarmonyPrefix] + private static bool DeserializeLoadedPluginData( + Action resolve, + Action reject, + // ReSharper disable once InconsistentNaming + DeserializeContentsFlowAction __instance + ) { // Skip plugin deserialization if there are no mods that have registered for save/load actions if (ModSaves.InternalPluginSaveData.Count == 0) + { return true; + } __instance._game.UI.SetLoadingBarText(__instance.Description); try { // Deserialize save data to our own class that extends game's SerializedSavedGame - SpaceWarpSerializedSavedGame serializedSavedGame = new(); - IOProvider.FromJsonFile(__instance._filename, out serializedSavedGame); + IOProvider.FromJsonFile(__instance._filename, out var serializedSavedGame); __instance._data.SavedGame = serializedSavedGame; __instance._data.DataLength = IOProvider.GetFileSize(__instance._filename); @@ -61,18 +74,27 @@ private static bool DeserializeLoadedPluginData(Action resolve, Action r foreach (var loadedData in serializedSavedGame.serializedPluginSaveData) { // Match registered plugin GUID with the GUID found in the save file - var existingData = ModSaves.InternalPluginSaveData.Find(p => p.ModGuid == loadedData.ModGuid); + var existingData = ModSaves.InternalPluginSaveData.Find( + p => p.ModGuid == loadedData.ModGuid + ); if (existingData == null) { - _logger.LogWarning($"Saved data for plugin '{loadedData.ModGuid}' found during a load event, however that plugin isn't registered for save/load events. Skipping load for this plugin."); + SpaceWarpPlugin.Logger.LogWarning( + $"Saved data for plugin '{loadedData.ModGuid}' found during a load event, however " + + $"that plugin isn't registered for save/load events. Skipping load for this plugin." + ); continue; } - // Perform a callback if plugin specified a callback function. This is done before plugin data is actually updated. + // Perform a callback if plugin specified a callback function. This is done before plugin data is + // actually updated. existingData.LoadEventCallback(loadedData.SaveData); // Copy loaded data to the SaveData object plugin registered - InternalExtensions.CopyFieldAndPropertyDataFromSourceToTargetObject(loadedData.SaveData, existingData.SaveData); + InternalExtensions.CopyFieldAndPropertyDataFromSourceToTargetObject( + loadedData.SaveData, + existingData.SaveData + ); } } } @@ -81,8 +103,11 @@ private static bool DeserializeLoadedPluginData(Action resolve, Action r UnityEngine.Debug.LogException(ex); reject(ex.Message); } + resolve(); return false; } -} + + #endregion +} \ No newline at end of file diff --git a/src/SpaceWarp.UI/Patching/ConfigurationPatch.cs b/src/SpaceWarp.Core/Patching/Settings/ConfigurationManagerPatch.cs similarity index 54% rename from src/SpaceWarp.UI/Patching/ConfigurationPatch.cs rename to src/SpaceWarp.Core/Patching/Settings/ConfigurationManagerPatch.cs index b2e6a2a..b38535d 100644 --- a/src/SpaceWarp.UI/Patching/ConfigurationPatch.cs +++ b/src/SpaceWarp.Core/Patching/Settings/ConfigurationManagerPatch.cs @@ -3,13 +3,14 @@ using ConfigurationManager.Utilities; using HarmonyLib; -namespace SpaceWarp.Patching; +namespace SpaceWarp.Patching.Settings; -[HarmonyPatch(typeof(Utils))] -[HarmonyPatch(nameof(Utils.FindPlugins))] -public class ConfigurationPatch +[HarmonyPatch] +internal class ConfigurationManagerPatch { - private static void Postfix(ref BaseUnityPlugin[] __result) + [HarmonyPatch(typeof(Utils), nameof(Utils.FindPlugins))] + [HarmonyPostfix] + private static void FindPluginsPatch(ref BaseUnityPlugin[] __result) { //Disable because I know what I am doing. #pragma warning disable CS0618 diff --git a/src/SpaceWarp.Core/Patching/SettingsManagerPatcher.cs b/src/SpaceWarp.Core/Patching/Settings/SettingsManagerPatcher.cs similarity index 57% rename from src/SpaceWarp.Core/Patching/SettingsManagerPatcher.cs rename to src/SpaceWarp.Core/Patching/Settings/SettingsManagerPatcher.cs index 5ff50e8..3196c04 100644 --- a/src/SpaceWarp.Core/Patching/SettingsManagerPatcher.cs +++ b/src/SpaceWarp.Core/Patching/Settings/SettingsManagerPatcher.cs @@ -1,15 +1,14 @@ using HarmonyLib; using KSP.UI; -namespace SpaceWarp.Patching; +namespace SpaceWarp.Patching.Settings; [HarmonyPatch] internal static class SettingsManagerPatcher { - internal static List AllExtrasSettingsMenus = new(); - + internal static readonly List AllExtrasSettingsMenus = new(); + + [HarmonyPatch(typeof(SettingsMenuManager), nameof(SettingsMenuManager.ResetAllSettings))] [HarmonyPostfix] - [HarmonyPatch(typeof(SettingsMenuManager))] - [HarmonyPatch(nameof(SettingsMenuManager.ResetAllSettings))] internal static void ResetModsMenu() { foreach (var menu in AllExtrasSettingsMenus.Where(menu => menu != null)) diff --git a/src/SpaceWarp.Core/Patching/FixGetTypes.cs b/src/SpaceWarp.Core/Patching/System/FixGetTypes.cs similarity index 96% rename from src/SpaceWarp.Core/Patching/FixGetTypes.cs rename to src/SpaceWarp.Core/Patching/System/FixGetTypes.cs index 0ebee94..0932b4c 100644 --- a/src/SpaceWarp.Core/Patching/FixGetTypes.cs +++ b/src/SpaceWarp.Core/Patching/System/FixGetTypes.cs @@ -2,14 +2,14 @@ using BepInEx.Logging; using HarmonyLib; -namespace SpaceWarp.Patching; +namespace SpaceWarp.Patching.System; [HarmonyPatch] internal static class FixGetTypes { - [HarmonyFinalizer] [HarmonyPatch(typeof(Assembly), nameof(Assembly.GetTypes), new Type[0])] [HarmonyPatch(typeof(Assembly), nameof(Assembly.GetExportedTypes))] + [HarmonyFinalizer] private static Exception GetTypesFix(Exception __exception, Assembly __instance, ref Type[] __result) { if (__exception is not ReflectionTypeLoadException reflectionTypeLoadException) @@ -30,6 +30,5 @@ private static Exception GetTypesFix(Exception __exception, Assembly __instance, __result = reflectionTypeLoadException.Types.Where(type => type != null).ToArray(); return null; - } } \ No newline at end of file diff --git a/src/SpaceWarp.Core/SpaceWarp.Core.csproj b/src/SpaceWarp.Core/SpaceWarp.Core.csproj index b366204..312723d 100644 --- a/src/SpaceWarp.Core/SpaceWarp.Core.csproj +++ b/src/SpaceWarp.Core/SpaceWarp.Core.csproj @@ -4,6 +4,9 @@ SpaceWarp + + + all diff --git a/src/SpaceWarp.UI/Patching/CurtainPatch.cs b/src/SpaceWarp.UI/Patching/LoadingScreen/CurtainPatch.cs similarity index 81% rename from src/SpaceWarp.UI/Patching/CurtainPatch.cs rename to src/SpaceWarp.UI/Patching/LoadingScreen/CurtainPatch.cs index eb1f8ff..db6f6aa 100644 --- a/src/SpaceWarp.UI/Patching/CurtainPatch.cs +++ b/src/SpaceWarp.UI/Patching/LoadingScreen/CurtainPatch.cs @@ -1,20 +1,21 @@ using HarmonyLib; using SpaceWarp.Backend.UI.Loading; -namespace SpaceWarp.Patching; +namespace SpaceWarp.Patching.LoadingScreen; [HarmonyPatch(typeof(Curtain))] internal static class CurtainPatch { internal static LoadingScreenManager LoadingScreenManager; - + [HarmonyPrefix] [HarmonyPatch(nameof(Curtain.Awake))] public static void LoadScreensEarly(Curtain __instance) { LoadingScreenManager = new LoadingScreenManager(); LoadingScreenManager.LoadScreens(__instance); - __instance._appStartLoadingScreenSpriteOptions.AddRange(LoadingScreenManager.LoadingScreens - .Values); + __instance._appStartLoadingScreenSpriteOptions.AddRange( + LoadingScreenManager.LoadingScreens.Values + ); } } \ No newline at end of file diff --git a/src/SpaceWarp.UI/Patching/LoadingFlowPatch.cs b/src/SpaceWarp.UI/Patching/LoadingScreen/LoadingFlowPatch.cs similarity index 85% rename from src/SpaceWarp.UI/Patching/LoadingFlowPatch.cs rename to src/SpaceWarp.UI/Patching/LoadingScreen/LoadingFlowPatch.cs index 9549fdf..2b5ffac 100644 --- a/src/SpaceWarp.UI/Patching/LoadingFlowPatch.cs +++ b/src/SpaceWarp.UI/Patching/LoadingScreen/LoadingFlowPatch.cs @@ -3,12 +3,12 @@ using KSP.Game.Flow; using KSP.Startup; -namespace SpaceWarp.Patching; +namespace SpaceWarp.Patching.LoadingScreen; [HarmonyPatch(typeof(SequentialFlow))] internal static class LoadingFlowPatch { - internal static long LoadingScreenTimer; + private static long _loadingScreenTimer; [HarmonyPostfix] [HarmonyPatch(nameof(SequentialFlow.NextFlowAction))] @@ -17,9 +17,9 @@ internal static void SelectRandomLoadingScreen(SequentialFlow __instance) if (__instance.FlowState != FlowState.Finished) { var time = ((DateTimeOffset)DateTime.Now).ToUnixTimeSeconds(); - if (time - LoadingScreenTimer >= 7) + if (time - _loadingScreenTimer >= 7) { - LoadingScreenTimer = time; + _loadingScreenTimer = time; // Switch loading screen if (GameManager.Instance == null || GameManager.Instance.Game == null || GameManager.Instance.Game.UI == null) return; @@ -34,5 +34,4 @@ internal static void SelectRandomLoadingScreen(SequentialFlow __instance) } } } - } \ No newline at end of file diff --git a/src/SpaceWarp.UI/Patching/LoadingScreenDeserializationPatch.cs b/src/SpaceWarp.UI/Patching/LoadingScreen/LoadingScreenDeserializationPatch.cs similarity index 76% rename from src/SpaceWarp.UI/Patching/LoadingScreenDeserializationPatch.cs rename to src/SpaceWarp.UI/Patching/LoadingScreen/LoadingScreenDeserializationPatch.cs index 9adf711..19e9a73 100644 --- a/src/SpaceWarp.UI/Patching/LoadingScreenDeserializationPatch.cs +++ b/src/SpaceWarp.UI/Patching/LoadingScreen/LoadingScreenDeserializationPatch.cs @@ -2,14 +2,14 @@ using KSP.Game; using KSP.Game.StartupFlow; -namespace SpaceWarp.Patching; +namespace SpaceWarp.Patching.LoadingScreen; [HarmonyPatch(typeof(DeserializeLoadingScreens))] -public static class LoadingScreenDeserializationPatch +internal static class LoadingScreenDeserializationPatch { [HarmonyPatch(nameof(DeserializeLoadingScreens.DoAction))] [HarmonyPostfix] - public static void AddToAllFlows() + private static void AddToAllFlows() { var curtain = GameManager.Instance.Game.UI.Curtain; foreach (var flow in curtain.LoadingScreens.Values.Distinct()) diff --git a/src/SpaceWarp.UI/Patching/MainMenuPatcher.cs b/src/SpaceWarp.UI/Patching/Settings/MainMenuPatcher.cs similarity index 96% rename from src/SpaceWarp.UI/Patching/MainMenuPatcher.cs rename to src/SpaceWarp.UI/Patching/Settings/MainMenuPatcher.cs index afaed3e..2394672 100644 --- a/src/SpaceWarp.UI/Patching/MainMenuPatcher.cs +++ b/src/SpaceWarp.UI/Patching/Settings/MainMenuPatcher.cs @@ -6,10 +6,9 @@ using TMPro; using UnityObject = UnityEngine.Object; -namespace SpaceWarp.Patching; +namespace SpaceWarp.Patching.Settings; -[HarmonyPatch(typeof(LandingHUD))] -[HarmonyPatch("Start")] +[HarmonyPatch(typeof(LandingHUD), nameof(LandingHUD.Start))] internal class MainMenuPatcher { internal static event Action MainMenuLoaded; diff --git a/src/SpaceWarp.UI/UI/Settings/SettingsMenuController.cs b/src/SpaceWarp.UI/UI/Settings/SettingsMenuController.cs index 55380a0..5d8d46b 100644 --- a/src/SpaceWarp.UI/UI/Settings/SettingsMenuController.cs +++ b/src/SpaceWarp.UI/UI/Settings/SettingsMenuController.cs @@ -7,7 +7,7 @@ using KSP.UI.Binding.Core; using SpaceWarp.API.UI.Settings; using SpaceWarp.InternalUtilities; -using SpaceWarp.Patching; +using SpaceWarp.Patching.Settings; using UnityEngine; using UnityEngine.UI; namespace SpaceWarp.UI.Settings; @@ -130,7 +130,7 @@ public void UpdatePrefabs() sliderPrefab.SetActive(false); ModsPropertyDrawers.SliderPrefab = sliderPrefab; } - + private void Setup() { if (_alreadySetup) return; @@ -139,7 +139,7 @@ private void Setup() var graphics = GameObject.Find(GraphicsPath); var content = GameObject.Find(ContentPath); var graphicsSettings = GameObject.Find(ContentGraphicsPath); - + var modsButton = Instantiate(graphics, categories.transform); From d84cbbaf6f5701ef377ce5cc2cd60ce4b911cb20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 21:23:48 +0100 Subject: [PATCH 35/82] LocalizationHelper for language source adding --- .../InternalUtilities/AssetHelpers.cs | 27 ++--------------- .../InternalUtilities/LocalizationHelpers.cs | 29 +++++++++++++++++++ src/SpaceWarp.Core/SpaceWarpPlugin.cs | 2 +- 3 files changed, 32 insertions(+), 26 deletions(-) create mode 100644 src/SpaceWarp.Core/InternalUtilities/LocalizationHelpers.cs diff --git a/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs b/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs index 8ad7481..c906289 100644 --- a/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs +++ b/src/SpaceWarp.Core/InternalUtilities/AssetHelpers.cs @@ -43,7 +43,7 @@ internal static void LoadLocalizationFromFolder(string folder) var csvData = File.ReadAllText(csvFile.FullName).Replace("\r\n", "\n"); csvSource.Import_CSV("", csvData, eSpreadsheetUpdateMode.AddNewTerms); loadedCount++; - AddSource(csvSource); + LocalizationHelpers.AddSource(csvSource); } foreach (var i2CsvFile in info.GetFiles("*.i2csv", SearchOption.AllDirectories)) @@ -52,34 +52,11 @@ internal static void LoadLocalizationFromFolder(string folder) var i2CsvData = File.ReadAllText(i2CsvFile.FullName).Replace("\r\n", "\n"); i2CsvSource.Import_I2CSV("", i2CsvData, eSpreadsheetUpdateMode.AddNewTerms); loadedCount++; - AddSource(i2CsvSource); + LocalizationHelpers.AddSource(i2CsvSource); } SpaceWarpPlugin.Instance.SWLogger.LogInfo( loadedCount > 0 ? $"Loaded localizations from {folder}" : $"No localizations found in {folder}" ); } - - private static void AddSource(LanguageSourceData source) - { - if (LocalizationManager.Sources.Contains(source)) - { - return; - } - - source.OnMissingTranslation = LanguageSourceData.MissingTranslationAction.Fallback; - - LocalizationManager.Sources.Insert(0, source); - foreach (var language in source.mLanguages) - { - language.SetLoaded(true); - } - - if (source.mDictionary.Count != 0) - { - return; - } - - source.UpdateDictionary(true); - } } \ No newline at end of file diff --git a/src/SpaceWarp.Core/InternalUtilities/LocalizationHelpers.cs b/src/SpaceWarp.Core/InternalUtilities/LocalizationHelpers.cs new file mode 100644 index 0000000..db51997 --- /dev/null +++ b/src/SpaceWarp.Core/InternalUtilities/LocalizationHelpers.cs @@ -0,0 +1,29 @@ +using I2.Loc; + +namespace SpaceWarp.InternalUtilities; + +internal static class LocalizationHelpers +{ + public static void AddSource(LanguageSourceData source) + { + if (LocalizationManager.Sources.Contains(source)) + { + return; + } + + source.OnMissingTranslation = LanguageSourceData.MissingTranslationAction.Fallback; + + LocalizationManager.Sources.Insert(0, source); + foreach (var language in source.mLanguages) + { + language.SetLoaded(true); + } + + if (source.mDictionary.Count != 0) + { + return; + } + + source.UpdateDictionary(true); + } +} \ No newline at end of file diff --git a/src/SpaceWarp.Core/SpaceWarpPlugin.cs b/src/SpaceWarp.Core/SpaceWarpPlugin.cs index 43bf28b..cbe5c1f 100644 --- a/src/SpaceWarp.Core/SpaceWarpPlugin.cs +++ b/src/SpaceWarp.Core/SpaceWarpPlugin.cs @@ -73,7 +73,7 @@ private static void OnLanguageSourceAssetLoaded(LanguageSourceAsset asset) } asset.mSource.owner = asset; - LocalizationManager.AddSource(asset.mSource); + LocalizationHelpers.AddSource(asset.mSource); } private void Awake() From cb1edb1b83c6618a17f313b58bc18c9d3b97abc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 21:59:39 +0100 Subject: [PATCH 36/82] Fixed SpaceWarp.Patching warnings --- .../Flow/SequentialFlowLoadersPatcher.cs | 3 +- .../LoadingActions/AddressableAction.cs | 15 ++++ .../LoadingActions/DescriptorLoadingAction.cs | 20 +++++ .../LoadingActions/ModLoadingAction.cs | 14 ++++ .../Patching/Mods/ModLoaderPatch.cs | 74 +++++++++++-------- .../Parts/PartOwnerComponentConstructor.cs | 2 + .../Settings/ConfigurationManagerPatch.cs | 1 + .../Patching/System/FixGetTypes.cs | 5 +- 8 files changed, 101 insertions(+), 33 deletions(-) diff --git a/src/SpaceWarp.Core/Patching/Flow/SequentialFlowLoadersPatcher.cs b/src/SpaceWarp.Core/Patching/Flow/SequentialFlowLoadersPatcher.cs index 3379ecc..4aa019e 100644 --- a/src/SpaceWarp.Core/Patching/Flow/SequentialFlowLoadersPatcher.cs +++ b/src/SpaceWarp.Core/Patching/Flow/SequentialFlowLoadersPatcher.cs @@ -101,6 +101,7 @@ int methodIndex [HarmonyPatch(typeof(GameManager), nameof(GameManager.StartGame))] [HarmonyPrefix] + // ReSharper disable once InconsistentNaming public static void PrefixGameManagerStartGame(GameManager __instance) { SequentialFlowAdditionMethods[FlowMethodStartgame].ApplyTo( @@ -166,7 +167,7 @@ internal void AddConstructor(string after, Type flowAction) }) .FirstOrDefault() ?? throw new InvalidOperationException( $"Flow action type {flowAction.Name} does not have a public constructor that has " + - $"parameters compatible with {Method.DeclaringType.Name}.{Method.Name}" + $"parameters compatible with {Method.DeclaringType!.Name}.{Method.Name}" ); _insertAfter.Add(new KeyValuePair(after, constructor)); diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/AddressableAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/AddressableAction.cs index b3ae450..6f1b6cf 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/AddressableAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/AddressableAction.cs @@ -8,6 +8,10 @@ namespace SpaceWarp.Patching.LoadingActions; // TODO: Move this to SpaceWarp.API.Loading in 2.0.0 +/// +/// A loading action that loads addressable assets by label. +/// +/// The type of assets to load. [Obsolete("This will be moved to SpaceWarp.API.Loading in 2.0.0")] [PublicAPI] public class AddressableAction : FlowAction where T : UnityObject @@ -15,6 +19,12 @@ public class AddressableAction : FlowAction where T : UnityObject private string _label; private Action _action; + /// + /// Creates a new addressable loading action. + /// + /// Name of the action. + /// Label of the asset to load. + /// Action to perform on the loaded asset. public AddressableAction(string name, string label, Action action) : base(name) { _label = label; @@ -27,6 +37,11 @@ private bool DoesLabelExist(object label) || Addressables.ResourceLocators.Any(locator => locator.Keys.Contains(label)); } + /// + /// Performs the loading action. + /// + /// Callback to call when the action is resolved. + /// Callback to call when the action is rejected. public override void DoAction(Action resolve, Action reject) { if (!DoesLabelExist(_label)) diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/DescriptorLoadingAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/DescriptorLoadingAction.cs index 0b88306..058b691 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/DescriptorLoadingAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/DescriptorLoadingAction.cs @@ -6,6 +6,9 @@ namespace SpaceWarp.Patching.LoadingActions; // TODO: Move this to SpaceWarp.API.Loading in 2.0.0 +/// +/// A general loading action for a mod descriptor. +/// [Obsolete("This will be moved to SpaceWarp.API.Loading in 2.0.0")] [PublicAPI] public class DescriptorLoadingAction : FlowAction @@ -13,6 +16,12 @@ public class DescriptorLoadingAction : FlowAction private readonly Action _action; private readonly SpaceWarpPluginDescriptor _plugin; + /// + /// Creates a new descriptor loading action. + /// + /// Name of the loading action. + /// Callback to perform the loading action. + /// The plugin descriptor to create the action for. public DescriptorLoadingAction( string actionName, Action action, @@ -23,21 +32,32 @@ SpaceWarpPluginDescriptor plugin _plugin = plugin; } + /// + /// Performs the loading action. + /// + /// Callback to call when the action is resolved. + /// Callback to call when the action is rejected. public override void DoAction(Action resolve, Action reject) { try { if (_plugin.DoLoadingActions) + { _action(_plugin); + } resolve(); } catch (Exception e) { if (_plugin.Plugin != null) + { _plugin.Plugin.SWLogger.LogError(e.ToString()); + } else + { SpaceWarpPlugin.Logger.LogError(_plugin.SWInfo.Name + ": " + e); + } reject(null); } diff --git a/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs b/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs index 08e917f..f54c7c6 100644 --- a/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs +++ b/src/SpaceWarp.Core/Patching/LoadingActions/ModLoadingAction.cs @@ -6,6 +6,9 @@ namespace SpaceWarp.Patching.LoadingActions; // TODO: Move this to SpaceWarp.API.Loading in 2.0.0 +/// +/// A general loading action for a SpaceWarp mod plugin. +/// [Obsolete("This will be moved to SpaceWarp.API.Loading in 2.0.0")] [PublicAPI] public class ModLoadingAction : FlowAction @@ -13,6 +16,12 @@ public class ModLoadingAction : FlowAction private Action _action; private BaseSpaceWarpPlugin _plugin; + /// + /// Creates a new mod plugin loading action. + /// + /// Name of the loading action. + /// Callback to perform the loading action. + /// The mod plugin to create the action for. public ModLoadingAction( string actionName, Action action, @@ -23,6 +32,11 @@ BaseSpaceWarpPlugin plugin _plugin = plugin; } + /// + /// Performs the loading action. + /// + /// Callback to call when the action is resolved. + /// Callback to call when the action is rejected. public override void DoAction(Action resolve, Action reject) { try diff --git a/src/SpaceWarp.Core/Patching/Mods/ModLoaderPatch.cs b/src/SpaceWarp.Core/Patching/Mods/ModLoaderPatch.cs index eb59403..edadbd1 100644 --- a/src/SpaceWarp.Core/Patching/Mods/ModLoaderPatch.cs +++ b/src/SpaceWarp.Core/Patching/Mods/ModLoaderPatch.cs @@ -39,10 +39,13 @@ private static ModInfo KspToSwinfo(KSP2Mod mod) return newInfo; } - [HarmonyPrefix] + [HarmonyPatch(nameof(KSP2Mod.Load))] + [HarmonyPrefix] + // ReSharper disable InconsistentNaming private static bool LoadPre(KSP2Mod __instance, ref bool __result, out bool __state) { + // ReSharper restore InconsistentNaming SpaceWarpPlugin.Logger.LogInfo($"KSP2Mod.Load (Pre): {__instance.ModName}"); var path = __instance.ModRootPath; var info = File.Exists(Path.Combine(path, "swinfo.json")) @@ -53,10 +56,12 @@ private static bool LoadPre(KSP2Mod __instance, ref bool __result, out bool __st return !disabled; } - [HarmonyPostfix] [HarmonyPatch(nameof(KSP2Mod.Load))] + [HarmonyPostfix] + // ReSharper disable InconsistentNaming private static void LoadPost(KSP2Mod __instance, ref bool __result, ref bool __state) { + // ReSharper restore InconsistentNaming SpaceWarpPlugin.Logger.LogInfo($"KSP2Mod.Load (Post): {__instance.ModName}"); if (__state) return; var path = __instance.ModRootPath; @@ -99,8 +104,8 @@ private static void LoadPost(KSP2Mod __instance, ref bool __result, ref bool __s } private static bool LoadCodeBasedMod( - KSP2Mod __instance, - ref bool __result, + KSP2Mod instance, + ref bool result, GameObject go, ref ISpaceWarpMod swMod, ref bool addAdapter, @@ -109,19 +114,26 @@ ref bool isSWMod ) { // Lets take a simple guess at what needs to be done. - if (File.Exists(Path.Combine(__instance.ModRootPath, __instance.EntryPoint))) + if (File.Exists(Path.Combine(instance.ModRootPath, instance.EntryPoint))) { - if (__instance.EntryPoint.EndsWith(".dll")) + if (instance.EntryPoint.EndsWith(".dll")) { - if (LoadModWithDLLEntryPoint(__instance, ref __result, go, ref swMod, ref addAdapter, ref configFile, - ref isSWMod)) + if (LoadModWithDLLEntryPoint( + instance, + ref result, + go, + ref swMod, + ref addAdapter, + ref configFile, + ref isSWMod + )) { return true; } } - else if (__instance.EntryPoint.EndsWith(".lua")) + else if (instance.EntryPoint.EndsWith(".lua")) { - if (LoadModWithLuaEntryPoint(__instance, ref __result)) + if (LoadModWithLuaEntryPoint(instance, ref result)) { return true; } @@ -129,32 +141,32 @@ ref bool isSWMod } else { - __instance.modType = KSP2ModType.Error; - __result = false; + instance.modType = KSP2ModType.Error; + result = false; return true; } return false; } - private static bool LoadModWithLuaEntryPoint(KSP2Mod __instance, ref bool __result) + private static bool LoadModWithLuaEntryPoint(KSP2Mod instance, ref bool result) { try { - __instance.modCore = new KSP2LuaModCore( - __instance.APIVersion, - __instance.ModName, - __instance.EntryPoint, - __instance.ModRootPath + instance.modCore = new KSP2LuaModCore( + instance.APIVersion, + instance.ModName, + instance.EntryPoint, + instance.ModRootPath ); - __instance.modType = KSP2ModType.Lua; - __instance.currentState = KSP2ModState.Active; + instance.modType = KSP2ModType.Lua; + instance.currentState = KSP2ModState.Active; } catch (Exception e) { SpaceWarpPlugin.Logger.LogError(e); - __instance.modType = KSP2ModType.Error; - __result = false; + instance.modType = KSP2ModType.Error; + result = false; return true; } @@ -162,8 +174,8 @@ private static bool LoadModWithLuaEntryPoint(KSP2Mod __instance, ref bool __resu } private static bool LoadModWithDLLEntryPoint( - KSP2Mod __instance, - ref bool __result, + KSP2Mod instance, + ref bool result, GameObject go, ref ISpaceWarpMod swMod, ref bool addAdapter, @@ -173,8 +185,8 @@ ref bool isSWMod { try { - var asm = Assembly.LoadFile(Path.Combine(__instance.ModRootPath, __instance.EntryPoint)); - __instance.modType = KSP2ModType.CSharp; + var asm = Assembly.LoadFile(Path.Combine(instance.ModRootPath, instance.EntryPoint)); + instance.modType = KSP2ModType.CSharp; foreach (var type in asm.GetTypes()) { if (!typeof(Mod).IsAssignableFrom(type) || type.IsAbstract) @@ -190,22 +202,22 @@ ref bool isSWMod SpaceWarpPlugin.Logger.LogInfo($"Loading mod: {comp}"); isSWMod = true; - baseKspLoaderSpaceWarpMod.SWLogger = new UnityLogSource(__instance.ModName); + baseKspLoaderSpaceWarpMod.SWLogger = new UnityLogSource(instance.ModName); // baseKspLoaderSpaceWarpMod.modFolder = __instance.ModRootPath; configFile = baseKspLoaderSpaceWarpMod.SWConfiguration = new JsonConfigFile( - Path.Combine(__instance.ModRootPath, "config.cfg") + Path.Combine(instance.ModRootPath, "config.cfg") ); swMod = baseKspLoaderSpaceWarpMod; addAdapter = false; } - __instance.currentState = KSP2ModState.Active; + instance.currentState = KSP2ModState.Active; } catch (Exception e) { SpaceWarpPlugin.Logger.LogError(e); - __instance.modType = KSP2ModType.Error; - __result = false; + instance.modType = KSP2ModType.Error; + result = false; return true; } diff --git a/src/SpaceWarp.Core/Patching/Parts/PartOwnerComponentConstructor.cs b/src/SpaceWarp.Core/Patching/Parts/PartOwnerComponentConstructor.cs index 38eab41..4eea15c 100644 --- a/src/SpaceWarp.Core/Patching/Parts/PartOwnerComponentConstructor.cs +++ b/src/SpaceWarp.Core/Patching/Parts/PartOwnerComponentConstructor.cs @@ -12,6 +12,7 @@ internal static class PartOwnerComponentConstructor typeof(PartOwnerComponent).GetField("HasRegisteredPartComponentsForFixedUpdate"); [HarmonyPatch(MethodType.Constructor)] + // ReSharper disable once InconsistentNaming private static void SetFalse(PartOwnerComponent __instance) { AddedField.SetValue(__instance, false); @@ -19,6 +20,7 @@ private static void SetFalse(PartOwnerComponent __instance) [HarmonyPatch(nameof(PartOwnerComponent.Add))] [HarmonyPrefix] + // ReSharper disable once InconsistentNaming private static void CheckForModule(PartOwnerComponent __instance, PartComponent part) { var currentValue = (bool)AddedField.GetValue(__instance); diff --git a/src/SpaceWarp.Core/Patching/Settings/ConfigurationManagerPatch.cs b/src/SpaceWarp.Core/Patching/Settings/ConfigurationManagerPatch.cs index b38535d..10027f4 100644 --- a/src/SpaceWarp.Core/Patching/Settings/ConfigurationManagerPatch.cs +++ b/src/SpaceWarp.Core/Patching/Settings/ConfigurationManagerPatch.cs @@ -10,6 +10,7 @@ internal class ConfigurationManagerPatch { [HarmonyPatch(typeof(Utils), nameof(Utils.FindPlugins))] [HarmonyPostfix] + // ReSharper disable once InconsistentNaming private static void FindPluginsPatch(ref BaseUnityPlugin[] __result) { //Disable because I know what I am doing. diff --git a/src/SpaceWarp.Core/Patching/System/FixGetTypes.cs b/src/SpaceWarp.Core/Patching/System/FixGetTypes.cs index 0932b4c..db80610 100644 --- a/src/SpaceWarp.Core/Patching/System/FixGetTypes.cs +++ b/src/SpaceWarp.Core/Patching/System/FixGetTypes.cs @@ -10,8 +10,10 @@ internal static class FixGetTypes [HarmonyPatch(typeof(Assembly), nameof(Assembly.GetTypes), new Type[0])] [HarmonyPatch(typeof(Assembly), nameof(Assembly.GetExportedTypes))] [HarmonyFinalizer] + // ReSharper disable InconsistentNaming private static Exception GetTypesFix(Exception __exception, Assembly __instance, ref Type[] __result) { + // ReSharper restore InconsistentNaming if (__exception is not ReflectionTypeLoadException reflectionTypeLoadException) { return __exception; @@ -20,7 +22,8 @@ private static Exception GetTypesFix(Exception __exception, Assembly __instance, var logger = new ManualLogSource("FixGetTypes"); logger.LogWarning( - $"Types failed to load from assembly {__instance.FullName} due to the reasons below, continuing anyway."); + $"Types failed to load from assembly {__instance.FullName} due to the reasons below, continuing anyway." + ); logger.LogWarning($"Exception: {__exception}"); foreach (var exception in reflectionTypeLoadException.LoaderExceptions) From c512883b4ca74e0eb105ec7a0a93c3af75fb5efe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 22:27:32 +0100 Subject: [PATCH 37/82] Fixed SpaceWarp.Game warnings --- .../Game/Extensions/PartProviderExtensions.cs | 9 + .../Extensions/VesselVehicleExtensions.cs | 125 +++++++++++++- .../API/Game/Messages/StateChanges.cs | 158 ++++++++++++++++++ .../API/Game/Messages/StateLoadings.cs | 26 +++ src/SpaceWarp.Game/API/Game/Vehicle.cs | 10 ++ src/SpaceWarp.Game/Modules/Game.cs | 17 +- 6 files changed, 331 insertions(+), 14 deletions(-) diff --git a/src/SpaceWarp.Game/API/Game/Extensions/PartProviderExtensions.cs b/src/SpaceWarp.Game/API/Game/Extensions/PartProviderExtensions.cs index e939bf7..353a764 100644 --- a/src/SpaceWarp.Game/API/Game/Extensions/PartProviderExtensions.cs +++ b/src/SpaceWarp.Game/API/Game/Extensions/PartProviderExtensions.cs @@ -4,9 +4,18 @@ namespace SpaceWarp.API.Game.Extensions; +/// +/// Extensions for . +/// [PublicAPI] public static class PartProviderExtensions { + /// + /// Gets all parts with a module of type . + /// + /// The part provider. + /// The module type. + /// All parts with a module of type . public static IEnumerable WithModule(this PartProvider provider) where T : ModuleData { return provider._partData.Values.Where(part => part.modules.OfType().Any()); diff --git a/src/SpaceWarp.Game/API/Game/Extensions/VesselVehicleExtensions.cs b/src/SpaceWarp.Game/API/Game/Extensions/VesselVehicleExtensions.cs index e8b4df6..b7553b2 100644 --- a/src/SpaceWarp.Game/API/Game/Extensions/VesselVehicleExtensions.cs +++ b/src/SpaceWarp.Game/API/Game/Extensions/VesselVehicleExtensions.cs @@ -5,9 +5,17 @@ namespace SpaceWarp.API.Game.Extensions; +/// +/// Extensions for . +/// [PublicAPI] public static class VesselVehicleExtensions { + /// + /// Sets the throttle of the vessel. + /// + /// The vessel. + /// The throttle value. public static void SetMainThrottle(this VesselVehicle vehicle, float throttle) { var incremental = new FlightCtrlStateIncremental @@ -17,6 +25,11 @@ public static void SetMainThrottle(this VesselVehicle vehicle, float throttle) vehicle.AtomicSet(incremental); } + /// + /// Sets the roll of the vessel. + /// + /// The vessel. + /// The roll value. public static void SetRoll(this VesselVehicle vehicle, float roll) { var incremental = new FlightCtrlStateIncremental @@ -26,6 +39,11 @@ public static void SetRoll(this VesselVehicle vehicle, float roll) vehicle.AtomicSet(incremental); } + /// + /// Sets the yaw of the vessel. + /// + /// The vessel. + /// The yaw value. public static void SetYaw(this VesselVehicle vehicle, float yaw) { var incremental = new FlightCtrlStateIncremental @@ -35,6 +53,11 @@ public static void SetYaw(this VesselVehicle vehicle, float yaw) vehicle.AtomicSet(incremental); } + /// + /// Sets the pitch of the vessel. + /// + /// The vessel. + /// The pitch value. public static void SetPitch(this VesselVehicle vehicle, float pitch) { var incremental = new FlightCtrlStateIncremental @@ -44,6 +67,13 @@ public static void SetPitch(this VesselVehicle vehicle, float pitch) vehicle.AtomicSet(incremental); } + /// + /// Sets the roll, yaw and pitch of the vessel. + /// + /// The vessel. + /// The roll value. + /// The yaw value. + /// The pitch value. public static void SetRollYawPitch(this VesselVehicle vehicle, float roll, float yaw, float pitch) { var incremental = new FlightCtrlStateIncremental @@ -55,6 +85,11 @@ public static void SetRollYawPitch(this VesselVehicle vehicle, float roll, float vehicle.AtomicSet(incremental); } + /// + /// Sets the roll trim of the vessel. + /// + /// The vessel. + /// The roll trim value. public static void SetRollTrim(this VesselVehicle vehicle, float rollTrim) { var incremental = new FlightCtrlStateIncremental @@ -64,6 +99,11 @@ public static void SetRollTrim(this VesselVehicle vehicle, float rollTrim) vehicle.AtomicSet(incremental); } + /// + /// Sets the yaw trim of the vessel. + /// + /// The vessel. + /// The yaw trim value. public static void SetYawTrim(this VesselVehicle vehicle, float yawTrim) { var incremental = new FlightCtrlStateIncremental @@ -73,6 +113,11 @@ public static void SetYawTrim(this VesselVehicle vehicle, float yawTrim) vehicle.AtomicSet(incremental); } + /// + /// Sets the pitch trim of the vessel. + /// + /// The vessel. + /// The pitch trim value. public static void SetPitchTrim(this VesselVehicle vehicle, float pitchTrim) { var incremental = new FlightCtrlStateIncremental @@ -83,6 +128,13 @@ public static void SetPitchTrim(this VesselVehicle vehicle, float pitchTrim) } + /// + /// Sets the roll, yaw and pitch trim of the vessel. + /// + /// The vessel. + /// The roll trim value. + /// The yaw trim value. + /// The pitch trim value. public static void SetRollYawPitchTrim(this VesselVehicle vehicle, float rollTrim, float yawTrim, float pitchTrim) { var incremental = new FlightCtrlStateIncremental @@ -94,6 +146,11 @@ public static void SetRollYawPitchTrim(this VesselVehicle vehicle, float rollTri vehicle.AtomicSet(incremental); } + /// + /// Sets the input roll of the vessel. + /// + /// The vessel. + /// The input roll value. public static void SetInputRoll(this VesselVehicle vehicle, float roll) { var incremental = new FlightCtrlStateIncremental @@ -103,6 +160,11 @@ public static void SetInputRoll(this VesselVehicle vehicle, float roll) vehicle.AtomicSet(incremental); } + /// + /// Sets the input yaw of the vessel. + /// + /// The vessel. + /// The input yaw value. public static void SetInputYaw(this VesselVehicle vehicle, float yaw) { var incremental = new FlightCtrlStateIncremental @@ -112,6 +174,11 @@ public static void SetInputYaw(this VesselVehicle vehicle, float yaw) vehicle.AtomicSet(incremental); } + /// + /// Sets the input pitch of the vessel. + /// + /// The vessel. + /// The input pitch value. public static void SetInputPitch(this VesselVehicle vehicle, float pitch) { var incremental = new FlightCtrlStateIncremental @@ -121,6 +188,13 @@ public static void SetInputPitch(this VesselVehicle vehicle, float pitch) vehicle.AtomicSet(incremental); } + /// + /// Sets the input roll, yaw and pitch of the vessel. + /// + /// The vessel. + /// The input roll value. + /// The input yaw value. + /// The input pitch value. public static void SetInputRollYawPitch(this VesselVehicle vehicle, float roll, float yaw, float pitch) { var incremental = new FlightCtrlStateIncremental @@ -132,6 +206,12 @@ public static void SetInputRollYawPitch(this VesselVehicle vehicle, float roll, vehicle.AtomicSet(incremental); } + /// + /// Sets the wheel steer and wheel steer trim of the vessel. + /// + /// The vessel. + /// The wheel steer value. + /// The wheel steer trim value. public static void SetWheelSteer(this VesselVehicle vehicle, float wheelSteer, float? wheelSteerTrim = null) { var incremental = new FlightCtrlStateIncremental @@ -142,6 +222,12 @@ public static void SetWheelSteer(this VesselVehicle vehicle, float wheelSteer, f vehicle.AtomicSet(incremental); } + /// + /// Sets the wheel throttle and wheel throttle trim of the vessel. + /// + /// The vessel. + /// The wheel throttle value. + /// The wheel throttle trim value. public static void SetWheelThrottle(this VesselVehicle vehicle, float wheelThrottle, float? wheelThrottleTrim = null) { @@ -153,6 +239,13 @@ public static void SetWheelThrottle(this VesselVehicle vehicle, float wheelThrot vehicle.AtomicSet(incremental); } + /// + /// Sets the X, Y and Z values of the vessel. + /// + /// The vessel. + /// The X orientation value. + /// The Y orientation value. + /// The Z orientation value. public static void SetXYZ(this VesselVehicle vehicle, float? x = null, float? y = null, float? z = null) { var incremental = new FlightCtrlStateIncremental @@ -164,6 +257,11 @@ public static void SetXYZ(this VesselVehicle vehicle, float? x = null, float? y vehicle.AtomicSet(incremental); } + /// + /// Sets the X, Y and Z values of the vessel. + /// + /// The vessel. + /// The X, Y and Z vector. public static void SetXYZ(this VesselVehicle vehicle, Vector3 xyz) { var incremental = new FlightCtrlStateIncremental @@ -175,6 +273,11 @@ public static void SetXYZ(this VesselVehicle vehicle, Vector3 xyz) vehicle.AtomicSet(incremental); } + /// + /// Sets the kill rotation value of the vessel. + /// + /// + /// public static void SetKillRot(this VesselVehicle vehicle, bool killRot) { var incremental = new FlightCtrlStateIncremental @@ -184,6 +287,11 @@ public static void SetKillRot(this VesselVehicle vehicle, bool killRot) vehicle.AtomicSet(incremental); } + /// + /// Sets the gear state of the vessel. + /// + /// The vessel. + /// Whether the gear is up. public static void SetGearState(this VesselVehicle vehicle, bool up) { var incremental = new FlightCtrlStateIncremental @@ -194,7 +302,11 @@ public static void SetGearState(this VesselVehicle vehicle, bool up) vehicle.AtomicSet(incremental); } - + /// + /// Sets the headlight state of the vessel. + /// + /// The vessel. + /// Whether the headlight is on. public static void SetHeadlight(this VesselVehicle vehicle, bool on) { var incremental = new FlightCtrlStateIncremental @@ -204,7 +316,11 @@ public static void SetHeadlight(this VesselVehicle vehicle, bool on) vehicle.AtomicSet(incremental); } - + /// + /// Sets the brake state of the vessel. + /// + /// The vessel. + /// Whether the brakes are on. public static void SetBrake(this VesselVehicle vehicle, bool on) { var incremental = new FlightCtrlStateIncremental @@ -214,6 +330,11 @@ public static void SetBrake(this VesselVehicle vehicle, bool on) vehicle.AtomicSet(incremental); } + /// + /// Sets the staging state of the vessel. + /// + /// The vessel. + /// Whether to stage. public static void SetStage(this VesselVehicle vehicle, bool stage) { var incremental = new FlightCtrlStateIncremental diff --git a/src/SpaceWarp.Game/API/Game/Messages/StateChanges.cs b/src/SpaceWarp.Game/API/Game/Messages/StateChanges.cs index 308268e..9169369 100644 --- a/src/SpaceWarp.Game/API/Game/Messages/StateChanges.cs +++ b/src/SpaceWarp.Game/API/Game/Messages/StateChanges.cs @@ -22,50 +22,208 @@ public static class StateChanges #region Entering States + /// + /// Invoked when the game state is changed to + /// public static event Action InvalidStateEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action WarmUpLoadingStateEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action MainMenuStateEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action KerbalSpaceCenterStateEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action VehicleAssemblyBuilderEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action BaseAssemblyEditorEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action FlightViewEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action ColonyViewEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action Map3DViewEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action PhotoModeEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action MetricsModeEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action PlanetViewerEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action LoadingEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action TrainingCenterEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action MissionControlEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action TrackingStationEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action ResearchAndDevelopmentEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action LaunchpadEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action RunwayEntered; + + /// + /// Invoked when the game state is changed to + /// public static event Action FlagEntered; #endregion #region Leaving States + /// + /// Invoked when the game state is changed from + /// public static event Action InvalidStateLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action WarmUpLoadingStateLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action MainMenuStateLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action KerbalSpaceCenterStateLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action VehicleAssemblyBuilderLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action BaseAssemblyEditorLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action FlightViewLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action ColonyViewLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action PhotoModeLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action Map3DViewLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action MetricsModeLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action PlanetViewerLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action LoadingLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action TrainingCenterLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action MissionControlLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action TrackingStationLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action ResearchAndDevelopmentLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action LaunchpadLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action RunwayLeft; + + /// + /// Invoked when the game state is changed from + /// public static event Action FlagLeft; #endregion diff --git a/src/SpaceWarp.Game/API/Game/Messages/StateLoadings.cs b/src/SpaceWarp.Game/API/Game/Messages/StateLoadings.cs index 2ea1ce1..df232a4 100644 --- a/src/SpaceWarp.Game/API/Game/Messages/StateLoadings.cs +++ b/src/SpaceWarp.Game/API/Game/Messages/StateLoadings.cs @@ -3,21 +3,47 @@ namespace SpaceWarp.API.Game.Messages; +/// +/// Messages related to the loading of game states. +/// [PublicAPI] public class StateLoadings { + /// + /// Invoked when the training center is loaded. + /// public static event Action TrainingCenterLoaded; + /// + /// Invoked when the tracking station is loaded. + /// public static event Action TrackingStationLoaded; + /// + /// Invoked when the tracking station is unloaded. + /// public static event Action TrackingStationUnloaded; + + /// + /// Handler for the evenr. + /// + /// The associated message. public static void TrainingCenterLoadedHandler(MessageCenterMessage message) { TrainingCenterLoaded?.Invoke(message as TrainingCenterLoadedMessage); } + + /// + /// Handler for the event. + /// + /// The associated message. public static void TrackingStationLoadedHandler(MessageCenterMessage message) { TrackingStationLoaded?.Invoke(message as TrackingStationLoadedMessage); } + /// + /// Handler for the event. + /// + /// The associated message. public static void TrackingStationUnloadedHandler(MessageCenterMessage message) { TrackingStationUnloaded?.Invoke(message as TrackingStationUnloadedMessage); diff --git a/src/SpaceWarp.Game/API/Game/Vehicle.cs b/src/SpaceWarp.Game/API/Game/Vehicle.cs index 6890297..9372bdf 100644 --- a/src/SpaceWarp.Game/API/Game/Vehicle.cs +++ b/src/SpaceWarp.Game/API/Game/Vehicle.cs @@ -5,10 +5,20 @@ namespace SpaceWarp.API.Game; +/// +/// Vehicle related API. +/// [SpaceWarpLuaAPI("Vehicle")] [PublicAPI] public static class Vehicle { + /// + /// Gets the active vessel. + /// public static VesselVehicle ActiveVesselVehicle => GameManager.Instance.Game.ViewController._activeVesselVehicle; + + /// + /// Gets the active vessel component. + /// public static VesselComponent ActiveSimVessel => GameManager.Instance.Game.ViewController.GetActiveSimVessel(); } \ No newline at end of file diff --git a/src/SpaceWarp.Game/Modules/Game.cs b/src/SpaceWarp.Game/Modules/Game.cs index 461156f..c9db243 100644 --- a/src/SpaceWarp.Game/Modules/Game.cs +++ b/src/SpaceWarp.Game/Modules/Game.cs @@ -5,19 +5,16 @@ namespace SpaceWarp.Modules; +/// +/// The module for game-related APIs. +/// [UsedImplicitly] public class Game : SpaceWarpModule { + /// public override string Name => "SpaceWarp.Game"; - public override void LoadModule() - { - } - - public override void PreInitializeModule() - { - } - + /// public override void InitializeModule() { var game = GameManager.Instance.Game; @@ -28,8 +25,4 @@ public override void InitializeModule() game.Messages.Subscribe(typeof(TrackingStationUnloadedMessage), StateLoadings.TrackingStationUnloadedHandler, false, true); game.Messages.Subscribe(typeof(TrainingCenterLoadedMessage), StateLoadings.TrainingCenterLoadedHandler, false, true); } - - public override void PostInitializeModule() - { - } } \ No newline at end of file From a522ec08b5fc18a2738d2f764b2c9421c9ae7665 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 23:00:05 +0100 Subject: [PATCH 38/82] Fixed SpaceWarp.Messaging warnings --- .../API/Messaging/MessageBus.cs | 270 ++++++++++++++++++ .../API/Messaging/MessageBusBase.cs | 6 + .../API/Messaging/MessageBusManager.cs | 155 ++++++---- src/SpaceWarp.Messaging/Modules/Messaging.cs | 19 +- 4 files changed, 381 insertions(+), 69 deletions(-) diff --git a/src/SpaceWarp.Messaging/API/Messaging/MessageBus.cs b/src/SpaceWarp.Messaging/API/Messaging/MessageBus.cs index 2a5b426..3659025 100644 --- a/src/SpaceWarp.Messaging/API/Messaging/MessageBus.cs +++ b/src/SpaceWarp.Messaging/API/Messaging/MessageBus.cs @@ -2,6 +2,9 @@ namespace SpaceWarp.API.Messaging; +/// +/// MessageBus that can be used to publish messages with no arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -9,21 +12,42 @@ public class MessageBus : MessageBusBase internal override IReadOnlyList Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) + { throw new ArgumentNullException(); + } _handlers.Add(handler); } + /// + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) + { if (_handlers[i] == handler) + { _handlers.RemoveAt(i); + } + } } + /// + /// Publishes a message to all subscribers. + /// + /// + /// Publishes a message to all subscribers. + /// public void Publish() { for (var i = _handlers.Count; i-- > 0;) @@ -40,6 +64,9 @@ public void Publish() } } +/// +/// MessageBus that can be used to publish messages with 1 argument to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -47,21 +74,39 @@ public class MessageBus : MessageBusBase internal override IReadOnlyList Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) + { throw new ArgumentNullException(); + } _handlers.Add(handler); } + /// + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) + { if (_handlers[i] == handler) + { _handlers.RemoveAt(i); + } + } } + /// + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0) { for (var i = _handlers.Count; i-- > 0;) @@ -78,6 +123,9 @@ public void Publish(T1 arg0) } } +/// +/// MessageBus that can be used to publish messages with 2 argument to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -85,6 +133,11 @@ public class MessageBus : MessageBusBase internal override IReadOnlyList Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -93,6 +146,10 @@ public void Subscribe(Action handler) _handlers.Add(handler); } + /// + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (int i = _handlers.Count; i-- > 0;) @@ -100,6 +157,9 @@ public void Unsubscribe(Action handler) _handlers.RemoveAt(i); } + /// + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1) { for (var i = _handlers.Count; i-- > 0;) @@ -116,6 +176,9 @@ public void Publish(T1 arg0, T2 arg1) } } +/// +/// MessageBus that can be used to publish messages with 3 arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -123,6 +186,11 @@ public class MessageBus : MessageBusBase internal override IReadOnlyList Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -131,6 +199,10 @@ public void Subscribe(Action handler) _handlers.Add(handler); } + /// + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) @@ -138,6 +210,9 @@ public void Unsubscribe(Action handler) _handlers.RemoveAt(i); } + /// + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1, T3 arg2) { for (var i = _handlers.Count; i-- > 0;) @@ -154,6 +229,9 @@ public void Publish(T1 arg0, T2 arg1, T3 arg2) } } +/// +/// MessageBus that can be used to publish messages with 4 arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -161,6 +239,11 @@ public class MessageBus : MessageBusBase internal override IReadOnlyList Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -169,6 +252,10 @@ public void Subscribe(Action handler) _handlers.Add(handler); } + /// + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) @@ -176,6 +263,9 @@ public void Unsubscribe(Action handler) _handlers.RemoveAt(i); } + /// + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3) { for (var i = _handlers.Count; i-- > 0;) @@ -192,6 +282,9 @@ public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3) } } +/// +/// MessageBus that can be used to publish messages with 5 arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -199,6 +292,11 @@ public class MessageBus : MessageBusBase internal override IReadOnlyList Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -207,6 +305,10 @@ public void Subscribe(Action handler) _handlers.Add(handler); } + /// + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) @@ -214,6 +316,9 @@ public void Unsubscribe(Action handler) _handlers.RemoveAt(i); } + /// + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4) { for (var i = _handlers.Count; i-- > 0;) @@ -230,6 +335,9 @@ public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4) } } +/// +/// MessageBus that can be used to publish messages with 6 arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -237,6 +345,11 @@ public class MessageBus : MessageBusBase internal override IReadOnlyList Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -245,6 +358,10 @@ public void Subscribe(Action handler) _handlers.Add(handler); } + /// + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) @@ -252,6 +369,9 @@ public void Unsubscribe(Action handler) _handlers.RemoveAt(i); } + /// + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5) { for (var i = _handlers.Count; i-- > 0;) @@ -268,6 +388,9 @@ public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5) } } +/// +/// MessageBus that can be used to publish messages with 7 arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -275,6 +398,11 @@ public class MessageBus : MessageBusBase internal override IReadOnlyList Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -283,6 +411,10 @@ public void Subscribe(Action handler) _handlers.Add(handler); } + /// + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) @@ -290,6 +422,9 @@ public void Unsubscribe(Action handler) _handlers.RemoveAt(i); } + /// + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg6) { for (var i = _handlers.Count; i-- > 0;) @@ -306,6 +441,9 @@ public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg } } +/// +/// MessageBus that can be used to publish messages with 8 arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -313,6 +451,11 @@ public class MessageBus : MessageBusBase internal override IReadOnlyList Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -321,6 +464,10 @@ public void Subscribe(Action handler) _handlers.Add(handler); } + /// + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) @@ -328,6 +475,9 @@ public void Unsubscribe(Action handler) _handlers.RemoveAt(i); } + /// + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg6, T8 arg7) { for (var i = _handlers.Count; i-- > 0;) @@ -344,6 +494,9 @@ public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg } } +/// +/// MessageBus that can be used to publish messages with 9 arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -351,6 +504,11 @@ public class MessageBus : MessageBusBase internal override IReadOnlyList Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -359,6 +517,10 @@ public void Subscribe(Action handler) _handlers.Add(handler); } + /// + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) @@ -366,6 +528,9 @@ public void Unsubscribe(Action handler) _handlers.RemoveAt(i); } + /// + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg6, T8 arg7, T9 arg8) { for (var i = _handlers.Count; i-- > 0;) @@ -382,6 +547,9 @@ public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg } } +/// +/// MessageBus that can be used to publish messages with 10 arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -389,6 +557,11 @@ public class MessageBus : MessageBusBas internal override IReadOnlyList Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -397,6 +570,10 @@ public void Subscribe(Action handler) _handlers.Add(handler); } + /// + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) @@ -404,6 +581,9 @@ public void Unsubscribe(Action handler) _handlers.RemoveAt(i); } + /// + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg6, T8 arg7, T9 arg8, T10 arg9) { for (var i = _handlers.Count; i-- > 0;) @@ -420,6 +600,9 @@ public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg } } +/// +/// MessageBus that can be used to publish messages with 11 arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -427,6 +610,11 @@ public class MessageBus : MessageB internal override IReadOnlyList Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -435,6 +623,10 @@ public void Subscribe(Action handl _handlers.Add(handler); } + /// + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) @@ -442,6 +634,9 @@ public void Unsubscribe(Action han _handlers.RemoveAt(i); } + /// + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg6, T8 arg7, T9 arg8, T10 arg9, T11 arg10) { @@ -459,6 +654,9 @@ public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg } } +/// +/// MessageBus that can be used to publish messages with 12 arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -466,6 +664,11 @@ public class MessageBus : Mes internal override IReadOnlyList Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -474,6 +677,10 @@ public void Subscribe(Action _handlers.Add(handler); } + /// + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) @@ -481,6 +688,9 @@ public void Unsubscribe(Action + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg6, T8 arg7, T9 arg8, T10 arg9, T11 arg10, T12 arg11) { @@ -498,6 +708,9 @@ public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg } } +/// +/// MessageBus that can be used to publish messages with 13 arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -505,6 +718,11 @@ public class MessageBus internal override IReadOnlyList Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -513,6 +731,10 @@ public void Subscribe(Action + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) @@ -520,6 +742,9 @@ public void Unsubscribe(Action + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg6, T8 arg7, T9 arg8, T10 arg9, T11 arg10, T12 arg11, T13 arg12) { @@ -537,6 +762,9 @@ public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg } } +/// +/// MessageBus that can be used to publish messages with 14 arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -544,6 +772,11 @@ public class MessageBus Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -552,6 +785,10 @@ public void Subscribe(Action + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) @@ -559,6 +796,9 @@ public void Unsubscribe(Action + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg6, T8 arg7, T9 arg8, T10 arg9, T11 arg10, T12 arg11, T13 arg12, T14 arg13) { @@ -577,6 +817,9 @@ public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg } } +/// +/// MessageBus that can be used to publish messages with 15 arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -584,6 +827,11 @@ public class MessageBus Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -592,6 +840,10 @@ public void Subscribe(Action + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) @@ -599,6 +851,9 @@ public void Unsubscribe(Action + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg6, T8 arg7, T9 arg8, T10 arg9, T11 arg10, T12 arg11, T13 arg12, T14 arg13, T15 arg14) { @@ -617,6 +872,9 @@ public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg } } +/// +/// MessageBus that can be used to publish messages with 16 arguments to subscribers. +/// [PublicAPI] public class MessageBus : MessageBusBase { @@ -626,6 +884,11 @@ public class MessageBus Handlers => _handlers; internal override void RemoveHandlerAt(int index) => _handlers.RemoveAt(index); + /// + /// Subscribes a handler to the MessageBus. + /// + /// The handler to subscribe. + /// Thrown when the handler is null. public void Subscribe(Action handler) { if (handler == null) @@ -634,6 +897,10 @@ public void Subscribe(Action + /// Unsubscribes a handler from the MessageBus. + /// + /// The handler to unsubscribe. public void Unsubscribe(Action handler) { for (var i = _handlers.Count; i-- > 0;) @@ -641,6 +908,9 @@ public void Unsubscribe(Action + /// Publishes a message to all subscribers. + /// public void Publish(T1 arg0, T2 arg1, T3 arg2, T4 arg3, T5 arg4, T6 arg5, T7 arg6, T8 arg7, T9 arg8, T10 arg9, T11 arg10, T12 arg11, T13 arg12, T14 arg13, T15 arg14, T16 arg15) { diff --git a/src/SpaceWarp.Messaging/API/Messaging/MessageBusBase.cs b/src/SpaceWarp.Messaging/API/Messaging/MessageBusBase.cs index 0fe45c2..7fd7547 100644 --- a/src/SpaceWarp.Messaging/API/Messaging/MessageBusBase.cs +++ b/src/SpaceWarp.Messaging/API/Messaging/MessageBusBase.cs @@ -2,9 +2,15 @@ namespace SpaceWarp.API.Messaging; +/// +/// A base class for MessageBus instances. +/// [PublicAPI] public abstract class MessageBusBase { + /// + /// The name of the MessageBus. + /// public string Name { get; internal set; } internal abstract IReadOnlyList Handlers { get; } internal abstract void RemoveHandlerAt(int index); diff --git a/src/SpaceWarp.Messaging/API/Messaging/MessageBusManager.cs b/src/SpaceWarp.Messaging/API/Messaging/MessageBusManager.cs index cc68732..9c716a0 100644 --- a/src/SpaceWarp.Messaging/API/Messaging/MessageBusManager.cs +++ b/src/SpaceWarp.Messaging/API/Messaging/MessageBusManager.cs @@ -2,77 +2,118 @@ namespace SpaceWarp.API.Messaging; +/// +/// A static class that manages the creation and retrieval of MessageBus instances. +/// [PublicAPI] public static class MessageBusManager { - private static Dictionary _messagesBusesByName = new Dictionary(); + private static Dictionary _messagesBusesByName = new(); - public static T Add(string name) where T : MessageBusBase, new() - { - if (string.IsNullOrEmpty(name)) - throw new ArgumentException("Null or empty MessageBus name"); + /// + /// Creates a new MessageBus instance with the given name. + /// + /// The name of the MessageBus to create. + /// The type of the MessageBus to create. + /// The created MessageBus instance. + /// Thrown when the given name is null or empty. + /// Thrown when a MessageBus with the given name already exists. + public static T Add(string name) where T : MessageBusBase, new() + { + if (string.IsNullOrEmpty(name)) + { + throw new ArgumentException("Null or empty MessageBus name"); + } - if (_messagesBusesByName.ContainsKey(name)) - throw new Exception($"MessageBus '{name}' exists already"); + if (_messagesBusesByName.ContainsKey(name)) + { + throw new Exception($"MessageBus '{name}' exists already"); + } - var messageBus = new T - { - Name = name - }; - _messagesBusesByName.Add(name, messageBus); + var messageBus = new T + { + Name = name + }; + _messagesBusesByName.Add(name, messageBus); - Modules.Messaging.Instance.ModuleLogger.LogDebug($"MessageBus '{name}' created"); - return messageBus; - } + Modules.Messaging.Instance.ModuleLogger.LogDebug($"MessageBus '{name}' created"); + return messageBus; + } - public static bool Exists(string messageBusName) => _messagesBusesByName.ContainsKey(messageBusName); + /// + /// Does a MessageBus with the given name exist? + /// + /// The name of the MessageBus to check. + /// True if a MessageBus with the given name exists, false otherwise. + public static bool Exists(string messageBusName) => _messagesBusesByName.ContainsKey(messageBusName); - public static bool TryGet(string messageBusName, out T messageBus) where T : MessageBusBase, new() - { - if (string.IsNullOrEmpty(messageBusName)) - throw new ArgumentException("Null or empty MessageBus name"); + /// + /// Gets a MessageBus instance with the given name. + /// + /// + /// + /// + /// + /// + /// + public static bool TryGet(string messageBusName, out T messageBus) where T : MessageBusBase, new() + { + if (string.IsNullOrEmpty(messageBusName)) + { + throw new ArgumentException("Null or empty MessageBus name"); + } - if (!_messagesBusesByName.TryGetValue(messageBusName, out MessageBusBase messageBusBase)) - { - messageBus = null; - return false; - } + if (!_messagesBusesByName.TryGetValue(messageBusName, out MessageBusBase messageBusBase)) + { + messageBus = null; + return false; + } - if (messageBusBase is not T @base) - throw new Exception( - $"Message bus '{messageBusBase.Name}' is of type '{messageBusBase.GetType()}' but the requested type was '{typeof(T)}'"); - messageBus = @base; - return true; + if (messageBusBase is not T @base) + { + throw new Exception( + $"Message bus '{messageBusBase.Name}' is of type '{messageBusBase.GetType()}' but the " + + $"requested type was '{typeof(T)}'" + ); + } - } + messageBus = @base; + return true; + } - // Call this (potentially a bit heavy) method on some occasions, for example when a loading screen happens - internal static void CheckForMemoryLeaks() - { - var memoryLeaks = 0; + // Call this (potentially a bit heavy) method on some occasions, for example when a loading screen happens + internal static void CheckForMemoryLeaks() + { + var memoryLeaks = 0; - foreach (var messageBus in _messagesBusesByName.Values) - { - var handlers = messageBus.Handlers; + foreach (var messageBus in _messagesBusesByName.Values) + { + var handlers = messageBus.Handlers; - for (var i = handlers.Count; i-- > 0;) - { - var target = handlers[i].Target; - switch (target) - { - // bypass UnityEngine.Object null equality overload - case null: - continue; - case UnityEngine.Object uObj when uObj == null: - Modules.Messaging.Instance.ModuleLogger.LogDebug($"Memory leak detected : a destroyed instance of the '{target.GetType().Assembly.GetName().Name}:{target.GetType().Name}' class is holding a '{messageBus.Name}' MessageBus handler"); - messageBus.RemoveHandlerAt(i); - memoryLeaks++; - break; - } - } - } + for (var i = handlers.Count; i-- > 0;) + { + var target = handlers[i].Target; + switch (target) + { + // bypass UnityEngine.Object null equality overload + case null: + continue; + case UnityEngine.Object uObj when uObj == null: + Modules.Messaging.Instance.ModuleLogger.LogDebug( + $"Memory leak detected : a destroyed instance of the " + + $"'{target.GetType().Assembly.GetName().Name}:{target.GetType().Name}' class is holding " + + $"a '{messageBus.Name}' MessageBus handler" + ); + messageBus.RemoveHandlerAt(i); + memoryLeaks++; + break; + } + } + } - if (memoryLeaks > 0) - Modules.Messaging.Instance.ModuleLogger.LogDebug($"{memoryLeaks} detected!"); - } + if (memoryLeaks > 0) + { + Modules.Messaging.Instance.ModuleLogger.LogDebug($"{memoryLeaks} detected!"); + } + } } \ No newline at end of file diff --git a/src/SpaceWarp.Messaging/Modules/Messaging.cs b/src/SpaceWarp.Messaging/Modules/Messaging.cs index 861ca15..003f396 100644 --- a/src/SpaceWarp.Messaging/Modules/Messaging.cs +++ b/src/SpaceWarp.Messaging/Modules/Messaging.cs @@ -2,25 +2,20 @@ namespace SpaceWarp.Modules; +/// +/// The messaging module. +/// [PublicAPI] public class Messaging : SpaceWarpModule { + /// public override string Name => "SpaceWarp.Messaging"; + internal static Messaging Instance; + + /// public override void LoadModule() { Instance = this; } - - public override void PreInitializeModule() - { - } - - public override void InitializeModule() - { - } - - public override void PostInitializeModule() - { - } } \ No newline at end of file From 4a4bfa97265c713b6afe8e70ce9359f624e339fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 23:04:10 +0100 Subject: [PATCH 39/82] Fixed SpaceWarp.Sound warnings --- src/SpaceWarp.Sound/API/Sound/Soundbank.cs | 11 ++++++++++ .../API/Sound/SoundbankManager.cs | 21 +++++++++++++++++++ src/SpaceWarp.Sound/Modules/Sound.cs | 18 ++++++---------- 3 files changed, 38 insertions(+), 12 deletions(-) diff --git a/src/SpaceWarp.Sound/API/Sound/Soundbank.cs b/src/SpaceWarp.Sound/API/Sound/Soundbank.cs index d95e376..c9e1d66 100644 --- a/src/SpaceWarp.Sound/API/Sound/Soundbank.cs +++ b/src/SpaceWarp.Sound/API/Sound/Soundbank.cs @@ -3,9 +3,16 @@ namespace SpaceWarp.API.Sound; +/// +/// Represents a Soundbank. +/// [PublicAPI] public class Soundbank { + /// + /// Creates a Soundbank object from bytes. + /// + /// The bytes of the Soundbank. public Soundbank(byte[] bankData) { BankData = bankData; @@ -42,6 +49,10 @@ public Soundbank(byte[] bankData) /// public uint WwiseID; + /// + /// Loads the Soundbank. + /// + /// The result of the operation. public AKRESULT Load() { // Pins BankData array in memory diff --git a/src/SpaceWarp.Sound/API/Sound/SoundbankManager.cs b/src/SpaceWarp.Sound/API/Sound/SoundbankManager.cs index 0f3ea60..7f1f92e 100644 --- a/src/SpaceWarp.Sound/API/Sound/SoundbankManager.cs +++ b/src/SpaceWarp.Sound/API/Sound/SoundbankManager.cs @@ -2,9 +2,19 @@ namespace SpaceWarp.API.Sound; +/// +/// Manages Soundbanks. +/// [PublicAPI] public static class SoundbankManager { + /// + /// Loads a Soundbank from bytes. + /// + /// The internal path of the Soundbank. + /// The bytes of the Soundbank. + /// The loaded Soundbank. + /// Whether the Soundbank was loaded successfully. public static bool LoadSoundbank(string internalPath, byte[] bankData, out Soundbank soundbank) { var bank = new Soundbank(bankData); @@ -23,11 +33,22 @@ public static bool LoadSoundbank(string internalPath, byte[] bankData, out Sound return true; } + /// + /// Gets a Soundbank by its internal path. + /// + /// The internal path of the Soundbank. + /// The Soundbank. public static Soundbank GetSoundbank(string internalPath) { return LoadedSoundbanks[internalPath]; } + /// + /// Tries to get a Soundbank by its internal path. + /// + /// The internal path of the Soundbank. + /// The Soundbank. + /// Whether the Soundbank was found. public static bool TryGetSoundbank(string internalPath, out Soundbank soundbank) { return LoadedSoundbanks.TryGetValue(internalPath, out soundbank); diff --git a/src/SpaceWarp.Sound/Modules/Sound.cs b/src/SpaceWarp.Sound/Modules/Sound.cs index 6d4b3b6..32f4562 100644 --- a/src/SpaceWarp.Sound/Modules/Sound.cs +++ b/src/SpaceWarp.Sound/Modules/Sound.cs @@ -5,32 +5,26 @@ namespace SpaceWarp.Modules; +/// +/// Module that handles sound. +/// [UsedImplicitly] public class Sound : SpaceWarpModule { + /// public override string Name => "SpaceWarp.Sound"; + internal static Sound Instance; private const string SoundbanksFolder = "soundbanks"; + /// public override void LoadModule() { Instance = this; Loading.AddAssetLoadingAction(SoundbanksFolder, "loading soundbanks", AssetSoundbankLoadingAction, "bnk"); } - public override void PreInitializeModule() - { - } - - public override void InitializeModule() - { - } - - public override void PostInitializeModule() - { - } - private static List<(string name, UnityObject asset)> AssetSoundbankLoadingAction( string internalPath, string filename From 9ddc8237b1f4c3453e0b320a73819a75e28088a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 23:08:03 +0100 Subject: [PATCH 40/82] Fixed SpaceWarp.VersionChecking warnings --- .../Modules/VersionChecking.cs | 47 +++++++++++++++---- 1 file changed, 39 insertions(+), 8 deletions(-) diff --git a/src/SpaceWarp.VersionChecking/Modules/VersionChecking.cs b/src/SpaceWarp.VersionChecking/Modules/VersionChecking.cs index 59f2b8b..2fa9e86 100644 --- a/src/SpaceWarp.VersionChecking/Modules/VersionChecking.cs +++ b/src/SpaceWarp.VersionChecking/Modules/VersionChecking.cs @@ -11,15 +11,33 @@ namespace SpaceWarp.Modules; +/// +/// Module that handles version checking. +/// [PublicAPI] public class VersionChecking : SpaceWarpModule { + /// public override string Name => "SpaceWarp.VersionChecking"; + + /// + /// The config value for whether this is the first launch. + /// public ConfigValue ConfigFirstLaunch; + + /// + /// The config value for whether to check versions. + /// public ConfigValue ConfigCheckVersions; + + /// + /// The instance of the version checking module. + /// public static VersionChecking Instance; + private string _kspVersion; + /// public override void LoadModule() { Instance = this; @@ -29,12 +47,15 @@ public override void LoadModule() "Set this to true to automatically check versions over the internet")); } + /// public override void PreInitializeModule() { - _kspVersion = typeof(VersionID).GetField("VERSION_TEXT", BindingFlags.Static | BindingFlags.Public) + _kspVersion = typeof(VersionID) + .GetField("VERSION_TEXT", BindingFlags.Static | BindingFlags.Public) ?.GetValue(null) as string; } + /// public override void InitializeModule() { if (ConfigCheckVersions.Value) @@ -45,11 +66,15 @@ public override void InitializeModule() CheckKspVersions(); } + /// public override void PostInitializeModule() { ConfigFirstLaunch.Value = false; } + /// + /// Clears the outdated flag on all plugins. + /// public void ClearVersions() { foreach (var plugin in PluginList.AllPlugins) @@ -58,6 +83,9 @@ public void ClearVersions() } } + /// + /// Checks the versions of all plugins. + /// public void CheckVersions() { var uiModule = (SpaceWarpModule)AppDomain.CurrentDomain.GetAssemblies() @@ -104,8 +132,6 @@ public void CheckVersions() SpaceWarpPlugin.Instance.StartCoroutine(CheckVersion(info.Guid, info, versionCheckCallback)); } } - - return; } private IEnumerator CheckVersion(string guid, SpaceWarpPluginDescriptor info, Func callback) @@ -121,26 +147,31 @@ private IEnumerator CheckVersion(string guid, SpaceWarpPluginDescriptor info, Fu { var isOutdated = false; var unsupported = false; - SupportedVersionsInfo newKSP2Versions = null; + SupportedVersionsInfo newKsp2Versions = null; var results = www.downloadHandler.text; try { if (info.SWInfo.Spec >= SpecVersion.V2_0) { isOutdated = CheckSemanticVersion(guid, info.SWInfo.Version, results, out unsupported, - out newKSP2Versions); + out newKsp2Versions); } + // TODO: Remove this in 2.0 +#pragma warning disable CS0618 // Type or member is obsolete else { + + isOutdated = info.SWInfo.VersionCheckType switch { VersionCheckType.SwInfo => CheckJsonVersion(guid, info.SWInfo.Version, results, out unsupported, - out newKSP2Versions), + out newKsp2Versions), VersionCheckType.Csproj => CheckCsprojVersion(guid, info.SWInfo.Version, results, - out unsupported, out newKSP2Versions), + out unsupported, out newKsp2Versions), _ => throw new ArgumentOutOfRangeException(nameof(info), "Invalid version_check_type") }; } +#pragma warning restore CS0618 // Type or member is obsolete } catch (Exception e) { @@ -157,7 +188,7 @@ private IEnumerator CheckVersion(string guid, SpaceWarpPluginDescriptor info, Fu if (unsupported) { ModuleLogger.LogWarning($"{guid} is unsupported"); - info.SWInfo.SupportedKsp2Versions = newKSP2Versions; + info.SWInfo.SupportedKsp2Versions = newKsp2Versions; } while (!callback(guid, isOutdated)) From 2ef92ac3adca0caf7adc1dc054ce6c6b63f78dd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 23:09:22 +0100 Subject: [PATCH 41/82] Fixed SpaceWarp assembly warnings --- src/SpaceWarp/TypeForwarders.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/SpaceWarp/TypeForwarders.cs b/src/SpaceWarp/TypeForwarders.cs index 312febd..9a598b9 100644 --- a/src/SpaceWarp/TypeForwarders.cs +++ b/src/SpaceWarp/TypeForwarders.cs @@ -18,6 +18,7 @@ using SpaceWarp.API.Versions; using SpaceWarp.Modules; using SpaceWarp.Patching.LoadingActions; +#pragma warning disable CS0618 // Type or member is obsolete [assembly: TypeForwardedTo(typeof(AssetManager))] [assembly: TypeForwardedTo(typeof(BepInExConfigEntry))] From 24428d1d8f91e09c3f69536f97bc29a5550e0033 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 23:12:26 +0100 Subject: [PATCH 42/82] Fixed SpaceWarpPatcher warnings --- src/SpaceWarpPatcher/AssemblyCSharpPatcher.cs | 28 +++++++++++------ src/SpaceWarpPatcher/Patcher.cs | 31 ++++++++++++++----- src/SpaceWarpPatcher/PathsGenerator.cs | 14 ++++----- 3 files changed, 47 insertions(+), 26 deletions(-) diff --git a/src/SpaceWarpPatcher/AssemblyCSharpPatcher.cs b/src/SpaceWarpPatcher/AssemblyCSharpPatcher.cs index 40a9b14..b02d209 100644 --- a/src/SpaceWarpPatcher/AssemblyCSharpPatcher.cs +++ b/src/SpaceWarpPatcher/AssemblyCSharpPatcher.cs @@ -7,14 +7,22 @@ namespace SpaceWarpPatcher; - +/// +/// Patcher for the game's main DLL +/// [UsedImplicitly] public class AssemblyCSharpPatcher { + /// + /// The target DLLs to patch + /// [UsedImplicitly] public static IEnumerable TargetDLLs => new[] { "Assembly-CSharp.dll"}; - + /// + /// Patches the target DLL + /// + /// The assembly definition to patch [UsedImplicitly] public static void Patch(ref AssemblyDefinition assemblyDefinition) { @@ -36,7 +44,7 @@ public static void Patch(ref AssemblyDefinition assemblyDefinition) firstTargetType.Fields.Add(new FieldDefinition("HasRegisteredPartComponentsForFixedUpdate",FieldAttributes.Public,boolType)); var field = firstTargetType.Fields.First(x => x.Name == "HasRegisteredPartComponentsForFixedUpdate"); // Now later we harmony patch the initializer for partownercomponent - + var targetMethod = firstTargetType.Methods.First(method => method.Name == "OnFixedUpdate"); var methodCallA = assemblyDefinition.MainModule.Types.First(t => t.Name == "ResourceFlowRequestManager").Methods .First(m => m.Name == "UpdateFlowRequests"); @@ -59,7 +67,7 @@ public static void Patch(ref AssemblyDefinition assemblyDefinition) { done = currentInstruction; nextIsTarget = false; - } + } newInstructions.Add(currentInstruction); if (!currentInstruction.MatchCallOrCallvirt(methodCallA)) continue; nextIsTarget = true; @@ -67,9 +75,9 @@ public static void Patch(ref AssemblyDefinition assemblyDefinition) newInstructions.Add(Instruction.Create(OpCodes.Ldarg_0)); @else = newInstructions.Last(); newInstructions.Add(Instruction.Create(OpCodes.Ldfld,field)); - newInstructions.Add(Instruction.Create(OpCodes.Ldarg_3)); + newInstructions.Add(Instruction.Create(OpCodes.Ldarg_3)); newInstructions.Add(Instruction.Create(OpCodes.Ldarg_0)); - newInstructions.Add(Instruction.Create(OpCodes.Call, methodCallB)); + newInstructions.Add(Instruction.Create(OpCodes.Call, methodCallB)); newInstructions.Add(Instruction.Create(OpCodes.Ldarg_1)); newInstructions.Add(Instruction.Create(OpCodes.Ldarg_2)); newInstructions.Add(Instruction.Create(OpCodes.Callvirt, methodCallA)); @@ -95,19 +103,19 @@ public static void Patch(ref AssemblyDefinition assemblyDefinition) { newInstructions[i] = Instruction.Create(OpCodes.Bne_Un_S, @else); } - + if (currentInstruction.OpCode == OpCodes.Nop) { newInstructions[i] = Instruction.Create(OpCodes.Br_S, done); } - + if (currentInstruction.OpCode == OpCodes.Ldarg_3) { newInstructions[i] = Instruction.Create(OpCodes.Brfalse_S, done); } } - - + + insts.Clear(); insts.AddRange(newInstructions); } diff --git a/src/SpaceWarpPatcher/Patcher.cs b/src/SpaceWarpPatcher/Patcher.cs index 7685ae5..e138cba 100644 --- a/src/SpaceWarpPatcher/Patcher.cs +++ b/src/SpaceWarpPatcher/Patcher.cs @@ -16,12 +16,22 @@ namespace SpaceWarpPatcher; +/// +/// Patcher for the UnityEngine.CoreModule assembly. +/// [UsedImplicitly] public static class Patcher { + /// + /// The target DLLs to patch. + /// [UsedImplicitly] public static IEnumerable TargetDLLs => new[] { "UnityEngine.CoreModule.dll"}; + /// + /// Patch the target assembly. + /// + /// The target assembly. [UsedImplicitly] public static void Patch(ref AssemblyDefinition asm) { @@ -100,19 +110,26 @@ public static void PatchChainloaderStart() } } +/// +/// Patches the Chainloader.Start method to disable plugins. +/// [HarmonyPatch] public static class ChainloaderPatch { - internal static string[] DisabledPluginGuids; + /// + /// The filepath to the disabled plugins file. + /// public static string DisabledPluginsFilepath; + + internal static string[] DisabledPluginGuids; internal static ManualLogSource LogSource; internal static List DisabledPlugins; internal static bool ModListChangedSinceLastRun; - private static string[] AllSourceFiles(DirectoryInfo directoryInfo) => - directoryInfo.EnumerateFiles("*.cs", SearchOption.AllDirectories) - .Select(fileInfo => fileInfo.FullName) - .ToArray(); + private static string[] AllSourceFiles(DirectoryInfo directoryInfo) => directoryInfo + .EnumerateFiles("*.cs", SearchOption.AllDirectories) + .Select(fileInfo => fileInfo.FullName) + .ToArray(); [HarmonyPrefix] [HarmonyPatch(typeof(Chainloader), nameof(Chainloader.Start))] @@ -131,8 +148,6 @@ private static void PreStartActions() } } - - private static bool CompileRoslynMods(ManualLogSource trueLogger) { try @@ -148,7 +163,7 @@ private static bool CompileRoslynMods(ManualLogSource trueLogger) "System.Runtime.CompilerServices.Unsafe", "System.Numerics.Vectors" }; - var loc = new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent.FullName; + var loc = new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent!.FullName; foreach (var file in toLoad) { trueLogger.LogInfo($"Loading: {file}"); diff --git a/src/SpaceWarpPatcher/PathsGenerator.cs b/src/SpaceWarpPatcher/PathsGenerator.cs index b248c27..0c16caa 100644 --- a/src/SpaceWarpPatcher/PathsGenerator.cs +++ b/src/SpaceWarpPatcher/PathsGenerator.cs @@ -10,15 +10,13 @@ namespace SpaceWarpPatcher; internal static class PathsGenerator { - - - private static Regex InvalidCharacterRegex = new(@"[^a-zA-Z0-9_]"); - private static Regex InvalidStartRegex = new(@"^[0-9].*$"); + private static readonly Regex InvalidCharacterRegex = new(@"[^a-zA-Z0-9_]"); + private static readonly Regex InvalidStartRegex = new(@"^[0-9].*$"); private static (string name, string path) GetNameAndPath(FileInfo jsonFile) { - var path = '"' + jsonFile.Directory.FullName.Replace("\"","\\\"").Replace("\\","\\\\") + '"'; + var path = '"' + jsonFile.Directory!.FullName.Replace("\"","\\\"").Replace("\\","\\\\") + '"'; var obj = JObject.Parse(File.ReadAllText(jsonFile.FullName)); - var id = obj["mod_id"].Value(); + var id = obj["mod_id"]!.Value(); // var replaced = id.Replace(".", "_").Replace(" ", "_").Replace("-","_"); var replaced = InvalidCharacterRegex.Replace(id, "_"); if (InvalidStartRegex.IsMatch(replaced)) @@ -31,8 +29,8 @@ private static bool IsDisabled(FileInfo jsonFile, string[] allDisabled) { var obj = JObject.Parse(File.ReadAllText(jsonFile.FullName)); if (!obj.ContainsKey("spec")) return false; - if (obj["spec"].Value() is "1.2" or "1.0") return false; - return !allDisabled.Contains(obj["mod_id"].Value()); + if (obj["spec"]!.Value() is "1.2" or "1.0") return false; + return !allDisabled.Contains(obj["mod_id"]!.Value()); } internal static void GenerateSpaceWarpPathsDLL(bool changed, ManualLogSource trueLogger) { From 9510df8d963715bfb970c8ad68474fe4f389b792 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Mon, 1 Jan 2024 23:12:58 +0100 Subject: [PATCH 43/82] Fixed SpaceWarpTest warnings --- src/SpaceWarpTest/API/Versions/SemanticVersionTests.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/SpaceWarpTest/API/Versions/SemanticVersionTests.cs b/src/SpaceWarpTest/API/Versions/SemanticVersionTests.cs index 554e612..baf13c2 100644 --- a/src/SpaceWarpTest/API/Versions/SemanticVersionTests.cs +++ b/src/SpaceWarpTest/API/Versions/SemanticVersionTests.cs @@ -39,6 +39,7 @@ public bool SemanticVersion_ConstructWithVersionString_ConstructsObject(string v { try { + // ReSharper disable once UnusedVariable var semanticVersion = new SemanticVersion(version); return true; } From 9a4d94b4d0597dcd1acc3dc7c28c6154de832fb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bure=C5=A1?= Date: Tue, 2 Jan 2024 01:11:23 +0100 Subject: [PATCH 44/82] Fixed SpaceWarp.UI warnings --- src/SpaceWarp.UI/API/Lua/AppBarInterop.cs | 84 ++++++++++++++++--- src/SpaceWarp.UI/API/UI/Appbar/Appbar.cs | 33 +++++--- src/SpaceWarp.UI/API/UI/Appbar/AppbarMenu.cs | 44 +++++++++- src/SpaceWarp.UI/API/UI/MainMenu.cs | 3 + src/SpaceWarp.UI/API/UI/ModList.cs | 3 + .../API/UI/Settings/ModsPropertyDrawers.cs | 43 ++++++++-- .../API/UI/Settings/SettingsMenu.cs | 3 + src/SpaceWarp.UI/API/UI/Skins.cs | 6 ++ .../Backend/UI/Appbar/AppbarBackend.cs | 17 ++++ ...tomSettingsElementDescriptionController.cs | 32 ++++++- src/SpaceWarp.UI/Modules/UI.cs | 45 ++++++---- .../Patching/LoadingScreen/CurtainPatch.cs | 1 + .../LoadingScreen/LoadingFlowPatch.cs | 1 + .../Patching/Settings/MainMenuPatcher.cs | 4 + .../UI/AvcDialog/AvcDialogController.cs | 2 +- src/SpaceWarp.UI/UI/Console/LogEntry.cs | 10 +-- .../UI/Console/SpaceWarpConsole.cs | 79 +++++++++-------- .../UI/ModList/ModListController.cs | 14 ++-- src/SpaceWarp.UI/UI/Settings/ModsSubMenu.cs | 10 ++- .../UI/Settings/SettingsMenuController.cs | 2 +- 20 files changed, 330 insertions(+), 106 deletions(-) diff --git a/src/SpaceWarp.UI/API/Lua/AppBarInterop.cs b/src/SpaceWarp.UI/API/Lua/AppBarInterop.cs index b830a3b..fd9821e 100644 --- a/src/SpaceWarp.UI/API/Lua/AppBarInterop.cs +++ b/src/SpaceWarp.UI/API/Lua/AppBarInterop.cs @@ -7,15 +7,32 @@ namespace SpaceWarp.API.Lua; +/// +/// Lua API for the AppBar. +/// [SpaceWarpLuaAPI("AppBar")] [PublicAPI] public static class AppBarInterop { + /// + /// Gets a sprite from a texture path. + /// + /// Path to the texture. + /// Width of the sprite. + /// Height of the sprite. + /// The sprite. public static Sprite GetSprite(string texturePath, int width = 0, int height = 0) { return GetSprite(AssetManager.GetAsset(texturePath)); } + /// + /// Gets a sprite from a texture. + /// + /// The texture. + /// Width of the sprite. + /// Height of the sprite. + /// public static Sprite GetSprite(Texture2D texture, int width = 0, int height = 0) { if (width == 0) @@ -31,11 +48,21 @@ public static Sprite GetSprite(Texture2D texture, int width = 0, int height = 0) return Sprite.Create(texture, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f)); } + /// + /// Registers an app button. + /// + /// Whether the button should be registered in the OAB. + /// Whether the button should be registered in flight. + /// The text of the button. + /// The ID of the button. + /// The icon of the button. + /// The callback to be called when the button is toggled. + /// The self parameter for the callback. public static void RegisterAppButton( bool oab, bool inFlight, string name, - string ID, + string id, Sprite icon, Closure toggleCallback, [CanBeNull] DynValue self = null @@ -53,30 +80,51 @@ public static void RegisterAppButton( if (oab) { - Appbar.RegisterAppButton(name, ID, icon, callback); + Appbar.RegisterAppButton(name, id, icon, callback); } if (inFlight) { - Appbar.RegisterOABAppButton(name, ID, icon, callback); + Appbar.RegisterOABAppButton(name, id, icon, callback); } } + /// + /// Registers an app button. + /// + /// Whether the button should be registered in the OAB. + /// Whether the button should be registered in flight. + /// The text of the button. + /// The ID of the button. + /// The path to the texture of the button. + /// The callback to be called when the button is toggled. + /// The self parameter for the callback. public static void RegisterAppButton( bool oab, bool inFlight, string name, - string ID, + string id, string texturePath, Closure toggleCallback, [CanBeNull] DynValue self = null - ) => RegisterAppButton(oab, inFlight, name, ID, GetSprite(texturePath), toggleCallback, self); + ) => RegisterAppButton(oab, inFlight, name, id, GetSprite(texturePath), toggleCallback, self); + /// + /// Registers an app window. + /// + /// Whether the window should be registered in the OAB. + /// Whether the window should be registered in flight. + /// The text of the button that opens the window. + /// The ID of the button that opens the window. + /// The icon of the button that opens the window. + /// The window. + /// The callback to be called when the button is toggled. + /// The self parameter for the callback. public static void RegisterAppWindow( bool oab, bool inFlight, string name, - string ID, + string id, Sprite icon, VisualElement window, Closure toggleCallback, @@ -103,26 +151,42 @@ public static void RegisterAppWindow( if (oab) { - Appbar.RegisterAppButton(name, ID, icon, callback); + Appbar.RegisterAppButton(name, id, icon, callback); } if (inFlight) { - Appbar.RegisterOABAppButton(name, ID, icon, callback); + Appbar.RegisterOABAppButton(name, id, icon, callback); } } + /// + /// Registers an app window. + /// + /// Whether the window should be registered in the OAB. + /// Whether the window should be registered in flight. + /// The text of the button that opens the window. + /// The ID of the button that opens the window. + /// The path to the texture of the button that opens the window. + /// The window. + /// The callback to be called when the button is toggled. + /// The self parameter for the callback. public static void RegisterAppWindow( bool oab, bool inFlight, string name, - string ID, + string id, string texturePath, VisualElement window, Closure toggleCallback, [CanBeNull] DynValue self = null - ) => RegisterAppWindow(oab, inFlight, name, ID, GetSprite(texturePath), window, toggleCallback, self); + ) => RegisterAppWindow(oab, inFlight, name, id, GetSprite(texturePath), window, toggleCallback, self); + /// + /// Sets the indicator of an app button. + /// + /// The ID of the button. + /// Whether the indicator should be set. public static void SetAppButtonIndicator(string id, bool b) { Appbar.SetAppBarButtonIndicator(id, b); diff --git a/src/SpaceWarp.UI/API/UI/Appbar/Appbar.cs b/src/SpaceWarp.UI/API/UI/Appbar/Appbar.cs index cc441bf..2bab0e5 100644 --- a/src/SpaceWarp.UI/API/UI/Appbar/Appbar.cs +++ b/src/SpaceWarp.UI/API/UI/Appbar/Appbar.cs @@ -7,17 +7,20 @@ namespace SpaceWarp.API.UI.Appbar; +/// +/// Used to register buttons on the game's AppBar. +/// [PublicAPI] public static class Appbar { private static readonly List<(string text, Sprite icon, string ID, Action action)> ButtonsToBeLoaded = new(); - private static readonly List<(string text, Sprite icon, string ID, Action action)> OABButtonsToBeLoaded = new(); + private static readonly List<(string text, Sprite icon, string ID, Action action)> OabButtonsToBeLoaded = new(); - private static readonly List<(string text, Sprite icon, string ID, Action action)> KSCButtonsToBeLoaded = new(); + private static readonly List<(string text, Sprite icon, string ID, Action action)> KscButtonsToBeLoaded = new(); /// - /// Register an appbar menu for the game + /// Register an AppBar menu for the game. /// /// The text in the appbar menu /// The title of the menu @@ -25,6 +28,7 @@ public static class Appbar /// A Sprite for the icon in the appbar /// The type of the appbar menu, must extend AppbarMenu /// An instance of T which has been added to a GameObject +#pragma warning disable CS0618 // Type or member is obsolete public static T RegisterGameAppbarMenu(string text, string title, string id, Sprite icon) where T : AppbarMenu { var toolBarUIObject = new GameObject($"Toolbar: {id}"); @@ -35,11 +39,11 @@ public static T RegisterGameAppbarMenu(string text, string title, string id, toolBarUIObject.transform.SetParent(Chainloader.ManagerObject.transform); toolBarUIObject.SetActive(true); ButtonsToBeLoaded.Add((text, icon, id, menu.ToggleGUI)); - return menu as T; + return (T)menu; } /// - /// Register a appbar menu for the game + /// Register an AppBar menu for the game. /// /// The text in the appbar menu /// The title of the menu @@ -51,9 +55,10 @@ public static T RegisterGameAppbarMenu(string text, string title, string id, { return RegisterGameAppbarMenu(text, title, id, GetAppBarIconFromTexture(icon)); } +#pragma warning restore CS0618 // Type or member is obsolete /// - /// Register a button on the games AppBar + /// Register a button on the game's AppBar /// /// The text in the appbar menu /// A unique id for the appbar menu eg: "BTN-Example" @@ -65,7 +70,7 @@ public static void RegisterAppButton(string text, string id, Sprite icon, Action } /// - /// Register a button on the games AppBar + /// Register a button on the game's AppBar /// /// The text in the appbar menu /// A unique id for the appbar menu eg: "BTN-Example" @@ -83,9 +88,10 @@ public static void RegisterAppButton(string text, string id, Texture2D icon, Act /// A unique id for the appbar menu eg: "BTN-ExampleOAB" /// A Sprite for the icon in the appbar /// The function to be called when this button is clicked + // ReSharper disable once InconsistentNaming public static void RegisterOABAppButton(string text, string id, Sprite icon, Action func) { - OABButtonsToBeLoaded.Add((text, icon, id, func)); + OabButtonsToBeLoaded.Add((text, icon, id, func)); } /// @@ -95,6 +101,7 @@ public static void RegisterOABAppButton(string text, string id, Sprite icon, Act /// A unique id for the appbar menu eg: "BTN-ExampleOAB" /// A Texture2D for the icon in the appbar /// The function to be called when this button is clicked + // ReSharper disable once InconsistentNaming public static void RegisterOABAppButton(string text, string id, Texture2D icon, Action func) { RegisterOABAppButton(text, id, GetAppBarIconFromTexture(icon), func); @@ -107,9 +114,10 @@ public static void RegisterOABAppButton(string text, string id, Texture2D icon, /// A unique id for the appbar menu eg: "BTN-ExampleKSC" /// A Sprite for the icon in the appbar /// The function to be called when this button is clicked + // ReSharper disable once InconsistentNaming public static void RegisterKSCAppButton(string text, string id, Sprite icon, Action func) { - KSCButtonsToBeLoaded.Add((text, icon, id, func)); + KscButtonsToBeLoaded.Add((text, icon, id, func)); } /// @@ -119,6 +127,7 @@ public static void RegisterKSCAppButton(string text, string id, Sprite icon, Act /// A unique id for the appbar menu eg: "BTN-ExampleKSC" /// A Texture2D for the icon in the appbar /// The function to be called when this button is clicked + // ReSharper disable once InconsistentNaming public static void RegisterKSCAppButton(string text, string id, Texture2D icon, Action func) { RegisterKSCAppButton(text, id, GetAppBarIconFromTexture(icon), func); @@ -165,17 +174,19 @@ internal static void LoadAllButtons() } } + // ReSharper disable once InconsistentNaming internal static void LoadOABButtons() { - foreach (var button in OABButtonsToBeLoaded) + foreach (var button in OabButtonsToBeLoaded) { AppbarBackend.AddOABButton(button.text, button.icon, button.ID, button.action); } } + // ReSharper disable once InconsistentNaming internal static void LoadKSCButtons() { - foreach (var button in KSCButtonsToBeLoaded) + foreach (var button in KscButtonsToBeLoaded) { AppbarBackend.AddKSCButton(button.text, button.icon, button.ID, button.action); } diff --git a/src/SpaceWarp.UI/API/UI/Appbar/AppbarMenu.cs b/src/SpaceWarp.UI/API/UI/Appbar/AppbarMenu.cs index 081b76b..4efe2d7 100644 --- a/src/SpaceWarp.UI/API/UI/Appbar/AppbarMenu.cs +++ b/src/SpaceWarp.UI/API/UI/Appbar/AppbarMenu.cs @@ -6,25 +6,48 @@ namespace SpaceWarp.API.UI.Appbar; +/// +/// Used to create a menu on the game's AppBar. +/// [Obsolete("Spacewarps support for IMGUI will not be getting updates, please use UITK instead")] [PublicAPI] public abstract class AppbarMenu : KerbalBehavior { + /// + /// The title of the menu + /// + // ReSharper disable once InconsistentNaming [FormerlySerializedAs("Title")] public string title; + private GUIStyle _closeButtonStyle; private bool _drawing; private GUISkin _spaceWarpConsoleSkin; private Rect _windowRect; internal string ID; + /// + /// The width of the menu + /// protected abstract float Width { get; } + /// + /// The height of the menu + /// protected abstract float Height { get; } + /// + /// The X position of the menu + /// protected abstract float X { get; } + /// + /// The Y position of the menu + /// protected abstract float Y { get; } + /// + /// The skin to use for the menu + /// protected virtual GUISkin Skin { get @@ -38,12 +61,18 @@ protected virtual GUISkin Skin } } - public new void Awake() + /// + /// Called when the menu is created + /// + protected new void Awake() { _windowRect = new Rect(X, Y, 0, 0); } - public void OnGUI() + /// + /// Draws the GUI + /// + protected void OnGUI() { if (!_drawing || GameManager.Instance.Game.GlobalGameState.GetState() != GameState.FlightView) @@ -70,6 +99,9 @@ internal void ToggleGUI(bool drawing) Appbar.SetAppBarButtonIndicator(ID, drawing); } + /// + /// Toggles the menu + /// public void ToggleGUI() { _drawing = !_drawing; @@ -77,7 +109,6 @@ public void ToggleGUI() private void DoDrawing(int windowID) { - var closeButtonRect = new Rect(Width - 23, 6, 16, 16); if (GUI.Button(new Rect(_windowRect.width - 18, 2, 16, 16), "x", _closeButtonStyle)) { CloseWindow(); @@ -88,8 +119,15 @@ private void DoDrawing(int windowID) GUI.DragWindow(new Rect(0, 0, 10000, 10000)); } + /// + /// Contains the code to draw the menu + /// + /// The ID of the window public abstract void DrawWindow(int windowID); + /// + /// Closes the menu + /// public void CloseWindow() { ToggleGUI(false); diff --git a/src/SpaceWarp.UI/API/UI/MainMenu.cs b/src/SpaceWarp.UI/API/UI/MainMenu.cs index 9e72d6f..2e1e945 100644 --- a/src/SpaceWarp.UI/API/UI/MainMenu.cs +++ b/src/SpaceWarp.UI/API/UI/MainMenu.cs @@ -2,6 +2,9 @@ namespace SpaceWarp.API.UI; +/// +/// Used to register buttons in the game's main menu. +/// [PublicAPI] public static class MainMenu { diff --git a/src/SpaceWarp.UI/API/UI/ModList.cs b/src/SpaceWarp.UI/API/UI/ModList.cs index 46c5d49..c8e57d0 100644 --- a/src/SpaceWarp.UI/API/UI/ModList.cs +++ b/src/SpaceWarp.UI/API/UI/ModList.cs @@ -3,6 +3,9 @@ namespace SpaceWarp.API.UI; +/// +/// API for the mod list UI +/// [PublicAPI] public static class ModList { diff --git a/src/SpaceWarp.UI/API/UI/Settings/ModsPropertyDrawers.cs b/src/SpaceWarp.UI/API/UI/Settings/ModsPropertyDrawers.cs index b1058ff..2132023 100644 --- a/src/SpaceWarp.UI/API/UI/Settings/ModsPropertyDrawers.cs +++ b/src/SpaceWarp.UI/API/UI/Settings/ModsPropertyDrawers.cs @@ -13,17 +13,39 @@ namespace SpaceWarp.API.UI.Settings; +/// +/// This class is used to register custom property drawers for the settings UI. +/// [PublicAPI] public static class ModsPropertyDrawers { private static readonly Dictionary> AllPropertyDrawers = new(); private static readonly Dictionary> AllAbstractedPropertyDrawers = new(); + /// + /// Registers a custom property drawer for a specific type. + /// + /// + /// A function that takes a and returns a that will be used + /// as the property drawer. + /// + /// The type to register the drawer for. public static void AddDrawer(Func drawerGenerator) => AllPropertyDrawers.Add(typeof(T), drawerGenerator); + /// + /// Registers a custom abstract property drawer for a specific type. + /// + /// + /// public static void AddAbstractedDrawer(Func drawerGenerator) => AllAbstractedPropertyDrawers.Add(typeof(T), drawerGenerator); + + /// + /// Gets a property drawer for a config entry. + /// + /// The config entry to get a drawer for. + /// A that will be used as the property drawer. public static GameObject Drawer(ConfigEntryBase entry) { if (entry.SettingType.IsEnum && !AllPropertyDrawers.ContainsKey(entry.SettingType)) @@ -42,6 +64,12 @@ public static GameObject Drawer(ConfigEntryBase entry) return AllPropertyDrawers.TryGetValue(entry.SettingType, out var func) ? func(entry) : null; } + /// + /// Gets a property drawer for a config entry with a name. + /// + /// The name of the config entry. + /// The config entry to get a drawer for. + /// public static GameObject Drawer(string name, IConfigEntry entry) { if (entry.ValueType.IsEnum && !AllAbstractedPropertyDrawers.ContainsKey(entry.ValueType)) @@ -75,7 +103,7 @@ private static Func GenerateEnumDrawerFor(Type t) { var memberInfos = t.GetMember(optionNames[i]); var enumValueInfo = memberInfos.FirstOrDefault(m => m.DeclaringType == t); - var valueAttributes = enumValueInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); + var valueAttributes = enumValueInfo!.GetCustomAttributes(typeof(DescriptionAttribute), false); optionNames[i] = ((DescriptionAttribute)valueAttributes[0]).Description; } catch @@ -187,7 +215,7 @@ private static Func GenerateAbstractEnumDrawer { var memberInfos = t.GetMember(optionNames[i]); var enumValueInfo = memberInfos.FirstOrDefault(m => m.DeclaringType == t); - var valueAttributes = enumValueInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); + var valueAttributes = enumValueInfo!.GetCustomAttributes(typeof(DescriptionAttribute), false); optionNames[i] = ((DescriptionAttribute)valueAttributes[0]).Description; } catch @@ -581,7 +609,7 @@ private static GameObject CreateFromAcceptableValueRange(ConfigEntry entry TypeCode.Decimal => x => (T)(object)Convert.ToDecimal(x), TypeCode.Double => x => (T)(object)Convert.ToDouble(x), TypeCode.Single => x => (T)(object)x, - _ => x => throw new NotImplementedException(typeof(T).ToString()) + _ => _ => throw new NotImplementedException(typeof(T).ToString()) }; slider.minValue = toFloat(acceptableValues.MinValue); slider.maxValue = toFloat(acceptableValues.MaxValue); @@ -623,7 +651,7 @@ private static GameObject CreateFromListConstraint(string key, IConfigEntry e ? (color.a < 1 ? ColorUtility.ToHtmlStringRGBA(color) : ColorUtility.ToHtmlStringRGB(color)) : option.ToString()))); } - + extended.value = constraint.AcceptableValues.IndexOf(value.Value); extended.onValueChanged.AddListener(idx => { value.Value = constraint.AcceptableValues[idx]; }); var sec = ddCopy.AddComponent(); @@ -668,7 +696,7 @@ private static GameObject CreateFromRangeConstraint(string key, IConfigEntry TypeCode.Decimal => x => (T)(object)Convert.ToDecimal(x), TypeCode.Double => x => (T)(object)Convert.ToDouble(x), TypeCode.Single => x => (T)(object)x, - _ => x => throw new NotImplementedException(typeof(T).ToString()) + _ => _ => throw new NotImplementedException(typeof(T).ToString()) }; slider.minValue = toFloat(constraint.Minimum); slider.maxValue = toFloat(constraint.Maximum); @@ -678,9 +706,8 @@ private static GameObject CreateFromRangeConstraint(string key, IConfigEntry // var trueValue = (acceptableValues.MaxValue-acceptableValues.MinValue) * (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value) // var trueValue = (toFloat(acceptableValues.MaxValue) - toFloat(acceptableValues.MinValue)) * value + // toFloat(acceptableValues.MinValue); - var trueValue = val; - value.Value = toT(trueValue) ?? value.Value; + value.Value = toT(val) ?? value.Value; if (entry.Value != null) text.text = entry.Value.ToString(); slider.SetWithoutCallback(toFloat(value.Value)); }); @@ -712,7 +739,7 @@ private static GameObject CreateStringConfig(ConfigEntryBase entryBase) textField.readOnly = false; textField.interactable = true; textField.text = entry.Value; - textField.onValueChanged.AddListener(str => { entry.Value = str; }); + textField.onValueChanged.AddListener(text => { entry.Value = text; }); var rectTransform = textFieldObject.transform.parent.gameObject.GetComponent(); rectTransform.anchorMin = new Vector2(0, 2.7f); rectTransform.anchorMax = new Vector2(0.19f, 2.25f); diff --git a/src/SpaceWarp.UI/API/UI/Settings/SettingsMenu.cs b/src/SpaceWarp.UI/API/UI/Settings/SettingsMenu.cs index 49f59a8..936bd71 100644 --- a/src/SpaceWarp.UI/API/UI/Settings/SettingsMenu.cs +++ b/src/SpaceWarp.UI/API/UI/Settings/SettingsMenu.cs @@ -3,6 +3,9 @@ namespace SpaceWarp.UI.API.UI.Settings; +/// +/// API for the mod settings menu +/// [PublicAPI] public static class SettingsMenu { diff --git a/src/SpaceWarp.UI/API/UI/Skins.cs b/src/SpaceWarp.UI/API/UI/Skins.cs index f8b35bb..ff1d663 100644 --- a/src/SpaceWarp.UI/API/UI/Skins.cs +++ b/src/SpaceWarp.UI/API/UI/Skins.cs @@ -4,6 +4,9 @@ namespace SpaceWarp.API.UI; +/// +/// SpaceWarp's internal GUI skins +/// // This exposes the SpaceWarp internal skins [Obsolete("SpaceWarp's support for IMGUI will not be getting updates, please use UITK instead")] [PublicAPI] @@ -11,6 +14,9 @@ public static class Skins { private static GUISkin _skin; + /// + /// The default SpaceWarp skin + /// [Obsolete("SpaceWarp's support for IMGUI will not be getting updates, please use UITK instead")] public static GUISkin ConsoleSkin { diff --git a/src/SpaceWarp.UI/Backend/UI/Appbar/AppbarBackend.cs b/src/SpaceWarp.UI/Backend/UI/Appbar/AppbarBackend.cs index 495f1fd..a9f25ee 100644 --- a/src/SpaceWarp.UI/Backend/UI/Appbar/AppbarBackend.cs +++ b/src/SpaceWarp.UI/Backend/UI/Appbar/AppbarBackend.cs @@ -6,6 +6,7 @@ using BepInEx.Logging; using HarmonyLib; using I2.Loc; +using JetBrains.Annotations; using KSP; using KSP.Api.CoreTypes; using KSP.Game; @@ -28,9 +29,11 @@ internal static class AppbarBackend { private static readonly ManualLogSource Logger = BepInEx.Logging.Logger.CreateLogSource("ToolbarBackend"); + // ReSharper disable InconsistentNaming public static readonly UnityEvent AppBarOABSubscriber = new(); public static readonly UnityEvent AppBarInFlightSubscriber = new(); public static readonly UnityEvent AppBarKSCSubscriber = new(); + // ReSharper restore InconsistentNaming internal static void SubscriberSchedulePing(AppbarEvent type) { @@ -51,12 +54,14 @@ internal static void SubscriberSchedulePing(AppbarEvent type) gameObject.SetActive(true); } + // ReSharper disable InconsistentNaming internal enum AppbarEvent { Flight, OAB, KSC } + // ReSharper restore InconsistentNaming #region Flight App Bar @@ -128,6 +133,7 @@ public static void SetTrayState(bool state) private static GameObject _oabTray; + // ReSharper disable once InconsistentNaming private static GameObject OABTray { get @@ -143,6 +149,7 @@ private static GameObject OABTray private static Property _oabState; + // ReSharper disable once InconsistentNaming private static GameObject CreateOABTray() { Logger.LogInfo("Creating OAB app button tray..."); @@ -226,6 +233,7 @@ private static GameObject CreateOABTray() return oabTray; } + // ReSharper disable once InconsistentNaming public static void AddOABButton(string buttonText, Sprite buttonIcon, string buttonId, Action function) { Logger.LogInfo($"Adding OAB app bar button: {buttonId}."); @@ -279,6 +287,7 @@ public static void AddOABButton(string buttonText, Sprite buttonIcon, string but Logger.LogInfo($"Added OAB appbar button: {buttonId}"); } + // ReSharper disable once InconsistentNaming private static void SetOABTrayState(bool state) { if (_oabTray == null) @@ -295,6 +304,7 @@ private static void SetOABTrayState(bool state) private static GameObject _kscTray; + // ReSharper disable once InconsistentNaming private static GameObject KSCTray { get @@ -308,6 +318,7 @@ private static GameObject KSCTray } } + // ReSharper disable once InconsistentNaming private static GameObject CreateKSCTray() { Logger.LogInfo("Creating KSC app tray..."); @@ -366,6 +377,7 @@ private static GameObject CreateKSCTray() return kscAppTray; } + // ReSharper disable once InconsistentNaming public static void AddKSCButton(string buttonText, Sprite buttonIcon, string buttonId, Action function) { Logger.LogInfo($"Adding KSC appbar button: {buttonId}."); @@ -456,6 +468,7 @@ private IEnumerator Awaiter() [HarmonyPatch("Start")] internal class ToolbarBackendAppBarPatcher { + [UsedImplicitly] public static void Postfix() { SubscriberSchedulePing(AppbarEvent.Flight); @@ -464,8 +477,10 @@ public static void Postfix() [HarmonyPatch(typeof(OABSideBar))] [HarmonyPatch("Start")] +// ReSharper disable once InconsistentNaming internal class ToolbarBackendOABSideBarPatcher { + [UsedImplicitly] public static void Postfix() { SubscriberSchedulePing(AppbarEvent.OAB); @@ -474,8 +489,10 @@ public static void Postfix() [HarmonyPatch(typeof(KSCMenuManager))] [HarmonyPatch("Start")] +// ReSharper disable once InconsistentNaming internal class ToolbarBackendKSCPatcher { + [UsedImplicitly] public static void Postfix() { SubscriberSchedulePing(AppbarEvent.KSC); diff --git a/src/SpaceWarp.UI/Backend/UI/Settings/CustomSettingsElementDescriptionController.cs b/src/SpaceWarp.UI/Backend/UI/Settings/CustomSettingsElementDescriptionController.cs index 709f0bd..25cddc8 100644 --- a/src/SpaceWarp.UI/Backend/UI/Settings/CustomSettingsElementDescriptionController.cs +++ b/src/SpaceWarp.UI/Backend/UI/Settings/CustomSettingsElementDescriptionController.cs @@ -4,23 +4,49 @@ namespace SpaceWarp.Backend.UI.Settings; +/// +/// This class is used to display a description for a custom setting element. +/// public class CustomSettingsElementDescriptionController : KerbalMonoBehaviour, IPointerEnterHandler, IPointerExitHandler { - + /// + /// The description to display when the element is hovered. + /// + // ReSharper disable once InconsistentNaming public string description; + + /// + /// Whether or not this element is an input setting element. + /// + // ReSharper disable once InconsistentNaming public bool isInputSettingElement; + /// + /// The tween animations to play when the element is hovered. + /// + // ReSharper disable once InconsistentNaming public List tweenAnimations = new(); + + /// + /// Called when the object is created. + /// public void Start() => tweenAnimations.AddRange(GetComponents()); + /// + /// Called when the pointer enters the object. + /// + /// public void OnPointerEnter(PointerEventData eventData) => OnHover(true); + /// + /// Called when the pointer exits the object. + /// + /// public void OnPointerExit(PointerEventData eventData) => OnHover(false); - private void OnHover(bool isHovered) { if (isHovered) @@ -39,6 +65,8 @@ private void HandleAnimation(string triggerType) { var all = tweenAnimations.FindAll(da => da.id.Equals(triggerType)); foreach (var animationComponent in all) + { animationComponent.tween.Restart(); + } } } diff --git a/src/SpaceWarp.UI/Modules/UI.cs b/src/SpaceWarp.UI/Modules/UI.cs index b2f2e71..08e6b85 100644 --- a/src/SpaceWarp.UI/Modules/UI.cs +++ b/src/SpaceWarp.UI/Modules/UI.cs @@ -16,13 +16,17 @@ namespace SpaceWarp.Modules; +/// +/// The UI module for Space Warp. +/// [PublicAPI] public class UI : SpaceWarpModule { + /// public override string Name => "SpaceWarp.UI"; internal static UI Instance; - + internal ConfigValue ConfigAllColor; internal ConfigValue ConfigCheckVersions; internal ConfigValue ConfigShowMainMenuWarningForOutdatedMods; @@ -40,7 +44,7 @@ public class UI : SpaceWarpModule internal ModListController ModListController; internal SpaceWarpConsole SpaceWarpConsole; - + /// public override void LoadModule() { AppbarBackend.AppBarInFlightSubscriber.AddListener(Appbar.LoadAllButtons); @@ -76,10 +80,12 @@ public override void LoadModule() BepInEx.Logging.Logger.Listeners.Add(new SpaceWarpConsoleLogListener(this)); } + /// public override void PreInitializeModule() { } + /// public override void InitializeModule() { ModuleLogger.LogInfo("Initializing UI"); @@ -93,7 +99,11 @@ public override void InitializeModule() var avcDialogUxml = AssetManager.GetAsset( $"{SpaceWarpPlugin.ModGuid}/avcdialog/ui/avcdialog/avcdialog.uxml"); - var avcDialog = Window.CreateFromUxml(avcDialogUxml, "Space Warp AVC Dialog", ui.transform, true); + + var windowOptions = WindowOptions.Default; + windowOptions.WindowId = "Space Warp AVC Dialog"; + windowOptions.Parent = ui.transform; + var avcDialog = Window.Create(windowOptions, avcDialogUxml); var avcDialogController = avcDialog.gameObject.AddComponent(); avcDialogController.Module = VersionChecking.Instance; @@ -102,6 +112,7 @@ public override void InitializeModule() InitializeUI(); } + /// public override void PostInitializeModule() { ModuleLogger.LogInfo("Post Initializing UI"); @@ -110,15 +121,14 @@ public override void PostInitializeModule() ModListController.AddMainMenuItem(); } - public override List Prerequisites => new() - { - "SpaceWarp.VersionChecking" - }; - + /// + public override List Prerequisites => ["SpaceWarp.VersionChecking"]; + private void InitializeUI() { - ConfigurationManager = (ConfigurationManager.ConfigurationManager)Chainloader - .PluginInfos[ConfigManager.GUID].Instance; + ConfigurationManager = (ConfigManager)Chainloader + .PluginInfos[ConfigManager.GUID] + .Instance; var ui = new GameObject("Space Warp UI"); ui.Persist(); @@ -127,18 +137,23 @@ private void InitializeUI() var modListUxml = AssetManager.GetAsset( $"{SpaceWarpPlugin.ModGuid}/modlist/ui/modlist/modlist.uxml" ); - var modList = Window.CreateFromUxml(modListUxml, "Space Warp Mod List", ui.transform, true); + var modListOptions = WindowOptions.Default; + modListOptions.WindowId = "Space Warp Mod List"; + modListOptions.Parent = ui.transform; + var modList = Window.Create(modListOptions, modListUxml); ModListController = modList.gameObject.AddComponent(); var swConsoleUxml = AssetManager.GetAsset( $"{SpaceWarpPlugin.ModGuid}/swconsole/ui/console/console.uxml" ); - - var swConsole = Window.CreateFromUxml(swConsoleUxml, "Space Warp Console", ui.transform, true); + var swConsoleOptions = WindowOptions.Default; + swConsoleOptions.WindowId = "Space Warp AVC Dialog"; + swConsoleOptions.Parent = ui.transform; + var swConsole = Window.Create(swConsoleOptions, swConsoleUxml); SpaceWarpConsole = swConsole.gameObject.AddComponent(); } - - + + private static void InitializeSettingsUI() { GameObject settingsController = new("Space Warp Settings Controller"); diff --git a/src/SpaceWarp.UI/Patching/LoadingScreen/CurtainPatch.cs b/src/SpaceWarp.UI/Patching/LoadingScreen/CurtainPatch.cs index db6f6aa..3ae52d6 100644 --- a/src/SpaceWarp.UI/Patching/LoadingScreen/CurtainPatch.cs +++ b/src/SpaceWarp.UI/Patching/LoadingScreen/CurtainPatch.cs @@ -10,6 +10,7 @@ internal static class CurtainPatch [HarmonyPrefix] [HarmonyPatch(nameof(Curtain.Awake))] + // ReSharper disable once InconsistentNaming public static void LoadScreensEarly(Curtain __instance) { LoadingScreenManager = new LoadingScreenManager(); diff --git a/src/SpaceWarp.UI/Patching/LoadingScreen/LoadingFlowPatch.cs b/src/SpaceWarp.UI/Patching/LoadingScreen/LoadingFlowPatch.cs index 2b5ffac..95bd781 100644 --- a/src/SpaceWarp.UI/Patching/LoadingScreen/LoadingFlowPatch.cs +++ b/src/SpaceWarp.UI/Patching/LoadingScreen/LoadingFlowPatch.cs @@ -12,6 +12,7 @@ internal static class LoadingFlowPatch [HarmonyPostfix] [HarmonyPatch(nameof(SequentialFlow.NextFlowAction))] + // ReSharper disable once InconsistentNaming internal static void SelectRandomLoadingScreen(SequentialFlow __instance) { if (__instance.FlowState != FlowState.Finished) diff --git a/src/SpaceWarp.UI/Patching/Settings/MainMenuPatcher.cs b/src/SpaceWarp.UI/Patching/Settings/MainMenuPatcher.cs index 2394672..7ce95fe 100644 --- a/src/SpaceWarp.UI/Patching/Settings/MainMenuPatcher.cs +++ b/src/SpaceWarp.UI/Patching/Settings/MainMenuPatcher.cs @@ -1,5 +1,6 @@ using HarmonyLib; using I2.Loc; +using JetBrains.Annotations; using KSP.Api.CoreTypes; using KSP.Game.StartupFlow; using SpaceWarp.API.UI; @@ -12,6 +13,9 @@ namespace SpaceWarp.Patching.Settings; internal class MainMenuPatcher { internal static event Action MainMenuLoaded; + + [UsedImplicitly] + // ReSharper disable once InconsistentNaming public static void Postfix(LandingHUD __instance) { var menuItemsGroupTransform = __instance.transform.FindChildEx("MenuItemsGroup"); diff --git a/src/SpaceWarp.UI/UI/AvcDialog/AvcDialogController.cs b/src/SpaceWarp.UI/UI/AvcDialog/AvcDialogController.cs index 3966c45..e65754b 100644 --- a/src/SpaceWarp.UI/UI/AvcDialog/AvcDialogController.cs +++ b/src/SpaceWarp.UI/UI/AvcDialog/AvcDialogController.cs @@ -5,7 +5,7 @@ namespace SpaceWarp.UI.AvcDialog; -public class AvcDialogController : MonoBehaviour +internal class AvcDialogController : MonoBehaviour { internal VersionChecking Module; diff --git a/src/SpaceWarp.UI/UI/Console/LogEntry.cs b/src/SpaceWarp.UI/UI/Console/LogEntry.cs index 64a18bd..7bc29b6 100644 --- a/src/SpaceWarp.UI/UI/Console/LogEntry.cs +++ b/src/SpaceWarp.UI/UI/Console/LogEntry.cs @@ -89,14 +89,7 @@ private bool Expanded set { _expanded = value; - if (value) - { - _logMessageLabel.style.display = DisplayStyle.Flex; - } - else - { - _logMessageLabel.style.display = DisplayStyle.None; - } + _logMessageLabel.style.display = value ? DisplayStyle.Flex : DisplayStyle.None; _logMessageHeaderLabel.text = LogMessageHeader; } } @@ -197,6 +190,7 @@ public LogEntry(LogInfo logInfo, bool startCollapsed = true) Expanded = !startCollapsed; } + [Obsolete] public override void HandleEvent(EventBase evt) { if(evt is ClickEvent) diff --git a/src/SpaceWarp.UI/UI/Console/SpaceWarpConsole.cs b/src/SpaceWarp.UI/UI/Console/SpaceWarpConsole.cs index 8e6743c..90b7e8e 100644 --- a/src/SpaceWarp.UI/UI/Console/SpaceWarpConsole.cs +++ b/src/SpaceWarp.UI/UI/Console/SpaceWarpConsole.cs @@ -7,10 +7,10 @@ using UnityEngine.UIElements; using static SpaceWarp.UI.Console.SpaceWarpConsoleLogListener; -namespace SpaceWarp.UI.Console; +namespace SpaceWarp.UI.Console; -internal sealed class SpaceWarpConsole : KerbalMonoBehaviour -{ +internal sealed class SpaceWarpConsole : KerbalMonoBehaviour +{ // State private bool _isLoaded; private bool _isWindowVisible; @@ -29,16 +29,13 @@ internal sealed class SpaceWarpConsole : KerbalMonoBehaviour private Toggle _toggleError; private Toggle _toggleAutoScroll; - - // Debugging - private static ManualLogSource _logger; - private void Start() { foreach (var logMessage in LogMessages) { CreateNewLogEntry(logMessage); } + // Binds the OnNewMessageReceived function to the OnNewMessage event OnNewLog += AddToQueue; } @@ -48,7 +45,6 @@ private void OnDestroy() { // Unbinds the OnNewMessageReceived function to the OnNewMessage event when destroyed OnNewLog -= AddToQueue; - } private void CreateNewLogEntry(LogInfo logInfo) @@ -64,18 +60,23 @@ private void CreateNewLogEntry(LogInfo logInfo) //First in first out if (_consoleContent.contentContainer.childCount > Modules.UI.Instance.ConfigDebugMessageLimit.Value) - _consoleContent.contentContainer.RemoveAt(0); - if(_toggleAutoScroll.value) + { + _consoleContent.contentContainer.RemoveAt(0); + } + + if (_toggleAutoScroll.value) + { AutoScrollToBottom(); + } } private void Awake() { - if (_isLoaded) return; - - // Debugging - _logger = SpaceWarpPlugin.Logger; + if (_isLoaded) + { + return; + } // Run the main UITK setup functions SetupDocument(); @@ -90,7 +91,7 @@ private void Awake() private void Update() { - if (Input.GetKey(KeyCode.LeftAlt) && Input.GetKeyDown(KeyCode.C)) + if (Input.GetKey(KeyCode.LeftAlt) && Input.GetKeyDown(KeyCode.C)) { ToggleWindow(); } @@ -100,9 +101,12 @@ private void Update() HideWindow(); } - if (!_isWindowVisible) return; - - while (Queue.TryDequeue(out var info)) + if (!_isWindowVisible) + { + return; + } + + while (_queue.TryDequeue(out var info)) { CreateNewLogEntry(info); } @@ -119,9 +123,9 @@ private void SetupDocument() { document.EnableLocalization(); } - + _container = document.rootVisualElement; - + StartCoroutine(SetupWindow()); } @@ -149,8 +153,9 @@ private void InitializeElements() // Binding all of the buttons to their respective functions _container.Q