Decompiled source of MenuScrollFix v1.3.0

MenuScrollFix.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.UI;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("MenuScrollFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MenuScrollFix")]
[assembly: AssemblyTitle("MenuScrollFix")]
[assembly: AssemblyMetadata("AI_Assisted_Creation", "Code generated with Anthropic Claude (Claude Opus 5.5 and other Claude models, via Claude Code); designed and tested by the author")]
[assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace MenuScrollFix;

internal static class Fixer
{
	private sealed class ModuleRecord
	{
		public InputSystemUIInputModule Module;

		public float Original;

		public float LastApplied;

		public bool Applied;
	}

	private sealed class RectRecord
	{
		public ScrollRect Rect;

		public float Original;

		public float LastApplied;

		public bool Applied;
	}

	private static readonly Dictionary<int, ModuleRecord> Modules = new Dictionary<int, ModuleRecord>();

	private static readonly Dictionary<int, RectRecord> Rects = new Dictionary<int, RectRecord>();

	private static readonly HashSet<int> TerminalSkipLogged = new HashSet<int>();

	public static ScrollConfig Cfg;

	public static readonly WheelDetector Wheel = new WheelDetector();

	private static bool _terminalTypeBroken;

	private static bool Verbose
	{
		get
		{
			if (Cfg != null)
			{
				return Cfg.VerboseLogging.Value;
			}
			return false;
		}
	}

	public static int TrackedModules => Modules.Count;

	public static int TrackedRects => Rects.Count;

	public static void ApplyAll(string reason)
	{
		if (Cfg == null || Safe.Tripped)
		{
			return;
		}
		Prune();
		if (Verbose)
		{
			Safe.Log.LogInfo((object)("Applying (" + reason + ")"));
		}
		InputSystemUIInputModule[] array = Safe.Run("find input modules", () => Object.FindObjectsOfType<InputSystemUIInputModule>(true), null);
		if (array != null)
		{
			InputSystemUIInputModule[] array2 = array;
			foreach (InputSystemUIInputModule val in array2)
			{
				InputSystemUIInputModule mm = val;
				Safe.Run("apply input module", delegate
				{
					ApplyModule(mm);
				});
			}
		}
		if (!Cfg.ListsWanted && Rects.Count <= 0)
		{
			return;
		}
		ScrollRect[] array3 = Safe.Run("find scroll lists", () => Object.FindObjectsOfType<ScrollRect>(true), null);
		if (array3 == null)
		{
			return;
		}
		ScrollRect[] array4 = array3;
		foreach (ScrollRect val2 in array4)
		{
			ScrollRect rr = val2;
			Safe.Run("apply scroll list", delegate
			{
				ApplyRect(rr);
			});
		}
	}

	public static void RestoreAll()
	{
		foreach (ModuleRecord value in Modules.Values)
		{
			try
			{
				if (value.Applied && (Object)(object)value.Module != (Object)null)
				{
					value.Module.scrollDeltaPerTick = value.Original;
				}
				value.Applied = false;
			}
			catch
			{
			}
		}
		foreach (RectRecord value2 in Rects.Values)
		{
			try
			{
				if (value2.Applied && (Object)(object)value2.Rect != (Object)null)
				{
					value2.Rect.scrollSensitivity = value2.Original;
				}
				value2.Applied = false;
			}
			catch
			{
			}
		}
	}

	private static void Prune()
	{
		Safe.Run("prune destroyed objects", delegate
		{
			List<int> list = null;
			foreach (KeyValuePair<int, ModuleRecord> module in Modules)
			{
				if ((Object)(object)module.Value.Module == (Object)null)
				{
					List<int> obj = list ?? new List<int>();
					list = obj;
					obj.Add(module.Key);
				}
			}
			if (list != null)
			{
				foreach (int item in list)
				{
					Modules.Remove(item);
				}
			}
			list = null;
			foreach (KeyValuePair<int, RectRecord> rect in Rects)
			{
				if ((Object)(object)rect.Value.Rect == (Object)null)
				{
					List<int> obj2 = list ?? new List<int>();
					list = obj2;
					obj2.Add(rect.Key);
				}
			}
			if (list != null)
			{
				foreach (int item2 in list)
				{
					Rects.Remove(item2);
				}
			}
		});
	}

	public static void ApplyModule(InputSystemUIInputModule module)
	{
		if ((Object)(object)module == (Object)null || Cfg == null || Safe.Tripped)
		{
			return;
		}
		int instanceID = ((Object)module).GetInstanceID();
		float scrollDeltaPerTick = module.scrollDeltaPerTick;
		ModuleRecord value;
		bool num = !Modules.TryGetValue(instanceID, out value);
		if (num)
		{
			value = new ModuleRecord
			{
				Module = module,
				Original = scrollDeltaPerTick
			};
			Modules[instanceID] = value;
		}
		else
		{
			value.Original = Rules.RebaseOriginal(value.Original, value.LastApplied, scrollDeltaPerTick, value.Applied);
		}
		float? num2 = Rules.ModuleDelta(scale: Cfg.AutoDetectWheelScale.Value ? Wheel.Scale : WheelScale.Unknown, enabled: Cfg.Enabled.Value, overrideDelta: Cfg.OverrideScrollDeltaPerTick.Value, configured: Cfg.DeltaPerTick, original: value.Original);
		if (num2.HasValue)
		{
			if (!Rules.Approximately(scrollDeltaPerTick, num2.Value))
			{
				module.scrollDeltaPerTick = num2.Value;
			}
			value.LastApplied = num2.Value;
			value.Applied = true;
		}
		else if (value.Applied)
		{
			module.scrollDeltaPerTick = value.Original;
			value.Applied = false;
		}
		if (num)
		{
			Safe.Log.LogInfo((object)("Input module '" + Path(((Component)module).transform) + "': original scrollDeltaPerTick " + value.Original + ", now " + module.scrollDeltaPerTick));
		}
		else if (Verbose)
		{
			Safe.Log.LogInfo((object)("Input module '" + Path(((Component)module).transform) + "': " + scrollDeltaPerTick + " -> " + module.scrollDeltaPerTick));
		}
	}

	public static void ApplyRect(ScrollRect rect)
	{
		if ((Object)(object)rect == (Object)null || Cfg == null || Safe.Tripped)
		{
			return;
		}
		int instanceID = ((Object)rect).GetInstanceID();
		RectRecord value;
		bool flag = Rects.TryGetValue(instanceID, out value);
		bool flag2 = Cfg.Enabled.Value && Cfg.ListsWanted;
		if (!flag2 && !flag)
		{
			return;
		}
		if (flag2 && Cfg.ExcludeTerminal.Value && IsTerminal((Component)(object)rect))
		{
			if (flag && value.Applied)
			{
				rect.scrollSensitivity = value.Original;
				value.Applied = false;
			}
			if (Verbose && TerminalSkipLogged.Add(instanceID))
			{
				Safe.Log.LogInfo((object)("Skipping terminal list '" + Path(((Component)rect).transform) + "'"));
			}
			return;
		}
		float scrollSensitivity = rect.scrollSensitivity;
		if (!flag)
		{
			value = new RectRecord
			{
				Rect = rect,
				Original = scrollSensitivity
			};
			Rects[instanceID] = value;
		}
		else
		{
			value.Original = Rules.RebaseOriginal(value.Original, value.LastApplied, scrollSensitivity, value.Applied);
		}
		if (flag2)
		{
			float num = (Cfg.NormalizeListSpeeds.Value ? Rules.NormalizedSensitivity(value.Original, Cfg.NormalizedValue) : Rules.ScaledSensitivity(value.Original, Cfg.Multiplier, Cfg.MinSensitivity));
			if (!Rules.Approximately(scrollSensitivity, num))
			{
				rect.scrollSensitivity = num;
			}
			bool flag3 = !value.Applied || !Rules.Approximately(value.LastApplied, num);
			value.LastApplied = num;
			value.Applied = true;
			if (Verbose && flag3)
			{
				Safe.Log.LogInfo((object)("List '" + Path(((Component)rect).transform) + "': sensitivity " + value.Original + " -> " + num));
			}
		}
		else if (value.Applied)
		{
			rect.scrollSensitivity = value.Original;
			value.Applied = false;
			if (Verbose)
			{
				Safe.Log.LogInfo((object)("List '" + Path(((Component)rect).transform) + "': restored " + value.Original));
			}
		}
	}

	public static bool IsTerminal(Component c)
	{
		if (_terminalTypeBroken)
		{
			return NameLooksLikeTerminal(c.transform);
		}
		try
		{
			return TerminalCheck.IsUnderTerminal(c);
		}
		catch (Exception ex)
		{
			_terminalTypeBroken = true;
			Safe.Log.LogWarning((object)("Terminal type check unavailable, using object names instead: " + ex.GetType().Name));
			return NameLooksLikeTerminal(c.transform);
		}
	}

	private static bool NameLooksLikeTerminal(Transform t)
	{
		int num = 0;
		while ((Object)(object)t != (Object)null && num < 64)
		{
			if (((Object)t).name != null && ((Object)t).name.IndexOf("Terminal", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
			num++;
			t = t.parent;
		}
		return false;
	}

	public static void ObserveWheel(Vector2 raw)
	{
		//IL_001e: 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)
		if (Cfg != null && Cfg.AutoDetectWheelScale.Value && Wheel.Observe(raw.x, raw.y))
		{
			if (Wheel.Scale == WheelScale.Normalized)
			{
				Safe.Log.LogWarning((object)("Mouse wheel already reports ~1 per notch (max " + Wheel.MaxSeen + " over " + Wheel.Samples + " events). The game seems fixed upstream, so the input module override is now off."));
				ApplyAll("wheel scale detected");
			}
			else
			{
				Safe.Log.LogInfo((object)("Mouse wheel reports ~" + Wheel.MaxSeen + " per notch; override active."));
			}
		}
	}

	public static string Path(Transform t)
	{
		try
		{
			StringBuilder stringBuilder = new StringBuilder();
			int num = 0;
			while ((Object)(object)t != (Object)null && num < 32)
			{
				if (stringBuilder.Length > 0)
				{
					stringBuilder.Insert(0, '/');
				}
				stringBuilder.Insert(0, ((Object)t).name);
				num++;
				t = t.parent;
			}
			return stringBuilder.ToString();
		}
		catch
		{
			return "?";
		}
	}
}
internal static class TerminalCheck
{
	private static Terminal[] _terminals;

	private static int _terminalsFrame = -1;

	[MethodImpl(MethodImplOptions.NoInlining)]
	public static bool IsUnderTerminal(Component c)
	{
		if ((Object)(object)c.GetComponentInParent<Terminal>(true) != (Object)null)
		{
			return true;
		}
		if (_terminalsFrame != Time.frameCount || _terminals == null)
		{
			_terminals = Object.FindObjectsOfType<Terminal>(true);
			_terminalsFrame = Time.frameCount;
		}
		Terminal[] terminals = _terminals;
		foreach (Terminal val in terminals)
		{
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			if ((Object)(object)val.terminalUIScreen != (Object)null && c.transform.IsChildOf(((Component)val.terminalUIScreen).transform))
			{
				return true;
			}
			if ((Object)(object)val.scrollBarVertical != (Object)null)
			{
				ScrollRect val2 = (ScrollRect)(object)((c is ScrollRect) ? c : null);
				if ((Object)(object)val2 != (Object)null && (Object)(object)val2.verticalScrollbar == (Object)(object)val.scrollBarVertical)
				{
					return true;
				}
			}
		}
		return false;
	}
}
internal static class Patches
{
	public static bool ModuleHooked { get; private set; }

	public static bool ListHooked { get; private set; }

	public static bool TerminalHooked { get; private set; }

	public static bool WheelHooked { get; private set; }

	public static void Apply(Harmony harmony)
	{
		ModuleHooked = TryPatch(harmony, typeof(InputSystemUIInputModule), "OnEnable", null, "ModulePostfix");
		ListHooked = TryPatch(harmony, typeof(ScrollRect), "OnEnable", null, "ListPostfix");
		WheelHooked = TryPatch(harmony, typeof(InputSystemUIInputModule), "OnScrollCallback", "WheelPrefix", null);
		TerminalHooked = TryPatch(harmony, typeof(PlayerControllerB), "ScrollMouse_performed", "TerminalScrollPrefix", null, 800);
	}

	private static bool TryPatch(Harmony harmony, Type type, string method, string prefix, string postfix, int priority = 400)
	{
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		string text = type.Name + "." + method;
		MethodInfo methodInfo = null;
		try
		{
			methodInfo = AccessTools.DeclaredMethod(type, method, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Safe.Log.LogWarning((object)("Hook target " + text + " not found; that hook is skipped (scene-load pass still runs)."));
				return false;
			}
			HarmonyMethod val = ((prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(AccessTools.Method(typeof(Patches), prefix, (Type[])null, (Type[])null))
			{
				priority = priority
			});
			HarmonyMethod val2 = ((postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(AccessTools.Method(typeof(Patches), postfix, (Type[])null, (Type[])null)));
			harmony.Patch((MethodBase)methodInfo, val, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return true;
		}
		catch (Exception ex)
		{
			Safe.Log.LogWarning((object)("Could not hook " + text + " (skipped, scene-load pass still runs): " + ex.Message));
			if (methodInfo != null)
			{
				try
				{
					harmony.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)0, harmony.Id);
				}
				catch
				{
				}
			}
			return false;
		}
	}

	private static void ModulePostfix(InputSystemUIInputModule __instance)
	{
		if (!Safe.Tripped)
		{
			InputSystemUIInputModule m = __instance;
			Safe.Run("input module enabled", delegate
			{
				Fixer.ApplyModule(m);
			});
		}
	}

	private static void ListPostfix(ScrollRect __instance)
	{
		if (!Safe.Tripped && Fixer.Cfg != null && (Fixer.Cfg.ListsWanted || Fixer.TrackedRects != 0))
		{
			ScrollRect r = __instance;
			Safe.Run("scroll list enabled", delegate
			{
				Fixer.ApplyRect(r);
			});
		}
	}

	private static void WheelPrefix(CallbackContext context)
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		if (Safe.Tripped || Fixer.Wheel.Scale != WheelScale.Unknown)
		{
			return;
		}
		try
		{
			Fixer.ObserveWheel(((CallbackContext)(ref context)).ReadValue<Vector2>());
		}
		catch (Exception e)
		{
			Safe.Report("wheel scale check", e);
		}
	}

	private static bool TerminalScrollPrefix(PlayerControllerB __instance, CallbackContext context)
	{
		try
		{
			if (Safe.Tripped || Fixer.Cfg == null || !Fixer.Cfg.Enabled.Value || !Fixer.Cfg.TerminalScrollFix.Value)
			{
				return true;
			}
			if ((Object)(object)__instance == (Object)null || !__instance.inTerminalMenu || (Object)(object)__instance.terminalScrollVertical == (Object)null)
			{
				return true;
			}
			float num = ((CallbackContext)(ref context)).ReadValue<float>();
			if (Math.Abs(num) < 0.0001f)
			{
				return false;
			}
			Scrollbar terminalScrollVertical = __instance.terminalScrollVertical;
			MeasureTerminal(terminalScrollVertical, out var lineHeight, out var scrollable);
			terminalScrollVertical.value = Mathf.Clamp01(terminalScrollVertical.value + Rules.TerminalStep(num, Fixer.Cfg.TerminalLines, lineHeight, scrollable));
			return false;
		}
		catch (Exception e)
		{
			Safe.Report("terminal scroll", e);
			return true;
		}
	}

	private static void MeasureTerminal(Scrollbar bar, out float lineHeight, out float scrollable)
	{
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		lineHeight = 0f;
		scrollable = 0f;
		ScrollRect componentInParent = ((Component)bar).GetComponentInParent<ScrollRect>();
		if (!((Object)(object)componentInParent == (Object)null) && !((Object)(object)componentInParent.content == (Object)null))
		{
			RectTransform val = (RectTransform)(((Object)(object)componentInParent.viewport != (Object)null) ? ((object)componentInParent.viewport) : ((object)(RectTransform)((Component)componentInParent).transform));
			Rect rect = componentInParent.content.rect;
			float height = ((Rect)(ref rect)).height;
			rect = val.rect;
			scrollable = height - ((Rect)(ref rect)).height;
			TMP_Text componentInChildren = ((Component)componentInParent.content).GetComponentInChildren<TMP_Text>();
			if (!((Object)(object)componentInChildren == (Object)null))
			{
				TMP_TextInfo textInfo = componentInChildren.textInfo;
				lineHeight = ((textInfo != null && textInfo.lineCount > 0 && textInfo.lineInfo != null && textInfo.lineInfo.Length != 0 && textInfo.lineInfo[0].lineHeight > 0f) ? textInfo.lineInfo[0].lineHeight : (componentInChildren.fontSize * 1.2f));
			}
		}
	}
}
[BepInPlugin("jacob.menuscrollfix", "MenuScrollFix", "1.3.0")]
public class Plugin : BaseUnityPlugin
{
	public const string Guid = "jacob.menuscrollfix";

	public const string Name = "MenuScrollFix";

	public const string Version = "1.3.0";

	private static bool _started;

	private void Awake()
	{
		//IL_019f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a9: Expected O, but got Unknown
		Safe.Log = ((BaseUnityPlugin)this).Logger;
		if (_started)
		{
			return;
		}
		_started = true;
		try
		{
			ScrollConfig scrollConfig = (Fixer.Cfg = new ScrollConfig(((BaseUnityPlugin)this).Config));
			Safe.OnTrip = Fixer.RestoreAll;
			((BaseUnityPlugin)this).Logger.LogInfo((object)("MenuScrollFix 1.3.0 loaded. Enabled=" + scrollConfig.Enabled.Value + ", input module override=" + scrollConfig.OverrideScrollDeltaPerTick.Value + " (" + scrollConfig.DeltaPerTick + " per notch), same speed for all lists=" + scrollConfig.NormalizeListSpeeds.Value + " (" + scrollConfig.NormalizedValue + "), per-list scaling=" + scrollConfig.ScaleScrollRectSensitivity.Value + " (x" + scrollConfig.Multiplier + ", min " + scrollConfig.MinSensitivity + "), exclude terminal=" + scrollConfig.ExcludeTerminal.Value + ", terminal fix=" + scrollConfig.TerminalScrollFix.Value + " (" + scrollConfig.TerminalLines + " lines per notch)"));
			try
			{
				Patches.Apply(new Harmony("jacob.menuscrollfix"));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Hooks unavailable, relying on scene-load passes only: " + ex.Message));
			}
			SceneManager.sceneLoaded += OnSceneLoaded;
			scrollConfig.Changed += delegate
			{
				Fixer.ApplyAll("config changed");
			};
			Safe.Run("startup pass", delegate
			{
				Fixer.ApplyAll("startup");
			});
		}
		catch (Exception ex2)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("MenuScrollFix failed to start and is inactive this session: " + ex2));
		}
	}

	private static void OnSceneLoaded(Scene scene, LoadSceneMode mode)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		string n = Safe.Run("scene name", () => ((Scene)(ref scene)).name, "?");
		Safe.Run("scene-load pass", delegate
		{
			Fixer.ApplyAll("scene " + n);
		});
	}
}
internal enum WheelScale
{
	Unknown,
	Legacy120,
	Normalized
}
internal static class Rules
{
	public const float MinDeltaPerTick = 0.01f;

	public const float MaxDeltaPerTick = 50f;

	public const float MinMultiplier = 0.01f;

	public const float MaxMultiplier = 10f;

	public const float MaxMinSensitivity = 1000f;

	public const float MinNormalized = 0.01f;

	public const float MaxNormalized = 100f;

	public const float LegacyThreshold = 50f;

	public const float NormalizedThreshold = 10f;

	public const int NormalizedSampleCount = 8;

	public static bool IsFinite(float v)
	{
		if (!float.IsNaN(v))
		{
			return !float.IsInfinity(v);
		}
		return false;
	}

	public static float Sanitize(float value, float min, float max, float fallback)
	{
		if (!IsFinite(value))
		{
			return fallback;
		}
		if (value < min)
		{
			return min;
		}
		if (value > max)
		{
			return max;
		}
		return value;
	}

	public static float ScaledSensitivity(float original, float multiplier, float minSensitivity)
	{
		if (!IsFinite(original))
		{
			return original;
		}
		if (!IsFinite(multiplier) || multiplier <= 0f)
		{
			return original;
		}
		float num = ((original < 0f) ? (-1f) : 1f);
		float num2 = Math.Abs(original);
		float val = ((IsFinite(minSensitivity) && minSensitivity > 0f) ? Math.Min(num2, minSensitivity) : 0f);
		float num3 = Math.Max(num2 * multiplier, val);
		return num * num3;
	}

	public static float NormalizedSensitivity(float original, float target)
	{
		if (!IsFinite(original) || original == 0f)
		{
			return original;
		}
		if (!IsFinite(target) || target <= 0f)
		{
			return original;
		}
		if (!(original < 0f))
		{
			return target;
		}
		return 0f - target;
	}

	public static float? ModuleDelta(bool enabled, bool overrideDelta, WheelScale scale, float configured, float original)
	{
		if (!enabled || !overrideDelta)
		{
			return null;
		}
		if (scale == WheelScale.Normalized)
		{
			return null;
		}
		if (!IsFinite(configured))
		{
			return null;
		}
		return Sanitize(configured, 0.01f, 50f, original);
	}

	public static float RebaseOriginal(float recordedOriginal, float lastApplied, float current, bool weApplied)
	{
		if (!weApplied)
		{
			return current;
		}
		if (Approximately(current, lastApplied))
		{
			return recordedOriginal;
		}
		return current;
	}

	public static bool Approximately(float a, float b)
	{
		return Math.Abs(a - b) <= 0.0001f * Math.Max(1f, Math.Max(Math.Abs(a), Math.Abs(b)));
	}

	public static float TerminalStep(float raw, float lines, float lineHeight, float scrollable)
	{
		if (float.IsNaN(raw) || float.IsInfinity(raw) || Math.Abs(raw) < 0.0001f)
		{
			return 0f;
		}
		if (float.IsNaN(scrollable) || scrollable <= 1f)
		{
			return 0f;
		}
		float num = Math.Abs(raw);
		int num2 = Math.Max(1, (int)Math.Round(num / ((num >= 30f) ? 120f : 1f)));
		float num3 = ((raw > 0f) ? 1f : (-1f));
		if (float.IsNaN(lines) || lines < 0.5f)
		{
			lines = 0.5f;
		}
		if (float.IsNaN(lineHeight) || lineHeight <= 0f)
		{
			return num3 * (float)num2 * 0.05f;
		}
		return num3 * (float)num2 * lines * lineHeight / scrollable;
	}
}
internal sealed class WheelDetector
{
	private int _samples;

	private float _maxAbs;

	public WheelScale Scale { get; private set; }

	public float MaxSeen => _maxAbs;

	public int Samples => _samples;

	public bool Observe(float x, float y)
	{
		if (Scale != WheelScale.Unknown)
		{
			return false;
		}
		if (!Rules.IsFinite(x) || !Rules.IsFinite(y))
		{
			return false;
		}
		float num = Math.Max(Math.Abs(x), Math.Abs(y));
		if (num <= 0f)
		{
			return false;
		}
		if (num > _maxAbs)
		{
			_maxAbs = num;
		}
		_samples++;
		if (num >= 50f)
		{
			Scale = WheelScale.Legacy120;
			return true;
		}
		if (_samples >= 8 && _maxAbs <= 10f)
		{
			Scale = WheelScale.Normalized;
			return true;
		}
		return false;
	}
}
internal static class Safe
{
	public const int ErrorBudget = 25;

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

	private static int _errors;

	private static bool _tripping;

	public static ManualLogSource Log;

	public static Action OnTrip;

	public static bool Tripped { get; private set; }

	public static int ErrorCount => _errors;

	public static void Run(string site, Action action)
	{
		if (Tripped || action == null)
		{
			return;
		}
		try
		{
			action();
		}
		catch (Exception e)
		{
			Report(site, e);
		}
	}

	public static T Run<T>(string site, Func<T> func, T fallback)
	{
		if (Tripped || func == null)
		{
			return fallback;
		}
		try
		{
			return func();
		}
		catch (Exception e)
		{
			Report(site, e);
			return fallback;
		}
	}

	public static void Report(string site, Exception e)
	{
		_errors++;
		try
		{
			if (Log != null)
			{
				if (LoggedSites.Add(site))
				{
					Log.LogError((object)("Error in " + site + " (handled, menus unaffected): " + e));
				}
				else
				{
					Log.LogDebug((object)("Repeat error in " + site + ": " + e.GetType().Name + ": " + e.Message));
				}
			}
		}
		catch
		{
		}
		if (_errors >= 25 && !Tripped && !_tripping)
		{
			Trip();
		}
	}

	private static void Trip()
	{
		_tripping = true;
		try
		{
			if (Log != null)
			{
				Log.LogError((object)("Too many errors (" + _errors + "). Restoring original scroll values and switching MenuScrollFix off until the game restarts."));
			}
			if (OnTrip != null)
			{
				OnTrip();
			}
		}
		catch (Exception ex)
		{
			try
			{
				if (Log != null)
				{
					Log.LogError((object)("Restore after error budget failed: " + ex));
				}
			}
			catch
			{
			}
		}
		finally
		{
			Tripped = true;
			_tripping = false;
		}
	}

	internal static void ResetForTests()
	{
		LoggedSites.Clear();
		_errors = 0;
		Tripped = false;
		_tripping = false;
		OnTrip = null;
	}
}
internal sealed class ScrollConfig
{
	public const float DefaultDeltaPerTick = 0.2f;

	public const float DefaultMultiplier = 0.15f;

	public const float DefaultMinSensitivity = 1f;

	public const float DefaultNormalized = 1f;

	public const float DefaultTerminalLines = 3f;

	public const float MinTerminalLines = 0.5f;

	public const float MaxTerminalLines = 40f;

	public ConfigEntry<bool> Enabled;

	public ConfigEntry<bool> OverrideScrollDeltaPerTick;

	public ConfigEntry<float> ScrollDeltaPerTick;

	public ConfigEntry<bool> ScaleScrollRectSensitivity;

	public ConfigEntry<float> ScrollSensitivityMultiplier;

	public ConfigEntry<float> MinScrollSensitivity;

	public ConfigEntry<bool> NormalizeListSpeeds;

	public ConfigEntry<float> NormalizedSensitivity;

	public ConfigEntry<bool> ExcludeTerminal;

	public ConfigEntry<bool> AutoDetectWheelScale;

	public ConfigEntry<bool> VerboseLogging;

	public ConfigEntry<bool> TerminalScrollFix;

	public ConfigEntry<float> TerminalScrollLines;

	public float DeltaPerTick => Rules.Sanitize(ScrollDeltaPerTick.Value, 0.01f, 50f, 0.2f);

	public float Multiplier => Rules.Sanitize(ScrollSensitivityMultiplier.Value, 0.01f, 10f, 0.15f);

	public float NormalizedValue => Rules.Sanitize(NormalizedSensitivity.Value, 0.01f, 100f, 1f);

	public bool ListsWanted
	{
		get
		{
			if (!NormalizeListSpeeds.Value)
			{
				return ScaleScrollRectSensitivity.Value;
			}
			return true;
		}
	}

	public float TerminalLines => Rules.Sanitize(TerminalScrollLines.Value, 0.5f, 40f, 3f);

	public float MinSensitivity => Rules.Sanitize(MinScrollSensitivity.Value, 0f, 1000f, 1f);

	public event Action Changed;

	public ScrollConfig(ConfigFile cfg)
	{
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Expected O, but got Unknown
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: Expected O, but got Unknown
		//IL_012e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0138: Expected O, but got Unknown
		//IL_0183: Unknown result type (might be due to invalid IL or missing references)
		//IL_018d: Expected O, but got Unknown
		//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e2: Expected O, but got Unknown
		Enabled = cfg.Bind<bool>("General", "Enabled", true, "Master switch. False puts every changed value back to the game's original.");
		ExcludeTerminal = cfg.Bind<bool>("General", "ExcludeTerminal", true, "Never touch scroll lists that belong to the ship terminal.");
		OverrideScrollDeltaPerTick = cfg.Bind<bool>("Primary fix (all menus)", "OverrideScrollDeltaPerTick", true, "Set the UI input module's scroll delta per wheel notch. This is the main fix and covers every menu at once.");
		ScrollDeltaPerTick = cfg.Bind<float>("Primary fix (all menus)", "ScrollDeltaPerTick", 0.2f, new ConfigDescription("Scroll amount per wheel notch sent to menus. The game's original is 6, which with Windows' 120-per-notch wheel jumps ~720 pixels. Lower = slower. Each 0.1 is about 12 pixels per notch at normal list sensitivity.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 50f), Array.Empty<object>()));
		AutoDetectWheelScale = cfg.Bind<bool>("Primary fix (all menus)", "AutoDetectWheelScale", true, "If the game ever starts reporting about 1 unit per notch (a future Unity fix), stop overriding so menus don't crawl.");
		ScaleScrollRectSensitivity = cfg.Bind<bool>("Secondary fix (per list)", "ScaleScrollRectSensitivity", false, "Also multiply every scroll list's own sensitivity. Only needed if one menu is still too fast with the primary fix.");
		ScrollSensitivityMultiplier = cfg.Bind<float>("Secondary fix (per list)", "ScrollSensitivityMultiplier", 0.15f, new ConfigDescription("Multiplier for each list's scrollSensitivity when the secondary fix is on. Always applied to the list's original value.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 10f), Array.Empty<object>()));
		MinScrollSensitivity = cfg.Bind<float>("Secondary fix (per list)", "MinScrollSensitivity", 1f, new ConfigDescription("Floor for a list's sensitivity after scaling (never raises a list that started lower).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1000f), Array.Empty<object>()));
		NormalizeListSpeeds = cfg.Bind<bool>("Secondary fix (per list)", "NormalizeListSpeeds", true, "Give every scroll list the same speed. The game sets each list differently (keybinds 0.05, credits 0.1, most lists 1), so once the wheel is slowed some menus crawl. When on, this replaces the multiplier and floor below.");
		NormalizedSensitivity = cfg.Bind<float>("Secondary fix (per list)", "NormalizedSensitivity", 1f, new ConfigDescription("Sensitivity every list gets when NormalizeListSpeeds is on. 1 matches LethalConfig's lists. Higher = faster.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 100f), Array.Empty<object>()));
		TerminalScrollFix = cfg.Bind<bool>("Terminal", "TerminalScrollFix", true, "Mouse wheel scrolls the ship terminal a few lines per notch instead of jumping most of the page (vanilla moves the scrollbar by wheel/3, and the wheel reports ~120 per notch).");
		TerminalScrollLines = cfg.Bind<float>("Terminal", "TerminalScrollLines", 3f, new ConfigDescription("Lines of terminal text per mouse wheel notch when TerminalScrollFix is on. Applies immediately.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 40f), Array.Empty<object>()));
		VerboseLogging = cfg.Bind<bool>("Debug", "VerboseLogging", false, "Log every input module and scroll list changed, with its hierarchy path and before/after values.");
		ConfigEntryBase[] array = (ConfigEntryBase[])(object)new ConfigEntryBase[10]
		{
			(ConfigEntryBase)Enabled,
			(ConfigEntryBase)ExcludeTerminal,
			(ConfigEntryBase)OverrideScrollDeltaPerTick,
			(ConfigEntryBase)ScrollDeltaPerTick,
			(ConfigEntryBase)AutoDetectWheelScale,
			(ConfigEntryBase)ScaleScrollRectSensitivity,
			(ConfigEntryBase)ScrollSensitivityMultiplier,
			(ConfigEntryBase)MinScrollSensitivity,
			(ConfigEntryBase)NormalizeListSpeeds,
			(ConfigEntryBase)NormalizedSensitivity
		};
		foreach (ConfigEntryBase entry in array)
		{
			Subscribe(entry);
		}
	}

	private void Subscribe(ConfigEntryBase entry)
	{
		if (entry is ConfigEntry<bool> val)
		{
			val.SettingChanged += delegate
			{
				Raise();
			};
		}
		else if (entry is ConfigEntry<float> val2)
		{
			val2.SettingChanged += delegate
			{
				Raise();
			};
		}
	}

	private void Raise()
	{
		Action h = this.Changed;
		if (h != null)
		{
			Safe.Run("config change", delegate
			{
				h();
			});
		}
	}
}