ColorJsonConverter.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. public 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. /// <inheritdoc/>
  23. public override Color Read (ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  24. {
  25. // Check if the value is a string
  26. if (reader.TokenType == JsonTokenType.String) {
  27. // Get the color string
  28. var colorString = reader.GetString ();
  29. // Check if the color string is a color name
  30. if (Enum.TryParse (colorString, ignoreCase: true, out Color color)) {
  31. // Return the parsed color
  32. return color;
  33. } else {
  34. // Parse the color string as an RGB value
  35. var match = Regex.Match (colorString, @"rgb\((\d+),(\d+),(\d+)\)");
  36. if (match.Success) {
  37. var r = int.Parse (match.Groups [1].Value);
  38. var g = int.Parse (match.Groups [2].Value);
  39. var b = int.Parse (match.Groups [3].Value);
  40. return new TrueColor (r, g, b).ToConsoleColor ();
  41. } else {
  42. throw new JsonException ($"Invalid Color: '{colorString}'");
  43. }
  44. }
  45. } else {
  46. throw new JsonException ($"Unexpected token when parsing Color: {reader.TokenType}");
  47. }
  48. }
  49. /// <inheritdoc/>
  50. public override void Write (Utf8JsonWriter writer, Color value, JsonSerializerOptions options)
  51. {
  52. // Try to get the human readable color name from the map
  53. var name = Enum.GetName (typeof (Color), value);
  54. if (name != null) {
  55. // Write the color name to the JSON
  56. writer.WriteStringValue (name);
  57. } else {
  58. //// If the color is not in the map, look up its RGB values in the consoleDriver.colors array
  59. //ConsoleColor consoleColor = (ConsoleDriver [(int)value]);
  60. //int r = consoleColor.R;
  61. //int g = consoleColor.G;
  62. //int b = consoleColor.B;
  63. //// Write the RGB values as a string to the JSON
  64. //writer.WriteStringValue ($"rgb({r},{g},{b})");
  65. throw new JsonException ($"Unknown Color value. Cannot serialize to JSON: {value}");
  66. }
  67. }
  68. }
  69. }