Decompiled source of ChatSounds v1.1.2

ChatSounds.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Localization;
using UnityEngine.Localization.Settings;
using UnityEngine.Networking;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ChatSounds")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.2.0")]
[assembly: AssemblyInformationalVersion("1.1.2+4d3adc5e8b33b300b49d662df7d64e9fd3d94082")]
[assembly: AssemblyProduct("ChatSounds")]
[assembly: AssemblyTitle("ChatSounds")]
[assembly: AssemblyVersion("1.1.2.0")]
namespace ChatSounds;

internal static class ChatCommands
{
	public const string CommandApiGuid = "com.on-together-mods.commandapi";

	private static readonly string[] Names = new string[3] { "chatsound", "chatsounds", "csnd" };

	public static bool TryExecute(string text)
	{
		if (string.IsNullOrEmpty(text) || text[0] != '/')
		{
			return false;
		}
		string[] array = text.Substring(1).Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
		if (array.Length == 0 || Array.IndexOf(Names, array[0].ToLowerInvariant()) < 0)
		{
			return false;
		}
		Execute(array.Skip(1).ToArray());
		return true;
	}

	public static void Execute(string[] args)
	{
		//IL_03e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f3: Unknown result type (might be due to invalid IL or missing references)
		Plugin instance = Plugin.Instance;
		if ((Object)(object)instance == (Object)null)
		{
			return;
		}
		Lang current = Lang.Current;
		if (args.Length == 0)
		{
			instance.ToggleWindow();
			return;
		}
		string text = args[0].ToLowerInvariant();
		switch (text)
		{
		case "on":
			instance.SetEnabled(enabled: true, notify: true);
			return;
		case "off":
			instance.SetEnabled(enabled: false, notify: true);
			return;
		case "toggle":
			instance.SetEnabled(!instance.Enabled.Value, notify: true);
			return;
		case "ui":
		case "window":
		case "settings":
			instance.ToggleWindow();
			return;
		case "vol":
		case "volume":
			Volume(instance, current, args);
			return;
		case "sound":
			SetSound(instance, current, args);
			return;
		case "sounds":
		case "list":
			instance.Sounds.Rescan();
			GameAccess.Notify(string.Format(current.SoundsList, string.Join(", ", instance.Sounds.Choices())));
			return;
		case "test":
		case "play":
			Test(instance, current, args);
			return;
		case "when":
			When(instance, current, args);
			return;
		case "kw":
		case "keywords":
		case "keyword":
			Keyword(instance, current, args);
			return;
		case "reload":
		case "rescan":
			GameAccess.Notify(string.Format(current.Rescanned, instance.Sounds.Rescan()));
			return;
		case "status":
			GameAccess.Notify(instance.DescribeStatus(current));
			return;
		}
		SoundCategory soundCategory = ParseCategory(instance, text);
		if (soundCategory != null)
		{
			Switch(current, soundCategory, args);
		}
		else
		{
			GameAccess.Notify(string.Format(current.Help, instance.WindowKey.Value, instance.ToggleKey.Value));
		}
	}

	private static void Switch(Lang lang, SoundCategory category, string[] args)
	{
		bool flag;
		switch ((args.Length > 1) ? args[1].ToLowerInvariant() : "toggle")
		{
		case "toggle":
			flag = !category.Enabled.Value;
			break;
		case "on":
			flag = true;
			break;
		case "off":
			flag = false;
			break;
		default:
			GameAccess.Notify(lang.UsageSwitch);
			return;
		}
		category.Enabled.Value = flag;
		GameAccess.Notify(string.Format(flag ? lang.CategoryOn : lang.CategoryOff, category.Title(lang)));
	}

	private static void Volume(Plugin plugin, Lang lang, string[] args)
	{
		SoundCategory soundCategory = ((args.Length > 2) ? ParseCategory(plugin, args[1]) : null);
		string text = ((args.Length > 2) ? args[2] : ((args.Length > 1) ? args[1] : null));
		if ((args.Length > 2 && soundCategory == null) || !TryParsePercent(text, out var percent))
		{
			GameAccess.Notify(lang.UsageVolume);
		}
		else if (soundCategory == null)
		{
			plugin.MasterVolume.Value = percent;
			GameAccess.Notify(string.Format(lang.MasterVolumeSet, percent));
		}
		else
		{
			soundCategory.Volume.Value = percent;
			GameAccess.Notify(string.Format(lang.VolumeSet, soundCategory.Title(lang), percent));
			plugin.Preview(soundCategory);
		}
	}

	private static void SetSound(Plugin plugin, Lang lang, string[] args)
	{
		SoundCategory soundCategory = ((args.Length > 2) ? ParseCategory(plugin, args[1]) : null);
		if (soundCategory == null)
		{
			GameAccess.Notify(lang.UsageSound);
			return;
		}
		plugin.Sounds.Rescan();
		string text = string.Join(" ", args, 2, args.Length - 2);
		string text2 = plugin.Sounds.Canonicalize(text);
		if (text2 == null)
		{
			GameAccess.Notify(string.Format(lang.UnknownSound, text));
			return;
		}
		soundCategory.Sound.Value = text2;
		GameAccess.Notify(string.Format(lang.SoundSet, soundCategory.Title(lang), plugin.Sounds.DisplayName(text2, lang)));
		plugin.Preview(soundCategory);
	}

	private static void Test(Plugin plugin, Lang lang, string[] args)
	{
		if (args.Length < 2)
		{
			plugin.PreviewAll();
			return;
		}
		SoundCategory soundCategory = ParseCategory(plugin, args[1]);
		if (soundCategory != null)
		{
			plugin.Preview(soundCategory);
			return;
		}
		plugin.Sounds.Rescan();
		string text = string.Join(" ", args, 1, args.Length - 1);
		string text2 = plugin.Sounds.Canonicalize(text);
		if (text2 == null)
		{
			GameAccess.Notify(string.Format(lang.UnknownSound, text));
		}
		else
		{
			plugin.Sounds.Play(text2, plugin.EffectiveVolume(plugin.Local));
		}
	}

	private static void When(Plugin plugin, Lang lang, string[] args)
	{
		SoundCategory soundCategory = ((args.Length > 2) ? ParseCategory(plugin, args[1]) : null);
		if (soundCategory == null || !TryParseWhen(args[2], out var when))
		{
			GameAccess.Notify(lang.UsageWhen);
			return;
		}
		soundCategory.When.Value = when;
		GameAccess.Notify(string.Format(lang.WhenSet, soundCategory.Title(lang), lang.Describe(when)));
	}

	private static void Keyword(Plugin plugin, Lang lang, string[] args)
	{
		string text = ((args.Length > 1) ? args[1].ToLowerInvariant() : "list");
		List<string> list = MentionMatcher.ParseKeywords((args.Length > 2) ? string.Join(" ", args, 2, args.Length - 2) : null);
		List<string> list2 = MentionMatcher.ParseKeywords(plugin.Keywords.Value);
		switch (text)
		{
		case "add":
			if (list.Count == 0)
			{
				break;
			}
			foreach (string word2 in list)
			{
				if (!list2.Exists((string w) => string.Equals(w, word2, StringComparison.OrdinalIgnoreCase)))
				{
					list2.Add(word2);
				}
			}
			plugin.Keywords.Value = MentionMatcher.JoinKeywords(list2);
			GameAccess.Notify(string.Format(lang.KeywordAdded, MentionMatcher.JoinKeywords(list)));
			return;
		case "remove":
		case "delete":
		{
			if (list.Count == 0)
			{
				break;
			}
			int num = 0;
			foreach (string word in list)
			{
				num += list2.RemoveAll((string w) => string.Equals(w, word, StringComparison.OrdinalIgnoreCase));
			}
			if (num == 0)
			{
				GameAccess.Notify(string.Format(lang.KeywordMissing, MentionMatcher.JoinKeywords(list)));
				return;
			}
			plugin.Keywords.Value = MentionMatcher.JoinKeywords(list2);
			GameAccess.Notify(string.Format(lang.KeywordRemoved, MentionMatcher.JoinKeywords(list)));
			return;
		}
		case "clear":
			plugin.Keywords.Value = string.Empty;
			GameAccess.Notify(lang.KeywordsCleared);
			return;
		case "list":
			GameAccess.Notify(string.Format(lang.KeywordsList, (list2.Count > 0) ? MentionMatcher.JoinKeywords(list2) : lang.None));
			return;
		}
		GameAccess.Notify(lang.UsageKeyword);
	}

	private static SoundCategory ParseCategory(Plugin plugin, string text)
	{
		switch (text.ToLowerInvariant())
		{
		case "g":
		case "global":
			return plugin.Global;
		case "l":
		case "local":
			return plugin.Local;
		case "m":
		case "mentions":
		case "mention":
			return plugin.Mentions;
		default:
			return null;
		}
	}

	private static bool TryParseWhen(string text, out PlayWhen when)
	{
		switch (text.ToLowerInvariant())
		{
		case "always":
			when = PlayWhen.Always;
			return true;
		case "notviewing":
		case "hidden":
			when = PlayWhen.NotViewing;
			return true;
		case "unfocused":
		case "background":
			when = PlayWhen.Unfocused;
			return true;
		default:
			when = PlayWhen.Always;
			return false;
		}
	}

	private static bool TryParsePercent(string text, out int percent)
	{
		percent = 0;
		if (string.IsNullOrEmpty(text) || !int.TryParse(text.TrimEnd('%'), out percent))
		{
			return false;
		}
		percent = Math.Max(0, Math.Min(100, percent));
		return true;
	}

	public static void RegisterWithCommandApi()
	{
		if (!Chainloader.PluginInfos.TryGetValue("com.on-together-mods.commandapi", out var value) || (Object)(object)value.Instance == (Object)null)
		{
			return;
		}
		try
		{
			Assembly assembly = ((object)value.Instance).GetType().Assembly;
			Type type = assembly.GetType("CommandAPI.CommandRegistry");
			Type type2 = assembly.GetType("CommandAPI.Parameter");
			Type type3 = assembly.GetType("CommandAPI.ParameterType");
			if (type == null || type2 == null || type3 == null)
			{
				return;
			}
			MethodInfo method = type.GetMethod("Register", new Type[5]
			{
				typeof(string),
				typeof(string),
				typeof(Action<string[]>),
				typeof(string),
				type2.MakeArrayType()
			});
			if (!(method == null))
			{
				object obj = Enum.Parse(type3, "String");
				Array array = Array.CreateInstance(type2, 2);
				array.SetValue(Activator.CreateInstance(type2, "action", obj, true, null, null), 0);
				array.SetValue(Activator.CreateInstance(type2, "value", obj, true, null, null), 1);
				Action<string[]> action = Execute;
				string[] names = Names;
				foreach (string text in names)
				{
					method.Invoke(null, new object[5] { text, "ChatSounds", action, "Chat message sounds: settings window, on/off, volume, sound, test, keywords, status", array });
				}
				Plugin.Log.LogInfo((object)"Registered /chatsound with CommandAPI.");
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Could not register with CommandAPI (the command still works): " + ex.Message));
		}
	}
}
[HarmonyPatch(typeof(TextChannelManager), "OnEnterPressed")]
internal static class ChatCommandPatch
{
	[HarmonyPrefix]
	[HarmonyPriority(800)]
	private static void Prefix()
	{
		try
		{
			UIManager i = MonoSingleton<UIManager>.I;
			TMP_InputField val = (((Object)(object)i != (Object)null) ? i.MessageInput : null);
			if ((Object)(object)val != (Object)null && ChatCommands.TryExecute(val.text))
			{
				val.text = string.Empty;
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Chat command failed: " + ex));
		}
	}
}
internal static class DockLayout
{
	internal readonly struct Box
	{
		internal readonly float X;

		internal readonly float Y;

		internal readonly float Width;

		internal readonly float Height;

		internal Box(float x, float y, float width, float height)
		{
			X = x;
			Y = y;
			Width = width;
			Height = height;
		}

		internal bool Overlaps(Box b)
		{
			if (X < b.X + b.Width && X + Width > b.X && Y < b.Y + b.Height)
			{
				return Y + Height > b.Y;
			}
			return false;
		}
	}

	internal static bool Find(float width, float height, float scale, int count, IReadOnlyList<Box> obstacles, out Box result)
	{
		return Find(width, height, 36f * scale, 36f * scale, 6f * scale, 12f * scale, count, obstacles, out result);
	}

	internal static bool FindRight(float width, float height, float x, float buttonWidth, float buttonHeight, float gap, float preferredTop, float margin, int count, IReadOnlyList<Box> obstacles, out Box result)
	{
		result = default(Box);
		float num = buttonHeight + gap;
		float num2 = (float)count * num - gap;
		if (count <= 0 || buttonWidth <= 0f || buttonHeight <= 0f || gap < 0f || x < 0f || x >= width || x + buttonWidth < width || num2 + 2f * margin > height)
		{
			return false;
		}
		int num3 = (int)Math.Ceiling((margin - preferredTop) / num);
		int num4 = (int)Math.Floor((height - margin - num2 - preferredTop) / num);
		List<int> list = new List<int>();
		for (int i = Math.Max(0, num3); i <= num4; i++)
		{
			list.Add(i);
		}
		for (int num5 = Math.Min(-1, num4); num5 >= num3; num5--)
		{
			list.Add(num5);
		}
		foreach (int item in list)
		{
			float y = preferredTop + (float)item * num;
			Box b = new Box(x, y, width - x, num2);
			bool flag = false;
			foreach (Box obstacle in obstacles)
			{
				if (obstacle.Overlaps(b))
				{
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				result = new Box(x, y, buttonWidth, num2);
				return true;
			}
		}
		return false;
	}

	internal static bool Find(float width, float height, float buttonWidth, float buttonHeight, float gap, float margin, int count, IReadOnlyList<Box> obstacles, out Box result)
	{
		float num = (float)count * (buttonHeight + gap) - gap;
		result = default(Box);
		if (count <= 0 || width < buttonWidth + 2f * margin || height < num + 24f || buttonWidth <= 0f || buttonHeight <= 0f)
		{
			return false;
		}
		bool[] array = new bool[2] { true, false };
		for (int i = 0; i < array.Length; i++)
		{
			float x = (array[i] ? (width - margin - buttonWidth) : margin);
			float num2 = Math.Max(12f, Math.Min((height - num) * 0.5f, height - num - 12f));
			for (int j = 0; (float)j < height / (buttonHeight + gap) + 2f; j++)
			{
				int[] array2 = new int[2] { 1, -1 };
				foreach (int num3 in array2)
				{
					float num4 = num2 + (float)j * (buttonHeight + gap) * (float)num3;
					if (num4 < 12f || num4 + num > height - 12f)
					{
						continue;
					}
					Box box = new Box(x, num4, buttonWidth, num);
					bool flag = false;
					foreach (Box obstacle in obstacles)
					{
						if (obstacle.Overlaps(box))
						{
							flag = true;
							break;
						}
					}
					if (!flag)
					{
						result = box;
						return true;
					}
				}
			}
		}
		return false;
	}
}
internal static class SidebarVisibility
{
	internal static bool Show(bool desktop, bool nativeActive, bool canvasEnabled, float alpha)
	{
		if (!desktop && nativeActive && canvasEnabled)
		{
			return alpha > 0.01f;
		}
		return false;
	}
}
internal static class GameAccess
{
	private const float LookupInterval = 1f;

	private static TextChannelManager _chat;

	private static UIManager _ui;

	private static DataManager _data;

	private static SFXManager _sfx;

	private static SoundManager _music;

	private static float _nextChatLookup;

	private static float _nextUiLookup;

	private static float _nextDataLookup;

	private static float _nextSfxLookup;

	private static float _nextMusicLookup;

	private static readonly FieldRef<TextChannelManager, TMP_Text> TextPrefabRef = TryFieldRef<TMP_Text>("_textPrefab");

	private static readonly FieldRef<TextChannelManager, List<GameObject>> LocalMessagesRef = TryFieldRef<List<GameObject>>("_messageObjectsLocal");

	public static TextChannelManager Chat => Lookup<TextChannelManager>(ref _chat, ref _nextChatLookup, (Func<TextChannelManager>)(() => NetworkSingleton<TextChannelManager>.I));

	public static UIManager UI => Lookup<UIManager>(ref _ui, ref _nextUiLookup, (Func<UIManager>)(() => MonoSingleton<UIManager>.I));

	public static DataManager Data => Lookup<DataManager>(ref _data, ref _nextDataLookup, (Func<DataManager>)(() => MonoSingleton<DataManager>.I));

	public static SFXManager Sfx => Lookup<SFXManager>(ref _sfx, ref _nextSfxLookup, (Func<SFXManager>)(() => MonoSingleton<SFXManager>.I));

	public static SoundManager Music => Lookup<SoundManager>(ref _music, ref _nextMusicLookup, (Func<SoundManager>)(() => MonoSingleton<SoundManager>.I));

	public static float GameMasterVolume
	{
		get
		{
			DataManager data = Data;
			SettingsData val = (((Object)(object)data != (Object)null) ? data.SettingsData : null);
			if (val == null)
			{
				return 1f;
			}
			return Mathf.Clamp01(val.MasterVolume);
		}
	}

	public static string LocalPlayerName
	{
		get
		{
			TextChannelManager chat = Chat;
			if (!((Object)(object)chat != (Object)null))
			{
				return null;
			}
			return chat.UserName;
		}
	}

	private static T Lookup<T>(ref T cached, ref float nextLookup, Func<T> find) where T : Object
	{
		if ((Object)(object)cached == (Object)null && Time.unscaledTime >= nextLookup)
		{
			nextLookup = Time.unscaledTime + 1f;
			cached = find();
		}
		return cached;
	}

	public static bool IsLocalPlayerFocusing()
	{
		TextChannelManager chat = Chat;
		PlayerFocusController val = (((Object)(object)chat != (Object)null) ? chat.MainFocusController : null);
		if ((Object)(object)val != (Object)null)
		{
			return val.IsFocus;
		}
		return false;
	}

	public static bool IsChannelVisible(bool isLocal)
	{
		if (!Application.isFocused)
		{
			return false;
		}
		UIManager uI = UI;
		TextChannelManager chat = Chat;
		if ((Object)(object)uI != (Object)null && !uI.IsMessagePanelHidden && (Object)(object)chat != (Object)null)
		{
			return chat.Islocal == isLocal;
		}
		return false;
	}

	public static bool IsAnyTextFieldFocused()
	{
		EventSystem current = EventSystem.current;
		if ((Object)(object)current == (Object)null)
		{
			return false;
		}
		GameObject currentSelectedGameObject = current.currentSelectedGameObject;
		if ((Object)(object)currentSelectedGameObject == (Object)null)
		{
			return false;
		}
		TMP_InputField component = currentSelectedGameObject.GetComponent<TMP_InputField>();
		if ((Object)(object)component != (Object)null && component.isFocused)
		{
			return true;
		}
		InputField component2 = currentSelectedGameObject.GetComponent<InputField>();
		if ((Object)(object)component2 != (Object)null)
		{
			return component2.isFocused;
		}
		return false;
	}

	public static void Notify(string message)
	{
		TextChannelManager chat = Chat;
		if ((Object)(object)chat == (Object)null)
		{
			return;
		}
		string text = "<color=#9FD1FF>[ChatSounds]</color> <noparse>" + message + "</noparse>";
		try
		{
			if (!chat.Islocal || !TryAddLocalLine(chat, text))
			{
				chat.AddNotification(text);
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Could not show chat notification: " + ex.Message));
		}
	}

	private static bool TryAddLocalLine(TextChannelManager chat, string text)
	{
		if (TextPrefabRef == null)
		{
			return false;
		}
		UIManager uI = UI;
		Transform val = (((Object)(object)uI != (Object)null) ? uI.TextContentLocalTransform : null);
		TMP_Text val2 = TextPrefabRef.Invoke(chat);
		if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null)
		{
			return false;
		}
		TMP_Text val3 = Object.Instantiate<TMP_Text>(val2, val);
		Button component = ((Component)val3).GetComponent<Button>();
		if ((Object)(object)component != (Object)null)
		{
			((Selectable)component).interactable = false;
		}
		val3.text = text;
		List<GameObject> list = ((LocalMessagesRef != null) ? LocalMessagesRef.Invoke(chat) : null);
		if (list != null)
		{
			list.Add(((Component)val3).gameObject);
			int localMessageLimitCount = ScriptableSingleton<GameSettings>.I.LocalMessageLimitCount;
			while (list.Count > localMessageLimitCount && list.Count > 0)
			{
				GameObject val4 = list[0];
				list.RemoveAt(0);
				if ((Object)(object)val4 != (Object)null)
				{
					Object.Destroy((Object)(object)val4);
				}
			}
		}
		return true;
	}

	private static FieldRef<TextChannelManager, T> TryFieldRef<T>(string fieldName)
	{
		try
		{
			return AccessTools.FieldRefAccess<TextChannelManager, T>(fieldName);
		}
		catch (Exception)
		{
			return null;
		}
	}
}
internal sealed class Lang
{
	public string Title;

	public string SoundsEnabled;

	public string MasterVolume;

	public string FollowGameVolume;

	public string QuietDuringFocus;

	public string GlobalChat;

	public string LocalChat;

	public string Mentions;

	public string Sound;

	public string Volume;

	public string When;

	public string Cooldown;

	public string NoCooldown;

	public string SecondsFormat;

	public bool DecimalComma;

	public string WhenAlways;

	public string WhenNotViewing;

	public string WhenUnfocused;

	public string MatchMyName;

	public string MatchMyNameFormat;

	public string Keywords;

	public string None;

	public string KeywordsHint;

	public string OpenFolder;

	public string Rescan;

	public string Close;

	public string WindowHint;

	public string FilesHint;

	public string GamePrefix;

	public string FilePrefix;

	public string[] SynthNames;

	public string On;

	public string Off;

	public string SoundsOn;

	public string SoundsOff;

	public string CategoryOn;

	public string CategoryOff;

	public string MasterVolumeSet;

	public string VolumeSet;

	public string SoundSet;

	public string WhenSet;

	public string UnknownSound;

	public string SoundsList;

	public string KeywordAdded;

	public string KeywordRemoved;

	public string KeywordMissing;

	public string KeywordsList;

	public string KeywordsCleared;

	public string Rescanned;

	public string StatusFormat;

	public string CategoryStatus;

	public string MentionStatus;

	public string UsageSwitch;

	public string UsageVolume;

	public string UsageSound;

	public string UsageWhen;

	public string UsageKeyword;

	public string Help;

	public static readonly Lang English = new Lang
	{
		Title = "Chat Sounds",
		SoundsEnabled = "Sounds for new chat messages",
		MasterVolume = "Master volume",
		FollowGameVolume = "Follow the game's master volume",
		QuietDuringFocus = "During focus sessions, only mentions",
		GlobalChat = "Global chat",
		LocalChat = "Local chat",
		Mentions = "Mentions",
		Sound = "Sound",
		Volume = "Volume",
		When = "Play",
		Cooldown = "Cooldown",
		NoCooldown = "off",
		SecondsFormat = "{0} s",
		WhenAlways = "Always",
		WhenNotViewing = "When the tab isn't visible",
		WhenUnfocused = "When the game is in background",
		MatchMyName = "Your name",
		MatchMyNameFormat = "Your name ({0})",
		Keywords = "Keywords",
		None = "none",
		KeywordsHint = "Change with /chatsound keyword add | remove <word>",
		OpenFolder = "Sounds folder",
		Rescan = "Rescan",
		Close = "Close",
		WindowHint = "{0}: this window · {1}: all sounds on/off · /chatsound help: commands",
		FilesHint = "Your sound files: {0} (.wav, .ogg, .mp3 in BepInEx/config/ChatSounds)",
		GamePrefix = "Game: ",
		FilePrefix = "File: ",
		SynthNames = new string[8] { "Ping", "Chime", "Bubble", "Drop", "Marimba", "Bell", "Soft", "Alert" },
		On = "on",
		Off = "off",
		SoundsOn = "Chat sounds: on",
		SoundsOff = "Chat sounds: off",
		CategoryOn = "{0}: sound on",
		CategoryOff = "{0}: sound off",
		MasterVolumeSet = "Master volume: {0}%",
		VolumeSet = "{0}: volume {1}%",
		SoundSet = "{0}: sound {1}",
		WhenSet = "{0}: {1}",
		UnknownSound = "Unknown sound \"{0}\". /chatsound sounds lists them all",
		SoundsList = "Sounds: {0}",
		KeywordAdded = "Keyword added: {0}",
		KeywordRemoved = "Keyword removed: {0}",
		KeywordMissing = "No such keyword: {0}",
		KeywordsList = "Keywords: {0}",
		KeywordsCleared = "Keywords cleared",
		Rescanned = "Sound files found: {0}",
		StatusFormat = "Chat sounds: {0}, master volume {1}%",
		CategoryStatus = "{0}: {1}, {2}, {3}%, {4}",
		MentionStatus = "Mentions match: name {0}; keywords {1}",
		UsageSwitch = "Usage: /chatsound global | local | mentions [on | off]",
		UsageVolume = "Usage: /chatsound volume [global | local | mentions] <0-100>",
		UsageSound = "Usage: /chatsound sound <global | local | mentions> <sound>",
		UsageWhen = "Usage: /chatsound when <global | local | mentions> always | notviewing | unfocused",
		UsageKeyword = "Usage: /chatsound keyword add | remove <word>, /chatsound keyword list | clear",
		Help = "Chat sounds, commands:\n/chatsound - settings window ({0})\n/chatsound on | off - all sounds ({1})\n/chatsound global | local | mentions [on | off]\n/chatsound volume [global | local | mentions] <0-100>\n/chatsound sound <global | local | mentions> <sound>\n/chatsound sounds - list of sounds\n/chatsound test [global | local | mentions | <sound>]\n/chatsound when <global | local | mentions> always | notviewing | unfocused\n/chatsound keyword add | remove <word>, keyword list | clear\n/chatsound reload - rescan your sound files\n/chatsound status"
	};

	public static readonly Lang Russian = new Lang
	{
		Title = "Звуки чата",
		SoundsEnabled = "Звуки новых сообщений",
		MasterVolume = "Общая громкость",
		FollowGameVolume = "Учитывать общую громкость игры",
		QuietDuringFocus = "Во время фокуса только упоминания",
		GlobalChat = "Глобальный чат",
		LocalChat = "Локальный чат",
		Mentions = "Упоминания",
		Sound = "Звук",
		Volume = "Громкость",
		When = "Когда",
		Cooldown = "Пауза",
		NoCooldown = "нет",
		SecondsFormat = "{0} с",
		DecimalComma = true,
		WhenAlways = "Всегда",
		WhenNotViewing = "Если вкладка не видна",
		WhenUnfocused = "Если игра в фоне",
		MatchMyName = "Ваше имя",
		MatchMyNameFormat = "Ваше имя ({0})",
		Keywords = "Слова",
		None = "нет",
		KeywordsHint = "Изменить: /chatsound keyword add | remove <слово>",
		OpenFolder = "Папка звуков",
		Rescan = "Обновить",
		Close = "Закрыть",
		WindowHint = "{0}: это окно · {1}: вкл/выкл все звуки · /chatsound help: команды",
		FilesHint = "Ваших звуковых файлов: {0} (.wav, .ogg, .mp3 в BepInEx/config/ChatSounds)",
		GamePrefix = "Игра: ",
		FilePrefix = "Файл: ",
		SynthNames = new string[8] { "Пинг", "Перезвон", "Пузырьки", "Капля", "Маримба", "Колокол", "Мягкий", "Сигнал" },
		On = "вкл",
		Off = "выкл",
		SoundsOn = "Звуки чата включены",
		SoundsOff = "Звуки чата выключены",
		CategoryOn = "{0}: звук включён",
		CategoryOff = "{0}: звук выключен",
		MasterVolumeSet = "Общая громкость: {0}%",
		VolumeSet = "{0}: громкость {1}%",
		SoundSet = "{0}: звук {1}",
		WhenSet = "{0}: {1}",
		UnknownSound = "Неизвестный звук «{0}». Список: /chatsound sounds",
		SoundsList = "Звуки: {0}",
		KeywordAdded = "Добавлено: {0}",
		KeywordRemoved = "Удалено: {0}",
		KeywordMissing = "Такого слова нет: {0}",
		KeywordsList = "Слова-упоминания: {0}",
		KeywordsCleared = "Слова-упоминания удалены",
		Rescanned = "Найдено звуковых файлов: {0}",
		StatusFormat = "Звуки чата: {0}, общая громкость {1}%",
		CategoryStatus = "{0}: {1}, {2}, {3}%, {4}",
		MentionStatus = "Упоминания: имя {0}; слова {1}",
		UsageSwitch = "Использование: /chatsound global | local | mentions [on | off]",
		UsageVolume = "Использование: /chatsound volume [global | local | mentions] <0-100>",
		UsageSound = "Использование: /chatsound sound <global | local | mentions> <звук>",
		UsageWhen = "Использование: /chatsound when <global | local | mentions> always | notviewing | unfocused",
		UsageKeyword = "Использование: /chatsound keyword add | remove <слово>, /chatsound keyword list | clear",
		Help = "Звуки чата, команды:\n/chatsound - окно настроек ({0})\n/chatsound on | off - все звуки ({1})\n/chatsound global | local | mentions [on | off] - глобальный чат, локальный чат, упоминания\n/chatsound volume [global | local | mentions] <0-100> - громкость\n/chatsound sound <global | local | mentions> <звук> - выбрать звук\n/chatsound sounds - список звуков\n/chatsound test [global | local | mentions | <звук>] - прослушать\n/chatsound when <global | local | mentions> always | notviewing | unfocused - когда играть\n/chatsound keyword add | remove <слово>, keyword list | clear - слова-упоминания\n/chatsound reload - перечитать папку со звуками\n/chatsound status - текущие настройки"
	};

	private static Lang _auto = English;

	private static float _nextAutoCheck;

	public static Lang Current
	{
		get
		{
			Plugin instance = Plugin.Instance;
			switch (((Object)(object)instance != (Object)null) ? instance.Language.Value : UiLanguage.Auto)
			{
			case UiLanguage.English:
				return English;
			case UiLanguage.Russian:
				return Russian;
			default:
				if (Time.unscaledTime >= _nextAutoCheck)
				{
					_nextAutoCheck = Time.unscaledTime + 10f;
					_auto = (DetectRussian() ? Russian : English);
				}
				return _auto;
			}
		}
	}

	public static void Invalidate()
	{
		_nextAutoCheck = 0f;
	}

	public string Describe(PlayWhen when)
	{
		return when switch
		{
			PlayWhen.NotViewing => WhenNotViewing, 
			PlayWhen.Unfocused => WhenUnfocused, 
			_ => WhenAlways, 
		};
	}

	public string Seconds(float value)
	{
		string text = value.ToString("0.#", CultureInfo.InvariantCulture);
		return string.Format(SecondsFormat, DecimalComma ? text.Replace('.', ',') : text);
	}

	public string SoundName(string builtin)
	{
		int num = Array.IndexOf(Synth.Names, builtin);
		if (num < 0 || num >= SynthNames.Length)
		{
			return builtin;
		}
		return SynthNames[num];
	}

	private static bool DetectRussian()
	{
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Invalid comparison between Unknown and I4
		try
		{
			string text = GameLocaleCode();
			if (!string.IsNullOrEmpty(text))
			{
				return text.StartsWith("ru", StringComparison.OrdinalIgnoreCase);
			}
		}
		catch (Exception)
		{
		}
		return (int)Application.systemLanguage == 30;
	}

	[MethodImpl(MethodImplOptions.NoInlining)]
	private static string GameLocaleCode()
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		Locale selectedLocale = LocalizationSettings.SelectedLocale;
		if (!((Object)(object)selectedLocale != (Object)null))
		{
			return null;
		}
		LocaleIdentifier identifier = selectedLocale.Identifier;
		return ((LocaleIdentifier)(ref identifier)).Code;
	}
}
internal static class MentionMatcher
{
	private static readonly Regex RichTextTag = new Regex("<[^<>]*>");

	private static readonly char[] KeywordSeparators = new char[4] { ',', ';', '\n', '\r' };

	public static string StripTags(string text)
	{
		if (!string.IsNullOrEmpty(text))
		{
			return RichTextTag.Replace(text, string.Empty);
		}
		return string.Empty;
	}

	public static List<string> ParseKeywords(string value)
	{
		List<string> list = new List<string>();
		if (string.IsNullOrEmpty(value))
		{
			return list;
		}
		string[] array = value.Split(KeywordSeparators, StringSplitOptions.RemoveEmptyEntries);
		foreach (string text in array)
		{
			string word = text.Trim();
			if (word.Length > 0 && !list.Exists((string w) => string.Equals(w, word, StringComparison.OrdinalIgnoreCase)))
			{
				list.Add(word);
			}
		}
		return list;
	}

	public static string JoinKeywords(IEnumerable<string> words)
	{
		return string.Join(", ", words);
	}

	public static bool IsMention(string message, string playerName, IList<string> keywords)
	{
		if (string.IsNullOrEmpty(message))
		{
			return false;
		}
		string text = StripTags(message).ToLowerInvariant();
		string text2 = StripTags(playerName).Trim();
		if (text2.Length >= 2 && ContainsWord(text, text2.ToLowerInvariant()))
		{
			return true;
		}
		if (keywords == null)
		{
			return false;
		}
		foreach (string keyword in keywords)
		{
			if (ContainsWord(text, keyword.Trim().ToLowerInvariant()))
			{
				return true;
			}
		}
		return false;
	}

	public static bool ContainsWord(string text, string word)
	{
		if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(word))
		{
			return false;
		}
		for (int num = text.IndexOf(word, StringComparison.Ordinal); num >= 0; num = text.IndexOf(word, num + 1, StringComparison.Ordinal))
		{
			int num2 = num + word.Length;
			bool num3 = num == 0 || !IsWordChar(text[num - 1]) || !IsWordChar(word[0]);
			bool flag = num2 >= text.Length || !IsWordChar(text[num2]) || !IsWordChar(word[word.Length - 1]);
			if (num3 && flag)
			{
				return true;
			}
		}
		return false;
	}

	private static bool IsWordChar(char c)
	{
		if (c < '⺀')
		{
			if (!char.IsLetterOrDigit(c))
			{
				return c == '_';
			}
			return true;
		}
		return false;
	}
}
[HarmonyPatch(typeof(TextChannelManager), "AddMessageUI")]
internal static class MessagePatch
{
	[HarmonyPostfix]
	private static void Postfix(string text, bool isLocal, bool sendByPlayer)
	{
		if (!sendByPlayer)
		{
			Plugin instance = Plugin.Instance;
			if ((Object)(object)instance != (Object)null)
			{
				instance.OnMessageShown(text, isLocal);
			}
		}
	}
}
internal sealed class ModDock : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
{
	private Func<string> _hint;

	private Func<bool> _isOpen;

	private Func<bool> _visible;

	private Image _image;

	private Image _iconImage;

	private Image _outlineImage;

	private Button _control;

	private Button _native;

	private Image _nativeBackground;

	private Image _nativeIcon;

	private Image _nativeOutline;

	private Text _tooltip;

	private RectTransform _tooltipRect;

	private Sprite _background;

	private Sprite _icon;

	private Texture2D _backgroundTexture;

	private Texture2D _iconTexture;

	private CanvasGroup _group;

	private float _nextLayout;

	private bool _hover;

	private readonly List<DockLayout.Box> _obstacles = new List<DockLayout.Box>();

	private readonly Vector3[] _corners = (Vector3[])(object)new Vector3[4];

	internal static ModDock Register(string name, string symbol, Action toggle, Func<bool> open, Func<string> hint, Func<bool> visible = null)
	{
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Expected O, but got Unknown
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Expected O, but got Unknown
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		//IL_013b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0177: Unknown result type (might be due to invalid IL or missing references)
		//IL_0186: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_0201: Unknown result type (might be due to invalid IL or missing references)
		//IL_020a: Unknown result type (might be due to invalid IL or missing references)
		//IL_020f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0213: Unknown result type (might be due to invalid IL or missing references)
		//IL_022e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0249: Unknown result type (might be due to invalid IL or missing references)
		//IL_0255: Unknown result type (might be due to invalid IL or missing references)
		//IL_026a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0274: Expected O, but got Unknown
		//IL_0299: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a0: Expected O, but got Unknown
		//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0304: Expected O, but got Unknown
		//IL_031e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0323: Unknown result type (might be due to invalid IL or missing references)
		//IL_032e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0338: Unknown result type (might be due to invalid IL or missing references)
		//IL_0343: Unknown result type (might be due to invalid IL or missing references)
		//IL_034d: Unknown result type (might be due to invalid IL or missing references)
		//IL_034e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0353: Unknown result type (might be due to invalid IL or missing references)
		//IL_0354: Unknown result type (might be due to invalid IL or missing references)
		//IL_035b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0389: Unknown result type (might be due to invalid IL or missing references)
		//IL_0398: Unknown result type (might be due to invalid IL or missing references)
		//IL_03cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_0425: Unknown result type (might be due to invalid IL or missing references)
		//IL_042c: Expected O, but got Unknown
		//IL_0473: Unknown result type (might be due to invalid IL or missing references)
		//IL_047d: Expected O, but got Unknown
		//IL_04a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_04a9: Expected O, but got Unknown
		//IL_04c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_04c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_04d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_04d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_04df: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_04fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0546: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = GameObject.Find("LightShaper.ModDock.v1");
		if ((Object)(object)val == (Object)null)
		{
			val = new GameObject("LightShaper.ModDock.v1", new Type[3]
			{
				typeof(RectTransform),
				typeof(Canvas),
				typeof(GraphicRaycaster)
			});
			Object.DontDestroyOnLoad((Object)(object)val);
			Canvas component = val.GetComponent<Canvas>();
			component.renderMode = (RenderMode)0;
			component.sortingOrder = 32765;
		}
		GameObject val2 = new GameObject(name, new Type[4]
		{
			typeof(RectTransform),
			typeof(Image),
			typeof(Button),
			typeof(CanvasGroup)
		});
		val2.transform.SetParent(val.transform, false);
		ModDock modDock = val2.AddComponent<ModDock>();
		modDock._hint = hint;
		modDock._isOpen = open;
		modDock._visible = visible ?? ((Func<bool>)(() => true));
		modDock._group = val2.GetComponent<CanvasGroup>();
		modDock._group.alpha = 0f;
		((RectTransform)val2.transform).anchoredPosition = new Vector2(-10000f, -10000f);
		modDock._image = val2.GetComponent<Image>();
		modDock._backgroundTexture = RoundedTexture();
		modDock._background = Sprite.Create(modDock._backgroundTexture, new Rect(0f, 0f, 64f, 64f), new Vector2(0.5f, 0.5f), 100f, 0u, (SpriteMeshType)0, new Vector4(16f, 16f, 16f, 16f));
		modDock._image.sprite = modDock._background;
		modDock._image.type = (Type)1;
		Button val3 = (modDock._control = val2.GetComponent<Button>());
		((Selectable)val3).targetGraphic = (Graphic)(object)modDock._image;
		Navigation navigation = default(Navigation);
		((Navigation)(ref navigation)).mode = (Mode)0;
		((Selectable)val3).navigation = navigation;
		ColorBlock colors = ((Selectable)val3).colors;
		((ColorBlock)(ref colors)).normalColor = Color.white;
		((ColorBlock)(ref colors)).highlightedColor = new Color(1f, 0.88f, 0.8f);
		((ColorBlock)(ref colors)).pressedColor = new Color(0.95f, 0.8f, 0.68f);
		((Selectable)val3).colors = colors;
		((UnityEvent)val3.onClick).AddListener((UnityAction)delegate
		{
			toggle();
			EventSystem current = EventSystem.current;
			if (current != null)
			{
				current.SetSelectedGameObject((GameObject)null);
			}
		});
		GameObject val4 = new GameObject("Outline", new Type[2]
		{
			typeof(RectTransform),
			typeof(Image)
		});
		val4.transform.SetParent(val2.transform, false);
		modDock._outlineImage = val4.GetComponent<Image>();
		((Graphic)modDock._outlineImage).raycastTarget = false;
		((Behaviour)modDock._outlineImage).enabled = false;
		GameObject val5 = new GameObject("Icon", new Type[2]
		{
			typeof(RectTransform),
			typeof(Image)
		});
		val5.transform.SetParent(val2.transform, false);
		RectTransform val6 = (RectTransform)val5.transform;
		val6.anchorMin = new Vector2(0.19f, 0.19f);
		val6.anchorMax = new Vector2(0.81f, 0.81f);
		Vector2 offsetMin = (val6.offsetMax = Vector2.zero);
		val6.offsetMin = offsetMin;
		modDock._iconTexture = IconTexture(symbol);
		modDock._icon = Sprite.Create(modDock._iconTexture, new Rect(0f, 0f, 32f, 32f), new Vector2(0.5f, 0.5f));
		val5.GetComponent<Image>().sprite = modDock._icon;
		((Graphic)val5.GetComponent<Image>()).color = new Color(0.67f, 0.31f, 0.24f);
		((Graphic)val5.GetComponent<Image>()).raycastTarget = false;
		val5.GetComponent<Image>().preserveAspect = true;
		modDock._iconImage = val5.GetComponent<Image>();
		GameObject val7 = new GameObject("Tooltip", new Type[2]
		{
			typeof(RectTransform),
			typeof(Image)
		});
		val7.transform.SetParent(val2.transform, false);
		val7.GetComponent<Image>().sprite = modDock._background;
		val7.GetComponent<Image>().type = (Type)1;
		((Graphic)val7.GetComponent<Image>()).raycastTarget = false;
		modDock._tooltipRect = (RectTransform)val7.transform;
		GameObject val8 = new GameObject("Text", new Type[2]
		{
			typeof(RectTransform),
			typeof(Text)
		});
		val8.transform.SetParent(val7.transform, false);
		RectTransform val9 = (RectTransform)val8.transform;
		val9.anchorMin = Vector2.zero;
		val9.anchorMax = Vector2.one;
		val9.offsetMin = new Vector2(10f, 4f);
		val9.offsetMax = new Vector2(-10f, -4f);
		modDock._tooltip = val8.GetComponent<Text>();
		modDock._tooltip.font = UiEnvironment.GameFont ?? Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
		modDock._tooltip.fontSize = 13;
		((Graphic)modDock._tooltip).color = UiSkin.TextColor;
		modDock._tooltip.alignment = (TextAnchor)4;
		((Graphic)modDock._tooltip).raycastTarget = false;
		modDock._tooltip.supportRichText = false;
		val7.SetActive(false);
		Transform[] array = ((IEnumerable)val.transform).Cast<Transform>().OrderBy<Transform, string>((Transform t) => ((Object)t).name, StringComparer.Ordinal).ToArray();
		for (int num = 0; num < array.Length; num++)
		{
			array[num].SetAsLastSibling();
		}
		return modDock;
	}

	private void Update()
	{
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d4: Expected O, but got Unknown
		//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_020b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0212: Unknown result type (might be due to invalid IL or missing references)
		//IL_0228: Unknown result type (might be due to invalid IL or missing references)
		//IL_0240: Unknown result type (might be due to invalid IL or missing references)
		//IL_0272: Unknown result type (might be due to invalid IL or missing references)
		//IL_0282: Unknown result type (might be due to invalid IL or missing references)
		ApplyNativeStyle();
		float opacity = NativeSidebar.Opacity;
		bool flag = _visible() && opacity > 0.01f && ((RectTransform)((Component)this).transform).anchoredPosition.x > -9000f;
		_group.alpha = (flag ? opacity : 0f);
		_group.blocksRaycasts = flag;
		_group.interactable = flag;
		if (!flag)
		{
			_hover = false;
		}
		((Graphic)_image).color = (((Object)(object)_native != (Object)null) ? NativeSidebar.SurfaceColor(_hover || _isOpen()) : Color.white);
		((Graphic)_iconImage).color = (Color)(((Object)(object)_nativeOutline != (Object)null) ? ((Graphic)_nativeOutline).color : new Color(0.43f, 0.34f, 0.35f, 1f));
		if (((Component)this).transform.GetSiblingIndex() == 0 && Time.unscaledTime >= _nextLayout)
		{
			_nextLayout = Time.unscaledTime + 0.15f;
			LayoutGroup();
		}
		bool flag2 = _hover && _group.alpha > 0f && _group.blocksRaycasts;
		((Component)_tooltipRect).gameObject.SetActive(flag2);
		if (flag2)
		{
			float scale = UiEnvironment.Scale;
			_tooltip.text = _hint();
			_tooltip.fontSize = Mathf.RoundToInt(13f * scale);
			float num = Mathf.Min((float)Screen.width - 24f, Mathf.Max(140f * scale, _tooltip.preferredWidth + 24f));
			RectTransform val = (RectTransform)((Component)this).transform;
			_tooltipRect.pivot = new Vector2(1f, 0.5f);
			RectTransform tooltipRect = _tooltipRect;
			RectTransform tooltipRect2 = _tooltipRect;
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(0f, 0.5f);
			tooltipRect2.anchorMax = val2;
			tooltipRect.anchorMin = val2;
			_tooltipRect.sizeDelta = new Vector2(num, 32f * scale);
			float num2 = Mathf.Min((float)Screen.width - 12f, val.anchoredPosition.x - 8f);
			num2 = Mathf.Max(num + 12f, num2);
			_tooltipRect.anchoredPosition = new Vector2(num2 - val.anchoredPosition.x, 0f);
		}
	}

	private void ApplyNativeStyle()
	{
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Invalid comparison between Unknown and I4
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_011c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0130: Unknown result type (might be due to invalid IL or missing references)
		//IL_0135: Unknown result type (might be due to invalid IL or missing references)
		//IL_0153: Unknown result type (might be due to invalid IL or missing references)
		Button button = NativeSidebar.Button;
		if ((Object)(object)button == (Object)null)
		{
			return;
		}
		Image val = NativeSidebar.Background(button);
		if (!((Object)(object)val == (Object)null))
		{
			_native = button;
			_nativeBackground = val;
			_nativeIcon = NativeSidebar.Icon(button);
			_nativeOutline = NativeSidebar.Outline(button);
			((Selectable)_control).transition = (Transition)(((int)((Selectable)button).transition == 1) ? ((int)((Selectable)button).transition) : 0);
			((Selectable)_control).colors = ((Selectable)button).colors;
			NativeSidebar.CopyImage(_nativeBackground, _image);
			float num = NativeSidebar.PixelScale(val);
			if ((Object)(object)_nativeOutline != (Object)null)
			{
				((Behaviour)_outlineImage).enabled = true;
				NativeSidebar.CopyImage(_nativeOutline, _outlineImage);
				NativeSidebar.CopyRect(((Graphic)_nativeOutline).rectTransform, ((Graphic)_outlineImage).rectTransform, num);
			}
			else
			{
				((Behaviour)_outlineImage).enabled = false;
			}
			if ((Object)(object)_nativeIcon != (Object)null)
			{
				NativeSidebar.CopyRect(((Graphic)_nativeIcon).rectTransform, ((Graphic)_iconImage).rectTransform, num);
				Rect rect = ((Graphic)_nativeIcon).rectTransform.rect;
				float width = ((Rect)(ref rect)).width;
				rect = ((Graphic)_nativeIcon).rectTransform.rect;
				float num2 = Mathf.Min(width, ((Rect)(ref rect)).height) * num;
				((Graphic)_iconImage).rectTransform.sizeDelta = new Vector2(num2, num2);
			}
		}
	}

	private void LayoutGroup()
	{
		//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Invalid comparison between Unknown and I4
		//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_032d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0332: Unknown result type (might be due to invalid IL or missing references)
		//IL_0333: Unknown result type (might be due to invalid IL or missing references)
		//IL_0334: Unknown result type (might be due to invalid IL or missing references)
		//IL_0346: Unknown result type (might be due to invalid IL or missing references)
		//IL_034d: Unknown result type (might be due to invalid IL or missing references)
		//IL_034f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0350: Unknown result type (might be due to invalid IL or missing references)
		//IL_0357: Unknown result type (might be due to invalid IL or missing references)
		//IL_035e: Unknown result type (might be due to invalid IL or missing references)
		//IL_035f: Unknown result type (might be due to invalid IL or missing references)
		//IL_038d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0398: Unknown result type (might be due to invalid IL or missing references)
		//IL_0374: Unknown result type (might be due to invalid IL or missing references)
		//IL_0131: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0154: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Unknown result type (might be due to invalid IL or missing references)
		//IL_0162: Unknown result type (might be due to invalid IL or missing references)
		//IL_0167: Unknown result type (might be due to invalid IL or missing references)
		//IL_016c: Unknown result type (might be due to invalid IL or missing references)
		//IL_016e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0175: Unknown result type (might be due to invalid IL or missing references)
		//IL_0187: Unknown result type (might be due to invalid IL or missing references)
		//IL_018e: Unknown result type (might be due to invalid IL or missing references)
		//IL_019b: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
		_obstacles.Clear();
		Graphic[] array = GraphicRegistryAll();
		foreach (Graphic val in array)
		{
			if (!((Behaviour)val).isActiveAndEnabled || (Object)(object)val.canvas == (Object)null || (int)val.canvas.renderMode == 2 || ((Component)val).transform.IsChildOf(((Component)this).transform.parent))
			{
				continue;
			}
			bool flag = false;
			Transform val2 = ((Component)val).transform;
			while ((Object)(object)val2 != (Object)null)
			{
				if (((Object)val2).name.IndexOf("chat", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					flag = true;
					break;
				}
				val2 = val2.parent;
			}
			if (!val.raycastTarget && !flag)
			{
				continue;
			}
			bool flag2 = ((Object)((Component)val).transform.root).name == "LightShaper.ModWindows.v1";
			if (flag2 || (!((flag ? 1f : val.color.a) * val.canvasRenderer.GetInheritedAlpha() < 0.03f) && !val.canvasRenderer.cull))
			{
				val.rectTransform.GetWorldCorners(_corners);
				Camera obj = (((int)val.canvas.renderMode == 0) ? null : val.canvas.worldCamera);
				Vector2 val3 = RectTransformUtility.WorldToScreenPoint(obj, _corners[0]);
				Vector2 val4 = RectTransformUtility.WorldToScreenPoint(obj, _corners[2]);
				Rect val5 = Rect.MinMaxRect(Mathf.Min(val3.x, val4.x), (float)Screen.height - Mathf.Max(val3.y, val4.y), Mathf.Max(val3.x, val4.x), (float)Screen.height - Mathf.Min(val3.y, val4.y));
				if (!(((Rect)(ref val5)).width > (float)Screen.width * 0.95f) || !(((Rect)(ref val5)).height > (float)Screen.height * 0.95f) || flag2)
				{
					((Rect)(ref val5)).xMin = ((Rect)(ref val5)).xMin - 6f;
					((Rect)(ref val5)).yMin = ((Rect)(ref val5)).yMin - 6f;
					((Rect)(ref val5)).xMax = ((Rect)(ref val5)).xMax + 6f;
					((Rect)(ref val5)).yMax = ((Rect)(ref val5)).yMax + 6f;
					_obstacles.Add(new DockLayout.Box(((Rect)(ref val5)).x, ((Rect)(ref val5)).y, ((Rect)(ref val5)).width, ((Rect)(ref val5)).height));
				}
			}
		}
		Transform[] array2 = (from Transform t in (IEnumerable)((Component)this).transform.parent
			where (Object)(object)((Component)t).GetComponent<Button>() != (Object)null
			select t).ToArray();
		float scale = UiEnvironment.Scale;
		Rect bounds;
		float gap;
		float preferredTop;
		bool num = NativeSidebar.TryGeometry(out bounds, out gap, out preferredTop);
		Vector2 size = ((Rect)(ref bounds)).size;
		DockLayout.Box result = default(DockLayout.Box);
		bool flag3 = num && DockLayout.FindRight(Screen.width, Screen.height, ((Rect)(ref bounds)).x, size.x, size.y, gap, preferredTop, 6f * scale, array2.Length, _obstacles, out result);
		Vector2 val7 = default(Vector2);
		for (int num2 = 0; num2 < array2.Length; num2++)
		{
			RectTransform val6 = (RectTransform)array2[num2];
			((Vector2)(ref val7))..ctor(0f, 1f);
			val6.pivot = val7;
			Vector2 anchorMin = (val6.anchorMax = val7);
			val6.anchorMin = anchorMin;
			val6.sizeDelta = size;
			val6.anchoredPosition = (flag3 ? new Vector2(result.X, 0f - result.Y - (float)num2 * (size.y + gap)) : new Vector2(-10000f, -10000f));
		}
	}

	private static Graphic[] GraphicRegistryAll()
	{
		return Object.FindObjectsByType<Graphic>((FindObjectsInactive)0, (FindObjectsSortMode)0);
	}

	public void OnPointerEnter(PointerEventData data)
	{
		_hover = true;
	}

	public void OnPointerExit(PointerEventData data)
	{
		_hover = false;
	}

	private void OnDestroy()
	{
		Object.Destroy((Object)(object)_background);
		Object.Destroy((Object)(object)_icon);
		Object.Destroy((Object)(object)_backgroundTexture);
		Object.Destroy((Object)(object)_iconTexture);
		if ((Object)(object)((Component)this).transform.parent != (Object)null && ((Component)this).transform.parent.childCount == 1)
		{
			Object.Destroy((Object)(object)((Component)((Component)this).transform.parent).gameObject);
		}
	}

	private static Texture2D RoundedTexture()
	{
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		Color[] array = (Color[])(object)new Color[4096];
		for (int i = 0; i < 64; i++)
		{
			for (int j = 0; j < 64; j++)
			{
				float num = Mathf.Abs((float)j + 0.5f - 32f) - 18f;
				float num2 = Mathf.Abs((float)i + 0.5f - 32f) - 18f;
				Vector2 val = new Vector2(Mathf.Max(num, 0f), Mathf.Max(num2, 0f));
				float num3 = ((Vector2)(ref val)).magnitude + Mathf.Min(Mathf.Max(num, num2), 0f) - 14f;
				Color val2 = Color.Lerp(new Color(0.43f, 0.34f, 0.35f, 1f), new Color(1f, 0.95f, 0.86f, 1f), Mathf.Clamp01(0.5f - num3 - 4f));
				val2.a = Mathf.Clamp01(0.5f - num3);
				array[i * 64 + j] = val2;
			}
		}
		return Texture(array, 64);
	}

	private static Texture2D IconTexture(string symbol)
	{
		//IL_0484: Unknown result type (might be due to invalid IL or missing references)
		//IL_0489: Unknown result type (might be due to invalid IL or missing references)
		//IL_048d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0494: Unknown result type (might be due to invalid IL or missing references)
		//IL_04a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_04a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_04b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_04b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_04be: Unknown result type (might be due to invalid IL or missing references)
		//IL_04c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_04c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_04c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_04c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_04cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_04cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_04d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_04e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_04eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_04f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_053f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0544: Unknown result type (might be due to invalid IL or missing references)
		List<Vector4> lines = new List<Vector4>();
		switch (symbol)
		{
		case "camera":
			Box(4f, 9f, 24f, 17f);
			Box(10f, 5f, 10f, 4f);
			Circle(lines, 16f, 17f, 6f);
			break;
		case "sound":
			Box(4f, 13f, 6f, 8f);
			Line(10f, 13f, 17f, 7f);
			Line(17f, 7f, 17f, 26f);
			Line(17f, 26f, 10f, 21f);
			Line(22f, 11f, 26f, 15f);
			Line(26f, 15f, 26f, 19f);
			Line(26f, 19f, 22f, 23f);
			break;
		case "range":
			Circle(lines, 16f, 16f, 11f);
			Line(16f, 2f, 16f, 9f);
			Line(16f, 23f, 16f, 30f);
			Line(2f, 16f, 9f, 16f);
			Line(23f, 16f, 30f, 16f);
			break;
		case "voice":
			Box(12f, 4f, 8f, 17f);
			Line(7f, 16f, 7f, 23f);
			Line(7f, 23f, 25f, 23f);
			Line(25f, 23f, 25f, 16f);
			Line(16f, 23f, 16f, 29f);
			Line(10f, 29f, 22f, 29f);
			break;
		case "move":
			Line(16f, 29f, 16f, 3f);
			Line(16f, 3f, 10f, 9f);
			Line(16f, 3f, 22f, 9f);
			Line(16f, 29f, 10f, 23f);
			Line(16f, 29f, 22f, 23f);
			Line(3f, 16f, 29f, 16f);
			Line(3f, 16f, 9f, 10f);
			Line(3f, 16f, 9f, 22f);
			Line(29f, 16f, 23f, 10f);
			Line(29f, 16f, 23f, 22f);
			break;
		default:
			Box(4f, 5f, 24f, 18f);
			Line(9f, 23f, 9f, 28f);
			Line(9f, 28f, 15f, 23f);
			Line(10f, 11f, 22f, 11f);
			Line(10f, 17f, 18f, 17f);
			break;
		}
		Color[] array = (Color[])(object)new Color[1024];
		Vector2 val = default(Vector2);
		Vector2 val2 = default(Vector2);
		for (int i = 0; i < 32; i++)
		{
			for (int j = 0; j < 32; j++)
			{
				((Vector2)(ref val))..ctor((float)j + 0.5f, 31.5f - (float)i);
				float num = 100f;
				foreach (Vector4 item in lines)
				{
					((Vector2)(ref val2))..ctor(item.x, item.y);
					Vector2 val3 = new Vector2(item.z, item.w) - val2;
					float num2 = num;
					Vector2 val4 = val - val2 - val3 * Mathf.Clamp01(Vector2.Dot(val - val2, val3) / ((Vector2)(ref val3)).sqrMagnitude);
					num = Mathf.Min(num2, ((Vector2)(ref val4)).magnitude);
				}
				array[i * 32 + j] = new Color(1f, 1f, 1f, Mathf.Clamp01(2.2f - num));
			}
		}
		return Texture(array);
		void Box(float x, float y, float w, float h)
		{
			Line(x, y, x + w, y);
			Line(x + w, y, x + w, y + h);
			Line(x + w, y + h, x, y + h);
			Line(x, y + h, x, y);
		}
		void Line(float x, float y, float a, float b)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			lines.Add(new Vector4(x, y, a, b));
		}
	}

	private static void Circle(List<Vector4> lines, float x, float y, float radius)
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		for (int i = 0; i < 32; i++)
		{
			float num = (float)i * MathF.PI / 16f;
			float num2 = (float)(i + 1) * MathF.PI / 16f;
			lines.Add(new Vector4(x + Mathf.Cos(num) * radius, y + Mathf.Sin(num) * radius, x + Mathf.Cos(num2) * radius, y + Mathf.Sin(num2) * radius));
		}
	}

	private static Texture2D Texture(Color[] pixels, int size = 32)
	{
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Expected O, but got Unknown
		Texture2D val = new Texture2D(size, size, (TextureFormat)4, false)
		{
			hideFlags = (HideFlags)61,
			filterMode = (FilterMode)1,
			wrapMode = (TextureWrapMode)1
		};
		val.SetPixels(pixels);
		val.Apply(false, true);
		return val;
	}
}
internal static class NativeSidebar
{
	private static readonly FieldInfo RightButtons = AccessTools.Field(typeof(OverlayManager), "_rightTopButtons");

	private static readonly FieldInfo IdleColor = AccessTools.Field(typeof(UIManager), "_extraButtonColor");

	private static readonly FieldInfo HoverColor = AccessTools.Field(typeof(UIManager), "_extraButtonHoverColor");

	private static UIManager _ui;

	private static OverlayManager _overlay;

	private static Button _button;

	private static float _retry;

	private static readonly Vector3[] Corners = (Vector3[])(object)new Vector3[4];

	internal static Button Button
	{
		get
		{
			if (((Object)(object)_overlay == (Object)null || (Object)(object)_button == (Object)null) && Time.unscaledTime >= _retry)
			{
				_retry = Time.unscaledTime + 0.5f;
				_overlay = Object.FindAnyObjectByType<OverlayManager>();
				if ((Object)(object)_overlay != (Object)null && RightButtons?.GetValue(_overlay) is List<GameObject> list)
				{
					foreach (GameObject item in list)
					{
						if ((Object)(object)item == (Object)null)
						{
							continue;
						}
						Button componentInChildren = item.GetComponentInChildren<Button>(true);
						if (!((Object)(object)componentInChildren == (Object)null))
						{
							Image obj = Background(componentInChildren);
							if (!((Object)(object)((obj != null) ? obj.sprite : null) == (Object)null))
							{
								_button = componentInChildren;
								break;
							}
						}
					}
				}
			}
			return _button;
		}
	}

	internal static float Opacity
	{
		get
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Invalid comparison between Unknown and I4
			Button button = Button;
			Image val = Background(button);
			if ((Object)(object)_overlay == (Object)null || (Object)(object)button == (Object)null || (Object)(object)val == (Object)null)
			{
				return 0f;
			}
			Canvas canvas = ((Graphic)val).canvas;
			float inheritedAlpha = ((Graphic)val).canvasRenderer.GetInheritedAlpha();
			if (!SidebarVisibility.Show((int)_overlay.ResolutionMode == 3, ((Component)button).gameObject.activeInHierarchy, (Object)(object)canvas != (Object)null && ((Behaviour)canvas).isActiveAndEnabled, inheritedAlpha))
			{
				return 0f;
			}
			return inheritedAlpha;
		}
	}

	internal static Vector2 Size
	{
		get
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			Button button = Button;
			Image val = Background(button);
			if ((Object)(object)button == (Object)null || (Object)(object)val == (Object)null || (Object)(object)((Graphic)val).canvas == (Object)null)
			{
				return Vector2.zero;
			}
			Rect val2 = ScreenRect((RectTransform)((Component)button).transform, ((Graphic)val).canvas);
			return ((Rect)(ref val2)).size;
		}
	}

	internal static Image Background(Button button)
	{
		object obj;
		if (!((Object)(object)button == (Object)null))
		{
			obj = ((Component)button).GetComponent<Image>();
			if (obj == null)
			{
				Graphic targetGraphic = ((Selectable)button).targetGraphic;
				return (Image)(object)((targetGraphic is Image) ? targetGraphic : null);
			}
		}
		else
		{
			obj = null;
		}
		return (Image)obj;
	}

	internal static Image Outline(Button button)
	{
		if (!((Object)(object)button == (Object)null))
		{
			Transform obj = ((Component)button).transform.Find("Image_Outline");
			if (obj == null)
			{
				return null;
			}
			return ((Component)obj).GetComponent<Image>();
		}
		return null;
	}

	internal static Image Icon(Button button)
	{
		if (!((Object)(object)button == (Object)null))
		{
			Transform obj = ((Component)button).transform.Find("Image_Icon");
			if (obj == null)
			{
				return null;
			}
			return ((Component)obj).GetComponent<Image>();
		}
		return null;
	}

	internal static Color SurfaceColor(bool highlighted)
	{
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)_ui == (Object)null)
		{
			_ui = Object.FindAnyObjectByType<UIManager>();
		}
		FieldInfo fieldInfo = (highlighted ? HoverColor : IdleColor);
		if ((Object)(object)_ui != (Object)null)
		{
			object obj = fieldInfo?.GetValue(_ui);
			if (obj is Color)
			{
				return (Color)obj;
			}
		}
		return new Color(0.9608f, 0.9294f, 0.8824f, highlighted ? 1f : 0.749f);
	}

	internal static Rect ScreenRect(RectTransform rect, Canvas canvas)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		rect.GetWorldCorners(Corners);
		Camera obj = (((int)canvas.renderMode == 0) ? null : canvas.worldCamera);
		Vector2 val = RectTransformUtility.WorldToScreenPoint(obj, Corners[0]);
		Vector2 val2 = RectTransformUtility.WorldToScreenPoint(obj, Corners[2]);
		return Rect.MinMaxRect(Mathf.Min(val.x, val2.x), (float)Screen.height - Mathf.Max(val.y, val2.y), Mathf.Max(val.x, val2.x), (float)Screen.height - Mathf.Min(val.y, val2.y));
	}

	internal static float PixelScale(Image image)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		Rect val = ScreenRect(((Graphic)image).rectTransform, ((Graphic)image).canvas);
		float height = ((Rect)(ref val)).height;
		val = ((Graphic)image).rectTransform.rect;
		return height / Mathf.Max(1f, ((Rect)(ref val)).height);
	}

	internal static void CopyImage(Image source, Image target)
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		target.sprite = source.sprite;
		target.type = source.type;
		((Graphic)target).material = ((Graphic)source).material;
		((Graphic)target).color = ((Graphic)source).color;
		target.preserveAspect = source.preserveAspect;
		target.fillCenter = source.fillCenter;
		((MaskableGraphic)target).maskable = ((MaskableGraphic)source).maskable;
		float num = ((Graphic)target).canvas.referencePixelsPerUnit / ((Graphic)source).canvas.referencePixelsPerUnit;
		target.pixelsPerUnitMultiplier = source.pixelsPerUnitMultiplier * num / Mathf.Max(0.01f, PixelScale(source));
	}

	internal static void CopyRect(RectTransform source, RectTransform target, float scale)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		target.anchorMin = source.anchorMin;
		target.anchorMax = source.anchorMax;
		target.pivot = source.pivot;
		target.sizeDelta = source.sizeDelta * scale;
		target.anchoredPosition = source.anchoredPosition * scale;
		((Transform)target).localScale = ((Transform)source).localScale;
		((Transform)target).localRotation = ((Transform)source).localRotation;
	}

	internal static bool TryGeometry(out Rect bounds, out float gap, out float preferredTop)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Expected O, but got Unknown
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Expected O, but got Unknown
		//IL_0154: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Unknown result type (might be due to invalid IL or missing references)
		bounds = default(Rect);
		gap = (preferredTop = 0f);
		Button button = Button;
		Image val = Background(button);
		if ((Object)(object)val == (Object)null || (Object)(object)((Graphic)val).canvas == (Object)null)
		{
			return false;
		}
		bounds = ScreenRect((RectTransform)((Component)button).transform, ((Graphic)val).canvas);
		if (((Rect)(ref bounds)).width < 1f || ((Rect)(ref bounds)).height < 1f)
		{
			return false;
		}
		float num = float.MaxValue;
		float num2 = ((Rect)(ref bounds)).y;
		if ((Object)(object)_overlay != (Object)null && RightButtons?.GetValue(_overlay) is List<GameObject> list)
		{
			foreach (GameObject item in list)
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				Button[] componentsInChildren = item.GetComponentsInChildren<Button>(true);
				foreach (Button val2 in componentsInChildren)
				{
					Image val3 = Background(val2);
					if (!((Component)val2).gameObject.activeInHierarchy || (Object)(object)val3 == (Object)null || (Object)(object)((Graphic)val3).canvas == (Object)null || (Object)(object)val3.sprite != (Object)(object)val.sprite)
					{
						continue;
					}
					Rect val4 = ScreenRect((RectTransform)((Component)val2).transform, ((Graphic)val3).canvas);
					if (!(Mathf.Abs(((Rect)(ref val4)).x - ((Rect)(ref bounds)).x) > ((Rect)(ref bounds)).height * 0.15f) && !(Mathf.Abs(((Rect)(ref val4)).height - ((Rect)(ref bounds)).height) > ((Rect)(ref bounds)).height * 0.15f))
					{
						num2 = Mathf.Max(num2, ((Rect)(ref val4)).y);
						float num3 = Mathf.Abs(((Rect)(ref val4)).y - ((Rect)(ref bounds)).y);
						if (num3 > ((Rect)(ref bounds)).height)
						{
							num = Mathf.Min(num, num3);
						}
					}
				}
			}
		}
		gap = ((num < float.MaxValue) ? (num - ((Rect)(ref bounds)).height) : (((Rect)(ref bounds)).height * 0.35f));
		preferredTop = num2 + ((Rect)(ref bounds)).height + gap;
		return true;
	}
}
public enum PlayWhen
{
	Always,
	NotViewing,
	Unfocused
}
public enum UiLanguage
{
	Auto,
	English,
	Russian
}
[BepInPlugin("ontogether.chatsounds", "ChatSounds", "1.1.2")]
[BepInProcess("OnTogether.exe")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
	public const string PluginGuid = "ontogether.chatsounds";

	public const string PluginName = "ChatSounds";

	public const string PluginVersion = "1.1.2";

	private const float ConfigPollInterval = 1f;

	private const float ConfigSettleTime = 0.5f;

	private const float SaveDelay = 0.75f;

	private const float RetryDelay = 2f;

	internal ConfigEntry<bool> Enabled;

	internal ConfigEntry<int> MasterVolume;

	internal ConfigEntry<bool> FollowGameVolume;

	internal ConfigEntry<bool> QuietDuringFocus;

	internal ConfigEntry<UiLanguage> Language;

	internal ConfigEntry<KeyboardShortcut> WindowKey;

	internal ConfigEntry<KeyboardShortcut> ToggleKey;

	internal ConfigEntry<bool> MatchMyName;

	internal ConfigEntry<string> Keywords;

	internal SoundCategory Global;

	internal SoundCategory Local;

	internal SoundCategory Mentions;

	internal SoundCategory[] Categories;

	private GameObject _host;

	private SettingsWindow _window;

	private ModDock _dock;

	private Harmony _harmony;

	private List<string> _keywords = new List<string>();

	private readonly Dictionary<ConfigEntryBase, object> _unsaved = new Dictionary<ConfigEntryBase, object>();

	private bool _reloading;

	private float _saveAt = -1f;

	private float _nextConfigPoll;

	private float _reloadAt = -1f;

	private DateTime _configStamp;

	private DateTime _pendingStamp;

	private bool _fileErrorLogged;

	private string _lastError;

	internal static Plugin Instance { get; private set; }

	internal static ManualLogSource Log { get; private set; }

	internal SoundLibrary Sounds { get; private set; }

	internal IList<string> KeywordList => _keywords;

	private void Awake()
	{
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		//IL_013d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Expected O, but got Unknown
		//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		BindConfig();
		ResolveDefaultHotkeyConflict();
		UiEnvironment.LanguageOverride = () => Lang.Current == Lang.Russian;
		((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
		_keywords = MentionMatcher.ParseKeywords(Keywords.Value);
		_configStamp = ConfigStamp();
		_host = new GameObject("ChatSounds")
		{
			hideFlags = (HideFlags)61
		};
		Object.DontDestroyOnLoad((Object)(object)_host);
		Sounds = _host.AddComponent<SoundLibrary>();
		Sounds.Init(Path.Combine(Paths.ConfigPath, "ChatSounds"));
		_window = _host.AddComponent<SettingsWindow>();
		((Behaviour)_window).enabled = false;
		_dock = ModDock.Register("ChatSounds", "sound", _window.Toggle, () => ((Behaviour)_window).enabled, () => "ChatSounds · " + ((object)WindowKey.Value/*cast due to .constrained prefix*/).ToString(), () => (Object)(object)GameAccess.Chat != (Object)null);
		_harmony = new Harmony("ontogether.chatsounds");
		UiEnvironment.InstallInputGuard(_harmony);
		Patch(typeof(MessagePatch), "no sounds will play");
		Patch(typeof(ChatCommandPatch), "the /chatsound command will not work");
		ChatCommands.RegisterWithCommandApi();
		((BaseUnityPlugin)this).Config.SettingChanged += OnSettingChanged;
		SoundCategory[] categories = Categories;
		foreach (SoundCategory soundCategory in categories)
		{
			Sounds.Preload(soundCategory.Sound.Value);
		}
		Log.LogInfo((object)string.Format("{0} {1} loaded. Settings window: {2} or /chatsound", "ChatSounds", "1.1.2", WindowKey.Value));
	}

	private void BindConfig()
	{
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Expected O, but got Unknown
		//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_010b: Unknown result type (might be due to invalid IL or missing references)
		Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Play a sound when another player's chat message arrives.");
		MasterVolume = ((BaseUnityPlugin)this).Config.Bind<int>("General", "MasterVolume", 80, new ConfigDescription("Volume of all chat sounds, in percent.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
		FollowGameVolume = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "FollowGameVolume", true, "Also scale chat sounds by the game's Master volume setting.");
		QuietDuringFocus = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "QuietDuringFocus", false, "While you are in a focus session, only mentions make a sound.");
		Language = ((BaseUnityPlugin)this).Config.Bind<UiLanguage>("General", "Language", UiLanguage.Auto, "Language of the settings window and of the mod's chat messages. Auto follows the game's language.");
		WindowKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "SettingsWindow", new KeyboardShortcut((KeyCode)285, Array.Empty<KeyCode>()), "Opens or closes the settings window (same as typing /chatsound). Ignored while typing.");
		ToggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "ToggleSounds", new KeyboardShortcut((KeyCode)285, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Turns all chat sounds on or off. Ignored while typing.");
		Global = new SoundCategory(((BaseUnityPlugin)this).Config, "Global", "Play a sound for new messages in the global chat.", "Ping", 60, 3f);
		Local = new SoundCategory(((BaseUnityPlugin)this).Config, "Local", "Play a sound for new messages in the local chat (players near you).", "Bubble", 80, 1f);
		Mentions = new SoundCategory(((BaseUnityPlugin)this).Config, "Mentions", "Play a separate sound when a message mentions you (in either chat). For that message it replaces the global/local sound.", "Alert", 100, 1f);
		MatchMyName = ((BaseUnityPlugin)this).Config.Bind<bool>("Mentions", "MatchMyName", true, "A message that contains your in-game name counts as a mention.");
		Keywords = ((BaseUnityPlugin)this).Config.Bind<string>("Mentions", "Keywords", "", "More words that count as a mention, separated by commas, e.g. nicknames: mark, markus. Case does not matter; only whole words match.");
		Categories = new SoundCategory[3] { Global, Local, Mentions };
	}

	private unsafe void ResolveDefaultHotkeyConflict()
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		bool movementPresent = Chainloader.PluginInfos.ContainsKey("ontogether.movementplus");
		KeyboardShortcut value = MigrateLegacyShortcut(WindowKey.Value, movementPresent, toggle: false);
		KeyboardShortcut value2 = MigrateLegacyShortcut(ToggleKey.Value, movementPresent, toggle: true);
		bool num = !((object)(*(KeyboardShortcut*)(&value))/*cast due to .constrained prefix*/).Equals((object?)WindowKey.Value) || !((object)(*(KeyboardShortcut*)(&value2))/*cast due to .constrained prefix*/).Equals((object?)ToggleKey.Value);
		WindowKey.Value = value;
		ToggleKey.Value = value2;
		if (num)
		{
			Log.LogInfo((object)"Default F9 conflict resolved: settings F4, sounds LeftShift+F4. Custom shortcuts retained.");
		}
	}

	internal unsafe static KeyboardShortcut MigrateLegacyShortcut(KeyboardShortcut current, bool movementPresent, bool toggle)
	{
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		KeyboardShortcut val = (toggle ? new KeyboardShortcut((KeyCode)290, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }) : new KeyboardShortcut((KeyCode)290, Array.Empty<KeyCode>()));
		if (!movementPresent || !((object)(*(KeyboardShortcut*)(&current))/*cast due to .constrained prefix*/).Equals((object?)val))
		{
			return current;
		}
		if (!toggle)
		{
			return new KeyboardShortcut((KeyCode)285, Array.Empty<KeyCode>());
		}
		return new KeyboardShortcut((KeyCode)285, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 });
	}

	private void Patch(Type patchClass, string consequence)
	{
		try
		{
			_harmony.CreateClassProcessor(patchClass).Patch();
		}
		catch (Exception arg)
		{
			Log.LogError((object)$"Could not patch the game ({consequence}): {arg}");
		}
	}

	private void Update()
	{
		try
		{
			HandleHotkeys();
			PollConfigFile();
			if (_saveAt >= 0f && Time.unscaledTime >= _saveAt)
			{
				SaveNow();
			}
		}
		catch (Exception e)
		{
			LogOnce("Update failed: ", e);
		}
	}

	private void HandleHotkeys()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		KeyboardShortcut value = ToggleKey.Value;
		KeyboardShortcut value2 = WindowKey.Value;
		bool flag = Pressed(value);
		bool flag2 = Pressed(value2);
		if (!flag && !flag2)
		{
			return;
		}
		if (flag && flag2)
		{
			if (((KeyboardShortcut)(ref value)).Modifiers.Count() >= ((KeyboardShortcut)(ref value2)).Modifiers.Count())
			{
				flag2 = false;
			}
			else
			{
				flag = false;
			}
		}
		if (!GameAccess.IsAnyTextFieldFocused())
		{
			if (flag)
			{
				SetEnabled(!Enabled.Value, notify: true);
			}
			else
			{
				ToggleWindow();
			}
		}
	}

	private static bool Pressed(KeyboardShortcut shortcut)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		KeyCode mainKey = ((KeyboardShortcut)(ref shortcut)).MainKey;
		if ((int)mainKey == 0 || !Input.GetKeyDown(mainKey))
		{
			return false;
		}
		foreach (KeyCode modifier in ((KeyboardShortcut)(ref shortcut)).Modifiers)
		{
			if (!Input.GetKey(modifier))
			{
				return false;
			}
		}
		return true;
	}

	internal void OnMessageShown(string text, bool isLocal)
	{
		try
		{
			if (!Enabled.Value)
			{
				return;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if ((!Mentions.Enabled.Value || !IsMention(text) || !TryPlay(Mentions, isLocal, realtimeSinceStartup)) && (!QuietDuringFocus.Value || !GameAccess.IsLocalPlayerFocusing()))
			{
				SoundCategory soundCategory = (isLocal ? Local : Global);
				if (soundCategory.Enabled.Value)
				{
					TryPlay(soundCategory, isLocal, realtimeSinceStartup);
				}
			}
		}
		catch (Exception e)
		{
			LogOnce("Could not play a chat sound: ", e);
		}
	}

	private bool IsMention(string text)
	{
		string playerName = (MatchMyName.Value ? GameAccess.LocalPlayerName : null);
		return MentionMatcher.IsMention(text, playerName, _keywords);
	}

	private bool TryPlay(SoundCategory category, bool isLocal, float now)
	{
		if (!IsAllowed(category.When.Value, isLocal))
		{
			return false;
		}
		float num = EffectiveVolume(category);
		if (num <= 0f || !category.TryStartCooldown(now))
		{
			return false;
		}
		Sounds.Play(category.Sound.Value, num);
		return true;
	}

	private static bool IsAllowed(PlayWhen when, bool isLocal)
	{
		return when switch
		{
			PlayWhen.NotViewing => !GameAccess.IsChannelVisible(isLocal), 
			PlayWhen.Unfocused => !Application.isFocused, 
			_ => true, 
		};
	}

	internal float EffectiveVolume(SoundCategory category)
	{
		float num = (float)MasterVolume.Value / 100f * ((float)category.Volume.Value / 100f);
		if (FollowGameVolume.Value)
		{
			num *= GameAccess.GameMasterVolume;
		}
		return Mathf.Clamp01(num);
	}

	internal void Preview(SoundCategory category)
	{
		Sounds.Play(category.Sound.Value, EffectiveVolume(category));
	}

	internal void PreviewAll()
	{
		((MonoBehaviour)this).StartCoroutine(PreviewSequence());
	}

	private IEnumerator PreviewSequence()
	{
		SoundCategory[] categories = Categories;
		foreach (SoundCategory category in categories)
		{
			Preview(category);
			yield return (object)new WaitForSecondsRealtime(1f);
		}
	}

	internal void SetEnabled(bool enabled, bool notify)
	{
		Enabled.Value = enabled;
		if (notify)
		{
			GameAccess.Notify(enabled ? Lang.Current.SoundsOn : Lang.Current.SoundsOff);
		}
	}

	internal void ToggleWindow()
	{
		_window.Toggle();
	}

	internal string DescribeStatus(Lang lang)
	{
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.AppendFormat(lang.StatusFormat, Enabled.Value ? lang.On : lang.Off, MasterVolume.Value);
		SoundCategory[] categories = Categories;
		foreach (SoundCategory soundCategory in categories)
		{
			stringBuilder.Append('\n').AppendFormat(lang.CategoryStatus, soundCategory.Title(lang), soundCategory.Enabled.Value ? lang.On : lang.Off, Sounds.DisplayName(soundCategory.Sound.Value, lang), soundCategory.Volume.Value, lang.Describe(soundCategory.When.Value));
		}
		string text = MentionMatcher.StripTags(GameAccess.LocalPlayerName);
		stringBuilder.Append('\n').AppendFormat(lang.MentionStatus, (MatchMyName.Value && text.Length > 0) ? text : lang.None, (_keywords.Count > 0) ? MentionMatcher.JoinKeywords(_keywords) : lang.None);
		return stringBuilder.ToString();
	}

	private void OnSettingChanged(object sender, SettingChangedEventArgs e)
	{
		ConfigEntryBase changedSetting = e.ChangedSetting;
		if (!_reloading)
		{
			_unsaved[changedSetting] = changedSetting.BoxedValue;
			_saveAt = Time.unscaledTime + 0.75f;
		}
		if ((object)changedSetting == Keywords)
		{
			_keywords = MentionMatcher.ParseKeywords(Keywords.Value);
			return;
		}
		if ((object)changedSetting == Language)
		{
			Lang.Invalidate();
			return;
		}
		SoundCategory[] categories = Categories;
		foreach (SoundCategory soundCategory in categories)
		{
			if ((object)changedSetting == soundCategory.Sound)
			{
				Sounds.Preload(soundCategory.Sound.Value);
			}
		}
	}

	private void PollConfigFile()
	{
		float unscaledTime = Time.unscaledTime;
		if (_reloadAt >= 0f)
		{
			if (!(unscaledTime < _reloadAt))
			{
				DateTime dateTime = ConfigStamp();
				if (dateTime == _configStamp)
				{
					_reloadAt = -1f;
				}
				else if (dateTime != _pendingStamp)
				{
					_pendingStamp = dateTime;
					_reloadAt = unscaledTime + 0.5f;
				}
				else
				{
					_reloadAt = (TryReloadConfig() ? (-1f) : (unscaledTime + 2f));
				}
			}
		}
		else if (!(unscaledTime < _nextConfigPoll))
		{
			_nextConfigPoll = unscaledTime + 1f;
			DateTime dateTime2 = ConfigStamp();
			if (!(dateTime2 == _configStamp))
			{
				_pendingStamp = dateTime2;
				_reloadAt = unscaledTime + 0.5f;
			}
		}
	}

	private bool TryReloadConfig()
	{
		if (!File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath))
		{
			SaveNow();
			return true;
		}
		DateTime configStamp = ConfigStamp();
		_reloading = true;
		try
		{
			((BaseUnityPlugin)this).Config.Reload();
			foreach (KeyValuePair<ConfigEntryBase, object> item in _unsaved)
			{
				item.Key.BoxedValue = item.Value;
			}
		}
		catch (Exception ex)
		{
			LogFileErrorOnce("Could not read the config file, will try again: " + ex.Message);
			return false;
		}
		finally
		{
			_reloading = false;
		}
		_configStamp = configStamp;
		_fileErrorLogged = false;
		Log.LogInfo((object)"Settings reloaded from the config file.");
		return true;
	}

	private void SaveNow()
	{
		_saveAt = -1f;
		if (File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath) && ConfigStamp() != _configStamp && !TryReloadConfig())
		{
			_saveAt = Time.unscaledTime + 2f;
			return;
		}
		try
		{
			((BaseUnityPlugin)this).Config.Save();
			_unsaved.Clear();
			_configStamp = ConfigStamp();
			_fileErrorLogged = false;
		}
		catch (Exception ex)
		{
			LogFileErrorOnce("Could not save the settings, will try again: " + ex.Message);
			_saveAt = Time.unscaledTime + 2f;
		}
	}

	private void LogFileErrorOnce(string message)
	{
		if (!_fileErrorLogged)
		{
			_fileErrorLogged = true;
			Log.LogWarning((object)message);
		}
	}

	private DateTime ConfigStamp()
	{
		try
		{
			return File.GetLastWriteTimeUtc(((BaseUnityPlugin)this).Config.ConfigFilePath);
		}
		catch (Exception)
		{
			return default(DateTime);
		}
	}

	private void LogOnce(string what, Exception e)
	{
		string text = what + e.GetType().Name + ": " + e.Message;
		if (!(text == _lastError))
		{
			_lastError = text;
			Log.LogError((object)(what + e));
		}
	}

	private void OnApplicationQuit()
	{
		if (_saveAt >= 0f)
		{
			SaveNow();
		}
	}

	private void OnDestroy()
	{
		if ((Object)(object)_dock != (Object)null)
		{
			Object.Destroy((Object)(object)((Component)_dock).gameObject);
		}
		((BaseUnityPlugin)this).Config.SettingChanged -= OnSettingChanged;
		if (_saveAt >= 0f)
		{
			SaveNow();
		}
		if (_harmony != null)
		{
			_harmony.UnpatchSelf();
		}
		if ((Object)(object)_host != (Object)null)
		{
			Object.Destroy((Object)(object)_host);
		}
	}
}
internal sealed class SettingsWindow : MonoBehaviour
{
	private const int WindowId = 1129532996;

	private const float Width = 600f;

	private const float ArrowWidth = 26f;

	private const float PlayWidth = 32f;

	private const float ValueWidth = 54f;

	private const float MaxCooldown = 60f;

	private const float PreviewDelay = 0.3f;

	private static readonly GUILayoutOption[] Shrinkable = (GUILayoutOption[])(object)new GUILayoutOption[2]
	{
		GUILayout.MinWidth(40f),
		GUILayout.ExpandWidth(true)
	};

	private UiSkin _skin;

	private GUISkin _guiSkin;

	private WindowInputShield _shield;

	private int _tab;

	private int _pendingTab = -1;

	private readonly Vector2[] _tabScrolls = (Vector2[])(object)new Vector2[4];

	private bool _advanced;

	private bool _pendingAdvanced;

	private bool _changeAdvanced;

	private string _keywords;

	private bool _keywordDirty;

	private WindowFunction _drawWindow;

	private Rect _rect;

	private bool _placed;

	private float _screenHeight;

	private Vector2 _scroll;

	private SoundCategory _pendingPreview;

	private float _previewAt;

	private int _hotControl;

	private float LabelWidth => Mathf.Clamp((((Rect)(ref _rect)).width - 40f) * 0.32f, 90f, 170f);

	public void Toggle()
	{
		SetOpen(!((Behaviour)this).enabled);
	}

	public void SetOpen(bool open)
	{
		if (open == ((Behaviour)this).enabled)
		{
			return;
		}
		((Behaviour)this).enabled = open;
		if (_shield == null)
		{
			_shield = new WindowInputShield("ChatSounds");
		}
		_shield.Set(open);
		if (open)
		{
			Lang.Invalidate();
			Plugin.Instance.Sounds.Rescan();
			_keywords = Plugin.Instance.Keywords.Value;
			_keywordDirty = false;
			return;
		}
		_pendingPreview = null;
		if (_hotControl != 0 && GUIUtility.hotControl == _hotControl)
		{
			GUIUtility.hotControl = 0;
		}
		_hotControl = 0;
	}

	private void OnDisable()
	{
		_shield?.Set(open: false);
	}

	private void Update()
	{
		if (Input.GetKeyDown((KeyCode)27))
		{
			SetOpen(open: false);
		}
		if (_pendingPreview != null && Time.unscaledTime >= _previewAt)
		{
			Plugin.Instance.Preview(_pendingPreview);
			_pendingPreview = null;
		}
	}

	private void OnGUI()
	{
		//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Expected O, but got Unknown
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0110: Unknown result type (might be due to invalid IL or missing references)
		//IL_013b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0140: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d2: Invalid comparison between Unknown and I4
		//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
		if (UiEnvironment.PreviewRendering || (Object)(object)Plugin.Instance == (Object)null)
		{
			return;
		}
		if (_skin == null)
		{
			_skin = new UiSkin();
			_guiSkin = _skin.CreateGuiSkin(GUI.skin);
		}
		if (_drawWindow == null)
		{
			_drawWindow = new WindowFunction(DrawWindow);
		}
		float scale = UiEnvironment.Scale;
		Matrix4x4 matrix = GUI.matrix;
		GUISkin skin = GUI.skin;
		try
		{
			GUI.skin = _guiSkin;
			GUI.matrix = Matrix4x4.Scale(new Vector3(scale, scale, 1f));
			float num = (float)Screen.width / scale;
			_screenHeight = (float)Screen.height / scale;
			if (!_placed)
			{
				_rect = new Rect(Mathf.Round((num - 600f) * 0.5f), Mathf.Round(_screenHeight * 0.08f), 600f, 0f);
				_placed = true;
			}
			float num2 = Mathf.Min(600f, num - 24f);
			((Rect)(ref _rect)).width = num2;
			_rect = GUILayout.Window(1129532996, _rect, _drawWindow, GUIContent.none, _skin.Window, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num2) });
			((Rect)(ref _rect)).x = Mathf.Clamp(((Rect)(ref _rect)).x, 0f, Mathf.Max(0f, num - ((Rect)(ref _rect)).width));
			((Rect)(ref _rect)).y = Mathf.Clamp(((Rect)(ref _rect)).y, 0f, Mathf.Max(0f, _screenHeight - ((Rect)(ref _rect)).height));
		}
		finally
		{
			GUI.matrix = matrix;
			GUI.skin = skin;
		}
		if ((int)Event.current.type == 7)
		{
			_shield?.Place(_rect, scale);
		}
	}

	private void DrawWindow(int id)
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Invalid comparison between Unknown and I4
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0234: Unknown result type (might be due to invalid IL or missing references)
		//IL_0264: Unknown result type (might be due to invalid IL or missing references)
		//IL_0269: Unknown result type (might be due to invalid IL or missing references)
		//IL_0363: Unknown result type (might be due to invalid IL or missing references)
		//IL_0373: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
		Plugin instance = Plugin.Instance;
		Lang current = Lang.Current;
		int hotControl = GUIUtility.hotControl;
		if ((int)Event.current.type == 8)
		{
			if (_pendingTab >= 0)
			{
				_tabScrolls[_tab] = _scroll;
				_tab = _pendingTab;
				_pendingTab = -1;
				_scroll = _tabScrolls[_tab];
				GUI.FocusControl((string)null);
			}
			if (_changeAdvanced)
			{
				_advanced = _pendingAdvanced;
				_changeAdvanced = false;
			}
		}
		GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
		GUILayout.Label("CS", _skin.Logo, Array.Empty<GUILayoutOption>());
		GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
		GUILayout.Label("ChatSounds", _skin.Title, Array.Empty<GUILayoutOption>());
		GUILayout.Label(UiEnvironment.L("Chat notifications", "Уведомления чата"), _skin.Subtitle, Array.Empty<GUILayoutOption>());
		GUILayout.EndVertical();
		GUILayout.FlexibleSpace();
		if (GUILayout.Button("×", _skin.CloseButton, Array.Empty<GUILayoutOption>()))
		{
			SetOpen(open: false);
		}
		GUILayout.EndHorizontal();
		GUILayout.Space(8f);
		string[] array = new string[4]
		{
			UiEnvironment.L("General", "Общее"),
			current.GlobalChat,
			current.LocalChat,
			current.Mentions
		};
		int num = ((((Rect)(ref _rect)).width < 480f) ? 2 : 4);
		for (int i = 0; i < 4; i += num)
		{
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			for (int j = i; j < i + num; j++)
			{
				if (GUILayout.Button(array[j], (j == _tab) ? _skin.SelectedTab : _skin.Tab, Array.Empty<GUILayoutOption>()))
				{
					_pendingTab = j;
				}
			}
			GUILayout.EndHorizontal();
		}
		GUILayout.Space(8f);
		float num2 = Mathf.Min(430f, Mathf.Max(80f, _screenHeight - ((((Rect)(ref _rect)).width < 480f) ? 290f : 250f)));
		_scroll = GUILayout.BeginScrollView(_scroll, false, false, GUI.skin.horizontalScrollbar, GUI.skin.verticalScrollbar, GUIStyle.none, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(num2) });
		GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
		DrawSettings(instance, current);
		GUILayout.EndVertical();
		GUILayout.EndScrollView();
		GUILayout.Space(10f);
		GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
		if (GUILayout.Button(current.OpenFolder, _skin.Button, Array.Empty<GUILayoutOption>()))
		{
			instance.Sounds.OpenFolder();
		}
		if (GUILayout.Button(current.Rescan, _skin.Button, Array.Empty<GUILayoutOption>()))
		{
			instance.Sounds.Rescan();
		}
		GUILayout.FlexibleSpace();
		if (GUILayout.Button(current.Close, _skin.Button, Array.Empty<GUILayoutOption>()))
		{
			SetOpen(open: false);
		}
		GUILayout.EndHorizontal();
		GUILayout.Space(6f);
		GUILayout.Label(string.Format(current.FilesHint, instance.Sounds.FileCount), _skin.Hint, Array.Empty<GUILayoutOption>());
		GUILayout.Label(string.Format(current.WindowHint, instance.WindowKey.Value, instance.ToggleKey.Value), _skin.Hint, Array.Empty<GUILayoutOption>());
		GUI.DragWindow(new Rect(0f, 0f, ((Rect)(ref _rect)).width - 48f, 62f));
		if (GUIUtility.hotControl != hotControl)
		{
			_hotControl = GUIUtility.hotControl;
		}
	}

	private void DrawSettings(Plugin plugin, Lang lang)
	{
		if (_tab == 0)
		{
			GUILayout.BeginVertical(_ski