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.

324 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. }
  104. var selfPlugin = new BSPluginMeta
  105. {
  106. Filename = Path.Combine(Environment.CurrentDirectory, "IPA.exe"),
  107. Plugin = new SelfPlugin()
  108. };
  109. selfPlugin.ModsaberInfo = selfPlugin.Plugin.ModInfo;
  110. _bsPlugins.Add(selfPlugin);
  111. //Load copied plugins
  112. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  113. foreach (string s in copiedPlugins)
  114. {
  115. var result = LoadPluginsFromFile(s, exeName);
  116. _bsPlugins.AddRange(result.Item1);
  117. _ipaPlugins.AddRange(result.Item2);
  118. }
  119. Logger.log.Info(exeName);
  120. Logger.log.Info($"Running on Unity {UnityEngine.Application.unityVersion}");
  121. Logger.log.Info($"Game version {UnityEngine.Application.version}");
  122. Logger.log.Info("-----------------------------");
  123. Logger.log.Info($"Loading plugins from {LoneFunctions.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  124. Logger.log.Info("-----------------------------");
  125. foreach (var plugin in _bsPlugins)
  126. {
  127. Logger.log.Info($"{plugin.Plugin.Name}: {plugin.Plugin.Version}");
  128. }
  129. Logger.log.Info("-----------------------------");
  130. foreach (var plugin in _ipaPlugins)
  131. {
  132. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  133. }
  134. Logger.log.Info("-----------------------------");
  135. }
  136. private static Tuple<IEnumerable<BSPluginMeta>, IEnumerable<IPlugin>> LoadPluginsFromFile(string file, string exeName)
  137. {
  138. List<BSPluginMeta> bsPlugins = new List<BSPluginMeta>();
  139. List<IPlugin> ipaPlugins = new List<IPlugin>();
  140. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  141. return new Tuple<IEnumerable<BSPluginMeta>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  142. T OptionalGetPlugin<T>(Type t) where T : class
  143. {
  144. // use typeof() to allow for easier renaming (in an ideal world this compiles to a string, but ¯\_(ツ)_/¯)
  145. if (t.GetInterface(typeof(T).Name) != null)
  146. {
  147. try
  148. {
  149. T pluginInstance = Activator.CreateInstance(t) as T;
  150. string[] filter = null;
  151. if (pluginInstance is IGenericEnhancedPlugin)
  152. {
  153. filter = ((IGenericEnhancedPlugin)pluginInstance).Filter;
  154. }
  155. if (filter == null || filter.Contains(exeName, StringComparer.OrdinalIgnoreCase))
  156. return pluginInstance;
  157. }
  158. catch (Exception e)
  159. {
  160. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  161. }
  162. }
  163. return null;
  164. }
  165. try
  166. {
  167. #region Fix assemblies for refactor
  168. var module = ModuleDefinition.ReadModule(file);
  169. bool modifiedModule = false;
  170. foreach (var @ref in module.AssemblyReferences)
  171. { // fix assembly references
  172. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  173. {
  174. @ref.Name = "IPA.Loader";
  175. modifiedModule = true;
  176. }
  177. }
  178. if (modifiedModule)
  179. { // types don't need to be fixed if it's already referencing the new version
  180. foreach (var @ref in module.GetTypeReferences())
  181. { // fix type references
  182. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  183. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  184. if (@ref.FullName == "IllusionPlugin.IBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  185. if (@ref.FullName == "IllusionPlugin.IEnhancedBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  186. if (@ref.FullName == "IllusionPlugin.BeatSaber.ModsaberModInfo") @ref.Namespace = "IPA"; //@ref.Name = "";
  187. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  188. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  189. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  190. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  191. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  192. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  193. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  194. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  195. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  196. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  197. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  198. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  199. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  200. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  201. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  202. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  203. if (@ref.Namespace == "IllusionInjector.Updating.ModsaberML") @ref.Namespace = "IPA.Updating.ModsaberML"; //@ref.Name = "";
  204. }
  205. module.Write(file);
  206. }
  207. #endregion
  208. Assembly assembly = Assembly.LoadFrom(file);
  209. foreach (Type t in assembly.GetTypes())
  210. {
  211. IBeatSaberPlugin bsPlugin = OptionalGetPlugin<IBeatSaberPlugin>(t);
  212. if (bsPlugin != null)
  213. {
  214. try
  215. {
  216. var init = t.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public);
  217. if (init != null)
  218. {
  219. var initArgs = new List<object>();
  220. var initParams = init.GetParameters();
  221. Logger modLogger = null;
  222. IModPrefs modPrefs = null;
  223. foreach (var param in initParams)
  224. {
  225. var ptype = param.ParameterType;
  226. if (ptype.IsAssignableFrom(typeof(Logger))) {
  227. if (modLogger == null) modLogger = new StandardLogger(bsPlugin.Name);
  228. initArgs.Add(modLogger);
  229. }
  230. else if (ptype.IsAssignableFrom(typeof(IModPrefs)))
  231. {
  232. if (modPrefs == null) modPrefs = new ModPrefs(bsPlugin);
  233. initArgs.Add(modPrefs);
  234. }
  235. else if (ptype.IsAssignableFrom(typeof(IConfigProvider)))
  236. {
  237. var configProvider = new JsonConfigProvider() { Filename = Path.Combine("UserData", $"{bsPlugin.Name}.{param.Name}") };
  238. configProviders.Add(configProvider);
  239. initArgs.Add(configProvider);
  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. }