SchemeManager.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. #nullable enable
  2. using System.Collections.Immutable;
  3. using System.Diagnostics;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Text.Json.Serialization;
  6. namespace Terminal.Gui.Configuration;
  7. /// <summary>
  8. /// Holds the <see cref="Drawing.Scheme"/>s that define the <see cref="System.Attribute"/>s that are used by views to
  9. /// render
  10. /// themselves. A Scheme is a mapping from <see cref="Drawing.VisualRole"/>s (such as
  11. /// <see cref="Drawing.VisualRole.Focus"/>) to <see cref="System.Attribute"/>s.
  12. /// A Scheme defines how a `View` should look based on its purpose (e.g. Menu or Dialog).
  13. /// </summary>
  14. public sealed class SchemeManager // : INotifyCollectionChanged, IDictionary<string, Scheme?>
  15. {
  16. #pragma warning disable IDE1006 // Naming Styles
  17. private static readonly object _schemesLock = new ();
  18. #pragma warning restore IDE1006 // Naming Styles
  19. /// <summary>
  20. /// INTERNAL: Gets the hard-coded schemes defined by <see cref="View"/>. These are not loaded from the configuration
  21. /// files,
  22. /// but are hard-coded in the source code. Used for unit testing when ConfigurationManager is not initialized.
  23. /// </summary>
  24. /// <returns></returns>
  25. internal static ImmutableSortedDictionary<string, Scheme?>? GetHardCodedSchemes () { return Scheme.GetHardCodedSchemes ()!; }
  26. /// <summary>
  27. /// Use <see cref="AddScheme"/>, <see cref="GetScheme(Drawing.Schemes)"/>, <see cref="GetSchemeNames"/>,
  28. /// <see cref="GetSchemesForCurrentTheme"/>, etc... instead.
  29. /// </summary>
  30. [ConfigurationProperty (Scope = typeof (ThemeScope), OmitClassName = true)]
  31. [JsonConverter (typeof (DictionaryJsonConverter<Scheme?>))]
  32. [UsedImplicitly]
  33. public static Dictionary<string, Scheme?>? Schemes
  34. {
  35. get => GetSchemes ();
  36. [RequiresUnreferencedCode ("Calls Terminal.Gui.SchemeManager.SetSchemes(Dictionary<String, Scheme>)")]
  37. [RequiresDynamicCode ("Calls Terminal.Gui.SchemeManager.SetSchemes(Dictionary<String, Scheme>)")]
  38. private set => SetSchemes (value);
  39. }
  40. /// <summary>INTERNAL: Gets the dictionary of defined <see cref="Scheme"/>s. The get method for <see cref="Schemes"/>.</summary>
  41. internal static Dictionary<string, Scheme?> GetSchemes ()
  42. {
  43. if (!ConfigurationManager.IsInitialized ())
  44. {
  45. // We're being called from the module initializer.
  46. // Hard coded default value
  47. return GetHardCodedSchemes ()!.ToDictionary (StringComparer.InvariantCultureIgnoreCase);
  48. }
  49. return GetSchemesForCurrentTheme ();
  50. }
  51. /// <summary>INTERNAL: The set method for <see cref="Schemes"/>.</summary>
  52. [RequiresUnreferencedCode ("Calls Terminal.Gui.ConfigProperty.UpdateFrom(Object)")]
  53. [RequiresDynamicCode ("Calls Terminal.Gui.ConfigProperty.UpdateFrom(Object)")]
  54. internal static void SetSchemes (Dictionary<string, Scheme?>? value)
  55. {
  56. lock (_schemesLock)
  57. {
  58. if (!ConfigurationManager.IsInitialized ())
  59. {
  60. throw new InvalidOperationException ("Schemes cannot be set before ConfigurationManager is initialized.");
  61. }
  62. Debug.Assert (value is { });
  63. // Update the backing store
  64. ThemeManager.GetCurrentTheme () ["Schemes"].UpdateFrom (value);
  65. }
  66. //Instance.OnThemeChanged (prevousValue);
  67. }
  68. /// <summary>
  69. /// Adds a new <see cref="Scheme"/> to <see cref="SchemeManager"/>. If the Scheme has already been added,
  70. /// it will be updated to <paramref name="scheme"/>.
  71. /// </summary>
  72. /// <param name="schemeName">The name of the Scheme. This must be unique.</param>
  73. /// <param name="scheme"></param>
  74. /// <returns></returns>
  75. public static void AddScheme (string schemeName, Scheme scheme)
  76. {
  77. if (!GetSchemes ()!.TryAdd (schemeName, scheme))
  78. {
  79. GetSchemes () [schemeName] = scheme;
  80. }
  81. }
  82. /// <summary>
  83. /// Removes a Scheme from <see cref="SchemeManager"/>.
  84. /// </summary>
  85. /// <param name="schemeName"></param>
  86. /// <exception cref="InvalidOperationException">If the scheme is a built-in Scheme or was not previously added.</exception>
  87. public static void RemoveScheme (string schemeName)
  88. {
  89. if (SchemeNameToSchemes (schemeName) is { })
  90. {
  91. throw new InvalidOperationException ($@"{schemeName}: Cannot remove a built-in Scheme.");
  92. }
  93. if (!GetSchemes ().TryGetValue (schemeName, out _))
  94. {
  95. throw new InvalidOperationException ($@"{schemeName}: Does not exist in Schemes.");
  96. }
  97. GetSchemes ().Remove (schemeName);
  98. }
  99. /// <summary>
  100. /// Gets the <see cref="Scheme"/> for the specified <see cref="Drawing.Schemes"/>.
  101. /// </summary>
  102. /// <param name="schemeName"></param>
  103. /// <returns></returns>
  104. /// <exception cref="ArgumentException"></exception>
  105. public static Scheme GetScheme (Schemes schemeName)
  106. {
  107. // Convert schemeName to string via Enum api
  108. string? schemeNameString = SchemesToSchemeName (schemeName);
  109. if (schemeNameString is null)
  110. {
  111. throw new ArgumentException ($"Invalid scheme name: {schemeName}");
  112. }
  113. return GetSchemesForCurrentTheme ()! [schemeNameString]!;
  114. }
  115. /// <summary>
  116. /// Gets the <see cref="Scheme"/> for the specified string.
  117. /// </summary>
  118. /// <param name="schemeName"></param>
  119. /// <returns></returns>
  120. /// <exception cref="ArgumentException"></exception>
  121. public static Scheme GetScheme (string schemeName) { return GetSchemesForCurrentTheme ()! [schemeName]!; }
  122. /// <summary>
  123. /// Gets the name of the specified <see cref="Schemes"/>. Will throw an exception if <paramref name="schemeName"/>
  124. /// is not a built-in Scheme.
  125. /// </summary>
  126. /// <param name="schemeName"></param>
  127. /// <returns>The name of scheme.</returns>
  128. public static string? SchemesToSchemeName (Schemes schemeName) { return Enum.GetName (typeof (Schemes), schemeName); }
  129. /// <summary>
  130. /// Converts a string to a <see cref="Schemes"/> enum value.
  131. /// </summary>
  132. /// <param name="schemeName"><see langword="null"/> if the schemeName is not a built-in Scheme name.</param>
  133. /// <returns><see langword="null"/> if <paramref name="schemeName"/> is not the name of a built-in Scheme.</returns>
  134. public static string? SchemeNameToSchemes (string schemeName)
  135. {
  136. if (Enum.TryParse (typeof (Schemes), schemeName, out object? value))
  137. {
  138. return value?.ToString ();
  139. }
  140. return null;
  141. }
  142. /// <summary>
  143. /// Get the dictionary of schemes from the current theme. Current means active.
  144. /// </summary>
  145. /// <returns></returns>
  146. public static Dictionary<string, Scheme?> GetSchemesForCurrentTheme ()
  147. {
  148. lock (_schemesLock)
  149. {
  150. if (!ConfigurationManager.IsInitialized ())
  151. {
  152. throw new InvalidOperationException ("CM Must be Initialized");
  153. }
  154. if (ThemeManager.GetCurrentTheme () ["Schemes"].PropertyValue is not Dictionary<string, Scheme?> schemes)
  155. {
  156. // Most likely because "Schemes": was left out of the config
  157. throw new InvalidOperationException ("Current Theme does not have a Scheme.");
  158. }
  159. return schemes!;
  160. }
  161. }
  162. /// <summary>
  163. /// Convenience method to get the names of the schemes.
  164. /// </summary>
  165. /// <returns></returns>
  166. public static ImmutableList<string> GetSchemeNames ()
  167. {
  168. lock (_schemesLock)
  169. {
  170. return GetSchemes ()!.Keys.ToImmutableList ();
  171. }
  172. }
  173. [RequiresUnreferencedCode ("Calls SetSchemes")]
  174. [RequiresDynamicCode ("Calls SetSchemes")]
  175. internal static void LoadToHardCodedDefaults ()
  176. {
  177. // BUGBUG: SchemeManager is broken and needs to be fixed to not have the hard coded schemes get overwritten.
  178. // BUGBUG: This is a partial workaround
  179. // BUGBUG: See https://github.com/gui-cs/Terminal.Gui/issues/4288
  180. SetSchemes (GetHardCodedSchemes ()!.ToDictionary ());
  181. }
  182. }