ConfigurationManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. internal 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. /// A dictionary of all properties in the Terminal.Gui project that are decorated with the <see cref="SerializableConfigurationProperty"/> attribute.
  68. /// The keys are the property names pre-pended with the class that implements the property (e.g. <c>Application.UseSystemConsole</c>).
  69. /// The values are instances of <see cref="ConfigProperty"/> which hold the property's value and the
  70. /// <see cref="PropertyInfo"/> that allows <see cref="ConfigurationManager"/> to get and set the property's value.
  71. /// </summary>
  72. /// <remarks>
  73. /// Is <see langword="null"/> until <see cref="Initialize"/> is called.
  74. /// </remarks>
  75. internal static Dictionary<string, ConfigProperty>? _allConfigProperties;
  76. /// <summary>
  77. /// The backing property for <see cref="Settings"/>.
  78. /// </summary>
  79. /// <remarks>
  80. /// Is <see langword="null"/> until <see cref="Reset"/> is called. Gets set to a new instance by
  81. /// deserialization (see <see cref="Load"/>).
  82. /// </remarks>
  83. private static SettingsScope? _settings;
  84. /// <summary>
  85. /// The root object of Terminal.Gui configuration settings / JSON schema. Contains only properties with the <see cref="SettingsScope"/>
  86. /// attribute value.
  87. /// </summary>
  88. public static SettingsScope? Settings {
  89. get {
  90. if (_settings == null) {
  91. throw new InvalidOperationException ("ConfigurationManager has not been initialized. Call ConfigurationManager.Reset() before accessing the Settings property.");
  92. }
  93. return _settings;
  94. }
  95. set {
  96. _settings = value!;
  97. }
  98. }
  99. /// <summary>
  100. /// The root object of Terminal.Gui themes manager. Contains only properties with the <see cref="ThemeScope"/>
  101. /// attribute value.
  102. /// </summary>
  103. public static ThemeManager? Themes => ThemeManager.Instance;
  104. /// <summary>
  105. /// Application-specific configuration settings scope.
  106. /// </summary>
  107. [SerializableConfigurationProperty (Scope = typeof (SettingsScope), OmitClassName = true), JsonPropertyName ("AppSettings")]
  108. public static AppScope? AppSettings { get; set; }
  109. /// <summary>
  110. /// The set of glyphs used to draw checkboxes, lines, borders, etc...See also <seealso cref="Terminal.Gui.GlyphDefinitions"/>.
  111. /// </summary>
  112. [SerializableConfigurationProperty (Scope = typeof (SettingsScope), OmitClassName = true),
  113. JsonPropertyName ("Glyphs")]
  114. public static GlyphDefinitions Glyphs { get; set; } = new GlyphDefinitions ();
  115. /// <summary>
  116. /// Initializes the internal state of ConfigurationManager. Nominally called once as part of application
  117. /// startup to initialize global state. Also called from some Unit Tests to ensure correctness (e.g. Reset()).
  118. /// </summary>
  119. internal static void Initialize ()
  120. {
  121. _allConfigProperties = new Dictionary<string, ConfigProperty> ();
  122. _settings = null;
  123. Dictionary<string, Type> classesWithConfigProps = new Dictionary<string, Type> (StringComparer.InvariantCultureIgnoreCase);
  124. // Get Terminal.Gui.dll classes
  125. var types = from assembly in AppDomain.CurrentDomain.GetAssemblies ()
  126. from type in assembly.GetTypes ()
  127. where type.GetProperties ().Any (prop => prop.GetCustomAttribute (typeof (SerializableConfigurationProperty)) != null)
  128. select type;
  129. foreach (var classWithConfig in types) {
  130. classesWithConfigProps.Add (classWithConfig.Name, classWithConfig);
  131. }
  132. Debug.WriteLine ($"ConfigManager.getConfigProperties found {classesWithConfigProps.Count} classes:");
  133. classesWithConfigProps.ToList ().ForEach (x => Debug.WriteLine ($" Class: {x.Key}"));
  134. foreach (var p in from c in classesWithConfigProps
  135. let props = c.Value.GetProperties (BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public).Where (prop =>
  136. prop.GetCustomAttribute (typeof (SerializableConfigurationProperty)) is SerializableConfigurationProperty)
  137. let enumerable = props
  138. from p in enumerable
  139. select p) {
  140. if (p.GetCustomAttribute (typeof (SerializableConfigurationProperty)) is SerializableConfigurationProperty scp) {
  141. if (p.GetGetMethod (true)!.IsStatic) {
  142. // If the class name is omitted, JsonPropertyName is allowed.
  143. _allConfigProperties!.Add (scp.OmitClassName ? ConfigProperty.GetJsonPropertyName (p) : $"{p.DeclaringType?.Name}.{p.Name}", new ConfigProperty {
  144. PropertyInfo = p,
  145. PropertyValue = null
  146. });
  147. } else {
  148. throw new Exception ($"Property {p.Name} in class {p.DeclaringType?.Name} is not static. All SerializableConfigurationProperty properties must be static.");
  149. }
  150. }
  151. }
  152. _allConfigProperties = _allConfigProperties!.OrderBy (x => x.Key).ToDictionary (x => x.Key, x => x.Value, StringComparer.InvariantCultureIgnoreCase);
  153. Debug.WriteLine ($"ConfigManager.Initialize found {_allConfigProperties.Count} properties:");
  154. //_allConfigProperties.ToList ().ForEach (x => Debug.WriteLine ($" Property: {x.Key}"));
  155. AppSettings = new AppScope ();
  156. }
  157. /// <summary>
  158. /// Creates a JSON document with the configuration specified.
  159. /// </summary>
  160. /// <returns></returns>
  161. internal static string ToJson ()
  162. {
  163. Debug.WriteLine ($"ConfigurationManager.ToJson()");
  164. return JsonSerializer.Serialize<SettingsScope> (Settings!, _serializerOptions);
  165. }
  166. internal static Stream ToStream ()
  167. {
  168. var json = JsonSerializer.Serialize<SettingsScope> (Settings!, _serializerOptions);
  169. // turn it into a stream
  170. var stream = new MemoryStream ();
  171. var writer = new StreamWriter (stream);
  172. writer.Write (json);
  173. writer.Flush ();
  174. stream.Position = 0;
  175. return stream;
  176. }
  177. /// <summary>
  178. /// Gets or sets whether the <see cref="ConfigurationManager"/> should throw an exception if it encounters
  179. /// an error on deserialization. If <see langword="false"/> (the default), the error is logged and printed to the
  180. /// console when <see cref="Application.Shutdown"/> is called.
  181. /// </summary>
  182. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  183. public static bool? ThrowOnJsonErrors { get; set; } = false;
  184. internal static StringBuilder jsonErrors = new StringBuilder ();
  185. internal static void AddJsonError (string error)
  186. {
  187. Debug.WriteLine ($"ConfigurationManager: {error}");
  188. jsonErrors.AppendLine (error);
  189. }
  190. /// <summary>
  191. /// Prints any Json deserialization errors that occurred during deserialization to the console.
  192. /// </summary>
  193. public static void PrintJsonErrors ()
  194. {
  195. if (jsonErrors.Length > 0) {
  196. Console.WriteLine ($"Terminal.Gui ConfigurationManager encountered the following errors while deserializing configuration files:");
  197. Console.WriteLine (jsonErrors.ToString ());
  198. }
  199. }
  200. private static void ClearJsonErrors ()
  201. {
  202. jsonErrors.Clear ();
  203. }
  204. /// <summary>
  205. /// Called when the configuration has been updated from a configuration file. Invokes the <see cref="Updated"/>
  206. /// event.
  207. /// </summary>
  208. public static void OnUpdated ()
  209. {
  210. Debug.WriteLine ($"ConfigurationManager.OnApplied()");
  211. Updated?.Invoke (null, new ConfigurationManagerEventArgs ());
  212. }
  213. /// <summary>
  214. /// Event fired when the configuration has been updated from a configuration source.
  215. /// application.
  216. /// </summary>
  217. public static event EventHandler<ConfigurationManagerEventArgs>? Updated;
  218. /// <summary>
  219. /// Resets the state of <see cref="ConfigurationManager"/>. Should be called whenever a new app session
  220. /// (e.g. in <see cref="Application.Init(ConsoleDriver, IMainLoopDriver)"/> starts. Called by <see cref="Load"/>
  221. /// if the <c>reset</c> parameter is <see langword="true"/>.
  222. /// </summary>
  223. /// <remarks>
  224. ///
  225. /// </remarks>
  226. public static void Reset ()
  227. {
  228. Debug.WriteLine ($"ConfigurationManager.Reset()");
  229. if (_allConfigProperties == null) {
  230. ConfigurationManager.Initialize ();
  231. }
  232. ClearJsonErrors ();
  233. Settings = new SettingsScope ();
  234. ThemeManager.Reset ();
  235. AppSettings = new AppScope ();
  236. // To enable some unit tests, we only load from resources if the flag is set
  237. if (Locations.HasFlag (ConfigLocations.DefaultOnly)) {
  238. Settings.UpdateFromResource (typeof (ConfigurationManager).Assembly, $"Terminal.Gui.Resources.{_configFilename}");
  239. }
  240. Apply ();
  241. ThemeManager.Themes? [ThemeManager.SelectedTheme]?.Apply ();
  242. AppSettings?.Apply ();
  243. }
  244. /// <summary>
  245. /// Retrieves the hard coded default settings from the Terminal.Gui library implementation. Used in development of
  246. /// the library to generate the default configuration file. Before calling Application.Init, make sure
  247. /// <see cref="Locations"/> is set to <see cref="ConfigLocations.None"/>.
  248. /// </summary>
  249. /// <remarks>
  250. /// <para>
  251. /// This method is only really useful when using ConfigurationManagerTests
  252. /// to generate the JSON doc that is embedded into Terminal.Gui (during development).
  253. /// </para>
  254. /// <para>
  255. /// WARNING: The <c>Terminal.Gui.Resources.config.json</c> resource has setting definitions (Themes)
  256. /// that are NOT generated by this function. If you use this function to regenerate <c>Terminal.Gui.Resources.config.json</c>,
  257. /// make sure you copy the Theme definitions from the existing <c>Terminal.Gui.Resources.config.json</c> file.
  258. /// </para>
  259. /// </remarks>
  260. internal static void GetHardCodedDefaults ()
  261. {
  262. if (_allConfigProperties == null) {
  263. throw new InvalidOperationException ("Initialize must be called first.");
  264. }
  265. Settings = new SettingsScope ();
  266. ThemeManager.GetHardCodedDefaults ();
  267. AppSettings?.RetrieveValues ();
  268. foreach (var p in Settings!.Where (cp => cp.Value.PropertyInfo != null)) {
  269. Settings! [p.Key].PropertyValue = p.Value.PropertyInfo?.GetValue (null);
  270. }
  271. }
  272. /// <summary>
  273. /// Applies the configuration settings to the running <see cref="Application"/> instance.
  274. /// </summary>
  275. public static void Apply ()
  276. {
  277. bool settings = Settings?.Apply () ?? false;
  278. bool themes = !string.IsNullOrEmpty (ThemeManager.SelectedTheme) && (ThemeManager.Themes? [ThemeManager.SelectedTheme]?.Apply () ?? false);
  279. bool appsettings = AppSettings?.Apply () ?? false;
  280. if (settings || themes || appsettings) {
  281. OnApplied ();
  282. }
  283. }
  284. /// <summary>
  285. /// Called when an updated configuration has been applied to the
  286. /// application. Fires the <see cref="Applied"/> event.
  287. /// </summary>
  288. public static void OnApplied ()
  289. {
  290. Debug.WriteLine ($"ConfigurationManager.OnApplied()");
  291. Applied?.Invoke (null, new ConfigurationManagerEventArgs ());
  292. }
  293. /// <summary>
  294. /// Event fired when an updated configuration has been applied to the
  295. /// application.
  296. /// </summary>
  297. public static event EventHandler<ConfigurationManagerEventArgs>? Applied;
  298. /// <summary>
  299. /// Name of the running application. By default this property is set to the application's assembly name.
  300. /// </summary>
  301. public static string AppName { get; set; } = Assembly.GetEntryAssembly ()?.FullName?.Split (',') [0]?.Trim ()!;
  302. /// <summary>
  303. /// Describes the location of the configuration files. The constants can be
  304. /// combined (bitwise) to specify multiple locations.
  305. /// </summary>
  306. [Flags]
  307. public enum ConfigLocations {
  308. /// <summary>
  309. /// No configuration will be loaded.
  310. /// </summary>
  311. /// <remarks>
  312. /// Used for development and testing only. For Terminal,Gui to function properly, at least
  313. /// <see cref="DefaultOnly"/> should be set.
  314. /// </remarks>
  315. None = 0,
  316. /// <summary>
  317. /// Global configuration in <c>Terminal.Gui.dll</c>'s resources (<c>Terminal.Gui.Resources.config.json</c>) -- Lowest Precidence.
  318. /// </summary>
  319. DefaultOnly,
  320. /// <summary>
  321. /// This constant is a combination of all locations
  322. /// </summary>
  323. All = -1
  324. }
  325. /// <summary>
  326. /// Gets and sets the locations where <see cref="ConfigurationManager"/> will look for config files.
  327. /// The value is <see cref="ConfigLocations.All"/>.
  328. /// </summary>
  329. public static ConfigLocations Locations { get; set; } = ConfigLocations.All;
  330. /// <summary>
  331. /// Loads all settings found in the various configuration storage locations to
  332. /// the <see cref="ConfigurationManager"/>. Optionally,
  333. /// resets all settings attributed with <see cref="SerializableConfigurationProperty"/> to the defaults.
  334. /// </summary>
  335. /// <remarks>
  336. /// Use <see cref="Apply"/> to cause the loaded settings to be applied to the running application.
  337. /// </remarks>
  338. /// <param name="reset">If <see langword="true"/> the state of <see cref="ConfigurationManager"/> will
  339. /// be reset to the defaults.</param>
  340. public static void Load (bool reset = false)
  341. {
  342. Debug.WriteLine ($"ConfigurationManager.Load()");
  343. if (reset) Reset ();
  344. // LibraryResources is always loaded by Reset
  345. if (Locations == ConfigLocations.All) {
  346. var embeddedStylesResourceName = Assembly.GetEntryAssembly ()?
  347. .GetManifestResourceNames ().FirstOrDefault (x => x.EndsWith (_configFilename));
  348. if (string.IsNullOrEmpty (embeddedStylesResourceName)) {
  349. embeddedStylesResourceName = _configFilename;
  350. }
  351. Settings = Settings?
  352. // Global current directory
  353. .Update ($"./.tui/{_configFilename}")?
  354. // Global home directory
  355. .Update ($"~/.tui/{_configFilename}")?
  356. // App resources
  357. .UpdateFromResource (Assembly.GetEntryAssembly ()!, embeddedStylesResourceName!)?
  358. // App current directory
  359. .Update ($"./.tui/{AppName}.{_configFilename}")?
  360. // App home directory
  361. .Update ($"~/.tui/{AppName}.{_configFilename}");
  362. }
  363. }
  364. /// <summary>
  365. /// Returns an empty Json document with just the $schema tag.
  366. /// </summary>
  367. /// <returns></returns>
  368. public static string GetEmptyJson ()
  369. {
  370. var emptyScope = new SettingsScope ();
  371. emptyScope.Clear ();
  372. return JsonSerializer.Serialize<SettingsScope> (emptyScope, _serializerOptions);
  373. }
  374. /// <summary>
  375. /// System.Text.Json does not support copying a deserialized object to an existing instance.
  376. /// To work around this, we implement a 'deep, memberwise copy' method.
  377. /// </summary>
  378. /// <remarks>
  379. /// TOOD: When System.Text.Json implements `PopulateObject` revisit
  380. /// https://github.com/dotnet/corefx/issues/37627
  381. /// </remarks>
  382. /// <param name="source"></param>
  383. /// <param name="destination"></param>
  384. /// <returns><paramref name="destination"/> updated from <paramref name="source"/></returns>
  385. internal static object? DeepMemberwiseCopy (object? source, object? destination)
  386. {
  387. if (destination == null) {
  388. throw new ArgumentNullException (nameof (destination));
  389. }
  390. if (source == null) {
  391. return null!;
  392. }
  393. if (source.GetType () == typeof (SettingsScope)) {
  394. return ((SettingsScope)destination).Update ((SettingsScope)source);
  395. }
  396. if (source.GetType () == typeof (ThemeScope)) {
  397. return ((ThemeScope)destination).Update ((ThemeScope)source);
  398. }
  399. if (source.GetType () == typeof (AppScope)) {
  400. return ((AppScope)destination).Update ((AppScope)source);
  401. }
  402. // If value type, just use copy constructor.
  403. if (source.GetType ().IsValueType || source.GetType () == typeof (string)) {
  404. return source;
  405. }
  406. // Dictionary
  407. if (source.GetType ().IsGenericType && source.GetType ().GetGenericTypeDefinition ().IsAssignableFrom (typeof (Dictionary<,>))) {
  408. foreach (var srcKey in ((IDictionary)source).Keys) {
  409. if (((IDictionary)destination).Contains (srcKey))
  410. ((IDictionary)destination) [srcKey] = DeepMemberwiseCopy (((IDictionary)source) [srcKey], ((IDictionary)destination) [srcKey]);
  411. else {
  412. ((IDictionary)destination).Add (srcKey, ((IDictionary)source) [srcKey]);
  413. }
  414. }
  415. return destination;
  416. }
  417. // ALl other object types
  418. var sourceProps = source?.GetType ().GetProperties ().Where (x => x.CanRead).ToList ();
  419. var destProps = destination?.GetType ().GetProperties ().Where (x => x.CanWrite).ToList ()!;
  420. foreach (var (sourceProp, destProp) in
  421. from sourceProp in sourceProps
  422. where destProps.Any (x => x.Name == sourceProp.Name)
  423. let destProp = destProps.First (x => x.Name == sourceProp.Name)
  424. where destProp.CanWrite
  425. select (sourceProp, destProp)) {
  426. var sourceVal = sourceProp.GetValue (source);
  427. var destVal = destProp.GetValue (destination);
  428. if (sourceVal != null) {
  429. if (destVal != null) {
  430. // Recurse
  431. destProp.SetValue (destination, DeepMemberwiseCopy (sourceVal, destVal));
  432. } else {
  433. destProp.SetValue (destination, sourceVal);
  434. }
  435. }
  436. }
  437. return destination!;
  438. }
  439. //public class ConfiguraitonLocation
  440. //{
  441. // public string Name { get; set; } = string.Empty;
  442. // public string? Path { get; set; }
  443. // public async Task<SettingsScope> UpdateAsync (Stream stream)
  444. // {
  445. // var scope = await JsonSerializer.DeserializeAsync<SettingsScope> (stream, serializerOptions);
  446. // if (scope != null) {
  447. // ConfigurationManager.Settings?.UpdateFrom (scope);
  448. // return scope;
  449. // }
  450. // return new SettingsScope ();
  451. // }
  452. //}
  453. //public class StreamConfiguration {
  454. // private bool _reset;
  455. // public StreamConfiguration (bool reset)
  456. // {
  457. // _reset = reset;
  458. // }
  459. // public StreamConfiguration UpdateAppResources ()
  460. // {
  461. // if (Locations.HasFlag (ConfigLocations.AppResources)) LoadAppResources ();
  462. // return this;
  463. // }
  464. // public StreamConfiguration UpdateAppDirectory ()
  465. // {
  466. // if (Locations.HasFlag (ConfigLocations.AppDirectory)) LoadAppDirectory ();
  467. // return this;
  468. // }
  469. // // Additional update methods for each location here
  470. // private void LoadAppResources ()
  471. // {
  472. // // Load AppResources logic here
  473. // }
  474. // private void LoadAppDirectory ()
  475. // {
  476. // // Load AppDirectory logic here
  477. // }
  478. //}
  479. }