ScopeJsonConverter.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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 terrible design. The only time it's used is for $schema though.
  97. PropertyInfo? property = scope!.GetType ()
  98. .GetProperties ()
  99. .Where (p =>
  100. {
  101. if (p.GetCustomAttribute (typeof (JsonIncludeAttribute)) is JsonIncludeAttribute { } jia)
  102. {
  103. var jsonPropertyNameAttribute =
  104. p.GetCustomAttribute (
  105. typeof (JsonPropertyNameAttribute)
  106. ) as
  107. JsonPropertyNameAttribute;
  108. if (jsonPropertyNameAttribute?.Name == propertyName)
  109. {
  110. // Bit of a hack, modifying propertyName in an enumerator...
  111. propertyName = p.Name;
  112. return true;
  113. }
  114. return p.Name == propertyName;
  115. }
  116. return false;
  117. }
  118. )
  119. .FirstOrDefault ();
  120. if (property is { })
  121. {
  122. // Set the value of propertyName on the scopeT.
  123. PropertyInfo prop = scope.GetType ().GetProperty (propertyName!)!;
  124. prop.SetValue (scope, JsonSerializer.Deserialize (ref reader, prop.PropertyType, ConfigurationManager.SerializerContext));
  125. }
  126. else
  127. {
  128. // Unknown property
  129. // TODO: To support forward compatibility, we should just ignore unknown properties?
  130. // TODO: Eg if we read an unknown property, it's possible that the property was added in a later version
  131. throw new JsonException ($"{propertyName}: Unknown property name.");
  132. }
  133. }
  134. }
  135. throw new JsonException ($"{propertyName}: Json error in ScopeJsonConverter");
  136. }
  137. [UnconditionalSuppressMessage (
  138. "AOT",
  139. "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.",
  140. Justification = "<Pending>")]
  141. public override void Write (Utf8JsonWriter writer, TScopeT scope, JsonSerializerOptions options)
  142. {
  143. writer.WriteStartObject ();
  144. IEnumerable<PropertyInfo> properties = scope!.GetType ()
  145. .GetProperties ()
  146. .Where (p => p.GetCustomAttribute (typeof (JsonIncludeAttribute))
  147. != null
  148. );
  149. foreach (PropertyInfo p in properties)
  150. {
  151. writer.WritePropertyName (ConfigProperty.GetJsonPropertyName (p));
  152. object? prop = scope.GetType ().GetProperty (p.Name)?.GetValue (scope);
  153. JsonSerializer.Serialize (writer, prop, prop!.GetType (), ConfigurationManager.SerializerContext);
  154. }
  155. foreach (KeyValuePair<string, ConfigProperty> p in from p in scope
  156. .Where (cp =>
  157. cp.Value.PropertyInfo?.GetCustomAttribute (
  158. typeof (
  159. ConfigurationPropertyAttribute)
  160. )
  161. is
  162. ConfigurationPropertyAttribute scp
  163. && scp?.Scope == typeof (TScopeT)
  164. )
  165. where p.Value.HasValue
  166. select p)
  167. {
  168. writer.WritePropertyName (p.Key);
  169. Type? propertyType = p.Value.PropertyInfo?.PropertyType;
  170. if (propertyType != null
  171. && p.Value.PropertyInfo?.GetCustomAttribute (typeof (JsonConverterAttribute)) is JsonConverterAttribute
  172. jca)
  173. {
  174. object converter = Activator.CreateInstance (jca.ConverterType!)!;
  175. if (converter.GetType ().BaseType == typeof (JsonConverterFactory))
  176. {
  177. var factory = (JsonConverterFactory)converter;
  178. if (factory.CanConvert (propertyType))
  179. {
  180. converter = factory.CreateConverter (propertyType, options)!;
  181. }
  182. }
  183. if (p.Value.PropertyValue is { })
  184. {
  185. converter.GetType ()
  186. .GetMethod ("Write")
  187. ?.Invoke (converter, [writer, p.Value.PropertyValue, options]);
  188. }
  189. }
  190. else
  191. {
  192. object? prop = p.Value.PropertyValue;
  193. if (prop == null)
  194. {
  195. writer.WriteNullValue ();
  196. }
  197. else
  198. {
  199. JsonSerializer.Serialize (writer, prop, prop.GetType (), ConfigurationManager.SerializerContext);
  200. }
  201. }
  202. }
  203. writer.WriteEndObject ();
  204. }
  205. // See: https://stackoverflow.com/questions/60830084/how-to-pass-an-argument-by-reference-using-reflection
  206. internal abstract class ReadHelper
  207. {
  208. public abstract object? Read (ref Utf8JsonReader reader, Type type, JsonSerializerOptions options);
  209. }
  210. [method: RequiresUnreferencedCode ("Calls System.Delegate.CreateDelegate(Type, Object, String)")]
  211. internal class ReadHelper<TConverter> (object converter) : ReadHelper
  212. {
  213. private readonly ReadDelegate _readDelegate = (ReadDelegate)Delegate.CreateDelegate (typeof (ReadDelegate), converter, "Read");
  214. public override object? Read (ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
  215. {
  216. return _readDelegate.Invoke (ref reader, type, options);
  217. }
  218. private delegate TConverter ReadDelegate (ref Utf8JsonReader reader, Type type, JsonSerializerOptions options);
  219. }
  220. }