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