SettingsScope.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 Dictionary<ConfigLocations, string> Sources { get; } = 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. /// <param name="location">Location</param>
  37. [RequiresUnreferencedCode ("AOT")]
  38. [RequiresDynamicCode ("AOT")]
  39. public SettingsScope? Update (Stream stream, string source, ConfigLocations location)
  40. {
  41. // Update the existing settings with the new settings.
  42. try
  43. {
  44. Update ((SettingsScope)JsonSerializer.Deserialize (stream, typeof (SettingsScope), _serializerOptions)!);
  45. OnUpdated ();
  46. Debug.WriteLine ($"ConfigurationManager: Read configuration from \"{source}\"");
  47. if (!Sources.ContainsValue (source))
  48. {
  49. Sources.Add (location, source);
  50. }
  51. return this;
  52. }
  53. catch (JsonException e)
  54. {
  55. if (ThrowOnJsonErrors ?? false)
  56. {
  57. throw;
  58. }
  59. AddJsonError ($"Error deserializing {source}: {e.Message}");
  60. }
  61. return this;
  62. }
  63. /// <summary>Updates the <see cref="SettingsScope"/> with the settings in a JSON file.</summary>
  64. /// <param name="filePath">Path to the file.</param>
  65. /// <param name="location">The location</param>
  66. [RequiresUnreferencedCode ("AOT")]
  67. [RequiresDynamicCode ("AOT")]
  68. public SettingsScope? Update (string filePath, ConfigLocations location)
  69. {
  70. string realPath = filePath.Replace ("~", Environment.GetFolderPath (Environment.SpecialFolder.UserProfile));
  71. if (!File.Exists (realPath))
  72. {
  73. Debug.WriteLine ($"ConfigurationManager: Configuration file \"{realPath}\" does not exist.");
  74. if (!Sources.ContainsValue (filePath))
  75. {
  76. Sources.Add (location, filePath);
  77. }
  78. return this;
  79. }
  80. int retryCount = 0;
  81. // Sometimes when the config file is written by an external agent, the change notification comes
  82. // before the file is closed. This works around that.
  83. while (retryCount < 2)
  84. {
  85. try
  86. {
  87. FileStream? stream = File.OpenRead (realPath);
  88. SettingsScope? s = Update (stream, filePath, location);
  89. stream.Close ();
  90. stream.Dispose ();
  91. return s;
  92. }
  93. catch (IOException ioe)
  94. {
  95. Debug.WriteLine ($"Couldn't open {filePath}. Retrying...: {ioe}");
  96. Task.Delay (100);
  97. retryCount++;
  98. }
  99. }
  100. return null;
  101. }
  102. /// <summary>Updates the <see cref="SettingsScope"/> with the settings in a JSON string.</summary>
  103. /// <param name="json">Json document to update the settings with.</param>
  104. /// <param name="source">The source (filename/resource name) the Json document was read from.</param>
  105. /// <param name="location">The location.</param>
  106. [RequiresUnreferencedCode ("AOT")]
  107. [RequiresDynamicCode ("AOT")]
  108. public SettingsScope? Update (string? json, string source, ConfigLocations location)
  109. {
  110. if (string.IsNullOrEmpty (json))
  111. {
  112. return null;
  113. }
  114. var stream = new MemoryStream ();
  115. var writer = new StreamWriter (stream);
  116. writer.Write (json);
  117. writer.Flush ();
  118. stream.Position = 0;
  119. return Update (stream, source, location);
  120. }
  121. /// <summary>Updates the <see cref="SettingsScope"/> with the settings from a Json resource.</summary>
  122. /// <param name="assembly"></param>
  123. /// <param name="resourceName"></param>
  124. /// <param name="location"></param>
  125. [RequiresUnreferencedCode ("AOT")]
  126. [RequiresDynamicCode ("AOT")]
  127. public SettingsScope? UpdateFromResource (Assembly assembly, string resourceName, ConfigLocations location)
  128. {
  129. if (string.IsNullOrEmpty (resourceName))
  130. {
  131. Debug.WriteLine (
  132. $"ConfigurationManager: Resource \"{resourceName}\" does not exist in \"{assembly.GetName ().Name}\"."
  133. );
  134. return this;
  135. }
  136. using Stream? stream = assembly.GetManifestResourceStream (resourceName);
  137. if (stream is null)
  138. {
  139. return null;
  140. }
  141. return Update (stream, $"resource://[{assembly.GetName ().Name}]/{resourceName}", location);
  142. }
  143. }