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.

475 lines
21 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. using IPA.Loader.Features;
  17. #if NET3
  18. using Net3_Proxy;
  19. using Path = Net3_Proxy.Path;
  20. using File = Net3_Proxy.File;
  21. using Directory = Net3_Proxy.Directory;
  22. #endif
  23. namespace IPA.Loader
  24. {
  25. /// <summary>
  26. /// The manager class for all plugins.
  27. /// </summary>
  28. public static class PluginManager
  29. {
  30. #pragma warning disable CS0618 // Type or member is obsolete (IPlugin)
  31. /// <summary>
  32. /// An <see cref="IEnumerable"/> of new Beat Saber plugins
  33. /// </summary>
  34. private static List<PluginExecutor> _bsPlugins;
  35. internal static IEnumerable<PluginExecutor> BSMetas => _bsPlugins;
  36. /// <summary>
  37. /// Gets info about the plugin with the specified name.
  38. /// </summary>
  39. /// <param name="name">the name of the plugin to get (must be an exact match)</param>
  40. /// <returns>the plugin info for the requested plugin or null</returns>
  41. public static PluginMetadata GetPlugin(string name)
  42. => BSMetas.Select(p => p.Metadata).FirstOrDefault(p => p.Name == name);
  43. /// <summary>
  44. /// Gets info about the plugin with the specified ModSaber name.
  45. /// </summary>
  46. /// <param name="name">the ModSaber name of the plugin to get (must be an exact match)</param>
  47. /// <returns>the plugin info for the requested plugin or null</returns>
  48. [Obsolete("Old name. Use GetPluginFromId instead.")]
  49. public static PluginMetadata GetPluginFromModSaberName(string name) => GetPluginFromId(name);
  50. /// <summary>
  51. /// Gets info about the plugin with the specified ID.
  52. /// </summary>
  53. /// <param name="name">the ID 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 PluginMetadata GetPluginFromId(string name)
  56. => BSMetas.Select(p => p.Metadata).FirstOrDefault(p => p.Id == name);
  57. /// <summary>
  58. /// Gets a disabled plugin's metadata by its name.
  59. /// </summary>
  60. /// <param name="name">the name of the disabled plugin to get</param>
  61. /// <returns>the metadata for the corresponding plugin</returns>
  62. public static PluginMetadata GetDisabledPlugin(string name) =>
  63. DisabledPlugins.FirstOrDefault(p => p.Name == name);
  64. /// <summary>
  65. /// Gets a disabled plugin's metadata by its ID.
  66. /// </summary>
  67. /// <param name="name">the ID of the disabled plugin to get</param>
  68. /// <returns>the metadata for the corresponding plugin</returns>
  69. public static PluginMetadata GetDisabledPluginFromId(string name) =>
  70. DisabledPlugins.FirstOrDefault(p => p.Id == name);
  71. // TODO: rewrite below
  72. /*
  73. /// <summary>
  74. /// Disables a plugin, and all dependents.
  75. /// </summary>
  76. /// <param name="plugin">the plugin to disable</param>
  77. /// <returns>whether or not it needs a restart to enable</returns>
  78. public static bool DisablePlugin(PluginInfo plugin)
  79. {
  80. if (plugin == null) return false;
  81. if (plugin.Metadata.IsBare)
  82. {
  83. Logger.loader.Warn($"Trying to disable bare manifest");
  84. return false;
  85. }
  86. if (IsDisabled(plugin.Metadata)) return false;
  87. var needsRestart = false;
  88. Logger.loader.Info($"Disabling {plugin.Metadata.Name}");
  89. var dependents = BSMetas.Where(m => m.Metadata.Dependencies.Contains(plugin.Metadata)).ToList();
  90. needsRestart = dependents.Aggregate(needsRestart, (b, p) => DisablePlugin(p) || b);
  91. DisabledConfig.Instance.DisabledModIds.Add(plugin.Metadata.Id ?? plugin.Metadata.Name);
  92. if (!needsRestart && plugin.Plugin is IDisablablePlugin disable)
  93. {
  94. try
  95. {
  96. disable.OnDisable();
  97. }
  98. catch (Exception e)
  99. {
  100. Logger.loader.Error($"Error occurred trying to disable {plugin.Metadata.Name}");
  101. Logger.loader.Error(e);
  102. }
  103. if (needsRestart)
  104. Logger.loader.Warn($"Disablable plugin has non-disablable dependents; some things may not work properly");
  105. }
  106. else needsRestart = true;
  107. runtimeDisabled.Add(plugin);
  108. _bsPlugins.Remove(plugin);
  109. try
  110. {
  111. PluginDisabled?.Invoke(plugin.Metadata, needsRestart);
  112. }
  113. catch (Exception e)
  114. {
  115. Logger.loader.Error($"Error occurred invoking disable event for {plugin.Metadata.Name}");
  116. Logger.loader.Error(e);
  117. }
  118. return needsRestart;
  119. }
  120. /// <summary>
  121. /// Disables a plugin, and all dependents.
  122. /// </summary>
  123. /// <param name="pluginId">the ID, or name if the ID is null, of the plugin to disable</param>
  124. /// <returns>whether a restart is needed to activate</returns>
  125. public static bool DisablePlugin(string pluginId) => DisablePlugin(GetPluginFromId(pluginId) ?? GetPlugin(pluginId));
  126. /// <summary>
  127. /// Enables a plugin that had been previously disabled.
  128. /// </summary>
  129. /// <param name="plugin">the plugin to enable</param>
  130. /// <returns>whether a restart is needed to activate</returns>
  131. public static bool EnablePlugin(PluginMetadata plugin)
  132. { // TODO: fix some of this behaviour, by adding better support for runtime enable/disable of mods
  133. if (plugin == null) return false;
  134. if (plugin.IsBare)
  135. {
  136. Logger.loader.Warn($"Trying to enable bare manifest");
  137. return false;
  138. }
  139. if (!IsDisabled(plugin)) return false;
  140. Logger.loader.Info($"Enabling {plugin.Name}");
  141. DisabledConfig.Instance.DisabledModIds.Remove(plugin.Id ?? plugin.Name);
  142. var needsRestart = true;
  143. var depsNeedRestart = plugin.Dependencies.Aggregate(false, (b, p) => EnablePlugin(p) || b);
  144. var runtimeInfo = runtimeDisabled.FirstOrDefault(p => p.Metadata == plugin);
  145. if (runtimeInfo != null && runtimeInfo.Plugin is IPlugin newPlugin)
  146. {
  147. try
  148. {
  149. newPlugin.OnEnable();
  150. }
  151. catch (Exception e)
  152. {
  153. Logger.loader.Error($"Error occurred trying to enable {plugin.Name}");
  154. Logger.loader.Error(e);
  155. }
  156. needsRestart = false;
  157. }
  158. else
  159. {
  160. PluginLoader.DisabledPlugins.Remove(plugin);
  161. if (runtimeInfo == null)
  162. {
  163. runtimeInfo = InitPlugin(plugin, AllPlugins.Select(i => i.Metadata));
  164. needsRestart = false;
  165. }
  166. }
  167. if (runtimeInfo != null)
  168. runtimeDisabled.Remove(runtimeInfo);
  169. _bsPlugins.Add(runtimeInfo);
  170. try
  171. {
  172. PluginEnabled?.Invoke(runtimeInfo, needsRestart || depsNeedRestart);
  173. }
  174. catch (Exception e)
  175. {
  176. Logger.loader.Error($"Error occurred invoking enable event for {plugin.Name}");
  177. Logger.loader.Error(e);
  178. }
  179. return needsRestart || depsNeedRestart;
  180. }
  181. /// <summary>
  182. /// Enables a plugin that had been previously disabled.
  183. /// </summary>
  184. /// <param name="pluginId">the ID, or name if the ID is null, of the plugin to enable</param>
  185. /// <returns>whether a restart is needed to activate</returns>
  186. public static bool EnablePlugin(string pluginId) =>
  187. EnablePlugin(GetDisabledPluginFromId(pluginId) ?? GetDisabledPlugin(pluginId));*/
  188. /// <summary>
  189. /// Checks if a given plugin is disabled.
  190. /// </summary>
  191. /// <param name="meta">the plugin to check</param>
  192. /// <returns><see langword="true"/> if the plugin is disabled, <see langword="false"/> otherwise.</returns>
  193. public static bool IsDisabled(PluginMetadata meta) => DisabledPlugins.Contains(meta);
  194. /// <summary>
  195. /// Checks if a given plugin is enabled.
  196. /// </summary>
  197. /// <param name="meta">the plugin to check</param>
  198. /// <returns><see langword="true"/> if the plugin is enabled, <see langword="false"/> otherwise.</returns>
  199. public static bool IsEnabled(PluginMetadata meta) => BSMetas.Any(p => p.Metadata == meta);
  200. private static readonly List<PluginInfo> runtimeDisabled = new List<PluginInfo>();
  201. /// <summary>
  202. /// Gets a list of disabled BSIPA plugins.
  203. /// </summary>
  204. /// <value>a collection of all disabled plugins as <see cref="PluginMetadata"/></value>
  205. public static IEnumerable<PluginMetadata> DisabledPlugins => PluginLoader.DisabledPlugins.Concat(runtimeDisabled.Select(p => p.Metadata));
  206. /// <summary>
  207. /// An invoker for the <see cref="PluginEnabled"/> event.
  208. /// </summary>
  209. /// <param name="plugin">the plugin that was enabled</param>
  210. /// <param name="needsRestart">whether it needs a restart to take effect</param>
  211. public delegate void PluginEnableDelegate(PluginInfo plugin, bool needsRestart);
  212. /// <summary>
  213. /// An invoker for the <see cref="PluginDisabled"/> event.
  214. /// </summary>
  215. /// <param name="plugin">the plugin that was disabled</param>
  216. /// <param name="needsRestart">whether it needs a restart to take effect</param>
  217. public delegate void PluginDisableDelegate(PluginMetadata plugin, bool needsRestart);
  218. /// <summary>
  219. /// Called whenever a plugin is enabled.
  220. /// </summary>
  221. public static event PluginEnableDelegate PluginEnabled;
  222. /// <summary>
  223. /// Called whenever a plugin is disabled.
  224. /// </summary>
  225. public static event PluginDisableDelegate PluginDisabled;
  226. /// <summary>
  227. /// Gets a list of all BSIPA plugins.
  228. /// </summary>
  229. /// <value>a collection of all enabled plugins as <see cref="PluginInfo"/>s</value>
  230. public static IEnumerable<PluginMetadata> AllPlugins => BSMetas.Select(p => p.Metadata);
  231. /*
  232. /// <summary>
  233. /// Converts a plugin's metadata to a <see cref="PluginInfo"/>.
  234. /// </summary>
  235. /// <param name="meta">the metadata</param>
  236. /// <returns>the plugin info</returns>
  237. public static PluginInfo InfoFromMetadata(PluginMetadata meta)
  238. {
  239. if (IsDisabled(meta))
  240. return runtimeDisabled.FirstOrDefault(p => p.Metadata == meta);
  241. else
  242. return AllPlugins.FirstOrDefault(p => p == meta);
  243. }
  244. */
  245. /// <summary>
  246. /// An <see cref="IEnumerable"/> of old IPA plugins.
  247. /// </summary>
  248. /// <value>all legacy plugin instances</value>
  249. [Obsolete("I mean, IPlugin shouldn't be used, so why should this? Not renaming to extend support for old plugins.")]
  250. public static IEnumerable<Old.IPlugin> Plugins => _ipaPlugins;
  251. private static List<Old.IPlugin> _ipaPlugins;
  252. internal static IConfigProvider SelfConfigProvider { get; set; }
  253. internal static void Load()
  254. {
  255. string pluginDirectory = BeatSaber.PluginsPath;
  256. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  257. // so we need to resort to P/Invoke
  258. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  259. _bsPlugins = new List<PluginExecutor>();
  260. _ipaPlugins = new List<Old.IPlugin>();
  261. if (!Directory.Exists(pluginDirectory)) return;
  262. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  263. if (!Directory.Exists(cacheDir))
  264. {
  265. Directory.CreateDirectory(cacheDir);
  266. }
  267. else
  268. {
  269. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  270. {
  271. File.Delete(plugin);
  272. }
  273. }
  274. // initialize BSIPA plugins first
  275. _bsPlugins.AddRange(PluginLoader.LoadPlugins());
  276. var metadataPaths = PluginsMetadata.Select(m => m.File.FullName).ToList();
  277. var ignoredPaths = ignoredPlugins.Select(m => m.Key.File.FullName).ToList();
  278. var disabledPaths = DisabledPlugins.Select(m => m.File.FullName).ToList();
  279. //Copy plugins to .cache
  280. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  281. foreach (string s in originalPlugins)
  282. {
  283. if (metadataPaths.Contains(s)) continue;
  284. if (ignoredPaths.Contains(s)) continue;
  285. if (disabledPaths.Contains(s)) continue;
  286. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  287. #region Fix assemblies for refactor
  288. var module = ModuleDefinition.ReadModule(Path.Combine(pluginDirectory, s));
  289. foreach (var @ref in module.AssemblyReferences)
  290. { // fix assembly references
  291. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  292. {
  293. @ref.Name = "IPA.Loader";
  294. }
  295. }
  296. foreach (var @ref in module.GetTypeReferences())
  297. { // fix type references
  298. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  299. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  300. if (@ref.FullName == "IllusionPlugin.IBeatSaberPlugin") { @ref.Namespace = "IPA"; @ref.Name = nameof(IPlugin); }
  301. if (@ref.FullName == "IllusionPlugin.IEnhancedBeatSaberPlugin") { @ref.Namespace = "IPA"; @ref.Name = nameof(IEnhancedPlugin); }
  302. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  303. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  304. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  305. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  306. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  307. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  308. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  309. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  310. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  311. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  312. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  313. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  314. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  315. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  316. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  317. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  318. }
  319. module.Write(pluginCopy);
  320. #endregion
  321. }
  322. //Load copied plugins
  323. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  324. foreach (string s in copiedPlugins)
  325. {
  326. var result = LoadPluginsFromFile(s);
  327. if (result == null) continue;
  328. _ipaPlugins.AddRange(result.NonNull());
  329. }
  330. Logger.log.Info(exeName);
  331. Logger.log.Info($"Running on Unity {Application.unityVersion}");
  332. Logger.log.Info($"Game version {BeatSaber.GameVersion}");
  333. Logger.log.Info("-----------------------------");
  334. Logger.log.Info($"Loading plugins from {Utils.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  335. Logger.log.Info("-----------------------------");
  336. foreach (var plugin in _bsPlugins)
  337. {
  338. Logger.log.Info($"{plugin.Metadata.Name} ({plugin.Metadata.Id}): {plugin.Metadata.Version}");
  339. }
  340. Logger.log.Info("-----------------------------");
  341. foreach (var plugin in _ipaPlugins)
  342. {
  343. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  344. }
  345. Logger.log.Info("-----------------------------");
  346. }
  347. private static IEnumerable<Old.IPlugin> LoadPluginsFromFile(string file)
  348. {
  349. var ipaPlugins = new List<Old.IPlugin>();
  350. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  351. return ipaPlugins;
  352. T OptionalGetPlugin<T>(Type t) where T : class
  353. {
  354. if (t.FindInterfaces((t, o) => t == (o as Type), typeof(T)).Length > 0)
  355. {
  356. try
  357. {
  358. T pluginInstance = Activator.CreateInstance(t) as T;
  359. return pluginInstance;
  360. }
  361. catch (Exception e)
  362. {
  363. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  364. }
  365. }
  366. return null;
  367. }
  368. try
  369. {
  370. Assembly assembly = Assembly.LoadFrom(file);
  371. foreach (Type t in assembly.GetTypes())
  372. {
  373. var ipaPlugin = OptionalGetPlugin<Old.IPlugin>(t);
  374. if (ipaPlugin != null)
  375. {
  376. ipaPlugins.Add(ipaPlugin);
  377. }
  378. }
  379. }
  380. catch (ReflectionTypeLoadException e)
  381. {
  382. Logger.loader.Error($"Could not load the following types from {Path.GetFileName(file)}:");
  383. Logger.loader.Error($" {string.Join("\n ", e.LoaderExceptions?.Select(e1 => e1?.Message).StrJP() ?? new string[0])}");
  384. }
  385. catch (Exception e)
  386. {
  387. Logger.loader.Error($"Could not load {Path.GetFileName(file)}!");
  388. Logger.loader.Error(e);
  389. }
  390. return ipaPlugins;
  391. }
  392. internal static class AppInfo
  393. {
  394. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = false)]
  395. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  396. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  397. public static string StartupPath
  398. {
  399. get
  400. {
  401. StringBuilder stringBuilder = new StringBuilder(260);
  402. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  403. return stringBuilder.ToString();
  404. }
  405. }
  406. }
  407. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  408. }
  409. }