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.

476 lines
21 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. using System.Threading.Tasks;
  18. #if NET3
  19. using Net3_Proxy;
  20. using Path = Net3_Proxy.Path;
  21. using File = Net3_Proxy.File;
  22. using Directory = Net3_Proxy.Directory;
  23. #endif
  24. namespace IPA.Loader
  25. {
  26. /// <summary>
  27. /// The manager class for all plugins.
  28. /// </summary>
  29. public static class PluginManager
  30. {
  31. #pragma warning disable CS0618 // Type or member is obsolete (IPlugin)
  32. private static List<PluginExecutor> _bsPlugins;
  33. internal static IEnumerable<PluginExecutor> BSMetas => _bsPlugins;
  34. /// <summary>
  35. /// Gets info about the enabled plugin with the specified name.
  36. /// </summary>
  37. /// <param name="name">the name of the plugin to get (must be an exact match)</param>
  38. /// <returns>the plugin metadata for the requested plugin or <see langword="null"/> if it doesn't exist or is disabled</returns>
  39. public static PluginMetadata GetPlugin(string name)
  40. => BSMetas.Select(p => p.Metadata).FirstOrDefault(p => p.Name == name);
  41. /// <summary>
  42. /// Gets info about the enabled plugin with the specified ID.
  43. /// </summary>
  44. /// <param name="name">the ID name of the plugin to get (must be an exact match)</param>
  45. /// <returns>the plugin metadata for the requested plugin or <see langword="null"/> if it doesn't exist or is disabled</returns>
  46. public static PluginMetadata GetPluginFromId(string name)
  47. => BSMetas.Select(p => p.Metadata).FirstOrDefault(p => p.Id == name);
  48. /// <summary>
  49. /// Gets a disabled plugin's metadata by its name.
  50. /// </summary>
  51. /// <param name="name">the name of the disabled plugin to get</param>
  52. /// <returns>the metadata for the corresponding plugin</returns>
  53. public static PluginMetadata GetDisabledPlugin(string name) =>
  54. DisabledPlugins.FirstOrDefault(p => p.Name == name);
  55. /// <summary>
  56. /// Gets a disabled plugin's metadata by its ID.
  57. /// </summary>
  58. /// <param name="name">the ID of the disabled plugin to get</param>
  59. /// <returns>the metadata for the corresponding plugin</returns>
  60. public static PluginMetadata GetDisabledPluginFromId(string name) =>
  61. DisabledPlugins.FirstOrDefault(p => p.Id == name);
  62. /// <summary>
  63. /// Creates a new transaction for mod enabling and disabling mods simultaneously.
  64. /// </summary>
  65. /// <returns>a new <see cref="StateTransitionTransaction"/> that captures the current state of loaded mods</returns>
  66. public static StateTransitionTransaction PluginStateTransaction()
  67. => new StateTransitionTransaction(AllPlugins, DisabledPlugins);
  68. internal static Task CommitTransaction(StateTransitionTransaction transaction)
  69. {
  70. throw new NotImplementedException();
  71. }
  72. // TODO: rewrite below
  73. /*
  74. /// <summary>
  75. /// Disables a plugin, and all dependents.
  76. /// </summary>
  77. /// <param name="plugin">the plugin to disable</param>
  78. /// <returns>whether or not it needs a restart to enable</returns>
  79. public static bool DisablePlugin(PluginInfo plugin)
  80. {
  81. if (plugin == null) return false;
  82. if (plugin.Metadata.IsBare)
  83. {
  84. Logger.loader.Warn($"Trying to disable bare manifest");
  85. return false;
  86. }
  87. if (IsDisabled(plugin.Metadata)) return false;
  88. var needsRestart = false;
  89. Logger.loader.Info($"Disabling {plugin.Metadata.Name}");
  90. var dependents = BSMetas.Where(m => m.Metadata.Dependencies.Contains(plugin.Metadata)).ToList();
  91. needsRestart = dependents.Aggregate(needsRestart, (b, p) => DisablePlugin(p) || b);
  92. DisabledConfig.Instance.DisabledModIds.Add(plugin.Metadata.Id ?? plugin.Metadata.Name);
  93. if (!needsRestart && plugin.Plugin is IDisablablePlugin disable)
  94. {
  95. try
  96. {
  97. disable.OnDisable();
  98. }
  99. catch (Exception e)
  100. {
  101. Logger.loader.Error($"Error occurred trying to disable {plugin.Metadata.Name}");
  102. Logger.loader.Error(e);
  103. }
  104. if (needsRestart)
  105. Logger.loader.Warn($"Disablable plugin has non-disablable dependents; some things may not work properly");
  106. }
  107. else needsRestart = true;
  108. runtimeDisabled.Add(plugin);
  109. _bsPlugins.Remove(plugin);
  110. try
  111. {
  112. PluginDisabled?.Invoke(plugin.Metadata, needsRestart);
  113. }
  114. catch (Exception e)
  115. {
  116. Logger.loader.Error($"Error occurred invoking disable event for {plugin.Metadata.Name}");
  117. Logger.loader.Error(e);
  118. }
  119. return needsRestart;
  120. }
  121. /// <summary>
  122. /// Disables a plugin, and all dependents.
  123. /// </summary>
  124. /// <param name="pluginId">the ID, or name if the ID is null, of the plugin to disable</param>
  125. /// <returns>whether a restart is needed to activate</returns>
  126. public static bool DisablePlugin(string pluginId) => DisablePlugin(GetPluginFromId(pluginId) ?? GetPlugin(pluginId));
  127. /// <summary>
  128. /// Enables a plugin that had been previously disabled.
  129. /// </summary>
  130. /// <param name="plugin">the plugin to enable</param>
  131. /// <returns>whether a restart is needed to activate</returns>
  132. public static bool EnablePlugin(PluginMetadata plugin)
  133. { // TODO: fix some of this behaviour, by adding better support for runtime enable/disable of mods
  134. if (plugin == null) return false;
  135. if (plugin.IsBare)
  136. {
  137. Logger.loader.Warn($"Trying to enable bare manifest");
  138. return false;
  139. }
  140. if (!IsDisabled(plugin)) return false;
  141. Logger.loader.Info($"Enabling {plugin.Name}");
  142. DisabledConfig.Instance.DisabledModIds.Remove(plugin.Id ?? plugin.Name);
  143. var needsRestart = true;
  144. var depsNeedRestart = plugin.Dependencies.Aggregate(false, (b, p) => EnablePlugin(p) || b);
  145. var runtimeInfo = runtimeDisabled.FirstOrDefault(p => p.Metadata == plugin);
  146. if (runtimeInfo != null && runtimeInfo.Plugin is IPlugin newPlugin)
  147. {
  148. try
  149. {
  150. newPlugin.OnEnable();
  151. }
  152. catch (Exception e)
  153. {
  154. Logger.loader.Error($"Error occurred trying to enable {plugin.Name}");
  155. Logger.loader.Error(e);
  156. }
  157. needsRestart = false;
  158. }
  159. else
  160. {
  161. PluginLoader.DisabledPlugins.Remove(plugin);
  162. if (runtimeInfo == null)
  163. {
  164. runtimeInfo = InitPlugin(plugin, AllPlugins.Select(i => i.Metadata));
  165. needsRestart = false;
  166. }
  167. }
  168. if (runtimeInfo != null)
  169. runtimeDisabled.Remove(runtimeInfo);
  170. _bsPlugins.Add(runtimeInfo);
  171. try
  172. {
  173. PluginEnabled?.Invoke(runtimeInfo, needsRestart || depsNeedRestart);
  174. }
  175. catch (Exception e)
  176. {
  177. Logger.loader.Error($"Error occurred invoking enable event for {plugin.Name}");
  178. Logger.loader.Error(e);
  179. }
  180. return needsRestart || depsNeedRestart;
  181. }
  182. /// <summary>
  183. /// Enables a plugin that had been previously disabled.
  184. /// </summary>
  185. /// <param name="pluginId">the ID, or name if the ID is null, of the plugin to enable</param>
  186. /// <returns>whether a restart is needed to activate</returns>
  187. public static bool EnablePlugin(string pluginId) =>
  188. EnablePlugin(GetDisabledPluginFromId(pluginId) ?? GetDisabledPlugin(pluginId));*/
  189. /// <summary>
  190. /// Checks if a given plugin is disabled.
  191. /// </summary>
  192. /// <param name="meta">the plugin to check</param>
  193. /// <returns><see langword="true"/> if the plugin is disabled, <see langword="false"/> otherwise.</returns>
  194. public static bool IsDisabled(PluginMetadata meta) => DisabledPlugins.Contains(meta);
  195. /// <summary>
  196. /// Checks if a given plugin is enabled.
  197. /// </summary>
  198. /// <param name="meta">the plugin to check</param>
  199. /// <returns><see langword="true"/> if the plugin is enabled, <see langword="false"/> otherwise.</returns>
  200. public static bool IsEnabled(PluginMetadata meta) => BSMetas.Any(p => p.Metadata == meta);
  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;
  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(PluginMetadata 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 enabled BSIPA plugins.
  228. /// </summary>
  229. /// <value>a collection of all enabled plugins as <see cref="PluginMetadata"/>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{T}"/> 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 = UnityGame.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 {UnityGame.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. }