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.

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