Decompiled source of SleddingChatTranslator v0.1.0

Mods/SleddingChatTranslator.dll

Decompiled 11 hours ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using HarmonyLib;
using Il2CppFishNet.Transporting;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using Il2CppTMPro;
using Il2CppTankAndHealerStudioAssets;
using Il2Cpp_Scripts.Systems.Chat;
using MelonLoader;
using MelonLoader.Preferences;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using SleddingChatTranslator;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Localization;
using UnityEngine.Localization.Settings;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(TranslatorMod), "Sledding Chat Translator", "0.1.0", "gomburger", null)]
[assembly: MelonGame("The Sledding Corporation", "Sledding Game")]
[assembly: HarmonyDontPatchAll]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("SleddingChatTranslator")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("SleddingChatTranslator")]
[assembly: AssemblyTitle("SleddingChatTranslator")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[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 SleddingChatTranslator
{
	internal static class ApiKeys
	{
		private struct DataBlob
		{
			public int cbData;

			public IntPtr pbData;
		}

		private const string Prefix = "dpapi:";

		private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("SleddingChatTranslator.ApiKey");

		private const int CRYPTPROTECT_UI_FORBIDDEN = 1;

		internal static string Get(Setting<string> entry)
		{
			string text = entry.Value?.Trim() ?? "";
			if (text.Length == 0)
			{
				return "";
			}
			if (!text.StartsWith("dpapi:", StringComparison.Ordinal))
			{
				return text;
			}
			try
			{
				return Unprotect(text.Substring("dpapi:".Length));
			}
			catch (Exception ex)
			{
				Mod.Log.LogWarning("API key could not be decrypted (config copied from another PC or user?): " + ex.Message);
				return "";
			}
		}

		internal static void Set(Setting<string> entry, string plainKey)
		{
			plainKey = plainKey?.Trim() ?? "";
			if (plainKey.Length == 0)
			{
				entry.Value = "";
				return;
			}
			try
			{
				entry.Value = "dpapi:" + Protect(plainKey);
			}
			catch (Exception ex)
			{
				Mod.Log.LogWarning($"Could not encrypt {entry.Key} ({ex.Message}); it is stored in plain text instead.");
				entry.Value = plainKey;
			}
		}

		internal static bool IsSet(Setting<string> entry)
		{
			return !string.IsNullOrWhiteSpace(entry.Value);
		}

		internal static bool IsPlain(Setting<string> entry)
		{
			string text = entry.Value?.Trim() ?? "";
			if (text.Length > 0)
			{
				return !text.StartsWith("dpapi:", StringComparison.Ordinal);
			}
			return false;
		}

		internal static void MigratePlain(Setting<string> entry)
		{
			if (IsPlain(entry))
			{
				Set(entry, entry.Value);
				if (!IsPlain(entry))
				{
					Mod.Log.LogInfo("Encrypted the stored " + entry.Key);
				}
			}
		}

		[DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		private static extern bool CryptProtectData(ref DataBlob dataIn, string description, ref DataBlob entropy, IntPtr reserved, IntPtr prompt, int flags, ref DataBlob dataOut);

		[DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		private static extern bool CryptUnprotectData(ref DataBlob dataIn, IntPtr description, ref DataBlob entropy, IntPtr reserved, IntPtr prompt, int flags, ref DataBlob dataOut);

		[DllImport("kernel32.dll")]
		private static extern IntPtr LocalFree(IntPtr mem);

		private static string Protect(string plain)
		{
			return Convert.ToBase64String(Run(Encoding.UTF8.GetBytes(plain), protect: true));
		}

		private static string Unprotect(string base64)
		{
			return Encoding.UTF8.GetString(Run(Convert.FromBase64String(base64), protect: false));
		}

		private static byte[] Run(byte[] data, bool protect)
		{
			DataBlob dataIn = default(DataBlob);
			DataBlob entropy = default(DataBlob);
			DataBlob dataOut = default(DataBlob);
			GCHandle gCHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
			GCHandle gCHandle2 = GCHandle.Alloc(Entropy, GCHandleType.Pinned);
			try
			{
				dataIn.cbData = data.Length;
				dataIn.pbData = gCHandle.AddrOfPinnedObject();
				entropy.cbData = Entropy.Length;
				entropy.pbData = gCHandle2.AddrOfPinnedObject();
				if (!(protect ? CryptProtectData(ref dataIn, "SleddingChatTranslator", ref entropy, IntPtr.Zero, IntPtr.Zero, 1, ref dataOut) : CryptUnprotectData(ref dataIn, IntPtr.Zero, ref entropy, IntPtr.Zero, IntPtr.Zero, 1, ref dataOut)))
				{
					throw new InvalidOperationException("DPAPI error " + Marshal.GetLastWin32Error());
				}
				byte[] array = new byte[dataOut.cbData];
				Marshal.Copy(dataOut.pbData, array, 0, dataOut.cbData);
				return array;
			}
			finally
			{
				gCHandle.Free();
				gCHandle2.Free();
				if (dataOut.pbData != IntPtr.Zero)
				{
					LocalFree(dataOut.pbData);
				}
			}
		}
	}
	internal static class Bilingual
	{
		private const char Mark = '\u200b';

		internal static string Wrap(string original)
		{
			return "\u200b" + original + "\u200b";
		}

		internal static bool TryExtractOriginal(string text, out string original)
		{
			original = null;
			if (string.IsNullOrEmpty(text))
			{
				return false;
			}
			int num = text.IndexOf('\u200b');
			if (num < 0)
			{
				return false;
			}
			int num2 = text.IndexOf('\u200b', num + 1);
			if (num2 <= num + 1)
			{
				return false;
			}
			original = text.Substring(num + 1, num2 - num - 1).Trim();
			return original.Length > 0;
		}
	}
	internal static class ChatBoxTweaks
	{
		private static IntPtr _boxPtr;

		private static string _appliedLayoutKey;

		private static bool _origScrollWheel;

		private static bool _origScrollbar;

		private static bool _origNoRich;

		private static bool _origOnlyOnHover;

		private static float _origScrollSpeed;

		private static float _origFontSize;

		private static float _origInputFont;

		private static float _origHSpacing;

		private static float _origVSpacing;

		private static float _origScrollbarWidth;

		private static float _origInactiveTime;

		private static float _origExtraImageHeight;

		private static float _origEmojiSize;

		private static int _origMaxText;

		private static Vector2 _origRatio;

		private static Vector2 _origInputSize;

		private static Vector2 _origInputPos;

		private static bool _hasScrollbarParts;

		private static int _scrollbarFixLogs;

		private static int _lastCount = -1;

		private static IntPtr _lastChatPtr;

		private static int _snapFrames;

		private static int _snapLogs;

		private static float _forceSnapUntil = -10f;

		private static bool _logPending;

		private static float _nextLog;

		private static readonly Regex IndentTag = new Regex("<indent=[0-9.]+(em)?>");

		private static readonly Dictionary<IntPtr, float> Indented = new Dictionary<IntPtr, float>();

		private static int _indentLogs;

		private const string LeadSpaces = "  ";

		internal static bool HasScrollbarParts => _hasScrollbarParts;

		internal static UltimateChatBox CurrentBox
		{
			get
			{
				try
				{
					ChatManagerBase instance = ChatManager.Instance;
					return ((Object)(object)instance == (Object)null) ? null : instance.chatBox;
				}
				catch
				{
					return null;
				}
			}
		}

		private static float Now => Time.realtimeSinceStartup;

		private static string LayoutKey => $"{Mod.ChatWidthPercent.Value}|{Mod.ChatHeightPercent.Value}|{Mod.ChatTextPercent.Value}|{Mod.ScrollEnabled.Value}|{Mod.ScrollSpeed.Value}|{Mod.HistoryLines.Value}|{Mod.ShowScrollbar.Value}|{Mod.UseRichText.Value}";

		private static bool WantScrollbar
		{
			get
			{
				if (_hasScrollbarParts && Mod.ScrollEnabled.Value)
				{
					return Mod.ShowScrollbar.Value;
				}
				return false;
			}
		}

		internal static void OnLocalSend()
		{
			if (Mod.AutoScrollToBottom.Value)
			{
				_forceSnapUntil = Now + 3f;
				_snapFrames = 3;
			}
		}

		internal static void Tick()
		{
			UltimateChatBox currentBox = CurrentBox;
			if ((Object)(object)currentBox == (Object)null)
			{
				return;
			}
			try
			{
				if (((Il2CppObjectBase)currentBox).Pointer != _boxPtr)
				{
					OnNewBox(currentBox);
				}
				string layoutKey = LayoutKey;
				if (layoutKey != _appliedLayoutKey)
				{
					_appliedLayoutKey = layoutKey;
					Apply(currentBox);
				}
				TrackNewMessages(currentBox);
				IndentOriginals(currentBox);
				if (_logPending && Now >= _nextLog)
				{
					_logPending = false;
					_nextLog = Now + 1.5f;
					RectTransform inputFieldTransform = currentBox.inputFieldTransform;
					Mod.Debug($"Chat box applied: width={Mod.ChatWidthPercent.Value}% height={Mod.ChatHeightPercent.Value}% text={Mod.ChatTextPercent.Value}% font={currentBox.CalculatedFontSize:0.#} rect={RectSize(currentBox.BaseTransform)} input={RectSize(inputFieldTransform)} spacing=({currentBox.horizontalSpacing:0.###},{currentBox.verticalSpacing:0.###}) scrollbar={currentBox.useScrollbar}");
				}
			}
			catch (Exception ex)
			{
				_appliedLayoutKey = LayoutKey;
				Mod.Log.LogWarning("Chat box tweak failed: " + ex);
			}
		}

		internal static void LateTick()
		{
			UltimateChatBox currentBox = CurrentBox;
			if ((Object)(object)currentBox == (Object)null || ((Il2CppObjectBase)currentBox).Pointer != _boxPtr)
			{
				return;
			}
			try
			{
				KeepScrollbarVisible(currentBox);
				if (_snapFrames > 0)
				{
					_snapFrames--;
					SnapToBottom(currentBox);
				}
			}
			catch (Exception ex)
			{
				_snapFrames = 0;
				Mod.Log.LogWarning("Chat box late update failed: " + ex.Message);
			}
		}

		private static void OnNewBox(UltimateChatBox box)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			_boxPtr = ((Il2CppObjectBase)box).Pointer;
			_origScrollWheel = box.useScrollWheel;
			_origScrollbar = box.useScrollbar;
			_origOnlyOnHover = box.visibleOnlyOnHover;
			_origNoRich = box.disableRichTextFromPlayers;
			_origScrollSpeed = box.mouseScrollSpeed;
			_origMaxText = box.maxTextInChatBox;
			_origRatio = box.chatBoxSizeRatio;
			_origFontSize = box.smartFontSize;
			_origInputFont = box.inputFieldSmartFontSize;
			_origInputSize = box.inputFieldSize;
			_origInputPos = box.inputFieldPosition;
			_origHSpacing = box.horizontalSpacing;
			_origVSpacing = box.verticalSpacing;
			_origScrollbarWidth = box.scrollbarWidth;
			_origInactiveTime = box.scrollbarInactiveTime;
			_origExtraImageHeight = box.extraImageHeight;
			_origEmojiSize = box.emojiButtonSize;
			_hasScrollbarParts = (Object)(object)box.scrollbarBase != (Object)null && (Object)(object)box.scrollbarHandle != (Object)null;
			_appliedLayoutKey = null;
			_lastCount = -1;
			Mod.Debug($"Chat box found: ratio={_origRatio} font={_origFontSize} calcFont={box.CalculatedFontSize} rect={RectSize(box.BaseTransform)} input size={_origInputSize} pos={_origInputPos} font={_origInputFont} rect={RectSize(box.inputFieldTransform)} spacing=({_origHSpacing},{_origVSpacing}) scrollbarWidth={_origScrollbarWidth} inactive={_origInactiveTime} extraImg={_origExtraImageHeight} emoji={_origEmojiSize} scrollbar={_origScrollbar} parts={_hasScrollbarParts} maxText={_origMaxText}");
		}

		private static void Apply(UltimateChatBox box)
		{
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			box.disableRichTextFromPlayers = !Mod.UseRichText.Value && _origNoRich;
			bool value = Mod.ScrollEnabled.Value;
			box.useScrollWheel = value || _origScrollWheel;
			float num = ((_origScrollSpeed > 0f) ? _origScrollSpeed : 1f);
			box.mouseScrollSpeed = (value ? (num * Mod.ScrollSpeed.Value) : _origScrollSpeed);
			box.maxTextInChatBox = Mod.HistoryLines.Value;
			float num2 = (float)Mod.ChatWidthPercent.Value / 100f;
			float num3 = (float)Mod.ChatHeightPercent.Value / 100f;
			float num4 = (float)Mod.ChatTextPercent.Value / 100f;
			box.chatBoxSizeRatio = new Vector2(_origRatio.x * num2, _origRatio.y * num3);
			box.smartFontSize = _origFontSize * num4 / num3;
			box.inputFieldSize = new Vector2(_origInputSize.x, _origInputSize.y / num3);
			box.inputFieldPosition = new Vector2(_origInputPos.x, _origInputPos.y / num3);
			box.inputFieldSmartFontSize = _origInputFont;
			box.extraImageHeight = _origExtraImageHeight;
			box.emojiButtonSize = _origEmojiSize;
			box.horizontalSpacing = _origHSpacing / num2;
			box.verticalSpacing = _origVSpacing / num2;
			box.scrollbarWidth = _origScrollbarWidth / num2;
			ApplyScrollbarSettings(box);
			box.isDirty = true;
			TryCall((Action)box.UpdateChatBoxComponentSizes, "UpdateChatBoxComponentSizes");
			TryCall((Action)box.UpdatePositioning, "UpdatePositioning");
			TryCall((Action)box.RepositionAllChats, "RepositionAllChats");
			Indented.Clear();
			if (Mod.AutoScrollToBottom.Value)
			{
				_snapFrames = 3;
			}
			_logPending = true;
		}

		private static void ApplyScrollbarSettings(UltimateChatBox box)
		{
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			if (!_hasScrollbarParts)
			{
				return;
			}
			bool wantScrollbar = WantScrollbar;
			box.useScrollbar = wantScrollbar || _origScrollbar;
			box.visibleOnlyOnHover = !wantScrollbar && _origOnlyOnHover;
			box.scrollbarInactiveTime = (wantScrollbar ? 1000000f : _origInactiveTime);
			if (!wantScrollbar)
			{
				return;
			}
			if (!((Component)box.scrollbarBase).gameObject.activeSelf)
			{
				((Component)box.scrollbarBase).gameObject.SetActive(true);
			}
			if (!((Component)box.scrollbarHandle).gameObject.activeSelf)
			{
				((Component)box.scrollbarHandle).gameObject.SetActive(true);
			}
			if ((Object)(object)box.scrollbarCanvasGroup == (Object)null)
			{
				CanvasGroup component = ((Component)box.scrollbarBase).GetComponent<CanvasGroup>();
				if ((Object)(object)component != (Object)null)
				{
					box.scrollbarCanvasGroup = component;
				}
			}
			Image scrollbarHandleImage = box.scrollbarHandleImage;
			if ((Object)(object)scrollbarHandleImage != (Object)null && ((Graphic)scrollbarHandleImage).color.a < 0.05f)
			{
				Color scrollbarHandleNormalColor = box.scrollbarHandleNormalColor;
				((Graphic)scrollbarHandleImage).color = (Color)((scrollbarHandleNormalColor.a < 0.05f) ? new Color(1f, 1f, 1f, 0.6f) : scrollbarHandleNormalColor);
			}
		}

		private static void KeepScrollbarVisible(UltimateChatBox box)
		{
			if (!WantScrollbar)
			{
				return;
			}
			bool flag = false;
			try
			{
				flag = (Object)(object)ChatManager.Instance != (Object)null && ChatManager.Instance.IsChatOpen;
			}
			catch
			{
			}
			if (!flag)
			{
				CanvasGroup scrollbarCanvasGroup = box.scrollbarCanvasGroup;
				if ((Object)(object)scrollbarCanvasGroup != (Object)null && scrollbarCanvasGroup.alpha > 0f)
				{
					scrollbarCanvasGroup.alpha = 0f;
				}
				box.scrollbarToggle = false;
				box.scrollbarToggleLerpValue = 0f;
				return;
			}
			string text = "";
			if (!box.useScrollbar)
			{
				box.useScrollbar = true;
				text += " useScrollbar";
			}
			if (box.visibleOnlyOnHover)
			{
				box.visibleOnlyOnHover = false;
				text += " onlyOnHover";
			}
			if (!box.scrollbarToggle)
			{
				box.scrollbarToggle = true;
				text += " toggle";
			}
			box.scrollbarToggleLerpValue = 1f;
			box._inactiveTime = 0f;
			CanvasGroup scrollbarCanvasGroup2 = box.scrollbarCanvasGroup;
			if ((Object)(object)scrollbarCanvasGroup2 != (Object)null && scrollbarCanvasGroup2.alpha < 0.99f)
			{
				scrollbarCanvasGroup2.alpha = 1f;
				text += " alpha";
			}
			GameObject gameObject = ((Component)box.scrollbarBase).gameObject;
			if (!gameObject.activeSelf)
			{
				gameObject.SetActive(true);
				text += " baseActive";
			}
			if (text.Length > 0 && _scrollbarFixLogs < 5)
			{
				_scrollbarFixLogs++;
				Mod.Debug($"Scrollbar kept visible:{text} (active={box.ScrollbarActive})");
			}
		}

		private static void TrackNewMessages(UltimateChatBox box)
		{
			List<ChatInformation> chatInformations = box.ChatInformations;
			if (chatInformations == null)
			{
				return;
			}
			int count = chatInformations.Count;
			IntPtr intPtr = ((count > 0 && chatInformations[count - 1] != null) ? ((Il2CppObjectBase)chatInformations[count - 1]).Pointer : IntPtr.Zero);
			if (_lastCount >= 0 && (count != _lastCount || intPtr != _lastChatPtr) && Mod.AutoScrollToBottom.Value)
			{
				bool flag = false;
				try
				{
					flag = (Object)(object)ChatManager.Instance != (Object)null && ChatManager.Instance.IsChatOpen;
				}
				catch
				{
				}
				if (!flag || Now < _forceSnapUntil)
				{
					_snapFrames = 3;
				}
			}
			_lastCount = count;
			_lastChatPtr = intPtr;
		}

		private static void SnapToBottom(UltimateChatBox box)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			RectTransform chatContentBox = box.ChatContentBox;
			if ((Object)(object)chatContentBox == (Object)null)
			{
				_snapFrames = 0;
				return;
			}
			Vector2 anchoredPosition = chatContentBox.anchoredPosition;
			float y = box.bottomContentPosition.y;
			if (Mathf.Abs(anchoredPosition.y - y) < 0.5f)
			{
				_snapFrames = 0;
				return;
			}
			chatContentBox.anchoredPosition = new Vector2(anchoredPosition.x, y);
			RectTransform scrollbarHandle = box.scrollbarHandle;
			if ((Object)(object)scrollbarHandle != (Object)null && _hasScrollbarParts)
			{
				scrollbarHandle.anchoredPosition = box.scrollbarBottomPosition;
			}
			TryCall((Action)box.ConstrainScrollbarHandle, "ConstrainScrollbarHandle");
			box.isDirty = true;
			if (_snapLogs < 4)
			{
				_snapLogs++;
				Mod.Debug($"Auto-scroll: content y {anchoredPosition.y:0.#} -> {y:0.#}");
			}
		}

		private static void IndentOriginals(UltimateChatBox box)
		{
			if (!Mod.UseRichText.Value)
			{
				return;
			}
			List<ChatInformation> chatInformations = box.ChatInformations;
			if (chatInformations == null)
			{
				return;
			}
			float calculatedFontSize = box.CalculatedFontSize;
			for (int i = Math.Max(0, chatInformations.Count - 8); i < chatInformations.Count; i++)
			{
				ChatInformation val = chatInformations[i];
				if (val == null)
				{
					continue;
				}
				string displayMessage = val.DisplayMessage;
				if (displayMessage == null || !displayMessage.Contains("\n</line-height>") || (Indented.TryGetValue(((Il2CppObjectBase)val).Pointer, out var value) && Mathf.Abs(value - calculatedFontSize) < 0.01f))
				{
					continue;
				}
				Indented[((Il2CppObjectBase)val).Pointer] = calculatedFontSize;
				if (Indented.Count > 1000)
				{
					Indented.Clear();
				}
				try
				{
					Indent(box, val);
				}
				catch (Exception ex)
				{
					if (_indentLogs++ < 3)
					{
						Mod.Log.LogWarning("Indent failed: " + ex.Message);
					}
				}
			}
		}

		private static void Indent(UltimateChatBox box, ChatInformation ci)
		{
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			TextMeshProUGUI chatText = ci.chatText;
			if ((Object)(object)chatText == (Object)null)
			{
				return;
			}
			string text = WithSpace(Clean(ci.DisplayMessage));
			string text2 = (ci._Message_k__BackingField = WithSpace(Clean(ci.Message ?? "")));
			ci.DisplayMessage = text;
			ci.UpdateText();
			((TMP_Text)chatText).ForceMeshUpdate(true, true);
			int num = (((TMP_Text)chatText).text ?? "").IndexOf(text, StringComparison.Ordinal);
			if (num < 0)
			{
				return;
			}
			TMP_TextInfo textInfo = ((TMP_Text)chatText).textInfo;
			Il2CppReferenceArray<TMP_CharacterInfo> characterInfo = textInfo.characterInfo;
			float num2 = float.NaN;
			for (int i = 0; i < textInfo.characterCount && i < ((Il2CppArrayBase<TMP_CharacterInfo>)(object)characterInfo).Length; i++)
			{
				TMP_CharacterInfo val = ((Il2CppArrayBase<TMP_CharacterInfo>)(object)characterInfo)[i];
				if (val.index >= num && val.isVisible)
				{
					num2 = val.origin;
					break;
				}
			}
			if (float.IsNaN(num2))
			{
				return;
			}
			float num3 = num2;
			Rect rect = ((TMP_Text)chatText).rectTransform.rect;
			float num4 = num3 - ((Rect)(ref rect)).xMin;
			if (!(num4 <= 0.5f))
			{
				string text4 = "<indent=" + num4.ToString("0.#", CultureInfo.InvariantCulture) + ">";
				ci._Message_k__BackingField = text4 + text2;
				ci.DisplayMessage = text4 + text;
				ci.UpdateText();
				box.isDirty = true;
				TryCall((Action)box.RepositionAllChats, "RepositionAllChats");
				if (_indentLogs++ < 3)
				{
					Mod.Debug($"Indented original by {num4:0.#} (font {box.CalculatedFontSize:0.#})");
				}
			}
		}

		private static string Clean(string s)
		{
			return IndentTag.Replace(s ?? "", "");
		}

		private static string WithSpace(string s)
		{
			int num = s.IndexOf("\n</line-height>", StringComparison.Ordinal);
			if (num < 0)
			{
				return s;
			}
			int num2 = num + "\n</line-height>".Length;
			int i;
			for (i = num2; i < s.Length && s[i] == ' '; i++)
			{
			}
			return s.Substring(0, num2) + "  " + s.Substring(i);
		}

		private static void TryCall(Action a, string name)
		{
			try
			{
				a();
			}
			catch (Exception ex)
			{
				Mod.Log.LogWarning(name + " failed: " + ex.Message);
			}
		}

		private static string RectSize(RectTransform rt)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)rt == (Object)null)
			{
				return "null";
			}
			Rect rect = rt.rect;
			return $"{((Rect)(ref rect)).width:0}x{((Rect)(ref rect)).height:0}";
		}
	}
	internal static class ChatContext
	{
		private enum Script
		{
			None,
			Latin,
			Hangul,
			Kana,
			Han,
			Cyrillic,
			Greek,
			Hebrew,
			Arabic,
			Thai,
			Other
		}

		internal const string Self = "\u0001self";

		private const int ReliableWeight = 12;

		private const int MaxPlayers = 200;

		private static readonly Dictionary<string, string> PlayerLang = new Dictionary<string, string>();

		private static readonly Queue<string> PlayerOrder = new Queue<string>();

		private const int ContextLines = 5;

		private const float ContextSeconds = 120f;

		private const int ContextChars = 800;

		private static readonly LinkedList<(float Time, string Text)> Recent = new LinkedList<(float, string)>();

		internal static string Hint(string player, string text)
		{
			if (!Mod.RememberPlayerLanguage.Value || string.IsNullOrEmpty(player))
			{
				return null;
			}
			if (!PlayerLang.TryGetValue(player, out var value))
			{
				return null;
			}
			int num = Weight(text);
			if (num == 0 || num >= 12)
			{
				return null;
			}
			if (!ScriptFits(text, value))
			{
				return null;
			}
			return value;
		}

		internal static void Learn(string player, string text, string detected)
		{
			if (string.IsNullOrEmpty(player) || string.IsNullOrEmpty(detected) || Weight(text) < 12)
			{
				return;
			}
			string text2 = Normalize(detected);
			if (ScriptFits(text, text2))
			{
				if (!PlayerLang.ContainsKey(player))
				{
					PlayerOrder.Enqueue(player);
				}
				PlayerLang[player] = text2;
				while (PlayerOrder.Count > 200)
				{
					PlayerLang.Remove(PlayerOrder.Dequeue());
				}
			}
		}

		private static string Normalize(string code)
		{
			code = code.Trim().Replace('_', '-').ToLowerInvariant();
			if (code.StartsWith("zh"))
			{
				if (!code.Contains("tw") && !code.Contains("hk") && !code.Contains("hant"))
				{
					return "zh-CN";
				}
				return "zh-TW";
			}
			int num = code.IndexOf('-');
			if (num <= 0)
			{
				return code;
			}
			return code.Substring(0, num);
		}

		private static Script Of(char c)
		{
			if (c < 'ɐ' || (c >= 'Ḁ' && c <= 'ỿ') || (c >= 'A' && c <= 'z'))
			{
				return Script.Latin;
			}
			if ((c >= '가' && c <= '힣') || (c >= 'ᄀ' && c <= 'ᇿ') || (c >= '\u3130' && c <= '\u318f'))
			{
				return Script.Hangul;
			}
			if ((c >= '\u3040' && c <= 'ヿ') || (c >= 'ㇰ' && c <= 'ㇿ') || (c >= 'ヲ' && c <= '゚'))
			{
				return Script.Kana;
			}
			if ((c >= '一' && c <= '鿿') || (c >= '㐀' && c <= '䶿'))
			{
				return Script.Han;
			}
			if (c >= 'Ѐ' && c <= 'ӿ')
			{
				return Script.Cyrillic;
			}
			if (c >= 'Ͱ' && c <= 'Ͽ')
			{
				return Script.Greek;
			}
			if (c >= '\u0590' && c <= '\u05ff')
			{
				return Script.Hebrew;
			}
			if (c >= '\u0600' && c <= 'ۿ')
			{
				return Script.Arabic;
			}
			if (c >= '\u0e00' && c <= '\u0e7f')
			{
				return Script.Thai;
			}
			return Script.Other;
		}

		private static bool LangUses(string lang, Script s)
		{
			switch (lang.ToLowerInvariant().Split('-')[0])
			{
			case "ko":
				return s == Script.Hangul;
			case "ja":
				if (s != Script.Kana)
				{
					return s == Script.Han;
				}
				return true;
			case "zh":
				return s == Script.Han;
			case "kk":
			case "ru":
			case "uk":
			case "bg":
			case "be":
			case "sr":
			case "mk":
			case "mn":
				return s == Script.Cyrillic;
			case "el":
				return s == Script.Greek;
			case "he":
			case "iw":
			case "yi":
				return s == Script.Hebrew;
			case "ur":
			case "ar":
			case "fa":
				return s == Script.Arabic;
			case "th":
				return s == Script.Thai;
			case "kn":
			case "km":
			case "ka":
			case "bn":
			case "si":
			case "mr":
			case "ml":
			case "my":
			case "hi":
			case "hy":
			case "am":
			case "ta":
			case "te":
			case "gu":
			case "pa":
			case "ne":
			case "lo":
				return false;
			default:
				return s == Script.Latin;
			}
		}

		private static bool ScriptFits(string text, string lang)
		{
			bool result = false;
			foreach (char c in text)
			{
				if (char.IsLetter(c))
				{
					result = true;
					if (!LangUses(lang, Of(c)))
					{
						return false;
					}
				}
			}
			return result;
		}

		private static int Weight(string text)
		{
			int num = 0;
			foreach (char c in text)
			{
				if (char.IsLetter(c))
				{
					Script script = Of(c);
					num += ((script != Script.Hangul && script != Script.Kana && script != Script.Han) ? 1 : 2);
				}
			}
			return num;
		}

		internal static bool ScriptSaysLanguage(string text, string lang)
		{
			if (string.IsNullOrEmpty(lang))
			{
				return false;
			}
			Script script;
			switch (lang.ToLowerInvariant().Split('-')[0])
			{
			case "ko":
				script = Script.Hangul;
				break;
			case "ja":
				script = Script.Kana;
				break;
			case "th":
				script = Script.Thai;
				break;
			case "el":
				script = Script.Greek;
				break;
			case "he":
			case "iw":
				script = Script.Hebrew;
				break;
			default:
				return false;
			}
			bool flag = false;
			bool flag2 = false;
			foreach (char c in text)
			{
				if (char.IsLetter(c))
				{
					flag = true;
					Script script2 = Of(c);
					if (script2 == Script.Kana)
					{
						flag2 = true;
					}
					if (script2 != script && (script != Script.Kana || script2 != Script.Han))
					{
						return false;
					}
				}
			}
			if (flag)
			{
				return script != Script.Kana || flag2;
			}
			return false;
		}

		internal static void Add(string text)
		{
			if (!string.IsNullOrWhiteSpace(text))
			{
				Recent.AddLast((Time.realtimeSinceStartup, text.Trim()));
				while (Recent.Count > 5)
				{
					Recent.RemoveFirst();
				}
			}
		}

		internal static void ClearRecent()
		{
			Recent.Clear();
		}

		internal static string Get()
		{
			if (!Mod.DeepLContext.Value || Mod.Engine.Value != TranslationEngine.DeepL || Recent.Count == 0)
			{
				return null;
			}
			float num = Time.realtimeSinceStartup - 120f;
			StringBuilder stringBuilder = new StringBuilder();
			LinkedListNode<(float, string)> linkedListNode = Recent.Last;
			while (linkedListNode != null && !(linkedListNode.Value.Item1 < num) && stringBuilder.Length + linkedListNode.Value.Item2.Length <= 800)
			{
				stringBuilder.Insert(0, linkedListNode.Value.Item2 + "\n");
				linkedListNode = linkedListNode.Previous;
			}
			if (stringBuilder.Length != 0)
			{
				return stringBuilder.ToString().TrimEnd();
			}
			return null;
		}
	}
	[HarmonyPatch]
	internal static class ChatPatches
	{
		[HarmonyPatch(typeof(ChatManagerBase), "OnClientReceivedChatBroadcastFromServer")]
		[HarmonyPrefix]
		private static bool OnIncoming(ChatManagerBase __instance, ChatMessage chatMessage, Channel channel)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if (TranslatorCore.Delivering)
			{
				return true;
			}
			try
			{
				if (chatMessage == null || (int)chatMessage.MessageType != 0)
				{
					return true;
				}
				string message = chatMessage.Message;
				if (string.IsNullOrWhiteSpace(message))
				{
					return true;
				}
				return !TranslatorCore.QueueIncoming(__instance, chatMessage, channel, message);
			}
			catch (Exception ex)
			{
				Mod.Log.LogError("Incoming patch: " + ex);
				return true;
			}
		}

		[HarmonyPatch(typeof(TMP_InputField), "KeyPressed")]
		[HarmonyPrefix]
		private static void OnInputKeyPressed(TMP_InputField __instance, Event evt)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Invalid comparison between Unknown and I4
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Invalid comparison between Unknown and I4
			try
			{
				if (evt != null)
				{
					KeyCode keyCode = evt.keyCode;
					if ((int)keyCode == 13 || (int)keyCode == 271)
					{
						ImeFix.OnEnterPressed(__instance);
					}
				}
			}
			catch (Exception ex)
			{
				Mod.Log.LogError("IME key patch: " + ex);
			}
		}

		[HarmonyPatch(typeof(ChatManagerBase), "SendPlayerChatMessage")]
		[HarmonyPrefix]
		private static void OnPlayerSubmit(ref string obj)
		{
			ChatBoxTweaks.OnLocalSend();
			try
			{
				string text = ImeFix.FixSubmit(obj);
				if (text != null)
				{
					obj = text;
				}
			}
			catch (Exception ex)
			{
				Mod.Log.LogError("IME submit patch: " + ex);
			}
		}

		[HarmonyPatch(typeof(UltimateChatBox), "ClearChat")]
		[HarmonyPostfix]
		private static void OnChatCleared()
		{
			try
			{
				TranslatorRuntime.ScheduleWelcome();
				ChatContext.ClearRecent();
			}
			catch (Exception ex)
			{
				Mod.Log.LogError("Clear chat patch: " + ex);
			}
		}

		[HarmonyPatch(typeof(ChatManagerBase), "SendChatMessage")]
		[HarmonyPrefix]
		private static bool OnOutgoing(ref string cleanedString)
		{
			if (TranslatorCore.Sending)
			{
				return true;
			}
			try
			{
				string text = ImeFix.FixSubmit(cleanedString);
				if (text != null)
				{
					cleanedString = text;
				}
				if (TranslatorCore.QueueOutgoing(cleanedString))
				{
					return false;
				}
				TranslatorCore.RememberOwn(cleanedString);
				return true;
			}
			catch (Exception ex)
			{
				Mod.Log.LogError("Outgoing patch: " + ex);
				return true;
			}
		}
	}
	internal static class DeepLTranslator
	{
		public static async Task<TranslationResult> TranslateAsync(string text, string target, string source = null, string context = null)
		{
			string text2 = ApiKeys.Get(Mod.DeepLKey);
			if (string.IsNullOrEmpty(text2))
			{
				return TranslationResult.Fail(text, "no DeepL API key");
			}
			string text3 = (text2.EndsWith(":fx", StringComparison.Ordinal) ? "https://api-free.deepl.com" : "https://api.deepl.com");
			string content;
			using (MemoryStream memoryStream = new MemoryStream())
			{
				using (Utf8JsonWriter utf8JsonWriter = new Utf8JsonWriter((Stream)memoryStream, default(JsonWriterOptions)))
				{
					utf8JsonWriter.WriteStartObject();
					utf8JsonWriter.WriteStartArray("text");
					utf8JsonWriter.WriteStringValue(text);
					utf8JsonWriter.WriteEndArray();
					utf8JsonWriter.WriteString("target_lang", Langs.ToDeepL(target));
					string text4 = Langs.ToDeepLSource(source);
					if (text4 != null)
					{
						utf8JsonWriter.WriteString("source_lang", text4);
					}
					if (!string.IsNullOrEmpty(context))
					{
						utf8JsonWriter.WriteString("context", context);
					}
					switch (Mod.DeepLFormality.Value)
					{
					case DeepLTone.Casual:
						utf8JsonWriter.WriteString("formality", "prefer_less");
						break;
					case DeepLTone.Formal:
						utf8JsonWriter.WriteString("formality", "prefer_more");
						break;
					}
					utf8JsonWriter.WriteEndObject();
				}
				content = Encoding.UTF8.GetString(memoryStream.ToArray());
			}
			using HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, text3 + "/v2/translate");
			req.Headers.TryAddWithoutValidation("Authorization", "DeepL-Auth-Key " + text2);
			req.Content = new StringContent(content, Encoding.UTF8, "application/json");
			using HttpResponseMessage resp = await Http.Client.SendAsync(req).ConfigureAwait(continueOnCapturedContext: false);
			string text5 = await resp.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false);
			if (!resp.IsSuccessStatusCode)
			{
				return TranslationResult.Fail(text, $"HTTP {resp.StatusCode} {Short(text5)}");
			}
			using JsonDocument jsonDocument = JsonDocument.Parse(text5);
			JsonElement jsonElement = jsonDocument.RootElement.GetProperty("translations")[0];
			JsonElement value;
			return new TranslationResult
			{
				Ok = true,
				Text = jsonElement.GetProperty("text").GetString()?.Trim(),
				SourceLang = ((!jsonElement.TryGetProperty("detected_source_language", out value)) ? null : value.GetString()?.ToLowerInvariant())
			};
		}

		internal static string Short(string s)
		{
			if (!string.IsNullOrEmpty(s))
			{
				if (s.Length <= 160)
				{
					return s;
				}
				return s.Substring(0, 160);
			}
			return "";
		}
	}
	internal static class GoogleCloudTranslator
	{
		private const string Endpoint = "https://translation.googleapis.com/language/translate/v2";

		public static async Task<TranslationResult> TranslateAsync(string text, string target, string source = null)
		{
			string value = ApiKeys.Get(Mod.GoogleCloudKey);
			if (string.IsNullOrEmpty(value))
			{
				return TranslationResult.Fail(text, "no Google Cloud API key");
			}
			string content;
			using (MemoryStream memoryStream = new MemoryStream())
			{
				using (Utf8JsonWriter utf8JsonWriter = new Utf8JsonWriter((Stream)memoryStream, default(JsonWriterOptions)))
				{
					utf8JsonWriter.WriteStartObject();
					utf8JsonWriter.WriteString("q", text);
					utf8JsonWriter.WriteString("target", target);
					if (!string.IsNullOrEmpty(source))
					{
						utf8JsonWriter.WriteString("source", source);
					}
					utf8JsonWriter.WriteString("format", "text");
					utf8JsonWriter.WriteEndObject();
				}
				content = Encoding.UTF8.GetString(memoryStream.ToArray());
			}
			using HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "https://translation.googleapis.com/language/translate/v2");
			req.Headers.TryAddWithoutValidation("X-Goog-Api-Key", value);
			req.Content = new StringContent(content, Encoding.UTF8, "application/json");
			using HttpResponseMessage resp = await Http.Client.SendAsync(req).ConfigureAwait(continueOnCapturedContext: false);
			string text2 = await resp.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false);
			if (!resp.IsSuccessStatusCode)
			{
				return TranslationResult.Fail(text, $"HTTP {resp.StatusCode} {ErrorMessage(text2)}");
			}
			using JsonDocument jsonDocument = JsonDocument.Parse(text2);
			JsonElement jsonElement = jsonDocument.RootElement.GetProperty("data").GetProperty("translations")[0];
			JsonElement value2;
			return new TranslationResult
			{
				Ok = true,
				Text = jsonElement.GetProperty("translatedText").GetString()?.Trim(),
				SourceLang = ((!jsonElement.TryGetProperty("detectedSourceLanguage", out value2)) ? null : value2.GetString()?.ToLowerInvariant())
			};
		}

		private static string ErrorMessage(string body)
		{
			try
			{
				using JsonDocument jsonDocument = JsonDocument.Parse(body);
				if (jsonDocument.RootElement.TryGetProperty("error", out var value) && value.TryGetProperty("message", out var value2))
				{
					return value2.GetString();
				}
			}
			catch
			{
			}
			return DeepLTranslator.Short(body);
		}
	}
	public static class GoogleTranslator
	{
		private static bool _chromeExtDead;

		private static bool _gtxDead;

		public static async Task<TranslationResult> TranslateAsync(string text, string target, string source = null)
		{
			string sl = Uri.EscapeDataString(string.IsNullOrEmpty(source) ? "auto" : source);
			var (text2, sourceLang) = await TryChromeExtEndpoint(text, target, sl).ConfigureAwait(continueOnCapturedContext: false);
			if (string.IsNullOrEmpty(text2))
			{
				(text2, sourceLang) = await TryGtxEndpoint(text, target, sl).ConfigureAwait(continueOnCapturedContext: false);
			}
			if (string.IsNullOrEmpty(text2))
			{
				return TranslationResult.Fail(text, "Google endpoints unavailable");
			}
			return new TranslationResult
			{
				Ok = true,
				Text = text2,
				SourceLang = sourceLang
			};
		}

		private static async Task<(string, string)> TryChromeExtEndpoint(string text, string target, string sl)
		{
			if (_chromeExtDead)
			{
				return (null, null);
			}
			string text2 = await GetJson("https://clients5.google.com/translate_a/t?client=dict-chrome-ex&sl=" + sl + "&tl=" + Uri.EscapeDataString(target) + "&q=" + Uri.EscapeDataString(text), delegate
			{
				_chromeExtDead = true;
			}).ConfigureAwait(continueOnCapturedContext: false);
			if (text2 == null)
			{
				return (null, null);
			}
			using JsonDocument jsonDocument = JsonDocument.Parse(text2);
			JsonElement rootElement = jsonDocument.RootElement;
			if (rootElement.ValueKind != JsonValueKind.Array)
			{
				return (null, null);
			}
			StringBuilder stringBuilder = new StringBuilder();
			string text3 = null;
			foreach (JsonElement item in rootElement.EnumerateArray())
			{
				if (item.ValueKind == JsonValueKind.String)
				{
					stringBuilder.Append(item.GetString());
				}
				else if (item.ValueKind == JsonValueKind.Array && item.GetArrayLength() > 0 && item[0].ValueKind == JsonValueKind.String)
				{
					stringBuilder.Append(item[0].GetString());
					if (text3 == null && item.GetArrayLength() > 1 && item[1].ValueKind == JsonValueKind.String)
					{
						text3 = item[1].GetString();
					}
				}
			}
			return (stringBuilder.ToString().Trim(), text3);
		}

		private static async Task<(string, string)> TryGtxEndpoint(string text, string target, string sl)
		{
			if (_gtxDead)
			{
				return (null, null);
			}
			string text2 = await GetJson("https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + sl + "&tl=" + Uri.EscapeDataString(target) + "&dt=t&q=" + Uri.EscapeDataString(text), delegate
			{
				_gtxDead = true;
			}).ConfigureAwait(continueOnCapturedContext: false);
			if (text2 == null)
			{
				return (null, null);
			}
			using JsonDocument jsonDocument = JsonDocument.Parse(text2);
			JsonElement rootElement = jsonDocument.RootElement;
			StringBuilder stringBuilder = new StringBuilder();
			if (rootElement.ValueKind == JsonValueKind.Array && rootElement.GetArrayLength() > 0 && rootElement[0].ValueKind == JsonValueKind.Array)
			{
				foreach (JsonElement item2 in rootElement[0].EnumerateArray())
				{
					if (item2.ValueKind == JsonValueKind.Array && item2.GetArrayLength() > 0 && item2[0].ValueKind == JsonValueKind.String)
					{
						stringBuilder.Append(item2[0].GetString());
					}
				}
			}
			string item = ((rootElement.ValueKind == JsonValueKind.Array && rootElement.GetArrayLength() > 2 && rootElement[2].ValueKind == JsonValueKind.String) ? rootElement[2].GetString() : null);
			return (stringBuilder.ToString().Trim(), item);
		}

		private static async Task<string> GetJson(string url, Action markDead)
		{
			_ = 1;
			try
			{
				using HttpResponseMessage resp = await Http.Client.GetAsync(url).ConfigureAwait(continueOnCapturedContext: false);
				string text = await resp.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false);
				if (resp.IsSuccessStatusCode && text.Length > 0 && (text[0] == '[' || text[0] == '{'))
				{
					return text;
				}
				if (text.Contains("<html", StringComparison.OrdinalIgnoreCase) || resp.StatusCode == HttpStatusCode.Forbidden)
				{
					markDead();
					Mod.Log.LogWarning($"Endpoint blocked ({resp.StatusCode}), skipping it: {new Uri(url).Host}");
				}
				return null;
			}
			catch (Exception ex) when (ex is HttpRequestException || ex is TaskCanceledException)
			{
				Mod.Log.LogWarning("Endpoint error " + new Uri(url).Host + ": " + ex.Message);
				return null;
			}
		}
	}
	internal static class ImeFix
	{
		private const int RecentFrames = 3;

		private const int SubmitFrames = 4;

		private static string _comp = "";

		private static int _compFrame = -100;

		private static string _enterText;

		private static string _enterComp;

		private static int _enterFrame;

		private static string _leftover;

		private static float _clearUntil;

		private static int _logs;

		private static float Now => Time.realtimeSinceStartup;

		internal static void OnEnterPressed(TMP_InputField field)
		{
			if (!Mod.ImeFixEnabled.Value || (Object)(object)field == (Object)null)
			{
				return;
			}
			TMP_InputField val = ChatField();
			if (!((Object)(object)val == (Object)null) && !(((Il2CppObjectBase)val).Pointer != ((Il2CppObjectBase)field).Pointer))
			{
				string text = ReadComposition();
				int num = Time.frameCount - _compFrame;
				string text2 = ((!string.IsNullOrEmpty(text)) ? text : ((num <= 3) ? _comp : null));
				string text3 = field.text ?? "";
				if (string.IsNullOrEmpty(text2) || string.IsNullOrWhiteSpace(text3))
				{
					_enterText = null;
					return;
				}
				_enterText = text3;
				_enterComp = text2;
				_enterFrame = Time.frameCount;
				Log($"Enter: field {R(text3)}, composition {R(text2)} {num} frame(s) ago");
			}
		}

		internal static string FixSubmit(string text)
		{
			if (!Mod.ImeFixEnabled.Value || _enterText == null)
			{
				return null;
			}
			string enterText = _enterText;
			_enterText = null;
			if (Time.frameCount - _enterFrame > 4)
			{
				return null;
			}
			string text2 = (text ?? "").TrimEnd();
			string text3 = enterText.TrimEnd();
			ArmLeftover();
			if (text2.Length < text3.Length && text3.StartsWith(text2, StringComparison.Ordinal))
			{
				Log("submit: " + R(text2) + " -> " + R(text3));
				return text3;
			}
			Log($"submit: {R(text2)} kept (Enter text {R(text3)})");
			return null;
		}

		internal static void Tick()
		{
			string text = ReadComposition();
			if (!string.IsNullOrEmpty(text))
			{
				_comp = text;
				_compFrame = Time.frameCount;
			}
			if (_enterText != null && Time.frameCount - _enterFrame > 4)
			{
				string text2 = _enterText.Trim();
				_enterText = null;
				bool flag = true;
				try
				{
					flag = (Object)(object)ChatManager.Instance != (Object)null && ChatManager.Instance.IsChatOpen;
				}
				catch
				{
				}
				if (!flag && text2.Length > 0)
				{
					ArmLeftover();
					Log("game sent nothing after Enter; sending " + R(text2));
					try
					{
						ChatManagerBase.SendChatMessage(text2);
					}
					catch (Exception ex)
					{
						Mod.Log.LogWarning("IME fix send failed: " + ex.Message);
					}
				}
				else
				{
					Log("game sent nothing after Enter but the chat is still open; left " + R(text2) + " in the field");
				}
			}
			if (_leftover == null)
			{
				return;
			}
			if (Now > _clearUntil)
			{
				_leftover = null;
				return;
			}
			try
			{
				TMP_InputField val = ChatField();
				if ((Object)(object)val != (Object)null && val.text == _leftover)
				{
					val.text = "";
					Log("cleared leftover " + R(_leftover) + " from the input field");
					_leftover = null;
				}
			}
			catch
			{
			}
		}

		private static void ArmLeftover()
		{
			_leftover = _enterComp;
			_clearUntil = Now + 0.6f;
		}

		private static TMP_InputField ChatField()
		{
			try
			{
				return ((Object)(object)ChatManager.Instance != (Object)null) ? ChatManager.Instance.inputField : null;
			}
			catch
			{
				return null;
			}
		}

		private static string ReadComposition()
		{
			string text = null;
			try
			{
				text = Input.compositionString;
			}
			catch
			{
			}
			if (string.IsNullOrEmpty(text))
			{
				try
				{
					TMP_InputField val = ChatField();
					if ((Object)(object)val != (Object)null)
					{
						text = val.compositionString;
					}
				}
				catch
				{
				}
			}
			return text;
		}

		private static string R(string s)
		{
			if (s != null)
			{
				return $"[{s.Length} chars]";
			}
			return "(none)";
		}

		private static void Log(string msg)
		{
			if (_logs++ < 40)
			{
				Mod.Debug("IME fix: " + msg);
			}
		}
	}
	internal static class Langs
	{
		internal static readonly (string Code, string Native, string English)[] All = new(string, string, string)[19]
		{
			("ko", "한국어", "Korean"),
			("en", "English", "English"),
			("ja", "日本語", "Japanese"),
			("zh-CN", "中文 (简体)", "Simplified Chinese"),
			("zh-TW", "中文 (繁體)", "Traditional Chinese"),
			("es", "Español", "Spanish"),
			("fr", "Français", "French"),
			("de", "Deutsch", "German"),
			("ru", "Русский", "Russian"),
			("pt", "Português", "Portuguese"),
			("it", "Italiano", "Italian"),
			("pl", "Polski", "Polish"),
			("tr", "Türkçe", "Turkish"),
			("vi", "Tiếng Việt", "Vietnamese"),
			("th", "ไทย", "Thai"),
			("id", "Bahasa Indonesia", "Indonesian"),
			("ar", "العربية", "Arabic"),
			("uk", "Українська", "Ukrainian"),
			("nl", "Nederlands", "Dutch")
		};

		private static readonly HashSet<string> DeepLSources = new HashSet<string>
		{
			"AR", "BG", "CS", "DA", "DE", "EL", "EN", "ES", "ET", "FI",
			"FR", "HE", "HU", "ID", "IT", "JA", "KO", "LT", "LV", "NB",
			"NL", "PL", "PT", "RO", "RU", "SK", "SL", "SV", "TH", "TR",
			"UK", "VI", "ZH"
		};

		internal static int IndexOf(string code)
		{
			return Array.FindIndex(All, ((string Code, string Native, string English) l) => string.Equals(l.Code, code, StringComparison.OrdinalIgnoreCase));
		}

		internal static string EnglishName(string code)
		{
			int num = IndexOf(code);
			if (num < 0)
			{
				return code;
			}
			return All[num].English;
		}

		internal static string ToDeepL(string code)
		{
			return code.ToLowerInvariant() switch
			{
				"en" => "EN-US", 
				"pt" => "PT-BR", 
				"zh-cn" => "ZH-HANS", 
				"zh-tw" => "ZH-HANT", 
				_ => code.Split('-')[0].ToUpperInvariant(), 
			};
		}

		internal static string ToDeepLSource(string code)
		{
			if (string.IsNullOrEmpty(code))
			{
				return null;
			}
			string text = code.Split('-')[0].ToUpperInvariant();
			if (!DeepLSources.Contains(text))
			{
				return null;
			}
			return text;
		}

		internal static bool Same(string a, string b)
		{
			if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b))
			{
				return false;
			}
			a = a.ToLowerInvariant();
			b = b.ToLowerInvariant();
			if (a == b)
			{
				return true;
			}
			if (a.StartsWith("zh") || b.StartsWith("zh"))
			{
				return a.Replace("_", "-") == b;
			}
			return a.Split('-')[0] == b.Split('-')[0];
		}
	}
	internal static class L
	{
		private readonly struct Entry
		{
			public readonly string En;

			public readonly string Ko;

			public readonly string Ja;

			public readonly string ZhCN;

			public readonly string ZhTW;

			public Entry(string en, string ko, string ja, string zhCN, string zhTW)
			{
				En = en;
				Ko = ko;
				Ja = ja;
				ZhCN = zhCN;
				ZhTW = zhTW;
			}
		}

		internal static readonly (string Code, string Native)[] UiLanguages = new(string, string)[5]
		{
			("en", "English"),
			("ko", "한국어"),
			("ja", "日本語"),
			("zh-CN", "简体中文"),
			("zh-TW", "繁體中文")
		};

		private static readonly Dictionary<string, string> Markers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
		{
			["en"] = "[translated]",
			["ko"] = "[번역]",
			["ja"] = "[翻訳]",
			["zh-CN"] = "[翻译]",
			["zh-TW"] = "[翻譯]"
		};

		private static readonly Dictionary<string, Entry> S = new Dictionary<string, Entry>
		{
			["title"] = new Entry("Chat Translator", "채팅 번역 설정", "チャット翻訳", "聊天翻译", "聊天翻譯"),
			["ui.auto"] = new Entry("Auto", "자동", "自動", "自动", "自動"),
			["ui.auto.item"] = new Entry("Auto (game language)", "자동 (게임 언어)", "自動(ゲームの言語)", "自动(游戏语言)", "自動(遊戲語言)"),
			["tab.translate"] = new Entry("Translation", "번역", "翻訳", "翻译", "翻譯"),
			["tab.chat"] = new Entry("Chat box", "채팅창", "チャット欄", "聊天框", "聊天框"),
			["tab.engine"] = new Entry("Engine", "번역 엔진", "翻訳エンジン", "翻译引擎", "翻譯引擎"),
			["sec.incoming"] = new Entry("Received chat", "받은 채팅", "受信チャット", "收到的消息", "收到的訊息"),
			["auto"] = new Entry("Translate automatically", "자동 번역", "自動で翻訳", "自动翻译", "自動翻譯"),
			["target"] = new Entry("Translate into", "번역할 언어", "翻訳先の言語", "翻译成", "翻譯成"),
			["orig.show"] = new Entry("Original", "원문 표시", "原文の表示", "原文显示", "原文顯示"),
			["orig.below"] = new Entry("Below", "아래 줄", "下の行", "下一行", "下一行"),
			["orig.inline"] = new Entry("Same line", "같은 줄", "同じ行", "同一行", "同一行"),
			["orig.hover"] = new Entry("On hover", "커서 올리기", "カーソルを合わせる", "鼠标悬停", "滑鼠懸停"),
			["orig.size"] = new Entry("Original size", "원문 크기", "原文のサイズ", "原文大小", "原文大小"),
			["orig.bright"] = new Entry("Original brightness", "원문 밝기", "原文の明るさ", "原文亮度", "原文亮度"),
			["orig.spacing"] = new Entry("Line gap", "원문 줄 간격", "行間", "行间距", "行間距"),
			["orig.hoverhint"] = new Entry("Open the chat and point at a line to see its original.", "채팅을 열고 줄에 커서를 올리면 원문이 보입니다.", "チャットを開いて行にカーソルを合わせると原文が表示されます。", "打开聊天并将鼠标悬停在消息上即可查看原文。", "開啟聊天並將滑鼠移到訊息上即可查看原文。"),
			["marker"] = new Entry("Add '{0}' marker", "'{0}' 표시 붙이기", "「{0}」マークを付ける", "添加“{0}”标记", "加上「{0}」標記"),
			["repeat"] = new Entry("Translate repeated syllables (크크, 흑흑) - not ㅋㅋ", "반복 음절도 번역 (크크, 흑흑) - ㅋㅋ 같은 자모는 제외", "繰り返し音節も翻訳(크크、흑흑)- ㅋㅋ などの字母は除く", "翻译重复音节(크크、흑흑)- 不含 ㅋㅋ 等字母", "翻譯重複音節(크크、흑흑)- 不含 ㅋㅋ 等字母"),
			["playerlang"] = new Entry("Short messages: use the language the player usually writes", "짧은 메시지는 그 플레이어가 쓰던 언어로 번역", "短いメッセージはそのプレイヤーが使っている言語として翻訳", "短消息按该玩家常用的语言翻译", "短訊息按該玩家常用的語言翻譯"),
			["rich"] = new Entry("Use text size/colour (turn off if tags show up)", "글자 크기·색 사용 (태그가 보이면 끄기)", "文字サイズ・色を使う(タグが表示される場合はオフ)", "使用字号/颜色(若显示标签代码请关闭)", "使用字級/顏色(若顯示標籤代碼請關閉)"),
			["preview"] = new Entry("Preview", "미리보기", "プレビュー", "预览", "預覽"),
			["sec.outgoing"] = new Entry("Your messages", "보내는 채팅", "送信チャット", "发送的消息", "發送的訊息"),
			["send.translate"] = new Entry("Translate before sending", "번역해서 보내기", "翻訳してから送信", "翻译后发送", "翻譯後發送"),
			["send.withorig"] = new Entry("Send the original too, e.g. Hi (안녕)", "원문 함께 보내기 (예: Hi (안녕))", "原文も一緒に送信(例: Hi (こんにちは))", "同时发送原文(例:Hi (你好))", "同時發送原文(例:Hi (你好))"),
			["send.lang"] = new Entry("Send in", "보낼 언어", "送信する言語", "发送语言", "發送語言"),
			["send.cycle"] = new Entry("Hotkey languages", "단축키 전환 언어", "切り替える言語", "快捷键切换语言", "快捷鍵切換語言"),
			["send.cycle.hint"] = new Entry("{0} switches through these in order. Click a language to add or remove it.", "{0} 키로 이 언어들을 순서대로 전환합니다. 언어를 눌러 추가하거나 뺄 수 있습니다.", "{0}キーでこれらの言語を順番に切り替えます。言語をクリックして追加・削除できます。", "按 {0} 依次切换这些语言。点击语言即可添加或移除。", "按 {0} 依序切換這些語言。點擊語言即可新增或移除。"),
			["send.raw"] = new Entry("Messages starting with '{0}' are sent untranslated", "'{0}'로 시작하는 메시지는 번역 없이 보냅니다", "「{0}」で始まるメッセージは翻訳せずに送信します", "以“{0}”开头的消息将不经翻译直接发送", "以「{0}」開頭的訊息將不經翻譯直接發送"),
			["sec.size"] = new Entry("Size", "크기", "サイズ", "大小", "大小"),
			["width"] = new Entry("Width", "가로 크기", "横幅", "宽度", "寬度"),
			["height"] = new Entry("Height", "세로 크기", "高さ", "高度", "高度"),
			["textsize"] = new Entry("Text size", "글자 크기", "文字サイズ", "字号", "字級"),
			["reset.size"] = new Entry("Reset size", "크기 초기화", "サイズをリセット", "重置大小", "重設大小"),
			["sec.scroll"] = new Entry("Scrolling", "스크롤", "スクロール", "滚动", "捲動"),
			["sec.other"] = new Entry("Other", "기타", "その他", "其他", "其他"),
			["scroll.wheel"] = new Entry("Scroll with the mouse wheel (while typing)", "마우스 휠로 스크롤 (채팅 입력 중)", "マウスホイールでスクロール(入力中)", "用鼠标滚轮滚动(输入时)", "用滑鼠滾輪捲動(輸入時)"),
			["scroll.bar"] = new Entry("Show scrollbar", "스크롤바 표시", "スクロールバーを表示", "显示滚动条", "顯示捲軸"),
			["scroll.bar.na"] = new Entry("Show scrollbar (chat box not found yet)", "스크롤바 표시 (채팅창을 아직 찾지 못함)", "スクロールバーを表示(チャット欄がまだ見つかりません)", "显示滚动条(尚未找到聊天框)", "顯示捲軸(尚未找到聊天框)"),
			["scroll.auto"] = new Entry("Jump to newest message when chat is closed", "채팅창이 닫혀 있으면 새 메시지로 자동 스크롤", "チャットを閉じている時は最新メッセージへ自動スクロール", "聊天关闭时自动滚动到最新消息", "聊天關閉時自動捲動到最新訊息"),
			["ime.fix"] = new Entry("Keep the last IME character when pressing Enter (Korean/Japanese/Chinese)", "Enter 시 마지막 글자 누락 방지 (한글·일본어·중국어 입력)", "Enter時に最後の文字が消える問題を修正(IME入力)", "修复按 Enter 时最后一个字丢失(输入法)", "修正按 Enter 時最後一個字遺失(輸入法)"),
			["scroll.speed"] = new Entry("Scroll speed", "스크롤 속도", "スクロール速度", "滚动速度", "捲動速度"),
			["history"] = new Entry("Messages kept", "보관할 메시지", "保存するメッセージ数", "保留消息数", "保留訊息數"),
			["count"] = new Entry("{0}", "{0}개", "{0}件", "{0}条", "{0}則"),
			["engine"] = new Entry("Engine", "번역 엔진", "翻訳エンジン", "翻译引擎", "翻譯引擎"),
			["engine.google"] = new Entry("Google (free)", "Google (무료)", "Google(無料)", "Google(免费)", "Google(免費)"),
			["engine.deepl"] = new Entry("DeepL", "DeepL", "DeepL", "DeepL", "DeepL"),
			["engine.gcloud"] = new Entry("Google API", "Google API", "Google API", "Google API", "Google API"),
			["engine.google.desc"] = new Entry("Unofficial free web endpoint, no key. May be rate-limited or stop working.", "비공식 무료 웹 엔드포인트, 키 불필요. 요청이 많으면 막히거나 갑자기 동작하지 않을 수 있음.", "非公式の無料Webエンドポイント。キー不要。制限されたり、使えなくなる場合があります。", "非官方免费网页接口,无需密钥。可能被限制或突然失效。", "非官方免費網頁介面,無需金鑰。可能被限制或突然失效。"),
			["engine.gcloud.desc"] = new Entry("Official Google Cloud Translation API. Key from console.cloud.google.com (enable the Cloud Translation API). Paid per character after the free monthly quota.", "공식 Google Cloud Translation API. console.cloud.google.com에서 Cloud Translation API를 사용 설정하고 API 키를 발급. 매월 무료 한도를 넘으면 글자 수만큼 과금.", "公式のGoogle Cloud Translation API。console.cloud.google.comでCloud Translation APIを有効にしてAPIキーを発行。毎月の無料枠を超えると文字数に応じて課金。", "官方 Google Cloud Translation API。在 console.cloud.google.com 启用 Cloud Translation API 并创建 API 密钥。超出每月免费额度后按字符计费。", "官方 Google Cloud Translation API。在 console.cloud.google.com 啟用 Cloud Translation API 並建立 API 金鑰。超出每月免費額度後按字元計費。"),
			["engine.deepl.desc"] = new Entry("DeepL API key from deepl.com (free plan keys end in ':fx').", "deepl.com에서 받은 API 키 (무료 플랜 키는 ':fx'로 끝남).", "deepl.com で取得したAPIキー(無料プランのキーは「:fx」で終わります)。", "在 deepl.com 获取的 API 密钥(免费版密钥以“:fx”结尾)。", "在 deepl.com 取得的 API 金鑰(免費版金鑰以「:fx」結尾)。"),
			["deepl.context"] = new Entry("Send recent chat as context (better short replies, not billed)", "최근 대화를 맥락으로 함께 보내기 (짧은 답 번역 개선, 과금 없음)", "最近の会話を文脈として送る(短い返事の翻訳が向上、課金なし)", "发送最近的聊天作为上下文(改善短回复翻译,不计费)", "傳送最近的聊天作為上下文(改善短回覆翻譯,不計費)"),
			["deepl.tone"] = new Entry("Speech", "말투", "口調", "语气", "語氣"),
			["tone.default"] = new Entry("Default", "기본", "標準", "默认", "預設"),
			["tone.casual"] = new Entry("Casual", "반말", "くだけた", "随意", "隨意"),
			["tone.formal"] = new Entry("Polite", "존댓말", "丁寧", "礼貌", "禮貌"),
			["deepl.tone.note"] = new Entry("Only for languages that have it (Japanese, German, French, Spanish, Russian ...).", "말투 구분이 있는 언어에만 적용됩니다 (일본어, 독일어, 프랑스어, 스페인어, 러시아어 등).", "口調の区別がある言語にのみ適用されます(日本語、ドイツ語、フランス語、スペイン語、ロシア語など)。", "仅适用于区分语气的语言(日语、德语、法语、西班牙语、俄语等)。", "僅適用於區分語氣的語言(日語、德語、法語、西班牙語、俄語等)。"),
			["apikey"] = new Entry("API key", "API 키", "APIキー", "API 密钥", "API 金鑰"),
			["key.none"] = new Entry("(not set)", "(없음)", "(未設定)", "(未设置)", "(未設定)"),
			["key.set"] = new Entry("Set", "설정됨", "設定済み", "已设置", "已設定"),
			["key.paste"] = new Entry("Paste", "붙여넣기", "貼り付け", "粘贴", "貼上"),
			["key.edit"] = new Entry("Type", "직접 입력", "直接入力", "手动输入", "手動輸入"),
			["key.done"] = new Entry("Done", "완료", "完了", "完成", "完成"),
			["key.clear"] = new Entry("Clear", "지우기", "消去", "清除", "清除"),
			["key.typing"] = new Entry("Keys you type also reach the game. Pasting is easier.", "입력하는 키가 게임에도 전달됩니다. 붙여넣기를 권장합니다.", "入力したキーはゲームにも伝わります。貼り付けがおすすめです。", "输入的按键也会传给游戏,建议直接粘贴。", "輸入的按鍵也會傳給遊戲,建議直接貼上。"),
			["key.plain"] = new Entry("Encryption is not available here (e.g. Linux/Proton), so this key is stored in plain text in UserData/SleddingChatTranslator.cfg.", "이 환경(예: 리눅스/Proton)에서는 암호화할 수 없어 키를 UserData/SleddingChatTranslator.cfg에 평문으로 저장했습니다.", "この環境(Linux/Protonなど)では暗号化できないため、キーを UserData/SleddingChatTranslator.cfg に平文で保存しました。", "此环境(如 Linux/Proton)无法加密,密钥以明文保存在 UserData/SleddingChatTranslator.cfg 中。", "此環境(如 Linux/Proton)無法加密,金鑰以明文儲存在 UserData/SleddingChatTranslator.cfg 中。"),
			["key.stored"] = new Entry("Stored encrypted for this Windows account (DPAPI). The key is never shown here.", "이 Windows 계정 전용으로 암호화해 저장합니다(DPAPI). 키는 화면에 표시되지 않습니다.", "このWindowsアカウント専用に暗号化して保存します(DPAPI)。キーは表示されません。", "已针对此 Windows 账户加密保存(DPAPI),不会在此显示。", "已針對此 Windows 帳戶加密儲存(DPAPI),不會在此顯示。"),
			["fallback"] = new Entry("Use Google if this engine fails", "실패하면 Google로 대체", "失敗したらGoogleで代替", "失败时改用 Google", "失敗時改用 Google"),
			["test"] = new Entry("Test", "테스트", "テスト", "测试", "測試"),
			["test.running"] = new Entry("Testing...", "테스트 중...", "テスト中...", "测试中...", "測試中..."),
			["test.fail"] = new Entry("Failed: ", "실패: ", "失敗: ", "失败:", "失敗:"),
			["test.ok"] = new Entry("OK ({0}): ", "성공 ({0}): ", "成功({0}): ", "成功({0}):", "成功({0}):"),
			["lasterror"] = new Entry("Last error: ", "최근 오류: ", "直近のエラー: ", "最近的错误:", "最近的錯誤:"),
			["hk.settings"] = new Entry("Settings", "설정", "設定", "设置", "設定"),
			["hk.outgoing"] = new Entry("Your messages", "보내는 채팅", "送信チャット", "发送的消息", "發送的訊息"),
			["hk.incoming"] = new Entry("Received chat", "받은 채팅", "受信チャット", "收到的消息", "收到的訊息"),
			["hk.cycle"] = new Entry("Send language", "보낼 언어", "送信言語", "发送语言", "發送語言"),
			["n.out.on"] = new Entry("[Chat Translator] Your messages → {0}", "[번역] 보내는 채팅 번역 켜짐 → {0}", "[翻訳] 送信チャットの翻訳 オン → {0}", "[翻译] 发送消息翻译已开启 → {0}", "[翻譯] 發送訊息翻譯已開啟 → {0}"),
			["n.out.off"] = new Entry("[Chat Translator] Your messages: off", "[번역] 보내는 채팅 번역 꺼짐", "[翻訳] 送信チャットの翻訳 オフ", "[翻译] 发送消息翻译已关闭", "[翻譯] 發送訊息翻譯已關閉"),
			["n.in.on"] = new Entry("[Chat Translator] Received chat → {0}", "[번역] 받은 채팅 번역 켜짐 → {0}", "[翻訳] 受信チャットの翻訳 オン → {0}", "[翻译] 收到消息翻译已开启 → {0}", "[翻譯] 收到訊息翻譯已開啟 → {0}"),
			["n.in.off"] = new Entry("[Chat Translator] Received chat: off", "[번역] 받은 채팅 번역 꺼짐", "[翻訳] 受信チャットの翻訳 オフ", "[翻译] 收到消息翻译已关闭", "[翻譯] 收到訊息翻譯已關閉"),
			["n.cycle"] = new Entry("[Chat Translator] Send language: {0}", "[번역] 보내는 채팅 언어: {0}", "[翻訳] 送信言語: {0}", "[翻译] 发送语言:{0}", "[翻譯] 發送語言:{0}"),
			["n.cycle.off"] = new Entry(" (off, press {0} to enable)", " (꺼져 있음, {0}로 켜기)", "(オフ、{0}でオン)", "(已关闭,按 {0} 开启)", "(已關閉,按 {0} 開啟)"),
			["n.welcome"] = new Entry("[Chat Translator] Auto-translation is on. Settings: {0}", "[번역] 자동 번역 모드를 사용 중입니다. 설정: {0}", "[翻訳] 自動翻訳モードを使用中です。設定: {0}", "[翻译] 正在使用自动翻译模式。设置:{0}", "[翻譯] 正在使用自動翻譯模式。設定:{0}"),
			["welcome"] = new Entry("Show a welcome notice when joining", "입장 시 안내 메시지 표시", "入室時に案内メッセージを表示", "进入时显示提示消息", "進入時顯示提示訊息")
		};

		internal const string Auto = "auto";

		private static string _gameLang;

		private static string _gameLangRaw;

		private static float _gameLangCheckedAt = -10f;

		internal static string Marker
		{
			get
			{
				if (string.IsNullOrWhiteSpace(Mod.MarkerText.Value))
				{
					if (!Markers.TryGetValue(Lang, out var value))
					{
						return Markers["en"];
					}
					return value;
				}
				return Mod.MarkerText.Value;
			}
		}

		internal static bool IsAuto => string.Equals(Mod.UiLanguage.Value, "auto", StringComparison.OrdinalIgnoreCase);

		internal static string Lang
		{
			get
			{
				string b = (IsAuto ? GameLanguage() : Mod.UiLanguage.Value);
				(string, string)[] uiLanguages = UiLanguages;
				for (int i = 0; i < uiLanguages.Length; i++)
				{
					(string, string) tuple = uiLanguages[i];
					if (string.Equals(tuple.Item1, b, StringComparison.OrdinalIgnoreCase))
					{
						return tuple.Item1;
					}
				}
				return "en";
			}
		}

		internal static string GameLanguage()
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (_gameLang != null && realtimeSinceStartup - _gameLangCheckedAt < 1f)
			{
				return _gameLang;
			}
			_gameLangCheckedAt = realtimeSinceStartup;
			try
			{
				if (!LocalizationSettings.InitializationOperation.IsDone)
				{
					return _gameLang ?? "en";
				}
				Locale selectedLocale = LocalizationSettings.SelectedLocale;
				if ((Object)(object)selectedLocale == (Object)null)
				{
					return _gameLang ?? "en";
				}
				string text = selectedLocale.Identifier.Code ?? "";
				string text2 = selectedLocale.LocaleName ?? "";
				string text3 = text + "|" + text2;
				if (text3 != _gameLangRaw)
				{
					_gameLangRaw = text3;
					_gameLang = MapGameLocale(text, text2);
					Mod.Log.LogInfo($"Game language: code '{text}', name '{text2}' -> settings window '{_gameLang}'");
				}
			}
			catch (Exception ex)
			{
				if (_gameLang == null)
				{
					Mod.Log.LogWarning("Could not read the game language: " + ex.Message);
				}
				if (_gameLang == null)
				{
					_gameLang = "en";
				}
			}
			return _gameLang;
		}

		private static string MapGameLocale(string code, string name)
		{
			switch ((code ?? "").Trim().ToLowerInvariant())
			{
			case "jp":
				return "ja";
			case "sch":
				return "zh-CN";
			case "tch":
				return "zh-TW";
			default:
			{
				string[] array = new string[3]
				{
					code,
					CodeInBrackets(name),
					name
				};
				for (int i = 0; i < array.Length; i++)
				{
					string text = (array[i] ?? "").Trim().ToLowerInvariant().Replace('_', '-');
					if (text.Length == 0)
					{
						continue;
					}
					if (text.StartsWith("ko") || text.Contains("korean"))
					{
						return "ko";
					}
					if (text.StartsWith("ja") || text.Contains("japanese"))
					{
						return "ja";
					}
					if (text.StartsWith("zh") || text.Contains("chinese"))
					{
						if (!text.Contains("hant") && !text.Contains("-tw") && !text.Contains("-hk") && !text.Contains("traditional"))
						{
							return "zh-CN";
						}
						return "zh-TW";
					}
				}
				return "en";
			}
			}
		}

		private static string CodeInBrackets(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return null;
			}
			int num = name.LastIndexOf(')');
			int num2 = ((num > 0) ? name.LastIndexOf('(', num) : (-1));
			if (num2 < 0)
			{
				return null;
			}
			return name.Substring(num2 + 1, num - num2 - 1);
		}

		internal static string T(string key)
		{
			if (!S.TryGetValue(key, out var value))
			{
				return key;
			}
			return Lang switch
			{
				"ko" => value.Ko, 
				"ja" => value.Ja, 
				"zh-CN" => value.ZhCN, 
				"zh-TW" => value.ZhTW, 
				_ => value.En, 
			};
		}

		internal static string T(string key, object arg)
		{
			return T(key).Replace("{0}", arg?.ToString());
		}
	}
	internal static class MessageFormatter
	{
		private static readonly Regex NoParseTag = new Regex("</?noparse>", RegexOptions.IgnoreCase);

		internal const string BelowTag = "\n</line-height>";

		private static readonly Dictionary<string, string> Originals = new Dictionary<string, string>();

		private static readonly Queue<string> OriginalsOrder = new Queue<string>();

		private static bool Rich => Mod.UseRichText.Value;

		internal static string Plain(string text)
		{
			if (!Rich || string.IsNullOrEmpty(text))
			{
				return text;
			}
			return "<noparse>" + NoParseTag.Replace(text, BreakTag) + "</noparse>";
		}

		private static string BreakTag(Match m)
		{
			return m.Value.Replace('<', '‹');
		}

		internal static string Compose(string translated, string original)
		{
			StringBuilder stringBuilder = new StringBuilder(Plain(translated));
			if (Mod.ShowMarker.Value && !string.IsNullOrEmpty(L.Marker))
			{
				if (Rich)
				{
					stringBuilder.Append(" <size=60%><color=#7FA6D6>").Append(L.Marker).Append("</color></size>");
				}
				else
				{
					stringBuilder.Append(' ').Append(L.Marker);
				}
			}
			OriginalDisplay value = Mod.OriginalMode.Value;
			if (string.IsNullOrWhiteSpace(original))
			{
				return stringBuilder.ToString();
			}
			if (value == OriginalDisplay.Hover)
			{
				string text = stringBuilder.ToString();
				Remember(text, original);
				return text;
			}
			bool flag = value == OriginalDisplay.Below;
			if (Rich)
			{
				int num = (int)(Mod.OriginalBrightness.Value * 255f);
				if (num < 0)
				{
					num = 0;
				}
				if (num > 255)
				{
					num = 255;
				}
				string value2 = num.ToString("X2");
				if (flag)
				{
					stringBuilder.Append("<line-height=").Append(Mod.OriginalLineSpacing.Value).Append("%>\n</line-height>");
				}
				else
				{
					stringBuilder.Append(' ');
				}
				stringBuilder.Append("<size=").Append(Mod.OriginalSize.Value).Append("%><color=#")
					.Append(value2)
					.Append(value2)
					.Append(value2)
					.Append('>')
					.Append(Plain(original))
					.Append("</color></size>");
			}
			else
			{
				stringBuilder.Append(flag ? "\n" : " ").Append('(').Append(original)
					.Append(')');
			}
			return stringBuilder.ToString();
		}

		internal static string GetOriginal(string shownMessage)
		{
			if (string.IsNullOrEmpty(shownMessage))
			{
				return null;
			}
			if (Originals.TryGetValue(shownMessage, out var value))
			{
				return value;
			}
			foreach (KeyValuePair<string, string> original in Originals)
			{
				if (shownMessage.Contains(original.Key) || original.Key.Contains(shownMessage))
				{
					return original.Value;
				}
			}
			return null;
		}

		private static void Remember(string shown, string original)
		{
			if (!Originals.ContainsKey(shown))
			{
				OriginalsOrder.Enqueue(shown);
			}
			Originals[shown] = original;
			while (OriginalsOrder.Count > 500)
			{
				Originals.Remove(OriginalsOrder.Dequeue());
			}
		}
	}
	public enum OriginalDisplay
	{
		Below,
		Inline,
		Hover
	}
	public enum TranslationEngine
	{
		Google,
		DeepL,
		GoogleCloud
	}
	public enum DeepLTone
	{
		Default,
		Casual,
		Formal
	}
	internal sealed class Setting<T>
	{
		private readonly Func<T> _get;

		private readonly Action<T> _set;

		public string Key { get; }

		public T Value
		{
			get
			{
				return _get();
			}
			set
			{
				if (!object.Equals(_get(), value))
				{
					_set(value);
					Mod.SettingsVersion++;
					Mod.Backend?.MarkDirty();
				}
			}
		}

		public Setting(string key, Func<T> get, Action<T> set)
		{
			Key = key;
			_get = get;
			_set = set;
		}
	}
	internal static class Mod
	{
		public const string Name = "Sledding Chat Translator";

		public const string Version = "0.1.0";

		public const string Author = "gomburger";

		internal static MelonLog Log;

		internal static MelonSettings Backend;

		internal static int SettingsVersion;

		internal static Setting<string> UiLanguage;

		internal static Setting<float> TimeoutSeconds;

		internal static Setting<bool> DebugLog;

		internal static Setting<bool> WelcomeMessage;

		internal static Setting<int> UiScale;

		internal static Setting<bool> IncomingEnabled;

		internal static Setting<string> IncomingLanguage;

		internal static Setting<OriginalDisplay> OriginalMode;

		internal static Setting<int> OriginalSize;

		internal static Setting<float> OriginalBrightness;

		internal static Setting<int> OriginalLineSpacing;

		internal static Setting<bool> ShowMarker;

		internal static Setting<string> MarkerText;

		internal static Setting<bool> UseRichText;

		internal static Setting<bool> TranslateRepeatedSyllables;

		internal static Setting<bool> RememberPlayerLanguage;

		internal static Setting<bool> OutgoingEnabled;

		internal static Setting<string> OutgoingLanguage;

		internal static Setting<string> OutgoingLanguageCycle;

		internal static Setting<string> RawPrefix;

		internal static Setting<bool> OutgoingWithOriginal;

		internal static Setting<string> OutgoingFormat;

		internal static Setting<TranslationEngine> Engine;

		internal static Setting<string> DeepLKey;

		internal static Setting<string> GoogleCloudKey;

		internal static Setting<bool> FallbackToGoogle;

		internal static Setting<bool> DeepLContext;

		internal static Setting<DeepLTone> DeepLFormality;

		internal static Setting<bool> ScrollEnabled;

		internal static Setting<float> ScrollSpeed;

		internal static Setting<int> HistoryLines;

		internal static Setting<bool> ShowScrollbar;

		internal static Setting<bool> AutoScrollToBottom;

		internal static Setting<bool> ImeFixEnabled;

		internal static Setting<int> ChatWidthPercent;

		internal static Setting<int> ChatHeightPercent;

		internal static Setting<int> ChatTextPercent;

		internal static Setting<string> OpenSettingsKey;

		internal static Setting<string> ToggleIncomingKey;

		internal static Setting<string> ToggleOutgoingKey;

		internal static Setting<string> CycleOutgoingKey;

		internal static void Debug(string message)
		{
			if (DebugLog != null && DebugLog.Value)
			{
				Log.LogInfo(message);
			}
		}

		internal static void DefineSettings(MelonSettings b)
		{
			Backend = b;
			UiLanguage = b.Bind("General", "UiLanguage", "auto", "Settings window language: auto (follow the game language) / en / ko / ja / zh-CN / zh-TW.");
			TimeoutSeconds = b.Bind("General", "TimeoutSeconds", 4f, "Max seconds to wait for a translation. After that the original is shown/sent.");
			UiScale = b.BindRange("General", "UiScalePercent", 100, 50, 250, "Settings window size (%).");
			WelcomeMessage = b.Bind("General", "WelcomeMessage", defaultValue: true, "Show \"Auto-translation is on. Settings: F7\" in the chat when you enter a game.");
			DebugLog = b.Bind("General", "DebugLog", defaultValue: false, "Write diagnostic lines (chat box layout, IME fix) to the log. Chat text itself is never logged.");
			IncomingEnabled = b.Bind("Incoming", "Enabled", defaultValue: true, "Auto-translate received chat.");
			IncomingLanguage = b.Bind("Incoming", "TargetLanguage", "ko", "Translate received chat into this language.");
			OriginalMode = b.Bind("Incoming", "OriginalDisplay", OriginalDisplay.Inline, "How the original text is shown: Below / Inline (small and dark) / Hover (tooltip when the cursor is over the line).");
			OriginalSize = b.BindRange("Incoming", "OriginalSizePercent", 80, 40, 100, "Original text size (%).");
			OriginalBrightness = b.BindRange("Incoming", "OriginalBrightness", 0.5f, 0.2f, 1f, "Original text brightness (0 = black, 1 = white).");
			OriginalLineSpacing = b.BindRange("Incoming", "OriginalLineSpacingPercent", 70, 40, 100, "Gap before the original in Below mode (%).");
			ShowMarker = b.Bind("Incoming", "ShowMarker", defaultValue: true, "Append a small marker to translated messages.");
			MarkerText = b.Bind("Incoming", "MarkerText", "", "Custom marker text. Empty = follow the UI language ([번역], [translated], [翻訳] ...).");
			TranslateRepeatedSyllables = b.Bind("Incoming", "TranslateRepeatedSyllables", defaultValue: false, "Translate messages (received and sent) that repeat one complete Hangul syllable (크크, 흑흑, 엉엉). Repeated jamo (ㅋㅋ, ㅏㅏ) are never translated.");
			RememberPlayerLanguage = b.Bind("Incoming", "RememberPlayerLanguage", defaultValue: true, "Short messages (ok, si, 了解) are translated from the language that player has been writing in, instead of being guessed. Also used for your own messages.");
			UseRichText = b.Bind("Incoming", "UseRichText", defaultValue: true, "Use TMP size/color tags. Turn off if raw tags show up (the original is then shown in parentheses).");
			OutgoingEnabled = b.Bind("Outgoing", "Enabled", defaultValue: false, "Translate your messages before sending.");
			OutgoingLanguage = b.Bind("Outgoing", "TargetLanguage", "en", "Language your messages are translated into.");
			OutgoingLanguageCycle = b.Bind("Outgoing", "LanguageCycle", "en,ja,ko", "Languages the cycle hotkey goes through (comma separated).");
			RawPrefix = b.Bind("Outgoing", "RawPrefix", "\\", "Messages starting with this are sent untranslated (prefix removed).");
			OutgoingWithOriginal = b.Bind("Outgoing", "IncludeOriginal", defaultValue: false, "Send the original together with the translation, e.g. Hi (안녕).");
			OutgoingFormat = b.Bind("Outgoing", "IncludeOriginalFormat", "{translated} ({original})", "Format used when IncludeOriginal is on. {translated} = translation, {original} = what you typed.");
			Engine = b.Bind("Engine", "Engine", TranslationEngine.Google, "Google (free web endpoint, no key) / GoogleCloud (official Cloud Translation API key) / DeepL (API key).");
			DeepLKey = b.Bind("Engine", "DeepLApiKey", "", "DeepL API key, stored encrypted (dpapi:...). A plain key typed here is encrypted on the next start. Keys ending in ':fx' use the free endpoint.");
			GoogleCloudKey = b.Bind("Engine", "GoogleCloudApiKey", "", "Google Cloud Translation API key, stored encrypted (dpapi:...). A plain key typed here is encrypted on the next start.");
			FallbackToGoogle = b.Bind("Engine", "FallbackToGoogle", defaultValue: true, "If the selected engine fails (no key, quota, network), try Google instead.");
			DeepLContext = b.Bind("Engine", "DeepLContext", defaultValue: true, "DeepL: send the last few chat lines as context (not translated, not billed) so short replies are translated better.");
			DeepLFormality = b.Bind("Engine", "DeepLFormality", DeepLTone.Casual, "DeepL: Default / Casual / Formal speech, for languages that have it (Japanese, German, French, Spanish ...).");
			ScrollEnabled = b.Bind("ChatBox", "ScrollEnabled", defaultValue: true, "Scroll the chat box with the mouse wheel.");
			ScrollSpeed = b.BindRange("ChatBox", "ScrollSpeed", 1f, 0.25f, 4f, "Scroll speed multiplier.");
			HistoryLines = b.BindRange("ChatBox", "MaxMessages", 500, 50, 1000, "Messages kept in the chat box (game default 500).");
			ShowScrollbar = b.Bind("ChatBox", "ShowScrollbar", defaultValue: true, "Show the chat box scrollbar.");
			ImeFixEnabled = b.Bind("ChatBox", "ImeFix", defaultValue: true, "Fix the last Korean/Japanese/Chinese character being dropped when pressing Enter.");
			AutoScrollToBottom = b.Bind("ChatBox", "AutoScrollToBottom", defaultValue: true, "When the chat input is closed, jump to the newest message when one arrives.");
			ChatWidthPercent = b.BindRange("ChatBox", "WidthPercent", 100, 50, 250, "Chat box width (%, game default = 100).");
			ChatHeightPercent = b.BindRange("ChatBox", "HeightPercent", 100, 50, 400, "Chat box height (%, game default = 100).");
			ChatTextPercent = b.BindRange("ChatBox", "TextSizePercent", 100, 50, 200, "Chat text size (%, game default = 100).");
			OpenSettingsKey = b.Bind("Hotkeys", "OpenSettings", "F7", "Open/close the settings window.");
			ToggleIncomingKey = b.Bind("Hotkeys", "ToggleIncoming", "F8", "Toggle incoming translation.");
			ToggleOutgoingKey = b.Bind("Hotkeys", "ToggleOutgoing", "F9", "Toggle outgoing translation.");
			CycleOutgoingKey = b.Bind("Hotkeys", "CycleOutgoingLanguage", "F10", "Cycle the outgoing language.");
			ApiKeys.MigratePlain(DeepLKey);
			ApiKeys.MigratePlain(GoogleCloudKey);
		}

		internal static void LogLoaded()
		{
			Log.LogInfo($"{"Sledding Chat Translator"} {"0.1.0"} loaded. Engine={Engine.Value} Incoming={IncomingEnabled.Value}({IncomingLanguage.Value}) Outgoing={OutgoingEnabled.Value}({OutgoingLanguage.Value})");
		}
	}
	internal sealed class SettingsWindow
	{
		private static readonly (string Code, string Label)[] LanguageItems = Langs.All.Select(((string Code, string Native, string English) l) => (Code: l.Code, l.Native + "  (" + l.Code + ")")).ToArray();

		private const string TestSentence = "Nice jump! Race you to the bottom of the hill?";

		private const float W = 620f;

		private const float Pad = 20f;

		private const float RowH = 36f;

		private const float LabelW = 190f;

		private const float ValueW = 90f;

		private const float Gap = 6f;

		private const float DropItemH = 32f;

		public bool Visible;

		private Rect _rect = new Rect(0f, 0f, 620f, 900f);

		private bool _dragging;

		private Vector2 _dragOffset;

		private int _tab;

		private Setting<string> _dropTarget;

		private (string Code, string Label)[] _dropItems;

		private Rect _dropAnchor;

		private Rect _dropRect;

		private Setting<string> _editingKey;

		private Task<TranslationResult> _test;

		private string _testStatus;

		private GUIStyle _footer;

		private GUIStyle _title;

		private GUIStyle _header;

		private GUIStyle _label;

		private GUIStyle _small;

		private GUIStyle _value;

		private GUIStyle _button;

		private GUIStyle _toggle;

		private GUIStyle _item;

		private GUIStyle _itemSel;

		private GUIStyle _tabOn;

		private GUIStyle _field;

		private GUIStyle _fieldHidden;

		private GUIStyle _status;

		private bool _stylesFailed;

		private bool _placed;

		private static readonly (string Code, string Label)[] ScaleItems = new int[8] { 75, 90, 100, 110, 125, 150, 175, 200 }.Select((int p) => (p.ToString(), p + "%")).ToArray();

		private static Setting<string> _scaleText;

		private string _keyBuffer;

		private GUIStyle _preview;

		private GUIStyle _previewTip;

		public bool TextFieldFocused
		{
			get
			{
				if (Visible)
				{
					return _editingKey != null;
				}
				return false;
			}
		}

		private static Setting<string> ScaleText => _scaleText ?? (_scaleText = new Setting<string>("UiScalePercent", () => Mod.UiScale.Value.ToString(), delegate(string v)
		{
			if (int.TryParse(v, out var result))
			{
				Mod.UiScale.Value = result;
			}
		}));

		private static float Scale => (float)Mathf.Clamp(Mod.UiScale.Value, 50, 250) / 100f;

		private static float ScreenW => (float)Screen.width / Scale;

		private static float ScreenH => (float)Screen.height / Scale;

		private static (string Code, string Label)[] UiLanguageChoices()
		{
			return new(string, string)[1] { ("auto", L.T("ui.auto.item")) }.Concat(L.UiLanguages.Select(((string Code, string Native) l) => (Code: l.Code, Native: l.Native))).ToArray();
		}

		public void Toggle()
		{
			Visible = !Visible;
			_dropTarget = null;
			_editingKey = null;
			_keyBuffer = null;
		}

		public void Draw()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			if (!Visible)
			{
				return;
			}
			Matrix4x4 matrix = GUI.matrix;
			GUI.matrix = Matrix4x4.Scale(new Vector3(Scale, Scale, 1f));
			try
			{
				DrawScaled();
			}
			finally
			{
				GUI.matrix = matrix;
			}
		}

		private void DrawScaled()
		{
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			EnsureStyles();
			if (!_placed)
			{
				((Rect)(ref _rect)).x = Mathf.Min(ScreenW * 0.5f, Mathf.Max(0f, ScreenW - ((Rect)(ref _rect)).width));
				((Rect)(ref _rect)).y = ScreenH / 8f;
				_placed = true;
			}
			((Rect)(ref _rect)).x = Mathf.Clamp(((Rect)(ref _rect)).x, 0f, Mathf.Max(0f, ScreenW - ((Rect)(ref _rect)).width));
			((Rect)(ref _rect)).y = Mathf.Clamp(((Rect)(ref _rect)).y, 0f, Mathf.Max(0f, ScreenH - 60f));
			Event current = Event.current;
			bool num = _dropTarget != null && current != null && IsMouseEvent(current.type) && ((Rect)(ref _dropRect)).Contains(current.mousePosition);
			EventType type = (EventType)11;
			if (num)
			{
				type = current.type;
				current.type = (EventType)11;
			}
			HandleDrag();
			DrawMain();
			if (num)
			{
				current.type = type;
			}
			if (_dropTarget != null)
			{
				DrawDropdown();
			}
		}

		private void DrawMain()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Expected O, but got Unknown
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0404: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0291: Unknown result type (might be due to invalid IL or missing references)
			//IL_0333: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f3: Expected O, but got Unknown
			Panel(_rect);
			float num = ((Rect)(ref _rect)).x + 20f;
			float num2 = ((Rect)(ref _rect)).y + 14f;
			float num3 = ((Rect)(ref _rect)).width - 40f;
			float num4 = ((Rect)(ref _rect)).xMax - 20f - 34f - 8f - 190f;
			float num5 = num4 - 6f - 84f;
			Label(new Rect(num, num2, num5 - num - 4f, 34f), L.T("title"), _title);
			float num6 = ((_title != null) ? _title.CalcSize(new GUIContent(L.T("title"))).x : 200f);
			Label(new Rect(num + num6 + 10f, num2 + 8f, 90f, 24f), "v0.1.0", _small);
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(num5, num2 + 2f, 84f, 30f);
			bool flag = _dropTarget == ScaleText;
			if (Button(val, Mod.UiScale.Value + "%" + (flag ? " ▲" : " ▼")))
			{
				if (flag)
				{
					_dropTarget = null;
				}
				else
				{
					_dropTarget = ScaleText;
					_dropItems = ScaleItems;
				}
			}
			if (_dropTarget == ScaleText)
			{
				_dropAnchor = val;
			}
			Rect val2 = default(Rect);
			((Rect)(ref val2))..ctor(num4, num2 + 2f, 190f, 30f);
			int num7 = Array.FindIndex(L.UiLanguages, ((string Code, string Native) l) => l.Code == L.Lang);
			string text = ((num7 >= 0) ? L.UiLanguages[num7].Native : "English");
			string text2 = "UI: " + (L.IsAuto ? (L.T("ui.auto") + " (" + text + ")") : text);
			bool flag2 = _dropTarget == Mod.UiLanguage;
			if (Button(val2, text2 + (flag2 ? "  ▲" : "  ▼")))
			{
				if (flag2)
				{
					_dropTarget = null;
				}
				else
				{
					_dropTarget = Mod.UiLanguage;
					_dropItems = UiLanguageChoices();
				}
			}
			if (_dropTarget == Mod.UiLanguage)
			{
				_dropAnchor = val2;
			}
			if (Button(new Rect(((Rect)(ref _rect)).xMax - 20f - 34f, num2 + 2f, 34f, 30f), "X"))
			{
				Toggle();
			}
			num2 += 44f;
			string[] array = new string[3]
			{
				L.T("tab.translate"),
				L.T("tab.chat"),
				L.T("tab.engine")
			};
			float num8 = num3 / (float)array.Length;
			for (int num9 = 0; num9 < array.Length; num9++)
			{
				if (Button(new Rect(num + num8 * (float)num9, num2, num8 - 4f, 36f), array[num9], (num9 == _tab) ? _tabOn : _button))
				{
					_tab = num9;
					_dropTarget = null;
					_editingKey = null;
				}
			}
			num2 += 48f;
			switch (_tab)
			{
			case 0:
				DrawTranslateTab(num, ref num2, num3);
				break;
			case 1:
				DrawChatTab(num, ref num2, num3);
				break;
			default:
				DrawEngineTab(num, ref num2, num3);
				break;
			}
			num2 += 8f;
			string text3 = HotkeyFooter();
			float num10 = 28f;
			if (_footer != null)
			{
				try
				{
					num10 = Mathf.Max(24f, _footer.CalcHeight(new GUIContent(text3), num3));
				}
				catch
				{
				}
			}
			Label(new Rect(num, num2, num3, num10), text3, _footer ?? _small);
			num2 += num10;
			((Rect)(ref _rect)).height = num2 - ((Rect)(ref _rect)).y + 10f;
		}

		private void DrawTranslateTab(float x, ref float y, float w)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_03db: Unknown result type (might be due to invalid IL or missing references)
			Section(ref y, x, w, L.T("sec.incoming"));
			Mod.IncomingEnabled.Value = Toggle(x, ref y, w, Mod.IncomingEnabled.Value, L.T("auto"));
			Picker(x, ref y, w, L.T("target"), Mod.IncomingLanguage, LanguageItems, arrows: true);
			Label(new Rect(x, y, 190f, 36f), L.T("orig.show"), _label);
			OriginalDisplay[] array = new OriginalDisplay[3]
			{
				OriginalDisplay.Below,
				OriginalDisplay.Inline,
				OriginalDisplay.Hover
			};
			string[] array2 = new string[3]
			{
				L.T("orig.below"),
				L.T("orig.inline"),
				L.T("orig.hover")
			};
			float num = (w - 190f) / 3f;
			for (int i = 0; i < 3; i++)
			{
				bool flag = Mod.OriginalMode.Value == array[i];
				if (Button(new Rect(x + 190f + num * (float)i, y + 2f, num - 6f, 32f), array2[i], flag ? _tabOn : _button))
				{
					Mod.OriginalMode.Value = array[i];
				}
			}
			y += 36f;
			if (Mod.OriginalMode.Value == OriginalDisplay.Hover)
			{
				Label(new Rect(x, y, w, 26f), L.T("orig.hoverhint"), _small);
				y += 30f;
			}
			else
			{
				Mod.OriginalSize.Value = Step(Slider(x, ref y, w, L.T("orig.size"), Mod.OriginalSize.Value, 40f, 100f, Mod.OriginalSize.Value + "%"), 5);
				if (Mod.OriginalMode.Value == OriginalDisplay.Below)
				{
					Mod.OriginalLineSpacing.Value = Step(Slider(x, ref y, w, L.T("orig.spacing"), Mod.OriginalLineSpacing.Value, 40f, 100f, Mod.OriginalLineSpacing.Value + "%"), 5);
				}
			}
			Mod.OriginalBrightness.Value = (float)Math.Round(Slider(x, ref y, w, L.T("orig.bright"), Mod.OriginalBrightness.Value, 0.2f, 1f, Mathf.RoundToInt(Mod.OriginalBrightness.Value * 100f) + "%"), 2);
			Mod.ShowMarker.Value = Toggle(x, ref y, w, Mod.ShowMarker.Value, L.T("marker", L.Marker));
			Mod.UseRichText.Value = Toggle(x, ref y, w, Mod.UseRichText.Value, L.T("rich"));
			DrawPreview(x, ref y, w);
			Mod.RememberPlayerLanguage.Value = Toggle(x, ref y, w, Mod.RememberPlayerLanguage.Value, L.T("playerlang"));
			Mod.TranslateRepeatedSyllables.Value = Toggle(x, ref y, w, Mod.TranslateRepeatedSyllables.Value, L.T("repeat"));
			y += 10f;
			Section(ref y, x, w, L.T("sec.outgoing"));
			Mod.OutgoingEnabled.Value = Toggle(x, ref y, w, Mod.OutgoingEnabled.Value, L.T("send.translate"));
			Mod.OutgoingWithOriginal.Value = Toggle(x, ref y, w, Mod.OutgoingWithOriginal.Value, L.T("send.withorig"));
			Picker(x, ref y, w, L.T("send.lang"), Mod.OutgoingLanguage, LanguageItems, arrows: true);
			CyclePicker(x, ref y, w);
			Label(new Rect(x, y, w, 26f), L.T("send.raw", Mod.RawPrefix.Value), _small);
			y += 30f;
		}

		private void CyclePicker(float x, ref float y, float w)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			Label(new Rect(x, y, 190f, 36f), L.T("send.cycle"), _label);
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(x + 190f, y + 2f, w - 190f, 32f);
			bool flag = _dropTarget == Mod.OutgoingLanguageCycle;
			string text = string.Join(" → ", CycleList());
			if (Button(val, text + (flag ? "   ▲" : "   ▼")))
			{
				if (flag)
				{
					_dropTarget = null;
				}
				else
				{
					_dropTarget = Mod.OutgoingLanguageCycle;
					_dropItems = LanguageItems;
				}
			}
			if (_dropTarget == Mod.OutgoingLanguageCycle)
			{
				_dropAnchor = val;
			}
			y += 36f;
			Label(new Rect(x, y, w, 26f), L.T("send.cycle.hint", Mod.CycleOutgoingKey.Value), _small);
			y += 28f;
		}

		private static List<string> CycleList()
		{
			return (from s in Mod.OutgoingLanguageCycle.Value.Split(',')
				select s.Trim() into s
				where s.Length > 0
				select s).ToList();
		}

		private void DrawChatTab(float x, ref float y, float w)
		{
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			Section(ref y, x, w, L.T("sec.size"));
			Mod.ChatWidthPercent.Value = Step(Slider(x, ref y, w, L.T("width"), Mod.ChatWidthPercent.Value, 50f, 250f, Mod.ChatWidthPercent.Value + "%"), 5);
			Mod.ChatHeightPercent.Value = Step(Slider(x, ref y, w, L.T("height"), Mod.ChatHeightPercent.Value, 50f, 400f, Mod.ChatHeightPercent.Value + "%"), 5);
			Mod.ChatTextPercent.Value = Step(Slider(x, ref y, w, L.T("textsize"), Mod.ChatTextPercent.Value, 50f, 200f, Mod.ChatTextPercent.Value + "%"), 5);
			if (Button(new Rect(x, y + 4f, 200f, 32f), L.T("reset.size")))
			{
				Mod.ChatWidthPercent.Value = 100;
				Mod.ChatHeightPercent.Value = 100;
				Mod.ChatTextPercent.Value = 100;
			}
			y += 48f;
			Section(ref y, x, w, L.T("sec.scroll"));
			Mod.ScrollEnabled.Value = Toggle(x, ref y, w, Mod.ScrollEnabled.Value, L.T("scroll.wheel"));
			Mod.ShowScrollbar.Value = Toggle(x, ref y, w, Mod.ShowScrollbar.Value, ChatBoxTweaks.HasScrollbarParts ? L.T("scroll.bar") : L.T("scroll.bar.na"));
			Mod.AutoScrollToBottom.Value = Toggle(x, ref y, w, Mod.AutoScrollToBottom.Value, L.T("scroll.auto"));
			Mod.ScrollSpeed.Value = (float)Math.Round(Slider(x, ref y, w, L.T("scroll.speed"), Mod.ScrollSpeed.Value, 0.25f, 4f, Mod.ScrollSpeed.Value.ToString("0.##") + "x"), 2);
			Mod.HistoryLines.Value = Step(Slider(x, ref y, w, L.T("history"), Mod.HistoryLines.Value, 50f, 1000f, L.T("count", Mod.HistoryLines.Value)), 50);
			y += 12f;
			Section(ref y, x, w, L.T("sec.other"));
			Mod.ImeFixEnabled.Value = Toggle(x, ref y, w, Mod.ImeFixEnabled.Value, L.T("ime.fix"));
			Mod.WelcomeMessage.Value = Toggle(x, ref y, w, Mod.WelcomeMessage.Value, L.T("welcome"));
		}

		private void DrawEngineTab(float x, ref float y, float w)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			Label(new Rect(x, y, 190f, 36f), L.T("engine"), _label);
			y += 36f;
			TranslationEngine[] array = new TranslationEngine[3]
			{
				TranslationEngine.Google,
				TranslationEngine.GoogleCloud,
				TranslationEngine.DeepL
			};
			string[] array2 = new string[3]
			{
				L.T("engine.google"),
				L.T("engine.gcloud"),
				L.T("engine.deepl")
			};
			float num = w / (float)array.Length;
			for (int i = 0; i < array.Length; i++)
			{
				bool flag = Mod.Engine.Value == array[i];
				if (Button(new Rect(x + num * (float)i, y + 2f, num - 6f, 32f), array2[i], flag ? _tabOn : _button))
				{
					Mod.Engine.Value = array[i];
					_editingKey = null;
					_testStatus = null;
					TranslationService.ClearCache();
				}
			}
			y += 40f;
			switch (Mod.Engine.Value)
			{
			case TranslationEngine.GoogleCloud:
				Note(x, ref y, w, L.T("engine.gcloud.desc"));
				KeyField(x, ref y, w, Mod.GoogleCloudKey);
				break;
			case TranslationEngine.DeepL:
				Note(x, ref y, w, L.T("engine.deepl.desc"));
				KeyField(x, ref y, w, Mod.DeepLKey);
				DeepLOptions(x, ref y, w);
				break;
			default:
				Note(x, ref y, w, L.T("engine.google.desc"));
				break;
			}
			if (Mod.Engine.Value != TranslationEngine.Google)
			{
				Mod.FallbackToGoogle.Value = Toggle(x, ref y, w, Mod.FallbackToGoogle.Value, L.T("fallback"));
			}
			y += 6f;
			bool flag2 = _test != null && !_test.IsCompleted;
			if (Button(new Rect(x, y, 160f, 34f), flag2 ? L.T("test.running") : L.T("test")) && !flag2)
			{
				TranslationService.ClearCache();
				_test = TranslationService.TranslateAsync("Nice jump! Race you to the bottom of the hill?", Mod.IncomingLanguage.Value);
				_testStatus = null;
			}
			if (_test != null && _test.IsCompleted)
			{
				TranslationResult result = _test.Result;
				_testStatus = (result.Ok ? (L.T("test.ok", result.Engine) + result.Text) : (L.T("test.fail") + (result.Error ?? TranslationService.LastError)));
				_test = null;
			}
			y += 38f;
			if (!string.IsNullOrEmpty(_testStatus))
			{
				Label(new Rect(x, y, w, 46f), _testStatus, _small);
				y += 50f;
			}
			else if (!string.IsNullOrEmpty(TranslationService.LastError))
			{
				Label(new Rect(x, y, w, 46f), L.T("lasterror") + TranslationService.LastError, _small);
				y += 50f;
			}
		}

		private void DeepLOptions(float x, ref float y, float w)
		{
			//IL_0034: Unknown result