Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of ExtendedLocalization v1.0.2
ExtendedLocalization.dll
Decompiled 2 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("BioHazardN7")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.2.0")] [assembly: AssemblyInformationalVersion("1.0.2")] [assembly: AssemblyProduct("ExtendedLocalization")] [assembly: AssemblyTitle("ExtendedLocalization")] [assembly: AssemblyVersion("1.0.2.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ExtendedLocalization { [HarmonyPatch(typeof(Localization), "SetupLanguage")] internal static class SetupLanguagePatch { [HarmonyPostfix] private static void Postfix(Localization __instance, string language) { TranslationStore.Rebuild(__instance, Plugin.CurrentLanguage = TranslationStore.GetSelectedLanguage(__instance, language)); } } [HarmonyPatch(typeof(Localization), "Translate", new Type[] { typeof(string) })] internal static class TranslatePatch { private static bool _loggedFirstHit; [HarmonyPrefix] private static bool Prefix(string word, ref string __result) { if (word != null && TranslationStore.Overrides.TryGetValue(word, out var value)) { __result = value; if (!_loggedFirstHit && Plugin.VerboseLogging.Value) { _loggedFirstHit = true; Plugin.Log.LogInfo((object)("Translate patch is active: first token served from the override table was '" + word + "'.")); } return false; } return true; } } [BepInPlugin("BioHazardN7.ExtendedLocalization", "ExtendedLocalization", "1.0.2")] public class Plugin : BaseUnityPlugin { public const string PluginGuid = "BioHazardN7.ExtendedLocalization"; public const string PluginName = "ExtendedLocalization"; public const string PluginVersion = "1.0.2"; private const long ReloadDelayTicks = 5000000L; internal static ManualLogSource Log; internal static string TranslationsDir; internal static string CurrentLanguage; internal static ConfigEntry<bool> Enabled; internal static ConfigEntry<bool> HotReload; internal static ConfigEntry<bool> VerboseLogging; private Harmony _harmony; private FileSystemWatcher _watcher; private volatile bool _reloadPending; private long _lastChangeTicks; private void Awake() { //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable or disable the mod. Takes effect the next time the game language is loaded."); HotReload = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Hot reload", true, "Reload translation files automatically when they change on disk."); VerboseLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Verbose logging", false, "Log every applied token and every parsing problem in detail."); TranslationsDir = Path.Combine(Paths.ConfigPath, "ExtendedLocalization"); Directory.CreateDirectory(TranslationsDir); _harmony = new Harmony("BioHazardN7.ExtendedLocalization"); try { _harmony.PatchAll(); } catch (Exception ex) { Log.LogError((object)("Failed to apply the Harmony patches (game version changed?): " + ex)); } if (HotReload.Value) { StartWatcher(); } } private void Update() { if (_reloadPending) { long num = Volatile.Read(in _lastChangeTicks); if (DateTime.UtcNow.Ticks - num >= 5000000) { _reloadPending = false; ReloadCurrentLanguage(); } } } private void OnDestroy() { if (_watcher != null) { _watcher.EnableRaisingEvents = false; _watcher.Dispose(); _watcher = null; } if (_harmony != null) { _harmony.UnpatchSelf(); } } private void StartWatcher() { try { _watcher = new FileSystemWatcher(TranslationsDir) { NotifyFilter = (NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite), IncludeSubdirectories = false }; _watcher.Changed += OnFileEvent; _watcher.Created += OnFileEvent; _watcher.Deleted += OnFileEvent; _watcher.Renamed += OnFileEvent; _watcher.EnableRaisingEvents = true; } catch (Exception ex) { Log.LogWarning((object)("Could not start the file watcher, hot reload is disabled: " + ex.Message)); } } private void OnFileEvent(object sender, FileSystemEventArgs e) { if (TranslationStore.IsTranslationFile(e.FullPath)) { Volatile.Write(ref _lastChangeTicks, DateTime.UtcNow.Ticks); _reloadPending = true; } } private static void ReloadCurrentLanguage() { string currentLanguage = CurrentLanguage; if (!string.IsNullOrEmpty(currentLanguage) && Localization.instance != null) { Log.LogInfo((object)("Translation files changed, reloading language '" + currentLanguage + "'.")); Localization.instance.SetupLanguage(currentLanguage); } } } internal static class TranslationStore { private sealed class CachedFile { public DateTime LastWrite; public long Length; public Dictionary<string, string> Entries; } internal static Dictionary<string, string> Overrides = new Dictionary<string, string>(StringComparer.Ordinal); private static readonly Dictionary<string, CachedFile> Files = new Dictionary<string, CachedFile>(StringComparer.OrdinalIgnoreCase); private static FieldInfo _cacheField; private static MethodInfo _evictAll; private static FieldInfo _instanceField; private static bool _cacheResolved; private static MethodInfo _addWord; private static FieldInfo _translations; private static bool _resolved; public static void Rebuild(Localization localization, string selected) { Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.Ordinal); if (Plugin.Enabled.Value && localization != null) { AddFile(dictionary, "English"); if (!string.IsNullOrEmpty(selected) && !string.Equals(selected, "English", StringComparison.OrdinalIgnoreCase)) { AddFile(dictionary, selected); } } Overrides = dictionary; if (localization != null) { WriteToTable(localization, dictionary); EvictCaches(localization); } } private static void AddFile(Dictionary<string, string> merged, string language) { string text = FindFile(language); if (text == null) { if (Plugin.VerboseLogging.Value) { Plugin.Log.LogInfo((object)("No translation file for language '" + language + "'.")); } return; } Dictionary<string, string> entries = GetEntries(text); if (entries == null) { return; } foreach (KeyValuePair<string, string> item in entries) { merged[item.Key] = item.Value; } } private static Dictionary<string, string> GetEntries(string path) { Files.TryGetValue(path, out var value); try { DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(path); long length = new FileInfo(path).Length; if (value != null && value.LastWrite == lastWriteTimeUtc && value.Length == length) { return value.Entries; } Dictionary<string, string> dictionary = Parse(path); Files[path] = new CachedFile { LastWrite = lastWriteTimeUtc, Length = length, Entries = dictionary }; Plugin.Log.LogInfo((object)("Loaded " + dictionary.Count + " token(s) from " + Path.GetFileName(path) + ".")); if (Plugin.VerboseLogging.Value) { foreach (KeyValuePair<string, string> item in dictionary) { Plugin.Log.LogInfo((object)(" $" + item.Key + " = " + item.Value)); } } return dictionary; } catch (Exception ex) { Plugin.Log.LogError((object)("Failed to read " + Path.GetFileName(path) + ": " + ex.Message)); return value?.Entries; } } private static void WriteToTable(Localization localization, Dictionary<string, string> tokens) { foreach (KeyValuePair<string, string> token in tokens) { if (!SetToken(localization, token.Key, token.Value)) { Plugin.Log.LogWarning((object)"Cannot write to the game's translation table (neither Localization.AddWord nor the field m_translations was found); only the lookup patch is used."); break; } } } private static void EvictCaches(Localization localization) { if (!_cacheResolved) { _cacheResolved = true; _cacheField = AccessTools.Field(typeof(Localization), "m_cache"); _instanceField = AccessTools.Field(typeof(Localization), "m_instance"); if (_cacheField != null) { _evictAll = AccessTools.Method(_cacheField.FieldType, "EvictAll", (Type[])null, (Type[])null); } } EvictCache(localization); if (_instanceField != null) { object? value = _instanceField.GetValue(null); EvictCache((Localization)((value is Localization) ? value : null)); } } private static void EvictCache(Localization localization) { if (localization == null || _cacheField == null || _evictAll == null) { return; } try { object value = _cacheField.GetValue(localization); if (value != null) { _evictAll.Invoke(value, null); } } catch (Exception) { } } internal static string GetSelectedLanguage(Localization localization, string fallback) { try { string selectedLanguage = localization.GetSelectedLanguage(); if (!string.IsNullOrEmpty(selectedLanguage)) { return selectedLanguage; } } catch (Exception) { } FieldInfo fieldInfo = AccessTools.Field(typeof(Localization), "m_language"); string text = ((fieldInfo != null) ? (fieldInfo.GetValue(localization) as string) : null); if (!string.IsNullOrEmpty(text)) { return text; } return fallback; } private static void Resolve() { if (!_resolved) { _resolved = true; _addWord = AccessTools.Method(typeof(Localization), "AddWord", new Type[2] { typeof(string), typeof(string) }, (Type[])null); _translations = AccessTools.Field(typeof(Localization), "m_translations"); if (Plugin.VerboseLogging.Value) { Plugin.Log.LogInfo((object)("AddWord found: " + (_addWord != null) + ", m_translations found: " + (_translations != null))); } } } private static bool SetToken(Localization localization, string key, string value) { Resolve(); if (_addWord != null) { _addWord.Invoke(localization, new object[2] { key, value }); return true; } Dictionary<string, string> dictionary = ((_translations != null) ? (_translations.GetValue(localization) as Dictionary<string, string>) : null); if (dictionary != null) { dictionary[key] = value; return true; } return false; } internal static bool IsTranslationFile(string path) { string extension = Path.GetExtension(path); if (!string.Equals(extension, ".yaml", StringComparison.OrdinalIgnoreCase)) { return string.Equals(extension, ".yml", StringComparison.OrdinalIgnoreCase); } return true; } private static string[] GetTranslationFiles() { List<string> list = new List<string>(); string[] files = Directory.GetFiles(Plugin.TranslationsDir); foreach (string text in files) { if (IsTranslationFile(text)) { list.Add(text); } } return list.ToArray(); } private static string FindFile(string language) { string[] translationFiles = GetTranslationFiles(); foreach (string text in translationFiles) { if (string.Equals(Path.GetFileNameWithoutExtension(text), language, StringComparison.OrdinalIgnoreCase)) { return text; } } return null; } private static Dictionary<string, string> Parse(string path) { Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.Ordinal); string[] array = File.ReadAllLines(path, Encoding.UTF8); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.Length == 0 || text[0] == '#') { continue; } int num = text.IndexOfAny(new char[2] { '=', ':' }); if (num <= 0) { Warn(path, i + 1, "no ':' found, line skipped"); continue; } string text2 = text.Substring(0, num).Trim(); string text3 = text.Substring(num + 1).Trim(); if (text2.StartsWith("$", StringComparison.Ordinal)) { text2 = text2.Substring(1); } if (text2.Length == 0 || text2.IndexOf(' ') >= 0) { Warn(path, i + 1, "invalid token name, line skipped"); continue; } bool num2 = text3.Length >= 2 && text3[0] == '"' && text3[text3.Length - 1] == '"'; text3 = Unquote(text3); if (num2) { text3 = text3.Replace("\\\"", "\""); } text3 = text3.Replace("\\n", "\n"); if (dictionary.ContainsKey(text2)) { Warn(path, i + 1, "duplicate token '" + text2 + "', the last value is used"); } dictionary[text2] = text3; } return dictionary; } private static string Unquote(string value) { if (value.Length >= 2) { char c = value[0]; char c2 = value[value.Length - 1]; if ((c == '"' && c2 == '"') || (c == '\'' && c2 == '\'')) { return value.Substring(1, value.Length - 2); } } return value; } private static void Warn(string path, int lineNumber, string message) { Plugin.Log.LogWarning((object)(Path.GetFileName(path) + ":" + lineNumber + " " + message)); } } }