JsonInputConfigConverter.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using Ryujinx.Common.Configuration.Hid.Controller;
  2. using Ryujinx.Common.Configuration.Hid.Keyboard;
  3. using System;
  4. using System.Text.Json;
  5. using System.Text.Json.Serialization;
  6. namespace Ryujinx.Common.Configuration.Hid
  7. {
  8. class JsonInputConfigConverter : JsonConverter<InputConfig>
  9. {
  10. private static InputBackendType GetInputBackendType(ref Utf8JsonReader reader)
  11. {
  12. // Temporary reader to get the backend type
  13. Utf8JsonReader tempReader = reader;
  14. InputBackendType result = InputBackendType.Invalid;
  15. while (tempReader.Read())
  16. {
  17. // NOTE: We scan all properties ignoring the depth entirely on purpose.
  18. // The reason behind this is that we cannot track in a reliable way the depth of the object because Utf8JsonReader never emit the first TokenType == StartObject if the json start with an object.
  19. // As such, this code will try to parse very field named "backend" to the correct enum.
  20. if (tempReader.TokenType == JsonTokenType.PropertyName)
  21. {
  22. string propertyName = tempReader.GetString();
  23. if (propertyName.Equals("backend"))
  24. {
  25. tempReader.Read();
  26. if (tempReader.TokenType == JsonTokenType.String)
  27. {
  28. string backendTypeRaw = tempReader.GetString();
  29. if (!Enum.TryParse(backendTypeRaw, out result))
  30. {
  31. result = InputBackendType.Invalid;
  32. }
  33. else
  34. {
  35. break;
  36. }
  37. }
  38. }
  39. }
  40. }
  41. return result;
  42. }
  43. public override InputConfig Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  44. {
  45. InputBackendType backendType = GetInputBackendType(ref reader);
  46. return backendType switch
  47. {
  48. InputBackendType.WindowKeyboard => (InputConfig)JsonSerializer.Deserialize(ref reader, typeof(StandardKeyboardInputConfig), options),
  49. InputBackendType.GamepadSDL2 => (InputConfig)JsonSerializer.Deserialize(ref reader, typeof(StandardControllerInputConfig), options),
  50. _ => throw new InvalidOperationException($"Unknown backend type {backendType}"),
  51. };
  52. }
  53. public override void Write(Utf8JsonWriter writer, InputConfig value, JsonSerializerOptions options)
  54. {
  55. switch (value.Backend)
  56. {
  57. case InputBackendType.WindowKeyboard:
  58. JsonSerializer.Serialize(writer, value as StandardKeyboardInputConfig, options);
  59. break;
  60. case InputBackendType.GamepadSDL2:
  61. JsonSerializer.Serialize(writer, value as StandardControllerInputConfig, options);
  62. break;
  63. default:
  64. throw new ArgumentException($"Unknown backend type {value.Backend}");
  65. }
  66. }
  67. }
  68. }