Decompiled source of PlayerPinColors v1.0.0

plugins/PlayerPinColors.Core.dll

Decompiled 9 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using PlayerPinColors.Core.Persistence;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("PlayerPinColors.Core")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+a6d767787a8d1275a904cb51d607daed877a6117")]
[assembly: AssemblyProduct("PlayerPinColors.Core")]
[assembly: AssemblyTitle("PlayerPinColors.Core")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[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 PlayerPinColors.Core
{
	public readonly struct RgbColor
	{
		public float R { get; }

		public float G { get; }

		public float B { get; }

		public RgbColor(float r, float g, float b)
		{
			R = r;
			G = g;
			B = b;
		}
	}
	public static class PerceptualColorDistance
	{
		private readonly struct Lab
		{
			internal float L { get; }

			internal float A { get; }

			internal float B { get; }

			internal Lab(float l, float a, float b)
			{
				L = l;
				A = a;
				B = b;
			}
		}

		public static readonly RgbColor GamePrimary = new RgbColor(1f, 0f, 0f);

		public static bool TooClose(RgbColor? first, RgbColor? second, float threshold)
		{
			return DeltaE(first ?? GamePrimary, second ?? GamePrimary) < threshold;
		}

		public static float DeltaE(RgbColor first, RgbColor second)
		{
			Lab lab = ToLab(first);
			Lab lab2 = ToLab(second);
			float num = lab.L - lab2.L;
			float num2 = lab.A - lab2.A;
			float num3 = lab.B - lab2.B;
			return (float)Math.Sqrt(num * num + num2 * num2 + num3 * num3);
		}

		private static Lab ToLab(RgbColor color)
		{
			float num = PivotRgb(Clamp01(color.R));
			float num2 = PivotRgb(Clamp01(color.G));
			float num3 = PivotRgb(Clamp01(color.B));
			float value = (num * 0.4124f + num2 * 0.3576f + num3 * 0.1805f) / 0.95047f;
			float value2 = num * 0.2126f + num2 * 0.7152f + num3 * 0.0722f;
			float value3 = (num * 0.0193f + num2 * 0.1192f + num3 * 0.9505f) / 1.08883f;
			float num4 = PivotLab(value);
			float num5 = PivotLab(value2);
			float num6 = PivotLab(value3);
			return new Lab(116f * num5 - 16f, 500f * (num4 - num5), 200f * (num5 - num6));
		}

		private static float Clamp01(float value)
		{
			if (!(value < 0f))
			{
				if (!(value > 1f))
				{
					return value;
				}
				return 1f;
			}
			return 0f;
		}

		private static float PivotRgb(float value)
		{
			if (!(value > 0.04045f))
			{
				return value / 12.92f;
			}
			return (float)Math.Pow((value + 0.055f) / 1.055f, 2.4000000953674316);
		}

		private static float PivotLab(float value)
		{
			if (!(value > 0.008856f))
			{
				return 7.787f * value + 0.13793103f;
			}
			return (float)Math.Pow(value, 0.3333333432674408);
		}
	}
	public sealed class ColorClaim
	{
		public string Key { get; }

		public string Name { get; }

		public string PrimaryColor { get; }

		public string RegisteredAt { get; }

		public string Account { get; }

		public ColorClaim(string key, string name, string primaryColor, string registeredAt, string account = "")
		{
			Key = key ?? string.Empty;
			Name = name ?? string.Empty;
			PrimaryColor = WorldColorStore.NormalizeHex(primaryColor);
			RegisteredAt = registeredAt ?? string.Empty;
			Account = account ?? string.Empty;
		}
	}
	public static class UniqueColorResolver
	{
		public static HashSet<string> FindConflicts(IEnumerable<ColorClaim> claims, Func<string, string, bool> tooClose)
		{
			if (claims == null)
			{
				throw new ArgumentNullException("claims");
			}
			if (tooClose == null)
			{
				throw new ArgumentNullException("tooClose");
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			List<ColorClaim> list = new List<ColorClaim>();
			DateTime utc;
			foreach (ColorClaim claim in (from colorClaim in claims
				where colorClaim != null
				orderby (!WorldColorStore.TryParseTimestamp(colorClaim.RegisteredAt, out utc)) ? DateTime.MaxValue : utc
				select colorClaim).ThenBy<ColorClaim, string>((ColorClaim colorClaim) => colorClaim.Name, StringComparer.OrdinalIgnoreCase).ThenBy<ColorClaim, string>((ColorClaim colorClaim) => colorClaim.Key, StringComparer.Ordinal))
			{
				if (list.Any((ColorClaim other) => !SameAccount(other, claim) && tooClose(other.PrimaryColor, claim.PrimaryColor)))
				{
					hashSet.Add(claim.Key);
				}
				else
				{
					list.Add(claim);
				}
			}
			return hashSet;
		}

		private static bool SameAccount(ColorClaim a, ColorClaim b)
		{
			if (a.Account.Length > 0)
			{
				return string.Equals(a.Account, b.Account, StringComparison.Ordinal);
			}
			return false;
		}
	}
	public static class UniqueColorReview
	{
		public const float MinDeltaE = 5f;

		public const float MaxDeltaE = 50f;

		public const float DefaultDeltaE = 25f;

		public static bool NeedsReview(float? reviewedAt, float newThreshold)
		{
			if (reviewedAt.HasValue)
			{
				return newThreshold > reviewedAt.Value;
			}
			return true;
		}

		public static float Clamp(float configured)
		{
			if (float.IsNaN(configured) || float.IsInfinity(configured))
			{
				return 25f;
			}
			if (!(configured < 5f))
			{
				if (!(configured > 50f))
				{
					return configured;
				}
				return 50f;
			}
			return 5f;
		}
	}
}
namespace PlayerPinColors.Core.Persistence
{
	public sealed class WorldColorData
	{
		[JsonProperty(Order = 1)]
		public int Version { get; set; } = 1;

		[JsonProperty(Order = 2)]
		public List<CharacterColorRecord> Characters { get; set; } = new List<CharacterColorRecord>();
	}
	public sealed class CharacterColorRecord
	{
		[JsonProperty(Order = 1)]
		public string CharacterName { get; set; } = string.Empty;

		[JsonProperty(Order = 2)]
		public string PlatformId { get; set; } = string.Empty;

		[JsonProperty(Order = 3)]
		public string PrimaryColor { get; set; } = string.Empty;

		[JsonProperty(Order = 4)]
		public string SecondaryColor { get; set; } = string.Empty;

		[JsonProperty(Order = 5)]
		public bool KeepVanillaNameColor { get; set; } = true;

		[JsonProperty(Order = 6)]
		public string FirstSeen { get; set; } = string.Empty;

		[JsonProperty(Order = 7)]
		public string LastSeen { get; set; } = string.Empty;

		[JsonProperty(Order = 8)]
		public string ColorSince { get; set; } = string.Empty;

		[JsonProperty(Order = 9)]
		public bool MustChooseNewColor { get; set; }

		[JsonIgnore]
		public string RegisteredAt
		{
			get
			{
				if (ColorSince.Length <= 0)
				{
					return FirstSeen;
				}
				return ColorSince;
			}
		}

		[JsonIgnore]
		public string Key => CharacterKey.Create(PlatformId, CharacterName);
	}
	public static class CharacterKey
	{
		public const int MaxPartLength = 128;

		public static string Create(string platformId, string characterName)
		{
			return platformId.Trim() + "_" + characterName.Trim().ToLowerInvariant();
		}

		public static bool IsValidPart(string? value)
		{
			if (value != null && value.Trim().Length > 0)
			{
				return value.Length <= 128;
			}
			return false;
		}
	}
	public sealed class WorldColorStore
	{
		public const int CurrentVersion = 1;

		public const int MaxWorldIdLength = 128;

		private const string TimestampFormat = "yyyy-MM-ddTHH:mm:ssZ";

		private readonly string _worldsDirectory;

		private readonly Action<string> _info;

		private readonly Action<string> _warning;

		public WorldColorStore(string worldsDirectory, Action<string>? info = null, Action<string>? warning = null)
		{
			_worldsDirectory = worldsDirectory ?? throw new ArgumentNullException("worldsDirectory");
			_info = info ?? ((Action<string>)delegate
			{
			});
			_warning = warning ?? ((Action<string>)delegate
			{
			});
		}

		public WorldColorData LoadState(string worldId)
		{
			//IL_00c7: Expected O, but got Unknown
			string path = GetPath(worldId);
			try
			{
				if (!File.Exists(path))
				{
					_info("No saved player colors exist yet for world '" + worldId + "'.");
					return new WorldColorData();
				}
				string text = File.ReadAllText(path);
				if (string.IsNullOrWhiteSpace(text))
				{
					_warning("Saved player colors for world '" + worldId + "' are empty; starting with none.");
					return new WorldColorData();
				}
				WorldColorData worldColorData = JsonConvert.DeserializeObject<WorldColorData>(text);
				if (worldColorData?.Characters == null)
				{
					_warning("Saved player colors for world '" + worldId + "' did not contain characters; starting empty.");
					return new WorldColorData();
				}
				worldColorData.Characters = CleanCharacters(worldColorData.Characters);
				worldColorData.Version = 1;
				return worldColorData;
			}
			catch (JsonException ex)
			{
				JsonException ex2 = ex;
				_warning("Could not parse saved player colors for world '" + worldId + "': " + ((Exception)(object)ex2).Message);
				return new WorldColorData();
			}
			catch (IOException ex3)
			{
				_warning("Could not read saved player colors for world '" + worldId + "': " + ex3.Message);
				return new WorldColorData();
			}
			catch (UnauthorizedAccessException ex4)
			{
				_warning("Could not access saved player colors for world '" + worldId + "': " + ex4.Message);
				return new WorldColorData();
			}
		}

		public bool Save(string worldId, IEnumerable<CharacterColorRecord> characters)
		{
			string path = GetPath(worldId);
			try
			{
				Directory.CreateDirectory(_worldsDirectory);
				string contents = JsonConvert.SerializeObject((object)new WorldColorData
				{
					Version = 1,
					Characters = CleanCharacters(characters)
				}, (Formatting)1);
				string text = path + ".tmp";
				File.WriteAllText(text, contents);
				if (File.Exists(path))
				{
					File.Delete(path);
				}
				File.Move(text, path);
				return true;
			}
			catch (IOException ex)
			{
				_warning("Could not save player colors for world '" + worldId + "': " + ex.Message);
				return false;
			}
			catch (UnauthorizedAccessException ex2)
			{
				_warning("Could not access saved player colors for world '" + worldId + "': " + ex2.Message);
				return false;
			}
		}

		public static string NormalizeHex(string? value)
		{
			if (value == null)
			{
				return string.Empty;
			}
			string text = value.Trim();
			if (text.StartsWith("#", StringComparison.Ordinal))
			{
				text = text.Substring(1);
			}
			if (text.Length != 6 || !text.All(Uri.IsHexDigit))
			{
				return string.Empty;
			}
			return "#" + text.ToUpperInvariant();
		}

		public static string FormatTimestamp(DateTime time)
		{
			return ((time.Kind == DateTimeKind.Local) ? time.ToUniversalTime() : time).ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
		}

		public static bool TryParseTimestamp(string? value, out DateTime utc)
		{
			utc = default(DateTime);
			if (value == null || value.Trim().Length == 0)
			{
				return false;
			}
			if (!DateTime.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out utc))
			{
				return false;
			}
			utc = DateTime.SpecifyKind(utc, DateTimeKind.Utc);
			return true;
		}

		public static string NormalizeTimestamp(string? value)
		{
			if (!TryParseTimestamp(value, out var utc))
			{
				return string.Empty;
			}
			return FormatTimestamp(utc);
		}

		public static bool IsValidWorldId(string? worldId)
		{
			if (worldId == null || worldId.Trim().Length == 0 || worldId.Length > 128)
			{
				return false;
			}
			foreach (char c in worldId)
			{
				if (!char.IsLetterOrDigit(c) && c != '_' && c != '-' && c != '.')
				{
					return false;
				}
			}
			return true;
		}

		private static List<CharacterColorRecord> CleanCharacters(IEnumerable<CharacterColorRecord?>? characters)
		{
			Dictionary<string, CharacterColorRecord> dictionary = new Dictionary<string, CharacterColorRecord>(StringComparer.Ordinal);
			foreach (CharacterColorRecord item in characters ?? Enumerable.Empty<CharacterColorRecord>())
			{
				if (item != null && CharacterKey.IsValidPart(item.CharacterName) && CharacterKey.IsValidPart(item.PlatformId))
				{
					dictionary[item.Key] = new CharacterColorRecord
					{
						CharacterName = item.CharacterName.Trim(),
						PlatformId = item.PlatformId.Trim(),
						PrimaryColor = NormalizeHex(item.PrimaryColor),
						SecondaryColor = NormalizeHex(item.SecondaryColor),
						KeepVanillaNameColor = item.KeepVanillaNameColor,
						FirstSeen = NormalizeTimestamp(item.FirstSeen),
						LastSeen = NormalizeTimestamp(item.LastSeen),
						ColorSince = NormalizeTimestamp(item.ColorSince),
						MustChooseNewColor = item.MustChooseNewColor
					};
				}
			}
			return dictionary.Values.OrderBy<CharacterColorRecord, string>((CharacterColorRecord record) => record.CharacterName, StringComparer.OrdinalIgnoreCase).ThenBy<CharacterColorRecord, string>((CharacterColorRecord record) => record.PlatformId, StringComparer.Ordinal).ToList();
		}

		private string GetPath(string worldId)
		{
			string text = (IsValidWorldId(worldId) ? worldId : "unknown-world");
			return Path.Combine(_worldsDirectory, text + ".json");
		}
	}
}
namespace PlayerPinColors.Core.Logging
{
	public sealed class LogCleaner
	{
		public const string Character = "Character";

		public const string PlatformId = "PlatformID";

		public const string PeerId = "PeerID";

		public const string WorldId = "WorldID";

		public const string FolderPath = "FolderPath";

		public const string IpAddress = "IPAddress";

		public const string SteamName = "SteamName";

		public const string PlayFabId = "PlayFabID";

		public const string WorldName = "WorldName";

		public const string WorldSeed = "WorldSeed";

		public const string ServerAddress = "ServerAddress";

		public const string Secret = "Secret";

		public const string UserName = "UserName";

		public const string MachineName = "MachineName";

		public const string NameStart = "#~%";

		public const string NameEnd = "%~#";

		public const string CleanSuffix = "_clean";

		private const RegexOptions Options = RegexOptions.Compiled | RegexOptions.CultureInvariant;

		private const string Segment = "[^\\\\/:*?\"<>|\\r\\n]+";

		private const string LastSegment = "[^\\\\/:*?\"<>|\\s]*";

		private static readonly Regex MarkedName = new Regex(Regex.Escape("#~%") + "(.+?)" + Regex.Escape("%~#"), RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly HashSet<string> CommonWords = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
		{
			"all", "and", "black", "blue", "character", "client", "color", "colors", "config", "data",
			"debug", "default", "error", "false", "fatal", "file", "files", "for", "from", "game",
			"green", "host", "info", "load", "loaded", "local", "map", "message", "mod", "mods",
			"name", "network", "new", "none", "not", "null", "offline", "online", "peer", "pin",
			"pins", "player", "players", "plugin", "primary", "red", "save", "saved", "secondary", "server",
			"steam", "system", "test", "the", "time", "true", "unity", "user", "version", "warning",
			"white", "with", "world", "you", "your"
		};

		private static readonly Regex SecretSetting = new Regex("([\\w.-]*(?:password|passwd|pwd|secret|api[_-]?key|token|webhook|join[ _-]?code)[\\w.-]*\\s*[:=]\\s*)(\"[^\"\\r\\n]*\"|[^\\s;,]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex SecretArgument = new Regex("(-password\\s+)(\"[^\"\\r\\n]*\"|\\S+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex DiscordWebhook = new Regex("https?://(?:[\\w-]+\\.)?discord(?:app)?\\.com/api/webhooks/[^\\s\"']+", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex CharacterFile = new Regex("(characters(?:_local)?[\\\\/])([^\\\\/\\s._]+)(?=(?:_backup[^\\\\/\\s]*)?\\.fch)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex WorldFolder = new Regex("(worlds(?:_local)?[\\\\/])([^\\\\/\\s.<]+?)(?=(?:_backup[^\\\\/\\s]*)?(?:[\\\\/]|\\.(?:fwl|db|old)))", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex Persona = new Regex("(persona:\\s*)(.+?)(?=\\s+\\[|\\s*$)", RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex PlayFabEntity = new Regex("(\\bentity\\s+id(?:\\s+is)?[\\s:=]+)([0-9A-Fa-f]{8,})", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex AddressSetting = new Regex("(\\b[\\w.]*(?:address|hostname|host|server)\\s*=\\s*)([A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex WorldFile = new Regex("(worlds[\\\\/])(-?\\d+)(?=\\.json)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex WorldLabel = new Regex("(\\bworld ')(-?\\d+)(?=')", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex Peer = new Regex("(\\bpeer(?:\\s*id)?[\\s:=]+)(-?\\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex SteamId = new Regex("(?<!\\d)7656119\\d{10}(?!\\d)", RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex Paths = new Regex("(?<![A-Za-z0-9])[A-Za-z]:[\\\\/](?:[^\\\\/:*?\"<>|\\r\\n]+[\\\\/])*[^\\\\/:*?\"<>|\\s]*|\\\\\\\\[^\\\\/\\s]+[\\\\/](?:[^\\\\/:*?\"<>|\\r\\n]+[\\\\/])*[^\\\\/:*?\"<>|\\s]*|(?<![\\w.:/\\\\<])/(?:[^/\\s:*?\"<>|\\\\]+/)+[^\\\\/:*?\"<>|\\s]*", RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex FileName = new Regex("^[^\\\\/]*\\.[A-Za-z0-9]{1,8}$", RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex Ipv4 = new Regex("(?<![\\d.])(?<!Version=)(?:\\d{1,3}\\.){3}\\d{1,3}(?![\\d.])", RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly Regex Ipv6 = new Regex("(?<![\\w:.])(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}(?![\\w:])", RegexOptions.Compiled | RegexOptions.CultureInvariant);

		private static readonly HashSet<string> NotSecret = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "true", "false", "none", "null", "empty", "0", "1" };

		private readonly object _lock = new object();

		private readonly Dictionary<string, string> _tokens = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		private readonly Dictionary<string, int> _counts = new Dictionary<string, int>(StringComparer.Ordinal);

		private readonly HashSet<string> _commonNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private Regex? _known;

		private Regex? _commonInContext;

		public static string MarkName(string? name)
		{
			string text = name?.Trim() ?? string.Empty;
			if (text.Length != 0)
			{
				return "#~%" + text + "%~#";
			}
			return string.Empty;
		}

		public static string MarkNameIn(string text, string? name)
		{
			string text2 = name?.Trim() ?? string.Empty;
			if (string.IsNullOrEmpty(text) || text2.Length == 0)
			{
				return text ?? string.Empty;
			}
			int num = text.LastIndexOf(text2, StringComparison.OrdinalIgnoreCase);
			if (num < 0)
			{
				return text;
			}
			return text.Substring(0, num) + MarkName(text.Substring(num, text2.Length)) + text.Substring(num + text2.Length);
		}

		public static string CleanPath(string path)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			string text = Path.GetFileNameWithoutExtension(path) + "_clean" + Path.GetExtension(path);
			string directoryName = Path.GetDirectoryName(path);
			if (!string.IsNullOrEmpty(directoryName))
			{
				return Path.Combine(directoryName, text);
			}
			return text;
		}

		public string Register(string item, string? value)
		{
			if (string.IsNullOrEmpty(item))
			{
				throw new ArgumentException("An item name is required.", "item");
			}
			string text = value?.Trim() ?? string.Empty;
			if (text.Length == 0)
			{
				return string.Empty;
			}
			lock (_lock)
			{
				if (_tokens.TryGetValue(text, out string value2))
				{
					return value2;
				}
				_counts.TryGetValue(item, out var value3);
				value2 = "<" + item + (_counts[item] = value3 + 1).ToString("D3", CultureInfo.InvariantCulture) + ">";
				_tokens[text] = value2;
				if (item == "Character" && CommonWords.Contains(text))
				{
					_commonNames.Add(text);
				}
				_known = null;
				_commonInContext = null;
				return value2;
			}
		}

		public string Clean(string? text)
		{
			if (string.IsNullOrEmpty(text))
			{
				return string.Empty;
			}
			lock (_lock)
			{
				string input = MarkedName.Replace(text, (Match m) => Register("Character", m.Groups[1].Value));
				input = SecretSetting.Replace(input, CleanSecret);
				input = SecretArgument.Replace(input, CleanSecret);
				input = DiscordWebhook.Replace(input, (Match m) => Register("Secret", m.Value));
				input = CharacterFile.Replace(input, (Match m) => m.Groups[1].Value + Register("Character", m.Groups[2].Value));
				input = WorldFolder.Replace(input, (Match m) => m.Groups[1].Value + Register("WorldName", m.Groups[2].Value));
				input = Persona.Replace(input, (Match m) => m.Groups[1].Value + Register("SteamName", m.Groups[2].Value));
				input = PlayFabEntity.Replace(input, (Match m) => m.Groups[1].Value + Register("PlayFabID", m.Groups[2].Value));
				input = AddressSetting.Replace(input, (Match m) => m.Groups[1].Value + Register("ServerAddress", m.Groups[2].Value));
				input = WorldFile.Replace(input, (Match m) => m.Groups[1].Value + Register("WorldID", m.Groups[2].Value));
				input = WorldLabel.Replace(input, (Match m) => m.Groups[1].Value + Register("WorldID", m.Groups[2].Value));
				input = Peer.Replace(input, (Match m) => (m.Groups[2].Length >= 4) ? (m.Groups[1].Value + Register("PeerID", m.Groups[2].Value)) : m.Value);
				input = SteamId.Replace(input, (Match m) => Register("PlatformID", m.Value));
				input = Paths.Replace(input, CleanPathMatch);
				input = Ipv4.Replace(input, (Match m) => (!IsIpv4(m.Value)) ? m.Value : Register("IPAddress", m.Value));
				input = Ipv6.Replace(input, (Match m) => (!IsIpv6(m.Value)) ? m.Value : Register("IPAddress", m.Value));
				return ReplaceKnown(input);
			}
		}

		public void RegisterThisComputer()
		{
			Register("UserName", Environment.UserName);
			Register("MachineName", Environment.MachineName);
		}

		private string CleanSecret(Match match)
		{
			string text = match.Groups[2].Value.Trim(new char[1] { '"' });
			if (text.Length == 0 || NotSecret.Contains(text))
			{
				return match.Value;
			}
			return match.Groups[1].Value + Register("Secret", text);
		}

		private string CleanPathMatch(Match match)
		{
			string value = match.Value;
			int num = value.LastIndexOfAny(new char[2] { '\\', '/' });
			if (num < 0)
			{
				return value;
			}
			string text = value.Substring(num + 1);
			if (text.Length == 0)
			{
				return Register("FolderPath", value.Substring(0, num)) + value[num];
			}
			if (!FileName.IsMatch(text))
			{
				return Register("FolderPath", value);
			}
			return Register("FolderPath", value.Substring(0, num)) + value[num] + text;
		}

		private string ReplaceKnown(string text)
		{
			if (_tokens.Count == 0)
			{
				return text;
			}
			text = ReplaceCommonNames(text);
			string[] array = _tokens.Keys.Where((string value) => !_commonNames.Contains(value)).ToArray();
			if (array.Length == 0)
			{
				return text;
			}
			if (_known == null)
			{
				IEnumerable<string> values = array.OrderByDescending((string value) => value.Length).Select(Regex.Escape);
				_known = new Regex("<[A-Za-z]+\\d{3,}>|(?<![\\p{L}\\p{N}])(?:" + string.Join("|", values) + ")(?![\\p{L}\\p{N}])", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
			}
			string value;
			return _known.Replace(text, (Match m) => (!_tokens.TryGetValue(m.Value, out value)) ? m.Value : value);
		}

		private string ReplaceCommonNames(string text)
		{
			if (_commonNames.Count == 0)
			{
				return text;
			}
			if (_commonInContext == null)
			{
				string text2 = string.Join("|", _commonNames.OrderByDescending((string value) => value.Length).Select(Regex.Escape));
				_commonInContext = new Regex("(\\b(?:character|player|name|ZDOID from)(?:\\s*[:=]\\s*|\\s+)['\"]?)(" + text2 + ")(?![\\p{L}\\p{N}])", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
			}
			return _commonInContext.Replace(text, (Match m) => m.Groups[1].Value + _tokens[m.Groups[2].Value]);
		}

		private static bool IsIpv4(string value)
		{
			int result;
			return value.Split(new char[1] { '.' }).All((string part) => int.TryParse(part, NumberStyles.None, CultureInfo.InvariantCulture, out result) && result <= 255);
		}

		private static bool IsIpv6(string value)
		{
			if (value.Any(Uri.IsHexDigit) && IPAddress.TryParse(value, out IPAddress address))
			{
				return address.AddressFamily == AddressFamily.InterNetworkV6;
			}
			return false;
		}
	}
}

plugins/PlayerPinColors.dll

Decompiled 9 hours ago
using System;
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.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.GUI;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using PlayerPinColors.Commands;
using PlayerPinColors.Core;
using PlayerPinColors.Core.Logging;
using PlayerPinColors.Core.Persistence;
using PlayerPinColors.Debugging;
using PlayerPinColors.Patches;
using PlayerPinColors.Persistence;
using PlayerPinColors.UI;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("Truncated")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+a6d767787a8d1275a904cb51d607daed877a6117")]
[assembly: AssemblyProduct("PlayerPinColors")]
[assembly: AssemblyTitle("PlayerPinColors")]
[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]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[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 PlayerPinColors
{
	internal static class ColorSync
	{
		private const string RpcColors = "Truncated.PlayerPinColors.ColorsBroadcast";

		private const string RpcProposal = "Truncated.PlayerPinColors.ColorProposal";

		private const string RpcProposalResult = "Truncated.PlayerPinColors.ColorProposalResult";

		private const string RpcSnapshotRequest = "Truncated.PlayerPinColors.ColorsSnapshotRequest";

		private const string RpcSnapshot = "Truncated.PlayerPinColors.ColorsSnapshot";

		private const string RpcSuggestionRequest = "Truncated.PlayerPinColors.SuggestionRequest";

		private const string RpcSuggestions = "Truncated.PlayerPinColors.Suggestions";

		private const string RpcChooseNewColor = "Truncated.PlayerPinColors.ChooseNewColor";

		internal const int PackageVersion = 2;

		private const float MinSendInterval = 1f;

		private const int MaxRemotePlayers = 256;

		private const int SuggestionCount = 5;

		private const int SuggestionAttempts = 20000;

		private const float MinSuggestionInterval = 0.5f;

		private const float UniqueCheckDelay = 1f;

		private static readonly FieldRef<Character, ZNetView> CharacterNView = AccessTools.FieldRefAccess<Character, ZNetView>("m_nview");

		private static readonly Dictionary<long, PlayerColorSet> Remote = new Dictionary<long, PlayerColorSet>();

		private static readonly Dictionary<long, PlayerColorSet> ServerColors = new Dictionary<long, PlayerColorSet>();

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

		private static readonly Dictionary<long, float> NextSuggestionByPeer = new Dictionary<long, float>();

		private static bool _sendPending;

		private static bool _hasQueuedProposal;

		private static PlayerColorSet _queuedProposal;

		private static float _nextSend;

		private static int _proposalId;

		private static bool _awaitingPickerProposal;

		private static bool _suppressConfigChange;

		private static float _nextSuggestionRequest;

		private static bool _uniqueCheckPending;

		private static float _uniqueCheckDueAt;

		private static float? _reviewedThreshold;

		internal static long LocalPeerId
		{
			get
			{
				if (!((Object)(object)ZNet.instance != (Object)null) || ZDOMan.instance == null)
				{
					return 0L;
				}
				return ZNet.GetUID();
			}
		}

		internal static ZNetView GetNView(Player player)
		{
			return CharacterNView.Invoke((Character)(object)player);
		}

		internal static void Register()
		{
			Remote.Clear();
			ServerColors.Clear();
			NextSuggestionByPeer.Clear();
			LoggedInPeers.Clear();
			_nextSuggestionRequest = 0f;
			_sendPending = false;
			_hasQueuedProposal = false;
			_queuedProposal = default(PlayerColorSet);
			_nextSend = 0f;
			_proposalId = 0;
			_awaitingPickerProposal = false;
			_uniqueCheckPending = true;
			_uniqueCheckDueAt = 0f;
			_reviewedThreshold = null;
			ZRoutedRpc.instance.Register<ZPackage>("Truncated.PlayerPinColors.ColorProposal", (Action<long, ZPackage>)RPC_Proposal);
			ZRoutedRpc.instance.Register<ZPackage>("Truncated.PlayerPinColors.ColorProposalResult", (Action<long, ZPackage>)RPC_ProposalResult);
			ZRoutedRpc.instance.Register<ZPackage>("Truncated.PlayerPinColors.ColorsSnapshotRequest", (Action<long, ZPackage>)RPC_SnapshotRequest);
			ZRoutedRpc.instance.Register<ZPackage>("Truncated.PlayerPinColors.ColorsSnapshot", (Action<long, ZPackage>)RPC_Snapshot);
			ZRoutedRpc.instance.Register<ZPackage>("Truncated.PlayerPinColors.ColorsBroadcast", (Action<long, ZPackage>)RPC_Colors);
			ZRoutedRpc.instance.Register<ZPackage>("Truncated.PlayerPinColors.SuggestionRequest", (Action<long, ZPackage>)RPC_SuggestionRequest);
			ZRoutedRpc.instance.Register<ZPackage>("Truncated.PlayerPinColors.Suggestions", (Action<long, ZPackage>)RPC_Suggestions);
			ZRoutedRpc.instance.Register<ZPackage>("Truncated.PlayerPinColors.ChooseNewColor", (Action<long, ZPackage>)RPC_ChooseNewColor);
			ForgetColorsCommand.RegisterRpcs();
			AdminCommand.RegisterRpcs();
			DebugCheckCommand.RegisterRpcs();
		}

		internal static void DebugView(long peerId, out float threshold, out bool known, out CharacterIdentity character, out bool hasLive, out PlayerColorSet live, out Color[] suggestions)
		{
			PruneAbsentPlayers();
			threshold = GetThreshold();
			known = TryGetCharacter(peerId, out character);
			hasLive = ServerColors.TryGetValue(peerId, out live);
			suggestions = CreateSuggestions(TakenPrimaries(peerId), threshold);
		}

		internal static void OnWorldClosed()
		{
			SavedColors.SaveCurrentWorld();
			SavedColors.Clear();
			ForgetColorsCommand.ClearNameCache();
			AdminPanel.Destroy();
			AdminCommand.ClearReply();
			DebugCheckLog.Finish("The world closed.");
			DebugCheckRelay.Clear();
		}

		internal static void OnAdminSettingChanged()
		{
			_uniqueCheckPending = true;
			_uniqueCheckDueAt = Time.unscaledTime + 1f;
		}

		internal static void OnMinimumDifferenceChanged()
		{
			float threshold = GetThreshold();
			if (UniqueColorReview.NeedsReview(_reviewedThreshold, threshold))
			{
				OnAdminSettingChanged();
			}
			else if (!_uniqueCheckPending)
			{
				_reviewedThreshold = threshold;
			}
		}

		internal static void OnLocalPlayerSpawned()
		{
			OwnColors.LoadForLocalCharacter();
			QueueProposal(ColorUtil.Own);
			RequestSnapshot();
		}

		internal static void OnOwnColorsChanged()
		{
			if (!_suppressConfigChange)
			{
				QueueProposal(ColorUtil.Own);
			}
		}

		internal static void RequestPrimaryColor(Color color)
		{
			//IL_0008: 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_0014: 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)
			PlayerColorSet own = ColorUtil.Own;
			own.Primary = new Color(color.r, color.g, color.b, 1f);
			_awaitingPickerProposal = true;
			QueueProposal(own);
		}

		internal static void ExpectPrimaryReset()
		{
			if (ColorUtil.Own.Primary.HasValue)
			{
				_awaitingPickerProposal = true;
			}
		}

		internal static void RequestSuggestions()
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			if ((Object)(object)ZNet.instance == (Object)null || ZRoutedRpc.instance == null || Time.unscaledTime < _nextSuggestionRequest)
			{
				return;
			}
			_nextSuggestionRequest = Time.unscaledTime + 0.5f;
			if (ZNet.instance.IsServer())
			{
				SendSuggestions(LocalPeerId);
				return;
			}
			ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
			if (serverPeer != null)
			{
				ZPackage val = new ZPackage();
				val.Write(2);
				ZRoutedRpc.instance.InvokeRoutedRPC(serverPeer.m_uid, "Truncated.PlayerPinColors.SuggestionRequest", new object[1] { val });
			}
		}

		internal static bool TryGet(ZDOID characterId, out PlayerColorSet colors)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			long userID = ((ZDOID)(ref characterId)).UserID;
			if (userID != 0L && userID == LocalPeerId)
			{
				colors = ColorUtil.Own;
				return !colors.IsDefault;
			}
			if (Remote.TryGetValue(userID, out colors))
			{
				return !colors.IsDefault;
			}
			ZDOMan instance = ZDOMan.instance;
			ZDO val = ((instance != null) ? instance.GetZDO(characterId) : null);
			colors = ((val != null) ? ReadKeys(val) : PlayerColorSet.GameColors);
			return !colors.IsDefault;
		}

		internal static bool TryGet(long peerId, out PlayerColorSet colors)
		{
			if (peerId != 0L && peerId == LocalPeerId)
			{
				colors = ColorUtil.Own;
				return !colors.IsDefault;
			}
			if (Remote.TryGetValue(peerId, out colors))
			{
				return !colors.IsDefault;
			}
			return false;
		}

		internal static PlayerColorSet ReadKeys(ZDO zdo)
		{
			return new PlayerColorSet
			{
				Primary = ColorUtil.FromHex(zdo.GetString("Truncated.PlayerPinColors.PrimaryColor", "")),
				Secondary = ColorUtil.FromHex(zdo.GetString("Truncated.PlayerPinColors.SecondaryColor", "")),
				KeepVanillaNameColor = zdo.GetBool("Truncated.PlayerPinColors.KeepVanillaNameColor", true)
			};
		}

		internal static void Tick()
		{
			if (_uniqueCheckPending && Time.unscaledTime >= _uniqueCheckDueAt)
			{
				TryRunUniqueColorCheck();
			}
			if (_sendPending && !(Time.unscaledTime < _nextSend) && ZRoutedRpc.instance != null && !((Object)(object)ZNet.instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null))
			{
				_sendPending = false;
				_nextSend = Time.unscaledTime + 1f;
				SubmitProposal(_hasQueuedProposal ? _queuedProposal : ColorUtil.Own);
			}
		}

		private static void QueueProposal(PlayerColorSet proposed)
		{
			_queuedProposal = proposed;
			_hasQueuedProposal = true;
			_sendPending = true;
		}

		private static void SubmitProposal(PlayerColorSet proposed)
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			if (ZRoutedRpc.instance == null || (Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			if (ZNet.instance.IsServer())
			{
				_sendPending = false;
				_hasQueuedProposal = false;
				int requestId = ++_proposalId;
				ProcessProposal(LocalPeerId, requestId, proposed);
				return;
			}
			ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
			if (serverPeer == null)
			{
				_sendPending = true;
				return;
			}
			_sendPending = false;
			_hasQueuedProposal = false;
			int num = ++_proposalId;
			ZPackage val = new ZPackage();
			val.Write(2);
			val.Write(num);
			WriteColors(val, proposed);
			ZRoutedRpc.instance.InvokeRoutedRPC(serverPeer.m_uid, "Truncated.PlayerPinColors.ColorProposal", new object[1] { val });
		}

		private static void RequestSnapshot()
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			if (!((Object)(object)ZNet.instance == (Object)null) && ZRoutedRpc.instance != null && !ZNet.instance.IsServer())
			{
				ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
				if (serverPeer != null)
				{
					ZRoutedRpc.instance.InvokeRoutedRPC(serverPeer.m_uid, "Truncated.PlayerPinColors.ColorsSnapshotRequest", new object[1] { (object)new ZPackage() });
				}
			}
		}

		private static void RPC_Proposal(long sender, ZPackage pkg)
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && TryReadColors(pkg, out var requestId, out var colors))
			{
				ProcessProposal(sender, requestId, colors);
			}
		}

		private static void ProcessProposal(long peerId, int requestId, PlayerColorSet proposed)
		{
			PruneAbsentPlayers();
			if (!ServerColors.ContainsKey(peerId) && ServerColors.Count >= 256)
			{
				SendProposalResult(peerId, requestId, accepted: false, GetThreshold(), GameColorsKeepingName(proposed), Array.Empty<Color>());
				return;
			}
			CharacterIdentity character;
			bool flag = TryGetCharacter(peerId, out character);
			bool flag2 = LoggedInPeers.Add(peerId);
			float threshold = GetThreshold();
			if (flag2 && flag && proposed.IsDefault && SavedColors.TryGet(character, out var colors) && !colors.IsDefault)
			{
				proposed = colors;
			}
			List<Color?> taken = (ModConfig.EnforceUniquePrimaryColors.Value ? TakenPrimaries(peerId) : new List<Color?>());
			bool flag3 = IsFree(proposed, taken, threshold);
			bool flag4 = false;
			PlayerColorSet playerColorSet = proposed;
			if (!flag3)
			{
				PlayerColorSet colors2;
				if (ServerColors.TryGetValue(peerId, out var value))
				{
					playerColorSet = value;
				}
				else if (flag && SavedColors.TryGet(character, out colors2) && IsFree(colors2, taken, threshold))
				{
					playerColorSet = colors2;
					flag4 = true;
				}
				else
				{
					playerColorSet = GameColorsKeepingName(proposed);
				}
			}
			if (flag3 || flag4)
			{
				ServerColors[peerId] = playerColorSet;
				SetRemote(peerId, playerColorSet);
				BroadcastColors(peerId, playerColorSet);
				if (flag)
				{
					SavedColors.Set(character, playerColorSet, flag2);
				}
			}
			else if (flag && flag2)
			{
				SavedColors.MarkLogin(character);
			}
			SendProposalResult(peerId, requestId, flag3, threshold, playerColorSet, flag3 ? Array.Empty<Color>() : CreateSuggestions(taken, threshold));
			if (flag2 && !flag3 && !flag4)
			{
				bool adminEnforced = flag && SavedColors.MustChooseNewColor(character.Key);
				SendChooseNewColor(peerId, threshold, adminEnforced);
			}
		}

		private static void TryRunUniqueColorCheck()
		{
			if (!((Object)(object)ZNet.instance == (Object)null))
			{
				if (!ZNet.instance.IsServer())
				{
					_uniqueCheckPending = false;
				}
				else if (SavedColors.EnsureWorldLoaded())
				{
					_uniqueCheckPending = false;
					RunUniqueColorCheck();
				}
			}
		}

		private static void RunUniqueColorCheck()
		{
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Expected O, but got Unknown
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Expected O, but got Unknown
			PruneAbsentPlayers();
			if (!ModConfig.EnforceUniquePrimaryColors.Value)
			{
				SavedColors.SetMustChooseFlags(new HashSet<string>());
				_reviewedThreshold = null;
				return;
			}
			float threshold = GetThreshold();
			_reviewedThreshold = threshold;
			List<ColorClaim> list = new List<ColorClaim>();
			Dictionary<string, long> dictionary = new Dictionary<string, long>(StringComparer.Ordinal);
			foreach (KeyValuePair<long, PlayerColorSet> serverColor in ServerColors)
			{
				if (TryGetCharacter(serverColor.Key, out var character))
				{
					dictionary[character.Key] = serverColor.Key;
					CharacterColorRecord val = SavedColors.Find(character.Key);
					list.Add(new ColorClaim(character.Key, character.Name, ColorUtil.ToHex(serverColor.Value.Primary), (val != null) ? val.RegisteredAt : string.Empty, character.PlatformId));
				}
			}
			if (ModConfig.UniqueColorCheckScope.Value == ModConfig.UniqueColorScope.AllSavedCharacters)
			{
				foreach (CharacterColorRecord item in SavedColors.All())
				{
					if (!dictionary.ContainsKey(item.Key))
					{
						list.Add(new ColorClaim(item.Key, item.CharacterName, item.PrimaryColor, item.RegisteredAt, item.PlatformId));
					}
				}
			}
			HashSet<string> hashSet = UniqueColorResolver.FindConflicts((IEnumerable<ColorClaim>)list, (Func<string, string, bool>)((string a, string b) => TooClose(a, b, threshold)));
			SavedColors.SetMustChooseFlags(hashSet);
			if (hashSet.Count > 0)
			{
				Plugin.Log.LogInfo((object)$"Unique colors: {hashSet.Count} character(s) must choose a new primary color.");
			}
			foreach (string item2 in hashSet)
			{
				if (dictionary.TryGetValue(item2, out var value))
				{
					SendChooseNewColor(value, threshold, adminEnforced: true);
				}
			}
		}

		private static PlayerColorSet GameColorsKeepingName(PlayerColorSet proposed)
		{
			PlayerColorSet gameColors = PlayerColorSet.GameColors;
			gameColors.KeepVanillaNameColor = proposed.KeepVanillaNameColor;
			return gameColors;
		}

		private static bool TooClose(string hexA, string hexB, float threshold)
		{
			return Conflicts(ColorUtil.FromHex(hexA), ColorUtil.FromHex(hexB), threshold);
		}

		private static void SendChooseNewColor(long peerId, float threshold, bool adminEnforced)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			//IL_004a: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			Color[] array = CreateSuggestions(TakenPrimaries(peerId), threshold);
			if (peerId == LocalPeerId)
			{
				ColorPanel.PromptNewColor(threshold, array, adminEnforced);
				return;
			}
			ZPackage val = new ZPackage();
			val.Write(2);
			val.Write(threshold);
			val.Write(adminEnforced);
			val.Write(array.Length);
			Color[] array2 = array;
			foreach (Color value in array2)
			{
				val.Write(ColorUtil.ToHex(value));
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(peerId, "Truncated.PlayerPinColors.ChooseNewColor", new object[1] { val });
		}

		private static void RPC_ChooseNewColor(long sender, ZPackage pkg)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			if (!IsServerSender(sender))
			{
				return;
			}
			try
			{
				if (pkg.ReadInt() == 2)
				{
					float threshold = pkg.ReadSingle();
					bool adminEnforced = pkg.ReadBool();
					int num = Mathf.Clamp(pkg.ReadInt(), 0, 5);
					Color[] array = (Color[])(object)new Color[num];
					for (int i = 0; i < num; i++)
					{
						array[i] = (Color)(((??)ColorUtil.FromHex(pkg.ReadString())) ?? Color.white);
					}
					ColorPanel.PromptNewColor(threshold, array, adminEnforced);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not read the server's request to choose a new color: " + ex.Message));
			}
		}

		private static List<Color?> TakenPrimaries(long peerId)
		{
			List<Color?> list = new List<Color?>();
			foreach (KeyValuePair<long, PlayerColorSet> serverColor in ServerColors)
			{
				if (serverColor.Key != peerId && (!TryGetCharacter(serverColor.Key, out var character) || !SavedColors.MustChooseNewColor(character.Key)))
				{
					list.Add(serverColor.Value.Primary);
				}
			}
			if (ModConfig.UniqueColorCheckScope.Value == ModConfig.UniqueColorScope.AllSavedCharacters)
			{
				CharacterIdentity character2;
				string ownAccount = (TryGetCharacter(peerId, out character2) ? character2.PlatformId : null);
				list.AddRange(SavedColors.SavedPrimaries(ownAccount));
			}
			return list;
		}

		private static bool IsFree(PlayerColorSet colors, List<Color?> taken, float threshold)
		{
			return taken.All((Color? other) => !Conflicts(colors.Primary, other, threshold));
		}

		private static bool Conflicts(Color? a, Color? b, float threshold)
		{
			return PerceptualColorDistance.TooClose(ToRgb(a), ToRgb(b), threshold);
		}

		private static RgbColor? ToRgb(Color? color)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			if (!color.HasValue)
			{
				return null;
			}
			return new RgbColor(color.Value.r, color.Value.g, color.Value.b);
		}

		private static bool TryGetCharacter(long peerId, out CharacterIdentity character)
		{
			if (peerId == LocalPeerId)
			{
				return CharacterIdentity.TryFromLocalHost(out character);
			}
			return CharacterIdentity.TryFromPeer(((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetPeer(peerId) : null, out character);
		}

		private static void SendProposalResult(long peerId, int requestId, bool accepted, float threshold, PlayerColorSet canonical, Color[] suggestions)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_003d: 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_0044: Unknown result type (might be due to invalid IL or missing references)
			ZPackage val = new ZPackage();
			val.Write(2);
			val.Write(requestId);
			val.Write(accepted);
			val.Write(threshold);
			WriteColors(val, canonical);
			val.Write(suggestions.Length);
			foreach (Color value in suggestions)
			{
				val.Write(ColorUtil.ToHex(value));
			}
			if (peerId == LocalPeerId)
			{
				HandleProposalResult(requestId, accepted, threshold, canonical, suggestions);
				return;
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(peerId, "Truncated.PlayerPinColors.ColorProposalResult", new object[1] { val });
		}

		private static void RPC_ProposalResult(long sender, ZPackage pkg)
		{
			//IL_0074: 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_0079: Unknown result type (might be due to invalid IL or missing references)
			if (!IsServerSender(sender))
			{
				return;
			}
			try
			{
				if (pkg.ReadInt() == 2)
				{
					int requestId = pkg.ReadInt();
					bool accepted = pkg.ReadBool();
					float threshold = pkg.ReadSingle();
					PlayerColorSet canonical = ReadColors(pkg);
					int num = Mathf.Clamp(pkg.ReadInt(), 0, 5);
					Color[] array = (Color[])(object)new Color[num];
					for (int i = 0; i < num; i++)
					{
						array[i] = (Color)(((??)ColorUtil.FromHex(pkg.ReadString())) ?? Color.white);
					}
					HandleProposalResult(requestId, accepted, threshold, canonical, array);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not read the server's color response: " + ex.Message));
			}
		}

		private static void HandleProposalResult(int requestId, bool accepted, float threshold, PlayerColorSet canonical, Color[] suggestions)
		{
			if (requestId == _proposalId)
			{
				bool awaitingPickerProposal = _awaitingPickerProposal;
				_awaitingPickerProposal = false;
				ApplyLocalColors(canonical);
				WriteOwnKeys();
				long localPeerId = LocalPeerId;
				if (localPeerId != 0L)
				{
					PlayerPinColorsApi.RaiseColorsChanged(localPeerId);
				}
				MinimapPatches.Refresh();
				ColorPanel.Refresh();
				if (awaitingPickerProposal && !accepted)
				{
					ColorPanel.ShowPrimaryColorRejected(threshold, suggestions);
				}
			}
		}

		private static void ApplyLocalColors(PlayerColorSet colors)
		{
			_suppressConfigChange = true;
			try
			{
				OwnColors.SetAll(colors);
			}
			finally
			{
				_suppressConfigChange = false;
			}
		}

		private static void WriteOwnKeys()
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null))
			{
				PlayerColorSet own = ColorUtil.Own;
				string text = ColorUtil.ToHex(own.Primary);
				string text2 = ColorUtil.ToHex(own.Secondary);
				ZNetView val = CharacterNView.Invoke((Character)(object)localPlayer);
				if ((Object)(object)val != (Object)null && val.IsValid() && val.IsOwner())
				{
					ZDO zDO = val.GetZDO();
					zDO.Set("Truncated.PlayerPinColors.PrimaryColor", text);
					zDO.Set("Truncated.PlayerPinColors.SecondaryColor", text2);
					zDO.Set("Truncated.PlayerPinColors.KeepVanillaNameColor", own.KeepVanillaNameColor);
				}
				SetCustomData(localPlayer, "Truncated.PlayerPinColors.PrimaryColor", text);
				SetCustomData(localPlayer, "Truncated.PlayerPinColors.SecondaryColor", text2);
			}
		}

		private static void SetCustomData(Player player, string key, string value)
		{
			if (string.IsNullOrEmpty(value))
			{
				player.m_customData.Remove(key);
			}
			else
			{
				player.m_customData[key] = value;
			}
		}

		private static void RPC_SnapshotRequest(long sender, ZPackage pkg)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			PruneAbsentPlayers();
			ZPackage val = new ZPackage();
			val.Write(2);
			List<KeyValuePair<long, PlayerColorSet>> list = ServerColors.Take(256).ToList();
			val.Write(list.Count);
			foreach (KeyValuePair<long, PlayerColorSet> item in list)
			{
				val.Write(item.Key);
				WriteColors(val, item.Value);
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(sender, "Truncated.PlayerPinColors.ColorsSnapshot", new object[1] { val });
		}

		private static void RPC_Snapshot(long sender, ZPackage pkg)
		{
			if (!IsServerSender(sender))
			{
				return;
			}
			try
			{
				if (pkg.ReadInt() == 2)
				{
					int num = Mathf.Clamp(pkg.ReadInt(), 0, 256);
					Remote.Clear();
					for (int i = 0; i < num; i++)
					{
						SetRemote(pkg.ReadLong(), ReadColors(pkg));
					}
					MinimapPatches.Refresh();
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not read the server's color snapshot: " + ex.Message));
			}
		}

		private static void RPC_SuggestionRequest(long sender, ZPackage pkg)
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			try
			{
				if (pkg.ReadInt() != 2)
				{
					return;
				}
			}
			catch (Exception)
			{
				return;
			}
			if (!NextSuggestionByPeer.TryGetValue(sender, out var value) || !(Time.unscaledTime < value))
			{
				NextSuggestionByPeer[sender] = Time.unscaledTime + 0.5f;
				SendSuggestions(sender);
			}
		}

		private static void SendSuggestions(long peerId)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0050: 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)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			PruneAbsentPlayers();
			float threshold = GetThreshold();
			Color[] array = CreateSuggestions(TakenPrimaries(peerId), threshold);
			if (peerId == LocalPeerId)
			{
				ColorPanel.ReplaceSuggestions(threshold, array);
				return;
			}
			ZPackage val = new ZPackage();
			val.Write(2);
			val.Write(threshold);
			val.Write(array.Length);
			Color[] array2 = array;
			foreach (Color value in array2)
			{
				val.Write(ColorUtil.ToHex(value));
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(peerId, "Truncated.PlayerPinColors.Suggestions", new object[1] { val });
		}

		private static void RPC_Suggestions(long sender, ZPackage pkg)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			if (!IsServerSender(sender))
			{
				return;
			}
			try
			{
				if (pkg.ReadInt() == 2)
				{
					float threshold = pkg.ReadSingle();
					int num = Mathf.Clamp(pkg.ReadInt(), 0, 5);
					Color[] array = (Color[])(object)new Color[num];
					for (int i = 0; i < num; i++)
					{
						array[i] = (Color)(((??)ColorUtil.FromHex(pkg.ReadString())) ?? Color.white);
					}
					ColorPanel.ReplaceSuggestions(threshold, array);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not read the server's color suggestions: " + ex.Message));
			}
		}

		private static void BroadcastColors(long peerId, PlayerColorSet colors)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(2);
			val.Write(peerId);
			WriteColors(val, colors);
			ZRoutedRpc.instance.InvokeRoutedRPC(0L, "Truncated.PlayerPinColors.ColorsBroadcast", new object[1] { val });
		}

		private static void RPC_Colors(long sender, ZPackage pkg)
		{
			if (((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()) || !IsServerSender(sender))
			{
				return;
			}
			try
			{
				if (pkg.ReadInt() == 2)
				{
					SetRemote(pkg.ReadLong(), ReadColors(pkg));
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not read the server's color update: " + ex.Message));
			}
		}

		private static void SetRemote(long peerId, PlayerColorSet colors)
		{
			if (peerId != 0L && peerId != LocalPeerId && (Remote.ContainsKey(peerId) || Remote.Count < 256 || PruneAbsentPlayers()) && (!Remote.TryGetValue(peerId, out var value) || !value.SameAs(colors)))
			{
				Remote[peerId] = colors;
				MinimapPatches.Refresh();
				PlayerPinColorsApi.RaiseColorsChanged(peerId);
			}
		}

		internal static bool IsServerSender(long sender)
		{
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return false;
			}
			if (ZNet.instance.IsServer())
			{
				return sender == LocalPeerId;
			}
			ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
			if (serverPeer != null)
			{
				return sender == serverPeer.m_uid;
			}
			return false;
		}

		private static bool TryReadColors(ZPackage pkg, out int requestId, out PlayerColorSet colors)
		{
			requestId = 0;
			colors = default(PlayerColorSet);
			try
			{
				if (pkg.ReadInt() != 2)
				{
					return false;
				}
				requestId = pkg.ReadInt();
				colors = ReadColors(pkg);
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Ignoring malformed color proposal: " + ex.Message));
				return false;
			}
		}

		private static PlayerColorSet ReadColors(ZPackage pkg)
		{
			return new PlayerColorSet
			{
				Primary = ColorUtil.FromHex(pkg.ReadString()),
				Secondary = ColorUtil.FromHex(pkg.ReadString()),
				KeepVanillaNameColor = pkg.ReadBool()
			};
		}

		private static void WriteColors(ZPackage pkg, PlayerColorSet colors)
		{
			pkg.Write(ColorUtil.ToHex(colors.Primary));
			pkg.Write(ColorUtil.ToHex(colors.Secondary));
			pkg.Write(colors.KeepVanillaNameColor);
		}

		private static float GetThreshold()
		{
			float value = ModConfig.MinimumPrimaryColorDifference.Value;
			if (float.IsNaN(value) || float.IsInfinity(value))
			{
				Plugin.Log.LogWarning((object)$"Invalid minimum color difference; using the default Delta E of {25f:0}.");
			}
			return UniqueColorReview.Clamp(value);
		}

		private static Color[] CreateSuggestions(List<Color?> taken, float threshold)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			List<Color> list = new List<Color>(5);
			for (int i = 0; i < 20000; i++)
			{
				if (list.Count >= 5)
				{
					break;
				}
				Color candidate = new Color(Random.value, Random.value, Random.value, 1f);
				if (taken.All((Color? other) => !Conflicts(candidate, other, threshold)) && list.All((Color existing) => !Conflicts(candidate, existing, threshold)))
				{
					list.Add(candidate);
				}
			}
			return list.ToArray();
		}

		private static bool PruneAbsentPlayers()
		{
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return false;
			}
			HashSet<long> present = new HashSet<long>(from p in ZNet.instance.GetPlayerList()
				select ((ZDOID)(ref p.m_characterID)).UserID);
			foreach (long item in Remote.Keys.Where((long id) => id != LocalPeerId && !present.Contains(id)).ToList())
			{
				Remote.Remove(item);
			}
			foreach (long item2 in ServerColors.Keys.Where((long id) => id != LocalPeerId && !present.Contains(id)).ToList())
			{
				ServerColors.Remove(item2);
			}
			foreach (long item3 in NextSuggestionByPeer.Keys.Where((long id) => id != LocalPeerId && !present.Contains(id)).ToList())
			{
				NextSuggestionByPeer.Remove(item3);
			}
			LoggedInPeers.RemoveWhere((long id) => id != LocalPeerId && !present.Contains(id));
			return Remote.Count < 256;
		}
	}
	internal struct PlayerColorSet
	{
		public Color? Primary;

		public Color? Secondary;

		public bool KeepVanillaNameColor;

		public static PlayerColorSet GameColors => new PlayerColorSet
		{
			KeepVanillaNameColor = true
		};

		public bool IsDefault
		{
			get
			{
				if (!Primary.HasValue)
				{
					return !Secondary.HasValue;
				}
				return false;
			}
		}

		public bool SameAs(PlayerColorSet other)
		{
			if (Nullable.Equals<Color>(Primary, other.Primary) && Nullable.Equals<Color>(Secondary, other.Secondary))
			{
				return KeepVanillaNameColor == other.KeepVanillaNameColor;
			}
			return false;
		}
	}
	internal static class ColorUtil
	{
		internal static readonly Color GameDefault = new Color(1f, 1f, 1f, 0f);

		internal static readonly Color GamePrimary = new Color(((RgbColor)(ref PerceptualColorDistance.GamePrimary)).R, ((RgbColor)(ref PerceptualColorDistance.GamePrimary)).G, ((RgbColor)(ref PerceptualColorDistance.GamePrimary)).B);

		internal static PlayerColorSet Own => OwnColors.Current;

		internal static Color? FromConfig(Color c)
		{
			//IL_0000: 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_001d: 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_002e: Unknown result type (might be due to invalid IL or missing references)
			if (!(c.a > 0f))
			{
				return null;
			}
			return new Color(c.r, c.g, c.b, 1f);
		}

		internal static Color ToFilePrecision(Color c)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return Color32.op_Implicit(Color32.op_Implicit(c));
		}

		internal static string ToHex(Color? c)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			if (!c.HasValue)
			{
				return "";
			}
			return "#" + ColorUtility.ToHtmlStringRGB(c.Value);
		}

		internal static Color? FromHex(string hex)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(hex) || hex.Length > 16)
			{
				return null;
			}
			hex = hex.Trim();
			if (!hex.StartsWith("#"))
			{
				hex = "#" + hex;
			}
			Color value = default(Color);
			if (hex.Length != 7 || !ColorUtility.TryParseHtmlString(hex, ref value))
			{
				return null;
			}
			value.a = 1f;
			return value;
		}

		internal static Color ContrastText(Color fill)
		{
			//IL_0005: 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_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			if (!(0.2126f * fill.r + 0.7152f * fill.g + 0.0722f * fill.b > 0.5f))
			{
				return Color.white;
			}
			return Color.black;
		}
	}
	internal sealed class ConfigWatcher : IDisposable
	{
		private const float ReloadDelay = 0.5f;

		private readonly ConfigFile _config;

		private readonly FileSystemWatcher _watcher;

		private volatile bool _changed;

		private float _reloadAt = -1f;

		internal ConfigWatcher(ConfigFile config)
		{
			_config = config;
			string configFilePath = config.ConfigFilePath;
			string path = Path.GetDirectoryName(configFilePath) ?? throw new InvalidOperationException("Config path '" + configFilePath + "' has no parent directory.");
			_watcher = new FileSystemWatcher(path, Path.GetFileName(configFilePath))
			{
				NotifyFilter = (NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite),
				IncludeSubdirectories = false
			};
			_watcher.Changed += OnFileEvent;
			_watcher.Created += OnFileEvent;
			_watcher.Renamed += OnFileEvent;
			_watcher.EnableRaisingEvents = true;
		}

		private void OnFileEvent(object sender, FileSystemEventArgs e)
		{
			_changed = true;
		}

		internal void Tick()
		{
			if (_changed)
			{
				_changed = false;
				_reloadAt = Time.unscaledTime + 0.5f;
			}
			if (_reloadAt < 0f || Time.unscaledTime < _reloadAt)
			{
				return;
			}
			_reloadAt = -1f;
			if (!File.Exists(_config.ConfigFilePath))
			{
				return;
			}
			int changedCount = 0;
			bool saveOnConfigSet = _config.SaveOnConfigSet;
			_config.SaveOnConfigSet = false;
			_config.SettingChanged += Count;
			try
			{
				_config.Reload();
			}
			catch (IOException ex)
			{
				Plugin.Log.LogError((object)("Could not reload " + Path.GetFileName(_config.ConfigFilePath) + ": " + ex.Message));
			}
			catch (UnauthorizedAccessException ex2)
			{
				Plugin.Log.LogError((object)("Could not reload " + Path.GetFileName(_config.ConfigFilePath) + ": " + ex2.Message));
			}
			catch (FormatException ex3)
			{
				Plugin.Log.LogError((object)("Could not reload " + Path.GetFileName(_config.ConfigFilePath) + ": " + ex3.Message + ". Check the file for typos."));
			}
			finally
			{
				_config.SettingChanged -= Count;
				_config.SaveOnConfigSet = saveOnConfigSet;
			}
			if (changedCount > 0)
			{
				Plugin.Log.LogInfo((object)$"Reloaded {changedCount} setting(s) from {Path.GetFileName(_config.ConfigFilePath)}.");
			}
			void Count(object s, SettingChangedEventArgs e)
			{
				changedCount++;
			}
		}

		public void Dispose()
		{
			_watcher.EnableRaisingEvents = false;
			_watcher.Dispose();
		}
	}
	internal static class ModConfig
	{
		internal enum ButtonAnchorArea
		{
			Map,
			Standard16x9Area,
			Screen
		}

		internal enum ButtonAnchorPoint
		{
			TopLeft,
			TopCenter,
			TopRight,
			MiddleLeft,
			Center,
			MiddleRight,
			BottomLeft,
			BottomCenter,
			BottomRight
		}

		internal enum UniqueColorScope
		{
			AllSavedCharacters,
			OnlineCharactersOnly
		}

		private const string InterfaceSection = "1 - Interface";

		private const string AdministrationSection = "2 - Administration";

		internal static ConfigEntry<ButtonAnchorArea> ButtonArea;

		internal static ConfigEntry<ButtonAnchorPoint> ButtonPoint;

		internal static ConfigEntry<Vector2> ButtonOffset;

		internal static ConfigEntry<bool> ColorizeMapIcon;

		internal static ConfigEntry<bool> EnforceUniquePrimaryColors;

		internal static ConfigEntry<float> MinimumPrimaryColorDifference;

		internal static ConfigEntry<UniqueColorScope> UniqueColorCheckScope;

		internal static void Bind(ConfigFile config)
		{
			bool saveOnConfigSet = config.SaveOnConfigSet;
			config.SaveOnConfigSet = false;
			try
			{
				BindAll(config);
			}
			finally
			{
				config.Save();
				config.SaveOnConfigSet = saveOnConfigSet;
			}
		}

		private static void BindAll(ConfigFile config)
		{
			//IL_0049: 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_00ac: Expected O, but got Unknown
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Expected O, but got Unknown
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Expected O, but got Unknown
			int num = 100;
			ButtonArea = BindInterface(config, "Map Button Anchor Area", ButtonAnchorArea.Map, "The area the map button is placed on. Map: the map image. Standard16x9Area: a centered, full-height 16:9 area, so the button sits in the same place on standard, wide and ultrawide screens (on 16:9 and narrower screens this is the whole screen). Screen: the whole screen.", num--);
			ButtonPoint = BindInterface(config, "Map Button Anchor Point", ButtonAnchorPoint.BottomRight, "The point on Map Button Anchor Area that Map Button Offset is measured from: a corner, the middle of an edge, or the center. The button's matching corner sits there, so an offset of 0 keeps it inside the area.", num--);
			ButtonOffset = BindInterface<Vector2>(config, "Map Button Offset", new Vector2(-100f, 125f), "Distance of the map button from the anchor point (x right, y up), in UI units. UI units scale with the game's UI, so the same value looks the same at any resolution.", num--);
			ColorizeMapIcon = BindInterface(config, "Colorize Your Map Icon", defaultValue: true, "When on (the default), your own arrow on the minimap and large map takes your primary color, or the game's red pin color when you use the game's color. When off, your arrow always keeps the game's yellow. Only changes what you see; your pin's colors for other players are unchanged.", num--);
			EnforceUniquePrimaryColors = config.Bind<bool>("2 - Administration", "Enforce Unique Primary Colors", false, new ConfigDescription("Server-side rule: modded players must choose primary colors at least the configured CIE76 ΔE apart. Requires PlayerPinColors on the server and on every client. Players who join without it are not checked. The game's default color is compared like any other color, and a player's own characters are never compared with each other. Only admins can change this in game; it is synced from the server. When it is on (at server start, or when turned on), every character's color is checked: whoever registered a color first keeps it, and the others are asked to choose a new one, at once if online or at their next login. Turning it off clears those requests.", (AcceptableValueBase)null, new object[1] { AdminOnly(num--) }));
			MinimumPrimaryColorDifference = config.Bind<float>("2 - Administration", "Minimum Primary Color Difference (Delta E)", 25f, new ConfigDescription("Minimum CIE76 ΔE between modded players' primary colors when server enforcement is enabled. From 5 (colors may be quite similar) to 50 (colors must be very different); the default is 25. Only admins can change this in game; it is synced from the server. While enforcement is on, raising it checks every color again: whoever registered a color first keeps it, and the others are asked to choose a new one (at once if online, otherwise at their next login). Lowering it doesn't ask anyone to choose again, because colors already far enough apart still are.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 50f), new object[1] { AdminOnly(num--) }));
			UniqueColorCheckScope = config.Bind<UniqueColorScope>("2 - Administration", "Check Unique Colors Against", UniqueColorScope.AllSavedCharacters, new ConfigDescription("Which characters a new primary color must differ from when Enforce Unique Primary Colors is on. AllSavedCharacters: every character in this world whose colors the server has saved, online or not, except your own other characters, so a color stays reserved for whoever registered it first, even while they're offline. OnlineCharactersOnly: only players who are online right now; of those, whoever registered a color first keeps it. The server saves colors in BepInEx\\config\\PlayerPinColors\\worlds\\<world id>.json; admins can free a character's color with the ppc_forget command. Only admins can change this in game; it is synced from the server. While enforcement is on, changing it checks every color again: whoever registered a color first keeps it, and the others are asked to choose a new one (at once if online, otherwise at their next login).", (AcceptableValueBase)null, new object[1] { AdminOnly(num--) }));
		}

		private static ConfigEntry<T> BindInterface<T>(ConfigFile config, string key, T defaultValue, string description, int order)
		{
			//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_0025: Expected O, but got Unknown
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			return config.Bind<T>("1 - Interface", key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = order
			} }));
		}

		private static ConfigurationManagerAttributes AdminOnly(int order)
		{
			//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_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			return new ConfigurationManagerAttributes
			{
				IsAdminOnly = true,
				Order = order
			};
		}
	}
	internal static class OwnColors
	{
		private const string Section = "My Colors";

		private const string FallbackPlatformId = "local";

		private const string ConnectedNote = "Change your colors while connected to the server: the server saves them for you, and if you log in on the game's colors (for example after resetting them while offline, or reinstalling), it gives your saved colors back.";

		private static ConfigFile? _file;

		private static ConfigWatcher? _watcher;

		private static string? _key;

		private static ConfigEntry<Color> _primary;

		private static ConfigEntry<Color> _secondary;

		private static ConfigEntry<bool> _keepVanillaName;

		internal static string Folder => Path.Combine(Paths.ConfigPath, "PlayerPinColors", "characters");

		internal static string? FilePath
		{
			get
			{
				ConfigFile? file = _file;
				if (file == null)
				{
					return null;
				}
				return file.ConfigFilePath;
			}
		}

		internal static PlayerColorSet Current
		{
			get
			{
				//IL_0016: 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)
				if (_file != null)
				{
					return new PlayerColorSet
					{
						Primary = ColorUtil.FromConfig(_primary.Value),
						Secondary = ColorUtil.FromConfig(_secondary.Value),
						KeepVanillaNameColor = _keepVanillaName.Value
					};
				}
				return PlayerColorSet.GameColors;
			}
		}

		internal static Color Get(bool primary)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			if (_file != null)
			{
				return (primary ? _primary : _secondary).Value;
			}
			return ColorUtil.GameDefault;
		}

		internal static void Set(bool primary, Color value)
		{
			//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)
			if (_file != null)
			{
				(primary ? _primary : _secondary).Value = ColorUtil.ToFilePrecision(value);
			}
		}

		internal static void SetKeepVanillaName(bool on)
		{
			if (_file != null)
			{
				_keepVanillaName.Value = on;
			}
		}

		internal static void SetAll(PlayerColorSet colors)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: 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_006e: Unknown result type (might be due to invalid IL or missing references)
			if (_file == null)
			{
				return;
			}
			bool saveOnConfigSet = _file.SaveOnConfigSet;
			_file.SaveOnConfigSet = false;
			try
			{
				_primary.Value = ColorUtil.ToFilePrecision((Color)(((??)colors.Primary) ?? ColorUtil.GameDefault));
				_secondary.Value = ColorUtil.ToFilePrecision((Color)(((??)colors.Secondary) ?? ColorUtil.GameDefault));
				_keepVanillaName.Value = colors.KeepVanillaNameColor;
			}
			finally
			{
				_file.SaveOnConfigSet = saveOnConfigSet;
				_file.Save();
			}
		}

		internal static void LoadForLocalCharacter()
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Expected O, but got Unknown
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			PlayerProfile val = (((Object)(object)Game.instance != (Object)null) ? Game.instance.GetPlayerProfile() : null);
			string text = ((val != null) ? val.GetName() : null);
			if (!CharacterKey.IsValidPart(text))
			{
				Plugin.Log.LogWarning((object)"Could not read your character's name, so your colors can't be loaded.");
				return;
			}
			string text2 = CharacterIdentity.LocalPlatformId();
			if (!CharacterKey.IsValidPart(text2))
			{
				text2 = "local";
			}
			string text3 = CharacterKey.Create(text2, text);
			if (text3 == _key)
			{
				return;
			}
			Unload();
			try
			{
				Directory.CreateDirectory(Folder);
				string text4 = Path.Combine(Folder, FileNameFor(text3));
				bool flag = File.Exists(text4);
				ConfigFile val2 = new ConfigFile(text4, false, new BepInPlugin("Truncated.PlayerPinColors", "PlayerPinColors", "1.0.0"))
				{
					SaveOnConfigSet = false
				};
				Bind(val2, text.Trim());
				val2.Save();
				val2.SaveOnConfigSet = true;
				_file = val2;
				_key = text3;
				_file.SettingChanged += OnSettingChanged;
				_watcher = new ConfigWatcher(_file);
				Plugin.Log.LogInfo((object)(flag ? ("Loaded " + LogCleaner.MarkName(text) + "'s colors from " + LogCleaner.MarkNameIn(Path.GetFileName(text4), text) + ".") : ("Created " + LogCleaner.MarkNameIn(Path.GetFileName(text4), text) + " for " + LogCleaner.MarkName(text) + "'s colors.")));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Could not load your character's colors from " + Folder + ": " + ex.Message));
				Unload();
			}
		}

		private static void Bind(ConfigFile file, string characterName)
		{
			//IL_000b: 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)
			_primary = file.Bind<Color>("My Colors", "Player Primary Color", ColorUtil.GameDefault, characterName + "'s colors. Each character has its own file in this folder, so sharing a mod profile (which replaces the main config) doesn't change them. Color of the figure in your map pin, your name under it, and your own map arrow. Other players with this mod see it. An alpha of 00 (the default) keeps the game's color. If you change it in this file while in a world and the server rejects it, it goes back to your last accepted color. Change your colors while connected to the server: the server saves them for you, and if you log in on the game's colors (for example after resetting them while offline, or reinstalling), it gives your saved colors back.");
			_secondary = file.Bind<Color>("My Colors", "Player Secondary Color", ColorUtil.GameDefault, "Color of the sword and shield in your map pin. Other players with this mod see it. An alpha of 00 (the default) keeps the game's color. Change your colors while connected to the server: the server saves them for you, and if you log in on the game's colors (for example after resetting them while offline, or reinstalling), it gives your saved colors back.");
			_keepVanillaName = file.Bind<bool>("My Colors", "Keep Vanilla Name Color", true, "When on (the default), your name under your map pin keeps the game's color instead of Player Primary Color. Other players with this mod see it this way too. Change your colors while connected to the server: the server saves them for you, and if you log in on the game's colors (for example after resetting them while offline, or reinstalling), it gives your saved colors back.");
		}

		internal static void Unload()
		{
			_watcher?.Dispose();
			_watcher = null;
			if (_file != null)
			{
				_file.SettingChanged -= OnSettingChanged;
			}
			_file = null;
			_key = null;
			_primary = null;
			_secondary = null;
			_keepVanillaName = null;
		}

		internal static void Tick()
		{
			_watcher?.Tick();
		}

		private static void OnSettingChanged(object sender, SettingChangedEventArgs e)
		{
			Plugin.OnOwnColorsChanged();
		}

		internal static string FileNameFor(string key)
		{
			char[] invalid = Path.GetInvalidFileNameChars();
			return new string(key.Select((char c) => (!invalid.Contains(c)) ? c : '_').ToArray()) + ".cfg";
		}
	}
	internal static class PinRecolor
	{
		private struct Key : IEquatable<Key>
		{
			public int Source;

			public int Primary;

			public int Secondary;

			public bool Equals(Key other)
			{
				if (Source == other.Source && Primary == other.Primary)
				{
					return Secondary == other.Secondary;
				}
				return false;
			}

			public override bool Equals(object obj)
			{
				if (obj is Key other)
				{
					return Equals(other);
				}
				return false;
			}

			public override int GetHashCode()
			{
				return (((Source * 397) ^ Primary) * 397) ^ Secondary;
			}
		}

		private sealed class SourcePixels
		{
			public Color[] Pixels;

			public int Width;

			public int Height;

			public float MaxRed;
		}

		private const int MaxCached = 64;

		private static readonly Dictionary<Key, Sprite?> Cache = new Dictionary<Key, Sprite>();

		private static readonly Dictionary<int, SourcePixels> Sources = new Dictionary<int, SourcePixels>();

		internal static readonly Color DefaultSecondary = Color.white;

		internal static bool IsOverCapacity => Cache.Count > 64;

		internal static Sprite? GetCached(Sprite source, Color? primary, Color? secondary)
		{
			if ((Object)(object)source == (Object)null)
			{
				return null;
			}
			if (!primary.HasValue && !secondary.HasValue)
			{
				return source;
			}
			Key key = new Key
			{
				Source = ((Object)source).GetInstanceID(),
				Primary = Pack(primary),
				Secondary = Pack(secondary)
			};
			if (Cache.TryGetValue(key, out Sprite value))
			{
				return value;
			}
			try
			{
				SourcePixels source2 = GetSource(source);
				Texture2D texture = NewTexture(source2, source);
				Fill(source2, texture, primary, secondary);
				value = NewSprite(texture, source);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not recolor the player pin: " + ex.Message));
				value = null;
			}
			Cache[key] = value;
			return value;
		}

		internal static Sprite CreateLive(Sprite source, out Texture2D texture)
		{
			SourcePixels source2 = GetSource(source);
			texture = NewTexture(source2, source);
			Fill(source2, texture, null, null);
			return NewSprite(texture, source);
		}

		internal static void RenderLive(Sprite source, Texture2D texture, Color? primary, Color? secondary)
		{
			Fill(GetSource(source), texture, primary, secondary);
		}

		internal static Color DefaultPrimary(Sprite source)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			return new Color(GetSource(source).MaxRed, 0f, 0f, 1f);
		}

		internal static void Clear()
		{
			foreach (Sprite value in Cache.Values)
			{
				if (!((Object)(object)value == (Object)null))
				{
					Object.Destroy((Object)(object)value.texture);
					Object.Destroy((Object)(object)value);
				}
			}
			Cache.Clear();
			Sources.Clear();
		}

		private static int Pack(Color? color)
		{
			//IL_000d: 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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if (!color.HasValue)
			{
				return -1;
			}
			Color32 val = Color32.op_Implicit(color.Value);
			return (val.r << 16) | (val.g << 8) | val.b;
		}

		private static Texture2D NewTexture(SourcePixels src, Sprite source)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: 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_0024: 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_0037: Expected O, but got Unknown
			return new Texture2D(src.Width, src.Height, (TextureFormat)4, false)
			{
				filterMode = ((Texture)source.texture).filterMode,
				wrapMode = (TextureWrapMode)1,
				name = "Truncated.PlayerPinColors.Pin"
			};
		}

		private static Sprite NewSprite(Texture2D texture, Sprite source)
		{
			//IL_0019: 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)
			return Sprite.Create(texture, new Rect(0f, 0f, (float)((Texture)texture).width, (float)((Texture)texture).height), new Vector2(0.5f, 0.5f), source.pixelsPerUnit);
		}

		private static void Fill(SourcePixels src, Texture2D texture, Color? primary, Color? secondary)
		{
			//IL_0014: 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_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: 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_004b: 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_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: 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_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			Color val = (Color)(((??)secondary) ?? Color.white);
			Color[] array = (Color[])(object)new Color[src.Pixels.Length];
			for (int i = 0; i < array.Length; i++)
			{
				Color val2 = src.Pixels[i];
				float num = Mathf.Min(val2.r, Mathf.Min(val2.g, val2.b));
				float num2 = Mathf.Max(0f, val2.r - Mathf.Max(val2.g, val2.b));
				Color val3 = (Color)(primary.HasValue ? (primary.Value * (num2 / src.MaxRed)) : new Color(num2, 0f, 0f));
				array[i] = new Color(Mathf.Clamp01(num * val.r + val3.r), Mathf.Clamp01(num * val.g + val3.g), Mathf.Clamp01(num * val.b + val3.b), val2.a);
			}
			texture.SetPixels(array);
			texture.Apply();
		}

		private static SourcePixels GetSource(Sprite source)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: 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_0138: Unknown result type (might be due to invalid IL or missing references)
			int instanceID = ((Object)source).GetInstanceID();
			if (Sources.TryGetValue(instanceID, out SourcePixels value))
			{
				return value;
			}
			Texture2D texture = source.texture;
			RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2);
			RenderTexture active = RenderTexture.active;
			Texture2D val = new Texture2D(((Texture)texture).width, ((Texture)texture).height, (TextureFormat)4, false);
			SourcePixels sourcePixels = new SourcePixels();
			try
			{
				Graphics.Blit((Texture)(object)texture, temporary);
				RenderTexture.active = temporary;
				val.ReadPixels(new Rect(0f, 0f, (float)((Texture)texture).width, (float)((Texture)texture).height), 0, 0);
				val.Apply();
				Rect textureRect = source.textureRect;
				sourcePixels.Width = (int)((Rect)(ref textureRect)).width;
				sourcePixels.Height = (int)((Rect)(ref textureRect)).height;
				sourcePixels.Pixels = val.GetPixels((int)((Rect)(ref textureRect)).x, (int)((Rect)(ref textureRect)).y, sourcePixels.Width, sourcePixels.Height);
			}
			finally
			{
				RenderTexture.active = active;
				RenderTexture.ReleaseTemporary(temporary);
				Object.Destroy((Object)(object)val);
			}
			Color[] pixels = sourcePixels.Pixels;
			foreach (Color val2 in pixels)
			{
				if (val2.a > 0f)
				{
					sourcePixels.MaxRed = Mathf.Max(sourcePixels.MaxRed, val2.r - Mathf.Max(val2.g, val2.b));
				}
			}
			sourcePixels.MaxRed = Mathf.Max(sourcePixels.MaxRed, 0.01f);
			Sources[instanceID] = sourcePixels;
			return sourcePixels;
		}
	}
	public static class PlayerPinColorsApi
	{
		public const string PrimaryColorKey = "Truncated.PlayerPinColors.PrimaryColor";

		public const string SecondaryColorKey = "Truncated.PlayerPinColors.SecondaryColor";

		public const string KeepVanillaNameColorKey = "Truncated.PlayerPinColors.KeepVanillaNameColor";

		public static Color? LocalPrimaryColor => ColorUtil.Own.Primary;

		public static Color? LocalSecondaryColor => ColorUtil.Own.Secondary;

		public static event Action<long>? ColorsChanged;

		public static bool TryGetPrimaryColor(Player player, out Color color)
		{
			return Unwrap(Get(player).Primary, out color);
		}

		public static bool TryGetSecondaryColor(Player player, out Color color)
		{
			return Unwrap(Get(player).Secondary, out color);
		}

		public static bool TryGetColors(long peerId, out Color? primary, out Color? secondary)
		{
			PlayerColorSet colors;
			bool result = ColorSync.TryGet(peerId, out colors);
			primary = colors.Primary;
			secondary = colors.Secondary;
			return result;
		}

		internal static void RaiseColorsChanged(long peerId)
		{
			Action<long> colorsChanged = PlayerPinColorsApi.ColorsChanged;
			if (colorsChanged == null)
			{
				return;
			}
			Delegate[] invocationList = colorsChanged.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				Action<long> action = (Action<long>)invocationList[i];
				try
				{
					action(peerId);
				}
				catch (Exception arg)
				{
					Plugin.Log.LogWarning((object)$"A ColorsChanged handler threw: {arg}");
				}
			}
		}

		private static PlayerColorSet Get(Player player)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player == (Object)null)
			{
				return default(PlayerColorSet);
			}
			if ((Object)(object)player == (Object)(object)Player.m_localPlayer)
			{
				return ColorUtil.Own;
			}
			ZNetView nView = ColorSync.GetNView(player);
			if ((Object)(object)nView != (Object)null && nView.IsValid() && ColorSync.TryGet(nView.GetZDO().m_uid, out var colors))
			{
				return colors;
			}
			return default(PlayerColorSet);
		}

		private static bool Unwrap(Color? value, out Color color)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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)
			color = (Color)(((??)value) ?? Color.white);
			return value.HasValue;
		}
	}
	[BepInPlugin("Truncated.PlayerPinColors", "PlayerPinColors", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	[SynchronizationMode(/*Could not decode attribute arguments.*/)]
	internal sealed class Plugin : BaseUnityPlugin
	{
		private readonly Harmony _harmony = new Harmony("Truncated.PlayerPinColors");

		private readonly Action<Terminal> _openColorsHandler = OpenColorPanel;

		private readonly Action<Terminal, string[]> _forgetColorsHandler = ForgetColorsCommand.Execute;

		private readonly Func<List<string>> _forgetOptionsHandler = ForgetColorsCommand.GetNameOptions;

		private readonly Action<Terminal> _adminHandler = AdminCommand.Execute;

		private readonly Action<Terminal, bool> _debugCheckHandler = DebugCheckCommand.Execute;

		private ConfigWatcher? _configWatcher;

		internal static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			ModConfig.Bind(((BaseUnityPlugin)this).Config);
			_configWatcher = new ConfigWatcher(((BaseUnityPlugin)this).Config);
			ModConfig.EnforceUniquePrimaryColors.SettingChanged += delegate
			{
				ColorSync.OnAdminSettingChanged();
			};
			ModConfig.MinimumPrimaryColorDifference.SettingChanged += delegate
			{
				ColorSync.OnMinimumDifferenceChanged();
			};
			ModConfig.UniqueColorCheckScope.SettingChanged += delegate
			{
				ColorSync.OnAdminSettingChanged();
			};
			ModConfig.ButtonArea.SettingChanged += delegate
			{
				ColorPanel.Reposition();
			};
			ModConfig.ButtonPoint.SettingChanged += delegate
			{
				ColorPanel.Reposition();
			};
			ModConfig.ButtonOffset.SettingChanged += delegate
			{
				ColorPanel.Reposition();
			};
			ModConfig.ColorizeMapIcon.SettingChanged += delegate
			{
				MinimapPatches.Refresh();
			};
			_harmony.PatchAll(typeof(Plugin).Assembly);
			MyColorsCommand.Register(_openColorsHandler);
			ForgetColorsCommand.Register(_forgetColorsHandler, _forgetOptionsHandler);
			AdminCommand.Register(_adminHandler);
			DebugCheckCommand.Register(_debugCheckHandler);
			Log.LogInfo((object)"PlayerPinColors 1.0.0 loaded");
		}

		private void Update()
		{
			_configWatcher?.Tick();
			OwnColors.Tick();
			ColorSync.Tick();
			ColorPanel.Tick();
			AdminPanel.Tick();
			DebugCheckLog.Tick();
			DebugCheckRelay.Tick();
		}

		private void OnDestroy()
		{
			_harmony.UnpatchSelf();
			_configWatcher?.Dispose();
			_configWatcher = null;
			OwnColors.Unload();
			MyColorsCommand.Unregister(_openColorsHandler);
			ForgetColorsCommand.Unregister(_forgetColorsHandler, _forgetOptionsHandler);
			AdminCommand.Unregister(_adminHandler);
			DebugCheckCommand.Unregister(_debugCheckHandler);
			ColorSync.OnWorldClosed();
			ColorPanel.Destroy();
			AdminPanel.Destroy();
			DebugCheckLog.Finish("The mod was unloaded.", background: false);
			PinRecolor.Clear();
		}

		private static void OpenColorPanel(Terminal context)
		{
			if (!ColorPanel.Open() && (Object)(object)context != (Object)null)
			{
				context.AddString("Player Pin Colors is unavailable until you enter a world.");
			}
		}

		internal static void OnOwnColorsChanged()
		{
			ColorSync.OnOwnColorsChanged();
			MinimapPatches.Refresh();
			ColorPanel.Refresh();
		}
	}
	internal static class PluginInfo
	{
		public const string Guid = "Truncated.PlayerPinColors";

		public const string Name = "PlayerPinColors";

		public const string Version = "1.0.0";

		public const string FullVersion = "1.0.0";
	}
}
namespace PlayerPinColors.UI
{
	internal static class AdminPanel
	{
		private readonly struct Column
		{
			public float X { get; }

			public float Width { get; }

			public float Center => X + Width / 2f;

			public Column(float x, float width)
			{
				X = x;
				Width = width;
			}
		}

		private sealed class Row
		{
			public AdminEntry Entry;

			public Toggle Toggle;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static UnityAction <0>__OnRefresh;

			public static UnityAction <1>__OnDelete;

			public static UnityAction <2>__Close;
		}

		private const float PanelWidth = 860f;

		private const float PanelHeight = 572f;

		private const float SidePadding = 24f;

		private const float HeaderCenterY = 104f;

		private const float HeaderHeight = 30f;

		private const float TableTop = 122f;

		private const float TableBottom = 124f;

		private const float StatusCenterY = 96f;

		private const float ButtonHeight = 46f;

		private const float BottomMargin = 22f;

		private const float RowHeight = 34f;

		private const float CheckboxSize = 24f;

		private const float ScrollbarWidth = 12f;

		private const float ScrollbarGap = 4f;

		private const float ScrollSensitivity = 35f;

		private const float ConfirmSeconds = 4f;

		private const float RowWidth = 796f;

		private static readonly Column CheckColumn = new Column(0f, 36f);

		private static readonly Column NameColumn = new Column(40f, 160f);

		private static readonly Column PlatformColumn = new Column(204f, 170f);

		private static readonly Column ColorColumn = new Column(378f, 70f);

		private static readonly Column FirstSeenColumn = new Column(452f, 130f);

		private static readonly Column LastSeenColumn = new Column(586f, 130f);

		private static readonly Column OnlineColumn = new Column(720f, 76f);

		private static readonly Color TableBackground = new Color(0f, 0f, 0f, 0.35f);

		private static readonly Color StripeColor = new Color(1f, 1f, 1f, 0.05f);

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

		private static readonly Color UnknownTextColor = new Color(0.6f, 0.6f, 0.6f, 1f);

		private static readonly Color OnlineTextColor = new Color(0.55f, 0.9f, 0.45f, 1f);

		private static readonly Color ConfirmTextColor = new Color(1f, 0.45f, 0.35f, 1f);

		private static RectTransform _panel = null;

		private static RectTransform _content = null;

		private static ScrollRect _scroll = null;

		private static Text _summary = null;

		private static Text _status = null;

		private static Toggle _selectAll = null;

		private static Button _deleteButton = null;

		private static Text _deleteLabel = null;

		private static Color _deleteLabelColor;

		private static readonly List<Row> Rows = new List<Row>();

		private static readonly HashSet<string> Selected = new HashSet<string>(StringComparer.Ordinal);

		private static bool _settingToggles;

		private static bool _blockingInput;

		private static int _unblockAfterFrame = -1;

		private static float _confirmUntil = float.NegativeInfinity;

		internal static bool IsOpen
		{
			get
			{
				if ((Object)(object)_panel != (Object)null)
				{
					return ((Component)_panel).gameObject.activeSelf;
				}
				return false;
			}
		}

		internal static string DescribeLayout()
		{
			if (!((Object)(object)_panel == (Object)null))
			{
				if (!IsOpen)
				{
					return "(closed)";
				}
				return ScreenClampedDrag.Describe(_panel);
			}
			return "(not built)";
		}

		internal static void Show(IReadOnlyList<AdminEntry> entries, int total, int removed)
		{
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			if (EnsureBuilt())
			{
				HashSet<string> remaining = new HashSet<string>(entries.Select((AdminEntry e) => e.Key), StringComparer.Ordinal);
				bool flag = removed > 0 && Rows.Any((Row r) => Selected.Contains(r.Entry.Key) && r.Entry.Online && !remaining.Contains(r.Entry.Key));
				Selected.IntersectWith(remaining);
				BuildRows(entries);
				_summary.text = ((total == entries.Count) ? $"{total} saved character(s) in this world. Select characters to delete their saved colors." : $"Showing {entries.Count} of {total} saved characters. Delete some to see the rest.");
				if (removed > 0)
				{
					_status.text = $"Removed the saved colors of {removed} character(s)." + (flag ? " Online characters' current colors still count until they log out." : string.Empty);
				}
				else
				{
					_status.text = ((entries.Count == 0) ? "No characters have saved colors yet." : string.Empty);
				}
				ResetConfirm();
				UpdateSelectionControls();
				if (!IsOpen)
				{
					((Component)_panel).gameObject.SetActive(true);
					_panel.anchoredPosition = Vector2.zero;
					_scroll.verticalNormalizedPosition = 1f;
				}
				((Transform)_panel).SetAsLastSibling();
				_unblockAfterFrame = -1;
				if (!_blockingInput)
				{
					GUIManager.BlockInput(true);
					_blockingInput = true;
				}
			}
		}

		internal static void Close()
		{
			if ((Object)(object)_panel != (Object)null)
			{
				((Component)_panel).gameObject.SetActive(false);
			}
			_unblockAfterFrame = -1;
			ReleaseInput();
			ResetConfirm();
		}

		private static void ReleaseInput()
		{
			if (_blockingInput)
			{
				GUIManager.BlockInput(false);
				_blockingInput = false;
			}
		}

		internal static void Destroy()
		{
			Close();
			if ((Object)(object)_panel != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)_panel).gameObject);
			}
			_panel = null;
			_content = null;
			_scroll = null;
			Rows.Clear();
			Selected.Clear();
		}

		internal static void Tick()
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			if (_unblockAfterFrame >= 0 && Time.frameCount > _unblockAfterFrame)
			{
				_unblockAfterFrame = -1;
				ReleaseInput();
			}
			if (IsOpen)
			{
				VanillaUiScale.Apply(_panel);
				ScreenClampedDrag.KeepOnScreenLogged(_panel, null, "admin window");
				if (ZInput.GetKeyDown((KeyCode)27, true))
				{
					((Component)_panel).gameObject.SetActive(false);
					ResetConfirm();
					_unblockAfterFrame = Time.frameCount;
				}
				else if (_confirmUntil > 0f && Time.unscaledTime > _confirmUntil)
				{
					ResetConfirm();
					UpdateSelectionControls();
				}
			}
		}

		private static bool EnsureBuilt()
		{
			//IL_0051: 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_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Expected O, but got Unknown
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: 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)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: 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_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Expected O, but got Unknown
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: 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_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Expected O, but got Unknown
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_029d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a3: Expected O, but got Unknown
			if ((Object)(object)_panel != (Object)null)
			{
				return true;
			}
			if ((Object)(object)GUIManager.CustomGUIFront == (Object)null)
			{
				return false;
			}
			GUIManager instance = GUIManager.Instance;
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(0.5f, 0.5f);
			Vector2 anchor = default(Vector2);
			((Vector2)(ref anchor))..ctor(0.5f, 1f);
			GameObject obj = instance.CreateWoodpanel(GUIManager.CustomGUIFront.transform, val, val, Vector2.zero, 860f, 572f, false);
			((Object)obj).name = "Truncated.PlayerPinColors.AdminPanel";
			_panel = (RectTransform)obj.transform;
			ScreenClampedDrag.Attach(obj, _panel, "admin window");
			VanillaUiScale.Apply(_panel);
			AddText("Saved Pin Colors", (Transform)(object)_panel, anchor, new Vector2(0f, -34f), instance.NorseBold, 32, instance.ValheimOrange, 600f, 44f, (TextAnchor)4);
			_summary = AddText(string.Empty, (Transform)(object)_panel, anchor, new Vector2(0f, -70f), instance.AveriaSerifBold, 15, instance.ValheimBeige, 812f, 24f, (TextAnchor)4);
			BuildHeader(instance);
			BuildTable(instance);
			_status = AddText(string.Empty, (Transform)(object)_panel, new Vector2(0.5f, 0f), new Vector2(0f, 96f), instance.AveriaSerifBold, 15, instance.ValheimBeige, 812f, 40f, (TextAnchor)4);
			_status.horizontalOverflow = (HorizontalWrapMode)0;
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(0.5f, 0f);
			float num = 45f;
			ButtonClickedEvent onClick = instance.CreateButton("Refresh", (Transform)(object)_panel, val2, val2, new Vector2(-260f, num), 150f, 46f).GetComponent<Button>().onClick;
			object obj2 = <>O.<0>__OnRefresh;
			if (obj2 == null)
			{
				UnityAction val3 = OnRefresh;
				<>O.<0>__OnRefresh = val3;
				obj2 = (object)val3;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj2);
			GameObject obj3 = instance.CreateButton(string.Empty, (Transform)(object)_panel, val2, val2, new Vector2(0f, num), 240f, 46f);
			_deleteButton = obj3.GetComponent<Button>();
			_deleteLabel = obj3.GetComponentInChildren<Text>();
			_deleteLabelColor = ((Graphic)_deleteLabel).color;
			ButtonClickedEvent onClick2 = _deleteButton.onClick;
			object obj4 = <>O.<1>__OnDelete;
			if (obj4 == null)
			{
				UnityAction val4 = OnDelete;
				<>O.<1>__OnDelete = val4;
				obj4 = (object)val4;
			}
			((UnityEvent)onClick2).AddListener((UnityAction)obj4);
			ButtonClickedEvent onClick3 = instance.CreateButton("Close", (Transform)(object)_panel, val2, val2, new Vector2(260f, num), 150f, 46f).GetComponent<Button>().onClick;
			object obj5 = <>O.<2>__Close;
			if (obj5 == null)
			{
				UnityAction val5 = Close;
				<>O.<2>__Close = val5;
				obj5 = (object)val5;
			}
			((UnityEvent)onClick3).AddListener((UnityAction)obj5);
			obj.SetActive(false);
			return true;
		}

		private static void BuildHeader(GUIManager gui)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: 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)
			RectTransform val = CreateRect("Header", (Transform)(object)_panel);
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(0f, 1f);
			val.anchorMax = val2;
			val.anchorMin = val2;
			val.pivot = new Vector2(0f, 0.5f);
			val.sizeDelta = new Vector2(796f, 30f);
			val.anchoredPosition = new Vector2(24f, -104f);
			_selectAll = AddCheckbox(gui, val);
			((UnityEvent<bool>)(object)_selectAll.onValueChanged).AddListener((UnityAction<bool>)delegate(bool on)
			{
				if (!_settingToggles)
				{
					SetAllSelected(on);
				}
			});
			AddHeading(gui, val, "Character", NameColumn);
			AddHeading(gui, val, "Platform ID", PlatformColumn);
			AddHeading(gui, val, "Colors", ColorColumn);
			AddHeading(gui, val, "First seen", FirstSeenColumn);
			AddHeading(gui, val, "Last login", LastSeenColumn);
			AddHeading(gui, val, "Status", OnlineColumn);
		}

		private static void AddHeading(GUIManager gui, RectTransform header, string text, Column column)
		{
			//IL_000c: 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_002b: Unknown result type (might be due to invalid IL or missing references)
			AddText(text, (Transform)(object)header, new Vector2(0f, 0.5f), new Vector2(column.Center, 0f), gui.AveriaSerifBold, 16, gui.ValheimOrange, column.Width, 30f, (TextAnchor)3);
		}

		private static void BuildTable(GUIManager gui)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: 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_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Expected O, but got Unknown
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Expected O, but got Unknown
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Expected O, but got Unknown
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Table", new Type[4]
			{
				typeof(RectTransform),
				typeof(Image),
				typeof(RectMask2D),
				typeof(ScrollRect)
			});
			RectTransform val2 = (RectTransform)val.transform;
			((Transform)val2).SetParent((Transform)(object)_panel, false);
			val2.anchorMin = Vector2.zero;
			val2.anchorMax = Vector2.one;
			val2.offsetMin = new Vector2(24f, 124f);
			val2.offsetMax = new Vector2(-40f, -122f);
			((Graphic)val.GetComponent<Image>()).color = TableBackground;
			_content = CreateRect("Rows", (Transform)(object)val2);
			_content.anchorMin = new Vector2(0f, 1f);
			_content.anchorMax = new Vector2(1f, 1f);
			_content.pivot = new Vector2(0.5f, 1f);
			_content.sizeDelta = Vector2.zero;
			_content.anchoredPosition = Vector2.zero;
			GameObject val3 = new GameObject("Scrollbar", new Type[3]
			{
				typeof(RectTransform),
				typeof(Image),
				typeof(Scrollbar)
			});
			RectTransform val4 = (RectTransform)val3.transform;
			((Transform)val4).SetParent((Transform)(object)_panel, false);
			val4.anchorMin = new Vector2(1f, 0f);
			val4.anchorMax = new Vector2(1f, 1f);
			val4.pivot = new Vector2(1f, 0.5f);
			val4.offsetMin = new Vector2(-36f, 124f);
			val4.offsetMax = new Vector2(-24f, -122f);
			((Graphic)val3.GetComponent<Image>()).color = ScrollTrackColor;
			RectTransform val5 = CreateRect("Sliding Area", (Transform)(object)val4);
			Stretch(val5, 0f);
			GameObject val6 = new GameObject("Handle", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			RectTransform val7 = (RectTransform)val6.transform;
			((Transform)val7).SetParent((Transform)(object)val5, false);
			Stretch(val7, 0f);
			Image component = val6.GetComponent<Image>();
			((Graphic)component).color = gui.ValheimOrange;
			Scrollbar component2 = val3.GetComponent<Scrollbar>();
			component2.handleRect = val7;
			((Selectable)component2).targetGraphic = (Graphic)(object)component;
			component2.direction = (Direction)2;
			_scroll = val.GetComponent<ScrollRect>();
			_scroll.viewport = val2;
			_scroll.content = _content;
			_scroll.horizontal = false;
			_scroll.vertical = true;
			_scroll.movementType = (MovementType)2;
			_scroll.scrollSensitivity = 35f;
			_scroll.verticalScrollbar = component2;
			_scroll.verticalScrollbarVisibility = (ScrollbarVisibility)1;
		}

		private static void BuildRows(IReadOnlyList<AdminEntry> entries)
		{
			//IL_0013: 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)
			foreach (Transform item in (Transform)_content)
			{
				Object.Destroy((Object)(object)((Component)item).gameObject);
			}
			Rows.Clear();
			GUIManager instance = GUIManager.Instance;
			_content.sizeDelta = new Vector2(0f, (float)entries.Count * 34f);
			for (int i = 0; i < entries.Count; i++)
			{
				Rows.Add(BuildRow(instance, entries[i], i));
			}
		}

		private static Row BuildRow(GUIManager gui, AdminEntry entry, int index)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_006a: 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_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: 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_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Row " + entry.Name, new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			RectTransform val2 = (RectTransform)val.transform;
			((Transform)val2).SetParent((Transform)(object)_content, false);
			val2.anchorMin = new Vector2(0f, 1f);
			val2.anchorMax = new Vector2(1f, 1f);
			val2.pivot = new Vector2(0.5f, 1f);
			val2.sizeDelta = new Vector2(0f, 34f);
			val2.anchoredPosition = new Vector2(0f, (float)(-index) * 34f);
			Image component = val.GetComponent<Image>();
			((Graphic)component).color = ((index % 2 == 1) ? StripeColor : Color.clear);
			((Graphic)component).raycastTarget = false;
			Row obj = new Row
			{
				Entry = entry,
				Toggle = AddCheckbox(gui, val2)
			};
			obj.Toggle.isOn = Selected.Contains(entry.Key);
			((UnityEvent<bool>)(object)obj.Toggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool on)
			{
				if (!_settingToggles)
				{
					if (on)
					{
						Selected.Add(entry.Key);
					}
					else
					{
						Selected.Remove(entry.Key);
					}
					ResetConfirm();
					UpdateSelectionControls();
				}
			});
			AddCell(gui, val2, entry.Name, NameColumn, gui.ValheimBeige);
			AddCell(gui, val2, entry.PlatformId, PlatformColumn, gui.ValheimBeige);
			AddColorBlock(val2, entry.PrimaryColor, ColorColumn.X + 17f, isPrimary: true);
			AddColorBlock(val2, entry.SecondaryColor, ColorColumn.X + 52f, isPrimary: false);
			AddDateCell(gui, val2, entry.FirstSeen, FirstSeenColumn);
			AddDateCell(gui, val2, entry.LastSeen, LastSeenColumn);
			if (entry.Online)
			{
				AddCell(gui, val2, "Online", OnlineColumn, OnlineTextColor);
			}
			return obj;
		}

		private static void AddCell(GUIManager gui, RectTransform row, string text, Column column, Color color)
		{
			//IL_000c: 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_002a: Unknown result type (might be due to invalid IL or missing references)
			Text obj = AddText(text, (Transform)(object)row, new Vector2(0f, 0.5f), new Vector2(column.Center, 0f), gui.AveriaSerifBold, 15, color, column.Width, 34f, (TextAnchor)3);
			obj.horizontalOverflow = (HorizontalWrapMode)0;
			obj.verticalOverflow = (VerticalWrapMode)0;
		}

		private static void AddDateCell(GUIManager gui, RectTransform row, string stored, Column column)
		{
			//IL_003a: 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)
			DateTime dateTime = default(DateTime);
			if (WorldColorStore.TryParseTimestamp(stored, ref dateTime))
			{
				AddCell(gui, row, dateTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture), column, gui.ValheimBeige);
			}
			else
			{
				AddCell(gui, row, "Unknown", column, UnknownTextColor);
			}
		}

		private static void AddColorBlock(RectTransform row, string hex, float centerX, bool isPrimary)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_005e: 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_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: 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)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//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_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Color", new Type[3]
			{
				typeof(RectTransform),
				typeof(Image),
				typeof(Outline)
			});
			RectTransform val2 = (RectTransform)val.transform;
			((Transform)val2).SetParent((Transform)(object)row, false);
			Vector2 val3 = default(Vector2);
			((Vector2)(ref val3))..ctor(0f, 0.5f);
			val2.anchorMax = val3;
			val2.anchorMin = val3;
			val2.sizeDelta = new Vector2(26f, 20f);
			val2.anchoredPosition = new Vector2(centerX, 0f);
			Color? val4 = ColorUtil.FromHex(hex);
			Color val5 = (Color)(((??)val4) ?? (isPrimary ? ColorUtil.GamePrimary : PinRecolor.DefaultSecondary));
			Image component = val.GetComponent<Image>();
			((Graphic)component).color = new Color(val5.r, val5.g, val5.b, 1f);
			((Graphic)component).raycastTarget = false;
			Outline component2 = val.GetComponent<Outline>();
			((Shadow)component2).effectColor = Color.black;
			((Shadow)component2).effectDistance = new Vector2(1f, -1f);
			if (!val4.HasValue)
			{
				Text component3 = GUIManager.Instance.CreateText("D", (Transform)(object)val2, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, GUIManager.Instance.AveriaSerifBold, 15, ColorUtil.ContrastText(val5), false, Color.clear, 26f, 20f, false).GetComponent<Text>();
				component3.alignment = (TextAnchor)4;
				((Graphic)component3).raycastTarget = false;
			}
		}

		private static Toggle AddCheckbox(GUIManager gui, RectTransform parent)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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)
			//IL_002f: 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_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: 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_0059: 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_0073: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = gui.CreateToggle((Transform)(object)parent, 24f, 24f);
			RectTransform val = (RectTransform)obj.transform;
			((Transform)val).SetParent((Transform)(object)parent, false);
			((Transform)val).localScale = Vector3.one;
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(0f, 0.5f);
			val.anchorMax = val2;
			val.anchorMin = val2;
			val.pivot = new Vector2(0.5f, 0.5f);
			val.anchoredPosition = new Vector2(CheckColumn.Center, 0f);
			Transform val3 = ((Transform)val).Find("Label");
			if ((Object)(object)val3 != (Object)null)
			{
				((Component)val3).gameObject.SetActive(false);
			}
			Toggle component = obj.GetComponent<Toggle>();
			component.isOn = false;
			return component;
		}

		private static void SetAllSelected(bool on)
		{
			_settingToggles = true;
			foreach (Row row in Rows)
			{
				row.Toggle.isOn = on;
				if (on)
				{
					Selected.Add(row.Entry.Key);
				}
				else
				{
					Selected.Remove(row.Entry.Key);
				}
			}
			_settingToggles = false;
			ResetConfirm();
			UpdateSelectionControls();
		}

		private static void UpdateSelectionControls()
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			int num = Rows.Count((Row r) => Selected.Contains(r.Entry.Key));
			_settingToggles = true;
			_selectAll.isOn = Rows.Count > 0 && num == Rows.Count;
			_settingToggles = false;
			((Selectable)_deleteButton).interactable = num > 0;
			bool flag = _confirmUntil > 0f;
			_deleteLabel.text = (flag ? $"Click again to delete {num}" : ((num > 0) ? $"Delete selected ({num})" : "Delete selected"));
			((Graphic)_deleteLabel).color = (flag ? ConfirmTextColor : _deleteLabelColor);
		}

		private static void ResetConfirm()
		{
			_confirmUntil = float.NegativeInfinity;
		}

		private static void OnDelete()
		{
			List<AdminEntry> list = (from r in Rows
				where Selected.Contains(r.Entry.Key)
				select r.Entry).ToList();
			if (list.Count != 0)
			{
				if (_confirmUntil <= 0f || Time.unscaledTime > _confirmUntil)
				{
					_confirmUntil = Time.unscaledTime + 4f;
					UpdateSelectionControls();
				}
				else
				{
					ResetConfirm();
					UpdateSelectionControls();
					_status.text = (AdminCommand.RequestDelete(list) ? "Deleting..." : "Not connected to a server.");
				}
			}
		}

		private static void OnRefresh()
		{
			ResetConfirm();
			UpdateSelectionControls();
			_status.text = (AdminCommand.RequestList() ? "Refreshing..." : "Not connected to a server.");
		}

		private static RectTransform CreateRect(string name, Transform parent)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: