Decompiled source of STRAFCHAT v1.0.0

plugins/STRAFCHAT.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using ComputerysModdingUtilities;
using FishNet.Object;
using HarmonyLib;
using HeathenEngineering.DEMO;
using HeathenEngineering.SteamworksIntegration;
using HeathenEngineering.SteamworksIntegration.API;
using HeathenEngineering.SteamworksIntegration.UI;
using Microsoft.CodeAnalysis;
using ModMenu.Api;
using ModMenu.Behaviours.OptionList;
using ModMenu.Behaviours.OptionList.Dummies;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Steamworks;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: StraftatMod(true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Strafchat
{
	internal static class ChatText
	{
		internal struct Evidence
		{
			internal string Language;

			internal bool Mixed;

			internal bool Certain;

			internal bool Vote;

			internal bool Neutral;

			internal string[] PossibleLanguages;

			internal bool LooksForeignTo(string reading)
			{
				if (!Mixed)
				{
					if (Language == null)
					{
						if (PossibleLanguages != null)
						{
							return Hint(reading) == null;
						}
						return false;
					}
					return Language != reading;
				}
				return true;
			}

			internal string Hint(string previous)
			{
				if (Mixed || Language != null)
				{
					return Language;
				}
				if (previous == null || PossibleLanguages == null)
				{
					return previous;
				}
				if (!PossibleLanguages.Contains(previous))
				{
					return null;
				}
				return previous;
			}
		}

		private const string ChineseOnly = "吗们这说么";

		private const string ChineseWithoutKana = "吗们这说么没";

		private static readonly Regex LatinWords;

		private static readonly Regex TitleFiller;

		private static readonly Regex DefaultTitle;

		private static readonly string[] HanLanguages;

		private static readonly string[] ArabicLanguages;

		private static readonly string[] DevanagariLanguages;

		private static readonly string[] CyrillicLanguages;

		private static readonly HashSet<string> StarredTags;

		private static readonly HashSet<string> StandaloneTags;

		private static readonly Regex TagName;

		internal const int WireLimit = 500;

		internal const float RowToInputSize = 1.2857143f;

		internal const string LanguageCodePattern = "[a-z]{2,3}(?:-[a-z]{4})?";

		internal const string TranslationColor = "#FFE29A";

		internal const string DangerColor = "#FF4949";

		private const string TranslationStyle = "<color=#FFE29A><i>";

		private const string TranslationEnd = "</i></color></link>";

		private const string TranslationBody = "(?:[^<\\r\\n]|<(?!/?[a-zA-Z#]))+";

		private const string Censored = "\\*{3,}";

		private const string Edges = "[\\p{L}\\p{N}_]";

		private const RegexOptions IgnoreCase = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant;

		internal static string Shown;

		internal static readonly string[,] Colors;

		private static readonly Regex ModelControl;

		private static readonly char[] ControlPrefixes;

		private static readonly Regex TagLike;

		private static readonly HashSet<string> TmpTags;

		private static readonly Regex NonLetters;

		private static readonly Regex Spaces;

		private static readonly Regex LocalSize;

		private static readonly Regex Translation;

		private static readonly Regex LanguageCode;

		private static readonly Regex MarkupStart;

		internal static readonly Regex Markers;

		private static readonly Regex Protected;

		private static readonly Regex NameToken;

		private static readonly Dictionary<int, Dictionary<int, List<string>>> FuzzyNames;

		private static readonly int[] FuzzyWordCounts;

		private static readonly HashSet<string> WordNames;

		private static readonly Dictionary<string, Dictionary<string, string>> Phrases;

		private static readonly Dictionary<string, HashSet<string>> PhraseLanguages;

		private static readonly Dictionary<string, Dictionary<string, int>> Profiles;

		private static readonly Dictionary<string, HashSet<string>> FunctionWords;

		private static readonly Dictionary<string, string[]> Shorthand;

		private static readonly Regex AloneTerms;

		private static readonly Dictionary<string, string> Hints;

		private static readonly Regex HintTerms;

		private static readonly Dictionary<string, string> PlainWords;

		private static readonly Regex SlangTerms;

		internal static string GuessLanguage(string text, string ignore = null)
		{
			string input = Plain(text ?? "");
			if (DefaultTitle.IsMatch(input))
			{
				return null;
			}
			if (!string.IsNullOrWhiteSpace(ignore))
			{
				input = Regex.Replace(input, Words(new string[1] { ignore }), " ", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
			}
			string text2 = TitleFiller.Replace(input, " ");
			string text3 = NonLetters.Replace(text2, " ").Trim();
			string text4 = LatinWords.Replace(text3, " ").Trim();
			if (text4.Length > 0 && text4.Length != text3.Length)
			{
				text2 = LatinWords.Replace(text2, " ");
			}
			if (NonLetters.Replace(text2, "").Length == 0)
			{
				return null;
			}
			Evidence evidence = Analyze(text2.Trim());
			if (evidence.Language == null || evidence.Certain || evidence.Vote || (!Scripts.Has(text2, Script.Cyrillic) && !Has(text2, 'A', 'Z') && !Has(text2, 'a', 'z')) || text3.Split(' ').Length >= 3)
			{
				return evidence.Language;
			}
			return null;
		}

		internal static string Detect(string text)
		{
			return Analyze(text).Language;
		}

		internal static Evidence Analyze(string text, string target = null)
		{
			string text2 = Key(text);
			if (PhraseLanguages.TryGetValue(text2, out var value) && value.Count == 1)
			{
				string text3 = value.First();
				return new Evidence
				{
					Language = text3,
					Certain = true,
					Vote = (text3 != "en" && text2.Length > 3)
				};
			}
			bool needsLocalization = false;
			string text4 = Protected.Replace(text, delegate(Match match)
			{
				if (!Keep(match.Value, target))
				{
					needsLocalization = true;
				}
				return " ";
			});
			string text5 = NonLetters.Replace(text4.ToLowerInvariant(), " ").Trim();
			if (text5.Length == 0)
			{
				return new Evidence
				{
					Neutral = (!needsLocalization && !HasLetters(text4))
				};
			}
			string text6 = text5.Replace(" ", "");
			if (Scripts.In(text6).Select(DetectedRun).Distinct()
				.Count() > 1)
			{
				return new Evidence
				{
					Mixed = true
				};
			}
			bool flag = Scripts.Has(text5, Script.Kana);
			bool flag2 = Scripts.Has(text5, Script.Hangul);
			bool flag3 = Scripts.Has(text5, Script.Han);
			if ((flag && flag2) || ((flag || flag2) && Has(text5, "吗们这说么")))
			{
				return new Evidence
				{
					Mixed = true
				};
			}
			string text7 = null;
			if (flag)
			{
				text7 = "ja";
			}
			else if (flag2)
			{
				text7 = "ko";
			}
			else if (Scripts.Has(text5, Script.Greek))
			{
				text7 = "el";
			}
			else if (Scripts.Has(text5, Script.Hebrew))
			{
				text7 = "he";
			}
			else if (Scripts.Has(text5, Script.Thai))
			{
				text7 = "th";
			}
			else if (Scripts.Has(text5, Script.Bengali))
			{
				text7 = "bn";
			}
			if (text7 != null)
			{
				return new Evidence
				{
					Language = text7,
					Certain = (!needsLocalization && !flag3),
					Vote = (text6.Length >= 3)
				};
			}
			if (flag3)
			{
				if (!Has(text5, "吗们这说么没"))
				{
					return new Evidence
					{
						PossibleLanguages = HanLanguages
					};
				}
				return new Evidence
				{
					Language = "zh",
					Vote = (text6.Length >= 3)
				};
			}
			if (Scripts.Has(text5, Script.Arabic))
			{
				return new Evidence
				{
					PossibleLanguages = ArabicLanguages
				};
			}
			if (Scripts.Has(text5, Script.Devanagari))
			{
				return new Evidence
				{
					PossibleLanguages = DevanagariLanguages
				};
			}
			bool strong;
			string text8 = ProfileLanguage(text5, text, out strong);
			bool flag4 = text6.Length >= 8 && (text8 != "en" || text5.Split(' ').Length >= 4);
			return new Evidence
			{
				Language = text8,
				Vote = (flag4 && strong),
				PossibleLanguages = (Scripts.Has(text5, Script.Cyrillic) ? CyrillicLanguages : null)
			};
		}

		private static Script DetectedRun(Script script)
		{
			switch (script)
			{
			case Script.Latin:
			case Script.Greek:
			case Script.Cyrillic:
			case Script.Hebrew:
			case Script.Arabic:
			case Script.Devanagari:
			case Script.Bengali:
			case Script.Thai:
				return script;
			case Script.Hangul:
			case Script.Kana:
			case Script.Han:
				return Script.Han;
			default:
				return Script.Other;
			}
		}

		private static string ProfileLanguage(string words, string text, out bool strong)
		{
			strong = true;
			if (Has(words, "әғқңөұүһ"))
			{
				return "kk";
			}
			if (Has(words, "іїєґ"))
			{
				return "uk";
			}
			if (Has(words, "ơư") || Has(words, 'Ạ', 'ỹ'))
			{
				return "vi";
			}
			if (Has(words, "șț"))
			{
				return "ro";
			}
			if (Has(words, "ñ") || Has(text, "¿¡"))
			{
				return "es";
			}
			if (words.Length < 4)
			{
				strong = false;
				return null;
			}
			string text2 = " " + words + " ";
			int num = 0;
			int num2 = 0;
			string result = null;
			string[] array = new string[text2.Length - 2];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = text2.Substring(i, 3);
			}
			bool flag = (Has(words, 'а', 'я') || Has(words, "ё")) && !Has(words, 'a', 'z');
			foreach (KeyValuePair<string, Dictionary<string, int>> profile in Profiles)
			{
				if (flag && profile.Key != "ru" && profile.Key != "uk" && profile.Key != "bg" && profile.Key != "sr")
				{
					continue;
				}
				int num3 = 0;
				string[] array2 = array;
				foreach (string key in array2)
				{
					if (profile.Value.TryGetValue(key, out var value))
					{
						num3 += 100 + value;
					}
				}
				if (num3 > num)
				{
					num2 = num;
					num = num3;
					result = profile.Key;
				}
				else
				{
					num2 = Math.Max(num3, num2);
				}
			}
			strong = num >= 950 && num - num2 > num / 4 && (flag || words.Split(' ').Length >= 4);
			if (num < 400 || num - num2 < num / 8)
			{
				return null;
			}
			return result;
		}

		private static bool Has(string s, char from, char to)
		{
			foreach (char c in s)
			{
				if (c >= from && c <= to)
				{
					return true;
				}
			}
			return false;
		}

		private static bool Has(string s, string chars)
		{
			return s.IndexOfAny(chars.ToCharArray()) >= 0;
		}

		internal static string ProtectTerms(string text, List<string> names, string target = null, bool useContext = false)
		{
			Match[] array = ((target == null) ? Array.Empty<Match>() : KeyboardKeys.In(text).ToArray());
			Match match = Protected.Match(text);
			Match[] array2 = NameToken.Matches(text).ToArray();
			StringBuilder stringBuilder = new StringBuilder();
			int num = 0;
			int i = 0;
			int j = 0;
			while (num < text.Length)
			{
				for (; j < array.Length && array[j].Index < num; j++)
				{
				}
				if (j < array.Length && array[j].Index == num)
				{
					string value = array[j++].Value;
					stringBuilder.Append(Marker(names.Count));
					names.Add(value);
					num += value.Length;
					while (match.Success && match.Index < num)
					{
						match = match.NextMatch();
					}
					continue;
				}
				for (; i < array2.Length && array2[i].Index < num; i++)
				{
				}
				string text2 = null;
				bool flag = false;
				if (match.Success && match.Index == num)
				{
					text2 = match.Value;
					match = match.NextMatch();
				}
				else if (i < array2.Length && array2[i].Index == num)
				{
					int[] fuzzyWordCounts = FuzzyWordCounts;
					foreach (int num2 in fuzzyWordCounts)
					{
						int num3 = i + num2 - 1;
						if (num3 >= array2.Length)
						{
							continue;
						}
						int num4 = array2[num3].Index + array2[num3].Length;
						if (match.Success && match.Index < num4)
						{
							continue;
						}
						int num5 = num4 - num;
						if (num5 < 6 || !FuzzyNames[num2].TryGetValue(num5, out var value2))
						{
							continue;
						}
						string text3 = text.Substring(num, num5);
						if (text3.Any((char c) => !char.IsLetterOrDigit(c) && c != ' ' && c != '_' && c != '-' && c != '\''))
						{
							continue;
						}
						int num6 = 0;
						foreach (string item in value2)
						{
							if (OneEdit(text3, item) && ++num6 == 2)
							{
								break;
							}
						}
						if (num6 == 1)
						{
							text2 = text3;
							flag = true;
							break;
						}
					}
				}
				if (text2 == null)
				{
					stringBuilder.Append(text[num++]);
					continue;
				}
				num += text2.Length;
				if ((useContext && WordNames.Contains(text2) && text2.Length != text.Length) || (!flag && !Keep(text2, target)))
				{
					stringBuilder.Append(text2);
					continue;
				}
				stringBuilder.Append(Marker(names.Count));
				names.Add(text2);
			}
			return stringBuilder.ToString();
		}

		internal static bool OneEdit(string typed, string name)
		{
			if (Math.Abs(typed.Length - name.Length) > 1)
			{
				return false;
			}
			if (typed.Length > name.Length)
			{
				return OneEdit(name, typed);
			}
			int i;
			for (i = 0; i < typed.Length && char.ToUpperInvariant(typed[i]) == char.ToUpperInvariant(name[i]); i++)
			{
			}
			if (i == typed.Length)
			{
				if (typed.Length != name.Length)
				{
					return !char.IsDigit(name[i]);
				}
				return false;
			}
			if (char.IsDigit(typed[i]) || char.IsDigit(name[i]))
			{
				return false;
			}
			if (typed.Length != name.Length)
			{
				return string.Compare(typed, i, name, i + 1, typed.Length - i, StringComparison.OrdinalIgnoreCase) == 0;
			}
			if (string.Compare(typed, i + 1, name, i + 1, typed.Length - i - 1, StringComparison.OrdinalIgnoreCase) == 0)
			{
				return true;
			}
			if (i + 1 < typed.Length && !char.IsDigit(typed[i + 1]) && !char.IsDigit(name[i + 1]) && char.ToUpperInvariant(typed[i]) == char.ToUpperInvariant(name[i + 1]) && char.ToUpperInvariant(typed[i + 1]) == char.ToUpperInvariant(name[i]))
			{
				return string.Compare(typed, i + 2, name, i + 2, typed.Length - i - 2, StringComparison.OrdinalIgnoreCase) == 0;
			}
			return false;
		}

		internal static string RestoreTerms(string text, List<string> names)
		{
			if (text == null)
			{
				return null;
			}
			HashSet<int> used = new HashSet<int>();
			bool valid = true;
			string result = Markers.Replace(text, delegate(Match m)
			{
				if (int.TryParse(m.Value.Substring(3, m.Length - 6), out var result2) && result2 < names.Count && m.Value == Marker(result2) && used.Add(result2))
				{
					return names[result2];
				}
				valid = false;
				return "";
			});
			if (!valid || used.Count != names.Count)
			{
				return null;
			}
			return result;
		}

		internal static bool NeedsIncomingTranslation(HashSet<string> translations, string target, bool mine, bool soloPractice)
		{
			if (!mine)
			{
				return !translations.Contains(target);
			}
			if (soloPractice)
			{
				return translations.Count == 0;
			}
			return false;
		}

		internal static string Original(string wire, out HashSet<string> langs)
		{
			Match match = LocalSize.Match(wire);
			if (match.Success && wire.EndsWith("</size>", StringComparison.Ordinal))
			{
				string result = Original(wire.Substring(match.Length, wire.Length - match.Length - 7), out langs);
				if (langs.Count <= 0)
				{
					return wire;
				}
				return result;
			}
			langs = new HashSet<string>();
			MatchCollection matchCollection = Translation.Matches(wire);
			if (matchCollection.Count == 0)
			{
				return wire;
			}
			int index = matchCollection[0].Index;
			int num = index;
			foreach (Match item in matchCollection)
			{
				if (item.Index != num)
				{
					return wire;
				}
				num += item.Length;
			}
			if (num != wire.Length)
			{
				return wire;
			}
			foreach (Match item2 in matchCollection)
			{
				langs.Add(item2.Groups["lang"].Value.ToLowerInvariant());
			}
			string text = wire.Substring(0, index);
			Match match4 = LocalSize.Match(text);
			if (match4.Success && text.EndsWith("</size>", StringComparison.Ordinal))
			{
				return text.Substring(match4.Length, text.Length - match4.Length - 7);
			}
			return text;
		}

		internal static string FormatReceived(string wire, float width, Func<string, float> measure)
		{
			HashSet<string> langs;
			string text = Original(wire, out langs);
			if (langs.Count == 0 || (LocalSize.IsMatch(wire) && wire.EndsWith("</size>", StringComparison.Ordinal)))
			{
				return wire;
			}
			Match match = Translation.Match(wire);
			if (LocalSize.IsMatch(wire) && wire.Substring(0, match.Index).EndsWith("</size>", StringComparison.Ordinal))
			{
				return wire;
			}
			string text2 = wire.Substring(match.Index);
			if (text.StartsWith("**********", StringComparison.Ordinal) && text.EndsWith("*******", StringComparison.Ordinal) && text.Length >= 17 && match.Value.Contains(">****************<color=#FFE29A>"))
			{
				text = text.Substring(10, text.Length - 17);
				text2 = text2.Replace(">****************<color=#FFE29A>", "><color=#FFE29A>").Replace("</color>*******</link>", "</color></link>");
			}
			string text3 = text + text2;
			if (width <= 0f || measure(text3) <= width)
			{
				return text3;
			}
			int num = 80;
			int num2 = 99;
			while (num < num2)
			{
				int num3 = (num + num2 + 1) / 2;
				if (measure(SizeRow(text3, num3)) <= width)
				{
					num = num3;
				}
				else
				{
					num2 = num3 - 1;
				}
			}
			return SizeRow(text3, num);
		}

		private static string SizeRow(string text, int percent)
		{
			return "<size=" + percent + "%>" + text + "</size>";
		}

		private static string OpenTagsClosed(string text)
		{
			List<string> list = new List<string>();
			for (int i = 0; i < text.Length; i++)
			{
				if (text[i] != '<')
				{
					continue;
				}
				int j;
				for (j = i + 1; j < text.Length && text[j] != '>' && text[j] != '<'; j++)
				{
				}
				if (j == text.Length || text[j] == '<')
				{
					continue;
				}
				string text2 = text.Substring(i + 1, j - i - 1);
				i = j;
				int k;
				for (k = 0; k < text2.Length && text2[k] != '=' && text2[k] != ' '; k++)
				{
				}
				string text3 = text2.Substring(0, k);
				if (string.Equals(text3, "g", StringComparison.OrdinalIgnoreCase) && k < text2.Length && text2[k] == '=')
				{
					text3 = "gradient";
				}
				else if (string.Equals(text2, "/g", StringComparison.OrdinalIgnoreCase))
				{
					text3 = "/gradient";
				}
				if (StarredTags.Contains(text3) || (text3.StartsWith("/", StringComparison.Ordinal) && StarredTags.Contains(text3.Substring(1))))
				{
					continue;
				}
				bool flag = text3.StartsWith("/", StringComparison.Ordinal);
				string name = (flag ? text3.Substring(1) : text3).TrimEnd('/');
				bool num = name.StartsWith("#", StringComparison.Ordinal);
				bool flag2 = num || TagName.IsMatch(name);
				if (num)
				{
					name = "color";
				}
				if (flag && flag2)
				{
					int num2 = list.FindLastIndex((string tag) => string.Equals(tag, name, StringComparison.OrdinalIgnoreCase));
					if (num2 >= 0)
					{
						list.RemoveRange(num2, list.Count - num2);
					}
				}
				else if (flag2 && !StandaloneTags.Contains(name))
				{
					list.Add(name);
				}
			}
			return string.Concat(from text4 in Enumerable.Reverse(list)
				select "</" + text4 + ">");
		}

		internal static string Append(string wire, string target, string result, int limit = 500)
		{
			if (string.IsNullOrWhiteSpace(result) || !LanguageCode.IsMatch(target))
			{
				return wire;
			}
			string text = Spaces.Replace(result, " ").Trim();
			text = Inert(text);
			string text2 = OpenTagsClosed(wire) + "  <link=\"sc-" + target + "\"><color=#FFE29A><i>";
			int num = limit - wire.Length - text2.Length - "</i></color></link>".Length;
			if (num < 1)
			{
				return wire;
			}
			if (text.Length > num)
			{
				if (num < 6)
				{
					return wire;
				}
				int num2 = 0;
				int[] array = StringInfo.ParseCombiningCharacters(text);
				foreach (int num3 in array)
				{
					if (num3 > num - 3)
					{
						break;
					}
					num2 = num3;
				}
				if (num2 == 0)
				{
					return wire;
				}
				text = text.Substring(0, num2) + "...";
			}
			return wire + text2 + text + "</i></color></link>";
		}

		static ChatText()
		{
			LatinWords = new Regex("[A-Za-z\\u00C0-\\u024F\\u1E00-\\u1EFF]+");
			TitleFiller = new Regex("\\b(?:straftat|lobby|private|public|ffa|1v1|2v2)\\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
			DefaultTitle = new Regex("['\\u2019]s\\s+lobby\\s*$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
			HanLanguages = new string[4] { "ja", "zh", "zh-hant", "yue" };
			ArabicLanguages = new string[4] { "ar", "fa", "ur", "ug" };
			DevanagariLanguages = new string[2] { "hi", "mr" };
			CyrillicLanguages = new string[6] { "ru", "uk", "sr", "bg", "kk", "mn" };
			StarredTags = new HashSet<string> { "size", "mark", "scale", "SIZE", "MARK", "SCALE" };
			StandaloneTags = new HashSet<string>(new string[8] { "br", "sprite", "space", "page", "pos", "alpha", "nbsp", "zwsp" }.SelectMany((string tag) => new string[2]
			{
				tag,
				tag.ToUpperInvariant()
			}));
			TagName = new Regex("\\A[a-zA-Z][a-zA-Z0-9-]*\\z");
			Shown = "#FFE29A";
			Colors = new string[4, 2]
			{
				{ "Gold", "#FFE29A" },
				{ "Lime", "#E4FF88" },
				{ "Mint", "#8CFFD9" },
				{ "Yellow (high contrast)", "#FFFF00" }
			};
			ModelControl = new Regex("<\\|(?:im_start|im_end|im_sep|begin_of_text|end_of_text|start_header_id|end_header_id|eot_id|eom_id|endoftext|fim_prefix|fim_middle|fim_suffix|system|developer|user|assistant|tool|observation|end|start|message|channel|return|call|constrain|think|endofturn|START_OF_TURN_TOKEN|END_OF_TURN_TOKEN|SYSTEM_TOKEN|USER_TOKEN|CHATBOT_TOKEN|TOOL_TOKEN)\\|>|<|(?:User|Assistant|System|begin▁of▁sentence|end▁of▁sentence|tool▁(?:calls?|outputs?)▁(?:begin|end)|tool▁sep)|>|\\[(?:gMASK|sMASK)\\]|\\[/?(?:INST|SYSTEM_PROMPT|AVAILABLE_TOOLS|TOOL_CALLS|TOOL_RESULTS|THINK)\\]|<</?SYS>>|<\\|(?:turn|channel|tool|tool_call|tool_response)>|<(?:turn|channel|tool|tool_call|tool_response)\\|>|<(?:start_of_turn|end_of_turn|bos|eos|sop|eop|/?s|/?think|/?tool_call|/?tool_response)>", RegexOptions.CultureInvariant);
			ControlPrefixes = new char[2] { '<', '[' };
			TagLike = new Regex("<(?<close>/?)(?<name>[^<>=\\s]*)[^<>]*>");
			TmpTags = new HashSet<string>(new string[48]
			{
				"a", "align", "allcaps", "alpha", "b", "br", "class", "color", "cspace", "font",
				"font-weight", "frac", "g", "gradient", "i", "indent", "liga", "line-height", "line-indent", "link",
				"lowercase", "margin", "margin-left", "margin-right", "mark", "material", "mspace", "nbsp", "nobr", "noparse",
				"page", "pos", "rotate", "s", "scale", "shy", "size", "smallcaps", "space", "sprite",
				"style", "sub", "sup", "u", "uppercase", "voffset", "width", "zwsp"
			}, StringComparer.OrdinalIgnoreCase);
			NonLetters = new Regex("[^\\p{L}]+");
			Spaces = new Regex("\\s+");
			LocalSize = new Regex("^<size=(?:8[0-9]|9[0-9])%>");
			Translation = new Regex("  <link=\"sc-(?<lang>[a-z]{2,3}(?:-[a-z]{4})?)\"><color=#[0-9A-F]{6}><i>(?:[^<\\r\\n]|<(?!/?[a-zA-Z#]))+" + Regex.Escape("</i></color></link>") + "|  <link=\"sc-(?<lang>[a-z]{2,3}(?:-[a-z]{4})?)\"><mark=#20180FCC><color=#FFE29A><i>(?:[^<\\r\\n]|<(?!/?[a-zA-Z#]))+</i></color></mark></link>|  <link=\"sc-(?<lang>[a-z]{2,3}(?:-[a-z]{4})?)\">\\*{16}<color=#FFE29A><i>(?:[^<\\r\\n]|<(?!/?[a-zA-Z#]))+</i></color>\\*{7}</link>", RegexOptions.IgnoreCase);
			LanguageCode = new Regex("^[a-z]{2,3}(?:-[a-z]{4})?$");
			MarkupStart = new Regex("<(?=/?[a-zA-Z#])");
			Markers = new Regex("ZXQ[0-9]+QXZ");
			NameToken = new Regex("[\\p{L}\\p{N}_'-]+");
			FuzzyNames = new Dictionary<int, Dictionary<int, List<string>>>();
			WordNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			Phrases = new Dictionary<string, Dictionary<string, string>>();
			PhraseLanguages = new Dictionary<string, HashSet<string>>();
			Profiles = new Dictionary<string, Dictionary<string, int>>();
			FunctionWords = new Dictionary<string, HashSet<string>>();
			Shorthand = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);
			Hints = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			PlainWords = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			string[] array = Lines("phrasebook.tsv");
			string[] array2 = array[0].Split('\t');
			foreach (string item in array.Skip(1))
			{
				string[] array3 = item.Split('\t');
				if (array3.Length > array2.Length)
				{
					throw new InvalidDataException("Too many columns in phrasebook.tsv");
				}
				Dictionary<string, string> dictionary = (from row in array2.Zip(array3, (string language, string phrase) => new
					{
						language = language,
						phrase = phrase.Trim()
					})
					where row.phrase.Length > 0
					select row).ToDictionary(row => row.language, row => row.phrase);
				foreach (string key3 in dictionary.Keys)
				{
					string text = Key(dictionary[key3]);
					Phrases[key3 + "|" + text] = dictionary;
					if (!PhraseLanguages.TryGetValue(text, out var value))
					{
						value = (PhraseLanguages[text] = new HashSet<string>());
					}
					value.Add(key3);
				}
			}
			foreach (string item2 in Lines("function-words.tsv").Skip(1))
			{
				string[] array4 = item2.Split('\t');
				FunctionWords.Add(array4[0], new HashSet<string>(array4[1].Split(' '), StringComparer.Ordinal));
			}
			foreach (string item3 in Lines("language-profiles.tsv").Skip(1))
			{
				string[] array5 = item3.Split('\t');
				Dictionary<string, int> dictionary2 = new Dictionary<string, int>();
				int num = 300;
				string[] array6 = array5[1].Replace('_', ' ').Split('|');
				foreach (string key in array6)
				{
					dictionary2[key] = Math.Max(1, num--);
				}
				Profiles.Add(array5[0], dictionary2);
			}
			List<string> list = new List<string>();
			List<string> list2 = new List<string>();
			foreach (string item4 in Lines("shorthand.tsv").Skip(1))
			{
				string[] array7 = item4.Split('\t');
				Shorthand.Add(array7[0], array7[1].Split(' '));
				((array7.Length > 2 && array7[2] == "alone") ? list : list2).Add(array7[0]);
			}
			AloneTerms = new Regex(Words(list), RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);
			foreach (string item5 in Lines("translation-context.tsv").Skip(1))
			{
				string[] array8 = item5.Split('\t');
				if (array8.Length > 2)
				{
					PlainWords.Add(array8[0], array8[2]);
				}
				else
				{
					Hints.Add(array8[0], array8[1]);
				}
			}
			SlangTerms = new Regex(Words(PlainWords.Keys), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
			List<string> list3 = new List<string>();
			List<string> list4 = new List<string>();
			foreach (string item6 in Lines("game-terms.tsv").Skip(1))
			{
				string[] array9 = item6.Split('\t');
				string text2 = array9[0];
				string text3 = array9[1];
				if (text3 != "name" && text3 != "word")
				{
					throw new InvalidDataException("Unknown kind in game-terms.tsv: " + text3);
				}
				list3.Add(text2);
				if (text3 == "word")
				{
					WordNames.Add(text2);
					Hints[text2] = "a weapon or map in this game when used as one (keep it as typed then), otherwise its ordinary meaning";
				}
				else if (text2.Length >= 6)
				{
					list4.Add(text2);
				}
			}
			foreach (string item7 in list4)
			{
				int key2 = 1 + item7.Count((char c) => c == ' ');
				if (!FuzzyNames.TryGetValue(key2, out var value2))
				{
					value2 = (FuzzyNames[key2] = new Dictionary<int, List<string>>());
				}
				for (int num3 = item7.Length - 1; num3 <= item7.Length + 1; num3++)
				{
					if (!value2.TryGetValue(num3, out var value3))
					{
						value3 = (value2[num3] = new List<string>());
					}
					value3.Add(item7);
				}
			}
			FuzzyWordCounts = FuzzyNames.Keys.OrderByDescending((int n) => n).ToArray();
			HintTerms = new Regex(Words(Hints.Keys), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
			Protected = new Regex(Markers?.ToString() + "|\\*{3,}|" + Words(list3.Concat(list2)), RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);
		}

		internal static string[] Lines(string name)
		{
			using Stream stream = typeof(ChatText).Assembly.GetManifestResourceStream(name) ?? throw new InvalidDataException("Missing language resource: " + name);
			using StreamReader streamReader = new StreamReader(stream);
			List<string> list = new List<string>();
			string text;
			while ((text = streamReader.ReadLine()) != null)
			{
				if (!string.IsNullOrWhiteSpace(text))
				{
					list.Add(text);
				}
			}
			return list.ToArray();
		}

		internal static string SourceTag(string code)
		{
			if (code != null)
			{
				return "[" + Languages.Short(code) + "] ";
			}
			return "";
		}

		internal static string ForDisplay(string text)
		{
			if (!(Shown == "#FFE29A"))
			{
				return text.Replace("<color=#FFE29A>", "<color=" + Shown + ">");
			}
			return text;
		}

		internal static bool IsCommand(string text)
		{
			return text.TrimStart().StartsWith("/", StringComparison.Ordinal);
		}

		internal static string Plain(string s)
		{
			return TagLike.Replace(StripModelControls(s), delegate(Match tag)
			{
				string value = tag.Groups["name"].Value;
				if (value.StartsWith("#", StringComparison.Ordinal) || TmpTags.Contains(value))
				{
					if (!value.Equals("br", StringComparison.OrdinalIgnoreCase))
					{
						return "";
					}
					return " ";
				}
				if (!TagName.IsMatch(value))
				{
					return tag.Value;
				}
				return (tag.Groups["close"].Length <= 0) ? Inert(tag.Value) : "";
			}).Trim();
		}

		internal static string Inert(string text)
		{
			return MarkupStart.Replace(text, "<");
		}

		internal static string StripModelControls(string text)
		{
			if (!string.IsNullOrEmpty(text))
			{
				if (text.IndexOfAny(ControlPrefixes) >= 0)
				{
					return ModelControl.Replace(text, " ").Trim();
				}
				return text.Trim();
			}
			return "";
		}

		internal static bool ContainsModelControl(string text)
		{
			return ModelControl.IsMatch(text);
		}

		internal static bool KnownPhrase(string text, string language)
		{
			return Phrases.ContainsKey(language + "|" + Key(text));
		}

		internal static string Phrase(string s, string src, string trg)
		{
			if (!Phrases.TryGetValue(src + "|" + Key(s), out var value) || value[src] != s)
			{
				return null;
			}
			if (!value.TryGetValue(trg, out var value2))
			{
				return null;
			}
			return value2;
		}

		private static string Key(string s)
		{
			return s.Trim().ToLowerInvariant();
		}

		internal static bool NeutralText(string s, string target = null)
		{
			MatchEvaluator evaluator = (Match m) => (!Keep(m.Value, target)) ? m.Value : " ";
			return !HasLetters(AloneTerms.Replace(Protected.Replace(s, evaluator), evaluator));
		}

		private static bool Keep(string token, string target)
		{
			if (!Shorthand.TryGetValue(token, out var value))
			{
				return true;
			}
			if (!value.Contains("*"))
			{
				return value.Contains(target);
			}
			return true;
		}

		private static bool HasLetters(string words)
		{
			for (int i = 0; i < words.Length; i++)
			{
				if (char.IsLetter(words, i))
				{
					return true;
				}
			}
			return false;
		}

		internal static bool FunctionWord(string word, string language)
		{
			if (FunctionWords.TryGetValue(language, out var value))
			{
				return value.Contains(word);
			}
			return false;
		}

		internal static string SpellOut(string text)
		{
			return SlangTerms.Replace(text, (Match m) => PlainWords[m.Value]);
		}

		internal static string Context(string text)
		{
			string[] array = (from m in HintTerms.Matches(text)
				select "\"" + m.Value + "\" means " + Hints[m.Value]).Distinct<string>(StringComparer.OrdinalIgnoreCase).ToArray();
			List<string> list = new List<string>();
			if (array.Length != 0)
			{
				list.Add("Meanings in this game, for understanding only (translate the meaning in natural target-language gamer words; never output these notes): " + string.Join("; ", array) + ".");
			}
			if (KeyboardKeys.In(text).Any())
			{
				list.Add("This is a keyboard callout. Use the keyboard sense of press, hold or release.");
			}
			return string.Join(" ", list);
		}

		private static string Marker(int index)
		{
			return "ZXQ" + index + "QXZ";
		}

		private static string Words(IEnumerable<string> terms)
		{
			return "(?<![\\p{L}\\p{N}_])(?:" + string.Join("|", (from s in terms.Distinct<string>(StringComparer.OrdinalIgnoreCase)
				orderby s.Length descending
				select s).Select(Regex.Escape)) + ")(?![\\p{L}\\p{N}_])";
		}
	}
	internal static class KeyboardKeys
	{
		private static readonly HashSet<string> Names;

		private static readonly Regex Keys;

		private static readonly Regex Cue;

		static KeyboardKeys()
		{
			Names = new HashSet<string>(new string[15]
			{
				"Enter", "Return", "Space", "Spacebar", "Space bar", "Shift", "Ctrl", "Control", "Alt", "Tab",
				"Esc", "Escape", "Backspace", "Delete", "Del"
			}, StringComparer.OrdinalIgnoreCase);
			Cue = new Regex("(?:\\b(?:press|hold|tap|hit|release|push|key|touche|taste|tecla|клавишу|кнопку|appuie|appuyez|presse|drück|drücke|presiona|pulsa|aperte|premi|naciśnij|wciśnij|нажми|нажмите|жми|зажми|натисни)(?:\\s+(?:down|the|sur|la|touche|die|taste|tecla|на|кнопку|клавишу))*\\s+|按(?:下|住)?)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
			string text = "(?:" + string.Join("|", Names.OrderByDescending((string x) => x.Length).Select(Regex.Escape)) + "|F(?:2[0-4]|1\\d|[1-9])|WASD|ZQSD|[A-Z0-9])";
			Keys = new Regex("(?<![a-z0-9_])" + text + "(?:\\s*\\+\\s*" + text + ")*(?![a-z0-9_])", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
		}

		internal static bool Standalone(string text)
		{
			string text2 = text.Trim();
			if (text2.Length == 0 || text2.Length > 48)
			{
				return false;
			}
			int num = ((text2.Length > 2 && text2[0] == '[' && text2[text2.Length - 1] == ']') ? 1 : 0);
			int num2 = text2.Length - 2 * num;
			Match match = Keys.Match(text2, num, num2);
			if (match.Success && match.Index == num && match.Length == num2)
			{
				return IsKey(text2, match);
			}
			return false;
		}

		internal static IEnumerable<Match> In(string text)
		{
			foreach (Match item in Keys.Matches(text))
			{
				if (IsKey(text, item))
				{
					yield return item;
				}
			}
		}

		private static bool IsKey(string text, Match match)
		{
			string value = match.Value;
			int index = match.Index;
			int num = index + match.Length;
			if ((index > 0 && char.IsLetterOrDigit(text[index - 1]) && !IsHan(text[index - 1])) || (num < text.Length && char.IsLetterOrDigit(text[num]) && !IsHan(text[num])))
			{
				return false;
			}
			if (value.Contains('+'))
			{
				return value.Any(char.IsLetter);
			}
			if (index > 0 && num < text.Length && text[index - 1] == '[' && text[num] == ']')
			{
				return true;
			}
			if (value.Length > 1 && ((char.ToUpperInvariant(value[0]) == 'F' && char.IsDigit(value[1])) || value.Equals("WASD", StringComparison.OrdinalIgnoreCase) || value.Equals("ZQSD", StringComparison.OrdinalIgnoreCase)))
			{
				return true;
			}
			if (index == 0 && num == text.Length && Names.Contains(value))
			{
				if (!char.IsUpper(value[0]))
				{
					switch (value)
					{
					default:
						return value == "tab";
					case "enter":
					case "esc":
					case "ctrl":
						break;
					}
				}
				return true;
			}
			if (index > 0 && (value != "a" || num == text.Length))
			{
				return Cue.IsMatch(text.Substring(0, index));
			}
			return false;
		}

		private static bool IsHan(char c)
		{
			return Scripts.Of(c) == Script.Han;
		}
	}
	internal sealed class LanguageHistory
	{
		internal const int Certain = 3;

		internal const int Vote = 2;

		internal const int Heard = 1;

		private const int MostHeard = 2;

		private const int Kept = 8;

		private readonly Dictionary<ulong, Queue<(string Language, int Points)>> players = new Dictionary<ulong, Queue<(string, int)>>();

		internal void Observe(ulong player, string language, int points)
		{
			if (language != null)
			{
				if (!players.TryGetValue(player, out Queue<(string, int)> value))
				{
					players.Add(player, value = new Queue<(string, int)>(8));
				}
				if (value.Count == 8)
				{
					value.Dequeue();
				}
				value.Enqueue((language, points));
			}
		}

		internal string ForPlayer(ulong player, string named = null)
		{
			Queue<(string, int)> value;
			List<(string, int)> list = (players.TryGetValue(player, out value) ? value.ToList() : new List<(string, int)>());
			if (named != null)
			{
				list.Add((named, 1));
			}
			List<(string, int)> list2 = (from clue in list
				group clue by clue.Language into @group
				select (Language: @group.Key, Points: @group.Where(((string Language, int Points) clue) => clue.Points > 1).Sum(((string Language, int Points) clue) => clue.Points) + Math.Min(2, @group.Count(((string Language, int Points) clue) => clue.Points == 1))) into language
				orderby language.Points descending
				select language).ToList();
			if (list2.Count == 0)
			{
				return null;
			}
			int num = ((list2.Count > 1) ? list2[1].Item2 : 0);
			if (list2[0].Item2 < 3 || list2[0].Item2 < 2 * num)
			{
				return null;
			}
			return list2[0].Item1;
		}

		internal void Clear()
		{
			players.Clear();
		}
	}
	internal sealed class RecentChat
	{
		private struct Line
		{
			internal ulong Sender;

			internal string Original;

			internal float At;
		}

		private readonly Queue<Line> lines = new Queue<Line>(3);

		internal void Add(ulong sender, string original, float now)
		{
			if (lines.Count == 3)
			{
				lines.Dequeue();
			}
			lines.Enqueue(new Line
			{
				Sender = sender,
				Original = original,
				At = now
			});
		}

		internal string[] Snapshot(float now, Func<ulong, bool> visible)
		{
			return (from line in lines
				where now - line.At <= 20f && line.Original.Length > 0 && line.Original.Length <= 96 && visible(line.Sender)
				select line.Original).ToArray();
		}

		internal void Clear()
		{
			lines.Clear();
		}
	}
	internal sealed class Recipient
	{
		internal readonly ulong Id;

		internal readonly string Name;

		internal readonly string Language;

		internal readonly string Named;

		internal Recipient(ulong id, string name, string language, string named = null)
		{
			Id = id;
			Name = name ?? "";
			Language = language;
			Named = named;
		}
	}
	internal sealed class OutgoingLanguage
	{
		private static readonly Regex Token = new Regex("[\\p{L}\\p{M}\\p{N}_-]+");

		internal string LobbyTarget { get; private set; }

		internal void Update(List<Recipient> peers, string source, string title)
		{
			List<IGrouping<string, Recipient>> list = (from p in peers
				where p.Language != null && p.Language != source
				group p by p.Language).ToList();
			int most = ((list.Count != 0) ? list.Max((IGrouping<string, Recipient> group) => group.Count()) : 0);
			List<string> list2 = (from @group in list
				where @group.Count() == most
				select @group.Key).ToList();
			if (list2.Count == 1)
			{
				LobbyTarget = list2[0];
				return;
			}
			if (list2.Count > 1)
			{
				LobbyTarget = (list2.Contains(LobbyTarget) ? LobbyTarget : (list2.Contains(title) ? title : source));
				return;
			}
			LobbyTarget = (peers.Any((Recipient p) => p.Language == source) ? source : (title ?? NamedByMost(peers) ?? source));
		}

		private static string NamedByMost(List<Recipient> peers)
		{
			return (from p in peers
				where p.Named != null
				group p by p.Named).FirstOrDefault((IGrouping<string, Recipient> group) => group.Count() * 2 > peers.Count)?.Key;
		}

		internal void Clear()
		{
			LobbyTarget = null;
		}

		internal static string Consensus(List<Recipient> peers, ulong sender, Func<ulong, bool> visible)
		{
			List<string> list = (from p in peers
				where p.Id != sender && p.Language != null && visible(p.Id)
				select p.Language).ToList();
			if (list.Count < 2 || list.Distinct().Count() != 1)
			{
				return null;
			}
			return list[0];
		}

		internal static Recipient Mention(string text, List<Recipient> peers)
		{
			Recipient recipient = null;
			int num = 0;
			foreach (Match item in Token.Matches(text))
			{
				if (item.Index < num)
				{
					continue;
				}
				Recipient recipient2 = null;
				int num2 = 0;
				foreach (Recipient peer in peers)
				{
					int num3 = MatchName(text, item, peer.Name);
					if (num3 > num2)
					{
						recipient2 = peer;
						num2 = num3;
					}
					else if (num3 == num2)
					{
						recipient2 = null;
					}
				}
				if (num2 != 0)
				{
					if (recipient2 == null || (recipient != null && recipient.Id != recipient2.Id))
					{
						return null;
					}
					recipient = recipient2;
					if (num2 >= 3)
					{
						num = item.Index + recipient2.Name.Length;
					}
				}
			}
			return recipient;
		}

		private static int MatchName(string text, Match token, string name)
		{
			int num = token.Index + name.Length;
			if (name.Length >= 2 && num <= text.Length && name.Length >= token.Length && string.Compare(text, token.Index, name, 0, name.Length, StringComparison.OrdinalIgnoreCase) == 0 && (num == text.Length || (!char.IsLetterOrDigit(text[num]) && text[num] != '_' && text[num] != '-')))
			{
				return 3 + name.Length;
			}
			if (token.Length < 4 || !token.Value.Any(char.IsLetter))
			{
				return 0;
			}
			if (name.Contains(token.Value, StringComparison.OrdinalIgnoreCase))
			{
				return 2;
			}
			if (token.Length < 5 || !ChatText.OneEdit(token.Value, name))
			{
				return 0;
			}
			return 1;
		}
	}
	internal sealed class SubmissionReplay
	{
		private object activeField;

		private string wire;

		internal bool Active => activeField != null;

		internal string Read(object field, string draft)
		{
			if (field != activeField)
			{
				return draft;
			}
			return wire;
		}

		internal static bool Send(string filtered, string original, bool translated, Func<string, bool> send, Func<string, string> filter)
		{
			if ((!translated || filtered.Length <= 500) && send(filtered))
			{
				return true;
			}
			if (!translated)
			{
				return false;
			}
			string text = filter(original);
			if (text != filtered)
			{
				return send(text);
			}
			return false;
		}

		internal void Submit(object field, string original, string formatted, Func<string> getDraft, Action<string> setDraft, Action submit, Action<string> keepDraft = null)
		{
			string text = getDraft();
			activeField = field;
			wire = formatted;
			try
			{
				setDraft(original);
				submit();
				if (text.Length == 0)
				{
					text = getDraft();
				}
				else if (getDraft() == original)
				{
					keepDraft?.Invoke(original);
				}
			}
			catch
			{
				if (text.Length == 0)
				{
					text = original;
				}
				else
				{
					keepDraft?.Invoke(original);
				}
				throw;
			}
			finally
			{
				activeField = null;
				wire = null;
				if (getDraft() != text)
				{
					setDraft(text);
				}
			}
		}
	}
	internal static class Languages
	{
		internal const string Auto = "Auto";

		private static readonly string[][] Rows = (from row in ChatText.Lines("model-languages.tsv").Skip(1)
			select row.Split('\t')).ToArray();

		private static readonly Dictionary<string, string> Names = Rows.ToDictionary((string[] row) => row[0], (string[] row) => row[1]);

		private static readonly Dictionary<string, string> Codes = Rows.ToDictionary<string[], string, string>((string[] row) => row[1], (string[] row) => row[0], StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, string> Labels = Rows.ToDictionary((string[] row) => row[0], (string[] row) => (row.Length <= 3 || row[3].Length <= 0) ? row[1] : (row[1] + " (" + row[3] + ")"));

		internal static readonly string[] Selectable = (from row in Rows
			where row[2] != "unreadable"
			select row[0]).ToArray();

		internal static string Name(string code)
		{
			if (code == null || !Names.TryGetValue(code, out var value))
			{
				return code;
			}
			return value;
		}

		internal static string Short(string code)
		{
			if (code == null)
			{
				return null;
			}
			return code.Split('-')[0];
		}

		internal static bool Known(string code)
		{
			if (code != null)
			{
				return Names.ContainsKey(code);
			}
			return false;
		}

		internal static string Label(string code)
		{
			if (code != null && Labels.TryGetValue(code, out var value))
			{
				return value;
			}
			return null;
		}

		internal static string[] ForModel(string id)
		{
			return (from row in Rows
				where row[2].Split(' ').Contains(id)
				select row[0]).ToArray();
		}

		internal static string Code(string value)
		{
			if (string.IsNullOrWhiteSpace(value))
			{
				return null;
			}
			value = value.Trim();
			string text = value.ToLowerInvariant();
			switch (text)
			{
			case "zh-hans":
			case "zh-cn":
				return "zh";
			case "zh-hant-tw":
				return "zh-hant";
			default:
			{
				if (Names.ContainsKey(text))
				{
					return text;
				}
				if (Codes.TryGetValue(value, out var value2))
				{
					return value2;
				}
				string text2 = (from n in Codes.Keys
					where value.StartsWith(n + " ", StringComparison.OrdinalIgnoreCase)
					orderby n.Length descending
					select n).FirstOrDefault();
				if (text2 != null)
				{
					return Codes[text2];
				}
				return null;
			}
			}
		}

		internal static string Selection(string value, string[] supported)
		{
			string text = Code(value);
			if (!supported.Contains(text))
			{
				return "Auto";
			}
			return Label(text);
		}

		internal static string LocalDefault(string locale, string[] supported)
		{
			string text = (locale ?? "").Replace('_', '-').ToLowerInvariant();
			switch (text)
			{
			default:
				if (!text.StartsWith("zh-hant", StringComparison.Ordinal))
				{
					break;
				}
				goto case "zh-tw";
			case "zh-tw":
			case "zh-hk":
			case "zh-mo":
				text = "zh-hant";
				break;
			}
			if (supported.Contains(text))
			{
				return text;
			}
			string text2 = text.Split('-')[0];
			if (text2 == "nb")
			{
				text2 = "no";
			}
			if (text2 == "fil")
			{
				text2 = "tl";
			}
			if (!supported.Contains(text2))
			{
				return "en";
			}
			return text2;
		}
	}
	internal enum Script
	{
		Other,
		Latin,
		Phonetic,
		Greek,
		Cyrillic,
		CyrillicExtended,
		Armenian,
		Hebrew,
		Arabic,
		Devanagari,
		Bengali,
		Indic,
		Thai,
		Jamo,
		Hangul,
		Kana,
		Han
	}
	internal static class Scripts
	{
		internal static Script Of(char c)
		{
			if (c >= 'ɐ')
			{
				if (c >= 'Ͱ')
				{
					if (c >= 'Ѐ')
					{
						if (c >= 'Ԁ')
						{
							if (c >= '\u0530')
							{
								if (c >= '\u0590')
								{
									if (c >= '\u0600')
									{
										if (c >= '܀')
										{
											if (c >= '\u0900')
											{
												if (c >= 'ঀ')
												{
													if (c >= '\u0a00')
													{
														if (c >= '\u0e00')
														{
															if (c >= '\u0e80')
															{
																if (c < 'ᄀ' || c >= 'ሀ')
																{
																	if (c < 'Ḁ' || c >= 'ἀ')
																	{
																		if (c < '\u3040' || c >= '\u3100')
																		{
																			if (c < '㐀' || c >= 'ꀀ')
																			{
																				if (c < '가' || c >= 'ힰ')
																				{
																					return Script.Other;
																				}
																				return Script.Hangul;
																			}
																			return Script.Han;
																		}
																		return Script.Kana;
																	}
																	return Script.Latin;
																}
																return Script.Jamo;
															}
															return Script.Thai;
														}
														return Script.Indic;
													}
													return Script.Bengali;
												}
												return Script.Devanagari;
											}
											return Script.Other;
										}
										return Script.Arabic;
									}
									return Script.Hebrew;
								}
								return Script.Armenian;
							}
							return Script.CyrillicExtended;
						}
						return Script.Cyrillic;
					}
					return Script.Greek;
				}
				return Script.Phonetic;
			}
			return Script.Latin;
		}

		internal static HashSet<Script> In(string text)
		{
			return new HashSet<Script>(text.Where(char.IsLetter).Select(Of));
		}

		internal static bool Has(string text, Script script)
		{
			foreach (char c in text)
			{
				if (Of(c) == script && char.IsLetter(c))
				{
					return true;
				}
			}
			return false;
		}

		internal static Script Family(Script script)
		{
			switch (script)
			{
			case Script.CyrillicExtended:
				return Script.Cyrillic;
			case Script.Jamo:
				return Script.Hangul;
			case Script.Devanagari:
			case Script.Bengali:
				return Script.Indic;
			default:
				return script;
			}
		}

		internal static IEnumerable<Script> Families(string text)
		{
			return In(text).Select(Family).Distinct();
		}

		internal static Script[] Of(string language)
		{
			string text = Languages.Short(language);
			if (text != null)
			{
				if (text != null)
				{
					int length = text.Length;
					if (length != 2)
					{
						if (length == 3 && text == "yue")
						{
							goto IL_0296;
						}
					}
					else
					{
						switch (text[0])
						{
						case 'e':
							if (!(text == "el"))
							{
								goto IL_02a2;
							}
							return new Script[1] { Script.Greek };
						case 'r':
							if (text == "ru")
							{
								goto IL_022c;
							}
							goto IL_02a2;
						case 'u':
							switch (text)
							{
							case "uk":
								break;
							case "ur":
							case "ug":
								goto IL_0251;
							default:
								goto IL_02a2;
							}
							goto IL_022c;
						case 'b':
							if (text == "bg")
							{
								goto IL_022c;
							}
							if (text == "bn")
							{
								goto IL_025c;
							}
							goto IL_02a2;
						case 'k':
							if (text == "kk")
							{
								goto IL_022c;
							}
							if (!(text == "ko"))
							{
								goto IL_02a2;
							}
							return new Script[2]
							{
								Script.Hangul,
								Script.Han
							};
						case 'm':
							if (text == "mn")
							{
								goto IL_022c;
							}
							if (text == "mr")
							{
								goto IL_025c;
							}
							goto IL_02a2;
						case 's':
							if (!(text == "sr"))
							{
								goto IL_02a2;
							}
							return new Script[2]
							{
								Script.Latin,
								Script.Cyrillic
							};
						case 'h':
							if (!(text == "he"))
							{
								if (text == "hi")
								{
									goto IL_025c;
								}
								goto IL_02a2;
							}
							return new Script[1] { Script.Hebrew };
						case 'a':
							if (text == "ar")
							{
								goto IL_0251;
							}
							goto IL_02a2;
						case 'f':
							if (text == "fa")
							{
								goto IL_0251;
							}
							goto IL_02a2;
						case 't':
							if (!(text == "th"))
							{
								goto IL_02a2;
							}
							return new Script[1] { Script.Thai };
						case 'j':
							if (!(text == "ja"))
							{
								goto IL_02a2;
							}
							return new Script[2]
							{
								Script.Kana,
								Script.Han
							};
						case 'z':
							break;
						default:
							goto IL_02a2;
							IL_022c:
							return new Script[1] { Script.Cyrillic };
							IL_025c:
							return new Script[1] { Script.Indic };
							IL_0251:
							return new Script[1] { Script.Arabic };
						}
						if (text == "zh")
						{
							goto IL_0296;
						}
					}
				}
				goto IL_02a2;
			}
			return null;
			IL_02a2:
			return new Script[2]
			{
				Script.Latin,
				Script.Phonetic
			};
			IL_0296:
			return new Script[1] { Script.Han };
		}

		internal static bool Latin(string language)
		{
			return Of(language)?.All((Script script) => script == Script.Latin || script == Script.Phonetic) ?? false;
		}
	}
	internal static class Headroom
	{
		private struct MemoryStatus
		{
			internal uint Length;

			internal uint Load;

			internal ulong TotalPhys;

			internal ulong AvailPhys;

			internal ulong TotalPageFile;

			internal ulong AvailPageFile;

			internal ulong TotalVirtual;

			internal ulong AvailVirtual;

			internal ulong AvailExtendedVirtual;
		}

		private const long GB = 1073741824L;

		internal const long DiskMargin = 1073741824L;

		internal const long ServerOverhead = 629145600L;

		internal static long MemoryFor(ModelChoice model, bool hearing)
		{
			return model.Bytes + ((hearing && model.SupportsVoice) ? model.ProjectorBytes : 0) + 629145600;
		}

		internal static long? FreeDisk(string folder)
		{
			try
			{
				string path = Path.GetFullPath(folder);
				StringComparison comparison = (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
				return (from d in DriveInfo.GetDrives()
					where d.IsReady && path.StartsWith(d.RootDirectory.FullName, comparison)
					orderby d.RootDirectory.FullName.Length descending
					select d).FirstOrDefault()?.AvailableFreeSpace;
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is ArgumentException)
			{
				return null;
			}
		}

		internal static long? FreeMemory()
		{
			try
			{
				if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
				{
					return WindowsFree();
				}
				if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
				{
					return MacFree();
				}
				if (File.Exists("/proc/meminfo"))
				{
					return LinuxFree(File.ReadAllLines("/proc/meminfo"));
				}
			}
			catch (Exception ex) when (!(ex is OutOfMemoryException))
			{
			}
			return null;
		}

		internal static long? LinuxFree(string[] meminfo)
		{
			string[] array = meminfo.FirstOrDefault((string l) => l.StartsWith("MemAvailable:", StringComparison.Ordinal))?.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
			if (array == null || array.Length < 2 || !long.TryParse(array[1], out var result))
			{
				return null;
			}
			return result * 1024;
		}

		private static long? MacFree()
		{
			using Process process = Process.Start(new ProcessStartInfo("/usr/sbin/sysctl", "-n kern.memorystatus_level hw.memsize")
			{
				UseShellExecute = false,
				RedirectStandardOutput = true,
				CreateNoWindow = true
			});
			string sysctl = process.StandardOutput.ReadToEnd();
			if (!process.WaitForExit(2000))
			{
				return null;
			}
			return MacFree(sysctl);
		}

		internal static long? MacFree(string sysctl)
		{
			string[] array = sysctl.Split(new char[1] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
			if (array.Length < 2 || !int.TryParse(array[0].Trim(), out var result) || !long.TryParse(array[1].Trim(), out var result2) || result < 0 || result > 100)
			{
				return null;
			}
			return result2 / 100 * result;
		}

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool GlobalMemoryStatusEx(ref MemoryStatus status);

		private static long? WindowsFree()
		{
			MemoryStatus status = new MemoryStatus
			{
				Length = (uint)Marshal.SizeOf(typeof(MemoryStatus))
			};
			if (!GlobalMemoryStatusEx(ref status))
			{
				return null;
			}
			return (long)status.AvailPhys;
		}

		internal static string Size(long bytes)
		{
			if (bytes < 1000000000)
			{
				if (bytes < 1000000)
				{
					if (bytes < 1000)
					{
						return bytes + " B";
					}
					return Format((double)bytes / 1000.0, "KB");
				}
				return Format((double)bytes / 1000000.0, "MB");
			}
			return Format((double)bytes / 1000000000.0, "GB");
		}

		private static string Format(double value, string unit)
		{
			return value.ToString("0.0", CultureInfo.InvariantCulture) + " " + unit;
		}
	}
	internal sealed class ShortOfSpaceException : IOException
	{
		internal ShortOfSpaceException(string message)
			: base(message)
		{
		}
	}
	internal sealed class ShortOfMemoryException : Exception
	{
		internal readonly bool FitsWithoutVoice;

		internal ShortOfMemoryException(string message, bool fitsWithoutVoice)
			: base(message)
		{
			FitsWithoutVoice = fitsWithoutVoice;
		}
	}
	internal sealed class LocalModel : IDisposable
	{
		private sealed class MetalStartupException : IOException
		{
			internal MetalStartupException(string message)
				: base(message)
			{
			}
		}

		private const string Release = "b12774";

		internal readonly ModelChoice Choice;

		private readonly CancellationTokenSource stop = new CancellationTokenSource();

		private readonly string cache;

		private readonly string platform;

		private readonly Action<string> log;

		internal readonly string Key = Guid.NewGuid().ToString("N");

		internal volatile Uri Endpoint;

		internal const string Ready = "Local model ready";

		private const string Downloading = "Downloading translation model ";

		private const string DownloadingVoice = "Downloading voice model ";

		private const string Loading = "Loading translator";

		private const string Starting = "Starting translator";

		private const string SettingUp = "Preparing translator";

		private const string GpuFailed = "GPU failed, using CPU (slower)";

		internal const string NoInternet = "Download failed: check internet";

		internal const string NoDisk = "Disk full: free space or pick a smaller Model";

		internal const string NoStart = "Translator won't start: pick a smaller Model";

		internal const string NoOpenSsl = "Translator needs OpenSSL 3: install libssl3";

		internal const string Restarting = "Translator stopped, restarting";

		internal const string NoMemory = "Not enough memory: pick a smaller Model";

		internal const string NoMemoryVoice = "Not enough memory: turn off Voice captions";

		internal const string NoMemorySmallest = "Not enough memory: close other apps";

		internal const string NotDownloaded = "Model not downloaded: turn on Autodownload models";

		internal const string VoiceNotDownloaded = "Voice model not downloaded: turn on Autodownload models";

		private volatile bool openSslMissing;

		internal volatile string Status = "Starting translator";

		internal volatile string Backend;

		internal volatile string Warning;

		private readonly bool cpuPicked;

		private readonly Action<string> warn;

		private readonly Task previous;

		private bool mayDownload;

		internal volatile bool Installed;

		internal volatile bool Removed;

		internal volatile bool VoiceEnabled;

		internal volatile bool VoiceMissing;

		private readonly bool autoDownload;

		private readonly Queue<string> serverErrors = new Queue<string>();

		private Process running;

		private static readonly string[] ServerProblems = new string[3] { "error", "fail", "out of memory" };

		private static readonly Regex OffloadedLayers = new Regex("offloaded\\s+([0-9]+)\\s*/\\s*[0-9]+\\s+layers?\\s+to\\s+GPU\\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

		private const string Manifest = "files.txt";

		private static readonly string[] OpenSsl = new string[2] { "libssl.so.3", "libcrypto.so.3" };

		private static readonly string[] ServerNames = new string[2] { "llama-server", "llama" };

		internal Task Stopped { get; }

		internal static string HudText(string status, int ms, string backend, bool timedOut = false, string warning = null)
		{
			if (status != null && status != "Local model ready")
			{
				if (!Progress(status))
				{
					return Red(status);
				}
				return status;
			}
			string text = ((ms < 0) ? "" : ("<size=90%>" + (timedOut ? ("<color=#FF4949>" + ms + "ms</color>") : (ms + "ms")) + ((backend == null || warning != null) ? "" : (" " + backend)) + "</size>"));
			if (warning != null)
			{
				if (text.Length != 0)
				{
					return Red(warning) + "  " + text;
				}
				return Red(warning);
			}
			return text;
		}

		private static string Red(string text)
		{
			return "<color=#FF4949>" + text + "</color>";
		}

		private static bool Progress(string status)
		{
			switch (status)
			{
			default:
				if (!status.StartsWith("Downloading translation model ", StringComparison.Ordinal))
				{
					return status.StartsWith("Downloading voice model ", StringComparison.Ordinal);
				}
				break;
			case "Starting translator":
			case "Preparing translator":
			case "Loading translator":
				break;
			}
			return true;
		}

		internal LocalModel(string folder, string platformKey, Action<string> report, ModelChoice choice = null, bool cpuOnly = false, Action<string> warning = null, bool installedBefore = false, bool hear = false, Task previous = null, bool autoDownload = true)
		{
			this.autoDownload = autoDownload;
			this.previous = previous ?? Task.CompletedTask;
			Choice = choice ?? ModelChoice.Available[0];
			VoiceEnabled = hear && Choice.SupportsVoice;
			cpuPicked = cpuOnly;
			mayDownload = !installedBefore || Choice == ModelChoice.Available[0];
			cache = folder;
			platform = platformKey;
			log = report;
			warn = warning ?? report;
			Stopped = Task.Run((Func<Task?>)Supervise);
		}

		private void NoteServerLine(string line)
		{
			if (line == null || !ServerProblems.Any((string word) => line.Contains(word, StringComparison.OrdinalIgnoreCase)))
			{
				return;
			}
			lock (serverErrors)
			{
				if (serverErrors.Count == 6)
				{
					serverErrors.Dequeue();
				}
				serverErrors.Enqueue(line.Trim());
			}
		}

		private string ServerErrors()
		{
			lock (serverErrors)
			{
				string result = ((serverErrors.Count == 0) ? "" : (" llama.cpp: " + string.Join(" | ", serverErrors)));
				serverErrors.Clear();
				return result;
			}
		}

		internal static string RuntimeHash(string platform)
		{
			return platform switch
			{
				"macos-arm64" => "70311c4751ed3221e63f47769327dd088d7400f76dcfb81c66ec843db165814d", 
				"macos-x64" => "0368e3dbdae70065a928c130aa235efc84090bb7817c3267998f00df4e6ed862", 
				"ubuntu-arm64" => "068e15b27cfaf2733855c313baad26fbce84952cbb770500e806073c41aa4214", 
				"ubuntu-x64" => "ab5837cca2317cfb7ecb5f85b550934e7355cd9df74cdde6e106581457034dbb", 
				"win-cpu-arm64" => "0ba8524390eee562ce196a5a901ea26cc4af1ea539b932fef0e91f4a5f7c8b3c", 
				"win-cpu-x64" => "44b70b20f3374eec3d16a002beceefef33cc3565678caeb3eea5f6cacba61836", 
				"win-vulkan-x64" => "d29a16265d26ef7598209caaf1a544cbfa6abe2858c24b0ce4ae6bff87a76f22", 
				"win-vulkan-arm64" => "f361ee4fe49562933b2b795519bc39174eebcb2b4cf61f4ad0cc5fb42abe9e53", 
				"ubuntu-vulkan-x64" => "75b7044df1232bd5bc78ffc753f14a5a44d9f3b5c67228b6103705c57084d02d", 
				"ubuntu-vulkan-arm64" => "e5023727501802ee7692396cf2a018790bb2f0acf989d8c8964bb44ea2b25c7b", 
				_ => throw new PlatformNotSupportedException(platform), 
			};
		}

		internal static string VulkanRuntime(string cpuRuntime)
		{
			return cpuRuntime switch
			{
				"win-cpu-x64" => "win-vulkan-x64", 
				"win-cpu-arm64" => "win-vulkan-arm64", 
				"ubuntu-x64" => "ubuntu-vulkan-x64", 
				"ubuntu-arm64" => "ubuntu-vulkan-arm64", 
				_ => null, 
			};
		}

		internal static string RuntimeKey(string platform, Architecture osArchitecture)
		{
			return platform + "-" + osArchitecture.ToString().ToLowerInvariant();
		}

		internal static int CpuThreads(int processors)
		{
			return Math.Max(2, Math.Min(4, processors / 4));
		}

		internal static string BackendArguments(string runtime, string platform, bool cpuOnly)
		{
			if (!cpuOnly && runtime == VulkanRuntime(platform))
			{
				return " --device Vulkan0 --gpu-layers auto";
			}
			if (!cpuOnly && runtime.StartsWith("macos-", StringComparison.Ordinal))
			{
				return " --device MTL0 --gpu-layers auto";
			}
			if (!cpuOnly && VulkanRuntime(platform) == null)
			{
				return "";
			}
			return " --device none --gpu-layers 0";
		}

		internal static async Task TryVulkan(string cpuRuntime, Func<string, Task> run, Action<Exception> fallback, CancellationToken token)
		{
			string text = VulkanRuntime(cpuRuntime);
			if (text == null)
			{
				return;
			}
			try
			{
				await run(text).ConfigureAwait(continueOnCapturedContext: false);
			}
			catch (Exception ex) when (!token.IsCancellationRequested && !(ex is ShortOfMemoryException))
			{
				fallback(ex);
			}
		}

		private async Task Supervise()
		{
			CancellationToken token = stop.Token;
			await Task.WhenAny(new Task[2]
			{
				previous,
				Task.Delay(-1, token)
			}).ConfigureAwait(continueOnCapturedContext: false);
			if (token.IsCancellationRequested)
			{
				return;
			}
			ServerTether.Sweep(cache, log);
			RemoveLeftovers(cache);
			HttpClient download = new HttpClient
			{
				Timeout = TimeSpan.FromMinutes(45.0)
			};
			try
			{
				HttpClient loopback = new HttpClient(new HttpClientHandler
				{
					UseProxy = false,
					AllowAutoRedirect = false
				})
				{
					Timeout = TimeSpan.FromSeconds(2.0)
				};
				try
				{
					loopback.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Key);
					bool tryVulkan = !cpuPicked;
					bool vulkanFailed = false;
					bool modelVerified = false;
					bool cpuOnly = cpuPicked;
					while (!token.IsCancellationRequested)
					{
						try
						{
							Directory.CreateDirectory(cache);
							string text = Path.Combine(cache, Choice.FileName);
							if (modelVerified && (!File.Exists(text) || new FileInfo(text).Length != Choice.Bytes))
							{
								modelVerified = false;
							}
							if (modelVerified && VoiceEnabled && !File.Exists(Path.Combine(cache, Choice.ProjectorFile)))
							{
								modelVerified = false;
							}
							if (!modelVerified)
							{
								if (!autoDownload && !File.Exists(text))
								{
									log(Choice.FileName + " is not downloaded and Autodownload models is off.");
									Status = "Model not downloaded: turn on Autodownload models";
									break;
								}
								if (!mayDownload && !File.Exists(text))
								{
									warn(Choice.FileName + " was deleted. It downloads again only if the model is picked again.");
									Removed = true;
									break;
								}
								if (File.Exists(text))
								{
									Status = "Starting translator";
								}
								bool flag = !Verified(text, Choice.Hash, token);
								string projectorFile = (VoiceEnabled ? Path.Combine(cache, Choice.ProjectorFile) : null);
								if (flag && !autoDownload)
								{
									log(Choice.FileName + " failed verification and Autodownload models is off.");
									Status = "Model not downloaded: turn on Autodownload models";
									break;
								}
								bool projectorNeeded = VoiceEnabled && !Verified(projectorFile, Choice.ProjectorHash, token);
								if (projectorNeeded && !autoDownload)
								{
									log(Choice.ProjectorFile + " is not downloaded and Autodownload models is off. Voice captions are off.");
									VoiceEnabled = false;
									VoiceMissing = true;
									projectorNeeded = false;
									if (Warning == null)
									{
										Warning = "Voice model not downloaded: turn on Autodownload models";
									}
								}
								CheckDisk((flag ? Choice.Bytes : 0) + (projectorNeeded ? Choice.ProjectorBytes : 0));
								if (flag)
								{
									log("Downloading " + Choice.FileName + " (" + Headroom.Size(Choice.Bytes) + ").");
									Status = "Downloading translation model 0%";
									await Download(download, Choice.Url, text, Choice.Hash, token, Choice.Bytes, delegate(int percent)
									{
										Status = "Downloading translation model " + percent + "%";
									}).ConfigureAwait(continueOnCapturedContext: false);
								}
								if (VoiceEnabled)
								{
									string file = projectorFile;
									if (projectorNeeded)
									{
										log("Downloading " + Choice.ProjectorFile + " (" + Headroom.Size(Choice.ProjectorBytes) + ") for voice captions.");
										Status = "Downloading voice model 0%";
										await Download(download, Choice.ProjectorUrl, file, Choice.ProjectorHash, token, Choice.ProjectorBytes, delegate(int percent)
										{
											Status = "Downloading voice model " + percent + "%";
										}).ConfigureAwait(continueOnCapturedContext: false);
									}
								}
								modelVerified = (Installed = true);
								mayDownload = Choice == ModelChoice.Available[0];
							}
							if (tryVulkan)
							{
								tryVulkan = false;
								await TryVulkan(platform, (string runtime) => RunServer(runtime, download, loopback, token), delegate(Exception error)
								{
									vulkanFailed = true;
									Warning = "GPU failed, using CPU (slower)";
									warn("Vulkan failed, using CPU: " + error.Message.TrimEnd('.') + "." + ServerErrors());
								}, token).ConfigureAwait(continueOnCapturedContext: false);
							}
							token.ThrowIfCancellationRequested();
							try
							{
								await RunServer(platform, download, loopback, token, cpuOnly).ConfigureAwait(continueOnCapturedContext: false);
							}
							catch (MetalStartupException ex) when (!cpuOnly && !token.IsCancellationRequested)
							{
								cpuOnly = true;
								Warning = "GPU failed, using CPU (slower)";
								warn("Metal failed, using CPU: " + ex.Message.TrimEnd('.') + "." + ServerErrors());
								continue;
							}
						}
						catch (OperationCanceledException) when (token.IsCancellationRequested)
						{
							break;
						}
						catch (ShortOfMemoryException ex3) when (!token.IsCancellationRequested)
						{
							tryVulkan = !cpuPicked && !vulkanFailed;
							Status = (ex3.FitsWithoutVoice ? "Not enough memory: turn off Voice captions" : (ModelChoice.Available.All((ModelChoice m) => m.Bytes >= Choice.Bytes) ? "Not enough memory: close other apps" : "Not enough memory: pick a smaller Model"));
							warn(ex3.Message + " Checking again in 15 s.");
							try
							{
								await Task.Delay(15000, token).ConfigureAwait(continueOnCapturedContext: false);
							}
							catch (OperationCanceledException)
							{
								break;
							}
							continue;
						}
						catch (Exception ex5) when (!token.IsCancellationRequested)
						{
							string status = ((modelVerified && !(Status == "Preparing translator")) ? ((Status == "Local model ready") ? "Translator stopped, restarting" : (openSslMissing ? "Translator needs OpenSSL 3: install libssl3" : "Translator won't start: pick a smaller Model")) : (DiskFull(ex5) ? "Disk full: free space or pick a smaller Model" : "Download failed: check internet"));
							string text2 = ((!modelVerified) ? "Model download" : ((Status == "Preparing translator") ? "Runtime setup" : ((Status == "Local model ready") ? "Model server" : "Model load")));
							Status = status;
							warn(text2 + " failed (" + ex5.GetType().Name + "): " + ex5.Message.TrimEnd('.') + ". Retrying in 60 s." + ServerErrors());
						}
						try
						{
							await Task.Delay(60000, token).ConfigureAwait(continueOnCapturedContext: false);
						}
						catch (OperationCanceledException)
						{
							break;
						}
					}
				}
				finally
				{
					if (loopback != null)
					{
						((IDisposable)loopback).Dispose();
					}
				}
			}
			finally
			{
				if (download != null)
				{
					((IDisposable)download).Dispose();
				}
			}
		}

		internal static int? GpuLayers(string line)
		{
			Match match = OffloadedLayers.Match(line ?? "");
			if (!match.Success || !int.TryParse(match.Groups[1].Value, out var result))
			{
				return null;
			}
			return result;
		}

		private async Task RunServer(string runtime, HttpClient download, HttpClient loopback, CancellationToken token, bool cpuOnly = false)
		{
			bool vulkan = runtime == VulkanRuntime(platform);
			bool metal = !cpuOnly && runtime.StartsWith("macos-", StringComparison.Ordinal);
			CheckMemory(vulkan);
			Status = "Preparing translator";
			string text;
			using (CancellationTokenSource install = CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken[1] { token }))
			{
				if (vulkan)
				{
					install.CancelAfter(TimeSpan.FromSeconds(60.0));
				}
				try
				{
					text = await InstallRuntime(download, runtime, install.Token).ConfigureAwait(continueOnCapturedContext: false);
				}
				catch (OperationCanceledException) when (vulkan && !token.IsCancellationRequested)
				{
					throw new TimeoutException("Vulkan runtime download did not finish within 60 seconds");
				}
			}
			Process server = null;
			try
			{
				token.ThrowIfCancellationRequested();
				int num = FreePort();
				string arguments = ((Path.GetFileNameWithoutExtension(text) == "llama") ? "serve " : "") + "--model \"" + Choice.FileName + "\" --alias strafchat --host 127.0.0.1 --port " + num + " --api-key " + Key + " --ctx-size 2048 --parallel 1 --threads " + ((vulkan || metal) ? 2 : CpuThreads(Environment.ProcessorCount)) + " --jinja --swa-full -lv 4" + (VoiceEnabled ? (" --mmproj \"" + Choice.ProjectorFile + "\"" + ((vulkan || metal) ? "" : " --no-mmproj-offload")) : "") + BackendArguments(runtime, platform, cpuOnly);
				Status = "Loading translator";
				ProcessStartInfo processStartInfo = new ProcessStartInfo(text, arguments)
				{
					WorkingDirectory = cache,
					UseShellExecute = false,
					CreateNoWindow = true,
					RedirectStandardOutput = true,
					RedirectStandardError = true
				};
				processStartInfo.EnvironmentVariables.Remove("LD_PRELOAD");
				if (runtime.StartsWith("ubuntu-", StringComparison.Ordinal))
				{
					string text2 = ProvideOpenSsl(Path.GetDirectoryName(text), runtime.EndsWith("arm64", StringComparison.Ordinal));
					openSslMissing = text2 != null;
					if (text2 != null)
					{
						warn(text2);
					}
				}
				TaskCompletionSource<int> offload = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
				TaskCompletionSource<bool> metalFailed = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
				server = new Process
				{
					StartInfo = processStartInfo
				};
				server.OutputDataReceived += delegate(object _, DataReceivedEventArgs line)
				{
					NoteServerLine(line.Data);
				};
				server.ErrorDataReceived += delegate(object _, DataReceivedEventArgs line)
				{
					NoteServerLine(line.Data);
				};
				if (vulkan || metal)
				{
					DataReceivedEventHandler value = delegate(object _, DataReceivedEventArgs line)
					{
						int? num2 = GpuLayers(line.Data);
						if (num2.HasValue)
						{
							offload.TrySetResult(num2.Value);
						}
						if (metal && line.Data != null && (line.Data.Contains("ggml_metal_init: error:", StringComparison.OrdinalIgnoreCase) || line.Data.Contains("ggml_backend_metal_device_init_backend: error:", StringComparison.OrdinalIgnoreCase)))
						{
							metalFailed.TrySetResult(result: true);
						}
					};
					server.OutputDataReceived += value;
					server.ErrorDataReceived += value;
				}
				if (!server.Start())
				{
					throw new IOException("Could not start llama.cpp");
				}
				running = server;
				ServerTether.Attach(server, cache, log);
				server.BeginOutputReadLine();
				server.BeginErrorReadLine();
				Uri root = new Uri("http://127.0.0.1:" + num);
				Stopwatch until = Stopwatch.StartNew();
				TimeSpan startupLimit = TimeSpan.FromMinutes(2.0);
				while (!server.HasExited && until.Elapsed < startupLimit)
				{
					token.ThrowIfCancellationRequested();
					try
					{
						using (HttpResponseMessage response = await loopback.GetAsync(new Uri(root, "/v1/models"), token).ConfigureAwait(continueOnCapturedContext: false))
						{
							if (response.IsSuccessStatusCode && !server.HasExited && (((IEnumerable<JToken>)JObject.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false))["data"])?.Any((JToken m) => (string)m[(object)"id"] == "strafchat") ?? false))
							{
								break;
							}
						}
						goto IL_06d5;
					}
					catch (HttpRequestException)
					{
						goto IL_06d5;
					}
					catch (OperationCanceledException) when (!token.IsCancellationRequested)
					{
						goto IL_06d5;
					}
					IL_06d5:
					await Task.Delay(300, token).ConfigureAwait(continueOnCapturedContext: false);
				}
				token.ThrowIfCancellationRequested();
				if (server.HasExited)
				{
					server.WaitForExit();
					if (metal)
					{
						throw new MetalStartupException(metalFailed.Task.IsCompleted ? "Metal backend initialization failed" : "llama.cpp exited before the model became ready");
					}
				}
				if (server.HasExited || until.Elapsed >= startupLimit)
				{
					if (metal)
					{
						throw new MetalStartupException("llama.cpp did not become ready");
					}
					throw new IOException("Server did not become ready (" + runtime + ")");
				}
				if (vulkan || metal)
				{
					await Task.WhenAny(new Task[2]
					{
						offload.Task,
						Task.Delay(1000, token)
					}).ConfigureAwait(continueOnCapturedContext: false);
					token.ThrowIfCancellationRequested();
				}
				bool flag = offload.Task.IsCompleted && offload.Task.Result > 0;
				if (vulkan && (!flag || server.HasExited))
				{
					throw new IOException("No GPU layers were confirmed");
				}
				if (metal && (!flag || server.HasExited))
				{
					throw new MetalStartupException("No Metal GPU layers were confirmed");
				}
				Backend = (flag ? "GPU" : "CPU");
				Endpoint = new Uri(root, "/v1/chat/completions");
				Status = "Local model ready";
				log($"Model server ready on {Backend} ({runtime}) in {until.Elapsed.TotalSeconds:0.0} s.");
				while (!server.HasExited)
				{
					await Task.Delay(500, token).ConfigureAwait(continueOnCapturedContext: false);
				}
				if (metal)
				{
					throw new MetalStartupException("Metal model server exited");
				}
				throw new IOException("Server exited");
			}
			finally
			{
				Endpoint = null;
				Backend = null;
				running = null;
				if (server != null)
				{
					try
					{
						if (!server.HasExited)
						{
							server.Kill();
							if (!server.WaitForExit(5000))
							{
								warn("Model server did not stop within 5 s.");
							}
						}
					}
					catch (InvalidOperationException)
					{
					}
					finally
					{
						server.Dispose();
						ServerTether.Detach(cache);
					}
				}
			}
		}

		internal static bool Verified(string file, string expected, CancellationToken token = default(CancellationToken))
		{
			if (!File.Exists(file))
			{
				return false;
			}
			using FileStream fileStream = File.OpenRead(file);
			using SHA256 sHA = SHA256.Create();
			byte[] array = new byte[1048576];
			int inputCount;
			while ((inputCount = fileStream.Read(array, 0, array.Length)) > 0)
			{
				token.ThrowIfCancellationRequested();
				sHA.TransformBlock(array, 0, inputCount, null, 0);
			}
			sHA.TransformFinalBlock(array, 0, 0);
			return string.Equals(BitConverter.ToString(sHA.Hash).Replace("-", ""), expected, StringComparison.OrdinalIgnoreCase);
		}

		internal static async Task Download(HttpClient client, string url, string file, string hash, CancellationToken token, long expectedBytes = 0L, Action<int> progress = null)
		{
			string partial = file + "." + Guid.NewGuid().ToString("N") + ".part";
			try
			{
				using (HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(continueOnCapturedContext: false))
				{
					response.EnsureSuccessStatusCode();
					using Stream input = await response.Content.ReadAsStreamAsync().ConfigureAwait(continueOnCapturedContext: false);
					using FileStream output = new FileStream(partial, FileMode.CreateNew, FileAccess.Write, FileShare.None);
					if (progress == null)
					{
						await input.CopyToAsync(output, 131072, token).ConfigureAwait(continueOnCapturedContext: false);
					}
					else
					{
						long total = response.Content.Headers.ContentLength ?? expectedBytes;
						long written = 0L;
						int last = 0;
						byte[] buffer = new byte[131072];
						while (true)
						{
							int num;
							int count = (num = await input.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(continueOnCapturedContext: false));
							if (num == 0)
							{
								break;
							}
							await output.WriteAsync(buffer, 0, count, token).ConfigureAwait(continueOnCapturedContext: false);
							written += count;
							int num2 = (int)((total > 0) ? Math.Min(99L, 100 * written / total) : 0);
							if (num2 != last)
							{
								last = num2;
								progress(num2);
							}
						}
					}
				}
				if (!Verified(partial, hash, token))
				{
					throw new InvalidDataException("Downloaded file failed SHA-256 verification");
				}
				token.ThrowIfCancellationRequested();
				if (File.Exists(file))
				{
					if (!Verified(file, hash))
					{
						File.Replace(partial, file, null);
					}
				}
				else
				{
					try
					{
						File.Move(partial, file);
					}
					catch (IOException) when (Verified(file, hash))
					{
					}
				}
				progress?.Invoke(100);
			}
			finally
			{
				File.Delete(partial);
			}
		}

		private async Task<string> InstallRuntime(HttpClient client, string runtime, CancellationToken token)
		{
			string folder = Path.Combine(cache, "b12774-" + runtime);
			if (Directory.Exists(folder))
			{
				if (Intact(folder))
				{
					return FindServer(folder);
				}
				warn("llama.cpp files are missing or changed. Reinstalling.");
				Directory.Delete(folder, recursive: true);
			}
			string hash = RuntimeHash(runtime);
			bool windows = runtime.StartsWith("win-", StringComparison.Ordinal);
			string text = (windows ? ".zip" : ".tar.gz");
			string text2 = "llama-b12774-bin-" + runtime + text;
			string stage = Path.Combine(cache, "stage-" + Guid.NewGuid().ToString("N"));
			Directory.CreateDirectory(stage);
			try
			{
				string archive = Path.Combine(stage, "runtime" + text);
				log("Downloading llama.cpp b12774 for " + runtime + ".");
				await Download(client, "https://github.com/ggml-org/llama.cpp/releases/download/b12774/" + text2, archive, hash, token, 0L).ConfigureAwait(continueOnCapturedContext: false);
				if (windows)
				{
					ZipFile.ExtractToDirectory(archive, stage);
				}
				else
				{
					using Process process = Process.Start(new ProcessStartInfo("/usr/bin/tar", "-xzf runtime.tar.gz")
					{
						WorkingDirectory = stage,
						UseShellExecute = false
					}) ?? throw new IOException("Could not start tar");
					process.WaitForExit();
					if (process.ExitCode != 0)
					{
						throw new InvalidDataException("Runtime extraction failed");
					}
				}
				File.Delete(archive);
				FindServer(stage);
				WriteManifest(stage);
				token.ThrowIfCancellationRequested();
				try
				{
					Directory.Move(stage, folder);
				}
				catch (IOException) when (Directory.Exists(folder))
				{
				}
				return FindServer(folder);
			}
			finally
			{
				if (Directory.Exists(stage))
				{
					Directory.Delete(stage, recursive: true);
				}
			}
		}

		internal static void WriteManifest(string folder)
		{
			File.WriteAllLines(Path.Combine(folder, "files.txt"), (from file in Directory.GetFiles(folder, "*", SearchOption.AllDirectories)
				select new FileInfo(file).Length + "\t" + file.Substring(folder.Length + 1)).ToArray());
		}

		internal static bool Intact(string folder)
		{
			try
			{
				string[] array = File.ReadAllLines(Path.Combine(folder, "files.txt"));
				return array.Length != 0 && array.All(delegate(string line)
				{
					string[] array2 = line.Split(new char[1] { '\t' }, 2);
					if (array2.Length != 2 || !long.TryParse(array2[0], out var result))
					{
						return false;
					}
					FileInfo fileInfo = new FileInfo(Path.Combine(folder, array2[1]));
					return fileInfo.Exists && fileInfo.Length == result;
				});
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is ArgumentException)
			{
				return false;
			}
		}

		internal static void RemoveLeftovers(string cache)
		{
			string[] array;
			try
			{
				array = (Directory.Exists(cache) ? Directory.GetFileSystemEntries(cache) : Array.Empty<string>());
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
			{
				return;
			}
			string[] array2 = array;
			foreach (string path in array2)
			{
				string fileName = Path.GetFileName(path);
				try
				{
					if (fileName.EndsWith(".part", StringComparison.Ordinal) && File.Exists(path))
					{
						File.Delete(path);
					}
					else if (fileName.StartsWith("stage-", StringComparison.Ordinal) && Directory.Exists(path))
					{
						Directory.Delete(path, recursive: true);
					}
				}
				catch (Exception ex2) when (ex2 is IOException || ex2 is UnauthorizedAccessException)
				{
				}
			}
		}

		internal static string ProvideOpenSsl(string folder, bool arm, string root = "")
		{
			string text = (arm ? "aarch64-linux-gnu" : "x86_64-linux-gnu");
			string[] places = new string[6]
			{
				"/usr/lib/" + text,
				"/lib/" + text,
				"/usr/lib64",
				"/lib64",
				"/usr/lib",
				"/lib"
			};
			if (Find("") != null)
			{
				return null;
			}
			string text2 = Find("/run/host");
			if (text2 == null)
			{
				return "OpenSSL 3 (libssl.so.3) was not found. llama.cpp needs it: install your system's libssl3 or openssl package.";
			}
			try
			{
				string[] openSsl = OpenSsl;
				foreach (string path in openSsl)
				{
					FileInfo fileInfo = new FileInfo(Path.Combine(text2, path));
					FileInfo fileInfo2 = new FileInfo(Path.Combine(folder, path));
					if (!fileInfo2.Exists || fileInfo2.Length != fileInfo.Length || fileInfo2.LastWriteTimeUtc < fileInfo.LastWriteTimeUtc)
					{
						fileInfo.CopyTo(fileInfo2.FullName, overwrite: true);
					}
				}
				return null;
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
			{
				return "Could not copy OpenSSL 3 from " + text2 + ": " + ex.Message;
			}
			string Find(string system)
			{
				return places.Select((string place) => root + system + place).FirstOrDefault((string place) => OpenSsl.All((string name) => File.Exists(Path.Combine(place, name))));
			}
		}

		private void CheckDisk(long bytes)
		{
			if (bytes > 0)
			{
				long? num = Headroom.FreeDisk(cache);
				if (num.HasValue && num.Value - bytes < 1073741824)
				{
					throw new ShortOfSpaceException("Not enough disk space: " + Headroom.Size(num.Value) + " free, " + Headroom.Size(bytes + 1073741824) + " needed for the download.");
				}
			}
		}

		private void CheckMemory(bool vulkan)
		{
			long? num = Headroom.FreeMemory();
			if (num.HasValue)
			{
				long num2 = Headroom.MemoryFor(Choice, VoiceEnabled);
				long num3 = Headroom.MemoryFor(Choice, hearing: false);
				if (vulkan)
				{
					num2 /= 2;
					num3 /= 2;
				}
				if (num.Value < num2)
				{
					throw new ShortOfMemoryException("Not enough free memory for " + Choice.Name + ": " + Headroom.Size(num.Value) + " free, " + Headroom.Size(num2) + " needed.", VoiceEnabled && num.Value >= num3);
				}
			}
		}

		internal static bool DiskFull(Exception error)
		{
			for (Exception ex = error; ex != null; ex = ex.InnerException)
			{
				if (ex is ShortOfSpaceException || (ex is IOException && ((ex.HResult & 0xFFFF) == 112 || (ex.HResult & 0xFFFF) == 39 || ex.Message.IndexOf("No space left", StringComparison.OrdinalIgnoreCase) >= 0 || ex.Message.IndexOf("disk full", StringComparison.OrdinalIgnoreCase) >= 0)))
				{
					return true;
				}
			}
			return false;
		}

		private static string FindServer(string root)
		{
			string text = ((Path.DirectorySeparatorChar == '\\') ? ".exe" : "");
			string[] serverNames = ServerNames;
			foreach (string text2 in serverNames)
			{
				string text3 = Directory.EnumerateFiles(root, text2 + text, SearchOption.AllDirectories).FirstOrDefault();
				if (text3 != null)
				{
					return text3;
				}
			}
			throw new FileNotFoundException("The runtime contains no llama server");
		}

		private static int FreePort()
		{
			TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 0);
			try
			{
				tcpListener.Start();
				return ((IPEndPoint)tcpListener.LocalEndpoint).Port;
			}
			finally
			{
				tcpListener.Stop();
			}
		}

		public void Dispose()
		{
			stop.Cancel();
			Process process = Interlocked.Exchange(ref running, null);
			try
			{
				if (process != null && !process.HasExited)
				{
					process.Kill();
				}
			}
			catch (InvalidOperationException)
			{
			}
			catch (Win32Exception)
			{
			}
			ServerTether.Detach(cache);
		}
	}
	internal static class ModelCache
	{
		internal static string DisplayFolder(string folder, string home, bool windows, string protonData)
		{
			if (windows && !string.IsNullOrEmpty(protonData) && folder.StartsWith("C:", StringComparison.OrdinalIgnoreCase))
			{
				return protonData.TrimEnd('/') + "/pfx/drive_c" + folder.Substring(2).Replace('\\', '/');
			}
			if (string.IsNullOrEmpty(home) || folder.Length <= home.Length || !folder.StartsWith(home, StringComparison.OrdinalIgnoreCase) || (folder[home.Length] != '/' && folder[home.Length] != '\\'))
			{
				return folder;
			}
			return (windows ? "%USERPROFILE%" : "~") + folder.Substring(home.Length);
		}

		internal static long Size(string fileName, string folder)
		{
			return InspectFile(folder, fileName, delete: false);
		}

		internal static long Delete(string fileName, string folder)
		{
			return InspectFile(folder, fileName, delete: true);
		}

		private static long InspectFile(string folder, string fileName, bool delete)
		{
			DirectoryInfo directoryInfo = new DirectoryInfo(folder);
			FileInfo fileInfo = new FileInfo(Path.Combine(directoryInfo.FullName, fileName));
			try
			{
				for (DirectoryInfo directoryInfo2 = directoryInfo; directoryInfo2 != null; directoryInfo2 = directoryInfo2.Parent)
				{
					if (directoryInfo2.Attributes == (FileAttributes)(-1))
					{
						return 0L;
					}
					if ((directoryInfo2.Attributes & FileAttributes.ReparsePoint) != FileAttributes.None)
					{
						throw new IOException("Model cache is redirected.");
					}
				}
				FileAttributes attributes = fileInfo.Attributes;
				if (attributes == (FileAttributes)(-1))
				{
					return 0L;
				}
				if ((attributes & (FileAttributes.Directory | FileAttributes.Device | FileAttributes.ReparsePoint)) != FileAttributes.None)
				{
					throw new IOException("Model cache entry is not a regular file.");
				}
				long length = fileInfo.Length;
				if (delete)
				{
					fileInfo.Delete();
				}
				return length;
			}
			catch (FileNotFoundException)
			{
				return 0L;
			}
			catch (DirectoryNotFoundException)
			{
				return 0L;
			}
		}
	}
	internal sealed class ModelChoice
	{
		internal readonly string Id;

		internal readonly string Name;

		internal readonly string Hint;

		internal readonly string FileName;

		internal readonly string Url;

		internal readonly string Hash;

		internal readonly long Bytes;

		internal readonly bool DisableThinking;

		internal readonly bool TranslationInstruction;

		internal readonly string LanguageSet;

		internal readonly string ProjectorFile;

		internal readonly string ProjectorUrl;

		internal readonly string ProjectorHash;

		internal readonly long ProjectorBytes;

		internal static bool ShowHints = true;

		internal static readonly ModelChoice[] Available = new ModelChoice[3]
		{
			new ModelChoice("gemma", "Gemma 4 E2B", "Balanced", "gemma-4-E2B-it-Q4_K_M.gguf", "https://huggingface.co/unsloth/gemma-4-E2B-it-GGUF/resolve/0314792d7f1f7e229411f620751375812bb9faf2/", "740185b21d22ceb83a11c3aa62ad5842ef32c70f6096d756bbee85a1e4ec34b8", 3106738272L, disableThinking: true, translationInstruction: false, "gemma-4-E2B-it-mmproj-F16.gguf", "mmproj-F16.gguf", "140be8d7849741f88c50757d529b84373ee8e27052cc2236855b537f4a8215fa", 985654080L),
			new ModelChoice("gemma-e4b", "Gemma 4 E4B", "Best quality, slow", "gemma-4-E4B-it-Q4_K_M.gguf", "https://huggingface.co/unsloth/gemma-4-E4B-it-GGUF/resolve/bfc15c382204943c3a8fff0c750b94ae2364d7a3/", "85a896a047553e842f25297ee5b031d64ff30147d9c4af17b1e4b394cd1fab87", 4977171584L, disableThinking: true, translationInstruction: false, "gemma-4-E4B-it-mmproj-F16.gguf", "mmproj-F16.gguf", "ddf46c21d7078e95338cfc22306b19b276a29a5ad089023449dd54d4b6170a51", 990372672L, "gemma"),
			new ModelChoice("tencent", "Tencent Hy-MT2-1.8B", "Slightly faster", "Hy-MT2-1.8B-Q4_K_M.gguf", "https://huggingface.co/tencent/Hy-MT2-1.8B-GGUF/resolve/a0c709d9fac510f2c807aa3af52872340dc37a4a/", "dc5f44fcf1fa496ee7ad725982c0c8c553a4de00259b53af84c4b89fb0c06699", 1133080448L, disableThinking: false, translationInstruction: true, null, null, null, 0L)
		};

		internal bool SupportsVoice => ProjectorFile != null;

		internal string Label
		{
			get
			{
				if (Hint != null && ShowHints)
				{
					return Name + " (" + Hint + ")";
				}
				return Name;
			}
		}

		private ModelChoice(string id, string name, string hint = null, string fileName = null, string baseUrl = null, string hash = null, long bytes = 0L, bool disableThinking = false, bool translationInstruction = false, string projector = null, string projectorSource = null, string projectorHash = null, long projectorBytes = 0L, string languageSet = null)
		{
			LanguageSet = languageSet ?? id;
			if (projector != null)
			{
				ProjectorFile = projector;
				ProjectorUrl = baseUrl + projectorSource;
				ProjectorHash = projectorHash;
				ProjectorBytes = projectorBytes;
			}
			Id = id;
			Name = name;
			Hint = hint;
			FileName = fileName;
			Url = ((baseUrl == null) ? null : (baseUrl + fileName));
			Hash = hash;
			Bytes = bytes;
			DisableThinking = disableThinking;
			TranslationInstruction = translationInstruction;
		}

		internal static ModelChoice Find(string saved)
		{
			return Available.FirstOrDefault((ModelChoice m) => saved != null && (saved.Trim().StartsWith(m.Name, StringComparison.OrdinalIgnoreCase) || string.Equals(saved.Trim(), m.Id, StringComparison.OrdinalIgnoreCase))) ?? Available[0];
		}
	}
	internal static class ServerTether
	{
		private struct BasicLimits
		{
			internal long PerProcessUserTimeLimit;

			internal long PerJobUserTimeLimit;

			internal uint LimitFlags;

			internal UIntPtr MinimumWorkingSetSize;

			internal UIntPtr MaximumWorkingSetSize;

			internal uint ActiveProcessLimit;

			internal UIntPtr Affinity;

			internal uint PriorityClass;

			internal uint SchedulingClass;
		}

		private struct ExtendedLimits
		{
			internal BasicLimits Basic;

			internal ulong ReadOperations;

			internal ulong WriteOperations;

			internal ulong OtherOperations;

			internal ulong ReadBytes;

			internal ulong WriteBytes;

			internal ulong OtherBytes;

			internal UIntPtr ProcessMemoryLimit;

			internal UIntPtr JobMemoryLimit;

			internal UIntPtr PeakProcessMemoryUsed;

			internal UIntPtr PeakJobMemoryUsed;
		}

		private const string PidFile = "llama-server.pid";

		private static IntPtr job;

		internal static void Attach(Process server, string cache, Action<string> log)
		{
			int id = Process.GetCurrentProcess().Id;
			try
			{
				File.WriteAllText(Path.Combine(cache, "llama-server.pid"), server.Id + " " + id);
			}
			catch (IOException ex)
			{
				log("Could not record the model server process ID: " + ex.Message);
			}
			catch (UnauthorizedAccessException ex2)
			{
				log("Could not record the model server process ID: " + ex2.Message);
			}
			try
			{
				if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
				{
					KillWithGame(server);
				}
				else
				{
					Watch(server.Id, id);
				}
			}
			catch (Exception ex3) when (ex3 is Win32Exception || ex3 is EntryPointNotFoundException || ex3 is DllNotFoundException || ex3 is InvalidOperationException)
			{
				log("Could not tie the model server to the game process: " + ex3.Message);
			}
		}

		internal static void Detach(string cache)
		{
			try
			{
				File.Delete(Path.Combine(cache, "llama-server.pid"));
			}
			catch (IOException)
			{
			}
			catch (UnauthorizedAccessException)
			{
			}
		}

		internal static void Sweep(string cache, Action<string> log)
		{
			string path = Path.Combine(cache, "llama-server.pid");
			string[] array;
			try
			{
				array = (File.Exists(path) ? File.ReadAllText(path).Split(' ') : null);
			}
			catch (IOException)
			{
				return;
			}
			catch (UnauthorizedAccessException)
			{
				return;
			}
			if (array == null || array.Length != 2 || !int.TryParse(array[0], out var result) || !int.TryParse(array[1], out var result2))
			{
				return;
			}
			if (!Alive(result2))
			{
				try
				{
					using Process process = Process.GetProcessById(result);
					if (process.ProcessName.Contains("llama", StringComparison.OrdinalIgnoreCase))
					{
						process.Kill();
						log("Stopped a model server left running by a previous session.");
					}
				}
				catch (ArgumentException)
				{
				}
				catch (InvalidOperationException)
				{
				}
				catch (Win32Exception)
				{
				}
			}
			Detach(cache);
		}

		private static bool Alive(int id)
		{
			if (id == Process.GetCurrentProcess().Id)
			{
				return false;
			}
			try
			{
				using Process process = Process.GetProcessById(id);
				return !process.HasExited;
			}
			catch (ArgumentException)
			{
				return false;
			}
			catch (InvalidOperationException)
			{
				return false;
			}
		}

		internal static void Watch(int server, int game)
		{
			string text = "while kill -0 " + game + " 2>/dev/null && kill -0 " + server + " 2>/dev/null; do sleep 1; done; kill " + server + " 2>/dev/null";
			using (Process.Start(new ProcessStartInfo("/bin/sh", "-c \"" + text + "\"")
			{
				UseShellExecute = false,
				CreateNoWindow = true
			}))
			{
			}
		}

		private static void KillWithGame(Process server)
		{
			if (job == IntPtr.Zero)
			{
				IntPtr intPtr = CreateJobObject(IntPtr.Zero, null);
				if (intPtr == IntPtr.Zero)
				{
					throw new Win32Exception(Marshal.GetLastWin32Error());
				}
				ExtendedLimits info = new ExtendedLimits
				{
					Basic = new BasicLimits
					{
						LimitFlags = 8192u
					}
				};
				if (!SetInformationJobObject(intPtr, 9, ref info, (uint)Marshal.SizeOf<ExtendedLimits>()))
				{
					throw new Win32Exception(Marshal.GetLastWin32Error());
				}
				job = intPtr;
			}
			if (!AssignProcessToJobObject(job, server.Handle))
			{
				throw new Win32Exception(Marshal.GetLastWin32Error());
			}
		}

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		private static extern IntPtr CreateJobObject(IntPtr attributes, string name);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref ExtendedLimits info, uint length);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
	}
	internal static class TranslationCheck
	{
		private static readonly string[] NoteMarks = new string[6] { "=", ":", ":", "—", "–", " - " };

		private static readonly Regex ChatWords = new Regex("[\\p{L}\\p{M}\\p{N}]+(?:['\\u2019][\\p{L}\\p{M}\\p{N}]+)*");

		private static readonly Regex Stretch = new Regex("(.)\\1{2,}");

		private static readonly string[] PromptMarkers = new string[24]
		{
			"〖", "〗", "<think", "</think", "<|", "ZXQ", "QXZ", "STRAFTAT", "Return only the translated", "Treat the message as text",
			"Earlier chat (quoted):", "Output only the translation", "Detect the language of each span", "Do not correct spelling", "Return only the message", "Translate foreign words in mixed messages", "goofy arena shooter", "types in game chat", "[Background Information]", "[Source Text]",
			"when used as one", "background information", "message to translate into", "speaker and listener"
		};

		private static readonly Regex Words = new Regex("\\p{L}[\\p{L}\\p{M}'\\u2019]*");

		internal static bool SameWords(string text, string translation)
		{
			string text2 = Letters(text);
			string text3 = Letters(translation);
			if (text2.Length == 0 || text3.Length == 0)
			{
				return text2 == text3;
			}
			int[] array = new int[text3.Length + 1];
			int[] array2 = new int[text3.Length + 1];
			for (int i = 0; i <= text3.Length; i++)
			{
				array[i] = i;
			}
			for (int j = 1; j <= text2.Length; j++)
			{
				array2[0] = j;
				for (int k = 1; k <= text3.Length; k++)
				{
					array2[k] = Math.Min(Math.Min(array2[k - 1], array[k]) + 1, array[k - 1] + ((text2[j - 1] != text3[k - 1]) ? 1 : 0));
				}
				int[] array3 = array2;
				array2 = array;
				array = array3;
			}
			return array[text3.Length] * 4 <= Math.Max(text2.Length, text3.Length);
		}

		internal static bool RepeatsReference(string text, string translation, string reference)
		{
			if (IsEcho("Ready", translation) && !IsEcho("Ready", text))
			{
				return true;
			}
			if (translation.TrimStart().StartsWith('{') && !text.TrimStart().StartsWith('{'))
			{
				return true;
			}
			foreach (string item in ((JContainer)JArray.Parse(reference)).Values<string>())
			{
				if (item.Length >= 4 && ContainsWords(translation, item) && !text.Contains(item, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}

		private static bool ContainsWords(string text, string part)
		{
			for (int num = text.IndexOf(part, StringComparison.OrdinalIgnoreCase); num >= 0; num = text.IndexOf(part, num + 1, StringComparison.OrdinalIgnoreCase))
			{
				if (Edge(text, num - 1) && Edge(text, num