You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
3.2 KiB

  1. #nullable enable
  2. using IPA.Logging;
  3. using System;
  4. using System.IO;
  5. using System.Text.Json;
  6. using System.Text.Json.Nodes;
  7. using System.Text.Json.Serialization;
  8. namespace IPA.Loader.Features
  9. {
  10. internal class DefineFeature : Feature
  11. {
  12. public static bool NewFeature = true;
  13. private class DataModel
  14. {
  15. [JsonPropertyName("type")]
  16. [JsonRequired]
  17. public string TypeName { get; init; } = "";
  18. [JsonPropertyName("name")]
  19. // TODO: Originally DisallowNull
  20. public string? ActualName { get; init; }
  21. public string Name => ActualName ?? TypeName;
  22. }
  23. private DataModel data = null!;
  24. protected override bool Initialize(PluginMetadata meta, JsonObject featureData)
  25. {
  26. Logger.Features.Debug("Executing DefineFeature Init");
  27. try
  28. {
  29. data = featureData.Deserialize<DataModel>() ?? throw new InvalidOperationException("Feature data is null");
  30. }
  31. catch (Exception e)
  32. {
  33. InvalidMessage = $"Invalid data: {e}";
  34. return false;
  35. }
  36. InvalidMessage = $"Feature {data.Name} already exists";
  37. return PreregisterFeature(meta, data.Name);
  38. }
  39. public override void BeforeInit(PluginMetadata meta)
  40. {
  41. Logger.Features.Debug("Executing DefineFeature AfterInit");
  42. Type type;
  43. try
  44. {
  45. type = meta.Assembly.GetType(data.TypeName);
  46. }
  47. catch (ArgumentException)
  48. {
  49. Logger.Features.Error($"Invalid type name {data.TypeName}");
  50. return;
  51. }
  52. catch (Exception e) when (e is FileNotFoundException or FileLoadException or BadImageFormatException)
  53. {
  54. var filename = "";
  55. switch (e)
  56. {
  57. case FileNotFoundException fn:
  58. filename = fn.FileName;
  59. break;
  60. case FileLoadException fl:
  61. filename = fl.FileName;
  62. break;
  63. case BadImageFormatException bi:
  64. filename = bi.FileName;
  65. break;
  66. }
  67. Logger.Features.Error($"Could not find {filename} while loading type");
  68. return;
  69. }
  70. if (type == null)
  71. {
  72. Logger.Features.Error($"Invalid type name {data.TypeName}");
  73. return;
  74. }
  75. try
  76. {
  77. if (RegisterFeature(meta, data.Name, type))
  78. {
  79. NewFeature = true;
  80. return;
  81. }
  82. Logger.Features.Error($"Feature with name {data.Name} already exists");
  83. return;
  84. }
  85. catch (ArgumentException)
  86. {
  87. Logger.Features.Error($"{type.FullName} not a subclass of {nameof(Feature)}");
  88. return;
  89. }
  90. }
  91. }
  92. }