Scope.cs 3.1 KB

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