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.

887 lines
37 KiB

  1. using IPA.Config;
  2. using IPA.Loader.Features;
  3. using IPA.Logging;
  4. using IPA.Utilities;
  5. using Mono.Cecil;
  6. using Newtonsoft.Json;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Reflection;
  12. using System.Text.RegularExpressions;
  13. using System.Threading.Tasks;
  14. using Version = SemVer.Version;
  15. using SemVer;
  16. #if NET4
  17. using Task = System.Threading.Tasks.Task;
  18. using TaskEx = System.Threading.Tasks.Task;
  19. #endif
  20. #if NET3
  21. using Net3_Proxy;
  22. using Path = Net3_Proxy.Path;
  23. using File = Net3_Proxy.File;
  24. using Directory = Net3_Proxy.Directory;
  25. #endif
  26. namespace IPA.Loader
  27. {
  28. /// <summary>
  29. /// A type to manage the loading of plugins.
  30. /// </summary>
  31. internal partial class PluginLoader
  32. {
  33. internal static Task LoadTask() =>
  34. TaskEx.Run(() =>
  35. {
  36. YeetIfNeeded();
  37. LoadMetadata();
  38. Resolve();
  39. ComputeLoadOrder();
  40. FilterDisabled();
  41. FilterWithoutFiles();
  42. ResolveDependencies();
  43. });
  44. internal static void YeetIfNeeded()
  45. {
  46. string pluginDir = UnityGame.PluginsPath;
  47. if (SelfConfig.YeetMods_ && UnityGame.IsGameVersionBoundary)
  48. {
  49. var oldPluginsName = Path.Combine(UnityGame.InstallPath, $"Old {UnityGame.OldVersion} Plugins");
  50. var newPluginsName = Path.Combine(UnityGame.InstallPath, $"Old {UnityGame.GameVersion} Plugins");
  51. if (Directory.Exists(oldPluginsName))
  52. Directory.Delete(oldPluginsName, true);
  53. Directory.Move(pluginDir, oldPluginsName);
  54. if (Directory.Exists(newPluginsName))
  55. Directory.Move(newPluginsName, pluginDir);
  56. else
  57. Directory.CreateDirectory(pluginDir);
  58. }
  59. }
  60. internal static List<PluginMetadata> PluginsMetadata = new List<PluginMetadata>();
  61. internal static List<PluginMetadata> DisabledPlugins = new List<PluginMetadata>();
  62. private static readonly Regex embeddedTextDescriptionPattern = new Regex(@"#!\[(.+)\]", RegexOptions.Compiled | RegexOptions.Singleline);
  63. internal static void LoadMetadata()
  64. {
  65. string[] plugins = Directory.GetFiles(UnityGame.PluginsPath, "*.dll");
  66. try
  67. {
  68. var selfMeta = new PluginMetadata
  69. {
  70. Assembly = Assembly.GetExecutingAssembly(),
  71. File = new FileInfo(Path.Combine(UnityGame.InstallPath, "IPA.exe")),
  72. PluginType = null,
  73. IsSelf = true
  74. };
  75. string manifest;
  76. using (var manifestReader =
  77. new StreamReader(
  78. selfMeta.Assembly.GetManifestResourceStream(typeof(PluginLoader), "manifest.json") ??
  79. throw new InvalidOperationException()))
  80. manifest = manifestReader.ReadToEnd();
  81. selfMeta.Manifest = JsonConvert.DeserializeObject<PluginManifest>(manifest);
  82. PluginsMetadata.Add(selfMeta);
  83. }
  84. catch (Exception e)
  85. {
  86. Logger.loader.Critical("Error loading own manifest");
  87. Logger.loader.Critical(e);
  88. }
  89. foreach (var plugin in plugins)
  90. {
  91. var metadata = new PluginMetadata
  92. {
  93. File = new FileInfo(Path.Combine(UnityGame.PluginsPath, plugin)),
  94. IsSelf = false
  95. };
  96. try
  97. {
  98. var pluginModule = AssemblyDefinition.ReadAssembly(plugin, new ReaderParameters
  99. {
  100. ReadingMode = ReadingMode.Immediate,
  101. ReadWrite = false,
  102. AssemblyResolver = new CecilLibLoader()
  103. }).MainModule;
  104. string pluginNs = "";
  105. foreach (var resource in pluginModule.Resources)
  106. {
  107. const string manifestSuffix = ".manifest.json";
  108. if (!(resource is EmbeddedResource embedded) ||
  109. !embedded.Name.EndsWith(manifestSuffix)) continue;
  110. pluginNs = embedded.Name.Substring(0, embedded.Name.Length - manifestSuffix.Length);
  111. string manifest;
  112. using (var manifestReader = new StreamReader(embedded.GetResourceStream()))
  113. manifest = manifestReader.ReadToEnd();
  114. metadata.Manifest = JsonConvert.DeserializeObject<PluginManifest>(manifest);
  115. break;
  116. }
  117. if (metadata.Manifest == null)
  118. {
  119. #if DIRE_LOADER_WARNINGS
  120. Logger.loader.Error($"Could not find manifest.json for {Path.GetFileName(plugin)}");
  121. #else
  122. Logger.loader.Notice($"No manifest.json in {Path.GetFileName(plugin)}");
  123. #endif
  124. continue;
  125. }
  126. void TryGetNamespacedPluginType(string ns, PluginMetadata meta)
  127. {
  128. foreach (var type in pluginModule.Types)
  129. {
  130. if (type.Namespace != ns) continue;
  131. if (type.HasCustomAttributes)
  132. {
  133. var attr = type.CustomAttributes.FirstOrDefault(a => a.Constructor.DeclaringType.FullName == typeof(PluginAttribute).FullName);
  134. if (attr != null)
  135. {
  136. if (!attr.HasConstructorArguments)
  137. {
  138. Logger.loader.Warn($"Attribute plugin found in {type.FullName}, but attribute has no arguments");
  139. return;
  140. }
  141. var args = attr.ConstructorArguments;
  142. if (args.Count != 1)
  143. {
  144. Logger.loader.Warn($"Attribute plugin found in {type.FullName}, but attribute has unexpected number of arguments");
  145. return;
  146. }
  147. var rtOptionsArg = args[0];
  148. if (rtOptionsArg.Type.FullName != typeof(RuntimeOptions).FullName)
  149. {
  150. Logger.loader.Warn($"Attribute plugin found in {type.FullName}, but first argument is of unexpected type {rtOptionsArg.Type.FullName}");
  151. return;
  152. }
  153. var rtOptionsValInt = (int)rtOptionsArg.Value; // `int` is the underlying type of RuntimeOptions
  154. meta.RuntimeOptions = (RuntimeOptions)rtOptionsValInt;
  155. meta.PluginType = type;
  156. return;
  157. }
  158. }
  159. }
  160. }
  161. var hint = metadata.Manifest.Misc?.PluginMainHint;
  162. if (hint != null)
  163. {
  164. var type = pluginModule.GetType(hint);
  165. if (type != null)
  166. TryGetNamespacedPluginType(hint, metadata);
  167. }
  168. if (metadata.PluginType == null)
  169. TryGetNamespacedPluginType(pluginNs, metadata);
  170. if (metadata.PluginType == null)
  171. {
  172. Logger.loader.Error($"No plugin found in the manifest {(hint != null ? $"hint path ({hint}) or " : "")}namespace ({pluginNs}) in {Path.GetFileName(plugin)}");
  173. continue;
  174. }
  175. Logger.loader.Debug($"Adding info for {Path.GetFileName(plugin)}");
  176. PluginsMetadata.Add(metadata);
  177. }
  178. catch (Exception e)
  179. {
  180. Logger.loader.Error($"Could not load data for plugin {Path.GetFileName(plugin)}");
  181. Logger.loader.Error(e);
  182. ignoredPlugins.Add(metadata, new IgnoreReason(Reason.Error)
  183. {
  184. ReasonText = "An error ocurred loading the data",
  185. Error = e
  186. });
  187. }
  188. }
  189. IEnumerable<string> bareManifests = Directory.GetFiles(UnityGame.PluginsPath, "*.json");
  190. bareManifests = bareManifests.Concat(Directory.GetFiles(UnityGame.PluginsPath, "*.manifest"));
  191. foreach (var manifest in bareManifests)
  192. { // TODO: maybe find a way to allow a bare manifest to specify an associated file
  193. try
  194. {
  195. var metadata = new PluginMetadata
  196. {
  197. File = new FileInfo(Path.Combine(UnityGame.PluginsPath, manifest)),
  198. IsSelf = false,
  199. IsBare = true,
  200. };
  201. metadata.Manifest = JsonConvert.DeserializeObject<PluginManifest>(File.ReadAllText(manifest));
  202. if (metadata.Manifest.Files.Length < 1)
  203. Logger.loader.Warn($"Bare manifest {Path.GetFileName(manifest)} does not declare any files. " +
  204. $"Dependency resolution and verification cannot be completed.");
  205. Logger.loader.Debug($"Adding info for bare manifest {Path.GetFileName(manifest)}");
  206. PluginsMetadata.Add(metadata);
  207. }
  208. catch (Exception e)
  209. {
  210. Logger.loader.Error($"Could not load data for bare manifest {Path.GetFileName(manifest)}");
  211. Logger.loader.Error(e);
  212. }
  213. }
  214. foreach (var meta in PluginsMetadata)
  215. { // process description include
  216. var lines = meta.Manifest.Description.Split('\n');
  217. var m = embeddedTextDescriptionPattern.Match(lines[0]);
  218. if (m.Success)
  219. {
  220. if (meta.IsBare)
  221. {
  222. Logger.loader.Warn($"Bare manifest cannot specify description file");
  223. meta.Manifest.Description = string.Join("\n", lines.Skip(1).StrJP()); // ignore first line
  224. continue;
  225. }
  226. var name = m.Groups[1].Value;
  227. string description;
  228. if (!meta.IsSelf)
  229. {
  230. var resc = meta.PluginType.Module.Resources.Select(r => r as EmbeddedResource)
  231. .NonNull()
  232. .FirstOrDefault(r => r.Name == name);
  233. if (resc == null)
  234. {
  235. Logger.loader.Warn($"Could not find description file for plugin {meta.Name} ({name}); ignoring include");
  236. meta.Manifest.Description = string.Join("\n", lines.Skip(1).StrJP()); // ignore first line
  237. continue;
  238. }
  239. using var reader = new StreamReader(resc.GetResourceStream());
  240. description = reader.ReadToEnd();
  241. }
  242. else
  243. {
  244. using var descriptionReader = new StreamReader(meta.Assembly.GetManifestResourceStream(name));
  245. description = descriptionReader.ReadToEnd();
  246. }
  247. meta.Manifest.Description = description;
  248. }
  249. }
  250. }
  251. }
  252. /// <summary>
  253. /// An enum that represents several categories of ignore reasons that the loader may encounter.
  254. /// </summary>
  255. /// <seealso cref="IgnoreReason"/>
  256. public enum Reason
  257. {
  258. /// <summary>
  259. /// An error was thrown either loading plugin information fomr disk, or when initializing the plugin.
  260. /// </summary>
  261. /// <remarks>
  262. /// When this is the set <see cref="Reason"/> in an <see cref="IgnoreReason"/> structure, the member
  263. /// <see cref="IgnoreReason.Error"/> will contain the thrown exception.
  264. /// </remarks>
  265. Error,
  266. /// <summary>
  267. /// The plugin this reason is associated with has the same ID as another plugin whose information was
  268. /// already loaded.
  269. /// </summary>
  270. /// <remarks>
  271. /// When this is the set <see cref="Reason"/> in an <see cref="IgnoreReason"/> structure, the member
  272. /// <see cref="IgnoreReason.RelatedTo"/> will contain the metadata of the already loaded plugin.
  273. /// </remarks>
  274. Duplicate,
  275. /// <summary>
  276. /// The plugin this reason is associated with conflicts with another already loaded plugin.
  277. /// </summary>
  278. /// <remarks>
  279. /// When this is the set <see cref="Reason"/> in an <see cref="IgnoreReason"/> structure, the member
  280. /// <see cref="IgnoreReason.RelatedTo"/> will contain the metadata of the plugin it conflicts with.
  281. /// </remarks>
  282. Conflict,
  283. /// <summary>
  284. /// The plugin this reason is assiciated with is missing a dependency.
  285. /// </summary>
  286. /// <remarks>
  287. /// Since this is only given when a dependency is missing, <see cref="IgnoreReason.RelatedTo"/> will
  288. /// not be set.
  289. /// </remarks>
  290. Dependency,
  291. /// <summary>
  292. /// The plugin this reason is associated with was released for a game update, but is still considered
  293. /// present for the purposes of updating.
  294. /// </summary>
  295. Released,
  296. /// <summary>
  297. /// The plugin this reason is associated with was denied from loading by a <see cref="Features.Feature"/>
  298. /// that it marks.
  299. /// </summary>
  300. Feature,
  301. /// <summary>
  302. /// The plugin this reason is assoicated with is unsupported.
  303. /// </summary>
  304. /// <remarks>
  305. /// Currently, there is no path in the loader that emits this <see cref="Reason"/>, however there may
  306. /// be in the future.
  307. /// </remarks>
  308. Unsupported,
  309. /// <summary>
  310. /// One of the files that a plugin declared in its manifest is missing.
  311. /// </summary>
  312. MissingFiles
  313. }
  314. /// <summary>
  315. /// A structure describing the reason that a plugin was ignored.
  316. /// </summary>
  317. public struct IgnoreReason
  318. {
  319. /// <summary>
  320. /// Gets the ignore reason, as represented by the <see cref="Loader.Reason"/> enum.
  321. /// </summary>
  322. public Reason Reason { get; }
  323. /// <summary>
  324. /// Gets the textual description of the particular ignore reason. This will typically
  325. /// include details about why the plugin was ignored, if it is present.
  326. /// </summary>
  327. public string ReasonText { get; internal set; }
  328. /// <summary>
  329. /// Gets the <see cref="Exception"/> that caused this plugin to be ignored, if any.
  330. /// </summary>
  331. public Exception Error { get; internal set; }
  332. /// <summary>
  333. /// Gets the metadata of the plugin that this ignore was related to, if any.
  334. /// </summary>
  335. public PluginMetadata RelatedTo { get; internal set; }
  336. /// <summary>
  337. /// Initializes an <see cref="IgnoreReason"/> with the provided data.
  338. /// </summary>
  339. /// <param name="reason">the <see cref="Loader.Reason"/> enum value that describes this reason</param>
  340. /// <param name="reasonText">the textual description of this ignore reason, if any</param>
  341. /// <param name="error">the <see cref="Exception"/> that caused this <see cref="IgnoreReason"/>, if any</param>
  342. /// <param name="relatedTo">the <see cref="PluginMetadata"/> this reason is related to, if any</param>
  343. public IgnoreReason(Reason reason, string reasonText = null, Exception error = null, PluginMetadata relatedTo = null)
  344. {
  345. Reason = reason;
  346. ReasonText = reasonText;
  347. Error = error;
  348. RelatedTo = relatedTo;
  349. }
  350. /// <inheritdoc/>
  351. public override bool Equals(object obj)
  352. => obj is IgnoreReason ir && Equals(ir);
  353. /// <summary>
  354. /// Compares this <see cref="IgnoreReason"/> with <paramref name="other"/> for equality.
  355. /// </summary>
  356. /// <param name="other">the reason to compare to</param>
  357. /// <returns><see langword="true"/> if the two reasons compare equal, <see langword="false"/> otherwise</returns>
  358. public bool Equals(IgnoreReason other)
  359. => Reason == other.Reason && ReasonText == other.ReasonText
  360. && Error == other.Error && RelatedTo == other.RelatedTo;
  361. /// <inheritdoc/>
  362. public override int GetHashCode()
  363. {
  364. int hashCode = 778404373;
  365. hashCode = hashCode * -1521134295 + Reason.GetHashCode();
  366. hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(ReasonText);
  367. hashCode = hashCode * -1521134295 + EqualityComparer<Exception>.Default.GetHashCode(Error);
  368. hashCode = hashCode * -1521134295 + EqualityComparer<PluginMetadata>.Default.GetHashCode(RelatedTo);
  369. return hashCode;
  370. }
  371. /// <summary>
  372. /// Checks if two <see cref="IgnoreReason"/>s are equal.
  373. /// </summary>
  374. /// <param name="left">the first <see cref="IgnoreReason"/> to compare</param>
  375. /// <param name="right">the second <see cref="IgnoreReason"/> to compare</param>
  376. /// <returns><see langword="true"/> if the two reasons compare equal, <see langword="false"/> otherwise</returns>
  377. public static bool operator ==(IgnoreReason left, IgnoreReason right)
  378. => left.Equals(right);
  379. /// <summary>
  380. /// Checks if two <see cref="IgnoreReason"/>s are not equal.
  381. /// </summary>
  382. /// <param name="left">the first <see cref="IgnoreReason"/> to compare</param>
  383. /// <param name="right">the second <see cref="IgnoreReason"/> to compare</param>
  384. /// <returns><see langword="true"/> if the two reasons are not equal, <see langword="false"/> otherwise</returns>
  385. public static bool operator !=(IgnoreReason left, IgnoreReason right)
  386. => !(left == right);
  387. }
  388. internal partial class PluginLoader
  389. {
  390. // keep track of these for the updater; it should still be able to update mods not loaded
  391. // the thing -> the reason
  392. internal static Dictionary<PluginMetadata, IgnoreReason> ignoredPlugins = new Dictionary<PluginMetadata, IgnoreReason>();
  393. internal static void Resolve()
  394. { // resolves duplicates and conflicts, etc
  395. PluginsMetadata.Sort((a, b) => b.Version.CompareTo(a.Version));
  396. var ids = new HashSet<string>();
  397. var ignore = new Dictionary<PluginMetadata, IgnoreReason>();
  398. var resolved = new List<PluginMetadata>(PluginsMetadata.Count);
  399. foreach (var meta in PluginsMetadata)
  400. {
  401. if (meta.Id != null)
  402. {
  403. if (ids.Contains(meta.Id))
  404. {
  405. Logger.loader.Warn($"Found duplicates of {meta.Id}, using newest");
  406. var ireason = new IgnoreReason(Reason.Duplicate)
  407. {
  408. ReasonText = $"Duplicate entry of same ID ({meta.Id})",
  409. RelatedTo = resolved.First(p => p.Id == meta.Id)
  410. };
  411. ignore.Add(meta, ireason);
  412. ignoredPlugins.Add(meta, ireason);
  413. continue; // because of sorted order, hightest order will always be the first one
  414. }
  415. bool processedLater = false;
  416. foreach (var meta2 in PluginsMetadata)
  417. {
  418. if (ignore.ContainsKey(meta2)) continue;
  419. if (meta == meta2)
  420. {
  421. processedLater = true;
  422. continue;
  423. }
  424. if (!meta2.Manifest.Conflicts.ContainsKey(meta.Id)) continue;
  425. var range = meta2.Manifest.Conflicts[meta.Id];
  426. if (!range.IsSatisfied(meta.Version)) continue;
  427. Logger.loader.Warn($"{meta.Id}@{meta.Version} conflicts with {meta2.Id}");
  428. if (processedLater)
  429. {
  430. Logger.loader.Warn($"Ignoring {meta2.Name}");
  431. ignore.Add(meta2, new IgnoreReason(Reason.Conflict)
  432. {
  433. ReasonText = $"{meta.Id}@{meta.Version} conflicts with {meta2.Id}",
  434. RelatedTo = meta
  435. });
  436. }
  437. else
  438. {
  439. Logger.loader.Warn($"Ignoring {meta.Name}");
  440. ignore.Add(meta, new IgnoreReason(Reason.Conflict)
  441. {
  442. ReasonText = $"{meta2.Id}@{meta2.Version} conflicts with {meta.Id}",
  443. RelatedTo = meta2
  444. });
  445. break;
  446. }
  447. }
  448. }
  449. if (ignore.TryGetValue(meta, out var reason))
  450. {
  451. ignoredPlugins.Add(meta, reason);
  452. continue;
  453. }
  454. if (meta.Id != null)
  455. ids.Add(meta.Id);
  456. resolved.Add(meta);
  457. }
  458. PluginsMetadata = resolved;
  459. }
  460. private static void FilterDisabled()
  461. {
  462. var enabled = new List<PluginMetadata>(PluginsMetadata.Count);
  463. var disabled = DisabledConfig.Instance.DisabledModIds;
  464. foreach (var meta in PluginsMetadata)
  465. {
  466. if (disabled.Contains(meta.Id ?? meta.Name))
  467. DisabledPlugins.Add(meta);
  468. else
  469. enabled.Add(meta);
  470. }
  471. PluginsMetadata = enabled;
  472. }
  473. private static void FilterWithoutFiles()
  474. {
  475. var enabled = new List<PluginMetadata>(PluginsMetadata.Count);
  476. foreach (var meta in PluginsMetadata)
  477. {
  478. var passed = true;
  479. foreach (var file in meta.AssociatedFiles)
  480. {
  481. if (!file.Exists)
  482. {
  483. passed = false;
  484. ignoredPlugins.Add(meta, new IgnoreReason(Reason.MissingFiles)
  485. {
  486. ReasonText = $"File {Utils.GetRelativePath(file.FullName, UnityGame.InstallPath)} (declared by {meta.Name}) does not exist"
  487. });
  488. Logger.loader.Warn($"File {Utils.GetRelativePath(file.FullName, UnityGame.InstallPath)}" +
  489. $" (declared by {meta.Name}) does not exist! Mod installation is incomplete, not loading it.");
  490. break;
  491. }
  492. }
  493. if (passed)
  494. enabled.Add(meta);
  495. }
  496. PluginsMetadata = enabled;
  497. }
  498. internal static void ComputeLoadOrder()
  499. {
  500. #if DEBUG
  501. Logger.loader.Debug(string.Join(", ", PluginsMetadata.Select(p => p.ToString()).StrJP()));
  502. #endif
  503. static bool InsertInto(HashSet<PluginMetadata> root, PluginMetadata meta, bool isRoot = false)
  504. { // this is slow, and hella recursive
  505. bool inserted = false;
  506. foreach (var sr in root)
  507. {
  508. inserted = inserted || InsertInto(sr.Dependencies, meta);
  509. if (meta.Id != null)
  510. if (sr.Manifest.Dependencies.ContainsKey(meta.Id) || sr.Manifest.LoadAfter.Contains(meta.Id))
  511. inserted = inserted || sr.Dependencies.Add(meta);
  512. if (sr.Id != null)
  513. if (meta.Manifest.LoadBefore.Contains(sr.Id))
  514. inserted = inserted || sr.Dependencies.Add(meta);
  515. }
  516. if (isRoot)
  517. {
  518. foreach (var sr in root)
  519. {
  520. InsertInto(meta.Dependencies, sr);
  521. if (sr.Id != null)
  522. if (meta.Manifest.Dependencies.ContainsKey(sr.Id) || meta.Manifest.LoadAfter.Contains(sr.Id))
  523. meta.Dependencies.Add(sr);
  524. if (meta.Id != null)
  525. if (sr.Manifest.LoadBefore.Contains(meta.Id))
  526. meta.Dependencies.Add(sr);
  527. }
  528. root.Add(meta);
  529. }
  530. return inserted;
  531. }
  532. var pluginTree = new HashSet<PluginMetadata>();
  533. foreach (var meta in PluginsMetadata)
  534. InsertInto(pluginTree, meta, true);
  535. static void DeTree(List<PluginMetadata> into, HashSet<PluginMetadata> tree)
  536. {
  537. foreach (var st in tree)
  538. if (!into.Contains(st))
  539. {
  540. DeTree(into, st.Dependencies);
  541. into.Add(st);
  542. }
  543. }
  544. PluginsMetadata = new List<PluginMetadata>();
  545. DeTree(PluginsMetadata, pluginTree);
  546. #if DEBUG
  547. Logger.loader.Debug(string.Join(", ", PluginsMetadata.Select(p => p.ToString()).StrJP()));
  548. #endif
  549. }
  550. internal static void ResolveDependencies()
  551. {
  552. var metadata = new List<PluginMetadata>();
  553. var pluginsToLoad = new Dictionary<string, Version>();
  554. var disabledLookup = DisabledPlugins.NonNull(m => m.Id).ToDictionary(m => m.Id, m => m.Version);
  555. foreach (var meta in PluginsMetadata)
  556. {
  557. var missingDeps = new List<(string id, Range version, bool disabled)>();
  558. foreach (var dep in meta.Manifest.Dependencies)
  559. {
  560. #if DEBUG
  561. Logger.loader.Debug($"Looking for dependency {dep.Key} with version range {dep.Value.Intersect(new SemVer.Range("*.*.*"))}");
  562. #endif
  563. if (pluginsToLoad.ContainsKey(dep.Key) && dep.Value.IsSatisfied(pluginsToLoad[dep.Key]))
  564. continue;
  565. if (disabledLookup.ContainsKey(dep.Key) && dep.Value.IsSatisfied(disabledLookup[dep.Key]))
  566. {
  567. Logger.loader.Warn($"Dependency {dep.Key} was found, but disabled. Disabling {meta.Name} too.");
  568. missingDeps.Add((dep.Key, dep.Value, true));
  569. }
  570. else
  571. {
  572. Logger.loader.Warn($"{meta.Name} is missing dependency {dep.Key}@{dep.Value}");
  573. missingDeps.Add((dep.Key, dep.Value, false));
  574. }
  575. }
  576. if (missingDeps.Count == 0)
  577. {
  578. metadata.Add(meta);
  579. if (meta.Id != null)
  580. pluginsToLoad.Add(meta.Id, meta.Version);
  581. }
  582. else if (missingDeps.Any(t => !t.disabled))
  583. { // missing deps
  584. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Dependency)
  585. {
  586. ReasonText = $"Missing dependencies {string.Join(", ", missingDeps.Where(t => !t.disabled).Select(t => $"{t.id}@{t.version}").StrJP())}"
  587. });
  588. }
  589. else
  590. {
  591. DisabledPlugins.Add(meta);
  592. DisabledConfig.Instance.DisabledModIds.Add(meta.Id ?? meta.Name);
  593. }
  594. }
  595. DisabledConfig.Instance.Changed();
  596. PluginsMetadata = metadata;
  597. }
  598. internal static void InitFeatures()
  599. {
  600. var parsedFeatures = PluginsMetadata.Select(m =>
  601. (metadata: m,
  602. features: m.Manifest.Features.Select(feature =>
  603. (feature, parsed: Ref.Create<Feature.FeatureParse?>(null))
  604. ).ToList()
  605. )
  606. ).ToList();
  607. while (DefineFeature.NewFeature)
  608. {
  609. DefineFeature.NewFeature = false;
  610. foreach (var (metadata, features) in parsedFeatures)
  611. for (var i = 0; i < features.Count; i++)
  612. {
  613. var feature = features[i];
  614. var success = Feature.TryParseFeature(feature.feature, metadata, out var featureObj,
  615. out var exception, out var valid, out var parsed, feature.parsed.Value);
  616. if (!success && !valid && featureObj == null && exception == null) // no feature of type found
  617. feature.parsed.Value = parsed;
  618. else if (success)
  619. {
  620. if (valid && featureObj.StoreOnPlugin)
  621. metadata.InternalFeatures.Add(featureObj);
  622. else if (!valid)
  623. Logger.features.Warn(
  624. $"Feature not valid on {metadata.Name}: {featureObj.InvalidMessage}");
  625. features.RemoveAt(i--);
  626. }
  627. else
  628. {
  629. Logger.features.Error($"Error parsing feature definition on {metadata.Name}");
  630. Logger.features.Error(exception);
  631. features.RemoveAt(i--);
  632. }
  633. }
  634. foreach (var plugin in PluginsMetadata)
  635. foreach (var feature in plugin.Features)
  636. feature.Evaluate();
  637. }
  638. foreach (var plugin in parsedFeatures)
  639. {
  640. if (plugin.features.Count <= 0) continue;
  641. Logger.features.Warn($"On plugin {plugin.metadata.Name}:");
  642. foreach (var feature in plugin.features)
  643. Logger.features.Warn($" Feature not found with name {feature.feature}");
  644. }
  645. }
  646. internal static void ReleaseAll(bool full = false)
  647. {
  648. if (full)
  649. ignoredPlugins = new Dictionary<PluginMetadata, IgnoreReason>();
  650. else
  651. {
  652. foreach (var m in PluginsMetadata)
  653. ignoredPlugins.Add(m, new IgnoreReason(Reason.Released));
  654. foreach (var m in ignoredPlugins.Keys)
  655. { // clean them up so we can still use the metadata for updates
  656. m.InternalFeatures.Clear();
  657. m.PluginType = null;
  658. m.Assembly = null;
  659. }
  660. }
  661. PluginsMetadata = new List<PluginMetadata>();
  662. DisabledPlugins = new List<PluginMetadata>();
  663. Feature.Reset();
  664. GC.Collect();
  665. }
  666. internal static void Load(PluginMetadata meta)
  667. {
  668. if (meta.Assembly == null && meta.PluginType != null)
  669. meta.Assembly = Assembly.LoadFrom(meta.File.FullName);
  670. }
  671. internal static PluginExecutor InitPlugin(PluginMetadata meta, IEnumerable<PluginMetadata> alreadyLoaded)
  672. {
  673. if (meta.Manifest.GameVersion != UnityGame.GameVersion)
  674. Logger.loader.Warn($"Mod {meta.Name} developed for game version {meta.Manifest.GameVersion}, so it may not work properly.");
  675. if (meta.IsSelf)
  676. return new PluginExecutor(meta, PluginExecutor.Special.Self);
  677. foreach (var dep in meta.Dependencies)
  678. {
  679. if (alreadyLoaded.Contains(dep)) continue;
  680. // otherwise...
  681. if (ignoredPlugins.TryGetValue(dep, out var reason))
  682. { // was added to the ignore list
  683. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Dependency)
  684. {
  685. ReasonText = $"Dependency was ignored at load time: {reason.ReasonText}",
  686. RelatedTo = dep
  687. });
  688. }
  689. else
  690. { // was not added to ignore list
  691. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Dependency)
  692. {
  693. ReasonText = $"Dependency was not already loaded at load time, but was also not ignored",
  694. RelatedTo = dep
  695. });
  696. }
  697. return null;
  698. }
  699. if (meta.IsBare)
  700. return new PluginExecutor(meta, PluginExecutor.Special.Bare);
  701. Load(meta);
  702. foreach (var feature in meta.Features)
  703. {
  704. if (!feature.BeforeLoad(meta))
  705. {
  706. Logger.loader.Warn(
  707. $"Feature {feature?.GetType()} denied plugin {meta.Name} from loading! {feature?.InvalidMessage}");
  708. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Feature)
  709. {
  710. ReasonText = $"Denied in {nameof(Feature.BeforeLoad)} of feature {feature?.GetType()}:\n\t{feature?.InvalidMessage}"
  711. });
  712. return null;
  713. }
  714. }
  715. PluginExecutor exec;
  716. try
  717. {
  718. exec = new PluginExecutor(meta);
  719. }
  720. catch (Exception e)
  721. {
  722. Logger.loader.Error($"Error creating executor for {meta.Name}");
  723. Logger.loader.Error(e);
  724. return null;
  725. }
  726. foreach (var feature in meta.Features)
  727. {
  728. if (!feature.BeforeInit(meta))
  729. {
  730. Logger.loader.Warn(
  731. $"Feature {feature?.GetType()} denied plugin {meta.Name} from initializing! {feature?.InvalidMessage}");
  732. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Feature)
  733. {
  734. ReasonText = $"Denied in {nameof(Feature.BeforeInit)} of feature {feature?.GetType()}:\n\t{feature?.InvalidMessage}"
  735. });
  736. return null;
  737. }
  738. }
  739. try
  740. {
  741. exec.Create();
  742. }
  743. catch (Exception e)
  744. {
  745. Logger.loader.Error($"Could not init plugin {meta.Name}");
  746. Logger.loader.Error(e);
  747. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Error)
  748. {
  749. ReasonText = "Error ocurred while initializing",
  750. Error = e
  751. });
  752. return null;
  753. }
  754. foreach (var feature in meta.Features)
  755. try
  756. {
  757. feature.AfterInit(meta, exec.Instance);
  758. }
  759. catch (Exception e)
  760. {
  761. Logger.loader.Critical($"Feature errored in {nameof(Feature.AfterInit)}: {e}");
  762. }
  763. return exec;
  764. }
  765. internal static List<PluginExecutor> LoadPlugins()
  766. {
  767. InitFeatures();
  768. DisabledPlugins.ForEach(Load); // make sure they get loaded into memory so their metadata and stuff can be read more easily
  769. var list = new List<PluginExecutor>();
  770. var loaded = new HashSet<PluginMetadata>();
  771. foreach (var meta in PluginsMetadata)
  772. {
  773. var exec = InitPlugin(meta, loaded);
  774. if (exec != null)
  775. {
  776. list.Add(exec);
  777. loaded.Add(meta);
  778. }
  779. }
  780. return list;
  781. }
  782. }
  783. }