Decompiled source of Auto Translate v1.0.12

AutoTranslate.dll

Decompiled 11 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using ETGGUI;
using HarmonyLib;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SGUI;
using UnityEngine;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("AutoTranslate")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AutoTranslate")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("825bc8e2-2faf-496c-803c-3f3e31eba1a0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace AutoTranslate;

internal class AssetBundleLoader
{
	public static AssetBundle LoadAssetBundle(string filePath)
	{
		AssetBundle result = null;
		if (File.Exists(filePath))
		{
			try
			{
				result = AssetBundle.LoadFromFile(filePath);
				Debug.Log((object)"已成功加载AssetBundle!Successfully loaded AssetBundle!");
			}
			catch (Exception ex)
			{
				Debug.LogError((object)"从文件加载AssetBundle失败。Failed loading AssetBundle from file.");
				Debug.LogError((object)ex.ToString());
			}
		}
		else
		{
			Debug.LogError((object)"AssetBundle不存在!AssetBundle does not exist!");
		}
		return result;
	}
}
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInPlugin("kleirof.etg.autotranslate", "Auto Translate", "1.0.12")]
public class AutoTranslateModule : BaseUnityPlugin
{
	public enum TranslationAPIType
	{
		Tencent,
		Baidu,
		Azure,
		LargeModel
	}

	public enum OverrideFontType
	{
		None,
		Chinese,
		English,
		Japanese,
		Korean,
		Russian,
		Polish,
		Custom
	}

	public const string GUID = "kleirof.etg.autotranslate";

	public const string NAME = "Auto Translate";

	public const string VERSION = "1.0.12";

	public const string TEXT_COLOR = "#AA3399";

	internal static AutoTranslateModule instance;

	private ConfigEntry<bool> AcceptedModDeclaration;

	private ConfigEntry<TranslationAPIType> TranslationAPI;

	private ConfigEntry<KeyCode> ToggleTranslationKeyBinding;

	private ConfigEntry<string> RegexForFullTextNeedToTranslate;

	private ConfigEntry<string> RegexForEachLineNeedToTranslate;

	private ConfigEntry<string> RegexForIgnoredSubstringWithinText;

	private ConfigEntry<int> RequestBatchSize;

	private ConfigEntry<int> MaxRetryCount;

	private ConfigEntry<int> TranslationCacheCapacity;

	private ConfigEntry<string> PresetTranslations;

	private ConfigEntry<bool> LogRequestedTexts;

	private ConfigEntry<OverrideFontType> OverrideFont;

	private ConfigEntry<string> FontAssetBundleName;

	private ConfigEntry<string> CustomDfFontName;

	private ConfigEntry<string> CustomTk2dFontName;

	private ConfigEntry<string> RegexForDfTokenizer;

	private ConfigEntry<float> DfTextScaleExpandThreshold;

	private ConfigEntry<float> DfTextScaleExpandToValue;

	private ConfigEntry<bool> ShowRequestedCharacterCount;

	private ConfigEntry<int> RequestedCharacterCountAlertThreshold;

	private ConfigEntry<KeyCode> ToggleRequestedCharacterCountKeyBinding;

	private ConfigEntry<string> CountLabelAnchor;

	private ConfigEntry<string> CountLabelPivot;

	private ConfigEntry<bool> TranslateTextsOfItemTipsMod;

	private ConfigEntry<string> RegexForItemTipsModTokenizer;

	private ConfigEntry<string> TencentSecretId;

	private ConfigEntry<string> TencentSecretKey;

	private ConfigEntry<string> TencentSourceLanguage;

	private ConfigEntry<string> TencentTargetLanguage;

	private ConfigEntry<string> TencentRegion;

	private ConfigEntry<string> BaiduAppId;

	private ConfigEntry<string> BaiduSecretKey;

	private ConfigEntry<string> BaiduSourceLanguage;

	private ConfigEntry<string> BaiduTargetLanguage;

	private ConfigEntry<string> AzureSubscriptionKey;

	private ConfigEntry<string> AzureSourceLanguage;

	private ConfigEntry<string> AzureTargetLanguage;

	private ConfigEntry<string> AzureRegion;

	private ConfigEntry<string> LargeModelBaseUrl;

	private ConfigEntry<string> LargeModelApiKey;

	private ConfigEntry<string> LargeModelName;

	private ConfigEntry<string> LargeModelPrompt;

	private ConfigEntry<int> LargeModelMaxTokens;

	private ConfigEntry<float> LargeModelTemperature;

	private ConfigEntry<float> LargeModelTopP;

	private ConfigEntry<float> LargeModelFrequencyPenalty;

	private Harmony harmony;

	private bool isConfigValid;

	private GameObject autoTranslateObject;

	internal TranslationManager translateManager;

	internal FontManager fontManager;

	internal AutoTranslateConfig config;

	internal StatusLabelController statusLabel;

	private readonly string errorColor = "#FF0000";

	public void Start()
	{
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Expected O, but got Unknown
		ETGModMainBehaviour.WaitForGameManagerStart((Action<GameManager>)GMStart);
		instance = this;
		config = InitializeConfigs();
		if (!AcceptedModDeclaration.Value)
		{
			Debug.LogError((object)"AutoTranslate: 还未接受Mod声明!Mod declaration not accepted!");
			return;
		}
		if (!isConfigValid)
		{
			Debug.LogError((object)"AutoTranslate: 翻译配置无效!Invalid Translate Config!");
			return;
		}
		fontManager = new FontManager();
		harmony = new Harmony("kleirof.etg.autotranslate");
		harmony.PatchAll();
		autoTranslateObject = new GameObject("Auto Translate Object");
		Object.DontDestroyOnLoad((Object)(object)autoTranslateObject);
		translateManager = autoTranslateObject.AddComponent<TranslationManager>();
		translateManager.Initialize();
		DoOptionalPatches();
		statusLabel = new StatusLabelController();
	}

	internal static void Log(string text, string color = "FFFFFF")
	{
		ETGModConsole.Log((object)("<color=" + color + ">" + text + "</color>"), false);
	}

	internal void GMStart(GameManager g)
	{
		if (!AcceptedModDeclaration.Value)
		{
			Log("Auto Translate v1.0.12 started, but AcceptedModDeclaration not checked!", errorColor);
			Log("(Important!) Please read the declaration on mod website and then check the config in mod manager or manually edit it.", errorColor);
		}
		else if (!isConfigValid)
		{
			Log("Auto Translate v1.0.12 started, but config invalid!", errorColor);
			Log("Please check the config in mod manager or manually edit it.", errorColor);
		}
		else
		{
			Log("Auto Translate v1.0.12 started successfully.", "#AA3399");
			fontManager?.InitializeFontAfterGameManager(OverrideFont.Value);
			statusLabel?.InitializeStatusLabel();
		}
	}

	private AutoTranslateConfig InitializeConfigs()
	{
		//IL_06a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_06ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_07da: Unknown result type (might be due to invalid IL or missing references)
		//IL_07df: Unknown result type (might be due to invalid IL or missing references)
		AcceptedModDeclaration = ((BaseUnityPlugin)this).Config.Bind<bool>("1.General", "AcceptedModDeclaration", false, "作为Mod用户,我已阅读并同意网站上此mod的声明,清楚潜在费用的去向并信任此mod的行为,并对自己的选择负责任。As a mod user, I have read and accepted the declaration on this mod's website, understand the potential destination of the fees, trust the actions of this mod, and take responsibility for my choice.");
		TranslationAPI = ((BaseUnityPlugin)this).Config.Bind<TranslationAPIType>("1.General", "TranslationAPI", TranslationAPIType.Tencent, "选择使用的翻译API。Choose the translation API to use.");
		ToggleTranslationKeyBinding = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("1.General", "ToggleTranslationKeyBinding", (KeyCode)291, "启用或关闭翻译的按键。The key binding of toggling translation.");
		RegexForFullTextNeedToTranslate = ((BaseUnityPlugin)this).Config.Bind<string>("1.General", "RegexForFullTextNeedToTranslate", "^(?!Enter the Gungeon).*$", "正则表达式,一个多行文本若匹配为真,则这个多行文本保留以待翻译。用来筛选待翻译的文本以节省翻译额度。Regular expression, if a multiple line text matches true, then this multiple line text is retained for translation. Used to filter the text to be translated to save translation quotas.");
		RegexForEachLineNeedToTranslate = ((BaseUnityPlugin)this).Config.Bind<string>("1.General", "RegexForEachLineNeedToTranslate", "^(?![@#])(?=\\S)(?!^[\\d\\p{P}]+$)(?!.*[\\u4e00-\\u9fa5\\u3000-\\u303F\\uFF00-\\uFFEF]).*$", "正则表达式,多行文本若存在一行匹配,整个多行文本保留以待翻译。用来筛选待翻译的文本以节省翻译额度。Regular expression, if there is a matching line in multiple lines of text, the entire multiple lines of text are retained for translation. Used to filter the text to be translated to save translation quotas.");
		RegexForIgnoredSubstringWithinText = ((BaseUnityPlugin)this).Config.Bind<string>("1.General", "RegexForIgnoredSubstringWithinText", "(?:\\[color\\s+[^\\]]+\\])|(?:\\[sprite\\s+[^\\]]+\\])|(?:\\[/color\\])|(?:\\{[^}]*\\})|(?:\\^[\\w\\d]{9})|(?:[\\u4e00-\\u9fa5\\u3000-\\u303F\\uFF00-\\uFFEF]+)|(?:<color=[^>]+>)|(?:</color>)|(?:<|>)|(?:^\\s*[\\d\\p{P}]+\\s*$)", "正则表达式,匹配文本中需要忽略的子文本。请使用非捕获组。这通常包括一些要特殊处理的贴图和转义符。Regular expression, matching sub texts that need to be ignored in the text. Please use non capture groups. This usually includes some textures and escape characters that require special handling.");
		RequestBatchSize = ((BaseUnityPlugin)this).Config.Bind<int>("1.General", "RequestBatchSize", 1024, "发送请求的批量数据总大小。若翻译api提示单次请求过长,请减小此值。The total size of batch data for sending requests. If the translation API prompts that a single request is too long, please reduce this value.");
		MaxRetryCount = ((BaseUnityPlugin)this).Config.Bind<int>("1.General", "MaxRetryCount", 3, "发生错误时的最大重试次数。The maximum number of retries when an error occurs.");
		TranslationCacheCapacity = ((BaseUnityPlugin)this).Config.Bind<int>("1.General", "TranslationCacheCapacity", 1024, "最大翻译缓存容量。Maximum translation cache capacity.");
		PresetTranslations = ((BaseUnityPlugin)this).Config.Bind<string>("1.General", "PresetTranslations", "PresetTranslations.json", "预设翻译的文件名。使用预设翻译以减少加载时常见文本的翻译请求,留空表示不使用。预设翻译为位于dll同目录下的json文件。The file name for the preset translation. Use preset translation to reduce translation requests for common text during loading, leaving blank to indicate not using. The preset translation is a JSON file located in the same directory as the DLL.");
		LogRequestedTexts = ((BaseUnityPlugin)this).Config.Bind<bool>("1.General", "LogRequestedTexts", false, "在日志中显示请求翻译的文本。Log the text requested for translation.");
		OverrideFont = ((BaseUnityPlugin)this).Config.Bind<OverrideFontType>("2.Font", "OverrideFont", OverrideFontType.Custom, "用来覆盖游戏字体的字体。根据你需要的目标语言选择。Font used to override the font of the game. Choose according to the target language you need.");
		FontAssetBundleName = ((BaseUnityPlugin)this).Config.Bind<string>("2.Font", "FontAssetBundleName", "fusion_pixel_12px_zh_cn", "包含自定义字体的AssetBundle名称。位于dll同目录下。AssetBundle name containing custom fonts. Located in the same directory as DLL.");
		CustomDfFontName = ((BaseUnityPlugin)this).Config.Bind<string>("2.Font", "CustomDfFontName", "Fusion_Pixel_12px_Monospaced_dfDynamic", "要使用的自定义df字体。请把它包含于FontAssetBundle。The custom df font to be used. Please include it in FontAssetBundle.");
		CustomTk2dFontName = ((BaseUnityPlugin)this).Config.Bind<string>("2.Font", "CustomTk2dFontName", "Fusion_Pixel_12px_Monospaced_tk2d", "要使用的自定义tk2d字体。请把它包含于FontAssetBundle。The custom tk2d font to be used. Please include it in FontAssetBundle.");
		RegexForDfTokenizer = ((BaseUnityPlugin)this).Config.Bind<string>("2.Font", "RegexForDfTokenizer", FontManager.defaultRegexForTokenizer, "用于df生成token的正则表达式。token用于处理文本的自动换行位置。如每个字换行还是单词后换行。参考默认样例填写。建议只修改Text相关内容。A regular expression used for generating tokens from df. Token is used to handle the automatic line break position of text. Whether to wrap each word or to wrap after each word. Fill in according to the default example. Suggest only modifying content related to Text.");
		DfTextScaleExpandThreshold = ((BaseUnityPlugin)this).Config.Bind<float>("2.Font", "DfTextScaleExpandThreshold", 1f, "低于这个值的Df TextScale会被扩大。为负表示不生效。Df TextScale below this value will be expanded. Negative indicates non effectiveness.");
		DfTextScaleExpandToValue = ((BaseUnityPlugin)this).Config.Bind<float>("2.Font", "DfTextScaleExpandToValue", 2f, "低于门槛的Df TextScale被扩大到多少。How much is the Df TextScale below the threshold expanded to.");
		ShowRequestedCharacterCount = ((BaseUnityPlugin)this).Config.Bind<bool>("3.RequestedCharacterCount", "ShowRequestedCharacterCount", true, "显示已翻译字符数。Show requested character count.");
		RequestedCharacterCountAlertThreshold = ((BaseUnityPlugin)this).Config.Bind<int>("3.RequestedCharacterCount", "RequestedCharacterCountAlertThreshold", 50000, "已请求翻译字符数警报阈值。当翻译请求即将超出时,会暂停翻译。为零表示不设阈值。The alert threshold of the count of characters requested for translation. When this count is about to exceed, translation will be paused. A value of zero indicates no threshold is set.");
		ToggleRequestedCharacterCountKeyBinding = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("3.RequestedCharacterCount", "ToggleRequestedCharacterCountKeyBinding", (KeyCode)287, "开启或关闭已翻译字符数的显示的按键。The key binding of toggling the display of requested character count.");
		CountLabelAnchor = ((BaseUnityPlugin)this).Config.Bind<string>("3.RequestedCharacterCount", "CountLabelAnchor", "0.5 0", "用空格或逗号分隔的一个二维向量,决定计数标签相对于父级的锚点位置。左上角为0 0,右下角是1 1。A two-dimensional vector separated by spaces or commas, which determines where the count label is anchored relative to its parent. The top left corner is 0 0, and the bottom right corner is 1 1.");
		CountLabelPivot = ((BaseUnityPlugin)this).Config.Bind<string>("3.RequestedCharacterCount", "CountLabelPivot", "0.5 0", "用空格或逗号分隔的一个二维向量,定义计数标签的定位基准点。左上角为0 0,右下角是1 1。A two-dimensional vector separated by spaces or commas, which defines the pivot point of the count label for positioning. The top left corner is 0 0, and the bottom right corner is 1 1.");
		TranslateTextsOfItemTipsMod = ((BaseUnityPlugin)this).Config.Bind<bool>("4.Compatibility", "TranslateTextsOfItemTipsMod", true, "翻译ItemTipsMod中的文本。Translate the text in ItemTipsMod.");
		RegexForItemTipsModTokenizer = ((BaseUnityPlugin)this).Config.Bind<string>("4.Compatibility", "RegexForItemTipsModTokenizer", FontManager.defaultRegexForItemTipsModTokenizer, "用于ItemTipsMod生成token的正则表达式。token用于处理文本的自动换行位置。如每个字换行还是单词后换行。A regular expression used for generating tokens from ItemTipsMod. Token is used to handle the automatic line break position of text. Whether to wrap each word or to wrap after each word.");
		TencentSecretId = ((BaseUnityPlugin)this).Config.Bind<string>("5.TencentTranslation", "SecretId", "", "腾讯翻译的SecretId。The SecretId of Tencent Translate.");
		TencentSecretKey = ((BaseUnityPlugin)this).Config.Bind<string>("5.TencentTranslation", "SecretKey", "", "腾讯翻译的SecretKey。The SecretKey of Tencent Translate.");
		TencentSourceLanguage = ((BaseUnityPlugin)this).Config.Bind<string>("5.TencentTranslation", "SourceLanguage", "en", "腾讯翻译的源语言,如en。The source language of Tencent Translate, such as en.");
		TencentTargetLanguage = ((BaseUnityPlugin)this).Config.Bind<string>("5.TencentTranslation", "TargetLanguage", "zh", "腾讯翻译的目标语言,如zh。Tencent Translate's target language, such as zh.");
		TencentRegion = ((BaseUnityPlugin)this).Config.Bind<string>("5.TencentTranslation", "Region", "ap-beijing", "地域,用来标识希望连接哪个地域的服务器,如ap-beijing。Region, used to identify which region's server you want to connect to, such as ap-beijing.");
		BaiduAppId = ((BaseUnityPlugin)this).Config.Bind<string>("6.BaiduTranslate", "SecretId", "", "百度翻译的AppId。The AppId of Baidu Translate.");
		BaiduSecretKey = ((BaseUnityPlugin)this).Config.Bind<string>("6.BaiduTranslate", "SecretKey", "", "百度翻译的SecretKey。The SecretKey for Baidu Translate.");
		BaiduSourceLanguage = ((BaseUnityPlugin)this).Config.Bind<string>("6.BaiduTranslate", "SourceLanguage", "en", "百度翻译的源语言,如en。The source language of Baidu Translate, such as en.");
		BaiduTargetLanguage = ((BaseUnityPlugin)this).Config.Bind<string>("6.BaiduTranslate", "TargetLanguage", "zh", "百度翻译的目标语言,如zh。The target language for Baidu Translate, such as zh.");
		AzureSubscriptionKey = ((BaseUnityPlugin)this).Config.Bind<string>("7.AzureTranslate", "AzureSubscriptionKey", "", "Azure翻译的SubscriptionKey。Subscription Key for Azure Translation.");
		AzureSourceLanguage = ((BaseUnityPlugin)this).Config.Bind<string>("7.AzureTranslate", "SourceLanguage", "en", "Azure翻译的源语言,如en。The source language for Azure translation, such as en.");
		AzureTargetLanguage = ((BaseUnityPlugin)this).Config.Bind<string>("7.AzureTranslate", "TargetLanguage", "zh-Hans", "Azure翻译的目标语言,如zh-Hans。The target language for Azure translation, such as zh-Hans.");
		AzureRegion = ((BaseUnityPlugin)this).Config.Bind<string>("7.AzureTranslate", "AzureRegion", "global", "地域,用来标识希望连接哪个地域的服务器,如global。Region, used to identify which region's server you want to connect to, such as global.");
		LargeModelBaseUrl = ((BaseUnityPlugin)this).Config.Bind<string>("8.LargeModel", "LargeModelBaseUrl", "", "大模型API的基础URL,用来连接到目标大模型服务的接口地址。Base URL of the large model API, used to connect to the target large model service endpoint.");
		LargeModelApiKey = ((BaseUnityPlugin)this).Config.Bind<string>("8.LargeModel", "LargeModelApiKey", "", "大模型API的访问密钥,用来进行身份验证并访问API服务。API key for the large model, used for authentication and accessing the API service.");
		LargeModelName = ((BaseUnityPlugin)this).Config.Bind<string>("8.LargeModel", "LargeModelName", "", "大模型的名称,指定要使用的模型版本或名称。The name of the large model, specifying which model version or name to use.");
		LargeModelPrompt = ((BaseUnityPlugin)this).Config.Bind<string>("8.LargeModel", "LargeModelPrompt", "英文翻译为中文,仅返回JSON的内容。输出格式和输入一致。输入:[{\"id\":1,\"text\":\"Hello\"}, {\"id\":2,\"text\":\"World\"}] 输出:[{\"id\":1,\"text\":\"你好\"}, {\"id\":2,\"text\":\"世界\"}]", "Prompt是向语言模型提供指示或请求的输入文本,帮助模型理解任务并生成响应。A prompt is the input text given to a language model to guide it in understanding the task and generating a response.");
		LargeModelMaxTokens = ((BaseUnityPlugin)this).Config.Bind<int>("8.LargeModel", "LargeModelMaxTokens", 1024, "大模型API允许的最大token数,控制生成内容的最大长度。Maximum number of tokens allowed by the large model API, controlling the maximum length of generated content.");
		LargeModelTemperature = ((BaseUnityPlugin)this).Config.Bind<float>("8.LargeModel", "LargeModelTemperature", 1.3f, "控制大模型生成文本的创造性,值越高,生成的文本越随机,越低则越确定。Controls the creativity of the large model's text generation, with higher values leading to more random and lower values leading to more deterministic output.");
		LargeModelTopP = ((BaseUnityPlugin)this).Config.Bind<float>("8.LargeModel", "LargeModelTopP", 0.7f, "控制大模型生成文本时的采样范围,值越低,结果越集中。Controls the sampling range of the large model's text generation, with lower values leading to more focused results.");
		LargeModelFrequencyPenalty = ((BaseUnityPlugin)this).Config.Bind<float>("8.LargeModel", "LargeModelFrequencyPenalty", 0f, "控制生成文本中词汇重复的概率。值越高,生成内容越多样化;值越低,生成内容越集中和重复。Controls the likelihood of token repetition in generated text.Higher values promote diversity, while lower values result in more focused and repetitive outputs.");
		AutoTranslateConfig autoTranslateConfig = new AutoTranslateConfig
		{
			TranslationAPI = TranslationAPI.Value,
			ToggleTranslationKeyBinding = ToggleTranslationKeyBinding.Value,
			RegexForFullTextNeedToTranslate = RegexForFullTextNeedToTranslate.Value,
			RegexForEachLineNeedToTranslate = RegexForEachLineNeedToTranslate.Value,
			RegexForIgnoredSubstringWithinText = RegexForIgnoredSubstringWithinText.Value,
			RequestBatchSize = RequestBatchSize.Value,
			MaxRetryCount = MaxRetryCount.Value,
			TranslationCacheCapacity = TranslationCacheCapacity.Value,
			PresetTranslations = PresetTranslations.Value,
			LogRequestedTexts = LogRequestedTexts.Value,
			OverrideFont = OverrideFont.Value,
			FontAssetBundleName = FontAssetBundleName.Value,
			CustomDfFontName = CustomDfFontName.Value,
			CustomTk2dFontName = CustomTk2dFontName.Value,
			RegexForDfTokenizer = RegexForDfTokenizer.Value,
			DfTextScaleExpandThreshold = DfTextScaleExpandThreshold.Value,
			DfTextScaleExpandToValue = DfTextScaleExpandToValue.Value,
			ShowRequestedCharacterCount = ShowRequestedCharacterCount.Value,
			RequestedCharacterCountAlertThreshold = RequestedCharacterCountAlertThreshold.Value,
			ToggleRequestedCharacterCountKeyBinding = ToggleRequestedCharacterCountKeyBinding.Value,
			CountLabelAnchor = CountLabelAnchor.Value,
			CountLabelPivot = CountLabelPivot.Value,
			RegexForItemTipsModTokenizer = RegexForItemTipsModTokenizer.Value,
			TencentSecretId = TencentSecretId.Value,
			TencentSecretKey = TencentSecretKey.Value,
			TencentSourceLanguage = TencentSourceLanguage.Value,
			TencentTargetLanguage = TencentTargetLanguage.Value,
			TencentRegion = TencentRegion.Value,
			BaiduAppId = BaiduAppId.Value,
			BaiduSecretKey = BaiduSecretKey.Value,
			BaiduSourceLanguage = BaiduSourceLanguage.Value,
			BaiduTargetLanguage = BaiduTargetLanguage.Value,
			AzureSubscriptionKey = AzureSubscriptionKey.Value,
			AzureSourceLanguage = AzureSourceLanguage.Value,
			AzureTargetLanguage = AzureTargetLanguage.Value,
			AzureRegion = AzureRegion.Value,
			LargeModelBaseUrl = LargeModelBaseUrl.Value,
			LargeModelApiKey = LargeModelApiKey.Value,
			LargeModelName = LargeModelName.Value,
			LargeModelPrompt = LargeModelPrompt.Value,
			LargeModelMaxTokens = LargeModelMaxTokens.Value,
			LargeModelTemperature = LargeModelTemperature.Value,
			LargeModelTopP = LargeModelTopP.Value,
			LargeModelFrequencyPenalty = LargeModelFrequencyPenalty.Value
		};
		isConfigValid = autoTranslateConfig.CheckConfigValues();
		return autoTranslateConfig;
	}

	private void DoOptionalPatches()
	{
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Expected O, but got Unknown
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Expected O, but got Unknown
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_0110: Expected O, but got Unknown
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Expected O, but got Unknown
		//IL_0195: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a2: Expected O, but got Unknown
		//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0202: Expected O, but got Unknown
		//IL_0261: Unknown result type (might be due to invalid IL or missing references)
		//IL_026f: Expected O, but got Unknown
		//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b0: Expected O, but got Unknown
		//IL_02ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fd: Expected O, but got Unknown
		//IL_0334: Unknown result type (might be due to invalid IL or missing references)
		//IL_033e: Expected O, but got Unknown
		if (Chainloader.PluginInfos.ContainsKey("glorfindel.etg.itemtips") && TranslateTextsOfItemTipsMod.Value)
		{
			FontManager.instance.itemTipsModuleType = AccessTools.TypeByName("ItemTipsMod.ItemTipsModule");
			MethodInfo methodInfo = AccessTools.Method(FontManager.instance.itemTipsModuleType, "GmStart", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(AutoTranslatePatches.GmStartPatchClass), "GmStartPostfix", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			MethodInfo methodInfo3 = AccessTools.Method(FontManager.instance.itemTipsModuleType, "LoadFont", (Type[])null, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.Method(typeof(AutoTranslatePatches.LoadFontPatchClass), "LoadFontPrefix", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(methodInfo4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			MethodInfo methodInfo5 = AccessTools.Method(FontManager.instance.itemTipsModuleType, "ConvertStringToFixedWidthLines", (Type[])null, (Type[])null);
			MethodInfo methodInfo6 = AccessTools.Method(typeof(AutoTranslatePatches.ConvertStringToFixedWidthLinesPatchClass), "ConvertStringToFixedWidthLinesPrefix", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo5, new HarmonyMethod(methodInfo6), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			MethodInfo methodInfo7 = AccessTools.Method(FontManager.instance.itemTipsModuleType, "GenerateTextInfo", (Type[])null, (Type[])null);
			MethodInfo methodInfo8 = AccessTools.Method(typeof(AutoTranslatePatches.GenerateTextInfoPatchClass), "GenerateTextInfoPatch", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo7, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo8));
			MethodInfo methodInfo9 = AccessTools.Method(FontManager.instance.itemTipsModuleType, "ShowTip", (Type[])null, (Type[])null);
			MethodInfo methodInfo10 = AccessTools.Method(typeof(AutoTranslatePatches.ShowTipPatchClass), "ShowTipPostfix", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo9, (HarmonyMethod)null, new HarmonyMethod(methodInfo10), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		if (Chainloader.PluginInfos.ContainsKey("lazymo3_and_NilT_PL.etg.NoBrain"))
		{
			MethodInfo methodInfo11 = AccessTools.Method(AccessTools.TypeByName("NBInteractableBehaviour"), "onNewShopItemController", (Type[])null, (Type[])null);
			MethodInfo methodInfo12 = AccessTools.Method(typeof(AutoTranslatePatches.NewShopItemControllerPatchClass), "NewShopItemControllerPrefix", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo11, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		if (RegexForDfTokenizer.Value != string.Empty)
		{
			Type typeFromHandle = typeof(DynamicFontRenderer);
			MethodInfo methodInfo13 = AccessTools.Method(typeFromHandle, "tokenize", (Type[])null, (Type[])null);
			MethodInfo methodInfo14 = AccessTools.Method(typeof(AutoTranslatePatches.DynamicFontRendererTokenizePatchClass), "TokenizePrefix", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo13, new HarmonyMethod(methodInfo14), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			MethodInfo methodInfo15 = AccessTools.Method(typeFromHandle, "calculateLinebreaks", (Type[])null, (Type[])null);
			MethodInfo methodInfo16 = AccessTools.Method(typeof(AutoTranslatePatches.DynamicFontRendererCalculateLinebreaksPatchClass), "CalculateLinebreaksPatch", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo15, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo16));
			Type typeFromHandle2 = typeof(BitmappedFontRenderer);
			MethodInfo methodInfo17 = AccessTools.Method(typeFromHandle2, "tokenize", (Type[])null, (Type[])null);
			MethodInfo methodInfo18 = AccessTools.Method(typeof(AutoTranslatePatches.BitmappedFontRendererTokenizePatchClass), "TokenizePrefix", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo17, new HarmonyMethod(methodInfo18), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			MethodInfo methodInfo19 = AccessTools.Method(typeFromHandle2, "calculateLinebreaks", (Type[])null, (Type[])null);
			MethodInfo methodInfo20 = AccessTools.Method(typeof(AutoTranslatePatches.BitmappedFontRendererCalculateLinebreaksPatchClass), "CalculateLinebreaksPatch", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo19, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo20));
		}
	}
}
public static class AutoTranslatePatches
{
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	public class DfLabelTextPatchClass
	{
		[HarmonyPostfix]
		public static void DfLabelTextPostfix(dfLabel __instance)
		{
			DfLabelTextAddCall(__instance);
		}
	}

	[HarmonyPatch(typeof(dfLabel), "OnLocalize")]
	public class DfLabelOnLocalizePatchClass
	{
		[HarmonyPostfix]
		public static void DfLabelOnLocalizePostfix(dfLabel __instance)
		{
			DfLabelTextAddCall(__instance);
		}
	}

	[HarmonyPatch(typeof(dfLabel), "ModifyLocalizedText")]
	public class DfLabelModifyLocalizedTextPatchClass
	{
		[HarmonyPostfix]
		public static void DfLabelModifyLocalizedTextPostfix(dfLabel __instance)
		{
			DfLabelTextAddCall(__instance);
		}
	}

	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	public class DfButtonTextPatchClass
	{
		[HarmonyPostfix]
		public static void DfButtonTextPostfix(dfButton __instance)
		{
			DfButtonTextAddCall(__instance);
		}
	}

	[HarmonyPatch(typeof(dfButton), "OnLocalize")]
	public class DfButtonOnLocalizePatchClass
	{
		[HarmonyPostfix]
		public static void DfButtonOnLocalizePostfix(dfButton __instance)
		{
			DfButtonTextAddCall(__instance);
		}
	}

	[HarmonyPatch(typeof(dfButton), "ModifyLocalizedText")]
	public class DfButtonModifyLocalizedTextPatchClass
	{
		[HarmonyPostfix]
		public static void DfButtonModifyLocalizedTextPostfix(dfButton __instance)
		{
			DfButtonTextAddCall(__instance);
		}
	}

	public class GmStartPatchClass
	{
		public static void GmStartPostfix(object __instance)
		{
			FontManager.instance.itemTipsModuleObject = __instance;
			FieldInfo field = FontManager.instance.itemTipsModuleType.GetField("_infoLabel", BindingFlags.Instance | BindingFlags.NonPublic);
			ref SLabel itemTipsModuleLabel = ref FontManager.instance.itemTipsModuleLabel;
			object? value = field.GetValue(__instance);
			itemTipsModuleLabel = (SLabel)((value is SLabel) ? value : null);
		}
	}

	public class ShowTipPatchClass
	{
		public static void ShowTipPostfix()
		{
			if (FontManager.instance.itemTipsModuleText != null)
			{
				TranslationManager.instance.AddTranslationRequest(FontManager.instance.itemTipsModuleText, FontManager.instance.itemTipsModuleLabel);
			}
		}
	}

	public class LoadFontPatchClass
	{
		public static bool LoadFontPrefix(ref Font __result)
		{
			FieldInfo field = FontManager.instance.itemTipsModuleType.GetField("_gameFont", BindingFlags.Instance | BindingFlags.NonPublic);
			dfFontBase dfFontBase = FontManager.instance.dfFontBase;
			if ((Object)(object)dfFontBase != (Object)null)
			{
				dfDynamicFont val = (dfDynamicFont)(object)((dfFontBase is dfDynamicFont) ? dfFontBase : null);
				if (val != null)
				{
					__result = val.baseFont;
					field.SetValue(FontManager.instance.itemTipsModuleObject, __result);
					FontManager.instance.itemTipsModuleFont = __result;
					return false;
				}
			}
			if ((Object)(object)dfFontBase != (Object)null)
			{
				dfFont val2 = (dfFont)(object)((dfFontBase is dfFont) ? dfFontBase : null);
				if (val2 != null)
				{
					__result = FontConverter.GetFontFromdfFont(val2, 2);
					field.SetValue(FontManager.instance.itemTipsModuleObject, __result);
					FontManager.instance.itemTipsModuleFont = __result;
					return false;
				}
			}
			dfFont gameFont = FontManager.GetGameFont();
			if ((Object)(object)gameFont != (Object)null)
			{
				__result = FontConverter.GetFontFromdfFont(gameFont, 2);
				field.SetValue(FontManager.instance.itemTipsModuleObject, __result);
				FontManager.instance.itemTipsModuleFont = __result;
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	public class Tk2dTextMeshTextPatchClass
	{
		[HarmonyPostfix]
		public static void Tk2dTextMeshTextPostfix(tk2dTextMesh __instance)
		{
			tk2dFontData tk2dFont = FontManager.instance.tk2dFont;
			if ((Object)(object)tk2dFont != (Object)null && (Object)(object)__instance.font != (Object)(object)tk2dFont)
			{
				FontManager.SetTextMeshFont(__instance, tk2dFont);
			}
			if (__instance.data != null && __instance.data.text != null)
			{
				TranslationManager.instance.AddTranslationRequest(__instance.data.text, __instance);
			}
		}
	}

	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	public class Tk2dTextMeshFontPatchClass
	{
		[HarmonyPrefix]
		public static bool Tk2dTextMeshFontPrefix(tk2dTextMesh __instance)
		{
			tk2dFontData tk2dFont = FontManager.instance.tk2dFont;
			if ((Object)(object)tk2dFont != (Object)null && (Object)(object)__instance.font != (Object)(object)tk2dFont)
			{
				FontManager.SetTextMeshFont(__instance, tk2dFont);
			}
			return false;
		}
	}

	[HarmonyPatch(typeof(TextBoxManager), "SetText")]
	public class SetTextPatchClass
	{
		[HarmonyPrefix]
		public static void SetTextPrefix(ref bool instant)
		{
			instant = true;
		}
	}

	public class DynamicFontRendererTokenizePatchClass
	{
		public static bool TokenizePrefix(DynamicFontRenderer __instance, string text)
		{
			try
			{
				if (__instance.tokens != null)
				{
					if ((object)__instance.tokens[0].Source == text)
					{
						return false;
					}
					__instance.tokens.ReleaseItems();
					__instance.tokens.Release();
				}
				__instance.tokens = FontManager.instance?.Tokenize(text);
				for (int i = 0; i < __instance.tokens.Count; i++)
				{
					__instance.calculateTokenRenderSize(__instance.tokens[i]);
				}
			}
			finally
			{
			}
			return false;
		}
	}

	public class DynamicFontRendererCalculateLinebreaksPatchClass
	{
		[HarmonyILManipulator]
		public static void CalculateLinebreaksPatch(ILContext ctx)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			ILCursor crs = new ILCursor(ctx);
			if (TheNthTime(() => crs.TryGotoNext((MoveType)0, new Func<Instruction, bool>[1]
			{
				(Instruction x) => ILPatternMatchingExt.MatchLdcI4(x, 0)
			}), 8))
			{
				crs.Emit(OpCodes.Ldloca_S, (byte)3);
				crs.EmitCall<DynamicFontRendererCalculateLinebreaksPatchClass>("CalculateLinebreaksPatchCall_1");
				ILCursor obj = crs;
				int index = obj.Index;
				obj.Index = index + 1;
			}
			if (crs.TryGotoNext((MoveType)0, new Func<Instruction, bool>[1]
			{
				(Instruction x) => ILPatternMatchingExt.MatchLdcI4(x, 0)
			}))
			{
				crs.Emit(OpCodes.Ldloca_S, (byte)3);
				crs.EmitCall<DynamicFontRendererCalculateLinebreaksPatchClass>("CalculateLinebreaksPatchCall_1");
			}
			if (crs.TryGotoNext((MoveType)0, new Func<Instruction, bool>[1]
			{
				(Instruction x) => ILPatternMatchingExt.MatchLdcI4(x, 2)
			}))
			{
				crs.EmitCall<DynamicFontRendererCalculateLinebreaksPatchClass>("CalculateLinebreaksPatchCall_2");
			}
		}

		private static void CalculateLinebreaksPatchCall_1(ref int orig)
		{
			orig--;
		}

		private static int CalculateLinebreaksPatchCall_2(int orig)
		{
			return 2;
		}
	}

	public class BitmappedFontRendererTokenizePatchClass
	{
		public static bool TokenizePrefix(BitmappedFontRenderer __instance, string text, ref dfList<dfMarkupToken> __result)
		{
			try
			{
				if (__instance.tokens != null)
				{
					if ((object)__instance.tokens[0].Source == text)
					{
						__result = __instance.tokens;
						return false;
					}
					__instance.tokens.ReleaseItems();
					__instance.tokens.Release();
				}
				__instance.tokens = FontManager.instance?.Tokenize(text);
				for (int i = 0; i < __instance.tokens.Count; i++)
				{
					__instance.calculateTokenRenderSize(__instance.tokens[i]);
				}
				__result = __instance.tokens;
			}
			finally
			{
			}
			return false;
		}
	}

	public class BitmappedFontRendererCalculateLinebreaksPatchClass
	{
		public static void CalculateLinebreaksPatch(ILContext ctx)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			ILCursor val = new ILCursor(ctx);
			if (val.TryGotoNext((MoveType)0, new Func<Instruction, bool>[1]
			{
				(Instruction x) => ILPatternMatchingExt.MatchLdcI4(x, 7)
			}))
			{
				val.EmitCall<BitmappedFontRendererCalculateLinebreaksPatchClass>("CalculateLinebreaksPatchCall_1");
			}
			if (val.TryGotoNext((MoveType)0, new Func<Instruction, bool>[1]
			{
				(Instruction x) => ILPatternMatchingExt.MatchLdcI4(x, 2)
			}))
			{
				val.EmitCall<BitmappedFontRendererCalculateLinebreaksPatchClass>("CalculateLinebreaksPatchCall_2");
			}
		}

		private static int CalculateLinebreaksPatchCall_1(int orig)
		{
			return 7;
		}

		private static int CalculateLinebreaksPatchCall_2(int orig)
		{
			return 2;
		}
	}

	[HarmonyPatch(typeof(tk2dTextMesh), "CheckFontsForLanguage")]
	public class Tk2dTextMeshCheckFontsForLanguagePatchClass
	{
		[HarmonyPrefix]
		public static bool CheckFontsForLanguagePrefix()
		{
			if ((Object)(object)FontManager.instance.tk2dFont != (Object)null)
			{
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(dfLabel), "CheckFontsForLanguage")]
	public class DfLabelCheckFontsForLanguagePatchClass
	{
		[HarmonyPrefix]
		public static bool CheckFontsForLanguagePrefix()
		{
			if ((Object)(object)FontManager.instance.tk2dFont != (Object)null)
			{
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(dfButton), "CheckFontsForLanguage")]
	public class DfButtonCheckFontsForLanguagePatchClass
	{
		[HarmonyPrefix]
		public static bool CheckFontsForLanguagePrefix()
		{
			if ((Object)(object)FontManager.instance.tk2dFont != (Object)null)
			{
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(DefaultLabelController), "Trigger", new Type[]
	{
		typeof(Transform),
		typeof(Vector3)
	})]
	public class DefaultLabelControllerTriggerPatchClass
	{
		[HarmonyPrefix]
		public static void TriggerPrefix(DefaultLabelController __instance)
		{
			__instance.label.AutoSize = true;
		}
	}

	[HarmonyPatch(typeof(SimpleStatLabel), "Start")]
	public class SimpleStatLabelStartPatchClass
	{
		[HarmonyPostfix]
		public static void StartPostfix(SimpleStatLabel __instance)
		{
			__instance.m_label.autoSize = true;
		}
	}

	[HarmonyPatch(typeof(GameUIRoot), "UpdatePlayerConsumables")]
	public class UpdatePlayerConsumablesPatchClass
	{
		[HarmonyPrefix]
		public static void UpdatePlayerConsumablesPrefix(GameUIRoot __instance)
		{
			__instance.p_playerKeyLabel.autoSize = true;
			__instance.p_playerCoinLabel.autoSize = true;
		}
	}

	[HarmonyPatch(typeof(DynamicFontRenderer), "renderText")]
	public class RenderTextPatchClass
	{
		[HarmonyILManipulator]
		public static void RenderTextPatch(ILContext ctx)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(ctx);
			if (val.TryGotoNext((MoveType)2, new Func<Instruction, bool>[1]
			{
				(Instruction x) => ILPatternMatchingExt.MatchCall<CharacterInfo>(x, "get_maxX")
			}))
			{
				val.Emit(OpCodes.Ldloca_S, (byte)3);
				val.EmitCall<RenderTextPatchClass>("RenderTextPatchCall");
			}
		}

		private static int RenderTextPatchCall(int orig, ref CharacterInfo characterInfo)
		{
			return ((CharacterInfo)(ref characterInfo)).advance;
		}
	}

	[HarmonyPatch(typeof(DynamicFontRenderer), "calculateTokenRenderSize")]
	public class CalculateTokenRenderSizePatchClass
	{
		[HarmonyILManipulator]
		public static void CalculateTokenRenderSizePatch(ILContext ctx)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(ctx);
			if (val.TryGotoNext((MoveType)2, new Func<Instruction, bool>[1]
			{
				(Instruction x) => ILPatternMatchingExt.MatchCall<CharacterInfo>(x, "get_maxX")
			}))
			{
				val.Emit(OpCodes.Ldloca_S, (byte)3);
				val.EmitCall<CalculateTokenRenderSizePatchClass>("CalculateTokenRenderSizePatchCall");
			}
		}

		private static int CalculateTokenRenderSizePatchCall(int orig, ref CharacterInfo characterInfo)
		{
			return ((CharacterInfo)(ref characterInfo)).advance;
		}
	}

	[HarmonyPatch]
	public class GetCharacterWidthsPatchClass
	{
		public static MethodBase TargetMethod()
		{
			return AccessTools.Method(typeof(DynamicFontRenderer), "GetCharacterWidths", new Type[4]
			{
				typeof(string),
				typeof(int),
				typeof(int),
				typeof(float).MakeByRefType()
			}, (Type[])null);
		}

		[HarmonyILManipulator]
		public static void GetCharacterWidthsPatch(ILContext ctx)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(ctx);
			if (val.TryGotoNext((MoveType)2, new Func<Instruction, bool>[1]
			{
				(Instruction x) => ILPatternMatchingExt.MatchCall<CharacterInfo>(x, "get_maxX")
			}))
			{
				val.Emit(OpCodes.Ldloca_S, (byte)5);
				val.EmitCall<GetCharacterWidthsPatchClass>("GetCharacterWidthsPatchCall");
			}
		}

		private static int GetCharacterWidthsPatchCall(int orig, ref CharacterInfo characterInfo)
		{
			return ((CharacterInfo)(ref characterInfo)).advance;
		}
	}

	public class ConvertStringToFixedWidthLinesPatchClass
	{
		public static bool ConvertStringToFixedWidthLinesPrefix(string text, ref List<string> __result)
		{
			__result = new List<string> { text };
			return false;
		}
	}

	public class GenerateTextInfoPatchClass
	{
		public static void GenerateTextInfoPatch(ILContext ctx)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(ctx);
			if (val.TryGotoNext((MoveType)2, new Func<Instruction, bool>[1]
			{
				(Instruction x) => ILPatternMatchingExt.MatchCall<string>(x, "Join")
			}))
			{
				val.Emit(OpCodes.Ldloca_S, (byte)4);
				val.EmitCall<GenerateTextInfoPatchClass>("GenerateTextInfoPatchCall");
			}
		}

		private static string GenerateTextInfoPatchCall(string text, ref Vector2 size)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			FontManager.instance.itemTipsModuleText = text;
			Vector2 resultSize;
			string result = FontManager.instance.WrapText(text, out resultSize);
			size = resultSize;
			return result;
		}
	}

	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	public class Expand_CRPatchClass
	{
		[HarmonyILManipulator]
		public static void Expand_CRPatch(ILContext ctx)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(ctx);
			if (val.TryGotoNext((MoveType)2, new Func<Instruction, bool>[1]
			{
				(Instruction x) => ILPatternMatchingExt.MatchLdfld(x, "DefaultLabelController+<Expand_CR>c__Iterator0", "<targetWidth>__0")
			}))
			{
				val.Emit(OpCodes.Ldarg_0);
				val.EmitCall<Expand_CRPatchClass>("Expand_CRPatchCall");
			}
		}

		private static float Expand_CRPatchCall(float orig, object selfObject)
		{
			DefaultLabelController fieldValueInEnumerator = GetFieldValueInEnumerator<DefaultLabelController>(selfObject, "this");
			return ((dfControl)fieldValueInEnumerator.label).Width + 1f;
		}
	}

	[HarmonyPatch(typeof(DefaultLabelController), "UpdateForLanguage")]
	public class DefaultLabelControllerUpdateForLanguagePatchClass
	{
		[HarmonyPrefix]
		public static bool UpdateForLanguagePrefix()
		{
			return false;
		}
	}

	public class NewShopItemControllerPatchClass
	{
		public static void NewShopItemControllerPrefix(DefaultLabelController labelController)
		{
			labelController.label.AutoSize = false;
		}
	}

	private static AutoTranslateConfig config = AutoTranslateModule.instance.config;

	private static readonly Regex spritePattern = new Regex("(\\[sprite\\s+\"[^\"]*\")(?!\\])", RegexOptions.Compiled);

	public static void EmitCall<T>(this ILCursor iLCursor, string methodName, Type[] parameters = null, Type[] generics = null)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		MethodInfo methodInfo = AccessTools.Method(typeof(T), methodName, parameters, generics);
		iLCursor.Emit(OpCodes.Call, (MethodBase)methodInfo);
	}

	public static bool TheNthTime(this Func<bool> predict, int n = 1)
	{
		for (int i = 0; i < n; i++)
		{
			if (!predict())
			{
				return false;
			}
		}
		return true;
	}

	public static T GetFieldValueInEnumerator<T>(object instance, string fieldNamePattern)
	{
		return (T)instance.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((FieldInfo f) => f.Name.Contains("$" + fieldNamePattern) || f.Name.Contains("<" + fieldNamePattern + ">") || f.Name == fieldNamePattern)
			.GetValue(instance);
	}

	private static string AddMissingBracket(string input)
	{
		return spritePattern.Replace(input, (Match match) => match.Groups[1].Value + "]");
	}

	private static void DfLabelTextAddCall(dfLabel instance)
	{
		dfFontBase dfFontBase = FontManager.instance.dfFontBase;
		if ((Object)(object)dfFontBase != (Object)null && (Object)(object)instance.Font != (Object)(object)dfFontBase)
		{
			instance.Font = dfFontBase;
			dfFont val = (dfFont)(object)((dfFontBase is dfFont) ? dfFontBase : null);
			if (val != null)
			{
				instance.Atlas = val.Atlas;
			}
			if (config.DfTextScaleExpandThreshold >= 0f && instance.TextScale < config.DfTextScaleExpandThreshold)
			{
				instance.TextScale = config.DfTextScaleExpandToValue;
			}
		}
		TranslationManager.instance.AddTranslationRequest(instance.text, instance);
	}

	private static void DfButtonTextAddCall(dfButton instance)
	{
		dfFontBase dfFontBase = FontManager.instance.dfFontBase;
		if ((Object)(object)dfFontBase != (Object)null && (Object)(object)instance.Font != (Object)(object)dfFontBase)
		{
			instance.Font = dfFontBase;
			dfFont val = (dfFont)(object)((dfFontBase is dfFont) ? dfFontBase : null);
			if (val != null)
			{
				((dfInteractiveBase)instance).Atlas = val.Atlas;
			}
			if (config.DfTextScaleExpandThreshold >= 0f && instance.TextScale < config.DfTextScaleExpandThreshold)
			{
				instance.TextScale = config.DfTextScaleExpandToValue;
			}
		}
		string text = AddMissingBracket(instance.text);
		if (text != instance.text)
		{
			instance.text = text;
			((dfControl)instance).Invalidate();
		}
		TranslationManager.instance.AddTranslationRequest(instance.text, instance);
	}
}
public class AzureTranslationService : ITranslationService
{
	private AutoTranslateConfig config;

	private string endpoint = "https://api.cognitive.microsofttranslator.com";

	private string action = "/translate";

	private string version = "3.0";

	public AzureTranslationService(AutoTranslateConfig config)
	{
		this.config = config;
	}

	private string[] ParseResponse(string responseJson)
	{
		//IL_000d: Expected O, but got Unknown
		JArray val;
		try
		{
			val = JArray.Parse(responseJson);
		}
		catch (JsonReaderException val2)
		{
			JsonReaderException innerException = val2;
			throw new InvalidOperationException("响应的JSON格式无效 The JSON format of the response is invalid: ", (Exception?)(object)innerException);
		}
		List<string> list = new List<string>();
		foreach (JToken item in val)
		{
			JToken obj = item[(object)"translations"];
			JArray val3 = (JArray)(object)((obj is JArray) ? obj : null);
			if (val3 == null)
			{
				continue;
			}
			foreach (JToken item2 in val3)
			{
				list.Add(((object)item2[(object)"text"]).ToString());
			}
		}
		if (list.Count == 0)
		{
			throw new InvalidOperationException("翻译结果为空!The translation result is empty!");
		}
		return list.ToArray();
	}

	public static string[] PreprocessText(List<string> inputTexts)
	{
		return inputTexts.Select((string text) => text.Replace("\r", "")).ToArray();
	}

	public IEnumerator StartTranslation(List<string> texts, Action<string[]> callback)
	{
		string[] preprocessedTexts = PreprocessText(texts);
		var payload = preprocessedTexts.Select((string text) => new
		{
			Text = text
		}).ToArray();
		string payloadJson = JsonConvert.SerializeObject((object)payload);
		string subscriptionKey = config.AzureSubscriptionKey;
		string region = config.AzureRegion;
		string requestUrl = endpoint + action + "?api-version=" + version + "&to=" + config.AzureTargetLanguage;
		if (config.AzureSourceLanguage != string.Empty)
		{
			requestUrl = requestUrl + "&from=" + config.AzureSourceLanguage;
		}
		int retryCount = 0;
		bool needRetry = false;
		while (true)
		{
			if (needRetry)
			{
				if (retryCount >= config.MaxRetryCount)
				{
					break;
				}
				retryCount++;
				Debug.Log((object)$"正在重试。。。尝试第 {retryCount} 次。Retrying... Attempt time {retryCount}.");
				needRetry = false;
				yield return (object)new WaitForSecondsRealtime(2f);
			}
			UnityWebRequest request = new UnityWebRequest(requestUrl, "POST");
			try
			{
				byte[] bodyRaw = Encoding.UTF8.GetBytes(payloadJson);
				request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
				request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
				request.SetRequestHeader("Content-Type", "application/json");
				request.SetRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
				request.SetRequestHeader("Ocp-Apim-Subscription-Region", region);
				yield return request.SendWebRequest();
				if (request.isNetworkError || request.isHttpError)
				{
					Debug.LogError((object)("请求失败 Request failed: " + request.error));
					needRetry = true;
					continue;
				}
				string responseJson = request.downloadHandler.text;
				string[] translatedTexts;
				try
				{
					translatedTexts = ParseResponse(responseJson);
				}
				catch (Exception ex2)
				{
					Exception ex = ex2;
					Debug.LogError((object)("解析翻译结果失败 Failed to parse translation result:" + ex.Message));
					Debug.LogError((object)("响应JSON Response JSON:\n" + responseJson));
					needRetry = true;
					goto end_IL_0272;
				}
				if (translatedTexts != null)
				{
					callback?.Invoke(translatedTexts);
					yield break;
				}
				Debug.LogError((object)"翻译失败,未获得翻译结果!Translation failed, no translation result obtained!");
				needRetry = true;
				yield break;
				end_IL_0272:;
			}
			finally
			{
				((IDisposable)request)?.Dispose();
			}
		}
		Debug.LogError((object)$"多次尝试失败。已重试 {config.MaxRetryCount} 次。翻译中止!Multiple attempts failed. Retried {config.MaxRetryCount} times. translation aborted!");
		callback?.Invoke(null);
	}
}
public class BaiduTranslationService : ITranslationService
{
	private AutoTranslateConfig config;

	private string apiUrl = "https://fanyi-api.baidu.com/api/trans/vip/translate";

	public BaiduTranslationService(AutoTranslateConfig config)
	{
		this.config = config;
	}

	private string[] ParseResponse(string responseJson)
	{
		//IL_000d: Expected O, but got Unknown
		JObject val;
		try
		{
			val = JObject.Parse(responseJson);
		}
		catch (JsonReaderException val2)
		{
			JsonReaderException innerException = val2;
			throw new InvalidOperationException("响应的JSON格式无效 The JSON format of the response is invalid: ", (Exception?)(object)innerException);
		}
		if (val.ContainsKey("error_code"))
		{
			string text = ((object)val["error_code"])?.ToString();
			string text2 = ((object)val["error_msg"])?.ToString();
			throw new InvalidOperationException("API请求失败 API request failed: " + text + " - " + text2);
		}
		if (!val.ContainsKey("trans_result"))
		{
			throw new InvalidOperationException("响应JSON中缺少trans_desult字段!The 'trans_desult' field is missing in the response JSON!");
		}
		JToken val3 = val["trans_result"];
		if (val3 == null || !((IEnumerable<JToken>)val3).Any())
		{
			throw new InvalidOperationException("翻译结果为空!The translation result is empty!");
		}
		return ((IEnumerable<JToken>)val3).Select((JToken result) => ((object)result[(object)"dst"])?.ToString() ?? string.Empty).ToArray();
	}

	public static string[] PreprocessText(List<string> inputTexts)
	{
		return inputTexts.Select((string text) => text.Replace("\n", "\\n").Replace("\r", "")).ToArray();
	}

	public IEnumerator StartTranslation(List<string> texts, Action<string[]> callback)
	{
		string salt = Guid.NewGuid().ToString();
		string[] preprocessedTexts = PreprocessText(texts);
		string sign = GenerateSign(config.BaiduAppId, string.Join("\n", preprocessedTexts), salt, config.BaiduSecretKey);
		string url = apiUrl + "?q=" + Uri.EscapeDataString(string.Join("\n", preprocessedTexts)) + "&from=" + config.BaiduSourceLanguage + "&to=" + config.BaiduTargetLanguage + "&appid=" + config.BaiduAppId + "&salt=" + salt + "&sign=" + sign;
		bool needRetry = false;
		int retryCount = 0;
		while (true)
		{
			if (needRetry)
			{
				if (retryCount >= config.MaxRetryCount)
				{
					break;
				}
				retryCount++;
				Debug.Log((object)$"正在重试。。。尝试第 {retryCount} 次。Retrying... Attempt time {retryCount}.");
				needRetry = false;
				yield return (object)new WaitForSecondsRealtime(2f);
			}
			UnityWebRequest request = UnityWebRequest.Get(url);
			try
			{
				yield return request.SendWebRequest();
				if (request.isNetworkError || request.isHttpError)
				{
					Debug.LogError((object)("请求失败 Request failed: " + request.error));
					needRetry = true;
					continue;
				}
				string responseJson = request.downloadHandler.text;
				string[] translatedTexts;
				try
				{
					translatedTexts = ParseResponse(responseJson);
				}
				catch (Exception ex2)
				{
					Exception ex = ex2;
					Debug.LogError((object)("解析翻译结果失败 Failed to parse translation result:" + ex.Message));
					Debug.LogError((object)("响应JSON Response JSON:\n" + responseJson));
					needRetry = true;
					goto end_IL_0270;
				}
				if (translatedTexts != null)
				{
					callback?.Invoke(translatedTexts);
					yield break;
				}
				Debug.LogError((object)"翻译失败,未获得翻译结果!Translation failed, no translation result obtained!");
				needRetry = true;
				yield break;
				end_IL_0270:;
			}
			finally
			{
				((IDisposable)request)?.Dispose();
			}
		}
		Debug.LogError((object)$"多次尝试失败。已重试 {config.MaxRetryCount} 次。翻译中止!Multiple attempts failed. Retried {config.MaxRetryCount} times. translation aborted!");
		callback?.Invoke(null);
	}

	private string GenerateSign(string appId, string query, string salt, string secretKey)
	{
		string s = appId + query + salt + secretKey;
		using MD5 mD = MD5.Create();
		byte[] array = mD.ComputeHash(Encoding.UTF8.GetBytes(s));
		StringBuilder stringBuilder = new StringBuilder();
		byte[] array2 = array;
		foreach (byte b in array2)
		{
			stringBuilder.Append(b.ToString("x2"));
		}
		return stringBuilder.ToString();
	}
}
public interface ITranslationService
{
	IEnumerator StartTranslation(List<string> texts, Action<string[]> callback);
}
public class LargeModelTranslationService : ITranslationService
{
	private AutoTranslateConfig config;

	public LargeModelTranslationService(AutoTranslateConfig config)
	{
		this.config = config;
	}

	private string[] ParseResponse(string responseJson)
	{
		//IL_000d: Expected O, but got Unknown
		//IL_00e9: Expected O, but got Unknown
		JObject val;
		try
		{
			val = JObject.Parse(responseJson);
		}
		catch (JsonReaderException val2)
		{
			JsonReaderException innerException = val2;
			throw new InvalidOperationException("响应的JSON格式无效 The JSON format of the response is invalid: ", (Exception?)(object)innerException);
		}
		List<string> list = new List<string>();
		JToken obj = val["choices"];
		JArray val3 = (JArray)(object)((obj is JArray) ? obj : null);
		if (val3 != null)
		{
			foreach (JToken item in val3)
			{
				JToken obj2 = item[(object)"message"];
				string text = ((obj2 == null) ? null : ((object)obj2[(object)"content"])?.ToString());
				if (string.IsNullOrEmpty(text))
				{
					continue;
				}
				try
				{
					JArray val4 = JArray.Parse(text);
					foreach (JToken item2 in val4)
					{
						list.Add(((object)item2[(object)"text"]).ToString());
					}
				}
				catch (JsonReaderException val5)
				{
					JsonReaderException val6 = val5;
					Debug.LogError((object)("解析 'content' 字段时失败: " + ((Exception)(object)val6).Message));
				}
			}
		}
		if (list.Count == 0)
		{
			throw new InvalidOperationException("翻译结果为空!The translation result is empty!");
		}
		return list.ToArray();
	}

	public static List<object> PreprocessText(List<string> inputTexts)
	{
		List<object> list = new List<object>();
		for (int i = 0; i < inputTexts.Count; i++)
		{
			string text = inputTexts[i].Replace("\r", "");
			list.Add(new
			{
				id = i + 1,
				text = text
			});
		}
		return list;
	}

	public IEnumerator StartTranslation(List<string> texts, Action<string[]> callback)
	{
		var payload = new
		{
			model = config.LargeModelName,
			messages = new[]
			{
				new
				{
					role = "system",
					content = config.LargeModelPrompt
				},
				new
				{
					role = "user",
					content = JsonConvert.SerializeObject((object)PreprocessText(texts))
				}
			},
			temperature = config.LargeModelTemperature,
			max_tokens = config.LargeModelMaxTokens,
			top_p = config.LargeModelTopP,
			frequency_penalty = config.LargeModelFrequencyPenalty,
			n = 1
		};
		string payloadJson = JsonConvert.SerializeObject((object)payload);
		string requestUrl = config.LargeModelBaseUrl ?? "";
		int retryCount = 0;
		bool needRetry = false;
		while (true)
		{
			if (needRetry)
			{
				if (retryCount >= config.MaxRetryCount)
				{
					break;
				}
				retryCount++;
				Debug.Log((object)$"正在重试。。。尝试第 {retryCount} 次。Retrying... Attempt time {retryCount}.");
				needRetry = false;
				yield return (object)new WaitForSecondsRealtime(2f);
			}
			UnityWebRequest request = new UnityWebRequest(requestUrl, "POST");
			try
			{
				byte[] bodyRaw = Encoding.UTF8.GetBytes(payloadJson);
				request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
				request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
				request.SetRequestHeader("Content-Type", "application/json");
				request.SetRequestHeader("Authorization", "Bearer " + config.LargeModelApiKey);
				yield return request.SendWebRequest();
				if (request.isNetworkError || request.isHttpError)
				{
					Debug.LogError((object)("请求失败 Request failed: " + request.error));
					needRetry = true;
					continue;
				}
				string responseJson = request.downloadHandler.text;
				string[] translatedTexts;
				try
				{
					translatedTexts = ParseResponse(responseJson);
				}
				catch (Exception ex2)
				{
					Exception ex = ex2;
					Debug.LogError((object)("解析翻译结果失败 Failed to parse translation result: " + ex.Message));
					Debug.LogError((object)("响应JSON Response JSON:\n" + responseJson));
					needRetry = true;
					goto end_IL_0217;
				}
				if (translatedTexts != null && translatedTexts.Length != 0)
				{
					callback?.Invoke(translatedTexts);
					yield break;
				}
				Debug.LogError((object)"翻译失败,未获得翻译结果!Translation failed, no translation result obtained!");
				needRetry = true;
				yield break;
				end_IL_0217:;
			}
			finally
			{
				((IDisposable)request)?.Dispose();
			}
		}
		Debug.LogError((object)$"多次尝试失败。已重试 {config.MaxRetryCount} 次。翻译中止!Multiple attempts failed. Retried {config.MaxRetryCount} times. Translation aborted!");
		callback?.Invoke(null);
	}
}
public class LRUCache<TKey, TValue>
{
	private class CacheItem
	{
		public TKey Key;

		public TValue Value;

		public void Reset(TKey key, TValue value)
		{
			Key = key;
			Value = value;
		}
	}

	private readonly int _capacity;

	private readonly Dictionary<TKey, LinkedListNode<CacheItem>> _cache;

	private readonly LinkedList<CacheItem> _order;

	private readonly ObjectPool<LinkedListNode<CacheItem>> _nodePool;

	private readonly ObjectPool<CacheItem> _cacheItemPool;

	public LRUCache(int capacity)
	{
		if (capacity <= 0)
		{
			throw new ArgumentException("容量必须大于0。Capacity must be greater than zero.");
		}
		_capacity = capacity;
		_cache = new Dictionary<TKey, LinkedListNode<CacheItem>>(capacity);
		_order = new LinkedList<CacheItem>();
		_nodePool = new ObjectPool<LinkedListNode<CacheItem>>(() => new LinkedListNode<CacheItem>(null), capacity, delegate(LinkedListNode<CacheItem> node)
		{
			node.Value = null;
		});
		_cacheItemPool = new ObjectPool<CacheItem>(() => new CacheItem(), capacity, delegate(CacheItem item)
		{
			item.Reset(default(TKey), default(TValue));
		});
	}

	public TValue Get(TKey key)
	{
		if (_cache.TryGetValue(key, out var value))
		{
			_order.Remove(value);
			_order.AddFirst(value);
			return value.Value.Value;
		}
		return default(TValue);
	}

	public bool TryGetValue(TKey key, out TValue value)
	{
		if (_cache.TryGetValue(key, out var value2))
		{
			_order.Remove(value2);
			_order.AddFirst(value2);
			value = value2.Value.Value;
			return true;
		}
		value = default(TValue);
		return false;
	}

	public void Set(TKey key, TValue value)
	{
		if (_cache.TryGetValue(key, out var value2))
		{
			_order.Remove(value2);
			value2.Value.Reset(key, value);
			_order.AddFirst(value2);
			return;
		}
		if (_cache.Count >= _capacity)
		{
			LinkedListNode<CacheItem> last = _order.Last;
			_cache.Remove(last.Value.Key);
			_order.RemoveLast();
			_cacheItemPool.Return(last.Value);
			_nodePool.Return(last);
		}
		CacheItem cacheItem = _cacheItemPool.Get();
		cacheItem.Reset(key, value);
		value2 = _nodePool.Get();
		value2.Value = cacheItem;
		_order.AddFirst(value2);
		_cache[key] = value2;
	}

	public bool ContainsKey(TKey key)
	{
		return _cache.ContainsKey(key);
	}
}
public class ObjectPool<T> where T : class
{
	private readonly Queue<T> _pool;

	private readonly int _maxSize;

	private readonly Func<T> _factory;

	private readonly Action<T> _resetAction;

	public ObjectPool(Func<T> factory, int maxSize = 16, Action<T> resetAction = null)
	{
		_factory = factory ?? throw new ArgumentNullException("factory");
		_maxSize = maxSize;
		_pool = new Queue<T>(maxSize);
		_resetAction = resetAction;
	}

	public T Get()
	{
		if (_pool.Count > 0)
		{
			return _pool.Dequeue();
		}
		return _factory();
	}

	public void Return(T obj)
	{
		if (_resetAction != null)
		{
			_resetAction(obj);
		}
		if (_pool.Count < _maxSize)
		{
			_pool.Enqueue(obj);
		}
	}
}
public class StatusLabelController
{
	internal class StatusLabelModifier : SModifier
	{
		private AutoTranslateConfig config;

		private StatusLabelController statusLabel;

		public StatusLabelModifier(AutoTranslateConfig autoTranslateConfig, StatusLabelController statusLabelController)
		{
			config = autoTranslateConfig;
			statusLabel = statusLabelController;
		}

		public override void Update()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			if (Input.GetKeyDown(config.ToggleRequestedCharacterCountKeyBinding))
			{
				statusLabel.ToggleVisibility();
			}
		}
	}

	internal SLabel label;

	private Font font;

	private readonly Color backgroundColor = new Color(0f, 0f, 0f, 0.5f);

	private readonly Color defaultColor = Color.white;

	private readonly Color highlightColor = Color.red;

	private StatusLabelModifier modifier;

	private bool highlight = false;

	private AutoTranslateConfig config;

	private static readonly Regex vector2Regex = new Regex("^\\s*(-?\\d+(\\.\\d+)?)\\s*[, ]\\s*(-?\\d+(\\.\\d+)?)\\s*$");

	private readonly Vector2 defaultAnchor = new Vector2(0.5f, 0f);

	private readonly Vector2 defaultPivot = new Vector2(0.5f, 0f);

	private Vector2 anchor;

	private Vector2 pivot;

	public static StatusLabelController instance;

	internal void InitializeStatusLabel()
	{
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Expected O, but got Unknown
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		instance = this;
		config = AutoTranslateModule.instance.config;
		try
		{
			anchor = ParseVector2(config.CountLabelAnchor);
			pivot = ParseVector2(config.CountLabelPivot);
		}
		catch
		{
			anchor = defaultAnchor;
			pivot = defaultPivot;
		}
		label = new SLabel();
		((SElement)label).Background = backgroundColor;
		((SElement)label).Foreground = defaultColor;
		modifier = new StatusLabelModifier(config, this);
		((SElement)label).With.Add((SModifier)(object)modifier);
		((SElement)label).OnUpdateStyle = delegate(SElement element)
		{
			element.Font = LoadFont();
			Reposition();
		};
		((SElement)label).Visible = config.ShowRequestedCharacterCount;
		SGUIRoot.Main.Children.Add((SElement)(object)label);
	}

	private Font LoadFont()
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Expected O, but got Unknown
		if ((Object)(object)font == (Object)null)
		{
			dfFont val = (dfFont)GameUIRoot.Instance.Manager.DefaultFont;
			font = FontConverter.GetFontFromdfFont(val, 2);
		}
		return font;
	}

	internal void SetText(string text)
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		label.Text = text;
		((SElement)label).Size = ((SElement)label).Backend.MeasureText(text, (Vector2?)null, (object)font);
		Reposition();
	}

	private void Reposition()
	{
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		if (((SElement)label).Root != null)
		{
			((SElement)label).Position.x = ((SElement)label).Root.Size.x * anchor.x - ((SElement)label).Size.x * pivot.x;
			((SElement)label).Position.y = ((SElement)label).Root.Size.y * anchor.y - ((SElement)label).Size.y * pivot.y;
		}
	}

	internal void SetHighlight()
	{
		if (!highlight)
		{
			highlight = true;
			ForceSetVisibility(value: true);
			((MonoBehaviour)TranslationManager.instance).StartCoroutine(AlternateColor());
		}
	}

	private IEnumerator AlternateColor()
	{
		while (true)
		{
			((SElement)label).Foreground = highlightColor;
			yield return (object)new WaitForSecondsRealtime(0.5f);
			((SElement)label).Foreground = defaultColor;
			yield return (object)new WaitForSecondsRealtime(0.5f);
		}
	}

	internal void ForceSetVisibility(bool value)
	{
		((SElement)label).Visible = value;
		Debug.Log((object)("请求字符计数强制设置为" + (value ? "ON" : "OFF") + "。RequestedCharacterCount forcefully set to " + (value ? "ON" : "OFF") + "."));
	}

	internal void ToggleVisibility()
	{
		((SElement)label).Visible = !((SElement)label).Visible;
		Debug.Log((object)("请求字符计数切换为" + (((SElement)label).Visible ? "ON" : "OFF") + "。RequestedCharacterCount toggled set to " + (((SElement)label).Visible ? "ON" : "OFF") + "."));
	}

	private static bool IsNullOrWhiteSpace(string value)
	{
		return string.IsNullOrEmpty(value) || value.Trim().Length == 0;
	}

	public static Vector2 ParseVector2(string input)
	{
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		if (IsNullOrWhiteSpace(input))
		{
			throw new ArgumentException("输入不能为空。Input cannot be empty.");
		}
		Match match = vector2Regex.Match(input);
		if (!match.Success)
		{
			throw new FormatException("输入格式不正确,应该是两个数字用空格或逗号分隔。The input format is incorrect. It should be two numbers separated by a space or comma.");
		}
		float num = float.Parse(match.Groups[1].Value);
		float num2 = float.Parse(match.Groups[3].Value);
		return new Vector2(num, num2);
	}
}
public class TencentTranslationService : ITranslationService
{
	private AutoTranslateConfig config;

	private string endpoint = "tmt.tencentcloudapi.com";

	private string action = "TextTranslateBatch";

	private string version = "2018-03-21";

	public TencentTranslationService(AutoTranslateConfig config)
	{
		this.config = config;
	}

	private string[] ParseResponse(string responseJson)
	{
		//IL_000d: Expected O, but got Unknown
		JObject val;
		try
		{
			val = JObject.Parse(responseJson);
		}
		catch (JsonReaderException val2)
		{
			JsonReaderException innerException = val2;
			throw new InvalidOperationException("响应的JSON格式无效 The JSON format of the response is invalid: ", (Exception?)(object)innerException);
		}
		if (val["Response"] == null)
		{
			throw new InvalidOperationException("响应中缺少Response字段!The 'Response' field is missing from the response!");
		}
		JToken val3 = val["Response"][(object)"TargetTextList"];
		if (val3 == null)
		{
			throw new InvalidOperationException("响应中缺少TargetTextList字段!The 'TargetTextList' field is missing from the response!");
		}
		string[] array = val3.ToObject<string[]>();
		if (array == null || array.Length == 0)
		{
			throw new InvalidOperationException("翻译结果为空!The translation result is empty!");
		}
		return array;
	}

	public static string[] PreprocessText(List<string> inputTexts)
	{
		return inputTexts.Select((string text) => text.Replace("\r", "")).ToArray();
	}

	public IEnumerator StartTranslation(List<string> texts, Action<string[]> callback)
	{
		string[] preprocessedTexts = PreprocessText(texts);
		long timestamp = GetUnixTimeSeconds();
		string date = DateTime.UtcNow.ToString("yyyy-MM-dd");
		var payload = new
		{
			SourceTextList = preprocessedTexts,
			Source = config.TencentSourceLanguage,
			Target = config.TencentTargetLanguage,
			ProjectId = 0
		};
		string payloadJson = JsonConvert.SerializeObject((object)payload);
		string stringToSign = string.Format(arg2: ComputeSHA256("POST\n/\n\ncontent-type:application/json\nhost:" + endpoint + "\n\ncontent-type;host\n" + ComputeSHA256(payloadJson)), format: "TC3-HMAC-SHA256\n{0}\n{1}/tmt/tc3_request\n{2}", arg0: timestamp, arg1: date);
		byte[] signingKey = GetSignatureKey(config.TencentSecretKey, date, "tmt", "tc3_request");
		string signature = ConvertToHexString(ComputeHMACSHA256(stringToSign, signingKey));
		string authorization = "TC3-HMAC-SHA256 Credential=" + config.TencentSecretId + "/" + date + "/tmt/tc3_request, SignedHeaders=content-type;host, Signature=" + signature;
		int retryCount = 0;
		bool needRetry = false;
		while (true)
		{
			if (needRetry)
			{
				if (retryCount >= config.MaxRetryCount)
				{
					break;
				}
				retryCount++;
				Debug.Log((object)$"正在重试。。。尝试第 {retryCount} 次。Retrying... Attempt time {retryCount}.");
				needRetry = false;
				yield return (object)new WaitForSecondsRealtime(2f);
			}
			UnityWebRequest request = new UnityWebRequest("https://" + endpoint, "POST");
			try
			{
				byte[] bodyRaw = Encoding.UTF8.GetBytes(payloadJson);
				request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
				request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
				request.SetRequestHeader("Content-Type", "application/json");
				request.SetRequestHeader("Authorization", authorization);
				request.SetRequestHeader("X-TC-Action", action);
				request.SetRequestHeader("X-TC-Timestamp", timestamp.ToString());
				request.SetRequestHeader("X-TC-Version", version);
				request.SetRequestHeader("X-TC-Region", config.TencentRegion);
				yield return request.SendWebRequest();
				if (request.isNetworkError || request.isHttpError)
				{
					Debug.LogError((object)("请求失败 Request failed: " + request.error));
					needRetry = true;
					continue;
				}
				string responseJson = request.downloadHandler.text;
				string[] translatedTexts;
				try
				{
					translatedTexts = ParseResponse(responseJson);
				}
				catch (Exception ex2)
				{
					Exception ex = ex2;
					Debug.LogError((object)("解析翻译结果失败 Failed to parse translation result:" + ex.Message));
					Debug.LogError((object)("响应JSON Response JSON:\n" + responseJson));
					needRetry = true;
					goto end_IL_02e3;
				}
				if (translatedTexts != null)
				{
					callback?.Invoke(translatedTexts);
					yield break;
				}
				Debug.LogError((object)"翻译失败,未获得翻译结果!Translation failed, no translation result obtained!");
				needRetry = true;
				yield break;
				end_IL_02e3:;
			}
			finally
			{
				((IDisposable)request)?.Dispose();
			}
		}
		Debug.LogError((object)$"多次尝试失败。已重试 {config.MaxRetryCount} 次。翻译中止!Multiple attempts failed. Retried {config.MaxRetryCount} times. translation aborted!");
		callback?.Invoke(null);
	}

	private string ComputeSHA256(string rawData)
	{
		using SHA256 sHA = SHA256.Create();
		byte[] bytes = sHA.ComputeHash(Encoding.UTF8.GetBytes(rawData));
		return ConvertToHexString(bytes);
	}

	private byte[] ComputeHMACSHA256(string data, byte[] key)
	{
		using HMACSHA256 hMACSHA = new HMACSHA256(key);
		return hMACSHA.ComputeHash(Encoding.UTF8.GetBytes(data));
	}

	private byte[] GetSignatureKey(string secretKey, string date, string service, string request)
	{
		byte[] key = ComputeHMACSHA256(date, Encoding.UTF8.GetBytes("TC3" + secretKey));
		byte[] key2 = ComputeHMACSHA256(service, key);
		return ComputeHMACSHA256(request, key2);
	}

	private string ConvertToHexString(byte[] bytes)
	{
		StringBuilder stringBuilder = new StringBuilder();
		foreach (byte b in bytes)
		{
			stringBuilder.Append(b.ToString("x2"));
		}
		return stringBuilder.ToString();
	}

	private long GetUnixTimeSeconds()
	{
		return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
	}
}
public class FontManager
{
	public string regexForDfTokenizer;

	public string regexForItemTipsModTokenizer;

	public AssetBundle assetBundle;

	public dfFontBase dfFontBase;

	public tk2dFontData tk2dFont;

	public AutoTranslateModule.OverrideFontType overrideFont;

	public static string defaultRegexForTokenizer = "(?<StartTag>\\[(?<StartTagName>(color|sprite))\\s*(?<AttributeValue>[^\\]\\s]+)?\\])|(?<EndTag>\\[\\/(?<EndTagName>color|sprite)\\])|(?<Newline>\\r?\\n)|(?<Whitespace>\\s+)|(?<Text>[a-zA-Z0-9]+|.)";

	public static string defaultRegexForItemTipsModTokenizer = "(?:<color=[^>]+?>|</color>|[a-zA-Z0-9]+|\\s+|.)";

	internal Regex DfTokenizerRegex;

	internal Regex ItemTipsModTokenizerRegex;

	internal static FontManager instance;

	private AutoTranslateConfig config;

	internal Type itemTipsModuleType;

	internal object itemTipsModuleObject;

	internal SLabel itemTipsModuleLabel;

	internal Font itemTipsModuleFont;

	internal string itemTipsModuleText;

	private static StringBuilder currentLine = new StringBuilder();

	private static List<string> wrappedLines = new List<string>();

	private static string[] newLineSymbols = new string[2] { "\r\n", "\n" };

	public FontManager()
	{
		instance = this;
		config = AutoTranslateModule.instance.config;
		regexForDfTokenizer = ((config.RegexForDfTokenizer == string.Empty) ? defaultRegexForTokenizer : config.RegexForDfTokenizer);
		regexForItemTipsModTokenizer = ((config.RegexForItemTipsModTokenizer == string.Empty) ? defaultRegexForTokenizer : config.RegexForItemTipsModTokenizer);
		DfTokenizerRegex = new Regex(regexForDfTokenizer, RegexOptions.Multiline | RegexOptions.Compiled);
		ItemTipsModTokenizerRegex = new Regex(regexForItemTipsModTokenizer, RegexOptions.Multiline | RegexOptions.Compiled);
		overrideFont = config.OverrideFont;
		if (overrideFont != AutoTranslateModule.OverrideFontType.Custom)
		{
			if (overrideFont != 0 && overrideFont != AutoTranslateModule.OverrideFontType.English && overrideFont != AutoTranslateModule.OverrideFontType.Polish)
			{
				if (overrideFont == AutoTranslateModule.OverrideFontType.Chinese)
				{
					ref dfFontBase reference = ref dfFontBase;
					Object obj = ResourceCache.Acquire("Alternate Fonts/SimSun12_DF");
					reference = (dfFontBase)(object)((GameObject)((obj is GameObject) ? obj : null)).GetComponent<dfFont>();
					ref tk2dFontData reference2 = ref tk2dFont;
					Object obj2 = ResourceCache.Acquire("Alternate Fonts/SimSun12_TK2D");
					reference2 = ((GameObject)((obj2 is GameObject) ? obj2 : null)).GetComponent<tk2dFont>().data;
				}
				else if (overrideFont == AutoTranslateModule.OverrideFontType.Japanese)
				{
					ref dfFontBase reference3 = ref dfFontBase;
					Object obj3 = ResourceCache.Acquire("Alternate Fonts/JackeyFont12_DF");
					reference3 = (dfFontBase)(object)((GameObject)((obj3 is GameObject) ? obj3 : null)).GetComponent<dfFont>();
					ref tk2dFontData reference4 = ref tk2dFont;
					Object obj4 = ResourceCache.Acquire("Alternate Fonts/JackeyFont_TK2D");
					reference4 = ((GameObject)((obj4 is GameObject) ? obj4 : null)).GetComponent<tk2dFont>().data;
				}
				else if (overrideFont == AutoTranslateModule.OverrideFontType.Korean)
				{
					ref dfFontBase reference5 = ref dfFontBase;
					Object obj5 = ResourceCache.Acquire("Alternate Fonts/NanumGothic16_DF");
					reference5 = (dfFontBase)(object)((GameObject)((obj5 is GameObject) ? obj5 : null)).GetComponent<dfFont>();
					ref tk2dFontData reference6 = ref tk2dFont;
					Object obj6 = ResourceCache.Acquire("Alternate Fonts/NanumGothic16TK2D");
					reference6 = ((GameObject)((obj6 is GameObject) ? obj6 : null)).GetComponent<tk2dFont>().data;
				}
				else if (overrideFont == AutoTranslateModule.OverrideFontType.Russian)
				{
					ref dfFontBase reference7 = ref dfFontBase;
					Object obj7 = ResourceCache.Acquire("Alternate Fonts/PixelaCYR_15_DF");
					reference7 = (dfFontBase)(object)((GameObject)((obj7 is GameObject) ? obj7 : null)).GetComponent<dfFont>();
					ref tk2dFontData reference8 = ref tk2dFont;
					Object obj8 = ResourceCache.Acquire("Alternate Fonts/PixelaCYR_15_TK2D");
					reference8 = ((GameObject)((obj8 is GameObject) ? obj8 : null)).GetComponent<tk2dFont>().data;
				}
			}
		}
		else if (!(config.FontAssetBundleName == string.Empty) && (!(config.CustomDfFontName == string.Empty) || !(config.CustomTk2dFontName == string.Empty)))
		{
			string filePath = Path.Combine(ETGMod.FolderPath((BaseUnityPlugin)(object)AutoTranslateModule.instance), config.FontAssetBundleName);
			try
			{
				assetBundle = AssetBundleLoader.LoadAssetBundle(filePath);
				dfFontBase = assetBundle.LoadAsset<GameObject>(config.CustomDfFontName).GetComponent<dfFontBase>();
				tk2dFont = assetBundle.LoadAsset<GameObject>(config.CustomTk2dFontName).GetComponent<tk2dFont>().data;
			}
			catch
			{
			}
		}
	}

	private int EstimateTokenCount(string source)
	{
		if (string.IsNullOrEmpty(source))
		{
			return 0;
		}
		return source.Length;
	}

	public dfList<dfMarkupToken> Tokenize(string source)
	{
		dfList<dfMarkupToken> val = dfList<dfMarkupToken>.Obtain();
		val.EnsureCapacity(EstimateTokenCount(source));
		val.AutoReleaseItems = true;
		MatchCollection matchCollection = DfTokenizerRegex.Matches(source);
		foreach (Match item in matchCollection)
		{
			if (item.Groups["StartTag"].Success)
			{
				Capture capture = item.Groups["StartTagName"];
				Capture capture2 = item.Groups["AttributeValue"];
				dfMarkupToken val2 = dfMarkupToken.Obtain(source, (dfMarkupTokenType)4, capture.Index, capture.Index + capture.Length - 1);
				if (capture2.Value != string.Empty)
				{
					string value = item.Groups["AttributeValue"].Value;
					bool flag = value.StartsWith("\"") && value.EndsWith("\"");
					dfMarkupToken val3 = dfMarkupToken.Obtain(source, (dfMarkupTokenType)1, flag ? (capture2.Index + 1) : capture2.Index, flag ? (capture2.Index + capture2.Length - 2) : (capture2.Index + capture2.Length - 1));
					val2.AddAttribute(val3, val3);
				}
				val.Add(val2);
			}
			else if (item.Groups["EndTag"].Success)
			{
				Capture capture3 = item.Groups["EndTagName"];
				if (capture3.Value != string.Empty)
				{
					val.Add(dfMarkupToken.Obtain(source, (dfMarkupTokenType)5, capture3.Index, capture3.Index + capture3.Length - 1));
				}
			}
			else if (item.Groups["Text"].Success)
			{
				val.Add(dfMarkupToken.Obtain(source, (dfMarkupTokenType)1, item.Index, item.Index + item.Length - 1));
			}
			else if (item.Groups["Whitespace"].Success)
			{
				val.Add(dfMarkupToken.Obtain(source, (dfMarkupTokenType)2, item.Index, item.Index + item.Length - 1));
			}
			else if (item.Groups["Newline"].Success)
			{
				val.Add(dfMarkupToken.Obtain(source, (dfMarkupTokenType)3, item.Index, item.Index + item.Length - 1));
			}
		}
		return val;
	}

	internal static dfFont GetGameFont()
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: 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_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Expected I4, but got Unknown
		dfFont result = null;
		GungeonSupportedLanguages currentLanguage = GameManager.Options.CurrentLanguage;
		GungeonSupportedLanguages val = currentLanguage;
		GungeonSupportedLanguages val2 = val;
		if ((int)val2 != 0)
		{
			switch (val2 - 7)
			{
			case 4:
			{
				Object obj4 = ResourceCache.Acquire("Alternate Fonts/SimSun12_DF");
				result = ((GameObject)((obj4 is GameObject) ? obj4 : null)).GetComponent<dfFont>();
				break;
			}
			case 0:
			{
				Object obj3 = ResourceCache.Acquire("Alternate Fonts/JackeyFont12_DF");
				result = ((GameObject)((obj3 is GameObject) ? obj3 : null)).GetComponent<dfFont>();
				break;
			}
			case 1:
			{
				Object obj2 = ResourceCache.Acquire("Alternate Fonts/NanumGothic16_DF");
				result = ((GameObject)((obj2 is GameObject) ? obj2 : null)).GetComponent<dfFont>();
				break;
			}
			case 2:
			{
				Object obj = ResourceCache.Acquire("Alternate Fonts/PixelaCYR_15_DF");
				result = ((GameObject)((obj is GameObject) ? obj : null)).GetComponent<dfFont>();
				break;
			}
			case 3:
			{
				dfFontBase defaultFont = GameUIRoot.Instance.Manager.defaultFont;
				result = (dfFont)(object)((defaultFont is dfFont) ? defaultFont : null);
				break;
			}
			}
		}
		else
		{
			dfFontBase defaultFont2 = GameUIRoot.Instance.Manager.defaultFont;
			result = (dfFont)(object)((defaultFont2 is dfFont) ? defaultFont2 : null);
		}
		return result;
	}

	internal void InitializeFontAfterGameManager(AutoTranslateModule.OverrideFontType fontType)
	{
		if (fontType == AutoTranslateModule.OverrideFontType.English || fontType == AutoTranslateModule.OverrideFontType.Polish)
		{
			ref dfFontBase reference = ref dfFontBase;
			dfFontBase defaultFont = GameUIRoot.Instance.Manager.defaultFont;
			reference = ((defaultFont is dfFont) ? defaultFont : null);
			tk2dFont = GameManager.Instance.DefaultNormalConversationFont;
		}
	}

	internal static void SetTextMeshFont(tk2dTextMesh textMesh, tk2dFontData font)
	{
		textMesh.UpgradeData();
		textMesh.data.font = font;
		textMesh._fontInst = textMesh.data.font.inst;
		textMesh.SetNeedUpdate((UpdateFlags)1);
		textMesh.UpdateMaterial();
	}

	public string WrapText(string text, out Vector2 resultSize)
	{
		//IL_0022: 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)
		Vector2 resultSize2;
		string result = WrapTextWithTokenizer(itemTipsModuleLabel, text, ItemTipsModTokenizerRegex, itemTipsModuleFont, 500, out resultSize2);
		resultSize = resultSize2;
		return result;
	}

	public static string WrapTextWithTokenizer(SLabel sLabel, string text, Regex tokenizer, Font font, int maxWidth, out Vector2 resultSize)
	{
		//IL_0264: Unknown result type (might be due to invalid IL or missing references)
		//IL_0269: Unknown result type (might be due to invalid IL or missing references)
		//IL_026c: Unknown result type (might be due to invalid IL or missing references)
		//IL_027a: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e8: 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)
		wrappedLines.Clear();
		string[] array = text.Split(newLineSymbols, StringSplitOptions.None);
		string[] array2 = array;
		foreach (string text2 in array2)
		{
			if (string.IsNullOrEmpty(text2))
			{
				wrappedLines.Add("");
				continue;
			}
			MatchCollection matchCollection = tokenizer.Matches(text2);
			if (matchCollection.Count == 0)
			{
				wrappedLines.Add(text2);
				continue;
			}
			currentLine.Length = 0;
			foreach (Match item in matchCollection)
			{
				string value = item.Value;
				float x = ((SElement)sLabel).Backend.MeasureText(value, (Vector2?)null, (object)font).x;
				float x2 = ((SElement)sLabel).Backend.MeasureText(currentLine.ToString(), (Vector2?)null, (object)font).x;
				float x3 = ((SElement)sLabel).Backend.MeasureText(" ", (Vector2?)null, (object)font).x;
				if (currentLine.Length > 0)
				{
					if (x2 + x3 + x > (float)maxWidth)
					{
						wrappedLines.Add(currentLine.ToString());
						currentLine.Length = 0;
						if (x > (float)maxWidth)
						{
							SplitAndAddToken(value, sLabel, font, maxWidth, wrappedLines);
						}
						else
						{
							currentLine.Append(value);
						}
					}
					else
					{
						currentLine.Append(value);
					}
				}
				else if (x > (float)maxWidth)
				{
					SplitAndAddToken(value, sLabel, font, maxWidth, wrappedLines);
				}
				else
				{
					currentLine.Append(value);
				}
			}
			if (currentLine.Length > 0)
			{
				wrappedLines.Add(currentLine.ToString());
			}
		}
		float num = 0f;
		float num2 = 0f;
		foreach (string wrappedLine in wrappedLines)
		{
			Vector2 val = ((SElement)sLabel).Backend.MeasureText(wrappedLine, (Vector2?)null, (object)font);
			num = Math.Max(num, val.x);
			num2 += val.y;
		}
		resultSize = new Vector2(num, num2);
		return string.Join("\n", wrappedLines.ToArray());
	}

	private static void SplitAndAddToken(string token, SLabel sLabel, Font font, int maxWidth, List<string> wrappedLines)
	{
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		int j;
		for (int i = 0; i < token.Length; i += j)
		{
			for (j = 1; i + j <= token.Length && ((SElement)sLabel).Backend.MeasureText(token.Substring(i, j), (Vector2?)null, (object)font).x <= (float)maxWidth; j++)
			{
			}
			j = Math.Max(1, j - 1);
			string item = token.Substring(i, j);
			wrappedLines.Add(item);
		}
	}
}
internal class TranslationManager : MonoBehaviour
{
	private AutoTranslateConfig config;

	private bool translateOn;

	private LRUCache<string, string> translationCache;

	private LRUCache<string, int> fullTextCache;

	private bool isProcessingQueue = false;

	private Queue<TranslationQueueElement> translationQueue;

	private ITranslationService translationService;

	private List<string> batchSubTexts;

	private Dictionary<string, List<string>> batchSplitMap;

	private Dictionary<string, string> batchTranslationDictionary;

	private HashSet<string> batchUniqueSubTexts;

	private List<string> batchTranslatedParts;

	private List<string> uniqueTexts;

	private Dictionary<string, List<object>> textControlMap;

	private Dictionary<object, List<string>> controlTextMap;

	private Regex fullTextRegex;

	private Regex eachLineRegex;

	private Regex ignoredSubstringWithinTextRegex;

	private string[] newLineSymbols = new string[3] { "\r\n", "\r", "\n" };

	private StringBuilder translatedTextBuilder;

	internal static TranslationManager instance;

	private int requestedCharacterCount = 0;

	internal bool exceededThreshold = false;

	private List<string> finalChunks;

	private ObjectPool<List<string>> listStringPool;

	private ObjectPool<List<object>> listObjectPool;

	private ObjectPool<TranslationQueueElement> translationQueueElementPool;

	public void Update()
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		if (Input.GetKeyDown(config.ToggleTranslationKeyBinding))
		{
			ToggleTranslate();
			SetStatusLabelText();
		}
	}

	public void Initialize()
	{
		instance = this;
		config = AutoTranslateModule.instance.config;
		switch (config.TranslationAPI)
		{
		case AutoTranslateModule.TranslationAPIType.Tencent:
			translationService = new TencentTranslationService(config);
			break;
		case AutoTranslateModule.TranslationAPIType.Baidu:
			translationService = new BaiduTranslationService(config);
			break;
		case AutoTranslateModule.TranslationAPIType.Azure:
			translationService = new AzureTranslationService(config);
			break;
		case AutoTranslateModule.TranslationAPIType.LargeModel:
			translationService = new LargeModelTranslationService(config);
			break;
		}
		fullTextCache = new LRUCache<string, int>(64);
		translationCache = new LRUCache<string, string>(config.TranslationCacheCapacity);
		translationQueue = new Queue<TranslationQueueElement>();
		if (config.PresetTranslations != string.Empty)
		{
			string filePath = Path.Combine(ETGMod.FolderPath((BaseUnityPlugin)(object)AutoTranslateModule.instance), config.PresetTranslations);
			ReadAndRestoreTranslationCache(filePath);
		}
		if (config.RegexForFullTextNeedToTranslate != string.Empty)
		{
			fullTextRegex = new Regex(config.RegexForFullTextNeedToTranslate, RegexOptions.Compiled | RegexOptions.Singleline);
		}
		if (config.RegexForEachLineNeedToTranslate != string.Empty)
		{
			eachLineRegex = new Regex(config.RegexForEachLineNeedToTranslate, RegexOptions.Compiled | RegexOptions.Singleline);
		}
		if (config.RegexForIgnoredSubstringWithinText != string.Empty)
		{
			ignoredSubstringWithinTextRegex = new Regex(config.RegexForIgnoredSubstringWithinText, RegexOptions.Multiline | RegexOptions.Compiled);
		}
		batchSubTexts = new List<string>();
		batchSplitMap = new Dictionary<string, List<string>>();
		batchTranslationDictionary = new Dictionary<string, string>();
		batchUniqueSubTexts = new HashSet<string>();
		batchTranslatedParts = new List<string>();
		uniqueTexts = new List<string>();
		textControlMap = new Dictionary<string, List<object>>();
		translatedTextBuilder = new StringBuilder();
		controlTextMap = new Dictionary<object, List<string>>();
		finalChunks = new List<string>();
		listStringPool = new ObjectPool<List<string>>(() => new List<string>(), 64, delegate(List<string> list)
		{
			list.Clear();
		});
		listObjectPool = new ObjectPool<List<object>>(() => new List<object>(), 64, delegate(List<object> list)
		{
			list.Clear();
		});
		translationQueueElementPool = new ObjectPool<TranslationQueueElement>(() => new TranslationQueueElement(), 64, delegate(TranslationQueueElement element)
		{
			element.Reset();
		});
		translateOn = true;
	}

	internal void ToggleTranslate()
	{
		translateOn = !translateOn;
		Debug.Log((object)("AutoTranslate切换为" + (translateOn ? "ON" : "OFF") + "。AutoTranslate toggled to " + (translateOn ? "ON" : "OFF") + "."));
	}

	internal void ForceSetTranslte(bool value)
	{
		translateOn = value;
		Debug.Log((object)("AutoTranslate强制设置为" + (translateOn ? "ON" : "OFF") + "。AutoTranslate forcefully set to " + (translateOn ? "ON" : "OFF") + "."));
	}

	private void SetStatusLabelText()
	{
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		if (exceededThreshold)
		{
			StatusLabelController.instance.SetText(string.Format("AT: {0}\nNow {1} ({2})", requestedCharacterCount, translateOn ? "ON" : "OFF", config.ToggleTranslationKeyBinding));
		}
		else
		{
			StatusLabelController.instance.SetText($"AT: {requestedCharacterCount}");
		}
	}

	private bool NeedToTranslate(string text)
	{
		if (IsNullOrWhiteSpace(text))
		{
			return false;
		}
		if (fullTextRegex != null && !fullTextRegex.IsMatch(text))
		{
			return false;
		}
		if (eachLineRegex != null)
		{
			string[] array = text.Split(newLineSymbols, StringSplitOptions.None);
			string[] array2 = array;
			foreach (string input in array2)
			{
				if (eachLineRegex.IsMatch(input))
				{
					return true;
				}
			}
			return false;
		}
		return true;
	}

	private IEnumerator ProcessTranslationQueue()
	{
		isProcessingQueue = true;
		while (true)
		{
			if (!translateOn)
			{
				yield return null;
				continue;
			}
			DeduplicateTexts();
			if (uniqueTexts.Count > 0)
			{
				int count = GenerateBatch();
				yield return ((MonoBehaviour)this).StartCoroutine(TranslateBatchCoroutine(count));
			}
			yield return null;
		}
	}

	private void DeduplicateTexts()
	{
		uniqueTexts.Clear();
		textControlMap.Clear();
		int num = 0;
		while (translationQueue.Count > 0 && num < config.RequestBatchSize)
		{
			TranslationQueueElement translationQueueElement = translationQueue.Peek();
			string text = translationQueueElement.text;
			object control = translationQueueElement.control;
			if (IsNullOrWhiteSpace(text))
			{
				translationQueueElementPool.Return(translationQueue.Dequeue());
				continue;
			}
			if (num + text.Length > config.RequestBatchSize)
			{
				break;
			}
			foreach (string uniqueText in uniqueTexts)
			{
				if (text.StartsWith(uniqueText) && !text.Equals(uniqueText) && textControlMap.TryGetValue(text, out var value) && value.Contains(control))
				{
					text = text.Substring(uniqueText.Length);
				}
			}
			if (!textControlMap.ContainsKey(text))
			{
				uniqueTexts.Add(text);
				num += text.Length;
				textControlMap[text] = listObjectPool.Get();
			}
			textControlMap[text].Add(control);
			translationQueueElementPool.Return(translationQueue.Dequeue());
		}
	}

	private int GenerateBatch()
	{
		batchSubTexts.Clear();
		batchSplitMap.Clear();
		batchTranslationDictionary.Clear();
		batchUniqueSubTexts.Clear();
		int num = 0;
		foreach (string uniqueText in uniqueTexts)
		{
			List<string> list = listStringPool.Get();
			if (config.RegexForIgnoredSubstringWithinText != null)
			{
				list.AddRange(from part in ignoredSubstringWithinTextRegex.Split(uniqueText)
					select part.Trim() into part
					where !IsNullOrWhiteSpace(part)
					select part);
			}
			else
			{
				list.Add(uniqueText.Trim());
			}
			bool flag = true;
			batchTranslatedParts.Clear();
			foreach (string item in list)
			{
				if (translationCache.TryGetValue(item, out var value))
				{
					batchTranslationDictionary[item] = value;
					continue;
				}
				flag = false;
				if (batchUniqueSubTexts.Add(item))
				{
					batchTranslatedParts.Add(item);
					num += item.Length;
				}
			}
			if (flag)
			{
				translatedTextBuilder.Length = 0;
				translatedTextBuilder.Append(uniqueText);
				foreach (string item2 in list)
				{
					int num2 = translatedTextBuilder.ToString().IndexOf(item2);
					if (num2 != -1 && batchTranslationDictionary.TryGetValue(item2, out var value2))
					{
						translatedTextBuilder.Replace(item2, value2, num2, item2.Length);
					}
				}
				string result = translatedTextBuilder.ToString();
				if (textControlMap.TryGetValue(uniqueText, out var value3))
				{
					foreach (object item3 in value3)
					{
						OnTranslationFinish(item3, uniqueText, result);
						RemoveTextFromControlStatusMap(item3, uniqueText);
					}
					listObjectPool.Return(value3);
					textControlMap.Remove(uniqueText);
				}
				listStringPool.Return(list);
			}
			else
			{
				batchSplitMap[uniqueText] = list;
				batchSubTexts.AddRange(batchTranslatedParts);
			}
		}
		return num;
	}

	private IEnumerator TranslateBatchCoroutine(int batchCharacterCount)
	{
		if (batchSubTexts.Count == 0)
		{
			yield break;
		}
		if (!exceededThreshold && config.RequestedCharacterCountAlertThreshold > 0 && requestedCharacterCount + batchCharacterCount > config.RequestedCharacterCountAlertThreshold)
		{
			exceededThreshold = true;
			StatusLabelController.instance.SetHighlight();
			ForceSetTranslte(value: false);
			SetStatusLabelText();
		}
		while (!translateOn)
		{
			yield return null;
		}
		if (config.LogRequestedTexts)
		{
			Debug.Log((object)"请求的文本 RequestedTexts:  {");
			foreach (string subText in batchSubTexts)
			{
				Debug.Log((object)("      " + subText));
			}
			Debug.Log((object)"}");
		}
		yield return ((MonoBehaviour)this).StartCoroutine(translationService.StartTranslation(batchSubTexts, delegate(string[] translatedTexts)
		{
			if (translatedTexts == null || translatedTexts.Length != batchSubTexts.Count)
			{
				if (translatedTexts != null)
				{
					Debug.LogError((object)"翻译结果数量与请求数量不匹配!The number of translation results does not match the number of requests!");
					Debug.LogError((object)"请求 Requests:");
					foreach (string batchSubText in batchSubTexts)
					{
						Debug.Log((object)("      " + batchSubText));
					}
					Debug.LogError((object)"结果 Results:");
					foreach (string text in translatedTexts)
					{
						Debug.Log((object)("      " + text));
					}
				}
				{
					foreach (string uniqueText in uniqueTexts)
					{
						if (batchSplitMap.TryGetValue(uniqueText, out var value))
						{
							listStringPool.Return(value);
							batchSplitMap.Remove(uniqueText);
							if (textControlMap.TryGetValue(uniqueText, out var va