JsonMotionConfigControllerConverter.cs 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. namespace Ryujinx.Common.Configuration.Hid.Controller.Motion
  5. {
  6. class JsonMotionConfigControllerConverter : JsonConverter<MotionConfigController>
  7. {
  8. private static MotionInputBackendType GetMotionInputBackendType(ref Utf8JsonReader reader)
  9. {
  10. // Temporary reader to get the backend type
  11. Utf8JsonReader tempReader = reader;
  12. MotionInputBackendType result = MotionInputBackendType.Invalid;
  13. while (tempReader.Read())
  14. {
  15. // NOTE: We scan all properties ignoring the depth entirely on purpose.
  16. // 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.
  17. // As such, this code will try to parse very field named "motion_backend" to the correct enum.
  18. if (tempReader.TokenType == JsonTokenType.PropertyName)
  19. {
  20. string propertyName = tempReader.GetString();
  21. if (propertyName.Equals("motion_backend"))
  22. {
  23. tempReader.Read();
  24. if (tempReader.TokenType == JsonTokenType.String)
  25. {
  26. string backendTypeRaw = tempReader.GetString();
  27. if (!Enum.TryParse(backendTypeRaw, out result))
  28. {
  29. result = MotionInputBackendType.Invalid;
  30. }
  31. else
  32. {
  33. break;
  34. }
  35. }
  36. }
  37. }
  38. }
  39. return result;
  40. }
  41. public override MotionConfigController Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  42. {
  43. MotionInputBackendType motionBackendType = GetMotionInputBackendType(ref reader);
  44. return motionBackendType switch
  45. {
  46. MotionInputBackendType.GamepadDriver => (MotionConfigController)JsonSerializer.Deserialize(ref reader, typeof(StandardMotionConfigController), options),
  47. MotionInputBackendType.CemuHook => (MotionConfigController)JsonSerializer.Deserialize(ref reader, typeof(CemuHookMotionConfigController), options),
  48. _ => throw new InvalidOperationException($"Unknown backend type {motionBackendType}"),
  49. };
  50. }
  51. public override void Write(Utf8JsonWriter writer, MotionConfigController value, JsonSerializerOptions options)
  52. {
  53. switch (value.MotionBackend)
  54. {
  55. case MotionInputBackendType.GamepadDriver:
  56. JsonSerializer.Serialize(writer, value as StandardMotionConfigController, options);
  57. break;
  58. case MotionInputBackendType.CemuHook:
  59. JsonSerializer.Serialize(writer, value as CemuHookMotionConfigController, options);
  60. break;
  61. default:
  62. throw new ArgumentException($"Unknown motion backend type {value.MotionBackend}");
  63. }
  64. }
  65. }
  66. }