Decompiled source of Saga del Doge Vikingo v1.1.1

plugins/TraduccionES.dll

Decompiled 10 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace TraduccionES;

[BepInPlugin("piero.TraduccionES", "TraduccionES", "1.0.1")]
public class Plugin : BaseUnityPlugin
{
	public const string GUID = "piero.TraduccionES";

	public const string VERSION = "1.0.1";

	public const string IDIOMA = "Spanish";

	internal static ManualLogSource Log;

	internal static Plugin Instance;

	internal static string Carpeta;

	internal static ConfigEntry<bool> GenerarFaltantes;

	internal static ConfigEntry<KeyCode> TeclaRecargar;

	internal static readonly Dictionary<string, string> ES = new Dictionary<string, string>(StringComparer.Ordinal);

	internal static readonly Dictionary<string, string> ArchivoDe = new Dictionary<string, string>(StringComparer.Ordinal);

	internal static readonly Dictionary<string, string> LIT = new Dictionary<string, string>(StringComparer.Ordinal);

	internal static string IdiomaActual = "";

	internal static HashSet<string> ClavesVanilla;

	private static FieldInfo fTranslations;

	private static FieldInfo fCache;

	private static FieldInfo fSettings;

	private static readonly Regex Linea = new Regex("^\\s*(?:\"(?<k>(?:\\\\.|[^\"\\\\])+)\"|'(?<k>[^']+)'|(?<k>[^\\s\"'#:{}\\[\\],][^:]*?))\\s*:\\s*(?<v>.*?)\\s*,?\\s*$", RegexOptions.Compiled);

	private static int frameIdioma = -1;

	private static bool cacheIdioma;

	private void Awake()
	{
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		Carpeta = Path.Combine(Paths.ConfigPath, "TraduccionES");
		Directory.CreateDirectory(Carpeta);
		GenerarFaltantes = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "GenerarListaFaltantes", true, "Genera BepInEx/config/TraduccionES/_faltantes.yml con los textos de mods que aun no tienen traduccion.");
		TeclaRecargar = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("General", "TeclaRecargar", (KeyCode)0, "Tecla para recargar las traducciones sin reiniciar el juego (None = desactivado).");
		fTranslations = AccessTools.Field(typeof(Localization), "m_translations");
		fCache = AccessTools.Field(typeof(Localization), "m_cache");
		fSettings = AccessTools.Field(typeof(Localization), "m_localizationSettings");
		Cargar();
		new Harmony("piero.TraduccionES").PatchAll(typeof(Plugin).Assembly);
	}

	private void Update()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		if ((int)TeclaRecargar.Value != 0 && Input.GetKeyDown(TeclaRecargar.Value))
		{
			Cargar();
			Aplicar(Localization.instance, "recarga manual");
		}
	}

	internal static void Cargar()
	{
		ES.Clear();
		ArchivoDe.Clear();
		LIT.Clear();
		IOrderedEnumerable<string> orderedEnumerable = (from f in Directory.GetFiles(Carpeta, "*.*", SearchOption.AllDirectories)
			where (f.EndsWith(".yml", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".yaml", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) && !Path.GetFileName(f).StartsWith("_")
			select f).OrderBy<string, string>((string f) => f, StringComparer.OrdinalIgnoreCase);
		foreach (string item in orderedEnumerable)
		{
			int num = 0;
			bool flag = Path.GetFileName(item).StartsWith("LIT_", StringComparison.OrdinalIgnoreCase);
			try
			{
				string[] array = File.ReadAllLines(item, Encoding.UTF8);
				foreach (string text in array)
				{
					string text2 = text.TrimStart(new char[1] { '\ufeff' });
					if (text2.TrimStart(new char[0]).StartsWith("#"))
					{
						continue;
					}
					Match match = Linea.Match(text2);
					if (!match.Success)
					{
						continue;
					}
					string text3 = match.Groups["k"].Value.Trim();
					if (text3.StartsWith("\""))
					{
						continue;
					}
					string text4 = Valor(match.Groups["v"].Value);
					if (flag)
					{
						text3 = Unescape(text3);
						if (text3.Length != 0 && text4 != null && text4.Length != 0)
						{
							LIT[text3] = text4;
							num++;
						}
						continue;
					}
					text3 = Unescape(text3).TrimStart(new char[1] { '$' });
					if (!string.IsNullOrEmpty(text3) && text4 != null && text4.Length != 0)
					{
						ES[text3] = text4;
						ArchivoDe[text3] = Path.GetFileName(item);
						num++;
					}
				}
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Error leyendo " + item + ": " + ex.Message));
			}
			Log.LogInfo((object)("Cargado " + Path.GetFileName(item) + " (" + num + " textos)"));
		}
		Log.LogInfo((object)("Total de traducciones: " + ES.Count + " (+ " + LIT.Count + " textos fijos)"));
	}

	private static string Valor(string v)
	{
		v = v.Trim();
		if (v.Length >= 2 && v[0] == '"' && v[v.Length - 1] == '"')
		{
			return Unescape(v.Substring(1, v.Length - 2));
		}
		if (v.Length >= 2 && v[0] == '\'' && v[v.Length - 1] == '\'')
		{
			return v.Substring(1, v.Length - 2).Replace("''", "'");
		}
		switch (v)
		{
		case "|":
		case ">":
		case "{":
		case "[":
			return null;
		default:
			return v;
		}
	}

	private 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++)
		{
			char c = s[i];
			if (c != '\\' || i + 1 >= s.Length)
			{
				stringBuilder.Append(c);
				continue;
			}
			char c2 = s[++i];
			switch (c2)
			{
			case 'n':
				stringBuilder.Append('\n');
				break;
			case 't':
				stringBuilder.Append('\t');
				break;
			case '"':
				stringBuilder.Append('"');
				break;
			case '\\':
				stringBuilder.Append('\\');
				break;
			case '/':
				stringBuilder.Append('/');
				break;
			case 'u':
				if (i + 4 < s.Length)
				{
					stringBuilder.Append((char)Convert.ToInt32(s.Substring(i + 1, 4), 16));
					i += 4;
				}
				break;
			default:
				stringBuilder.Append('\\').Append(c2);
				break;
			case 'r':
				break;
			}
		}
		return stringBuilder.ToString();
	}

	internal static Dictionary<string, string> Tabla(Localization loc)
	{
		if (loc != null)
		{
			return fTranslations.GetValue(loc) as Dictionary<string, string>;
		}
		return null;
	}

	internal static bool EsEspanolRapido()
	{
		int frameCount = Time.frameCount;
		if (frameCount != frameIdioma)
		{
			frameIdioma = frameCount;
			cacheIdioma = EsEspanol();
		}
		return cacheIdioma;
	}

	internal static bool EsEspanol()
	{
		try
		{
			Localization instance = Localization.instance;
			if (instance != null)
			{
				string selectedLanguage = instance.GetSelectedLanguage();
				if (!string.IsNullOrEmpty(selectedLanguage))
				{
					return selectedLanguage == "Spanish";
				}
			}
		}
		catch
		{
		}
		return IdiomaActual == "Spanish";
	}

	internal static void Aplicar(Localization loc, string motivo)
	{
		if (!EsEspanol())
		{
			return;
		}
		Dictionary<string, string> dictionary = Tabla(loc);
		if (dictionary == null)
		{
			return;
		}
		int num = 0;
		foreach (KeyValuePair<string, string> e in ES)
		{
			if (!dictionary.TryGetValue(e.Key, out var value) || value != e.Value)
			{
				dictionary[e.Key] = e.Value;
				num++;
			}
		}
		LimpiarCache(loc);
		if (num > 0)
		{
			Log.LogInfo((object)("Aplicadas " + num + " traducciones (" + motivo + ")"));
		}
	}

	internal static void LimpiarCache(Localization loc)
	{
		try
		{
			if (fCache == null)
			{
				return;
			}
			object value = fCache.GetValue(loc);
			if (value != null)
			{
				MethodInfo method = value.GetType().GetMethod("Clear", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (method != null)
				{
					method.Invoke(value, null);
				}
			}
		}
		catch
		{
		}
	}

	internal static void CalcularVanilla(Localization loc)
	{
		if (ClavesVanilla != null)
		{
			return;
		}
		ClavesVanilla = new HashSet<string>(StringComparer.Ordinal);
		try
		{
			object value = fSettings.GetValue(null);
			PropertyInfo property = value.GetType().GetProperty("Localizations", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			IEnumerable enumerable = ((property == null) ? null : (property.GetValue(value, null) as IEnumerable));
			MethodInfo methodInfo = AccessTools.Method(typeof(Localization), "DoQuoteLineSplit", (Type[])null, (Type[])null);
			if (enumerable == null || methodInfo == null)
			{
				return;
			}
			foreach (object item in enumerable)
			{
				TextAsset val = (TextAsset)((item is TextAsset) ? item : null);
				if ((Object)(object)val == (Object)null || !(methodInfo.Invoke(loc, new object[1]
				{
					new StringReader(val.text)
				}) is List<List<string>> list))
				{
					continue;
				}
				foreach (List<string> item2 in list)
				{
					if (item2.Count > 0 && !string.IsNullOrEmpty(item2[0]))
					{
						ClavesVanilla.Add(item2[0]);
					}
				}
			}
			Log.LogInfo((object)("Claves vanilla detectadas: " + ClavesVanilla.Count));
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("No se pudieron leer las claves vanilla: " + ex.Message));
		}
	}

	internal static void EscribirFaltantes(string momento)
	{
		if (!GenerarFaltantes.Value)
		{
			return;
		}
		Localization instance = Localization.instance;
		Dictionary<string, string> dictionary = Tabla(instance);
		if (dictionary == null)
		{
			return;
		}
		CalcularVanilla(instance);
		if (ClavesVanilla == null || ClavesVanilla.Count == 0)
		{
			return;
		}
		List<KeyValuePair<string, string>> list = dictionary.Where((KeyValuePair<string, string> kv) => !ClavesVanilla.Contains(kv.Key) && !ES.ContainsKey(kv.Key)).OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> kv) => kv.Key, StringComparer.Ordinal).ToList();
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.AppendLine("# Textos registrados por mods que NO estan en ningun archivo de TraduccionES.");
		stringBuilder.AppendLine("# Idioma: " + (EsEspanol() ? "Spanish" : IdiomaActual) + " | Momento: " + momento + " | " + DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
		stringBuilder.AppendLine("# Total: " + list.Count + "  (algunos ya pueden estar en espanol gracias al propio mod)");
		foreach (KeyValuePair<string, string> item in list)
		{
			stringBuilder.AppendLine(item.Key + ": \"" + Escape(item.Value) + "\"");
		}
		string text = Path.Combine(Carpeta, "_faltantes.yml");
		File.WriteAllText(text, stringBuilder.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
		StringBuilder stringBuilder2 = new StringBuilder();
		stringBuilder2.AppendLine("# Todas las claves de mods activas en este momento (" + momento + ")");
		foreach (KeyValuePair<string, string> item2 in dictionary.Where((KeyValuePair<string, string> kv) => !ClavesVanilla.Contains(kv.Key)).OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> kv) => kv.Key, StringComparer.Ordinal))
		{
			stringBuilder2.AppendLine(item2.Key + ": \"" + Escape(item2.Value) + "\"" + (ArchivoDe.ContainsKey(item2.Key) ? ("   # " + ArchivoDe[item2.Key]) : ""));
		}
		File.WriteAllText(Path.Combine(Carpeta, "_claves_mods.yml"), stringBuilder2.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
		Log.LogInfo((object)("Lista de faltantes escrita (" + list.Count + ") en " + text));
	}

	internal static string Escape(string s)
	{
		return (s ?? "").Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\r", "")
			.Replace("\n", "\\n")
			.Replace("\t", "\\t");
	}

	internal static IEnumerator DespuesDe(float seg, Action a)
	{
		yield return (object)new WaitForSeconds(seg);
		try
		{
			a();
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)ex.Message);
		}
	}
}
[HarmonyPatch(typeof(Localization), "SetupLanguage")]
internal static class Patch_SetupLanguage
{
	[HarmonyPriority(800)]
	[HarmonyPrefix]
	private static void Prefix(string language)
	{
		Plugin.IdiomaActual = language ?? "";
	}

	[HarmonyPriority(-1)]
	[HarmonyPostfix]
	private static void Postfix(Localization __instance)
	{
		Plugin.Aplicar(__instance, "SetupLanguage");
	}
}
[HarmonyPatch(typeof(Localization), "AddWord")]
internal static class Patch_AddWord
{
	[HarmonyPostfix]
	[HarmonyPriority(0)]
	private static void Postfix(Localization __instance, string key)
	{
		if (key != null && Plugin.EsEspanol() && Plugin.ES.TryGetValue(key.TrimStart(new char[1] { '$' }), out var value))
		{
			Dictionary<string, string> dictionary = Plugin.Tabla(__instance);
			if (dictionary != null)
			{
				dictionary[key] = value;
			}
		}
	}
}
[HarmonyPatch(typeof(Localization), "Localize", new Type[] { typeof(string) })]
internal static class Patch_Localize
{
	private static readonly Dictionary<string, string> cache = new Dictionary<string, string>(StringComparer.Ordinal);

	[HarmonyPriority(0)]
	[HarmonyPostfix]
	private static void Postfix(ref string __result)
	{
		if (string.IsNullOrEmpty(__result) || Plugin.LIT.Count == 0 || !Plugin.EsEspanolRapido())
		{
			return;
		}
		if (Plugin.LIT.TryGetValue(__result, out var value))
		{
			__result = value;
		}
		else
		{
			if (__result.Length < 12)
			{
				return;
			}
			if (cache.TryGetValue(__result, out value))
			{
				__result = value;
				return;
			}
			string key = __result;
			string text = __result;
			foreach (KeyValuePair<string, string> item in Plugin.LIT)
			{
				if (item.Key.Length >= 12 && text.IndexOf(item.Key, StringComparison.Ordinal) >= 0)
				{
					text = text.Replace(item.Key, item.Value);
				}
			}
			if (cache.Count > 4000)
			{
				cache.Clear();
			}
			cache[key] = text;
			__result = text;
		}
	}
}
[HarmonyPatch(typeof(FejdStartup), "Start")]
internal static class Patch_Menu
{
	private static void Postfix(FejdStartup __instance)
	{
		Plugin.Aplicar(Localization.instance, "menu");
		((MonoBehaviour)Plugin.Instance).StartCoroutine(Plugin.DespuesDe(8f, delegate
		{
			Plugin.Aplicar(Localization.instance, "menu+8s");
			Plugin.EscribirFaltantes("menu principal");
		}));
	}
}
[HarmonyPatch(typeof(ZNetScene), "Awake")]
internal static class Patch_ZNetScene
{
	private static void Postfix()
	{
		Plugin.Aplicar(Localization.instance, "ZNetScene");
	}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
internal static class Patch_Spawn
{
	private static bool hecho;

	private static void Postfix(Player __instance)
	{
		if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer)
		{
			return;
		}
		Plugin.Aplicar(Localization.instance, "jugador");
		if (!hecho)
		{
			hecho = true;
			((MonoBehaviour)Plugin.Instance).StartCoroutine(Plugin.DespuesDe(10f, delegate
			{
				Plugin.Aplicar(Localization.instance, "jugador+10s");
				Plugin.EscribirFaltantes("en el mundo");
			}));
		}
	}
}