ThemeManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. using System.Collections.Concurrent;
  2. using System.Collections.Immutable;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Text.Json.Serialization;
  5. namespace Terminal.Gui.Configuration;
  6. /// <summary>Manages Themes.</summary>
  7. /// <remarks>
  8. /// <para>A Theme is a collection of settings that are named. The default theme is named "Default".</para>
  9. /// <para>The <see cref="Theme"/> property is used to determine the currently active theme.</para>
  10. /// <para>The <see cref="Themes"/> property is a dictionary of themes.</para>
  11. /// </remarks>
  12. public static class ThemeManager
  13. {
  14. /// <summary>
  15. /// Convenience method to get the current theme. The current theme is the item in the <see cref="Themes"/> dictionary,
  16. /// with the key of <see cref="Theme"/>.
  17. /// </summary>
  18. /// <returns></returns>
  19. public static ThemeScope GetCurrentTheme () { return Themes! [Theme]; }
  20. /// <summary>
  21. /// INTERNAL: Getter for <see cref="Themes"/>.
  22. /// Convenience method to get the themes dictionary. The themes dictionary is a dictionary of <see cref="ThemeScope"/>
  23. /// objects, with the key being the name of the theme.
  24. /// </summary>
  25. /// <returns></returns>
  26. /// <exception cref="InvalidOperationException"></exception>
  27. private static ConcurrentDictionary<string, ThemeScope> GetThemes ()
  28. {
  29. if (!ConfigurationManager.IsInitialized ())
  30. {
  31. // We're being called from the module initializer.
  32. // We need to provide a dictionary of themes containing the hard-coded theme.
  33. return GetHardCodedThemes ()!;
  34. }
  35. if (ConfigurationManager.Settings is null)
  36. {
  37. throw new InvalidOperationException ("Settings is null.");
  38. }
  39. if (ConfigurationManager.Settings.TryGetValue ("Themes", out ConfigProperty? themes))
  40. {
  41. if (themes.HasValue)
  42. {
  43. return (themes.PropertyValue as ConcurrentDictionary<string, ThemeScope>)!;
  44. }
  45. return GetHardCodedThemes ()!;
  46. }
  47. throw new InvalidOperationException ("Settings has no Themes property.");
  48. }
  49. /// <summary>
  50. /// INTERNAL: Convenience method to get a list of theme names.
  51. /// </summary>
  52. /// <returns></returns>
  53. /// <exception cref="InvalidOperationException"></exception>
  54. public static ImmutableList<string> GetThemeNames ()
  55. {
  56. if (!ConfigurationManager.IsInitialized ())
  57. {
  58. // We're being called from the module initializer.
  59. // We need to provide a dictionary of themes containing the hard-coded theme.
  60. return GetHardCodedThemes ()!.Keys.ToImmutableList ();
  61. }
  62. if (ConfigurationManager.Settings is null)
  63. {
  64. throw new InvalidOperationException ("Settings is null.");
  65. }
  66. if (!ConfigurationManager.Settings.TryGetValue ("Themes", out ConfigProperty? themes))
  67. {
  68. throw new InvalidOperationException ("Settings has no Themes property.");
  69. }
  70. ConcurrentDictionary<string, ThemeScope>? returnConcurrentDictionary;
  71. if (themes.HasValue)
  72. {
  73. returnConcurrentDictionary = themes.PropertyValue as ConcurrentDictionary<string, ThemeScope>;
  74. }
  75. else
  76. {
  77. returnConcurrentDictionary = GetHardCodedThemes ();
  78. }
  79. return returnConcurrentDictionary!.Keys
  80. .OrderBy (key => key == DEFAULT_THEME_NAME ? string.Empty : key) // Ensure DEFAULT_THEME_NAME is first
  81. .ToImmutableList ();
  82. }
  83. /// <summary>
  84. /// Convenience method to get the current theme name. The current theme name is the value of <see cref="Theme"/>.
  85. /// </summary>
  86. /// <returns></returns>
  87. public static string GetCurrentThemeName () { return Theme!; }
  88. // TODO: Add a lock around Theme and Themes
  89. // TODO: For now, this test can't run in parallel with other tests that access Theme or Themes.
  90. // TODO: ThemeScopeList_WithThemes_ClonesSuccessfully
  91. /// <summary>
  92. /// Gets the Themes dictionary. <see cref="GetThemes"/> is preferred.
  93. /// The backing store is <c><see cref="ConfigurationManager.Settings"/> ["Themes"]</c>.
  94. /// However, if <see cref="ConfigurationManager.IsInitialized"/> is <c>false</c>, this property will return the
  95. /// hard-coded themes.
  96. /// </summary>
  97. /// <exception cref="InvalidOperationException"></exception>
  98. [JsonConverter (typeof (ConcurrentDictionaryJsonConverter<ThemeScope>))]
  99. [ConfigurationProperty (Scope = typeof (SettingsScope), OmitClassName = true)]
  100. public static ConcurrentDictionary<string, ThemeScope>? Themes
  101. {
  102. // Note: This property getter must be public; DeepClone depends on it.
  103. get => GetThemes ();
  104. internal set => SetThemes (value);
  105. }
  106. /// <summary>
  107. /// INTERNAL: Setter for <see cref="Themes"/>.
  108. /// </summary>
  109. /// <param name="dictionary"></param>
  110. /// <exception cref="InvalidOperationException"></exception>
  111. private static void SetThemes (ConcurrentDictionary<string, ThemeScope>? dictionary)
  112. {
  113. if (dictionary is { } && !dictionary.ContainsKey (DEFAULT_THEME_NAME))
  114. {
  115. throw new InvalidOperationException ($"Themes must include an item named {DEFAULT_THEME_NAME}");
  116. }
  117. if (ConfigurationManager.Settings is { } && ConfigurationManager.Settings.TryGetValue ("Themes", out ConfigProperty? themes))
  118. {
  119. ConfigurationManager.Settings ["Themes"].PropertyValue = dictionary;
  120. return;
  121. }
  122. throw new InvalidOperationException ("Settings is null.");
  123. }
  124. /// <summary>
  125. /// INTERNAL: Returns the hard-coded Themes dictionary.
  126. /// </summary>
  127. /// <returns></returns>
  128. /// <exception cref="InvalidOperationException"></exception>
  129. private static ConcurrentDictionary<string, ThemeScope>? GetHardCodedThemes ()
  130. {
  131. ThemeScope? hardCodedThemeScope = GetHardCodedThemeScope ();
  132. if (hardCodedThemeScope is null)
  133. {
  134. throw new InvalidOperationException ("Hard coded theme scope is null.");
  135. }
  136. return new (new Dictionary<string, ThemeScope> { { DEFAULT_THEME_NAME, hardCodedThemeScope } }, StringComparer.InvariantCultureIgnoreCase);
  137. }
  138. /// <summary>
  139. /// INTERNAL: Returns the ThemeScope containing the hard-coded Themes.
  140. /// </summary>
  141. /// <returns></returns>
  142. private static ThemeScope GetHardCodedThemeScope ()
  143. {
  144. IEnumerable<KeyValuePair<string, ConfigProperty>>? hardCodedThemeProperties = ConfigurationManager.GetHardCodedConfigPropertiesByScope ("ThemeScope");
  145. if (hardCodedThemeProperties is null)
  146. {
  147. throw new InvalidOperationException ("Hard coded theme properties are null.");
  148. }
  149. var hardCodedThemeScope = new ThemeScope ();
  150. foreach (KeyValuePair<string, ConfigProperty> p in hardCodedThemeProperties)
  151. {
  152. hardCodedThemeScope.AddValue (p.Key, p.Value.PropertyValue);
  153. }
  154. return hardCodedThemeScope;
  155. }
  156. /// <summary>
  157. /// The name of the default theme ("Default").
  158. /// </summary>
  159. public const string DEFAULT_THEME_NAME = "Default";
  160. /// <summary>
  161. /// The currently selected theme. The backing store is <c><see cref="ConfigurationManager.Settings"/> ["Theme"]</c>.
  162. /// </summary>
  163. [JsonInclude]
  164. [ConfigurationProperty (Scope = typeof (SettingsScope), OmitClassName = true)]
  165. [JsonPropertyName ("Theme")]
  166. public static string Theme
  167. {
  168. get
  169. {
  170. if (!ConfigurationManager.IsInitialized ())
  171. {
  172. // We're being called from the module initializer.
  173. // Hard coded default value
  174. return DEFAULT_THEME_NAME;
  175. }
  176. if (ConfigurationManager.Settings is { } && ConfigurationManager.Settings.TryGetValue ("Theme", out ConfigProperty? themeCp))
  177. {
  178. if (themeCp.HasValue)
  179. {
  180. return (themeCp.PropertyValue as string)!;
  181. }
  182. return DEFAULT_THEME_NAME;
  183. }
  184. throw new InvalidOperationException ("Settings is null.");
  185. }
  186. [RequiresUnreferencedCode ("Calls Terminal.Gui.ConfigurationManager.Settings")]
  187. [RequiresDynamicCode ("Calls Terminal.Gui.ConfigurationManager.Settings")]
  188. set
  189. {
  190. if (!ConfigurationManager.IsInitialized ())
  191. {
  192. throw new InvalidOperationException ("Theme cannot be set before ConfigurationManager is initialized.");
  193. }
  194. if (ConfigurationManager.Settings is null || !ConfigurationManager.Settings.TryGetValue ("Theme", out ConfigProperty? themeCp))
  195. {
  196. throw new InvalidOperationException ("Settings is null.");
  197. }
  198. if (themeCp is null || !themeCp.HasValue)
  199. {
  200. throw new InvalidOperationException ("Theme has no value.");
  201. }
  202. if (!ConfigurationManager.Settings.TryGetValue ("Themes", out ConfigProperty? themesCp))
  203. {
  204. throw new InvalidOperationException ("Settings has no Themes property.");
  205. }
  206. string previousThemeValue = GetCurrentThemeName ();
  207. if (value == previousThemeValue)
  208. {
  209. return;
  210. }
  211. if (!Themes!.ContainsKey (value))
  212. {
  213. Logging.Warning ($"{value} is not a valid theme name.");
  214. }
  215. // Update the backing store
  216. ConfigurationManager.Settings! ["Theme"].PropertyValue = value;
  217. OnThemeChanged (previousThemeValue, value);
  218. }
  219. }
  220. /// <summary>
  221. /// INTERNAL: Updates <see cref="Themes"/> to the current values of the static
  222. /// <see cref="ConfigurationPropertyAttribute"/> properties.
  223. /// </summary>
  224. [RequiresUnreferencedCode ("Calls Terminal.Gui.ThemeManager.Themes")]
  225. [RequiresDynamicCode ("Calls Terminal.Gui.ThemeManager.Themes")]
  226. internal static void UpdateToCurrentValues ()
  227. {
  228. // BUGBUG: This corrupts _hardCodedDefaults. See #4288
  229. Themes! [Theme].UpdateToCurrentValues ();
  230. }
  231. /// <summary>
  232. /// INTERNAL: Loads all Themes to their hard-coded default values.
  233. /// </summary>
  234. [RequiresUnreferencedCode ("Calls SchemeManager.LoadToHardCodedDefaults")]
  235. [RequiresDynamicCode ("Calls SchemeManager.LoadToHardCodedDefaults")]
  236. internal static void LoadHardCodedDefaults ()
  237. {
  238. if (!ConfigurationManager.IsInitialized ())
  239. {
  240. throw new InvalidOperationException ("ThemeManager is not initialized.");
  241. }
  242. if (ConfigurationManager.Settings is null)
  243. {
  244. return;
  245. }
  246. ThemeScope? hardCodedThemeScope = GetHardCodedThemeScope ();
  247. if (hardCodedThemeScope is null)
  248. {
  249. throw new InvalidOperationException ("Hard coded theme scope is null.");
  250. }
  251. ConcurrentDictionary<string, ThemeScope> hardCodedThemes = new (
  252. new Dictionary<string, ThemeScope>
  253. {
  254. { Theme, hardCodedThemeScope }
  255. },
  256. StringComparer.InvariantCultureIgnoreCase);
  257. // BUGBUG: SchemeManager is broken and needs to be fixed to not have the hard coded schemes get overwritten.
  258. // BUGBUG: This is a partial workaround
  259. // BUGBUG: See https://github.com/gui-cs/Terminal.Gui/issues/4288
  260. SchemeManager.LoadToHardCodedDefaults ();
  261. ConfigurationManager.Settings ["Themes"].PropertyValue = hardCodedThemes;
  262. ConfigurationManager.Settings ["Theme"].PropertyValue = DEFAULT_THEME_NAME;
  263. }
  264. /// <summary>Called when the selected theme has changed. Fires the <see cref="ThemeChanged"/> event.</summary>
  265. internal static void OnThemeChanged (string previousThemeName, string newThemeName)
  266. {
  267. Logging.Debug ($"Themes.OnThemeChanged({previousThemeName}) -> {Theme}");
  268. EventArgs<string> args = new (newThemeName);
  269. ThemeChanged?.Invoke (null, args);
  270. }
  271. /// <summary>Raised when the selected theme has changed.</summary>
  272. public static event EventHandler<EventArgs<string>>? ThemeChanged;
  273. }