Decompiled source of AutoMute v1.2.1

AutoMute.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("AutoMute")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AutoMute")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("4b2c8cf7-fb91-4b71-b98c-6c209e9bdb68")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.1.0")]
[module: UnverifiableCode]
namespace AutoMute;

internal class IngameUI
{
	private static GameObject group;

	private static UIToggle backGroundMuteToggle;

	private static InputField filterInput;

	private static Text muteInfoText;

	private static UIToggle filterMuteOnlyToggle;

	private static UIComboBox audioComboBox;

	private static Text audioClipPath;

	private static UIToggle audioEnableToggle;

	private static Button playAudioButton;

	private static Text playAutoButtonText;

	private static bool filterMuteOnly = false;

	private static string searchStr = "";

	private static AudioProto audioProto = null;

	private static VFAudio vFAudio = null;

	[HarmonyPrefix]
	[HarmonyPatch(typeof(VFListener), "SetPassFilter")]
	public static bool SetPassFilter_Block()
	{
		if ((Object)(object)vFAudio != (Object)null && vFAudio.isPlaying)
		{
			((Behaviour)VFListener.lowPassFilter).enabled = false;
			((Behaviour)VFListener.highPassFilter).enabled = false;
			return false;
		}
		return true;
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(UIOptionWindow), "_OnOpen")]
	public static void Init()
	{
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Expected O, but got Unknown
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_0132: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_021f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0265: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0329: Unknown result type (might be due to invalid IL or missing references)
		//IL_045a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0464: Expected O, but got Unknown
		//IL_0498: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_0558: Unknown result type (might be due to invalid IL or missing references)
		//IL_0573: Unknown result type (might be due to invalid IL or missing references)
		//IL_059a: Unknown result type (might be due to invalid IL or missing references)
		//IL_05a4: Expected O, but got Unknown
		if (!((Object)(object)group == (Object)null))
		{
			return;
		}
		Plugin.Log.LogDebug((object)"init");
		try
		{
			GameObject val = GameObject.Find("UI Root/Overlay Canvas/Top Windows/Option Window/details/content-2");
			GameObject val2 = GameObject.Find("UI Root/Overlay Canvas/Top Windows/Option Window/details/content-1/fullscreen");
			GameObject val3 = GameObject.Find("UI Root/Overlay Canvas/Top Windows/Option Window/details/content-1/resolution/ComboBox");
			GameObject val4 = GameObject.Find("UI Root/Overlay Canvas/In Game/Globe Panel/name-input");
			GameObject val5 = GameObject.Find("UI Root/Overlay Canvas/Top Windows/Option Window/details/content-2/revert-button");
			group = new GameObject("AutoMute_Group");
			group.transform.SetParent(val.transform);
			group.transform.localPosition = new Vector3(-100f, 280f);
			group.transform.localScale = Vector3.one;
			GameObject val6 = Object.Instantiate<GameObject>(val2, group.transform);
			((Object)val6).name = "MuteInBackground Toggle";
			val6.transform.localPosition = new Vector3(0f, 0f, 0f);
			Object.Destroy((Object)(object)val6.GetComponent<Localizer>());
			val6.GetComponent<Text>().text = Localization.Translate("Mute in background");
			backGroundMuteToggle = val6.GetComponentInChildren<UIToggle>();
			((Component)backGroundMuteToggle).transform.localPosition = new Vector3(130f, 5f, 0f);
			backGroundMuteToggle.isOn = Plugin.Instance.MuteInBackground.Value;
			((UnityEvent<bool>)(object)backGroundMuteToggle.toggle.onValueChanged).AddListener((UnityAction<bool>)OnBackGroundMuteToggleChange);
			val6 = Object.Instantiate<GameObject>(val4, group.transform);
			((Object)val6).name = "AudioName Filter";
			val6.transform.localPosition = new Vector3(-2f, -30f, 0f);
			filterInput = val6.GetComponent<InputField>();
			filterInput.text = "";
			((UnityEvent<string>)(object)filterInput.onValueChanged).AddListener((UnityAction<string>)OnInputValueChanged);
			val6.GetComponent<RectTransform>().sizeDelta = new Vector2(203f, 30f);
			((Graphic)val6.GetComponent<Image>()).color = new Color(0f, 0f, 0f, 0.5f);
			val6.SetActive(true);
			val6 = Object.Instantiate<GameObject>(val2, group.transform);
			((Object)val6).name = "Filter Mute Only Toggle";
			val6.transform.localPosition = new Vector3(240f, -30f, 0f);
			Object.Destroy((Object)(object)val6.GetComponent<Localizer>());
			muteInfoText = val6.GetComponent<Text>();
			muteInfoText.text = "";
			filterMuteOnlyToggle = val6.GetComponentInChildren<UIToggle>();
			((Component)filterMuteOnlyToggle).transform.localPosition = new Vector3(-40f, 5f, 0f);
			filterMuteOnlyToggle.isOn = filterMuteOnly;
			((UnityEvent<bool>)(object)filterMuteOnlyToggle.toggle.onValueChanged).AddListener((UnityAction<bool>)OnFilterMuteOnlyToggleChange);
			val6 = Object.Instantiate<GameObject>(val3, group.transform, false);
			((Object)val6).name = "Audio ComboBox";
			val6.transform.localPosition = new Vector3(0f, -60f, 0f);
			Transform val7 = val6.transform.Find("Dropdown List ScrollBox/Mask/Content Panel/");
			for (int num = val7.childCount - 1; num >= 0; num--)
			{
				if (((Object)val7.GetChild(num)).name == "Item Button(Clone)")
				{
					Object.Destroy((Object)(object)((Component)val7.GetChild(num)).gameObject);
				}
			}
			audioComboBox = val6.GetComponentInChildren<UIComboBox>();
			((UnityEventBase)audioComboBox.onItemIndexChange).RemoveAllListeners();
			RefreshAudioComboBox();
			audioComboBox.m_Text.supportRichText = true;
			audioComboBox.m_EmptyItemRes.supportRichText = true;
			((Component)audioComboBox.m_ListItemRes).GetComponentInChildren<Text>().supportRichText = true;
			foreach (Button itemButton in audioComboBox.ItemButtons)
			{
				((Component)itemButton).GetComponentInChildren<Text>().supportRichText = true;
			}
			audioComboBox.DropDownCount = 20;
			audioComboBox.itemIndex = 0;
			audioComboBox.m_Input.text = "<i>(Select Audio)</i>";
			((UnityEvent)audioComboBox.onItemIndexChange).AddListener(new UnityAction(OnComboBoxIndexChange));
			val6 = Object.Instantiate<GameObject>(val2, group.transform);
			((Object)val6).name = "Audio Enable Toggle";
			val6.transform.localPosition = new Vector3(240f, -60f, 0f);
			Object.Destroy((Object)(object)val6.GetComponent<Localizer>());
			audioClipPath = val6.GetComponent<Text>();
			audioClipPath.text = "(Audio ClipPath)";
			audioEnableToggle = val6.GetComponentInChildren<UIToggle>();
			((Component)audioEnableToggle).transform.localPosition = new Vector3(-40f, 5f, 0f);
			audioEnableToggle.isOn = true;
			((UnityEvent<bool>)(object)audioEnableToggle.toggle.onValueChanged).AddListener((UnityAction<bool>)OnAudioEnableToggleChange);
			val6 = Object.Instantiate<GameObject>(val5, group.transform);
			((Object)val6).name = "Play Audio Button";
			val6.transform.localPosition = new Vector3(210f, -130f, 0f);
			val6.GetComponent<RectTransform>().sizeDelta = new Vector2(90f, 30f);
			playAudioButton = val6.GetComponent<Button>();
			((UnityEvent)playAudioButton.onClick).AddListener(new UnityAction(PlayAudio));
			playAutoButtonText = val6.GetComponentInChildren<Text>();
			playAutoButtonText.text = Localization.Translate("Play Audio");
			Object.Destroy((Object)(object)val6.GetComponent<UIButton>());
			Object.Destroy((Object)(object)val6.GetComponentInChildren<Localizer>());
		}
		catch
		{
			Plugin.Log.LogWarning((object)"UI component initial fail!");
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(UIOptionWindow), "_OnClose")]
	public static void OnClose()
	{
		VFAudio obj = vFAudio;
		if (obj != null)
		{
			obj.Stop();
		}
		vFAudio = null;
	}

	public static void OnDestory()
	{
		VFAudio obj = vFAudio;
		if (obj != null)
		{
			obj.Stop();
		}
		vFAudio = null;
		backGroundMuteToggle = null;
		Object.Destroy((Object)(object)group);
		group = null;
	}

	private static void OnBackGroundMuteToggleChange(bool value)
	{
		Plugin.Instance.MuteInBackground.Value = value;
		backGroundMuteToggle.isOn = value;
	}

	private static void PlayAudio()
	{
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		if (audioProto != null)
		{
			Plugin.Log.LogDebug((object)("PlayAudio: " + ((Proto)audioProto).name));
			if ((Object)(object)vFAudio != (Object)null)
			{
				vFAudio.Stop();
			}
			vFAudio = VFAudio.Create(((Proto)audioProto).name, (Transform)null, Vector3.zero, false, 0, -1, -1L);
			vFAudio.Play();
		}
	}

	private static void OnFilterMuteOnlyToggleChange(bool value)
	{
		filterMuteOnlyToggle.isOn = value;
		filterMuteOnly = value;
		RefreshAudioComboBox();
		OnComboBoxIndexChange();
	}

	private static void OnAudioEnableToggleChange(bool value)
	{
		audioEnableToggle.isOn = value;
		if (audioProto == null)
		{
			return;
		}
		if (value)
		{
			if (Plugin.AudioVolumes.TryGetValue(((Proto)audioProto).name, out var value2))
			{
				audioProto.Volume = value2;
				Plugin.AudioVolumes.Remove(((Proto)audioProto).name);
				playAutoButtonText.text = Localization.Translate("Play Audio");
			}
		}
		else if (!Plugin.AudioVolumes.ContainsKey(((Proto)audioProto).name))
		{
			Plugin.AudioVolumes.Add(((Proto)audioProto).name, audioProto.Volume);
			audioProto.Volume = 0f;
			playAutoButtonText.text = Localization.Translate("Muted");
		}
		audioComboBox.m_Input.text = GetRichText(((Proto)audioProto).name);
		Plugin.Log.LogDebug((object)$"[{((Proto)audioProto).name}]: {audioProto.Volume}");
		StringBuilder stringBuilder = new StringBuilder();
		foreach (string key in Plugin.AudioVolumes.Keys)
		{
			stringBuilder.Append(key);
			stringBuilder.Append(' ');
		}
		Plugin.Instance.MuteList.Value = stringBuilder.ToString();
		Plugin.IsDirty = true;
		RefreshAudioComboBox();
	}

	public static void OnComboBoxIndexChange()
	{
		if (audioComboBox.itemIndex >= 0 && audioComboBox.itemIndex < audioComboBox.Items.Count)
		{
			int num = audioComboBox.ItemsData[audioComboBox.itemIndex];
			audioProto = ((ProtoSet<AudioProto>)(object)LDB.audios).dataArray[num];
			audioClipPath.text = audioProto.ClipPath;
			bool flag = Plugin.AudioVolumes.ContainsKey(((Proto)audioProto).name);
			audioEnableToggle.isOn = !flag;
			playAutoButtonText.text = (flag ? Localization.Translate("Muted") : Localization.Translate("Play Audio"));
		}
		else
		{
			audioProto = null;
			audioComboBox.m_Input.text = "";
			audioClipPath.text = "";
			audioEnableToggle.isOn = false;
			playAutoButtonText.text = Localization.Translate("No Audio");
		}
		if ((Object)(object)vFAudio != (Object)null)
		{
			vFAudio.Stop();
			vFAudio = null;
		}
	}

	private static void OnInputValueChanged(string value)
	{
		searchStr = value;
		RefreshAudioComboBox();
		if (audioComboBox.Items.Count > 0)
		{
			audioComboBox.itemIndex = 0;
		}
		OnComboBoxIndexChange();
	}

	private static void RefreshAudioComboBox()
	{
		audioComboBox.Items.Clear();
		audioComboBox.ItemsData.Clear();
		int num = 0;
		for (int i = 0; i < ((ProtoSet<AudioProto>)(object)LDB.audios).dataArray.Length; i++)
		{
			string name = ((Proto)((ProtoSet<AudioProto>)(object)LDB.audios).dataArray[i]).name;
			if (Plugin.AudioVolumes.ContainsKey(name))
			{
				num++;
			}
			else if (filterMuteOnly)
			{
				continue;
			}
			if (string.IsNullOrEmpty(searchStr) || name.IndexOf(searchStr, 0, StringComparison.OrdinalIgnoreCase) != -1)
			{
				audioComboBox.ItemsData.Add(i);
				audioComboBox.Items.Add(GetRichText(name));
			}
		}
		muteInfoText.text = $"{audioComboBox.Items.Count}/{((ProtoSet<AudioProto>)(object)LDB.audios).dataArray.Length}";
		if (filterMuteOnly)
		{
			Text obj = muteInfoText;
			obj.text += " (mute only)";
		}
		else
		{
			Text obj2 = muteInfoText;
			obj2.text += $" ({num} muted)";
		}
	}

	private static string GetRichText(string audioName)
	{
		if (Plugin.AudioVolumes.ContainsKey(audioName))
		{
			return "<color=#ff9900ff>" + audioName + "</color>";
		}
		return audioName;
	}
}
[BepInPlugin("starfi5h.plugin.AutoMute", "AutoMute", "1.2.1")]
public class Plugin : BaseUnityPlugin
{
	public const string GUID = "starfi5h.plugin.AutoMute";

	public const string NAME = "AutoMute";

	public const string VERSION = "1.2.1";

	internal static Plugin Instance;

	internal static ManualLogSource Log;

	internal Harmony harmony;

	internal ConfigEntry<bool> MuteInBackground;

	internal ConfigEntry<string> MuteBuildingIds;

	internal ConfigEntry<string> MuteList;

	private static float? OriginalVolume = null;

	public static readonly Dictionary<string, float> AudioVolumes = new Dictionary<string, float>();

	private static readonly Dictionary<int, float> ModelVolumes = new Dictionary<int, float>();

	internal static bool IsDirty = true;

	public void BindConfig()
	{
		MuteInBackground = ((BaseUnityPlugin)this).Config.Bind<bool>("- General -", "Mute In Background", true, "Enable to mute the game when in the background, i.e. alt-tabbed.\n游戏在后台时自动静音,切换到前台时恢复");
		MuteBuildingIds = ((BaseUnityPlugin)this).Config.Bind<string>("- General -", "Mute Building Ids", "", "The ids of building to mute, separated by white spaces.\n消除指定建筑的音讯。输入:建筑物品id, 以空白分隔。");
		MuteList = ((BaseUnityPlugin)this).Config.Bind<string>("- General -", "MuteList", "vc-broadcast-4 vc-broadcast-5 vc-broadcast-6 vc-broadcast-7 vc-broadcast-8 vc-broadcast-22", "The list of audio name to mute, separated by white spaces. Check mod page wiki for available names.\n消除指定的音讯。输入:音讯名称, 以空白分隔(名称可以在mod页面wiki查询)");
	}

	internal void Awake()
	{
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Expected O, but got Unknown
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Expected O, but got Unknown
		BindConfig();
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		harmony = new Harmony("starfi5h.plugin.AutoMute");
		harmony.PatchAll(typeof(Plugin));
		harmony.PatchAll(typeof(IngameUI));
		MethodInfo methodInfo = AccessTools.Method(typeof(UIMechaMoveTip), "OnForgeTaskDelivery", (Type[])null, (Type[])null);
		if (methodInfo != null)
		{
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(Plugin), "Suppress", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
	}

	internal void OnApplicationFocus(bool hasFocus)
	{
		if (hasFocus)
		{
			if (OriginalVolume.HasValue)
			{
				AudioListener.volume = OriginalVolume.Value;
			}
			OriginalVolume = null;
		}
		else if (MuteInBackground.Value)
		{
			OriginalVolume = AudioListener.volume;
			AudioListener.volume = 0f;
		}
	}

	private static bool Suppress()
	{
		return false;
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(UIOptionWindow), "OnApplyClick")]
	internal static void OnApplyClick()
	{
		((BaseUnityPlugin)Instance).Config.Reload();
		ApplySettings();
		if (IsDirty)
		{
			AudioData.LoadStatic();
			IsDirty = false;
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(VFPreload), "InvokeOnLoadWorkEnded")]
	[HarmonyAfter(new string[] { "me.xiaoye97.plugin.Dyson.LDBTool" })]
	internal static void ApplySettings()
	{
		ChangeAudioVolumes();
		ChangeBuildingVolumes();
		if (AudioVolumes.Count + ModelVolumes.Count > 0)
		{
			((BaseUnityPlugin)Instance).Logger.LogDebug((object)$"Mute {AudioVolumes.Count} audios and {ModelVolumes.Count} buildings.");
		}
	}

	private static void ChangeAudioVolumes()
	{
		foreach (KeyValuePair<string, float> audioVolume in AudioVolumes)
		{
			AudioProto val = LDB.audios[audioVolume.Key];
			if (val != null)
			{
				val.Volume = audioVolume.Value;
			}
		}
		AudioVolumes.Clear();
		string[] array = Instance.MuteList.Value.Split(' ', ',', '\n');
		foreach (string text in array)
		{
			if (!Utility.IsNullOrWhiteSpace(text))
			{
				AudioProto val2 = LDB.audios[text];
				if (val2 != null)
				{
					AudioVolumes.Add(text, val2.Volume);
					val2.Volume = 0f;
				}
				else
				{
					((BaseUnityPlugin)Instance).Logger.LogWarning((object)("Can't find audio name: " + text));
				}
			}
		}
	}

	private static void ChangeBuildingVolumes()
	{
		foreach (KeyValuePair<int, float> modelVolume in ModelVolumes)
		{
			ModelProto val = ((ProtoSet<ModelProto>)(object)LDB.models).Select(modelVolume.Key);
			if (val != null)
			{
				val.prefabDesc.audioVolume = modelVolume.Value;
			}
		}
		ModelVolumes.Clear();
		string[] array = Instance.MuteBuildingIds.Value.Split(' ', ',');
		foreach (string text in array)
		{
			if (Utility.IsNullOrWhiteSpace(text))
			{
				continue;
			}
			if (int.TryParse(text, out var result))
			{
				ItemProto obj = ((ProtoSet<ItemProto>)(object)LDB.items).Select(result);
				if (obj == null)
				{
					((BaseUnityPlugin)Instance).Logger.LogWarning((object)$"Can't find item {result}");
				}
				_ = ((Proto)obj).Name;
				int modelIndex = obj.ModelIndex;
				ModelProto val2 = ((ProtoSet<ModelProto>)(object)LDB.models).Select(modelIndex);
				if (val2 != null)
				{
					ModelVolumes.Add(modelIndex, val2.prefabDesc.audioVolume);
					val2.prefabDesc.audioVolume = 0f;
				}
			}
			else
			{
				((BaseUnityPlugin)Instance).Logger.LogWarning((object)("Can't parse \"" + text + "\" to int"));
			}
		}
	}
}