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.

255 lines
9.4 KiB

  1. using IllusionInjector.Logging;
  2. using IllusionInjector.Updating;
  3. using IllusionInjector.Utilities;
  4. using IllusionPlugin;
  5. using IllusionPlugin.BeatSaber;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Reflection;
  12. using System.Runtime.CompilerServices;
  13. using System.Runtime.InteropServices;
  14. using System.Text;
  15. using System.Threading.Tasks;
  16. using LoggerBase = IllusionPlugin.Logging.Logger;
  17. namespace IllusionInjector
  18. {
  19. public static class PluginManager
  20. {
  21. #pragma warning disable CS0618 // Type or member is obsolete (IPlugin)
  22. public class BSPluginMeta
  23. {
  24. public IBeatSaberPlugin Plugin { get; internal set; }
  25. public string Filename { get; internal set; }
  26. public ModsaberModInfo ModsaberInfo { get; internal set; }
  27. }
  28. public static IEnumerable<IBeatSaberPlugin> BSPlugins
  29. {
  30. get
  31. {
  32. if(_bsPlugins == null)
  33. {
  34. LoadPlugins();
  35. }
  36. return _bsPlugins.Select(p => p.Plugin);
  37. }
  38. }
  39. private static List<BSPluginMeta> _bsPlugins = null;
  40. internal static IEnumerable<BSPluginMeta> BSMetas
  41. {
  42. get
  43. {
  44. if (_bsPlugins == null)
  45. {
  46. LoadPlugins();
  47. }
  48. return _bsPlugins;
  49. }
  50. }
  51. public static IEnumerable<IPlugin> Plugins
  52. {
  53. get
  54. {
  55. if (_ipaPlugins == null)
  56. {
  57. LoadPlugins();
  58. }
  59. return _ipaPlugins;
  60. }
  61. }
  62. private static List<IPlugin> _ipaPlugins = null;
  63. private static void LoadPlugins()
  64. {
  65. string pluginDirectory = Path.Combine(Environment.CurrentDirectory, "Plugins");
  66. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  67. // so we need to resort to P/Invoke
  68. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  69. Logger.log.Info(exeName);
  70. _bsPlugins = new List<BSPluginMeta>();
  71. _ipaPlugins = new List<IPlugin>();
  72. if (!Directory.Exists(pluginDirectory)) return;
  73. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  74. if (!Directory.Exists(cacheDir))
  75. {
  76. Directory.CreateDirectory(cacheDir);
  77. }
  78. else
  79. {
  80. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  81. {
  82. File.Delete(plugin);
  83. }
  84. }
  85. //Copy plugins to .cache
  86. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  87. foreach (string s in originalPlugins)
  88. {
  89. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  90. File.Copy(Path.Combine(pluginDirectory, s), pluginCopy);
  91. }
  92. var selfPlugin = new BSPluginMeta
  93. {
  94. Filename = Path.Combine(Environment.CurrentDirectory, "IPA.exe"),
  95. Plugin = new SelfPlugin()
  96. };
  97. selfPlugin.ModsaberInfo = selfPlugin.Plugin.ModInfo;
  98. _bsPlugins.Add(selfPlugin);
  99. //Load copied plugins
  100. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  101. foreach (string s in copiedPlugins)
  102. {
  103. var result = LoadPluginsFromFile(s, exeName);
  104. _bsPlugins.AddRange(result.Item1);
  105. _ipaPlugins.AddRange(result.Item2);
  106. }
  107. // DEBUG
  108. Logger.log.Info($"Running on Unity {UnityEngine.Application.unityVersion}");
  109. Logger.log.Info($"Game version {UnityEngine.Application.version}");
  110. Logger.log.Info("-----------------------------");
  111. Logger.log.Info($"Loading plugins from {LoneFunctions.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  112. Logger.log.Info("-----------------------------");
  113. foreach (var plugin in _bsPlugins)
  114. {
  115. Logger.log.Info($"{plugin.Plugin.Name}: {plugin.Plugin.Version}");
  116. }
  117. Logger.log.Info("-----------------------------");
  118. foreach (var plugin in _ipaPlugins)
  119. {
  120. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  121. }
  122. Logger.log.Info("-----------------------------");
  123. }
  124. private static Tuple<IEnumerable<BSPluginMeta>, IEnumerable<IPlugin>> LoadPluginsFromFile(string file, string exeName)
  125. {
  126. List<BSPluginMeta> bsPlugins = new List<BSPluginMeta>();
  127. List<IPlugin> ipaPlugins = new List<IPlugin>();
  128. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  129. return new Tuple<IEnumerable<BSPluginMeta>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  130. T OptionalGetPlugin<T>(Type t) where T : class
  131. {
  132. // use typeof() to allow for easier renaming (in an ideal world this compiles to a string, but ¯\_(ツ)_/¯)
  133. if (t.GetInterface(typeof(T).Name) != null)
  134. {
  135. try
  136. {
  137. T pluginInstance = Activator.CreateInstance(t) as T;
  138. string[] filter = null;
  139. if (pluginInstance is IGenericEnhancedPlugin)
  140. {
  141. filter = ((IGenericEnhancedPlugin)pluginInstance).Filter;
  142. }
  143. if (filter == null || filter.Contains(exeName, StringComparer.OrdinalIgnoreCase))
  144. return pluginInstance;
  145. }
  146. catch (Exception e)
  147. {
  148. Logger.log.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  149. }
  150. }
  151. return null;
  152. }
  153. try
  154. {
  155. Assembly assembly = Assembly.LoadFrom(file);
  156. foreach (Type t in assembly.GetTypes())
  157. {
  158. IBeatSaberPlugin bsPlugin = OptionalGetPlugin<IBeatSaberPlugin>(t);
  159. if (bsPlugin != null)
  160. {
  161. try
  162. {
  163. var init = t.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public);
  164. if (init != null)
  165. {
  166. var initArgs = new List<object>();
  167. var initParams = init.GetParameters();
  168. foreach (var param in initParams)
  169. {
  170. var ptype = param.ParameterType;
  171. if (ptype.IsAssignableFrom(typeof(LoggerBase)))
  172. initArgs.Add(new StandardLogger(bsPlugin.Name));
  173. else if (ptype.IsAssignableFrom(typeof(IModPrefs)))
  174. initArgs.Add(new ModPrefs(bsPlugin));
  175. else
  176. initArgs.Add(ptype.GetDefault());
  177. }
  178. init.Invoke(bsPlugin, initArgs.ToArray());
  179. }
  180. bsPlugins.Add(new BSPluginMeta
  181. {
  182. Plugin = bsPlugin,
  183. Filename = file.Replace("\\.cache", ""), // quick and dirty fix
  184. ModsaberInfo = bsPlugin.ModInfo
  185. });
  186. }
  187. catch (AmbiguousMatchException)
  188. {
  189. Logger.log.Error($"Only one Init allowed per plugin");
  190. }
  191. }
  192. else
  193. {
  194. IPlugin ipaPlugin = OptionalGetPlugin<IPlugin>(t);
  195. if (ipaPlugin != null)
  196. {
  197. ipaPlugins.Add(ipaPlugin);
  198. }
  199. }
  200. }
  201. }
  202. catch (Exception e)
  203. {
  204. Logger.log.Error($"Could not load {Path.GetFileName(file)}! {e}");
  205. }
  206. return new Tuple<IEnumerable<BSPluginMeta>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  207. }
  208. public class AppInfo
  209. {
  210. [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
  211. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  212. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  213. public static string StartupPath
  214. {
  215. get
  216. {
  217. StringBuilder stringBuilder = new StringBuilder(260);
  218. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  219. return stringBuilder.ToString();
  220. }
  221. }
  222. }
  223. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  224. }
  225. }