ThemeManager.cs 13 KB

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