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.

223 lines
9.4 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. #if NET3
  5. using Net3_Proxy;
  6. #endif
  7. namespace IPA.Loader.Features
  8. {
  9. /// <summary>
  10. /// The root interface for a mod Feature.
  11. /// </summary>
  12. /// <remarks>
  13. /// Avoid storing any data in any subclasses. If you do, it may result in a failure to load the feature.
  14. /// </remarks>
  15. public abstract class Feature
  16. {
  17. /// <summary>
  18. /// Initializes the feature with the parameters provided in the definition.
  19. ///
  20. /// Note: When no parenthesis are provided, <paramref name="parameters"/> is an empty array.
  21. /// </summary>
  22. /// <remarks>
  23. /// This gets called BEFORE *your* `Init` method.
  24. ///
  25. /// Returning <see langword="false" /> does *not* prevent the plugin from being loaded. It simply prevents the feature from being used.
  26. /// </remarks>
  27. /// <param name="meta">the metadata of the plugin that is being prepared</param>
  28. /// <param name="parameters">the parameters passed to the feature definition, or null</param>
  29. /// <returns><see langword="true"/> if the feature is valid for the plugin, <see langword="false"/> otherwise</returns>
  30. public abstract bool Initialize(PluginMetadata meta, string[] parameters);
  31. /// <summary>
  32. /// Evaluates the Feature for use in conditional meta-Features. This should be re-calculated on every call, unless it can be proven to not change.
  33. ///
  34. /// This will be called on every feature that returns <see langword="true" /> from <see cref="Initialize"/>
  35. /// </summary>
  36. /// <returns>the truthiness of the Feature.</returns>
  37. public virtual bool Evaluate() => true;
  38. /// <summary>
  39. /// The message to be logged when the feature is not valid for a plugin.
  40. /// This should also be set whenever either <see cref="BeforeLoad"/> or <see cref="BeforeInit"/> returns false.
  41. /// </summary>
  42. /// <value>the message to show when the feature is marked invalid</value>
  43. public virtual string InvalidMessage { get; protected set; }
  44. /// <summary>
  45. /// Called before a plugin is loaded. This should never throw an exception. An exception will abort the loading of the plugin with an error.
  46. /// </summary>
  47. /// <remarks>
  48. /// The assembly will still be loaded, but the plugin will not be constructed if this returns <see langword="false" />.
  49. /// Any features it defines, for example, will still be loaded.
  50. /// </remarks>
  51. /// <param name="plugin">the plugin about to be loaded</param>
  52. /// <returns>whether or not the plugin should be loaded</returns>
  53. public virtual bool BeforeLoad(PluginMetadata plugin) => true;
  54. /// <summary>
  55. /// 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.
  56. /// </summary>
  57. /// <param name="plugin">the plugin to be initialized</param>
  58. /// <returns>whether or not to call the Init method</returns>
  59. public virtual bool BeforeInit(PluginLoader.PluginInfo plugin) => true;
  60. /// <summary>
  61. /// Called after a plugin has been fully initialized, whether or not there is an `Init` method. This should never throw an exception.
  62. /// </summary>
  63. /// <param name="plugin">the plugin that was just initialized</param>
  64. /// <param name="pluginInstance">the instance of the plugin being initialized</param>
  65. public virtual void AfterInit(PluginLoader.PluginInfo plugin, IPlugin pluginInstance) => AfterInit(plugin);
  66. /// <summary>
  67. /// Called after a plugin has been fully initialized, whether or not there is an `Init` method. This should never throw an exception.
  68. /// </summary>
  69. /// <param name="plugin">the plugin that was just initialized</param>
  70. public virtual void AfterInit(PluginLoader.PluginInfo plugin) { }
  71. /// <summary>
  72. /// Ensures a plugin's assembly is loaded. Do not use unless you need to.
  73. /// </summary>
  74. /// <param name="plugin">the plugin to ensure is loaded.</param>
  75. protected void RequireLoaded(PluginMetadata plugin) => PluginLoader.Load(plugin);
  76. /// <summary>
  77. /// Defines whether or not this feature will be accessible from the plugin metadata once loaded.
  78. /// </summary>
  79. /// <value><see langword="true"/> if this <see cref="Feature"/> will be stored on the plugin metadata, <see langword="false"/> otherwise</value>
  80. protected internal virtual bool StoreOnPlugin => true;
  81. static Feature()
  82. {
  83. Reset();
  84. }
  85. internal static void Reset()
  86. {
  87. featureTypes = new Dictionary<string, Type>
  88. {
  89. { "define-feature", typeof(DefineFeature) }
  90. };
  91. }
  92. private static Dictionary<string, Type> featureTypes;
  93. internal static bool HasFeature(string name) => featureTypes.ContainsKey(name);
  94. internal static bool RegisterFeature(string name, Type type)
  95. {
  96. if (!typeof(Feature).IsAssignableFrom(type))
  97. throw new ArgumentException($"Feature type not subclass of {nameof(Feature)}", nameof(type));
  98. if (featureTypes.ContainsKey(name)) return false;
  99. featureTypes.Add(name, type);
  100. return true;
  101. }
  102. internal struct FeatureParse
  103. {
  104. public readonly string Name;
  105. public readonly string[] Parameters;
  106. public FeatureParse(string name, string[] parameters)
  107. {
  108. Name = name;
  109. Parameters = parameters;
  110. }
  111. }
  112. // returns false with both outs null for no such feature
  113. internal static bool TryParseFeature(string featureString, PluginMetadata plugin,
  114. out Feature feature, out Exception failException, out bool featureValid, out FeatureParse parsed,
  115. FeatureParse? preParsed = null)
  116. {
  117. failException = null;
  118. feature = null;
  119. featureValid = false;
  120. if (preParsed == null)
  121. {
  122. var builder = new StringBuilder();
  123. string name = null;
  124. var parameters = new List<string>();
  125. bool escape = false;
  126. int parens = 0;
  127. bool removeWhitespace = true;
  128. foreach (var chr in featureString)
  129. {
  130. if (escape)
  131. {
  132. builder.Append(chr);
  133. escape = false;
  134. }
  135. else
  136. {
  137. switch (chr)
  138. {
  139. case '\\':
  140. escape = true;
  141. break;
  142. case '(':
  143. parens++;
  144. if (parens != 1) goto default;
  145. removeWhitespace = true;
  146. name = builder.ToString();
  147. builder.Clear();
  148. break;
  149. case ')':
  150. parens--;
  151. if (parens != 0) goto default;
  152. goto case ',';
  153. case ',':
  154. if (parens > 1) goto default;
  155. parameters.Add(builder.ToString());
  156. builder.Clear();
  157. removeWhitespace = true;
  158. break;
  159. default:
  160. if (removeWhitespace && !char.IsWhiteSpace(chr))
  161. removeWhitespace = false;
  162. if (!removeWhitespace)
  163. builder.Append(chr);
  164. break;
  165. }
  166. }
  167. }
  168. if (name == null)
  169. name = builder.ToString();
  170. parsed = new FeatureParse(name, parameters.ToArray());
  171. if (parens != 0)
  172. {
  173. failException = new Exception("Malformed feature definition");
  174. return false;
  175. }
  176. }
  177. else
  178. parsed = preParsed.Value;
  179. if (!featureTypes.TryGetValue(parsed.Name, out var featureType))
  180. return false;
  181. try
  182. {
  183. if (!(Activator.CreateInstance(featureType) is Feature aFeature))
  184. {
  185. failException = new InvalidCastException("Feature type not a subtype of Feature");
  186. return false;
  187. }
  188. featureValid = aFeature.Initialize(plugin, parsed.Parameters);
  189. feature = aFeature;
  190. return true;
  191. }
  192. catch (Exception e)
  193. {
  194. failException = e;
  195. return false;
  196. }
  197. }
  198. }
  199. }