Scope.cs 3.1 KB

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