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 BaconTranslations v1.0.1
BepInEx/plugins/BaconTranslations.dll
Decompiled 39 minutes ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("BaconTranslations")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("BaconTranslations")] [assembly: AssemblyTitle("BaconTranslations")] [assembly: AssemblyMetadata("AI_Assisted_Creation", "Code generated with Claude Code, Anthropic's AI coding agent")] [assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic")] [assembly: AssemblyVersion("1.0.0.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 BaconTranslations { internal static class Currency { private static readonly Regex Amount = new Regex("\\$(\\d(?:[\\d,. ]*\\d)?)", RegexOptions.CultureInvariant); private static readonly Regex WordNext = new Regex("^[ \\t]*\\p{L}", RegexOptions.CultureInvariant); internal static string Keep(string original, string translated) { if (original == null || translated == null || original.IndexOf('$') < 0) { return translated; } foreach (Match item in Amount.Matches(original)) { if (!WordNext.IsMatch(original.Substring(item.Index + item.Length))) { string value = item.Groups[1].Value; string text = "$" + value; translated = ((translated.IndexOf(text, StringComparison.Ordinal) >= 0) ? new Regex(Regex.Escape(text) + "[ \\t]+\\p{L}+\\.?").Replace(translated, text, 1) : new Regex("(?<![\\d$])" + Regex.Escape(value) + "[ \\t]+\\p{L}+\\.?").Replace(translated, text, 1)); } } return translated; } } internal static class Engine { private static readonly Dictionary<string, string> Cache = new Dictionary<string, string>(StringComparer.Ordinal); private static readonly Regex Tags = new Regex("(<[^<>\\n]+>)", RegexOptions.Compiled); private const string Miss = "\0"; internal static bool Active => Languages.ActiveName != "Original"; internal static void Clear() { Cache.Clear(); Untranslated.Clear(); } internal static string Translate(string text, string owner, bool trackMissing = true) { if (!Active || string.IsNullOrEmpty(text) || !HasLetter(text)) { return null; } string key = (trackMissing ? "1" : "0") + owner + "\u0001" + text; if (Cache.TryGetValue(key, out var value)) { if ((object)value != "\0") { return value; } return null; } string text2 = null; try { text2 = Currency.Keep(text, Whole(text, owner, trackMissing)); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Translating \"" + Short(text) + "\" failed: " + ex.Message)); } if (Cache.Count > 30000) { Cache.Clear(); } Cache[key] = text2 ?? "\0"; return text2; } private static string Whole(string text, string owner, bool trackMissing) { string text2 = Piece(text, owner, trackMissing && text.IndexOf('\n') < 0 && text.IndexOf('<') < 0); if (text2 != null || (text.IndexOf('\n') < 0 && text.IndexOf('<') < 0)) { return text2; } string[] array = text.Split('\n'); bool flag = false; for (int i = 0; i < array.Length; i++) { if (HasLetter(array[i])) { string text3 = Line(array[i], owner, trackMissing); if (text3 != null) { array[i] = text3; flag = true; } } } if (!flag) { return null; } return string.Join("\n", array); } private static string Line(string line, string owner, bool trackMissing) { bool flag = line.IndexOf('<') >= 0; string text = Piece(line, owner, trackMissing && !flag); if (text != null || !flag) { return text; } string[] array = Tags.Split(line); bool flag2 = false; for (int i = 0; i < array.Length; i += 2) { if (HasLetter(array[i])) { string text2 = Piece(array[i], owner, trackMissing); if (text2 != null) { array[i] = text2; flag2 = true; } } } if (!flag2) { return null; } return string.Concat(array); } private static bool Blank(char c) { if (!char.IsWhiteSpace(c) && c != '\u200b' && c != '\u200c' && c != '\u200d') { return c == '\ufeff'; } return true; } private static string Piece(string piece, string owner, bool record) { int i = 0; int num; for (num = piece.Length; i < num && Blank(piece[i]); i++) { } while (num > i && Blank(piece[num - 1])) { num--; } if (i == num) { return null; } string text = piece.Substring(i, num - i); string text2 = null; string template = null; int num2 = (string.Equals(owner, "BaconTranslations", StringComparison.OrdinalIgnoreCase) ? 1 : 2); for (int j = 0; j < num2; j++) { if (text2 != null) { break; } foreach (Source file in Languages.Files) { if (file.Lines.Count == 0 || !Sources.On(file, owner)) { continue; } Dictionary value = file.Lines; if (j != 0 || (owner != null && file.ByMod.TryGetValue(owner, out value))) { text2 = value.Lookup(text, out template); if (text2 != null) { Sources.Count(file, owner, template ?? text); break; } } } } if (template == null && HasDigit(text) && Languages.Files.Count > 0) { Languages.Files[0].Lines.Lookup(text, out template); } Seen.Add(owner, template ?? text); if (text2 == null) { if (record) { Untranslated.Add(owner, template ?? text); Missing.Note(template ?? text, owner); } return null; } return piece.Substring(0, i) + text2 + piece.Substring(num); } internal static bool HasLetter(string s) { if (s == null) { return false; } bool flag = false; for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c == '<' && s.IndexOf('>', i + 1) > i) { flag = true; } else if (c == '>') { flag = false; } else if (!flag && char.IsLetter(c)) { return true; } } return false; } internal static bool HasDigit(string s) { foreach (char c in s) { if (c >= '0' && c <= '9') { return true; } } return false; } internal static bool IsCaps(string s) { int num = 0; foreach (char c in s) { if (char.IsLetter(c)) { if (char.IsLower(c)) { return false; } num++; } } return num >= 2; } internal static string Short(string s) { if (s.Length <= 60) { return s; } return s.Substring(0, 60) + "..."; } } internal static class Owners { private static readonly Dictionary<Assembly, string> Names = new Dictionary<Assembly, string>(); private static readonly Assembly Own = typeof(Owners).Assembly; private static readonly Assembly Tmp = typeof(TMP_Text).Assembly; internal static string FromStack() { try { StackTrace stackTrace = new StackTrace(2, fNeedFileInfo: false); for (int i = 0; i < stackTrace.FrameCount; i++) { Type type = stackTrace.GetFrame(i)?.GetMethod()?.DeclaringType; if (!(type == null)) { Assembly assembly = type.Assembly; if (!(assembly == Own) && !(assembly == Tmp) && !Skipped(assembly)) { return NameOf(assembly); } } } } catch (Exception) { } return "Game"; } private static bool Skipped(Assembly assembly) { string name = assembly.GetName().Name; if (!name.StartsWith("UnityEngine") && !name.StartsWith("Unity.") && !name.StartsWith("0Harmony") && !name.StartsWith("Harmony") && !name.StartsWith("MonoMod") && !name.StartsWith("System") && !(name == "mscorlib") && !(name == "netstandard") && !name.StartsWith("XUnity")) { return name.StartsWith("BepInEx"); } return true; } private static string NameOf(Assembly assembly) { if (Names.TryGetValue(assembly, out var value)) { return value; } foreach (PluginInfo value2 in Chainloader.PluginInfos.Values) { if ((Object)(object)value2.Instance != (Object)null && ((object)value2.Instance).GetType().Assembly == assembly) { value = value2.Metadata.Name; break; } } if (value == null) { string name = assembly.GetName().Name; value = ((name == "Assembly-CSharp" || name == "Assembly-CSharp-firstpass") ? "Game" : name); } if (Chainloader.PluginInfos.Values.All((PluginInfo p) => (Object)(object)p.Instance != (Object)null)) { Names[assembly] = value; } return value; } } internal static class Seen { private static readonly Dictionary<string, HashSet<string>> Lines = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase); private static int _count; internal static void Add(string owner, string line) { if (_count < 30000 && line.Length <= 2000 && Engine.HasLetter(line)) { owner = (string.IsNullOrEmpty(owner) ? "Game" : owner); if (!Lines.TryGetValue(owner, out var value)) { value = (Lines[owner] = new HashSet<string>(StringComparer.Ordinal)); } if (value.Add(line)) { _count++; } } } internal static IEnumerable<string> Of(string mod) { if (!Lines.TryGetValue(mod, out var value)) { return Enumerable.Empty<string>(); } return value; } } internal static class Untranslated { private static readonly Dictionary<string, HashSet<string>> Lines = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase); private static readonly Regex NoisePattern = new Regex("^(?:v\\d+(?:\\.\\d+)*(?:\\s*\\([^)]+\\))?|v\\{\\d+\\}(?:\\s*\\([^)]+\\))?|https?://\\S+|\"[^\"]+\"\\s+by\\s+.+|Copyright\\s*\\(C\\).+|\\{\\d+\\}\\s+\\{\\d+\\}\\s+\\S+\\s+H\\{\\d+\\}|[A-Za-z]\\{\\d+\\}|[A-Z]{1,2}|AM|PM|Tab)$", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex AssetExt = new Regex("\\.(?:wav|mp3|mp\\{\\d+\\}|aif|aiff|ogg|jpg|jpeg|png|m4a|m\\{\\d+\\}a)\\b", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly HashSet<string> PlaceholderNoise = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "New Text", "Text", "Option A", "[POPOVER PLACEHOLDER]", "Very cool config description", "This is a very cool mod description that you can add!", "My Hex Color Config", "LethalConfig v{1}", "LethalConfig", "LobbyImprovements", "BaconTranslations" }; private static HashSet<string> _pluginNames; private static int _pluginCount = -1; internal static void Clear() { Lines.Clear(); } private static bool IsPluginIdentifier(string text) { int count = Chainloader.PluginInfos.Count; if (_pluginNames == null || _pluginCount != count) { _pluginCount = count; _pluginNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (PluginInfo value in Chainloader.PluginInfos.Values) { BepInPlugin metadata = value.Metadata; if (!string.IsNullOrEmpty((metadata != null) ? metadata.Name : null)) { _pluginNames.Add(value.Metadata.Name); } BepInPlugin metadata2 = value.Metadata; if (!string.IsNullOrEmpty((metadata2 != null) ? metadata2.GUID : null)) { _pluginNames.Add(value.Metadata.GUID); } } try { if (Directory.Exists(Paths.PatcherPluginPath)) { string[] files = Directory.GetFiles(Paths.PatcherPluginPath, "*.dll", SearchOption.AllDirectories); foreach (string path in files) { _pluginNames.Add(Path.GetFileNameWithoutExtension(path)); } } } catch (Exception) { } } return _pluginNames.Contains(text); } internal static void Remove(string owner, string text) { if (string.IsNullOrEmpty(text)) { return; } owner = (string.IsNullOrEmpty(owner) ? "Game" : owner); if (!Lines.TryGetValue(owner, out var value)) { return; } string[] array = text.Split('\n'); for (int i = 0; i < array.Length; i++) { string text2 = array[i].Trim(); if (text2.Length > 0) { value.Remove(text2); } } } internal static bool IsNoise(string line) { string text = line.Trim(); if (text.Length < 2) { return true; } if (PlaceholderNoise.Contains(text)) { return true; } if (NoisePattern.IsMatch(text)) { return true; } if (AssetExt.IsMatch(text)) { return true; } if (IsPluginIdentifier(text)) { return true; } if ((text.StartsWith("Microphone (", StringComparison.OrdinalIgnoreCase) || text.StartsWith("Mikrofon (", StringComparison.OrdinalIgnoreCase)) && text.EndsWith(")")) { return true; } return false; } internal static void Add(string owner, string line) { if (!string.IsNullOrEmpty(line) && line.Length >= 2 && line.Length <= 2000 && Engine.HasLetter(line) && !IsNoise(line)) { owner = (string.IsNullOrEmpty(owner) ? "Game" : owner); if (!Lines.TryGetValue(owner, out var value)) { value = (Lines[owner] = new HashSet<string>(StringComparer.Ordinal)); } if (value.Count < 2000) { value.Add(line); } } } internal static int CountOf(string mod) { if (string.IsNullOrEmpty(mod) || !Lines.TryGetValue(mod, out var value)) { return 0; } return value.Count; } internal static int TotalLines() { return Lines.Values.Sum((HashSet<string> s) => s.Count); } internal static int TotalMods() { return Lines.Count((KeyValuePair<string, HashSet<string>> p) => p.Value.Count > 0); } internal static List<KeyValuePair<string, int>> All() { return (from p in (from p in Lines where p.Value.Count > 0 orderby (!(p.Key == "Game")) ? ((p.Key == "Terminal") ? 1 : 2) : 0 select p).ThenBy<KeyValuePair<string, HashSet<string>>, string>((KeyValuePair<string, HashSet<string>> p) => p.Key, StringComparer.OrdinalIgnoreCase) select new KeyValuePair<string, int>(p.Key, p.Value.Count)).ToList(); } internal static IEnumerable<string> Of(string mod) { if (string.IsNullOrEmpty(mod) || !Lines.TryGetValue(mod, out var value)) { return Enumerable.Empty<string>(); } return value; } } internal static class Missing { internal const string Folder = "_missing"; private static string _folder; private static readonly HashSet<string> Known = new HashSet<string>(StringComparer.Ordinal); private static readonly Dictionary<string, StringBuilder> Pending = new Dictionary<string, StringBuilder>(StringComparer.OrdinalIgnoreCase); private static int _count; internal static void Use(string language) { Flush(); Known.Clear(); _count = 0; _folder = ((language == null) ? null : Path.Combine(Languages.OwnRoot, language, "_missing")); if (_folder == null || !Directory.Exists(_folder)) { return; } string[] files = Directory.GetFiles(_folder, "*.txt"); for (int i = 0; i < files.Length; i++) { foreach (string item in File.ReadLines(files[i], Encoding.UTF8)) { int num = item.LastIndexOf('='); if (num > 0) { Known.Add(Dictionary.Unescape(item.Substring(0, num))); } } } } internal static void Note(string text, string owner) { if (_folder != null && Plugin.CollectMissing.Value && _count < 5000 && text.Length <= 2000 && Engine.HasLetter(text) && !Untranslated.IsNoise(text) && Known.Add(text)) { _count++; char[] invalid = Path.GetInvalidFileNameChars(); string key = new string((owner ?? "Game").Where((char c) => Array.IndexOf(invalid, c) < 0).ToArray()); if (!Pending.TryGetValue(key, out var value)) { value = (Pending[key] = new StringBuilder()); } value.Append(Dictionary.Escape(text)).Append("=\n"); } } internal static void Flush() { if (Pending.Count == 0 || _folder == null) { Pending.Clear(); return; } try { Directory.CreateDirectory(_folder); foreach (KeyValuePair<string, StringBuilder> item in Pending) { File.AppendAllText(Path.Combine(_folder, ((item.Key.Length > 0) ? item.Key : "Game") + ".txt"), item.Value.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Can't write missing lines: " + ex.Message)); } Pending.Clear(); } } internal static class Fonts { private static bool _tried; private static TMP_FontAsset _gameFont; private static readonly HashSet<char> Pending = new HashSet<char>(); internal static void SetGameFont(TMP_FontAsset font) { _gameFont = font; if (Pending.Count > 0) { EnsureFallback(Pending.ToList()); } } internal static void EnsureFallback(IEnumerable<char> letters) { if (_tried) { return; } if ((Object)(object)_gameFont == (Object)null) { Pending.UnionWith(letters); return; } Pending.Clear(); List<char> list = letters.Where((char c) => !char.IsWhiteSpace(c) && !_gameFont.HasCharacter(c, true, true)).Distinct().Take(12) .ToList(); if (list.Count == 0) { return; } _tried = true; Plugin.Log.LogInfo((object)("The game's font lacks " + new string(list.ToArray()) + "; adding a font for them")); try { Font val = null; string[] array = new string[2] { "LegacyRuntime.ttf", "Arial.ttf" }; foreach (string text in array) { try { val = Resources.GetBuiltinResource<Font>(text); } catch (Exception) { } if ((Object)(object)val != (Object)null) { break; } } TMP_FontAsset val2 = (((Object)(object)val == (Object)null) ? null : TMP_FontAsset.CreateFontAsset(val)); if ((Object)(object)val2 == (Object)null) { val = Font.CreateDynamicFontFromOSFont(Plugin.FallbackFont.Value, 64); val2 = (((Object)(object)val == (Object)null) ? null : TMP_FontAsset.CreateFontAsset(val)); } if ((Object)(object)val2 == (Object)null) { Plugin.Log.LogWarning((object)("No font for " + new string(list.ToArray()) + " could be loaded; those letters show as boxes")); return; } ((Object)val2).name = "BaconTranslations " + ((Object)val).name; List<TMP_FontAsset> list2 = TMP_Settings.fallbackFontAssets; if (list2 == null) { list2 = new List<TMP_FontAsset>(); Traverse.Create((object)TMP_Settings.instance).Field("m_fallbackFontAssets").SetValue((object)list2); } list2.Add(val2); foreach (char item in list) { val2.TryAddCharacters(item.ToString(), false); } char[] array2 = list.Where((char c) => !_gameFont.HasCharacter(c, true, false)).ToArray(); Plugin.Log.LogInfo((object)("Missing letters come from " + ((Object)val).name + ((array2.Length != 0) ? ("; it can't draw " + new string(array2) + " either") : ""))); } catch (Exception ex2) { Plugin.Log.LogWarning((object)("The fallback font failed: " + ex2.Message)); } } } internal static class Languages { internal const string YourFiles = "Your files"; internal static List<Source> Files = new List<Source>(); internal static string ActiveName = "Original"; internal static CultureInfo Culture = CultureInfo.InvariantCulture; internal static string OwnRoot => Path.Combine(Paths.ConfigPath, "BaconTranslations"); internal static string Raw(string line) { return Files.Select((Source s) => s.Lines.Raw(line)).FirstOrDefault((string r) => r != null); } private static string ModOf(string folder) { string text = folder.Substring(Paths.PluginPath.Length).TrimStart(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar)[0]; int num = text.IndexOf('-'); if (num <= 0 || num >= text.Length - 1) { return text; } return text.Substring(num + 1); } private static List<string> Roots() { List<string> list = new List<string>(); try { list.AddRange(Directory.GetDirectories(Paths.PluginPath, "BaconTranslations", SearchOption.AllDirectories)); } catch (Exception ex) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("Can't look for translation mods: " + ex.Message)); } } Directory.CreateDirectory(OwnRoot); list.Add(OwnRoot); return list; } private static IEnumerable<string> Folders(string language) { return from d in Roots().SelectMany(Directory.GetDirectories) where string.Equals(Path.GetFileName(d), language, StringComparison.OrdinalIgnoreCase) select d; } internal static IEnumerable<string> Found() { return from n in (from n in Roots().SelectMany(Directory.GetDirectories).Select(Path.GetFileName) where !n.StartsWith("_") select n).Distinct<string>(StringComparer.OrdinalIgnoreCase) orderby n select n; } internal static IEnumerable<string> All() { List<string> list = Found().ToList(); string xunity = XUnityBridge.LanguageFolder(); if (xunity != null && !list.Any((string n) => SameLanguage(n, xunity))) { list.Add(xunity); } return list.OrderBy<string, string>((string n) => n, StringComparer.OrdinalIgnoreCase); } internal static string Named(string language) { string text = CultureOf(language)?.EnglishName; if (text == null || string.Equals(text, language, StringComparison.OrdinalIgnoreCase)) { return language; } return language + " (" + text + ")"; } private static IEnumerable<string> FilesIn(string folder) { return (from f in Directory.GetFiles(folder, "*.txt", SearchOption.AllDirectories) where f.IndexOf(Path.DirectorySeparatorChar + "_missing" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) < 0 select f).OrderBy<string, string>((string f) => f, StringComparer.OrdinalIgnoreCase); } internal static void Select() { string value = Plugin.Language.Value; Files = new List<Source>(); ActiveName = "Original"; Culture = CultureInfo.InvariantCulture; Engine.Clear(); if (string.IsNullOrEmpty(value) || value == "Original") { Missing.Use(null); return; } ActiveName = value; Culture = CultureOf(value) ?? CultureInfo.InvariantCulture; string text = Path.Combine(OwnRoot, value); List<string> list = (from f in Folders(value) where !f.StartsWith(OwnRoot, StringComparison.OrdinalIgnoreCase) select f).ToList(); string text2 = Folders(value).FirstOrDefault((string f) => f.StartsWith(OwnRoot, StringComparison.OrdinalIgnoreCase)); list.Insert(0, text2 ?? text); HashSet<char> hashSet = new HashSet<char>(); List<string> list2 = new List<string>(); foreach (string item in list) { bool flag = item.StartsWith(OwnRoot, StringComparison.OrdinalIgnoreCase); Source source = new Source { Name = (flag ? "Your files" : ModOf(item)), Kind = (flag ? "asked first" : "translation mod"), Folder = item, Lines = new Dictionary() }; if (Directory.Exists(item)) { foreach (string item2 in FilesIn(item)) { try { source.Lines.Load(item2); string key = Regex.Replace(Path.GetFileNameWithoutExtension(item2), "^z+[-_]", ""); if (!source.ByMod.TryGetValue(key, out var value2)) { value2 = (source.ByMod[key] = new Dictionary()); } value2.Load(item2); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Can't read " + item2 + ": " + ex.Message)); } } } Files.Add(source); hashSet.UnionWith(source.Lines.Letters); list2.Add($"{source.Name} {source.Lines.Count}" + ((source.Lines.Skipped > 0) ? $" ({source.Lines.Skipped} split-regex lines skipped)" : "")); } Missing.Use(value); if (hashSet.Count > 0) { Fonts.EnsureFallback(hashSet); } Plugin.Log.LogInfo((object)(value + ": lines from " + string.Join(", ", list2))); } internal static CultureInfo CultureOf(string name) { if (string.IsNullOrEmpty(name)) { return null; } CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.NeutralCultures); foreach (CultureInfo cultureInfo in cultures) { if (cultureInfo.Name.Length > 0 && (string.Equals(cultureInfo.Name, name, StringComparison.OrdinalIgnoreCase) || string.Equals(cultureInfo.NativeName, name, StringComparison.OrdinalIgnoreCase) || string.Equals(cultureInfo.EnglishName, name, StringComparison.OrdinalIgnoreCase))) { return cultureInfo; } } return null; } internal static bool SameLanguage(string a, string b) { if (string.Equals(a, b, StringComparison.OrdinalIgnoreCase)) { return true; } CultureInfo cultureInfo = CultureOf(a); if (cultureInfo != null) { return object.Equals(cultureInfo, CultureOf(b)); } return false; } internal static string FolderFor(string code) { foreach (string item in Found()) { if (SameLanguage(item, code)) { return item; } } CultureInfo cultureInfo = CultureOf(code); if (cultureInfo == null) { return code; } string nativeName = cultureInfo.NativeName; if (nativeName.Length <= 0) { return code; } return char.ToUpper(nativeName[0], cultureInfo) + nativeName.Substring(1); } } internal sealed class Dictionary { private sealed class Pattern { internal Regex Regex; internal string Value; internal string Prefix; internal string Template; } private readonly Dictionary<string, string> _exact = new Dictionary<string, string>(StringComparer.Ordinal); private readonly Dictionary<string, string> _upper = new Dictionary<string, string>(StringComparer.Ordinal); private readonly List<Pattern> _patterns = new List<Pattern>(); internal int Skipped; internal readonly HashSet<char> Letters = new HashSet<char>(); private static readonly Regex Placeholder = new Regex("\\{(\\d)\\}", RegexOptions.Compiled); private static readonly Regex Numbers = new Regex("\\d+(?:[.,]\\d+)*", RegexOptions.Compiled); internal int Count => _exact.Count + _patterns.Count; private string Inner(string part) { string text = part.Trim(); if (text.Length == 0 || !Engine.HasLetter(text)) { return null; } if (_exact.TryGetValue(text, out var value)) { return part.Replace(text, value); } if (Engine.IsCaps(text) && _upper.TryGetValue(text, out value)) { return part.Replace(text, value.ToUpper(Languages.Culture)); } if (text == text.ToLowerInvariant() && _upper.TryGetValue(text.ToUpperInvariant(), out value)) { return part.Replace(text, value.ToLower(Languages.Culture)); } if (Engine.HasDigit(text)) { List<string> numbers = new List<string>(); string key = Numbers.Replace(text, delegate(Match m) { numbers.Add(m.Value); return "{" + numbers.Count + "}"; }); if (numbers.Count <= 9 && (_exact.TryGetValue(key, out value) || (Engine.IsCaps(text) && _upper.TryGetValue(key, out value)))) { return part.Replace(text, Fill(value, numbers)); } } return null; } internal void Load(string file) { foreach (string item in File.ReadLines(file, Encoding.UTF8)) { string text = item.TrimEnd('\r'); string text2 = text.TrimStart(); if (text2.Length == 0 || text2.StartsWith("//") || text2.StartsWith("#")) { continue; } if (text2.StartsWith("sr:")) { Skipped++; continue; } if (text2.StartsWith("r:\"")) { int num = text2.IndexOf("\"=", 3, StringComparison.Ordinal); if (num < 0) { continue; } string text3 = Unescape(text2.Substring(num + 2)).Trim(); if (text3.Length != 0) { try { _patterns.Add(new Pattern { Regex = new Regex(text2.Substring(3, num - 3), RegexOptions.CultureInvariant), Value = text3, Prefix = null }); Note(text3); } catch (ArgumentException ex) { Plugin.Log.LogWarning((object)(Path.GetFileName(file) + ": bad pattern " + text2.Substring(0, num + 1) + ": " + ex.Message)); } } continue; } int num2 = Separator(text); if (num2 <= 0) { continue; } string text4 = Unescape(text.Substring(0, num2)).Trim(); string text5 = Unescape(text.Substring(num2 + 1)).Trim(); if (text4.Length != 0 && text5.Length != 0) { _exact[text4] = text5; _upper[text4.ToUpperInvariant()] = text5; Note(text5); if (Placeholder.IsMatch(text4)) { AddPlaceholderPattern(text4, text5); } } } } private void Note(string text) { foreach (char c in text) { if (c > '\u007f') { Letters.Add(c); } } } private void AddPlaceholderPattern(string key, string value) { string[] array = Placeholder.Split(key); StringBuilder stringBuilder = new StringBuilder("^"); for (int i = 0; i < array.Length; i++) { stringBuilder.Append((i % 2 == 0) ? Regex.Escape(array[i]) : ("(?<p" + array[i] + ">.+?)")); } stringBuilder.Append('$'); _patterns.Add(new Pattern { Regex = new Regex(stringBuilder.ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant), Value = Placeholder.Replace(value.Replace("$", "$$"), (Match m) => "${p" + m.Groups[1].Value + "}"), Prefix = array[0], Template = value }); } private static int Separator(string line) { for (int i = 0; i < line.Length; i++) { if (line[i] == '\\') { i++; } else if (line[i] == '=') { return i; } } return -1; } internal static string Unescape(string s) { if (s.IndexOf('\\') < 0) { return s; } StringBuilder stringBuilder = new StringBuilder(s.Length); for (int i = 0; i < s.Length; i++) { if (s[i] != '\\' || i + 1 == s.Length) { stringBuilder.Append(s[i]); continue; } char c = s[++i]; switch (c) { case 'n': stringBuilder.Append('\n'); break; case 'r': stringBuilder.Append('\r'); break; case 't': stringBuilder.Append('\t'); break; case '=': case '\\': stringBuilder.Append(c); break; default: stringBuilder.Append('\\').Append(c); break; } } return stringBuilder.ToString(); } internal static string Escape(string s) { return s.Replace("\\", "\\\\").Replace("=", "\\=").Replace("\r", "\\r") .Replace("\n", "\\n") .Replace("\t", "\\t"); } internal string Lookup(string s, out string template) { template = null; if (_exact.TryGetValue(s, out var value)) { return value; } bool flag = Engine.IsCaps(s); if (flag && _upper.TryGetValue(s, out value)) { return value.ToUpper(Languages.Culture); } if (Engine.HasDigit(s)) { List<string> numbers = new List<string>(); template = Numbers.Replace(s, delegate(Match match) { numbers.Add(match.Value); return "{" + numbers.Count + "}"; }); if (numbers.Count <= 9) { if (_exact.TryGetValue(template, out value)) { return Fill(value, numbers); } if (flag && _upper.TryGetValue(template, out value)) { return Fill(value, numbers).ToUpper(Languages.Culture); } } } foreach (Pattern pattern in _patterns) { if (!string.IsNullOrEmpty(pattern.Prefix) && !s.StartsWith(pattern.Prefix, StringComparison.OrdinalIgnoreCase)) { continue; } Match m = pattern.Regex.Match(s); if (m.Success && m.Length == s.Length) { string text = ((pattern.Prefix == null) ? m.Result(pattern.Value) : Placeholder.Replace(pattern.Template, delegate(Match h) { string value2 = m.Groups["p" + h.Groups[1].Value].Value; return Inner(value2) ?? value2; })); return (flag && pattern.Prefix != null) ? text.ToUpper(Languages.Culture) : text; } } return null; } internal string Raw(string key) { if (_exact.TryGetValue(key, out var value)) { return value; } if (!_upper.TryGetValue(key.ToUpperInvariant(), out value)) { return null; } return value; } private static string Fill(string value, List<string> numbers) { return Placeholder.Replace(value, delegate(Match m) { int num = m.Groups[1].Value[0] - 49; return (num < 0 || num >= numbers.Count) ? m.Value : numbers[num]; }); } } internal sealed class Panel : MonoBehaviour { private const float Width = 600f; private const float LanguagesWidth = 200f; private const float ModsHeight = 250f; private const float ButtonHeight = 17f; private const float TitleSize = 15f; private const float HeadingSize = 11.5f; private const float TextSize = 10.5f; private const float SmallSize = 9f; private static readonly Color Orange = new Color(1f, 0.42f, 0.13f); private static readonly Color Dim = new Color(1f, 0.55f, 0.32f, 0.85f); private static readonly Color Fill = new Color(0.085f, 0.012f, 0.01f, 0.98f); private static readonly Color Border = new Color(0.72f, 0.05f, 0.04f); private static readonly Color Shade = new Color(0f, 0f, 0f, 0.6f); private static readonly Color ButtonOff = new Color(1f, 0.42f, 0.13f, 0.14f); private static readonly Color ButtonHover = new Color(1f, 0.42f, 0.13f, 0.38f); private static Panel _instance; private MenuManager _menu; private TMP_FontAsset _font; private GameObject _button; private GameObject _window; private RectTransform _frame; private TextMeshProUGUI _buttonLabel; private TextMeshProUGUI _status; private Transform _languages; private Transform _mods; private Button _shrink; private Button _collect; private static Sprite _globe; private TextMeshProUGUI _saved; private TextMeshProUGUI _path; private TextMeshProUGUI _sourcesTitle; private string _mod; [HarmonyPatch(typeof(MenuManager), "Start")] [HarmonyPostfix] private static void Build(MenuManager __instance) { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Expected O, but got Unknown try { if (!__instance.isInitScene && !((Object)(object)__instance.menuButtons == (Object)null) && !((Object)(object)__instance.lobbyNameInputField == (Object)null)) { Canvas componentInParent = __instance.menuButtons.GetComponentInParent<Canvas>(); if (!((Object)(object)componentInParent == (Object)null)) { GameObject obj = NewObject("BaconTranslations Language", ((Component)componentInParent.rootCanvas).transform); Stretch((RectTransform)obj.transform); _instance = obj.AddComponent<Panel>(); _instance._menu = __instance; _instance._font = __instance.lobbyNameInputField.textComponent.font; TMP_Text componentInChildren = __instance.menuButtons.GetComponentInChildren<TMP_Text>(true); Fonts.SetGameFont(((Object)(object)componentInChildren != (Object)null) ? componentInChildren.font : _instance._font); _instance.BuildButton(); _instance.BuildWindow(); } } } catch (Exception arg) { Plugin.Log.LogWarning((object)$"The LANGUAGE button failed: {arg}"); } } internal static void RefreshIfOpen() { if ((Object)(object)_instance != (Object)null && _instance._window.activeSelf) { _instance.Refresh(); } } private void LateUpdate() { bool flag = (Object)(object)_menu != (Object)null && (Object)(object)_menu.menuButtons != (Object)null && _menu.menuButtons.activeInHierarchy && ((Object)(object)_menu.HostSettingsScreen == (Object)null || !_menu.HostSettingsScreen.activeInHierarchy); if (_button.activeSelf != (flag && !_window.activeSelf)) { _button.SetActive(flag && !_window.activeSelf); } if (_window.activeSelf && ((Component)this).transform.GetSiblingIndex() != ((Component)this).transform.parent.childCount - 1) { ((Component)this).transform.SetAsLastSibling(); } string text = ShownName().ToUpperInvariant(); if (((TMP_Text)_buttonLabel).text != text) { ((TMP_Text)_buttonLabel).text = text; } } private static string ShownName() { return Plugin.Language.Value; } private void BuildButton() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Expected O, but got Unknown //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Unknown result type (might be due to invalid IL or missing references) _button = NewObject("Button", ((Component)this).transform); RectTransform val = (RectTransform)_button.transform; Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor(1f, 1f); val.pivot = val2; Vector2 anchorMin = (val.anchorMax = val2); val.anchorMin = anchorMin; val.anchoredPosition = new Vector2(-10f, -8f); HorizontalLayoutGroup obj = _button.AddComponent<HorizontalLayoutGroup>(); ((LayoutGroup)obj).padding = new RectOffset(6, 9, 4, 4); ((HorizontalOrVerticalLayoutGroup)obj).spacing = 6f; ((LayoutGroup)obj).childAlignment = (TextAnchor)3; bool childControlWidth = (((HorizontalOrVerticalLayoutGroup)obj).childControlHeight = true); ((HorizontalOrVerticalLayoutGroup)obj).childControlWidth = childControlWidth; childControlWidth = (((HorizontalOrVerticalLayoutGroup)obj).childForceExpandHeight = false); ((HorizontalOrVerticalLayoutGroup)obj).childForceExpandWidth = childControlWidth; ContentSizeFitter obj2 = _button.AddComponent<ContentSizeFitter>(); FitMode horizontalFit = (FitMode)2; obj2.verticalFit = (FitMode)2; obj2.horizontalFit = horizontalFit; Button obj3 = _button.AddComponent<Button>(); ((Selectable)obj3).targetGraphic = (Graphic)(object)_button.AddComponent<Image>(); ((UnityEvent)obj3.onClick).AddListener(new UnityAction(Open)); GameObject obj4 = NewObject("Globe", _button.transform); Image obj5 = obj4.AddComponent<Image>(); obj5.sprite = Globe(); ((Graphic)obj5).color = Orange; ((Graphic)obj5).raycastTarget = false; LayoutElement obj6 = obj4.AddComponent<LayoutElement>(); float num = (obj6.minHeight = 18f); float num3 = (obj6.preferredHeight = num); float preferredWidth = (obj6.minWidth = num3); obj6.preferredWidth = preferredWidth; _buttonLabel = NewText(_button.transform, "", 14.5f, Orange); TextHooks.Exclude((TMP_Text)(object)_buttonLabel, ""); Outline obj7 = _button.AddComponent<Outline>(); ((Shadow)obj7).effectColor = Border; ((Shadow)obj7).effectDistance = new Vector2(1f, -1f); ColorBlock colors = ((Selectable)obj3).colors; ((ColorBlock)(ref colors)).normalColor = new Color(0.16f, 0.035f, 0.02f, 1f); Color val4 = default(Color); ((Color)(ref val4))..ctor(0.36f, 0.11f, 0.04f, 1f); ((ColorBlock)(ref colors)).selectedColor = val4; ((ColorBlock)(ref colors)).highlightedColor = val4; ((ColorBlock)(ref colors)).pressedColor = Orange; ((ColorBlock)(ref colors)).colorMultiplier = 1f; ((Selectable)obj3).colors = colors; } private static Sprite Globe() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_globe != (Object)null) { return _globe; } Texture2D val = new Texture2D(48, 48, (TextureFormat)4, false) { filterMode = (FilterMode)1, wrapMode = (TextureWrapMode)1 }; Color32[] array = (Color32[])(object)new Color32[2304]; float num = 23.5f; float num2 = 22f; float w = 1.7f; for (int i = 0; i < 48; i++) { for (int j = 0; j < 48; j++) { float num3 = (float)j - num; float num4 = (float)i - num; float num5 = Mathf.Sqrt(num3 * num3 + num4 * num4); float num6 = Line(num5 - num2); if (num5 < num2) { num6 = Mathf.Max(num6, Line(num4)); float num7 = num2 * 0.55f; num6 = Mathf.Max(num6, Line(Mathf.Abs(num4) - num7) * 0.9f); num6 = Mathf.Max(num6, Line(num3)); float num8 = Mathf.Sqrt(num3 * num3 / (num2 * num2 * 0.2f) + num4 * num4 / (num2 * num2)) * num2; num6 = Mathf.Max(num6, Line(num8 - num2 * 0.98f)); } array[i * 48 + j] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, (byte)(num6 * 255f)); } } val.SetPixels32(array); val.Apply(); _globe = Sprite.Create(val, new Rect(0f, 0f, 48f, 48f), new Vector2(0.5f, 0.5f), 100f); ((Object)_globe).name = "BaconTranslations globe"; return _globe; float Line(float distance) { return Mathf.Clamp01(1f - Mathf.Abs(distance) / w); } } private void BuildWindow() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Expected O, but got Unknown //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Expected O, but got Unknown //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_02f1: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Unknown result type (might be due to invalid IL or missing references) _window = NewObject("Window", ((Component)this).transform); RectTransform val = (RectTransform)_window.transform; Stretch(val); val.offsetMin = new Vector2(-100f, -100f); val.offsetMax = new Vector2(100f, 100f); ((Graphic)_window.AddComponent<Image>()).color = Shade; GameObject val2 = NewObject("Frame", _window.transform); _frame = (RectTransform)val2.transform; RectTransform frame = _frame; RectTransform frame2 = _frame; RectTransform frame3 = _frame; Vector2 val3 = default(Vector2); ((Vector2)(ref val3))..ctor(0.5f, 0.5f); frame3.pivot = val3; Vector2 anchorMin = (frame2.anchorMax = val3); frame.anchorMin = anchorMin; _frame.sizeDelta = new Vector2(600f, 0f); MakeFrame(val2); ((LayoutGroup)NewVertical(val2, 7f)).padding = new RectOffset(14, 14, 10, 10); val2.AddComponent<ContentSizeFitter>().verticalFit = (FitMode)2; NewText(val2.transform, "LANGUAGE AND TRANSLATIONS", 15f, Orange); Transform obj = NewRow(val2.transform, 18f); ((LayoutGroup)((Component)obj).GetComponent<HorizontalLayoutGroup>()).childAlignment = (TextAnchor)0; Transform parent = NewColumn(obj, 200f, 4f); Transform parent2 = NewColumn(obj, 354f, 4f); NewText(parent, "LANGUAGE", 11.5f, Orange); _languages = NewObject("Languages", parent).transform; NewVertical(((Component)_languages).gameObject, 3f); ((TMP_Text)NewText(parent, "OPTIONS", 11.5f, Orange)).margin = new Vector4(0f, 6f, 0f, 0f); _shrink = NewButton(parent, "", 0f, delegate { Plugin.Shrink.Value = !Plugin.Shrink.Value; Runner.ApplyNow(reload: false); }); _collect = NewButton(parent, "", 0f, delegate { Plugin.CollectMissing.Value = !Plugin.CollectMissing.Value; Runner.ApplyNow(reload: false); }); _status = NewWrapped(parent, ""); ((TMP_Text)_status).margin = new Vector4(0f, 6f, 0f, 0f); _sourcesTitle = NewText(parent2, "", 11.5f, Orange); NewWrapped(parent2, "Each source of this language, and what it translates. A switch off leaves that mod to the next source, or to its own text. Your files are asked first."); _mods = NewScrollList(parent2, 250f); ((TMP_Text)NewText(val2.transform, "TRANSLATION FILES", 11.5f, Orange)).margin = new Vector4(0f, 6f, 0f, 0f); NewWrapped(val2.transform, "Click a mod's name, then COPY PATH: its .txt file in your files is made with every text of that mod seen so far, as \"text=\" lines. Write the translation after each =, in any text editor. Saving the file updates the game at once. A translation the same as the text keeps it as it is, also against XUnity."); _saved = NewWrapped(val2.transform, ""); ((Graphic)_saved).color = Orange; Transform parent3 = NewRow(val2.transform, 6f); _path = NewWrapped(parent3, ""); ((Component)_path).gameObject.AddComponent<LayoutElement>().flexibleWidth = 1f; NewButton(parent3, "COPY PATH", 104f, CopyPath); Transform val5 = NewRow(val2.transform, 4f); ((LayoutGroup)((Component)val5).GetComponent<HorizontalLayoutGroup>()).childAlignment = (TextAnchor)5; NewObject("Space", val5).AddComponent<LayoutElement>().flexibleWidth = 1f; NewButton(val5, "RELOAD", 86f, Reload); NewButton(val5, "DONE", 80f, Close); _window.SetActive(false); } private void Reload() { Runner.ApplyNow(reload: true); ((TMP_Text)_saved).text = "Reloaded languages and translation files."; } private void ExportUntranslated() { string text = Folder(); if (text == null) { ((TMP_Text)_saved).text = "Pick a language first: its folder is made then."; return; } int num = 0; int num2 = 0; foreach (KeyValuePair<string, int> item2 in Untranslated.All()) { try { string path = FileFor(text, item2.Key); List<string> list2; if (!File.Exists(path)) { List<string> list = new List<string>(); list.Add("// " + item2.Key + " in " + Languages.ActiveName + ". Write the translation after each =; lines left empty are skipped."); list2 = list; } else { list2 = File.ReadAllLines(path, Encoding.UTF8).ToList(); } List<string> list3 = list2; HashSet<string> hashSet = new HashSet<string>(list3.Select(delegate(string l) { int num4 = l.IndexOf('='); return (num4 <= 0) ? l : l.Substring(0, num4 + 1); })); int num3 = 0; foreach (string item3 in Untranslated.Of(item2.Key).OrderBy<string, string>((string l) => l, StringComparer.OrdinalIgnoreCase)) { string item = Dictionary.Escape(item3) + "="; if (hashSet.Add(item)) { list3.Add(item); num3++; } } if (num3 > 0 || !File.Exists(path)) { File.WriteAllLines(path, list3, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); num++; num2 += num3; } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Couldn't export " + item2.Key + ": " + ex.Message)); } } GUIUtility.systemCopyBuffer = text; ((TMP_Text)_saved).text = $"Exported {num2} untranslated lines into {num} files; folder path copied."; } private static string FileFor(string folder, string mod) { char[] invalid = Path.GetInvalidFileNameChars(); return Path.Combine(folder, new string(mod.Where((char c) => Array.IndexOf(invalid, c) < 0).ToArray()) + ".txt"); } private void CopyPath() { string text = Folder(); if (text == null) { ((TMP_Text)_saved).text = "Pick a language first: its folder is made then."; return; } if (_mod == null) { GUIUtility.systemCopyBuffer = text; ((TMP_Text)_saved).text = "The folder's path is copied: paste it into File Explorer's address bar."; return; } try { string text2 = FileFor(text, _mod); List<string> list2; if (!File.Exists(text2)) { List<string> list = new List<string>(); list.Add("// " + _mod + " in " + Languages.ActiveName + ". Write the translation after each =; lines left empty are skipped."); list2 = list; } else { list2 = File.ReadAllLines(text2, Encoding.UTF8).ToList(); } List<string> list3 = list2; HashSet<string> hashSet = new HashSet<string>(list3.Select(delegate(string l) { int num2 = l.IndexOf('='); return (num2 <= 0) ? l : l.Substring(0, num2 + 1); })); int num = 0; foreach (string item in Seen.Of(_mod).OrderBy<string, string>((string l) => l, StringComparer.OrdinalIgnoreCase)) { string text3 = Dictionary.Escape(item) + "="; if (hashSet.Add(text3)) { string text4 = Languages.Raw(item); list3.Add(text3 + ((text4 != null) ? Dictionary.Escape(text4) : "")); num++; } } File.WriteAllLines(text2, list3, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); GUIUtility.systemCopyBuffer = text2; ((TMP_Text)_saved).text = "Copied the path of " + Path.GetFileName(text2) + ((num > 0) ? $"; {num} lines of {_mod} seen so far were added to it, ready to fill in." : "."); } catch (Exception ex) { ((TMP_Text)_saved).text = "Couldn't write the file: " + ex.Message; } } private static string Folder() { if (Languages.ActiveName == "Original") { return null; } string text = Path.Combine(Languages.OwnRoot, Languages.ActiveName); Directory.CreateDirectory(text); return text; } private void Open() { _window.SetActive(true); Refresh(); FitOnScreen(); } private void Close() { _window.SetActive(false); } private void Update() { if (_window.activeSelf) { Keyboard current = Keyboard.current; if (current != null && ((ButtonControl)current.escapeKey).wasPressedThisFrame) { Close(); } } } private void Refresh() { //IL_058b: Unknown result type (might be due to invalid IL or missing references) //IL_05aa: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_0650: Unknown result type (might be due to invalid IL or missing references) //IL_06ce: Unknown result type (might be due to invalid IL or missing references) //IL_06dd: Unknown result type (might be due to invalid IL or missing references) //IL_0709: Unknown result type (might be due to invalid IL or missing references) //IL_03cc: Unknown result type (might be due to invalid IL or missing references) //IL_03db: Unknown result type (might be due to invalid IL or missing references) //IL_0412: Unknown result type (might be due to invalid IL or missing references) //IL_040b: Unknown result type (might be due to invalid IL or missing references) Clear(_languages); AddLanguage("Original", "Original"); foreach (string item in Languages.All()) { AddLanguage(item, Languages.Named(item)); } SetLabel(_shrink, "SHRINK LONG LINES: " + (Plugin.Shrink.Value ? "ON" : "OFF")); SetLabel(_collect, "COLLECT MISSING LINES: " + (Plugin.CollectMissing.Value ? "ON" : "OFF")); ((TMP_Text)_status).text = XUnityBridge.Status(); string text = Folder(); TextHooks.Exclude((TMP_Text)(object)_path, (text == null) ? "BepInEx/config/BaconTranslations/<language>/" : text); Clear(_mods); bool flag = Languages.ActiveName == "Original"; ((TMP_Text)_sourcesTitle).text = (flag ? "SOURCES" : ("SOURCES FOR " + Languages.Named(Languages.ActiveName).ToUpperInvariant())); if (flag) { NewWrapped(_mods, "Every mod shows its own text. Pick a language to see what translates into it."); return; } List<Source> list = Languages.Files.ToList(); if (XUnityBridge.ServesActive) { list.Add(XUnityBridge.Source); } HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (Source item2 in list) { Source from = item2; List<KeyValuePair<string, int>> list2 = Sources.ModsOf(item2); Transform parent = NewRow(_mods, 4f); string text2 = (string.Equals(item2.Name, "Your files", StringComparison.OrdinalIgnoreCase) ? (Engine.Translate("YOUR FILES", "BaconTranslations") ?? "YOUR FILES") : item2.Name.ToUpperInvariant()); string text3 = Engine.Translate(item2.Kind, "BaconTranslations") ?? item2.Kind; TextMeshProUGUI obj = NewText(parent, "", 10.5f, Orange); TextHooks.Exclude((TMP_Text)(object)obj, text2 + " <size=80%>" + text3 + "</size>"); ((TMP_Text)obj).margin = new Vector4(0f, 4f, 0f, 0f); ((Component)obj).gameObject.AddComponent<LayoutElement>().flexibleWidth = 1f; if (list2.Count > 0) { NewButton(parent, "ALL ON", 56f, delegate { Sources.SetAll(from, on: true); }); NewButton(parent, "ALL OFF", 60f, delegate { Sources.SetAll(from, on: false); }); } if (list2.Count == 0) { NewWrapped(_mods, (item2 == Languages.Files[0]) ? "Nothing yet. Click any mod's name, then COPY PATH, to start a file for it here." : "Nothing translated yet this session."); } foreach (KeyValuePair<string, int> item3 in list2) { string name = item3.Key; hashSet.Add(name); Transform parent2 = NewRow(_mods, 6f); bool flag2 = Sources.On(from, name); Paint(NewButton(parent2, flag2 ? "ON" : "OFF", 40f, delegate { Sources.Set(from, name, !Sources.On(from, name)); Runner.ApplyNow(reload: false); }), flag2); Button obj2 = NewButton(parent2, "", 0f, delegate { _mod = (string.Equals(_mod, name, StringComparison.OrdinalIgnoreCase) ? null : name); Refresh(); }); ((Component)obj2).GetComponent<LayoutElement>().flexibleWidth = 1f; TextMeshProUGUI componentInChildren = ((Component)obj2).GetComponentInChildren<TextMeshProUGUI>(); ((TMP_Text)componentInChildren).alignment = (TextAlignmentOptions)4097; ((RectTransform)((TMP_Text)componentInChildren).transform).offsetMin = new Vector2(4f, 0f); bool flag3 = string.Equals(_mod, name, StringComparison.OrdinalIgnoreCase); Paint(obj2, flag3); if (!flag3) { ((Graphic)componentInChildren).color = (flag2 ? Orange : Dim); } int num = (flag2 ? Untranslated.CountOf(name) : 0); string text4 = Engine.Translate("lines", "BaconTranslations") ?? "lines"; string text5 = Engine.Translate("missing", "BaconTranslations") ?? "missing"; string text6 = ((item3.Value > 0 && num > 0) ? $" {item3.Value} {text4} · {num} {text5}" : ((item3.Value > 0) ? $" {item3.Value} {text4}" : ((num > 0) ? $" {num} {text5}" : ""))); TextHooks.Exclude((TMP_Text)(object)componentInChildren, name + text6); } } List<KeyValuePair<string, int>> list3 = Untranslated.All(); if (list3.Count <= 0) { return; } Transform parent3 = NewRow(_mods, 4f); TextMeshProUGUI obj3 = NewText(parent3, $"UNTRANSLATED PARTS ({list3.Count} mods, {Untranslated.TotalLines()} lines)", 10.5f, Orange); ((TMP_Text)obj3).margin = new Vector4(0f, 6f, 0f, 0f); ((Component)obj3).gameObject.AddComponent<LayoutElement>().flexibleWidth = 1f; NewButton(parent3, "EXPORT ALL", 84f, ExportUntranslated); foreach (KeyValuePair<string, int> item4 in list3) { string name2 = item4.Key; Transform parent4 = NewRow(_mods, 6f); TextMeshProUGUI obj4 = NewText(parent4, hashSet.Contains(name2) ? "PART" : "NEW", 9f, Dim); ((TMP_Text)obj4).alignment = (TextAlignmentOptions)514; LayoutElement obj5 = ((Component)obj4).gameObject.AddComponent<LayoutElement>(); float preferredWidth = (obj5.minWidth = 40f); obj5.preferredWidth = preferredWidth; Button obj6 = NewButton(parent4, "", 0f, delegate { _mod = (string.Equals(_mod, name2, StringComparison.OrdinalIgnoreCase) ? null : name2); Refresh(); }); ((Component)obj6).GetComponent<LayoutElement>().flexibleWidth = 1f; TextMeshProUGUI componentInChildren2 = ((Component)obj6).GetComponentInChildren<TextMeshProUGUI>(); ((TMP_Text)componentInChildren2).alignment = (TextAlignmentOptions)4097; ((RectTransform)((TMP_Text)componentInChildren2).transform).offsetMin = new Vector2(4f, 0f); bool flag4 = string.Equals(_mod, name2, StringComparison.OrdinalIgnoreCase); Paint(obj6, flag4); if (!flag4) { ((Graphic)componentInChildren2).color = Orange; } string arg = Engine.Translate("untranslated", "BaconTranslations") ?? "untranslated"; TextHooks.Exclude((TMP_Text)(object)componentInChildren2, $"{name2} {item4.Value} {arg}"); } } private void AddLanguage(string value, string label) { Button obj = NewButton(_languages, "", 0f, delegate { Plugin.Language.Value = value; Plugin.SaveConfig(); Runner.ApplyNow(reload: true); }); Paint(obj, Plugin.Language.Value == value); TextMeshProUGUI componentInChildren = ((Component)obj).GetComponentInChildren<TextMeshProUGUI>(); if (value == "Original") { ((TMP_Text)componentInChildren).text = label.ToUpperInvariant(); } else { TextHooks.Exclude((TMP_Text)(object)componentInChildren, label.ToUpperInvariant()); } } private void FitOnScreen() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) RectTransform val = (RectTransform)((Component)this).transform.parent; ((Transform)_frame).localScale = Vector3.one; LayoutRebuilder.ForceRebuildLayoutImmediate(_frame); Rect rect = _frame.rect; Vector2 size = ((Rect)(ref rect)).size; rect = val.rect; Vector2 val2 = ((Rect)(ref rect)).size * 0.95f; if (!(size.x <= 0f) && !(size.y <= 0f)) { float num = Mathf.Min(new float[3] { 1f, val2.x / size.x, val2.y / size.y }); ((Transform)_frame).localScale = new Vector3(num, num, 1f); } } private Transform NewScrollList(Transform parent, float height) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Expected O, but got Unknown //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Expected O, but got Unknown GameObject val = NewObject("Mods", parent); val.AddComponent<LayoutElement>().preferredHeight = height; ((Graphic)val.AddComponent<Image>()).color = new Color(0f, 0f, 0f, 0.25f); val.AddComponent<RectMask2D>(); GameObject obj = NewObject("Content", val.transform); RectTransform val2 = (RectTransform)obj.transform; val2.anchorMin = new Vector2(0f, 1f); val2.anchorMax = Vector2.one; val2.pivot = new Vector2(0.5f, 1f); Vector2 offsetMin = (val2.offsetMax = Vector2.zero); val2.offsetMin = offsetMin; ((LayoutGroup)NewVertical(obj, 3f)).padding = new RectOffset(4, 4, 4, 4); obj.AddComponent<ContentSizeFitter>().verticalFit = (FitMode)2; ScrollRect obj2 = val.AddComponent<ScrollRect>(); obj2.content = val2; obj2.viewport = (RectTransform)val.transform; obj2.horizontal = false; obj2.movementType = (MovementType)2; obj2.scrollSensitivity = 18f; return obj.transform; } private static void Clear(Transform parent) { for (int num = parent.childCount - 1; num >= 0; num--) { GameObject gameObject = ((Component)parent.GetChild(num)).gameObject; gameObject.SetActive(false); Object.Destroy((Object)(object)gameObject); } } private static void Stretch(RectTransform rect) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) rect.anchorMin = Vector2.zero; rect.anchorMax = Vector2.one; Vector2 offsetMin = (rect.offsetMax = Vector2.zero); rect.offsetMin = offsetMin; } private static GameObject NewObject(string name, Transform parent) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) }) { layer = ((Component)parent).gameObject.layer }; val.transform.SetParent(parent, false); return val; } private static void MakeFrame(GameObject target) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) ((Graphic)target.AddComponent<Image>()).color = Fill; Outline obj = target.AddComponent<Outline>(); ((Shadow)obj).effectColor = Border; ((Shadow)obj).effectDistance = new Vector2(1f, -1f); } private static VerticalLayoutGroup NewVertical(GameObject target, float spacing) { VerticalLayoutGroup obj = target.AddComponent<VerticalLayoutGroup>(); ((HorizontalOrVerticalLayoutGroup)obj).spacing = spacing; bool childControlWidth = (((HorizontalOrVerticalLayoutGroup)obj).childControlHeight = true); ((HorizontalOrVerticalLayoutGroup)obj).childControlWidth = childControlWidth; ((HorizontalOrVerticalLayoutGroup)obj).childForceExpandWidth = true; ((HorizontalOrVerticalLayoutGroup)obj).childForceExpandHeight = false; return obj; } private static Transform NewColumn(Transform parent, float width, float spacing) { GameObject obj = NewObject("Column", parent); NewVertical(obj, spacing); LayoutElement obj2 = obj.AddComponent<LayoutElement>(); float preferredWidth = (obj2.minWidth = width); obj2.preferredWidth = preferredWidth; return obj.transform; } private static Transform NewRow(Transform parent, float spacing) { GameObject obj = NewObject("Row", parent); HorizontalLayoutGroup obj2 = obj.AddComponent<HorizontalLayoutGroup>(); ((HorizontalOrVerticalLayoutGroup)obj2).spacing = spacing; ((LayoutGroup)obj2).childAlignment = (TextAnchor)3; bool childControlWidth = (((HorizontalOrVerticalLayoutGroup)obj2).childControlHeight = true); ((HorizontalOrVerticalLayoutGroup)obj2).childControlWidth = childControlWidth; childControlWidth = (((HorizontalOrVerticalLayoutGroup)obj2).childForceExpandHeight = false); ((HorizontalOrVerticalLayoutGroup)obj2).childForceExpandWidth = childControlWidth; return obj.transform; } private TextMeshProUGUI NewText(Transform parent, string text, float size, Color color) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) TextMeshProUGUI obj = NewObject("Text", parent).AddComponent<TextMeshProUGUI>(); ((TMP_Text)obj).font = _font; ((TMP_Text)obj).fontSize = size; ((Graphic)obj).color = color; ((Graphic)obj).raycastTarget = false; ((TMP_Text)obj).enableWordWrapping = false; TextHooks.SetOwner((TMP_Text)(object)obj, "BaconTranslations", text); return obj; } private TextMeshProUGUI NewWrapped(Transform parent, string text) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) TextMeshProUGUI obj = NewText(parent, text, 9f, Dim); ((TMP_Text)obj).enableWordWrapping = true; return obj; } private Button NewButton(Transform parent, string text, float width, Action onClick) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown GameObject val = NewObject("Button", parent); Button obj = val.AddComponent<Button>(); ((Selectable)obj).targetGraphic = (Graphic)(object)val.AddComponent<Image>(); ((UnityEvent)obj.onClick).AddListener((UnityAction)delegate { onClick(); }); LayoutElement val2 = val.AddComponent<LayoutElement>(); float preferredHeight = (val2.minHeight = 17f); val2.preferredHeight = preferredHeight; if (width > 0f) { preferredHeight = (val2.minWidth = width); val2.preferredWidth = preferredHeight; } TextMeshProUGUI obj2 = NewText(val.transform, text, 10.5f, Orange); ((TMP_Text)obj2).alignment = (TextAlignmentOptions)514; Stretch((RectTransform)((TMP_Text)obj2).transform); Paint(obj, selected: false); return obj; } private static void SetLabel(Button button, string text) { ((TMP_Text)((Component)button).GetComponentInChildren<TextMeshProUGUI>()).text = text; } private static void Paint(Button button, bool selected) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) ColorBlock colors = ((Selectable)button).colors; ((ColorBlock)(ref colors)).normalColor = (selected ? Orange : ButtonOff); Color highlightedColor = (((ColorBlock)(ref colors)).selectedColor = (selected ? Orange : ButtonHover)); ((ColorBlock)(ref colors)).highlightedColor = highlightedColor; ((ColorBlock)(ref colors)).pressedColor = Orange; ((ColorBlock)(ref colors)).colorMultiplier = 1f; ((Selectable)button).colors = colors; ((Graphic)((Component)button).GetComponentInChildren<TextMeshProUGUI>()).color = (selected ? Fill : Orange); ((Selectable)button).targetGraphic.CrossFadeColor(((ColorBlock)(ref colors)).normalColor, 0f, true, true); } } [BepInPlugin("bacontranslations", "BaconTranslations", "1.0.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { internal const string Guid = "bacontranslations"; internal const string Version = "1.0.1"; internal const string Original = "Original"; internal static ManualLogSource Log; internal static Plugin Instance; internal static ConfigEntry<string> Language; internal static ConfigEntry<bool> Shrink; internal static ConfigEntry<bool> CollectMissing; internal static ConfigEntry<string> FallbackFont; private void Awake() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected O, but got Unknown //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; Instance = this; Harmony val = new Harmony("bacontranslations"); XUnityBridge.Init(val); Language = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Language", "Original", new ConfigDescription("The language to show. Original shows every mod's own text, also over XUnity. The others are the language folders found in BepInEx/config/BaconTranslations and in translation mods.", (AcceptableValueBase)(object)new AcceptableLanguages(), Array.Empty<object>())); Shrink = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Shrink long lines", true, "A translated line that is longer than the original gets smaller until it fits its box."); CollectMissing = ((BaseUnityPlugin)this).Config.Bind<bool>("Translators", "Collect missing lines", false, "Writes each line of text that has no translation yet into the language's _missing folder, one file per mod, as \"original=\" lines ready to fill in."); FallbackFont = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Font for missing letters", "Arial", "A Windows font used for letters the game's fonts don't have, such as ą or ж."); Sources.Load(((BaseUnityPlugin)this).Config); val.PatchAll(typeof(TextHooks)); val.PatchAll(typeof(Panel)); Languages.Select(); Language.SettingChanged += delegate { SaveConfig(); Runner.Request(reload: true); }; Shrink.SettingChanged += delegate { SaveConfig(); Runner.Request(reload: false); }; CollectMissing.SettingChanged += delegate { SaveConfig(); if (!CollectMissing.Value) { Missing.Flush(); } Runner.Request(reload: false); }; FallbackFont.SettingChanged += delegate { SaveConfig(); }; GameObject val2 = new GameObject("BaconTranslations") { hideFlags = (HideFlags)61 }; Object.DontDestroyOnLoad((Object)val2); val2.AddComponent<Runner>(); Log.LogInfo((object)("BaconTranslations 1.0.1 loaded, showing " + Languages.ActiveName)); } internal static void SaveConfig() { if ((Object)(object)Instance == (Object)null) { return; } try { Sources.SavedAt = Time.realtimeSinceStartup; ((BaseUnityPlugin)Instance).Config.Save(); Sources.SavedAt = Time.realtimeSinceStartup; } catch (Exception ex) { ManualLogSource log = Log; if (log != null) { log.LogWarning((object)("Saving settings failed: " + ex.Message)); } } } } internal sealed class Runner : MonoBehaviour { private static readonly object Gate = new object(); private static bool _reload; private static bool _refresh; private static bool _configChanged; private static float _due; private FileSystemWatcher _files; private FileSystemWatcher _config; private float _nextFlush; internal static void Request(bool reload) { lock (Gate) { _refresh = true; _reload |= reload; _due = 0f; } } internal static void ApplyNow(bool reload) { lock (Gate) { _reload = false; _refresh = false; } try { if (reload) { Languages.Select(); } TextHooks.Refresh(); Panel.RefreshIfOpen(); } catch (Exception arg) { Plugin.Log.LogWarning((object)$"Refreshing translations failed: {arg}"); } Sources.SaveIfNeeded(); } private void Start() { try { _files = Watch(Languages.OwnRoot, "*", includeSubfolders: true, delegate { lock (Gate) { _reload = (_refresh = true); _due = -1f; } }); _config = Watch(Path.GetDirectoryName(((BaseUnityPlugin)Plugin.Instance).Config.ConfigFilePath), Path.GetFileName(((BaseUnityPlugin)Plugin.Instance).Config.ConfigFilePath), includeSubfolders: false, delegate { lock (Gate) { _configChanged = true; _due = -1f; } }); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Can't watch the translation files: " + ex.Message)); } } private static FileSystemWatcher Watch(string folder, string filter, bool includeSubfolders, Action changed) { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(folder, filter); fileSystemWatcher.IncludeSubdirectories = includeSubfolders; fileSystemWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite; FileSystemEventHandler value = delegate(object _, FileSystemEventArgs e) { if (e.FullPath.IndexOf(Path.DirectorySeparatorChar + "_missing" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) < 0) { changed(); } }; fileSystemWatcher.Changed += value; fileSystemWatcher.Created += value; fileSystemWatcher.Deleted += value; fileSystemWatcher.Renamed += delegate { changed(); }; fileSystemWatcher.EnableRaisingEvents = true; return fileSystemWatcher; } private void Update() { bool flag; bool flag2; bool configChanged; lock (Gate) { if (_due < 0f) { _due = Time.realtimeSinceStartup + 0.5f; } if ((_reload || _refresh || _configChanged) && !(Time.realtimeSinceStartup < _due)) { flag = _reload; flag2 = _refresh; configChanged = _configChanged; _reload = (_refresh = (_configChanged = false)); goto IL_0085; } } goto IL_00e0; IL_0085: try { if (configChanged && Time.realtimeSinceStartup - Sources.SavedAt > 2f) { ((BaseUnityPlugin)Plugin.Instance).Config.Reload(); flag = (flag2 = true); } if (flag) { Languages.Select(); } if (flag2 || flag) { TextHooks.Refresh(); } Panel.RefreshIfOpen(); } catch (Exception arg) { Plugin.Log.LogWarning((object)$"Refreshing translations failed: {arg}"); } goto IL_00e0; IL_00e0: Sources.SaveIfNeeded(); if (Time.realtimeSinceStartup >= _nextFlush) { _nextFlush = Time.realtimeSinceStartup + 5f; Missing.Flush(); } } private void OnDestroy() { _files?.Dispose(); _config?.Dispose(); Missing.Flush(); } } internal sealed class AcceptableLanguages : AcceptableValueList<string> { public override string[] AcceptableValues => Current(); public AcceptableLanguages() : base(Current()) { } private static string[] Current() { List<string> list = new List<string>(); list.Add("Original"); list.AddRange(Languages.All()); return list.ToArray(); } public override bool IsValid(object value) { string s = value as string; if (s != null && !string.IsNullOrEmpty(s)) { return Current().Any((string n) => string.Equals(n, s, StringComparison.OrdinalIgnoreCase)); } return false; } public override object Clamp(object value) { string s = value as string; if (s != null) { string text = Current().FirstOrDefault((string n) => string.Equals(n, s, StringComparison.OrdinalIgnoreCase)); if (text != null) { return text; } } return "Original"; } public override string ToDescriptionString() { return "# Acceptable values: " + string.Join(", ", Current()); } } internal sealed class Source { internal string Name; internal string Kind; internal string Folder; internal Dictionary Lines; internal readonly Dictionary<string, Dictionary> ByMod = new Dictionary<string, Dictionary>(StringComparer.OrdinalIgnoreCase); } internal static class Sources { private const string Section = "Sources"; private static ConfigFile _config; private static readonly Dictionary<string, ConfigEntry<bool>> Switches = new Dictionary<string, ConfigEntry<bool>>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary<string, Dictionary<string, HashSet<string>>> Translated = new Dictionary<string, Dictionary<string, HashSet<string>>>(StringComparer.OrdinalIgnoreCase); private static bool _dirty; internal static float SavedAt = -10f; private static bool _batching; internal static void Load(ConfigFile config) { _config = config; if (!File.Exists(config.ConfigFilePath)) { return; } bool flag = false; bool saveOnConfigSet = config.SaveOnConfigSet; config.SaveOnConfigSet = false; string[] array = File.ReadAllLines(config.ConfigFilePath); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.StartsWith("[")) { flag = text == "[Sources]"; continue; } int num = text.IndexOf('='); if (flag && num > 0 && !text.StartsWith("#")) { string[] array2 = (from p in text.Substring(0, num).Split('|') select p.Trim()).ToArray(); if (array2.Length == 3) { Bind(array2[0], array2[1], array2[2], fromLoad: true); } } } config.SaveOnConfigSet = saveOnConfigSet; } internal static bool On(Source source, string mod) { if (source != null && Switches.TryGetValue(Key(Languages.ActiveName, source.Name, mod ?? "Game"), out var value)) { return value.Value; } return true; } private static string Key(string language, string source, string mod) { return Clean(language) + " | " + Clean(source) + " | " + Clean(mod); } internal static void Set(Source source, string mod, bool on) { ConfigEntry<bool> val = Bind(Languages.ActiveName, source.Name, mod); _batching = true; bool saveOnConfigSet = _config.SaveOnConfigSet; _config.SaveOnConfigSet = false; try { val.Value = on; } finally { _config.SaveOnConfigSet = saveOnConfigSet; _batching = false; } _dirty = false; Plugin.SaveConfig(); } internal static void SetAll(Source source, bool on) { if (source == null) { return; } _batching = true; bool saveOnConfigSet = _config.SaveOnConfigSet; _config.SaveOnConfigSet = false; try { foreach (KeyValuePair<string, int> item in ModsOf(source)) { Bind(Languages.ActiveName, source.Name, item.Key).Value = on; } } finally { _config.SaveOnConfigSet = saveOnConfigSet; _batching = false; } _dirty = false; Plugin.SaveConfig(); Runner.ApplyNow(reload: false); } private static ConfigEntry<bool> Bind(string language, string source, string mod, bool fromLoad = false) { string text = Key(language, source, mod); if (Switches.TryGetValue(text, out var value)) { return value; } bool saveOnConfigSet = _config.SaveOnConfigSet; _config.SaveOnConfigSet = false; value = _config.Bind<bool>("Sources", text, true, "In " + language + ", " + source + " translates " + mod + "'s text. Off leaves that to the other sources, or shows the original."); _config.SaveOnConfigSet = saveOnConfigSet; value.SettingChanged += delegate { if (!_batching) { _dirty = false; Plugin.SaveConfig(); Runner.Request(reload: false); } }; Switches[text] = value; if (!fromLoad) { _dirty = true; } return value; } private static string Clean(string name) { return new string(name.Where((char c) => "=\n\t\\\"'[]|".IndexOf(c) < 0).ToArray()).Trim(); } internal static void SaveIfNeeded() { if (_dirty) { _dirty = false; Plugin.SaveConfig(); } } internal static void Count(Source source, string mod, string line) { string key = Languages.ActiveName + "|" + source.Name; if (!Translated.TryGetValue(key, out var value)) { value = (Translated[key] = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase)); } mod = (string.IsNullOrEmpty(mod) ? "Game" : mod); if (!value.TryGetValue(mod, out var value2)) { value2 = (value[mod] = new HashSet<string>(StringComparer.Ordinal)); } if (value2.Count < 5000) { value2.Add(line); } } internal static List<KeyValuePair<string, int>> ModsOf(Source source) { Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); if (Translated.TryGetValue(Languages.ActiveName + "|" + source.Name, out var value)) { foreach (KeyValuePair<string, HashSet<string>> item in value) { dictionary[item.Key] = item.Value.Count; } } if (source.Folder != null && Directory.Exists(source.Folder)) { string[] files = Directory.GetFiles(source.Folder, "*.txt"); for (int i = 0; i < files.Length; i++) { string key = Regex.Replace(Path.GetFileNameWithoutExtension(files[i]), "^z+[-_]", ""); if (!dictionary.ContainsKey(key)) { dictionary[key] = 0; } } } string text = Clean(Languages.ActiveName) + " | " + Clean(source.Name) + " | "; foreach (string key2 in Switches.Keys) { if (key2.StartsWith(text, StringComparison.OrdinalIgnoreCase) && !dictionary.ContainsKey(key2.Substring(text.Length))) { dictionary[key2.Substring(text.Length)] = 0; } } return dictionary.OrderBy((KeyValuePair<string, int> p) => (!(p.Key == "Game")) ? ((p.Key == "Terminal") ? 1 : 2) : 0).ThenBy<KeyValuePair<string, int>, string>((KeyValuePair<string, int> p) => p.Key, StringComparer.OrdinalIgnoreCase).ToList(); } } internal static class TextHooks { internal sealed class State { internal string Original; internal string Translated; internal string XUnityText; internal string Owner; internal bool Skip; internal bool NoMissing; internal bool ByXUnity; internal TMP_InputField Field; internal bool Sized; internal float FontSize; internal float Min; internal float Max; } private static readonly ConditionalWeakTable<TMP_Text, State> States = new ConditionalWeakTable<TMP_Text, State>(); private static readonly Dictionary<string, string> Reverse = new Dictionary<string, string>(StringComparer.Ordinal); private static bool Working { get { if (!Engine.Active) { return XUnityBridge.Present; } return true; } } private static string RecoverOriginal(string value) { if (value == null || !Reverse.TryGetValue(value, out var value2)) { return value; } return value2; } internal static State StateOf(TMP_Text text) { if (States.TryGetValue(text, out var value)) { return value; } value = new State { Owner = Owners.FromStack() }; try { Mark(value, ((Component)text).GetComponentInParent<TMP_InputField>(true)); if ((Object)(object)HUDManager.Instance != (Object)null && (Object)(object)text == (Object)(object)HUDManager.Instance.chatText) { value.Skip = true; } Transform val = text.transform; while ((Object)(object)val != (Object)null) { if (((Object)val).name.IndexOf("Credit", StringComparison.OrdinalIgnoreCase) >= 0) { value.NoMissing = true; break; } val = val.parent; } } catch (Exception) { } States.Add(text, value); return value; } private static void Mark(State state, TMP_InputField field) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)field == (Object)null)) { state.Field = field; if ((int)field.lineType != 0 || ((Object)(object)HUDManager.Instance != (Object)null && (Object)(object)field == (Object)(object)HUDManager.Instance.chatTextField)) { state.Skip = true; } } } internal static bool Hold(State state) { if (!state.Skip) { if ((Object)(object)state.Field != (Object)null) { return state.Field.isFocused; } return false; } return true; } internal static bool TryState(TMP_Text text, out State state) { return States.TryGetValue(text, out state); } private static string Apply(TMP_Text text, string value) { if (XUnityBridge.Setting || (Object)(object)text == (Object)null) { return value; } if (!Working) { if (States.TryGetValue(text, out var value2)) { if (!Hold(value2) && (value == null || value2.Translated == null || !string.Equals(value, value2.Translated, StringComparison.Ordinal))) { value2.Original = value; } value2.Translated = null; value2.XUnityText = null; value2.ByXUnity = false; Fit(text, value2, value2.Original ?? value, null); } return value; } State state = StateOf(text); if (Hold(state)) { state.Translated = null; return value; } if (value != null && state.Translated != null && string.Equals(value, state.Translated, StringComparison.Ordinal)) { return value; } if (state.Original == null && value != null) { value = RecoverOriginal(value); } state.Original = value; state.ByXUnity = false; state.XUnityText = null; bool trackMissing = (Object)(object)state.Field == (Object)null && (!state.NoMissing || value == null || value.Length <= 200); state.Translated = Engine.Translate(value, state.Owner, trackMissing); if (state.Translated != null && value != null && !string.Equals(state.Translated, value, StringComparison.Ordinal)) { if (Reverse.Count > 30000) { Reverse.Clear(); } Reverse[state.Translated] = value; } Fit(text, state, value, state.Translated); return state.Translated ?? value; } [HarmonyPatch(/*Could not decode attribute arguments.*/)] [HarmonyPrefix] private static void SetTextProperty(TMP_Text __instance, ref string value) { value = Apply(__instance, value); } [HarmonyPatch(typeof(TMP_Text), "SetText", new Type[] { typeof(string), typeof(bool) })] [HarmonyPrefix] private static void SetTextMethod(TMP_Text __instance, ref string sourceText) { sourceText = Apply(__instance, sourceText); } [HarmonyPatch(/*Could not decode attribute arguments.*/)] [HarmonyPostfix] private static void GetText(TMP_Text __instance, ref string __result) { if (__result != null && States.TryGetValue(__instance, out var value) && value.Translated != null && string.Equals(__result, value.Translated, StringComparison.Ordinal)) { __result = value.Original; } } [HarmonyPatch(typeof(TMP_Text), "GetPreferredValues", new Type[] { typeof(string) })] [HarmonyPrefix] private static void MeasureString(TMP_Text __instance, ref string text) { text = MeasureText(__instance, text); } [HarmonyPatch(typeof(TMP_Text), "GetPreferredValues", new Type[] { typeof(string), typeof(float), typeof(float) })] [HarmonyPrefix] private static void MeasureBox(TMP_Text __instance, ref string text) { text = MeasureText(__instance, text); } private static string MeasureText(TMP_Text ui, string text) { if (!Working || (Object)(object)ui == (Object)null || string.IsNullOrEmpty(text)) { return text; } if (States.TryGetValue(ui, out var value)) { if (value.Skip) { return text; } string text2 = value.Translated ?? (value.ByXUnity ? value.XUnityText : null); if (text2 != null) { if (string.Equals(text, text2, StringComparison.Ordinal)) { return text; } if (string.Equals(text, value.Original, StringComparison.Ordinal)) { return text2; } } if (!Engine.Active) { return text; } return Engine.Translate(text, value.Owner, trackMissing: false) ?? text; } if (!Engine.Active) { return text; } return Engine.Translate(text, Owners.FromStack(), trackMissing: false) ?? text; } internal static void Exclude(TMP_Text text, string shown) { State state = StateOf(text); state.Skip = true; state.Translated = null; text.text = shown; } internal static void SetOwner(TMP_Text text, string owner, string shown) { State state = StateOf(text); state.Owner = owner; state.Skip = false; text.text = shown; } [HarmonyPatch(typeof(TextMeshProUGUI), "OnEnable")] [HarmonyPostfix] [HarmonyPriority(800)] private static void EnabledUi(TextMeshProUGUI __instance) { Enabled((TMP_Text)(object)__instance); } [HarmonyPatch(typeof(TextMeshPro), "OnEnable")] [HarmonyPostfix] [HarmonyPriority(800)] private static void EnabledWorld(TextMeshPro __instance) { Enabled((TMP_Text)(object)__instance); } private static void Enabled(TMP_Text text) { if (Working && !States.TryGetValue(text, out var _)) { string text2 = text.text; if (Engine.HasLetter(text2)) { text.text = text2; } else { StateOf(text); } } } [HarmonyPatch(typeof(TMP_InputField), "OnEnable")] [HarmonyPostfix] private static void FieldEnabled(TMP_InputField __instance) { if (!((Object)(object)__instance.textComponent == (Object)null)) { Mark(StateOf(__instance.textComponent), __instance); } } [HarmonyPatch(typeof(Terminal), "TextPostProcess")] [HarmonyPostfix] private static void TerminalPage(ref string __result) { if (Engine.Active) { __result = Engine.Translate(__result, "Terminal") ?? __result; } } internal static void Fit(TMP_Text text, State state, string original, string shown) { bool flag = Plugin.Shrink.Value && shown != null && original != null && shown.Length > original.Length; if (flag && !state.Sized && !text.enableAutoSizing && (Object)(object)((Component)text).GetComponent<ContentSizeFitter>() == (Object)null) { state.Sized = true; state.FontSize = text.fontSize; state.Min = text.fontSizeMin; state.Max = text.fontSizeMax; text.fontSizeMax = text.fontSize; text.fontSizeMin = text.fontSize * 0.55f; text.enableAutoSizing = true; } else if (!flag && state.Sized) { state.Sized = false; text.enableAutoSizing = false; text.fontSizeMin = state.Min; text.fontSizeMax = state.Max; text.fontSize = state.FontSize; } } internal static void Refresh() { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) Engine.Clear(); XUnityBridge.Refresh(); int num = 0; TMP_Text[] array = Resources.FindObjectsOfTypeAll<TMP_Text>(); foreach (TMP_Text val in array) { if ((Object)(object)val == (Object)null) { continue; } Scene scene = ((Component)val).gameObject.scene; if (!((Scene)(ref scene)).IsValid() || (States.TryGetValue(val, out var state) && (state.Skip || state.ByXUnity))) { continue; } string text = state?.Original ?? RecoverOriginal(val.text); if (state != null || Engine.HasLetter(text)) { val.text = text; num++; if (TryState(val, out state) && state.Translated == null && Engine.Active) { XUnityBridge.Offer(val); } } } Plugin.Log.LogInfo((object)$"Showing {Languages.ActiveName}: {num} texts set again"); } } internal static class XUnityBridge { internal const string Guid = "gravydevsupreme.xunity.autotranslator"; internal static bool Present; [ThreadStatic] internal static bool Setting; private static MethodInfo _setText; private static MethodInfo _hook; private static MethodInfo _registered; private static FieldInfo _current; private static PropertyInfo _isTranslated; private static PropertyInfo _originalText; private static PropertyInfo _translatedText; private static Type _infoType; private static string _language; private static string _orphanOf; internal static Source Source = new Source { Name = "XUnity AutoTranslator", Kind = "XUnity translation mod" }; internal static bool ServesActive { get { if (Present && _orphanOf == null && _language != null && Languages.ActiveName != "Original") { return Languages.SameLanguage(Languages.ActiveName, _language); } return false; } } internal static void Init(Harmony harmony) { //IL_0239: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Expected O, but got Unknown //IL_026f: Expected O, but got Unknown //IL_026f: Expected O, but got Unknown ReadIni(); Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "XUnity.AutoTranslator.Plugin.Core"); if (assembly == null) { return; } try { Type type = assembly.GetType("XUnity.AutoTranslator.Plugin.Core.AutoTranslationPlugin"); _infoType = assembly.GetType("XUnity.AutoTranslator.Plugin.Core.TextTranslationInfo"); _setText = AccessTools.Method(type, "SetText", new Type[5] { typeof(object), typeof(string), typeof(bool), typeof(string), _infoType }, (Type[])null); _hook = AccessTools.Method(type, "Hook_TextChanged", new Type[2] { typeof(object), typeof(bool) }, (Type[])null); _current = AccessTools.Field(type, "Current"); _isTranslated = AccessTools.Property(_infoType, "IsTranslated"); _originalText = AccessTools.Property(_infoType, "OriginalText"); _translatedText = AccessTools.Property(_infoType, "TranslatedText"); Type type2 = AccessTools.TypeByName("XUnity.Common.Utilities.ExtensionDataHelper") ?? (from a in AppDomain.CurrentDomain.GetAssemblies() where a.GetName().Name.StartsWith("XUnity") select a).SelectMany(delegate(Assembly a) { try { return a.GetTypes(); } catch (ReflectionTypeLoadException ex) { return ex.Types.Where((Type t) => t != null); } }).FirstOrDefault((Type t) => t.Name == "ExtensionDataHelper"); _registered = ((type2 == null) ? null : AccessTools.Method(type2, "GetAllRegisteredObjects", (Type[])null, (Type[])null)); if (_setText == null || _current == null || _isTranslated == null || _originalText == null || _translatedText == null) { Plugin.Log.LogWarning((object)"This XUnity AutoTranslator version isn't known: it translates without BaconTranslations' switches"); return; } harmony.Patch((MethodBase)_setText, new HarmonyMethod(typeof(XUnityBridge), "Before", (Type[])null), new HarmonyMethod(typeof(XUnityBridge), "After", (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(XUnityBridge), "Done", (Type[])null), (HarmonyMethod)null); Present = true; Plugin.Log.LogInfo((object)("XUnity AutoTranslator follows BaconTranslations' switches (its language: " + (_language ?? "unknown") + ")" + ((_orphanOf != null) ? (". Its files are in a folder of " + _orphanOf + ", which isn't installed, so they stay off") : ""))); } catch (Exception arg) { Plugin.Log.LogWarning((object)$"Linking XUnity AutoTranslator failed: {arg}"); } } private static void ReadIni() { string path = Path.Combine(Paths.ConfigPath, "AutoTranslatorConfig.ini"); if (!File.Exists(path)) { return; } string text = null; string directory = null; string[] array = File.ReadAllLines(path); for (int i = 0; i < array.Length; i++) { string text2 = array[i].Trim(); if (text2.StartsWith("[")) { text = text2; continue; } int num = text2.IndexOf('='); if (num > 0) { string text3 = text2.Substring(0, num).Trim(); string text4 = text2.Substring(num + 1).Trim(); if (text == "[General]" && text3 == "Language") { _language = text4; } if (text == "[Files]" && text3 == "Directory") { directory