ScopeJsonConverter.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. #nullable enable
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Reflection;
  4. using System.Text.Json;
  5. using System.Text.Json.Serialization;
  6. namespace Terminal.Gui.Configuration;
  7. /// <summary>
  8. /// Converts <see cref="Scope{T}"/> instances to/from JSON. Does all the heavy lifting of reading/writing config
  9. /// data to/from <see cref="ConfigurationManager"/> JSON documents.
  10. /// </summary>
  11. /// <typeparam name="TScopeT"></typeparam>
  12. [RequiresUnreferencedCode ("AOT")]
  13. internal class ScopeJsonConverter<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TScopeT> : JsonConverter<TScopeT>
  14. where TScopeT : Scope<TScopeT>
  15. {
  16. [RequiresDynamicCode ("Calls System.Type.MakeGenericType(params Type[])")]
  17. #pragma warning disable IL3051 // 'RequiresDynamicCodeAttribute' annotations must match across all interface implementations or overrides.
  18. public override TScopeT Read (ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  19. #pragma warning restore IL3051 // 'RequiresDynamicCodeAttribute' annotations must match across all interface implementations or overrides.
  20. {
  21. if (reader.TokenType != JsonTokenType.StartObject)
  22. {
  23. throw new JsonException (
  24. $$"""Expected a JSON object ("{ "propName" : ... }"), but got "{{reader.TokenType}}"."""
  25. );
  26. }
  27. var scope = (TScopeT)Activator.CreateInstance (typeof (TScopeT))!;
  28. var propertyName = string.Empty;
  29. while (reader.Read ())
  30. {
  31. if (reader.TokenType == JsonTokenType.EndObject)
  32. {
  33. return scope!;
  34. }
  35. if (reader.TokenType != JsonTokenType.PropertyName)
  36. {
  37. throw new JsonException ($"After {propertyName}: Expected a JSON property name, but got \"{reader.TokenType}\"");
  38. }
  39. propertyName = reader.GetString ();
  40. reader.Read ();
  41. // Get the hardcoded property from the TscopeT (e.g. ThemeScope.GetHardCodedProperty)
  42. ConfigProperty? configProperty = scope.GetHardCodedProperty (propertyName!);
  43. if (propertyName is { } && configProperty is { })
  44. {
  45. // This property name was found in the cached hard-coded scope dict.
  46. // Add it, with no value
  47. configProperty.HasValue = false;
  48. configProperty.PropertyValue = null;
  49. scope.TryAdd (propertyName, configProperty);
  50. // Figure out if it needs a JsonConverter and if so, create one
  51. Type? propertyType = configProperty?.PropertyInfo?.PropertyType!;
  52. if (configProperty?.PropertyInfo?.GetCustomAttribute (typeof (JsonConverterAttribute)) is
  53. JsonConverterAttribute jca)
  54. {
  55. object? converter = Activator.CreateInstance (jca.ConverterType!)!;
  56. if (converter.GetType ().BaseType == typeof (JsonConverterFactory))
  57. {
  58. var factory = (JsonConverterFactory)converter;
  59. if (factory.CanConvert (propertyType))
  60. {
  61. converter = factory.CreateConverter (propertyType, options);
  62. }
  63. }
  64. try
  65. {
  66. var type = (Type?)typeof (ReadHelper<>).MakeGenericType (typeof (TScopeT), propertyType!);
  67. var readHelper = Activator.CreateInstance (type!, converter) as ReadHelper;
  68. scope! [propertyName].PropertyValue = readHelper?.Read (ref reader, propertyType!, options);
  69. }
  70. catch (NotSupportedException e)
  71. {
  72. throw new JsonException (
  73. $"{propertyName}: Error reading property of type \"{propertyType?.Name}\".",
  74. e
  75. );
  76. }
  77. catch (TargetInvocationException)
  78. {
  79. // QUESTION: Should we try/catch here?
  80. scope! [propertyName].PropertyValue = JsonSerializer.Deserialize (ref reader, propertyType!, options);
  81. }
  82. }
  83. else
  84. {
  85. // QUESTION: Should we try/catch here?
  86. scope! [propertyName].PropertyValue = JsonSerializer.Deserialize (ref reader, propertyType!, ConfigurationManager.SerializerContext);
  87. }
  88. //Logging.Warning ($"{propertyName} = {scope! [propertyName].PropertyValue}");
  89. }
  90. else
  91. {
  92. // It is not a config property. Maybe it's just a property on the Scope with [JsonInclude]
  93. // like ScopeSettings.$schema.
  94. // If so, don't add it to the dictionary but apply it to the underlying property on
  95. // the scopeT.
  96. // BUGBUG: This is a really bad design. The only time it's used is for $schema though.
  97. PropertyInfo? property = scope!.GetType ()
  98. .GetProperties ()
  99. .Where (
  100. p =>
  101. {
  102. if (p.GetCustomAttribute (typeof (JsonIncludeAttribute)) is JsonIncludeAttribute { } jia)
  103. {
  104. var jsonPropertyNameAttribute =
  105. p.GetCustomAttribute (
  106. typeof (JsonPropertyNameAttribute)
  107. ) as
  108. JsonPropertyNameAttribute;
  109. if (jsonPropertyNameAttribute?.Name == propertyName)
  110. {
  111. // Bit of a hack, modifying propertyName in an enumerator...
  112. propertyName = p.Name;
  113. return true;
  114. }
  115. return p.Name == propertyName;
  116. }
  117. return false;
  118. }
  119. )
  120. .FirstOrDefault ();
  121. if (property is { })
  122. {
  123. // Set the value of propertyName on the scopeT.
  124. PropertyInfo prop = scope.GetType ().GetProperty (propertyName!)!;
  125. prop.SetValue (scope, JsonSerializer.Deserialize (ref reader, prop.PropertyType, ConfigurationManager.SerializerContext));
  126. }
  127. else
  128. {
  129. // Unknown property
  130. // TODO: To support forward compatibility, we should just ignore unknown properties?
  131. // TODO: Eg if we read an unknown property, it's possible that the property was added in a later version
  132. throw new JsonException ($"{propertyName}: Unknown property name.");
  133. }
  134. }
  135. }
  136. throw new JsonException ($"{propertyName}: Json error in ScopeJsonConverter");
  137. }
  138. [UnconditionalSuppressMessage (
  139. "AOT",
  140. "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.",
  141. Justification = "<Pending>")]
  142. public override void Write (Utf8JsonWriter writer, TScopeT scope, JsonSerializerOptions options)
  143. {
  144. writer.WriteStartObject ();
  145. IEnumerable<PropertyInfo> properties = scope!.GetType ()
  146. .GetProperties ()
  147. .Where (
  148. p => p.GetCustomAttribute (typeof (JsonIncludeAttribute))
  149. != null
  150. );
  151. foreach (PropertyInfo p in properties)
  152. {
  153. writer.WritePropertyName (ConfigProperty.GetJsonPropertyName (p));
  154. object? prop = scope.GetType ().GetProperty (p.Name)?.GetValue (scope);
  155. JsonSerializer.Serialize (writer, prop, prop!.GetType (), ConfigurationManager.SerializerContext);
  156. }
  157. foreach (KeyValuePair<string, ConfigProperty> p in from p in scope
  158. .Where (
  159. cp =>
  160. cp.Value.PropertyInfo?.GetCustomAttribute (
  161. typeof (
  162. ConfigurationPropertyAttribute)
  163. )
  164. is
  165. ConfigurationPropertyAttribute scp
  166. && scp?.Scope == typeof (TScopeT)
  167. )
  168. where p.Value.HasValue
  169. select p)
  170. {
  171. writer.WritePropertyName (p.Key);
  172. Type? propertyType = p.Value.PropertyInfo?.PropertyType;
  173. if (propertyType != null
  174. && p.Value.PropertyInfo?.GetCustomAttribute (typeof (JsonConverterAttribute)) is JsonConverterAttribute
  175. jca)
  176. {
  177. object converter = Activator.CreateInstance (jca.ConverterType!)!;
  178. if (converter.GetType ().BaseType == typeof (JsonConverterFactory))
  179. {
  180. var factory = (JsonConverterFactory)converter;
  181. if (factory.CanConvert (propertyType))
  182. {
  183. converter = factory.CreateConverter (propertyType, options)!;
  184. }
  185. }
  186. if (p.Value.PropertyValue is { })
  187. {
  188. converter.GetType ()
  189. .GetMethod ("Write")
  190. ?.Invoke (converter, [writer, p.Value.PropertyValue, options]);
  191. }
  192. }
  193. else
  194. {
  195. object? prop = p.Value.PropertyValue;
  196. if (prop == null)
  197. {
  198. writer.WriteNullValue ();
  199. }
  200. else
  201. {
  202. JsonSerializer.Serialize (writer, prop, prop.GetType (), ConfigurationManager.SerializerContext);
  203. }
  204. }
  205. }
  206. writer.WriteEndObject ();
  207. }
  208. // See: https://stackoverflow.com/questions/60830084/how-to-pass-an-argument-by-reference-using-reflection
  209. internal abstract class ReadHelper
  210. {
  211. public abstract object? Read (ref Utf8JsonReader reader, Type type, JsonSerializerOptions options);
  212. }
  213. [method: RequiresUnreferencedCode ("Calls System.Delegate.CreateDelegate(Type, Object, String)")]
  214. internal class ReadHelper<TConverter> (object converter) : ReadHelper
  215. {
  216. private readonly ReadDelegate _readDelegate = (ReadDelegate)Delegate.CreateDelegate (typeof (ReadDelegate), converter, "Read");
  217. public override object? Read (ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
  218. {
  219. return _readDelegate.Invoke (ref reader, type, options);
  220. }
  221. private delegate TConverter ReadDelegate (ref Utf8JsonReader reader, Type type, JsonSerializerOptions options);
  222. }
  223. }