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.

729 lines
30 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. ResolveDependencies();
  42. });
  43. internal static void YeetIfNeeded()
  44. {
  45. string pluginDir = UnityGame.PluginsPath;
  46. if (SelfConfig.YeetMods_ && UnityGame.IsGameVersionBoundary)
  47. {
  48. var oldPluginsName = Path.Combine(UnityGame.InstallPath, $"Old {UnityGame.OldVersion} Plugins");
  49. var newPluginsName = Path.Combine(UnityGame.InstallPath, $"Old {UnityGame.GameVersion} Plugins");
  50. if (Directory.Exists(oldPluginsName))
  51. Directory.Delete(oldPluginsName, true);
  52. Directory.Move(pluginDir, oldPluginsName);
  53. if (Directory.Exists(newPluginsName))
  54. Directory.Move(newPluginsName, pluginDir);
  55. else
  56. Directory.CreateDirectory(pluginDir);
  57. }
  58. }
  59. internal static List<PluginMetadata> PluginsMetadata = new List<PluginMetadata>();
  60. internal static List<PluginMetadata> DisabledPlugins = new List<PluginMetadata>();
  61. private static readonly Regex embeddedTextDescriptionPattern = new Regex(@"#!\[(.+)\]", RegexOptions.Compiled | RegexOptions.Singleline);
  62. internal static void LoadMetadata()
  63. {
  64. string[] plugins = Directory.GetFiles(UnityGame.PluginsPath, "*.dll");
  65. try
  66. {
  67. var selfMeta = new PluginMetadata
  68. {
  69. Assembly = Assembly.GetExecutingAssembly(),
  70. File = new FileInfo(Path.Combine(UnityGame.InstallPath, "IPA.exe")),
  71. PluginType = null,
  72. IsSelf = true
  73. };
  74. string manifest;
  75. using (var manifestReader =
  76. new StreamReader(
  77. selfMeta.Assembly.GetManifestResourceStream(typeof(PluginLoader), "manifest.json") ??
  78. throw new InvalidOperationException()))
  79. manifest = manifestReader.ReadToEnd();
  80. selfMeta.Manifest = JsonConvert.DeserializeObject<PluginManifest>(manifest);
  81. PluginsMetadata.Add(selfMeta);
  82. }
  83. catch (Exception e)
  84. {
  85. Logger.loader.Critical("Error loading own manifest");
  86. Logger.loader.Critical(e);
  87. }
  88. foreach (var plugin in plugins)
  89. {
  90. var metadata = new PluginMetadata
  91. {
  92. File = new FileInfo(Path.Combine(UnityGame.PluginsPath, plugin)),
  93. IsSelf = false
  94. };
  95. try
  96. {
  97. var pluginModule = AssemblyDefinition.ReadAssembly(plugin, new ReaderParameters
  98. {
  99. ReadingMode = ReadingMode.Immediate,
  100. ReadWrite = false,
  101. AssemblyResolver = new CecilLibLoader()
  102. }).MainModule;
  103. string pluginNs = "";
  104. foreach (var resource in pluginModule.Resources)
  105. {
  106. const string manifestSuffix = ".manifest.json";
  107. if (!(resource is EmbeddedResource embedded) ||
  108. !embedded.Name.EndsWith(manifestSuffix)) continue;
  109. pluginNs = embedded.Name.Substring(0, embedded.Name.Length - manifestSuffix.Length);
  110. string manifest;
  111. using (var manifestReader = new StreamReader(embedded.GetResourceStream()))
  112. manifest = manifestReader.ReadToEnd();
  113. metadata.Manifest = JsonConvert.DeserializeObject<PluginManifest>(manifest);
  114. break;
  115. }
  116. if (metadata.Manifest == null)
  117. {
  118. #if DIRE_LOADER_WARNINGS
  119. Logger.loader.Error($"Could not find manifest.json for {Path.GetFileName(plugin)}");
  120. #else
  121. Logger.loader.Notice($"No manifest.json in {Path.GetFileName(plugin)}");
  122. #endif
  123. continue;
  124. }
  125. void TryGetNamespacedPluginType(string ns, PluginMetadata meta)
  126. {
  127. foreach (var type in pluginModule.Types)
  128. {
  129. if (type.Namespace != ns) continue;
  130. if (type.HasCustomAttributes)
  131. {
  132. var attr = type.CustomAttributes.FirstOrDefault(a => a.Constructor.DeclaringType.FullName == typeof(PluginAttribute).FullName);
  133. if (attr != null)
  134. {
  135. if (!attr.HasConstructorArguments)
  136. {
  137. Logger.loader.Warn($"Attribute plugin found in {type.FullName}, but attribute has no arguments");
  138. return;
  139. }
  140. var args = attr.ConstructorArguments;
  141. if (args.Count != 1)
  142. {
  143. Logger.loader.Warn($"Attribute plugin found in {type.FullName}, but attribute has unexpected number of arguments");
  144. return;
  145. }
  146. var rtOptionsArg = args[0];
  147. if (rtOptionsArg.Type.FullName != typeof(RuntimeOptions).FullName)
  148. {
  149. Logger.loader.Warn($"Attribute plugin found in {type.FullName}, but first argument is of unexpected type {rtOptionsArg.Type.FullName}");
  150. return;
  151. }
  152. var rtOptionsValInt = (int)rtOptionsArg.Value; // `int` is the underlying type of RuntimeOptions
  153. meta.RuntimeOptions = (RuntimeOptions)rtOptionsValInt;
  154. meta.PluginType = type;
  155. return;
  156. }
  157. }
  158. }
  159. }
  160. var hint = metadata.Manifest.Misc?.PluginMainHint;
  161. if (hint != null)
  162. {
  163. var type = pluginModule.GetType(hint);
  164. if (type != null)
  165. TryGetNamespacedPluginType(hint, metadata);
  166. }
  167. if (metadata.PluginType == null)
  168. TryGetNamespacedPluginType(pluginNs, metadata);
  169. if (metadata.PluginType == null)
  170. {
  171. Logger.loader.Error($"No plugin found in the manifest {(hint != null ? $"hint path ({hint}) or " : "")}namespace ({pluginNs}) in {Path.GetFileName(plugin)}");
  172. continue;
  173. }
  174. Logger.loader.Debug($"Adding info for {Path.GetFileName(plugin)}");
  175. PluginsMetadata.Add(metadata);
  176. }
  177. catch (Exception e)
  178. {
  179. Logger.loader.Error($"Could not load data for plugin {Path.GetFileName(plugin)}");
  180. Logger.loader.Error(e);
  181. ignoredPlugins.Add(metadata, new IgnoreReason(Reason.Error)
  182. {
  183. ReasonText = "An error ocurred loading the data",
  184. Error = e
  185. });
  186. }
  187. }
  188. IEnumerable<string> bareManifests = Directory.GetFiles(UnityGame.PluginsPath, "*.json");
  189. bareManifests = bareManifests.Concat(Directory.GetFiles(UnityGame.PluginsPath, "*.manifest"));
  190. foreach (var manifest in bareManifests)
  191. { // TODO: maybe find a way to allow a bare manifest to specify an associated file
  192. try
  193. {
  194. var metadata = new PluginMetadata
  195. {
  196. File = new FileInfo(Path.Combine(UnityGame.PluginsPath, manifest)),
  197. IsSelf = false,
  198. IsBare = true,
  199. };
  200. metadata.Manifest = JsonConvert.DeserializeObject<PluginManifest>(File.ReadAllText(manifest));
  201. Logger.loader.Debug($"Adding info for bare manifest {Path.GetFileName(manifest)}");
  202. PluginsMetadata.Add(metadata);
  203. }
  204. catch (Exception e)
  205. {
  206. Logger.loader.Error($"Could not load data for bare manifest {Path.GetFileName(manifest)}");
  207. Logger.loader.Error(e);
  208. }
  209. }
  210. foreach (var meta in PluginsMetadata)
  211. { // process description include
  212. var lines = meta.Manifest.Description.Split('\n');
  213. var m = embeddedTextDescriptionPattern.Match(lines[0]);
  214. if (m.Success)
  215. {
  216. if (meta.IsBare)
  217. {
  218. Logger.loader.Warn($"Bare manifest cannot specify description file");
  219. meta.Manifest.Description = string.Join("\n", lines.Skip(1).StrJP()); // ignore first line
  220. continue;
  221. }
  222. var name = m.Groups[1].Value;
  223. string description;
  224. if (!meta.IsSelf)
  225. {
  226. var resc = meta.PluginType.Module.Resources.Select(r => r as EmbeddedResource)
  227. .NonNull()
  228. .FirstOrDefault(r => r.Name == name);
  229. if (resc == null)
  230. {
  231. Logger.loader.Warn($"Could not find description file for plugin {meta.Name} ({name}); ignoring include");
  232. meta.Manifest.Description = string.Join("\n", lines.Skip(1).StrJP()); // ignore first line
  233. continue;
  234. }
  235. using var reader = new StreamReader(resc.GetResourceStream());
  236. description = reader.ReadToEnd();
  237. }
  238. else
  239. {
  240. using var descriptionReader = new StreamReader(meta.Assembly.GetManifestResourceStream(name));
  241. description = descriptionReader.ReadToEnd();
  242. }
  243. meta.Manifest.Description = description;
  244. }
  245. }
  246. }
  247. internal enum Reason
  248. {
  249. Error, Duplicate, Conflict, Dependency,
  250. Released, Feature, Unsupported
  251. }
  252. internal struct IgnoreReason
  253. {
  254. public Reason Reason { get; }
  255. public string ReasonText { get; set; }
  256. public Exception Error { get; set; }
  257. public PluginMetadata RelatedTo { get; set; }
  258. public IgnoreReason(Reason reason)
  259. {
  260. Reason = reason;
  261. ReasonText = null;
  262. Error = null;
  263. RelatedTo = null;
  264. }
  265. }
  266. // keep track of these for the updater; it should still be able to update mods not loaded
  267. // the thing -> the reason
  268. internal static Dictionary<PluginMetadata, IgnoreReason> ignoredPlugins = new Dictionary<PluginMetadata, IgnoreReason>();
  269. internal static void Resolve()
  270. { // resolves duplicates and conflicts, etc
  271. PluginsMetadata.Sort((a, b) => b.Version.CompareTo(a.Version));
  272. var ids = new HashSet<string>();
  273. var ignore = new Dictionary<PluginMetadata, IgnoreReason>();
  274. var resolved = new List<PluginMetadata>(PluginsMetadata.Count);
  275. foreach (var meta in PluginsMetadata)
  276. {
  277. if (meta.Id != null)
  278. {
  279. if (ids.Contains(meta.Id))
  280. {
  281. Logger.loader.Warn($"Found duplicates of {meta.Id}, using newest");
  282. var ireason = new IgnoreReason(Reason.Duplicate)
  283. {
  284. ReasonText = $"Duplicate entry of same ID ({meta.Id})",
  285. RelatedTo = resolved.First(p => p.Id == meta.Id)
  286. };
  287. ignore.Add(meta, ireason);
  288. ignoredPlugins.Add(meta, ireason);
  289. continue; // because of sorted order, hightest order will always be the first one
  290. }
  291. bool processedLater = false;
  292. foreach (var meta2 in PluginsMetadata)
  293. {
  294. if (ignore.ContainsKey(meta2)) continue;
  295. if (meta == meta2)
  296. {
  297. processedLater = true;
  298. continue;
  299. }
  300. if (!meta2.Manifest.Conflicts.ContainsKey(meta.Id)) continue;
  301. var range = meta2.Manifest.Conflicts[meta.Id];
  302. if (!range.IsSatisfied(meta.Version)) continue;
  303. Logger.loader.Warn($"{meta.Id}@{meta.Version} conflicts with {meta2.Id}");
  304. if (processedLater)
  305. {
  306. Logger.loader.Warn($"Ignoring {meta2.Name}");
  307. ignore.Add(meta2, new IgnoreReason(Reason.Conflict)
  308. {
  309. ReasonText = $"{meta.Id}@{meta.Version} conflicts with {meta2.Id}",
  310. RelatedTo = meta
  311. });
  312. }
  313. else
  314. {
  315. Logger.loader.Warn($"Ignoring {meta.Name}");
  316. ignore.Add(meta, new IgnoreReason(Reason.Conflict)
  317. {
  318. ReasonText = $"{meta2.Id}@{meta2.Version} conflicts with {meta.Id}",
  319. RelatedTo = meta2
  320. });
  321. break;
  322. }
  323. }
  324. }
  325. if (ignore.TryGetValue(meta, out var reason))
  326. {
  327. ignoredPlugins.Add(meta, reason);
  328. continue;
  329. }
  330. if (meta.Id != null)
  331. ids.Add(meta.Id);
  332. resolved.Add(meta);
  333. }
  334. PluginsMetadata = resolved;
  335. }
  336. private static void FilterDisabled()
  337. {
  338. var enabled = new List<PluginMetadata>(PluginsMetadata.Count);
  339. var disabled = DisabledConfig.Instance.DisabledModIds;
  340. foreach (var meta in PluginsMetadata)
  341. {
  342. if (disabled.Contains(meta.Id ?? meta.Name))
  343. DisabledPlugins.Add(meta);
  344. else
  345. enabled.Add(meta);
  346. }
  347. PluginsMetadata = enabled;
  348. }
  349. internal static void ComputeLoadOrder()
  350. {
  351. #if DEBUG
  352. Logger.loader.Debug(string.Join(", ", PluginsMetadata.Select(p => p.ToString()).StrJP()));
  353. #endif
  354. static bool InsertInto(HashSet<PluginMetadata> root, PluginMetadata meta, bool isRoot = false)
  355. { // this is slow, and hella recursive
  356. bool inserted = false;
  357. foreach (var sr in root)
  358. {
  359. inserted = inserted || InsertInto(sr.Dependencies, meta);
  360. if (meta.Id != null)
  361. if (sr.Manifest.Dependencies.ContainsKey(meta.Id) || sr.Manifest.LoadAfter.Contains(meta.Id))
  362. inserted = inserted || sr.Dependencies.Add(meta);
  363. if (sr.Id != null)
  364. if (meta.Manifest.LoadBefore.Contains(sr.Id))
  365. inserted = inserted || sr.Dependencies.Add(meta);
  366. }
  367. if (isRoot)
  368. {
  369. foreach (var sr in root)
  370. {
  371. InsertInto(meta.Dependencies, sr);
  372. if (sr.Id != null)
  373. if (meta.Manifest.Dependencies.ContainsKey(sr.Id) || meta.Manifest.LoadAfter.Contains(sr.Id))
  374. meta.Dependencies.Add(sr);
  375. if (meta.Id != null)
  376. if (sr.Manifest.LoadBefore.Contains(meta.Id))
  377. meta.Dependencies.Add(sr);
  378. }
  379. root.Add(meta);
  380. }
  381. return inserted;
  382. }
  383. var pluginTree = new HashSet<PluginMetadata>();
  384. foreach (var meta in PluginsMetadata)
  385. InsertInto(pluginTree, meta, true);
  386. static void DeTree(List<PluginMetadata> into, HashSet<PluginMetadata> tree)
  387. {
  388. foreach (var st in tree)
  389. if (!into.Contains(st))
  390. {
  391. DeTree(into, st.Dependencies);
  392. into.Add(st);
  393. }
  394. }
  395. PluginsMetadata = new List<PluginMetadata>();
  396. DeTree(PluginsMetadata, pluginTree);
  397. #if DEBUG
  398. Logger.loader.Debug(string.Join(", ", PluginsMetadata.Select(p => p.ToString()).StrJP()));
  399. #endif
  400. }
  401. internal static void ResolveDependencies()
  402. {
  403. var metadata = new List<PluginMetadata>();
  404. var pluginsToLoad = new Dictionary<string, Version>();
  405. var disabledLookup = DisabledPlugins.NonNull(m => m.Id).ToDictionary(m => m.Id, m => m.Version);
  406. foreach (var meta in PluginsMetadata)
  407. {
  408. var missingDeps = new List<(string id, Range version, bool disabled)>();
  409. foreach (var dep in meta.Manifest.Dependencies)
  410. {
  411. #if DEBUG
  412. Logger.loader.Debug($"Looking for dependency {dep.Key} with version range {dep.Value.Intersect(new SemVer.Range("*.*.*"))}");
  413. #endif
  414. if (pluginsToLoad.ContainsKey(dep.Key) && dep.Value.IsSatisfied(pluginsToLoad[dep.Key]))
  415. continue;
  416. if (disabledLookup.ContainsKey(dep.Key) && dep.Value.IsSatisfied(disabledLookup[dep.Key]))
  417. {
  418. Logger.loader.Warn($"Dependency {dep.Key} was found, but disabled. Disabling {meta.Name} too.");
  419. missingDeps.Add((dep.Key, dep.Value, true));
  420. }
  421. else
  422. {
  423. Logger.loader.Warn($"{meta.Name} is missing dependency {dep.Key}@{dep.Value}");
  424. missingDeps.Add((dep.Key, dep.Value, false));
  425. }
  426. }
  427. if (missingDeps.Count == 0)
  428. {
  429. metadata.Add(meta);
  430. if (meta.Id != null)
  431. pluginsToLoad.Add(meta.Id, meta.Version);
  432. }
  433. else if (missingDeps.Any(t => !t.disabled))
  434. { // missing deps
  435. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Dependency)
  436. {
  437. ReasonText = $"Missing dependencies {string.Join(", ", missingDeps.Where(t => !t.disabled).Select(t => $"{t.id}@{t.version}").StrJP())}"
  438. });
  439. }
  440. else
  441. {
  442. DisabledPlugins.Add(meta);
  443. DisabledConfig.Instance.DisabledModIds.Add(meta.Id ?? meta.Name);
  444. }
  445. }
  446. DisabledConfig.Instance.Changed();
  447. PluginsMetadata = metadata;
  448. }
  449. internal static void InitFeatures()
  450. {
  451. var parsedFeatures = PluginsMetadata.Select(m =>
  452. (metadata: m,
  453. features: m.Manifest.Features.Select(feature =>
  454. (feature, parsed: Ref.Create<Feature.FeatureParse?>(null))
  455. ).ToList()
  456. )
  457. ).ToList();
  458. while (DefineFeature.NewFeature)
  459. {
  460. DefineFeature.NewFeature = false;
  461. foreach (var (metadata, features) in parsedFeatures)
  462. for (var i = 0; i < features.Count; i++)
  463. {
  464. var feature = features[i];
  465. var success = Feature.TryParseFeature(feature.feature, metadata, out var featureObj,
  466. out var exception, out var valid, out var parsed, feature.parsed.Value);
  467. if (!success && !valid && featureObj == null && exception == null) // no feature of type found
  468. feature.parsed.Value = parsed;
  469. else if (success)
  470. {
  471. if (valid && featureObj.StoreOnPlugin)
  472. metadata.InternalFeatures.Add(featureObj);
  473. else if (!valid)
  474. Logger.features.Warn(
  475. $"Feature not valid on {metadata.Name}: {featureObj.InvalidMessage}");
  476. features.RemoveAt(i--);
  477. }
  478. else
  479. {
  480. Logger.features.Error($"Error parsing feature definition on {metadata.Name}");
  481. Logger.features.Error(exception);
  482. features.RemoveAt(i--);
  483. }
  484. }
  485. foreach (var plugin in PluginsMetadata)
  486. foreach (var feature in plugin.Features)
  487. feature.Evaluate();
  488. }
  489. foreach (var plugin in parsedFeatures)
  490. {
  491. if (plugin.features.Count <= 0) continue;
  492. Logger.features.Warn($"On plugin {plugin.metadata.Name}:");
  493. foreach (var feature in plugin.features)
  494. Logger.features.Warn($" Feature not found with name {feature.feature}");
  495. }
  496. }
  497. internal static void ReleaseAll(bool full = false)
  498. {
  499. if (full)
  500. ignoredPlugins = new Dictionary<PluginMetadata, IgnoreReason>();
  501. else
  502. {
  503. foreach (var m in PluginsMetadata)
  504. ignoredPlugins.Add(m, new IgnoreReason(Reason.Released));
  505. foreach (var m in ignoredPlugins.Keys)
  506. { // clean them up so we can still use the metadata for updates
  507. m.InternalFeatures.Clear();
  508. m.PluginType = null;
  509. m.Assembly = null;
  510. }
  511. }
  512. PluginsMetadata = new List<PluginMetadata>();
  513. DisabledPlugins = new List<PluginMetadata>();
  514. Feature.Reset();
  515. GC.Collect();
  516. }
  517. internal static void Load(PluginMetadata meta)
  518. {
  519. if (meta.Assembly == null && meta.PluginType != null)
  520. meta.Assembly = Assembly.LoadFrom(meta.File.FullName);
  521. }
  522. internal static PluginExecutor InitPlugin(PluginMetadata meta, IEnumerable<PluginMetadata> alreadyLoaded)
  523. {
  524. if (meta.Manifest.GameVersion != UnityGame.GameVersion)
  525. Logger.loader.Warn($"Mod {meta.Name} developed for game version {meta.Manifest.GameVersion}, so it may not work properly.");
  526. if (meta.IsSelf)
  527. return new PluginExecutor(meta, PluginExecutor.Special.Self);
  528. foreach (var dep in meta.Dependencies)
  529. {
  530. if (alreadyLoaded.Contains(dep)) continue;
  531. // otherwise...
  532. if (ignoredPlugins.TryGetValue(dep, out var reason))
  533. { // was added to the ignore list
  534. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Dependency)
  535. {
  536. ReasonText = $"Dependency was ignored at load time: {reason.ReasonText}",
  537. RelatedTo = dep
  538. });
  539. }
  540. else
  541. { // was not added to ignore list
  542. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Dependency)
  543. {
  544. ReasonText = $"Dependency was not already loaded at load time, but was also not ignored",
  545. RelatedTo = dep
  546. });
  547. }
  548. return null;
  549. }
  550. if (meta.IsBare)
  551. return new PluginExecutor(meta, PluginExecutor.Special.Bare);
  552. Load(meta);
  553. foreach (var feature in meta.Features)
  554. {
  555. if (!feature.BeforeLoad(meta))
  556. {
  557. Logger.loader.Warn(
  558. $"Feature {feature?.GetType()} denied plugin {meta.Name} from loading! {feature?.InvalidMessage}");
  559. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Feature)
  560. {
  561. ReasonText = $"Denied in {nameof(Feature.BeforeLoad)} of feature {feature?.GetType()}:\n\t{feature?.InvalidMessage}"
  562. });
  563. return null;
  564. }
  565. }
  566. PluginExecutor exec;
  567. try
  568. {
  569. exec = new PluginExecutor(meta);
  570. }
  571. catch (Exception e)
  572. {
  573. Logger.loader.Error($"Error creating executor for {meta.Name}");
  574. Logger.loader.Error(e);
  575. return null;
  576. }
  577. foreach (var feature in meta.Features)
  578. {
  579. if (!feature.BeforeInit(meta))
  580. {
  581. Logger.loader.Warn(
  582. $"Feature {feature?.GetType()} denied plugin {meta.Name} from initializing! {feature?.InvalidMessage}");
  583. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Feature)
  584. {
  585. ReasonText = $"Denied in {nameof(Feature.BeforeInit)} of feature {feature?.GetType()}:\n\t{feature?.InvalidMessage}"
  586. });
  587. return null;
  588. }
  589. }
  590. try
  591. {
  592. exec.Create();
  593. }
  594. catch (Exception e)
  595. {
  596. Logger.loader.Error($"Could not init plugin {meta.Name}");
  597. Logger.loader.Error(e);
  598. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Error)
  599. {
  600. ReasonText = "Error ocurred while initializing",
  601. Error = e
  602. });
  603. return null;
  604. }
  605. foreach (var feature in meta.Features)
  606. try
  607. {
  608. feature.AfterInit(meta, exec.Instance);
  609. }
  610. catch (Exception e)
  611. {
  612. Logger.loader.Critical($"Feature errored in {nameof(Feature.AfterInit)}: {e}");
  613. }
  614. return exec;
  615. }
  616. internal static List<PluginExecutor> LoadPlugins()
  617. {
  618. InitFeatures();
  619. DisabledPlugins.ForEach(Load); // make sure they get loaded into memory so their metadata and stuff can be read more easily
  620. var list = new List<PluginExecutor>();
  621. var loaded = new HashSet<PluginMetadata>();
  622. foreach (var meta in PluginsMetadata)
  623. {
  624. var exec = InitPlugin(meta, loaded);
  625. if (exec != null)
  626. {
  627. list.Add(exec);
  628. loaded.Add(meta);
  629. }
  630. }
  631. return list;
  632. }
  633. }
  634. }