Decompiled source of ElectoralColorChangerV2 v1.0.1

ElectoralColorChanger.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using UnityEngine;

[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("ElectoralColorChanger")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("ElectoralColorChanger")]
[assembly: AssemblyTitle("ElectoralColorChanger")]
[assembly: AssemblyVersion("1.0.1.0")]
namespace ElectoralColorChanger;

[BepInPlugin("com.electoralcarnage.colorchanger", "Electoral Color Changer", "1.0.1")]
public sealed class ElectoralColorChangerPlugin : BaseUnityPlugin
{
	private sealed class PaletteState
	{
		public Component Component;

		public Object Original;

		public Object Clone;
	}

	[Serializable]
	private sealed class SkinFile
	{
		public string format = "ElectoralColorChangerSkin";

		public int formatVersion = 1;

		public int exportedPlayer = 1;

		public List<SkinColor> colors = new List<SkinColor>();
	}

	[Serializable]
	private sealed class SkinColor
	{
		public int index;

		public string hex;
	}

	private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

	private ConfigEntry<bool> enabledSetting;

	private ConfigEntry<int> playerSlotSetting;

	private ConfigEntry<float> refreshIntervalSetting;

	private Type swapType;

	private FieldInfo infoField;

	private FieldInfo playerField;

	private FieldInfo rendererField;

	private FieldInfo paletteField;

	private FieldInfo replacementPalettesField;

	private FieldInfo sourceColorsField;

	private FieldInfo canonicalColorHexListField;

	private FieldInfo appliedColorIDField;

	private MethodInfo applyMethod;

	private readonly Dictionary<Component, PaletteState> paletteStates = new Dictionary<Component, PaletteState>();

	private readonly Dictionary<int, string> committedColors = new Dictionary<int, string>();

	private float nextRefresh;

	private bool windowOpen;

	private bool cursorStateCaptured;

	private CursorLockMode previousCursorLockState;

	private bool previousCursorVisible;

	private Rect windowRect = new Rect(30f, 30f, 390f, 460f);

	private Vector2 windowScrollPosition = Vector2.zero;

	private string editableHex = "#FF4040";

	private string currentColorHex = "#FF4040";

	private int selectedPaletteIndex;

	private string uiMessage = "Choose a palette entry and color, then Apply.";

	private string skinFileName = "MySkin";

	private Vector2 skinListScroll = Vector2.zero;

	private string browseDir;

	private string selectedSkinPath;

	private readonly List<string> browseFolders = new List<string>();

	private readonly List<string> browseFiles = new List<string>();

	private readonly List<string> availableSkinFiles = new List<string>();

	private float red = 1f;

	private float green = 0.25f;

	private float blue = 0.25f;

	private int detectedEntries;

	private int detectedComponents;

	private bool guiCallbackSeen;

	private bool previewSelectedIndex = true;

	private void Awake()
	{
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		enabledSetting = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable local palette color editing.");
		playerSlotSetting = ((BaseUnityPlugin)this).Config.Bind<int>("General", "PlayerSlot", 1, "Player slot to edit. Player 1 is Reagan.");
		refreshIntervalSetting = ((BaseUnityPlugin)this).Config.Bind<float>("General", "RefreshIntervalSeconds", 0.25f, "How often to apply the local palette edit.");
		editableHex = currentColorHex;
		Color val = default(Color);
		if (ColorUtility.TryParseHtmlString(editableHex, ref val))
		{
			red = val.r;
			green = val.g;
			blue = val.b;
		}
		ResolveGameTypes();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Electoral Color Changer 1.0.1 loaded. F6 opens the editor. Per-index colors are session-only and reset when the game closes.");
	}

	private void Update()
	{
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: 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_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		if (windowOpen)
		{
			UnlockCursor();
		}
		float num = Mathf.Clamp(refreshIntervalSetting.Value, 0.05f, 3f);
		if (Time.unscaledTime < nextRefresh)
		{
			return;
		}
		nextRefresh = Time.unscaledTime + num;
		if (!enabledSetting.Value)
		{
			RestorePalettes();
			return;
		}
		Color replacement = default(Color);
		if (previewSelectedIndex && windowOpen)
		{
			float num2 = 0.5f + 0.5f * Mathf.Sin(Time.unscaledTime * 5f);
			replacement = Color.Lerp(new Color(0f, 1f, 1f, 1f), Color.white, num2 * 0.35f);
		}
		else if (!ColorUtility.TryParseHtmlString(currentColorHex, ref replacement))
		{
			return;
		}
		if (!(swapType == null) || ResolveGameTypes())
		{
			int slot = Mathf.Clamp(playerSlotSetting.Value, 1, 2);
			if (!previewSelectedIndex && GetCommittedCountForSlot(slot) == 0)
			{
				RestorePalettesForSlot(slot);
			}
			else
			{
				ApplyPaletteEdit(replacement, previewSelectedIndex && windowOpen);
			}
		}
	}

	private bool ResolveGameTypes()
	{
		Assembly assembly = null;
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		for (int i = 0; i < assemblies.Length; i++)
		{
			if (string.Equals(assemblies[i].GetName().Name, "Assembly-CSharp", StringComparison.OrdinalIgnoreCase))
			{
				assembly = assemblies[i];
				break;
			}
		}
		if (assembly == null)
		{
			return false;
		}
		swapType = assembly.GetType("PaletteSwapTest", throwOnError: false);
		if (swapType == null)
		{
			return false;
		}
		infoField = swapType.GetField("info", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		rendererField = swapType.GetField("spriteRenderer", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		paletteField = swapType.GetField("characterPalette", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		applyMethod = swapType.GetMethod("Apply", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		if (infoField == null || rendererField == null || paletteField == null || applyMethod == null)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"PaletteSwapTest was found, but required palette fields or Apply() were missing.");
			swapType = null;
			return false;
		}
		playerField = infoField.FieldType.GetField("player", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		Type fieldType = paletteField.FieldType;
		replacementPalettesField = fieldType.GetField("replacementPalettes", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		sourceColorsField = fieldType.GetField("sourceColors", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		canonicalColorHexListField = fieldType.GetField("canonicalColorHexList", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		appliedColorIDField = swapType.GetField("appliedColorID", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		if (playerField == null || replacementPalettesField == null || sourceColorsField == null)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"Could not resolve PlayerInfo.player or CharacterPalette palette data.");
			swapType = null;
			return false;
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Resolved PaletteSwapTest and CharacterPalette replacementPalettes/sourceColors.");
		return true;
	}

	private void ApplyPaletteEdit(Color replacement, bool previewOnly)
	{
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		Object[] array;
		try
		{
			array = Object.FindObjectsOfType(swapType);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not find palette components: " + ex.Message));
			return;
		}
		int num = Mathf.Clamp(playerSlotSetting.Value, 1, 2);
		int num2 = Mathf.Clamp(selectedPaletteIndex, 0, 255);
		string text = "#" + ColorUtility.ToHtmlStringRGB(replacement);
		HashSet<Component> hashSet = new HashSet<Component>();
		detectedEntries = 0;
		detectedComponents = 0;
		foreach (object obj in array)
		{
			if (obj == null)
			{
				continue;
			}
			object value = infoField.GetValue(obj);
			if (value == null)
			{
				continue;
			}
			object value2 = playerField.GetValue(value);
			if (!(value2 is int) || (int)value2 != num)
			{
				continue;
			}
			object? value3 = rendererField.GetValue(obj);
			SpriteRenderer val = (SpriteRenderer)((value3 is SpriteRenderer) ? value3 : null);
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			Component val2 = (Component)((obj is Component) ? obj : null);
			if ((Object)(object)val2 == (Object)null)
			{
				continue;
			}
			object? value4 = paletteField.GetValue(obj);
			Object val3 = (Object)((value4 is Object) ? value4 : null);
			if (val3 == (Object)null)
			{
				continue;
			}
			PaletteState value5;
			bool flag = paletteStates.TryGetValue(val2, out value5);
			if (!flag || (val3 != value5.Clone && val3 != value5.Original))
			{
				if (flag && value5.Clone != (Object)null)
				{
					Object.Destroy(value5.Clone);
				}
				Object val4 = Object.Instantiate(val3);
				if (val4 == (Object)null)
				{
					continue;
				}
				val4.name = val3.name + "_LocalColorChanger";
				value5 = new PaletteState
				{
					Component = val2,
					Original = val3,
					Clone = val4
				};
				paletteStates[val2] = value5;
				paletteField.SetValue(obj, val4);
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Created private palette copy for Player " + num + " renderer '" + ((Object)val).name + "' using palette '" + val3.name + "'."));
			}
			else if (val3 == value5.Original)
			{
				paletteField.SetValue(obj, value5.Clone);
			}
			if (!(replacementPalettesField.GetValue(value5.Original) is string[] array2) || array2.Length == 0)
			{
				continue;
			}
			string[] array3 = (string[])array2.Clone();
			object value6 = sourceColorsField.GetValue(value5.Clone);
			int num3 = ((value6 is ICollection) ? ((ICollection)value6).Count : 0);
			int num4 = int.MaxValue;
			for (int j = 0; j < array3.Length; j++)
			{
				if (string.IsNullOrEmpty(array3[j]))
				{
					continue;
				}
				string[] array4 = array3[j].Replace("\r", "").Split('\n');
				if (array4.Length < num4)
				{
					num4 = array4.Length;
				}
				bool flag2 = false;
				foreach (KeyValuePair<int, string> committedColor in committedColors)
				{
					int num5 = committedColor.Key / 1000;
					int num6 = committedColor.Key % 1000;
					if (num5 == num && num6 >= 0 && num6 < array4.Length)
					{
						array4[num6] = committedColor.Value;
						flag2 = true;
					}
				}
				if (previewOnly && num2 >= 0 && num2 < array4.Length)
				{
					array4[num2] = text;
					flag2 = true;
				}
				if (flag2)
				{
					array3[j] = string.Join("\n", array4);
					detectedEntries++;
				}
			}
			replacementPalettesField.SetValue(value5.Clone, array3);
			detectedComponents++;
			if (previewOnly && num3 > 0 && num2 >= num3)
			{
				uiMessage = "Index exceeds this palette's source color count (" + num3 + ").";
			}
			hashSet.Add(val2);
			try
			{
				if (appliedColorIDField != null && appliedColorIDField.FieldType == typeof(int))
				{
					appliedColorIDField.SetValue(obj, -1);
				}
				applyMethod.Invoke(obj, null);
			}
			catch (Exception ex2)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Palette Apply() failed on '" + ((Object)val).name + "': " + ex2.GetBaseException().Message));
			}
		}
		RemoveInactiveStates(hashSet);
	}

	private void RemoveInactiveStates(HashSet<Component> active)
	{
		List<Component> list = new List<Component>();
		foreach (KeyValuePair<Component, PaletteState> paletteState2 in paletteStates)
		{
			if ((Object)(object)paletteState2.Key == (Object)null || !active.Contains(paletteState2.Key))
			{
				list.Add(paletteState2.Key);
			}
		}
		for (int i = 0; i < list.Count; i++)
		{
			PaletteState paletteState = paletteStates[list[i]];
			if ((Object)(object)paletteState.Component != (Object)null && paletteState.Original != (Object)null)
			{
				PaletteSwapTestRestore(paletteState.Component, paletteState.Original);
			}
			if (paletteState.Clone != (Object)null)
			{
				Object.Destroy(paletteState.Clone);
			}
			paletteStates.Remove(list[i]);
		}
	}

	private void PaletteSwapTestRestore(Component component, Object original)
	{
		try
		{
			paletteField.SetValue(component, original);
			if (appliedColorIDField != null && appliedColorIDField.FieldType == typeof(int))
			{
				appliedColorIDField.SetValue(component, -1);
			}
			applyMethod.Invoke(component, null);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Restored original palette on '" + ((Object)component).name + "'."));
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Palette restore failed on '" + ((Object)component).name + "': " + ex.GetBaseException().Message));
		}
	}

	private int GetCommittedCountForSlot(int slot)
	{
		int num = 0;
		foreach (int key in committedColors.Keys)
		{
			if (key / 1000 == slot)
			{
				num++;
			}
		}
		return num;
	}

	private void RestorePalettesForSlot(int slot)
	{
		List<Component> list = new List<Component>();
		foreach (KeyValuePair<Component, PaletteState> paletteState in paletteStates)
		{
			PaletteState value = paletteState.Value;
			if ((Object)(object)value.Component == (Object)null)
			{
				list.Add(paletteState.Key);
				continue;
			}
			object obj = ((infoField != null) ? infoField.GetValue(value.Component) : null);
			object obj2 = ((obj != null && playerField != null) ? playerField.GetValue(obj) : null);
			if (obj2 is int && (int)obj2 == slot)
			{
				if (value.Original != (Object)null)
				{
					PaletteSwapTestRestore(value.Component, value.Original);
				}
				if (value.Clone != (Object)null)
				{
					Object.Destroy(value.Clone);
				}
				list.Add(paletteState.Key);
			}
		}
		for (int i = 0; i < list.Count; i++)
		{
			paletteStates.Remove(list[i]);
		}
	}

	private int GetSelectedPlayerMaxIndex()
	{
		if (swapType == null && !ResolveGameTypes())
		{
			return 127;
		}
		Object[] array;
		try
		{
			array = Object.FindObjectsOfType(swapType);
		}
		catch
		{
			return 127;
		}
		int num = Mathf.Clamp(playerSlotSetting.Value, 1, 2);
		int num2 = 0;
		foreach (object obj2 in array)
		{
			if (obj2 == null)
			{
				continue;
			}
			object value = infoField.GetValue(obj2);
			if (value == null)
			{
				continue;
			}
			object value2 = playerField.GetValue(value);
			if (!(value2 is int) || (int)value2 != num)
			{
				continue;
			}
			object value3 = paletteField.GetValue(obj2);
			if (value3 != null)
			{
				object value4 = sourceColorsField.GetValue(value3);
				int num3 = ((value4 is ICollection) ? ((ICollection)value4).Count : 0);
				if (num3 > num2)
				{
					num2 = num3;
				}
			}
		}
		if (num2 <= 0)
		{
			return 127;
		}
		return Mathf.Clamp(num2 - 1, 0, 255);
	}

	private void RestorePalettes()
	{
		foreach (KeyValuePair<Component, PaletteState> paletteState in paletteStates)
		{
			PaletteState value = paletteState.Value;
			if ((Object)(object)value.Component != (Object)null && value.Original != (Object)null)
			{
				PaletteSwapTestRestore(value.Component, value.Original);
			}
			if (value.Clone != (Object)null)
			{
				Object.Destroy(value.Clone);
			}
		}
		paletteStates.Clear();
	}

	private void OnGUI()
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Invalid comparison between Unknown and I4
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Invalid comparison between Unknown and I4
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Expected O, but got Unknown
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		Event current = Event.current;
		if (current != null && (int)current.type == 4 && (int)current.keyCode == 287)
		{
			SetWindowOpen(!windowOpen);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("F6 toggled the color editor: " + (windowOpen ? "open" : "closed")));
			current.Use();
		}
		if (!guiCallbackSeen)
		{
			guiCallbackSeen = true;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Color editor GUI callback active.");
		}
		if (windowOpen)
		{
			UnlockCursor();
			windowRect = GUI.Window(731904, windowRect, new WindowFunction(DrawWindow), "Electoral Color Changer");
		}
	}

	private void DrawWindow(int id)
	{
		//IL_0002: 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_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0969: 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_03b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_046f: Unknown result type (might be due to invalid IL or missing references)
		//IL_047c: 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_049b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0536: Unknown result type (might be due to invalid IL or missing references)
		//IL_05b4: Unknown result type (might be due to invalid IL or missing references)
		windowScrollPosition = GUILayout.BeginScrollView(windowScrollPosition, (GUILayoutOption[])(object)new GUILayoutOption[2]
		{
			GUILayout.Width(((Rect)(ref windowRect)).width - 12f),
			GUILayout.Height(((Rect)(ref windowRect)).height - 34f)
		});
		GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
		GUILayout.Label("LOCAL PALETTE EDITOR — no network values are changed", Array.Empty<GUILayoutOption>());
		GUILayout.Space(5f);
		bool flag = GUILayout.Toggle(enabledSetting.Value, " Enable palette edit", Array.Empty<GUILayoutOption>());
		if (flag != enabledSetting.Value)
		{
			enabledSetting.Value = flag;
			if (!flag)
			{
				RestorePalettes();
			}
			SaveConfig();
		}
		GUILayout.Space(5f);
		GUILayout.Label("Target player", Array.Empty<GUILayoutOption>());
		int num = GUILayout.SelectionGrid(Mathf.Clamp(playerSlotSetting.Value, 1, 2) - 1, new string[2] { "Player 1", "Player 2" }, 1, Array.Empty<GUILayoutOption>()) + 1;
		if (num != playerSlotSetting.Value)
		{
			RestorePalettes();
			playerSlotSetting.Value = num;
			previewSelectedIndex = true;
			uiMessage = "Target set to Player " + num + ".";
			SaveConfig();
		}
		GUILayout.Space(6f);
		int selectedPlayerMaxIndex = GetSelectedPlayerMaxIndex();
		selectedPaletteIndex = Mathf.Clamp(selectedPaletteIndex, 0, selectedPlayerMaxIndex);
		GUILayout.Label("Palette index (zero-based): " + selectedPaletteIndex + " / " + selectedPlayerMaxIndex, Array.Empty<GUILayoutOption>());
		int num2 = Mathf.RoundToInt(GUILayout.HorizontalSlider((float)selectedPaletteIndex, 0f, (float)selectedPlayerMaxIndex, Array.Empty<GUILayoutOption>()));
		if (num2 != selectedPaletteIndex)
		{
			selectedPaletteIndex = num2;
			previewSelectedIndex = true;
			enabledSetting.Value = true;
			uiMessage = "Previewing index " + num2 + " on the character with a pulsing cyan highlight.";
			SaveConfig();
		}
		GUILayout.Label("The selected index is highlighted directly on the character while this window is open.", Array.Empty<GUILayoutOption>());
		GUILayout.Label("If no highlight appears, that index may not be used by the current character.", Array.Empty<GUILayoutOption>());
		GUILayout.Space(6f);
		GUILayout.Label("Replacement color", Array.Empty<GUILayoutOption>());
		float num3 = red;
		float num4 = green;
		float num5 = blue;
		GUILayout.Label("Red: " + Mathf.RoundToInt(red * 255f), Array.Empty<GUILayoutOption>());
		red = GUILayout.HorizontalSlider(red, 0f, 1f, Array.Empty<GUILayoutOption>());
		GUILayout.Label("Green: " + Mathf.RoundToInt(green * 255f), Array.Empty<GUILayoutOption>());
		green = GUILayout.HorizontalSlider(green, 0f, 1f, Array.Empty<GUILayoutOption>());
		GUILayout.Label("Blue: " + Mathf.RoundToInt(blue * 255f), Array.Empty<GUILayoutOption>());
		blue = GUILayout.HorizontalSlider(blue, 0f, 1f, Array.Empty<GUILayoutOption>());
		if (Mathf.Abs(num3 - red) > 0.001f || Mathf.Abs(num4 - green) > 0.001f || Mathf.Abs(num5 - blue) > 0.001f)
		{
			editableHex = "#" + ColorUtility.ToHtmlStringRGB(new Color(red, green, blue, 1f));
		}
		GUI.backgroundColor = new Color(red, green, blue, 1f);
		GUILayout.Box("COLOR PREVIEW", (GUILayoutOption[])(object)new GUILayoutOption[2]
		{
			GUILayout.ExpandWidth(true),
			GUILayout.Height(25f)
		});
		GUI.backgroundColor = Color.white;
		GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
		GUILayout.Label("Hex", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(35f) });
		editableHex = GUILayout.TextField(editableHex, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
		GUILayout.EndHorizontal();
		GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
		if (GUILayout.Button("Apply to palette index", Array.Empty<GUILayoutOption>()))
		{
			Color val = default(Color);
			if (ColorUtility.TryParseHtmlString(editableHex, ref val))
			{
				red = val.r;
				green = val.g;
				blue = val.b;
				currentColorHex = "#" + ColorUtility.ToHtmlStringRGB(val);
				committedColors[Mathf.Clamp(playerSlotSetting.Value, 1, 2) * 1000 + selectedPaletteIndex] = currentColorHex;
				enabledSetting.Value = true;
				previewSelectedIndex = false;
				uiMessage = "Applied " + currentColorHex + " to palette index " + selectedPaletteIndex + ".";
				SaveConfig();
				ApplyPaletteEdit(val, previewOnly: false);
			}
			else
			{
				uiMessage = "Invalid hex. Enter #RRGGBB.";
			}
		}
		GUILayout.EndHorizontal();
		if (GUILayout.Button("Reset this index", Array.Empty<GUILayoutOption>()))
		{
			int num6 = Mathf.Clamp(playerSlotSetting.Value, 1, 2);
			int key = num6 * 1000 + selectedPaletteIndex;
			bool flag2 = committedColors.Remove(key);
			previewSelectedIndex = false;
			if (GetCommittedCountForSlot(num6) == 0)
			{
				RestorePalettesForSlot(num6);
			}
			else
			{
				ApplyPaletteEdit(Color.white, previewOnly: false);
			}
			if (GetCommittedCountForSlot(1) + GetCommittedCountForSlot(2) == 0)
			{
				enabledSetting.Value = false;
			}
			uiMessage = (flag2 ? ("Reset Player " + num6 + " index " + selectedPaletteIndex + " to its original color.") : "This index has no committed edit to reset.");
			((BaseUnityPlugin)this).Logger.LogInfo((object)uiMessage);
			SaveConfig();
		}
		if (GUILayout.Button("Restore this player", Array.Empty<GUILayoutOption>()))
		{
			int num7 = Mathf.Clamp(playerSlotSetting.Value, 1, 2);
			List<int> list = new List<int>();
			foreach (int key2 in committedColors.Keys)
			{
				if (key2 / 1000 == num7)
				{
					list.Add(key2);
				}
			}
			for (int i = 0; i < list.Count; i++)
			{
				committedColors.Remove(list[i]);
			}
			RestorePalettesForSlot(num7);
			previewSelectedIndex = false;
			if (GetCommittedCountForSlot(1) + GetCommittedCountForSlot(2) == 0)
			{
				enabledSetting.Value = false;
			}
			uiMessage = "Restored Player " + num7 + " originals and cleared " + list.Count + " session edit(s).";
			((BaseUnityPlugin)this).Logger.LogInfo((object)uiMessage);
			SaveConfig();
		}
		if (GUILayout.Button("Restore all players", Array.Empty<GUILayoutOption>()))
		{
			int count = committedColors.Count;
			committedColors.Clear();
			RestorePalettes();
			previewSelectedIndex = false;
			enabledSetting.Value = false;
			uiMessage = "Restored both players' original palettes and cleared " + count + " session edit(s).";
			((BaseUnityPlugin)this).Logger.LogInfo((object)uiMessage);
			SaveConfig();
		}
		GUILayout.Space(8f);
		GUILayout.Label("Skin import / export — Windows Downloads folder", Array.Empty<GUILayoutOption>());
		GUILayout.Label("Folder: " + GetDownloadsDirectory(), Array.Empty<GUILayoutOption>());
		GUILayout.Label("Export file name:", Array.Empty<GUILayoutOption>());
		skinFileName = GUILayout.TextField(skinFileName, Array.Empty<GUILayoutOption>());
		if (GUILayout.Button("Export player skin to Downloads", Array.Empty<GUILayoutOption>()))
		{
			try
			{
				string downloadsSkinPath = GetDownloadsSkinPath();
				ExportSkin(Mathf.Clamp(playerSlotSetting.Value, 1, 2), downloadsSkinPath);
			}
			catch (Exception ex)
			{
				uiMessage = "Skin export failed: " + ex.Message;
				((BaseUnityPlugin)this).Logger.LogWarning((object)uiMessage);
			}
		}
		GUILayout.Space(4f);
		DrawSkinBrowser();
		GUILayout.Label("Import replaces the selected player's current session edits. Skin files remain standard .json.", Array.Empty<GUILayoutOption>());
		GUILayout.Space(4f);
		GUILayout.Label("Live palette renderers: " + detectedComponents + "   Variant entries edited: " + detectedEntries, Array.Empty<GUILayoutOption>());
		GUILayout.Label("Session edits — Player 1: " + GetCommittedCountForSlot(1) + "   Player 2: " + GetCommittedCountForSlot(2), Array.Empty<GUILayoutOption>());
		GUILayout.Label(uiMessage, Array.Empty<GUILayoutOption>());
		GUILayout.Label("F6 closes this window. Mouse cursor is released while open.", Array.Empty<GUILayoutOption>());
		GUILayout.EndVertical();
		GUILayout.EndScrollView();
		GUI.DragWindow(new Rect(0f, 0f, 10000f, 24f));
	}

	private static string SerializeSkin(SkinFile skin)
	{
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.AppendLine("{");
		stringBuilder.AppendLine("  \"format\": \"ElectoralColorChangerSkin\",");
		stringBuilder.AppendLine("  \"formatVersion\": 1,");
		stringBuilder.AppendLine("  \"exportedPlayer\": " + skin.exportedPlayer + ",");
		stringBuilder.AppendLine("  \"colors\": [");
		for (int i = 0; i < skin.colors.Count; i++)
		{
			SkinColor skinColor = skin.colors[i];
			stringBuilder.Append("    { \"index\": ").Append(skinColor.index).Append(", \"hex\": \"")
				.Append(skinColor.hex)
				.Append("\" }");
			if (i + 1 < skin.colors.Count)
			{
				stringBuilder.Append(',');
			}
			stringBuilder.AppendLine();
		}
		stringBuilder.AppendLine("  ]");
		stringBuilder.Append("}");
		return stringBuilder.ToString();
	}

	private static SkinFile DeserializeSkin(string json)
	{
		if (string.IsNullOrEmpty(json))
		{
			return null;
		}
		Match match = Regex.Match(json, "\"format\"\\s*:\\s*\"([^\"]+)\"");
		Match match2 = Regex.Match(json, "\"formatVersion\"\\s*:\\s*(\\d+)");
		Match match3 = Regex.Match(json, "\"exportedPlayer\"\\s*:\\s*(\\d+)");
		if (!match.Success || !match2.Success)
		{
			return null;
		}
		SkinFile skinFile = new SkinFile();
		skinFile.format = match.Groups[1].Value;
		skinFile.formatVersion = int.Parse(match2.Groups[1].Value);
		if (match3.Success)
		{
			skinFile.exportedPlayer = int.Parse(match3.Groups[1].Value);
		}
		Match match4 = Regex.Match(json, "\"colors\"\\s*:\\s*\\[(.*?)\\]", RegexOptions.Singleline);
		if (!match4.Success)
		{
			return skinFile;
		}
		foreach (Match item in Regex.Matches(match4.Groups[1].Value, "\\{[^{}]*\\}"))
		{
			Match match5 = Regex.Match(item.Value, "\"index\"\\s*:\\s*(\\d+)");
			Match match6 = Regex.Match(item.Value, "\"hex\"\\s*:\\s*\"#?([0-9a-fA-F]{6})\"");
			if (match5.Success && match6.Success)
			{
				skinFile.colors.Add(new SkinColor
				{
					index = int.Parse(match5.Groups[1].Value),
					hex = "#" + match6.Groups[1].Value
				});
			}
		}
		return skinFile;
	}

	private string GetDownloadsDirectory()
	{
		string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
		if (string.IsNullOrEmpty(folderPath))
		{
			throw new DirectoryNotFoundException("Could not determine the Windows user profile folder.");
		}
		string text = Path.Combine(folderPath, "Downloads");
		Directory.CreateDirectory(text);
		return text;
	}

	private string GetDownloadsSkinPath()
	{
		string text = (skinFileName ?? "").Trim();
		if (text.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
		{
			text = text.Substring(0, text.Length - 5);
		}
		char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
		foreach (char oldChar in invalidFileNameChars)
		{
			text = text.Replace(oldChar, '_');
		}
		text = text.Trim().Trim('.');
		if (string.IsNullOrEmpty(text))
		{
			throw new ArgumentException("Enter a valid skin file name.");
		}
		return Path.Combine(GetDownloadsDirectory(), text + ".json");
	}

	private void DrawSkinBrowser()
	{
		//IL_00cf: 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_00ec: Unknown result type (might be due to invalid IL or missing references)
		GUILayout.Label("Import skin - browse for a .json file", Array.Empty<GUILayoutOption>());
		GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
		if (GUILayout.Button("Downloads", Array.Empty<GUILayoutOption>()))
		{
			NavigateBrowser(GetDownloadsDirectory());
		}
		if (GUILayout.Button("Desktop", Array.Empty<GUILayoutOption>()))
		{
			NavigateBrowser(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
		}
		if (GUILayout.Button("Documents", Array.Empty<GUILayoutOption>()))
		{
			NavigateBrowser(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
		}
		GUILayout.EndHorizontal();
		GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
		if (GUILayout.Button("Refresh", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }))
		{
			RefreshBrowser();
		}
		GUILayout.EndHorizontal();
		GUILayout.Label("Folder: " + (browseDir ?? "(none)"), Array.Empty<GUILayoutOption>());
		skinListScroll = GUILayout.BeginScrollView(skinListScroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(170f) });
		if (browseFiles.Count == 0)
		{
			GUILayout.Label("No .json files found in this folder.", Array.Empty<GUILayoutOption>());
		}
		for (int i = 0; i < browseFiles.Count; i++)
		{
			string fileName = Path.GetFileName(browseFiles[i]);
			if (GUILayout.Button((string.Equals(browseFiles[i], selectedSkinPath, StringComparison.OrdinalIgnoreCase) ? "> " : "") + fileName, Array.Empty<GUILayoutOption>()))
			{
				selectedSkinPath = browseFiles[i];
			}
		}
		GUILayout.EndScrollView();
		GUILayout.Label("Selected: " + (string.IsNullOrEmpty(selectedSkinPath) ? "(none)" : Path.GetFileName(selectedSkinPath)), Array.Empty<GUILayoutOption>());
		if (GUILayout.Button("Import selected skin", Array.Empty<GUILayoutOption>()))
		{
			if (string.IsNullOrEmpty(selectedSkinPath))
			{
				uiMessage = "Click a .json file in the list first.";
				return;
			}
			skinFileName = Path.GetFileNameWithoutExtension(selectedSkinPath);
			ImportSkin(Mathf.Clamp(playerSlotSetting.Value, 1, 2), selectedSkinPath);
		}
	}

	private void NavigateBrowser(string dir)
	{
		//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)
		if (string.IsNullOrEmpty(dir) || !Directory.Exists(dir))
		{
			uiMessage = "Folder not found.";
			return;
		}
		browseDir = dir;
		skinListScroll = Vector2.zero;
		RefreshBrowser();
	}

	private void RefreshBrowser()
	{
		browseFolders.Clear();
		browseFiles.Clear();
		try
		{
			if (string.IsNullOrEmpty(browseDir) || !Directory.Exists(browseDir))
			{
				browseDir = GetDownloadsDirectory();
			}
			string[] files = Directory.GetFiles(browseDir, "*.json", SearchOption.TopDirectoryOnly);
			Array.Sort(files, (IComparer<string>?)StringComparer.OrdinalIgnoreCase);
			for (int i = 0; i < files.Length; i++)
			{
				browseFiles.Add(files[i]);
			}
			uiMessage = "Found " + browseFiles.Count + " .json file(s).";
		}
		catch (Exception ex)
		{
			uiMessage = "Could not read folder: " + ex.Message;
			((BaseUnityPlugin)this).Logger.LogWarning((object)uiMessage);
		}
	}

	private static bool LooksLikeSkinFile(string path)
	{
		try
		{
			if (new FileInfo(path).Length > 1048576)
			{
				return false;
			}
			return File.ReadAllText(path).Contains("ElectoralColorChangerSkin");
		}
		catch
		{
			return false;
		}
	}

	private void RefreshAvailableSkins()
	{
		try
		{
			availableSkinFiles.Clear();
			string[] files = Directory.GetFiles(GetDownloadsDirectory(), "*.json", SearchOption.TopDirectoryOnly);
			Array.Sort(files, (IComparer<string>?)StringComparer.OrdinalIgnoreCase);
			for (int i = 0; i < files.Length; i++)
			{
				if (LooksLikeSkinFile(files[i]))
				{
					availableSkinFiles.Add(Path.GetFileName(files[i]));
				}
			}
			uiMessage = "Found " + availableSkinFiles.Count + " Electoral Color Changer skin(s) in Downloads.";
			((BaseUnityPlugin)this).Logger.LogInfo((object)uiMessage);
		}
		catch (Exception ex)
		{
			uiMessage = "Could not list Downloads: " + ex.Message;
			((BaseUnityPlugin)this).Logger.LogWarning((object)uiMessage);
		}
	}

	private void ExportSkin(int slot, string path)
	{
		try
		{
			SkinFile skinFile = new SkinFile();
			skinFile.exportedPlayer = slot;
			foreach (KeyValuePair<int, string> committedColor in committedColors)
			{
				if (committedColor.Key / 1000 == slot)
				{
					skinFile.colors.Add(new SkinColor
					{
						index = committedColor.Key % 1000,
						hex = committedColor.Value
					});
				}
			}
			skinFile.colors.Sort((SkinColor a, SkinColor b) => a.index.CompareTo(b.index));
			File.WriteAllText(path, SerializeSkin(skinFile));
			uiMessage = "Exported " + skinFile.colors.Count + " color edit(s) to " + Path.GetFileName(path) + ".";
			((BaseUnityPlugin)this).Logger.LogInfo((object)(uiMessage + " Full path: " + path));
		}
		catch (Exception ex)
		{
			uiMessage = "Skin export failed: " + ex.Message;
			((BaseUnityPlugin)this).Logger.LogWarning((object)uiMessage);
		}
	}

	private void ImportSkin(int targetSlot, string path)
	{
		//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if (!File.Exists(path))
			{
				uiMessage = "Skin file not found: " + Path.GetFileName(path);
				return;
			}
			SkinFile skinFile = DeserializeSkin(File.ReadAllText(path));
			if (skinFile == null || skinFile.format != "ElectoralColorChangerSkin" || skinFile.formatVersion != 1 || skinFile.colors == null)
			{
				uiMessage = "This is not a supported Electoral Color Changer skin file.";
				return;
			}
			Dictionary<int, string> dictionary = new Dictionary<int, string>();
			Color val = default(Color);
			for (int i = 0; i < skinFile.colors.Count; i++)
			{
				SkinColor skinColor = skinFile.colors[i];
				if (skinColor != null && skinColor.index >= 0 && skinColor.index <= 255 && ColorUtility.TryParseHtmlString(skinColor.hex, ref val))
				{
					dictionary[skinColor.index] = "#" + ColorUtility.ToHtmlStringRGB(val);
				}
			}
			List<int> list = new List<int>();
			foreach (int key in committedColors.Keys)
			{
				if (key / 1000 == targetSlot)
				{
					list.Add(key);
				}
			}
			for (int j = 0; j < list.Count; j++)
			{
				committedColors.Remove(list[j]);
			}
			foreach (KeyValuePair<int, string> item in dictionary)
			{
				committedColors[targetSlot * 1000 + item.Key] = item.Value;
			}
			RestorePalettesForSlot(targetSlot);
			if (dictionary.Count > 0)
			{
				enabledSetting.Value = true;
				previewSelectedIndex = false;
				ApplyPaletteEdit(Color.white, previewOnly: false);
				uiMessage = "Imported " + dictionary.Count + " color edit(s) from " + Path.GetFileName(path) + " onto Player " + targetSlot + ".";
			}
			else
			{
				previewSelectedIndex = false;
				uiMessage = "Imported skin contained no valid color entries; Player " + targetSlot + " edits were cleared.";
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)uiMessage);
			SaveConfig();
		}
		catch (Exception ex)
		{
			uiMessage = "Skin import failed: " + ex.Message;
			((BaseUnityPlugin)this).Logger.LogWarning((object)uiMessage);
		}
	}

	private void SetWindowOpen(bool open)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		if (open == windowOpen)
		{
			return;
		}
		if (open)
		{
			RestorePalettes();
			previewSelectedIndex = true;
			previousCursorLockState = Cursor.lockState;
			previousCursorVisible = Cursor.visible;
			cursorStateCaptured = true;
			windowOpen = true;
			RefreshBrowser();
			UnlockCursor();
		}
		else
		{
			windowOpen = false;
			if (previewSelectedIndex)
			{
				RestorePalettes();
				previewSelectedIndex = false;
			}
			RestoreCursor();
		}
	}

	private void UnlockCursor()
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		if (!cursorStateCaptured)
		{
			previousCursorLockState = Cursor.lockState;
			previousCursorVisible = Cursor.visible;
			cursorStateCaptured = true;
		}
		Cursor.lockState = (CursorLockMode)0;
		Cursor.visible = true;
	}

	private void RestoreCursor()
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		if (cursorStateCaptured)
		{
			Cursor.lockState = previousCursorLockState;
			Cursor.visible = previousCursorVisible;
			cursorStateCaptured = false;
		}
	}

	private void SaveConfig()
	{
		try
		{
			((BaseUnityPlugin)this).Config.Save();
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not save settings: " + ex.Message));
		}
	}

	private void OnDisable()
	{
		RestoreCursor();
		RestorePalettes();
	}

	private void OnDestroy()
	{
		RestoreCursor();
		RestorePalettes();
	}
}