Decompiled source of RussianLocalization v0.2.0

RussianLocalization.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("0.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;
		}
	}
}
internal static class FontFix
{
	private static AssetBundle bundle;

	private static TMP_FontAsset ruFont;

	private static bool failed;

	internal static TMP_FontAsset Get()
	{
		if ((Object)(object)ruFont != (Object)null || failed)
		{
			return ruFont;
		}
		try
		{
			string text = Path.Combine(RussianLocalization.Dir, "russianlocalization");
			if (!File.Exists(text))
			{
				failed = true;
				RussianLocalization.Log.LogError((object)("Не найден файл шрифта: " + text));
				return null;
			}
			bundle = AssetBundle.LoadFromFile(text);
			if ((Object)(object)bundle == (Object)null)
			{
				failed = true;
				RussianLocalization.Log.LogError((object)"Файл шрифта не загрузился (не та версия Unity/TextMeshPro?)");
				return null;
			}
			TMP_FontAsset[] array = bundle.LoadAllAssets<TMP_FontAsset>();
			if (array.Length == 0)
			{
				failed = true;
				RussianLocalization.Log.LogError((object)"В файле шрифта нет TMP_FontAsset");
				return null;
			}
			ruFont = array[0];
			((Object)ruFont).hideFlags = (HideFlags)32;
			RussianLocalization.Log.LogInfo((object)("Русский шрифт загружен: " + ((Object)ruFont).name));
		}
		catch (Exception ex)
		{
			failed = true;
			RussianLocalization.Log.LogError((object)("Ошибка шрифта: " + ex));
		}
		return ruFont;
	}

	internal static bool HasCyrillic(string s)
	{
		foreach (char c in s)
		{
			if (c >= 'Ѐ' && c <= 'ӿ')
			{
				return true;
			}
		}
		return false;
	}

	internal static void Apply(TMP_Text text)
	{
		TMP_FontAsset val = Get();
		if (!((Object)(object)val == (Object)null) && !((Object)(object)text == (Object)null) && !((Object)(object)text.font == (Object)(object)val))
		{
			text.font = val;
			text.fontSharedMaterial = ((TMP_Asset)val).material;
		}
	}
}
[BepInPlugin("ru.localization.rounds", "ROUNDS Russian", "0.2.0")]
public class RussianLocalization : BaseUnityPlugin
{
	public const string PluginGuid = "ru.localization.rounds";

	public const string PluginName = "ROUNDS Russian";

	public const string PluginVersion = "0.2.0";

	internal static readonly Dictionary<string, string> Dict = new Dictionary<string, string>();

	internal static readonly HashSet<string> Missing = new HashSet<string>();

	internal static ManualLogSource Log;

	internal static string Dir;

	internal static string UserDir;

	private static bool collectMissing;

	private static bool dirty;

	private static string missingPath;

	private float nextScan;

	private static readonly Regex StatRx = new Regex("^([^:\\r\\n<>]{1,32}):\\s*(.+)$", RegexOptions.Compiled | RegexOptions.Singleline);

	private void Awake()
	{
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		Log = ((BaseUnityPlugin)this).Logger;
		Dir = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
		UserDir = Path.Combine(Paths.ConfigPath, "RussianLocalization");
		Directory.CreateDirectory(UserDir);
		missingPath = Path.Combine(UserDir, "missing.txt");
		collectMissing = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "CollectMissing", false, "true = записывать непереведённые строки в BepInEx\\config\\RussianLocalization\\missing.txt (для переводчиков).").Value;
		LoadDictionary(Path.Combine(Dir, "ru.txt"), required: true);
		LoadDictionary(Path.Combine(UserDir, "ru_user.txt"), required: false);
		if (collectMissing)
		{
			LoadPreviousMissing();
		}
		new Harmony("ru.localization.rounds").PatchAll();
		Log.LogInfo((object)string.Format("{0} {1}: загружено переводов: {2}", "ROUNDS Russian", "0.2.0", Dict.Count));
	}

	private static int FindSeparator(string line)
	{
		bool flag = false;
		for (int i = 0; i < line.Length; i++)
		{
			char c = line[i];
			if (flag)
			{
				if (c == '>')
				{
					flag = false;
				}
			}
			else if (c == '<' && i + 1 < line.Length && (char.IsLetter(line[i + 1]) || line[i + 1] == '/'))
			{
				flag = true;
			}
			else if (c == '=')
			{
				return i;
			}
		}
		return -1;
	}

	private static void LoadDictionary(string path, bool required)
	{
		if (!File.Exists(path))
		{
			if (required)
			{
				Log.LogError((object)("Файл переводов не найден: " + path));
			}
			return;
		}
		string[] array = File.ReadAllLines(path);
		for (int i = 0; i < array.Length; i++)
		{
			string text = array[i].TrimEnd(new char[1] { '\r' });
			if (!string.IsNullOrWhiteSpace(text) && !text.TrimStart(Array.Empty<char>()).StartsWith("#"))
			{
				int num = FindSeparator(text);
				if (num > 0)
				{
					string key = text.Substring(0, num).Replace("\\n", "\n");
					string value = text.Substring(num + 1).Replace("\\n", "\n");
					Dict[key] = value;
				}
			}
		}
	}

	private static string Normalize(string s)
	{
		if (s.IndexOf('\r') < 0)
		{
			return s;
		}
		return s.Replace("\r\n", "\n").Replace("\r", "\n");
	}

	private static bool TryTranslateLine(string line, out string ru)
	{
		if (Dict.TryGetValue(line, out ru))
		{
			return true;
		}
		string text = line.TrimEnd(Array.Empty<char>());
		if (text.Length != line.Length && Dict.TryGetValue(text, out ru))
		{
			return true;
		}
		Match match = StatRx.Match(line);
		if (match.Success && Dict.TryGetValue(match.Groups[1].Value + ":", out var value))
		{
			ru = value + " " + match.Groups[2].Value;
			return true;
		}
		ru = null;
		return false;
	}

	internal static bool TryTranslate(string s, out string ru)
	{
		if (Dict.TryGetValue(s, out ru))
		{
			return true;
		}
		string text = Normalize(s);
		if (text != s && Dict.TryGetValue(text, out ru))
		{
			return true;
		}
		if (text.IndexOf('\n') >= 0)
		{
			string[] array = text.Split(new char[1] { '\n' });
			bool flag = false;
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i].Length != 0)
				{
					if (TryTranslateLine(array[i], out var ru2))
					{
						array[i] = ru2;
						flag = true;
					}
					else
					{
						AddMissing(array[i]);
					}
				}
			}
			if (flag)
			{
				ru = string.Join("\n", array);
				return true;
			}
			ru = null;
			return false;
		}
		if (TryTranslateLine(text, out ru))
		{
			return true;
		}
		AddMissing(text);
		ru = null;
		return false;
	}

	internal static void AddMissing(string s)
	{
		if (!collectMissing || string.IsNullOrWhiteSpace(s) || s.Length >= 300 || FontFix.HasCyrillic(s))
		{
			return;
		}
		bool flag = false;
		for (int i = 0; i < s.Length; i++)
		{
			if (char.IsLetter(s[i]))
			{
				flag = true;
				break;
			}
		}
		if (flag && s.IndexOf("ms</color>", StringComparison.Ordinal) < 0 && (s.IndexOf(' ') >= 0 || s.IndexOf('_') < 0) && Missing.Add(s))
		{
			dirty = true;
		}
	}

	private static void LoadPreviousMissing()
	{
		if (!File.Exists(missingPath))
		{
			return;
		}
		string[] array = File.ReadAllLines(missingPath);
		for (int i = 0; i < array.Length; i++)
		{
			string text = array[i].TrimEnd(new char[1] { '\r' }).Replace("\\n", "\n");
			if (text.Length != 0 && !Dict.ContainsKey(text))
			{
				Missing.Add(text);
			}
		}
	}

	private static void SaveMissing()
	{
		List<string> list = new List<string>();
		foreach (string item in Missing)
		{
			if (!Dict.ContainsKey(item))
			{
				list.Add(Normalize(item).Replace("\n", "\\n"));
			}
		}
		File.WriteAllLines(missingPath, list.ToArray());
	}

	private void Update()
	{
		if (Time.unscaledTime < nextScan)
		{
			return;
		}
		nextScan = Time.unscaledTime + 0.5f;
		TMP_Text[] array = Object.FindObjectsOfType<TMP_Text>();
		foreach (TMP_Text val in array)
		{
			string text = val.text;
			if (!string.IsNullOrEmpty(text) && !FontFix.HasCyrillic(text) && TryTranslate(text, out var ru))
			{
				val.text = ru;
				if (FontFix.HasCyrillic(ru))
				{
					FontFix.Apply(val);
				}
			}
		}
		if (!dirty)
		{
			return;
		}
		dirty = false;
		try
		{
			SaveMissing();
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("Не удалось записать missing.txt: " + ex.Message));
		}
	}
}
[HarmonyPatch(/*Could not decode attribute arguments.*/)]
internal static class TextPatch
{
	private static void Prefix(TMP_Text __instance, ref string value)
	{
		if (!string.IsNullOrEmpty(value) && !FontFix.HasCyrillic(value) && RussianLocalization.TryTranslate(value, out var ru))
		{
			value = ru;
			if (FontFix.HasCyrillic(ru))
			{
				FontFix.Apply(__instance);
			}
		}
	}
}