Decompiled source of WiresNativeCursorSupport v0.4.3

WiresNativeCursorSupport.dll

Decompiled a week ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;
using Valheim.SettingsGui;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("WiresNativeCursorSupport")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+c272e5e8db178698fe0ae2d6e1b0d067036cf058")]
[assembly: AssemblyProduct("WiresNativeCursorSupport")]
[assembly: AssemblyTitle("WiresNativeCursorSupport")]
[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 WiresNativeCursorSupport
{
	internal static class AccessibilityIntegration
	{
		private static readonly FieldInfo ToggleBlockField = AccessTools.Field(typeof(AccessibilitySettings), "m_toggleBlockToggle");

		private static AccessibilitySettings _owner;

		private static Toggle _toggle;

		private static bool _openedValue;

		internal static void Initialize(AccessibilitySettings settings)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Expected O, but got Unknown
			if ((Object)(object)settings == (Object)null || ToggleBlockField == null)
			{
				return;
			}
			object? value = ToggleBlockField.GetValue(settings);
			Toggle val = (Toggle)((value is Toggle) ? value : null);
			if ((Object)(object)val == (Object)null || (Object)(object)((Component)val).transform.parent == (Object)null)
			{
				return;
			}
			if ((Object)(object)_owner != (Object)(object)settings || (Object)(object)_toggle == (Object)null)
			{
				_owner = settings;
				_toggle = FindOrCreateToggle(val);
			}
			if (!((Object)(object)_toggle == (Object)null))
			{
				_openedValue = Plugin.RuntimeEnabled;
				_toggle.SetIsOnWithoutNotify(_openedValue);
				_toggle.onValueChanged = new ToggleEvent();
				((UnityEvent<bool>)(object)_toggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool runtimeEnabled)
				{
					Plugin.SetRuntimeEnabled(runtimeEnabled);
				});
				SetLabel(_toggle);
			}
		}

		private static Toggle FindOrCreateToggle(Toggle source)
		{
			Transform parent = ((Component)source).transform.parent;
			Transform val = parent.Find("WireNativeCursor");
			if ((Object)(object)val != (Object)null)
			{
				return ((Component)val).GetComponent<Toggle>();
			}
			GameObject obj = Object.Instantiate<GameObject>(((Component)source).gameObject, parent, false);
			((Object)obj).name = "WireNativeCursor";
			obj.transform.SetSiblingIndex(((Component)source).transform.GetSiblingIndex() + 1);
			Toggle component = obj.GetComponent<Toggle>();
			if ((Object)(object)component != (Object)null)
			{
				SetLabel(component);
			}
			return component;
		}

		private static void SetLabel(Toggle toggle)
		{
			if (!((Object)(object)toggle == (Object)null))
			{
				Transform obj = ((Component)toggle).transform.Find("Label");
				TMP_Text val = ((obj != null) ? ((Component)obj).GetComponent<TMP_Text>() : null);
				if ((Object)(object)val == (Object)null)
				{
					val = ((Component)toggle).GetComponentInChildren<TMP_Text>(true);
				}
				if ((Object)(object)val != (Object)null)
				{
					val.text = "Native System Cursor";
				}
			}
		}

		internal static void Save()
		{
			if (!((Object)(object)_toggle == (Object)null))
			{
				bool isOn = _toggle.isOn;
				PlayerPrefs.SetInt("WireNativeCursorSupport", isOn ? 1 : 0);
				PlayerPrefs.Save();
				_openedValue = isOn;
				Plugin.SetRuntimeEnabled(isOn);
			}
		}

		internal static void Cancel()
		{
			if ((Object)(object)_toggle != (Object)null)
			{
				_toggle.SetIsOnWithoutNotify(_openedValue);
			}
			Plugin.SetRuntimeEnabled(_openedValue);
		}

		internal static void ConfigureNavigation(AccessibilitySettings settings, Button okButton)
		{
			if (!((Object)(object)settings == (Object)null) && !((Object)(object)okButton == (Object)null) && !((Object)(object)_toggle == (Object)null) && !(ToggleBlockField == null))
			{
				object? value = ToggleBlockField.GetValue(settings);
				Toggle val = (Toggle)((value is Toggle) ? value : null);
				if (!((Object)(object)val == (Object)null))
				{
					GuiUtils.SetNavigationDown((Selectable)(object)val, (Selectable)(object)_toggle);
					GuiUtils.SetNavigationUp((Selectable)(object)_toggle, (Selectable)(object)val);
					GuiUtils.SetNavigationDown((Selectable)(object)_toggle, (Selectable)(object)okButton);
					GuiUtils.SetNavigationUp((Selectable)(object)okButton, (Selectable)(object)_toggle);
				}
			}
		}
	}
	[HarmonyPatch(typeof(AccessibilitySettings), "Initialize")]
	internal static class AccessibilityInitializePatch
	{
		[HarmonyPostfix]
		private static void Postfix(AccessibilitySettings __instance)
		{
			AccessibilityIntegration.Initialize(__instance);
		}
	}
	[HarmonyPatch(typeof(AccessibilitySettings), "OnOkAsync")]
	internal static class AccessibilityOkPatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			AccessibilityIntegration.Save();
		}
	}
	[HarmonyPatch(typeof(AccessibilitySettings), "OnBack")]
	internal static class AccessibilityBackPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			AccessibilityIntegration.Cancel();
		}
	}
	[HarmonyPatch(typeof(AccessibilitySettings), "OnTabOpen")]
	internal static class AccessibilityTabOpenPatch
	{
		[HarmonyPostfix]
		private static void Postfix(AccessibilitySettings __instance, Button okButton)
		{
			AccessibilityIntegration.ConfigureNavigation(__instance, okButton);
		}
	}
	internal static class CursorEvents
	{
		[HarmonyPatch(typeof(UIInputHandler), "OnPointerEnter")]
		private static class HandlerEnter
		{
			private static void Postfix(UIInputHandler __instance)
			{
				Hover((Object)(object)__instance, ForHandler(__instance));
			}
		}

		[HarmonyPatch(typeof(UIInputHandler), "OnPointerExit")]
		private static class HandlerExit
		{
			private static void Postfix(UIInputHandler __instance)
			{
				Leave((Object)(object)__instance);
			}
		}

		[HarmonyPatch(typeof(Selectable), "OnPointerEnter")]
		private static class SelectableEnter
		{
			private static void Postfix(Selectable __instance)
			{
				if (IsTextBox(__instance))
				{
					Hover((Object)(object)__instance, NativeCursorKind.Text);
				}
			}
		}

		[HarmonyPatch(typeof(Selectable), "OnPointerExit")]
		private static class SelectableExit
		{
			private static void Postfix(Selectable __instance)
			{
				Leave((Object)(object)__instance);
			}
		}

		[HarmonyPatch(typeof(Selectable), "OnDisable")]
		private static class SelectableGone
		{
			private static void Postfix(Selectable __instance)
			{
				Leave((Object)(object)__instance);
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "SetupDragItem")]
		private static class Drag
		{
			private static void Postfix(InventoryGui __instance)
			{
				Dragging = DragItem.Invoke(__instance) != null;
				Object s_hover = CursorEvents.s_hover;
				UIInputHandler val = (UIInputHandler)(object)((s_hover is UIInputHandler) ? s_hover : null);
				if (val != null && (Object)(object)val != (Object)null)
				{
					s_hoverKind = ForHandler(val);
				}
				SystemCursor.Refresh();
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "OnCraftPressed")]
		private static class CraftStart
		{
			private static void Postfix(InventoryGui __instance)
			{
				Crafting = CraftTimer.Invoke(__instance) >= 0f;
				SystemCursor.Refresh();
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
		private static class CraftDone
		{
			private static void Postfix()
			{
				Crafting = false;
				SystemCursor.Refresh();
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "OnCraftCancelPressed")]
		private static class CraftCancel
		{
			private static void Postfix()
			{
				Crafting = false;
				SystemCursor.Refresh();
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "Hide")]
		private static class InventoryClosed
		{
			private static void Postfix()
			{
				Crafting = false;
				if (s_hover is UIInputHandler)
				{
					s_hover = null;
				}
				SystemCursor.Refresh();
			}
		}

		[HarmonyPatch(typeof(Minimap), "OnMapLeftDown")]
		private static class MapDown
		{
			private static void Postfix()
			{
				MapDrag = true;
				SystemCursor.Refresh();
			}
		}

		[HarmonyPatch(typeof(Minimap), "OnMapLeftUp")]
		private static class MapUp
		{
			private static void Postfix()
			{
				MapDrag = false;
				SystemCursor.Refresh();
			}
		}

		[HarmonyPatch(typeof(FejdStartup), "Awake")]
		private static class Loading
		{
			private static void Postfix(FejdStartup __instance)
			{
				SystemCursor.Refresh();
				Mark(__instance.m_loading);
				Mark(__instance.m_pleaseWait);
			}

			private static void Mark(GameObject go)
			{
				if ((Object)(object)go != (Object)null && (Object)(object)go.GetComponent<WaitMarker>() == (Object)null)
				{
					go.AddComponent<WaitMarker>();
				}
			}
		}

		internal static int Waiting;

		internal static bool Crafting;

		internal static bool Dragging;

		internal static bool MapDrag;

		private static Object s_hover;

		private static NativeCursorKind s_hoverKind;

		private static readonly FieldRef<InventoryGui, ItemData> DragItem = AccessTools.FieldRefAccess<InventoryGui, ItemData>("m_dragItem");

		private static readonly FieldRef<InventoryGui, float> CraftTimer = AccessTools.FieldRefAccess<InventoryGui, float>("m_craftTimer");

		internal static NativeCursorKind Kind
		{
			get
			{
				if (Waiting > 0)
				{
					return NativeCursorKind.Wait;
				}
				if (Crafting)
				{
					return NativeCursorKind.Working;
				}
				if (Dragging || MapDrag)
				{
					return NativeCursorKind.Move;
				}
				if (!(s_hover != (Object)null))
				{
					return NativeCursorKind.Arrow;
				}
				return s_hoverKind;
			}
		}

		internal static void Hover(Object over, NativeCursorKind kind)
		{
			s_hover = over;
			s_hoverKind = kind;
			SystemCursor.Refresh();
		}

		internal static void Leave(Object over)
		{
			if (!(s_hover != over))
			{
				s_hover = null;
				SystemCursor.Refresh();
			}
		}

		internal static void Reset()
		{
			Waiting = 0;
			Crafting = (Dragging = (MapDrag = false));
			s_hover = null;
		}

		private static NativeCursorKind ForHandler(UIInputHandler h)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			InventoryElement componentInParent = ((Component)h).GetComponentInParent<InventoryElement>();
			if ((Object)(object)componentInParent == (Object)null)
			{
				return NativeCursorKind.Arrow;
			}
			InventoryGrid componentInParent2 = ((Component)componentInParent).GetComponentInParent<InventoryGrid>();
			Inventory val = (((Object)(object)componentInParent2 != (Object)null) ? componentInParent2.GetInventory() : null);
			if (val == null || val.GetItemAt(componentInParent.Position.x, componentInParent.Position.y) == null)
			{
				return NativeCursorKind.Arrow;
			}
			return NativeCursorKind.Hand;
		}

		private static bool IsTextBox(Selectable s)
		{
			if (s is TMP_InputField || s is InputField)
			{
				return s.IsInteractable();
			}
			return false;
		}
	}
	internal sealed class WaitMarker : MonoBehaviour
	{
		private void OnEnable()
		{
			CursorEvents.Waiting++;
			SystemCursor.Refresh();
		}

		private void OnDisable()
		{
			if (CursorEvents.Waiting > 0)
			{
				CursorEvents.Waiting--;
			}
			SystemCursor.Refresh();
		}
	}
	internal sealed class PointerHand : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
	{
		public void OnPointerEnter(PointerEventData e)
		{
			CursorEvents.Hover((Object)(object)this, NativeCursorKind.Hand);
		}

		public void OnPointerExit(PointerEventData e)
		{
			CursorEvents.Leave((Object)(object)this);
		}

		private void OnDisable()
		{
			CursorEvents.Leave((Object)(object)this);
		}
	}
	internal static class DesktopCursorSize
	{
		internal static int Preferred()
		{
			int num = Parse(Environment.GetEnvironmentVariable("XCURSOR_SIZE"));
			if (num > 0)
			{
				return num;
			}
			string text = Environment.GetEnvironmentVariable("HOME");
			if (string.IsNullOrEmpty(text))
			{
				return 0;
			}
			if (text[0] == '/')
			{
				text = "Z:" + text.Replace('/', '\\');
			}
			if (!Directory.Exists(text))
			{
				return 0;
			}
			int num2 = ReadSetting(Path.Combine(text, ".config", "kcminputrc"), "cursorSize");
			if (num2 > 0)
			{
				return num2;
			}
			return ReadSetting(Path.Combine(text, ".config", "gtk-3.0", "settings.ini"), "gtk-cursor-theme-size");
		}

		private static int Parse(string value)
		{
			if (!int.TryParse(value, out var result) || result < 8 || result > 256)
			{
				return 0;
			}
			return result;
		}

		private static int ReadSetting(string path, string key)
		{
			try
			{
				if (!File.Exists(path))
				{
					return 0;
				}
				string[] array = File.ReadAllLines(path);
				for (int i = 0; i < array.Length; i++)
				{
					string text = array[i].Trim();
					int num = text.IndexOf('=');
					if (num > 0 && string.Equals(text.Substring(0, num).Trim(), key, StringComparison.OrdinalIgnoreCase))
					{
						return Parse(text.Substring(num + 1).Trim());
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogDebug((object)("Cursor size configuration unavailable: " + ex.Message));
				}
			}
			return 0;
		}

		internal static Texture2D Resize(Texture2D input, int target, ref Vector2 hotspot, int nominal = 0)
		{
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Expected O, but got Unknown
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)input == (Object)null || target <= 0)
			{
				return input;
			}
			int num = ((nominal > 0) ? nominal : Math.Max(((Texture)input).width, ((Texture)input).height));
			if (num == target)
			{
				return input;
			}
			float num2 = (float)target / (float)num;
			int num3 = Mathf.Clamp(Mathf.RoundToInt((float)((Texture)input).width * num2), 1, 256);
			int num4 = Mathf.Clamp(Mathf.RoundToInt((float)((Texture)input).height * num2), 1, 256);
			Color32[] pixels = input.GetPixels32();
			Color32[] array = (Color32[])(object)new Color32[num3 * num4];
			for (int i = 0; i < num4; i++)
			{
				int num5 = Mathf.Min(((Texture)input).height - 1, i * ((Texture)input).height / num4);
				for (int j = 0; j < num3; j++)
				{
					int num6 = Mathf.Min(((Texture)input).width - 1, j * ((Texture)input).width / num3);
					array[i * num3 + j] = pixels[num5 * ((Texture)input).width + num6];
				}
			}
			Texture2D val = new Texture2D(num3, num4, (TextureFormat)4, false)
			{
				name = ((Object)input).name + "_desktop_size",
				hideFlags = (HideFlags)61,
				filterMode = (FilterMode)0
			};
			val.SetPixels32(array);
			val.Apply(false, false);
			hotspot = new Vector2(hotspot.x * (float)num3 / (float)((Texture)input).width, hotspot.y * (float)num4 / (float)((Texture)input).height);
			Object.Destroy((Object)(object)input);
			return val;
		}
	}
	internal static class LinuxSystemCursor
	{
		private const string X11 = "libX11.so.6";

		private const string Xcursor = "libXcursor.so.1";

		private static readonly string[][] Names = new string[9][]
		{
			new string[3] { "left_ptr", "default", "arrow" },
			new string[3] { "pointer", "hand2", "hand1" },
			new string[2] { "text", "xterm" },
			new string[3] { "grabbing", "closedhand", "fleur" },
			new string[2] { "ew-resize", "sb_h_double_arrow" },
			new string[2] { "ns-resize", "sb_v_double_arrow" },
			new string[2] { "crosshair", "cross" },
			new string[3] { "progress", "left_ptr_watch", "watch" },
			new string[2] { "wait", "watch" }
		};

		private static IntPtr s_display;

		private static IntPtr[] s_cursors;

		private static IntPtr s_window;

		private static int ResolveSize(IntPtr display)
		{
			int num = 0;
			try
			{
				num = XcursorGetDefaultSize(display);
			}
			catch (EntryPointNotFoundException)
			{
			}
			int num2 = DesktopCursorSize.Preferred();
			if (num2 > 0)
			{
				return num2;
			}
			if (num < 16 || num > 256)
			{
				return 24;
			}
			return num;
		}

		private static IntPtr LoadSizedCursor(IntPtr display, string name, string theme, int size)
		{
			IntPtr intPtr = XcursorLibraryLoadImages(name, theme, size);
			if (intPtr == IntPtr.Zero)
			{
				return IntPtr.Zero;
			}
			try
			{
				return XcursorImagesLoadCursor(display, intPtr);
			}
			finally
			{
				XcursorImagesDestroy(intPtr);
			}
		}

		internal static bool Initialize()
		{
			if (s_display != IntPtr.Zero)
			{
				return true;
			}
			try
			{
				IntPtr intPtr = XOpenDisplay(IntPtr.Zero);
				if (intPtr == IntPtr.Zero)
				{
					ManualLogSource log = Plugin.Log;
					if (log != null)
					{
						log.LogWarning((object)"Native Linux cursor requires an X11/XWayland window. Wayland-native cursor support is unavailable.");
					}
					return false;
				}
				int size = ResolveSize(intPtr);
				string text = Environment.GetEnvironmentVariable("XCURSOR_THEME");
				if (string.IsNullOrEmpty(text))
				{
					IntPtr intPtr2 = XcursorGetTheme(intPtr);
					if (intPtr2 != IntPtr.Zero)
					{
						text = Marshal.PtrToStringAnsi(intPtr2);
					}
				}
				IntPtr[] array = new IntPtr[Names.Length];
				for (int i = 0; i < Names.Length; i++)
				{
					string[] array2 = Names[i];
					foreach (string name in array2)
					{
						array[i] = LoadSizedCursor(intPtr, name, text, size);
						if (array[i] != IntPtr.Zero)
						{
							break;
						}
					}
				}
				if (array[0] == IntPtr.Zero)
				{
					XCloseDisplay(intPtr);
					return false;
				}
				for (int k = 1; k < array.Length; k++)
				{
					if (array[k] == IntPtr.Zero)
					{
						array[k] = array[0];
					}
				}
				s_display = intPtr;
				s_cursors = array;
				ManualLogSource log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogInfo((object)("Native X11 system cursor handles enabled at " + size + "px (theme=" + (text ?? "default") + ")."));
				}
				return true;
			}
			catch (Exception ex) when (ex is DllNotFoundException || ex is EntryPointNotFoundException)
			{
				ManualLogSource log3 = Plugin.Log;
				if (log3 != null)
				{
					log3.LogWarning((object)("Native Linux/X11 cursor APIs unavailable: " + ex.Message));
				}
				return false;
			}
		}

		internal static void Apply(NativeCursorKind kind)
		{
			if (s_display == IntPtr.Zero)
			{
				return;
			}
			try
			{
				if (s_window == IntPtr.Zero)
				{
					XGetInputFocus(s_display, out var focus, out var _);
					if (focus == IntPtr.Zero || focus == new IntPtr(1))
					{
						return;
					}
					IntPtr intPtr = focus;
					for (int i = 0; i < 10; i++)
					{
						if (!(intPtr != IntPtr.Zero))
						{
							break;
						}
						if (XFetchName(s_display, intPtr, out var name) != 0)
						{
							try
							{
								string text = Marshal.PtrToStringAnsi(name);
								if (!string.IsNullOrEmpty(text) && text.IndexOf("Valheim", StringComparison.OrdinalIgnoreCase) >= 0)
								{
									s_window = intPtr;
									break;
								}
							}
							finally
							{
								if (name != IntPtr.Zero)
								{
									XFree(name);
								}
							}
						}
						if (XQueryTree(s_display, intPtr, out var root, out var parent, out var children, out var _) == 0)
						{
							break;
						}
						if (children != IntPtr.Zero)
						{
							XFree(children);
						}
						if (parent == intPtr || parent == root)
						{
							break;
						}
						intPtr = parent;
					}
				}
				if (!(s_window == IntPtr.Zero))
				{
					XDefineCursor(s_display, s_window, s_cursors[(int)kind]);
					XFlush(s_display);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Couldn't apply native X11 cursor: " + ex.Message));
				}
			}
		}

		internal static void Shutdown()
		{
			if (s_display == IntPtr.Zero)
			{
				return;
			}
			if (s_window != IntPtr.Zero)
			{
				XUndefineCursor(s_display, s_window);
				XFlush(s_display);
			}
			if (s_cursors != null)
			{
				for (int i = 0; i < s_cursors.Length; i++)
				{
					IntPtr intPtr = s_cursors[i];
					if (intPtr == IntPtr.Zero)
					{
						continue;
					}
					bool flag = false;
					for (int j = 0; j < i; j++)
					{
						if (s_cursors[j] == intPtr)
						{
							flag = true;
							break;
						}
					}
					if (!flag)
					{
						XFreeCursor(s_display, intPtr);
					}
				}
			}
			XCloseDisplay(s_display);
			s_display = (s_window = IntPtr.Zero);
			s_cursors = null;
		}

		[DllImport("libX11.so.6")]
		private static extern IntPtr XOpenDisplay(IntPtr display);

		[DllImport("libX11.so.6")]
		private static extern int XCloseDisplay(IntPtr display);

		[DllImport("libX11.so.6")]
		private static extern int XGetInputFocus(IntPtr display, out IntPtr focus, out int revert);

		[DllImport("libX11.so.6")]
		private static extern int XFetchName(IntPtr display, IntPtr window, out IntPtr name);

		[DllImport("libX11.so.6")]
		private static extern int XQueryTree(IntPtr display, IntPtr window, out IntPtr root, out IntPtr parent, out IntPtr children, out uint count);

		[DllImport("libX11.so.6")]
		private static extern int XDefineCursor(IntPtr display, IntPtr window, IntPtr cursor);

		[DllImport("libX11.so.6")]
		private static extern int XUndefineCursor(IntPtr display, IntPtr window);

		[DllImport("libX11.so.6")]
		private static extern int XFlush(IntPtr display);

		[DllImport("libX11.so.6")]
		private static extern int XFree(IntPtr ptr);

		[DllImport("libX11.so.6")]
		private static extern int XFreeCursor(IntPtr display, IntPtr cursor);

		[DllImport("libXcursor.so.1")]
		private static extern int XcursorGetDefaultSize(IntPtr display);

		[DllImport("libXcursor.so.1")]
		private static extern IntPtr XcursorGetTheme(IntPtr display);

		[DllImport("libXcursor.so.1", CharSet = CharSet.Ansi)]
		private static extern IntPtr XcursorLibraryLoadImages(string name, string theme, int size);

		[DllImport("libXcursor.so.1")]
		private static extern IntPtr XcursorImagesLoadCursor(IntPtr display, IntPtr images);

		[DllImport("libXcursor.so.1")]
		private static extern void XcursorImagesDestroy(IntPtr images);
	}
	internal static class MacCursors
	{
		private const string ObjC = "/usr/lib/libobjc.A.dylib";

		internal static bool InitializeNative()
		{
			return Class("NSCursor") != IntPtr.Zero;
		}

		internal static void ApplyNative(NativeCursorKind kind)
		{
			IntPtr intPtr = Cursor(kind);
			if (intPtr == IntPtr.Zero)
			{
				intPtr = Cursor(NativeCursorKind.Arrow);
			}
			if (intPtr != IntPtr.Zero)
			{
				msgSend(intPtr, Sel("set"));
			}
		}

		internal static void ShutdownNative()
		{
			ApplyNative(NativeCursorKind.Arrow);
		}

		private static IntPtr Cursor(NativeCursorKind kind)
		{
			return kind switch
			{
				NativeCursorKind.Arrow => Named("arrowCursor"), 
				NativeCursorKind.Hand => Named("pointingHandCursor"), 
				NativeCursorKind.Text => Named("IBeamCursor"), 
				NativeCursorKind.Move => Named("closedHandCursor", "openHandCursor"), 
				NativeCursorKind.ResizeHorizontal => Named("resizeLeftRightCursor"), 
				NativeCursorKind.ResizeVertical => Named("resizeUpDownCursor"), 
				NativeCursorKind.Crosshair => Named("crosshairCursor"), 
				NativeCursorKind.Working => Named("busyButClickableCursor", "arrowCursor"), 
				NativeCursorKind.Wait => Named("busyButClickableCursor", "arrowCursor"), 
				_ => Named("arrowCursor"), 
			};
		}

		private static IntPtr Named(params string[] names)
		{
			IntPtr intPtr = Class("NSCursor");
			if (intPtr == IntPtr.Zero)
			{
				return IntPtr.Zero;
			}
			for (int i = 0; i < names.Length; i++)
			{
				IntPtr intPtr2 = Sel(names[i]);
				if (intPtr2 != IntPtr.Zero && msgSend_bool(intPtr, Sel("respondsToSelector:"), intPtr2))
				{
					IntPtr intPtr3 = msgSend(intPtr, intPtr2);
					if (intPtr3 != IntPtr.Zero)
					{
						return intPtr3;
					}
				}
			}
			return IntPtr.Zero;
		}

		private static IntPtr Class(string name)
		{
			return objc_getClass(name);
		}

		private static IntPtr Sel(string name)
		{
			return sel_registerName(name);
		}

		[DllImport("/usr/lib/libobjc.A.dylib")]
		private static extern IntPtr objc_getClass(string name);

		[DllImport("/usr/lib/libobjc.A.dylib")]
		private static extern IntPtr sel_registerName(string name);

		[DllImport("/usr/lib/libobjc.A.dylib", EntryPoint = "objc_msgSend")]
		private static extern IntPtr msgSend(IntPtr receiver, IntPtr selector);

		[DllImport("/usr/lib/libobjc.A.dylib", EntryPoint = "objc_msgSend")]
		[return: MarshalAs(UnmanagedType.I1)]
		private static extern bool msgSend_bool(IntPtr receiver, IntPtr selector, IntPtr arg);
	}
	public static class NativeCursorApi
	{
		public static void SetHand(GameObject go)
		{
			if ((Object)(object)go != (Object)null && (Object)(object)go.GetComponent<PointerHand>() == (Object)null)
			{
				go.AddComponent<PointerHand>();
			}
		}

		public static void Clear(GameObject go)
		{
			PointerHand pointerHand = (((Object)(object)go != (Object)null) ? go.GetComponent<PointerHand>() : null);
			if ((Object)(object)pointerHand != (Object)null)
			{
				Object.Destroy((Object)(object)pointerHand);
			}
		}
	}
	[BepInPlugin("wire.valheim.nativecursorsupport", "Wire's Native Cursor", "0.4.3")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Guid = "wire.valheim.nativecursorsupport";

		public const string Name = "Wire's Native Cursor";

		public const string Version = "0.4.3";

		internal const string PrefKey = "WireNativeCursorSupport";

		internal static Plugin Instance;

		internal static ManualLogSource Log;

		private Harmony _harmony;

		internal static bool RuntimeEnabled { get; private set; }

		private void Awake()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			RuntimeEnabled = PlayerPrefs.GetInt("WireNativeCursorSupport", 1) == 1;
			_harmony = new Harmony("wire.valheim.nativecursorsupport");
			Type[] nestedTypes = typeof(CursorEvents).GetNestedTypes(BindingFlags.NonPublic);
			foreach (Type type in nestedTypes)
			{
				try
				{
					_harmony.CreateClassProcessor(type).Patch();
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Cursor change not hooked (" + type.Name + "): " + ex.Message));
				}
			}
			try
			{
				RequireMethod(typeof(AccessibilitySettings), "Initialize");
				RequireMethod(typeof(AccessibilitySettings), "OnOkAsync");
				RequireMethod(typeof(AccessibilitySettings), "OnBack");
				RequireMethod(typeof(AccessibilitySettings), "OnTabOpen");
				if (AccessTools.Field(typeof(AccessibilitySettings), "m_toggleBlockToggle") == null)
				{
					throw new MissingFieldException(typeof(AccessibilitySettings).FullName, "m_toggleBlockToggle");
				}
				_harmony.CreateClassProcessor(typeof(AccessibilityInitializePatch)).Patch();
				_harmony.CreateClassProcessor(typeof(AccessibilityOkPatch)).Patch();
				_harmony.CreateClassProcessor(typeof(AccessibilityBackPatch)).Patch();
				_harmony.CreateClassProcessor(typeof(AccessibilityTabOpenPatch)).Patch();
			}
			catch (Exception ex2)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("No row in the Accessibility settings: " + ex2.Message));
			}
			SystemCursor.Apply(RuntimeEnabled);
		}

		private void OnDestroy()
		{
			SystemCursor.Shutdown();
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			_harmony = null;
			Instance = null;
		}

		internal static void SetRuntimeEnabled(bool enabled)
		{
			if (enabled != RuntimeEnabled)
			{
				RuntimeEnabled = enabled;
				SystemCursor.Apply(enabled);
			}
		}

		private static void RequireMethod(Type type, string name)
		{
			if (AccessTools.DeclaredMethod(type, name, (Type[])null, (Type[])null) == null)
			{
				throw new MissingMethodException(type.FullName, name);
			}
		}
	}
	internal enum NativeCursorKind
	{
		Arrow,
		Hand,
		Text,
		Move,
		ResizeHorizontal,
		ResizeVertical,
		Crosshair,
		Working,
		Wait
	}
	internal static class SystemCursor
	{
		private static bool s_enabled;

		private static bool s_active;

		private static NativeCursorKind? s_current;

		internal static void Apply(bool enabled)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			s_enabled = enabled;
			if (!enabled)
			{
				ShutdownBackend();
				Cursor.SetCursor((Texture2D)null, Vector2.zero, (CursorMode)0);
			}
			else
			{
				Refresh();
			}
		}

		internal static void Refresh()
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Invalid comparison between Unknown and I4
			//IL_0029: 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)
			//IL_006d: Invalid comparison between Unknown and I4
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Invalid comparison between Unknown and I4
			if (!s_enabled)
			{
				return;
			}
			if (!s_active)
			{
				if (!InitializeBackend())
				{
					return;
				}
				s_active = true;
				s_current = null;
				Cursor.SetCursor((Texture2D)null, Vector2.zero, (CursorMode)0);
			}
			NativeCursorKind kind = CursorEvents.Kind;
			if (s_current != kind)
			{
				if ((int)Application.platform == 2)
				{
					WindowsNativeCursor.Apply(kind);
				}
				else if ((int)Application.platform == 1)
				{
					MacCursors.ApplyNative(kind);
				}
				else if ((int)Application.platform == 13)
				{
					LinuxSystemCursor.Apply(kind);
				}
				s_current = kind;
			}
		}

		private static bool InitializeBackend()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Invalid comparison between Unknown and I4
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if ((int)Application.platform == 2)
			{
				return WindowsNativeCursor.Initialize();
			}
			if ((int)Application.platform == 1)
			{
				return MacCursors.InitializeNative();
			}
			if ((int)Application.platform == 13)
			{
				return LinuxSystemCursor.Initialize();
			}
			ManualLogSource log = Plugin.Log;
			if (log != null)
			{
				log.LogWarning((object)("No native cursor API for " + ((object)Application.platform/*cast due to .constrained prefix*/).ToString()));
			}
			return false;
		}

		private static void ShutdownBackend()
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Invalid comparison between Unknown and I4
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			if (s_active)
			{
				if ((int)Application.platform == 2)
				{
					WindowsNativeCursor.Shutdown();
				}
				else if ((int)Application.platform == 1)
				{
					MacCursors.ShutdownNative();
				}
				else if ((int)Application.platform == 13)
				{
					LinuxSystemCursor.Shutdown();
				}
				s_active = false;
				s_current = null;
			}
		}

		internal static void Shutdown()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			s_enabled = false;
			ShutdownBackend();
			Cursor.SetCursor((Texture2D)null, Vector2.zero, (CursorMode)0);
		}
	}
	internal static class WindowsNativeCursor
	{
		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		private delegate IntPtr WindowProc(IntPtr hwnd, uint msg, IntPtr wp, IntPtr lp);

		private const int WM_SETCURSOR = 32;

		private const int WM_MOUSEMOVE = 512;

		private const int WM_LBUTTONUP = 514;

		private const int WM_RBUTTONUP = 517;

		private const int WM_MBUTTONUP = 520;

		private const int WM_XBUTTONUP = 524;

		private const int WM_NCDESTROY = 130;

		private const int HTCLIENT = 1;

		private const int GWLP_WNDPROC = -4;

		private const uint IMAGE_CURSOR = 2u;

		private const uint LR_COPYFROMRESOURCE = 16384u;

		private static readonly int[] Ids = new int[9] { 32512, 32649, 32513, 32646, 32644, 32645, 32515, 32650, 32514 };

		private static IntPtr s_hwnd;

		private static IntPtr s_previous;

		private static IntPtr[] s_handles;

		private static bool[] s_owned;

		private static WindowProc s_hook;

		private static IntPtr s_hookPointer;

		private static bool s_hooked;

		private static bool s_enabled;

		private static NativeCursorKind s_kind;

		private static int ProtonCursorSize()
		{
			return DesktopCursorSize.Preferred();
		}

		internal static bool Initialize()
		{
			if (s_hooked)
			{
				s_enabled = true;
				return true;
			}
			IntPtr activeWindow = GetActiveWindow();
			if (activeWindow == IntPtr.Zero)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"Windows cursor: game window not ready; will retry on a cursor event.");
				}
				return false;
			}
			GetWindowThreadProcessId(activeWindow, out var processId);
			if (processId != (uint)Process.GetCurrentProcess().Id)
			{
				return false;
			}
			IntPtr[] array = new IntPtr[Ids.Length];
			bool[] array2 = new bool[Ids.Length];
			int num = ProtonCursorSize();
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = LoadCursor(IntPtr.Zero, new IntPtr(Ids[i]));
				if (array[i] == IntPtr.Zero)
				{
					array[i] = LoadCursor(IntPtr.Zero, new IntPtr(Ids[0]));
				}
				if (num > 0 && array[i] != IntPtr.Zero)
				{
					IntPtr intPtr = CopyImage(array[i], 2u, num, num, 16384u);
					if (intPtr != IntPtr.Zero)
					{
						array[i] = intPtr;
						array2[i] = true;
					}
				}
			}
			if (array[0] == IntPtr.Zero)
			{
				ManualLogSource log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)"Windows native cursor: could not load system arrow.");
				}
				return false;
			}
			s_hook = WndProc;
			s_hookPointer = Marshal.GetFunctionPointerForDelegate(s_hook);
			SetLastError(0);
			IntPtr intPtr2 = SetWindowLongPtr(activeWindow, -4, s_hookPointer);
			int lastWin32Error = Marshal.GetLastWin32Error();
			if (intPtr2 == IntPtr.Zero && lastWin32Error != 0)
			{
				ManualLogSource log3 = Plugin.Log;
				if (log3 != null)
				{
					log3.LogWarning((object)("Couldn't install native window cursor handler: " + lastWin32Error));
				}
				s_hook = null;
				s_hookPointer = IntPtr.Zero;
				return false;
			}
			s_hwnd = activeWindow;
			s_previous = intPtr2;
			s_handles = array;
			s_owned = array2;
			if (num > 0)
			{
				ManualLogSource log4 = Plugin.Log;
				if (log4 != null)
				{
					log4.LogInfo((object)("Wine/Proton cursor requested size: " + num + "px (one-time native HCURSOR loading)."));
				}
			}
			s_hooked = true;
			s_enabled = true;
			s_kind = NativeCursorKind.Arrow;
			Apply(s_kind);
			ManualLogSource log5 = Plugin.Log;
			if (log5 != null)
			{
				log5.LogInfo((object)"Native Windows system cursor handles enabled (also used by Wine/Proton).");
			}
			return true;
		}

		internal static void Apply(NativeCursorKind kind)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Invalid comparison between Unknown and I4
			if (s_hooked && s_handles != null)
			{
				s_kind = kind;
				IntPtr intPtr = s_handles[(int)kind];
				if (intPtr == IntPtr.Zero)
				{
					intPtr = s_handles[0];
				}
				if (Cursor.visible && (int)Cursor.lockState != 1)
				{
					SetCursor(intPtr);
				}
			}
		}

		private static IntPtr WndProc(IntPtr hwnd, uint msg, IntPtr wp, IntPtr lp)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Invalid comparison between Unknown and I4
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Invalid comparison between Unknown and I4
			if (msg == 32 && s_hooked && s_enabled && hwnd == s_hwnd && ((long)lp & 0xFFFF) == 1 && Cursor.visible && (int)Cursor.lockState != 1)
			{
				IntPtr intPtr = s_handles[(int)s_kind];
				if (intPtr == IntPtr.Zero)
				{
					intPtr = s_handles[0];
				}
				SetCursor(intPtr);
				return new IntPtr(1);
			}
			IntPtr result = ((s_previous != IntPtr.Zero) ? CallWindowProc(s_previous, hwnd, msg, wp, lp) : DefWindowProc(hwnd, msg, wp, lp));
			if (s_hooked && s_enabled && hwnd == s_hwnd && (msg == 512 || msg == 514 || msg == 517 || msg == 520 || msg == 524) && Cursor.visible && (int)Cursor.lockState != 1 && GetForegroundWindow() == hwnd)
			{
				IntPtr intPtr2 = s_handles[(int)s_kind];
				if (intPtr2 == IntPtr.Zero)
				{
					intPtr2 = s_handles[0];
				}
				if (GetCursor() != intPtr2)
				{
					SetCursor(intPtr2);
				}
			}
			if (msg == 130 && hwnd == s_hwnd)
			{
				s_hwnd = IntPtr.Zero;
				s_hooked = false;
			}
			return result;
		}

		internal static void Shutdown()
		{
			s_enabled = false;
			if (!s_hooked || !(s_hwnd != IntPtr.Zero) || !(s_previous != IntPtr.Zero))
			{
				return;
			}
			if (GetWindowLongPtr(s_hwnd, -4) == s_hookPointer)
			{
				SetWindowLongPtr(s_hwnd, -4, s_previous);
				s_hwnd = (s_previous = IntPtr.Zero);
				if (s_handles != null && s_owned != null)
				{
					for (int i = 0; i < s_handles.Length; i++)
					{
						if (s_owned[i] && s_handles[i] != IntPtr.Zero)
						{
							DestroyCursor(s_handles[i]);
						}
					}
				}
				s_handles = null;
				s_owned = null;
				s_hooked = false;
				s_hookPointer = IntPtr.Zero;
				s_hook = null;
			}
			else
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"Native cursor disabled; window hook chain retained safely.");
				}
			}
		}

		[DllImport("user32.dll")]
		private static extern IntPtr GetActiveWindow();

		[DllImport("user32.dll")]
		private static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint processId);

		[DllImport("user32.dll")]
		private static extern IntPtr LoadCursor(IntPtr instance, IntPtr resource);

		[DllImport("user32.dll", SetLastError = true)]
		private static extern IntPtr CopyImage(IntPtr handle, uint type, int width, int height, uint flags);

		[DllImport("user32.dll")]
		private static extern bool DestroyCursor(IntPtr cursor);

		[DllImport("user32.dll")]
		private static extern IntPtr SetCursor(IntPtr cursor);

		[DllImport("user32.dll")]
		private static extern IntPtr GetCursor();

		[DllImport("user32.dll")]
		private static extern IntPtr GetForegroundWindow();

		[DllImport("user32.dll", CharSet = CharSet.Unicode)]
		private static extern IntPtr CallWindowProc(IntPtr old, IntPtr hwnd, uint msg, IntPtr wp, IntPtr lp);

		[DllImport("user32.dll", CharSet = CharSet.Unicode)]
		private static extern IntPtr DefWindowProc(IntPtr hwnd, uint msg, IntPtr wp, IntPtr lp);

		[DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW", SetLastError = true)]
		private static extern IntPtr GetWindowLongPtr(IntPtr hwnd, int index);

		[DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW", SetLastError = true)]
		private static extern IntPtr SetWindowLongPtr(IntPtr hwnd, int index, IntPtr value);

		[DllImport("kernel32.dll")]
		private static extern void SetLastError(int error);
	}
}