From 1aaaf050ad16693b65b29bc6b8bb3611de289283 Mon Sep 17 00:00:00 2001 From: Az <56699741+AlchlcDvl@users.noreply.github.com> Date: Sat, 7 Nov 2026 03:56:47 -0500 Subject: [PATCH] reorganise plugin loading code + debug mode stuff and also some minor project cleanup --- MiraAPI/Colors/PaletteManager.cs | 60 +++- MiraAPI/Events/MiraEventManager.cs | 22 ++ MiraAPI/GameModes/CustomGameModeManager.cs | 5 +- MiraAPI/GameOptions/ModdedOptionsManager.cs | 85 +++--- MiraAPI/Hud/CustomButtonManager.cs | 1 + MiraAPI/Keybinds/KeybindManager.cs | 62 +++- .../LocalSettingsButtonAttribute.cs | 4 +- MiraAPI/LocalSettings/LocalSettingsManager.cs | 66 ++++- .../MeetingAbilities/MeetingButtonManager.cs | 4 +- MiraAPI/MiraAPI.csproj | 7 - MiraAPI/MiraApiPlugin.cs | 3 + MiraAPI/Modifiers/ModifierManager.cs | 6 +- MiraAPI/PluginLoading/IMiraPlugin.cs | 5 + MiraAPI/PluginLoading/MiraPluginInfo.cs | 14 +- MiraAPI/PluginLoading/MiraPluginManager.cs | 274 +++--------------- MiraAPI/Roles/CustomRoleManager.cs | 22 +- 16 files changed, 335 insertions(+), 305 deletions(-) diff --git a/MiraAPI/Colors/PaletteManager.cs b/MiraAPI/Colors/PaletteManager.cs index b05c30fd..fb0106a8 100644 --- a/MiraAPI/Colors/PaletteManager.cs +++ b/MiraAPI/Colors/PaletteManager.cs @@ -1,7 +1,11 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using HarmonyLib; +using MiraAPI.PluginLoading; +using MiraAPI.Translation; +using MiraAPI.Utilities; using UnityEngine; namespace MiraAPI.Colors; @@ -16,9 +20,8 @@ public static class PaletteManager /// public static CustomColor[] RegisteredColors => [.. CustomColors]; - internal static readonly List CustomColors = []; - internal static readonly HashSet VariableColorNames = []; - + private static readonly List CustomColors = []; + private static readonly HashSet VariableColorNames = []; private static readonly CustomColorBrightness[] ColorBrightnessMap = [ CustomColorBrightness.Darker, // Red @@ -43,6 +46,55 @@ public static class PaletteManager private static int originalLength; + internal static bool RegisterColors(Type type, MiraPluginInfo miraPlugin) + { + if (!type.TryGetCustomAttribute(out var attribute)) + { + return false; + } + + if (!type.IsStatic()) + { + Error($"Color class {type.Name} must be static."); + return false; + } + + foreach (var property in type.GetProperties(MiraPluginManager.DeclaredStaticMembers)) + { + if (!property.PropertyType.IsAssignableTo(typeof(CustomColor))) + { + continue; + } + + if (property.GetValue(null) is not CustomColor color) + { + Error($"Color property {property.Name} in {type.Name} is not a CustomColor."); + continue; + } + + if (!string.IsNullOrEmpty(color.RawId) && !string.IsNullOrEmpty(attribute.IdPrefix)) + { + color.Name = MiraLocaleManager.GetOrCreateLocaleString(attribute.IdPrefix + color.RawId); + } + + CustomColors.Add(color); + + if (color is VariableColor) + VariableColorNames.Add(color.Name); + } + + if (!miraPlugin.DebugMode) + return true; + + foreach (var field in type.GetFields(MiraPluginManager.DeclaredStaticMembers) + .Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(CustomColor)))) + { + Error($"{field.Name} is a field, not a property. Use properties for colors."); + } + + return true; + } + internal static void RegisterAllColors() { originalLength = Palette.PlayerColors.Length; diff --git a/MiraAPI/Events/MiraEventManager.cs b/MiraAPI/Events/MiraEventManager.cs index a8b34f16..1f4cf74c 100644 --- a/MiraAPI/Events/MiraEventManager.cs +++ b/MiraAPI/Events/MiraEventManager.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; using System.Reflection; +using MiraAPI.PluginLoading; +using MiraAPI.Utilities; namespace MiraAPI.Events; @@ -153,4 +155,24 @@ public static class MiraEventManager return true; } + + internal static void RegisterEvents(Type type) + { + foreach (var method in type.GetMethods(MiraPluginManager.DeclaredStaticMembers)) + { + if (!method.TryGetCustomAttribute(out var eventAttribute)) + continue; + + var parameters = method.GetParameters(); + + if (parameters.Length != 1 || !parameters[0].ParameterType.IsSubclassOf(typeof(MiraEvent))) + { + Error($"Invalid event registration method {method.Name} in {type.Name}"); + continue; + } + + var paramType = parameters[0].ParameterType; + RegisterEventHandler(paramType, method, eventAttribute.Priority); + } + } } diff --git a/MiraAPI/GameModes/CustomGameModeManager.cs b/MiraAPI/GameModes/CustomGameModeManager.cs index acb0f51b..8a74f4f1 100644 --- a/MiraAPI/GameModes/CustomGameModeManager.cs +++ b/MiraAPI/GameModes/CustomGameModeManager.cs @@ -29,13 +29,10 @@ public static class CustomGameModeManager { if (!typeof(AbstractGameMode).IsAssignableFrom(gameModeType)) { - Warning($"{gameModeType.Name} does not inherit CustomGameMode!"); return false; } - var instance = Activator.CreateInstance(gameModeType); - - if (instance is not AbstractGameMode mode) + if (Activator.CreateInstance(gameModeType) is not AbstractGameMode mode) { Error($"Failed to create instance of {gameModeType.Name}"); return false; diff --git a/MiraAPI/GameOptions/ModdedOptionsManager.cs b/MiraAPI/GameOptions/ModdedOptionsManager.cs index 677f43ee..e3c1446f 100644 --- a/MiraAPI/GameOptions/ModdedOptionsManager.cs +++ b/MiraAPI/GameOptions/ModdedOptionsManager.cs @@ -66,25 +66,17 @@ public static class ModdedOptionsManager notif.SettingsChangeMessageLogic(key, item, playSound); } - internal static bool RegisterGroup(Type type) - { - if (TypeToGroup.ContainsKey(type)) - { - Error($"Group {type.Name} already exists."); - return false; - } - - if (Activator.CreateInstance(type) is not AbstractOptionGroup group) - { - return false; - } - - RegisterGroupInternal(group, type); - return true; - } - + [SuppressMessage( + "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) { + if (!type.IsAssignableTo(typeof(AbstractOptionGroup))) + { + return false; + } + if (TypeToGroup.ContainsKey(type)) { Error($"Group {type.Name} already exists."); @@ -110,24 +102,49 @@ public static class ModdedOptionsManager pluginInfo.InternalOptionGroups.Add(group); - RegisterGroupInternal(group, type); - return true; - } - - [SuppressMessage( - "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.")] - private static void RegisterGroupInternal(AbstractOptionGroup group, Type type) - { Groups.Add(group); TypeToGroup.Add(type, group); typeof(OptionGroupSingleton<>).MakeGenericType(type) .GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! .SetValue(null, group); + + foreach (var property in type.GetProperties(MiraPluginManager.DeclaredInstanceMembers)) + { + if (property.PropertyType.IsAssignableTo(typeof(IModdedOption))) + { + RegisterPropertyOption(type, property, pluginInfo); + continue; + } + + if (property.PropertyType.IsAssignableTo(typeof(IModdedOptionList))) + { + RegisterPropertyOptionList(type, property, pluginInfo); + continue; + } + + if (property.TryGetCustomAttribute(out var attribute)) + { + RegisterAttributeOption(type, attribute, property, pluginInfo); + continue; + } + + if (property.TryGetCustomAttribute(out var listAttr)) + { + RegisterAttributeOptionList(type, listAttr, property, pluginInfo); + } + } + + foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers) + .Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) + && (f.FieldType.IsAssignableTo(typeof(IModdedOption)) || f.FieldType.IsAssignableTo(typeof(IModdedOptionList))))) + { + Error($"{field.Name} is a field, not a property. Use properties for options."); + } + + return true; } - internal static void RegisterPropertyOption(Type type, PropertyInfo property, MiraPluginInfo pluginInfo) + private static void RegisterPropertyOption(Type type, PropertyInfo property, MiraPluginInfo pluginInfo) { if (!TypeToGroup.TryGetValue(type, out var group)) { @@ -144,7 +161,7 @@ public static class ModdedOptionsManager RegisterOption(option, group, property.Name, pluginInfo); } - internal static void RegisterAttributeOption( + private static void RegisterAttributeOption( Type type, ModdedOptionAttribute attribute, PropertyInfo property, @@ -209,7 +226,7 @@ public static class ModdedOptionsManager RegisterOption(option, group, property.Name, pluginInfo); } - internal static void RegisterPropertyOptionList(Type type, PropertyInfo property, MiraPluginInfo pluginInfo) + private static void RegisterPropertyOptionList(Type type, PropertyInfo property, MiraPluginInfo pluginInfo) { if (!TypeToGroup.TryGetValue(type, out var group)) { @@ -231,7 +248,7 @@ public static class ModdedOptionsManager } } - internal static void RegisterAttributeOptionList( + private static void RegisterAttributeOptionList( Type type, ModdedOptionListAttribute attribute, PropertyInfo property, @@ -342,7 +359,7 @@ public static class ModdedOptionsManager } } - internal static void RegisterOption( + private static void RegisterOption( IModdedOption option, AbstractOptionGroup group, string propertyName, @@ -363,9 +380,9 @@ public static class ModdedOptionsManager { var chunks = ModdedOptions.Values.Select(option => option.GetNetData()).ChunkNetData(1000); - while (chunks.Count > 0) + while (chunks.TryDequeue(out var netData)) { - Rpc.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, chunks.Dequeue())); + Rpc.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, netData)); } } diff --git a/MiraAPI/Hud/CustomButtonManager.cs b/MiraAPI/Hud/CustomButtonManager.cs index a532f8e0..1e8656ed 100644 --- a/MiraAPI/Hud/CustomButtonManager.cs +++ b/MiraAPI/Hud/CustomButtonManager.cs @@ -45,6 +45,7 @@ public static class CustomButtonManager CustomButtons.Add(button); pluginInfo.InternalButtons.Add(button); + typeof(CustomButtonSingleton<>).MakeGenericType(buttonType) .GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Suppression message refers to this .SetValue(null, button); diff --git a/MiraAPI/Keybinds/KeybindManager.cs b/MiraAPI/Keybinds/KeybindManager.cs index b3097e14..057b3243 100644 --- a/MiraAPI/Keybinds/KeybindManager.cs +++ b/MiraAPI/Keybinds/KeybindManager.cs @@ -2,6 +2,8 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; +using MiraAPI.PluginLoading; +using MiraAPI.Translation; using MiraAPI.Utilities; using Rewired; @@ -76,6 +78,48 @@ public static class KeybindManager } } + internal static bool RegisterKeybinds(Type type, IMiraPlugin plugin) + { + if (!type.IsDefined()) + { + return false; + } + + if (!type.IsStatic()) + { + Error($"Keybinds class {type.Name} must be static."); + return false; + } + + foreach (var property in type.GetProperties(MiraPluginManager.DeclaredStaticMembers)) + { + if (property.PropertyType != typeof(MiraKeybind)) + { + continue; + } + + if (property.GetValue(null) is not MiraKeybind keybind) + { + Error($"Keybind property {property.Name} in {type.Name} is not a MiraKeybind."); + continue; + } + + Keybinds.Add(keybind); + keybind.SourcePluginName = plugin.OptionsTitleText.Translate(); + } + + if (!plugin.DebugMode) + return true; + + foreach (var field in type.GetFields(MiraPluginManager.DeclaredStaticMembers) + .Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(MiraKeybind)))) + { + Error($"{field.Name} is a field, not a property. Use properties for keybinds."); + } + + return true; + } + /// /// Returns all conflicts where s use the same key. /// @@ -89,16 +133,18 @@ public static class KeybindManager if (key == KeyboardKeyCode.None) continue; var all = GetKeybindsForKey(key, true); - if (all.Length > 1) + if (all.Length <= 1) { - if (!conflicts.TryGetValue(key, out var group)) - { - group = []; - conflicts.Add(key, group); - } - - if (!group.Contains(keybind)) group.Add(keybind); + continue; } + + if (!conflicts.TryGetValue(key, out var group)) + { + group = []; + conflicts.Add(key, group); + } + + if (!group.Contains(keybind)) group.Add(keybind); } return conflicts; diff --git a/MiraAPI/LocalSettings/Attributes/LocalSettingsButtonAttribute.cs b/MiraAPI/LocalSettings/Attributes/LocalSettingsButtonAttribute.cs index 83a39556..8c0eb3d4 100644 --- a/MiraAPI/LocalSettings/Attributes/LocalSettingsButtonAttribute.cs +++ b/MiraAPI/LocalSettings/Attributes/LocalSettingsButtonAttribute.cs @@ -6,6 +6,4 @@ namespace MiraAPI.LocalSettings.Attributes; /// Attribute for local setting buttons. /// [AttributeUsage(AttributeTargets.Property)] -public class LocalSettingsButtonAttribute : Attribute -{ -} +public class LocalSettingsButtonAttribute : Attribute; diff --git a/MiraAPI/LocalSettings/LocalSettingsManager.cs b/MiraAPI/LocalSettings/LocalSettingsManager.cs index 4907d8c1..44d77681 100644 --- a/MiraAPI/LocalSettings/LocalSettingsManager.cs +++ b/MiraAPI/LocalSettings/LocalSettingsManager.cs @@ -1,8 +1,13 @@ using System; using System.Collections.Generic; 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; namespace MiraAPI.LocalSettings; @@ -19,9 +24,9 @@ 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 RegisterTab(Type type, BasePlugin pluginInfo) + internal static bool RegisterLocalTabs(Type type, BasePlugin pluginInfo) { - if (Activator.CreateInstance(type, pluginInfo.Config) is not LocalSettingsTab tab) + if (!type.IsAssignableTo(typeof(LocalSettingsTab))) { return false; } @@ -32,17 +37,64 @@ public static class LocalSettingsManager return false; } - Tabs.Add(tab); - if (tab.ShouldCreateButton) + if (Activator.CreateInstance(type, pluginInfo.Config) is not LocalSettingsTab tabInstance) { - AvailableTabs.Add(tab); + return false; } - TypeToTab.Add(type, tab); + Tabs.Add(tabInstance); + + if (tabInstance.ShouldCreateButton) + { + AvailableTabs.Add(tabInstance); + } + + TypeToTab.Add(type, tabInstance); typeof(LocalSettingsTabSingleton<>).MakeGenericType(type) .GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Suppression message refers to this - .SetValue(null, tab); + .SetValue(null, tabInstance); + + foreach (var property in type.GetProperties(MiraPluginManager.DeclaredInstanceMembers)) + { + if (property.IsDefined()) + { + if (property.GetValue(tabInstance) is not LocalSettingsButton button) + { + Error($"Option property {property.Name} in {type.Name} has to be a settings button."); + continue; + } + + button.Tab = tabInstance; + tabInstance.Buttons.Add(button); + continue; + } + + if (!property.TryGetCustomAttribute(out var attribute)) + { + continue; + } + + if (!typeof(ConfigEntryBase).IsAssignableFrom(property.PropertyType)) + { + continue; + } + + if (property.GetValue(tabInstance) is not ConfigEntryBase configEntry) + { + Error($"Option property {property.Name} in {type.Name} has to be a config entry."); + continue; + } + + attribute.CreateSetting(type, configEntry); + } + + foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers) + .Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) + && (f.FieldType.IsAssignableTo(typeof(ConfigEntryBase)) || f.FieldType.IsAssignableTo(typeof(LocalSettingsButton))))) + { + Error($"{field.Name} is a field, not a property. Use properties for local settings or buttons."); + } return true; } diff --git a/MiraAPI/MeetingAbilities/MeetingButtonManager.cs b/MiraAPI/MeetingAbilities/MeetingButtonManager.cs index 5ca75d85..92348f5d 100644 --- a/MiraAPI/MeetingAbilities/MeetingButtonManager.cs +++ b/MiraAPI/MeetingAbilities/MeetingButtonManager.cs @@ -13,12 +13,12 @@ namespace MiraAPI.MeetingAbilities; public static class MeetingButtonManager { /// - /// Gets a list if==of all registered . + /// Gets a list of all registered . /// public static List TargetedButtons { get; internal set; } = []; /// - /// Gets a list if==of all registered . + /// Gets a list of all registered . /// public static List UntargetedButtons { get; internal set; } = []; diff --git a/MiraAPI/MiraAPI.csproj b/MiraAPI/MiraAPI.csproj index b6bcb5d2..2d47477a 100644 --- a/MiraAPI/MiraAPI.csproj +++ b/MiraAPI/MiraAPI.csproj @@ -5,7 +5,6 @@ AllOfUs.MiraAPI true true - IDE0031;IDE0032 @@ -16,11 +15,5 @@ - - - - - - diff --git a/MiraAPI/MiraApiPlugin.cs b/MiraAPI/MiraApiPlugin.cs index dc926b2e..7e744781 100644 --- a/MiraAPI/MiraApiPlugin.cs +++ b/MiraAPI/MiraApiPlugin.cs @@ -41,6 +41,9 @@ public partial class MiraApiPlugin : BasePlugin, IMiraPlugin /// public bool DisplayOnOptionsMenu => false; + /// + public bool DebugMode => IsDevBuild; + /// /// Gets a value indicating whether the current device is running Starlight (on mobile). /// diff --git a/MiraAPI/Modifiers/ModifierManager.cs b/MiraAPI/Modifiers/ModifierManager.cs index 935c82e5..f12d2172 100644 --- a/MiraAPI/Modifiers/ModifierManager.cs +++ b/MiraAPI/Modifiers/ModifierManager.cs @@ -72,7 +72,9 @@ public static class ModifierManager TypeToIdModifierMap.Add(modifierType, _nextTypeId); BaseModifier modifier; - if (modifierType.GetConstructor(Type.EmptyTypes) != null) + var ctor = modifierType.GetConstructor(Type.EmptyTypes); + + if (ctor != null) { modifier = (BaseModifier)Activator.CreateInstance(modifierType)!; } @@ -90,7 +92,7 @@ public static class ModifierManager return true; } - if (modifierType.GetConstructor(Type.EmptyTypes) == null) + if (ctor == null) { Error($"Game Modifier {modifierType.FullName} does not have a parameterless constructor!"); return false; diff --git a/MiraAPI/PluginLoading/IMiraPlugin.cs b/MiraAPI/PluginLoading/IMiraPlugin.cs index c77a97e0..f1f9fc30 100644 --- a/MiraAPI/PluginLoading/IMiraPlugin.cs +++ b/MiraAPI/PluginLoading/IMiraPlugin.cs @@ -58,6 +58,11 @@ public interface IMiraPlugin /// string CustomOptionMenuTwoDescription => "Apply game settings for this mod!"; + /// + /// Gets a value indicating whether the plugin is in debug mode. + /// + bool DebugMode => false; + /// /// Gets the for the plugin. /// diff --git a/MiraAPI/PluginLoading/MiraPluginInfo.cs b/MiraAPI/PluginLoading/MiraPluginInfo.cs index ca7812cd..4bbfe363 100644 --- a/MiraAPI/PluginLoading/MiraPluginInfo.cs +++ b/MiraAPI/PluginLoading/MiraPluginInfo.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Reflection; using BepInEx; using BepInEx.Configuration; using MiraAPI.GameModes; @@ -17,12 +18,13 @@ namespace MiraAPI.PluginLoading; /// public class MiraPluginInfo { - internal MiraPluginInfo(IMiraPlugin miraPlugin, PluginInfo info) + internal MiraPluginInfo(IMiraPlugin miraPlugin, PluginInfo info, Assembly assembly) { MiraPlugin = miraPlugin; PluginConfig = miraPlugin.GetConfigFile(); PluginInfo = info; PluginId = info.Metadata.GUID; + PluginAssembly = assembly; } /// @@ -45,6 +47,16 @@ public class MiraPluginInfo /// public ConfigFile PluginConfig { get; } + /// + /// Gets the plugin's . + /// + public Assembly PluginAssembly { get; } + + /// + /// Gets a value indicating whether the plugin is in debug mode. + /// + public bool DebugMode => MiraPlugin.DebugMode; + /// /// Gets a of this 's s. This is not safe for s with constructors. /// diff --git a/MiraAPI/PluginLoading/MiraPluginManager.cs b/MiraAPI/PluginLoading/MiraPluginManager.cs index e0b7ff38..d0bcaa14 100644 --- a/MiraAPI/PluginLoading/MiraPluginManager.cs +++ b/MiraAPI/PluginLoading/MiraPluginManager.cs @@ -9,24 +9,19 @@ using System.Runtime.CompilerServices; using BepInEx; using BepInEx.Configuration; using BepInEx.Unity.IL2CPP; -using HarmonyLib; using MiraAPI.Colors; using MiraAPI.Events; using MiraAPI.GameEnd; using MiraAPI.GameModes; using MiraAPI.GameOptions; -using MiraAPI.GameOptions.Attributes; using MiraAPI.Hud; using MiraAPI.Keybinds; using MiraAPI.LocalSettings; -using MiraAPI.LocalSettings.Attributes; using MiraAPI.MeetingAbilities; using MiraAPI.Modifiers; using MiraAPI.Presets; using MiraAPI.Roles; -using MiraAPI.Translation; using MiraAPI.Utilities; -using Reactor.Networking; namespace MiraAPI.PluginLoading; @@ -40,10 +35,10 @@ public sealed class MiraPluginManager { } - private const BindingFlags DeclaredInstanceMembers = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; - private const BindingFlags DeclaredStaticMembers = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + internal const BindingFlags DeclaredInstanceMembers = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + internal const BindingFlags DeclaredStaticMembers = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; - private readonly Dictionary _registeredPlugins = []; + private readonly Dictionary _registeredPlugins = []; internal MiraPluginInfo[] RegisteredPlugins { get; private set; } = []; internal MiraPluginInfo[] RegisteredPluginsWithOptions { get; private set; } = []; @@ -104,7 +99,7 @@ public sealed class MiraPluginManager private MiraPluginInfo RegisterPlugin(Assembly assembly, IMiraPlugin plugin, PluginInfo pluginInfo, BasePlugin basePlugin, bool isMira) { - var info = new MiraPluginInfo(plugin, pluginInfo); + var info = new MiraPluginInfo(plugin, pluginInfo, assembly); var roles = new List(); var oldConfigSetting = info.PluginConfig.SaveOnConfigSet; @@ -117,7 +112,7 @@ public sealed class MiraPluginManager info.InternalOptionGroups.Sort((x, y) => x.GroupPriority.CompareTo(y.GroupPriority)); QueuedRoleRegistrations.Add(info, roles); - _registeredPlugins.Add(assembly, info); + _registeredPlugins.Add(pluginInfo.Metadata.GUID, info); info.SavePublicCollections(); PresetManager.CreateDefaultPreset(info); @@ -126,12 +121,13 @@ public sealed class MiraPluginManager return info; } - private static bool IsAutoPropertyBackingField(FieldInfo field) + internal static bool IsAutoPropertyBackingField(FieldInfo field) { return field.IsDefined(false) && - field.Name.Contains(">k__BackingField", StringComparison.Ordinal); + 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) { foreach (var type in assembly.GetTypes()) @@ -141,21 +137,30 @@ public sealed class MiraPluginManager RegisterEvents(type); - if (RegisterModifier(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; @@ -164,37 +169,18 @@ public sealed class MiraPluginManager if (RegisterTargetedMeetingAbility(type, info)) continue; - - if (RegisterGameModeAttribute(type, info)) - continue; - - if (!RegisterColorClasses(type)) - RegisterKeybinds(type, plugin); } } private static void RegisterEvents(Type type) { - foreach (var method in AccessTools.GetDeclaredMethods(type)) + try { - if (!method.TryGetCustomAttribute(out var eventAttribute)) - continue; - - if (!method.IsStatic) - { - Error($"Event method {method.Name} in {type.Name} must be static."); - continue; - } - - var parameters = method.GetParameters(); - if (parameters.Length != 1 || !parameters[0].ParameterType.IsSubclassOf(typeof(MiraEvent))) - { - Error($"Invalid event registration method {method.Name} in {type.Name}"); - continue; - } - - var paramType = parameters[0].ParameterType; - MiraEventManager.RegisterEventHandler(paramType, method, eventAttribute.Priority); + MiraEventManager.RegisterEvents(type); + } + catch (Exception e) + { + Error($"Failed to register events in {type.Name}: {e}"); } } @@ -205,7 +191,7 @@ public sealed class MiraPluginManager /// A . public static MiraPluginInfo? GetPluginByGuid(string pluginId) { - return Instance._registeredPlugins.Values.FirstOrDefault(plugin => plugin.PluginId == pluginId); + return Instance._registeredPlugins.GetValueOrDefault(pluginId); } private static bool RegisterGameOver(Type type) @@ -225,54 +211,7 @@ public sealed class MiraPluginManager { try { - if (!type.IsAssignableTo(typeof(AbstractOptionGroup))) - { - return false; - } - - if (!ModdedOptionsManager.RegisterGroup(type, pluginInfo)) - { - return false; - } - - foreach (var property in type.GetProperties(DeclaredInstanceMembers)) - { - if (property.IsDefined()) - continue; - - if (property.PropertyType.IsAssignableTo(typeof(IModdedOption))) - { - ModdedOptionsManager.RegisterPropertyOption(type, property, pluginInfo); - continue; - } - - if (property.PropertyType.IsAssignableTo(typeof(IModdedOptionList))) - { - ModdedOptionsManager.RegisterPropertyOptionList(type, property, pluginInfo); - continue; - } - - var attribute = property.GetCustomAttribute(); - if (attribute != null) - { - ModdedOptionsManager.RegisterAttributeOption(type, attribute, property, pluginInfo); - continue; - } - - var listAttr = property.GetCustomAttribute(); - if (listAttr != null) - { - ModdedOptionsManager.RegisterAttributeOptionList(type, listAttr, property, pluginInfo); - } - } - - foreach (var field in type.GetFields(DeclaredInstanceMembers) - .Where(f => !IsAutoPropertyBackingField(f) && (f.FieldType.IsAssignableTo(typeof(IModdedOption)) || f.FieldType.IsAssignableTo(typeof(IModdedOptionList))))) - { - Error($"{field.Name} is a field, not a property. Use properties for options."); - } - - return true; + return ModdedOptionsManager.RegisterGroup(type, pluginInfo); } catch (Exception e) { @@ -286,19 +225,7 @@ public sealed class MiraPluginManager { try { - if (!(typeof(RoleBehaviour).IsAssignableFrom(type) && typeof(ICustomRole).IsAssignableFrom(type))) - { - return false; - } - - if (!ModList.GetById(pluginInfo.PluginId).IsRequiredOnAllClients) - { - Error("Custom roles are only supported on all clients."); - return false; - } - - roles.Add(type); - return true; + return CustomRoleManager.RegisterRole(type, pluginInfo, roles); } catch (Exception e) { @@ -308,51 +235,11 @@ public sealed class MiraPluginManager return false; } - private static bool RegisterColorClasses(Type type) + private static bool RegisterColors(Type type, MiraPluginInfo miraPlugin) { try { - if (!type.TryGetCustomAttribute(out var attribute)) - { - return false; - } - - if (!type.IsStatic()) - { - Error($"Color class {type.Name} must be static."); - return false; - } - - foreach (var property in type.GetProperties(DeclaredStaticMembers)) - { - if (!property.PropertyType.IsAssignableTo(typeof(CustomColor))) - { - continue; - } - - if (property.GetValue(null) is not CustomColor color) - { - Error($"Color property {property.Name} in {type.Name} is not a CustomColor."); - continue; - } - - if (!string.IsNullOrEmpty(color.RawId) && !string.IsNullOrEmpty(attribute.IdPrefix)) - { - color.Name = MiraLocaleManager.GetOrCreateLocaleString(attribute.IdPrefix + color.RawId); - } - - PaletteManager.CustomColors.Add(color); - - if (color is VariableColor) - PaletteManager.VariableColorNames.Add(color.Name); - } - - foreach (var field in type.GetFields(DeclaredStaticMembers).Where(f => !IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(CustomColor)))) - { - Error($"{field.Name} is a field, not a property. Use properties for colors."); - } - - return true; + return PaletteManager.RegisterColors(type, miraPlugin); } catch (Exception e) { @@ -371,8 +258,9 @@ public sealed class MiraPluginManager catch (Exception e) { Error($"Failed to register modifier {type.Name}: {e}"); - return false; } + + return false; } private static bool RegisterButton(Type type, MiraPluginInfo pluginInfo) @@ -393,8 +281,7 @@ public sealed class MiraPluginManager { try { - if (typeof(AbstractGameMode).IsAssignableFrom(type)) - return CustomGameModeManager.RegisterGameMode(type, pluginInfo); + return CustomGameModeManager.RegisterGameMode(type, pluginInfo); } catch (Exception e) { @@ -408,55 +295,7 @@ public sealed class MiraPluginManager { try { - if (!type.IsAssignableTo(typeof(LocalSettingsTab))) - { - return false; - } - - if (!LocalSettingsManager.RegisterTab(type, pluginInfo)) - { - return false; - } - - if (!LocalSettingsManager.TypeToTab.TryGetValue(type, out var tabInstance)) - { - return false; - } - - foreach (var property in type.GetProperties(DeclaredInstanceMembers)) - { - if (property.IsDefined() && - property.PropertyType.IsAssignableTo(typeof(LocalSettingsButton))) - { - var button = property.GetValue(tabInstance) as LocalSettingsButton; - button!.Tab = tabInstance; - tabInstance.Buttons.Add(button); - continue; - } - - if (!typeof(ConfigEntryBase).IsAssignableFrom(property.PropertyType)) - { - continue; - } - - if (property.GetValue(tabInstance) is not ConfigEntryBase configEntry) - { - Error($"Option property {property.Name} in {type.Name} has to be a config entry."); - continue; - } - - if (property.TryGetCustomAttribute(out var attribute)) - { - attribute.CreateSetting(type, configEntry); - } - } - - foreach (var field in type.GetFields(DeclaredInstanceMembers).Where(f => !IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(ConfigEntryBase)) && f.IsDefined())) - { - Error($"{field.Name} is a field, not a property. Use properties for local settings."); - } - - return true; + return LocalSettingsManager.RegisterLocalTabs(type, pluginInfo); } catch (Exception e) { @@ -466,47 +305,18 @@ public sealed class MiraPluginManager return false; } - private static void RegisterKeybinds(Type type, IMiraPlugin plugin) + private static bool RegisterKeybinds(Type type, IMiraPlugin plugin) { try { - if (!type.IsDefined()) - { - return; - } - - if (!type.IsStatic()) - { - Error($"Keybinds class {type.Name} must be static."); - return; - } - - foreach (var property in type.GetProperties(DeclaredStaticMembers)) - { - if (property.PropertyType != typeof(MiraKeybind)) - { - continue; - } - - if (property.GetValue(null) is not MiraKeybind keybind) - { - Error($"Keybind property {property.Name} in {type.Name} is not a MiraKeybind."); - continue; - } - - KeybindManager.Keybinds.Add(keybind); - keybind.SourcePluginName = plugin.OptionsTitleText.Translate(); - } - - foreach (var field in type.GetFields(DeclaredStaticMembers).Where(f => !IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(MiraKeybind)))) - { - Error($"{field.Name} is a field, not a property. Use properties for keybinds."); - } + 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) @@ -518,8 +328,9 @@ public sealed class MiraPluginManager catch (Exception e) { Error($"Failed to register meeting ability {type.Name}: {e}"); - return false; } + + return false; } private static bool RegisterTargetedMeetingAbility(Type type, MiraPluginInfo info) @@ -531,7 +342,8 @@ public sealed class MiraPluginManager catch (Exception e) { Error($"Failed to register targeted meeting ability {type.Name}: {e}"); - return false; } + + return false; } } diff --git a/MiraAPI/Roles/CustomRoleManager.cs b/MiraAPI/Roles/CustomRoleManager.cs index d9325e6a..a2a0164f 100644 --- a/MiraAPI/Roles/CustomRoleManager.cs +++ b/MiraAPI/Roles/CustomRoleManager.cs @@ -10,6 +10,7 @@ using MiraAPI.PluginLoading; using MiraAPI.Translation; using MiraAPI.Utilities; using MiraAPI.Utilities.Assets; +using Reactor.Networking; using Reactor.Networking.Rpc; using Reactor.Utilities.Extensions; using TMPro; @@ -118,6 +119,23 @@ public static class CustomRoleManager pluginInfo.PluginConfig.SaveOnConfigSet = oldConfigSetting; } + internal static bool RegisterRole(Type type, MiraPluginInfo miraPlugin, List roles) + { + if (!(typeof(RoleBehaviour).IsAssignableFrom(type) && typeof(ICustomRole).IsAssignableFrom(type))) + { + return false; + } + + if (!ModList.GetById(miraPlugin.PluginId).IsRequiredOnAllClients) + { + Error("Custom roles are only supported on all clients."); + return false; + } + + roles.Add(type); + return true; + } + private static RoleBehaviour? RegisterRole(Type roleType, MiraPluginInfo parentMod) { if (!(typeof(RoleBehaviour).IsAssignableFrom(roleType) && typeof(ICustomRole).IsAssignableFrom(roleType))) @@ -278,9 +296,9 @@ public static class CustomRoleManager .Select(x => ((ICustomRole)x).GetNetData()) .ChunkNetData(1000); - while (data.Count > 0) + while (data.TryDequeue(out var netData)) { - Rpc.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, data.Dequeue())); + Rpc.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, netData)); } }