SettingsScope.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. #nullable enable
  2. using System.Diagnostics;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Reflection;
  5. using System.Text.Json;
  6. using System.Text.Json.Serialization;
  7. namespace Terminal.Gui;
  8. /// <summary>
  9. /// The root object of Terminal.Gui configuration settings / JSON schema. Contains only properties attributed with
  10. /// <see cref="SettingsScope"/>.
  11. /// </summary>
  12. /// <example>
  13. /// <code>
  14. /// {
  15. /// "$schema" : "https://gui-cs.github.io/Terminal.GuiV2Docs/schemas/tui-config-schema.json",
  16. /// "Application.UseSystemConsole" : true,
  17. /// "Theme" : "Default",
  18. /// "Themes": {
  19. /// },
  20. /// },
  21. /// </code>
  22. /// </example>
  23. /// <remarks></remarks>
  24. [JsonConverter (typeof (ScopeJsonConverter<SettingsScope>))]
  25. public class SettingsScope : Scope<SettingsScope>
  26. {
  27. /// <summary>The list of paths to the configuration files.</summary>
  28. public List<string> Sources = new ();
  29. /// <summary>Points to our JSON schema.</summary>
  30. [JsonInclude]
  31. [JsonPropertyName ("$schema")]
  32. public string Schema { get; set; } = "https://gui-cs.github.io/Terminal.GuiV2Docs/schemas/tui-config-schema.json";
  33. /// <summary>Updates the <see cref="SettingsScope"/> with the settings in a JSON string.</summary>
  34. /// <param name="stream">Json document to update the settings with.</param>
  35. /// <param name="source">The source (filename/resource name) the Json document was read from.</param>
  36. [RequiresUnreferencedCode ("AOT")]
  37. [RequiresDynamicCode ("AOT")]
  38. public SettingsScope? Update (Stream stream, string source)
  39. {
  40. // Update the existing settings with the new settings.
  41. try
  42. {
  43. Update ((SettingsScope)JsonSerializer.Deserialize (stream, typeof (SettingsScope), _serializerOptions)!);
  44. OnUpdated ();
  45. Debug.WriteLine ($"ConfigurationManager: Read configuration from \"{source}\"");
  46. if (!Sources.Contains (source))
  47. {
  48. Sources.Add (source);
  49. }
  50. return this;
  51. }
  52. catch (JsonException e)
  53. {
  54. if (ThrowOnJsonErrors ?? false)
  55. {
  56. throw;
  57. }
  58. AddJsonError ($"Error deserializing {source}: {e.Message}");
  59. }
  60. return this;
  61. }
  62. /// <summary>Updates the <see cref="SettingsScope"/> with the settings in a JSON file.</summary>
  63. /// <param name="filePath"></param>
  64. [RequiresUnreferencedCode ("AOT")]
  65. [RequiresDynamicCode ("AOT")]
  66. public SettingsScope? Update (string filePath)
  67. {
  68. string realPath = filePath.Replace ("~", Environment.GetFolderPath (Environment.SpecialFolder.UserProfile));
  69. if (!File.Exists (realPath))
  70. {
  71. Debug.WriteLine ($"ConfigurationManager: Configuration file \"{realPath}\" does not exist.");
  72. if (!Sources.Contains (filePath))
  73. {
  74. Sources.Add (filePath);
  75. }
  76. return this;
  77. }
  78. int retryCount = 0;
  79. // Sometimes when the config file is written by an external agent, the change notification comes
  80. // before the file is closed. This works around that.
  81. while (retryCount < 2)
  82. {
  83. try
  84. {
  85. FileStream? stream = File.OpenRead (realPath);
  86. SettingsScope? s = Update (stream, filePath);
  87. stream.Close ();
  88. stream.Dispose ();
  89. return s;
  90. }
  91. catch (IOException ioe)
  92. {
  93. Debug.WriteLine($"Couldn't open {filePath}. Retrying...: {ioe}");
  94. Task.Delay (100);
  95. retryCount++;
  96. }
  97. }
  98. return null;
  99. }
  100. /// <summary>Updates the <see cref="SettingsScope"/> with the settings in a JSON string.</summary>
  101. /// <param name="json">Json document to update the settings with.</param>
  102. /// <param name="source">The source (filename/resource name) the Json document was read from.</param>
  103. [RequiresUnreferencedCode ("AOT")]
  104. [RequiresDynamicCode ("AOT")]
  105. public SettingsScope? Update (string json, string source)
  106. {
  107. var stream = new MemoryStream ();
  108. var writer = new StreamWriter (stream);
  109. writer.Write (json);
  110. writer.Flush ();
  111. stream.Position = 0;
  112. return Update (stream, source);
  113. }
  114. /// <summary>Updates the <see cref="SettingsScope"/> with the settings from a Json resource.</summary>
  115. /// <param name="assembly"></param>
  116. /// <param name="resourceName"></param>
  117. [RequiresUnreferencedCode ("AOT")]
  118. [RequiresDynamicCode ("AOT")]
  119. public SettingsScope? UpdateFromResource (Assembly assembly, string resourceName)
  120. {
  121. if (resourceName is null || string.IsNullOrEmpty (resourceName))
  122. {
  123. Debug.WriteLine (
  124. $"ConfigurationManager: Resource \"{resourceName}\" does not exist in \"{assembly.GetName ().Name}\"."
  125. );
  126. return this;
  127. }
  128. // BUG: Not trim-compatible
  129. // Not a bug, per se, but it's easily fixable by just loading the file.
  130. // Defaults can just be field initializers for involved types.
  131. using Stream? stream = assembly.GetManifestResourceStream (resourceName)!;
  132. if (stream is null)
  133. {
  134. Debug.WriteLine (
  135. $"ConfigurationManager: Failed to read resource \"{resourceName}\" from \"{assembly.GetName ().Name}\"."
  136. );
  137. return this;
  138. }
  139. return Update (stream, $"resource://[{assembly.GetName ().Name}]/{resourceName}");
  140. }
  141. }