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.

446 lines
16 KiB

  1. using IPA.Loader.Features;
  2. using IPA.Logging;
  3. using IPA.Utilities;
  4. using Mono.Cecil;
  5. using Newtonsoft.Json;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Threading.Tasks;
  12. using Version = SemVer.Version;
  13. namespace IPA.Loader
  14. {
  15. /// <summary>
  16. /// A type to manage the loading of plugins.
  17. /// </summary>
  18. public class PluginLoader
  19. {
  20. internal static Task LoadTask() => Task.Run(() =>
  21. {
  22. LoadMetadata();
  23. Resolve();
  24. ComputeLoadOrder();
  25. InitFeatures();
  26. });
  27. /// <summary>
  28. /// A class which describes
  29. /// </summary>
  30. public class PluginMetadata
  31. {
  32. /// <summary>
  33. /// The assembly the plugin was loaded from.
  34. /// </summary>
  35. public Assembly Assembly { get; internal set; }
  36. /// <summary>
  37. /// The TypeDefinition for the main type of the plugin.
  38. /// </summary>
  39. public TypeDefinition PluginType { get; internal set; }
  40. /// <summary>
  41. /// The human readable name of the plugin.
  42. /// </summary>
  43. public string Name { get; internal set; }
  44. /// <summary>
  45. /// The ModSaber ID of the plugin, or null if it doesn't have one.
  46. /// </summary>
  47. public string Id { get; internal set; }
  48. /// <summary>
  49. /// The version of the plugin.
  50. /// </summary>
  51. public Version Version { get; internal set; }
  52. /// <summary>
  53. /// The file the plugin was loaded from.
  54. /// </summary>
  55. public FileInfo File { get; internal set; }
  56. // ReSharper disable once UnusedAutoPropertyAccessor.Global
  57. /// <summary>
  58. /// The features this plugin requests.
  59. /// </summary>
  60. public IReadOnlyList<Feature> Features => InternalFeatures;
  61. internal readonly List<Feature> InternalFeatures = new List<Feature>();
  62. internal bool IsSelf;
  63. private PluginManifest manifest;
  64. internal PluginManifest Manifest
  65. {
  66. get => manifest;
  67. set
  68. {
  69. manifest = value;
  70. Name = value.Name;
  71. Version = value.Version;
  72. Id = value.Id;
  73. }
  74. }
  75. /// <inheritdoc />
  76. public override string ToString() => $"{Name}({Id}@{Version})({PluginType?.FullName}) from '{Utils.GetRelativePath(File?.FullName, BeatSaber.InstallPath)}'";
  77. }
  78. /// <summary>
  79. /// A container object for all the data relating to a plugin.
  80. /// </summary>
  81. public class PluginInfo
  82. {
  83. internal IBeatSaberPlugin Plugin { get; set; }
  84. /// <summary>
  85. /// Metadata for the plugin.
  86. /// </summary>
  87. public PluginMetadata Metadata { get; internal set; } = new PluginMetadata();
  88. }
  89. internal static List<PluginMetadata> PluginsMetadata = new List<PluginMetadata>();
  90. internal static void LoadMetadata()
  91. {
  92. string[] plugins = Directory.GetFiles(BeatSaber.PluginsPath, "*.dll");
  93. try
  94. {
  95. var selfMeta = new PluginMetadata
  96. {
  97. Assembly = Assembly.GetExecutingAssembly(),
  98. File = new FileInfo(Path.Combine(BeatSaber.InstallPath, "IPA.exe")),
  99. PluginType = null,
  100. IsSelf = true
  101. };
  102. string manifest;
  103. using (var manifestReader =
  104. new StreamReader(
  105. selfMeta.Assembly.GetManifestResourceStream(typeof(PluginLoader), "manifest.json") ??
  106. throw new InvalidOperationException()))
  107. manifest = manifestReader.ReadToEnd();
  108. selfMeta.Manifest = JsonConvert.DeserializeObject<PluginManifest>(manifest);
  109. PluginsMetadata.Add(selfMeta);
  110. }
  111. catch (Exception e)
  112. {
  113. Logger.loader.Critical("Error loading own manifest");
  114. Logger.loader.Critical(e);
  115. }
  116. foreach (var plugin in plugins)
  117. {
  118. try
  119. {
  120. var metadata = new PluginMetadata
  121. {
  122. File = new FileInfo(Path.Combine(BeatSaber.PluginsPath, plugin)),
  123. IsSelf = false
  124. };
  125. var pluginModule = AssemblyDefinition.ReadAssembly(plugin, new ReaderParameters
  126. {
  127. ReadingMode = ReadingMode.Immediate,
  128. ReadWrite = false,
  129. AssemblyResolver = new CecilLibLoader()
  130. }).MainModule;
  131. var iBeatSaberPlugin = pluginModule.ImportReference(typeof(IBeatSaberPlugin));
  132. foreach (var type in pluginModule.Types)
  133. {
  134. foreach (var inter in type.Interfaces)
  135. {
  136. var ifType = inter.InterfaceType;
  137. if (iBeatSaberPlugin.FullName == ifType.FullName)
  138. {
  139. metadata.PluginType = type;
  140. break;
  141. }
  142. }
  143. if (metadata.PluginType != null) break;
  144. }
  145. if (metadata.PluginType == null)
  146. {
  147. Logger.loader.Notice(
  148. #if DIRE_LOADER_WARNINGS
  149. $"Could not find plugin type for {Path.GetFileName(plugin)}"
  150. #else
  151. $"New plugin type not present in {Path.GetFileName(plugin)}; maybe an old plugin?"
  152. #endif
  153. );
  154. continue;
  155. }
  156. foreach (var resource in pluginModule.Resources)
  157. {
  158. if (!(resource is EmbeddedResource embedded) ||
  159. embedded.Name != $"{metadata.PluginType.Namespace}.manifest.json") continue;
  160. string manifest;
  161. using (var manifestReader = new StreamReader(embedded.GetResourceStream()))
  162. manifest = manifestReader.ReadToEnd();
  163. metadata.Manifest = JsonConvert.DeserializeObject<PluginManifest>(manifest);
  164. break;
  165. }
  166. if (metadata.Manifest == null)
  167. {
  168. Logger.loader.Error("Could not find manifest.json in namespace " +
  169. $"{metadata.PluginType.Namespace} for {Path.GetFileName(plugin)}");
  170. continue;
  171. }
  172. Logger.loader.Debug($"Adding info for {Path.GetFileName(plugin)}");
  173. PluginsMetadata.Add(metadata);
  174. }
  175. catch (Exception e)
  176. {
  177. Logger.loader.Error($"Could not load data for plugin {Path.GetFileName(plugin)}");
  178. Logger.loader.Error(e);
  179. }
  180. }
  181. }
  182. internal static void Resolve()
  183. { // resolves duplicates and conflicts, etc
  184. PluginsMetadata.Sort((a, b) => a.Version.CompareTo(b.Version));
  185. var ids = new HashSet<string>();
  186. var ignore = new HashSet<PluginMetadata>();
  187. var resolved = new List<PluginMetadata>(PluginsMetadata.Count);
  188. foreach (var meta in PluginsMetadata)
  189. {
  190. if (meta.Id != null)
  191. {
  192. if (ids.Contains(meta.Id))
  193. {
  194. Logger.loader.Warn($"Found duplicates of {meta.Id}, using newest");
  195. ignore.Add(meta);
  196. continue; // because of sorted order, hightest order will always be the first one
  197. }
  198. bool processedLater = false;
  199. foreach (var meta2 in PluginsMetadata)
  200. {
  201. if (ignore.Contains(meta2)) continue;
  202. if (meta == meta2)
  203. {
  204. processedLater = true;
  205. continue;
  206. }
  207. if (!meta2.Manifest.Conflicts.ContainsKey(meta.Id)) continue;
  208. var range = meta2.Manifest.Conflicts[meta.Id];
  209. if (!range.IsSatisfied(meta.Version)) continue;
  210. Logger.loader.Warn($"{meta.Id}@{meta.Version} conflicts with {meta2.Name}");
  211. if (processedLater)
  212. {
  213. Logger.loader.Warn($"Ignoring {meta2.Name}");
  214. ignore.Add(meta2);
  215. }
  216. else
  217. {
  218. Logger.loader.Warn($"Ignoring {meta.Name}");
  219. ignore.Add(meta);
  220. break;
  221. }
  222. }
  223. }
  224. if (ignore.Contains(meta)) continue;
  225. if (meta.Id != null) ids.Add(meta.Id);
  226. resolved.Add(meta);
  227. }
  228. PluginsMetadata = resolved;
  229. }
  230. internal static void ComputeLoadOrder()
  231. {
  232. PluginsMetadata.Sort((a, b) =>
  233. {
  234. if (a.Id == b.Id) return 0;
  235. if (a.Id != null)
  236. {
  237. if (b.Manifest.Dependencies.ContainsKey(a.Id) || b.Manifest.LoadAfter.Contains(a.Id)) return -1;
  238. if (b.Manifest.LoadBefore.Contains(a.Id)) return 1;
  239. }
  240. if (b.Id != null)
  241. {
  242. if (a.Manifest.Dependencies.ContainsKey(b.Id) || a.Manifest.LoadAfter.Contains(b.Id)) return 1;
  243. if (a.Manifest.LoadBefore.Contains(b.Id)) return -1;
  244. }
  245. return 0;
  246. });
  247. var metadata = new List<PluginMetadata>();
  248. var pluginsToLoad = new Dictionary<string, Version>();
  249. foreach (var meta in PluginsMetadata)
  250. {
  251. bool load = true;
  252. foreach (var dep in meta.Manifest.Dependencies)
  253. {
  254. if (pluginsToLoad.ContainsKey(dep.Key) && dep.Value.IsSatisfied(pluginsToLoad[dep.Key])) continue;
  255. load = false;
  256. Logger.loader.Warn($"{meta.Name} is missing dependency {dep.Key}@{dep.Value}");
  257. }
  258. if (load)
  259. {
  260. metadata.Add(meta);
  261. if (meta.Id != null)
  262. pluginsToLoad.Add(meta.Id, meta.Version);
  263. }
  264. }
  265. PluginsMetadata = metadata;
  266. }
  267. internal static void InitFeatures()
  268. {
  269. var parsedFeatures = PluginsMetadata.Select(m =>
  270. Tuple.Create(m,
  271. m.Manifest.Features.Select(f =>
  272. Tuple.Create(f, Ref.Create<Feature.FeatureParse?>(null))
  273. ).ToList()
  274. )
  275. ).ToList();
  276. while (DefineFeature.NewFeature)
  277. {
  278. DefineFeature.NewFeature = false;
  279. foreach (var plugin in parsedFeatures)
  280. for (var i = 0; i < plugin.Item2.Count; i++)
  281. {
  282. var feature = plugin.Item2[i];
  283. var success = Feature.TryParseFeature(feature.Item1, plugin.Item1, out var featureObj,
  284. out var exception, out var valid, out var parsed, feature.Item2.Value);
  285. if (!success && !valid && featureObj == null && exception == null) // no feature of type found
  286. feature.Item2.Value = parsed;
  287. else if (success)
  288. {
  289. if (valid && featureObj.StoreOnPlugin)
  290. plugin.Item1.InternalFeatures.Add(featureObj);
  291. else if (!valid)
  292. Logger.features.Warn(
  293. $"Feature not valid on {plugin.Item1.Name}: {featureObj.InvalidMessage}");
  294. plugin.Item2.RemoveAt(i--);
  295. }
  296. else
  297. {
  298. Logger.features.Error($"Error parsing feature definition on {plugin.Item1.Name}");
  299. Logger.features.Error(exception);
  300. plugin.Item2.RemoveAt(i--);
  301. }
  302. }
  303. foreach (var plugin in PluginsMetadata)
  304. foreach (var feature in plugin.Features)
  305. feature.Evaluate();
  306. }
  307. foreach (var plugin in parsedFeatures)
  308. {
  309. if (plugin.Item2.Count <= 0) continue;
  310. Logger.features.Warn($"On plugin {plugin.Item1.Name}:");
  311. foreach (var feature in plugin.Item2)
  312. Logger.features.Warn($" Feature not found with name {feature.Item1}");
  313. }
  314. }
  315. internal static void Load(PluginMetadata meta)
  316. {
  317. if (meta.Assembly == null)
  318. meta.Assembly = Assembly.LoadFrom(meta.File.FullName);
  319. }
  320. internal static PluginInfo InitPlugin(PluginMetadata meta)
  321. {
  322. if (meta.PluginType == null)
  323. return new PluginInfo()
  324. {
  325. Metadata = meta,
  326. Plugin = null
  327. };
  328. var info = new PluginInfo();
  329. try
  330. {
  331. Load(meta);
  332. Feature denyingFeature = null;
  333. if (!meta.Features.All(f => (denyingFeature = f).BeforeLoad(meta)))
  334. {
  335. Logger.loader.Warn(
  336. $"Feature {denyingFeature?.GetType()} denied plugin {meta.Name} from loading! {denyingFeature?.InvalidMessage}");
  337. return null;
  338. }
  339. var type = meta.Assembly.GetType(meta.PluginType.FullName);
  340. var instance = (IBeatSaberPlugin)Activator.CreateInstance(type);
  341. info.Metadata = meta;
  342. info.Plugin = instance;
  343. var init = type.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public);
  344. if (init != null)
  345. {
  346. denyingFeature = null;
  347. if (!meta.Features.All(f => (denyingFeature = f).BeforeInit(info)))
  348. {
  349. Logger.loader.Warn(
  350. $"Feature {denyingFeature?.GetType()} denied plugin {meta.Name} from initializing! {denyingFeature?.InvalidMessage}");
  351. return null;
  352. }
  353. PluginInitInjector.Inject(init, info);
  354. }
  355. foreach (var feature in meta.Features)
  356. try
  357. {
  358. feature.AfterInit(info);
  359. }
  360. catch (Exception e)
  361. {
  362. Logger.loader.Critical($"Feature errored in {nameof(Feature.AfterInit)}: {e}");
  363. }
  364. }
  365. catch (AmbiguousMatchException)
  366. {
  367. Logger.loader.Error($"Only one Init allowed per plugin (ambiguous match in {meta.Name})");
  368. return null;
  369. }
  370. catch (Exception e)
  371. {
  372. Logger.loader.Error($"Could not init plugin {meta.Name}: {e}");
  373. return null;
  374. }
  375. return info;
  376. }
  377. internal static List<PluginInfo> LoadPlugins() => PluginsMetadata.Select(InitPlugin).Where(p => p != null).ToList();
  378. }
  379. }