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.

318 lines
14 KiB

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