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.

297 lines
12 KiB

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