Decompiled source of Logo Changer v1.0.11

LogoChanger.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
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 HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("LogoChanger")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Azumatt")]
[assembly: AssemblyProduct("LogoChanger")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")]
[assembly: AssemblyFileVersion("1.0.11")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.11.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace LogoChanger
{
	[BepInPlugin("Azumatt.LogoChanger", "LogoChanger", "1.0.11")]
	public class LogoChangerPlugin : BaseUnityPlugin
	{
		private enum Toggle
		{
			On = 1,
			Off = 0
		}

		internal const string ModName = "LogoChanger";

		internal const string ModVersion = "1.0.11";

		internal const string Author = "Azumatt";

		private const string ModGUID = "Azumatt.LogoChanger";

		private static readonly string ConfigFileName = "Azumatt.LogoChanger.cfg";

		private static readonly string ConfigFileFullPath;

		private readonly Harmony _harmony = new Harmony("Azumatt.LogoChanger");

		private static readonly ManualLogSource LogoChangerLogger;

		internal static bool IsAshlandsLogoAdjusted;

		private static ConfigEntry<Toggle> _modEnabled;

		private static ConfigEntry<string> _mainMenuLogo;

		private static ConfigEntry<string> _mistMenuLogo;

		private static Sprite _mainLogoSprite;

		private static Sprite _mistLogoSprite;

		public void Awake()
		{
			_modEnabled = ((BaseUnityPlugin)this).Config.Bind<Toggle>("1 - General", "Mod Enabled?", Toggle.On, "Enable/Disable the mod");
			_mainMenuLogo = ((BaseUnityPlugin)this).Config.Bind<string>("2 - Main Menu", "Main Menu Logo", "LogoChanger_LOGO.png", "The logo to use on the main menu to replace \"Valheim\" image, should be found somewhere in the plugins folder and sized at 1000x394");
			_mistMenuLogo = ((BaseUnityPlugin)this).Config.Bind<string>("2 - Main Menu", "Mislands Menu Logo", "LogoChanger_AshlandsLogo.png", "The logo to use on the main menu to replace \"Valheim\" image, should be found somewhere in the plugins folder and sized at 2048x448");
			_modEnabled.SettingChanged += ReloadImagesFromFolder;
			MoveImagesToConfigFolder();
			ReloadImagesFromFolder(null, null);
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			_harmony.PatchAll(executingAssembly);
			SetupWatcher();
		}

		private void OnDestroy()
		{
			((BaseUnityPlugin)this).Config.Save();
		}

		private void SetupWatcher()
		{
			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName);
			fileSystemWatcher.Changed += ReadConfigValues;
			fileSystemWatcher.Created += ReadConfigValues;
			fileSystemWatcher.Renamed += ReadConfigValues;
			fileSystemWatcher.IncludeSubdirectories = true;
			fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher.EnableRaisingEvents = true;
			FileSystemWatcher fileSystemWatcher2 = new FileSystemWatcher(Paths.ConfigPath, "LogoChanger*.png");
			fileSystemWatcher2.Changed += ReloadImagesFromFolder;
			fileSystemWatcher2.Created += ReloadImagesFromFolder;
			fileSystemWatcher2.Renamed += ReloadImagesFromFolder;
			fileSystemWatcher2.IncludeSubdirectories = true;
			fileSystemWatcher2.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher2.EnableRaisingEvents = true;
		}

		private static void MoveImagesToConfigFolder()
		{
			string text = Path.Combine(Paths.ConfigPath, "Azumatt.LogoChanger_Images");
			if (!Directory.Exists(text))
			{
				Directory.CreateDirectory(text);
			}
			string[] files = Directory.GetFiles(Paths.PluginPath, "LogoChanger*.png", SearchOption.AllDirectories);
			string[] files2 = Directory.GetFiles(Paths.PluginPath, "DefaultLogos.zip", SearchOption.AllDirectories);
			if (files2.Length != 0)
			{
				string sourceFileName = files2[0];
				string text2 = Path.Combine(text, "DefaultLogos.zip");
				if (File.Exists(text2))
				{
					File.Delete(text2);
				}
				File.Move(sourceFileName, text2);
			}
			string[] array = files;
			foreach (string obj in array)
			{
				string fileName = Path.GetFileName(obj);
				string destFileName = Path.Combine(text, fileName);
				File.Move(obj, destFileName);
			}
		}

		private void ReadConfigValues(object sender, FileSystemEventArgs e)
		{
			if (!File.Exists(ConfigFileFullPath))
			{
				return;
			}
			try
			{
				LogoChangerLogger.LogDebug((object)"ReadConfigValues called");
				((BaseUnityPlugin)this).Config.Reload();
			}
			catch
			{
				LogoChangerLogger.LogError((object)("There was an issue loading your " + ConfigFileName));
				LogoChangerLogger.LogError((object)"Please check your config entries for spelling and format!");
			}
		}

		internal static void ReloadImagesFromFolder(object sender, FileSystemEventArgs e)
		{
			if (CheckIfStartScene() && _modEnabled.Value == Toggle.On)
			{
				Load("(file system)");
				FindMenuLogos();
			}
		}

		private static void ReloadImagesFromFolder(object sender, EventArgs e)
		{
			if (CheckIfStartScene() && _modEnabled.Value == Toggle.On)
			{
				Load("(setting changed)");
				FindMenuLogos();
			}
		}

		private static void Load(string calledMethod)
		{
			LogoChangerLogger.LogDebug((object)("ReloadImagesFromFolder " + calledMethod + " called"));
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				((Character)Player.m_localPlayer).Message((MessageType)2, "Reloading images...please wait...", 12, (Sprite)null);
			}
			if (_modEnabled.Value == Toggle.On)
			{
				_mainLogoSprite = LoadSprite(_mainMenuLogo.Value);
				_mistLogoSprite = LoadSprite(_mistMenuLogo.Value);
			}
		}

		private static Sprite LoadSprite(string name, bool isEmbed = false)
		{
			//IL_002c: 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)
			Texture2D val = LoadTexture(name, isEmbed);
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), Vector2.zero);
		}

		private static Texture2D LoadTexture(string name, bool isEmbed)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			string name2 = name;
			Texture2D val = new Texture2D(0, 0);
			string directoryName = Path.GetDirectoryName(Paths.ConfigPath);
			if (directoryName == null)
			{
				return val;
			}
			List<string> list = Directory.GetFiles(directoryName, "LogoChanger*.png", SearchOption.AllDirectories).OrderBy(Path.GetFileName).ToList();
			try
			{
				byte[] array = File.ReadAllBytes(list.Find((string x) => x.Contains(name2)));
				ImageConversion.LoadImage(val, array);
			}
			catch (Exception arg)
			{
				LogoChangerLogger.LogWarning((object)("The file " + name2 + " couldn't be found in the directory path. Please make sure you are naming your files correctly and they are location somewhere in the BepInEx/plugins folder.\n" + $" Optionally, you can turn off 'Use Custom Backgrounds' inside of your configuration file. If you no longer wish to see this error.\n {arg}"));
				val = null;
			}
			return val;
		}

		internal static bool CheckIfStartScene()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			Scene activeScene = SceneManager.GetActiveScene();
			return ((Scene)(ref activeScene)).name == "start";
		}

		private static void FindMenuLogos()
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_mainLogoSprite == (Object)null || (Object)(object)_mistLogoSprite == (Object)null)
			{
				return;
			}
			Transform obj = Utils.FindChild(FejdStartup.m_instance.m_mainMenu.transform, "Logo", (IterativeSearchType)0);
			Transform val = ((obj != null) ? ((Component)obj).transform : null);
			if (!((Object)(object)val == (Object)null))
			{
				TryUpdateLogo(val, "LOGO", _mainLogoSprite, "Couldn't find LOGO in hierarchy of the main menu or couldn't assign the LOGO sprite.");
				Transform obj2 = Utils.FindChild(val, "Ashlands", (IterativeSearchType)0);
				if (obj2 != null)
				{
					((Component)obj2).gameObject.SetActive(true);
				}
				Transform val2 = Utils.FindChild(val, "AshlandsLogo", (IterativeSearchType)0);
				if (!Object.op_Implicit((Object)(object)val2))
				{
					LogoChangerLogger.LogError((object)"Couldn't find AshlandsLogo in hierarchy of the main menu or couldn't assign the AshlandsLogo sprite.");
					throw new Exception();
				}
				if (!IsAshlandsLogoAdjusted)
				{
					val2.localPosition -= new Vector3(0f, 10f, 0f);
					IsAshlandsLogoAdjusted = true;
				}
				((Component)val2).GetComponent<Image>().sprite = _mistLogoSprite;
				string[] array = new string[4] { "Embers", "Embers (1)", "Embers (2)", "Embers (3)" };
				_ = new string[4] { "Embers", "Embers (1)", "Embers (2)", "Embers (3)" };
				string[] array2 = new string[7] { "Heat Distortion", "AshlandsLogo_Glow", "Embers", "Embers (1)", "Embers (2)", "Embers (3)", "Ash" };
				foreach (string text in array2)
				{
					TryDisableChild(val, text, "Couldn't find " + text + " in hierarchy of the main menu or couldn't disable " + text + " gameobject.");
				}
				array2 = array;
				foreach (string text2 in array2)
				{
					TryDisableChild(val, text2, "Couldn't find " + text2 + " in hierarchy of the main menu or couldn't disable " + text2 + " gameobject.");
				}
			}
		}

		private static void TryUpdateLogo(Transform parentTransform, string childName, Sprite logoSprite, string errorMessage)
		{
			try
			{
				((Component)Utils.FindChild(parentTransform, childName, (IterativeSearchType)0)).GetComponent<Image>().sprite = logoSprite;
			}
			catch (Exception arg)
			{
				LogoChangerLogger.LogError((object)$"{errorMessage} {arg}");
				throw;
			}
		}

		private static void TryDisableChild(Transform parentTransform, string childName, string errorMessage)
		{
			try
			{
				((Component)Utils.FindChild(parentTransform, childName, (IterativeSearchType)0)).gameObject.SetActive(false);
			}
			catch (Exception arg)
			{
				LogoChangerLogger.LogError((object)$"{errorMessage} {arg}");
				throw;
			}
		}

		static LogoChangerPlugin()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName;
			LogoChangerLogger = Logger.CreateLogSource("LogoChanger");
			IsAshlandsLogoAdjusted = false;
			_modEnabled = null;
			_mainMenuLogo = null;
			_mistMenuLogo = null;
			_mainLogoSprite = null;
			_mistLogoSprite = null;
		}
	}
	[HarmonyPatch(typeof(Player), "Awake")]
	internal static class PlayerAwakePatch
	{
		private static void Prefix(Player __instance)
		{
			if (!LogoChangerPlugin.CheckIfStartScene())
			{
				LogoChangerPlugin.IsAshlandsLogoAdjusted = false;
			}
			else
			{
				LogoChangerPlugin.ReloadImagesFromFolder(null, null);
			}
		}
	}
}