Decompiled source of Tweaks v1.0.0

BepInEx/plugins/DiceModders.Tweaks.dll

Decompiled 9 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using DiceKingdoms.Game;
using DiceKingdoms.Interface;
using DiceKingdoms.Meta;
using DiceModders.ModCore;
using DiceModders.ModCore.Tools;
using DiceModders.UiKit;
using DiceModders.UiKit.Custom;
using DiceModders.UiKit.Native;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using Steamworks.Data;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("DiceModders")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Interface and lobby tweaks for Dice Kingdoms: anonymous attacks, chat and event history, next-host chooser, chat and event log options.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DiceModders.Tweaks")]
[assembly: AssemblyTitle("DiceModders.Tweaks")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DiceModders.Tweaks
{
	internal static class AnonymousAttacks
	{
		private static LobbyRule<bool> _rule;

		private static Type _summaryType;

		internal static bool Active
		{
			get
			{
				if (Plugin.On && _rule != null)
				{
					return _rule.Value;
				}
				return false;
			}
		}

		internal static void Install(Patcher patcher)
		{
			_rule = Rules.Toggle("tweaks.anonymousAttacks", "Anonymous attacks", false, "Hides who is attacking: no attacker flags next to the player names, no attack summaries at the top right of the scoreboard, and every other player's models in one grey colour.", (Func<bool>)null, false);
			_rule.Changed += delegate
			{
				RefreshAll();
			};
			patcher.Patch("PlayerSummary", "OnEnable", typeof(AnonymousAttacks), (string)null, "SummaryPostfix");
			patcher.Patch("PlayerSummary", "OnSyncPhase", typeof(AnonymousAttacks), (string)null, "SummaryPostfix");
			patcher.Patch("Scoreboard", "OnCombatStart", typeof(AnonymousAttacks), "CombatStartPrefix", (string)null);
		}

		internal static bool CombatStartPrefix()
		{
			return !Active;
		}

		internal static void SummaryPostfix(object __instance)
		{
			try
			{
				Apply(__instance);
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("anonymous attacks: " + ex.Message));
			}
		}

		private static void Apply(object summary)
		{
			object obj = default(object);
			if (!Reflect.TryGetMember(summary, "attackerPrefab", ref obj))
			{
				return;
			}
			Component val = (Component)((obj is Component) ? obj : null);
			if (val == null || (Object)(object)val.gameObject == (Object)null)
			{
				return;
			}
			GameObject gameObject = val.gameObject;
			CanvasGroup val2 = gameObject.GetComponent<CanvasGroup>();
			if ((Object)(object)val2 == (Object)null)
			{
				if (!Active)
				{
					return;
				}
				val2 = gameObject.AddComponent<CanvasGroup>();
			}
			val2.alpha = (Active ? 0f : 1f);
			val2.blocksRaycasts = !Active;
		}

		internal static void RefreshAll()
		{
			try
			{
				if ((object)_summaryType == null)
				{
					_summaryType = GameTypes.Find("PlayerSummary");
				}
				if (_summaryType == null)
				{
					return;
				}
				foreach (Object item in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.From(_summaryType)))
				{
					Apply(Reflect.Wrap(_summaryType, Mem.PtrOf((object)item)));
				}
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("anonymous attacks: refresh failed: " + ex.Message));
			}
		}
	}
	internal static class AnonymousColours
	{
		private static readonly HashSet<IntPtr> PlayerPalettes = new HashSet<IntPtr>();

		private static Texture2D _grey;

		private static IntPtr _greyOf;

		internal static void Install(Patcher patcher)
		{
			patcher.Patch(typeof(ColoredPaperOverrides), "SetColorPalette", typeof(AnonymousColours), "PalettePrefix", (string)null);
			patcher.Patch(typeof(ColoredPaperOverrides), "SlowSetColorPalette", typeof(AnonymousColours), "PalettePrefix", (string)null);
		}

		internal static void PalettePrefix(ref Texture __0)
		{
			if (!AnonymousAttacks.Active || (Object)(object)__0 == (Object)null)
			{
				return;
			}
			try
			{
				Player localPlayer = Player.LocalPlayer;
				object obj;
				if (localPlayer == null)
				{
					obj = null;
				}
				else
				{
					PlayerColor color = localPlayer.Color;
					obj = ((color != null) ? color.CustomColorPalette : null);
				}
				Texture2D val = (Texture2D)obj;
				if (!((Object)(object)val == (Object)null) && !(((Il2CppObjectBase)__0).Pointer == ((Il2CppObjectBase)val).Pointer) && IsPlayerPalette(__0))
				{
					__0 = (Texture)(object)Grey(val);
				}
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("anonymous colours: " + ex.Message));
			}
		}

		private static bool IsPlayerPalette(Texture t)
		{
			if (PlayerPalettes.Count == 0)
			{
				foreach (PlayerColors item in Resources.FindObjectsOfTypeAll<PlayerColors>())
				{
					foreach (PlayerColor item2 in (Il2CppArrayBase<PlayerColor>)(object)item.Colors)
					{
						if ((Object)(object)((item2 != null) ? item2.CustomColorPalette : null) != (Object)null)
						{
							PlayerPalettes.Add(((Il2CppObjectBase)item2.CustomColorPalette).Pointer);
						}
					}
				}
			}
			return PlayerPalettes.Contains(((Il2CppObjectBase)t).Pointer);
		}

		private static Texture2D Grey(Texture2D source)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: 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_0079: Expected O, but got Unknown
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_grey != (Object)null && _greyOf == ((Il2CppObjectBase)source).Pointer)
			{
				return _grey;
			}
			RenderTexture temporary = RenderTexture.GetTemporary(((Texture)source).width, ((Texture)source).height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2);
			RenderTexture active = RenderTexture.active;
			Graphics.Blit((Texture)(object)source, temporary);
			RenderTexture.active = temporary;
			Texture2D val = new Texture2D(((Texture)source).width, ((Texture)source).height, (TextureFormat)4, false)
			{
				filterMode = ((Texture)source).filterMode,
				wrapMode = ((Texture)source).wrapMode
			};
			val.ReadPixels(new Rect(0f, 0f, (float)((Texture)source).width, (float)((Texture)source).height), 0, 0);
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
			Il2CppStructArray<Color32> pixels = val.GetPixels32();
			for (int i = 0; i < ((Il2CppArrayBase<Color32>)(object)pixels).Length; i++)
			{
				byte b = (byte)Math.Clamp((int)(0.3f * (float)(int)((Il2CppArrayBase<Color32>)(object)pixels)[i].r + 0.59f * (float)(int)((Il2CppArrayBase<Color32>)(object)pixels)[i].g + 0.11f * (float)(int)((Il2CppArrayBase<Color32>)(object)pixels)[i].b), 0, 255);
				((Il2CppArrayBase<Color32>)(object)pixels)[i] = new Color32(b, b, b, ((Il2CppArrayBase<Color32>)(object)pixels)[i].a);
			}
			val.SetPixels32(pixels);
			val.Apply(false, true);
			if ((Object)(object)_grey != (Object)null)
			{
				Object.Destroy((Object)(object)_grey);
			}
			_grey = val;
			_greyOf = ((Il2CppObjectBase)source).Pointer;
			return _grey;
		}
	}
	internal static class BuildHotkeys
	{
		private const int GridBuildings = 264;

		private static ConfigEntry<bool> _burnCastle;

		private static BuildInterface _ui;

		private static int _selection = -1;

		internal static void Install(ConfigFile config, Patcher patcher)
		{
			_burnCastle = config.Bind<bool>("BuildKeys", "BurnCastle", false, "The burn key may also burn your Castle (burning a Castle burns every other building; with no Castle left you lose).");
			patcher.Patch(typeof(BuildInterface), "OnEnable", typeof(BuildHotkeys), (string)null, "Shown");
			patcher.Patch(typeof(BuildInterface), "OnDisable", typeof(BuildHotkeys), (string)null, "Hidden");
			Hotkeys.Add(config, "pickaxe", "Pickaxe tool", "Q", (Action)Pickaxe, (Func<bool>)(() => Plugin.On && (Object)(object)_ui != (Object)null));
			Hotkeys.Add(config, "burn", "Burn the building under the mouse", "X", (Action)Burn, (Func<bool>)(() => Plugin.On && (Object)(object)_ui != (Object)null));
		}

		internal static void Shown(BuildInterface __instance)
		{
			_ui = __instance;
		}

		internal static void Hidden(BuildInterface __instance)
		{
			if ((Object)(object)_ui != (Object)null && (Object)(object)__instance != (Object)null && ((Il2CppObjectBase)_ui).Pointer == ((Il2CppObjectBase)__instance).Pointer)
			{
				_ui = null;
			}
		}

		private static BuildInterface Active()
		{
			return _ui;
		}

		private static void Pickaxe()
		{
			try
			{
				BuildInterface obj = Active();
				if (obj != null)
				{
					obj._Awake_b__33_0();
				}
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("[keys] pickaxe: " + ex.Message));
			}
		}

		private static IntPtr SelectionField()
		{
			return (IntPtr)typeof(TilePointer).GetField("NativeFieldInfoPtr_selection", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
		}

		private unsafe static void Burn()
		{
			//IL_01c3: 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_01cb: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				BuildInterface val = Active();
				BuildData val2 = ((PhaseInterface<BuildData, BuildIslandState>)(object)val)?.Data;
				object obj;
				if (val == null)
				{
					obj = null;
				}
				else
				{
					BuildingSelector buildingSelector = val.buildingSelector;
					obj = ((buildingSelector != null) ? buildingSelector.tilePointer : null);
				}
				TilePointer val3 = (TilePointer)obj;
				if ((Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null)
				{
					return;
				}
				if (_selection < 0)
				{
					_selection = (int)IL2CPP.il2cpp_field_get_offset(SelectionField());
				}
				byte* ptr = (byte*)(void*)((Il2CppObjectBase)val3).Pointer + _selection;
				if (*ptr == 0)
				{
					return;
				}
				IntPtr intPtr = *(IntPtr*)(ptr + 8);
				Island island = ((PhaseData<BuildData, BuildIslandState>)(object)val2).Island;
				if (intPtr == IntPtr.Zero || (Object)(object)island == (Object)null || intPtr != ((Il2CppObjectBase)island).Pointer)
				{
					return;
				}
				IslandGrid grid = island.grid;
				if ((Object)(object)grid == (Object)null)
				{
					return;
				}
				(int, int) tuple = (((int*)ptr)[4], ((int*)ptr)[5]);
				IntPtr intPtr2 = *(IntPtr*)((byte*)(void*)((Il2CppObjectBase)grid).Pointer + 264);
				if (intPtr2 == IntPtr.Zero)
				{
					return;
				}
				IntPtr intPtr3 = *(IntPtr*)((byte*)(void*)intPtr2 + 16);
				int num = ((int*)(void*)intPtr2)[6];
				int num2 = ((int*)(void*)intPtr2)[7];
				if (intPtr3 == IntPtr.Zero || tuple.Item1 < 0 || tuple.Item2 < 0 || tuple.Item1 >= num || tuple.Item2 >= num2)
				{
					return;
				}
				byte* ptr2 = (byte*)(void*)intPtr3 + 32 + (tuple.Item2 * num + tuple.Item1) * 8;
				if (*ptr2 != 0)
				{
					int source = ((int*)ptr2)[1];
					if (!_burnCastle.Value && IsCastle(grid, source))
					{
						Plugin.L.LogInfo((object)"[keys] burn: that is your Castle; skipped ([BuildKeys] BurnCastle is off)");
						return;
					}
					Id val4 = Unsafe.As<int, Id>(ref source);
					val2.BurnBuilding(val4);
					val.RefreshButtons();
				}
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("[keys] burn: " + ex.Message));
			}
		}

		private static bool IsCastle(IslandGrid grid, int id)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<Id, Building> enumerator = grid.Buildings.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Building current = enumerator.Current;
				if (current.id.value == id)
				{
					if (current.type != null)
					{
						return ((Il2CppObjectBase)current.type).TryCast<BuildingTypeCastle>() != null;
					}
					return false;
				}
			}
			return false;
		}
	}
	internal static class ChatLog
	{
		private sealed class Original
		{
			public int Lines;

			public float Seconds;
		}

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

		private static readonly List<object> Live = new List<object>();

		internal static void Install(Patcher patcher)
		{
			patcher.Patch("ChatInterface", "Add", typeof(ChatLog), "ChatAdd", (string)null);
			patcher.Patch("LogInterface", "Add", typeof(ChatLog), "EventAdd", (string)null);
			patcher.Patch("ChatInterface", "Awake", typeof(ChatLog), "MatchUiCreated", (string)null);
			patcher.Patch("ChatInterface", "OnEnable", typeof(ChatLog), (string)null, "Enabled");
			patcher.Patch("LogInterface", "OnEnable", typeof(ChatLog), (string)null, "Enabled");
			ConfigEntry<int>[] array = new ConfigEntry<int>[4]
			{
				Options.ChatLines,
				Options.ChatSeconds,
				Options.EventLines,
				Options.EventSeconds
			};
			for (int i = 0; i < array.Length; i++)
			{
				array[i].SettingChanged += delegate
				{
					ApplyAll();
				};
			}
		}

		internal static void ChatAdd(object[] __args)
		{
			History.Record(HistoryKind.Chat, __args);
		}

		internal static void EventAdd(object[] __args)
		{
			History.Record(HistoryKind.Event, __args);
		}

		internal static void MatchUiCreated()
		{
			Live.Clear();
			History.StartSession();
		}

		internal static void Enabled(object __instance)
		{
			if (!Live.Contains(__instance))
			{
				Live.Add(__instance);
			}
			Apply(__instance);
		}

		internal static void ApplyAll()
		{
			Live.RemoveAll(delegate(object o)
			{
				Object val = (Object)((o is Object) ? o : null);
				return val != null && val == (Object)null;
			});
			foreach (object item in Live)
			{
				Apply(item);
			}
		}

		private static void Apply(object ui)
		{
			try
			{
				bool flag = ui.GetType().Name.Contains("Chat");
				int num = (Plugin.On ? (flag ? Options.ChatLines : Options.EventLines).Value : 0);
				int num2 = (Plugin.On ? (flag ? Options.ChatSeconds : Options.EventSeconds).Value : 0);
				object obj = default(object);
				if (Reflect.TryGetMember(ui, "messagePrefab", ref obj) && obj != null)
				{
					IntPtr key = Mem.PtrOf(ui);
					if (!Originals.TryGetValue(key, out var value))
					{
						object obj2 = default(object);
						Reflect.TryGetMember(ui, "maximumMessages", ref obj2);
						object obj3 = default(object);
						Reflect.TryGetMember(obj, "displayDuration", ref obj3);
						Dictionary<IntPtr, Original> originals = Originals;
						Original obj4 = new Original
						{
							Lines = ((obj2 is int num3) ? num3 : 5),
							Seconds = ((obj3 is float num4) ? num4 : 10f)
						};
						value = obj4;
						originals[key] = obj4;
					}
					Reflect.TrySetMember(ui, "maximumMessages", (object)((num > 0) ? num : value.Lines));
					Reflect.TrySetMember(obj, "displayDuration", (object)((num2 > 0) ? ((float)num2) : value.Seconds));
				}
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("chat / event log options: " + ex.Message));
			}
		}
	}
	internal static class GameSettings
	{
		internal static void Install(UiScope ui)
		{
			Tx.Block(ui, delegate
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Expected O, but got Unknown
				SettingsBlockSpec val = new SettingsBlockSpec();
				val.set_Id("org.dicemodders.dicekingdoms.tweaks.settings");
				val.set_Page((SettingsPage)3);
				val.set_Title(Tx.T("settings.title"));
				val.set_Order(10);
				val.set_Build((Action<SettingsBlockHandle>)delegate(SettingsBlockHandle block)
				{
					Slider(block, Tx.T("settings.chatLines"), Options.ChatLines, 20);
					Slider(block, Tx.T("settings.chatSeconds"), Options.ChatSeconds, 120);
					Slider(block, Tx.T("settings.eventLines"), Options.EventLines, 20);
					Slider(block, Tx.T("settings.eventSeconds"), Options.EventSeconds, 120);
					block.AddInfo(Tx.T("settings.zeroKeeps"));
					block.AddButton(Tx.T("history.title"), Tx.T("common.open"), (Action)HistoryWindow.Toggle);
				});
				return val;
			});
		}

		private static void Slider(SettingsBlockHandle block, string label, ConfigEntry<int> entry, int max)
		{
			SettingsRowHandle row = block.AddSlider(label, 0f, (float)max, (float)entry.Value, (Action<float>)delegate(float v)
			{
				entry.Value = (int)v;
			}, "0", true);
			if (row != null)
			{
				entry.SettingChanged += delegate
				{
					row.SetValue(entry.Value);
				};
			}
		}
	}
	internal enum HistoryKind
	{
		Chat,
		Event
	}
	internal static class History
	{
		private sealed class Item
		{
			public HistoryKind Kind;

			public DateTime Time;

			public float GameTime;

			public string Text;
		}

		private const int MaxItems = 5000;

		private static readonly List<Item> Items = new List<Item>();

		private static readonly HashSet<long> Seen = new HashSet<long>();

		private static readonly Regex Tags = new Regex("<[^>]+>", RegexOptions.Compiled);

		internal static int Count => Items.Count;

		internal static event Action Changed;

		internal static void StartSession()
		{
			if (Items.Count <= 0 || !((DateTime.Now - Items[Items.Count - 1].Time).TotalMinutes < 1.0))
			{
				Items.Clear();
				Seen.Clear();
				History.Changed?.Invoke();
			}
		}

		internal static void Record(HistoryKind kind, object[] args)
		{
			try
			{
				if (args == null || args.Length == 0 || args[0] == null)
				{
					return;
				}
				object obj = args[0];
				object obj2 = default(object);
				float num = ((Reflect.TryGetMember(obj, "creationTime", ref obj2) && obj2 is float num2) ? num2 : 0f);
				string text = "";
				object obj3 = default(object);
				if (Reflect.TryGetMember(obj, "Message", ref obj3) && obj3 != null)
				{
					try
					{
						text = (Reflect.Call(obj3, "Render", Array.Empty<object>()) as string) ?? "";
					}
					catch (Exception)
					{
						text = "(message could not be rendered)";
					}
				}
				if (text.Length == 0 || !Seen.Add(KeyOf(kind, num, text)))
				{
					return;
				}
				Items.Add(new Item
				{
					Kind = kind,
					Time = DateTime.Now,
					GameTime = num,
					Text = text
				});
				if (Items.Count > 5000)
				{
					Items.RemoveRange(0, Items.Count - 5000);
					Seen.Clear();
					foreach (Item item in Items)
					{
						Seen.Add(KeyOf(item.Kind, item.GameTime, item.Text));
					}
				}
				History.Changed?.Invoke();
			}
			catch (Exception ex2)
			{
				Plugin.L.LogWarning((object)("history: " + ex2.Message));
			}
		}

		private static long KeyOf(HistoryKind kind, float time, string text)
		{
			return ((long)(time * 1000f) * 397) ^ text.GetHashCode() ^ ((long)kind << 40);
		}

		internal static string Render(bool chat, bool events, int max)
		{
			List<Item> list = new List<Item>();
			int num = Items.Count - 1;
			while (num >= 0 && list.Count < max)
			{
				Item item = Items[num];
				if ((item.Kind == HistoryKind.Chat && chat) || (item.Kind == HistoryKind.Event && events))
				{
					list.Add(item);
				}
				num--;
			}
			list.Reverse();
			StringBuilder stringBuilder = new StringBuilder();
			foreach (Item item2 in list)
			{
				stringBuilder.Append("<color=#8a8f98>").Append(item2.Time.ToString("HH:mm:ss")).Append("</color>  ");
				if (item2.Kind == HistoryKind.Event && chat)
				{
					stringBuilder.Append("<color=#c9a66b>*</color> ");
				}
				stringBuilder.Append(item2.Text).Append('\n');
			}
			if (stringBuilder.Length != 0)
			{
				return stringBuilder.ToString();
			}
			return Tx.T("history.empty");
		}

		internal static string Save()
		{
			string text = Path.Combine(Paths.BepInExRootPath, "history");
			Directory.CreateDirectory(text);
			string text2 = Path.Combine(text, "history-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".txt");
			List<string> list = new List<string>(Items.Count);
			foreach (Item item in Items)
			{
				list.Add($"{item.Time:HH:mm:ss} [{((item.Kind == HistoryKind.Chat) ? "chat " : "event")}] {Tags.Replace(item.Text, "")}");
			}
			File.WriteAllLines(text2, list, Encoding.UTF8);
			return text2;
		}
	}
	internal static class HistoryWindow
	{
		private const int MaxLines = 400;

		private static UiScope _ui;

		private static TopBarButtonHandle _button;

		private static UiWindow _window;

		private static UiText _text;

		private static UiText _status;

		private static UiScroll _scroll;

		private static UiButton _all;

		private static UiButton _chat;

		private static UiButton _events;

		private static bool _showChat = true;

		private static bool _showEvents = true;

		internal static void Install(UiScope ui)
		{
			_ui = ui;
			UiScope ui2 = _ui;
			if (ui2 != null)
			{
				ui2.WhenReady((Action<UiScope>)delegate(UiScope s)
				{
					_button = s.Native.TopBar.AddIconButton("research", Tx.T("history.tooltip"), (Action)Toggle, 20);
				});
			}
			Texts.LanguageChanged += delegate
			{
				TopBarButtonHandle button = _button;
				if (button != null)
				{
					button.SetTooltip(Tx.T("history.tooltip"));
				}
			};
			History.Changed += Redraw;
		}

		internal static void RefreshButton()
		{
			TopBarButtonHandle button = _button;
			if (button != null)
			{
				button.SetVisible(Plugin.On);
			}
		}

		internal static void Toggle()
		{
			if (_window != null)
			{
				_window.Close();
				return;
			}
			UiScope ui = _ui;
			_window = ((ui != null) ? ui.Custom.Window((Action<UiWindow>)delegate(UiWindow w)
			{
				w.Title(Tx.T("history.title")).Size(560f, 480f).Position(40f, 40f)
					.Draggable(true)
					.Closable(true)
					.Fullscreenable(true)
					.FullscreenButton(true);
				w.OnClose((Action)delegate
				{
					_window = null;
					_text = (_status = null);
					_scroll = null;
				});
				UiContainer obj = w.Body.Row((Action<UiContainer>)delegate(UiContainer row)
				{
					UiButton obj3 = row.Button(Tx.T("history.all"), (Action)delegate
					{
						Filter(chat: true, events: true);
					});
					_all = ((obj3 != null) ? UiLayout.FillWidth<UiButton>(obj3) : null);
					UiButton obj4 = row.Button(Tx.T("history.chat"), (Action)delegate
					{
						Filter(chat: true, events: false);
					});
					_chat = ((obj4 != null) ? UiLayout.FillWidth<UiButton>(obj4) : null);
					UiButton obj5 = row.Button(Tx.T("history.events"), (Action)delegate
					{
						Filter(chat: false, events: true);
					});
					_events = ((obj5 != null) ? UiLayout.FillWidth<UiButton>(obj5) : null);
					UiButton obj6 = row.Button(Tx.T("history.save"), (Action)Save);
					if (obj6 != null)
					{
						UiLayout.FillWidth<UiButton>(obj6);
					}
				});
				if (obj != null)
				{
					UiLayout.Height<UiContainer>(obj, 36f);
				}
				UiScroll obj2 = w.Body.Scroll((Action<UiContainer>)delegate(UiContainer s)
				{
					_text = s.Paragraph("");
				});
				_scroll = ((obj2 != null) ? UiLayout.FillHeight<UiScroll>(UiLayout.FillWidth<UiScroll>(obj2)) : null);
				_status = w.Body.Text("");
			}) : null);
			Filter(_showChat, _showEvents);
		}

		private static void Filter(bool chat, bool events)
		{
			_showChat = chat;
			_showEvents = events;
			UiButton all = _all;
			if (all != null)
			{
				all.Selected(chat && events);
			}
			UiButton chat2 = _chat;
			if (chat2 != null)
			{
				chat2.Selected(chat && !events);
			}
			UiButton events2 = _events;
			if (events2 != null)
			{
				events2.Selected(!chat && events);
			}
			Redraw();
		}

		private static void Redraw()
		{
			if (_window != null && _text != null)
			{
				_text.Value = History.Render(_showChat, _showEvents, 400);
				if (_status != null)
				{
					_status.Value = Tx.T("history.status", History.Count, 400);
				}
				UiScroll scroll = _scroll;
				if (scroll != null)
				{
					scroll.ToBottom();
				}
			}
		}

		private static void Save()
		{
			try
			{
				string text = History.Save();
				if (_status != null)
				{
					_status.Value = Tx.T("history.saved", text);
				}
			}
			catch (Exception ex)
			{
				if (_status != null)
				{
					_status.Value = Tx.T("history.failed", ex.Message);
				}
			}
		}
	}
	internal static class NextHost
	{
		private static readonly Regex IdLine = new Regex("^\\D*(\\d{15,20})\\s*$", RegexOptions.Compiled);

		private static string _listKey;

		private static UiScope _ui;

		private static TopBarButtonHandle _button;

		private static UiWindow _window;

		private static UiDropdown _dropdown;

		private static UiText _status;

		private static readonly List<LobbyMember> Candidates = new List<LobbyMember>();

		internal static ulong Chosen { get; private set; }

		internal static void Install(Patcher patcher)
		{
			MethodInfo methodInfo = typeof(MainMenu).GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic).SelectMany((Type t) => t.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)).FirstOrDefault((MethodInfo m) => m.Name.Contains("g__RefreshPlayers"));
			if (methodInfo != null)
			{
				patcher.Patch(methodInfo.DeclaringType, methodInfo.Name, typeof(NextHost), (string)null, "AfterRefresh");
			}
			else
			{
				Plugin.L.LogWarning((object)"next host: the game's RefreshPlayers was not found; the choice is applied when the lobby changes only");
			}
			Lobby.Changed += OnLobbyChanged;
		}

		internal static void InstallButton(UiScope ui)
		{
			_ui = ui;
			UiScope ui2 = _ui;
			if (ui2 != null)
			{
				ui2.WhenReady((Action<UiScope>)delegate(UiScope s)
				{
					_button = s.Native.TopBar.AddIconButton("host", Tx.T("nexthost.tooltip"), (Action)Toggle, 21);
					RefreshButton();
				});
			}
			Texts.LanguageChanged += delegate
			{
				TopBarButtonHandle button = _button;
				if (button != null)
				{
					button.SetTooltip(Tx.T("nexthost.tooltip"));
				}
			};
		}

		internal static void RefreshButton()
		{
			TopBarButtonHandle button = _button;
			if (button != null)
			{
				button.SetVisible(Plugin.On && Lobby.InLobby && Lobby.IsHost);
			}
		}

		internal static void AfterRefresh()
		{
			if (Chosen != 0L)
			{
				Enforce();
			}
		}

		private static void OnLobbyChanged()
		{
			_listKey = null;
			if (!Lobby.InLobby)
			{
				Chosen = 0uL;
			}
			RefreshButton();
			if (Chosen != 0L)
			{
				Enforce();
			}
			if (_window != null)
			{
				FillCandidates();
			}
		}

		private static void Choose(ulong steamId)
		{
			Chosen = steamId;
			if (steamId == 0L)
			{
				Status(Tx.T("nexthost.auto"));
			}
			else
			{
				Status(Enforce() ? Tx.T("nexthost.done") : Tx.T("nexthost.saved"));
			}
		}

		private static bool Enforce()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: 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)
			if (Plugin.On && Chosen != 0L && Lobby.IsHost)
			{
				Lobby? current = Lobby.Current;
				if (current.HasValue)
				{
					Lobby valueOrDefault = current.GetValueOrDefault();
					try
					{
						if (_listKey == null)
						{
							_listKey = FindListKey(valueOrDefault);
						}
						if (_listKey == null)
						{
							return false;
						}
						List<string> list = new List<string>((((Lobby)(ref valueOrDefault)).GetData(_listKey) ?? "").Split('\n'));
						int num = list.FindIndex((string l) => IdOf(l) == Chosen);
						if (num < 0)
						{
							Chosen = 0uL;
							Status(Tx.T("nexthost.left"));
							return false;
						}
						if (num == 0)
						{
							return true;
						}
						string item = list[num];
						list.RemoveAt(num);
						list.Insert(0, item);
						return ((Lobby)(ref valueOrDefault)).SetData(_listKey, string.Join("\n", list));
					}
					catch (Exception ex)
					{
						Plugin.L.LogWarning((object)("next host: " + ex.Message));
						return false;
					}
				}
			}
			return false;
		}

		private static ulong IdOf(string line)
		{
			Match match = IdLine.Match(line ?? "");
			if (!match.Success || !ulong.TryParse(match.Groups[1].Value, out var result))
			{
				return 0uL;
			}
			return result;
		}

		private static string FindListKey(Lobby lobby)
		{
			ulong localSteamId = Lobby.LocalSteamId;
			IEnumerator<KeyValuePair<string, string>> enumerator = ((Lobby)(ref lobby)).Data.GetEnumerator();
			while (((IEnumerator)enumerator).MoveNext())
			{
				KeyValuePair<string, string> current = enumerator.Current;
				if (!string.IsNullOrEmpty(current.Value))
				{
					List<ulong> list = current.Value.Split('\n').Select(IdOf).ToList();
					if (list.All((ulong id) => id != 0) && list.Contains(localSteamId))
					{
						return current.Key;
					}
				}
			}
			return null;
		}

		private static void Toggle()
		{
			if (_window != null)
			{
				_window.Close();
				return;
			}
			UiScope ui = _ui;
			_window = ((ui != null) ? ui.Custom.Window((Action<UiWindow>)delegate(UiWindow w)
			{
				w.Title(Tx.T("nexthost.title")).Size(420f, 260f).Center()
					.Draggable(true)
					.Closable(true);
				w.OnClose((Action)delegate
				{
					_window = null;
					_dropdown = null;
					_status = null;
				});
				w.Body.Paragraph(Tx.T("nexthost.help"));
				_dropdown = w.Body.Dropdown((IEnumerable<string>)new string[1] { Tx.T("nexthost.automatic") }, 0, (Action<int>)delegate(int i)
				{
					//IL_0019: Unknown result type (might be due to invalid IL or missing references)
					//IL_001e: Unknown result type (might be due to invalid IL or missing references)
					long steamId;
					if (i > 0 && i <= Candidates.Count)
					{
						LobbyMember val = Candidates[i - 1];
						steamId = (long)((LobbyMember)(ref val)).SteamId;
					}
					else
					{
						steamId = 0L;
					}
					Choose((ulong)steamId);
				});
				_status = w.Body.Paragraph((Chosen == 0L) ? Tx.T("nexthost.auto") : Tx.T("nexthost.set"));
			}) : null);
			FillCandidates();
		}

		private static void FillCandidates()
		{
			Candidates.Clear();
			Candidates.AddRange(Lobby.Members.Where((LobbyMember m) => !((LobbyMember)(ref m)).IsLocal));
			UiDropdown dropdown = _dropdown;
			if (dropdown != null)
			{
				dropdown.Options(new string[1] { Tx.T("nexthost.automatic") }.Concat(Candidates.Select((LobbyMember m) => ((LobbyMember)(ref m)).Name)));
			}
			int num = Candidates.FindIndex((LobbyMember m) => ((LobbyMember)(ref m)).SteamId == Chosen);
			UiDropdown dropdown2 = _dropdown;
			if (dropdown2 != null)
			{
				dropdown2.Set((num >= 0) ? (num + 1) : 0);
			}
		}

		private static void Status(string text)
		{
			if (_status != null)
			{
				_status.Value = text;
			}
		}
	}
	internal static class Options
	{
		internal static ConfigEntry<int> ChatLines;

		internal static ConfigEntry<int> ChatSeconds;

		internal static ConfigEntry<int> EventLines;

		internal static ConfigEntry<int> EventSeconds;

		internal static void Bind(ConfigFile config)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			ChatLines = config.Bind<int>("Chat", "Lines", 0, new ConfigDescription("How many chat messages stay on screen (0 = the game's number). The History window keeps all of them.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()));
			ChatSeconds = config.Bind<int>("Chat", "Seconds", 0, new ConfigDescription("How many seconds a chat message stays on screen (0 = the game's time).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 120), Array.Empty<object>()));
			EventLines = config.Bind<int>("EventLog", "Lines", 0, new ConfigDescription("How many events stay on screen (0 = the game's number).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()));
			EventSeconds = config.Bind<int>("EventLog", "Seconds", 0, new ConfigDescription("How many seconds an event stays on screen (0 = the game's time).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 120), Array.Empty<object>()));
		}
	}
	[BepInPlugin("org.dicemodders.dicekingdoms.tweaks", "DiceKingdoms Tweaks", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInProcess("Dice-Kingdoms.exe")]
	public sealed class Plugin : BasePlugin
	{
		public const string Guid = "org.dicemodders.dicekingdoms.tweaks";

		public const string Name = "DiceKingdoms Tweaks";

		public const string Version = "1.0.0";

		internal static ManualLogSource L;

		internal static bool On;

		public override void Load()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			Tx.Load();
			L = ((BasePlugin)this).Log;
			Options.Bind(((BasePlugin)this).Config);
			Patcher val = new Patcher("org.dicemodders.dicekingdoms.tweaks", ((BasePlugin)this).Log);
			AnonymousAttacks.Install(val);
			AnonymousColours.Install(val);
			ChatLog.Install(val);
			NextHost.Install(val);
			BuildHotkeys.Install(((BasePlugin)this).Config, val);
			val.Summary();
			UiScope ui = UiKit.CreateScope("org.dicemodders.dicekingdoms.tweaks");
			HistoryWindow.Install(ui);
			NextHost.InstallButton(ui);
			GameSettings.Install(ui);
			Mods.Switch(((BasePlugin)this).Config, false, false, "Turns every tweak of this mod on or off.").WhenOn((Action)delegate
			{
				On = true;
				Changed();
			}, (Action)delegate
			{
				On = false;
				Changed();
			});
		}

		private static void Changed()
		{
			AnonymousAttacks.RefreshAll();
			ChatLog.ApplyAll();
			NextHost.RefreshButton();
			HistoryWindow.RefreshButton();
		}
	}
	internal static class Tx
	{
		internal static TextSet Set;

		internal static void Load()
		{
			Set = Texts.Load("texts.json", (string)null);
		}

		internal static string T(string key)
		{
			TextSet set = Set;
			return ((set != null) ? set.Get(key) : null) ?? key;
		}

		internal static string T(string key, params object[] values)
		{
			TextSet set = Set;
			return ((set != null) ? set.Get(key, values) : null) ?? key;
		}

		internal static SettingsBlockHandle Block(UiScope ui, Func<SettingsBlockSpec> spec)
		{
			if (ui == null)
			{
				return null;
			}
			SettingsBlockHandle handle = ui.Native.Settings.AddBlock(spec());
			Texts.LanguageChanged += delegate
			{
				SettingsBlockHandle obj = handle;
				if (obj != null)
				{
					((NativeHandle)obj).Dispose();
				}
				handle = ui.Native.Settings.AddBlock(spec());
			};
			return handle;
		}
	}
}