Decompiled source of Silence v1.7.0

Silence.dll

Decompiled 2 weeks 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 Microsoft.CodeAnalysis;
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.7.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.7.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 Silence
{
	public static class SilenceManager
	{
		public static readonly WaitForEndOfFrame EndOfFrame = new WaitForEndOfFrame();

		public static Chat ChatInstance { get; set; }

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


		public static IEnumerator ToggleSilenceCoroutine()
		{
			if (Object.op_Implicit((Object)(object)ChatInstance))
			{
				yield return EndOfFrame;
				IsSilenced = !IsSilenced;
				Silence.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.WorldTexts.Clear();
		}
	}
	[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 (SilenceManager.IsSilenced)
				{
					Chat val = (Chat)_chatField.GetValue(__instance);
					val.m_hideTimer = val.m_hideDelay;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("Awake")]
		private static void AwakePostfix(Chat __instance)
		{
			SilenceManager.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_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).Start().MatchStartForward((CodeMatch[])(object)new CodeMatch[3]
			{
				new CodeMatch((OpCode?)OpCodes.Ldsfld, (object)AccessTools.Field(typeof(Player), "m_localPlayer"), (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldnull, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Call, (object)null, (string)null)
			}).ThrowIfInvalid("Could not patch Chat.Update()! (local-player-not-null)")
				.Advance(3)
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(ChatPatch), "LocalPlayerNotNullDelegate", (Type[])null, (Type[])null))
				})
				.InstructionEnumeration();
		}

		private static bool LocalPlayerNotNullDelegate(bool playerIsNotNull)
		{
			if (playerIsNotNull)
			{
				return !SilenceManager.IsSilenced;
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch("AddInworldText")]
		private static bool AddInworldTextPrefix()
		{
			return !SilenceManager.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_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).Start().MatchStartForward((CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(Player), "UpdateHover", (Type[])null, (Type[])null), (string)null)
			}).ThrowIfInvalid("Could not patch Player.Update()! (update-hover)")
				.Advance(1)
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[2]
				{
					new CodeInstruction(OpCodes.Ldloc_1, (object)null),
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(PlayerPatch), "UpdateHoverPostDelegate", (Type[])null, (Type[])null))
				})
				.InstructionEnumeration();
		}

		private static void UpdateHoverPostDelegate(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(SilenceManager.ToggleSilenceCoroutine());
				}
			}
		}
	}
	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_003c: 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.7.0")]
	public sealed class Silence : BaseUnityPlugin
	{
		public const string PluginGuid = "redseiko.valheim.silence";

		public const string PluginName = "Silence";

		public const string PluginVersion = "1.7.0";

		private static ManualLogSource _logger;

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

		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 bool? HideSettingName;

			public bool? IsAdvanced;

			public int? Order;

			public bool? ReadOnly;
		}

		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, bool browsable = true, bool hideDefaultButton = false, bool hideSettingName = false, bool isAdvanced = false, bool readOnly = false)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			return config.Bind<T>(section, key, defaultValue, new ConfigDescription(description, acceptableValues, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Browsable = browsable,
					CustomDrawer = null,
					HideDefaultButton = hideDefaultButton,
					HideSettingName = hideSettingName,
					IsAdvanced = isAdvanced,
					Order = GetSettingOrder(section),
					ReadOnly = readOnly
				}
			}));
		}

		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, bool isAdvanced = false, bool readOnly = false)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: 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,
					HideSettingName = hideSettingName,
					IsAdvanced = isAdvanced,
					Order = GetSettingOrder(section),
					ReadOnly = readOnly
				}
			}));
		}

		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);
			};
		}

		public static string[] GetStringValues(this ConfigEntry<string> configEntry)
		{
			return configEntry.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
		}
	}
}