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.

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