SettingsScope.cs 5.6 KB

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