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.

264 lines
9.8 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. LoggerBase modLogger = null;
  169. IModPrefs modPrefs = null;
  170. foreach (var param in initParams)
  171. {
  172. var ptype = param.ParameterType;
  173. if (ptype.IsAssignableFrom(typeof(LoggerBase))) {
  174. if (modLogger == null) modLogger = new StandardLogger(bsPlugin.Name);
  175. initArgs.Add(modLogger);
  176. }
  177. else if (ptype.IsAssignableFrom(typeof(IModPrefs)))
  178. {
  179. if (modPrefs == null) modPrefs = new ModPrefs(bsPlugin);
  180. initArgs.Add(modPrefs);
  181. }
  182. else
  183. initArgs.Add(ptype.GetDefault());
  184. }
  185. init.Invoke(bsPlugin, initArgs.ToArray());
  186. }
  187. bsPlugins.Add(new BSPluginMeta
  188. {
  189. Plugin = bsPlugin,
  190. Filename = file.Replace("\\.cache", ""), // quick and dirty fix
  191. ModsaberInfo = bsPlugin.ModInfo
  192. });
  193. }
  194. catch (AmbiguousMatchException)
  195. {
  196. Logger.log.Error($"Only one Init allowed per plugin");
  197. }
  198. }
  199. else
  200. {
  201. IPlugin ipaPlugin = OptionalGetPlugin<IPlugin>(t);
  202. if (ipaPlugin != null)
  203. {
  204. ipaPlugins.Add(ipaPlugin);
  205. }
  206. }
  207. }
  208. }
  209. catch (Exception e)
  210. {
  211. Logger.log.Error($"Could not load {Path.GetFileName(file)}! {e}");
  212. }
  213. return new Tuple<IEnumerable<BSPluginMeta>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  214. }
  215. public class AppInfo
  216. {
  217. [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
  218. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  219. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  220. public static string StartupPath
  221. {
  222. get
  223. {
  224. StringBuilder stringBuilder = new StringBuilder(260);
  225. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  226. return stringBuilder.ToString();
  227. }
  228. }
  229. }
  230. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  231. }
  232. }