diff --git a/.editorconfig b/.editorconfig index 1f8ecc2c..d5fe079c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -105,6 +105,12 @@ dotnet_diagnostic.S1244.severity = none # S2325: Methods and properties that don't access instance data should be static dotnet_diagnostic.S2325.severity = none +# CA1710: Identifiers should have correct suffix +dotnet_diagnostic.CA1710.severity = silent + +# CA1010: Generic interface should also be implemented +dotnet_diagnostic.CA1010.severity = silent + # IDE0005: Using directive is unnecessary. dotnet_diagnostic.IDE0005.severity = warning @@ -113,3 +119,6 @@ dotnet_diagnostic.SA1114.severity = none # SA1143: Conditional expressions must be formatted consistently dotnet_diagnostic.SA1143.severity = none + +# SA1504: All accessors should be single-line or multi-line +dotnet_diagnostic.SA1504.severity = none diff --git a/MiraAPI/Colors/PaletteManager.cs b/MiraAPI/Colors/PaletteManager.cs index 837e6bc2..c5cba43f 100644 --- a/MiraAPI/Colors/PaletteManager.cs +++ b/MiraAPI/Colors/PaletteManager.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using HarmonyLib; @@ -46,8 +45,11 @@ public static class PaletteManager private static int originalLength; - internal static bool RegisterColors(Type type, MiraPluginInfo miraPlugin) + internal static bool RegisterColors(in MiraPluginManager.RegistrationContext context) { + var type = context.Type; + var miraPlugin = context.MiraPlugin; + if (!type.TryGetCustomAttribute(out var attribute)) { return false; diff --git a/MiraAPI/Events/MiraEventManager.cs b/MiraAPI/Events/MiraEventManager.cs index 60bb38dd..219b00d1 100644 --- a/MiraAPI/Events/MiraEventManager.cs +++ b/MiraAPI/Events/MiraEventManager.cs @@ -75,8 +75,11 @@ public static class MiraEventManager return true; } - internal static bool RegisterEventType(Type eventType, MiraPluginInfo info) + internal static bool RegisterEventType(in MiraPluginManager.RegistrationContext context) { + var eventType = context.Type; + var pluginInfo = context.PluginInfo; + if (eventType.IsAbstract || !eventType.IsSubclassOf(typeof(MiraEvent))) { return false; @@ -91,7 +94,7 @@ public static class MiraEventManager AddTypeToTracked(supertype, eventType); } - info.InternalEventTypes.Add(eventType); + pluginInfo.InternalEventTypes.Add(eventType); InternalEventTypes.Add(eventType); return true; @@ -334,11 +337,16 @@ public static class MiraEventManager EventHandlersToLoad.Clear(); } - internal static void RegisterEvents(Type type, IMiraPlugin miraPlugin) + internal static bool RegisterEvents(in MiraPluginManager.RegistrationContext context) { - if (!miraPlugin.ForceRegisterEvents && !type.IsDefined()) + var type = context.Type; + var miraPlugin = context.MiraPlugin; + + var hasContainerAttribute = type.IsDefined(); + + if (!miraPlugin.ForceRegisterEvents && !hasContainerAttribute) { - return; + return false; } foreach (var method in type.GetMethods(MiraPluginManager.DeclaredStaticMembers)) @@ -356,5 +364,7 @@ public static class MiraEventManager RegisterEventHandler(method, eventAttribute.Priority, eventAttribute.InvokeOnSubtype); } + + return hasContainerAttribute; } } diff --git a/MiraAPI/GameEnd/GameOverManager.cs b/MiraAPI/GameEnd/GameOverManager.cs index 0a6288d8..e86c2c7a 100644 --- a/MiraAPI/GameEnd/GameOverManager.cs +++ b/MiraAPI/GameEnd/GameOverManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using MiraAPI.PluginLoading; namespace MiraAPI.GameEnd; @@ -14,26 +15,28 @@ public static class GameOverManager private static int nextId = Enum.GetNames().Length; - internal static bool RegisterGameOver(Type gameOverType) + internal static bool RegisterGameOver(in MiraPluginManager.RegistrationContext context) { - if (!typeof(CustomGameOver).IsAssignableFrom(gameOverType)) + var type = context.Type; + + if (!typeof(CustomGameOver).IsAssignableFrom(type)) { return false; } - if (gameOverType.IsAbstract) + if (type.IsAbstract) { return false; } - if (gameOverType.GetConstructor(Type.EmptyTypes) == null) + if (type.GetConstructor(Type.EmptyTypes) == null) { Error("The type must have a parameterless constructor."); return false; } - GameOverIds.Add(gameOverType, nextId); - GameOverTypes.Add(nextId, gameOverType); + GameOverIds.Add(type, nextId); + GameOverTypes.Add(nextId, type); nextId++; return true; } diff --git a/MiraAPI/GameModes/CustomGameModeManager.cs b/MiraAPI/GameModes/CustomGameModeManager.cs index b6e90e39..11f8fd6c 100644 --- a/MiraAPI/GameModes/CustomGameModeManager.cs +++ b/MiraAPI/GameModes/CustomGameModeManager.cs @@ -19,16 +19,19 @@ public static class CustomGameModeManager return ++lastId; } - internal static bool RegisterGameMode(Type gameModeType, MiraPluginInfo pluginInfo) + internal static bool RegisterGameMode(in MiraPluginManager.RegistrationContext context) { - if (!typeof(AbstractGameMode).IsAssignableFrom(gameModeType)) + var type = context.Type; + var pluginInfo = context.PluginInfo; + + if (!typeof(AbstractGameMode).IsAssignableFrom(type)) { return false; } - if (Activator.CreateInstance(gameModeType) is not AbstractGameMode mode) + if (Activator.CreateInstance(type) is not AbstractGameMode mode) { - Error($"Failed to create instance of {gameModeType.Name}"); + Error($"Failed to create instance of {type.Name}"); return false; } diff --git a/MiraAPI/GameOptions/AbstractOptionGroup.cs b/MiraAPI/GameOptions/AbstractOptionGroup.cs index 589f705e..be370b1d 100644 --- a/MiraAPI/GameOptions/AbstractOptionGroup.cs +++ b/MiraAPI/GameOptions/AbstractOptionGroup.cs @@ -154,9 +154,6 @@ public abstract class AbstractOptionGroup : AbstractOptionGroup public abstract class AbstractRoleOptionGroup : AbstractOptionGroup where T : ICustomRole { - /// - public override Type OptionableType => typeof(T); - /// public override MenuCategory ParentMenu => MenuCategory.Roles; diff --git a/MiraAPI/GameOptions/Attributes/OptionList/ModdedEnumOptionListAttribute.cs b/MiraAPI/GameOptions/Attributes/OptionList/ModdedEnumOptionListAttribute.cs index bf2fdf07..55e78a74 100644 --- a/MiraAPI/GameOptions/Attributes/OptionList/ModdedEnumOptionListAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/OptionList/ModdedEnumOptionListAttribute.cs @@ -15,7 +15,7 @@ namespace MiraAPI.GameOptions.Attributes; public class ModdedEnumOptionListAttribute(string title, Type enumType, string[]? values = null) : ModdedOptionListAttribute(title) { - internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property) + internal override IBaseModdedOptionList CreateOptionList(IList value, PropertyInfo property) { var optList = new ModdedOptionList( value.Count, idx => new(GetFormattedTitle(idx), (int)(value[idx] ?? 0), enumType, values)); @@ -25,14 +25,14 @@ public class ModdedEnumOptionListAttribute(string title, Type enumType, string[] /// public override void SetValue(int idx, object value) { - var opt = HolderOptionList?[idx] as ModdedEnumOption; + var opt = HolderOptionList?.ElementAt(idx) as ModdedEnumOption; opt?.SetValue((int)value); } /// public override object GetValue(int idx) { - return HolderOptionList?[idx] is ModdedEnumOption opt + return HolderOptionList?.ElementAt(idx) is ModdedEnumOption opt ? Enum.ToObject(enumType, opt.Value) : throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" with EnumType {enumType.FullName} is not a ModdedEnumOption"); } @@ -49,7 +49,7 @@ public class ModdedEnumOptionListAttribute(string title, string[]? values = n : ModdedOptionListAttribute(title) where T : struct, Enum { - internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property) + internal override IBaseModdedOptionList CreateOptionList(IList value, PropertyInfo property) { var optList = new ModdedOptionList>( value.Count, idx => new(GetFormattedTitle(idx), (T)(value[idx] ?? 0), values)); @@ -59,14 +59,14 @@ public class ModdedEnumOptionListAttribute(string title, string[]? values = n /// public override void SetValue(int idx, object value) { - var opt = HolderOptionList?[idx] as ModdedEnumOption; + var opt = HolderOptionList?.ElementAt(idx) as ModdedEnumOption; opt?.SetValue((T)value); } /// public override object GetValue(int idx) { - return HolderOptionList?[idx] is ModdedEnumOption opt + return HolderOptionList?.ElementAt(idx) is ModdedEnumOption opt ? opt.Value : throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" with EnumType {typeof(T).FullName} is not a ModdedEnumOption<{typeof(T).FullName}>"); } diff --git a/MiraAPI/GameOptions/Attributes/OptionList/ModdedNumberOptionListAttribute.cs b/MiraAPI/GameOptions/Attributes/OptionList/ModdedNumberOptionListAttribute.cs index 2f761faa..bbcf4d92 100644 --- a/MiraAPI/GameOptions/Attributes/OptionList/ModdedNumberOptionListAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/OptionList/ModdedNumberOptionListAttribute.cs @@ -53,7 +53,7 @@ public class ModdedNumberOptionListAttribute( { } - internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property) + internal override IBaseModdedOptionList CreateOptionList(IList value, PropertyInfo property) { return new ModdedOptionList(value.Count, idx => { @@ -81,7 +81,7 @@ public class ModdedNumberOptionListAttribute( /// public override void SetValue(int idx, object value) { - if (HolderOptionList?[idx] is not ModdedNumberOption opt) + if (HolderOptionList?.ElementAt(idx) is not ModdedNumberOption opt) return; var final = value switch @@ -95,7 +95,7 @@ public class ModdedNumberOptionListAttribute( /// public override object GetValue(int idx) { - if (HolderOptionList?[idx] is not ModdedNumberOption opt) + if (HolderOptionList?.ElementAt(idx) is not ModdedNumberOption opt) throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedNumberOption"); var value = opt.Value; diff --git a/MiraAPI/GameOptions/Attributes/OptionList/ModdedOptionListAttribute.cs b/MiraAPI/GameOptions/Attributes/OptionList/ModdedOptionListAttribute.cs index 6881fcb3..781707d5 100644 --- a/MiraAPI/GameOptions/Attributes/OptionList/ModdedOptionListAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/OptionList/ModdedOptionListAttribute.cs @@ -16,7 +16,7 @@ namespace MiraAPI.GameOptions.Attributes; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")] public abstract class ModdedOptionListAttribute(string title) : PropertyOptionAttribute { - internal IModdedOptionList? HolderOptionList; + internal IBaseModdedOptionList? HolderOptionList; internal IList? Value; internal Type ValueType; @@ -70,7 +70,7 @@ public abstract class ModdedOptionListAttribute(string title) : PropertyOptionAt /// The value of the option as an object. public abstract object GetValue(int idx); - internal abstract IModdedOptionList? CreateOptionList(IList value, PropertyInfo property); + internal abstract IBaseModdedOptionList? CreateOptionList(IList value, PropertyInfo property); /// /// Gets the formatted with the option's index. diff --git a/MiraAPI/GameOptions/Attributes/OptionList/ModdedPlayerOptionListAttribute.cs b/MiraAPI/GameOptions/Attributes/OptionList/ModdedPlayerOptionListAttribute.cs index a8fdd502..c9666608 100644 --- a/MiraAPI/GameOptions/Attributes/OptionList/ModdedPlayerOptionListAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/OptionList/ModdedPlayerOptionListAttribute.cs @@ -16,7 +16,7 @@ public class ModdedPlayerOptionListAttribute( bool allowNone = true) : ModdedOptionListAttribute(title) { - internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property) + internal override IBaseModdedOptionList CreateOptionList(IList value, PropertyInfo property) { return new ModdedOptionList(value.Count, idx => new(GetFormattedTitle(idx), allowNone)); } @@ -24,7 +24,7 @@ public class ModdedPlayerOptionListAttribute( /// public override void SetValue(int idx, object value) { - if (HolderOptionList?[idx] is not ModdedPlayerOption opt) + if (HolderOptionList?.ElementAt(idx) is not ModdedPlayerOption opt) return; var final = value switch @@ -38,7 +38,7 @@ public class ModdedPlayerOptionListAttribute( /// public override object GetValue(int idx) { - if (HolderOptionList?[idx] is not ModdedPlayerOption opt) + if (HolderOptionList?.ElementAt(idx) is not ModdedPlayerOption opt) throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedPlayerOption"); if (ValueType == typeof(int)) diff --git a/MiraAPI/GameOptions/Attributes/OptionList/ModdedStringOptionListAttribute.cs b/MiraAPI/GameOptions/Attributes/OptionList/ModdedStringOptionListAttribute.cs index c8b9063d..d3b551fd 100644 --- a/MiraAPI/GameOptions/Attributes/OptionList/ModdedStringOptionListAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/OptionList/ModdedStringOptionListAttribute.cs @@ -17,7 +17,7 @@ public class ModdedStringOptionListAttribute( string[] values) : ModdedOptionListAttribute(title) { - internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property) + internal override IBaseModdedOptionList CreateOptionList(IList value, PropertyInfo property) { return new ModdedOptionList(value.Count, idx => new ModdedStringOption(Title.Translate(), (string)(value[idx] ?? string.Empty), values)); @@ -26,14 +26,14 @@ public class ModdedStringOptionListAttribute( /// public override void SetValue(int idx, object value) { - var opt = HolderOptionList?[idx] as ModdedStringOption; + var opt = HolderOptionList?.ElementAt(idx) as ModdedStringOption; opt?.SetValue((string)value); } /// public override object GetValue(int idx) { - return HolderOptionList?[idx] is ModdedStringOption opt + return HolderOptionList?.ElementAt(idx) is ModdedStringOption opt ? opt.Value : throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedStringOption"); } diff --git a/MiraAPI/GameOptions/Attributes/OptionList/ModdedToggleOptionListAttribute.cs b/MiraAPI/GameOptions/Attributes/OptionList/ModdedToggleOptionListAttribute.cs index b79b4a6d..1fa45010 100644 --- a/MiraAPI/GameOptions/Attributes/OptionList/ModdedToggleOptionListAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/OptionList/ModdedToggleOptionListAttribute.cs @@ -28,7 +28,7 @@ public class ModdedToggleOptionListAttribute( { } - internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property) + internal override IBaseModdedOptionList CreateOptionList(IList value, PropertyInfo property) { var optList = new ModdedOptionList( value.Count, idx => new(GetFormattedTitle(idx), (bool)(value[idx] ?? false), on, off)); @@ -38,14 +38,14 @@ public class ModdedToggleOptionListAttribute( /// public override void SetValue(int idx, object value) { - var opt = HolderOptionList?[idx] as ModdedToggleOption; + var opt = HolderOptionList?.ElementAt(idx) as ModdedToggleOption; opt?.SetValue((bool)value); } /// public override object GetValue(int idx) { - return HolderOptionList?[idx] is ModdedToggleOption opt + return HolderOptionList?.ElementAt(idx) is ModdedToggleOption opt ? opt.Value : throw new InvalidOperationException($"Holder option for {GetFormattedTitle(idx)} is not a ModdedToggleOption."); } diff --git a/MiraAPI/GameOptions/IModdedOption.cs b/MiraAPI/GameOptions/IModdedOption.cs index a40c9460..344e2b38 100644 --- a/MiraAPI/GameOptions/IModdedOption.cs +++ b/MiraAPI/GameOptions/IModdedOption.cs @@ -1,4 +1,5 @@ using System; +using System.Collections; using System.Collections.Generic; using BepInEx.Configuration; using MiraAPI.Networking; @@ -143,9 +144,11 @@ public interface IModdedOption } /// -/// Interface for list of modded options. +/// Base interface for list of modded options. +/// +/// Do not implement directly, implement or instead. /// -public interface IModdedOptionList : IReadOnlyList +public interface IBaseModdedOptionList : IEnumerable { /// /// Gets the function to name the keys of the individual options in the configuration file. @@ -153,18 +156,34 @@ public interface IModdedOptionList : IReadOnlyList /// Return to use the default of the property's name with its index appended. /// Func? ConfigName { get; init; } + + /// + int Count { get; } + + /// + IModdedOption ElementAt(int index); +} + +/// +/// Interface for list of modded options. +/// +public interface IModdedOptionList : IBaseModdedOptionList, IReadOnlyList +{ + IModdedOption IBaseModdedOptionList.ElementAt(int index) + { + return this[index]; + } } /// /// Interface for list of options. /// /// The type of . -public interface IModdedOptionList : IModdedOptionList +public interface IModdedOptionList : IBaseModdedOptionList, IReadOnlyList where T : IModdedOption { - /// - new T this[int index] { get; } - - /// - new IEnumerator GetEnumerator(); + IModdedOption IBaseModdedOptionList.ElementAt(int index) + { + return this[index]; + } } diff --git a/MiraAPI/GameOptions/ModdedOptionsManager.cs b/MiraAPI/GameOptions/ModdedOptionsManager.cs index 2a7cbede..8071299f 100644 --- a/MiraAPI/GameOptions/ModdedOptionsManager.cs +++ b/MiraAPI/GameOptions/ModdedOptionsManager.cs @@ -70,8 +70,11 @@ public static class ModdedOptionsManager "Major Code Smell", "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")] - internal static bool RegisterGroup(Type type, MiraPluginInfo pluginInfo) + internal static bool RegisterGroup(in MiraPluginManager.RegistrationContext context) { + var type = context.Type; + var pluginInfo = context.PluginInfo; + if (!type.IsAssignableTo(typeof(AbstractOptionGroup))) { return false; @@ -116,7 +119,7 @@ public static class ModdedOptionsManager continue; } - if (property.PropertyType.IsAssignableTo(typeof(IModdedOptionList))) + if (property.PropertyType.IsAssignableTo(typeof(IBaseModdedOptionList))) { RegisterPropertyOptionList(type, property, pluginInfo); continue; @@ -136,7 +139,7 @@ public static class ModdedOptionsManager foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers) .Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) - && (f.FieldType.IsAssignableTo(typeof(IModdedOption)) || f.FieldType.IsAssignableTo(typeof(IModdedOptionList))))) + && (f.FieldType.IsAssignableTo(typeof(IModdedOption)) || f.FieldType.IsAssignableTo(typeof(IBaseModdedOptionList))))) { Error($"{field.Name} is a field, not a property. Use properties for options."); } @@ -234,7 +237,7 @@ public static class ModdedOptionsManager return; } - if (property.GetValue(group) is not IModdedOptionList optionList) + if (property.GetValue(group) is not IBaseModdedOptionList optionList) { Error($"Failed to get option list for {property.Name}"); return; @@ -244,7 +247,7 @@ public static class ModdedOptionsManager for (var i = 0; i < optionList.Count; i++) { - RegisterOption(optionList[i], group, configName(i), pluginInfo); + RegisterOption(optionList.ElementAt(i), group, configName(i), pluginInfo); } } @@ -341,7 +344,7 @@ public static class ModdedOptionsManager for (var i = 0; i < optionList.Count; i++) { - var option = optionList[i]; + var option = optionList.ElementAt(i); if (visibilityFactory != null) option.Visible = (Func)(visibilityFactory(i) ?? DelegateUtilities.AlwaysTrue); diff --git a/MiraAPI/GameOptions/OptionTypes/ModdedOptionList.cs b/MiraAPI/GameOptions/OptionTypes/ModdedOptionList.cs index a7a8549e..95beb16f 100644 --- a/MiraAPI/GameOptions/OptionTypes/ModdedOptionList.cs +++ b/MiraAPI/GameOptions/OptionTypes/ModdedOptionList.cs @@ -62,13 +62,4 @@ public class ModdedOptionList : IModdedOptionList { return Options.GetEnumerator(); } - - /// - IEnumerator IEnumerable.GetEnumerator() - { - return ((IEnumerable)Options).GetEnumerator(); - } - - /// - IModdedOption IReadOnlyList.this[int index] => this[index]; } diff --git a/MiraAPI/Hud/CustomButtonManager.cs b/MiraAPI/Hud/CustomButtonManager.cs index 1e8656ed..36e4da66 100644 --- a/MiraAPI/Hud/CustomButtonManager.cs +++ b/MiraAPI/Hud/CustomButtonManager.cs @@ -16,17 +16,17 @@ public static class CustomButtonManager /// /// Gets a list of all registered custom s. /// - public static ReadOnlyCollection Buttons { get; internal set; } = new([]); + public static ReadOnlyCollection Buttons { get; private set; } = new([]); /// /// Gets a list of all registered button-specific s. /// - public static ReadOnlyDictionary EventTypes { get; internal set; } = new(new Dictionary()); + public static ReadOnlyDictionary EventTypes { get; private set; } = new(new Dictionary()); /// /// Gets a list of all registered button-specific s. /// - public static ReadOnlyDictionary CancelledEventTypes { get; internal set; } = new(new Dictionary()); + public static ReadOnlyDictionary CancelledEventTypes { get; private set; } = new(new Dictionary()); internal static readonly List CustomButtons = []; internal static readonly Dictionary ButtonEventTypes = []; @@ -36,9 +36,12 @@ public static class CustomButtonManager "Major Code Smell", "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")] - internal static bool RegisterButton(Type buttonType, MiraPluginInfo pluginInfo) + internal static bool RegisterButton(in MiraPluginManager.RegistrationContext context) { - if (!buttonType.IsAssignableTo(typeof(CustomActionButton)) || Activator.CreateInstance(buttonType) is not CustomActionButton button) + var type = context.Type; + var pluginInfo = context.PluginInfo; + + if (!type.IsAssignableTo(typeof(CustomActionButton)) || Activator.CreateInstance(type) is not CustomActionButton button) { return false; } @@ -46,13 +49,21 @@ public static class CustomButtonManager CustomButtons.Add(button); pluginInfo.InternalButtons.Add(button); - typeof(CustomButtonSingleton<>).MakeGenericType(buttonType) + typeof(CustomButtonSingleton<>).MakeGenericType(type) .GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Suppression message refers to this .SetValue(null, button); - ButtonEventTypes.Add(buttonType, typeof(MiraButtonClickEvent<>).MakeGenericType(buttonType)); - ButtonCancelledEventTypes.Add(buttonType, typeof(MiraButtonCancelledEvent<>).MakeGenericType(buttonType)); + ButtonEventTypes.Add(type, typeof(MiraButtonClickEvent<>).MakeGenericType(type)); + ButtonCancelledEventTypes.Add(type, typeof(MiraButtonCancelledEvent<>).MakeGenericType(type)); return true; } + + internal static void RegisterAllButtons() + { + // Save all buttons into a read-only collection for easy access + Buttons = new ReadOnlyCollection(CustomButtonManager.CustomButtons); + EventTypes = new ReadOnlyDictionary(CustomButtonManager.ButtonEventTypes); + CancelledEventTypes = new ReadOnlyDictionary(CustomButtonManager.ButtonCancelledEventTypes); + } } diff --git a/MiraAPI/Keybinds/KeybindManager.cs b/MiraAPI/Keybinds/KeybindManager.cs index 2f0287d2..cffe9b35 100644 --- a/MiraAPI/Keybinds/KeybindManager.cs +++ b/MiraAPI/Keybinds/KeybindManager.cs @@ -78,8 +78,11 @@ public static class KeybindManager } } - internal static bool RegisterKeybinds(Type type, IMiraPlugin plugin) + internal static bool RegisterKeybinds(in MiraPluginManager.RegistrationContext context) { + var type = context.Type; + var miraPlugin = context.MiraPlugin; + if (!type.IsDefined()) { return false; @@ -87,7 +90,7 @@ public static class KeybindManager foreach (var property in type.GetProperties(MiraPluginManager.DeclaredStaticMembers)) { - if (property.PropertyType != typeof(MiraKeybind)) + if (!property.PropertyType.IsAssignableTo(typeof(MiraKeybind))) { continue; } @@ -99,10 +102,10 @@ public static class KeybindManager } Keybinds.Add(keybind); - keybind.SourcePluginName = plugin.OptionsTitleText.Translate(); + keybind.SourcePluginName = miraPlugin.OptionsTitleText.Translate(); } - if (!plugin.DebugMode) + if (!miraPlugin.DebugMode) return true; foreach (var field in type.GetFields(MiraPluginManager.DeclaredStaticMembers) diff --git a/MiraAPI/LocalSettings/LocalSettingsManager.cs b/MiraAPI/LocalSettings/LocalSettingsManager.cs index 44d77681..646a2664 100644 --- a/MiraAPI/LocalSettings/LocalSettingsManager.cs +++ b/MiraAPI/LocalSettings/LocalSettingsManager.cs @@ -4,7 +4,6 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using BepInEx.Configuration; -using BepInEx.Unity.IL2CPP; using MiraAPI.LocalSettings.Attributes; using MiraAPI.PluginLoading; using MiraAPI.Utilities; @@ -24,8 +23,11 @@ public static class LocalSettingsManager "Major Code Smell", "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")] - internal static bool RegisterLocalTabs(Type type, BasePlugin pluginInfo) + internal static bool RegisterLocalTabs(in MiraPluginManager.RegistrationContext context) { + var type = context.Type; + var basePlugin = context.BasePlugin; + if (!type.IsAssignableTo(typeof(LocalSettingsTab))) { return false; @@ -37,7 +39,7 @@ public static class LocalSettingsManager return false; } - if (Activator.CreateInstance(type, pluginInfo.Config) is not LocalSettingsTab tabInstance) + if (Activator.CreateInstance(type, basePlugin.Config) is not LocalSettingsTab tabInstance) { return false; } diff --git a/MiraAPI/MeetingAbilities/MeetingButtonManager.cs b/MiraAPI/MeetingAbilities/MeetingButtonManager.cs index 92348f5d..f93aa7c6 100644 --- a/MiraAPI/MeetingAbilities/MeetingButtonManager.cs +++ b/MiraAPI/MeetingAbilities/MeetingButtonManager.cs @@ -22,28 +22,34 @@ public static class MeetingButtonManager /// public static List UntargetedButtons { get; internal set; } = []; - internal static bool RegisterTargetedMeetingButton(Type type, MiraPluginInfo info) + internal static bool RegisterTargetedMeetingButton(in MiraPluginManager.RegistrationContext context) { + var type = context.Type; + var pluginInfo = context.PluginInfo; + if (!typeof(TargetedMeetingButton).IsAssignableFrom(type)) { return false; } var button = (Activator.CreateInstance(type) as TargetedMeetingButton)!; - info.InternalTargetedMeetingButtons.Add(button); + pluginInfo.InternalTargetedMeetingButtons.Add(button); TargetedButtons.Add(button); return true; } - internal static bool RegisterMeetingButton(Type type, MiraPluginInfo info) + internal static bool RegisterMeetingButton(in MiraPluginManager.RegistrationContext context) { + var type = context.Type; + var pluginInfo = context.PluginInfo; + if (!typeof(MeetingActionButton).IsAssignableFrom(type)) { return false; } var button = (Activator.CreateInstance(type) as MeetingActionButton)!; - info.InternalMeetingButtons.Add(button); + pluginInfo.InternalMeetingButtons.Add(button); UntargetedButtons.Add(button); return true; } diff --git a/MiraAPI/Modifiers/ModifierManager.cs b/MiraAPI/Modifiers/ModifierManager.cs index aa6c5120..d22edb67 100644 --- a/MiraAPI/Modifiers/ModifierManager.cs +++ b/MiraAPI/Modifiers/ModifierManager.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; using System.Runtime.Serialization; using MiraAPI.Modifiers.Types; @@ -25,7 +26,7 @@ public static class ModifierManager /// /// Gets the list of all registered s. /// - public static IReadOnlyList Modifiers { get; internal set; } = []; + public static IReadOnlyList Modifiers { get; private set; } = []; internal static List InternalModifiers { get; } = []; @@ -61,31 +62,39 @@ public static class ModifierManager return !TypeToIdModifierMap.TryGetValue(type, out var id) ? null : id; } - internal static bool RegisterModifier(Type modifierType, MiraPluginInfo info) + internal static void RegisterAllModifiers() { - if (!typeof(BaseModifier).IsAssignableFrom(modifierType)) + Modifiers = new ReadOnlyCollection(InternalModifiers); + } + + internal static bool RegisterModifier(in MiraPluginManager.RegistrationContext context) + { + var type = context.Type; + var pluginInfo = context.PluginInfo; + + if (!typeof(BaseModifier).IsAssignableFrom(type)) { return false; } var id = GetNextTypeId(); - IdToTypeModifierMap.Add(id, modifierType); - TypeToIdModifierMap.Add(modifierType, id); + IdToTypeModifierMap.Add(id, type); + TypeToIdModifierMap.Add(type, id); BaseModifier modifier; - var ctor = modifierType.GetConstructor(Type.EmptyTypes); + var ctor = type.GetConstructor(Type.EmptyTypes); if (ctor != null) { - modifier = (BaseModifier)Activator.CreateInstance(modifierType)!; + modifier = (BaseModifier)Activator.CreateInstance(type)!; } else { // this is probably terrible but its good enough for now. - modifier = (BaseModifier)FormatterServices.GetUninitializedObject(modifierType); + modifier = (BaseModifier)FormatterServices.GetUninitializedObject(type); } - info.InternalModifiers.Add(modifier); + pluginInfo.InternalModifiers.Add(modifier); InternalModifiers.Add(modifier); if (modifier is not GameModifier gameModifier) @@ -95,7 +104,7 @@ public static class ModifierManager if (ctor == null) { - Error($"Game Modifier {modifierType.FullName} does not have a parameterless constructor!"); + Error($"Game Modifier {type.FullName} does not have a parameterless constructor!"); return false; } diff --git a/MiraAPI/Patches/RoleGuidePatches.cs b/MiraAPI/Patches/RoleGuidePatches.cs index f7a28caf..ddb814f9 100644 --- a/MiraAPI/Patches/RoleGuidePatches.cs +++ b/MiraAPI/Patches/RoleGuidePatches.cs @@ -88,6 +88,8 @@ public static class RoleGuidePatches private static bool IsModifiersTabActive => ActiveGuideTabIndex == ModifiersTabIndex; + private static readonly PropertyInfo? CaretYOffset = typeof(TextBoxTMP).GetProperty("caretYOffset", BindingFlags.Instance | BindingFlags.Public); + [HarmonyPostfix] [HarmonyPriority(Priority.First)] [HarmonyPatch(typeof(MatchInfoGuide), nameof(MatchInfoGuide.CreateNormalModeSettings))] @@ -214,16 +216,6 @@ public static class RoleGuidePatches Coroutines.Start(CoPreload(__instance)); } - public static void TriggerPreload(MatchInfoGuide instance) - { - if (!instance || _populate != null) - { - return; - } - - Coroutines.Start(CoPreload(instance)); - } - private static IEnumerator CoPreload(MatchInfoGuide instance) { while (instance && (!HudManager.InstanceExists || !GameManager.Instance)) @@ -765,8 +757,7 @@ public static class RoleGuidePatches modifier.ModifierCategoryTitle, modifier.ParentMod.MiraPlugin.GetAbbreviatedModName(), null, - modifier, - modifier.TypeId)); + modifier)); } } @@ -802,8 +793,7 @@ public static class RoleGuidePatches roleBehaviour.GetCategoryTitle(), modId, roleBehaviour, - null, - (uint)roleBehaviour.Role)); + null)); } _roleEntriesMode = activeModeType; @@ -834,16 +824,14 @@ public static class RoleGuidePatches private static float GetCaretYOffset(TextBoxTMP box) { + if (CaretYOffset == null) + { + return 0f; + } + try { - var prop = typeof(TextBoxTMP).GetProperty("caretYOffset", BindingFlags.Instance | BindingFlags.Public); - - if (prop == null) - { - return 0f; - } - - return Convert.ToSingle(prop.GetValue(box), CultureInfo.InvariantCulture); + return Convert.ToSingle(CaretYOffset.GetValue(box), CultureInfo.InvariantCulture); } catch { @@ -960,14 +948,13 @@ public static class RoleGuidePatches } } - private sealed class DetailedPanel(string title, string category, string modId, RoleBehaviour? role, GameModifier? modifier, uint typeId) + private sealed class DetailedPanel(string title, string category, string modId, RoleBehaviour? role, GameModifier? modifier) { public string Title => title; public string Category => category; public string ModId => modId; public RoleBehaviour? Role => role; public GameModifier? Modifier => modifier; - public uint TypeId => typeId; public MatchInfoRolePanel? Panel { get; set; } public int Amount { get; set; } public int Chance { get; set; } @@ -1004,12 +991,12 @@ public static class RoleGuidePatches private static void UpdateSpinner() { - if (_loadingSpinner != null) - { - _loadingSpinner.gameObject.SetActive( - _loading && ActiveGuideTabIndex is RolesTabIndex or ModifiersTabIndex && - !(_wikiScroller && _wikiScroller.gameObject.activeSelf)); - } + if (_loadingSpinner == null) + return; + + _loadingSpinner.gameObject.SetActive( + _loading && ActiveGuideTabIndex is RolesTabIndex or ModifiersTabIndex && + !(_wikiScroller && _wikiScroller.gameObject.activeSelf)); } private static float GetGridScrollBounds(int count) @@ -1074,14 +1061,16 @@ public static class RoleGuidePatches foreach (var item in collection) { action(item); - if (timer.ElapsedMilliseconds > budget) + if (timer.ElapsedMilliseconds <= budget) { - timer.Restart(); - yield return null; - if (!_guide) - { - yield break; - } + continue; + } + + timer.Restart(); + yield return null; + if (!_guide) + { + yield break; } } } @@ -1188,15 +1177,17 @@ public static class RoleGuidePatches { ComputeCounts(entry); entry.Visible = entry.CanShow && MatchesSearch(entry, searchText); - if (entry.Panel) + if (!entry.Panel) { - dynamic entryType = entry.Modifier != null ? entry.Modifier : entry.Role!; - var text = GetPanelCountText(entryType, entry.Amount, entry.Chance, entry.ModId); - SetPanelCount(entry.Panel!, text); - if (!entry.Visible && entry.Panel!.gameObject.activeSelf) - { - entry.Panel.gameObject.SetActive(false); - } + continue; + } + + dynamic entryType = entry.Modifier != null ? entry.Modifier : entry.Role!; + var text = GetPanelCountText(entryType, entry.Amount, entry.Chance, entry.ModId); + SetPanelCount(entry.Panel!, text); + if (!entry.Visible && entry.Panel!.gameObject.activeSelf) + { + entry.Panel.gameObject.SetActive(false); } } @@ -1244,7 +1235,6 @@ public static class RoleGuidePatches var activeModifiers = GetActiveModifiers(); var comparisons = activeModifiers.Select(x => x.TypeId).ToList(); comparisons.AddRange(GetActiveRoles().Select(x => (uint)x.Role)); - return comparisons; } @@ -1450,26 +1440,20 @@ public static class RoleGuidePatches { if (hover) { - switch (value) + return value switch { - case SortingFilter.AllRoles: - return MiraAssets.VisibleAllHoverSprite; - case SortingFilter.DisabledOnly: - return MiraAssets.VisibleOffHoverSprite; - default: - return MiraAssets.VisibleOnHoverSprite; - } + SortingFilter.AllRoles => MiraAssets.VisibleAllHoverSprite, + SortingFilter.DisabledOnly => MiraAssets.VisibleOffHoverSprite, + _ => MiraAssets.VisibleOnHoverSprite, + }; } - switch (value) + return value switch { - case SortingFilter.AllRoles: - return MiraAssets.VisibleAllIdleSprite; - case SortingFilter.DisabledOnly: - return MiraAssets.VisibleOffIdleSprite; - default: - return MiraAssets.VisibleOnIdleSprite; - } + SortingFilter.AllRoles => MiraAssets.VisibleAllIdleSprite, + SortingFilter.DisabledOnly => MiraAssets.VisibleOffIdleSprite, + _ => MiraAssets.VisibleOnIdleSprite, + }; } public static void SwitchMethod() @@ -1535,26 +1519,20 @@ public static class RoleGuidePatches { if (hover) { - switch (value) + return value switch { - case SortingGroups.Faction: - return MiraAssets.GroupFactionHoverSprite; - case SortingGroups.AmountChance: - return MiraAssets.GroupCountHoverSprite; - default: - return MiraAssets.GroupNoneHoverSprite; - } + SortingGroups.Faction => MiraAssets.GroupFactionHoverSprite, + SortingGroups.AmountChance => MiraAssets.GroupCountHoverSprite, + _ => MiraAssets.GroupNoneHoverSprite, + }; } - switch (value) + return value switch { - case SortingGroups.Faction: - return MiraAssets.GroupFactionIdleSprite; - case SortingGroups.AmountChance: - return MiraAssets.GroupCountIdleSprite; - default: - return MiraAssets.GroupNoneIdleSprite; - } + SortingGroups.Faction => MiraAssets.GroupFactionIdleSprite, + SortingGroups.AmountChance => MiraAssets.GroupCountIdleSprite, + _ => MiraAssets.GroupNoneIdleSprite, + }; } private static void CopyTextLayout(TextMeshPro source, TextMeshPro target) @@ -1597,7 +1575,7 @@ public static class RoleGuidePatches passiveButton.ClickSound = HudManager.Instance.MapButton.ClickSound; passiveButton.OnMouseOver = new UnityEvent(); passiveButton.OnMouseOver.AddListener( - (UnityAction)(() => { panel.roleIcon.color = new Color32(255, 255, 255, 150); })); + (UnityAction)(() => panel.roleIcon.color = new Color32(255, 255, 255, 150))); passiveButton.OnMouseOut = new UnityEvent(); passiveButton.OnMouseOut.AddListener((UnityAction)(() => { panel.roleIcon.color = Color.white; })); @@ -1724,12 +1702,10 @@ public static class RoleGuidePatches var roles = GetActiveRoles().Shuffle().ToList(); foreach (var role in roles) { - if (role.RoleIconSolid == null) + if (role.RoleIconSolid != null) { - continue; + return role.RoleIconSolid; } - - return role.RoleIconSolid; } return GetRandomFactionIcon(); @@ -1920,7 +1896,7 @@ public static class RoleGuidePatches modId); } - private static string GetPanelCountText(BaseModifier modifier, int amount, int chance, string modId) + private static string GetPanelCountText(GameModifier modifier, int amount, int chance, string modId) { return modifier.GetAmountText(amount, chance, modId); } @@ -2054,12 +2030,10 @@ public static class RoleGuidePatches private static void EnterSettingsTab() { - if (!_uiInitialized) + if (_uiInitialized) { - return; + RefreshSettingsTab(true); } - - RefreshSettingsTab(true); } private static void LeaveSettingsTab() @@ -2285,16 +2259,19 @@ public static class RoleGuidePatches private static void UpdateSettingsTitle() { - if (_titleText && IsSettingsTabActive) + if (!_titleText || !IsSettingsTabActive) { - _titleText.text = GetSettingsTitle(); - if (_titleIcon) - { - _titleIcon.sprite = GetSettingsIcon(); - - _titleIcon.SetSizeLimit(0.55f); - } + return; } + + _titleText.text = GetSettingsTitle(); + if (!_titleIcon) + { + return; + } + + _titleIcon.sprite = GetSettingsIcon(); + _titleIcon.SetSizeLimit(0.55f); } /// diff --git a/MiraAPI/PluginLoading/MiraPluginManager.cs b/MiraAPI/PluginLoading/MiraPluginManager.cs index 4f83cb80..526b96f1 100644 --- a/MiraAPI/PluginLoading/MiraPluginManager.cs +++ b/MiraAPI/PluginLoading/MiraPluginManager.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -31,6 +30,10 @@ namespace MiraAPI.PluginLoading; [SuppressMessage("Major Code Smell", "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", Justification = "Intended behaviour.")] public sealed class MiraPluginManager { + internal delegate bool TypeRegistrationHandler(in RegistrationContext context); + + internal readonly record struct RegistrationContext(Type Type, MiraPluginInfo PluginInfo, IMiraPlugin MiraPlugin, BasePlugin BasePlugin, List Roles); + private MiraPluginManager() { } @@ -49,6 +52,23 @@ public sealed class MiraPluginManager internal static ConfigFile MiraApiConfig { get; private set; } = null!; internal static MiraPluginInfo MiraApiPluginInfo { get; private set; } = null!; + private static readonly (string LogContext, TypeRegistrationHandler Handler)[] RegistrationHandlers = + [ + ("events in", MiraEventManager.RegisterEvents), + ("event type", MiraEventManager.RegisterEventType), + ("options for", ModdedOptionsManager.RegisterGroup), + ("options for", LocalSettingsManager.RegisterLocalTabs), + ("color class", PaletteManager.RegisterColors), + ("role for", CustomRoleManager.RegisterRole), + ("modifier", ModifierManager.RegisterModifier), + ("button", CustomButtonManager.RegisterButton), + ("keybind class", KeybindManager.RegisterKeybinds), + ("gamemode", CustomGameModeManager.RegisterGameMode), + ("game over", GameOverManager.RegisterGameOver), + ("meeting ability", MeetingButtonManager.RegisterMeetingButton), + ("targeted meeting ability", MeetingButtonManager.RegisterTargetedMeetingButton), + ]; + /// /// Get a mira plugin by its GUID. /// @@ -92,19 +112,14 @@ public sealed class MiraPluginManager IL2CPPChainloader.Instance.Finished += () => { PaletteManager.RegisterAllColors(); - - // Save all buttons into a read-only collection for easy access - CustomButtonManager.Buttons = new ReadOnlyCollection(CustomButtonManager.CustomButtons); - CustomButtonManager.EventTypes = new ReadOnlyDictionary(CustomButtonManager.ButtonEventTypes); - CustomButtonManager.CancelledEventTypes = new ReadOnlyDictionary(CustomButtonManager.ButtonCancelledEventTypes); + CustomButtonManager.RegisterAllButtons(); + ModifierManager.RegisterAllModifiers(); + MiraEventManager.OnLoadFinalize(); // Cache all the registered plugins into an array for easy access RegisteredPlugins = [.. _registeredPlugins.Values]; RegisteredPluginsWithOptions = [.. RegisteredPlugins.Where(m => m.MiraPlugin.DisplayOnOptionsMenu)]; PluginsWithOptionsOrGameModes = [.. RegisteredPlugins.Where(m => m.MiraPlugin.DisplayOnOptionsMenu || m.GameModes.Count > 0)]; - - ModifierManager.Modifiers = new ReadOnlyCollection(ModifierManager.InternalModifiers); - MiraEventManager.OnLoadFinalize(); }; } @@ -138,7 +153,6 @@ public sealed class MiraPluginManager field.Name.Contains(">k__BackingField", StringComparison.Ordinal); } - [SuppressMessage("Minor Code Smell", "S3626:Jump statements should not be redundant", Justification = "Code consistency.")] private static void ProcessAssemblyTypes(Assembly assembly, MiraPluginInfo info, BasePlugin basePlugin, IMiraPlugin plugin, List roles, bool isMira) { if (plugin.ForceRegisterEvents) @@ -151,221 +165,20 @@ public sealed class MiraPluginManager if ((isMira && type.IsAbstract) || type.IsDefined()) continue; - RegisterEvents(type, plugin); + var context = new RegistrationContext(type, info, plugin, basePlugin, roles); - if (RegisterEventType(type, info)) - continue; - - if (RegisterOptions(type, info)) - continue; - - if (RegisterLocalTabs(type, basePlugin)) - continue; - - if (RegisterColors(type, info)) - continue; - - if (RegisterRole(type, info, roles)) - continue; - - if (RegisterModifier(type, info)) - continue; - - if (RegisterButton(type, info)) - continue; - - if (RegisterKeybinds(type, plugin)) - continue; - - if (RegisterGameModeAttribute(type, info)) - continue; - - if (RegisterGameOver(type)) - continue; - - if (RegisterMeetingAbility(type, info)) - continue; - - if (RegisterTargetedMeetingAbility(type, info)) - continue; + foreach (var (logContext, handler) in RegistrationHandlers) + { + try + { + if (handler(in context)) + break; + } + catch (Exception e) + { + Error($"Failed to register {logContext} {type.Name}: {e}"); + } + } } } - - private static void RegisterEvents(Type type, IMiraPlugin miraPlugin) - { - try - { - MiraEventManager.RegisterEvents(type, miraPlugin); - } - catch (Exception e) - { - Error($"Failed to register events in {type.Name}: {e}"); - } - } - - private static bool RegisterEventType(Type type, MiraPluginInfo info) - { - try - { - return MiraEventManager.RegisterEventType(type, info); - } - catch (Exception e) - { - Error($"Failed to register event type {type.Name}: {e}"); - return false; - } - } - - private static bool RegisterGameOver(Type type) - { - try - { - return GameOverManager.RegisterGameOver(type); - } - catch (Exception e) - { - Error($"Failed to register game over {type.Name}: {e}"); - return false; - } - } - - private static bool RegisterOptions(Type type, MiraPluginInfo pluginInfo) - { - try - { - return ModdedOptionsManager.RegisterGroup(type, pluginInfo); - } - catch (Exception e) - { - Error($"Failed to register options for {type.Name}: {e}"); - } - - return false; - } - - private static bool RegisterRole(Type type, MiraPluginInfo pluginInfo, List roles) - { - try - { - return CustomRoleManager.RegisterRole(type, pluginInfo, roles); - } - catch (Exception e) - { - Error($"Failed to register role for {type.Name}: {e}"); - } - - return false; - } - - private static bool RegisterColors(Type type, MiraPluginInfo miraPlugin) - { - try - { - return PaletteManager.RegisterColors(type, miraPlugin); - } - catch (Exception e) - { - Error($"Failed to register color class {type.Name}: {e}"); - } - - return false; - } - - private static bool RegisterModifier(Type type, MiraPluginInfo info) - { - try - { - return ModifierManager.RegisterModifier(type, info); - } - catch (Exception e) - { - Error($"Failed to register modifier {type.Name}: {e}"); - } - - return false; - } - - private static bool RegisterButton(Type type, MiraPluginInfo pluginInfo) - { - try - { - return CustomButtonManager.RegisterButton(type, pluginInfo); - } - catch (Exception e) - { - Error($"Failed to register button {type.Name}: {e}"); - } - - return false; - } - - private static bool RegisterGameModeAttribute(Type type, MiraPluginInfo pluginInfo) - { - try - { - return CustomGameModeManager.RegisterGameMode(type, pluginInfo); - } - catch (Exception e) - { - Error($"Failed to register gamemode {type.Name}: {e}"); - } - - return false; - } - - private static bool RegisterLocalTabs(Type type, BasePlugin pluginInfo) - { - try - { - return LocalSettingsManager.RegisterLocalTabs(type, pluginInfo); - } - catch (Exception e) - { - Error($"Failed to register options for {type.Name}: {e}"); - } - - return false; - } - - private static bool RegisterKeybinds(Type type, IMiraPlugin plugin) - { - try - { - return KeybindManager.RegisterKeybinds(type, plugin); - } - catch (Exception e) - { - Error($"Failed to register keybind class {type.Name}: {e}"); - } - - return false; - } - - private static bool RegisterMeetingAbility(Type type, MiraPluginInfo info) - { - try - { - return MeetingButtonManager.RegisterMeetingButton(type, info); - } - catch (Exception e) - { - Error($"Failed to register meeting ability {type.Name}: {e}"); - } - - return false; - } - - private static bool RegisterTargetedMeetingAbility(Type type, MiraPluginInfo info) - { - try - { - return MeetingButtonManager.RegisterTargetedMeetingButton(type, info); - } - catch (Exception e) - { - Error($"Failed to register targeted meeting ability {type.Name}: {e}"); - } - - return false; - } } diff --git a/MiraAPI/Roles/CustomRoleManager.cs b/MiraAPI/Roles/CustomRoleManager.cs index a2a0164f..e836d23e 100644 --- a/MiraAPI/Roles/CustomRoleManager.cs +++ b/MiraAPI/Roles/CustomRoleManager.cs @@ -119,14 +119,18 @@ public static class CustomRoleManager pluginInfo.PluginConfig.SaveOnConfigSet = oldConfigSetting; } - internal static bool RegisterRole(Type type, MiraPluginInfo miraPlugin, List roles) + internal static bool RegisterRole(in MiraPluginManager.RegistrationContext context) { + var type = context.Type; + var pluginInfo = context.PluginInfo; + var roles = context.Roles; + if (!(typeof(RoleBehaviour).IsAssignableFrom(type) && typeof(ICustomRole).IsAssignableFrom(type))) { return false; } - if (!ModList.GetById(miraPlugin.PluginId).IsRequiredOnAllClients) + if (!ModList.GetById(pluginInfo.PluginId).IsRequiredOnAllClients) { Error("Custom roles are only supported on all clients."); return false; @@ -144,7 +148,7 @@ public static class CustomRoleManager return null; } - var roleBehaviour = (RoleBehaviour)new GameObject(roleType.Name).DontDestroy().AddComponent(Il2CppType.From(roleType)); + var roleBehaviour = new GameObject(roleType.Name).DontDestroy().AddComponent(Il2CppType.From(roleType)).Cast(); if (roleBehaviour is not ICustomRole customRole) { diff --git a/MiraAPI/Translation/MiraLocaleManager.cs b/MiraAPI/Translation/MiraLocaleManager.cs index 1bd925df..028ffcb2 100644 --- a/MiraAPI/Translation/MiraLocaleManager.cs +++ b/MiraAPI/Translation/MiraLocaleManager.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using System.Reflection; using System.Xml; +using AmongUs.Data; using MiraAPI.Utilities; using Reactor.Localization.Utilities; using UnityEngine; @@ -16,6 +17,8 @@ namespace MiraAPI.Translation; public static class MiraLocaleManager { private const string LangDirectory = "mira_languages"; + private const string RefPrefix = "@ref:"; + private const int MaxDepth = 10; // Language, XML Name, then Value @@ -40,6 +43,7 @@ public static class MiraLocaleManager /// public static Dictionary LangList { get; } = new() { + // Vanilla { MiraLanguage.English, "en_US" }, { MiraLanguage.Latam, "es_419" }, { MiraLanguage.Brazilian, "pt_BR" }, @@ -56,51 +60,26 @@ public static class MiraLocaleManager { MiraLanguage.SChinese, "zh_CN" }, { MiraLanguage.TChinese, "zh_TW" }, { MiraLanguage.Irish, "ga_IE" }, - { MiraLanguage.Polish, "pl_PL" }, // Custom - { MiraLanguage.Turkish, "tr_TR" }, // Custom - { MiraLanguage.Swedish, "sv_SE" }, // Custom - { MiraLanguage.Lithuanian, "lt_LT" }, // Custom - { MiraLanguage.Czech, "cs_CZ" }, // Custom - { MiraLanguage.LChinese, "lzh_CN" }, // Custom - { MiraLanguage.Greek, "el_GR" }, // Custom - { MiraLanguage.Arabic, "arb" }, // Custom - { MiraLanguage.Hebrew, "heb" }, // Custom + + // Custom + { MiraLanguage.Polish, "pl_PL" }, + { MiraLanguage.Turkish, "tr_TR" }, + { MiraLanguage.Swedish, "sv_SE" }, + { MiraLanguage.Lithuanian, "lt_LT" }, + { MiraLanguage.Czech, "cs_CZ" }, + { MiraLanguage.LChinese, "lzh_CN" }, + { MiraLanguage.Greek, "el_GR" }, + { MiraLanguage.Arabic, "arb" }, + { MiraLanguage.Hebrew, "heb" }, }; + private static readonly Dictionary ReverseLangLookup = + LangList.ToDictionary(x => x.Value, x => x.Key); /// /// Gets a dictionary mapping values to their standard language codes. /// - public static Dictionary LangCultureList { get; } = new() - { - // Vanilla - { MiraLanguage.English, "en-US" }, - { MiraLanguage.Latam, "es-419" }, - { MiraLanguage.Brazilian, "pt-BR" }, - { MiraLanguage.Portuguese, "pt-PT" }, - { MiraLanguage.Korean, "ko-KR" }, - { MiraLanguage.Russian, "ru-RU" }, - { MiraLanguage.Dutch, "nl-NL" }, - { MiraLanguage.Filipino, "fil-PH" }, - { MiraLanguage.French, "fr-FR" }, - { MiraLanguage.German, "de-DE" }, - { MiraLanguage.Italian, "it-IT" }, - { MiraLanguage.Japanese, "ja-JP" }, - { MiraLanguage.Spanish, "es-ES" }, - { MiraLanguage.SChinese, "zh-CN" }, - { MiraLanguage.TChinese, "zh-TW" }, - { MiraLanguage.Irish, "ga-IE" }, - - // Custom - { MiraLanguage.Polish, "pl-PL" }, - { MiraLanguage.Turkish, "tr-TR" }, - { MiraLanguage.Swedish, "sv-SE" }, - { MiraLanguage.Lithuanian, "lt-LT" }, - { MiraLanguage.Czech, "cs-CZ" }, - { MiraLanguage.LChinese, "lzh-CN" }, - { MiraLanguage.Greek, "el-GR" }, - { MiraLanguage.Arabic, "arb" }, - { MiraLanguage.Hebrew, "heb" }, - }; + public static Dictionary LangCultureList { get; } = + LangList.ToDictionary(x => x.Key, x => x.Value.Replace('_', '-')); /// /// Gets the current language from Among Us settings. @@ -111,7 +90,7 @@ public static class MiraLocaleManager { try { - var langName = AmongUs.Data.DataManager.Settings.Language.CurrentLanguage; + var langName = DataManager.Settings.Language.CurrentLanguage; return (MiraLanguage)langName; } catch @@ -121,40 +100,24 @@ public static class MiraLocaleManager } } - /// - /// Registers translations for a mod. - /// Call once per mod during plugin Load(). - /// - /// The mod GUID (e.g., "mira.example"). + /// [Obsolete("Pass typeof(YourPlugin).Assembly directly to Register for better performance.")] public static void Register(string modGuid) { - var callingAssembly = Assembly.GetCallingAssembly(); - LoadInternalStrings(callingAssembly, callingAssembly.GetName().Name!, modGuid); + LoadInternalStrings(Assembly.GetCallingAssembly(), modGuid); } - /// - /// Registers translations for a mod. - /// Call once per mod during plugin Load(). - /// - /// The mod GUID (e.g., "mira.example"). - /// The to load the strings from. + /// public static void Register(string modGuid, Assembly assembly) { - LoadInternalStrings(assembly, assembly.GetName().Name!, modGuid); + LoadInternalStrings(assembly, modGuid); } - /// - /// Registers translations for a mod. - /// Call once per mod during plugin Load(). - /// - /// The mod GUID (e.g., "mira.example"). - /// The mod's root namespace (e.g., "mira.api"). + /// [Obsolete("Pass typeof(YourPlugin).Assembly directly to Register for better performance.")] public static void Register(string modGuid, string internalName) { - var callingAssembly = Assembly.GetCallingAssembly(); - LoadInternalStrings(callingAssembly, internalName, modGuid); + LoadInternalStrings(Assembly.GetCallingAssembly(), internalName, modGuid); } /// @@ -169,15 +132,10 @@ public static class MiraLocaleManager LoadInternalStrings(assembly, internalName, modGuid); } - /// - /// Translates a key into the current language. - /// - /// The string id to find. - /// Fallback string to use if no translation is found. - /// A based on the key provided. + /// public static string Get(string key, string fallback = "") { - return Get(CurrentLanguage, key, fallback != string.Empty ? fallback : key); + return Get(CurrentLanguage, key, string.IsNullOrEmpty(fallback) ? key : fallback); } /// @@ -189,34 +147,30 @@ public static class MiraLocaleManager /// A based on the key provided. public static string Get(MiraLanguage language, string key, string fallback = "") { - if (Locale.TryGetValue(language, out var translations) && - translations.TryGetValue(key, out var translation)) - { - return translation; - } + var text = Locale.GetValueOrDefault(language)?.GetValueOrDefault(key); - if (Locale.TryGetValue(MiraLanguage.English, out var translationsEng) && - translationsEng.TryGetValue(key, out var translationEng)) - { - return translationEng; - } + if (language != MiraLanguage.English) + text ??= Locale.GetValueOrDefault(MiraLanguage.English)?.GetValueOrDefault(key); - return fallback; + return text ?? fallback; } - /// - /// Translates a key into the current language. - /// - /// The string id to find. - /// List of keys to change into other text. - /// Fallback string to use if no translation is found. - /// A based on the key provided. + /// public static string GetParsed( string key, Dictionary parseList, string fallback = "") { - return GetParsed(CurrentLanguage, key, parseList, fallback != string.Empty ? fallback : key); + return GetParsed(CurrentLanguage, key, parseList, string.IsNullOrEmpty(fallback) ? key : fallback); + } + + /// + public static string GetParsed( + string key, + (string, string)[] parseList, + string fallback = "") + { + return GetParsed(CurrentLanguage, key, parseList, string.IsNullOrEmpty(fallback) ? key : fallback); } /// @@ -233,24 +187,35 @@ public static class MiraLocaleManager Dictionary parseList, string fallback = "") { - var text = fallback; + var text = Get(language, key, fallback); - if (Locale.TryGetValue(MiraLanguage.English, out var translationsEng) && - translationsEng.TryGetValue(key, out var translationEng)) + foreach (var (toReplace, value) in parseList) { - text = translationEng; + text = text.Replace(toReplace, value); } - if (language is not MiraLanguage.English && - Locale.TryGetValue(language, out var translations) && - translations.TryGetValue(key, out var translation)) - { - text = translation; - } + return text; + } - foreach (var tmpText in parseList.Where(x => text.Contains(x.Key))) + /// + /// Translates a key into the current language. + /// + /// The specific language to prioritize. + /// The string id to find. + /// List of keys to change into other text. + /// Fallback string to use if no translation is found. + /// A based on the key provided. + public static string GetParsed( + MiraLanguage language, + string key, + (string, string)[] parseList, + string fallback = "") + { + var text = Get(language, key, fallback); + + foreach (var (toReplace, value) in parseList) { - text = text.Replace(tmpText.Key, tmpText.Value); + text = text.Replace(toReplace, value); } return text; @@ -268,12 +233,7 @@ public static class MiraLocaleManager return idPart.StartsWith('#') ? idPart[1..] : $"{modId}.{idPart}.{suffix}"; } - /// - /// Builds a formatted translation ID string using a mod ID and a specific ID part. - /// - /// The mod GUID. - /// The core part of the ID. If it starts with '#', the character is stripped. - /// A formatted translation ID . + /// public static string BuildTranslationId(string modId, string idPart) { return idPart.StartsWith('#') ? idPart[1..] : $"{modId}.{idPart}"; @@ -329,16 +289,16 @@ public static class MiraLocaleManager { var fileName = Path.GetFileNameWithoutExtension(filePath); - var lang = LangList.ContainsValue(fileName) - ? LangList.First(x => x.Value == fileName).Key - : (MiraLanguage)(-1); - if ((int)lang == -1) continue; + if (!ReverseLangLookup.TryGetValue(fileName, out var lang)) + { + continue; + } try { Locale.TryAdd(lang, []); - var xmlContent = File.ReadAllText(filePath); - ParseXmlFile(xmlContent, lang, false); + using var fileStream = File.OpenRead(filePath); + ParseXmlFile(fileStream, lang, false); } catch (Exception e) { @@ -347,6 +307,11 @@ public static class MiraLocaleManager } } + private static void LoadInternalStrings(Assembly assembly, string modGuid) + { + LoadInternalStrings(assembly, assembly.GetName().Name!, modGuid); + } + private static void LoadInternalStrings(Assembly assembly, string internalName, string modGuid) { var resourcePrefix = $"{internalName}.Resources.Locale."; @@ -354,27 +319,26 @@ public static class MiraLocaleManager RegisteredModIds.Add(modGuid); var atLeastOneLoaded = false; - foreach (var locale in LangList) + + foreach (var (lang, name) in LangList) { - using var resourceStream = - assembly.GetManifestResourceStream(resourcePrefix + locale.Value + ".xml"); + using var resourceStream = assembly.GetManifestResourceStream(resourcePrefix + name + ".xml"); + if (resourceStream == null) { // Silently skipped continue; } - using StreamReader reader = new(resourceStream); - var xmlContent = reader.ReadToEnd(); try { - Locale.TryAdd(locale.Key, []); - ParseXmlFile(xmlContent, locale.Key, true); + Locale.TryAdd(lang, []); + ParseXmlFile(resourceStream, lang, true); atLeastOneLoaded = true; } catch (Exception e) { - Error($"Failed to load translation {resourcePrefix}{locale.Value}: {e.Message}"); + Error($"Failed to load translation {resourcePrefix}{name}: {e.Message}"); } } @@ -391,52 +355,96 @@ public static class MiraLocaleManager /// The language that the xml file corresponds to. /// Flag that indicates if the xml being parsed is internal or not. public static void ParseXmlFile(string xmlContent, MiraLanguage language, bool loadingInternal) + { + using var stringReader = new StringReader(xmlContent); + using var xmlReader = XmlReader.Create(stringReader); + ParseXml(xmlReader, language, loadingInternal); + } + + /// + /// Parses the provided xml stream into translation keys and values and registers them to the locale manager. + /// + /// The stream to the xml content. + /// The language that the xml file corresponds to. + /// Flag that indicates if the xml being parsed is internal or not. + public static void ParseXmlFile(Stream xmlStream, MiraLanguage language, bool loadingInternal) + { + using var reader = XmlReader.Create(xmlStream); + ParseXml(reader, language, loadingInternal); + } + + private static void ParseXml(XmlReader reader, MiraLanguage language, bool loadingInternal) { var dict = Locale[language]; - XmlDocument xmlDoc = new(); + var total = 0; + + var pendingRefs = new Dictionary(); + try { - xmlDoc.LoadXml(xmlContent); - var stringNodes = xmlDoc.SelectNodes("/resources/string"); - - if (stringNodes == null) + while (reader.ReadToFollowing("string")) { - return; + var name = reader.GetAttribute("name"); + + if (string.IsNullOrEmpty(name)) + continue; + + if (loadingInternal && dict.ContainsKey(name)) + { + Error($"String for \"{name}\" in {language} was overwritten by a duplicate!"); + } + + var value = reader.ReadElementContentAsString(); + + if (value.StartsWith(RefPrefix, StringComparison.Ordinal)) + { + pendingRefs[name] = value[RefPrefix.Length..]; + } + else + { + value = value.Replace('[', '<') + .Replace(']', '>') + .Replace("", "\n") + .Replace("", "&"); + + dict[name] = value; + total++; + } } - var total = 0; - - foreach (XmlNode node in stringNodes) + foreach (var unresolved in pendingRefs) { - if (node.Attributes?["name"] == null) + var originalKey = unresolved.Key; + var currentTarget = unresolved.Value; + var depth = 0; + var resolved = false; + + while (depth < MaxDepth) { - continue; + if (dict.TryGetValue(currentTarget, out var resolvedValue)) + { + dict[originalKey] = resolvedValue; + total++; + resolved = true; + break; + } + + if (pendingRefs.TryGetValue(currentTarget, out var nextTarget)) + { + currentTarget = nextTarget; + depth++; + } + else + { + Error($"Translation reference '{unresolved.Value}' for '{originalKey}' not found."); + break; + } } - var name = node.Attributes["name"]!.Value; - var value = node.InnerText; - - if (string.IsNullOrEmpty(name)) continue; - - if (value.Contains('[')) + if (!resolved && depth >= MaxDepth) { - value = value.Replace('[', '<'); + Error($"Circular translation reference or max depth exceeded for '{originalKey}'."); } - - if (value.Contains(']')) - { - value = value.Replace(']', '>'); - } - - value = value.Replace("", "\n").Replace("", "&"); - - if (loadingInternal && Locale[language].ContainsKey(name)) - { - Error($"String for \"{name}\" in {language} was overwritten by duplicate!"); - } - - dict[name] = value; - total++; } Info($"Loaded {language.ToDisplayString()} translation with ({total} keys)"); diff --git a/MiraAPI/Utilities/Assets/LoadableAsset.cs b/MiraAPI/Utilities/Assets/LoadableAsset.cs index dea91e71..061cef5d 100644 --- a/MiraAPI/Utilities/Assets/LoadableAsset.cs +++ b/MiraAPI/Utilities/Assets/LoadableAsset.cs @@ -26,9 +26,9 @@ public abstract class LoadableAsset /// Converts the into its by loading the asset. /// /// The to get the asset from. - public static implicit operator T(LoadableAsset loadable) + public static implicit operator T(LoadableAsset? loadable) { - return loadable.LoadAsset(); + return loadable?.LoadAsset()!; } /// diff --git a/MiraAPI/Utilities/StateMachineWrapper.cs b/MiraAPI/Utilities/StateMachineWrapper.cs index 298feb19..120155f3 100644 --- a/MiraAPI/Utilities/StateMachineWrapper.cs +++ b/MiraAPI/Utilities/StateMachineWrapper.cs @@ -96,4 +96,10 @@ public class StateMachineWrapper _propertyCache[parameterName] = property; return (TField)property.GetValue(_stateMachine)!; } + + /// + /// Implicitly converts a state machine wrapper into its instance. + /// + /// The wrapper. + public static implicit operator T(StateMachineWrapper wrapper) => wrapper.Instance; }