ColorJsonConverter.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Text.Json.Serialization;
  3. using System.Text.Json;
  4. using System.Text.RegularExpressions;
  5. namespace Terminal.Gui {
  6. /// <summary>
  7. /// Json converter for the <see cref="Color"/> class.
  8. /// </summary>
  9. internal class ColorJsonConverter : JsonConverter<Color> {
  10. private static ColorJsonConverter instance;
  11. /// <summary>
  12. /// Singleton
  13. /// </summary>
  14. public static ColorJsonConverter Instance {
  15. get {
  16. if (instance == null) {
  17. instance = new ColorJsonConverter ();
  18. }
  19. return instance;
  20. }
  21. }
  22. public override Color Read (ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  23. {
  24. // Check if the value is a string
  25. if (reader.TokenType == JsonTokenType.String) {
  26. // Get the color string
  27. var colorString = reader.GetString ();
  28. // Check if the color string is a color name
  29. if (Enum.TryParse (colorString, ignoreCase: true, out Color color)) {
  30. // Return the parsed color
  31. return color;
  32. } else {
  33. // Parse the color string as an RGB value
  34. var match = Regex.Match (colorString, @"rgb\((\d+),(\d+),(\d+)\)");
  35. if (match.Success) {
  36. var r = int.Parse (match.Groups [1].Value);
  37. var g = int.Parse (match.Groups [2].Value);
  38. var b = int.Parse (match.Groups [3].Value);
  39. return TrueColor.ToConsoleColor(new TrueColor (r, g, b));
  40. } else {
  41. throw new JsonException ($"Invalid Color: '{colorString}'");
  42. }
  43. }
  44. } else {
  45. throw new JsonException ($"Unexpected token when parsing Color: {reader.TokenType}");
  46. }
  47. }
  48. public override void Write (Utf8JsonWriter writer, Color value, JsonSerializerOptions options)
  49. {
  50. // Try to get the human readable color name from the map
  51. var name = Enum.GetName (typeof (Color), value);
  52. if (name != null) {
  53. // Write the color name to the JSON
  54. writer.WriteStringValue (name);
  55. } else {
  56. //// If the color is not in the map, look up its RGB values in the consoleDriver.colors array
  57. //ConsoleColor consoleColor = (ConsoleDriver [(int)value]);
  58. //int r = consoleColor.R;
  59. //int g = consoleColor.G;
  60. //int b = consoleColor.B;
  61. //// Write the RGB values as a string to the JSON
  62. //writer.WriteStringValue ($"rgb({r},{g},{b})");
  63. throw new JsonException ($"Unknown Color value. Cannot serialize to JSON: {value}");
  64. }
  65. }
  66. }
  67. }