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.

308 lines
13 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.Generic;
  9. using System.Diagnostics;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Reflection;
  13. using System.Runtime.CompilerServices;
  14. using System.Runtime.InteropServices;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. namespace IPA.Loader
  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. #region Fix assemblies for refactor
  156. var module = ModuleDefinition.ReadModule(file);
  157. bool modifiedModule = false;
  158. foreach (var @ref in module.AssemblyReferences)
  159. { // fix assembly references
  160. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  161. {
  162. @ref.Name = "IPA.Loader";
  163. modifiedModule = true;
  164. }
  165. }
  166. if (modifiedModule)
  167. { // types don't need to be fixed if it's already referencing the new version
  168. foreach (var @ref in module.GetTypeReferences())
  169. { // fix type references
  170. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  171. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  172. if (@ref.FullName == "IllusionPlugin.IBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  173. if (@ref.FullName == "IllusionPlugin.IEnhancedBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  174. if (@ref.FullName == "IllusionPlugin.BeatSaber.ModsaberModInfo") @ref.Namespace = "IPA"; //@ref.Name = "";
  175. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA"; //@ref.Name = "";
  176. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA"; //@ref.Name = "";
  177. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA"; //@ref.Name = "";
  178. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  179. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  180. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  181. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  182. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  183. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  184. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  185. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  186. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  187. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  188. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  189. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  190. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  191. if (@ref.Namespace == "IllusionInjector.Updating.ModsaberML") @ref.Namespace = "IPA.Updating.ModsaberML"; //@ref.Name = "";
  192. }
  193. module.Write(file);
  194. }
  195. #endregion
  196. Assembly assembly = Assembly.LoadFrom(file);
  197. foreach (Type t in assembly.GetTypes())
  198. {
  199. IBeatSaberPlugin bsPlugin = OptionalGetPlugin<IBeatSaberPlugin>(t);
  200. if (bsPlugin != null)
  201. {
  202. try
  203. {
  204. var init = t.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public);
  205. if (init != null)
  206. {
  207. var initArgs = new List<object>();
  208. var initParams = init.GetParameters();
  209. Logger modLogger = null;
  210. IModPrefs modPrefs = null;
  211. foreach (var param in initParams)
  212. {
  213. var ptype = param.ParameterType;
  214. if (ptype.IsAssignableFrom(typeof(Logger))) {
  215. if (modLogger == null) modLogger = new StandardLogger(bsPlugin.Name);
  216. initArgs.Add(modLogger);
  217. }
  218. else if (ptype.IsAssignableFrom(typeof(IModPrefs)))
  219. {
  220. if (modPrefs == null) modPrefs = new ModPrefs(bsPlugin);
  221. initArgs.Add(modPrefs);
  222. }
  223. else
  224. initArgs.Add(ptype.GetDefault());
  225. }
  226. init.Invoke(bsPlugin, initArgs.ToArray());
  227. }
  228. bsPlugins.Add(new BSPluginMeta
  229. {
  230. Plugin = bsPlugin,
  231. Filename = file.Replace("\\.cache", ""), // quick and dirty fix
  232. ModsaberInfo = bsPlugin.ModInfo
  233. });
  234. }
  235. catch (AmbiguousMatchException)
  236. {
  237. Logger.log.Error($"Only one Init allowed per plugin");
  238. }
  239. }
  240. else
  241. {
  242. IPlugin ipaPlugin = OptionalGetPlugin<IPlugin>(t);
  243. if (ipaPlugin != null)
  244. {
  245. ipaPlugins.Add(ipaPlugin);
  246. }
  247. }
  248. }
  249. }
  250. catch (Exception e)
  251. {
  252. Logger.log.Error($"Could not load {Path.GetFileName(file)}! {e}");
  253. }
  254. return new Tuple<IEnumerable<BSPluginMeta>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  255. }
  256. public class AppInfo
  257. {
  258. [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
  259. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  260. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  261. public static string StartupPath
  262. {
  263. get
  264. {
  265. StringBuilder stringBuilder = new StringBuilder(260);
  266. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  267. return stringBuilder.ToString();
  268. }
  269. }
  270. }
  271. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  272. }
  273. }