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.

331 lines
15 KiB

  1. using IPA;
  2. using IPA.Config;
  3. using IPA.Config.ConfigProviders;
  4. using IPA.Logging;
  5. using IPA.Old;
  6. using IPA.Updating;
  7. using IPA.Utilities;
  8. using Mono.Cecil;
  9. using System;
  10. using System.Collections;
  11. using System.Collections.Generic;
  12. using System.Diagnostics;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Reflection;
  16. using System.Runtime.CompilerServices;
  17. using System.Runtime.InteropServices;
  18. using System.Text;
  19. using System.Threading.Tasks;
  20. namespace IPA.Loader
  21. {
  22. /// <summary>
  23. /// The manager class for all plugins.
  24. /// </summary>
  25. public static class PluginManager
  26. {
  27. #pragma warning disable CS0618 // Type or member is obsolete (IPlugin)
  28. internal class BSPluginMeta
  29. {
  30. public IBeatSaberPlugin Plugin { get; internal set; }
  31. public string Filename { get; internal set; }
  32. public ModsaberModInfo ModsaberInfo { get; internal set; }
  33. }
  34. /// <summary>
  35. /// An <see cref="IEnumerable"/> of new Beat Saber plugins
  36. /// </summary>
  37. public static IEnumerable<IBeatSaberPlugin> BSPlugins
  38. {
  39. get
  40. {
  41. if(_bsPlugins == null)
  42. {
  43. LoadPlugins();
  44. }
  45. return _bsPlugins.Select(p => p.Plugin);
  46. }
  47. }
  48. private static List<BSPluginMeta> _bsPlugins = null;
  49. internal static IEnumerable<BSPluginMeta> BSMetas
  50. {
  51. get
  52. {
  53. if (_bsPlugins == null)
  54. {
  55. LoadPlugins();
  56. }
  57. return _bsPlugins;
  58. }
  59. }
  60. /// <summary>
  61. /// An <see cref="IEnumerable"/> of old IPA plugins
  62. /// </summary>
  63. public static IEnumerable<IPlugin> Plugins
  64. {
  65. get
  66. {
  67. if (_ipaPlugins == null)
  68. {
  69. LoadPlugins();
  70. }
  71. return _ipaPlugins;
  72. }
  73. }
  74. private static List<IPlugin> _ipaPlugins = null;
  75. internal static IConfigProvider SelfConfigProvider { get; set; } = null;
  76. internal static List<KeyValuePair<IConfigProvider,Ref<DateTime>>> configProviders = new List<KeyValuePair<IConfigProvider, Ref<DateTime>>>();
  77. private static void LoadPlugins()
  78. {
  79. string pluginDirectory = Path.Combine(Environment.CurrentDirectory, "Plugins");
  80. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  81. // so we need to resort to P/Invoke
  82. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  83. _bsPlugins = new List<BSPluginMeta>();
  84. _ipaPlugins = new List<IPlugin>();
  85. if (!Directory.Exists(pluginDirectory)) return;
  86. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  87. if (!Directory.Exists(cacheDir))
  88. {
  89. Directory.CreateDirectory(cacheDir);
  90. }
  91. else
  92. {
  93. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  94. {
  95. File.Delete(plugin);
  96. }
  97. }
  98. //Copy plugins to .cache
  99. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  100. foreach (string s in originalPlugins)
  101. {
  102. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  103. File.Copy(Path.Combine(pluginDirectory, s), pluginCopy);
  104. #region Fix assemblies for refactor
  105. var module = ModuleDefinition.ReadModule(Path.Combine(pluginDirectory, s));
  106. foreach (var @ref in module.AssemblyReferences)
  107. { // fix assembly references
  108. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  109. {
  110. @ref.Name = "IPA.Loader";
  111. }
  112. }
  113. foreach (var @ref in module.GetTypeReferences())
  114. { // fix type references
  115. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  116. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  117. if (@ref.FullName == "IllusionPlugin.IBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  118. if (@ref.FullName == "IllusionPlugin.IEnhancedBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  119. if (@ref.FullName == "IllusionPlugin.BeatSaber.ModsaberModInfo") @ref.Namespace = "IPA"; //@ref.Name = "";
  120. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  121. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  122. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  123. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  124. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  125. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  126. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  127. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  128. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  129. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  130. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  131. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  132. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  133. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  134. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  135. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  136. if (@ref.Namespace == "IllusionInjector.Updating.ModsaberML") @ref.Namespace = "IPA.Updating.ModsaberML"; //@ref.Name = "";
  137. }
  138. module.Write(pluginCopy);
  139. #endregion
  140. }
  141. var selfPlugin = new BSPluginMeta
  142. {
  143. Filename = Path.Combine(Environment.CurrentDirectory, "IPA.exe"),
  144. Plugin = SelfPlugin.Instance
  145. };
  146. selfPlugin.ModsaberInfo = selfPlugin.Plugin.ModInfo;
  147. _bsPlugins.Add(selfPlugin);
  148. configProviders.Add(new KeyValuePair<IConfigProvider, Ref<DateTime>>(SelfConfigProvider = new JsonConfigProvider() { Filename = Path.Combine("UserData", SelfPlugin.IPA_Name) }, new Ref<DateTime>(SelfConfigProvider.LastModified)));
  149. SelfConfigProvider.Load();
  150. //Load copied plugins
  151. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  152. foreach (string s in copiedPlugins)
  153. {
  154. var result = LoadPluginsFromFile(s, exeName);
  155. _bsPlugins.AddRange(result.Item1);
  156. _ipaPlugins.AddRange(result.Item2);
  157. }
  158. Logger.log.Info(exeName);
  159. Logger.log.Info($"Running on Unity {UnityEngine.Application.unityVersion}");
  160. Logger.log.Info($"Game version {BeatSaber.GameVersion}");
  161. Logger.log.Info("-----------------------------");
  162. Logger.log.Info($"Loading plugins from {LoneFunctions.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  163. Logger.log.Info("-----------------------------");
  164. foreach (var plugin in _bsPlugins)
  165. {
  166. Logger.log.Info($"{plugin.Plugin.Name}: {plugin.Plugin.Version}");
  167. }
  168. Logger.log.Info("-----------------------------");
  169. foreach (var plugin in _ipaPlugins)
  170. {
  171. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  172. }
  173. Logger.log.Info("-----------------------------");
  174. }
  175. private static Tuple<IEnumerable<BSPluginMeta>, IEnumerable<IPlugin>> LoadPluginsFromFile(string file, string exeName)
  176. {
  177. List<BSPluginMeta> bsPlugins = new List<BSPluginMeta>();
  178. List<IPlugin> ipaPlugins = new List<IPlugin>();
  179. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  180. return new Tuple<IEnumerable<BSPluginMeta>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  181. T OptionalGetPlugin<T>(Type t) where T : class
  182. {
  183. // use typeof() to allow for easier renaming (in an ideal world this compiles to a string, but ¯\_(ツ)_/¯)
  184. if (t.GetInterface(typeof(T).Name) != null)
  185. {
  186. try
  187. {
  188. T pluginInstance = Activator.CreateInstance(t) as T;
  189. string[] filter = null;
  190. if (pluginInstance is IGenericEnhancedPlugin)
  191. {
  192. filter = ((IGenericEnhancedPlugin)pluginInstance).Filter;
  193. }
  194. if (filter == null || filter.Contains(exeName, StringComparer.OrdinalIgnoreCase))
  195. return pluginInstance;
  196. }
  197. catch (Exception e)
  198. {
  199. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  200. }
  201. }
  202. return null;
  203. }
  204. try
  205. {
  206. Assembly assembly = Assembly.LoadFrom(file);
  207. foreach (Type t in assembly.GetTypes())
  208. {
  209. IBeatSaberPlugin bsPlugin = OptionalGetPlugin<IBeatSaberPlugin>(t);
  210. if (bsPlugin != null)
  211. {
  212. try
  213. {
  214. var init = t.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public);
  215. if (init != null)
  216. {
  217. var initArgs = new List<object>();
  218. var initParams = init.GetParameters();
  219. Logger modLogger = null;
  220. IModPrefs modPrefs = null;
  221. IConfigProvider cfgProvider = null;
  222. foreach (var param in initParams)
  223. {
  224. var ptype = param.ParameterType;
  225. if (ptype.IsAssignableFrom(typeof(Logger))) {
  226. if (modLogger == null) modLogger = new StandardLogger(bsPlugin.Name);
  227. initArgs.Add(modLogger);
  228. }
  229. else if (ptype.IsAssignableFrom(typeof(IModPrefs)))
  230. {
  231. if (modPrefs == null) modPrefs = new ModPrefs(bsPlugin);
  232. initArgs.Add(modPrefs);
  233. }
  234. else if (ptype.IsAssignableFrom(typeof(IConfigProvider)))
  235. {
  236. if (cfgProvider == null)
  237. {
  238. cfgProvider = new JsonConfigProvider() { Filename = Path.Combine("UserData", $"{bsPlugin.Name}") };
  239. configProviders.Add(new KeyValuePair<IConfigProvider, Ref<DateTime>>(cfgProvider, new Ref<DateTime>(cfgProvider.LastModified)));
  240. cfgProvider.Load();
  241. }
  242. initArgs.Add(cfgProvider);
  243. }
  244. else
  245. initArgs.Add(ptype.GetDefault());
  246. }
  247. init.Invoke(bsPlugin, initArgs.ToArray());
  248. }
  249. bsPlugins.Add(new BSPluginMeta
  250. {
  251. Plugin = bsPlugin,
  252. Filename = file.Replace("\\.cache", ""), // quick and dirty fix
  253. ModsaberInfo = bsPlugin.ModInfo
  254. });
  255. }
  256. catch (AmbiguousMatchException)
  257. {
  258. Logger.loader.Error($"Only one Init allowed per plugin");
  259. }
  260. }
  261. else
  262. {
  263. IPlugin ipaPlugin = OptionalGetPlugin<IPlugin>(t);
  264. if (ipaPlugin != null)
  265. {
  266. ipaPlugins.Add(ipaPlugin);
  267. }
  268. }
  269. }
  270. }
  271. catch (Exception e)
  272. {
  273. Logger.loader.Error($"Could not load {Path.GetFileName(file)}! {e}");
  274. }
  275. return new Tuple<IEnumerable<BSPluginMeta>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  276. }
  277. internal class AppInfo
  278. {
  279. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = false)]
  280. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  281. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  282. public static string StartupPath
  283. {
  284. get
  285. {
  286. StringBuilder stringBuilder = new StringBuilder(260);
  287. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  288. return stringBuilder.ToString();
  289. }
  290. }
  291. }
  292. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  293. }
  294. }