Skip to main content

fresh/view/theme/
types.rs

1//! Pure theme types without I/O operations.
2//!
3//! This module contains all theme-related data structures that can be used
4//! without filesystem access. This enables WASM compatibility and easier testing.
5
6use ratatui::style::{Color, Modifier};
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9
10pub const THEME_DARK: &str = "dark";
11pub const THEME_LIGHT: &str = "light";
12pub const THEME_HIGH_CONTRAST: &str = "high-contrast";
13pub const THEME_NOSTALGIA: &str = "nostalgia";
14pub const THEME_DRACULA: &str = "dracula";
15pub const THEME_NORD: &str = "nord";
16pub const THEME_SOLARIZED_DARK: &str = "solarized-dark";
17/// Theme that defers to the host terminal's palette and background
18/// (uses `Default` and named ANSI colors for everything visual), so
19/// fresh inherits whatever colorscheme the terminal already has.
20pub const THEME_TERMINAL: &str = "terminal";
21
22/// A builtin theme with its name, pack, and embedded JSON content.
23pub struct BuiltinTheme {
24    pub name: &'static str,
25    /// Pack name (subdirectory path, empty for root themes)
26    pub pack: &'static str,
27    pub json: &'static str,
28}
29
30// Include the auto-generated BUILTIN_THEMES array from build.rs
31include!(concat!(env!("OUT_DIR"), "/builtin_themes.rs"));
32
33/// Information about an available theme.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct ThemeInfo {
36    /// Theme display name (e.g., "dark", "adwaita-dark")
37    pub name: String,
38    /// Pack name (subdirectory path, empty for root themes)
39    pub pack: String,
40    /// Unique key used as the registry identifier.
41    ///
42    /// Derivation priority:
43    /// 1. Package themes: `{repository_url}#{theme_name}`
44    /// 2. User-saved themes (theme editor): `file://{absolute_path}`
45    /// 3. Loose user themes: `{pack}/{name}` or just `{name}` if pack is empty
46    /// 4. Builtins: just the name
47    pub key: String,
48}
49
50impl ThemeInfo {
51    /// Create a new ThemeInfo. The key defaults to `pack/name` (or just `name`
52    /// when pack is empty).
53    pub fn new(name: impl Into<String>, pack: impl Into<String>) -> Self {
54        let name = name.into();
55        let pack = pack.into();
56        let key = if pack.is_empty() {
57            name.clone()
58        } else {
59            format!("{}/{}", pack, name)
60        };
61        Self { name, pack, key }
62    }
63
64    /// Create a ThemeInfo with an explicit key (e.g. a repository URL).
65    pub fn with_key(
66        name: impl Into<String>,
67        pack: impl Into<String>,
68        key: impl Into<String>,
69    ) -> Self {
70        Self {
71            name: name.into(),
72            pack: pack.into(),
73            key: key.into(),
74        }
75    }
76
77    /// Get display name showing pack if present
78    pub fn display_name(&self) -> String {
79        if self.pack.is_empty() {
80            self.name.clone()
81        } else {
82            format!("{} ({})", self.name, self.pack)
83        }
84    }
85}
86
87/// Convert a ratatui Color to RGB values.
88/// Returns None for Reset or Indexed colors.
89pub fn color_to_rgb(color: Color) -> Option<(u8, u8, u8)> {
90    match color {
91        Color::Rgb(r, g, b) => Some((r, g, b)),
92        Color::White => Some((255, 255, 255)),
93        Color::Black => Some((0, 0, 0)),
94        Color::Red => Some((205, 0, 0)),
95        Color::Green => Some((0, 205, 0)),
96        Color::Blue => Some((0, 0, 238)),
97        Color::Yellow => Some((205, 205, 0)),
98        Color::Magenta => Some((205, 0, 205)),
99        Color::Cyan => Some((0, 205, 205)),
100        Color::Gray => Some((229, 229, 229)),
101        Color::DarkGray => Some((127, 127, 127)),
102        Color::LightRed => Some((255, 0, 0)),
103        Color::LightGreen => Some((0, 255, 0)),
104        Color::LightBlue => Some((92, 92, 255)),
105        Color::LightYellow => Some((255, 255, 0)),
106        Color::LightMagenta => Some((255, 0, 255)),
107        Color::LightCyan => Some((0, 255, 255)),
108        Color::Reset | Color::Indexed(_) => None,
109    }
110}
111
112/// Brighten a color by adding an amount to each RGB component.
113/// Clamps values to 255.
114pub fn brighten_color(color: Color, amount: u8) -> Color {
115    if let Some((r, g, b)) = color_to_rgb(color) {
116        Color::Rgb(
117            r.saturating_add(amount),
118            g.saturating_add(amount),
119            b.saturating_add(amount),
120        )
121    } else {
122        color
123    }
124}
125
126/// Shift an RGB color a small amount toward the opposite end of the
127/// brightness spectrum: dark colors become slightly brighter, light colors
128/// slightly darker. Non-RGB colors are returned unchanged.
129///
130/// Used to derive subtle visual cues (e.g. post-EOF background shade) from
131/// a theme's editor background without requiring theme authors to pick an
132/// explicit color.
133pub fn shade_toward_contrast(color: Color, amount: u8) -> Color {
134    if let Some((r, g, b)) = color_to_rgb(color) {
135        let avg = (u16::from(r) + u16::from(g) + u16::from(b)) / 3;
136        if avg < 128 {
137            Color::Rgb(
138                r.saturating_add(amount),
139                g.saturating_add(amount),
140                b.saturating_add(amount),
141            )
142        } else {
143            Color::Rgb(
144                r.saturating_sub(amount),
145                g.saturating_sub(amount),
146                b.saturating_sub(amount),
147            )
148        }
149    } else {
150        color
151    }
152}
153
154/// Serializable color representation
155#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
156#[serde(untagged)]
157pub enum ColorDef {
158    /// RGB color as [r, g, b]
159    Rgb(u8, u8, u8),
160    /// Named color
161    Named(String),
162}
163
164impl From<ColorDef> for Color {
165    fn from(def: ColorDef) -> Self {
166        match def {
167            ColorDef::Rgb(r, g, b) => Color::Rgb(r, g, b),
168            ColorDef::Named(name) => match name.as_str() {
169                "Black" => Color::Black,
170                "Red" => Color::Red,
171                "Green" => Color::Green,
172                "Yellow" => Color::Yellow,
173                "Blue" => Color::Blue,
174                "Magenta" => Color::Magenta,
175                "Cyan" => Color::Cyan,
176                "Gray" => Color::Gray,
177                "DarkGray" => Color::DarkGray,
178                "LightRed" => Color::LightRed,
179                "LightGreen" => Color::LightGreen,
180                "LightYellow" => Color::LightYellow,
181                "LightBlue" => Color::LightBlue,
182                "LightMagenta" => Color::LightMagenta,
183                "LightCyan" => Color::LightCyan,
184                "White" => Color::White,
185                // Default/Reset uses the terminal's default color (preserves transparency)
186                "Default" | "Reset" => Color::Reset,
187                _ => Color::White, // Default fallback
188            },
189        }
190    }
191}
192
193/// Serializable text-attribute modifier list.
194///
195/// Lets a theme specify SGR text attributes (reverse video, bold,
196/// italic, underline, dim) on top of fg/bg colors. Designed for
197/// terminal-adaptive themes that want to use `["reversed"]` on the
198/// visual selection — the canonical pattern documented for native-
199/// palette themes (vim/neovim Visual mode, helix term16, htop, less)
200/// because reverse video automatically inverts the terminal's
201/// current fg/bg and so adapts to both light and dark backgrounds
202/// without a separate variant.
203///
204/// JSON form: `["reversed"]` or `["bold", "underlined"]`. Unknown
205/// strings are silently dropped so a typo can't crash a render.
206#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
207#[serde(transparent)]
208pub struct ModifierDef(pub Vec<String>);
209
210impl From<&ModifierDef> for Modifier {
211    fn from(def: &ModifierDef) -> Self {
212        let mut m = Modifier::empty();
213        for s in &def.0 {
214            match s.as_str() {
215                "reversed" | "reverse" => m |= Modifier::REVERSED,
216                "bold" => m |= Modifier::BOLD,
217                "italic" => m |= Modifier::ITALIC,
218                "underlined" | "underline" => m |= Modifier::UNDERLINED,
219                "dim" => m |= Modifier::DIM,
220                _ => {}
221            }
222        }
223        m
224    }
225}
226
227impl From<ModifierDef> for Modifier {
228    fn from(def: ModifierDef) -> Self {
229        Modifier::from(&def)
230    }
231}
232
233impl From<Modifier> for ModifierDef {
234    fn from(m: Modifier) -> Self {
235        // Order matches the canonical order in the parser, so a
236        // round-trip Theme -> ThemeFile -> Theme yields the same set.
237        let mut out = Vec::new();
238        if m.contains(Modifier::REVERSED) {
239            out.push("reversed".to_string());
240        }
241        if m.contains(Modifier::BOLD) {
242            out.push("bold".to_string());
243        }
244        if m.contains(Modifier::ITALIC) {
245            out.push("italic".to_string());
246        }
247        if m.contains(Modifier::UNDERLINED) {
248            out.push("underlined".to_string());
249        }
250        if m.contains(Modifier::DIM) {
251            out.push("dim".to_string());
252        }
253        ModifierDef(out)
254    }
255}
256
257/// Convert a named color string (e.g. "Yellow", "Red") to a ratatui Color.
258/// Returns None if the string is not a recognized named color.
259pub fn named_color_from_str(name: &str) -> Option<Color> {
260    match name {
261        "Black" => Some(Color::Black),
262        "Red" => Some(Color::Red),
263        "Green" => Some(Color::Green),
264        "Yellow" => Some(Color::Yellow),
265        "Blue" => Some(Color::Blue),
266        "Magenta" => Some(Color::Magenta),
267        "Cyan" => Some(Color::Cyan),
268        "Gray" => Some(Color::Gray),
269        "DarkGray" => Some(Color::DarkGray),
270        "LightRed" => Some(Color::LightRed),
271        "LightGreen" => Some(Color::LightGreen),
272        "LightYellow" => Some(Color::LightYellow),
273        "LightBlue" => Some(Color::LightBlue),
274        "LightMagenta" => Some(Color::LightMagenta),
275        "LightCyan" => Some(Color::LightCyan),
276        "White" => Some(Color::White),
277        "Default" | "Reset" => Some(Color::Reset),
278        _ => None,
279    }
280}
281
282/// Convert a ratatui `Color` into the lossless `TokenColor::Named`
283/// string form used by `ViewTokenStyle` (for everything except
284/// `Color::Rgb`, which uses the array variant). The corresponding
285/// inverse lives on [`TokenColorExt::to_ratatui`].
286fn token_color_named_from_ratatui(color: Color) -> &'static str {
287    match color {
288        Color::Black => "Black",
289        Color::Red => "Red",
290        Color::Green => "Green",
291        Color::Yellow => "Yellow",
292        Color::Blue => "Blue",
293        Color::Magenta => "Magenta",
294        Color::Cyan => "Cyan",
295        Color::Gray => "Gray",
296        Color::DarkGray => "DarkGray",
297        Color::LightRed => "LightRed",
298        Color::LightGreen => "LightGreen",
299        Color::LightYellow => "LightYellow",
300        Color::LightBlue => "LightBlue",
301        Color::LightMagenta => "LightMagenta",
302        Color::LightCyan => "LightCyan",
303        Color::White => "White",
304        Color::Reset => "Default",
305        // Rgb and Indexed are handled by callers; this fn is for the
306        // named-only set above.
307        _ => "Default",
308    }
309}
310
311/// Resolve a `TokenColor` (the lossless RGB-or-named color carried by
312/// `ViewTokenStyle`) and produce a ratatui `Color` ready for the
313/// renderer. Named strings try (in order) an ANSI name, then
314/// `"Indexed:N"` for 256-color values, then a theme-key lookup
315/// against `theme`. Unknown strings fall through to `Color::Reset`
316/// so a typo in a plugin can't make text disappear.
317pub trait TokenColorExt {
318    fn to_ratatui(&self, theme: &Theme) -> Color;
319    fn from_ratatui(color: Color) -> Option<fresh_core::api::TokenColor>;
320}
321
322impl TokenColorExt for fresh_core::api::TokenColor {
323    fn to_ratatui(&self, theme: &Theme) -> Color {
324        use fresh_core::api::TokenColor;
325        match self {
326            TokenColor::Rgb(r, g, b) => Color::Rgb(*r, *g, *b),
327            TokenColor::Named(name) => {
328                if let Some(c) = named_color_from_str(name) {
329                    return c;
330                }
331                if let Some(rest) = name.strip_prefix("Indexed:") {
332                    if let Ok(n) = rest.parse::<u8>() {
333                        return Color::Indexed(n);
334                    }
335                }
336                theme.resolve_theme_key(name).unwrap_or(Color::Reset)
337            }
338        }
339    }
340
341    fn from_ratatui(color: Color) -> Option<fresh_core::api::TokenColor> {
342        use fresh_core::api::TokenColor;
343        match color {
344            Color::Rgb(r, g, b) => Some(TokenColor::Rgb(r, g, b)),
345            Color::Indexed(n) => Some(TokenColor::Named(format!("Indexed:{n}"))),
346            other => Some(TokenColor::Named(
347                token_color_named_from_ratatui(other).to_string(),
348            )),
349        }
350    }
351}
352
353impl From<Color> for ColorDef {
354    fn from(color: Color) -> Self {
355        match color {
356            Color::Rgb(r, g, b) => ColorDef::Rgb(r, g, b),
357            Color::White => ColorDef::Named("White".to_string()),
358            Color::Black => ColorDef::Named("Black".to_string()),
359            Color::Red => ColorDef::Named("Red".to_string()),
360            Color::Green => ColorDef::Named("Green".to_string()),
361            Color::Blue => ColorDef::Named("Blue".to_string()),
362            Color::Yellow => ColorDef::Named("Yellow".to_string()),
363            Color::Magenta => ColorDef::Named("Magenta".to_string()),
364            Color::Cyan => ColorDef::Named("Cyan".to_string()),
365            Color::Gray => ColorDef::Named("Gray".to_string()),
366            Color::DarkGray => ColorDef::Named("DarkGray".to_string()),
367            Color::LightRed => ColorDef::Named("LightRed".to_string()),
368            Color::LightGreen => ColorDef::Named("LightGreen".to_string()),
369            Color::LightBlue => ColorDef::Named("LightBlue".to_string()),
370            Color::LightYellow => ColorDef::Named("LightYellow".to_string()),
371            Color::LightMagenta => ColorDef::Named("LightMagenta".to_string()),
372            Color::LightCyan => ColorDef::Named("LightCyan".to_string()),
373            Color::Reset => ColorDef::Named("Default".to_string()),
374            Color::Indexed(_) => {
375                // Fallback for indexed colors
376                if let Some((r, g, b)) = color_to_rgb(color) {
377                    ColorDef::Rgb(r, g, b)
378                } else {
379                    ColorDef::Named("Default".to_string())
380                }
381            }
382        }
383    }
384}
385
386/// Serializable theme definition (matches JSON structure)
387///
388/// The five color sections (`editor`, `ui`, `search`, `diagnostic`, `syntax`)
389/// are all optional. Every leaf field within each section already has a
390/// `#[serde(default = "…")]` fallback, so a theme JSON only needs to specify
391/// the colors it cares about. This matches the minimal example shipped in
392/// `docs/features/themes.md` and unblocks user-authored themes that override
393/// just `editor`/`syntax` (issue #1281).
394///
395/// **Inheritance**: when a theme omits whole sections, the unset fields are
396/// resolved against a *base* theme rather than against the per-field hardcoded
397/// fallback. The base is chosen in this order:
398///
399/// 1. Explicit `extends` field (`"builtin://light"`, `"dark"`, etc.).
400/// 2. If `editor.bg` is provided, the relative-luminance of that color picks
401///    `builtin://light` or `builtin://dark` automatically — so a user theme
402///    that sets a cream background gets light UI chrome without any extra
403///    configuration.
404/// 3. Otherwise, fall through to the per-field hardcoded defaults.
405///
406/// Only built-in themes are valid `extends` targets in this version. Chained
407/// inheritance across user themes is intentionally out of scope here.
408#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
409pub struct ThemeFile {
410    /// Theme name
411    pub name: String,
412    /// Optional base theme to inherit from. Accepts `"builtin://NAME"` or a
413    /// bare built-in name (e.g. `"dark"`, `"light"`, `"high-contrast"`).
414    /// When set, every field this theme does not specify is taken from the
415    /// base; explicit fields override the base. See [`ThemeFile`] for the
416    /// full inheritance resolution order.
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub extends: Option<String>,
419    /// Editor area colors
420    #[serde(default = "default_editor_colors")]
421    pub editor: EditorColors,
422    /// UI element colors (tabs, menus, status bar, etc.)
423    #[serde(default = "default_ui_colors")]
424    pub ui: UiColors,
425    /// Search result highlighting colors
426    #[serde(default = "default_search_colors")]
427    pub search: SearchColors,
428    /// LSP diagnostic colors (errors, warnings, etc.)
429    #[serde(default = "default_diagnostic_colors")]
430    pub diagnostic: DiagnosticColors,
431    /// Syntax highlighting colors
432    #[serde(default = "default_syntax_colors")]
433    pub syntax: SyntaxColors,
434}
435
436// Per-section defaults piggyback on the field-level `#[serde(default = "…")]`
437// already declared on every leaf — deserializing an empty object materializes
438// an all-defaults section without us having to restate every field here, and
439// keeps the section default in lock-step with its field defaults.
440fn default_section<T: serde::de::DeserializeOwned>(section: &'static str) -> T {
441    serde_json::from_str("{}").unwrap_or_else(|e| {
442        panic!(
443            "theme section `{}` must be default-constructible from `{{}}` \
444             (every field needs `#[serde(default = ...)]`): {}",
445            section, e
446        )
447    })
448}
449
450fn default_editor_colors() -> EditorColors {
451    default_section("editor")
452}
453
454fn default_ui_colors() -> UiColors {
455    default_section("ui")
456}
457
458fn default_search_colors() -> SearchColors {
459    default_section("search")
460}
461
462fn default_diagnostic_colors() -> DiagnosticColors {
463    default_section("diagnostic")
464}
465
466fn default_syntax_colors() -> SyntaxColors {
467    default_section("syntax")
468}
469
470/// Editor area colors
471#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
472pub struct EditorColors {
473    /// Editor background color
474    #[serde(default = "default_editor_bg")]
475    pub bg: ColorDef,
476    /// Default text color
477    #[serde(default = "default_editor_fg")]
478    pub fg: ColorDef,
479    /// Cursor color
480    #[serde(default = "default_cursor")]
481    pub cursor: ColorDef,
482    /// Cursor color in unfocused splits
483    #[serde(default = "default_inactive_cursor")]
484    pub inactive_cursor: ColorDef,
485    /// Selected text background
486    #[serde(default = "default_selection_bg")]
487    pub selection_bg: ColorDef,
488    /// Optional text-attribute modifiers (e.g. `["reversed"]`) layered
489    /// on top of `selection_bg`. Themes that want a terminal-adaptive
490    /// visual selection (the canonical pattern for native-palette
491    /// themes — vim/neovim Visual, helix term16, htop, less) set
492    /// `["reversed"]` here; the renderer ORs `Modifier::REVERSED` into
493    /// the selected cells, which works on any terminal because it
494    /// inverts whatever fg/bg the terminal already uses.
495    #[serde(default)]
496    pub selection_modifier: Option<ModifierDef>,
497    /// Background of the line containing cursor
498    #[serde(default = "default_current_line_bg")]
499    pub current_line_bg: ColorDef,
500    /// Line number text color
501    #[serde(default = "default_line_number_fg")]
502    pub line_number_fg: ColorDef,
503    /// Line number gutter background
504    #[serde(default = "default_line_number_bg")]
505    pub line_number_bg: ColorDef,
506    /// Diff added line background
507    #[serde(default = "default_diff_add_bg")]
508    pub diff_add_bg: ColorDef,
509    /// Diff removed line background
510    #[serde(default = "default_diff_remove_bg")]
511    pub diff_remove_bg: ColorDef,
512    /// Diff added word-level highlight background (optional override)
513    /// When not set, computed by brightening diff_add_bg
514    #[serde(default)]
515    pub diff_add_highlight_bg: Option<ColorDef>,
516    /// Diff removed word-level highlight background (optional override)
517    /// When not set, computed by brightening diff_remove_bg
518    #[serde(default)]
519    pub diff_remove_highlight_bg: Option<ColorDef>,
520    /// Diff modified line background
521    #[serde(default = "default_diff_modify_bg")]
522    pub diff_modify_bg: ColorDef,
523    /// Fallback fg for cells whose existing fg matches `diff_add_bg`
524    /// (e.g. ANSI Green-on-Green). Only applied on collision; other
525    /// tokens keep their syntax colour.
526    #[serde(default)]
527    pub diff_add_collision_fg: Option<ColorDef>,
528    /// Collision-only fallback fg for `diff_remove_bg`.
529    #[serde(default)]
530    pub diff_remove_collision_fg: Option<ColorDef>,
531    /// Collision-only fallback fg for `diff_modify_bg`.
532    #[serde(default)]
533    pub diff_modify_collision_fg: Option<ColorDef>,
534    /// Vertical ruler background color
535    #[serde(default = "default_ruler_bg")]
536    pub ruler_bg: ColorDef,
537    /// Whitespace indicator foreground color (for tab arrows and space dots)
538    #[serde(default = "default_whitespace_indicator_fg")]
539    pub whitespace_indicator_fg: ColorDef,
540    /// Bracket match highlight color (used when rainbow is disabled)
541    #[serde(default = "default_bracket_match_fg")]
542    pub bracket_match_fg: ColorDef,
543    /// Rainbow bracket color (nesting level 1)
544    #[serde(default = "default_bracket_rainbow_1")]
545    pub bracket_rainbow_1: ColorDef,
546    /// Rainbow bracket color (nesting level 2)
547    #[serde(default = "default_bracket_rainbow_2")]
548    pub bracket_rainbow_2: ColorDef,
549    /// Rainbow bracket color (nesting level 3)
550    #[serde(default = "default_bracket_rainbow_3")]
551    pub bracket_rainbow_3: ColorDef,
552    /// Rainbow bracket color (nesting level 4)
553    #[serde(default = "default_bracket_rainbow_4")]
554    pub bracket_rainbow_4: ColorDef,
555    /// Rainbow bracket color (nesting level 5)
556    #[serde(default = "default_bracket_rainbow_5")]
557    pub bracket_rainbow_5: ColorDef,
558    /// Rainbow bracket color (nesting level 6)
559    #[serde(default = "default_bracket_rainbow_6")]
560    pub bracket_rainbow_6: ColorDef,
561    /// Background color for lines after end-of-file (optional override).
562    /// When not set, computed as a slightly contrasting shade of `bg`
563    /// (lighter for dark themes, darker for light themes) to give post-EOF
564    /// rows a subtle visual separation from the buffer content.
565    #[serde(default)]
566    pub after_eof_bg: Option<ColorDef>,
567}
568
569// Default editor colors (for minimal themes)
570fn default_editor_bg() -> ColorDef {
571    ColorDef::Rgb(30, 30, 30)
572}
573fn default_editor_fg() -> ColorDef {
574    ColorDef::Rgb(212, 212, 212)
575}
576fn default_cursor() -> ColorDef {
577    ColorDef::Rgb(255, 255, 255)
578}
579fn default_inactive_cursor() -> ColorDef {
580    ColorDef::Named("DarkGray".to_string())
581}
582fn default_selection_bg() -> ColorDef {
583    ColorDef::Rgb(38, 79, 120)
584}
585fn default_current_line_bg() -> ColorDef {
586    ColorDef::Rgb(40, 40, 40)
587}
588fn default_line_number_fg() -> ColorDef {
589    ColorDef::Rgb(100, 100, 100)
590}
591fn default_line_number_bg() -> ColorDef {
592    ColorDef::Rgb(30, 30, 30)
593}
594fn default_diff_add_bg() -> ColorDef {
595    ColorDef::Rgb(35, 60, 35) // Dark green
596}
597fn default_diff_remove_bg() -> ColorDef {
598    ColorDef::Rgb(70, 35, 35) // Dark red
599}
600fn default_diff_modify_bg() -> ColorDef {
601    ColorDef::Rgb(40, 38, 30) // Very subtle yellow tint, close to dark bg
602}
603fn default_ruler_bg() -> ColorDef {
604    ColorDef::Rgb(50, 50, 50) // Subtle dark gray, slightly lighter than default editor bg
605}
606fn default_whitespace_indicator_fg() -> ColorDef {
607    ColorDef::Rgb(70, 70, 70) // Subdued dark gray, subtle but visible
608}
609fn default_bracket_match_fg() -> ColorDef {
610    ColorDef::Rgb(255, 215, 0) // Gold
611}
612fn default_bracket_rainbow_1() -> ColorDef {
613    ColorDef::Rgb(255, 215, 0) // Gold
614}
615fn default_bracket_rainbow_2() -> ColorDef {
616    ColorDef::Rgb(218, 112, 214) // Orchid
617}
618fn default_bracket_rainbow_3() -> ColorDef {
619    ColorDef::Rgb(50, 205, 50) // Lime Green
620}
621fn default_bracket_rainbow_4() -> ColorDef {
622    ColorDef::Rgb(30, 144, 255) // Dodger Blue
623}
624fn default_bracket_rainbow_5() -> ColorDef {
625    ColorDef::Rgb(255, 127, 80) // Coral
626}
627fn default_bracket_rainbow_6() -> ColorDef {
628    ColorDef::Rgb(147, 112, 219) // Medium Purple
629}
630
631/// UI element colors (tabs, menus, status bar, etc.)
632///
633/// Naming convention: every `*_bg` key that has text drawn on top of
634/// it MUST have a matching `*_fg` key, and renderers must pair them
635/// (never borrow a foreground from an unrelated surface — doing so is
636/// how text ends up invisible when a theme's borrowed fg matches the
637/// real bg). `popup_text_fg` is the foreground for `popup_bg` (kept
638/// under its historical name with a `popup_fg` serde alias).
639///
640/// `*_bg` keys WITHOUT a matching `*_fg` are intentional — they don't
641/// draw their own text and inherit the surrounding foreground:
642///   - lines / borders / separators: `tab_separator_bg`,
643///     `popup_border_fg`, `menu_border_fg`, `menu_separator_fg`,
644///     `split_separator_fg`, `scrollbar_*`, `tab_drop_zone_border`
645///   - selection / hover / highlight tints layered over a surface that
646///     keeps its base fg: `*_selection_bg`, `*_hover_bg`,
647///     `suggestion_selected_bg`, `text_input_selection_bg`,
648///     `semantic_highlight_bg`, `compose_margin_bg`, `inline_code_bg`
649#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
650pub struct UiColors {
651    /// Active tab text color
652    #[serde(default = "default_tab_active_fg")]
653    pub tab_active_fg: ColorDef,
654    /// Active tab background color
655    #[serde(default = "default_tab_active_bg")]
656    pub tab_active_bg: ColorDef,
657    /// Inactive tab text color
658    #[serde(default = "default_tab_inactive_fg")]
659    pub tab_inactive_fg: ColorDef,
660    /// Inactive tab background color
661    #[serde(default = "default_tab_inactive_bg")]
662    pub tab_inactive_bg: ColorDef,
663    /// Tab bar separator color
664    #[serde(default = "default_tab_separator_bg")]
665    pub tab_separator_bg: ColorDef,
666    /// Tab close button hover color
667    #[serde(default = "default_tab_close_hover_fg")]
668    pub tab_close_hover_fg: ColorDef,
669    /// Tab hover background color
670    #[serde(default = "default_tab_hover_bg")]
671    pub tab_hover_bg: ColorDef,
672    /// Menu bar background
673    #[serde(default = "default_menu_bg")]
674    pub menu_bg: ColorDef,
675    /// Menu bar text color
676    #[serde(default = "default_menu_fg")]
677    pub menu_fg: ColorDef,
678    /// Active menu item background
679    #[serde(default = "default_menu_active_bg")]
680    pub menu_active_bg: ColorDef,
681    /// Active menu item text color
682    #[serde(default = "default_menu_active_fg")]
683    pub menu_active_fg: ColorDef,
684    /// Dropdown menu background
685    #[serde(default = "default_menu_dropdown_bg")]
686    pub menu_dropdown_bg: ColorDef,
687    /// Dropdown menu text color
688    #[serde(default = "default_menu_dropdown_fg")]
689    pub menu_dropdown_fg: ColorDef,
690    /// Highlighted menu item background
691    #[serde(default = "default_menu_highlight_bg")]
692    pub menu_highlight_bg: ColorDef,
693    /// Highlighted menu item text color
694    #[serde(default = "default_menu_highlight_fg")]
695    pub menu_highlight_fg: ColorDef,
696    /// Menu border color
697    #[serde(default = "default_menu_border_fg")]
698    pub menu_border_fg: ColorDef,
699    /// Menu separator line color
700    #[serde(default = "default_menu_separator_fg")]
701    pub menu_separator_fg: ColorDef,
702    /// Menu item hover background
703    #[serde(default = "default_menu_hover_bg")]
704    pub menu_hover_bg: ColorDef,
705    /// Menu item hover text color
706    #[serde(default = "default_menu_hover_fg")]
707    pub menu_hover_fg: ColorDef,
708    /// Disabled menu item text color
709    #[serde(default = "default_menu_disabled_fg")]
710    pub menu_disabled_fg: ColorDef,
711    /// Disabled menu item background
712    #[serde(default = "default_menu_disabled_bg")]
713    pub menu_disabled_bg: ColorDef,
714    /// Status bar text color
715    #[serde(default = "default_status_bar_fg")]
716    pub status_bar_fg: ColorDef,
717    /// Status bar background color
718    #[serde(default = "default_status_bar_bg")]
719    pub status_bar_bg: ColorDef,
720    /// Command palette shortcut hint text color in status bar (falls back to status_bar_fg)
721    #[serde(default)]
722    pub status_palette_fg: Option<ColorDef>,
723    /// Command palette shortcut hint background in status bar (falls back to status_bar_bg)
724    #[serde(default)]
725    pub status_palette_bg: Option<ColorDef>,
726    /// Status bar LSP indicator text color when LSP is running (falls back to status_bar_fg)
727    #[serde(default)]
728    pub status_lsp_on_fg: Option<ColorDef>,
729    /// Status bar LSP indicator background when LSP is running (falls back to status_bar_bg)
730    #[serde(default)]
731    pub status_lsp_on_bg: Option<ColorDef>,
732    /// Status bar LSP indicator text color when LSP options are available
733    /// to act on (configured-but-not-running). Drawn prominently to signal
734    /// "click here to enable". Falls back to `status_warning_indicator_fg`.
735    #[serde(default)]
736    pub status_lsp_actionable_fg: Option<ColorDef>,
737    /// Status bar LSP indicator background when LSP options are available
738    /// to act on. Falls back to `status_warning_indicator_bg`.
739    #[serde(default)]
740    pub status_lsp_actionable_bg: Option<ColorDef>,
741    /// Command prompt text color
742    #[serde(default = "default_prompt_fg")]
743    pub prompt_fg: ColorDef,
744    /// Command prompt background
745    #[serde(default = "default_prompt_bg")]
746    pub prompt_bg: ColorDef,
747    /// Prompt selected text color
748    #[serde(default = "default_prompt_selection_fg")]
749    pub prompt_selection_fg: ColorDef,
750    /// Prompt selection background
751    #[serde(default = "default_prompt_selection_bg")]
752    pub prompt_selection_bg: ColorDef,
753    /// Popup window border color
754    #[serde(default = "default_popup_border_fg")]
755    pub popup_border_fg: ColorDef,
756    /// Popup window background
757    #[serde(default = "default_popup_bg")]
758    pub popup_bg: ColorDef,
759    /// Popup selected item background
760    #[serde(default = "default_popup_selection_bg")]
761    pub popup_selection_bg: ColorDef,
762    /// Selection background inside a widget Text input. Reads
763    /// against `prompt_bg`, so it needs higher contrast against
764    /// that tint than `editor.selection_bg` (which targets the
765    /// editor surface). Defaults to the same `popup_selection_bg`
766    /// blue used everywhere "selected item inside a chrome
767    /// surface" is shown — same key the prompt selection uses, so
768    /// the cue reads consistently across selection UIs.
769    #[serde(default = "default_text_input_selection_bg")]
770    pub text_input_selection_bg: ColorDef,
771    /// Popup selected item text color
772    #[serde(default = "default_popup_selection_fg")]
773    pub popup_selection_fg: ColorDef,
774    /// Popup window text color. Per the `*_bg`/`*_fg` convention this
775    /// is the foreground for `popup_bg`; `popup_fg` is accepted as an
776    /// alias so theme JSON can use the convention-consistent name.
777    #[serde(default = "default_popup_text_fg", alias = "popup_fg")]
778    pub popup_text_fg: ColorDef,
779    /// Autocomplete suggestion background
780    #[serde(default = "default_suggestion_bg")]
781    pub suggestion_bg: ColorDef,
782    /// Text color for content drawn on `suggestion_bg` (autocomplete
783    /// items, the overlay-prompt title/input field). Falls back to
784    /// `popup_text_fg` so existing themes need no change.
785    #[serde(default)]
786    pub suggestion_fg: Option<ColorDef>,
787    /// Selected suggestion background
788    #[serde(default = "default_suggestion_selected_bg")]
789    pub suggestion_selected_bg: ColorDef,
790    /// Help panel background
791    #[serde(default = "default_help_bg")]
792    pub help_bg: ColorDef,
793    /// Help panel text color
794    #[serde(default = "default_help_fg")]
795    pub help_fg: ColorDef,
796    /// Help keybinding text color
797    #[serde(default = "default_help_key_fg")]
798    pub help_key_fg: ColorDef,
799    /// Help panel separator color
800    #[serde(default = "default_help_separator_fg")]
801    pub help_separator_fg: ColorDef,
802    /// Help indicator text color
803    #[serde(default = "default_help_indicator_fg")]
804    pub help_indicator_fg: ColorDef,
805    /// Help indicator background
806    #[serde(default = "default_help_indicator_bg")]
807    pub help_indicator_bg: ColorDef,
808    /// Inline code block background
809    #[serde(default = "default_inline_code_bg")]
810    pub inline_code_bg: ColorDef,
811    /// Split pane separator color
812    #[serde(default = "default_split_separator_fg")]
813    pub split_separator_fg: ColorDef,
814    /// Split separator hover color
815    #[serde(default = "default_split_separator_hover_fg")]
816    pub split_separator_hover_fg: ColorDef,
817    /// Scrollbar track color
818    #[serde(default = "default_scrollbar_track_fg")]
819    pub scrollbar_track_fg: ColorDef,
820    /// Scrollbar thumb color
821    #[serde(default = "default_scrollbar_thumb_fg")]
822    pub scrollbar_thumb_fg: ColorDef,
823    /// Scrollbar track hover color
824    #[serde(default = "default_scrollbar_track_hover_fg")]
825    pub scrollbar_track_hover_fg: ColorDef,
826    /// Scrollbar thumb hover color
827    #[serde(default = "default_scrollbar_thumb_hover_fg")]
828    pub scrollbar_thumb_hover_fg: ColorDef,
829    /// Compose mode margin background
830    #[serde(default = "default_compose_margin_bg")]
831    pub compose_margin_bg: ColorDef,
832    /// Word under cursor highlight
833    #[serde(default = "default_semantic_highlight_bg")]
834    pub semantic_highlight_bg: ColorDef,
835    /// Optional text-attribute modifiers (e.g. `["bold"]` or
836    /// `["reversed"]`) layered on top of `semantic_highlight_bg`.
837    /// Per the canonical native-palette pattern, current-word
838    /// highlights are often shown via `Bold` (so the word stands
839    /// out against other variables without altering its color slot)
840    /// or `Reversed`. See `EditorColors::selection_modifier`.
841    #[serde(default)]
842    pub semantic_highlight_modifier: Option<ModifierDef>,
843    /// Embedded terminal background (use Default for transparency)
844    #[serde(default = "default_terminal_bg")]
845    pub terminal_bg: ColorDef,
846    /// Embedded terminal default text color
847    #[serde(default = "default_terminal_fg")]
848    pub terminal_fg: ColorDef,
849    /// Warning indicator background in status bar
850    #[serde(default = "default_status_warning_indicator_bg")]
851    pub status_warning_indicator_bg: ColorDef,
852    /// Warning indicator text color in status bar
853    #[serde(default = "default_status_warning_indicator_fg")]
854    pub status_warning_indicator_fg: ColorDef,
855    /// Error indicator background in status bar
856    #[serde(default = "default_status_error_indicator_bg")]
857    pub status_error_indicator_bg: ColorDef,
858    /// Error indicator text color in status bar
859    #[serde(default = "default_status_error_indicator_fg")]
860    pub status_error_indicator_fg: ColorDef,
861    /// Warning indicator hover background
862    #[serde(default = "default_status_warning_indicator_hover_bg")]
863    pub status_warning_indicator_hover_bg: ColorDef,
864    /// Warning indicator hover text color
865    #[serde(default = "default_status_warning_indicator_hover_fg")]
866    pub status_warning_indicator_hover_fg: ColorDef,
867    /// Error indicator hover background
868    #[serde(default = "default_status_error_indicator_hover_bg")]
869    pub status_error_indicator_hover_bg: ColorDef,
870    /// Error indicator hover text color
871    #[serde(default = "default_status_error_indicator_hover_fg")]
872    pub status_error_indicator_hover_fg: ColorDef,
873    /// Tab drop zone background during drag
874    #[serde(default = "default_tab_drop_zone_bg")]
875    pub tab_drop_zone_bg: ColorDef,
876    /// Tab drop zone border during drag
877    #[serde(default = "default_tab_drop_zone_border")]
878    pub tab_drop_zone_border: ColorDef,
879    /// Settings UI selected item background
880    #[serde(default = "default_settings_selected_bg")]
881    pub settings_selected_bg: ColorDef,
882    /// Settings UI selected item foreground (text on selected background)
883    #[serde(default = "default_settings_selected_fg")]
884    pub settings_selected_fg: ColorDef,
885    /// File status: added file color in file explorer (falls back to diagnostic.info_fg)
886    #[serde(default)]
887    pub file_status_added_fg: Option<ColorDef>,
888    /// File status: modified file color in file explorer (falls back to diagnostic.warning_fg)
889    #[serde(default)]
890    pub file_status_modified_fg: Option<ColorDef>,
891    /// File status: deleted file color in file explorer (falls back to diagnostic.error_fg)
892    #[serde(default)]
893    pub file_status_deleted_fg: Option<ColorDef>,
894    /// File status: renamed file color in file explorer (falls back to diagnostic.info_fg)
895    #[serde(default)]
896    pub file_status_renamed_fg: Option<ColorDef>,
897    /// File status: untracked file color in file explorer (falls back to diagnostic.hint_fg)
898    #[serde(default)]
899    pub file_status_untracked_fg: Option<ColorDef>,
900    /// File status: conflicted file color in file explorer (falls back to diagnostic.error_fg)
901    #[serde(default)]
902    pub file_status_conflicted_fg: Option<ColorDef>,
903}
904
905// Default tab close hover color (for backward compatibility with existing themes)
906// Default tab colors (for minimal themes)
907fn default_tab_active_fg() -> ColorDef {
908    ColorDef::Named("Yellow".to_string())
909}
910fn default_tab_active_bg() -> ColorDef {
911    ColorDef::Named("Blue".to_string())
912}
913fn default_tab_inactive_fg() -> ColorDef {
914    ColorDef::Named("White".to_string())
915}
916fn default_tab_inactive_bg() -> ColorDef {
917    ColorDef::Named("DarkGray".to_string())
918}
919fn default_tab_separator_bg() -> ColorDef {
920    ColorDef::Named("Black".to_string())
921}
922fn default_tab_close_hover_fg() -> ColorDef {
923    ColorDef::Rgb(255, 100, 100) // Red-ish color for close button hover
924}
925fn default_tab_hover_bg() -> ColorDef {
926    ColorDef::Rgb(70, 70, 75) // Slightly lighter than inactive tab bg for hover
927}
928
929// Default menu colors (for backward compatibility with existing themes)
930fn default_menu_bg() -> ColorDef {
931    ColorDef::Rgb(60, 60, 65)
932}
933fn default_menu_fg() -> ColorDef {
934    ColorDef::Rgb(220, 220, 220)
935}
936fn default_menu_active_bg() -> ColorDef {
937    ColorDef::Rgb(60, 60, 60)
938}
939fn default_menu_active_fg() -> ColorDef {
940    ColorDef::Rgb(255, 255, 255)
941}
942fn default_menu_dropdown_bg() -> ColorDef {
943    ColorDef::Rgb(50, 50, 50)
944}
945fn default_menu_dropdown_fg() -> ColorDef {
946    ColorDef::Rgb(220, 220, 220)
947}
948fn default_menu_highlight_bg() -> ColorDef {
949    ColorDef::Rgb(70, 130, 180)
950}
951fn default_menu_highlight_fg() -> ColorDef {
952    ColorDef::Rgb(255, 255, 255)
953}
954fn default_menu_border_fg() -> ColorDef {
955    ColorDef::Rgb(100, 100, 100)
956}
957fn default_menu_separator_fg() -> ColorDef {
958    ColorDef::Rgb(80, 80, 80)
959}
960fn default_menu_hover_bg() -> ColorDef {
961    ColorDef::Rgb(55, 55, 55)
962}
963fn default_menu_hover_fg() -> ColorDef {
964    ColorDef::Rgb(255, 255, 255)
965}
966fn default_menu_disabled_fg() -> ColorDef {
967    ColorDef::Rgb(100, 100, 100) // Gray for disabled items
968}
969fn default_menu_disabled_bg() -> ColorDef {
970    ColorDef::Rgb(50, 50, 50) // Same as dropdown bg
971}
972// Default status bar colors
973fn default_status_bar_fg() -> ColorDef {
974    ColorDef::Named("White".to_string())
975}
976fn default_status_bar_bg() -> ColorDef {
977    ColorDef::Named("DarkGray".to_string())
978}
979
980// Default prompt colors
981fn default_prompt_fg() -> ColorDef {
982    ColorDef::Named("White".to_string())
983}
984fn default_prompt_bg() -> ColorDef {
985    ColorDef::Named("Black".to_string())
986}
987fn default_prompt_selection_fg() -> ColorDef {
988    ColorDef::Named("White".to_string())
989}
990fn default_prompt_selection_bg() -> ColorDef {
991    ColorDef::Rgb(58, 79, 120)
992}
993
994// Default popup colors
995fn default_popup_border_fg() -> ColorDef {
996    ColorDef::Named("Gray".to_string())
997}
998fn default_popup_bg() -> ColorDef {
999    ColorDef::Rgb(30, 30, 30)
1000}
1001fn default_popup_selection_bg() -> ColorDef {
1002    ColorDef::Rgb(58, 79, 120)
1003}
1004fn default_text_input_selection_bg() -> ColorDef {
1005    // Match the popup-selection blue. Widget Text inputs sit on a
1006    // `prompt_bg` field tint, so the selection needs the same
1007    // "selected on chrome" contrast that popups + prompts use.
1008    ColorDef::Rgb(58, 79, 120)
1009}
1010fn default_popup_selection_fg() -> ColorDef {
1011    ColorDef::Rgb(255, 255, 255) // White text on selected popup item
1012}
1013fn default_popup_text_fg() -> ColorDef {
1014    ColorDef::Named("White".to_string())
1015}
1016
1017// Default suggestion colors
1018fn default_suggestion_bg() -> ColorDef {
1019    ColorDef::Rgb(30, 30, 30)
1020}
1021fn default_suggestion_selected_bg() -> ColorDef {
1022    ColorDef::Rgb(58, 79, 120)
1023}
1024
1025// Default help colors
1026fn default_help_bg() -> ColorDef {
1027    ColorDef::Named("Black".to_string())
1028}
1029fn default_help_fg() -> ColorDef {
1030    ColorDef::Named("White".to_string())
1031}
1032fn default_help_key_fg() -> ColorDef {
1033    ColorDef::Named("Cyan".to_string())
1034}
1035fn default_help_separator_fg() -> ColorDef {
1036    ColorDef::Named("DarkGray".to_string())
1037}
1038fn default_help_indicator_fg() -> ColorDef {
1039    ColorDef::Named("Red".to_string())
1040}
1041fn default_help_indicator_bg() -> ColorDef {
1042    ColorDef::Named("Black".to_string())
1043}
1044
1045fn default_inline_code_bg() -> ColorDef {
1046    ColorDef::Named("DarkGray".to_string())
1047}
1048
1049// Default split separator colors
1050fn default_split_separator_fg() -> ColorDef {
1051    ColorDef::Rgb(100, 100, 100)
1052}
1053fn default_split_separator_hover_fg() -> ColorDef {
1054    ColorDef::Rgb(100, 149, 237) // Cornflower blue for visibility
1055}
1056fn default_scrollbar_track_fg() -> ColorDef {
1057    ColorDef::Named("DarkGray".to_string())
1058}
1059fn default_scrollbar_thumb_fg() -> ColorDef {
1060    ColorDef::Named("Gray".to_string())
1061}
1062fn default_scrollbar_track_hover_fg() -> ColorDef {
1063    ColorDef::Named("Gray".to_string())
1064}
1065fn default_scrollbar_thumb_hover_fg() -> ColorDef {
1066    ColorDef::Named("White".to_string())
1067}
1068fn default_compose_margin_bg() -> ColorDef {
1069    ColorDef::Rgb(18, 18, 18) // Darker than editor_bg for "desk" effect
1070}
1071fn default_semantic_highlight_bg() -> ColorDef {
1072    ColorDef::Rgb(60, 60, 80) // Subtle dark highlight for word occurrences
1073}
1074fn default_terminal_bg() -> ColorDef {
1075    ColorDef::Named("Default".to_string()) // Use terminal's default background (preserves transparency)
1076}
1077fn default_terminal_fg() -> ColorDef {
1078    ColorDef::Named("Default".to_string()) // Use terminal's default foreground
1079}
1080fn default_status_warning_indicator_bg() -> ColorDef {
1081    ColorDef::Rgb(181, 137, 0) // Solarized yellow/amber - noticeable but not harsh
1082}
1083fn default_status_warning_indicator_fg() -> ColorDef {
1084    ColorDef::Rgb(0, 0, 0) // Black text on amber background
1085}
1086fn default_status_error_indicator_bg() -> ColorDef {
1087    ColorDef::Rgb(220, 50, 47) // Solarized red - clearly an error
1088}
1089fn default_status_error_indicator_fg() -> ColorDef {
1090    ColorDef::Rgb(255, 255, 255) // White text on red background
1091}
1092fn default_status_warning_indicator_hover_bg() -> ColorDef {
1093    ColorDef::Rgb(211, 167, 30) // Lighter amber for hover
1094}
1095fn default_status_warning_indicator_hover_fg() -> ColorDef {
1096    ColorDef::Rgb(0, 0, 0) // Black text on hover
1097}
1098fn default_status_error_indicator_hover_bg() -> ColorDef {
1099    ColorDef::Rgb(250, 80, 77) // Lighter red for hover
1100}
1101fn default_status_error_indicator_hover_fg() -> ColorDef {
1102    ColorDef::Rgb(255, 255, 255) // White text on hover
1103}
1104fn default_tab_drop_zone_bg() -> ColorDef {
1105    ColorDef::Rgb(70, 130, 180) // Steel blue with transparency effect
1106}
1107fn default_tab_drop_zone_border() -> ColorDef {
1108    ColorDef::Rgb(100, 149, 237) // Cornflower blue for border
1109}
1110fn default_settings_selected_bg() -> ColorDef {
1111    ColorDef::Rgb(60, 60, 70) // Subtle highlight for selected settings item
1112}
1113fn default_settings_selected_fg() -> ColorDef {
1114    ColorDef::Rgb(255, 255, 255) // White text on selected background
1115}
1116/// Search result highlighting colors
1117#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1118pub struct SearchColors {
1119    /// Search match background color
1120    #[serde(default = "default_search_match_bg")]
1121    pub match_bg: ColorDef,
1122    /// Search match text color
1123    #[serde(default = "default_search_match_fg")]
1124    pub match_fg: ColorDef,
1125    /// Background color for jump labels (e.g. flash plugin labels).
1126    /// Should be visually distinct from `match_bg` so labels stand
1127    /// out against highlighted matches.  Default: bright magenta.
1128    #[serde(default = "default_search_label_bg")]
1129    pub label_bg: ColorDef,
1130    /// Foreground color for jump labels.  Should be high contrast
1131    /// against `label_bg` so the single label letter is unambiguous
1132    /// even on small terminal cells.  Default: white.
1133    #[serde(default = "default_search_label_fg")]
1134    pub label_fg: ColorDef,
1135}
1136
1137// Default search colors
1138fn default_search_match_bg() -> ColorDef {
1139    ColorDef::Rgb(100, 100, 20)
1140}
1141fn default_search_match_fg() -> ColorDef {
1142    ColorDef::Rgb(255, 255, 255)
1143}
1144// Mirrors flash.nvim's default FlashLabel (links to Substitute, which
1145// is a magenta-family colour in most colorschemes).  The pairing is
1146// chosen so labels pop visually distinct from `search.match_bg`
1147// (typically yellow / orange).
1148fn default_search_label_bg() -> ColorDef {
1149    ColorDef::Rgb(199, 78, 189)
1150}
1151fn default_search_label_fg() -> ColorDef {
1152    ColorDef::Rgb(255, 255, 255)
1153}
1154
1155/// LSP diagnostic colors (errors, warnings, etc.)
1156#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1157pub struct DiagnosticColors {
1158    /// Error message text color
1159    #[serde(default = "default_diagnostic_error_fg")]
1160    pub error_fg: ColorDef,
1161    /// Error highlight background
1162    #[serde(default = "default_diagnostic_error_bg")]
1163    pub error_bg: ColorDef,
1164    /// Warning message text color
1165    #[serde(default = "default_diagnostic_warning_fg")]
1166    pub warning_fg: ColorDef,
1167    /// Warning highlight background
1168    #[serde(default = "default_diagnostic_warning_bg")]
1169    pub warning_bg: ColorDef,
1170    /// Info message text color
1171    #[serde(default = "default_diagnostic_info_fg")]
1172    pub info_fg: ColorDef,
1173    /// Info highlight background
1174    #[serde(default = "default_diagnostic_info_bg")]
1175    pub info_bg: ColorDef,
1176    /// Hint message text color
1177    #[serde(default = "default_diagnostic_hint_fg")]
1178    pub hint_fg: ColorDef,
1179    /// Hint highlight background
1180    #[serde(default = "default_diagnostic_hint_bg")]
1181    pub hint_bg: ColorDef,
1182}
1183
1184// Default diagnostic colors
1185fn default_diagnostic_error_fg() -> ColorDef {
1186    ColorDef::Named("Red".to_string())
1187}
1188fn default_diagnostic_error_bg() -> ColorDef {
1189    ColorDef::Rgb(60, 20, 20)
1190}
1191fn default_diagnostic_warning_fg() -> ColorDef {
1192    ColorDef::Named("Yellow".to_string())
1193}
1194fn default_diagnostic_warning_bg() -> ColorDef {
1195    ColorDef::Rgb(60, 50, 0)
1196}
1197fn default_diagnostic_info_fg() -> ColorDef {
1198    ColorDef::Named("Blue".to_string())
1199}
1200fn default_diagnostic_info_bg() -> ColorDef {
1201    ColorDef::Rgb(0, 30, 60)
1202}
1203fn default_diagnostic_hint_fg() -> ColorDef {
1204    ColorDef::Named("Gray".to_string())
1205}
1206fn default_diagnostic_hint_bg() -> ColorDef {
1207    ColorDef::Rgb(30, 30, 30)
1208}
1209
1210/// Syntax highlighting colors
1211#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1212pub struct SyntaxColors {
1213    /// Language keywords (if, for, fn, etc.)
1214    #[serde(default = "default_syntax_keyword")]
1215    pub keyword: ColorDef,
1216    /// String literals
1217    #[serde(default = "default_syntax_string")]
1218    pub string: ColorDef,
1219    /// Code comments
1220    #[serde(default = "default_syntax_comment")]
1221    pub comment: ColorDef,
1222    /// Function names
1223    #[serde(default = "default_syntax_function")]
1224    pub function: ColorDef,
1225    /// Type names
1226    #[serde(rename = "type", default = "default_syntax_type")]
1227    pub type_: ColorDef,
1228    /// Variable names
1229    #[serde(default = "default_syntax_variable")]
1230    pub variable: ColorDef,
1231    /// Built-in language variables (self, this, super, etc.)
1232    #[serde(default = "default_syntax_variable_builtin")]
1233    pub variable_builtin: ColorDef,
1234    /// Constants and literals
1235    #[serde(default = "default_syntax_constant")]
1236    pub constant: ColorDef,
1237    /// Operators (+, -, =, etc.)
1238    #[serde(default = "default_syntax_operator")]
1239    pub operator: ColorDef,
1240    /// Punctuation brackets ({, }, (, ), [, ])
1241    #[serde(default = "default_syntax_punctuation_bracket")]
1242    pub punctuation_bracket: ColorDef,
1243    /// Punctuation delimiters (;, ,, .)
1244    #[serde(default = "default_syntax_punctuation_delimiter")]
1245    pub punctuation_delimiter: ColorDef,
1246}
1247
1248// Default syntax colors (VSCode Dark+ inspired)
1249fn default_syntax_keyword() -> ColorDef {
1250    ColorDef::Rgb(86, 156, 214)
1251}
1252fn default_syntax_string() -> ColorDef {
1253    ColorDef::Rgb(206, 145, 120)
1254}
1255fn default_syntax_comment() -> ColorDef {
1256    ColorDef::Rgb(106, 153, 85)
1257}
1258fn default_syntax_function() -> ColorDef {
1259    ColorDef::Rgb(220, 220, 170)
1260}
1261fn default_syntax_type() -> ColorDef {
1262    ColorDef::Rgb(78, 201, 176)
1263}
1264fn default_syntax_variable() -> ColorDef {
1265    ColorDef::Rgb(156, 220, 254)
1266}
1267fn default_syntax_variable_builtin() -> ColorDef {
1268    ColorDef::Rgb(86, 156, 214) // same as keyword — self/this/super are language-defined
1269}
1270fn default_syntax_constant() -> ColorDef {
1271    ColorDef::Rgb(79, 193, 255)
1272}
1273fn default_syntax_operator() -> ColorDef {
1274    ColorDef::Rgb(212, 212, 212)
1275}
1276fn default_syntax_punctuation_bracket() -> ColorDef {
1277    ColorDef::Rgb(212, 212, 212) // default foreground — brackets blend with text
1278}
1279fn default_syntax_punctuation_delimiter() -> ColorDef {
1280    ColorDef::Rgb(212, 212, 212) // default foreground — delimiters blend with text
1281}
1282
1283/// Comprehensive theme structure with all UI colors
1284#[derive(Debug, Clone)]
1285pub struct Theme {
1286    /// Theme name (e.g., "dark", "light", "high-contrast")
1287    pub name: String,
1288
1289    // Editor colors
1290    pub editor_bg: Color,
1291    pub editor_fg: Color,
1292    pub cursor: Color,
1293    pub inactive_cursor: Color,
1294    pub selection_bg: Color,
1295    /// SGR text attributes layered onto selected cells. Empty for
1296    /// traditional themes; native-palette themes set
1297    /// `Modifier::REVERSED` so the selection inverts the terminal's
1298    /// current fg/bg (vim/neovim Visual, helix term16, htop, less).
1299    pub selection_modifier: Modifier,
1300    pub current_line_bg: Color,
1301    pub line_number_fg: Color,
1302    pub line_number_bg: Color,
1303
1304    /// Background color for rows past end-of-file
1305    pub after_eof_bg: Color,
1306
1307    // Vertical ruler color
1308    pub ruler_bg: Color,
1309
1310    // Whitespace indicator color (tab arrows, space dots)
1311    pub whitespace_indicator_fg: Color,
1312
1313    // Bracket matching colors
1314    pub bracket_match_fg: Color,
1315    pub bracket_rainbow_1: Color,
1316    pub bracket_rainbow_2: Color,
1317    pub bracket_rainbow_3: Color,
1318    pub bracket_rainbow_4: Color,
1319    pub bracket_rainbow_5: Color,
1320    pub bracket_rainbow_6: Color,
1321
1322    // Diff highlighting colors
1323    pub diff_add_bg: Color,
1324    pub diff_remove_bg: Color,
1325    pub diff_modify_bg: Color,
1326    /// Brighter background for inline diff highlighting on added content
1327    pub diff_add_highlight_bg: Color,
1328    /// Brighter background for inline diff highlighting on removed content
1329    pub diff_remove_highlight_bg: Color,
1330    /// Collision-only fg fallback for cells whose existing fg matches
1331    /// `diff_*_bg`. `None` keeps the cell's original fg; overlays opt
1332    /// into the override via `fg_on_collision_only`.
1333    pub diff_add_collision_fg: Option<Color>,
1334    pub diff_remove_collision_fg: Option<Color>,
1335    pub diff_modify_collision_fg: Option<Color>,
1336
1337    // UI element colors
1338    pub tab_active_fg: Color,
1339    pub tab_active_bg: Color,
1340    pub tab_inactive_fg: Color,
1341    pub tab_inactive_bg: Color,
1342    pub tab_separator_bg: Color,
1343    pub tab_close_hover_fg: Color,
1344    pub tab_hover_bg: Color,
1345
1346    // Menu bar colors
1347    pub menu_bg: Color,
1348    pub menu_fg: Color,
1349    pub menu_active_bg: Color,
1350    pub menu_active_fg: Color,
1351    pub menu_dropdown_bg: Color,
1352    pub menu_dropdown_fg: Color,
1353    pub menu_highlight_bg: Color,
1354    pub menu_highlight_fg: Color,
1355    pub menu_border_fg: Color,
1356    pub menu_separator_fg: Color,
1357    pub menu_hover_bg: Color,
1358    pub menu_hover_fg: Color,
1359    pub menu_disabled_fg: Color,
1360    pub menu_disabled_bg: Color,
1361
1362    pub status_bar_fg: Color,
1363    pub status_bar_bg: Color,
1364    /// Status bar palette shortcut hint colors (default: same as status bar)
1365    pub status_palette_fg: Color,
1366    pub status_palette_bg: Color,
1367    /// Status bar LSP indicator colors when running (default: same as status bar)
1368    pub status_lsp_on_fg: Color,
1369    pub status_lsp_on_bg: Color,
1370    /// Status bar LSP indicator colors when actionable options are available
1371    /// (configured-but-not-running). Default: same as status warning indicator.
1372    pub status_lsp_actionable_fg: Color,
1373    pub status_lsp_actionable_bg: Color,
1374    pub prompt_fg: Color,
1375    pub prompt_bg: Color,
1376    pub prompt_selection_fg: Color,
1377    pub prompt_selection_bg: Color,
1378
1379    pub popup_border_fg: Color,
1380    pub popup_bg: Color,
1381    pub popup_selection_bg: Color,
1382    pub popup_selection_fg: Color,
1383    pub popup_text_fg: Color,
1384    /// Background for the selection span inside a widget Text
1385    /// input. See the file-format field doc for why this isn't
1386    /// just `editor.selection_bg`.
1387    pub text_input_selection_bg: Color,
1388
1389    pub suggestion_bg: Color,
1390    pub suggestion_fg: Color,
1391    pub suggestion_selected_bg: Color,
1392
1393    pub help_bg: Color,
1394    pub help_fg: Color,
1395    pub help_key_fg: Color,
1396    pub help_separator_fg: Color,
1397
1398    pub help_indicator_fg: Color,
1399    pub help_indicator_bg: Color,
1400
1401    /// Background color for inline code in help popups
1402    pub inline_code_bg: Color,
1403
1404    pub split_separator_fg: Color,
1405    pub split_separator_hover_fg: Color,
1406
1407    // Scrollbar colors
1408    pub scrollbar_track_fg: Color,
1409    pub scrollbar_thumb_fg: Color,
1410    pub scrollbar_track_hover_fg: Color,
1411    pub scrollbar_thumb_hover_fg: Color,
1412
1413    // Compose mode colors
1414    pub compose_margin_bg: Color,
1415
1416    // Semantic highlighting (word under cursor)
1417    pub semantic_highlight_bg: Color,
1418    /// SGR text attributes layered onto current-word-highlight cells.
1419    /// Native-palette themes typically set `Modifier::BOLD` (so the
1420    /// word stands out without altering its color slot) or
1421    /// `Modifier::REVERSED`.
1422    pub semantic_highlight_modifier: Modifier,
1423
1424    // Terminal colors (for embedded terminal buffers)
1425    pub terminal_bg: Color,
1426    pub terminal_fg: Color,
1427
1428    // Status bar warning/error indicator colors
1429    pub status_warning_indicator_bg: Color,
1430    pub status_warning_indicator_fg: Color,
1431    pub status_error_indicator_bg: Color,
1432    pub status_error_indicator_fg: Color,
1433    pub status_warning_indicator_hover_bg: Color,
1434    pub status_warning_indicator_hover_fg: Color,
1435    pub status_error_indicator_hover_bg: Color,
1436    pub status_error_indicator_hover_fg: Color,
1437
1438    // Tab drag-and-drop colors
1439    pub tab_drop_zone_bg: Color,
1440    pub tab_drop_zone_border: Color,
1441
1442    // Settings UI colors
1443    pub settings_selected_bg: Color,
1444    pub settings_selected_fg: Color,
1445
1446    // File status colors (git status indicators in file explorer)
1447    pub file_status_added_fg: Color,
1448    pub file_status_modified_fg: Color,
1449    pub file_status_deleted_fg: Color,
1450    pub file_status_renamed_fg: Color,
1451    pub file_status_untracked_fg: Color,
1452    pub file_status_conflicted_fg: Color,
1453
1454    // Search colors
1455    pub search_match_bg: Color,
1456    pub search_match_fg: Color,
1457    pub search_label_bg: Color,
1458    pub search_label_fg: Color,
1459
1460    // Diagnostic colors
1461    pub diagnostic_error_fg: Color,
1462    pub diagnostic_error_bg: Color,
1463    pub diagnostic_warning_fg: Color,
1464    pub diagnostic_warning_bg: Color,
1465    pub diagnostic_info_fg: Color,
1466    pub diagnostic_info_bg: Color,
1467    pub diagnostic_hint_fg: Color,
1468    pub diagnostic_hint_bg: Color,
1469
1470    // Syntax highlighting colors
1471    pub syntax_keyword: Color,
1472    pub syntax_string: Color,
1473    pub syntax_comment: Color,
1474    pub syntax_function: Color,
1475    pub syntax_type: Color,
1476    pub syntax_variable: Color,
1477    pub syntax_variable_builtin: Color,
1478    pub syntax_constant: Color,
1479    pub syntax_operator: Color,
1480    pub syntax_punctuation_bracket: Color,
1481    pub syntax_punctuation_delimiter: Color,
1482}
1483
1484impl From<ThemeFile> for Theme {
1485    fn from(file: ThemeFile) -> Self {
1486        Self {
1487            name: file.name,
1488            editor_bg: file.editor.bg.clone().into(),
1489            editor_fg: file.editor.fg.into(),
1490            cursor: file.editor.cursor.into(),
1491            inactive_cursor: file.editor.inactive_cursor.into(),
1492            selection_bg: file.editor.selection_bg.into(),
1493            selection_modifier: file
1494                .editor
1495                .selection_modifier
1496                .as_ref()
1497                .map(Modifier::from)
1498                .unwrap_or(Modifier::empty()),
1499            current_line_bg: file.editor.current_line_bg.into(),
1500            line_number_fg: file.editor.line_number_fg.into(),
1501            line_number_bg: file.editor.line_number_bg.into(),
1502            // Use explicit override if provided, otherwise derive a subtle
1503            // contrasting shade from the editor background.
1504            after_eof_bg: file
1505                .editor
1506                .after_eof_bg
1507                .clone()
1508                .map(|c| c.into())
1509                .unwrap_or_else(|| shade_toward_contrast(file.editor.bg.clone().into(), 10)),
1510            ruler_bg: file.editor.ruler_bg.into(),
1511            whitespace_indicator_fg: file.editor.whitespace_indicator_fg.into(),
1512            bracket_match_fg: file.editor.bracket_match_fg.into(),
1513            bracket_rainbow_1: file.editor.bracket_rainbow_1.into(),
1514            bracket_rainbow_2: file.editor.bracket_rainbow_2.into(),
1515            bracket_rainbow_3: file.editor.bracket_rainbow_3.into(),
1516            bracket_rainbow_4: file.editor.bracket_rainbow_4.into(),
1517            bracket_rainbow_5: file.editor.bracket_rainbow_5.into(),
1518            bracket_rainbow_6: file.editor.bracket_rainbow_6.into(),
1519            diff_add_bg: file.editor.diff_add_bg.clone().into(),
1520            diff_remove_bg: file.editor.diff_remove_bg.clone().into(),
1521            diff_modify_bg: file.editor.diff_modify_bg.into(),
1522            // Use explicit override if provided, otherwise brighten from base
1523            diff_add_highlight_bg: file
1524                .editor
1525                .diff_add_highlight_bg
1526                .map(|c| c.into())
1527                .unwrap_or_else(|| brighten_color(file.editor.diff_add_bg.into(), 40)),
1528            diff_remove_highlight_bg: file
1529                .editor
1530                .diff_remove_highlight_bg
1531                .map(|c| c.into())
1532                .unwrap_or_else(|| brighten_color(file.editor.diff_remove_bg.into(), 40)),
1533            diff_add_collision_fg: file.editor.diff_add_collision_fg.clone().map(|c| c.into()),
1534            diff_remove_collision_fg: file
1535                .editor
1536                .diff_remove_collision_fg
1537                .clone()
1538                .map(|c| c.into()),
1539            diff_modify_collision_fg: file
1540                .editor
1541                .diff_modify_collision_fg
1542                .clone()
1543                .map(|c| c.into()),
1544            tab_active_fg: file.ui.tab_active_fg.into(),
1545            tab_active_bg: file.ui.tab_active_bg.into(),
1546            tab_inactive_fg: file.ui.tab_inactive_fg.into(),
1547            tab_inactive_bg: file.ui.tab_inactive_bg.into(),
1548            tab_separator_bg: file.ui.tab_separator_bg.into(),
1549            tab_close_hover_fg: file.ui.tab_close_hover_fg.into(),
1550            tab_hover_bg: file.ui.tab_hover_bg.into(),
1551            menu_bg: file.ui.menu_bg.into(),
1552            menu_fg: file.ui.menu_fg.into(),
1553            menu_active_bg: file.ui.menu_active_bg.into(),
1554            menu_active_fg: file.ui.menu_active_fg.into(),
1555            menu_dropdown_bg: file.ui.menu_dropdown_bg.into(),
1556            menu_dropdown_fg: file.ui.menu_dropdown_fg.into(),
1557            menu_highlight_bg: file.ui.menu_highlight_bg.into(),
1558            menu_highlight_fg: file.ui.menu_highlight_fg.into(),
1559            menu_border_fg: file.ui.menu_border_fg.into(),
1560            menu_separator_fg: file.ui.menu_separator_fg.into(),
1561            menu_hover_bg: file.ui.menu_hover_bg.into(),
1562            menu_hover_fg: file.ui.menu_hover_fg.into(),
1563            menu_disabled_fg: file.ui.menu_disabled_fg.into(),
1564            menu_disabled_bg: file.ui.menu_disabled_bg.into(),
1565            status_bar_fg: file.ui.status_bar_fg.clone().into(),
1566            status_bar_bg: file.ui.status_bar_bg.clone().into(),
1567            status_palette_fg: file
1568                .ui
1569                .status_palette_fg
1570                .clone()
1571                .map(|c| c.into())
1572                .unwrap_or_else(|| file.ui.status_bar_fg.clone().into()),
1573            status_palette_bg: file
1574                .ui
1575                .status_palette_bg
1576                .clone()
1577                .map(|c| c.into())
1578                .unwrap_or_else(|| file.ui.status_bar_bg.clone().into()),
1579            status_lsp_on_fg: file
1580                .ui
1581                .status_lsp_on_fg
1582                .clone()
1583                .map(|c| c.into())
1584                .unwrap_or_else(|| file.ui.status_bar_fg.clone().into()),
1585            status_lsp_on_bg: file
1586                .ui
1587                .status_lsp_on_bg
1588                .clone()
1589                .map(|c| c.into())
1590                .unwrap_or_else(|| file.ui.status_bar_bg.clone().into()),
1591            status_lsp_actionable_fg: file
1592                .ui
1593                .status_lsp_actionable_fg
1594                .clone()
1595                .map(|c| c.into())
1596                .unwrap_or_else(|| file.ui.status_warning_indicator_fg.clone().into()),
1597            status_lsp_actionable_bg: file
1598                .ui
1599                .status_lsp_actionable_bg
1600                .clone()
1601                .map(|c| c.into())
1602                .unwrap_or_else(|| file.ui.status_warning_indicator_bg.clone().into()),
1603            prompt_fg: file.ui.prompt_fg.into(),
1604            prompt_bg: file.ui.prompt_bg.into(),
1605            prompt_selection_fg: file.ui.prompt_selection_fg.into(),
1606            prompt_selection_bg: file.ui.prompt_selection_bg.into(),
1607            popup_border_fg: file.ui.popup_border_fg.into(),
1608            popup_bg: file.ui.popup_bg.into(),
1609            popup_selection_bg: file.ui.popup_selection_bg.into(),
1610            popup_selection_fg: file.ui.popup_selection_fg.into(),
1611            popup_text_fg: file.ui.popup_text_fg.clone().into(),
1612            text_input_selection_bg: file.ui.text_input_selection_bg.into(),
1613            suggestion_bg: file.ui.suggestion_bg.into(),
1614            suggestion_fg: file
1615                .ui
1616                .suggestion_fg
1617                .clone()
1618                .map(|c| c.into())
1619                .unwrap_or_else(|| file.ui.popup_text_fg.clone().into()),
1620            suggestion_selected_bg: file.ui.suggestion_selected_bg.into(),
1621            help_bg: file.ui.help_bg.into(),
1622            help_fg: file.ui.help_fg.into(),
1623            help_key_fg: file.ui.help_key_fg.into(),
1624            help_separator_fg: file.ui.help_separator_fg.into(),
1625            help_indicator_fg: file.ui.help_indicator_fg.into(),
1626            help_indicator_bg: file.ui.help_indicator_bg.into(),
1627            inline_code_bg: file.ui.inline_code_bg.into(),
1628            split_separator_fg: file.ui.split_separator_fg.into(),
1629            split_separator_hover_fg: file.ui.split_separator_hover_fg.into(),
1630            scrollbar_track_fg: file.ui.scrollbar_track_fg.into(),
1631            scrollbar_thumb_fg: file.ui.scrollbar_thumb_fg.into(),
1632            scrollbar_track_hover_fg: file.ui.scrollbar_track_hover_fg.into(),
1633            scrollbar_thumb_hover_fg: file.ui.scrollbar_thumb_hover_fg.into(),
1634            compose_margin_bg: file.ui.compose_margin_bg.into(),
1635            semantic_highlight_bg: file.ui.semantic_highlight_bg.into(),
1636            semantic_highlight_modifier: file
1637                .ui
1638                .semantic_highlight_modifier
1639                .as_ref()
1640                .map(Modifier::from)
1641                .unwrap_or(Modifier::empty()),
1642            terminal_bg: file.ui.terminal_bg.into(),
1643            terminal_fg: file.ui.terminal_fg.into(),
1644            status_warning_indicator_bg: file.ui.status_warning_indicator_bg.into(),
1645            status_warning_indicator_fg: file.ui.status_warning_indicator_fg.into(),
1646            status_error_indicator_bg: file.ui.status_error_indicator_bg.into(),
1647            status_error_indicator_fg: file.ui.status_error_indicator_fg.into(),
1648            status_warning_indicator_hover_bg: file.ui.status_warning_indicator_hover_bg.into(),
1649            status_warning_indicator_hover_fg: file.ui.status_warning_indicator_hover_fg.into(),
1650            status_error_indicator_hover_bg: file.ui.status_error_indicator_hover_bg.into(),
1651            status_error_indicator_hover_fg: file.ui.status_error_indicator_hover_fg.into(),
1652            tab_drop_zone_bg: file.ui.tab_drop_zone_bg.into(),
1653            tab_drop_zone_border: file.ui.tab_drop_zone_border.into(),
1654            settings_selected_bg: file.ui.settings_selected_bg.into(),
1655            settings_selected_fg: file.ui.settings_selected_fg.into(),
1656            file_status_added_fg: file
1657                .ui
1658                .file_status_added_fg
1659                .map(|c| c.into())
1660                .unwrap_or_else(|| file.diagnostic.info_fg.clone().into()),
1661            file_status_modified_fg: file
1662                .ui
1663                .file_status_modified_fg
1664                .map(|c| c.into())
1665                .unwrap_or_else(|| file.diagnostic.warning_fg.clone().into()),
1666            file_status_deleted_fg: file
1667                .ui
1668                .file_status_deleted_fg
1669                .map(|c| c.into())
1670                .unwrap_or_else(|| file.diagnostic.error_fg.clone().into()),
1671            file_status_renamed_fg: file
1672                .ui
1673                .file_status_renamed_fg
1674                .map(|c| c.into())
1675                .unwrap_or_else(|| file.diagnostic.info_fg.clone().into()),
1676            file_status_untracked_fg: file
1677                .ui
1678                .file_status_untracked_fg
1679                .map(|c| c.into())
1680                .unwrap_or_else(|| file.diagnostic.hint_fg.clone().into()),
1681            file_status_conflicted_fg: file
1682                .ui
1683                .file_status_conflicted_fg
1684                .map(|c| c.into())
1685                .unwrap_or_else(|| file.diagnostic.error_fg.clone().into()),
1686            search_match_bg: file.search.match_bg.into(),
1687            search_match_fg: file.search.match_fg.into(),
1688            search_label_bg: file.search.label_bg.into(),
1689            search_label_fg: file.search.label_fg.into(),
1690            diagnostic_error_fg: file.diagnostic.error_fg.into(),
1691            diagnostic_error_bg: file.diagnostic.error_bg.into(),
1692            diagnostic_warning_fg: file.diagnostic.warning_fg.into(),
1693            diagnostic_warning_bg: file.diagnostic.warning_bg.into(),
1694            diagnostic_info_fg: file.diagnostic.info_fg.into(),
1695            diagnostic_info_bg: file.diagnostic.info_bg.into(),
1696            diagnostic_hint_fg: file.diagnostic.hint_fg.into(),
1697            diagnostic_hint_bg: file.diagnostic.hint_bg.into(),
1698            syntax_keyword: file.syntax.keyword.into(),
1699            syntax_string: file.syntax.string.into(),
1700            syntax_comment: file.syntax.comment.into(),
1701            syntax_function: file.syntax.function.into(),
1702            syntax_type: file.syntax.type_.into(),
1703            syntax_variable: file.syntax.variable.into(),
1704            syntax_variable_builtin: file.syntax.variable_builtin.into(),
1705            syntax_constant: file.syntax.constant.into(),
1706            syntax_operator: file.syntax.operator.into(),
1707            syntax_punctuation_bracket: file.syntax.punctuation_bracket.into(),
1708            syntax_punctuation_delimiter: file.syntax.punctuation_delimiter.into(),
1709        }
1710    }
1711}
1712
1713impl From<Theme> for ThemeFile {
1714    fn from(theme: Theme) -> Self {
1715        Self {
1716            name: theme.name,
1717            // A round-tripped `Theme` is already fully resolved — no further
1718            // inheritance is needed when serializing back out.
1719            extends: None,
1720            editor: EditorColors {
1721                bg: theme.editor_bg.into(),
1722                fg: theme.editor_fg.into(),
1723                cursor: theme.cursor.into(),
1724                inactive_cursor: theme.inactive_cursor.into(),
1725                selection_bg: theme.selection_bg.into(),
1726                selection_modifier: if theme.selection_modifier.is_empty() {
1727                    None
1728                } else {
1729                    Some(theme.selection_modifier.into())
1730                },
1731                current_line_bg: theme.current_line_bg.into(),
1732                line_number_fg: theme.line_number_fg.into(),
1733                line_number_bg: theme.line_number_bg.into(),
1734                diff_add_bg: theme.diff_add_bg.into(),
1735                diff_remove_bg: theme.diff_remove_bg.into(),
1736                diff_add_highlight_bg: Some(theme.diff_add_highlight_bg.into()),
1737                diff_remove_highlight_bg: Some(theme.diff_remove_highlight_bg.into()),
1738                diff_modify_bg: theme.diff_modify_bg.into(),
1739                diff_add_collision_fg: theme.diff_add_collision_fg.map(|c| c.into()),
1740                diff_remove_collision_fg: theme.diff_remove_collision_fg.map(|c| c.into()),
1741                diff_modify_collision_fg: theme.diff_modify_collision_fg.map(|c| c.into()),
1742                ruler_bg: theme.ruler_bg.into(),
1743                whitespace_indicator_fg: theme.whitespace_indicator_fg.into(),
1744                bracket_match_fg: theme.bracket_match_fg.into(),
1745                bracket_rainbow_1: theme.bracket_rainbow_1.into(),
1746                bracket_rainbow_2: theme.bracket_rainbow_2.into(),
1747                bracket_rainbow_3: theme.bracket_rainbow_3.into(),
1748                bracket_rainbow_4: theme.bracket_rainbow_4.into(),
1749                bracket_rainbow_5: theme.bracket_rainbow_5.into(),
1750                bracket_rainbow_6: theme.bracket_rainbow_6.into(),
1751                after_eof_bg: Some(theme.after_eof_bg.into()),
1752            },
1753            ui: UiColors {
1754                tab_active_fg: theme.tab_active_fg.into(),
1755                tab_active_bg: theme.tab_active_bg.into(),
1756                tab_inactive_fg: theme.tab_inactive_fg.into(),
1757                tab_inactive_bg: theme.tab_inactive_bg.into(),
1758                tab_separator_bg: theme.tab_separator_bg.into(),
1759                tab_close_hover_fg: theme.tab_close_hover_fg.into(),
1760                tab_hover_bg: theme.tab_hover_bg.into(),
1761                menu_bg: theme.menu_bg.into(),
1762                menu_fg: theme.menu_fg.into(),
1763                menu_active_bg: theme.menu_active_bg.into(),
1764                menu_active_fg: theme.menu_active_fg.into(),
1765                menu_dropdown_bg: theme.menu_dropdown_bg.into(),
1766                menu_dropdown_fg: theme.menu_dropdown_fg.into(),
1767                menu_highlight_bg: theme.menu_highlight_bg.into(),
1768                menu_highlight_fg: theme.menu_highlight_fg.into(),
1769                menu_border_fg: theme.menu_border_fg.into(),
1770                menu_separator_fg: theme.menu_separator_fg.into(),
1771                menu_hover_bg: theme.menu_hover_bg.into(),
1772                menu_hover_fg: theme.menu_hover_fg.into(),
1773                menu_disabled_fg: theme.menu_disabled_fg.into(),
1774                menu_disabled_bg: theme.menu_disabled_bg.into(),
1775                status_bar_fg: theme.status_bar_fg.into(),
1776                status_bar_bg: theme.status_bar_bg.into(),
1777                status_palette_fg: Some(theme.status_palette_fg.into()),
1778                status_palette_bg: Some(theme.status_palette_bg.into()),
1779                status_lsp_on_fg: Some(theme.status_lsp_on_fg.into()),
1780                status_lsp_on_bg: Some(theme.status_lsp_on_bg.into()),
1781                status_lsp_actionable_fg: Some(theme.status_lsp_actionable_fg.into()),
1782                status_lsp_actionable_bg: Some(theme.status_lsp_actionable_bg.into()),
1783                prompt_fg: theme.prompt_fg.into(),
1784                prompt_bg: theme.prompt_bg.into(),
1785                prompt_selection_fg: theme.prompt_selection_fg.into(),
1786                prompt_selection_bg: theme.prompt_selection_bg.into(),
1787                popup_border_fg: theme.popup_border_fg.into(),
1788                popup_bg: theme.popup_bg.into(),
1789                popup_selection_bg: theme.popup_selection_bg.into(),
1790                popup_selection_fg: theme.popup_selection_fg.into(),
1791                popup_text_fg: theme.popup_text_fg.into(),
1792                text_input_selection_bg: theme.text_input_selection_bg.into(),
1793                suggestion_bg: theme.suggestion_bg.into(),
1794                suggestion_fg: Some(theme.suggestion_fg.into()),
1795                suggestion_selected_bg: theme.suggestion_selected_bg.into(),
1796                help_bg: theme.help_bg.into(),
1797                help_fg: theme.help_fg.into(),
1798                help_key_fg: theme.help_key_fg.into(),
1799                help_separator_fg: theme.help_separator_fg.into(),
1800                help_indicator_fg: theme.help_indicator_fg.into(),
1801                help_indicator_bg: theme.help_indicator_bg.into(),
1802                inline_code_bg: theme.inline_code_bg.into(),
1803                split_separator_fg: theme.split_separator_fg.into(),
1804                split_separator_hover_fg: theme.split_separator_hover_fg.into(),
1805                scrollbar_track_fg: theme.scrollbar_track_fg.into(),
1806                scrollbar_thumb_fg: theme.scrollbar_thumb_fg.into(),
1807                scrollbar_track_hover_fg: theme.scrollbar_track_hover_fg.into(),
1808                scrollbar_thumb_hover_fg: theme.scrollbar_thumb_hover_fg.into(),
1809                compose_margin_bg: theme.compose_margin_bg.into(),
1810                semantic_highlight_bg: theme.semantic_highlight_bg.into(),
1811                semantic_highlight_modifier: if theme.semantic_highlight_modifier.is_empty() {
1812                    None
1813                } else {
1814                    Some(theme.semantic_highlight_modifier.into())
1815                },
1816                terminal_bg: theme.terminal_bg.into(),
1817                terminal_fg: theme.terminal_fg.into(),
1818                status_warning_indicator_bg: theme.status_warning_indicator_bg.into(),
1819                status_warning_indicator_fg: theme.status_warning_indicator_fg.into(),
1820                status_error_indicator_bg: theme.status_error_indicator_bg.into(),
1821                status_error_indicator_fg: theme.status_error_indicator_fg.into(),
1822                status_warning_indicator_hover_bg: theme.status_warning_indicator_hover_bg.into(),
1823                status_warning_indicator_hover_fg: theme.status_warning_indicator_hover_fg.into(),
1824                status_error_indicator_hover_bg: theme.status_error_indicator_hover_bg.into(),
1825                status_error_indicator_hover_fg: theme.status_error_indicator_hover_fg.into(),
1826                tab_drop_zone_bg: theme.tab_drop_zone_bg.into(),
1827                tab_drop_zone_border: theme.tab_drop_zone_border.into(),
1828                settings_selected_bg: theme.settings_selected_bg.into(),
1829                settings_selected_fg: theme.settings_selected_fg.into(),
1830                file_status_added_fg: Some(theme.file_status_added_fg.into()),
1831                file_status_modified_fg: Some(theme.file_status_modified_fg.into()),
1832                file_status_deleted_fg: Some(theme.file_status_deleted_fg.into()),
1833                file_status_renamed_fg: Some(theme.file_status_renamed_fg.into()),
1834                file_status_untracked_fg: Some(theme.file_status_untracked_fg.into()),
1835                file_status_conflicted_fg: Some(theme.file_status_conflicted_fg.into()),
1836            },
1837            search: SearchColors {
1838                match_bg: theme.search_match_bg.into(),
1839                match_fg: theme.search_match_fg.into(),
1840                label_bg: theme.search_label_bg.into(),
1841                label_fg: theme.search_label_fg.into(),
1842            },
1843            diagnostic: DiagnosticColors {
1844                error_fg: theme.diagnostic_error_fg.into(),
1845                error_bg: theme.diagnostic_error_bg.into(),
1846                warning_fg: theme.diagnostic_warning_fg.into(),
1847                warning_bg: theme.diagnostic_warning_bg.into(),
1848                info_fg: theme.diagnostic_info_fg.into(),
1849                info_bg: theme.diagnostic_info_bg.into(),
1850                hint_fg: theme.diagnostic_hint_fg.into(),
1851                hint_bg: theme.diagnostic_hint_bg.into(),
1852            },
1853            syntax: SyntaxColors {
1854                keyword: theme.syntax_keyword.into(),
1855                string: theme.syntax_string.into(),
1856                comment: theme.syntax_comment.into(),
1857                function: theme.syntax_function.into(),
1858                type_: theme.syntax_type.into(),
1859                variable: theme.syntax_variable.into(),
1860                variable_builtin: theme.syntax_variable_builtin.into(),
1861                constant: theme.syntax_constant.into(),
1862                operator: theme.syntax_operator.into(),
1863                punctuation_bracket: theme.syntax_punctuation_bracket.into(),
1864                punctuation_delimiter: theme.syntax_punctuation_delimiter.into(),
1865            },
1866        }
1867    }
1868}
1869
1870/// Resolve the base theme that a parsed `ThemeFile` should be layered on top of.
1871///
1872/// See [`ThemeFile`] for the resolution order. Returns an error only when
1873/// `extends` references a base that does not exist; the no-info-at-all case
1874/// quietly falls through to the per-field hardcoded defaults so a theme of
1875/// `{"name": "x"}` keeps working.
1876fn resolve_base_theme(theme_file: &ThemeFile, raw: &serde_json::Value) -> Result<Theme, String> {
1877    // 1. Explicit `extends`.
1878    if let Some(extends) = theme_file.extends.as_deref() {
1879        let name = extends.strip_prefix("builtin://").unwrap_or(extends);
1880        return Theme::load_builtin(name).ok_or_else(|| {
1881            let available: Vec<&str> = BUILTIN_THEMES.iter().map(|t| t.name).collect();
1882            format!(
1883                "theme `extends: {:?}` does not match any built-in theme. \
1884                 Available: {}. \
1885                 Inheriting from other user themes is not yet supported.",
1886                extends,
1887                available.join(", ")
1888            )
1889        });
1890    }
1891
1892    // 2. Auto-infer from explicit `editor.bg` luminance. We deliberately read
1893    //    the *raw* JSON here instead of `theme_file.editor.bg` — the typed
1894    //    struct fills in a default for `bg` even when the user didn't write
1895    //    one, and inferring a base from a default we ourselves invented would
1896    //    be circular.
1897    if let Some(bg) = raw
1898        .get("editor")
1899        .and_then(|e| e.get("bg"))
1900        .cloned()
1901        .and_then(|v| serde_json::from_value::<ColorDef>(v).ok())
1902    {
1903        let color: Color = bg.into();
1904        if let Some((r, g, b)) = color_to_rgb(color) {
1905            let lum = relative_luminance(r, g, b);
1906            let base_name = if lum > 0.5 { THEME_LIGHT } else { THEME_DARK };
1907            if let Some(base) = Theme::load_builtin(base_name) {
1908                return Ok(base);
1909            }
1910        }
1911    }
1912
1913    // 3. Fallback: per-field hardcoded defaults via the existing typed path.
1914    Ok(theme_file.clone().into())
1915}
1916
1917/// Compute sRGB relative luminance (ITU-R BT.709) for an RGB triple in 0..=255.
1918/// Used for picking a light vs dark base when the user didn't ask for one.
1919fn relative_luminance(r: u8, g: u8, b: u8) -> f64 {
1920    0.2126 * (r as f64 / 255.0) + 0.7152 * (g as f64 / 255.0) + 0.0722 * (b as f64 / 255.0)
1921}
1922
1923/// Walk the user-supplied JSON and overlay every explicitly-set leaf onto the
1924/// base theme. Reuses [`Theme::resolve_theme_key_mut`] so the override surface
1925/// is exactly the surface the rest of the editor already knows how to address;
1926/// unknown keys are silently ignored, matching `override_colors` semantics.
1927fn apply_theme_overrides(theme: &mut Theme, theme_file: &ThemeFile, raw: &serde_json::Value) {
1928    // Name always comes from the user file — that's the theme's identity.
1929    theme.name = theme_file.name.clone();
1930
1931    for section in ["editor", "ui", "search", "diagnostic", "syntax"] {
1932        let Some(obj) = raw.get(section).and_then(|v| v.as_object()) else {
1933            continue;
1934        };
1935        for (field, value) in obj {
1936            // Optional `Option<ColorDef>` fields encode `null` as JSON null.
1937            // Treat that as "no override," not "set to default."
1938            if value.is_null() {
1939                continue;
1940            }
1941            let key = format!("{}.{}", section, field);
1942            if let Ok(color_def) = serde_json::from_value::<ColorDef>(value.clone()) {
1943                if let Some(slot) = theme.resolve_theme_key_mut(&key) {
1944                    *slot = color_def.into();
1945                }
1946            }
1947        }
1948    }
1949}
1950
1951impl Theme {
1952    /// Returns `true` when the theme has a light background.
1953    ///
1954    /// Uses the relative luminance of `editor_bg` (perceived brightness).
1955    /// A threshold of 0.5 separates dark from light; for `Color::Reset` or
1956    /// unresolvable colors, falls back to `false` (dark).
1957    pub fn is_light(&self) -> bool {
1958        color_to_rgb(self.editor_bg)
1959            .map(|(r, g, b)| relative_luminance(r, g, b) > 0.5)
1960            .unwrap_or(false)
1961    }
1962
1963    /// Load a builtin theme by name (no I/O, uses embedded JSON).
1964    pub fn load_builtin(name: &str) -> Option<Self> {
1965        BUILTIN_THEMES
1966            .iter()
1967            .find(|t| t.name == name)
1968            .and_then(|t| serde_json::from_str::<ThemeFile>(t.json).ok())
1969            .map(|tf| tf.into())
1970    }
1971
1972    /// Parse theme from JSON string (no I/O).
1973    ///
1974    /// Supports the inheritance model documented on [`ThemeFile`]: an explicit
1975    /// `extends` chooses the base; otherwise the relative luminance of an
1976    /// explicit `editor.bg` picks `builtin://light` vs `builtin://dark`;
1977    /// otherwise the per-field hardcoded defaults apply. Every leaf the user
1978    /// JSON specifies overrides the corresponding field on the base — the
1979    /// override walk uses the same `resolve_theme_key_mut` machinery as
1980    /// `override_colors`, so the supported set of keys stays in lock-step.
1981    pub fn from_json(json: &str) -> Result<Self, String> {
1982        // Dual-parse: the typed `ThemeFile` validates the schema and gives us
1983        // `name` / `extends` cheaply; the raw `Value` tells us *which* fields
1984        // the user actually specified, which we cannot recover from the typed
1985        // struct because every field has a serde default.
1986        let raw: serde_json::Value =
1987            serde_json::from_str(json).map_err(|e| format!("Failed to parse theme JSON: {}", e))?;
1988        let theme_file: ThemeFile = serde_json::from_value(raw.clone())
1989            .map_err(|e| format!("Failed to parse theme: {}", e))?;
1990
1991        let mut theme = resolve_base_theme(&theme_file, &raw)?;
1992        apply_theme_overrides(&mut theme, &theme_file, &raw);
1993        Ok(theme)
1994    }
1995
1996    /// SGR text-attribute modifier associated with a bg theme key.
1997    ///
1998    /// Lets overlay-driven highlights (e.g. word-under-cursor via
1999    /// `ui.semantic_highlight_bg`, selection via `editor.selection_bg`)
2000    /// pick up the same modifier the theme would apply directly when
2001    /// painting that region, so a `terminal` theme's `["reversed"]`
2002    /// selection works whether the cells go through `char_style` or
2003    /// the overlay pipeline. Unknown keys return `Modifier::empty()`.
2004    pub fn modifier_for_bg_key(&self, key: &str) -> Modifier {
2005        match key {
2006            "editor.selection_bg" => self.selection_modifier,
2007            "ui.semantic_highlight_bg" => self.semantic_highlight_modifier,
2008            _ => Modifier::empty(),
2009        }
2010    }
2011
2012    /// Resolve a theme key to a Color.
2013    ///
2014    /// Theme keys use dot notation: "section.field"
2015    /// Examples:
2016    /// - "ui.status_bar_fg" -> status_bar_fg
2017    /// - "editor.selection_bg" -> selection_bg
2018    /// - "syntax.keyword" -> syntax_keyword
2019    /// - "diagnostic.error_fg" -> diagnostic_error_fg
2020    ///
2021    /// Returns None if the key is not recognized.
2022    pub fn resolve_theme_key(&self, key: &str) -> Option<Color> {
2023        // Parse "section.field" format
2024        let parts: Vec<&str> = key.split('.').collect();
2025        if parts.len() != 2 {
2026            return None;
2027        }
2028
2029        let (section, field) = (parts[0], parts[1]);
2030
2031        match section {
2032            "editor" => match field {
2033                "after_eof_bg" => Some(self.after_eof_bg),
2034                "bg" => Some(self.editor_bg),
2035                "current_line_bg" => Some(self.current_line_bg),
2036                "cursor" => Some(self.cursor),
2037                "diff_add_bg" => Some(self.diff_add_bg),
2038                "diff_add_collision_fg" => self.diff_add_collision_fg,
2039                "diff_add_highlight_bg" => Some(self.diff_add_highlight_bg),
2040                "diff_modify_bg" => Some(self.diff_modify_bg),
2041                "diff_modify_collision_fg" => self.diff_modify_collision_fg,
2042                "diff_remove_bg" => Some(self.diff_remove_bg),
2043                "diff_remove_collision_fg" => self.diff_remove_collision_fg,
2044                "diff_remove_highlight_bg" => Some(self.diff_remove_highlight_bg),
2045                "fg" => Some(self.editor_fg),
2046                "inactive_cursor" => Some(self.inactive_cursor),
2047                "line_number_bg" => Some(self.line_number_bg),
2048                "line_number_fg" => Some(self.line_number_fg),
2049                "ruler_bg" => Some(self.ruler_bg),
2050                "selection_bg" => Some(self.selection_bg),
2051                "whitespace_indicator_fg" => Some(self.whitespace_indicator_fg),
2052                "bracket_match_fg" => Some(self.bracket_match_fg),
2053                "bracket_rainbow_1" => Some(self.bracket_rainbow_1),
2054                "bracket_rainbow_2" => Some(self.bracket_rainbow_2),
2055                "bracket_rainbow_3" => Some(self.bracket_rainbow_3),
2056                "bracket_rainbow_4" => Some(self.bracket_rainbow_4),
2057                "bracket_rainbow_5" => Some(self.bracket_rainbow_5),
2058                "bracket_rainbow_6" => Some(self.bracket_rainbow_6),
2059                _ => None,
2060            },
2061            "ui" => match field {
2062                "compose_margin_bg" => Some(self.compose_margin_bg),
2063                "file_status_added_fg" => Some(self.file_status_added_fg),
2064                "file_status_conflicted_fg" => Some(self.file_status_conflicted_fg),
2065                "file_status_deleted_fg" => Some(self.file_status_deleted_fg),
2066                "file_status_modified_fg" => Some(self.file_status_modified_fg),
2067                "file_status_renamed_fg" => Some(self.file_status_renamed_fg),
2068                "file_status_untracked_fg" => Some(self.file_status_untracked_fg),
2069                "help_bg" => Some(self.help_bg),
2070                "help_fg" => Some(self.help_fg),
2071                "help_indicator_bg" => Some(self.help_indicator_bg),
2072                "help_indicator_fg" => Some(self.help_indicator_fg),
2073                "help_key_fg" => Some(self.help_key_fg),
2074                "help_separator_fg" => Some(self.help_separator_fg),
2075                "inline_code_bg" => Some(self.inline_code_bg),
2076                "menu_active_bg" => Some(self.menu_active_bg),
2077                "menu_active_fg" => Some(self.menu_active_fg),
2078                "menu_bg" => Some(self.menu_bg),
2079                "menu_border_fg" => Some(self.menu_border_fg),
2080                "menu_disabled_bg" => Some(self.menu_disabled_bg),
2081                "menu_disabled_fg" => Some(self.menu_disabled_fg),
2082                "menu_dropdown_bg" => Some(self.menu_dropdown_bg),
2083                "menu_dropdown_fg" => Some(self.menu_dropdown_fg),
2084                "menu_fg" => Some(self.menu_fg),
2085                "menu_highlight_bg" => Some(self.menu_highlight_bg),
2086                "menu_highlight_fg" => Some(self.menu_highlight_fg),
2087                "menu_hover_bg" => Some(self.menu_hover_bg),
2088                "menu_hover_fg" => Some(self.menu_hover_fg),
2089                "menu_separator_fg" => Some(self.menu_separator_fg),
2090                "popup_bg" => Some(self.popup_bg),
2091                "popup_border_fg" => Some(self.popup_border_fg),
2092                "popup_selection_bg" => Some(self.popup_selection_bg),
2093                "popup_selection_fg" => Some(self.popup_selection_fg),
2094                "popup_text_fg" => Some(self.popup_text_fg),
2095                "prompt_bg" => Some(self.prompt_bg),
2096                "prompt_fg" => Some(self.prompt_fg),
2097                "prompt_selection_bg" => Some(self.prompt_selection_bg),
2098                "prompt_selection_fg" => Some(self.prompt_selection_fg),
2099                "scrollbar_thumb_fg" => Some(self.scrollbar_thumb_fg),
2100                "scrollbar_thumb_hover_fg" => Some(self.scrollbar_thumb_hover_fg),
2101                "scrollbar_track_fg" => Some(self.scrollbar_track_fg),
2102                "scrollbar_track_hover_fg" => Some(self.scrollbar_track_hover_fg),
2103                "semantic_highlight_bg" => Some(self.semantic_highlight_bg),
2104                "settings_selected_bg" => Some(self.settings_selected_bg),
2105                "settings_selected_fg" => Some(self.settings_selected_fg),
2106                "split_separator_fg" => Some(self.split_separator_fg),
2107                "split_separator_hover_fg" => Some(self.split_separator_hover_fg),
2108                "status_bar_bg" => Some(self.status_bar_bg),
2109                "status_bar_fg" => Some(self.status_bar_fg),
2110                "status_error_indicator_bg" => Some(self.status_error_indicator_bg),
2111                "status_error_indicator_fg" => Some(self.status_error_indicator_fg),
2112                "status_error_indicator_hover_bg" => Some(self.status_error_indicator_hover_bg),
2113                "status_error_indicator_hover_fg" => Some(self.status_error_indicator_hover_fg),
2114                "status_lsp_actionable_bg" => Some(self.status_lsp_actionable_bg),
2115                "status_lsp_actionable_fg" => Some(self.status_lsp_actionable_fg),
2116                "status_lsp_on_bg" => Some(self.status_lsp_on_bg),
2117                "status_lsp_on_fg" => Some(self.status_lsp_on_fg),
2118                "status_palette_bg" => Some(self.status_palette_bg),
2119                "status_palette_fg" => Some(self.status_palette_fg),
2120                "status_warning_indicator_bg" => Some(self.status_warning_indicator_bg),
2121                "status_warning_indicator_fg" => Some(self.status_warning_indicator_fg),
2122                "status_warning_indicator_hover_bg" => Some(self.status_warning_indicator_hover_bg),
2123                "status_warning_indicator_hover_fg" => Some(self.status_warning_indicator_hover_fg),
2124                "suggestion_bg" => Some(self.suggestion_bg),
2125                "suggestion_fg" => Some(self.suggestion_fg),
2126                "suggestion_selected_bg" => Some(self.suggestion_selected_bg),
2127                "tab_active_bg" => Some(self.tab_active_bg),
2128                "tab_active_fg" => Some(self.tab_active_fg),
2129                "tab_close_hover_fg" => Some(self.tab_close_hover_fg),
2130                "tab_drop_zone_bg" => Some(self.tab_drop_zone_bg),
2131                "tab_drop_zone_border" => Some(self.tab_drop_zone_border),
2132                "tab_hover_bg" => Some(self.tab_hover_bg),
2133                "tab_inactive_bg" => Some(self.tab_inactive_bg),
2134                "tab_inactive_fg" => Some(self.tab_inactive_fg),
2135                "tab_separator_bg" => Some(self.tab_separator_bg),
2136                "terminal_bg" => Some(self.terminal_bg),
2137                "terminal_fg" => Some(self.terminal_fg),
2138                "text_input_selection_bg" => Some(self.text_input_selection_bg),
2139                _ => None,
2140            },
2141            "syntax" => match field {
2142                "comment" => Some(self.syntax_comment),
2143                "constant" => Some(self.syntax_constant),
2144                "function" => Some(self.syntax_function),
2145                "keyword" => Some(self.syntax_keyword),
2146                "operator" => Some(self.syntax_operator),
2147                "punctuation_bracket" => Some(self.syntax_punctuation_bracket),
2148                "punctuation_delimiter" => Some(self.syntax_punctuation_delimiter),
2149                "string" => Some(self.syntax_string),
2150                "type" => Some(self.syntax_type),
2151                "variable" => Some(self.syntax_variable),
2152                "variable_builtin" => Some(self.syntax_variable_builtin),
2153                _ => None,
2154            },
2155            "diagnostic" => match field {
2156                "error_bg" => Some(self.diagnostic_error_bg),
2157                "error_fg" => Some(self.diagnostic_error_fg),
2158                "hint_bg" => Some(self.diagnostic_hint_bg),
2159                "hint_fg" => Some(self.diagnostic_hint_fg),
2160                "info_bg" => Some(self.diagnostic_info_bg),
2161                "info_fg" => Some(self.diagnostic_info_fg),
2162                "warning_bg" => Some(self.diagnostic_warning_bg),
2163                "warning_fg" => Some(self.diagnostic_warning_fg),
2164                _ => None,
2165            },
2166            "search" => match field {
2167                "label_bg" => Some(self.search_label_bg),
2168                "label_fg" => Some(self.search_label_fg),
2169                "match_bg" => Some(self.search_match_bg),
2170                "match_fg" => Some(self.search_match_fg),
2171                _ => None,
2172            },
2173            _ => None,
2174        }
2175    }
2176
2177    /// Mutable companion to [`resolve_theme_key`]. Keep the two matches in
2178    /// lock-step: any key readable by `resolve_theme_key` should also be
2179    /// writable here, and vice versa.
2180    pub fn resolve_theme_key_mut(&mut self, key: &str) -> Option<&mut Color> {
2181        let parts: Vec<&str> = key.split('.').collect();
2182        if parts.len() != 2 {
2183            return None;
2184        }
2185        let (section, field) = (parts[0], parts[1]);
2186        match section {
2187            "editor" => match field {
2188                "bg" => Some(&mut self.editor_bg),
2189                "fg" => Some(&mut self.editor_fg),
2190                "cursor" => Some(&mut self.cursor),
2191                "inactive_cursor" => Some(&mut self.inactive_cursor),
2192                "selection_bg" => Some(&mut self.selection_bg),
2193                "current_line_bg" => Some(&mut self.current_line_bg),
2194                "line_number_fg" => Some(&mut self.line_number_fg),
2195                "line_number_bg" => Some(&mut self.line_number_bg),
2196                "diff_add_bg" => Some(&mut self.diff_add_bg),
2197                "diff_remove_bg" => Some(&mut self.diff_remove_bg),
2198                "diff_modify_bg" => Some(&mut self.diff_modify_bg),
2199                // `Option<Color>` — only addressable for mutation
2200                // when already set in the theme JSON (lock-step with
2201                // `resolve_theme_key`).
2202                "diff_add_collision_fg" => self.diff_add_collision_fg.as_mut(),
2203                "diff_remove_collision_fg" => self.diff_remove_collision_fg.as_mut(),
2204                "diff_modify_collision_fg" => self.diff_modify_collision_fg.as_mut(),
2205                "ruler_bg" => Some(&mut self.ruler_bg),
2206                "whitespace_indicator_fg" => Some(&mut self.whitespace_indicator_fg),
2207                "bracket_match_fg" => Some(&mut self.bracket_match_fg),
2208                "bracket_rainbow_1" => Some(&mut self.bracket_rainbow_1),
2209                "bracket_rainbow_2" => Some(&mut self.bracket_rainbow_2),
2210                "bracket_rainbow_3" => Some(&mut self.bracket_rainbow_3),
2211                "bracket_rainbow_4" => Some(&mut self.bracket_rainbow_4),
2212                "bracket_rainbow_5" => Some(&mut self.bracket_rainbow_5),
2213                "bracket_rainbow_6" => Some(&mut self.bracket_rainbow_6),
2214                "diff_add_highlight_bg" => Some(&mut self.diff_add_highlight_bg),
2215                "diff_remove_highlight_bg" => Some(&mut self.diff_remove_highlight_bg),
2216                "after_eof_bg" => Some(&mut self.after_eof_bg),
2217                _ => None,
2218            },
2219            "ui" => match field {
2220                "tab_active_fg" => Some(&mut self.tab_active_fg),
2221                "tab_active_bg" => Some(&mut self.tab_active_bg),
2222                "tab_inactive_fg" => Some(&mut self.tab_inactive_fg),
2223                "tab_inactive_bg" => Some(&mut self.tab_inactive_bg),
2224                "status_bar_fg" => Some(&mut self.status_bar_fg),
2225                "status_bar_bg" => Some(&mut self.status_bar_bg),
2226                "status_palette_fg" => Some(&mut self.status_palette_fg),
2227                "status_palette_bg" => Some(&mut self.status_palette_bg),
2228                "status_lsp_on_fg" => Some(&mut self.status_lsp_on_fg),
2229                "status_lsp_on_bg" => Some(&mut self.status_lsp_on_bg),
2230                "status_lsp_actionable_fg" => Some(&mut self.status_lsp_actionable_fg),
2231                "status_lsp_actionable_bg" => Some(&mut self.status_lsp_actionable_bg),
2232                "prompt_fg" => Some(&mut self.prompt_fg),
2233                "prompt_bg" => Some(&mut self.prompt_bg),
2234                "prompt_selection_fg" => Some(&mut self.prompt_selection_fg),
2235                "prompt_selection_bg" => Some(&mut self.prompt_selection_bg),
2236                "popup_bg" => Some(&mut self.popup_bg),
2237                "popup_border_fg" => Some(&mut self.popup_border_fg),
2238                "popup_selection_bg" => Some(&mut self.popup_selection_bg),
2239                "popup_selection_fg" => Some(&mut self.popup_selection_fg),
2240                "popup_text_fg" => Some(&mut self.popup_text_fg),
2241                "text_input_selection_bg" => Some(&mut self.text_input_selection_bg),
2242                "menu_bg" => Some(&mut self.menu_bg),
2243                "menu_fg" => Some(&mut self.menu_fg),
2244                "menu_active_bg" => Some(&mut self.menu_active_bg),
2245                "menu_active_fg" => Some(&mut self.menu_active_fg),
2246                "menu_disabled_fg" => Some(&mut self.menu_disabled_fg),
2247                "menu_disabled_bg" => Some(&mut self.menu_disabled_bg),
2248                "help_bg" => Some(&mut self.help_bg),
2249                "help_fg" => Some(&mut self.help_fg),
2250                "help_key_fg" => Some(&mut self.help_key_fg),
2251                "split_separator_fg" => Some(&mut self.split_separator_fg),
2252                "scrollbar_track_fg" => Some(&mut self.scrollbar_track_fg),
2253                "scrollbar_thumb_fg" => Some(&mut self.scrollbar_thumb_fg),
2254                "scrollbar_track_hover_fg" => Some(&mut self.scrollbar_track_hover_fg),
2255                "scrollbar_thumb_hover_fg" => Some(&mut self.scrollbar_thumb_hover_fg),
2256                "semantic_highlight_bg" => Some(&mut self.semantic_highlight_bg),
2257                "file_status_added_fg" => Some(&mut self.file_status_added_fg),
2258                "file_status_modified_fg" => Some(&mut self.file_status_modified_fg),
2259                "file_status_deleted_fg" => Some(&mut self.file_status_deleted_fg),
2260                "file_status_renamed_fg" => Some(&mut self.file_status_renamed_fg),
2261                "file_status_untracked_fg" => Some(&mut self.file_status_untracked_fg),
2262                "file_status_conflicted_fg" => Some(&mut self.file_status_conflicted_fg),
2263                "menu_dropdown_bg" => Some(&mut self.menu_dropdown_bg),
2264                "menu_dropdown_fg" => Some(&mut self.menu_dropdown_fg),
2265                "menu_highlight_bg" => Some(&mut self.menu_highlight_bg),
2266                "menu_highlight_fg" => Some(&mut self.menu_highlight_fg),
2267                "menu_border_fg" => Some(&mut self.menu_border_fg),
2268                "menu_separator_fg" => Some(&mut self.menu_separator_fg),
2269                "menu_hover_bg" => Some(&mut self.menu_hover_bg),
2270                "menu_hover_fg" => Some(&mut self.menu_hover_fg),
2271                "tab_separator_bg" => Some(&mut self.tab_separator_bg),
2272                "tab_close_hover_fg" => Some(&mut self.tab_close_hover_fg),
2273                "tab_hover_bg" => Some(&mut self.tab_hover_bg),
2274                "inline_code_bg" => Some(&mut self.inline_code_bg),
2275                "split_separator_hover_fg" => Some(&mut self.split_separator_hover_fg),
2276                "compose_margin_bg" => Some(&mut self.compose_margin_bg),
2277                "terminal_bg" => Some(&mut self.terminal_bg),
2278                "terminal_fg" => Some(&mut self.terminal_fg),
2279                "status_warning_indicator_bg" => Some(&mut self.status_warning_indicator_bg),
2280                "status_warning_indicator_fg" => Some(&mut self.status_warning_indicator_fg),
2281                "status_error_indicator_bg" => Some(&mut self.status_error_indicator_bg),
2282                "status_error_indicator_fg" => Some(&mut self.status_error_indicator_fg),
2283                "status_warning_indicator_hover_bg" => {
2284                    Some(&mut self.status_warning_indicator_hover_bg)
2285                }
2286                "status_warning_indicator_hover_fg" => {
2287                    Some(&mut self.status_warning_indicator_hover_fg)
2288                }
2289                "status_error_indicator_hover_bg" => {
2290                    Some(&mut self.status_error_indicator_hover_bg)
2291                }
2292                "status_error_indicator_hover_fg" => {
2293                    Some(&mut self.status_error_indicator_hover_fg)
2294                }
2295                "tab_drop_zone_bg" => Some(&mut self.tab_drop_zone_bg),
2296                "tab_drop_zone_border" => Some(&mut self.tab_drop_zone_border),
2297                "settings_selected_bg" => Some(&mut self.settings_selected_bg),
2298                "settings_selected_fg" => Some(&mut self.settings_selected_fg),
2299                "suggestion_bg" => Some(&mut self.suggestion_bg),
2300                "suggestion_fg" => Some(&mut self.suggestion_fg),
2301                "suggestion_selected_bg" => Some(&mut self.suggestion_selected_bg),
2302                "help_separator_fg" => Some(&mut self.help_separator_fg),
2303                "help_indicator_fg" => Some(&mut self.help_indicator_fg),
2304                "help_indicator_bg" => Some(&mut self.help_indicator_bg),
2305                _ => None,
2306            },
2307            "syntax" => match field {
2308                "keyword" => Some(&mut self.syntax_keyword),
2309                "string" => Some(&mut self.syntax_string),
2310                "comment" => Some(&mut self.syntax_comment),
2311                "function" => Some(&mut self.syntax_function),
2312                "type" => Some(&mut self.syntax_type),
2313                "variable" => Some(&mut self.syntax_variable),
2314                "variable_builtin" => Some(&mut self.syntax_variable_builtin),
2315                "constant" => Some(&mut self.syntax_constant),
2316                "operator" => Some(&mut self.syntax_operator),
2317                "punctuation_bracket" => Some(&mut self.syntax_punctuation_bracket),
2318                "punctuation_delimiter" => Some(&mut self.syntax_punctuation_delimiter),
2319                _ => None,
2320            },
2321            "diagnostic" => match field {
2322                "error_fg" => Some(&mut self.diagnostic_error_fg),
2323                "error_bg" => Some(&mut self.diagnostic_error_bg),
2324                "warning_fg" => Some(&mut self.diagnostic_warning_fg),
2325                "warning_bg" => Some(&mut self.diagnostic_warning_bg),
2326                "info_fg" => Some(&mut self.diagnostic_info_fg),
2327                "info_bg" => Some(&mut self.diagnostic_info_bg),
2328                "hint_fg" => Some(&mut self.diagnostic_hint_fg),
2329                "hint_bg" => Some(&mut self.diagnostic_hint_bg),
2330                _ => None,
2331            },
2332            "search" => match field {
2333                "match_bg" => Some(&mut self.search_match_bg),
2334                "match_fg" => Some(&mut self.search_match_fg),
2335                "label_bg" => Some(&mut self.search_label_bg),
2336                "label_fg" => Some(&mut self.search_label_fg),
2337                _ => None,
2338            },
2339            _ => None,
2340        }
2341    }
2342
2343    /// Apply a map of `"section.field" -> Color` overrides to the running
2344    /// theme in-place. Returns the number of keys that matched a known
2345    /// theme field. Unknown keys are silently dropped so a typo in a fast
2346    /// animation loop doesn't crash the caller.
2347    pub fn override_colors<I, K>(&mut self, overrides: I) -> usize
2348    where
2349        I: IntoIterator<Item = (K, Color)>,
2350        K: AsRef<str>,
2351    {
2352        let mut applied = 0;
2353        for (key, color) in overrides {
2354            if let Some(slot) = self.resolve_theme_key_mut(key.as_ref()) {
2355                *slot = color;
2356                applied += 1;
2357            }
2358        }
2359        applied
2360    }
2361}
2362
2363// =============================================================================
2364// Theme Schema Generation for Plugin API
2365// =============================================================================
2366
2367/// Returns the raw JSON Schema for ThemeFile, generated by schemars.
2368/// The schema uses standard JSON Schema format with $ref for type references.
2369/// Plugins are responsible for parsing and resolving $ref references.
2370pub fn get_theme_schema() -> serde_json::Value {
2371    use schemars::schema_for;
2372    let schema = schema_for!(ThemeFile);
2373    serde_json::to_value(&schema).unwrap_or_default()
2374}
2375
2376/// Returns a map of built-in theme names to their JSON content.
2377pub fn get_builtin_themes() -> serde_json::Value {
2378    let mut map = serde_json::Map::new();
2379    for theme in BUILTIN_THEMES {
2380        map.insert(
2381            theme.name.to_string(),
2382            serde_json::Value::String(theme.json.to_string()),
2383        );
2384    }
2385    serde_json::Value::Object(map)
2386}
2387
2388#[cfg(test)]
2389mod tests {
2390    use super::*;
2391
2392    #[test]
2393    fn test_load_builtin_theme() {
2394        let dark = Theme::load_builtin(THEME_DARK).expect("Dark theme must exist");
2395        assert_eq!(dark.name, THEME_DARK);
2396
2397        let light = Theme::load_builtin(THEME_LIGHT).expect("Light theme must exist");
2398        assert_eq!(light.name, THEME_LIGHT);
2399
2400        let high_contrast =
2401            Theme::load_builtin(THEME_HIGH_CONTRAST).expect("High contrast theme must exist");
2402        assert_eq!(high_contrast.name, THEME_HIGH_CONTRAST);
2403
2404        let terminal = Theme::load_builtin(THEME_TERMINAL).expect("Terminal theme must exist");
2405        assert_eq!(terminal.name, THEME_TERMINAL);
2406        // The terminal theme defers to the host palette: backgrounds and
2407        // primary text use Color::Reset so the terminal's own colors
2408        // (including transparency) show through.
2409        assert_eq!(terminal.editor_bg, Color::Reset);
2410        assert_eq!(terminal.editor_fg, Color::Reset);
2411        assert_eq!(terminal.terminal_bg, Color::Reset);
2412        // Adaptive accents use SGR text attributes so they invert/emphasise
2413        // against whatever fg/bg the terminal already has.
2414        assert!(terminal.selection_modifier.contains(Modifier::REVERSED));
2415        assert!(terminal
2416            .semantic_highlight_modifier
2417            .contains(Modifier::BOLD));
2418    }
2419
2420    #[test]
2421    fn test_suggestion_fg_falls_back_and_contrasts() {
2422        // Regression: the overlay prompt (Live Grep) drew its title/input
2423        // on `suggestion_bg`/`editor_bg` but borrowed `prompt_fg` for the
2424        // text. Dracula's `prompt_fg` equals its editor background, so the
2425        // text was invisible. `suggestion_fg` is the dedicated foreground
2426        // for that surface; when a theme omits it, it falls back to
2427        // `popup_text_fg` (never `prompt_fg`).
2428        let dracula = Theme::load_builtin(THEME_DRACULA).expect("Dracula theme must exist");
2429        assert_eq!(
2430            dracula.suggestion_fg, dracula.popup_text_fg,
2431            "suggestion_fg should fall back to popup_text_fg when unset"
2432        );
2433        assert_ne!(
2434            dracula.suggestion_fg, dracula.suggestion_bg,
2435            "suggestion_fg must contrast with suggestion_bg, not vanish into it"
2436        );
2437    }
2438
2439    #[test]
2440    fn test_modifier_def_round_trip() {
2441        let cases = [
2442            (vec!["reversed"], Modifier::REVERSED),
2443            (
2444                vec!["bold", "underlined"],
2445                Modifier::BOLD | Modifier::UNDERLINED,
2446            ),
2447            (vec!["italic", "dim"], Modifier::ITALIC | Modifier::DIM),
2448            (vec!["reverse"], Modifier::REVERSED),     // alias
2449            (vec!["underline"], Modifier::UNDERLINED), // alias
2450        ];
2451        for (strs, expected) in cases {
2452            let def = ModifierDef(strs.iter().map(|s| s.to_string()).collect());
2453            let m: Modifier = (&def).into();
2454            assert_eq!(m, expected, "ModifierDef({:?}) -> Modifier", strs);
2455        }
2456    }
2457
2458    #[test]
2459    fn test_modifier_def_unknown_strings_are_dropped() {
2460        // A typo in a theme JSON shouldn't crash a render — unknown
2461        // modifier names are silently dropped.
2462        let def = ModifierDef(vec!["reversed".into(), "wibble".into(), "bold".into()]);
2463        let m: Modifier = (&def).into();
2464        assert_eq!(m, Modifier::REVERSED | Modifier::BOLD);
2465    }
2466
2467    #[test]
2468    fn test_themes_without_modifier_default_to_empty() {
2469        // Existing themes (no `*_modifier` keys in their JSON) must
2470        // resolve to Modifier::empty() — i.e. the new fields are
2471        // backward compatible and don't change rendering for old
2472        // themes.
2473        let dark = Theme::load_builtin(THEME_DARK).expect("Dark theme must exist");
2474        assert!(dark.selection_modifier.is_empty());
2475        assert!(dark.semantic_highlight_modifier.is_empty());
2476    }
2477
2478    #[test]
2479    fn test_modifier_for_bg_key_lookup() {
2480        let terminal = Theme::load_builtin(THEME_TERMINAL).expect("Terminal theme must exist");
2481        // Overlay-driven highlights pick up the same modifier the
2482        // direct-paint path uses, keyed by bg theme key.
2483        assert!(terminal
2484            .modifier_for_bg_key("editor.selection_bg")
2485            .contains(Modifier::REVERSED));
2486        assert!(terminal
2487            .modifier_for_bg_key("ui.semantic_highlight_bg")
2488            .contains(Modifier::BOLD));
2489        // Unknown / unmapped keys yield empty so we don't accidentally
2490        // tint other UI regions.
2491        assert!(terminal
2492            .modifier_for_bg_key("ui.popup_selection_bg")
2493            .is_empty());
2494        assert!(terminal.modifier_for_bg_key("nonsense").is_empty());
2495    }
2496
2497    #[test]
2498    fn test_modifier_round_trip_via_theme_file() {
2499        // Theme -> ThemeFile -> Theme preserves modifiers.
2500        let original = Theme::load_builtin(THEME_TERMINAL).expect("Terminal theme must exist");
2501        let file: ThemeFile = original.clone().into();
2502        let json = serde_json::to_string(&file).expect("serialize");
2503        let parsed: ThemeFile = serde_json::from_str(&json).expect("parse");
2504        let round_tripped: Theme = parsed.into();
2505        assert_eq!(
2506            round_tripped.selection_modifier,
2507            original.selection_modifier
2508        );
2509        assert_eq!(
2510            round_tripped.semantic_highlight_modifier,
2511            original.semantic_highlight_modifier
2512        );
2513    }
2514
2515    #[test]
2516    fn test_builtin_themes_match_schema() {
2517        for theme in BUILTIN_THEMES {
2518            let _: ThemeFile = serde_json::from_str(theme.json)
2519                .unwrap_or_else(|_| panic!("Theme '{}' does not match schema", theme.name));
2520        }
2521    }
2522
2523    #[test]
2524    fn test_from_json() {
2525        let json = r#"{"name":"test","editor":{},"ui":{},"search":{},"diagnostic":{},"syntax":{}}"#;
2526        let theme = Theme::from_json(json).expect("Should parse minimal theme");
2527        assert_eq!(theme.name, "test");
2528    }
2529
2530    /// Regression test for #1281: a user theme that follows the minimal example
2531    /// in `docs/features/themes.md` (only `name`, `editor`, `syntax` — no `ui`,
2532    /// `search`, or `diagnostic` sections) must load successfully. Before the
2533    /// fix, `serde_json::from_str::<ThemeFile>` errored with `missing field
2534    /// `ui``, the loader silently dropped the theme, and the user saw
2535    /// "Failed to load theme" in the status bar.
2536    ///
2537    /// Beyond loading, this also pins the auto-inheritance behavior: with a
2538    /// cream `editor.bg`, the unspecified UI/diagnostic colors must come from
2539    /// `builtin://light` (so the theme reads coherently end-to-end), not from
2540    /// the dark-flavored hardcoded fallbacks.
2541    #[test]
2542    fn test_minimal_user_theme_from_issue_1281_loads() {
2543        // Verbatim from https://github.com/sinelaw/fresh/issues/1281
2544        let json = r#"{
2545  "name": "gruvbox-light-orange",
2546  "editor": {
2547    "bg": [251, 241, 199],
2548    "fg": [60, 56, 54],
2549    "cursor": [254, 128, 25],
2550    "selection_bg": [213, 196, 161]
2551  },
2552  "syntax": {
2553    "keyword": [175, 58, 3],
2554    "string": [152, 151, 26],
2555    "comment": [146, 131, 116]
2556  }
2557}"#;
2558        let theme = Theme::from_json(json)
2559            .expect("Theme from issue #1281 should parse without `ui`/`search`/`diagnostic`");
2560        assert_eq!(theme.name, "gruvbox-light-orange");
2561
2562        // Explicit fields land where expected.
2563        assert_eq!(theme.editor_bg, Color::Rgb(251, 241, 199));
2564        assert_eq!(theme.editor_fg, Color::Rgb(60, 56, 54));
2565        assert_eq!(theme.cursor, Color::Rgb(254, 128, 25));
2566        assert_eq!(theme.selection_bg, Color::Rgb(213, 196, 161));
2567        assert_eq!(theme.syntax_keyword, Color::Rgb(175, 58, 3));
2568        assert_eq!(theme.syntax_string, Color::Rgb(152, 151, 26));
2569        assert_eq!(theme.syntax_comment, Color::Rgb(146, 131, 116));
2570
2571        // Auto-inheritance: cream bg → `builtin://light` is the base. The
2572        // unspecified UI/diagnostic colors should match the light builtin's
2573        // values — not the dark-flavored hardcoded fallbacks.
2574        let light = Theme::load_builtin(THEME_LIGHT).expect("light builtin");
2575        assert_eq!(
2576            theme.status_bar_fg, light.status_bar_fg,
2577            "ui.status_bar_fg should inherit from builtin://light when bg is bright"
2578        );
2579        assert_eq!(
2580            theme.diagnostic_error_fg, light.diagnostic_error_fg,
2581            "diagnostic.error_fg should inherit from builtin://light when bg is bright"
2582        );
2583        assert_eq!(
2584            theme.menu_bg, light.menu_bg,
2585            "ui.menu_bg should inherit from builtin://light when bg is bright"
2586        );
2587    }
2588
2589    /// A user theme with an explicit `extends` must inherit from that base —
2590    /// even when auto-inference would have picked something different.
2591    #[test]
2592    fn test_extends_explicit_builtin_wins_over_auto_infer() {
2593        // `editor.bg` is dark (would auto-infer `dark`), but `extends` asks
2594        // for `light`. The explicit choice must win.
2595        let json = r#"{
2596            "name": "explicit-light",
2597            "extends": "builtin://light",
2598            "editor": { "bg": [0, 0, 0] }
2599        }"#;
2600        let theme = Theme::from_json(json).expect("extends should resolve");
2601        let light = Theme::load_builtin(THEME_LIGHT).expect("light builtin");
2602
2603        // Override applied.
2604        assert_eq!(theme.editor_bg, Color::Rgb(0, 0, 0));
2605        // Unspecified fields come from the explicit base, not from auto-infer.
2606        assert_eq!(theme.menu_bg, light.menu_bg);
2607        assert_eq!(theme.tab_active_bg, light.tab_active_bg);
2608        assert_eq!(theme.diagnostic_warning_fg, light.diagnostic_warning_fg);
2609    }
2610
2611    /// Bare-name `extends` (e.g. `"dark"`) is the legacy form accepted by the
2612    /// rest of the registry (`ThemeRegistry::resolve_key`), so we accept it
2613    /// here too — being strict about a `builtin://` prefix would just be a
2614    /// papercut for users hand-writing a theme JSON.
2615    #[test]
2616    fn test_extends_bare_builtin_name_works() {
2617        let json = r#"{ "name": "x", "extends": "high-contrast" }"#;
2618        let theme = Theme::from_json(json).expect("bare-name extends should resolve");
2619        let hc = Theme::load_builtin("high-contrast").expect("hc builtin");
2620        assert_eq!(theme.menu_bg, hc.menu_bg);
2621    }
2622
2623    /// An unknown `extends` target must produce a clear error that names what
2624    /// went wrong and lists the valid alternatives — anything less leaves the
2625    /// user staring at the same opaque "Failed to load theme" message that
2626    /// motivated #1281 in the first place.
2627    #[test]
2628    fn test_extends_unknown_builtin_errors_with_helpful_message() {
2629        let json = r#"{ "name": "x", "extends": "builtin://no-such-theme" }"#;
2630        let err = Theme::from_json(json).expect_err("unknown extends must error");
2631        assert!(
2632            err.contains("no-such-theme"),
2633            "error should quote the bad value, got: {}",
2634            err
2635        );
2636        assert!(
2637            err.contains("dark") && err.contains("light"),
2638            "error should list available builtins, got: {}",
2639            err
2640        );
2641    }
2642
2643    /// Auto-inference picks `dark` for a clearly-dark `editor.bg`. Mirrors
2644    /// the light path tested in the #1281 regression so both branches stay
2645    /// honest.
2646    #[test]
2647    fn test_auto_infer_dark_base_from_dark_bg() {
2648        let json = r#"{ "name": "x", "editor": { "bg": [20, 20, 30] } }"#;
2649        let theme = Theme::from_json(json).expect("should parse");
2650        let dark = Theme::load_builtin(THEME_DARK).expect("dark builtin");
2651        assert_eq!(theme.menu_bg, dark.menu_bg);
2652        assert_eq!(theme.diagnostic_error_fg, dark.diagnostic_error_fg);
2653    }
2654
2655    /// With neither `extends` nor an explicit `editor.bg`, there's nothing to
2656    /// infer from — the theme should still load and use the per-field
2657    /// hardcoded defaults rather than failing or picking an arbitrary builtin.
2658    #[test]
2659    fn test_no_inheritance_signal_uses_hardcoded_defaults() {
2660        let json = r#"{ "name": "x" }"#;
2661        let theme = Theme::from_json(json).expect("should parse");
2662        // The hardcoded `default_editor_bg` is `Rgb(30, 30, 30)`. Pin that so
2663        // a future change to the default prompts a deliberate test update.
2664        assert_eq!(theme.editor_bg, Color::Rgb(30, 30, 30));
2665    }
2666
2667    /// `name` remains the only truly required top-level field. A theme JSON
2668    /// missing `name` should still be rejected with a clear error so users
2669    /// don't end up with an unidentifiable theme in the registry.
2670    #[test]
2671    fn test_theme_without_name_still_errors() {
2672        let json = r#"{ "editor": {} }"#;
2673        let err = Theme::from_json(json).expect_err("missing `name` must be an error");
2674        assert!(
2675            err.contains("name"),
2676            "error should mention the missing `name` field, got: {}",
2677            err
2678        );
2679    }
2680
2681    /// Overriding a single nested field on top of an explicit `extends` must
2682    /// only touch that field — every sibling stays at the base's value. This
2683    /// is the surgical-tweak workflow ("I love `dark` but want a different
2684    /// cursor color"), and the override walk must not bleed into other fields.
2685    #[test]
2686    fn test_extends_overrides_compose_field_by_field() {
2687        let json = r#"{
2688            "name": "dark-with-pink-cursor",
2689            "extends": "builtin://dark",
2690            "editor": { "cursor": [255, 105, 180] }
2691        }"#;
2692        let theme = Theme::from_json(json).expect("should parse");
2693        let dark = Theme::load_builtin(THEME_DARK).expect("dark builtin");
2694
2695        // Cursor was overridden.
2696        assert_eq!(theme.cursor, Color::Rgb(255, 105, 180));
2697        // Every other editor field comes from the base verbatim.
2698        assert_eq!(theme.editor_bg, dark.editor_bg);
2699        assert_eq!(theme.editor_fg, dark.editor_fg);
2700        assert_eq!(theme.selection_bg, dark.selection_bg);
2701        // And so do the other sections.
2702        assert_eq!(theme.menu_bg, dark.menu_bg);
2703        assert_eq!(theme.syntax_keyword, dark.syntax_keyword);
2704    }
2705
2706    #[test]
2707    fn test_default_reset_color() {
2708        // Test that "Default" maps to Color::Reset
2709        let color: Color = ColorDef::Named("Default".to_string()).into();
2710        assert_eq!(color, Color::Reset);
2711
2712        // Test that "Reset" also maps to Color::Reset
2713        let color: Color = ColorDef::Named("Reset".to_string()).into();
2714        assert_eq!(color, Color::Reset);
2715    }
2716
2717    #[test]
2718    fn test_file_status_colors_fall_back_to_diagnostic_colors() {
2719        // A theme with NO file_status_* keys should inherit from diagnostic colors
2720        let json = r#"{
2721            "name": "test-fallback",
2722            "editor": {},
2723            "ui": {},
2724            "search": {},
2725            "diagnostic": {
2726                "error_fg": [220, 50, 47],
2727                "warning_fg": [181, 137, 0],
2728                "info_fg": [38, 139, 210],
2729                "hint_fg": [101, 123, 131]
2730            },
2731            "syntax": {}
2732        }"#;
2733        let theme = Theme::from_json(json).expect("Should parse theme without file_status keys");
2734
2735        // Verify fallback: added/renamed -> info_fg
2736        assert_eq!(theme.file_status_added_fg, Color::Rgb(38, 139, 210));
2737        assert_eq!(theme.file_status_renamed_fg, Color::Rgb(38, 139, 210));
2738        // modified -> warning_fg
2739        assert_eq!(theme.file_status_modified_fg, Color::Rgb(181, 137, 0));
2740        // deleted/conflicted -> error_fg
2741        assert_eq!(theme.file_status_deleted_fg, Color::Rgb(220, 50, 47));
2742        assert_eq!(theme.file_status_conflicted_fg, Color::Rgb(220, 50, 47));
2743        // untracked -> hint_fg
2744        assert_eq!(theme.file_status_untracked_fg, Color::Rgb(101, 123, 131));
2745    }
2746
2747    #[test]
2748    fn test_file_status_colors_explicit_override() {
2749        // A theme WITH explicit file_status keys should use those, not the fallback
2750        let json = r#"{
2751            "name": "test-override",
2752            "editor": {},
2753            "ui": {
2754                "file_status_added_fg": [80, 250, 123],
2755                "file_status_modified_fg": [255, 184, 108]
2756            },
2757            "search": {},
2758            "diagnostic": {
2759                "info_fg": [38, 139, 210],
2760                "warning_fg": [181, 137, 0]
2761            },
2762            "syntax": {}
2763        }"#;
2764        let theme = Theme::from_json(json).expect("Should parse theme with file_status overrides");
2765
2766        // Explicit overrides should win
2767        assert_eq!(theme.file_status_added_fg, Color::Rgb(80, 250, 123));
2768        assert_eq!(theme.file_status_modified_fg, Color::Rgb(255, 184, 108));
2769        // Non-overridden should still fall back
2770        assert_eq!(theme.file_status_renamed_fg, Color::Rgb(38, 139, 210));
2771    }
2772
2773    #[test]
2774    fn test_file_status_colors_resolve_via_theme_key() {
2775        let json = r#"{
2776            "name": "test-resolve",
2777            "editor": {},
2778            "ui": {
2779                "file_status_added_fg": [80, 250, 123]
2780            },
2781            "search": {},
2782            "diagnostic": {
2783                "warning_fg": [181, 137, 0]
2784            },
2785            "syntax": {}
2786        }"#;
2787        let theme = Theme::from_json(json).expect("Should parse theme");
2788
2789        // Theme key resolution should work for file_status keys
2790        assert_eq!(
2791            theme.resolve_theme_key("ui.file_status_added_fg"),
2792            Some(Color::Rgb(80, 250, 123))
2793        );
2794        assert_eq!(
2795            theme.resolve_theme_key("ui.file_status_modified_fg"),
2796            Some(Color::Rgb(181, 137, 0))
2797        );
2798    }
2799
2800    #[test]
2801    fn override_colors_writes_known_keys_and_drops_unknowns() {
2802        let mut theme = Theme::load_builtin(THEME_DARK).expect("dark builtin");
2803        let applied = theme.override_colors([
2804            ("editor.bg".to_string(), Color::Rgb(10, 20, 30)),
2805            ("ui.status_bar_fg".to_string(), Color::Rgb(1, 2, 3)),
2806            ("does.not_exist".to_string(), Color::Rgb(9, 9, 9)),
2807            ("garbage_no_dot".to_string(), Color::Rgb(9, 9, 9)),
2808        ]);
2809        assert_eq!(applied, 2, "only the two valid keys should be applied");
2810        assert_eq!(
2811            theme.resolve_theme_key("editor.bg"),
2812            Some(Color::Rgb(10, 20, 30))
2813        );
2814        assert_eq!(
2815            theme.resolve_theme_key("ui.status_bar_fg"),
2816            Some(Color::Rgb(1, 2, 3))
2817        );
2818    }
2819
2820    #[test]
2821    fn resolve_theme_key_mut_matches_resolve_theme_key_domain() {
2822        // If a key resolves readably, it must also resolve as a mutable
2823        // slot — the two matches must stay in lock-step.
2824        let mut theme = Theme::load_builtin(THEME_DARK).expect("dark builtin");
2825        let probe = [
2826            "editor.bg",
2827            "editor.fg",
2828            "ui.status_bar_fg",
2829            "ui.tab_active_bg",
2830            "syntax.keyword",
2831            "diagnostic.error_fg",
2832            "search.match_bg",
2833        ];
2834        for key in probe {
2835            assert!(
2836                theme.resolve_theme_key(key).is_some(),
2837                "reader lost key {key}"
2838            );
2839            assert!(
2840                theme.resolve_theme_key_mut(key).is_some(),
2841                "mutator missing key {key}"
2842            );
2843        }
2844    }
2845
2846    /// The set of `(section, field)` color keys that the theme's JSON
2847    /// surface — and therefore the plugin schema — exposes. Derived by
2848    /// taking a fully resolved builtin back to a `ThemeFile`, so every
2849    /// optional color slot is materialized as `Some`. Non-color leaves
2850    /// (text-attribute modifiers, `name`/`extends`) are filtered by shape.
2851    ///
2852    /// This is the single authority the resolvers/conversions are checked
2853    /// against: there is no hand-maintained key list to drift.
2854    fn schema_color_keys() -> Vec<(String, String)> {
2855        let theme = Theme::load_builtin(THEME_DARK).expect("dark builtin");
2856        let file: ThemeFile = theme.into();
2857        let value = serde_json::to_value(&file).expect("ThemeFile serializes");
2858        let obj = value.as_object().expect("ThemeFile is a JSON object");
2859
2860        let mut keys = Vec::new();
2861        for section in ["editor", "ui", "search", "diagnostic", "syntax"] {
2862            let fields = obj
2863                .get(section)
2864                .and_then(|v| v.as_object())
2865                .unwrap_or_else(|| panic!("section `{section}` missing from serialized ThemeFile"));
2866            for (field, val) in fields {
2867                if is_color_leaf(val) {
2868                    keys.push((section.to_string(), field.clone()));
2869                }
2870            }
2871        }
2872        assert!(
2873            keys.len() >= 100,
2874            "expected the theme to expose at least ~100 color keys, found {} — \
2875             has the serialization shape changed?",
2876            keys.len()
2877        );
2878        keys
2879    }
2880
2881    /// A `ColorDef` JSON leaf is either a named-color string or an
2882    /// `[r, g, b]` array of three numbers. Text-attribute modifiers
2883    /// serialize as arrays of *strings*, so this excludes them.
2884    fn is_color_leaf(v: &serde_json::Value) -> bool {
2885        v.is_string()
2886            || v.as_array()
2887                .is_some_and(|a| a.len() == 3 && a.iter().all(serde_json::Value::is_number))
2888    }
2889
2890    /// Distinct, round-trip-stable sentinel color for index `i`. Always an
2891    /// RGB triple, which `ColorDef` passes through unchanged (only the named
2892    /// `Color` variants get folded into `ColorDef::Named`).
2893    fn sentinel(i: usize) -> Color {
2894        Color::Rgb((i >> 8) as u8, (i & 0xff) as u8, 0x5a)
2895    }
2896
2897    #[test]
2898    fn every_exposed_color_key_resolves_in_both_directions() {
2899        // Every color the JSON/schema surface exposes must be addressable by
2900        // BOTH resolvers, under the SAME section it appears in. A key the
2901        // schema advertises but a resolver drops is silently un-overridable
2902        // (the drift bug behind #2079): plugin overrides and theme-JSON loads
2903        // both go through `resolve_theme_key_mut`, the inspector through
2904        // `resolve_theme_key`.
2905        let mut theme = Theme::load_builtin(THEME_DARK).expect("dark builtin");
2906        let mut missing_reader = Vec::new();
2907        let mut missing_mutator = Vec::new();
2908        for (section, field) in schema_color_keys() {
2909            let key = format!("{section}.{field}");
2910            if theme.resolve_theme_key(&key).is_none() {
2911                missing_reader.push(key.clone());
2912            }
2913            if theme.resolve_theme_key_mut(&key).is_none() {
2914                missing_mutator.push(key);
2915            }
2916        }
2917        assert!(
2918            missing_reader.is_empty() && missing_mutator.is_empty(),
2919            "theme color keys exposed by the JSON schema but dropped by a resolver:\n  \
2920             resolve_theme_key:     {missing_reader:?}\n  \
2921             resolve_theme_key_mut: {missing_mutator:?}"
2922        );
2923    }
2924
2925    #[test]
2926    fn color_keys_round_trip_through_the_same_field_and_section() {
2927        // Assign every exposed key a distinct color, then push it all the way
2928        // around the loop and back, checking the value lands in the same slot
2929        // at every hop:
2930        //   write    via resolve_theme_key_mut   (string key   -> Theme field)
2931        //   read     via resolve_theme_key        (Theme field  -> string key)
2932        //   serialize via From<Theme> for ThemeFile (Theme field -> section.field)
2933        //   reload   via from_json                 (section.field -> Theme field)
2934        // If field name OR section disagree between any of these four paths, a
2935        // sentinel lands in the wrong field and an assert fires — this is what
2936        // pins names and categories together in all directions.
2937        let keys = schema_color_keys();
2938        let mut theme = Theme::load_builtin(THEME_DARK).expect("dark builtin");
2939
2940        let pairs: Vec<(String, Color)> = keys
2941            .iter()
2942            .enumerate()
2943            .map(|(i, (s, f))| (format!("{s}.{f}"), sentinel(i)))
2944            .collect();
2945        let applied = theme.override_colors(pairs.iter().map(|(k, c)| (k.as_str(), *c)));
2946        assert_eq!(
2947            applied,
2948            keys.len(),
2949            "override_colors should write every exposed key via resolve_theme_key_mut"
2950        );
2951
2952        // reader agrees with mutator on which field each key addresses.
2953        for (i, (s, f)) in keys.iter().enumerate() {
2954            let key = format!("{s}.{f}");
2955            assert_eq!(
2956                theme.resolve_theme_key(&key),
2957                Some(sentinel(i)),
2958                "reader and mutator disagree on the field `{key}` addresses"
2959            );
2960        }
2961
2962        // reverse conversion serializes each sentinel back under the SAME
2963        // section.field — proves field name + category wiring in From<Theme>.
2964        let file: ThemeFile = theme.into();
2965        let value = serde_json::to_value(&file).expect("ThemeFile serializes");
2966        let obj = value.as_object().expect("ThemeFile is a JSON object");
2967        for (i, (s, f)) in keys.iter().enumerate() {
2968            let leaf = obj
2969                .get(s)
2970                .and_then(|sec| sec.get(f))
2971                .unwrap_or_else(|| panic!("`{s}.{f}` vanished from serialized ThemeFile"));
2972            let color: Color = serde_json::from_value::<ColorDef>(leaf.clone())
2973                .expect("color leaf parses as ColorDef")
2974                .into();
2975            assert_eq!(
2976                color,
2977                sentinel(i),
2978                "`{s}.{f}` serialized back to the wrong field or section"
2979            );
2980        }
2981
2982        // forward conversion (from_json) routes each section.field leaf back to
2983        // the field the reader reads — proves From<ThemeFile> for Theme wiring.
2984        let reloaded = Theme::from_json(&value.to_string()).expect("from_json round-trips");
2985        for (i, (s, f)) in keys.iter().enumerate() {
2986            let key = format!("{s}.{f}");
2987            assert_eq!(
2988                reloaded.resolve_theme_key(&key),
2989                Some(sentinel(i)),
2990                "`{key}` did not survive ThemeFile -> JSON -> from_json"
2991            );
2992        }
2993    }
2994
2995    #[test]
2996    fn test_all_builtin_themes_set_prominent_palette_indicator() {
2997        // Issue #1711: the Ctrl+P palette hint should be a *prominent*
2998        // accent drawn from each theme's own palette, not the neutral
2999        // status-bar colors. The fallback to status_bar_* exists for
3000        // user themes that don't opt in, but every shipped theme must
3001        // set explicit values that differ from the bar so the hint
3002        // pops as intended.
3003        for builtin in BUILTIN_THEMES {
3004            let theme = Theme::from_json(builtin.json)
3005                .unwrap_or_else(|e| panic!("Theme '{}' failed to parse: {}", builtin.name, e));
3006            assert!(
3007                theme.status_palette_fg != theme.status_bar_fg
3008                    || theme.status_palette_bg != theme.status_bar_bg,
3009                "Theme '{}' must set status_palette_fg/bg to a prominent \
3010                 accent distinct from status_bar_fg/bg",
3011                builtin.name
3012            );
3013        }
3014    }
3015
3016    #[test]
3017    fn test_all_builtin_themes_have_file_status_colors() {
3018        // Every builtin theme must produce valid file_status colors (via fallback or explicit)
3019        for builtin in BUILTIN_THEMES {
3020            let theme = Theme::from_json(builtin.json)
3021                .unwrap_or_else(|e| panic!("Theme '{}' failed to parse: {}", builtin.name, e));
3022
3023            // All six keys must resolve to Some via resolve_theme_key
3024            for key in &[
3025                "ui.file_status_added_fg",
3026                "ui.file_status_modified_fg",
3027                "ui.file_status_deleted_fg",
3028                "ui.file_status_renamed_fg",
3029                "ui.file_status_untracked_fg",
3030                "ui.file_status_conflicted_fg",
3031            ] {
3032                assert!(
3033                    theme.resolve_theme_key(key).is_some(),
3034                    "Theme '{}' missing resolution for '{}'",
3035                    builtin.name,
3036                    key
3037                );
3038            }
3039        }
3040    }
3041}