Decompiled source of Silence v1.6.0

Silence.dll

Decompiled 5 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ComfyLib;
using HarmonyLib;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Silence")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Silence")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("80fe78cc-4cbb-4a45-9790-809b6ed70b46")]
[assembly: AssemblyFileVersion("1.6.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.6.0.0")]
[module: UnverifiableCode]
namespace Silence
{
	[HarmonyPatch(typeof(Chat))]
	internal static class ChatPatch
	{
		[HarmonyPatch]
		private static class OnNewChatMessageDelegatePatch
		{
			private static Type _delegateType;

			private static FieldInfo _chatField;

			[HarmonyTargetMethod]
			private static MethodBase DelegateMethod()
			{
				_delegateType = AccessTools.Inner(typeof(Chat), "<>c__DisplayClass11_0");
				_chatField = AccessTools.Field(_delegateType, "<>4__this");
				return AccessTools.Method(_delegateType, "<OnNewChatMessage>b__2", (Type[])null, (Type[])null);
			}

			[HarmonyPostfix]
			private static void DelegatePostfix(object __instance)
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				if (Silence.IsSilenced)
				{
					Chat val = (Chat)_chatField.GetValue(__instance);
					val.m_hideTimer = val.m_hideDelay;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("Awake")]
		private static void AwakePostfix(Chat __instance)
		{
			Silence.ChatInstance = __instance;
		}

		[HarmonyTranspiler]
		[HarmonyPatch("Update")]
		private static IEnumerable<CodeInstruction> UpdateTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(ZInput), "GetKeyDown", new Type[2]
				{
					typeof(KeyCode),
					typeof(bool)
				}, (Type[])null), (string)null)
			}).ThrowIfInvalid("Could not patch Chat.Update()! (GetKeyDown)").Advance(1)
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(Transpilers.EmitDelegate<Func<bool, bool>>((Func<bool, bool>)GetKeyDownDelegate))
				})
				.InstructionEnumeration();
		}

		private static bool GetKeyDownDelegate(bool result)
		{
			if (result)
			{
				return !Silence.IsSilenced;
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch("AddInworldText")]
		private static bool AddInworldTextPrefix()
		{
			return !Silence.IsSilenced;
		}
	}
	[HarmonyPatch(typeof(Player))]
	internal static class PlayerPatch
	{
		[HarmonyTranspiler]
		[HarmonyPatch("Update")]
		private static IEnumerable<CodeInstruction> UpdateTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Callvirt, (object)AccessTools.Method(typeof(Character), "TakeInput", (Type[])null, (Type[])null), (string)null)
			}).Advance(1).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { Transpilers.EmitDelegate<Func<bool, bool>>((Func<bool, bool>)TakeInputDelegate) })
				.InstructionEnumeration();
		}

		private static bool TakeInputDelegate(bool takeInput)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (takeInput && PluginConfig.IsModEnabled.Value)
			{
				KeyboardShortcut value = PluginConfig.ToggleSilenceShortcut.Value;
				if (((KeyboardShortcut)(ref value)).IsDown())
				{
					((MonoBehaviour)Player.m_localPlayer).StartCoroutine(Silence.ToggleSilenceCoroutine());
					return false;
				}
			}
			return takeInput;
		}
	}
	public static class PluginConfig
	{
		public static ConfigEntry<bool> IsModEnabled { get; private set; }

		public static ConfigEntry<KeyboardShortcut> ToggleSilenceShortcut { get; private set; }

		public static ConfigEntry<bool> HideChatWindow { get; private set; }

		public static ConfigEntry<bool> HideInWorldTexts { get; private set; }

		public static void BindConfig(ConfigFile config)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			IsModEnabled = config.BindInOrder("_Global", "isModEnabled", defaultValue: true, "Globally enable/disable this mod (restart required).");
			ToggleSilenceShortcut = config.BindInOrder<KeyboardShortcut>("Silence", "toggleSilenceShortcut", new KeyboardShortcut((KeyCode)115, (KeyCode[])(object)new KeyCode[1] { (KeyCode)305 }), "Shortcut to toggle silence.");
			HideChatWindow = config.BindInOrder("Silence", "hideChatWindow", defaultValue: true, "When silenced, chat window is hidden.");
			HideInWorldTexts = config.BindInOrder("Silence", "hideInWorldTexts", defaultValue: true, "When silenced, hides text in-world.");
		}
	}
	[BepInPlugin("redseiko.valheim.silence", "Silence", "1.6.0")]
	public class Silence : BaseUnityPlugin
	{
		public const string PluginGuid = "redseiko.valheim.silence";

		public const string PluginName = "Silence";

		public const string PluginVersion = "1.6.0";

		private static ManualLogSource _logger;

		private Harmony _harmony;

		public static readonly WaitForEndOfFrame EndOfFrame = new WaitForEndOfFrame();

		public static Chat ChatInstance { get; set; }

		public static bool IsSilenced { get; set; } = false;


		private void Awake()
		{
			_logger = ((BaseUnityPlugin)this).Logger;
			PluginConfig.BindConfig(((BaseUnityPlugin)this).Config);
			if (PluginConfig.IsModEnabled.Value)
			{
				_harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "redseiko.valheim.silence");
			}
		}

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

		public static IEnumerator ToggleSilenceCoroutine()
		{
			if (Object.op_Implicit((Object)(object)ChatInstance))
			{
				yield return EndOfFrame;
				IsSilenced = !IsSilenced;
				LogInfo($"IsSilenced: {IsSilenced}");
				MessageHud.instance.ShowMessage((MessageType)2, $"IsSilenced: {IsSilenced}", 0, (Sprite)null);
				if (PluginConfig.HideChatWindow.Value)
				{
					ToggleChatWindow(IsSilenced);
				}
				if (PluginConfig.HideInWorldTexts.Value)
				{
					ToggleInWorldTexts(IsSilenced);
				}
			}
		}

		private static void ToggleChatWindow(bool isSilenced)
		{
			if (isSilenced)
			{
				ChatInstance.m_hideTimer = ChatInstance.m_hideDelay;
				((Terminal)ChatInstance).m_focused = false;
				ChatInstance.m_wasFocused = false;
				((TMP_InputField)((Terminal)ChatInstance).m_input).DeactivateInputField(false);
				((Component)((Terminal)ChatInstance).m_input).gameObject.SetActive(false);
			}
			((Component)((Terminal)ChatInstance).m_chatWindow).gameObject.SetActive(isSilenced);
		}

		private static void ToggleInWorldTexts(bool isSilenced)
		{
			if (!isSilenced)
			{
				return;
			}
			foreach (WorldTextInstance worldText in ChatInstance.m_worldTexts)
			{
				Object.Destroy((Object)(object)worldText.m_gui);
			}
			ChatInstance.m_worldTexts.Clear();
		}

		public static void LogInfo(object o)
		{
			_logger.LogInfo((object)$"[{DateTime.Now.ToString(DateTimeFormatInfo.InvariantInfo)}] {o}");
		}
	}
}
namespace ComfyLib
{
	public static class ConfigFileExtensions
	{
		internal sealed class ConfigurationManagerAttributes
		{
			public Action<ConfigEntryBase> CustomDrawer;

			public bool? Browsable;

			public bool? HideDefaultButton;

			public int? Order;
		}

		private static readonly Dictionary<string, int> _sectionToSettingOrder = new Dictionary<string, int>();

		private static int GetSettingOrder(string section)
		{
			if (!_sectionToSettingOrder.TryGetValue(section, out var value))
			{
				value = 0;
			}
			_sectionToSettingOrder[section] = value - 1;
			return value;
		}

		public static ConfigEntry<T> BindInOrder<T>(this ConfigFile config, string section, string key, T defaultValue, string description, AcceptableValueBase acceptableValues)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			return config.Bind<T>(section, key, defaultValue, new ConfigDescription(description, acceptableValues, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = GetSettingOrder(section)
				}
			}));
		}

		public static ConfigEntry<T> BindInOrder<T>(this ConfigFile config, string section, string key, T defaultValue, string description, Action<ConfigEntryBase> customDrawer = null, bool browsable = true, bool hideDefaultButton = false, bool hideSettingName = false)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			return config.Bind<T>(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Browsable = browsable,
					CustomDrawer = customDrawer,
					HideDefaultButton = hideDefaultButton,
					Order = GetSettingOrder(section)
				}
			}));
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action settingChangedHandler)
		{
			configEntry.SettingChanged += delegate
			{
				settingChangedHandler();
			};
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action<T> settingChangedHandler)
		{
			configEntry.SettingChanged += delegate(object _, EventArgs eventArgs)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				settingChangedHandler((T)((SettingChangedEventArgs)eventArgs).ChangedSetting.BoxedValue);
			};
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action<ConfigEntry<T>> settingChangedHandler)
		{
			configEntry.SettingChanged += delegate(object _, EventArgs eventArgs)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				settingChangedHandler((ConfigEntry<T>)((SettingChangedEventArgs)eventArgs).ChangedSetting.BoxedValue);
			};
		}
	}
}