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.

287 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. /// An <see cref="IEnumerable"/> of old IPA plugins
  70. /// </summary>
  71. [Obsolete("I mean, IPlugin shouldn't be used, so why should this? Not renaming to extend support for old plugins.")]
  72. public static IEnumerable<IPlugin> Plugins
  73. {
  74. get
  75. {
  76. if (_ipaPlugins == null)
  77. {
  78. LoadPlugins();
  79. }
  80. return _ipaPlugins;
  81. }
  82. }
  83. private static List<IPlugin> _ipaPlugins;
  84. internal static IConfigProvider SelfConfigProvider { get; set; }
  85. private static void LoadPlugins()
  86. {
  87. string pluginDirectory = Path.Combine(Environment.CurrentDirectory, "Plugins");
  88. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  89. // so we need to resort to P/Invoke
  90. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  91. _bsPlugins = new List<PluginInfo>();
  92. _ipaPlugins = new List<IPlugin>();
  93. if (!Directory.Exists(pluginDirectory)) return;
  94. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  95. if (!Directory.Exists(cacheDir))
  96. {
  97. Directory.CreateDirectory(cacheDir);
  98. }
  99. else
  100. {
  101. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  102. {
  103. File.Delete(plugin);
  104. }
  105. }
  106. //Copy plugins to .cache
  107. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  108. foreach (string s in originalPlugins)
  109. {
  110. if (PluginsMetadata.Select(m => m.File.Name).Contains(s)) continue;
  111. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  112. #region Fix assemblies for refactor
  113. var module = ModuleDefinition.ReadModule(Path.Combine(pluginDirectory, s));
  114. foreach (var @ref in module.AssemblyReferences)
  115. { // fix assembly references
  116. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  117. {
  118. @ref.Name = "IPA.Loader";
  119. }
  120. }
  121. foreach (var @ref in module.GetTypeReferences())
  122. { // fix type references
  123. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  124. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  125. if (@ref.FullName == "IllusionPlugin.IBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  126. if (@ref.FullName == "IllusionPlugin.IEnhancedBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  127. if (@ref.FullName == "IllusionPlugin.BeatSaber.ModsaberModInfo") @ref.Namespace = "IPA"; //@ref.Name = "";
  128. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  129. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  130. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  131. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  132. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  133. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  134. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  135. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  136. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  137. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  138. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  139. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  140. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  141. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  142. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  143. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  144. if (@ref.Namespace == "IllusionInjector.Updating.ModsaberML") @ref.Namespace = "IPA.Updating.ModSaber"; //@ref.Name = "";
  145. }
  146. module.Write(pluginCopy);
  147. #endregion
  148. }
  149. /*var selfPlugin = new PluginInfo
  150. {
  151. Filename = Path.Combine(BeatSaber.InstallPath, "IPA.exe"),
  152. Plugin = SelfPlugin.Instance
  153. };
  154. selfPlugin.Metadata.Manifest = new PluginManifest
  155. {
  156. Author = "DaNike",
  157. Features = new string[0],
  158. Description = "",
  159. Version = new SemVer.Version(SelfConfig.IPA_Version),
  160. GameVersion = BeatSaber.GameVersion,
  161. Id = "beatsaber-ipa-reloaded"
  162. };
  163. selfPlugin.Metadata.File = new FileInfo(Path.Combine(BeatSaber.InstallPath, "IPA.exe"));
  164. _bsPlugins.Add(selfPlugin);*/
  165. //Load copied plugins
  166. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  167. foreach (string s in copiedPlugins)
  168. {
  169. var result = LoadPluginsFromFile(s);
  170. _ipaPlugins.AddRange(result.Item2);
  171. }
  172. _bsPlugins.AddRange(PluginLoader.LoadPlugins());
  173. Logger.log.Info(exeName);
  174. Logger.log.Info($"Running on Unity {Application.unityVersion}");
  175. Logger.log.Info($"Game version {BeatSaber.GameVersion}");
  176. Logger.log.Info("-----------------------------");
  177. Logger.log.Info($"Loading plugins from {LoneFunctions.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  178. Logger.log.Info("-----------------------------");
  179. foreach (var plugin in _bsPlugins)
  180. {
  181. Logger.log.Info($"{plugin.Metadata.Name}: {plugin.Metadata.Version}");
  182. }
  183. Logger.log.Info("-----------------------------");
  184. foreach (var plugin in _ipaPlugins)
  185. {
  186. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  187. }
  188. Logger.log.Info("-----------------------------");
  189. }
  190. private static Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>> LoadPluginsFromFile(string file)
  191. {
  192. List<IPlugin> ipaPlugins = new List<IPlugin>();
  193. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  194. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(null, ipaPlugins);
  195. T OptionalGetPlugin<T>(Type t) where T : class
  196. {
  197. // use typeof() to allow for easier renaming (in an ideal world this compiles to a string, but ¯\_(ツ)_/¯)
  198. if (t.GetInterface(typeof(T).Name) != null)
  199. {
  200. try
  201. {
  202. T pluginInstance = Activator.CreateInstance(t) as T;
  203. /*string[] filter = null;
  204. if (typeof(T) == typeof(IPlugin) && pluginInstance is IEnhancedPlugin enhancedPlugin)
  205. filter = enhancedPlugin.Filter;
  206. else if (pluginInstance is IGenericEnhancedPlugin plugin)
  207. filter = plugin.Filter;*/
  208. //if (filter == null || filter.Contains(exeName, StringComparer.OrdinalIgnoreCase))
  209. return pluginInstance;
  210. }
  211. catch (Exception e)
  212. {
  213. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  214. }
  215. }
  216. return null;
  217. }
  218. try
  219. {
  220. Assembly assembly = Assembly.LoadFrom(file);
  221. foreach (Type t in assembly.GetTypes())
  222. {
  223. IPlugin ipaPlugin = OptionalGetPlugin<IPlugin>(t);
  224. if (ipaPlugin != null)
  225. {
  226. ipaPlugins.Add(ipaPlugin);
  227. }
  228. }
  229. }
  230. catch (Exception e)
  231. {
  232. Logger.loader.Error($"Could not load {Path.GetFileName(file)}! {e}");
  233. }
  234. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(null, ipaPlugins);
  235. }
  236. internal class AppInfo
  237. {
  238. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = false)]
  239. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  240. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  241. public static string StartupPath
  242. {
  243. get
  244. {
  245. StringBuilder stringBuilder = new StringBuilder(260);
  246. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  247. return stringBuilder.ToString();
  248. }
  249. }
  250. }
  251. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  252. }
  253. }