Decompiled source of ConfigManager v1.0.0

Mods/ConfigManager.dll

Decompiled 5 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using ConfigManager;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(MainMod), "Config Manager", "1.0.0", "Flipo42", null)]
[assembly: MelonGame(null, null)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("ConfigManager")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ConfigManager")]
[assembly: AssemblyTitle("ConfigManager")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ConfigManager
{
	internal static class ConfigUI
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static WindowFunction <0>__DrawWindow;
		}

		private const int WindowId = 19779;

		private const float SaveDelay = 0.75f;

		private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;

		private static bool _visible;

		private static Rect _window = new Rect(60f, 60f, 660f, 600f);

		private static Vector2 _scroll;

		private static string _filter = "";

		private static readonly HashSet<string> _expanded = new HashSet<string>();

		private static readonly Dictionary<MelonPreferences_Entry, string> _buffers = new Dictionary<MelonPreferences_Entry, string>();

		private static readonly HashSet<MelonPreferences_Category> _dirty = new HashSet<MelonPreferences_Category>();

		private static float _lastChange;

		private static bool _prevCursorVisible;

		private static CursorLockMode _prevLock;

		private static GUIStyle _windowStyle;

		private static GUIStyle _headerStyle;

		private static GUIStyle _descStyle;

		private static Texture2D _bg;

		public static void OnGUI()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Invalid comparison between Unknown and I4
			//IL_0068: 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_001d: 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_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Expected O, but got Unknown
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Invalid comparison between Unknown and I4
			Event current = Event.current;
			if (current != null && (int)current.type == 4)
			{
				if (current.keyCode == MainMod.ToggleKey.Value)
				{
					SetVisible(!_visible);
					current.Use();
				}
				else if (_visible && (int)current.keyCode == 27)
				{
					SetVisible(value: false);
					current.Use();
				}
			}
			if (_visible)
			{
				InitStyles();
				Rect window = _window;
				object obj = <>O.<0>__DrawWindow;
				if (obj == null)
				{
					WindowFunction val = DrawWindow;
					<>O.<0>__DrawWindow = val;
					obj = (object)val;
				}
				_window = GUI.Window(19779, window, (WindowFunction)obj, "Gerenciador de Configurações  (" + ((object)MainMod.ToggleKey.Value/*cast due to .constrained prefix*/).ToString() + " para fechar)", _windowStyle);
				((Rect)(ref _window)).x = Mathf.Clamp(((Rect)(ref _window)).x, 0f, Mathf.Max(0f, (float)Screen.width - 80f));
				((Rect)(ref _window)).y = Mathf.Clamp(((Rect)(ref _window)).y, 0f, Mathf.Max(0f, (float)Screen.height - 40f));
			}
		}

		public static void LateTick()
		{
			if (_visible)
			{
				ApplyCursor();
			}
			FlushSaves(force: false);
		}

		private static void SetVisible(bool value)
		{
			//IL_003c: 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_0021: Unknown result type (might be due to invalid IL or missing references)
			if (value != _visible)
			{
				_visible = value;
				if (value)
				{
					_prevCursorVisible = Cursor.visible;
					_prevLock = Cursor.lockState;
					ApplyCursor();
				}
				else
				{
					FlushSaves(force: true);
					Cursor.visible = _prevCursorVisible;
					Cursor.lockState = _prevLock;
				}
			}
		}

		private static void ApplyCursor()
		{
			Cursor.lockState = (CursorLockMode)0;
			Cursor.visible = true;
		}

		public static void FlushSaves(bool force)
		{
			if (_dirty.Count == 0 || (!force && Time.realtimeSinceStartup - _lastChange < 0.75f))
			{
				return;
			}
			foreach (MelonPreferences_Category item in _dirty)
			{
				try
				{
					item.SaveToFile(false);
				}
				catch (Exception ex)
				{
					MainMod.Log.Error("Falha ao salvar '" + item.Identifier + "': " + ex.Message);
				}
			}
			_dirty.Clear();
		}

		private static void Apply(MelonPreferences_Category cat, MelonPreferences_Entry entry, object value)
		{
			try
			{
				entry.BoxedValue = value;
				_dirty.Add(cat);
				_lastChange = Time.realtimeSinceStartup;
			}
			catch (Exception ex)
			{
				MainMod.Log.Error("Valor inválido para '" + entry.Identifier + "': " + ex.Message);
			}
		}

		private static void DrawWindow(int id)
		{
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label("Filtro:", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(45f) });
			_filter = GUILayout.TextField(_filter ?? "", Array.Empty<GUILayoutOption>());
			if (GUILayout.Button("Salvar tudo", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) }))
			{
				MelonPreferences.Save();
			}
			if (GUILayout.Button("Recarregar", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) }))
			{
				MelonPreferences.Load();
				_buffers.Clear();
			}
			if (GUILayout.Button("X", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(28f) }))
			{
				SetVisible(value: false);
			}
			GUILayout.EndHorizontal();
			bool flag = !string.IsNullOrEmpty(_filter);
			_scroll = GUILayout.BeginScrollView(_scroll, Array.Empty<GUILayoutOption>());
			foreach (MelonPreferences_Category item in new List<MelonPreferences_Category>(MelonPreferences.Categories))
			{
				List<MelonPreferences_Entry> visibleEntries = GetVisibleEntries(item);
				if (visibleEntries.Count == 0)
				{
					continue;
				}
				bool flag2 = flag || _expanded.Contains(item.Identifier);
				if (GUILayout.Button((flag2 ? "[-] " : "[+] ") + CategoryName(item) + "   (" + visibleEntries.Count + ")", _headerStyle, Array.Empty<GUILayoutOption>()) && !_expanded.Remove(item.Identifier))
				{
					_expanded.Add(item.Identifier);
				}
				if (!flag2)
				{
					continue;
				}
				foreach (MelonPreferences_Entry item2 in visibleEntries)
				{
					DrawEntry(item, item2);
				}
				GUILayout.Space(8f);
			}
			GUILayout.EndScrollView();
			GUI.DragWindow(new Rect(0f, 0f, 10000f, 22f));
		}

		private static string CategoryName(MelonPreferences_Category cat)
		{
			if (!string.IsNullOrEmpty(cat.DisplayName))
			{
				return cat.DisplayName;
			}
			return cat.Identifier;
		}

		private static string EntryName(MelonPreferences_Entry e)
		{
			if (!string.IsNullOrEmpty(e.DisplayName))
			{
				return e.DisplayName;
			}
			return e.Identifier;
		}

		private static List<MelonPreferences_Entry> GetVisibleEntries(MelonPreferences_Category cat)
		{
			List<MelonPreferences_Entry> list = new List<MelonPreferences_Entry>();
			bool flag = string.IsNullOrEmpty(_filter) || Contains(CategoryName(cat), _filter) || Contains(cat.Identifier, _filter);
			foreach (MelonPreferences_Entry entry in cat.Entries)
			{
				if (!IsHidden(entry) && (flag || Contains(EntryName(entry), _filter) || Contains(entry.Identifier, _filter)))
				{
					list.Add(entry);
				}
			}
			return list;
		}

		private static bool Contains(string text, string filter)
		{
			if (text != null)
			{
				return text.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0;
			}
			return false;
		}

		private static void DrawEntry(MelonPreferences_Category cat, MelonPreferences_Entry entry)
		{
			Type reflectedType = entry.GetReflectedType();
			object boxedValue = entry.BoxedValue;
			object value = boxedValue;
			bool flag = false;
			string key = cat.Identifier + "/" + entry.Identifier;
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label(EntryName(entry), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(210f) });
			if (reflectedType == typeof(bool))
			{
				bool flag2 = (bool)boxedValue;
				bool flag3 = GUILayout.Toggle(flag2, flag2 ? "Ligado" : "Desligado", Array.Empty<GUILayoutOption>());
				if (flag3 != flag2)
				{
					value = flag3;
					flag = true;
				}
			}
			else if (reflectedType.IsEnum)
			{
				Array values = Enum.GetValues(reflectedType);
				string edited;
				if (values.Length <= 12)
				{
					int num = Array.IndexOf(values, boxedValue);
					if (GUILayout.Button("<", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(26f) }))
					{
						num = (num - 1 + values.Length) % values.Length;
						value = values.GetValue(num);
						flag = true;
					}
					GUILayout.Label(boxedValue.ToString(), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.MinWidth(90f) });
					if (GUILayout.Button(">", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(26f) }))
					{
						num = (num + 1) % values.Length;
						value = values.GetValue(num);
						flag = true;
					}
				}
				else if (BufferedField(entry, key, boxedValue.ToString(), 0f, out edited))
				{
					try
					{
						value = Enum.Parse(reflectedType, edited.Trim(), ignoreCase: true);
						flag = true;
					}
					catch
					{
					}
				}
			}
			else if (IsNumeric(reflectedType))
			{
				if (TryGetRange(entry, out var min, out var max))
				{
					float num2 = Convert.ToSingle(boxedValue, Inv);
					float num3 = GUILayout.HorizontalSlider(num2, (float)min, (float)max, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.MinWidth(120f) });
					if (IsInteger(reflectedType))
					{
						num3 = Mathf.Round(num3);
					}
					if (Mathf.Abs(num3 - num2) > 1E-06f)
					{
						try
						{
							value = Convert.ChangeType(num3, reflectedType, Inv);
							flag = true;
						}
						catch (OverflowException)
						{
						}
					}
				}
				if (BufferedField(entry, key, Convert.ToString(boxedValue, Inv), 80f, out var edited2) && TryParseNumber(reflectedType, edited2, out var result))
				{
					value = result;
					flag = true;
				}
			}
			else if (reflectedType == typeof(string))
			{
				if (BufferedField(entry, key, ((string)boxedValue) ?? "", 0f, out var edited3))
				{
					value = edited3;
					flag = true;
				}
			}
			else
			{
				GUILayout.Label(((boxedValue != null) ? boxedValue.ToString() : "(nulo)") + "   [" + reflectedType.Name + ", somente leitura]", Array.Empty<GUILayoutOption>());
			}
			if (GUILayout.Button("R", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(24f) }))
			{
				try
				{
					entry.ResetToDefault();
					_buffers.Remove(entry);
					_dirty.Add(cat);
					_lastChange = Time.realtimeSinceStartup;
				}
				catch (Exception ex2)
				{
					MainMod.Log.Error("Falha ao resetar: " + ex2.Message);
				}
			}
			GUILayout.EndHorizontal();
			if (!string.IsNullOrEmpty(entry.Description))
			{
				GUILayout.Label(entry.Description, _descStyle, Array.Empty<GUILayoutOption>());
			}
			if (flag)
			{
				Apply(cat, entry, value);
			}
		}

		private static bool BufferedField(MelonPreferences_Entry entry, string key, string display, float width, out string edited)
		{
			string text = "cfg_" + key;
			GUI.SetNextControlName(text);
			bool num = GUI.GetNameOfFocusedControl() == text;
			string text2 = display;
			if (num)
			{
				if (_buffers.TryGetValue(entry, out var value))
				{
					text2 = value;
				}
			}
			else
			{
				_buffers.Remove(entry);
			}
			string text3 = (edited = ((width > 0f) ? GUILayout.TextField(text2, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(width) }) : GUILayout.TextField(text2, Array.Empty<GUILayoutOption>())));
			if (text3 == text2)
			{
				return false;
			}
			_buffers[entry] = text3;
			return true;
		}

		private static bool IsNumeric(Type t)
		{
			TypeCode typeCode = Type.GetTypeCode(t);
			if ((uint)(typeCode - 5) <= 10u)
			{
				return true;
			}
			return false;
		}

		private static bool IsInteger(Type t)
		{
			TypeCode typeCode = Type.GetTypeCode(t);
			if (IsNumeric(t) && typeCode != TypeCode.Single && typeCode != TypeCode.Double)
			{
				return typeCode != TypeCode.Decimal;
			}
			return false;
		}

		private static bool TryParseNumber(Type t, string text, out object result)
		{
			result = null;
			if (string.IsNullOrWhiteSpace(text))
			{
				return false;
			}
			text = text.Trim().Replace(',', '.');
			if (!double.TryParse(text, NumberStyles.Float, Inv, out var result2))
			{
				return false;
			}
			if (double.IsNaN(result2) || double.IsInfinity(result2))
			{
				return false;
			}
			if (IsInteger(t) && result2 != Math.Floor(result2))
			{
				return false;
			}
			try
			{
				result = Convert.ChangeType(result2, t, Inv);
				return true;
			}
			catch (OverflowException)
			{
				return false;
			}
		}

		private static bool IsHidden(MelonPreferences_Entry entry)
		{
			try
			{
				PropertyInfo property = ((object)entry).GetType().GetProperty("IsHidden", BindingFlags.Instance | BindingFlags.Public);
				if (property != null)
				{
					return (bool)property.GetValue(entry, null);
				}
			}
			catch
			{
			}
			return false;
		}

		private static bool TryGetRange(MelonPreferences_Entry entry, out double min, out double max)
		{
			min = (max = 0.0);
			try
			{
				PropertyInfo property = ((object)entry).GetType().GetProperty("Validator", BindingFlags.Instance | BindingFlags.Public);
				object obj = ((property != null) ? property.GetValue(entry, null) : null);
				if (obj == null)
				{
					return false;
				}
				if (!ReadNumber(obj, out min, "MinValue", "Min"))
				{
					return false;
				}
				if (!ReadNumber(obj, out max, "MaxValue", "Max"))
				{
					return false;
				}
				return max > min && !double.IsInfinity(min) && !double.IsInfinity(max);
			}
			catch
			{
				return false;
			}
		}

		private static bool ReadNumber(object obj, out double value, params string[] names)
		{
			value = 0.0;
			Type type = obj.GetType();
			foreach (string name in names)
			{
				object obj2 = null;
				PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public);
				if (property != null)
				{
					obj2 = property.GetValue(obj, null);
				}
				else
				{
					FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public);
					if (field != null)
					{
						obj2 = field.GetValue(obj);
					}
				}
				if (obj2 != null)
				{
					value = Convert.ToDouble(obj2, Inv);
					return true;
				}
			}
			return false;
		}

		private static void InitStyles()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			//IL_002f: 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: Expected O, but got Unknown
			//IL_0095: 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_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Expected O, but got Unknown
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			if (_windowStyle == null)
			{
				_bg = new Texture2D(1, 1);
				_bg.SetPixel(0, 0, new Color(0.08f, 0.08f, 0.1f, 0.97f));
				_bg.Apply();
				((Object)_bg).hideFlags = (HideFlags)61;
				_windowStyle = new GUIStyle(GUI.skin.window);
				_windowStyle.normal.background = _bg;
				_windowStyle.onNormal.background = _bg;
				_windowStyle.normal.textColor = Color.white;
				_windowStyle.onNormal.textColor = Color.white;
				_headerStyle = new GUIStyle(GUI.skin.button);
				_headerStyle.alignment = (TextAnchor)3;
				_headerStyle.fontStyle = (FontStyle)1;
				_descStyle = new GUIStyle(GUI.skin.label);
				_descStyle.fontSize = 11;
				_descStyle.wordWrap = true;
				_descStyle.normal.textColor = new Color(0.65f, 0.65f, 0.7f);
			}
		}
	}
	public class MainMod : MelonMod
	{
		internal static MelonPreferences_Category Prefs;

		internal static MelonPreferences_Entry<KeyCode> ToggleKey;

		internal static Instance Log;

		public override void OnInitializeMelon()
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			Log = ((MelonBase)this).LoggerInstance;
			Prefs = MelonPreferences.CreateCategory("ConfigManager", "Gerenciador de Configurações");
			ToggleKey = Prefs.CreateEntry<KeyCode>("ToggleKey", (KeyCode)277, "Tecla de atalho", (string)null, false, false, (ValueValidator)null, (string)null);
			Log.Msg($"Config Manager carregado. Pressione {ToggleKey.Value} para abrir o painel.");
		}

		public override void OnGUI()
		{
			ConfigUI.OnGUI();
		}

		public override void OnLateUpdate()
		{
			ConfigUI.LateTick();
		}

		public override void OnApplicationQuit()
		{
			ConfigUI.FlushSaves(force: true);
		}
	}
}