SchemeManager.cs 8.1 KB

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