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.

294 lines
13 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. /*var selfPlugin = new PluginInfo
  156. {
  157. Filename = Path.Combine(BeatSaber.InstallPath, "IPA.exe"),
  158. Plugin = SelfPlugin.Instance
  159. };
  160. selfPlugin.Metadata.Manifest = new PluginManifest
  161. {
  162. Author = "DaNike",
  163. Features = new string[0],
  164. Description = "",
  165. Version = new SemVer.Version(SelfConfig.IPA_Version),
  166. GameVersion = BeatSaber.GameVersion,
  167. Id = "beatsaber-ipa-reloaded"
  168. };
  169. selfPlugin.Metadata.File = new FileInfo(Path.Combine(BeatSaber.InstallPath, "IPA.exe"));
  170. _bsPlugins.Add(selfPlugin);*/
  171. //Load copied plugins
  172. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  173. foreach (string s in copiedPlugins)
  174. {
  175. var result = LoadPluginsFromFile(s);
  176. _ipaPlugins.AddRange(result.Item2);
  177. }
  178. Logger.log.Info(exeName);
  179. Logger.log.Info($"Running on Unity {Application.unityVersion}");
  180. Logger.log.Info($"Game version {BeatSaber.GameVersion}");
  181. Logger.log.Info("-----------------------------");
  182. Logger.log.Info($"Loading plugins from {Utils.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  183. Logger.log.Info("-----------------------------");
  184. foreach (var plugin in _bsPlugins)
  185. {
  186. Logger.log.Info($"{plugin.Metadata.Name}: {plugin.Metadata.Version}");
  187. }
  188. Logger.log.Info("-----------------------------");
  189. foreach (var plugin in _ipaPlugins)
  190. {
  191. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  192. }
  193. Logger.log.Info("-----------------------------");
  194. }
  195. private static Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>> LoadPluginsFromFile(string file)
  196. {
  197. List<IPlugin> ipaPlugins = new List<IPlugin>();
  198. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  199. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(null, ipaPlugins);
  200. T OptionalGetPlugin<T>(Type t) where T : class
  201. {
  202. // use typeof() to allow for easier renaming (in an ideal world this compiles to a string, but ¯\_(ツ)_/¯)
  203. if (t.GetInterface(typeof(T).Name) != null)
  204. {
  205. try
  206. {
  207. T pluginInstance = Activator.CreateInstance(t) as T;
  208. /*string[] filter = null;
  209. if (typeof(T) == typeof(IPlugin) && pluginInstance is IEnhancedPlugin enhancedPlugin)
  210. filter = enhancedPlugin.Filter;
  211. else if (pluginInstance is IGenericEnhancedPlugin plugin)
  212. filter = plugin.Filter;*/
  213. //if (filter == null || filter.Contains(exeName, StringComparer.OrdinalIgnoreCase))
  214. return pluginInstance;
  215. }
  216. catch (Exception e)
  217. {
  218. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  219. }
  220. }
  221. return null;
  222. }
  223. try
  224. {
  225. Assembly assembly = Assembly.LoadFrom(file);
  226. foreach (Type t in assembly.GetTypes())
  227. {
  228. IPlugin ipaPlugin = OptionalGetPlugin<IPlugin>(t);
  229. if (ipaPlugin != null)
  230. {
  231. ipaPlugins.Add(ipaPlugin);
  232. }
  233. }
  234. }
  235. catch (Exception e)
  236. {
  237. Logger.loader.Error($"Could not load {Path.GetFileName(file)}! {e}");
  238. }
  239. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(null, ipaPlugins);
  240. }
  241. internal class AppInfo
  242. {
  243. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = false)]
  244. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  245. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  246. public static string StartupPath
  247. {
  248. get
  249. {
  250. StringBuilder stringBuilder = new StringBuilder(260);
  251. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  252. return stringBuilder.ToString();
  253. }
  254. }
  255. }
  256. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  257. }
  258. }