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.

109 lines
3.1 KiB

  1. using IPA.Logging;
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace IPA.Config.ConfigProviders
  11. {
  12. internal class JsonConfigProvider : IConfigProvider
  13. {
  14. private JObject jsonObj;
  15. // TODO: create a wrapper that allows empty object creation
  16. public dynamic Dynamic => jsonObj;
  17. public bool HasChanged { get; private set; } = false;
  18. public DateTime LastModified => File.GetLastWriteTime(Filename + ".json");
  19. private string _filename = null;
  20. public string Filename
  21. {
  22. get => _filename;
  23. set
  24. {
  25. if (_filename != null)
  26. throw new InvalidOperationException("Can only assign to Filename once");
  27. _filename = value;
  28. }
  29. }
  30. public void Load()
  31. {
  32. Logger.config.Debug($"Loading file {Filename}.json");
  33. var finfo = new FileInfo(Filename + ".json");
  34. if (finfo.Exists)
  35. {
  36. string json = finfo.OpenText().ReadToEnd();
  37. try
  38. {
  39. jsonObj = JObject.Parse(json);
  40. }
  41. catch (Exception e)
  42. {
  43. Logger.config.Error($"Error parsing JSON in file {Filename}.json; resetting to empty JSON");
  44. Logger.config.Error(e);
  45. jsonObj = new JObject();
  46. File.WriteAllText(finfo.FullName, JsonConvert.SerializeObject(jsonObj, Formatting.Indented));
  47. }
  48. }
  49. else
  50. {
  51. jsonObj = new JObject();
  52. }
  53. SetupListeners();
  54. }
  55. private void SetupListeners()
  56. {
  57. jsonObj.PropertyChanged += JsonObj_PropertyChanged;
  58. jsonObj.ListChanged += JsonObj_ListChanged;
  59. jsonObj.CollectionChanged += JsonObj_CollectionChanged;
  60. }
  61. private void JsonObj_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
  62. {
  63. HasChanged = true;
  64. }
  65. private void JsonObj_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e)
  66. {
  67. HasChanged = true;
  68. }
  69. private void JsonObj_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
  70. {
  71. HasChanged = true;
  72. }
  73. public T Parse<T>()
  74. {
  75. return jsonObj.ToObject<T>();
  76. }
  77. public void Save()
  78. {
  79. Logger.config.Debug($"Saving file {Filename}.json");
  80. var finfo = new FileInfo(Filename + ".json");
  81. File.WriteAllText(finfo.FullName, JsonConvert.SerializeObject(jsonObj, Formatting.Indented));
  82. HasChanged = false;
  83. }
  84. public void Store<T>(T obj)
  85. {
  86. jsonObj = JObject.FromObject(obj);
  87. SetupListeners();
  88. HasChanged = true;
  89. }
  90. }
  91. }