Skip to main content

gpui_component/theme/
schema.rs

1use std::{rc::Rc, sync::Arc};
2
3use gpui::{Background, BoxShadow, FontWeight, Hsla, SharedString, px};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6
7use crate::highlighter::{HighlightTheme, HighlightThemeStyle};
8
9use super::color::{
10    try_parse_background, try_parse_background_clamped, try_parse_color, try_parse_theme_color,
11};
12use super::{Colorize, SemanticThemeTokens, Theme, ThemeColor, ThemeMode, ThemeToken, ThemeTokens};
13
14fn try_parse_theme_token(value: &str) -> anyhow::Result<ThemeToken> {
15    Ok(ThemeToken::new(
16        try_parse_theme_color(value)?,
17        try_parse_background(value)?,
18    ))
19}
20
21/// Represents a theme configuration.
22#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
23#[serde(default)]
24#[non_exhaustive]
25pub struct ThemeSet {
26    /// The name of the theme set.
27    pub name: SharedString,
28    /// The author of the theme.
29    pub author: Option<SharedString>,
30    /// The URL of the theme.
31    pub url: Option<SharedString>,
32    /// The theme list of the theme set.
33    #[serde(rename = "themes")]
34    pub themes: Vec<ThemeConfig>,
35}
36
37#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
38#[serde(default)]
39#[non_exhaustive]
40pub struct ThemeConfig {
41    /// Whether this theme is the default theme.
42    pub is_default: bool,
43    /// The name of the theme.
44    pub name: SharedString,
45    /// The mode of the theme, default is light.
46    pub mode: ThemeMode,
47
48    /// The base font size, default is 16.
49    #[serde(rename = "font.size")]
50    pub font_size: Option<f32>,
51    /// The base font family, default is system font: `.SystemUIFont`.
52    #[serde(rename = "font.family")]
53    pub font_family: Option<SharedString>,
54    /// The monospace font family, default is platform specific:
55    /// - macOS: `Menlo`
56    /// - Windows: `Consolas`
57    /// - Linux: `DejaVu Sans Mono`
58    ///
59    /// The default falls back to an installed monospace font, then to
60    /// `.SystemUIFont`, when the machine lacks it. A family named here is used
61    /// as-is, so name one that is installed or embedded with `add_fonts`.
62    #[serde(rename = "mono_font.family")]
63    pub mono_font_family: Option<SharedString>,
64    /// The monospace font size, default is 13.
65    #[serde(rename = "mono_font.size")]
66    pub mono_font_size: Option<f32>,
67
68    /// The border radius for general elements, default is 6.
69    #[serde(rename = "radius")]
70    pub radius: Option<usize>,
71    /// The border radius for large elements like Dialogs and Notifications, default is 8.
72    #[serde(rename = "radius.lg")]
73    pub radius_lg: Option<usize>,
74    /// The corner radius of client-decorated windows, default is 0.
75    #[serde(rename = "window.radius")]
76    pub window_radius: Option<usize>,
77    /// Set shadows in the theme, for example the Input and Button, default is true.
78    #[serde(rename = "shadow")]
79    pub shadow: Option<bool>,
80
81    /// The colors of the theme.
82    pub colors: ThemeConfigColors,
83    /// The highlight theme, this part is combilbility with `style` section in Zed theme.
84    ///
85    /// https://github.com/zed-industries/zed/blob/f50041779dcfd7a76c8aec293361c60c53f02d51/assets/themes/ayu/ayu.json#L9
86    pub highlight: Option<HighlightThemeStyle>,
87}
88
89#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
90#[serde(default)]
91#[non_exhaustive]
92pub struct SemanticThemeConfig {
93    pub colors: SemanticColorConfig,
94    pub radius: SemanticRadiusConfig,
95    pub spacing: SemanticSpacingConfig,
96    pub typography: SemanticTypographyConfig,
97    pub shadow: SemanticShadowConfig,
98}
99
100/// Standalone semantic theme configuration file.
101///
102/// This wrapper is intentionally separate from [`ThemeConfig`] so adding
103/// semantic tokens does not change the legacy public struct shape.
104#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
105#[serde(default)]
106#[non_exhaustive]
107pub struct SemanticThemeConfigFile {
108    pub tokens: SemanticThemeConfig,
109}
110
111#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
112#[serde(default)]
113#[non_exhaustive]
114pub struct SemanticColorConfig {
115    pub background: Option<SharedString>,
116    pub foreground: Option<SharedString>,
117    pub surface: Option<SharedString>,
118    pub surface_foreground: Option<SharedString>,
119    pub primary: Option<SharedString>,
120    pub primary_foreground: Option<SharedString>,
121    pub secondary: Option<SharedString>,
122    pub secondary_foreground: Option<SharedString>,
123    pub muted: Option<SharedString>,
124    pub muted_foreground: Option<SharedString>,
125    pub accent: Option<SharedString>,
126    pub accent_foreground: Option<SharedString>,
127    pub destructive: Option<SharedString>,
128    pub destructive_foreground: Option<SharedString>,
129    pub border: Option<SharedString>,
130    pub input: Option<SharedString>,
131    pub ring: Option<SharedString>,
132}
133
134#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
135#[serde(default)]
136#[non_exhaustive]
137pub struct SemanticRadiusConfig {
138    pub none: Option<f32>,
139    pub sm: Option<f32>,
140    pub md: Option<f32>,
141    pub lg: Option<f32>,
142    pub xl: Option<f32>,
143    pub full: Option<f32>,
144}
145
146#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
147#[serde(default)]
148#[non_exhaustive]
149pub struct SemanticSpacingConfig {
150    pub xxs: Option<f32>,
151    pub xs: Option<f32>,
152    pub sm: Option<f32>,
153    pub md: Option<f32>,
154    pub lg: Option<f32>,
155    pub xl: Option<f32>,
156    pub xxl: Option<f32>,
157}
158
159#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
160#[serde(default)]
161#[non_exhaustive]
162pub struct SemanticTextStyleConfig {
163    pub size: Option<f32>,
164    pub line_height: Option<f32>,
165    pub weight: Option<FontWeight>,
166}
167
168#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
169#[serde(default)]
170#[non_exhaustive]
171pub struct SemanticTypographyConfig {
172    pub sans: Option<SharedString>,
173    pub mono: Option<SharedString>,
174    pub xs: SemanticTextStyleConfig,
175    pub sm: SemanticTextStyleConfig,
176    pub md: SemanticTextStyleConfig,
177    pub lg: SemanticTextStyleConfig,
178    pub xl: SemanticTextStyleConfig,
179    pub mono_md: SemanticTextStyleConfig,
180}
181
182#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
183#[serde(default)]
184#[non_exhaustive]
185pub struct SemanticShadowConfig {
186    pub sm: Option<Vec<BoxShadow>>,
187    pub md: Option<Vec<BoxShadow>>,
188    pub lg: Option<Vec<BoxShadow>>,
189}
190
191impl SemanticThemeConfig {
192    pub(crate) fn apply_to(&self, tokens: &mut SemanticThemeTokens) {
193        macro_rules! apply_color {
194            ($field:ident) => {
195                if let Some(value) = &self.colors.$field
196                    && let Ok(value) = try_parse_color(value)
197                {
198                    tokens.colors.$field = value;
199                }
200            };
201        }
202        apply_color!(background);
203        apply_color!(foreground);
204        apply_color!(surface);
205        apply_color!(surface_foreground);
206        apply_color!(primary);
207        apply_color!(primary_foreground);
208        apply_color!(secondary);
209        apply_color!(secondary_foreground);
210        apply_color!(muted);
211        apply_color!(muted_foreground);
212        apply_color!(accent);
213        apply_color!(accent_foreground);
214        apply_color!(destructive);
215        apply_color!(destructive_foreground);
216        apply_color!(border);
217        apply_color!(input);
218        apply_color!(ring);
219
220        macro_rules! apply_pixels {
221            ($config:expr, $tokens:expr, $($field:ident),+ $(,)?) => {
222                $(if let Some(value) = $config.$field { $tokens.$field = px(value); })+
223            };
224        }
225        apply_pixels!(self.radius, tokens.radius, none, sm, md, lg, xl, full);
226        apply_pixels!(self.spacing, tokens.spacing, xxs, xs, sm, md, lg, xl, xxl);
227
228        if let Some(value) = &self.typography.sans {
229            tokens.typography.sans = value.clone();
230        }
231        if let Some(value) = &self.typography.mono {
232            tokens.typography.mono = value.clone();
233        }
234        apply_text_style(&self.typography.xs, &mut tokens.typography.xs);
235        apply_text_style(&self.typography.sm, &mut tokens.typography.sm);
236        apply_text_style(&self.typography.md, &mut tokens.typography.md);
237        apply_text_style(&self.typography.lg, &mut tokens.typography.lg);
238        apply_text_style(&self.typography.xl, &mut tokens.typography.xl);
239        apply_text_style(&self.typography.mono_md, &mut tokens.typography.mono_md);
240
241        if let Some(value) = &self.shadow.sm {
242            tokens.shadow.sm = value.clone();
243        }
244        if let Some(value) = &self.shadow.md {
245            tokens.shadow.md = value.clone();
246        }
247        if let Some(value) = &self.shadow.lg {
248            tokens.shadow.lg = value.clone();
249        }
250    }
251}
252
253fn apply_text_style(config: &SemanticTextStyleConfig, token: &mut gpui_base::TextStyleToken) {
254    if let Some(value) = config.size {
255        token.size = px(value);
256    }
257    if let Some(value) = config.line_height {
258        token.line_height = px(value);
259    }
260    if let Some(value) = config.weight {
261        token.weight = value;
262    }
263}
264
265#[derive(Debug, Default, Clone, JsonSchema, Serialize, Deserialize)]
266#[non_exhaustive]
267pub struct ThemeConfigColors {
268    /// Used for accents such as hover background on MenuItem, ListItem, etc.
269    #[serde(rename = "accent.background")]
270    pub accent: Option<SharedString>,
271    /// Used for accent text color.
272    #[serde(rename = "accent.foreground")]
273    pub accent_foreground: Option<SharedString>,
274    /// Accordion background color.
275    #[serde(rename = "accordion.background")]
276    pub accordion: Option<SharedString>,
277    /// Default background color.
278    #[serde(rename = "background")]
279    pub background: Option<SharedString>,
280    /// Default border color
281    #[serde(rename = "border")]
282    pub border: Option<SharedString>,
283    /// Default Button background color.
284    #[serde(rename = "button.background")]
285    pub button: Option<SharedString>,
286    /// Default Button active background color.
287    #[serde(rename = "button.active.background")]
288    pub button_active: Option<SharedString>,
289    /// Default Button text color.
290    #[serde(rename = "button.foreground")]
291    pub button_foreground: Option<SharedString>,
292    /// Default Button hover background color.
293    #[serde(rename = "button.hover.background")]
294    pub button_hover: Option<SharedString>,
295    /// Button danger background color, fallback to `danger`.
296    #[serde(rename = "button.danger.background")]
297    pub button_danger: Option<SharedString>,
298    /// Button danger active background color, fallback to `danger_active`.
299    #[serde(rename = "button.danger.active.background")]
300    pub button_danger_active: Option<SharedString>,
301    /// Button danger text color, fallback to `danger_foreground`.
302    #[serde(rename = "button.danger.foreground")]
303    pub button_danger_foreground: Option<SharedString>,
304    /// Button danger hover background color, fallback to `danger_hover`.
305    #[serde(rename = "button.danger.hover.background")]
306    pub button_danger_hover: Option<SharedString>,
307    /// Button info background color, fallback to `info`.
308    #[serde(rename = "button.info.background")]
309    pub button_info: Option<SharedString>,
310    /// Button info active background color, fallback to `info_active`.
311    #[serde(rename = "button.info.active.background")]
312    pub button_info_active: Option<SharedString>,
313    /// Button info text color, fallback to `info_foreground`.
314    #[serde(rename = "button.info.foreground")]
315    pub button_info_foreground: Option<SharedString>,
316    /// Button info hover background color, fallback to `info_hover`.
317    #[serde(rename = "button.info.hover.background")]
318    pub button_info_hover: Option<SharedString>,
319    /// Button primary background color, fallback to `primary`.
320    #[serde(rename = "button.primary.background")]
321    pub button_primary: Option<SharedString>,
322    /// Button primary active background color, fallback to `primary_active`.
323    #[serde(rename = "button.primary.active.background")]
324    pub button_primary_active: Option<SharedString>,
325    /// Button primary text color, fallback to `primary_foreground`.
326    #[serde(rename = "button.primary.foreground")]
327    pub button_primary_foreground: Option<SharedString>,
328    /// Button primary hover background color, fallback to `primary_hover`.
329    #[serde(rename = "button.primary.hover.background")]
330    pub button_primary_hover: Option<SharedString>,
331    /// Button secondary background color, fallback to `secondary`.
332    #[serde(rename = "button.secondary.background")]
333    pub button_secondary: Option<SharedString>,
334    /// Button secondary active background color, fallback to `secondary_active`.
335    #[serde(rename = "button.secondary.active.background")]
336    pub button_secondary_active: Option<SharedString>,
337    /// Button secondary text color, fallback to `secondary_foreground`.
338    #[serde(rename = "button.secondary.foreground")]
339    pub button_secondary_foreground: Option<SharedString>,
340    /// Button secondary hover background color, fallback to `secondary_hover`.
341    #[serde(rename = "button.secondary.hover.background")]
342    pub button_secondary_hover: Option<SharedString>,
343    /// Button success background color, fallback to `success`.
344    #[serde(rename = "button.success.background")]
345    pub button_success: Option<SharedString>,
346    /// Button success active background color, fallback to `success_active`.
347    #[serde(rename = "button.success.active.background")]
348    pub button_success_active: Option<SharedString>,
349    /// Button success text color, fallback to `success_foreground`.
350    #[serde(rename = "button.success.foreground")]
351    pub button_success_foreground: Option<SharedString>,
352    /// Button success hover background color, fallback to `success_hover`.
353    #[serde(rename = "button.success.hover.background")]
354    pub button_success_hover: Option<SharedString>,
355    /// Button warning background color, fallback to `warning`.
356    #[serde(rename = "button.warning.background")]
357    pub button_warning: Option<SharedString>,
358    /// Button warning active background color, fallback to `warning_active`.
359    #[serde(rename = "button.warning.active.background")]
360    pub button_warning_active: Option<SharedString>,
361    /// Button warning text color, fallback to `warning_foreground`.
362    #[serde(rename = "button.warning.foreground")]
363    pub button_warning_foreground: Option<SharedString>,
364    /// Button warning hover background color, fallback to `warning_hover`.
365    #[serde(rename = "button.warning.hover.background")]
366    pub button_warning_hover: Option<SharedString>,
367    /// Background color for GroupBox.
368    #[serde(rename = "group_box.background")]
369    pub group_box: Option<SharedString>,
370    /// Text color for GroupBox.
371    #[serde(rename = "group_box.foreground")]
372    pub group_box_foreground: Option<SharedString>,
373    /// Title text color for GroupBox.
374    #[serde(rename = "group_box.title.foreground")]
375    pub group_box_title_foreground: Option<SharedString>,
376    /// Input caret color (Blinking cursor).
377    #[serde(rename = "caret")]
378    pub caret: Option<SharedString>,
379    /// Chart 1 color.
380    #[serde(rename = "chart.1")]
381    pub chart_1: Option<SharedString>,
382    /// Chart 2 color.
383    #[serde(rename = "chart.2")]
384    pub chart_2: Option<SharedString>,
385    /// Chart 3 color.
386    #[serde(rename = "chart.3")]
387    pub chart_3: Option<SharedString>,
388    /// Chart 4 color.
389    #[serde(rename = "chart.4")]
390    pub chart_4: Option<SharedString>,
391    /// Chart 5 color.
392    #[serde(rename = "chart.5")]
393    pub chart_5: Option<SharedString>,
394    /// Bullish color for candlestick charts (upward price movement).
395    #[serde(rename = "chart.bullish")]
396    pub chart_bullish: Option<SharedString>,
397    /// Bearish color for candlestick charts (downward price movement).
398    #[serde(rename = "chart.bearish")]
399    pub chart_bearish: Option<SharedString>,
400    /// Chart grid line color.
401    #[serde(rename = "chart.grid")]
402    pub chart_grid: Option<SharedString>,
403    /// Danger background color.
404    #[serde(rename = "danger.background")]
405    pub danger: Option<SharedString>,
406    /// Danger active background color.
407    #[serde(rename = "danger.active.background")]
408    pub danger_active: Option<SharedString>,
409    /// Danger text color.
410    #[serde(rename = "danger.foreground")]
411    pub danger_foreground: Option<SharedString>,
412    /// Danger hover background color.
413    #[serde(rename = "danger.hover.background")]
414    pub danger_hover: Option<SharedString>,
415    /// Description List label background color.
416    #[serde(rename = "description_list.label.background")]
417    pub description_list_label: Option<SharedString>,
418    /// Description List label foreground color.
419    #[serde(rename = "description_list.label.foreground")]
420    pub description_list_label_foreground: Option<SharedString>,
421    /// Drag border color.
422    #[serde(rename = "drag.border")]
423    pub drag_border: Option<SharedString>,
424    /// Drop target background color.
425    #[serde(rename = "drop_target.background")]
426    pub drop_target: Option<SharedString>,
427    /// Default text color.
428    #[serde(rename = "foreground")]
429    pub foreground: Option<SharedString>,
430    /// Info background color.
431    #[serde(rename = "info.background")]
432    pub info: Option<SharedString>,
433    /// Info active background color.
434    #[serde(rename = "info.active.background")]
435    pub info_active: Option<SharedString>,
436    /// Info text color.
437    #[serde(rename = "info.foreground")]
438    pub info_foreground: Option<SharedString>,
439    /// Info hover background color.
440    #[serde(rename = "info.hover.background")]
441    pub info_hover: Option<SharedString>,
442    /// Border color for inputs such as Input, Select, etc.
443    #[serde(rename = "input.border")]
444    pub input: Option<SharedString>,
445    /// Link text color.
446    #[serde(rename = "link")]
447    pub link: Option<SharedString>,
448    /// Active link text color.
449    #[serde(rename = "link.active")]
450    pub link_active: Option<SharedString>,
451    /// Hover link text color.
452    #[serde(rename = "link.hover")]
453    pub link_hover: Option<SharedString>,
454    /// Background color for List and ListItem.
455    #[serde(rename = "list.background")]
456    pub list: Option<SharedString>,
457    /// Background color for active ListItem.
458    #[serde(rename = "list.active.background")]
459    pub list_active: Option<SharedString>,
460    /// Border color for active ListItem.
461    #[serde(rename = "list.active.border")]
462    pub list_active_border: Option<SharedString>,
463    /// Stripe background color for even ListItem.
464    #[serde(rename = "list.even.background")]
465    pub list_even: Option<SharedString>,
466    /// Background color for List header.
467    #[serde(rename = "list.head.background")]
468    pub list_head: Option<SharedString>,
469    /// Hover background color for ListItem.
470    #[serde(rename = "list.hover.background")]
471    pub list_hover: Option<SharedString>,
472    /// Text color for the part of a list row that matches the search query.
473    #[serde(rename = "list.highlight.foreground")]
474    pub list_highlight_foreground: Option<SharedString>,
475    /// Muted backgrounds such as Skeleton and Switch.
476    #[serde(rename = "muted.background")]
477    pub muted: Option<SharedString>,
478    /// Muted text color, as used in disabled text.
479    #[serde(rename = "muted.foreground")]
480    pub muted_foreground: Option<SharedString>,
481    /// Background color for Popover.
482    #[serde(rename = "popover.background")]
483    pub popover: Option<SharedString>,
484    /// Text color for Popover.
485    #[serde(rename = "popover.foreground")]
486    pub popover_foreground: Option<SharedString>,
487    /// Primary background color.
488    #[serde(rename = "primary.background")]
489    pub primary: Option<SharedString>,
490    /// Active primary background color.
491    #[serde(rename = "primary.active.background")]
492    pub primary_active: Option<SharedString>,
493    /// Primary text color.
494    #[serde(rename = "primary.foreground")]
495    pub primary_foreground: Option<SharedString>,
496    /// Hover primary background color.
497    #[serde(rename = "primary.hover.background")]
498    pub primary_hover: Option<SharedString>,
499    /// Progress bar background color.
500    #[serde(rename = "progress.bar.background")]
501    pub progress_bar: Option<SharedString>,
502    /// Used for focus ring.
503    #[serde(rename = "ring")]
504    pub ring: Option<SharedString>,
505    /// Scrollbar background color.
506    #[serde(rename = "scrollbar.background")]
507    pub scrollbar: Option<SharedString>,
508    /// Scrollbar thumb background color.
509    #[serde(rename = "scrollbar.thumb.background")]
510    pub scrollbar_thumb: Option<SharedString>,
511    /// Scrollbar thumb hover background color.
512    #[serde(rename = "scrollbar.thumb.hover.background")]
513    pub scrollbar_thumb_hover: Option<SharedString>,
514    /// Secondary background color.
515    #[serde(rename = "secondary.background")]
516    pub secondary: Option<SharedString>,
517    /// Active secondary background color.
518    #[serde(rename = "secondary.active.background")]
519    pub secondary_active: Option<SharedString>,
520    /// Secondary text color, used for secondary Button text color or secondary text.
521    #[serde(rename = "secondary.foreground")]
522    pub secondary_foreground: Option<SharedString>,
523    /// Hover secondary background color.
524    #[serde(rename = "secondary.hover.background")]
525    pub secondary_hover: Option<SharedString>,
526    /// Input selection background color.
527    #[serde(rename = "selection.background")]
528    pub selection: Option<SharedString>,
529    /// Sidebar background color.
530    #[serde(rename = "sidebar.background")]
531    pub sidebar: Option<SharedString>,
532    /// Sidebar accent background color.
533    #[serde(rename = "sidebar.accent.background")]
534    pub sidebar_accent: Option<SharedString>,
535    /// Sidebar accent text color.
536    #[serde(rename = "sidebar.accent.foreground")]
537    pub sidebar_accent_foreground: Option<SharedString>,
538    /// Sidebar border color.
539    #[serde(rename = "sidebar.border")]
540    pub sidebar_border: Option<SharedString>,
541    /// Sidebar text color.
542    #[serde(rename = "sidebar.foreground")]
543    pub sidebar_foreground: Option<SharedString>,
544    /// Sidebar primary background color.
545    #[serde(rename = "sidebar.primary.background")]
546    pub sidebar_primary: Option<SharedString>,
547    /// Sidebar primary text color.
548    #[serde(rename = "sidebar.primary.foreground")]
549    pub sidebar_primary_foreground: Option<SharedString>,
550    /// Skeleton background color.
551    #[serde(rename = "skeleton.background")]
552    pub skeleton: Option<SharedString>,
553    /// Slider bar background color.
554    #[serde(rename = "slider.background")]
555    pub slider_bar: Option<SharedString>,
556    /// Slider thumb background color.
557    #[serde(rename = "slider.thumb.background")]
558    pub slider_thumb: Option<SharedString>,
559    /// Success background color.
560    #[serde(rename = "success.background")]
561    pub success: Option<SharedString>,
562    /// Success text color.
563    #[serde(rename = "success.foreground")]
564    pub success_foreground: Option<SharedString>,
565    /// Success hover background color.
566    #[serde(rename = "success.hover.background")]
567    pub success_hover: Option<SharedString>,
568    /// Success active background color.
569    #[serde(rename = "success.active.background")]
570    pub success_active: Option<SharedString>,
571    /// Switch background color.
572    #[serde(rename = "switch.background")]
573    pub switch: Option<SharedString>,
574    /// Switch thumb background color.
575    #[serde(rename = "switch.thumb.background")]
576    pub switch_thumb: Option<SharedString>,
577    /// Tab background color.
578    #[serde(rename = "tab.background")]
579    pub tab: Option<SharedString>,
580    /// Tab active background color.
581    #[serde(rename = "tab.active.background")]
582    pub tab_active: Option<SharedString>,
583    /// Tab active text color.
584    #[serde(rename = "tab.active.foreground")]
585    pub tab_active_foreground: Option<SharedString>,
586    /// TabBar background color.
587    #[serde(rename = "tab_bar.background")]
588    pub tab_bar: Option<SharedString>,
589    /// TabBar segmented background color.
590    #[serde(rename = "tab_bar.segmented.background")]
591    pub tab_bar_segmented: Option<SharedString>,
592    /// Tab text color.
593    #[serde(rename = "tab.foreground")]
594    pub tab_foreground: Option<SharedString>,
595    /// Table background color.
596    #[serde(rename = "table.background")]
597    pub table: Option<SharedString>,
598    /// Table active item background color.
599    #[serde(rename = "table.active.background")]
600    pub table_active: Option<SharedString>,
601    /// Table active item border color.
602    #[serde(rename = "table.active.border")]
603    pub table_active_border: Option<SharedString>,
604    /// Stripe background color for even TableRow.
605    #[serde(rename = "table.even.background")]
606    pub table_even: Option<SharedString>,
607    /// Table header background color.
608    #[serde(rename = "table.head.background")]
609    pub table_head: Option<SharedString>,
610    /// Table header text color.
611    #[serde(rename = "table.head.foreground")]
612    pub table_head_foreground: Option<SharedString>,
613    /// Table footer background color.
614    #[serde(rename = "table.foot.background")]
615    pub table_foot: Option<SharedString>,
616    /// Table footer text color.
617    #[serde(rename = "table.foot.foreground")]
618    pub table_foot_foreground: Option<SharedString>,
619    /// Table item hover background color.
620    #[serde(rename = "table.hover.background")]
621    pub table_hover: Option<SharedString>,
622    /// Table row border color.
623    #[serde(rename = "table.row.border")]
624    pub table_row_border: Option<SharedString>,
625    /// TitleBar background color, use for Window title bar.
626    #[serde(rename = "title_bar.background")]
627    pub title_bar: Option<SharedString>,
628    /// TitleBar border color.
629    #[serde(rename = "title_bar.border")]
630    pub title_bar_border: Option<SharedString>,
631    /// StatusBar background color, use for the bottom status bar.
632    #[serde(rename = "status_bar.background")]
633    pub status_bar: Option<SharedString>,
634    /// StatusBar border color.
635    #[serde(rename = "status_bar.border")]
636    pub status_bar_border: Option<SharedString>,
637    /// Warning background color.
638    #[serde(rename = "warning.background")]
639    pub warning: Option<SharedString>,
640    /// Warning active background color.
641    #[serde(rename = "warning.active.background")]
642    pub warning_active: Option<SharedString>,
643    /// Warning hover background color.
644    #[serde(rename = "warning.hover.background")]
645    pub warning_hover: Option<SharedString>,
646    /// Warning foreground color.
647    #[serde(rename = "warning.foreground")]
648    pub warning_foreground: Option<SharedString>,
649    /// Overlay background color.
650    #[serde(rename = "overlay")]
651    pub overlay: Option<SharedString>,
652    /// Window border color.
653    ///
654    /// # Platform specific:
655    ///
656    /// This is only works on Linux, other platforms we can't change the window border color.
657    #[serde(rename = "window.border")]
658    pub window_border: Option<SharedString>,
659
660    /// Base blue color.
661    #[serde(rename = "base.blue")]
662    blue: Option<String>,
663    /// Base light blue color.
664    #[serde(rename = "base.blue.light")]
665    blue_light: Option<String>,
666    /// Base cyan color.
667    #[serde(rename = "base.cyan")]
668    cyan: Option<String>,
669    /// Base light cyan color.
670    #[serde(rename = "base.cyan.light")]
671    cyan_light: Option<String>,
672    /// Base green color.
673    #[serde(rename = "base.green")]
674    green: Option<String>,
675    /// Base light green color.
676    #[serde(rename = "base.green.light")]
677    green_light: Option<String>,
678    /// Base magenta color.
679    #[serde(rename = "base.magenta")]
680    magenta: Option<String>,
681    #[serde(rename = "base.magenta.light")]
682    magenta_light: Option<String>,
683    /// Base red color.
684    #[serde(rename = "base.red")]
685    red: Option<String>,
686    /// Base light red color.
687    #[serde(rename = "base.red.light")]
688    red_light: Option<String>,
689    /// Base yellow color.
690    #[serde(rename = "base.yellow")]
691    yellow: Option<String>,
692    /// Base light yellow color.
693    #[serde(rename = "base.yellow.light")]
694    yellow_light: Option<String>,
695}
696
697impl ThemeColor {
698    /// Create a new `ThemeColor` from a `ThemeConfig`.
699    pub(crate) fn apply_config(
700        &mut self,
701        config: &ThemeConfig,
702        default_theme: &ThemeColor,
703    ) -> ThemeTokens {
704        let colors = config.colors.clone();
705        let default_tokens = ThemeTokens::from(default_theme);
706        let mut tokens = default_tokens;
707
708        macro_rules! apply_color {
709            ($config_field:ident) => {
710                if let Some(value) = &colors.$config_field {
711                    self.$config_field =
712                        try_parse_color(value).unwrap_or(default_theme.$config_field);
713                } else {
714                    self.$config_field = default_theme.$config_field;
715                }
716                tokens.$config_field = self.$config_field.into();
717            };
718            // With fallback
719            ($config_field:ident, fallback = $fallback:expr) => {
720                let fallback: gpui::Hsla = ($fallback).into();
721                if let Some(value) = &colors.$config_field {
722                    self.$config_field = try_parse_color(value).unwrap_or(fallback);
723                } else {
724                    self.$config_field = fallback;
725                }
726                tokens.$config_field = self.$config_field.into();
727            };
728        }
729
730        macro_rules! apply_background_color {
731            ($config_field:ident) => {
732                let token = if let Some(value) = &colors.$config_field {
733                    if let Ok(token) = try_parse_theme_token(&value) {
734                        token
735                    } else {
736                        default_tokens.$config_field
737                    }
738                } else {
739                    default_tokens.$config_field
740                };
741                self.$config_field = token.color;
742                tokens.$config_field = token;
743            };
744            ($config_field:ident, fallback = $fallback:expr) => {
745                let fallback: ThemeToken = ($fallback).into();
746                let token = if let Some(value) = &colors.$config_field {
747                    if let Ok(token) = try_parse_theme_token(&value) {
748                        token
749                    } else {
750                        fallback
751                    }
752                } else {
753                    fallback
754                };
755                self.$config_field = token.color;
756                tokens.$config_field = token;
757            };
758        }
759
760        apply_background_color!(background);
761
762        // Base colors for fallback
763        apply_color!(red);
764        apply_color!(
765            red_light,
766            fallback = self.background.blend(self.red.opacity(0.8))
767        );
768        apply_color!(green);
769        apply_color!(
770            green_light,
771            fallback = self.background.blend(self.green.opacity(0.8))
772        );
773        apply_color!(blue);
774        apply_color!(
775            blue_light,
776            fallback = self.background.blend(self.blue.opacity(0.8))
777        );
778        apply_color!(magenta);
779        apply_color!(
780            magenta_light,
781            fallback = self.background.blend(self.magenta.opacity(0.8))
782        );
783        apply_color!(yellow);
784        apply_color!(
785            yellow_light,
786            fallback = self.background.blend(self.yellow.opacity(0.8))
787        );
788        apply_color!(cyan);
789        apply_color!(
790            cyan_light,
791            fallback = self.background.blend(self.cyan.opacity(0.8))
792        );
793
794        apply_color!(border);
795        apply_color!(foreground);
796        apply_color!(input, fallback = self.border);
797        apply_background_color!(muted);
798        apply_color!(
799            muted_foreground,
800            fallback = self.muted.blend(self.foreground.opacity(0.7))
801        );
802
803        // Button colors
804        let active_darken = if config.mode.is_dark() { 0.2 } else { 0.1 };
805        let hover_opacity = 0.9;
806        let transparent = gpui::transparent_black();
807        let button_background = if config.mode.is_dark() {
808            self.input.mix_oklab(transparent, 0.3)
809        } else {
810            self.background
811        };
812        apply_background_color!(button, fallback = button_background);
813        apply_color!(button_foreground, fallback = self.foreground);
814        apply_background_color!(
815            button_hover,
816            fallback = self.input.mix_oklab(transparent, 0.5)
817        );
818        apply_background_color!(
819            button_active,
820            fallback = self.input.mix_oklab(transparent, 0.7)
821        );
822        apply_background_color!(primary);
823        apply_color!(primary_foreground, fallback = self.foreground);
824        apply_background_color!(
825            primary_hover,
826            fallback = self.background.blend(self.primary.opacity(hover_opacity))
827        );
828        apply_background_color!(
829            primary_active,
830            fallback = self.primary.darken(active_darken)
831        );
832        apply_background_color!(button_primary, fallback = tokens.primary);
833        apply_color!(
834            button_primary_foreground,
835            fallback = self.primary_foreground
836        );
837        apply_background_color!(button_primary_hover, fallback = tokens.primary_hover);
838        apply_background_color!(button_primary_active, fallback = tokens.primary_active);
839        apply_background_color!(secondary);
840        apply_color!(secondary_foreground, fallback = self.foreground);
841        apply_background_color!(
842            secondary_hover,
843            fallback = self.background.blend(self.secondary.opacity(hover_opacity))
844        );
845        apply_background_color!(
846            secondary_active,
847            fallback = self.secondary.darken(active_darken)
848        );
849        apply_background_color!(button_secondary, fallback = tokens.secondary);
850        apply_color!(
851            button_secondary_foreground,
852            fallback = self.secondary_foreground
853        );
854        apply_background_color!(button_secondary_hover, fallback = tokens.secondary_hover);
855        apply_background_color!(button_secondary_active, fallback = tokens.secondary_active);
856        apply_background_color!(success, fallback = self.green);
857        apply_color!(success_foreground, fallback = self.primary_foreground);
858        apply_background_color!(
859            success_hover,
860            fallback = self.background.blend(self.success.opacity(hover_opacity))
861        );
862        apply_background_color!(
863            success_active,
864            fallback = self.success.darken(active_darken)
865        );
866        apply_background_color!(
867            button_success,
868            fallback = self.success.mix_oklab(transparent, 0.2)
869        );
870        apply_color!(button_success_foreground, fallback = self.success);
871        apply_background_color!(
872            button_success_hover,
873            fallback = self.success.mix_oklab(transparent, 0.3)
874        );
875        apply_background_color!(
876            button_success_active,
877            fallback = self.success.mix_oklab(transparent, 0.4)
878        );
879        apply_background_color!(info, fallback = self.cyan);
880        apply_color!(info_foreground, fallback = self.primary_foreground);
881        apply_background_color!(
882            info_hover,
883            fallback = self.background.blend(self.info.opacity(hover_opacity))
884        );
885        apply_background_color!(info_active, fallback = self.info.darken(active_darken));
886        apply_background_color!(
887            button_info,
888            fallback = self.info.mix_oklab(transparent, 0.2)
889        );
890        apply_color!(button_info_foreground, fallback = self.info);
891        apply_background_color!(
892            button_info_hover,
893            fallback = self.info.mix_oklab(transparent, 0.3)
894        );
895        apply_background_color!(
896            button_info_active,
897            fallback = self.info.mix_oklab(transparent, 0.4)
898        );
899        apply_background_color!(warning, fallback = self.yellow);
900        apply_color!(warning_foreground, fallback = self.primary_foreground);
901        apply_background_color!(
902            warning_hover,
903            fallback = self.background.blend(self.warning.opacity(0.9))
904        );
905        apply_background_color!(
906            warning_active,
907            fallback = self.background.blend(self.warning.darken(active_darken))
908        );
909        apply_background_color!(
910            button_warning,
911            fallback = self.warning.mix_oklab(transparent, 0.2)
912        );
913        apply_color!(button_warning_foreground, fallback = self.warning);
914        apply_background_color!(
915            button_warning_hover,
916            fallback = self.warning.mix_oklab(transparent, 0.3)
917        );
918        apply_background_color!(
919            button_warning_active,
920            fallback = self.warning.mix_oklab(transparent, 0.4)
921        );
922
923        // Other colors
924        apply_background_color!(accent, fallback = tokens.secondary);
925        apply_color!(accent_foreground, fallback = self.foreground);
926        apply_background_color!(accordion, fallback = tokens.background);
927        apply_background_color!(
928            group_box,
929            fallback = self
930                .background
931                .blend(
932                    self.secondary
933                        .opacity(if config.mode.is_dark() { 0.3 } else { 0.4 })
934                )
935        );
936        apply_color!(group_box_foreground, fallback = self.foreground);
937        apply_color!(caret, fallback = self.primary);
938        apply_color!(chart_1, fallback = self.blue.lighten(0.4));
939        apply_color!(chart_2, fallback = self.blue.lighten(0.2));
940        apply_color!(chart_3, fallback = self.blue);
941        apply_color!(chart_4, fallback = self.blue.darken(0.2));
942        apply_color!(chart_5, fallback = self.blue.darken(0.4));
943        apply_color!(chart_bullish, fallback = self.green);
944        apply_color!(chart_bearish, fallback = self.red);
945        apply_color!(chart_grid, fallback = self.border.opacity(0.6));
946        apply_background_color!(danger, fallback = self.red);
947        apply_background_color!(danger_active, fallback = self.danger.darken(active_darken));
948        apply_color!(danger_foreground, fallback = self.primary_foreground);
949        apply_background_color!(
950            danger_hover,
951            fallback = self.background.blend(self.danger.opacity(0.9))
952        );
953        apply_background_color!(
954            button_danger,
955            fallback = self.danger.mix_oklab(transparent, 0.2)
956        );
957        apply_color!(button_danger_foreground, fallback = self.danger);
958        apply_background_color!(
959            button_danger_hover,
960            fallback = self.danger.mix_oklab(transparent, 0.3)
961        );
962        apply_background_color!(
963            button_danger_active,
964            fallback = self.danger.mix_oklab(transparent, 0.4)
965        );
966        apply_background_color!(
967            description_list_label,
968            fallback = self.background.blend(self.border.opacity(0.2))
969        );
970        apply_color!(
971            description_list_label_foreground,
972            fallback = self.muted_foreground
973        );
974        apply_color!(drag_border, fallback = self.primary.opacity(0.65));
975        apply_background_color!(drop_target, fallback = self.primary.opacity(0.2));
976        apply_color!(link, fallback = self.primary);
977        apply_color!(link_active, fallback = self.link);
978        apply_color!(link_hover, fallback = self.link);
979        apply_background_color!(list, fallback = tokens.background);
980        apply_background_color!(
981            list_active,
982            fallback = self.background.blend(self.primary.opacity(0.1))
983        );
984        apply_color!(
985            list_active_border,
986            fallback = self.background.blend(self.primary.opacity(0.6))
987        );
988        apply_background_color!(list_even, fallback = tokens.list);
989        apply_background_color!(list_head, fallback = tokens.list);
990        apply_background_color!(list_hover, fallback = self.accent.opacity(0.6));
991        apply_color!(list_highlight_foreground, fallback = self.blue);
992        apply_background_color!(popover, fallback = tokens.background);
993        apply_color!(popover_foreground, fallback = self.foreground);
994        apply_background_color!(progress_bar, fallback = tokens.primary);
995        apply_color!(ring, fallback = self.blue);
996        apply_background_color!(scrollbar, fallback = tokens.background);
997        apply_background_color!(scrollbar_thumb, fallback = tokens.accent);
998        apply_background_color!(scrollbar_thumb_hover, fallback = tokens.scrollbar_thumb);
999        apply_background_color!(selection, fallback = tokens.primary);
1000        apply_background_color!(
1001            sidebar,
1002            fallback = self.background.blend(self.border.opacity(0.15))
1003        );
1004        apply_background_color!(sidebar_accent, fallback = tokens.accent);
1005        apply_color!(sidebar_accent_foreground, fallback = self.accent_foreground);
1006        apply_color!(sidebar_border, fallback = self.border);
1007        apply_color!(sidebar_foreground, fallback = self.foreground);
1008        apply_background_color!(sidebar_primary, fallback = tokens.primary);
1009        apply_color!(
1010            sidebar_primary_foreground,
1011            fallback = self.primary_foreground
1012        );
1013        apply_background_color!(skeleton, fallback = tokens.secondary);
1014        apply_background_color!(slider_bar, fallback = tokens.primary);
1015        apply_background_color!(slider_thumb, fallback = self.primary_foreground);
1016        apply_background_color!(switch, fallback = tokens.secondary_active);
1017        apply_background_color!(switch_thumb, fallback = tokens.background);
1018        apply_background_color!(tab, fallback = tokens.background);
1019        apply_background_color!(tab_active, fallback = tokens.background);
1020        apply_color!(tab_active_foreground, fallback = self.foreground);
1021        apply_background_color!(tab_bar, fallback = tokens.background);
1022        apply_background_color!(tab_bar_segmented, fallback = tokens.secondary);
1023        apply_color!(tab_foreground, fallback = self.foreground);
1024        apply_background_color!(table, fallback = tokens.list);
1025        apply_background_color!(table_active, fallback = tokens.list_active);
1026        apply_color!(table_active_border, fallback = self.list_active_border);
1027        apply_background_color!(table_even, fallback = tokens.list_even);
1028        apply_background_color!(table_head, fallback = tokens.list_head);
1029        apply_color!(table_head_foreground, fallback = self.muted_foreground);
1030        apply_background_color!(table_foot, fallback = tokens.list_head);
1031        apply_color!(table_foot_foreground, fallback = self.muted_foreground);
1032        apply_background_color!(table_hover, fallback = tokens.list_hover);
1033        apply_color!(table_row_border, fallback = self.border);
1034        apply_background_color!(title_bar, fallback = tokens.background);
1035        apply_color!(title_bar_border, fallback = self.border);
1036        apply_background_color!(status_bar, fallback = tokens.title_bar);
1037        apply_color!(status_bar_border, fallback = self.title_bar_border);
1038        apply_background_color!(overlay);
1039        apply_color!(window_border, fallback = self.border);
1040
1041        // TODO: Apply default fallback colors to highlight.
1042
1043        // Ensure opacity for list_active, table_active, selection.
1044        let clamp_alpha = |raw: Option<&str>, color: Hsla, background: Background, max: f32| {
1045            let base = color.a;
1046            let target = base.min(max);
1047            let color = color.alpha(target);
1048            let background = raw
1049                .and_then(|value| try_parse_background_clamped(value, max).ok())
1050                .unwrap_or_else(|| {
1051                    let factor = if base > 0. { target / base } else { 1. };
1052                    background.opacity(factor)
1053                });
1054            (color, ThemeToken::new(color, background))
1055        };
1056
1057        (self.list_active, tokens.list_active) = clamp_alpha(
1058            colors.list_active.as_deref(),
1059            self.list_active,
1060            tokens.list_active.background,
1061            0.2,
1062        );
1063        (self.table_active, tokens.table_active) = clamp_alpha(
1064            colors.table_active.as_deref(),
1065            self.table_active,
1066            tokens.table_active.background,
1067            0.2,
1068        );
1069        (self.selection, tokens.selection) = clamp_alpha(
1070            colors.selection.as_deref(),
1071            self.selection,
1072            tokens.selection.background,
1073            0.3,
1074        );
1075
1076        tokens
1077    }
1078}
1079
1080impl Theme {
1081    /// Apply the given theme configuration to the current theme.
1082    pub fn apply_config(&mut self, config: &Rc<ThemeConfig>) {
1083        if config.mode.is_dark() {
1084            self.dark_theme = config.clone();
1085        } else {
1086            self.light_theme = config.clone();
1087        }
1088        if let Some(style) = &config.highlight {
1089            let highlight_theme = Arc::new(HighlightTheme {
1090                name: config.name.to_string(),
1091                appearance: config.mode,
1092                style: style.clone(),
1093            });
1094            self.highlight_theme = highlight_theme;
1095        }
1096
1097        let default_colors = if config.mode.is_dark() {
1098            ThemeColor::dark()
1099        } else {
1100            ThemeColor::light()
1101        };
1102
1103        if let Some(font_size) = config.font_size {
1104            self.font_size = px(font_size);
1105        }
1106        if let Some(font_family) = &config.font_family {
1107            self.font_family = font_family.clone();
1108        }
1109        if let Some(mono_font_family) = &config.mono_font_family {
1110            self.mono_font_family = mono_font_family.clone();
1111        }
1112        if let Some(mono_font_size) = config.mono_font_size {
1113            self.mono_font_size = px(mono_font_size);
1114        }
1115        if let Some(radius) = config.radius {
1116            self.radius = px(radius as f32);
1117        }
1118        if let Some(radius_lg) = config.radius_lg {
1119            self.radius_lg = px(radius_lg as f32);
1120        }
1121        if let Some(window_radius) = config.window_radius {
1122            self.window_radius = px(window_radius as f32);
1123        }
1124        if let Some(shadow) = config.shadow {
1125            self.shadow = shadow;
1126        }
1127
1128        self.tokens = self.colors.apply_config(&config, &default_colors);
1129        self.mode = config.mode;
1130    }
1131}
1132
1133#[cfg(test)]
1134mod tests {
1135    use gpui::{linear_color_stop, linear_gradient, px};
1136
1137    use crate::{Colorize as _, Theme, ThemeConfig, ThemeMode, ThemeSet, try_parse_color};
1138
1139    #[test]
1140    fn test_semantic_theme_config_parses_and_roundtrips() {
1141        let value = serde_json::json!({
1142            "name": "Semantic",
1143            "mode": "dark",
1144            "tokens": {
1145                "colors": {
1146                    "surface": "#111827",
1147                    "surface_foreground": "#f9fafb",
1148                    "primary": "#2563eb",
1149                    "destructive": "#dc2626"
1150                },
1151                "radius": { "sm": 2.0, "md": 6.0, "lg": 10.0 },
1152                "spacing": { "xs": 4.0, "md": 12.0, "xl": 24.0 },
1153                "typography": {
1154                    "sans": "Inter",
1155                    "md": { "size": 15.0, "line_height": 22.0 }
1156                }
1157            }
1158        });
1159        let config: super::SemanticThemeConfigFile = serde_json::from_value(value).unwrap();
1160        let serialized = serde_json::to_string(&config).unwrap();
1161        let reparsed: super::SemanticThemeConfigFile = serde_json::from_str(&serialized).unwrap();
1162        let semantic = reparsed.tokens;
1163
1164        assert_eq!(semantic.colors.surface.as_deref(), Some("#111827"));
1165        assert_eq!(semantic.colors.destructive.as_deref(), Some("#dc2626"));
1166        assert_eq!(semantic.radius.lg, Some(10.0));
1167        assert_eq!(semantic.spacing.xl, Some(24.0));
1168        assert_eq!(semantic.typography.sans.as_deref(), Some("Inter"));
1169        assert_eq!(semantic.typography.md.line_height, Some(22.0));
1170
1171        let mut theme = Theme::default();
1172        let resolved = theme.apply_semantic_config_str(&serialized).unwrap();
1173        assert_eq!(theme.primary, try_parse_color("#2563eb").unwrap());
1174        assert_eq!(resolved.spacing.xl, px(24.));
1175        assert_eq!(resolved.typography.md.line_height, px(22.));
1176    }
1177
1178    #[test]
1179    fn test_semantic_tokens_override_legacy_generic_fields_only() {
1180        let config = serde_json::from_value::<super::SemanticThemeConfigFile>(serde_json::json!({
1181            "tokens": {
1182                "colors": { "primary": "#2563eb", "destructive": "#b91c1c" },
1183                "spacing": { "md": 14.0 },
1184                "typography": { "md": { "size": 15.0 } }
1185            }
1186        }))
1187        .unwrap();
1188        let mut theme = Theme::default();
1189        let component_color = theme.button_primary;
1190        let resolved = theme.apply_semantic_config(&config.tokens);
1191
1192        assert_eq!(theme.primary, try_parse_color("#2563eb").unwrap());
1193        assert_eq!(theme.danger, try_parse_color("#b91c1c").unwrap());
1194        assert_eq!(theme.button_primary, component_color);
1195        assert_eq!(resolved.spacing.md, px(14.));
1196        assert_eq!(resolved.typography.md.size, px(15.));
1197    }
1198
1199    #[test]
1200    fn test_legacy_config_without_semantic_tokens_is_unchanged() {
1201        let config = serde_json::from_value::<ThemeConfig>(serde_json::json!({
1202            "name": "Legacy",
1203            "mode": "light",
1204            "radius": 7,
1205            "colors": { "primary.background": "#7c3aed" }
1206        }))
1207        .unwrap();
1208        let mut theme = Theme::default();
1209        theme.apply_config(&std::rc::Rc::new(config));
1210        assert_eq!(theme.primary, try_parse_color("#7c3aed").unwrap());
1211        assert_eq!(theme.radius, px(7.));
1212        assert_eq!(theme.semantic_tokens().spacing, Default::default());
1213    }
1214
1215    #[test]
1216    fn test_apply_config_reads_the_window_radius() {
1217        let config = serde_json::from_value::<ThemeConfig>(serde_json::json!({
1218            "name": "Rounded",
1219            "mode": "dark",
1220            "window.radius": 10
1221        }))
1222        .unwrap();
1223        let mut theme = Theme::default();
1224        assert_eq!(theme.window_radius, px(0.));
1225        theme.apply_config(&std::rc::Rc::new(config));
1226        assert_eq!(theme.window_radius, px(10.));
1227    }
1228
1229    #[test]
1230    fn test_apply_config_reads_the_chart_colors() {
1231        let config = serde_json::from_value::<ThemeConfig>(serde_json::json!({
1232            "name": "Palette",
1233            "mode": "light",
1234            "colors": {
1235                "chart.1": "#111111",
1236                "chart.2": "not a color",
1237                "chart.3": "#333333",
1238                "chart.bullish": "#00ff00",
1239                "chart.bearish": "#ff0000",
1240                "chart.grid": "#eeeeee"
1241            }
1242        }))
1243        .unwrap();
1244
1245        let mut theme = Theme::default();
1246        theme.apply_config(&std::rc::Rc::new(config));
1247
1248        // The keys match the fields; an unparsable or missing one falls back
1249        // to the ramp of the base blue.
1250        assert_eq!(theme.chart_1, try_parse_color("#111111").unwrap());
1251        assert_eq!(theme.chart_2, theme.blue.lighten(0.2));
1252        assert_eq!(theme.chart_3, try_parse_color("#333333").unwrap());
1253        assert_eq!(theme.chart_4, theme.blue.darken(0.2));
1254        assert_eq!(theme.chart_5, theme.blue.darken(0.4));
1255        assert_eq!(theme.tokens.chart_3.color, theme.chart_3);
1256        assert_eq!(theme.chart_bullish, try_parse_color("#00ff00").unwrap());
1257        assert_eq!(theme.chart_bearish, try_parse_color("#ff0000").unwrap());
1258        assert_eq!(theme.chart_grid, try_parse_color("#eeeeee").unwrap());
1259
1260        theme.apply_config(&std::rc::Rc::new(ThemeConfig::default()));
1261        assert_eq!(theme.chart_grid, theme.border.opacity(0.6));
1262    }
1263
1264    #[test]
1265    fn test_apply_config_reads_the_list_highlight_foreground_color() {
1266        let config = serde_json::from_value::<ThemeConfig>(serde_json::json!({
1267            "name": "Highlight",
1268            "mode": "light",
1269            "colors": {
1270                "list.highlight.foreground": "#ff8800"
1271            }
1272        }))
1273        .unwrap();
1274
1275        let mut theme = Theme::default();
1276        theme.apply_config(&std::rc::Rc::new(config));
1277        assert_eq!(
1278            theme.list_highlight_foreground,
1279            try_parse_color("#ff8800").unwrap()
1280        );
1281
1282        theme.apply_config(&std::rc::Rc::new(ThemeConfig::default()));
1283        assert_eq!(theme.list_highlight_foreground, theme.blue);
1284    }
1285
1286    #[test]
1287    fn test_apply_config_preserves_gradient_background_and_solid_color_fallback() {
1288        let config = serde_json::from_value::<ThemeConfig>(serde_json::json!({
1289            "name": "Gradient",
1290            "mode": "light",
1291            "colors": {
1292                "primary.background": "linear-gradient(135deg, #4F46E5, #06B6D4)",
1293                "button.primary.hover.background": "linear-gradient(to right, red-500 25%, blue-600 75%)"
1294            }
1295        }))
1296        .unwrap();
1297
1298        let mut theme = Theme::default();
1299        theme.apply_config(&std::rc::Rc::new(config));
1300
1301        let primary_from = try_parse_color("#4F46E5").unwrap();
1302        let primary_to = try_parse_color("#06B6D4").unwrap();
1303        assert_eq!(theme.primary, primary_from);
1304        assert_eq!(theme.tokens.primary.color, primary_from);
1305        assert_eq!(
1306            theme.tokens.primary.background,
1307            linear_gradient(
1308                135.,
1309                linear_color_stop(primary_from, 0.),
1310                linear_color_stop(primary_to, 1.)
1311            )
1312        );
1313        assert_eq!(
1314            theme.tokens.button_primary.background,
1315            theme.tokens.primary.background
1316        );
1317        assert_eq!(
1318            theme.tokens.button_primary_hover.background,
1319            linear_gradient(
1320                90.,
1321                linear_color_stop(crate::red_500(), 0.25),
1322                linear_color_stop(crate::blue_600(), 0.75)
1323            )
1324        );
1325        assert_eq!(theme.mode, ThemeMode::Light);
1326    }
1327
1328    #[test]
1329    fn test_aurora_theme_parses_gradient_backgrounds() {
1330        let theme_set =
1331            serde_json::from_str::<ThemeSet>(include_str!("../../../../themes/aurora.json"))
1332                .unwrap();
1333        assert_eq!(theme_set.themes.len(), 1);
1334        assert!(theme_set.themes.iter().all(|theme| !theme.mode.is_dark()));
1335
1336        let light = theme_set
1337            .themes
1338            .iter()
1339            .find(|theme| theme.name.as_ref() == "Aurora Light")
1340            .unwrap();
1341        let mut theme = Theme::default();
1342        theme.apply_config(&std::rc::Rc::new(light.clone()));
1343
1344        assert_ne!(
1345            theme.tokens.button_primary.background,
1346            theme.button_primary.into()
1347        );
1348        assert_eq!(theme.tokens.background.background, theme.background.into());
1349        assert_eq!(theme.button_primary, try_parse_color("#1E293B").unwrap());
1350        assert_eq!(theme.background, try_parse_color("#FFFFFF").unwrap());
1351        assert_ne!(
1352            theme.tokens.progress_bar.background,
1353            theme.progress_bar.into()
1354        );
1355        assert_ne!(
1356            theme.tokens.scrollbar_thumb.background,
1357            theme.scrollbar_thumb.into()
1358        );
1359        assert_ne!(theme.tokens.switch.background, theme.switch.into());
1360        assert_ne!(
1361            theme.tokens.switch_thumb.background,
1362            theme.switch_thumb.into()
1363        );
1364        assert_ne!(theme.tokens.title_bar.background, theme.title_bar.into());
1365        assert_ne!(theme.tokens.status_bar.background, theme.status_bar.into());
1366    }
1367
1368    #[test]
1369    fn test_apply_config_clamps_highlight_alpha_per_gradient_stop() {
1370        let config = serde_json::from_value::<ThemeConfig>(serde_json::json!({
1371            "name": "Highlight",
1372            "mode": "light",
1373            "colors": {
1374                // Solid above the cap: must be capped to 0.2, not attenuated twice.
1375                "list.active.background": "#3b82f6",
1376                // Gradient with a faint `from` stop and an opaque `to` stop: the
1377                // `to` stop must be clamped independently, not left at full alpha.
1378                "table.active.background": "linear-gradient(#bfdbfe33, #3b82f6)",
1379                // Gradient with a transparent `from` stop: the opaque `to` stop
1380                // must still be clamped (the `base == 0` factor fallback used to
1381                // leave it untouched).
1382                "selection.background": "linear-gradient(#3b82f600, #3b82f6)",
1383            }
1384        }))
1385        .unwrap();
1386
1387        let mut theme = Theme::default();
1388        theme.apply_config(&std::rc::Rc::new(config));
1389
1390        // Solid: representative color and rendered background both capped at 0.2.
1391        let blue = try_parse_color("#3b82f6").unwrap();
1392        assert_eq!(theme.list_active, blue.alpha(0.2));
1393        assert_eq!(theme.tokens.list_active.background, blue.alpha(0.2).into());
1394
1395        // Gradient: the opaque `to` stop is clamped to 0.2, not left fully opaque.
1396        let faint = try_parse_color("#bfdbfe33").unwrap();
1397        assert_eq!(
1398            theme.tokens.table_active.background,
1399            linear_gradient(
1400                180.,
1401                linear_color_stop(faint.alpha(faint.a.min(0.2)), 0.),
1402                linear_color_stop(blue.alpha(0.2), 1.),
1403            )
1404        );
1405
1406        // Gradient: a transparent `from` stop stays transparent while the opaque
1407        // `to` stop is still clamped to 0.3 (selection cap).
1408        let clear = try_parse_color("#3b82f600").unwrap();
1409        assert_eq!(
1410            theme.tokens.selection.background,
1411            linear_gradient(
1412                180.,
1413                linear_color_stop(clear.alpha(clear.a.min(0.3)), 0.),
1414                linear_color_stop(blue.alpha(0.3), 1.),
1415            )
1416        );
1417    }
1418}