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.

463 lines
20 KiB

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