Scope.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using static Terminal.Gui.ConfigurationManager;
  7. #nullable enable
  8. namespace Terminal.Gui {
  9. /// <summary>
  10. /// Defines a configuration settings scope. Classes that inherit from this abstract class can be used to define
  11. /// scopes for configuration settings. Each scope is a JSON object that contains a set of configuration settings.
  12. /// </summary>
  13. public class Scope<T> : Dictionary<string, ConfigProperty> { //, IScope<Scope<T>> {
  14. /// <summary>
  15. /// Crates a new instance.
  16. /// </summary>
  17. public Scope () : base (StringComparer.InvariantCultureIgnoreCase)
  18. {
  19. foreach (var p in GetScopeProperties ()) {
  20. Add (p.Key, new ConfigProperty () { PropertyInfo = p.Value.PropertyInfo, PropertyValue = null });
  21. }
  22. }
  23. private IEnumerable<KeyValuePair<string, ConfigProperty>> GetScopeProperties ()
  24. {
  25. return ConfigurationManager._allConfigProperties!.Where (cp =>
  26. (cp.Value.PropertyInfo?.GetCustomAttribute (typeof (SerializableConfigurationProperty))
  27. as SerializableConfigurationProperty)?.Scope == GetType ());
  28. }
  29. /// <summary>
  30. /// Updates this instance from the specified source scope.
  31. /// </summary>
  32. /// <param name="source"></param>
  33. /// <returns>The updated scope (this).</returns>
  34. public Scope<T>? Update (Scope<T> source)
  35. {
  36. foreach (var prop in source) {
  37. if (ContainsKey (prop.Key))
  38. this [prop.Key].PropertyValue = this [prop.Key].UpdateValueFrom (prop.Value.PropertyValue!);
  39. else {
  40. this [prop.Key].PropertyValue = prop.Value.PropertyValue;
  41. }
  42. }
  43. return this;
  44. }
  45. /// <summary>
  46. /// Retrieves the values of the properties of this scope from their corresponding static properties.
  47. /// </summary>
  48. public void RetrieveValues ()
  49. {
  50. foreach (var p in this.Where (cp => cp.Value.PropertyInfo != null)) {
  51. p.Value.RetrieveValue ();
  52. }
  53. }
  54. /// <summary>
  55. /// Applies the values of the properties of this scope to their corresponding static properties.
  56. /// </summary>
  57. /// <returns></returns>
  58. internal virtual bool Apply ()
  59. {
  60. bool set = false;
  61. foreach (var p in this.Where (t => t.Value != null && t.Value.PropertyValue != null)) {
  62. if (p.Value.Apply ()) {
  63. set = true;
  64. }
  65. }
  66. return set;
  67. }
  68. }
  69. }