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.

450 lines
22 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 System.Threading.Tasks;
  16. using IPA.Utilities.Async;
  17. #if NET4
  18. using TaskEx = System.Threading.Tasks.Task;
  19. using TaskEx6 = System.Threading.Tasks.Task;
  20. using Task = System.Threading.Tasks.Task;
  21. #endif
  22. #if NET3
  23. using Net3_Proxy;
  24. using Path = Net3_Proxy.Path;
  25. using File = Net3_Proxy.File;
  26. using Directory = Net3_Proxy.Directory;
  27. #endif
  28. namespace IPA.Loader
  29. {
  30. /// <summary>
  31. /// The manager class for all plugins.
  32. /// </summary>
  33. public static class PluginManager
  34. {
  35. #pragma warning disable CS0618 // Type or member is obsolete (IPlugin)
  36. private static List<PluginExecutor> _bsPlugins;
  37. internal static IEnumerable<PluginExecutor> BSMetas => _bsPlugins;
  38. /// <summary>
  39. /// Gets info about the enabled plugin with the specified name.
  40. /// </summary>
  41. /// <param name="name">the name of the plugin to get (must be an exact match)</param>
  42. /// <returns>the plugin metadata for the requested plugin or <see langword="null"/> if it doesn't exist or is disabled</returns>
  43. public static PluginMetadata GetPlugin(string name)
  44. => BSMetas.Select(p => p.Metadata).FirstOrDefault(p => p.Name == name);
  45. /// <summary>
  46. /// Gets info about the enabled plugin with the specified ID.
  47. /// </summary>
  48. /// <param name="name">the ID name of the plugin to get (must be an exact match)</param>
  49. /// <returns>the plugin metadata for the requested plugin or <see langword="null"/> if it doesn't exist or is disabled</returns>
  50. public static PluginMetadata GetPluginFromId(string name)
  51. => BSMetas.Select(p => p.Metadata).FirstOrDefault(p => p.Id == name);
  52. /// <summary>
  53. /// Gets a disabled plugin's metadata by its name.
  54. /// </summary>
  55. /// <param name="name">the name of the disabled plugin to get</param>
  56. /// <returns>the metadata for the corresponding plugin</returns>
  57. public static PluginMetadata GetDisabledPlugin(string name) =>
  58. DisabledPlugins.FirstOrDefault(p => p.Name == name);
  59. /// <summary>
  60. /// Gets a disabled plugin's metadata by its ID.
  61. /// </summary>
  62. /// <param name="name">the ID of the disabled plugin to get</param>
  63. /// <returns>the metadata for the corresponding plugin</returns>
  64. public static PluginMetadata GetDisabledPluginFromId(string name) =>
  65. DisabledPlugins.FirstOrDefault(p => p.Id == name);
  66. /// <summary>
  67. /// Creates a new transaction for mod enabling and disabling mods simultaneously.
  68. /// </summary>
  69. /// <returns>a new <see cref="StateTransitionTransaction"/> that captures the current state of loaded mods</returns>
  70. public static StateTransitionTransaction PluginStateTransaction()
  71. => new StateTransitionTransaction(AllPlugins, DisabledPlugins);
  72. private static readonly object commitTransactionLockObject = new object();
  73. internal static Task CommitTransaction(StateTransitionTransaction transaction)
  74. {
  75. if (!UnityGame.OnMainThread)
  76. return UnityMainThreadTaskScheduler.Factory.StartNew(() => CommitTransaction(transaction)).Unwrap();
  77. lock (commitTransactionLockObject)
  78. {
  79. if (transaction.CurrentlyEnabled.Except(AllPlugins)
  80. .Concat(AllPlugins.Except(transaction.CurrentlyEnabled)).Any()
  81. || transaction.CurrentlyDisabled.Except(DisabledPlugins)
  82. .Concat(DisabledPlugins.Except(transaction.CurrentlyDisabled)).Any())
  83. { // ensure that the transaction's base state reflects the current state, otherwise throw
  84. throw new InvalidOperationException("Transaction no longer resembles the current state of plugins");
  85. }
  86. var toEnable = transaction.ToEnable;
  87. var toDisable = transaction.ToDisable;
  88. transaction.Dispose();
  89. {
  90. // first enable the mods that need to be
  91. void DeTree(List<PluginMetadata> into, IEnumerable<PluginMetadata> tree)
  92. {
  93. foreach (var st in tree)
  94. if (toEnable.Contains(st) && !into.Contains(st))
  95. {
  96. DeTree(into, st.Dependencies);
  97. into.Add(st);
  98. }
  99. }
  100. var enableOrder = new List<PluginMetadata>();
  101. DeTree(enableOrder, toEnable);
  102. foreach (var meta in enableOrder)
  103. {
  104. var executor = runtimeDisabledPlugins.FirstOrDefault(e => e.Metadata == meta);
  105. if (meta.RuntimeOptions == RuntimeOptions.DynamicInit)
  106. {
  107. if (executor != null)
  108. runtimeDisabledPlugins.Remove(executor);
  109. else
  110. executor = PluginLoader.InitPlugin(meta, AllPlugins);
  111. if (executor == null) continue; // couldn't initialize, skip to next
  112. }
  113. PluginLoader.DisabledPlugins.Remove(meta);
  114. DisabledConfig.Instance.DisabledModIds.Remove(meta.Id ?? meta.Name);
  115. PluginEnabled?.Invoke(meta, meta.RuntimeOptions != RuntimeOptions.DynamicInit);
  116. if (meta.RuntimeOptions == RuntimeOptions.DynamicInit)
  117. {
  118. _bsPlugins.Add(executor);
  119. try
  120. {
  121. executor.Enable();
  122. }
  123. catch (Exception e)
  124. {
  125. Logger.loader.Error($"Error while enabling {meta.Id}:");
  126. Logger.loader.Error(e);
  127. // this should still be considered enabled, hence its position
  128. }
  129. }
  130. }
  131. }
  132. Task result;
  133. {
  134. // then disable the mods that need to be
  135. static DisableExecutor MakeDisableExec(PluginExecutor e)
  136. => new DisableExecutor
  137. {
  138. Executor = e,
  139. Dependents = BSMetas.Where(f => f.Metadata.Dependencies.Contains(e.Metadata)).Select(MakeDisableExec)
  140. };
  141. var disableExecs = toDisable.Select(m => BSMetas.FirstOrDefault(e => e.Metadata == m)).NonNull().ToArray(); // eagerly evaluate once
  142. foreach (var exec in disableExecs)
  143. {
  144. PluginLoader.DisabledPlugins.Add(exec.Metadata);
  145. DisabledConfig.Instance.DisabledModIds.Add(exec.Metadata.Id ?? exec.Metadata.Name);
  146. if (exec.Metadata.RuntimeOptions == RuntimeOptions.DynamicInit)
  147. {
  148. runtimeDisabledPlugins.Add(exec);
  149. _bsPlugins.Remove(exec);
  150. }
  151. PluginDisabled?.Invoke(exec.Metadata, exec.Metadata.RuntimeOptions != RuntimeOptions.DynamicInit);
  152. }
  153. var disableStructure = disableExecs.Select(MakeDisableExec);
  154. static Task Disable(DisableExecutor exec, Dictionary<PluginExecutor, Task> alreadyDisabled)
  155. {
  156. if (alreadyDisabled.TryGetValue(exec.Executor, out var task))
  157. return task;
  158. else
  159. {
  160. if (exec.Executor.Metadata.RuntimeOptions != RuntimeOptions.DynamicInit)
  161. return TaskEx6.FromException(new CannotRuntimeDisableException(exec.Executor.Metadata));
  162. var res = TaskEx.WhenAll(exec.Dependents.Select(d => Disable(d, alreadyDisabled)))
  163. .ContinueWith(t => TaskEx.WhenAll(t, exec.Executor.Disable()), UnityMainThreadTaskScheduler.Default).Unwrap();
  164. // The WhenAll above allows us to wait for the executor to disable, but still propagate errors
  165. // By scheduling on a UnityMainThreadScheduler, we ensure that Disable() is always called on the Unity main thread
  166. alreadyDisabled.Add(exec.Executor, res);
  167. return res;
  168. }
  169. }
  170. var disabled = new Dictionary<PluginExecutor, Task>();
  171. result = TaskEx.WhenAll(disableStructure.Select(d => Disable(d, disabled)));
  172. }
  173. DisabledConfig.Instance.Changed();
  174. return result;
  175. }
  176. }
  177. private struct DisableExecutor
  178. {
  179. public PluginExecutor Executor;
  180. public IEnumerable<DisableExecutor> Dependents;
  181. }
  182. /// <summary>
  183. /// Checks if a given plugin is disabled.
  184. /// </summary>
  185. /// <param name="meta">the plugin to check</param>
  186. /// <returns><see langword="true"/> if the plugin is disabled, <see langword="false"/> otherwise.</returns>
  187. public static bool IsDisabled(PluginMetadata meta) => DisabledPlugins.Contains(meta);
  188. /// <summary>
  189. /// Checks if a given plugin is enabled.
  190. /// </summary>
  191. /// <param name="meta">the plugin to check</param>
  192. /// <returns><see langword="true"/> if the plugin is enabled, <see langword="false"/> otherwise.</returns>
  193. public static bool IsEnabled(PluginMetadata meta) => BSMetas.Any(p => p.Metadata == meta);
  194. /// <summary>
  195. /// Gets a list of disabled BSIPA plugins.
  196. /// </summary>
  197. /// <value>a collection of all disabled plugins as <see cref="PluginMetadata"/></value>
  198. public static IEnumerable<PluginMetadata> DisabledPlugins => PluginLoader.DisabledPlugins;
  199. private static readonly HashSet<PluginExecutor> runtimeDisabledPlugins = new HashSet<PluginExecutor>();
  200. /// <summary>
  201. /// An invoker for the <see cref="PluginEnabled"/> event.
  202. /// </summary>
  203. /// <param name="plugin">the plugin that was enabled</param>
  204. /// <param name="needsRestart">whether it needs a restart to take effect</param>
  205. public delegate void PluginEnableDelegate(PluginMetadata plugin, bool needsRestart);
  206. /// <summary>
  207. /// An invoker for the <see cref="PluginDisabled"/> event.
  208. /// </summary>
  209. /// <param name="plugin">the plugin that was disabled</param>
  210. /// <param name="needsRestart">whether it needs a restart to take effect</param>
  211. public delegate void PluginDisableDelegate(PluginMetadata plugin, bool needsRestart);
  212. /// <summary>
  213. /// Called whenever a plugin is enabled.
  214. /// </summary>
  215. public static event PluginEnableDelegate PluginEnabled;
  216. /// <summary>
  217. /// Called whenever a plugin is disabled.
  218. /// </summary>
  219. public static event PluginDisableDelegate PluginDisabled;
  220. /// <summary>
  221. /// Gets a list of all enabled BSIPA plugins.
  222. /// </summary>
  223. /// <value>a collection of all enabled plugins as <see cref="PluginMetadata"/>s</value>
  224. public static IEnumerable<PluginMetadata> AllPlugins => BSMetas.Select(p => p.Metadata);
  225. /// <summary>
  226. /// An <see cref="IEnumerable{T}"/> of old IPA plugins.
  227. /// </summary>
  228. /// <value>all legacy plugin instances</value>
  229. [Obsolete("I mean, IPlugin shouldn't be used, so why should this? Not renaming to extend support for old plugins.")]
  230. public static IEnumerable<Old.IPlugin> Plugins => _ipaPlugins;
  231. private static List<Old.IPlugin> _ipaPlugins;
  232. internal static IConfigProvider SelfConfigProvider { get; set; }
  233. internal static void Load()
  234. {
  235. string pluginDirectory = UnityGame.PluginsPath;
  236. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  237. // so we need to resort to P/Invoke
  238. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  239. _bsPlugins = new List<PluginExecutor>();
  240. _ipaPlugins = new List<Old.IPlugin>();
  241. if (!Directory.Exists(pluginDirectory)) return;
  242. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  243. if (!Directory.Exists(cacheDir))
  244. {
  245. Directory.CreateDirectory(cacheDir);
  246. }
  247. else
  248. {
  249. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  250. {
  251. File.Delete(plugin);
  252. }
  253. }
  254. // initialize BSIPA plugins first
  255. _bsPlugins.AddRange(PluginLoader.LoadPlugins());
  256. var metadataPaths = PluginLoader.PluginsMetadata.Select(m => m.File.FullName).ToList();
  257. var ignoredPaths = PluginLoader.ignoredPlugins.Select(m => m.Key.File.FullName).ToList();
  258. var disabledPaths = DisabledPlugins.Select(m => m.File.FullName).ToList();
  259. //Copy plugins to .cache
  260. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  261. foreach (string s in originalPlugins)
  262. {
  263. if (metadataPaths.Contains(s)) continue;
  264. if (ignoredPaths.Contains(s)) continue;
  265. if (disabledPaths.Contains(s)) continue;
  266. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  267. #region Fix assemblies for refactor
  268. var module = ModuleDefinition.ReadModule(Path.Combine(pluginDirectory, s));
  269. foreach (var @ref in module.AssemblyReferences)
  270. { // fix assembly references
  271. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  272. {
  273. @ref.Name = "IPA.Loader";
  274. }
  275. }
  276. foreach (var @ref in module.GetTypeReferences())
  277. { // fix type references
  278. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  279. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  280. if (@ref.FullName == "IllusionPlugin.IBeatSaberPlugin") { @ref.Namespace = "IPA"; @ref.Name = nameof(IPlugin); }
  281. if (@ref.FullName == "IllusionPlugin.IEnhancedBeatSaberPlugin") { @ref.Namespace = "IPA"; @ref.Name = nameof(IEnhancedPlugin); }
  282. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  283. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  284. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  285. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  286. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  287. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  288. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  289. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  290. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  291. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  292. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  293. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  294. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  295. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  296. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  297. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  298. }
  299. module.Write(pluginCopy);
  300. #endregion
  301. }
  302. //Load copied plugins
  303. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  304. foreach (string s in copiedPlugins)
  305. {
  306. var result = LoadPluginsFromFile(s);
  307. if (result == null) continue;
  308. _ipaPlugins.AddRange(result.NonNull());
  309. }
  310. Logger.log.Info(exeName);
  311. Logger.log.Info($"Running on Unity {Application.unityVersion}");
  312. Logger.log.Info($"Game version {UnityGame.GameVersion}");
  313. Logger.log.Info("-----------------------------");
  314. Logger.log.Info($"Loading plugins from {Utils.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  315. Logger.log.Info("-----------------------------");
  316. foreach (var plugin in _bsPlugins)
  317. {
  318. Logger.log.Info($"{plugin.Metadata.Name} ({plugin.Metadata.Id}): {plugin.Metadata.Version}");
  319. }
  320. Logger.log.Info("-----------------------------");
  321. foreach (var plugin in _ipaPlugins)
  322. {
  323. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  324. }
  325. Logger.log.Info("-----------------------------");
  326. }
  327. private static IEnumerable<Old.IPlugin> LoadPluginsFromFile(string file)
  328. {
  329. var ipaPlugins = new List<Old.IPlugin>();
  330. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  331. return ipaPlugins;
  332. T OptionalGetPlugin<T>(Type t) where T : class
  333. {
  334. if (t.FindInterfaces((t, o) => t == (o as Type), typeof(T)).Length > 0)
  335. {
  336. try
  337. {
  338. T pluginInstance = Activator.CreateInstance(t) as T;
  339. return pluginInstance;
  340. }
  341. catch (Exception e)
  342. {
  343. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  344. }
  345. }
  346. return null;
  347. }
  348. try
  349. {
  350. Assembly assembly = Assembly.LoadFrom(file);
  351. foreach (Type t in assembly.GetTypes())
  352. {
  353. var ipaPlugin = OptionalGetPlugin<Old.IPlugin>(t);
  354. if (ipaPlugin != null)
  355. {
  356. ipaPlugins.Add(ipaPlugin);
  357. }
  358. }
  359. }
  360. catch (ReflectionTypeLoadException e)
  361. {
  362. Logger.loader.Error($"Could not load the following types from {Path.GetFileName(file)}:");
  363. Logger.loader.Error($" {string.Join("\n ", e.LoaderExceptions?.Select(e1 => e1?.Message).StrJP() ?? new string[0])}");
  364. }
  365. catch (Exception e)
  366. {
  367. Logger.loader.Error($"Could not load {Path.GetFileName(file)}!");
  368. Logger.loader.Error(e);
  369. }
  370. return ipaPlugins;
  371. }
  372. internal static class AppInfo
  373. {
  374. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = false)]
  375. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  376. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  377. public static string StartupPath
  378. {
  379. get
  380. {
  381. StringBuilder stringBuilder = new StringBuilder(260);
  382. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  383. return stringBuilder.ToString();
  384. }
  385. }
  386. }
  387. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  388. }
  389. }