Decompiled source of RevTranslate v1.0.0

RevTranslate.dll

Decompiled an hour 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;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[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;
		}
	}
}
namespace RevTranslate
{
	[BepInPlugin("rev.translate", "RevTranslate", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "rev.translate";

		public const string Name = "RevTranslate";

		public const string Version = "1.0.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> CollectMissing;

		private void Awake()
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			CollectMissing = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "CollectMissing", true, "Write every name that has no translation yet into rev.translate.missing.tsv, ready to be filled in.");
			Dictionary.Load(Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath));
			new Harmony("rev.translate").PatchAll(typeof(Patches));
			Log.LogInfo((object)string.Format("{0} {1} loaded ({2} translations)", "RevTranslate", "1.0.0", Dictionary.Count));
		}

		private void OnApplicationQuit()
		{
			Dictionary.SaveMissing();
		}
	}
	internal static class Dictionary
	{
		private const string FileName = "rev.translate.tsv";

		private const string MissingName = "rev.translate.missing.tsv";

		private static readonly Dictionary<string, string> entries = new Dictionary<string, string>(StringComparer.Ordinal);

		private static readonly HashSet<string> missing = new HashSet<string>(StringComparer.Ordinal);

		private static string directory;

		private static bool missingDirty;

		public static int Count => entries.Count;

		public static void Load(string configDirectory)
		{
			directory = configDirectory;
			string path = Path.Combine(directory, "rev.translate.tsv");
			if (!File.Exists(path))
			{
				WriteTemplate(path);
				return;
			}
			string[] array = File.ReadAllLines(path, Encoding.UTF8);
			foreach (string text in array)
			{
				if (string.IsNullOrWhiteSpace(text) || text.StartsWith("#"))
				{
					continue;
				}
				string[] array2 = text.Split('\t');
				if (array2.Length >= 2)
				{
					string text2 = array2[0].Trim();
					string text3 = array2[1].Trim();
					if (text2.Length > 0 && text3.Length > 0)
					{
						entries[text2] = text3;
					}
				}
			}
		}

		public static string Translate(string original)
		{
			if (string.IsNullOrEmpty(original))
			{
				return original;
			}
			if (entries.TryGetValue(original, out var value))
			{
				return value;
			}
			if (Plugin.CollectMissing.Value && !IsTranslatedAlready(original) && missing.Add(original))
			{
				missingDirty = true;
			}
			return original;
		}

		private static bool IsTranslatedAlready(string text)
		{
			foreach (char c in text)
			{
				if (c >= 'Ѐ' && c <= 'ӿ')
				{
					return true;
				}
			}
			return false;
		}

		public static void SaveMissing()
		{
			if (!missingDirty || directory == null || missing.Count == 0)
			{
				return;
			}
			try
			{
				List<string> list = new List<string> { "# Названия, для которых ещё нет перевода.", "# Впишите перевод во вторую колонку и перенесите строки в rev.translate.tsv" };
				foreach (string item in missing)
				{
					list.Add(item + "\t");
				}
				File.WriteAllLines(Path.Combine(directory, "rev.translate.missing.tsv"), list, Encoding.UTF8);
				missingDirty = false;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Failed to write the missing list: " + ex.Message));
			}
		}

		private static void WriteTemplate(string path)
		{
			try
			{
				File.WriteAllLines(path, new string[4] { "# Словарь перевода: английское название, табуляция, русское название.", "# Строки, начинающиеся с #, игнорируются.", "# Пример:", "# Upgrade Player Health\tЗдоровье" }, Encoding.UTF8);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Failed to create the dictionary file: " + ex.Message));
			}
		}
	}
	internal static class Patches
	{
		private static readonly FieldRef<ItemAttributes, string> CachedNameRef = AccessTools.FieldRefAccess<ItemAttributes, string>("cachedItemName");

		[HarmonyPatch(typeof(ItemAttributes), "RefreshLocalizations")]
		[HarmonyPostfix]
		private static void ItemName(ItemAttributes __instance)
		{
			if (!((Object)(object)__instance.item == (Object)null))
			{
				CachedNameRef.Invoke(__instance) = Dictionary.Translate(CachedNameRef.Invoke(__instance));
			}
		}

		[HarmonyPatch(typeof(MapShopScreen), "ItemNameGet")]
		[HarmonyPostfix]
		private static void ShopListName(ref string __result)
		{
			__result = Dictionary.Translate(__result);
		}

		[HarmonyPatch(typeof(StatsUI), "GetUpgradeDisplayName")]
		[HarmonyPostfix]
		private static void UpgradeName(ref string __result)
		{
			__result = Dictionary.Translate(__result);
		}
	}
}