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.

187 lines
8.0 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using IPA.Config;
  6. using IPA.Logging;
  7. using IPA.Utilities;
  8. using System.Linq.Expressions;
  9. #if NET3
  10. using Net3_Proxy;
  11. #endif
  12. namespace IPA.Loader
  13. {
  14. /// <summary>
  15. /// The type that handles value injecting into a plugin's initialization methods.
  16. /// </summary>
  17. /// <remarks>
  18. /// The default injectors and what they provide are shown in this table.
  19. /// <list type="table">
  20. /// <listheader>
  21. /// <term>Parameter Type</term>
  22. /// <description>Injected Value</description>
  23. /// </listheader>
  24. /// <item>
  25. /// <term><see cref="Logger"/></term>
  26. /// <description>A <see cref="StandardLogger"/> specialized for the plugin being injected</description>
  27. /// </item>
  28. /// <item>
  29. /// <term><see cref="PluginMetadata"/></term>
  30. /// <description>The <see cref="PluginMetadata"/> of the plugin being injected</description>
  31. /// </item>
  32. /// <item>
  33. /// <term><see cref="Config.Config"/></term>
  34. /// <description>
  35. /// <para>A <see cref="Config.Config"/> object for the plugin being injected.</para>
  36. /// <para>
  37. /// These parameters may have <see cref="Config.Config.NameAttribute"/> and <see cref="Config.Config.PreferAttribute"/> to control
  38. /// how it is constructed.
  39. /// </para>
  40. /// </description>
  41. /// </item>
  42. /// </list>
  43. /// For all of the default injectors, only one of each will be generated, and any later parameters will recieve the same value as the first one.
  44. /// </remarks>
  45. public static class PluginInitInjector
  46. {
  47. /// <summary>
  48. /// 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.
  49. /// </summary>
  50. /// <param name="previous">the previous return value of the function, or <see langword="null"/> if never called for plugin.</param>
  51. /// <param name="param">the <see cref="ParameterInfo"/> of the parameter being injected.</param>
  52. /// <param name="meta">the <see cref="PluginMetadata"/> for the plugin being loaded.</param>
  53. /// <returns>the value to inject into that parameter.</returns>
  54. public delegate object InjectParameter(object previous, ParameterInfo param, PluginMetadata meta);
  55. /// <summary>
  56. /// Adds an injector to be used when calling future plugins' Init methods.
  57. /// </summary>
  58. /// <param name="type">the type of the parameter.</param>
  59. /// <param name="injector">the function to call for injection.</param>
  60. public static void AddInjector(Type type, InjectParameter injector)
  61. {
  62. injectors.Add(new TypedInjector(type, injector));
  63. }
  64. private struct TypedInjector : IEquatable<TypedInjector>
  65. {
  66. public Type Type;
  67. public InjectParameter Injector;
  68. public TypedInjector(Type t, InjectParameter i)
  69. { Type = t; Injector = i; }
  70. public object Inject(object prev, ParameterInfo info, PluginMetadata meta)
  71. => Injector(prev, info, meta);
  72. public bool Equals(TypedInjector other)
  73. => Type == other.Type && Injector == other.Injector;
  74. public override bool Equals(object obj)
  75. => obj is TypedInjector i && Equals(i);
  76. public override int GetHashCode()
  77. => Type.GetHashCode() ^ Injector.GetHashCode();
  78. public static bool operator ==(TypedInjector a, TypedInjector b) => a.Equals(b);
  79. public static bool operator !=(TypedInjector a, TypedInjector b) => !a.Equals(b);
  80. }
  81. private static readonly List<TypedInjector> injectors = new List<TypedInjector>
  82. {
  83. new TypedInjector(typeof(Logger), (prev, param, meta) => prev ?? new StandardLogger(meta.Name)),
  84. new TypedInjector(typeof(PluginMetadata), (prev, param, meta) => prev ?? meta),
  85. new TypedInjector(typeof(Config.Config), (prev, param, meta) =>
  86. {
  87. if (prev != null) return prev;
  88. return Config.Config.GetConfigFor(meta.Name, param);
  89. })
  90. };
  91. private static int? MatchPriority(Type target, Type source)
  92. {
  93. if (target == source) return int.MaxValue;
  94. if (!target.IsAssignableFrom(source)) return null;
  95. if (!target.IsInterface && !source.IsSubclassOf(target)) return int.MinValue;
  96. int value = 0;
  97. while (true)
  98. {
  99. if (source == null) return value;
  100. if (target.IsInterface && source.GetInterfaces().Contains(target))
  101. return value;
  102. else if (target == source)
  103. return value;
  104. else
  105. {
  106. value--; // lower priority
  107. source = source.BaseType;
  108. }
  109. }
  110. }
  111. private static readonly MethodInfo InjectMethod = typeof(PluginInitInjector).GetMethod(nameof(Inject), BindingFlags.NonPublic | BindingFlags.Static);
  112. internal static Expression InjectedCallExpr(ParameterInfo[] initParams, Expression meta, ParameterExpression persistVar, Func<IEnumerable<Expression>, Expression> exprGen)
  113. {
  114. var arr = Expression.Variable(typeof(object[]), "initArr");
  115. return Expression.Block(new[] { arr },
  116. Expression.Assign(arr, Expression.Call(InjectMethod, Expression.Constant(initParams), meta, persistVar)),
  117. exprGen(initParams
  118. .Select(p => p.ParameterType)
  119. .Select((t, i) => Expression.Convert(
  120. Expression.ArrayIndex(arr, Expression.Constant(i)), t))));
  121. }
  122. internal static object[] Inject(ParameterInfo[] initParams, PluginMetadata meta, ref object persist)
  123. {
  124. var initArgs = new List<object>();
  125. var previousValues = persist as Dictionary<TypedInjector, object>;
  126. if (previousValues == null)
  127. {
  128. previousValues = new Dictionary<TypedInjector, object>(injectors.Count);
  129. persist = previousValues;
  130. }
  131. foreach (var param in initParams)
  132. {
  133. var paramType = param.ParameterType;
  134. var value = paramType.GetDefault();
  135. var toUse = injectors.Select(i => (inject: i, priority: MatchPriority(paramType, i.Type))) // check match priority, combine it
  136. .Where(t => t.priority != null) // filter null priorities
  137. .Select(t => (t.inject, priority: t.priority.Value)) // remove nullable
  138. .OrderByDescending(t => t.priority) // sort by value
  139. .Select(t => t.inject); // remove priority value
  140. // this tries injectors in order of closest match by type provided
  141. foreach (var pair in toUse)
  142. {
  143. object prev = null;
  144. if (previousValues.ContainsKey(pair))
  145. prev = previousValues[pair];
  146. var val = pair.Inject(prev, param, meta);
  147. if (previousValues.ContainsKey(pair))
  148. previousValues[pair] = val;
  149. else
  150. previousValues.Add(pair, val);
  151. if (val == null) continue;
  152. value = val;
  153. break;
  154. }
  155. initArgs.Add(value);
  156. }
  157. //init.Invoke(instance, initArgs.ToArray());
  158. return initArgs.ToArray();
  159. }
  160. }
  161. }