Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of NoMessageHudToggle v1.4.0
NoMessageHudToggle.dll
Decompiled 2 weeks agousing 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.4.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.4.0.0")] namespace NoMessageHudToggle; [BepInPlugin("com.xtasy.NoMessageHudToggle", "No Message HUD Toggle", "1.4.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.4.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 ConfigEntry<bool> _disableAutomaticChatPopup; 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; } } internal static bool DisableAutomaticChatPopup { get { if ((Object)(object)Instance != (Object)null) { return Instance._disableAutomaticChatPopup.Value; } return false; } } private void Awake() { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Expected O, but got Unknown //IL_0250: 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 the summary notification shown after new content unlock messages. / Скрывать итоговое уведомление после сообщений об открытии нового содержимого. Uses $inventory_logs_new and reports the number of new discoveries. / Использует $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 $msg_new* unlock categories without a dedicated setting. Dedicated settings always take priority, including when set to false. / Применяется к категориям открытия $msg_new* без отдельной настройки. Отдельные настройки всегда имеют приоритет, в том числе при значении false."); _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. / По умолчанию отключено, поэтому неизвестные сообщения остаются видимыми."); _disableAutomaticChatPopup = ((BaseUnityPlugin)this).Config.Bind<bool>("Chat", "Disable Automatic Chat Popup", true, "Prevent chat from automatically appearing on incoming messages and player join/leave notifications. / Запретить автоматическое появление чата при сообщениях, входе и выходе игроков. Chat can still be opened manually using Enter; incoming messages are not discarded. / Чат по-прежнему открывается вручную через Enter; сообщения не удаляются."); _modActive = _enabled.Value; _harmony = new Harmony("com.xtasy.NoMessageHudToggle"); if (_modActive) { ApplyPatches(); } InitializeConfigWatcher(); Log.LogInfo((object)("No Message HUD Toggle 1.4.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)) { DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(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; } DateTime lastWriteTimeUtc2 = File.GetLastWriteTimeUtc(configFilePath); _lastConfigWriteTimeUtc = lastWriteTimeUtc; if (!File.Exists(configFilePath) || lastWriteTimeUtc2 != lastWriteTimeUtc) { _configReloadPending = true; _configReloadTime = Time.unscaledTime + 0.25f; Log.LogInfo((object)"Configuration changed during reload. A new reload is pending."); } else { 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; } if (Minimap.InTextInput()) { 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 //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0117: 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."); } MethodInfo methodInfo3 = AccessTools.Method(typeof(Chat), "Update", (Type[])null, (Type[])null); if (methodInfo3 != null) { _harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(NoMessageHudPatches), "ChatUpdatePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Log.LogInfo((object)"Patched Chat.Update for automatic chat popup suppression."); } else { Log.LogWarning((object)"Chat.Update not found; chat popup suppression unavailable."); } 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() { NoMessageHudPatches.ResetChatState(); 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); MethodInfo methodInfo3 = AccessTools.Method(typeof(Chat), "Update", (Type[])null, (Type[])null); if (methodInfo3 != null) { _harmony.Unpatch((MethodBase)methodInfo3, (HarmonyPatchType)2, "com.xtasy.NoMessageHudToggle"); } 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 { private static readonly FieldInfo ChatWindowField = AccessTools.Field(typeof(Chat), "m_chatWindow"); private static readonly FieldInfo ChatInputField = AccessTools.Field(typeof(Chat), "m_input"); private static Chat _manualChat; private static readonly MethodInfo HudAddLogMethod = AccessTools.Method(typeof(MessageHud), "AddLog", (Type[])null, (Type[])null); private static readonly Type LocalizationType = AccessTools.TypeByName("Localization") ?? Type.GetType("Localization, assembly_guiutils", throwOnError: false); private static readonly MethodInfo LocalizationInstanceGetter = ((LocalizationType == null) ? null : AccessTools.PropertyGetter(LocalizationType, "instance")); private static readonly MethodInfo LocalizeTextMethod = ((LocalizationType == null) ? null : AccessTools.Method(LocalizationType, "Localize", new Type[1] { typeof(string) }, (Type[])null)); internal static void ResetChatState() { _manualChat = null; } public static void ChatUpdatePostfix(Chat __instance) { if (!NoMessageHudTogglePlugin.IsModActive() || !NoMessageHudTogglePlugin.DisableAutomaticChatPopup) { ResetChatState(); } else { if ((Object)(object)__instance == (Object)null || ChatWindowField == null || ChatInputField == null) { return; } object? value = ChatInputField.GetValue(__instance); Component val = (Component)((value is Component) ? value : null); object? value2 = ChatWindowField.GetValue(__instance); Component val2 = (Component)((value2 is Component) ? value2 : null); if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null) { return; } if (__instance.HasFocus() || val.gameObject.activeSelf) { _manualChat = __instance; return; } if ((Object)(object)_manualChat == (Object)(object)__instance) { if (val2.gameObject.activeSelf) { return; } ResetChatState(); } __instance.Hide(); if (val2.gameObject.activeSelf) { val2.gameObject.SetActive(false); } } } public static bool ShowMessagePrefix(MessageHud __instance, MessageType type, string text, int amount, Sprite icon, bool showDespiteHiddenHUD, bool log, ref bool ___m_showDespiteHiddenHUD) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Invalid comparison between Unknown and I4 if (ShouldShowMessage(type, text, amount, icon)) { return true; } if (log && (!Hud.IsUserHidden() || showDespiteHiddenHUD) && ((int)type == 1 || (int)type == 2)) { if (HudAddLogMethod == null || LocalizationInstanceGetter == null || LocalizeTextMethod == null) { return true; } object obj = LocalizationInstanceGetter.Invoke(null, null); if (obj == null) { return true; } object obj2 = LocalizeTextMethod.Invoke(obj, new object[1] { text }); HudAddLogMethod.Invoke(__instance, new object[1] { obj2 }); } ___m_showDespiteHiddenHUD = showDespiteHiddenHUD; return false; } public static bool QueueUnlockMsgPrefix(MessageHud __instance, Sprite icon, string topic, string description, ref int ___m_unlockMsgCount) { if (ShouldShowUnlock(icon, topic, description) || HudAddLogMethod == null) { return true; } HudAddLogMethod.Invoke(__instance, new object[1] { topic + ": " + description }); ___m_unlockMsgCount++; return false; } internal static bool ShouldShowMessage(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; } internal static bool ShouldShowUnlock(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; } }