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.

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