diff --git a/BSIPA.sln.DotSettings b/BSIPA.sln.DotSettings index a98617fe..88825ef8 100644 --- a/BSIPA.sln.DotSettings +++ b/BSIPA.sln.DotSettings @@ -23,6 +23,7 @@ True True True + True True True True diff --git a/IPA.Loader/IPA.Loader.csproj b/IPA.Loader/IPA.Loader.csproj index 3f382f65..33fa27fe 100644 --- a/IPA.Loader/IPA.Loader.csproj +++ b/IPA.Loader/IPA.Loader.csproj @@ -14,6 +14,7 @@ true $(SolutionDir)=C:\ portable + true @@ -61,6 +62,10 @@ + + + + @@ -96,7 +101,7 @@ - + diff --git a/IPA.Loader/Loader/Features/DefineFeature.cs b/IPA.Loader/Loader/Features/DefineFeature.cs new file mode 100644 index 00000000..c2b30511 --- /dev/null +++ b/IPA.Loader/Loader/Features/DefineFeature.cs @@ -0,0 +1,66 @@ +using System; +using System.IO; + +namespace IPA.Loader.Features +{ + internal class DefineFeature : Feature + { + public static bool NewFeature = true; + + public override bool Initialize(PluginLoader.PluginMetadata meta, string[] parameters) + { // parameters should be (name, fully qualified type) + if (parameters.Length != 2) + { + InvalidMessage = "Incorrect number of parameters"; + return false; + } + + RequireLoaded(meta); + + Type type; + try + { + type = meta.Assembly.GetType(parameters[1]); + } + catch (ArgumentException) + { + InvalidMessage = $"Invalid type name {parameters[1]}"; + return false; + } + catch (Exception e) when (e is FileNotFoundException || e is FileLoadException || e is BadImageFormatException) + { + var filename = ""; + + switch (e) + { + case FileNotFoundException fn: + filename = fn.FileName; + break; + case FileLoadException fl: + filename = fl.FileName; + break; + case BadImageFormatException bi: + filename = bi.FileName; + break; + } + + InvalidMessage = $"Could not find {filename} while loading type"; + return false; + } + + try + { + if (RegisterFeature(parameters[0], type)) return NewFeature = true; + + InvalidMessage = $"Feature with name {parameters[0]} already exists"; + return false; + + } + catch (ArgumentException) + { + InvalidMessage = $"{type.FullName} not a subclass of {nameof(Feature)}"; + return false; + } + } + } +} diff --git a/IPA.Loader/Loader/Features/Feature.cs b/IPA.Loader/Loader/Features/Feature.cs index 2c2d565a..7f707732 100644 --- a/IPA.Loader/Loader/Features/Feature.cs +++ b/IPA.Loader/Loader/Features/Feature.cs @@ -1,38 +1,183 @@ -namespace IPA.Loader.Features +using System; +using System.Collections.Generic; +using System.Text; + +namespace IPA.Loader.Features { /// /// The root interface for a mod Feature. /// + /// + /// Avoid storing any data in any subclasses. If you do, it may result in a failure to load the feature. + /// public abstract class Feature { /// /// Initializes the feature with the parameters provided in the definition. /// - /// Note: When no parenthesis are provided, is null. + /// Note: When no parenthesis are provided, is an empty array. /// + /// + /// Returning does *not* prevent the plugin from being loaded. It simply prevents the feature from being used. + /// /// the metadata of the plugin that is being prepared /// the parameters passed to the feature definition, or null /// if the feature is valid for the plugin, otherwise public abstract bool Initialize(PluginLoader.PluginMetadata meta, string[] parameters); /// - /// Called before a plugin is loaded. + /// The message to be logged when the feature is not valid for a plugin. + /// This should also be set whenever either or returns false. /// + public virtual string InvalidMessage { get; protected set; } + + /// + /// Called before a plugin is loaded. This should never throw an exception. An exception will abort the loading of the plugin with an error. + /// + /// + /// The assembly will still be loaded, but the plugin will not be constructed if this returns . + /// Any features it defines, for example, will still be loaded. + /// /// the plugin about to be loaded /// whether or not the plugin should be loaded public virtual bool BeforeLoad(PluginLoader.PluginMetadata plugin) => true; /// - /// Called before a plugin's Init method is called. + /// Called before a plugin's Init method is called. This will not be called if there is no Init method. This should never throw an exception. An exception will abort the loading of the plugin with an error. /// /// the plugin to be initialized /// whether or not to call the Init method public virtual bool BeforeInit(PluginLoader.PluginInfo plugin) => true; /// - /// Called after a plugin has been fully initialized, whether or not there is an Init method. + /// Called after a plugin has been fully initialized, whether or not there is an Init method. This should never throw an exception. /// /// the plugin that was just initialized public virtual void AfterInit(PluginLoader.PluginInfo plugin) { } + + /// + /// Ensures a plugin's assembly is loaded. Do not use unless you need to. + /// + /// the plugin to ensure is loaded. + protected void RequireLoaded(PluginLoader.PluginMetadata plugin) => PluginLoader.Load(plugin); + + private static readonly Dictionary featureTypes = new Dictionary + { + { "define-feature", typeof(DefineFeature) } + }; + + internal static bool RegisterFeature(string name, Type type) + { + if (!typeof(Feature).IsAssignableFrom(type)) + throw new ArgumentException($"Feature type not subclass of {nameof(Feature)}", nameof(type)); + if (featureTypes.ContainsKey(name)) return false; + featureTypes.Add(name, type); + return true; + } + + internal struct FeatureParse + { + public readonly string Name; + public readonly string[] Parameters; + + public FeatureParse(string name, string[] parameters) + { + Name = name; + Parameters = parameters; + } + } + + // returns false with both outs null for no such feature + internal static bool TryParseFeature(string featureString, PluginLoader.PluginMetadata plugin, + out Feature feature, out Exception failException, out bool featureValid, out FeatureParse parsed, + FeatureParse? preParsed = null) + { + failException = null; + feature = null; + featureValid = false; + + if (preParsed == null) + { + var builder = new StringBuilder(); + string name = null; + var parameters = new List(); + + bool escape = false; + bool readingParams = false; + bool removeWhitespace = true; + foreach (var chr in featureString) + { + if (escape) + { + builder.Append(chr); + escape = false; + } + else + { + switch (chr) + { + case '\\': + escape = true; + break; + case '(' when !readingParams: + removeWhitespace = true; + readingParams = true; + name = builder.ToString(); + builder.Clear(); + break; + case ')' when readingParams: + readingParams = false; + goto case ','; + case ',': + parameters.Add(builder.ToString()); + if (!readingParams) break; + builder.Clear(); + removeWhitespace = true; + break; + default: + if (removeWhitespace && !char.IsWhiteSpace(chr)) + removeWhitespace = false; + if (!removeWhitespace) + builder.Append(chr); + break; + } + } + } + + if (name == null) + name = builder.ToString(); + + parsed = new FeatureParse(name, parameters.ToArray()); + + if (readingParams) + { + failException = new Exception("Malformed feature definition"); + return false; + } + } + else + parsed = preParsed.Value; + + if (!featureTypes.TryGetValue(parsed.Name, out var featureType)) + return false; + + try + { + if (!(Activator.CreateInstance(featureType) is Feature aFeature)) + { + failException = new InvalidCastException("Feature type not a subtype of Feature"); + return false; + } + + featureValid = aFeature.Initialize(plugin, parsed.Parameters); + feature = aFeature; + return true; + } + catch (Exception e) + { + failException = e; + return false; + } + } } } \ No newline at end of file diff --git a/IPA.Loader/Loader/Features/NoUpdateFeature.cs b/IPA.Loader/Loader/Features/NoUpdateFeature.cs new file mode 100644 index 00000000..ed5ebd97 --- /dev/null +++ b/IPA.Loader/Loader/Features/NoUpdateFeature.cs @@ -0,0 +1,12 @@ +namespace IPA.Loader.Features +{ + internal class NoUpdateFeature : Feature + { + public override bool Initialize(PluginLoader.PluginMetadata meta, string[] parameters) + { + return meta.Id != null; + } + + public override string InvalidMessage { get; protected set; } = "No ID specified; cannot update anyway"; + } +} diff --git a/IPA.Loader/Loader/Features/PrintFeature.cs b/IPA.Loader/Loader/Features/PrintFeature.cs new file mode 100644 index 00000000..52b03316 --- /dev/null +++ b/IPA.Loader/Loader/Features/PrintFeature.cs @@ -0,0 +1,14 @@ + +using IPA.Logging; + +namespace IPA.Loader.Features +{ + internal class PrintFeature : Feature + { + public override bool Initialize(PluginLoader.PluginMetadata meta, string[] parameters) + { + Logger.features.Info($"{meta.Name}: {string.Join(" ", parameters)}"); + return true; + } + } +} diff --git a/IPA.Loader/Loader/PluginInitInjector.cs b/IPA.Loader/Loader/PluginInitInjector.cs new file mode 100644 index 00000000..aaf82437 --- /dev/null +++ b/IPA.Loader/Loader/PluginInitInjector.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using IPA.Config; +using IPA.Logging; +using IPA.Utilities; + +namespace IPA.Loader +{ + /// + /// The type that handles value injecting into a plugin's Init. + /// + public static class PluginInitInjector + { + + /// + /// A typed injector for a plugin's Init method. When registered, called for all associated types. If it returns null, the default for the type will be used. + /// + /// the previous return value of the function, or if never called for plugin. + /// the of the parameter being injected. + /// the for the plugin being loaded. + /// the value to inject into that parameter. + public delegate object InjectParameter(object previous, ParameterInfo param, PluginLoader.PluginMetadata meta); + + /// + /// Adds an injector to be used when calling future plugins' Init methods. + /// + /// the type of the parameter. + /// the function to call for injection. + public static void AddInjector(Type type, InjectParameter injector) + { + injectors.Add(new Tuple(type, injector)); + } + + private static readonly List> injectors = new List> + { + new Tuple(typeof(Logger), (prev, param, meta) => prev ?? new StandardLogger(meta.Name)), + new Tuple(typeof(IModPrefs), (prev, param, meta) => prev ?? new ModPrefs(meta)), + new Tuple(typeof(IConfigProvider), (prev, param, meta) => + { + if (prev != null) return prev; + var cfgProvider = Config.Config.GetProviderFor(meta.Name, param); + cfgProvider.Load(); + return cfgProvider; + }) + }; + + internal static void Inject(MethodInfo init, PluginLoader.PluginInfo info) + { + var instance = info.Plugin; + var meta = info.Metadata; + + var initArgs = new List(); + var initParams = init.GetParameters(); + + Dictionary, object> previousValues = + new Dictionary, object>(injectors.Count); + + foreach (var param in initParams) + { + var paramType = param.ParameterType; + + var value = paramType.GetDefault(); + foreach (var pair in injectors.Where(t => paramType.IsAssignableFrom(t.Item1))) + { + object prev = null; + if (previousValues.ContainsKey(pair)) + prev = previousValues[pair]; + + var val = pair.Item2?.Invoke(prev, param, meta); + + if (previousValues.ContainsKey(pair)) + previousValues[pair] = val; + else + previousValues.Add(pair, val); + + if (val == null) continue; + value = val; + break; + } + + initArgs.Add(value); + } + + init.Invoke(instance, initArgs.ToArray()); + } + } +} diff --git a/IPA.Loader/Loader/PluginLoader.cs b/IPA.Loader/Loader/PluginLoader.cs index 16ebedc5..57e58dc6 100644 --- a/IPA.Loader/Loader/PluginLoader.cs +++ b/IPA.Loader/Loader/PluginLoader.cs @@ -1,5 +1,4 @@ -using IPA.Config; -using IPA.Loader.Features; +using IPA.Loader.Features; using IPA.Logging; using IPA.Utilities; using Mono.Cecil; @@ -24,6 +23,7 @@ namespace IPA.Loader LoadMetadata(); Resolve(); ComputeLoadOrder(); + InitFeatures(); }); /// @@ -84,7 +84,7 @@ namespace IPA.Loader } /// - public override string ToString() => $"{Name}({Id}@{Version})({PluginType?.FullName}) from '{LoneFunctions.GetRelativePath(File?.FullName, BeatSaber.InstallPath)}'"; + public override string ToString() => $"{Name}({Id}@{Version})({PluginType?.FullName}) from '{Utils.GetRelativePath(File?.FullName, BeatSaber.InstallPath)}'"; } /// @@ -296,6 +296,58 @@ namespace IPA.Loader PluginsMetadata = metadata; } + internal static void InitFeatures() + { + var parsedFeatures = PluginsMetadata.Select(m => + Tuple.Create(m, + m.Manifest.Features.Select(f => + Tuple.Create(f, Ref.Create(null)) + ).ToList() + ) + ).ToList(); + + while (DefineFeature.NewFeature) + { + DefineFeature.NewFeature = false; + + foreach (var plugin in parsedFeatures) + for (var i = 0; i < plugin.Item2.Count; i++) + { + var feature = plugin.Item2[i]; + + var success = Feature.TryParseFeature(feature.Item1, plugin.Item1, out var featureObj, + out var exception, out var valid, out var parsed, feature.Item2.Value); + + if (!success && !valid && featureObj == null && exception == null) // no feature of type found + feature.Item2.Value = parsed; + else if (success) + { + if (valid) + plugin.Item1.InternalFeatures.Add(featureObj); + else + Logger.features.Warn( + $"Feature not valid on {plugin.Item1.Name}: {featureObj.InvalidMessage}"); + plugin.Item2.RemoveAt(i--); + } + else + { + Logger.features.Error($"Error parsing feature definition on {plugin.Item1.Name}"); + Logger.features.Error(exception); + plugin.Item2.RemoveAt(i--); + } + } + } + + foreach (var plugin in parsedFeatures) + { + if (plugin.Item2.Count <= 0) continue; + + Logger.features.Warn($"On plugin {plugin.Item1.Name}:"); + foreach (var feature in plugin.Item2) + Logger.features.Warn($" Feature not found with name {feature.Item1}"); + } + } + internal static void Load(PluginMetadata meta) { if (meta.Assembly == null) @@ -317,52 +369,43 @@ namespace IPA.Loader { Load(meta); + Feature denyingFeature = null; + if (!meta.Features.All(f => (denyingFeature = f).BeforeLoad(meta))) + { + Logger.loader.Warn( + $"Feature {denyingFeature?.GetType()} denied plugin {meta.Name} from loading! {denyingFeature?.InvalidMessage}"); + return null; + } + var type = meta.Assembly.GetType(meta.PluginType.FullName); var instance = (IBeatSaberPlugin)Activator.CreateInstance(type); info.Metadata = meta; info.Plugin = instance; + var init = type.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public); + if (init != null) { - var init = type.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public); - if (init != null) + denyingFeature = null; + if (!meta.Features.All(f => (denyingFeature = f).BeforeInit(info))) { - var initArgs = new List(); - var initParams = init.GetParameters(); - - Logger modLogger = null; - IModPrefs modPrefs = null; - IConfigProvider cfgProvider = null; + Logger.loader.Warn( + $"Feature {denyingFeature?.GetType()} denied plugin {meta.Name} from initializing! {denyingFeature?.InvalidMessage}"); + return null; + } - foreach (var param in initParams) - { - var paramType = param.ParameterType; - if (paramType.IsAssignableFrom(typeof(Logger))) - { - if (modLogger == null) modLogger = new StandardLogger(meta.Name); - initArgs.Add(modLogger); - } - else if (paramType.IsAssignableFrom(typeof(IModPrefs))) - { - if (modPrefs == null) modPrefs = new ModPrefs(instance); - initArgs.Add(modPrefs); - } - else if (paramType.IsAssignableFrom(typeof(IConfigProvider))) - { - if (cfgProvider == null) - { - cfgProvider = Config.Config.GetProviderFor(Path.Combine("UserData", $"{meta.Name}"), param); - cfgProvider.Load(); - } - initArgs.Add(cfgProvider); - } - else - initArgs.Add(paramType.GetDefault()); - } + PluginInitInjector.Inject(init, info); + } - init.Invoke(instance, initArgs.ToArray()); + foreach (var feature in meta.Features) + try + { + feature.AfterInit(info); + } + catch (Exception e) + { + Logger.loader.Critical($"Feature errored in {nameof(Feature.AfterInit)}: {e}"); } - } } catch (AmbiguousMatchException) { @@ -379,5 +422,5 @@ namespace IPA.Loader } internal static List LoadPlugins() => PluginsMetadata.Select(InitPlugin).Where(p => p != null).ToList(); - } + } } \ No newline at end of file diff --git a/IPA.Loader/Loader/manifest.json b/IPA.Loader/Loader/manifest.json index 566cbd55..029b5189 100644 --- a/IPA.Loader/Loader/manifest.json +++ b/IPA.Loader/Loader/manifest.json @@ -7,6 +7,8 @@ "name": "BSIPA", "version": "3.12.0", "features": [ - "early-load" + "define-feature(print, IPA.Loader.Features.PrintFeature)", + "define-feature(no-update, IPA.Loader.Features.NoUpdateFeature)", + "print(YO! Howz it goin\\, its ya boi desinc here)" ] } \ No newline at end of file diff --git a/IPA.Loader/Logging/Logger.cs b/IPA.Loader/Logging/Logger.cs index fe4409ef..33b5b5fd 100644 --- a/IPA.Loader/Logging/Logger.cs +++ b/IPA.Loader/Logging/Logger.cs @@ -24,6 +24,7 @@ namespace IPA.Logging internal static Logger updater => log.GetChildLogger("Updater"); internal static Logger libLoader => log.GetChildLogger("LibraryLoader"); internal static Logger loader => log.GetChildLogger("Loader"); + internal static Logger features => loader.GetChildLogger("Features"); internal static Logger config => log.GetChildLogger("Config"); internal static bool LogCreated => _log != null || UnityLogProvider.Logger != null; diff --git a/IPA.Loader/Utilities/BeatSaber.cs b/IPA.Loader/Utilities/BeatSaber.cs index a26d9b85..18f39990 100644 --- a/IPA.Loader/Utilities/BeatSaber.cs +++ b/IPA.Loader/Utilities/BeatSaber.cs @@ -52,6 +52,10 @@ namespace IPA.Utilities /// The directory to load plugins from. /// public static string PluginsPath => Path.Combine(InstallPath, "Plugins"); + /// + /// The path to the `UserData` folder. + /// + public static string UserDataPath => Path.Combine(InstallPath, "UserData"); private static bool FindSteamVRAsset() { diff --git a/Refs/UnityEngine.CoreModule.dll b/Refs/UnityEngine.CoreModule.dll index a802a5c6..0913c47b 100644 Binary files a/Refs/UnityEngine.CoreModule.dll and b/Refs/UnityEngine.CoreModule.dll differ