ConfigurationManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. global using CM = Terminal.Gui.ConfigurationManager;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Text;
  10. using System.Text.Json;
  11. using System.Text.Json.Serialization;
  12. #nullable enable
  13. namespace Terminal.Gui;
  14. /// <summary>
  15. /// Provides settings and configuration management for Terminal.Gui applications.
  16. /// <para>
  17. /// Users can set Terminal.Gui settings on a global or per-application basis by providing JSON formatted configuration files.
  18. /// The configuration files can be placed in at <c>.tui</c> folder in the user's home directory (e.g. <c>C:/Users/username/.tui</c>,
  19. /// or <c>/usr/username/.tui</c>),
  20. /// the folder where the Terminal.Gui application was launched from (e.g. <c>./.tui</c>), or as a resource
  21. /// within the Terminal.Gui application's main assembly.
  22. /// </para>
  23. /// <para>
  24. /// Settings are defined in JSON format, according to this schema:
  25. /// https://gui-cs.github.io/Terminal.Gui/schemas/tui-config-schema.json
  26. /// </para>
  27. /// <para>
  28. /// Settings that will apply to all applications (global settings) reside in files named <c>config.json</c>. Settings
  29. /// that will apply to a specific Terminal.Gui application reside in files named <c>appname.config.json</c>,
  30. /// where <c>appname</c> is the assembly name of the application (e.g. <c>UICatalog.config.json</c>).
  31. /// </para>
  32. /// Settings are applied using the following precedence (higher precedence settings
  33. /// overwrite lower precedence settings):
  34. /// <para>
  35. /// 1. Application configuration found in the users's home directory (<c>~/.tui/appname.config.json</c>) -- Highest precedence
  36. /// </para>
  37. /// <para>
  38. /// 2. Application configuration found in the directory the app was launched from (<c>./.tui/appname.config.json</c>).
  39. /// </para>
  40. /// <para>
  41. /// 3. Application configuration found in the applications's resources (<c>Resources/config.json</c>).
  42. /// </para>
  43. /// <para>
  44. /// 4. Global configuration found in the user's home directory (<c>~/.tui/config.json</c>).
  45. /// </para>
  46. /// <para>
  47. /// 5. Global configuration found in the directory the app was launched from (<c>./.tui/config.json</c>).
  48. /// </para>
  49. /// <para>
  50. /// 6. Global configuration in <c>Terminal.Gui.dll</c>'s resources (<c>Terminal.Gui.Resources.config.json</c>) -- Lowest Precidence.
  51. /// </para>
  52. /// </summary>
  53. public static partial class ConfigurationManager {
  54. private static readonly string _configFilename = "config.json";
  55. private static readonly JsonSerializerOptions _serializerOptions = new JsonSerializerOptions {
  56. ReadCommentHandling = JsonCommentHandling.Skip,
  57. PropertyNameCaseInsensitive = true,
  58. DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
  59. WriteIndented = true,
  60. Converters = {
  61. // We override the standard Rune converter to support specifying Glyphs in
  62. // a flexible way
  63. new RuneJsonConverter(),
  64. },
  65. };
  66. /// <summary>
  67. /// An attribute that can be applied to a property to indicate that it should included in the configuration file.
  68. /// </summary>
  69. /// <example>
  70. /// [SerializableConfigurationProperty(Scope = typeof(Configuration.ThemeManager.ThemeScope)), JsonConverter (typeof (JsonStringEnumConverter))]
  71. /// public static LineStyle DefaultBorderStyle {
  72. /// ...
  73. /// </example>
  74. [AttributeUsage (AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
  75. public class SerializableConfigurationProperty : System.Attribute {
  76. /// <summary>
  77. /// Specifies the scope of the property.
  78. /// </summary>
  79. public Type? Scope { get; set; }
  80. /// <summary>
  81. /// If <see langword="true"/>, the property will be serialized to the configuration file using only the property name
  82. /// as the key. If <see langword="false"/>, the property will be serialized to the configuration file using the
  83. /// property name pre-pended with the classname (e.g. <c>Application.UseSystemConsole</c>).
  84. /// </summary>
  85. public bool OmitClassName { get; set; }
  86. }
  87. /// <summary>
  88. /// Holds a property's value and the <see cref="PropertyInfo"/> that allows <see cref="ConfigurationManager"/>
  89. /// to get and set the property's value.
  90. /// </summary>
  91. /// <remarks>
  92. /// Configuration properties must be <see langword="public"/> and <see langword="static"/>
  93. /// and have the <see cref="SerializableConfigurationProperty"/>
  94. /// attribute. If the type of the property requires specialized JSON serialization,
  95. /// a <see cref="JsonConverter"/> must be provided using
  96. /// the <see cref="JsonConverterAttribute"/> attribute.
  97. /// </remarks>
  98. public class ConfigProperty {
  99. private object? propertyValue;
  100. /// <summary>
  101. /// Describes the property.
  102. /// </summary>
  103. public PropertyInfo? PropertyInfo { get; set; }
  104. /// <summary>
  105. /// Helper to get either the Json property named (specified by [JsonPropertyName(name)]
  106. /// or the actual property name.
  107. /// </summary>
  108. /// <param name="pi"></param>
  109. /// <returns></returns>
  110. public static string GetJsonPropertyName (PropertyInfo pi)
  111. {
  112. var jpna = pi.GetCustomAttribute (typeof (JsonPropertyNameAttribute)) as JsonPropertyNameAttribute;
  113. return jpna?.Name ?? pi.Name;
  114. }
  115. /// <summary>
  116. /// Holds the property's value as it was either read from the class's implementation or from a config file.
  117. /// If the property has not been set (e.g. because no configuration file specified a value),
  118. /// this will be <see langword="null"/>.
  119. /// </summary>
  120. /// <remarks>
  121. /// On <see langword="set"/>, performs a sparse-copy of the new value to the existing value (only copies elements of
  122. /// the object that are non-null).
  123. /// </remarks>
  124. public object? PropertyValue {
  125. get => propertyValue;
  126. set {
  127. propertyValue = value;
  128. }
  129. }
  130. internal object? UpdateValueFrom (object source)
  131. {
  132. if (source == null) {
  133. return PropertyValue;
  134. }
  135. var ut = Nullable.GetUnderlyingType (PropertyInfo!.PropertyType);
  136. if (source.GetType () != PropertyInfo!.PropertyType && (ut != null && source.GetType () != ut)) {
  137. throw new ArgumentException ($"The source object ({PropertyInfo!.DeclaringType}.{PropertyInfo!.Name}) is not of type {PropertyInfo!.PropertyType}.");
  138. }
  139. if (PropertyValue != null && source != null) {
  140. PropertyValue = DeepMemberwiseCopy (source, PropertyValue);
  141. } else {
  142. PropertyValue = source;
  143. }
  144. return PropertyValue;
  145. }
  146. /// <summary>
  147. /// Retrieves (using reflection) the value of the static property described in <see cref="PropertyInfo"/>
  148. /// into <see cref="PropertyValue"/>.
  149. /// </summary>
  150. /// <returns></returns>
  151. public object? RetrieveValue ()
  152. {
  153. return PropertyValue = PropertyInfo!.GetValue (null);
  154. }
  155. /// <summary>
  156. /// Applies the <see cref="PropertyValue"/> to the property described by <see cref="PropertyInfo"/>.
  157. /// </summary>
  158. /// <returns></returns>
  159. public bool Apply ()
  160. {
  161. if (PropertyValue != null) {
  162. PropertyInfo?.SetValue (null, DeepMemberwiseCopy (PropertyValue, PropertyInfo?.GetValue (null)));
  163. }
  164. return PropertyValue != null;
  165. }
  166. }
  167. /// <summary>
  168. /// A dictionary of all properties in the Terminal.Gui project that are decorated with the <see cref="SerializableConfigurationProperty"/> attribute.
  169. /// The keys are the property names pre-pended with the class that implements the property (e.g. <c>Application.UseSystemConsole</c>).
  170. /// The values are instances of <see cref="ConfigProperty"/> which hold the property's value and the
  171. /// <see cref="PropertyInfo"/> that allows <see cref="ConfigurationManager"/> to get and set the property's value.
  172. /// </summary>
  173. /// <remarks>
  174. /// Is <see langword="null"/> until <see cref="Initialize"/> is called.
  175. /// </remarks>
  176. private static Dictionary<string, ConfigProperty>? _allConfigProperties;
  177. /// <summary>
  178. /// The backing property for <see cref="Settings"/>.
  179. /// </summary>
  180. /// <remarks>
  181. /// Is <see langword="null"/> until <see cref="Reset"/> is called. Gets set to a new instance by
  182. /// deserialization (see <see cref="Load"/>).
  183. /// </remarks>
  184. private static SettingsScope? _settings;
  185. /// <summary>
  186. /// The root object of Terminal.Gui configuration settings / JSON schema. Contains only properties with the <see cref="SettingsScope"/>
  187. /// attribute value.
  188. /// </summary>
  189. public static SettingsScope? Settings {
  190. get {
  191. if (_settings == null) {
  192. throw new InvalidOperationException ("ConfigurationManager has not been initialized. Call ConfigurationManager.Reset() before accessing the Settings property.");
  193. }
  194. return _settings;
  195. }
  196. set {
  197. _settings = value!;
  198. }
  199. }
  200. /// <summary>
  201. /// The root object of Terminal.Gui themes manager. Contains only properties with the <see cref="ThemeScope"/>
  202. /// attribute value.
  203. /// </summary>
  204. public static ThemeManager? Themes => ThemeManager.Instance;
  205. /// <summary>
  206. /// Application-specific configuration settings scope.
  207. /// </summary>
  208. [SerializableConfigurationProperty (Scope = typeof (SettingsScope), OmitClassName = true), JsonPropertyName ("AppSettings")]
  209. public static AppScope? AppSettings { get; set; }
  210. /// <summary>
  211. /// The set of glyphs used to draw checkboxes, lines, borders, etc...See also <seealso cref="Terminal.Gui.GlyphDefinitions"/>.
  212. /// </summary>
  213. [SerializableConfigurationProperty (Scope = typeof (SettingsScope), OmitClassName = true),
  214. JsonPropertyName ("Glyphs")]
  215. public static GlyphDefinitions Glyphs { get; set; } = new GlyphDefinitions ();
  216. /// <summary>
  217. /// Initializes the internal state of ConfigurationManager. Nominally called once as part of application
  218. /// startup to initialize global state. Also called from some Unit Tests to ensure correctness (e.g. Reset()).
  219. /// </summary>
  220. internal static void Initialize ()
  221. {
  222. _allConfigProperties = new Dictionary<string, ConfigProperty> ();
  223. _settings = null;
  224. Dictionary<string, Type> classesWithConfigProps = new Dictionary<string, Type> (StringComparer.InvariantCultureIgnoreCase);
  225. // Get Terminal.Gui.dll classes
  226. var types = from assembly in AppDomain.CurrentDomain.GetAssemblies ()
  227. from type in assembly.GetTypes ()
  228. where type.GetProperties ().Any (prop => prop.GetCustomAttribute (typeof (SerializableConfigurationProperty)) != null)
  229. select type;
  230. foreach (var classWithConfig in types) {
  231. classesWithConfigProps.Add (classWithConfig.Name, classWithConfig);
  232. }
  233. Debug.WriteLine ($"ConfigManager.getConfigProperties found {classesWithConfigProps.Count} classes:");
  234. classesWithConfigProps.ToList ().ForEach (x => Debug.WriteLine ($" Class: {x.Key}"));
  235. foreach (var p in from c in classesWithConfigProps
  236. let props = c.Value.GetProperties (BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public).Where (prop =>
  237. prop.GetCustomAttribute (typeof (SerializableConfigurationProperty)) is SerializableConfigurationProperty)
  238. let enumerable = props
  239. from p in enumerable
  240. select p) {
  241. if (p.GetCustomAttribute (typeof (SerializableConfigurationProperty)) is SerializableConfigurationProperty scp) {
  242. if (p.GetGetMethod (true)!.IsStatic) {
  243. // If the class name is omitted, JsonPropertyName is allowed.
  244. _allConfigProperties!.Add (scp.OmitClassName ? ConfigProperty.GetJsonPropertyName (p) : $"{p.DeclaringType?.Name}.{p.Name}", new ConfigProperty {
  245. PropertyInfo = p,
  246. PropertyValue = null
  247. });
  248. } else {
  249. throw new Exception ($"Property {p.Name} in class {p.DeclaringType?.Name} is not static. All SerializableConfigurationProperty properties must be static.");
  250. }
  251. }
  252. }
  253. _allConfigProperties = _allConfigProperties!.OrderBy (x => x.Key).ToDictionary (x => x.Key, x => x.Value, StringComparer.InvariantCultureIgnoreCase);
  254. Debug.WriteLine ($"ConfigManager.Initialize found {_allConfigProperties.Count} properties:");
  255. //_allConfigProperties.ToList ().ForEach (x => Debug.WriteLine ($" Property: {x.Key}"));
  256. AppSettings = new AppScope ();
  257. }
  258. /// <summary>
  259. /// Creates a JSON document with the configuration specified.
  260. /// </summary>
  261. /// <returns></returns>
  262. internal static string ToJson ()
  263. {
  264. Debug.WriteLine ($"ConfigurationManager.ToJson()");
  265. return JsonSerializer.Serialize<SettingsScope> (Settings!, _serializerOptions);
  266. }
  267. internal static Stream ToStream ()
  268. {
  269. var json = JsonSerializer.Serialize<SettingsScope> (Settings!, _serializerOptions);
  270. // turn it into a stream
  271. var stream = new MemoryStream ();
  272. var writer = new StreamWriter (stream);
  273. writer.Write (json);
  274. writer.Flush ();
  275. stream.Position = 0;
  276. return stream;
  277. }
  278. /// <summary>
  279. /// Gets or sets whether the <see cref="ConfigurationManager"/> should throw an exception if it encounters
  280. /// an error on deserialization. If <see langword="false"/> (the default), the error is logged and printed to the
  281. /// console when <see cref="Application.Shutdown"/> is called.
  282. /// </summary>
  283. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  284. public static bool? ThrowOnJsonErrors { get; set; } = false;
  285. internal static StringBuilder jsonErrors = new StringBuilder ();
  286. private static void AddJsonError (string error)
  287. {
  288. Debug.WriteLine ($"ConfigurationManager: {error}");
  289. jsonErrors.AppendLine (error);
  290. }
  291. /// <summary>
  292. /// Prints any Json deserialization errors that occurred during deserialization to the console.
  293. /// </summary>
  294. public static void PrintJsonErrors ()
  295. {
  296. if (jsonErrors.Length > 0) {
  297. Console.WriteLine ($"Terminal.Gui ConfigurationManager encountered the following errors while deserializing configuration files:");
  298. Console.WriteLine (jsonErrors.ToString ());
  299. }
  300. }
  301. private static void ClearJsonErrors ()
  302. {
  303. jsonErrors.Clear ();
  304. }
  305. /// <summary>
  306. /// Called when the configuration has been updated from a configuration file. Invokes the <see cref="Updated"/>
  307. /// event.
  308. /// </summary>
  309. public static void OnUpdated ()
  310. {
  311. Debug.WriteLine ($"ConfigurationManager.OnApplied()");
  312. Updated?.Invoke (null, new ConfigurationManagerEventArgs ());
  313. }
  314. /// <summary>
  315. /// Event fired when the configuration has been updated from a configuration source.
  316. /// application.
  317. /// </summary>
  318. public static event EventHandler<ConfigurationManagerEventArgs>? Updated;
  319. /// <summary>
  320. /// Resets the state of <see cref="ConfigurationManager"/>. Should be called whenever a new app session
  321. /// (e.g. in <see cref="Application.Init(ConsoleDriver, IMainLoopDriver)"/> starts. Called by <see cref="Load"/>
  322. /// if the <c>reset</c> parameter is <see langword="true"/>.
  323. /// </summary>
  324. /// <remarks>
  325. ///
  326. /// </remarks>
  327. public static void Reset ()
  328. {
  329. Debug.WriteLine ($"ConfigurationManager.Reset()");
  330. if (_allConfigProperties == null) {
  331. ConfigurationManager.Initialize ();
  332. }
  333. ClearJsonErrors ();
  334. Settings = new SettingsScope ();
  335. ThemeManager.Reset ();
  336. AppSettings = new AppScope ();
  337. // To enable some unit tests, we only load from resources if the flag is set
  338. if (Locations.HasFlag (ConfigLocations.DefaultOnly)) {
  339. Settings.UpdateFromResource (typeof (ConfigurationManager).Assembly, $"Terminal.Gui.Resources.{_configFilename}");
  340. }
  341. Apply ();
  342. ThemeManager.Themes? [ThemeManager.SelectedTheme]?.Apply ();
  343. AppSettings?.Apply ();
  344. }
  345. /// <summary>
  346. /// Retrieves the hard coded default settings from the Terminal.Gui library implementation. Used in development of
  347. /// the library to generate the default configuration file. Before calling Application.Init, make sure
  348. /// <see cref="Locations"/> is set to <see cref="ConfigLocations.None"/>.
  349. /// </summary>
  350. /// <remarks>
  351. /// <para>
  352. /// This method is only really useful when using ConfigurationManagerTests
  353. /// to generate the JSON doc that is embedded into Terminal.Gui (during development).
  354. /// </para>
  355. /// <para>
  356. /// WARNING: The <c>Terminal.Gui.Resources.config.json</c> resource has setting definitions (Themes)
  357. /// that are NOT generated by this function. If you use this function to regenerate <c>Terminal.Gui.Resources.config.json</c>,
  358. /// make sure you copy the Theme definitions from the existing <c>Terminal.Gui.Resources.config.json</c> file.
  359. /// </para>
  360. /// </remarks>
  361. internal static void GetHardCodedDefaults ()
  362. {
  363. if (_allConfigProperties == null) {
  364. throw new InvalidOperationException ("Initialize must be called first.");
  365. }
  366. Settings = new SettingsScope ();
  367. ThemeManager.GetHardCodedDefaults ();
  368. AppSettings?.RetrieveValues ();
  369. foreach (var p in Settings!.Where (cp => cp.Value.PropertyInfo != null)) {
  370. Settings! [p.Key].PropertyValue = p.Value.PropertyInfo?.GetValue (null);
  371. }
  372. }
  373. /// <summary>
  374. /// Applies the configuration settings to the running <see cref="Application"/> instance.
  375. /// </summary>
  376. public static void Apply ()
  377. {
  378. bool settings = Settings?.Apply () ?? false;
  379. bool themes = !string.IsNullOrEmpty (ThemeManager.SelectedTheme) && (ThemeManager.Themes? [ThemeManager.SelectedTheme]?.Apply () ?? false);
  380. bool appsettings = AppSettings?.Apply () ?? false;
  381. if (settings || themes || appsettings) {
  382. OnApplied ();
  383. }
  384. }
  385. /// <summary>
  386. /// Called when an updated configuration has been applied to the
  387. /// application. Fires the <see cref="Applied"/> event.
  388. /// </summary>
  389. public static void OnApplied ()
  390. {
  391. Debug.WriteLine ($"ConfigurationManager.OnApplied()");
  392. Applied?.Invoke (null, new ConfigurationManagerEventArgs ());
  393. }
  394. /// <summary>
  395. /// Event fired when an updated configuration has been applied to the
  396. /// application.
  397. /// </summary>
  398. public static event EventHandler<ConfigurationManagerEventArgs>? Applied;
  399. /// <summary>
  400. /// Name of the running application. By default this property is set to the application's assembly name.
  401. /// </summary>
  402. public static string AppName { get; set; } = Assembly.GetEntryAssembly ()?.FullName?.Split (',') [0]?.Trim ()!;
  403. /// <summary>
  404. /// Describes the location of the configuration files. The constants can be
  405. /// combined (bitwise) to specify multiple locations.
  406. /// </summary>
  407. [Flags]
  408. public enum ConfigLocations {
  409. /// <summary>
  410. /// No configuration will be loaded.
  411. /// </summary>
  412. /// <remarks>
  413. /// Used for development and testing only. For Terminal,Gui to function properly, at least
  414. /// <see cref="DefaultOnly"/> should be set.
  415. /// </remarks>
  416. None = 0,
  417. /// <summary>
  418. /// Global configuration in <c>Terminal.Gui.dll</c>'s resources (<c>Terminal.Gui.Resources.config.json</c>) -- Lowest Precidence.
  419. /// </summary>
  420. DefaultOnly,
  421. /// <summary>
  422. /// This constant is a combination of all locations
  423. /// </summary>
  424. All = -1
  425. }
  426. /// <summary>
  427. /// Gets and sets the locations where <see cref="ConfigurationManager"/> will look for config files.
  428. /// The value is <see cref="ConfigLocations.All"/>.
  429. /// </summary>
  430. public static ConfigLocations Locations { get; set; } = ConfigLocations.All;
  431. /// <summary>
  432. /// Loads all settings found in the various configuration storage locations to
  433. /// the <see cref="ConfigurationManager"/>. Optionally,
  434. /// resets all settings attributed with <see cref="SerializableConfigurationProperty"/> to the defaults.
  435. /// </summary>
  436. /// <remarks>
  437. /// Use <see cref="Apply"/> to cause the loaded settings to be applied to the running application.
  438. /// </remarks>
  439. /// <param name="reset">If <see langword="true"/> the state of <see cref="ConfigurationManager"/> will
  440. /// be reset to the defaults.</param>
  441. public static void Load (bool reset = false)
  442. {
  443. Debug.WriteLine ($"ConfigurationManager.Load()");
  444. if (reset) Reset ();
  445. // LibraryResources is always loaded by Reset
  446. if (Locations == ConfigLocations.All) {
  447. var embeddedStylesResourceName = Assembly.GetEntryAssembly ()?
  448. .GetManifestResourceNames ().FirstOrDefault (x => x.EndsWith (_configFilename));
  449. if (string.IsNullOrEmpty (embeddedStylesResourceName)) {
  450. embeddedStylesResourceName = _configFilename;
  451. }
  452. Settings = Settings?
  453. // Global current directory
  454. .Update ($"./.tui/{_configFilename}")?
  455. // Global home directory
  456. .Update ($"~/.tui/{_configFilename}")?
  457. // App resources
  458. .UpdateFromResource (Assembly.GetEntryAssembly ()!, embeddedStylesResourceName!)?
  459. // App current directory
  460. .Update ($"./.tui/{AppName}.{_configFilename}")?
  461. // App home directory
  462. .Update ($"~/.tui/{AppName}.{_configFilename}");
  463. }
  464. }
  465. /// <summary>
  466. /// Returns an empty Json document with just the $schema tag.
  467. /// </summary>
  468. /// <returns></returns>
  469. public static string GetEmptyJson ()
  470. {
  471. var emptyScope = new SettingsScope ();
  472. emptyScope.Clear ();
  473. return JsonSerializer.Serialize<SettingsScope> (emptyScope, _serializerOptions);
  474. }
  475. /// <summary>
  476. /// System.Text.Json does not support copying a deserialized object to an existing instance.
  477. /// To work around this, we implement a 'deep, memberwise copy' method.
  478. /// </summary>
  479. /// <remarks>
  480. /// TOOD: When System.Text.Json implements `PopulateObject` revisit
  481. /// https://github.com/dotnet/corefx/issues/37627
  482. /// </remarks>
  483. /// <param name="source"></param>
  484. /// <param name="destination"></param>
  485. /// <returns><paramref name="destination"/> updated from <paramref name="source"/></returns>
  486. internal static object? DeepMemberwiseCopy (object? source, object? destination)
  487. {
  488. if (destination == null) {
  489. throw new ArgumentNullException (nameof (destination));
  490. }
  491. if (source == null) {
  492. return null!;
  493. }
  494. if (source.GetType () == typeof (SettingsScope)) {
  495. return ((SettingsScope)destination).Update ((SettingsScope)source);
  496. }
  497. if (source.GetType () == typeof (ThemeScope)) {
  498. return ((ThemeScope)destination).Update ((ThemeScope)source);
  499. }
  500. if (source.GetType () == typeof (AppScope)) {
  501. return ((AppScope)destination).Update ((AppScope)source);
  502. }
  503. // If value type, just use copy constructor.
  504. if (source.GetType ().IsValueType || source.GetType () == typeof (string)) {
  505. return source;
  506. }
  507. // Dictionary
  508. if (source.GetType ().IsGenericType && source.GetType ().GetGenericTypeDefinition ().IsAssignableFrom (typeof (Dictionary<,>))) {
  509. foreach (var srcKey in ((IDictionary)source).Keys) {
  510. if (((IDictionary)destination).Contains (srcKey))
  511. ((IDictionary)destination) [srcKey] = DeepMemberwiseCopy (((IDictionary)source) [srcKey], ((IDictionary)destination) [srcKey]);
  512. else {
  513. ((IDictionary)destination).Add (srcKey, ((IDictionary)source) [srcKey]);
  514. }
  515. }
  516. return destination;
  517. }
  518. // ALl other object types
  519. var sourceProps = source?.GetType ().GetProperties ().Where (x => x.CanRead).ToList ();
  520. var destProps = destination?.GetType ().GetProperties ().Where (x => x.CanWrite).ToList ()!;
  521. foreach (var (sourceProp, destProp) in
  522. from sourceProp in sourceProps
  523. where destProps.Any (x => x.Name == sourceProp.Name)
  524. let destProp = destProps.First (x => x.Name == sourceProp.Name)
  525. where destProp.CanWrite
  526. select (sourceProp, destProp)) {
  527. var sourceVal = sourceProp.GetValue (source);
  528. var destVal = destProp.GetValue (destination);
  529. if (sourceVal != null) {
  530. if (destVal != null) {
  531. // Recurse
  532. destProp.SetValue (destination, DeepMemberwiseCopy (sourceVal, destVal));
  533. } else {
  534. destProp.SetValue (destination, sourceVal);
  535. }
  536. }
  537. }
  538. return destination!;
  539. }
  540. //public class ConfiguraitonLocation
  541. //{
  542. // public string Name { get; set; } = string.Empty;
  543. // public string? Path { get; set; }
  544. // public async Task<SettingsScope> UpdateAsync (Stream stream)
  545. // {
  546. // var scope = await JsonSerializer.DeserializeAsync<SettingsScope> (stream, serializerOptions);
  547. // if (scope != null) {
  548. // ConfigurationManager.Settings?.UpdateFrom (scope);
  549. // return scope;
  550. // }
  551. // return new SettingsScope ();
  552. // }
  553. //}
  554. //public class StreamConfiguration {
  555. // private bool _reset;
  556. // public StreamConfiguration (bool reset)
  557. // {
  558. // _reset = reset;
  559. // }
  560. // public StreamConfiguration UpdateAppResources ()
  561. // {
  562. // if (Locations.HasFlag (ConfigLocations.AppResources)) LoadAppResources ();
  563. // return this;
  564. // }
  565. // public StreamConfiguration UpdateAppDirectory ()
  566. // {
  567. // if (Locations.HasFlag (ConfigLocations.AppDirectory)) LoadAppDirectory ();
  568. // return this;
  569. // }
  570. // // Additional update methods for each location here
  571. // private void LoadAppResources ()
  572. // {
  573. // // Load AppResources logic here
  574. // }
  575. // private void LoadAppDirectory ()
  576. // {
  577. // // Load AppDirectory logic here
  578. // }
  579. //}
  580. }