AttributeJsonConverter.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. using Terminal.Gui;
  5. namespace Terminal.Gui {
  6. /// <summary>
  7. /// Json converter fro the <see cref="Attribute"/> class.
  8. /// </summary>
  9. class AttributeJsonConverter : JsonConverter<Attribute> {
  10. private static AttributeJsonConverter instance;
  11. /// <summary>
  12. ///
  13. /// </summary>
  14. public static AttributeJsonConverter Instance {
  15. get {
  16. if (instance == null) {
  17. instance = new AttributeJsonConverter ();
  18. }
  19. return instance;
  20. }
  21. }
  22. public override Attribute Read (ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  23. {
  24. if (reader.TokenType != JsonTokenType.StartObject) {
  25. throw new JsonException ($"Unexpected StartObject token when parsing Attribute: {reader.TokenType}.");
  26. }
  27. Attribute attribute = new Attribute ();
  28. Color foreground = (Color)(-1);
  29. Color background = (Color)(-1);
  30. while (reader.Read ()) {
  31. if (reader.TokenType == JsonTokenType.EndObject) {
  32. if (foreground == (Color)(-1) || background == (Color)(-1)) {
  33. throw new JsonException ($"Both Foreground and Background colors must be provided.");
  34. }
  35. return attribute;
  36. }
  37. if (reader.TokenType != JsonTokenType.PropertyName) {
  38. throw new JsonException ($"Unexpected token when parsing Attribute: {reader.TokenType}.");
  39. }
  40. string propertyName = reader.GetString ();
  41. reader.Read ();
  42. string color = $"\"{reader.GetString ()}\"";
  43. switch (propertyName.ToLower ()) {
  44. case "foreground":
  45. foreground = JsonSerializer.Deserialize<Color> (color, options);
  46. break;
  47. case "background":
  48. background = JsonSerializer.Deserialize<Color> (color, options);
  49. break;
  50. //case "Bright":
  51. // attribute.Bright = reader.GetBoolean ();
  52. // break;
  53. //case "Underline":
  54. // attribute.Underline = reader.GetBoolean ();
  55. // break;
  56. //case "Reverse":
  57. // attribute.Reverse = reader.GetBoolean ();
  58. // break;
  59. default:
  60. throw new JsonException ($"Unknown Attribute property {propertyName}.");
  61. }
  62. attribute = new Attribute (foreground, background);
  63. }
  64. throw new JsonException ();
  65. }
  66. public override void Write (Utf8JsonWriter writer, Attribute value, JsonSerializerOptions options)
  67. {
  68. writer.WriteStartObject ();
  69. writer.WritePropertyName ("Foreground");
  70. ColorJsonConverter.Instance.Write (writer, value.Foreground, options);
  71. writer.WritePropertyName ("Background");
  72. ColorJsonConverter.Instance.Write (writer, value.Background, options);
  73. writer.WriteEndObject ();
  74. }
  75. }
  76. }