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.

764 lines
31 KiB

4 years ago
  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 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. internal enum Reason
  252. {
  253. Error, Duplicate, Conflict, Dependency,
  254. Released, Feature, Unsupported,
  255. MissingFiles
  256. }
  257. internal struct IgnoreReason
  258. {
  259. public Reason Reason { get; }
  260. public string ReasonText { get; set; }
  261. public Exception Error { get; set; }
  262. public PluginMetadata RelatedTo { get; set; }
  263. public IgnoreReason(Reason reason)
  264. {
  265. Reason = reason;
  266. ReasonText = null;
  267. Error = null;
  268. RelatedTo = null;
  269. }
  270. }
  271. // keep track of these for the updater; it should still be able to update mods not loaded
  272. // the thing -> the reason
  273. internal static Dictionary<PluginMetadata, IgnoreReason> ignoredPlugins = new Dictionary<PluginMetadata, IgnoreReason>();
  274. internal static void Resolve()
  275. { // resolves duplicates and conflicts, etc
  276. PluginsMetadata.Sort((a, b) => b.Version.CompareTo(a.Version));
  277. var ids = new HashSet<string>();
  278. var ignore = new Dictionary<PluginMetadata, IgnoreReason>();
  279. var resolved = new List<PluginMetadata>(PluginsMetadata.Count);
  280. foreach (var meta in PluginsMetadata)
  281. {
  282. if (meta.Id != null)
  283. {
  284. if (ids.Contains(meta.Id))
  285. {
  286. Logger.loader.Warn($"Found duplicates of {meta.Id}, using newest");
  287. var ireason = new IgnoreReason(Reason.Duplicate)
  288. {
  289. ReasonText = $"Duplicate entry of same ID ({meta.Id})",
  290. RelatedTo = resolved.First(p => p.Id == meta.Id)
  291. };
  292. ignore.Add(meta, ireason);
  293. ignoredPlugins.Add(meta, ireason);
  294. continue; // because of sorted order, hightest order will always be the first one
  295. }
  296. bool processedLater = false;
  297. foreach (var meta2 in PluginsMetadata)
  298. {
  299. if (ignore.ContainsKey(meta2)) continue;
  300. if (meta == meta2)
  301. {
  302. processedLater = true;
  303. continue;
  304. }
  305. if (!meta2.Manifest.Conflicts.ContainsKey(meta.Id)) continue;
  306. var range = meta2.Manifest.Conflicts[meta.Id];
  307. if (!range.IsSatisfied(meta.Version)) continue;
  308. Logger.loader.Warn($"{meta.Id}@{meta.Version} conflicts with {meta2.Id}");
  309. if (processedLater)
  310. {
  311. Logger.loader.Warn($"Ignoring {meta2.Name}");
  312. ignore.Add(meta2, new IgnoreReason(Reason.Conflict)
  313. {
  314. ReasonText = $"{meta.Id}@{meta.Version} conflicts with {meta2.Id}",
  315. RelatedTo = meta
  316. });
  317. }
  318. else
  319. {
  320. Logger.loader.Warn($"Ignoring {meta.Name}");
  321. ignore.Add(meta, new IgnoreReason(Reason.Conflict)
  322. {
  323. ReasonText = $"{meta2.Id}@{meta2.Version} conflicts with {meta.Id}",
  324. RelatedTo = meta2
  325. });
  326. break;
  327. }
  328. }
  329. }
  330. if (ignore.TryGetValue(meta, out var reason))
  331. {
  332. ignoredPlugins.Add(meta, reason);
  333. continue;
  334. }
  335. if (meta.Id != null)
  336. ids.Add(meta.Id);
  337. resolved.Add(meta);
  338. }
  339. PluginsMetadata = resolved;
  340. }
  341. private static void FilterDisabled()
  342. {
  343. var enabled = new List<PluginMetadata>(PluginsMetadata.Count);
  344. var disabled = DisabledConfig.Instance.DisabledModIds;
  345. foreach (var meta in PluginsMetadata)
  346. {
  347. if (disabled.Contains(meta.Id ?? meta.Name))
  348. DisabledPlugins.Add(meta);
  349. else
  350. enabled.Add(meta);
  351. }
  352. PluginsMetadata = enabled;
  353. }
  354. private static void FilterWithoutFiles()
  355. {
  356. var enabled = new List<PluginMetadata>(PluginsMetadata.Count);
  357. foreach (var meta in PluginsMetadata)
  358. {
  359. var passed = true;
  360. foreach (var file in meta.AssociatedFiles)
  361. {
  362. if (!file.Exists)
  363. {
  364. passed = false;
  365. ignoredPlugins.Add(meta, new IgnoreReason(Reason.MissingFiles)
  366. {
  367. ReasonText = $"File {Utils.GetRelativePath(file.FullName, UnityGame.InstallPath)} (declared by {meta.Name}) does not exist"
  368. });
  369. Logger.loader.Warn($"File {Utils.GetRelativePath(file.FullName, UnityGame.InstallPath)}" +
  370. $" (declared by {meta.Name}) does not exist! Mod installation is incomplete, not loading it.");
  371. break;
  372. }
  373. }
  374. if (passed)
  375. enabled.Add(meta);
  376. }
  377. PluginsMetadata = enabled;
  378. }
  379. internal static void ComputeLoadOrder()
  380. {
  381. #if DEBUG
  382. Logger.loader.Debug(string.Join(", ", PluginsMetadata.Select(p => p.ToString()).StrJP()));
  383. #endif
  384. static bool InsertInto(HashSet<PluginMetadata> root, PluginMetadata meta, bool isRoot = false)
  385. { // this is slow, and hella recursive
  386. bool inserted = false;
  387. foreach (var sr in root)
  388. {
  389. inserted = inserted || InsertInto(sr.Dependencies, meta);
  390. if (meta.Id != null)
  391. if (sr.Manifest.Dependencies.ContainsKey(meta.Id) || sr.Manifest.LoadAfter.Contains(meta.Id))
  392. inserted = inserted || sr.Dependencies.Add(meta);
  393. if (sr.Id != null)
  394. if (meta.Manifest.LoadBefore.Contains(sr.Id))
  395. inserted = inserted || sr.Dependencies.Add(meta);
  396. }
  397. if (isRoot)
  398. {
  399. foreach (var sr in root)
  400. {
  401. InsertInto(meta.Dependencies, sr);
  402. if (sr.Id != null)
  403. if (meta.Manifest.Dependencies.ContainsKey(sr.Id) || meta.Manifest.LoadAfter.Contains(sr.Id))
  404. meta.Dependencies.Add(sr);
  405. if (meta.Id != null)
  406. if (sr.Manifest.LoadBefore.Contains(meta.Id))
  407. meta.Dependencies.Add(sr);
  408. }
  409. root.Add(meta);
  410. }
  411. return inserted;
  412. }
  413. var pluginTree = new HashSet<PluginMetadata>();
  414. foreach (var meta in PluginsMetadata)
  415. InsertInto(pluginTree, meta, true);
  416. static void DeTree(List<PluginMetadata> into, HashSet<PluginMetadata> tree)
  417. {
  418. foreach (var st in tree)
  419. if (!into.Contains(st))
  420. {
  421. DeTree(into, st.Dependencies);
  422. into.Add(st);
  423. }
  424. }
  425. PluginsMetadata = new List<PluginMetadata>();
  426. DeTree(PluginsMetadata, pluginTree);
  427. #if DEBUG
  428. Logger.loader.Debug(string.Join(", ", PluginsMetadata.Select(p => p.ToString()).StrJP()));
  429. #endif
  430. }
  431. internal static void ResolveDependencies()
  432. {
  433. var metadata = new List<PluginMetadata>();
  434. var pluginsToLoad = new Dictionary<string, Version>();
  435. var disabledLookup = DisabledPlugins.NonNull(m => m.Id).ToDictionary(m => m.Id, m => m.Version);
  436. foreach (var meta in PluginsMetadata)
  437. {
  438. var missingDeps = new List<(string id, Range version, bool disabled)>();
  439. foreach (var dep in meta.Manifest.Dependencies)
  440. {
  441. #if DEBUG
  442. Logger.loader.Debug($"Looking for dependency {dep.Key} with version range {dep.Value.Intersect(new SemVer.Range("*.*.*"))}");
  443. #endif
  444. if (pluginsToLoad.ContainsKey(dep.Key) && dep.Value.IsSatisfied(pluginsToLoad[dep.Key]))
  445. continue;
  446. if (disabledLookup.ContainsKey(dep.Key) && dep.Value.IsSatisfied(disabledLookup[dep.Key]))
  447. {
  448. Logger.loader.Warn($"Dependency {dep.Key} was found, but disabled. Disabling {meta.Name} too.");
  449. missingDeps.Add((dep.Key, dep.Value, true));
  450. }
  451. else
  452. {
  453. Logger.loader.Warn($"{meta.Name} is missing dependency {dep.Key}@{dep.Value}");
  454. missingDeps.Add((dep.Key, dep.Value, false));
  455. }
  456. }
  457. if (missingDeps.Count == 0)
  458. {
  459. metadata.Add(meta);
  460. if (meta.Id != null)
  461. pluginsToLoad.Add(meta.Id, meta.Version);
  462. }
  463. else if (missingDeps.Any(t => !t.disabled))
  464. { // missing deps
  465. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Dependency)
  466. {
  467. ReasonText = $"Missing dependencies {string.Join(", ", missingDeps.Where(t => !t.disabled).Select(t => $"{t.id}@{t.version}").StrJP())}"
  468. });
  469. }
  470. else
  471. {
  472. DisabledPlugins.Add(meta);
  473. DisabledConfig.Instance.DisabledModIds.Add(meta.Id ?? meta.Name);
  474. }
  475. }
  476. DisabledConfig.Instance.Changed();
  477. PluginsMetadata = metadata;
  478. }
  479. internal static void InitFeatures()
  480. {
  481. var parsedFeatures = PluginsMetadata.Select(m =>
  482. (metadata: m,
  483. features: m.Manifest.Features.Select(feature =>
  484. (feature, parsed: Ref.Create<Feature.FeatureParse?>(null))
  485. ).ToList()
  486. )
  487. ).ToList();
  488. while (DefineFeature.NewFeature)
  489. {
  490. DefineFeature.NewFeature = false;
  491. foreach (var (metadata, features) in parsedFeatures)
  492. for (var i = 0; i < features.Count; i++)
  493. {
  494. var feature = features[i];
  495. var success = Feature.TryParseFeature(feature.feature, metadata, out var featureObj,
  496. out var exception, out var valid, out var parsed, feature.parsed.Value);
  497. if (!success && !valid && featureObj == null && exception == null) // no feature of type found
  498. feature.parsed.Value = parsed;
  499. else if (success)
  500. {
  501. if (valid && featureObj.StoreOnPlugin)
  502. metadata.InternalFeatures.Add(featureObj);
  503. else if (!valid)
  504. Logger.features.Warn(
  505. $"Feature not valid on {metadata.Name}: {featureObj.InvalidMessage}");
  506. features.RemoveAt(i--);
  507. }
  508. else
  509. {
  510. Logger.features.Error($"Error parsing feature definition on {metadata.Name}");
  511. Logger.features.Error(exception);
  512. features.RemoveAt(i--);
  513. }
  514. }
  515. foreach (var plugin in PluginsMetadata)
  516. foreach (var feature in plugin.Features)
  517. feature.Evaluate();
  518. }
  519. foreach (var plugin in parsedFeatures)
  520. {
  521. if (plugin.features.Count <= 0) continue;
  522. Logger.features.Warn($"On plugin {plugin.metadata.Name}:");
  523. foreach (var feature in plugin.features)
  524. Logger.features.Warn($" Feature not found with name {feature.feature}");
  525. }
  526. }
  527. internal static void ReleaseAll(bool full = false)
  528. {
  529. if (full)
  530. ignoredPlugins = new Dictionary<PluginMetadata, IgnoreReason>();
  531. else
  532. {
  533. foreach (var m in PluginsMetadata)
  534. ignoredPlugins.Add(m, new IgnoreReason(Reason.Released));
  535. foreach (var m in ignoredPlugins.Keys)
  536. { // clean them up so we can still use the metadata for updates
  537. m.InternalFeatures.Clear();
  538. m.PluginType = null;
  539. m.Assembly = null;
  540. }
  541. }
  542. PluginsMetadata = new List<PluginMetadata>();
  543. DisabledPlugins = new List<PluginMetadata>();
  544. Feature.Reset();
  545. GC.Collect();
  546. }
  547. internal static void Load(PluginMetadata meta)
  548. {
  549. if (meta.Assembly == null && meta.PluginType != null)
  550. meta.Assembly = Assembly.LoadFrom(meta.File.FullName);
  551. }
  552. internal static PluginExecutor InitPlugin(PluginMetadata meta, IEnumerable<PluginMetadata> alreadyLoaded)
  553. {
  554. if (meta.Manifest.GameVersion != UnityGame.GameVersion)
  555. Logger.loader.Warn($"Mod {meta.Name} developed for game version {meta.Manifest.GameVersion}, so it may not work properly.");
  556. if (meta.IsSelf)
  557. return new PluginExecutor(meta, PluginExecutor.Special.Self);
  558. foreach (var dep in meta.Dependencies)
  559. {
  560. if (alreadyLoaded.Contains(dep)) continue;
  561. // otherwise...
  562. if (ignoredPlugins.TryGetValue(dep, out var reason))
  563. { // was added to the ignore list
  564. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Dependency)
  565. {
  566. ReasonText = $"Dependency was ignored at load time: {reason.ReasonText}",
  567. RelatedTo = dep
  568. });
  569. }
  570. else
  571. { // was not added to ignore list
  572. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Dependency)
  573. {
  574. ReasonText = $"Dependency was not already loaded at load time, but was also not ignored",
  575. RelatedTo = dep
  576. });
  577. }
  578. return null;
  579. }
  580. if (meta.IsBare)
  581. return new PluginExecutor(meta, PluginExecutor.Special.Bare);
  582. Load(meta);
  583. foreach (var feature in meta.Features)
  584. {
  585. if (!feature.BeforeLoad(meta))
  586. {
  587. Logger.loader.Warn(
  588. $"Feature {feature?.GetType()} denied plugin {meta.Name} from loading! {feature?.InvalidMessage}");
  589. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Feature)
  590. {
  591. ReasonText = $"Denied in {nameof(Feature.BeforeLoad)} of feature {feature?.GetType()}:\n\t{feature?.InvalidMessage}"
  592. });
  593. return null;
  594. }
  595. }
  596. PluginExecutor exec;
  597. try
  598. {
  599. exec = new PluginExecutor(meta);
  600. }
  601. catch (Exception e)
  602. {
  603. Logger.loader.Error($"Error creating executor for {meta.Name}");
  604. Logger.loader.Error(e);
  605. return null;
  606. }
  607. foreach (var feature in meta.Features)
  608. {
  609. if (!feature.BeforeInit(meta))
  610. {
  611. Logger.loader.Warn(
  612. $"Feature {feature?.GetType()} denied plugin {meta.Name} from initializing! {feature?.InvalidMessage}");
  613. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Feature)
  614. {
  615. ReasonText = $"Denied in {nameof(Feature.BeforeInit)} of feature {feature?.GetType()}:\n\t{feature?.InvalidMessage}"
  616. });
  617. return null;
  618. }
  619. }
  620. try
  621. {
  622. exec.Create();
  623. }
  624. catch (Exception e)
  625. {
  626. Logger.loader.Error($"Could not init plugin {meta.Name}");
  627. Logger.loader.Error(e);
  628. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Error)
  629. {
  630. ReasonText = "Error ocurred while initializing",
  631. Error = e
  632. });
  633. return null;
  634. }
  635. foreach (var feature in meta.Features)
  636. try
  637. {
  638. feature.AfterInit(meta, exec.Instance);
  639. }
  640. catch (Exception e)
  641. {
  642. Logger.loader.Critical($"Feature errored in {nameof(Feature.AfterInit)}: {e}");
  643. }
  644. return exec;
  645. }
  646. internal static List<PluginExecutor> LoadPlugins()
  647. {
  648. InitFeatures();
  649. DisabledPlugins.ForEach(Load); // make sure they get loaded into memory so their metadata and stuff can be read more easily
  650. var list = new List<PluginExecutor>();
  651. var loaded = new HashSet<PluginMetadata>();
  652. foreach (var meta in PluginsMetadata)
  653. {
  654. var exec = InitPlugin(meta, loaded);
  655. if (exec != null)
  656. {
  657. list.Add(exec);
  658. loaded.Add(meta);
  659. }
  660. }
  661. return list;
  662. }
  663. }
  664. }