using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.TextCore.LowLevel;
using UnityEngine.UI;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace AbobaRu;
internal sealed class CardTranslation
{
internal readonly string Title;
internal readonly string RussianTitle;
internal readonly string Description;
internal readonly string RussianDescription;
internal CardTranslation(string[] cells)
{
Title = cells[1];
RussianTitle = cells[2];
Description = cells[3];
RussianDescription = cells[4];
}
}
internal sealed class Locale
{
private static readonly Regex Escape = new Regex("\\\\([\\\\nrt])", RegexOptions.CultureInvariant);
private static readonly Regex CarriageReturn = new Regex("\\r\\n?", RegexOptions.CultureInvariant);
private static readonly Regex Latin = new Regex("[a-z]", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex Percentage = new Regex("^(\\d+(?:[,.]\\d+)?%\\s+)([\\p{L} ]+)$", RegexOptions.CultureInvariant);
private static readonly Regex NumberLabel = new Regex("^(Cards Per Line:|Maps Per Line:|Estimated cards that will be visible with these settings:)\\s*([-\\d.,]+)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex CardBarKey = new Regex("^Toggle card bar keybind: (\\w+)$", RegexOptions.CultureInvariant);
private static readonly Regex TeamPoint = new Regex("^(POINT TO TEAM|TEAM WINS)(\\s*<color=#[a-fA-F0-9]{6,8}>)([^<]+)(</color>)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex Amount = new Regex("^[\\s+\\d.,/%&xX-]+(?:HP Per Second|hp/s|dmg/s|seconds?|min|total|deg|all|s|m)(?:[\\s+\\d.,/%&xX-]|HP Per Second|hp/s|dmg/s|seconds?|min|total|deg|all|s|m)*$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex AmountUnit = new Regex("HP Per Second|hp/s|dmg/s|seconds?|min|total|deg|all|[sm]|(?<=\\d)\\.(?=\\d)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Dictionary<string, string> Units = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "HP Per Second", "здоровья/с" },
{ "hp/s", "здоровья/с" },
{ "dmg/s", "урона/с" },
{ "second", " с" },
{ "seconds", " с" },
{ "min", " мин." },
{ "total", "от исходного" },
{ "deg", "°" },
{ "all", "ко всему" },
{ "s", " с" },
{ "m", " м" },
{ ".", "," }
};
private readonly Dictionary<string, string> ui = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, string> cardText = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, CardTranslation> cards = new Dictionary<string, CardTranslation>(StringComparer.Ordinal);
private readonly HashSet<string> ambiguousCardText = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
internal void Load(string directory, ManualLogSource log)
{
ReadTable(Path.Combine(directory, "cards.tsv"), 5, log, delegate(string[] cells)
{
if (cells[0].Length != 0 && cells[1].Length != 0 && cells[2].Length != 0)
{
cards[cells[0]] = new CardTranslation(cells);
}
});
foreach (CardTranslation value in cards.Values)
{
AddCardText(value.Title, value.RussianTitle);
AddCardText(value.Description, value.RussianDescription);
}
ReadTable(Path.Combine(directory, "ui.tsv"), 2, log, delegate(string[] cells)
{
if (cells[0].Length != 0 && cells[1].Length != 0)
{
ui[Normalize(cells[0])] = cells[1];
}
});
log.LogInfo((object)$"Loaded {cards.Count} cards and {ui.Count} UI/stat entries from local TSV files.");
}
internal CardTranslation FindCard(CardInfo card)
{
if (!Object.op_Implicit((Object)(object)card))
{
return null;
}
CardTranslation cardTranslation = FindCardById(((Object)((Component)card).gameObject).name);
if (cardTranslation == null)
{
if (!Object.op_Implicit((Object)(object)card.sourceCard))
{
return null;
}
cardTranslation = FindCardById(((Object)((Component)card.sourceCard).gameObject).name);
}
return cardTranslation;
}
internal CardTranslation FindCardById(string id)
{
if (string.IsNullOrEmpty(id))
{
return null;
}
while (id.EndsWith("(Clone)", StringComparison.Ordinal))
{
id = id.Substring(0, id.Length - "(Clone)".Length).TrimEnd(new char[0]);
}
if (!cards.TryGetValue(id, out var value))
{
return null;
}
return value;
}
internal string GetText(string source, bool cardContext, CardTranslation card, bool title)
{
if (string.IsNullOrWhiteSpace(source))
{
return source;
}
string text = Normalize(source);
if (card != null)
{
if (title && SameText(text, card.Title))
{
return MatchCase(source, card.RussianTitle);
}
if (SameText(text, card.Description) && card.RussianDescription.Length != 0)
{
return card.RussianDescription;
}
}
if (cardContext && cardText.TryGetValue(text, out var value))
{
return MatchCase(source, value);
}
if (ui.TryGetValue(text, out value))
{
return MatchCase(source, value);
}
if (cardText.TryGetValue(text, out value))
{
return MatchCase(source, value);
}
if (cardContext && Amount.IsMatch(text))
{
return AmountUnit.Replace(text, (Match match5) => Units[match5.Value]).Replace(" ", " ").Replace(" °", "°");
}
if (text.Length < 3)
{
return source;
}
if (char.IsDigit(text[0]))
{
Match match = Percentage.Match(text);
if (match.Success && ui.TryGetValue(match.Groups[2].Value.Trim(), out value))
{
return match.Groups[1].Value + MatchCase(match.Groups[2].Value, value);
}
}
Match match2 = NumberLabel.Match(text);
if (match2.Success && ui.TryGetValue(match2.Groups[1].Value, out value))
{
return value + " " + match2.Groups[2].Value;
}
Match match3 = CardBarKey.Match(text);
if (match3.Success)
{
return "Клавиша панели карт: " + match3.Groups[1].Value;
}
Match match4 = TeamPoint.Match(text);
if (match4.Success && ui.TryGetValue(match4.Groups[1].Value, out value))
{
string text2 = match4.Groups[3].Value.Trim();
if (!ui.TryGetValue(text2, out var value2))
{
value2 = text2;
}
return MatchCase(match4.Groups[1].Value, value) + match4.Groups[2].Value + MatchCase(text2, value2) + match4.Groups[4].Value;
}
return source;
}
internal string GetMapName(string source)
{
int num = source.IndexOf('\n');
string text = ((num < 0) ? source.Trim() : source.Substring(0, num).Trim());
if (!ui.TryGetValue("LevelName:" + text, out var value))
{
return source;
}
if (num >= 0)
{
return value + source.Substring(num);
}
return value;
}
private void AddCardText(string source, string translated)
{
if (source.Length == 0 || translated.Length == 0)
{
return;
}
string text = Normalize(source);
if (!ambiguousCardText.Contains(text))
{
if (cardText.TryGetValue(text, out var value) && value != translated)
{
cardText.Remove(text);
ambiguousCardText.Add(text);
}
else
{
cardText[text] = translated;
}
}
}
private static bool SameText(string key, string value)
{
return string.Equals(key, Normalize(value), StringComparison.OrdinalIgnoreCase);
}
private static string MatchCase(string source, string translation)
{
if (source.Length <= 90 && source.IndexOf('<') < 0 && string.Equals(source, source.ToUpperInvariant(), StringComparison.Ordinal) && Latin.IsMatch(source))
{
return translation.ToUpperInvariant();
}
return translation;
}
private static string Normalize(string source)
{
return CarriageReturn.Replace(source, "\n").Trim();
}
private static void ReadTable(string path, int columnCount, ManualLogSource log, Action<string[]> read)
{
try
{
int num = 0;
foreach (string item in File.ReadLines(path, Encoding.UTF8))
{
num++;
if (string.IsNullOrWhiteSpace(item) || item.StartsWith("#", StringComparison.Ordinal))
{
continue;
}
string[] array = item.Split(new char[1] { '\t' });
if (array.Length != columnCount)
{
log.LogWarning((object)(Path.GetFileName(path) + ":" + num + ": expected " + columnCount + " TSV columns."));
continue;
}
for (int i = 0; i < array.Length; i++)
{
array[i] = Escape.Replace(array[i], (Match match) => match.Value[1] switch
{
'n' => "\n",
'r' => "\r",
't' => "\t",
_ => "\\",
});
}
read(array);
}
}
catch (IOException ex)
{
log.LogWarning((object)(path + ": " + ex.Message));
}
catch (UnauthorizedAccessException ex2)
{
log.LogWarning((object)(path + ": " + ex2.Message));
}
}
}
[BepInPlugin("aboba.rounds.ru", "Aboba RU", "1.0.0")]
[BepInProcess("Rounds.exe")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
private struct LegacyState
{
internal string Text;
}
private const string Id = "aboba.rounds.ru";
private static readonly Regex Cyrillic = new Regex("[\\u0400-\\u052f]", RegexOptions.CultureInvariant);
private static readonly string[] WindowsFonts = new string[3] { "Arial", "Segoe UI", "Tahoma" };
private static readonly Locale Locale = new Locale();
private static readonly FieldInfo BadgeCard = AccessTools.Field(typeof(CardBarButton), "card");
private static readonly ConditionalWeakTable<TMP_Text, CardTranslation> MenuTitles = new ConditionalWeakTable<TMP_Text, CardTranslation>();
private static ManualLogSource log;
private static Font systemFont;
private static string systemFontPath;
private static TMP_FontAsset fallback;
private static bool fontInitialized;
private Harmony harmony;
[ThreadStatic]
private static CardInfo menuCard;
private static FieldInfo searchField;
private static readonly FieldInfo LegacyFontData = AccessTools.Field(typeof(Text), "m_FontData");
private void Awake()
{
//IL_0045: Unknown result type (might be due to invalid IL or missing references)
//IL_004f: Expected O, but got Unknown
log = ((BaseUnityPlugin)this).Logger;
string directoryName = Path.GetDirectoryName(typeof(Plugin).Assembly.Location);
Locale.Load(Path.Combine(directoryName, "Aboba_RU_locale"), log);
harmony = new Harmony("aboba.rounds.ru");
try
{
Attach(typeof(TMP_Text), "StringToCharArray", "TranslateTmp");
Attach(typeof(TMP_Text), "SetTextArrayToCharArray", "TranslateTmpArray", null, "RestoreTmpArrayLength");
Attach(typeof(Text), "OnPopulateMesh", "TranslateLegacy", new Type[1] { typeof(VertexHelper) }, "RestoreLegacy");
Attach(typeof(Text), "get_preferredWidth", "TranslateLegacy", null, "RestoreLegacy");
Attach(typeof(Text), "get_preferredHeight", "TranslateLegacy", null, "RestoreLegacy");
Attach(typeof(CardBar), "AddCard", null, null, null, "CardAdded");
}
catch (Exception ex)
{
harmony.UnpatchSelf();
log.LogError((object)ex);
return;
}
try
{
PatchUnbound();
}
catch (Exception ex2)
{
log.LogWarning((object)("UnboundLib UI compatibility: " + ex2.Message));
}
}
private void Attach(Type type, string methodName, string prefix, Type[] arguments = null, string finalizer = null, string postfix = null)
{
MethodInfo methodInfo = AccessTools.DeclaredMethod(type, methodName, arguments, (Type[])null);
if (methodInfo == null)
{
throw new MissingMethodException(type.FullName, methodName);
}
harmony.Patch((MethodBase)methodInfo, Hook(prefix), Hook(postfix), (HarmonyMethod)null, Hook(finalizer), (HarmonyMethod)null);
}
private static HarmonyMethod Hook(string name)
{
//IL_0015: Unknown result type (might be due to invalid IL or missing references)
//IL_001b: Expected O, but got Unknown
if (name != null)
{
return new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Plugin), name, (Type[])null, (Type[])null));
}
return null;
}
private void PatchUnbound()
{
Type type = AccessTools.TypeByName("UnboundLib.Utils.UI.ToggleCardsMenuHandler");
if (type == null)
{
return;
}
Attach(typeof(TMP_Text), "set_text", "BindMenuTitle");
Attach(type, "SetupCardVisuals", "StartCardMenu", null, "FinishCardMenu");
Attach(type, "ActiveOnSearch", null, null, null, "SearchRussianTitle");
Type type2 = AccessTools.TypeByName("UnboundLib.Unbound");
MethodInfo methodInfo = AccessTools.Method(type2, "RegisterClientSideMod", new Type[1] { typeof(string) }, (Type[])null);
if (!(methodInfo == null))
{
object obj = (methodInfo.IsStatic ? null : AccessTools.Property(type2, "Instance").GetValue(null, null));
if (methodInfo.IsStatic || obj != null)
{
methodInfo.Invoke(obj, new object[1] { "aboba.rounds.ru" });
}
}
}
private static void StartCardMenu(CardInfo __0, out CardInfo __state)
{
__state = menuCard;
menuCard = __0;
}
private static void FinishCardMenu(CardInfo __state)
{
menuCard = __state;
}
private static void BindMenuTitle(TMP_Text __instance, string __0)
{
if (Object.op_Implicit((Object)(object)menuCard) && !string.IsNullOrEmpty(__0) && string.Equals(__0, menuCard.cardName, StringComparison.OrdinalIgnoreCase))
{
CardTranslation cardTranslation = Locale.FindCard(menuCard);
if (cardTranslation != null)
{
MenuTitles.Remove(__instance);
MenuTitles.Add(__instance, cardTranslation);
}
}
}
private static void SearchRussianTitle(object __instance, string __0, ref bool __result)
{
if (__result || string.IsNullOrEmpty(__0))
{
return;
}
if (searchField == null)
{
searchField = AccessTools.Field(__instance.GetType(), "currentSearch");
}
string text = ((searchField == null) ? null : (searchField.GetValue(__instance) as string));
if (!string.IsNullOrWhiteSpace(text))
{
CardTranslation cardTranslation = Locale.FindCardById(__0);
if (cardTranslation != null)
{
__result = cardTranslation.RussianTitle.IndexOf(text.Trim(), StringComparison.OrdinalIgnoreCase) >= 0;
}
}
}
private static void TranslateTmp(TMP_Text __instance, ref string __0)
{
__0 = RenderTmp(__instance, __0);
}
private static void TranslateTmpArray(TMP_Text __instance, ref char[] __0, ref int ___m_charArray_Length, out int __state)
{
__state = ___m_charArray_Length;
if (__0 == null || __state <= 0 || __state > __0.Length)
{
return;
}
int num = __state;
while (num > 0 && __0[num - 1] == '\0')
{
num--;
}
if (num != 0)
{
string text = new string(__0, 0, num);
string text2 = RenderTmp(__instance, text);
if (!(text2 == text))
{
__0 = text2.ToCharArray();
___m_charArray_Length = __0.Length;
}
}
}
private static void RestoreTmpArrayLength(ref int ___m_charArray_Length, int __state)
{
___m_charArray_Length = __state;
}
private static string RenderTmp(TMP_Text label, string original)
{
if (string.IsNullOrWhiteSpace(original))
{
return original;
}
if (Cyrillic.IsMatch(original))
{
EnsureTmpFont(label.font);
return original;
}
if (original.Length < 2)
{
return original;
}
TMP_InputField componentInParent = ((Component)label).GetComponentInParent<TMP_InputField>();
if (Object.op_Implicit((Object)(object)componentInParent) && (Object)(object)componentInParent.textComponent == (Object)(object)label)
{
return original;
}
if (((Object)label).name.IndexOf("ChatMessage", StringComparison.OrdinalIgnoreCase) >= 0)
{
return original;
}
if (((Object)label).name == "LevelName")
{
string mapName = Locale.GetMapName(original);
if (mapName != original)
{
EnsureTmpFont(label.font);
}
return mapName;
}
CardBarButton componentInParent2 = ((Component)label).GetComponentInParent<CardBarButton>();
CardInfo val = (CardInfo)((Object.op_Implicit((Object)(object)componentInParent2) && BadgeCard != null) ? /*isinst with value type is only supported in some contexts*/: null);
string text;
if (Object.op_Implicit((Object)(object)val) && original.Length == 2 && val.cardName != null && val.cardName.StartsWith(original, StringComparison.OrdinalIgnoreCase))
{
text = Initials(val, original);
}
else
{
CardInfoDisplayer componentInParent3 = ((Component)label).GetComponentInParent<CardInfoDisplayer>();
CardInfo val2 = (Object.op_Implicit((Object)(object)componentInParent3) ? ((Component)componentInParent3).GetComponentInParent<CardInfo>() : menuCard);
CardTranslation value;
bool flag = MenuTitles.TryGetValue(label, out value);
bool title = (Object.op_Implicit((Object)(object)componentInParent3) && (Object)(object)componentInParent3.nameText == (Object)(object)label) || ((Object)label).name == "Text_Name" || flag;
text = Locale.GetText(original, Object.op_Implicit((Object)(object)componentInParent3) || Object.op_Implicit((Object)(object)val2) || flag, Locale.FindCard(val2) ?? value, title);
}
if (text != original && Cyrillic.IsMatch(text))
{
EnsureTmpFont(label.font);
}
return text;
}
private static string Initials(CardInfo card, string original)
{
CardTranslation cardTranslation = Locale.FindCard(card);
if (cardTranslation == null || cardTranslation.RussianTitle.Length < 2)
{
return original;
}
return char.ToUpperInvariant(cardTranslation.RussianTitle[0]) + cardTranslation.RussianTitle.Substring(1, 1).ToLowerInvariant();
}
private static void CardAdded(CardBar __instance, CardInfo __0)
{
//IL_0031: Unknown result type (might be due to invalid IL or missing references)
//IL_003c: Expected O, but got Unknown
if (!Object.op_Implicit((Object)(object)__0) || BadgeCard == null)
{
return;
}
CardBarButton[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<CardBarButton>(true);
foreach (CardBarButton val in componentsInChildren)
{
if (!((Object)(CardInfo)BadgeCard.GetValue(val) != (Object)(object)__0))
{
TMP_Text componentInChildren = ((Component)val).GetComponentInChildren<TMP_Text>(true);
if (Object.op_Implicit((Object)(object)componentInChildren))
{
componentInChildren.havePropertiesChanged = true;
}
}
}
}
private static void EnsureTmpFont(TMP_FontAsset primary)
{
if (!fontInitialized)
{
fontInitialized = true;
try
{
systemFont = Font.CreateDynamicFontFromOSFont(WindowsFonts, 32);
if (Object.op_Implicit((Object)(object)systemFont))
{
fallback = CreateCyrillicAtlas();
}
if (Object.op_Implicit((Object)(object)fallback))
{
((Object)fallback).name = "Aboba RU Cyrillic";
((Object)fallback).hideFlags = (HideFlags)32;
}
else
{
log.LogWarning((object)"No system Cyrillic font could be loaded.");
}
}
catch (Exception ex)
{
log.LogWarning((object)("Cyrillic font: " + ex));
}
}
if (Object.op_Implicit((Object)(object)fallback) && Object.op_Implicit((Object)(object)primary) && !((Object)(object)primary == (Object)(object)fallback))
{
List<TMP_FontAsset> list = primary.fallbackFontAssetTable;
if (list == null)
{
list = (primary.fallbackFontAssetTable = new List<TMP_FontAsset>());
}
if (!list.Contains(fallback))
{
list.Add(fallback);
}
}
}
private static TMP_FontAsset CreateCyrillicAtlas()
{
//IL_0065: Unknown result type (might be due to invalid IL or missing references)
//IL_006b: Expected O, but got Unknown
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
string[] array = new string[3] { "arial.ttf", "segoeui.ttf", "tahoma.ttf" };
foreach (string path in array)
{
string path2 = Path.Combine(folderPath, path);
if (File.Exists(path2))
{
systemFontPath = path2;
break;
}
}
Harmony val = new Harmony("aboba.rounds.ru.font");
if (systemFontPath != null)
{
MethodInfo methodInfo = AccessTools.Method(typeof(FontEngine), "LoadFontFace", new Type[2]
{
typeof(Font),
typeof(int)
}, (Type[])null);
val.Patch((MethodBase)methodInfo, Hook("LoadSystemFontFace"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
try
{
TMP_FontAsset val2 = TMP_FontAsset.CreateFontAsset(systemFont);
if (!Object.op_Implicit((Object)(object)val2))
{
return null;
}
StringBuilder stringBuilder = new StringBuilder();
string text = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя\u0301";
foreach (char c in text)
{
if (!val2.HasCharacter(c, false))
{
stringBuilder.Append(c);
}
}
if (stringBuilder.Length != 0)
{
log.LogWarning((object)("Missing Cyrillic font characters: " + stringBuilder));
}
val2.atlasPopulationMode = (AtlasPopulationMode)0;
return val2;
}
finally
{
val.UnpatchSelf();
}
}
private static bool LoadSystemFontFace(Font __0, int __1, ref FontEngineError __result)
{
//IL_0016: Unknown result type (might be due to invalid IL or missing references)
//IL_001c: Expected I4, but got Unknown
if ((Object)(object)__0 != (Object)(object)systemFont)
{
return true;
}
__result = (FontEngineError)(int)FontEngine.LoadFontFace(systemFontPath, __1);
return false;
}
private static void TranslateLegacy(Text __instance, ref string ___m_Text, out LegacyState __state)
{
__state = default(LegacyState);
if (string.IsNullOrWhiteSpace(___m_Text) || ((Object)__instance).name.IndexOf("ChatMessage", StringComparison.OrdinalIgnoreCase) >= 0)
{
return;
}
InputField componentInParent = ((Component)__instance).GetComponentInParent<InputField>();
if (Object.op_Implicit((Object)(object)componentInParent) && (Object)(object)componentInParent.textComponent == (Object)(object)__instance)
{
return;
}
string text = Locale.GetText(___m_Text, cardContext: false, null, title: false);
if (text == ___m_Text)
{
return;
}
if (Cyrillic.IsMatch(text))
{
Font font = __instance.font;
if (Object.op_Implicit((Object)(object)font) && !font.HasCharacter('Я'))
{
EnsureTmpFont(null);
FontData val = (FontData)((LegacyFontData == null) ? null : /*isinst with value type is only supported in some contexts*/);
if (Object.op_Implicit((Object)(object)systemFont) && val != null)
{
val.font = systemFont;
}
}
}
__state.Text = ___m_Text;
___m_Text = text;
}
private static void RestoreLegacy(ref string ___m_Text, LegacyState __state)
{
if (__state.Text != null)
{
___m_Text = __state.Text;
}
}
}