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.

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