Decompiled source of EPLang TR Turkish Language v1.0.2

plugins/EPLang-1.0.2.dll

Decompiled a day ago
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.Configuration;
using BepInEx.Logging;
using HarmonyLib;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace EPLang;

[BepInPlugin("com.epstudio.eplang", "EPLang", "1.0.1")]
public class EPLangPlugin : BaseUnityPlugin
{
	private class RegexReplacement
	{
		public Regex Pattern;

		public string Replacement;

		public RegexReplacement(Regex p, string r)
		{
			Pattern = p;
			Replacement = r;
		}
	}

	public static EPLangPlugin Instance;

	internal static ManualLogSource Log;

	private static Dictionary<string, string> Exact = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

	private static List<RegexReplacement> Regexes = new List<RegexReplacement>();

	private static bool Ready;

	private static string ActiveFile = "";

	private ConfigEntry<bool> Enabled;

	private ConfigEntry<string> FolderName;

	private ConfigEntry<bool> LogMissing;

	private ConfigEntry<string> PreferredFile;

	private void Awake()
	{
		//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Expected O, but got Unknown
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable EPLang translations");
		FolderName = ((BaseUnityPlugin)this).Config.Bind<string>("General", "FolderName", "EPLang", "Name of the language folder (you create this folder yourself)");
		LogMissing = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "LogMissing", false, "Log texts that have no translation");
		PreferredFile = ((BaseUnityPlugin)this).Config.Bind<string>("General", "PreferredFile", "", "When multiple language files exist, use this exact filename");
		PrintBanner();
		if (!Enabled.Value)
		{
			Log.LogInfo((object)"EPLang disabled by config.");
			return;
		}
		LoadLanguageFiles();
		if (Ready)
		{
			Harmony val = new Harmony("com.epstudio.eplang");
			val.PatchAll(typeof(EPLangPlugin).Assembly);
			Log.LogInfo((object)("EPLang 1.0.1 ready | File: " + ActiveFile + " | Entries: " + Exact.Count));
		}
	}

	private void PrintBanner()
	{
		Log.LogInfo((object)"+=============================================================+");
		Log.LogInfo((object)"|                                                             |");
		Log.LogInfo((object)"|      ███████╗██████╗ ██╗      █████╗ ███╗   ██╗ ██████╗     |");
		Log.LogInfo((object)"|      ██╔════╝██╔══██╗██║     ██╔══██╗████╗  ██║██╔════╝     |");
		Log.LogInfo((object)"|      █████╗  ██████╔╝██║     ███████║██╔██╗ ██║██║  ███╗    |");
		Log.LogInfo((object)"|      ██╔══╝  ██╔═══╝ ██║     ██╔══██║██║╚██╗██║██║   ██║    |");
		Log.LogInfo((object)"|      ███████╗██║     ███████╗██║  ██║██║ ╚████║╚██████╔╝    |");
		Log.LogInfo((object)"|      ╚══════╝╚═╝     ╚══════╝╚═╝  ╚═╝╚═╝  ╚═══╝ ╚═════╝     |");
		Log.LogInfo((object)"|                                                             |");
		Log.LogInfo((object)"|          Independent Language System  v1.0.1              |");
		Log.LogInfo((object)"|                                                             |");
		Log.LogInfo((object)"|          Author : ElderPlayer                               |");
		Log.LogInfo((object)"|          Studio : EPStudio                                  |");
		Log.LogInfo((object)"|                                                             |");
		Log.LogInfo((object)"+=============================================================+");
	}

	private void LoadLanguageFiles()
	{
		Exact.Clear();
		Regexes.Clear();
		Ready = false;
		ActiveFile = "";
		string[] array = new string[4]
		{
			Path.Combine(Paths.BepInExRootPath, FolderName.Value),
			Path.Combine(Paths.ConfigPath, FolderName.Value),
			Path.Combine(Paths.PluginPath, FolderName.Value),
			Path.Combine(Paths.GameRootPath, FolderName.Value)
		};
		string text = null;
		for (int i = 0; i < array.Length; i++)
		{
			if (Directory.Exists(array[i]))
			{
				text = array[i];
				break;
			}
		}
		if (text == null)
		{
			Log.LogWarning((object)("EPLang folder not found. Create a folder named \"" + FolderName.Value + "\" and place .txt / .tsv files inside it."));
			return;
		}
		List<string> list = new List<string>();
		string[] files = Directory.GetFiles(text, "*.*", SearchOption.TopDirectoryOnly);
		for (int j = 0; j < files.Length; j++)
		{
			string text2 = Path.GetExtension(files[j]).ToLowerInvariant();
			if (text2 == ".txt" || text2 == ".tsv")
			{
				list.Add(files[j]);
			}
		}
		if (list.Count == 0)
		{
			Log.LogWarning((object)"EPLang folder exists but contains no .txt or .tsv files.");
			return;
		}
		if (list.Count > 1)
		{
			string value = PreferredFile.Value;
			if (!string.IsNullOrEmpty(value))
			{
				string text3 = null;
				for (int k = 0; k < list.Count; k++)
				{
					string fileName = Path.GetFileName(list[k]);
					string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(list[k]);
					if (string.Equals(fileName, value, StringComparison.OrdinalIgnoreCase) || string.Equals(fileNameWithoutExtension, value, StringComparison.OrdinalIgnoreCase))
					{
						text3 = list[k];
						break;
					}
				}
				if (text3 == null)
				{
					Log.LogError((object)"Multiple language files detected and PreferredFile does not match any:");
					for (int l = 0; l < list.Count; l++)
					{
						Log.LogError((object)("  - " + Path.GetFileName(list[l])));
					}
					Log.LogError((object)"Set PreferredFile in config or keep only one file.");
					return;
				}
				Log.LogWarning((object)("Multiple language files found. Using preferred: " + Path.GetFileName(text3)));
				list.Clear();
				list.Add(text3);
			}
			else
			{
				list.Sort(StringComparer.OrdinalIgnoreCase);
				Log.LogWarning((object)("Multiple language files (" + list.Count + "). Auto-selecting: " + Path.GetFileName(list[0])));
				for (int m = 1; m < list.Count; m++)
				{
					Log.LogWarning((object)("  ignored: " + Path.GetFileName(list[m])));
				}
				string item = list[0];
				list.Clear();
				list.Add(item);
			}
		}
		string path = list[0];
		ParseFile(path);
		ActiveFile = Path.GetFileName(path);
		Ready = Exact.Count > 0 || Regexes.Count > 0;
		if (!Ready)
		{
			Log.LogWarning((object)("Language file contained no usable entries: " + ActiveFile));
			return;
		}
		Log.LogInfo((object)("Loaded " + Exact.Count + " entries from " + ActiveFile));
	}

	private void ParseFile(string path)
	{
		try
		{
			string[] array = File.ReadAllLines(path, Encoding.UTF8);
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length == 0 || text[0] == '#' || (text.Length > 1 && text[0] == '/' && text[1] == '/'))
				{
					continue;
				}
				int num = text.IndexOf('\t');
				if (num > 0)
				{
					AddExact(text.Substring(0, num).Trim(), text.Substring(num + 1).Trim());
					continue;
				}
				int num2 = text.IndexOf('=');
				if (num2 <= 0)
				{
					continue;
				}
				string text2 = text.Substring(0, num2).Trim();
				string text3 = text.Substring(num2 + 1).Trim();
				if (text2.StartsWith("sr:", StringComparison.OrdinalIgnoreCase))
				{
					string pattern = text2.Substring(3).Trim().Trim('"');
					try
					{
						Regexes.Add(new RegexReplacement(new Regex(pattern, RegexOptions.Compiled | RegexOptions.CultureInvariant), text3));
					}
					catch (Exception ex)
					{
						Log.LogWarning((object)("Invalid regex: " + ex.Message));
					}
				}
				else
				{
					AddExact(text2, text3);
				}
			}
		}
		catch (Exception ex2)
		{
			Log.LogError((object)("Could not read language file: " + ex2.Message));
		}
	}

	private static void AddExact(string key, string value)
	{
		if (key != null && key.Length != 0 && value != null && value.Length != 0)
		{
			Exact[key] = value;
		}
	}

	internal static string Translate(string original)
	{
		if (!Ready || original == null || original.Length == 0)
		{
			return original;
		}
		if (Exact.TryGetValue(original, out var value))
		{
			return value;
		}
		string text = Regex.Replace(original, "<[^>]+>", "").Trim();
		if (text.Length > 0 && text != original && Exact.TryGetValue(text, out value))
		{
			return value;
		}
		for (int i = 0; i < Regexes.Count; i++)
		{
			if (Regexes[i].Pattern.IsMatch(original))
			{
				return Regexes[i].Pattern.Replace(original, Regexes[i].Replacement);
			}
		}
		if (Instance != null && Instance.LogMissing.Value)
		{
			Log.LogDebug((object)("[Missing] " + original));
		}
		return original;
	}
}
public static class PluginInfo
{
	public const string PLUGIN_GUID = "com.epstudio.eplang";

	public const string PLUGIN_NAME = "EPLang";

	public const string PLUGIN_VERSION = "1.0.1";
}
[HarmonyPatch]
internal static class TextPatches
{
	private static IEnumerable<MethodBase> TargetMethods()
	{
		string[] typeNames = new string[3] { "UnityEngine.UI.Text", "TMPro.TMP_Text", "UnityEngine.TextMesh" };
		for (int i = 0; i < typeNames.Length; i++)
		{
			Type type = AccessTools.TypeByName(typeNames[i]);
			if (!(type == null))
			{
				MethodBase setter = AccessTools.PropertySetter(type, "text");
				if (setter != null)
				{
					yield return setter;
				}
			}
		}
	}

	private static void Prefix(ref string value)
	{
		if (value != null)
		{
			value = EPLangPlugin.Translate(value);
		}
	}
}