using System; using System.Collections.Generic; using System.IO; using System.Reflection; using MelonLoader; using Newtonsoft.Json; using UnityEngine; namespace ADOFAIRenderer.Localization; /// /// Provides access to localized strings and handles language synchronization with the game. /// internal static class LocalizationManager { private static readonly Dictionary> Locales = new(StringComparer.OrdinalIgnoreCase); private static readonly string FallbackLocaleCode = "en"; /// /// Event triggered when the active language changes. /// public static event Action? OnLanguageChanged; /// /// Currently active SystemLanguage. /// public static SystemLanguage CurrentLanguage { get; private set; } = SystemLanguage.English; /// /// Currently active locale code (e.g. "en", "ko"). /// public static string CurrentLocaleCode { get; private set; } = "en"; private static bool _initialized; /// /// Initializes the localization system and loads embedded language dictionaries. /// public static void Initialize() { if (_initialized) return; _initialized = true; LoadEmbeddedLocales(); // Detect initial language from game settings var initialLang = DetectGameLanguage(); SetLanguage(initialLang, notify: false); LogMsg($"[Localization] Initialized. Active language: {CurrentLanguage} ({CurrentLocaleCode})"); } private static void LogMsg(string msg) { try { Melon.Logger.Msg(msg); } catch { Console.WriteLine(msg); } } private static void LogError(string msg) { try { Melon.Logger.Error(msg); } catch { Console.Error.WriteLine(msg); } } /// /// Loads all *.json locale files embedded in this assembly. /// private static void LoadEmbeddedLocales() { var assembly = typeof(LocalizationManager).Assembly; var resourceNames = assembly.GetManifestResourceNames(); foreach (var resourceName in resourceNames) { if (!resourceName.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) continue; if (!resourceName.Contains("Localization.Locale")) continue; try { using var stream = assembly.GetManifestResourceStream(resourceName); if (stream == null) continue; using var reader = new StreamReader(stream); var json = reader.ReadToEnd(); var dict = JsonConvert.DeserializeObject>(json); if (dict != null) { // Extract locale code from resource name: e.g. "ADOFAIRenderer.Localization.Locale.ko.json" -> "ko" var parts = resourceName.Split('.'); if (parts.Length >= 2) { var code = parts[^2].ToLowerInvariant(); Locales[code] = dict; LogMsg($"[Localization] Loaded locale '{code}' ({dict.Count} keys)."); } } } catch (Exception ex) { LogError($"[Localization] Failed to load locale resource '{resourceName}': {ex.Message}"); } } } /// /// Sets the active language and notifies subscribers if changed. /// public static void SetLanguage(SystemLanguage language, bool notify = true) { var localeCode = LanguageToLocaleCode(language); if (!Locales.ContainsKey(localeCode)) { // Fallback to English if translation for this language does not exist localeCode = FallbackLocaleCode; } var isChanged = (language != CurrentLanguage) || (localeCode != CurrentLocaleCode); CurrentLanguage = language; CurrentLocaleCode = localeCode; if (isChanged && notify) { LogMsg($"[Localization] Language changed to: {CurrentLanguage} ({CurrentLocaleCode})"); try { OnLanguageChanged?.Invoke(CurrentLanguage); } catch (Exception ex) { LogError($"[Localization] Error during OnLanguageChanged notification: {ex.Message}"); } } } /// /// Retrieves a localized string for the specified key. /// public static string Get(string key) { if (string.IsNullOrEmpty(key)) return string.Empty; // 1. Try currently active locale if (Locales.TryGetValue(CurrentLocaleCode, out var activeDict) && activeDict.TryGetValue(key, out var val)) { return val; } // 2. Fallback to English locale if (CurrentLocaleCode != FallbackLocaleCode && Locales.TryGetValue(FallbackLocaleCode, out var fallbackDict) && fallbackDict.TryGetValue(key, out var fallbackVal)) { return fallbackVal; } // 3. Fallback to raw key if missing return key; } /// /// Retrieves a formatted localized string. /// public static string Get(string key, params object[] args) { var template = Get(key); if (args == null || args.Length == 0) return template; try { return string.Format(template, args); } catch (FormatException) { return template; } } /// /// Maps Unity's SystemLanguage enum to an internal locale code. /// private static string LanguageToLocaleCode(SystemLanguage language) { return language switch { SystemLanguage.Korean => "ko", SystemLanguage.English => "en", _ => "en" }; } /// /// Attempts to read the game's current language from RDString or Persistence. /// private static SystemLanguage DetectGameLanguage() { try { // First attempt: RDString.language return RDString.language; } catch { try { // Fallback attempt: Persistence.language return Persistence.language; } catch { return SystemLanguage.English; } } } } /// /// Convenient shorthand alias for . /// internal static class I18n { /// public static string Get(string key) => LocalizationManager.Get(key); /// public static string Get(string key, params object[] args) => LocalizationManager.Get(key, args); /// public static SystemLanguage CurrentLanguage => LocalizationManager.CurrentLanguage; /// public static string CurrentLocaleCode => LocalizationManager.CurrentLocaleCode; /// public static event Action? OnLanguageChanged { add => LocalizationManager.OnLanguageChanged += value; remove => LocalizationManager.OnLanguageChanged -= value; } }