You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

272 lines
12 KiB

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using IPA.Config;
  10. using IPA.Old;
  11. using IPA.Utilities;
  12. using Mono.Cecil;
  13. using UnityEngine;
  14. using Logger = IPA.Logging.Logger;
  15. using static IPA.Loader.PluginLoader;
  16. namespace IPA.Loader
  17. {
  18. /// <summary>
  19. /// The manager class for all plugins.
  20. /// </summary>
  21. public static class PluginManager
  22. {
  23. #pragma warning disable CS0618 // Type or member is obsolete (IPlugin)
  24. /// <summary>
  25. /// An <see cref="IEnumerable"/> of new Beat Saber plugins
  26. /// </summary>
  27. internal static IEnumerable<IBeatSaberPlugin> BSPlugins
  28. {
  29. get
  30. {
  31. if(_bsPlugins == null)
  32. {
  33. LoadPlugins();
  34. }
  35. return (_bsPlugins ?? throw new InvalidOperationException()).Select(p => p.Plugin);
  36. }
  37. }
  38. private static List<PluginInfo> _bsPlugins;
  39. internal static IEnumerable<PluginInfo> BSMetas
  40. {
  41. get
  42. {
  43. if (_bsPlugins == null)
  44. {
  45. LoadPlugins();
  46. }
  47. return _bsPlugins;
  48. }
  49. }
  50. /// <summary>
  51. /// Gets info about the plugin with the specified name.
  52. /// </summary>
  53. /// <param name="name">the name of the plugin to get (must be an exact match)</param>
  54. /// <returns>the plugin info for the requested plugin or null</returns>
  55. public static PluginInfo GetPlugin(string name)
  56. {
  57. return BSMetas.FirstOrDefault(p => p.Metadata.Name == name);
  58. }
  59. /// <summary>
  60. /// Gets info about the plugin with the specified ModSaber name.
  61. /// </summary>
  62. /// <param name="name">the ModSaber name of the plugin to get (must be an exact match)</param>
  63. /// <returns>the plugin info for the requested plugin or null</returns>
  64. public static PluginInfo GetPluginFromModSaberName(string name)
  65. {
  66. return BSMetas.FirstOrDefault(p => p.Metadata.Id == name);
  67. }
  68. /// <summary>
  69. /// Gets a list of all BSIPA plugins.
  70. /// </summary>
  71. public static IEnumerable<PluginInfo> AllPlugins => BSMetas;
  72. /// <summary>
  73. /// An <see cref="IEnumerable"/> of old IPA plugins
  74. /// </summary>
  75. [Obsolete("I mean, IPlugin shouldn't be used, so why should this? Not renaming to extend support for old plugins.")]
  76. public static IEnumerable<IPlugin> Plugins
  77. {
  78. get
  79. {
  80. if (_ipaPlugins == null)
  81. {
  82. LoadPlugins();
  83. }
  84. return _ipaPlugins;
  85. }
  86. }
  87. private static List<IPlugin> _ipaPlugins;
  88. internal static IConfigProvider SelfConfigProvider { get; set; }
  89. private static void LoadPlugins()
  90. {
  91. string pluginDirectory = Path.Combine(Environment.CurrentDirectory, "Plugins");
  92. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  93. // so we need to resort to P/Invoke
  94. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  95. _bsPlugins = new List<PluginInfo>();
  96. _ipaPlugins = new List<IPlugin>();
  97. if (!Directory.Exists(pluginDirectory)) return;
  98. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  99. if (!Directory.Exists(cacheDir))
  100. {
  101. Directory.CreateDirectory(cacheDir);
  102. }
  103. else
  104. {
  105. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  106. {
  107. File.Delete(plugin);
  108. }
  109. }
  110. // initialize BSIPA plugins first
  111. _bsPlugins.AddRange(PluginLoader.LoadPlugins());
  112. //Copy plugins to .cache
  113. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  114. foreach (string s in originalPlugins)
  115. {
  116. if (PluginsMetadata.Select(m => m.File.FullName).Contains(s)) continue;
  117. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  118. #region Fix assemblies for refactor
  119. var module = ModuleDefinition.ReadModule(Path.Combine(pluginDirectory, s));
  120. foreach (var @ref in module.AssemblyReferences)
  121. { // fix assembly references
  122. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  123. {
  124. @ref.Name = "IPA.Loader";
  125. }
  126. }
  127. foreach (var @ref in module.GetTypeReferences())
  128. { // fix type references
  129. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  130. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  131. if (@ref.FullName == "IllusionPlugin.IBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  132. if (@ref.FullName == "IllusionPlugin.IEnhancedBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  133. if (@ref.FullName == "IllusionPlugin.BeatSaber.ModsaberModInfo") @ref.Namespace = "IPA"; //@ref.Name = "";
  134. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  135. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  136. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  137. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  138. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  139. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  140. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  141. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  142. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  143. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  144. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  145. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  146. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  147. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  148. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  149. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  150. if (@ref.Namespace == "IllusionInjector.Updating.ModsaberML") @ref.Namespace = "IPA.Updating.ModSaber"; //@ref.Name = "";
  151. }
  152. module.Write(pluginCopy);
  153. #endregion
  154. }
  155. //Load copied plugins
  156. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  157. foreach (string s in copiedPlugins)
  158. {
  159. var result = LoadPluginsFromFile(s);
  160. _ipaPlugins.AddRange(result.Item2);
  161. }
  162. Logger.log.Info(exeName);
  163. Logger.log.Info($"Running on Unity {Application.unityVersion}");
  164. Logger.log.Info($"Game version {BeatSaber.GameVersion}");
  165. Logger.log.Info("-----------------------------");
  166. Logger.log.Info($"Loading plugins from {Utils.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  167. Logger.log.Info("-----------------------------");
  168. foreach (var plugin in _bsPlugins)
  169. {
  170. Logger.log.Info($"{plugin.Metadata.Name} ({plugin.Metadata.Id}): {plugin.Metadata.Version}");
  171. }
  172. Logger.log.Info("-----------------------------");
  173. foreach (var plugin in _ipaPlugins)
  174. {
  175. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  176. }
  177. Logger.log.Info("-----------------------------");
  178. }
  179. private static Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>> LoadPluginsFromFile(string file)
  180. {
  181. List<IPlugin> ipaPlugins = new List<IPlugin>();
  182. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  183. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(null, ipaPlugins);
  184. T OptionalGetPlugin<T>(Type t) where T : class
  185. {
  186. // use typeof() to allow for easier renaming (in an ideal world this compiles to a string, but ¯\_(ツ)_/¯)
  187. if (t.GetInterface(typeof(T).Name) != null)
  188. {
  189. try
  190. {
  191. T pluginInstance = Activator.CreateInstance(t) as T;
  192. return pluginInstance;
  193. }
  194. catch (Exception e)
  195. {
  196. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  197. }
  198. }
  199. return null;
  200. }
  201. try
  202. {
  203. Assembly assembly = Assembly.LoadFrom(file);
  204. foreach (Type t in assembly.GetTypes())
  205. {
  206. IPlugin ipaPlugin = OptionalGetPlugin<IPlugin>(t);
  207. if (ipaPlugin != null)
  208. {
  209. ipaPlugins.Add(ipaPlugin);
  210. }
  211. }
  212. }
  213. catch (ReflectionTypeLoadException e)
  214. {
  215. Logger.loader.Error($"Could not load the following types from {Path.GetFileName(file)}:");
  216. Logger.loader.Error($" {string.Join("\n ", e.LoaderExceptions?.Select(e1 => e1?.Message) ?? new string[0])}");
  217. }
  218. catch (Exception e)
  219. {
  220. Logger.loader.Error($"Could not load {Path.GetFileName(file)}!");
  221. Logger.loader.Error(e);
  222. }
  223. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(null, ipaPlugins);
  224. }
  225. internal static class AppInfo
  226. {
  227. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = false)]
  228. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  229. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  230. public static string StartupPath
  231. {
  232. get
  233. {
  234. StringBuilder stringBuilder = new StringBuilder(260);
  235. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  236. return stringBuilder.ToString();
  237. }
  238. }
  239. }
  240. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  241. }
  242. }