Decompiled source of NoMessageHudToggle v1.2.0

NoMessageHudToggle.dll

Decompiled 2 days 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.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("NoMessageHudToggle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NoMessageHudToggle")]
[assembly: AssemblyCopyright("Copyright ©  2026")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("C7FE73AA-F7AF-403C-8535-E9F11339F04D")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace NoMessageHudToggle;

[BepInPlugin("com.xtasy.NoMessageHudToggle", "No Message HUD Toggle", "1.2.0")]
public class NoMessageHudTogglePlugin : BaseUnityPlugin
{
	private const string GUID = "com.xtasy.NoMessageHudToggle";

	private const string NAME = "No Message HUD Toggle";

	private const string VERSION = "1.2.0";

	internal static ManualLogSource Log;

	private Harmony _harmony;

	private ConfigEntry<bool> _enabled;

	private ConfigEntry<KeyboardShortcut> _toggleHotkey;

	private ConfigEntry<bool> _hideItemPickup;

	private ConfigEntry<bool> _hideInventoryNotifications;

	private ConfigEntry<bool> _hideSkillUp;

	private ConfigEntry<bool> _hideNewItems;

	private ConfigEntry<bool> _hideNewMaterials;

	private ConfigEntry<bool> _hideNewRecipes;

	private ConfigEntry<bool> _hideNewStations;

	private ConfigEntry<bool> _hideStationLevelUp;

	private ConfigEntry<bool> _hideEvents;

	private ConfigEntry<bool> _hideCenterMessages;

	private ConfigEntry<bool> _hideOther;

	private bool _modActive;

	private const float ConfigCheckInterval = 0.5f;

	private const float ConfigReloadDelay = 0.25f;

	private float _nextConfigCheckTime;

	private float _configReloadTime;

	private bool _configReloadPending;

	private DateTime _lastConfigWriteTimeUtc;

	internal static NoMessageHudTogglePlugin Instance { get; private set; }

	internal static bool HideItemPickup
	{
		get
		{
			if ((Object)(object)Instance != (Object)null)
			{
				return Instance._hideItemPickup.Value;
			}
			return false;
		}
	}

	internal static bool HideInventoryNotifications
	{
		get
		{
			if ((Object)(object)Instance != (Object)null)
			{
				return Instance._hideInventoryNotifications.Value;
			}
			return false;
		}
	}

	internal static bool HideSkillUp
	{
		get
		{
			if ((Object)(object)Instance != (Object)null)
			{
				return Instance._hideSkillUp.Value;
			}
			return false;
		}
	}

	internal static bool HideNewItems
	{
		get
		{
			if ((Object)(object)Instance != (Object)null)
			{
				return Instance._hideNewItems.Value;
			}
			return false;
		}
	}

	internal static bool HideNewMaterials
	{
		get
		{
			if ((Object)(object)Instance != (Object)null)
			{
				return Instance._hideNewMaterials.Value;
			}
			return false;
		}
	}

	internal static bool HideNewRecipes
	{
		get
		{
			if ((Object)(object)Instance != (Object)null)
			{
				return Instance._hideNewRecipes.Value;
			}
			return false;
		}
	}

	internal static bool HideNewStations
	{
		get
		{
			if ((Object)(object)Instance != (Object)null)
			{
				return Instance._hideNewStations.Value;
			}
			return false;
		}
	}

	internal static bool HideStationLevelUp
	{
		get
		{
			if ((Object)(object)Instance != (Object)null)
			{
				return Instance._hideStationLevelUp.Value;
			}
			return false;
		}
	}

	internal static bool HideEvents
	{
		get
		{
			if ((Object)(object)Instance != (Object)null)
			{
				return Instance._hideEvents.Value;
			}
			return false;
		}
	}

	internal static bool HideCenterMessages
	{
		get
		{
			if ((Object)(object)Instance != (Object)null)
			{
				return Instance._hideCenterMessages.Value;
			}
			return false;
		}
	}

	internal static bool HideOther
	{
		get
		{
			if ((Object)(object)Instance != (Object)null)
			{
				return Instance._hideOther.Value;
			}
			return false;
		}
	}

	private void Awake()
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ed: Expected O, but got Unknown
		//IL_022f: Unknown result type (might be due to invalid IL or missing references)
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		_enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable the mod when the game starts. / Включать мод при запуске игры. This controls the initial state only. Pressing the toggle hotkey does not change this setting. / Этот параметр определяет только начальное состояние. Нажатие клавиши переключения не изменяет эту настройку.");
		_toggleHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("General", "Toggle Hotkey", new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()), "Hotkey used to temporarily enable or disable the mod during gameplay. / Клавиша для временного включения или отключения мода во время игры. Pressing this key does not modify or save configuration values. / Нажатие этой клавиши не изменяет и не сохраняет настройки конфигурации.");
		_hideItemPickup = ((BaseUnityPlugin)this).Config.Bind<bool>("Messages", "Hide Item Pickup", true, "Hide item pickup notifications. / Скрывать сообщения о получении предметов. Includes items picked up from the ground and item drops from creatures. / Включает предметы, подобранные с земли, и добычу, выпавшую из существ.");
		_hideInventoryNotifications = ((BaseUnityPlugin)this).Config.Bind<bool>("Messages", "Hide Inventory Notifications", true, "Hide inventory change notifications. / Скрывать уведомления об изменениях инвентаря. Includes notifications using $inventory_logs_new, such as items received from chests. / Включает уведомления с использованием $inventory_logs_new, например при получении предметов из сундуков.");
		_hideSkillUp = ((BaseUnityPlugin)this).Config.Bind<bool>("Messages", "Hide Skill Up", true, "Hide skill level-up notifications. / Скрывать сообщения о повышении уровня навыков. Examples: Running, Jump, Clubs, Crafting, Cooking and Farming. / Примеры: бег, прыжок, дубины, крафт, готовка и фермерство.");
		_hideNewItems = ((BaseUnityPlugin)this).Config.Bind<bool>("Messages", "Hide New Items", true, "Hide notifications for newly discovered items and other new content. / Скрывать уведомления об открытии новых предметов и другого нового содержимого. Applies to all $msg_new* unlock messages, including new items, trophies, materials, recipes and stations unless a more specific setting is enabled. / Применяется ко всем сообщениям открытия вида $msg_new*, включая новые предметы, трофеи, материалы, рецепты и станции, если для конкретной категории не задана отдельная настройка.");
		_hideNewMaterials = ((BaseUnityPlugin)this).Config.Bind<bool>("Messages", "Hide New Materials", true, "Hide notifications when a new material is discovered. / Скрывать уведомления об открытии новых материалов. Uses messages such as $msg_newmaterial. / Использует сообщения вида $msg_newmaterial.");
		_hideNewRecipes = ((BaseUnityPlugin)this).Config.Bind<bool>("Messages", "Hide New Recipes", true, "Hide notifications when a new recipe is discovered. / Скрывать уведомления об открытии новых рецептов. Uses messages such as $msg_newrecipe. / Использует сообщения вида $msg_newrecipe.");
		_hideNewStations = ((BaseUnityPlugin)this).Config.Bind<bool>("Messages", "Hide New Stations", true, "Hide notifications when a new crafting station is discovered. / Скрывать уведомления об открытии новых ремесленных станций. Examples: Workbench, Forge and other crafting stations. / Примеры: верстак, кузница и другие ремесленные станции.");
		_hideStationLevelUp = ((BaseUnityPlugin)this).Config.Bind<bool>("Messages", "Hide Station Level Up", true, "Hide crafting station level-up notifications. / Скрывать уведомления о повышении уровня ремесленных станций. Examples: Workbench and Forge upgrades. / Примеры: улучшение верстака и кузницы.");
		_hideEvents = ((BaseUnityPlugin)this).Config.Bind<bool>("Messages", "Hide Events", false, "Hide global event and raid notifications. / Скрывать глобальные события и уведомления о рейдах. Includes messages starting with $event_. Event messages are controlled separately and are not affected by Hide Center Messages. / Включает сообщения, начинающиеся с $event_. Сообщения событий управляются отдельно и не зависят от Hide Center Messages. Disabled by default, so raids and events remain visible. / По умолчанию отключено, поэтому рейды и события остаются видимыми.");
		_hideCenterMessages = ((BaseUnityPlugin)this).Config.Bind<bool>("Messages", "Hide Center Messages", true, "Hide regular center-screen Message HUD notifications. / Скрывать обычные сообщения Message HUD по центру экрана. Includes resting, rested, station and other center-screen messages. Raid and event messages are controlled separately by Hide Events. / Включает сообщения об отдыхе, хорошем отдыхе, станках и другие сообщения по центру экрана. Сообщения о рейдах и событиях управляются отдельно через Hide Events.");
		_hideOther = ((BaseUnityPlugin)this).Config.Bind<bool>("Messages", "Hide Other", false, "Hide other Message HUD notifications that do not match a specific category. / Скрывать остальные уведомления Message HUD, которые не относятся к отдельной категории. Disabled by default, so unknown messages remain visible. / По умолчанию отключено, поэтому неизвестные сообщения остаются видимыми.");
		_modActive = _enabled.Value;
		_harmony = new Harmony("com.xtasy.NoMessageHudToggle");
		if (_modActive)
		{
			ApplyPatches();
		}
		InitializeConfigWatcher();
		Log.LogInfo((object)("No Message HUD Toggle 1.2.0 loaded. State: " + (_modActive ? "ON" : "OFF") + ". " + $"Toggle: {_toggleHotkey.Value}"));
	}

	private void Update()
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		HandleConfigAutoReload();
		KeyboardShortcut value = _toggleHotkey.Value;
		if (((KeyboardShortcut)(ref value)).IsDown() && !IsInputBlocked())
		{
			ToggleMod();
		}
	}

	private void HandleConfigAutoReload()
	{
		try
		{
			if (Time.unscaledTime < _nextConfigCheckTime)
			{
				return;
			}
			_nextConfigCheckTime = Time.unscaledTime + 0.5f;
			string configFilePath = ((BaseUnityPlugin)this).Config.ConfigFilePath;
			if (!string.IsNullOrEmpty(configFilePath) && File.Exists(configFilePath))
			{
				DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(configFilePath);
				if (lastWriteTimeUtc != _lastConfigWriteTimeUtc)
				{
					_lastConfigWriteTimeUtc = lastWriteTimeUtc;
					_configReloadPending = true;
					_configReloadTime = Time.unscaledTime + 0.25f;
				}
				if (_configReloadPending && !(Time.unscaledTime < _configReloadTime))
				{
					_configReloadPending = false;
					ReloadConfiguration();
				}
			}
		}
		catch (Exception arg)
		{
			Log.LogError((object)$"Failed to monitor configuration file: {arg}");
		}
	}

	private void ReloadConfiguration()
	{
		try
		{
			string configFilePath = ((BaseUnityPlugin)this).Config.ConfigFilePath;
			if (File.Exists(configFilePath))
			{
				Log.LogInfo((object)"Configuration file changed. Reloading configuration...");
				bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
				((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
				try
				{
					((BaseUnityPlugin)this).Config.Reload();
				}
				finally
				{
					((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
				}
				_lastConfigWriteTimeUtc = File.GetLastWriteTimeUtc(configFilePath);
				Log.LogInfo((object)"Configuration reloaded successfully.");
			}
		}
		catch (Exception arg)
		{
			Log.LogError((object)$"Failed to reload configuration: {arg}");
			_configReloadPending = true;
			_configReloadTime = Time.unscaledTime + 1f;
		}
	}

	private void InitializeConfigWatcher()
	{
		try
		{
			if (((BaseUnityPlugin)this).Config == null)
			{
				return;
			}
			string configFilePath = ((BaseUnityPlugin)this).Config.ConfigFilePath;
			if (!string.IsNullOrEmpty(configFilePath))
			{
				if (!File.Exists(configFilePath))
				{
					Log.LogWarning((object)("Configuration file does not exist: " + configFilePath));
					return;
				}
				_lastConfigWriteTimeUtc = File.GetLastWriteTimeUtc(configFilePath);
				_nextConfigCheckTime = Time.unscaledTime + 0.5f;
				_configReloadPending = false;
				Log.LogInfo((object)("Configuration auto-reload enabled. File: " + configFilePath));
			}
		}
		catch (Exception arg)
		{
			Log.LogError((object)$"Failed to initialize configuration auto-reload: {arg}");
		}
	}

	private static bool IsInputBlocked()
	{
		if ((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus())
		{
			return true;
		}
		if (Console.IsVisible())
		{
			return true;
		}
		if (TextInput.IsVisible())
		{
			return true;
		}
		return false;
	}

	private void ToggleMod()
	{
		_modActive = !_modActive;
		if (_modActive)
		{
			ApplyPatches();
			Log.LogInfo((object)"No Message HUD: ON. Configuration values were not changed.");
		}
		else
		{
			RemovePatches();
			Log.LogInfo((object)"No Message HUD: OFF. Configuration values were not changed.");
		}
	}

	private void ApplyPatches()
	{
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Expected O, but got Unknown
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Expected O, but got Unknown
		try
		{
			RemovePatches();
			MethodInfo methodInfo = AccessTools.Method(typeof(MessageHud), "ShowMessage", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogError((object)"Could not find MessageHud.ShowMessage!");
			}
			else
			{
				_harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(NoMessageHudPatches), "ShowMessagePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)"Patched MessageHud.ShowMessage.");
			}
			MethodInfo methodInfo2 = AccessTools.Method(typeof(MessageHud), "QueueUnlockMsg", (Type[])null, (Type[])null);
			if (methodInfo2 == null)
			{
				Log.LogError((object)"Could not find MessageHud.QueueUnlockMsg!");
			}
			else
			{
				_harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(NoMessageHudPatches), "QueueUnlockMsgPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)"Patched MessageHud.QueueUnlockMsg.");
			}
			Log.LogInfo((object)"No Message HUD patches applied.");
		}
		catch (Exception arg)
		{
			Log.LogError((object)$"Failed to apply No Message HUD patches: {arg}");
		}
	}

	private void RemovePatches()
	{
		try
		{
			if (_harmony != null)
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(MessageHud), "ShowMessage", (Type[])null, (Type[])null);
				MethodInfo methodInfo2 = AccessTools.Method(typeof(MessageHud), "QueueUnlockMsg", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					_harmony.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)1, "com.xtasy.NoMessageHudToggle");
				}
				if (methodInfo2 != null)
				{
					_harmony.Unpatch((MethodBase)methodInfo2, (HarmonyPatchType)1, "com.xtasy.NoMessageHudToggle");
				}
			}
		}
		catch (Exception arg)
		{
			Log.LogError((object)$"Failed to remove No Message HUD patches: {arg}");
		}
	}

	internal static bool IsModActive()
	{
		if ((Object)(object)Instance != (Object)null)
		{
			return Instance._modActive;
		}
		return false;
	}

	private void OnDestroy()
	{
		try
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
		catch (Exception arg)
		{
			ManualLogSource log = Log;
			if (log != null)
			{
				log.LogError((object)$"Failed to unpatch: {arg}");
			}
		}
		if ((Object)(object)Instance == (Object)(object)this)
		{
			Instance = null;
		}
	}
}
internal static class NoMessageHudPatches
{
	public static bool ShowMessagePrefix(MessageType type, string text, int amount, Sprite icon)
	{
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Invalid comparison between Unknown and I4
		if (!NoMessageHudTogglePlugin.IsModActive())
		{
			return true;
		}
		if (string.IsNullOrEmpty(text))
		{
			return true;
		}
		if (text.StartsWith("$event_", StringComparison.OrdinalIgnoreCase))
		{
			return !NoMessageHudTogglePlugin.HideEvents;
		}
		if ((int)type == 2)
		{
			return !NoMessageHudTogglePlugin.HideCenterMessages;
		}
		if (text.IndexOf("$msg_added", StringComparison.OrdinalIgnoreCase) >= 0)
		{
			return !NoMessageHudTogglePlugin.HideItemPickup;
		}
		if (text.IndexOf("$inventory_logs_new", StringComparison.OrdinalIgnoreCase) >= 0)
		{
			return !NoMessageHudTogglePlugin.HideInventoryNotifications;
		}
		if (text.IndexOf("$msg_skillup", StringComparison.OrdinalIgnoreCase) >= 0)
		{
			return !NoMessageHudTogglePlugin.HideSkillUp;
		}
		return !NoMessageHudTogglePlugin.HideOther;
	}

	public static bool QueueUnlockMsgPrefix(Sprite icon, string topic, string description)
	{
		if (!NoMessageHudTogglePlugin.IsModActive())
		{
			return true;
		}
		if (string.IsNullOrEmpty(topic))
		{
			return !NoMessageHudTogglePlugin.HideOther;
		}
		if (topic.Equals("$msg_newmaterial", StringComparison.OrdinalIgnoreCase))
		{
			return !NoMessageHudTogglePlugin.HideNewMaterials;
		}
		if (topic.Equals("$msg_newrecipe", StringComparison.OrdinalIgnoreCase))
		{
			return !NoMessageHudTogglePlugin.HideNewRecipes;
		}
		if (topic.Equals("$msg_newstation", StringComparison.OrdinalIgnoreCase))
		{
			return !NoMessageHudTogglePlugin.HideNewStations;
		}
		if (topic.Equals("$msg_newstation_level", StringComparison.OrdinalIgnoreCase))
		{
			return !NoMessageHudTogglePlugin.HideStationLevelUp;
		}
		if (topic.StartsWith("$msg_new", StringComparison.OrdinalIgnoreCase))
		{
			return !NoMessageHudTogglePlugin.HideNewItems;
		}
		return !NoMessageHudTogglePlugin.HideOther;
	}
}