Merge branch 'dev' into no-boxing

This commit is contained in:
Az committed 2026-11-11 14:58:56 -05:00
commit 43f5effe50
16 files changed
+308 -416

No files matched your search

+5 -3
View File
@@ -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<RegisterCustomColorsAttribute>(out var attribute))
{
return false;
+10 -3
View File
@@ -156,11 +156,16 @@ public static class MiraEventManager
return true;
}
internal static void RegisterEvents(Type type, IMiraPlugin miraPlugin)
internal static bool RegisterEvents(in MiraPluginManager.RegistrationContext context)
{
if (!miraPlugin.ForceRegisterEvents && !type.IsDefined<RegisterEventContainerAttribute>())
var type = context.Type;
var miraPlugin = context.MiraPlugin;
var hasContainerAttribute = type.IsDefined<RegisterEventContainerAttribute>();
if (!miraPlugin.ForceRegisterEvents && !hasContainerAttribute)
{
return;
return false;
}
foreach (var method in type.GetMethods(MiraPluginManager.DeclaredStaticMembers))
@@ -179,5 +184,7 @@ public static class MiraEventManager
var paramType = parameters[0].ParameterType;
RegisterEventHandler(paramType, method, eventAttribute.Priority);
}
return hasContainerAttribute;
}
}
+9 -6
View File
@@ -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<GameOverReason>().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;
}
+7 -4
View File
@@ -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;
}
@@ -167,9 +167,6 @@ public abstract class AbstractOptionGroup<T> : AbstractOptionGroup
public abstract class AbstractRoleOptionGroup<T> : AbstractOptionGroup<T>
where T : ICustomRole
{
/// <inheritdoc />
public override Type OptionableType => typeof(T);
/// <inheritdoc />
public override MenuCategory ParentMenu => MenuCategory.Roles;
+4 -1
View File
@@ -74,8 +74,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;
+19 -8
View File
@@ -16,17 +16,17 @@ public static class CustomButtonManager
/// <summary>
/// Gets a list of all registered custom <see cref="CustomActionButton"/>s.
/// </summary>
public static ReadOnlyCollection<CustomActionButton> Buttons { get; internal set; } = new([]);
public static ReadOnlyCollection<CustomActionButton> Buttons { get; private set; } = new([]);
/// <summary>
/// Gets a list of all registered button-specific <see cref="MiraButtonClickEvent"/>s.
/// </summary>
public static ReadOnlyDictionary<Type, Type> EventTypes { get; internal set; } = new(new Dictionary<Type, Type>());
public static ReadOnlyDictionary<Type, Type> EventTypes { get; private set; } = new(new Dictionary<Type, Type>());
/// <summary>
/// Gets a list of all registered button-specific <see cref="MiraButtonCancelledEvent"/>s.
/// </summary>
public static ReadOnlyDictionary<Type, Type> CancelledEventTypes { get; internal set; } = new(new Dictionary<Type, Type>());
public static ReadOnlyDictionary<Type, Type> CancelledEventTypes { get; private set; } = new(new Dictionary<Type, Type>());
internal static readonly List<CustomActionButton> CustomButtons = [];
internal static readonly Dictionary<Type, Type> 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<CustomActionButton>(CustomButtonManager.CustomButtons);
EventTypes = new ReadOnlyDictionary<Type, Type>(CustomButtonManager.ButtonEventTypes);
CancelledEventTypes = new ReadOnlyDictionary<Type, Type>(CustomButtonManager.ButtonCancelledEventTypes);
}
}
+7 -4
View File
@@ -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<RegisterCustomKeybindsAttribute>())
{
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)
@@ -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;
}
@@ -22,28 +22,34 @@ public static class MeetingButtonManager
/// </summary>
public static List<MeetingActionButton> 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;
}
+19 -10
View File
@@ -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
/// <summary>
/// Gets the list of all registered <see cref="BaseModifier"/>s.
/// </summary>
public static IReadOnlyList<BaseModifier> Modifiers { get; internal set; } = [];
public static IReadOnlyList<BaseModifier> Modifiers { get; private set; } = [];
internal static List<BaseModifier> 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<BaseModifier>(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;
}
+36 -208
View File
@@ -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<Type> Roles);
private MiraPluginManager()
{
}
@@ -49,6 +52,22 @@ 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),
("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),
];
/// <summary>
/// Get a mira plugin by its GUID.
/// </summary>
@@ -92,18 +111,13 @@ public sealed class MiraPluginManager
IL2CPPChainloader.Instance.Finished += () =>
{
PaletteManager.RegisterAllColors();
// Save all buttons into a read-only collection for easy access
CustomButtonManager.Buttons = new ReadOnlyCollection<CustomActionButton>(CustomButtonManager.CustomButtons);
CustomButtonManager.EventTypes = new ReadOnlyDictionary<Type, Type>(CustomButtonManager.ButtonEventTypes);
CustomButtonManager.CancelledEventTypes = new ReadOnlyDictionary<Type, Type>(CustomButtonManager.ButtonCancelledEventTypes);
CustomButtonManager.RegisterAllButtons();
ModifierManager.RegisterAllModifiers();
// 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<BaseModifier>(ModifierManager.InternalModifiers);
};
}
@@ -137,12 +151,11 @@ 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<Type> roles, bool isMira)
{
if (plugin.ForceRegisterEvents)
{
Warning("For optimisation reasons, MiraAPI no longer automatically searches every type for events. Please use RegisterEventsAttribute moving forward.");
Warning("For optimisation reasons, MiraAPI no longer automatically searches every type for events. Please use RegisterEventContainerAttribute moving forward.");
}
foreach (var type in assembly.GetTypes())
@@ -150,205 +163,20 @@ public sealed class MiraPluginManager
if ((isMira && type.IsAbstract) || type.IsDefined<MiraIgnoreAttribute>())
continue;
RegisterEvents(type, plugin);
var context = new RegistrationContext(type, info, plugin, basePlugin, roles);
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 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<Type> 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;
}
}
+7 -3
View File
@@ -119,14 +119,18 @@ public static class CustomRoleManager
pluginInfo.PluginConfig.SaveOnConfigSet = oldConfigSetting;
}
internal static bool RegisterRole(Type type, MiraPluginInfo miraPlugin, List<Type> 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<RoleBehaviour>();
if (roleBehaviour is not ICustomRole customRole)
{
+162 -154
View File
@@ -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
/// </summary>
public static Dictionary<MiraLanguage, string> 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<string, MiraLanguage> ReverseLangLookup =
LangList.ToDictionary(x => x.Value, x => x.Key);
/// <summary>
/// Gets a dictionary mapping <see cref="MiraLanguage"/> values to their standard language codes.
/// </summary>
public static Dictionary<MiraLanguage, string> 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<MiraLanguage, string> LangCultureList { get; } =
LangList.ToDictionary(x => x.Key, x => x.Value.Replace('_', '-'));
/// <summary>
/// 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
}
}
/// <summary>
/// Registers translations for a mod.
/// Call once per mod during plugin Load().
/// </summary>
/// <param name="modGuid">The mod GUID (e.g., "mira.example").</param>
/// <inheritdoc cref="Register(string, string, Assembly)"/>
[Obsolete("Pass typeof(YourPlugin).Assembly directly to Register for better performance. This will be removed in a future version.")]
public static void Register(string modGuid)
{
var callingAssembly = Assembly.GetCallingAssembly();
LoadInternalStrings(callingAssembly, callingAssembly.GetName().Name!, modGuid);
LoadInternalStrings(Assembly.GetCallingAssembly(), modGuid);
}
/// <summary>
/// Registers translations for a mod.
/// Call once per mod during plugin Load().
/// </summary>
/// <param name="modGuid">The mod GUID (e.g., "mira.example").</param>
/// <param name="assembly">The <see cref="Assembly"/> to load the strings from.</param>
/// <inheritdoc cref="Register(string, string, Assembly)"/>
public static void Register(string modGuid, Assembly assembly)
{
LoadInternalStrings(assembly, assembly.GetName().Name!, modGuid);
LoadInternalStrings(assembly, modGuid);
}
/// <summary>
/// Registers translations for a mod.
/// Call once per mod during plugin Load().
/// </summary>
/// <param name="modGuid">The mod GUID (e.g., "mira.example").</param>
/// <param name="internalName">The mod's root namespace (e.g., "mira.api").</param>
/// <inheritdoc cref="Register(string, string, Assembly)"/>
[Obsolete("Pass typeof(YourPlugin).Assembly directly to Register for better performance. This will be removed in a future version.")]
public static void Register(string modGuid, string internalName)
{
var callingAssembly = Assembly.GetCallingAssembly();
LoadInternalStrings(callingAssembly, internalName, modGuid);
LoadInternalStrings(Assembly.GetCallingAssembly(), internalName, modGuid);
}
/// <summary>
@@ -169,15 +132,10 @@ public static class MiraLocaleManager
LoadInternalStrings(assembly, internalName, modGuid);
}
/// <summary>
/// Translates a key into the current language.
/// </summary>
/// <param name="key">The string id to find.</param>
/// <param name="fallback">Fallback string to use if no translation is found.</param>
/// <returns>A <see cref="string"/> based on the key provided.</returns>
/// <inheritdoc cref="Get(MiraLanguage, string, string)"/>
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);
}
/// <summary>
@@ -189,34 +147,30 @@ public static class MiraLocaleManager
/// <returns>A <see cref="string"/> based on the key provided.</returns>
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;
}
/// <summary>
/// Translates a key into the current language.
/// </summary>
/// <param name="key">The string id to find.</param>
/// <param name="parseList">List of keys to change into other text.</param>
/// <param name="fallback">Fallback string to use if no translation is found.</param>
/// <returns>A <see cref="string"/> based on the key provided.</returns>
/// <inheritdoc cref="GetParsed(MiraLanguage, string, Dictionary{string, string}, string)"/>
public static string GetParsed(
string key,
Dictionary<string, string> parseList,
string fallback = "")
{
return GetParsed(CurrentLanguage, key, parseList, fallback != string.Empty ? fallback : key);
return GetParsed(CurrentLanguage, key, parseList, string.IsNullOrEmpty(fallback) ? key : fallback);
}
/// <inheritdoc cref="GetParsed(MiraLanguage, string, ValueTuple{string, string}[], string)"/>
public static string GetParsed(
string key,
(string, string)[] parseList,
string fallback = "")
{
return GetParsed(CurrentLanguage, key, parseList, string.IsNullOrEmpty(fallback) ? key : fallback);
}
/// <summary>
@@ -233,24 +187,35 @@ public static class MiraLocaleManager
Dictionary<string, string> 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)))
/// <summary>
/// Translates a key into the current language.
/// </summary>
/// <param name="language">The specific language to prioritize.</param>
/// <param name="key">The string id to find.</param>
/// <param name="parseList">List of keys to change into other text.</param>
/// <param name="fallback">Fallback string to use if no translation is found.</param>
/// <returns>A <see cref="string"/> based on the key provided.</returns>
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}";
}
/// <summary>
/// Builds a formatted translation ID string using a mod ID and a specific ID part.
/// </summary>
/// <param name="modId">The mod GUID.</param>
/// <param name="idPart">The core part of the ID. If it starts with '#', the character is stripped.</param>
/// <returns>A formatted translation ID <see cref="string"/>.</returns>
/// <inheritdoc cref="BuildTranslationId(string, string, string)"/>
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
/// <param name="language">The language that the xml file corresponds to.</param>
/// <param name="loadingInternal">Flag that indicates if the xml being parsed is internal or not.</param>
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);
}
/// <summary>
/// Parses the provided xml stream into translation keys and values and registers them to the locale manager.
/// </summary>
/// <param name="xmlStream">The stream to the xml content.</param>
/// <param name="language">The language that the xml file corresponds to.</param>
/// <param name="loadingInternal">Flag that indicates if the xml being parsed is internal or not.</param>
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<string, string>();
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("<nl>", "\n")
.Replace("<and>", "&");
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("<nl>", "\n").Replace("<and>", "&");
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)");
+2 -2
View File
@@ -26,9 +26,9 @@ public abstract class LoadableAsset<T>
/// Converts the <see cref="LoadableAsset{T}"/> into its <typeparamref name="T"/> by loading the asset.
/// </summary>
/// <param name="loadable">The <see cref="LoadableAsset{T}"/> to get the asset from.</param>
public static implicit operator T(LoadableAsset<T> loadable)
public static implicit operator T(LoadableAsset<T>? loadable)
{
return loadable.LoadAsset();
return loadable?.LoadAsset()!;
}
/// <summary>
+6
View File
@@ -96,4 +96,10 @@ public class StateMachineWrapper<T>
_propertyCache[parameterName] = property;
return (TField)property.GetValue(_stateMachine)!;
}
/// <summary>
/// Implicitly converts a state machine wrapper into its <typeparamref name="T"/> instance.
/// </summary>
/// <param name="wrapper">The wrapper.</param>
public static implicit operator T(StateMachineWrapper<T> wrapper) => wrapper.Instance;
}