ScopeJsonConverter.cs 12 KB

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