Skip to main content

native_theme_gtk/
lib.rs

1//! Resolve the effective GTK 4 theme through GTK itself.
2//!
3//! The crate intentionally does not parse `gtk.css`. GTK themes have selectors,
4//! imports, variables, media queries, user overrides, and version-dependent
5//! lookup rules. [`probe`] asks GTK for the effective settings and computed
6//! values after those layers have been applied.
7
8use std::collections::HashSet;
9
10use gtk::gdk;
11use gtk::glib;
12use gtk::prelude::*;
13use serde::{Deserialize, Serialize};
14use thiserror::Error;
15
16/// Version of the JSON snapshot contract.
17pub const SCHEMA_VERSION: u32 = 1;
18
19/// Stable toolkit-neutral role names shared with `native-theme-qt`.
20pub const SEMANTIC_COLOR_ROLES: [&str; 18] = [
21    "window_background",
22    "window_text",
23    "surface_background",
24    "surface_text",
25    "input_background",
26    "input_text",
27    "selection_background",
28    "selection_text",
29    "accent",
30    "accent_text",
31    "border",
32    "disabled_text",
33    "tooltip_background",
34    "tooltip_text",
35    "link",
36    "error",
37    "warning",
38    "success",
39];
40
41/// An RGBA color in the sRGB color space.
42#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
43pub struct Rgba {
44    /// Red channel in the inclusive range 0..=1.
45    pub red: f32,
46    /// Green channel in the inclusive range 0..=1.
47    pub green: f32,
48    /// Blue channel in the inclusive range 0..=1.
49    pub blue: f32,
50    /// Alpha channel in the inclusive range 0..=1.
51    pub alpha: f32,
52}
53
54impl From<gdk::RGBA> for Rgba {
55    fn from(value: gdk::RGBA) -> Self {
56        Self {
57            red: value.red(),
58            green: value.green(),
59            blue: value.blue(),
60            alpha: value.alpha(),
61        }
62    }
63}
64
65/// Identity of the active GTK theme and display backend.
66#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
67pub struct ThemeIdentity {
68    /// GTK theme name selected by the desktop.
69    pub theme_name: String,
70    /// GTK runtime version used to resolve the theme.
71    pub toolkit_version: String,
72    /// GDK display backend, when it can be determined.
73    pub display_backend: Option<String>,
74}
75
76/// A dynamically discovered GTK enum preference.
77///
78/// This representation lets the crate expose preferences introduced by newer
79/// GTK runtimes while retaining its GTK 4.10 build requirement.
80#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
81pub struct EnumSetting {
82    /// Numeric GEnum value.
83    pub value: i32,
84    /// Stable GEnum constant name.
85    pub name: String,
86    /// Human-readable GEnum nickname.
87    pub nick: String,
88}
89
90/// User preferences exposed by `GtkSettings`.
91#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
92pub struct GtkSettingsSnapshot {
93    /// Default interface font description.
94    pub font_name: Option<String>,
95    /// Active icon theme name.
96    pub icon_theme_name: Option<String>,
97    /// Active cursor theme name.
98    pub cursor_theme_name: Option<String>,
99    /// Preferred cursor size in logical pixels.
100    pub cursor_theme_size: Option<i32>,
101    /// Whether GTK animations are enabled.
102    pub enable_animations: Option<bool>,
103    /// Whether overlay scrollbars are enabled.
104    pub overlay_scrolling: Option<bool>,
105    /// Whether the primary mouse button warps a slider to the click position.
106    pub primary_button_warps_slider: Option<bool>,
107    /// Double-click interval in milliseconds.
108    pub double_click_time_ms: Option<i32>,
109    /// Cursor blink interval in milliseconds.
110    pub cursor_blink_time_ms: Option<i32>,
111    /// Whether the application prefers the theme's dark variant.
112    pub prefer_dark: Option<bool>,
113    /// Desktop light/dark preference, available with GTK 4.20 and newer.
114    #[serde(default)]
115    pub interface_color_scheme: Option<EnumSetting>,
116    /// Desktop contrast preference, available with GTK 4.20 and newer.
117    #[serde(default)]
118    pub interface_contrast: Option<EnumSetting>,
119    /// Desktop reduced-motion preference, available with GTK 4.22 and newer.
120    #[serde(default)]
121    pub interface_reduced_motion: Option<EnumSetting>,
122    /// Desktop accent color, available on GTK runtimes that publish it.
123    #[serde(default)]
124    pub interface_accent_color: Option<Rgba>,
125}
126
127/// A symbolic color resolved by GTK's CSS engine.
128#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
129pub struct NamedColor {
130    /// GTK or libadwaita symbolic color name.
131    pub name: String,
132    /// Effective value after theme and user overrides.
133    pub value: Rgba,
134}
135
136/// Toolkit-neutral colors projected from GTK symbolic color roles.
137///
138/// Fields remain optional because custom themes are not required to publish
139/// every conventional GTK or libadwaita symbolic name.
140#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
141pub struct SemanticPalette {
142    /// Main application window background.
143    pub window_background: Option<Rgba>,
144    /// Text drawn directly on the window background.
145    pub window_text: Option<Rgba>,
146    /// Raised surface or card background.
147    pub surface_background: Option<Rgba>,
148    /// Text drawn on raised surfaces.
149    pub surface_text: Option<Rgba>,
150    /// Editable/view content background.
151    pub input_background: Option<Rgba>,
152    /// Editable/view content text.
153    pub input_text: Option<Rgba>,
154    /// Selected item background.
155    pub selection_background: Option<Rgba>,
156    /// Text drawn on a selected item.
157    pub selection_text: Option<Rgba>,
158    /// Primary accent background.
159    pub accent: Option<Rgba>,
160    /// Text drawn over the primary accent.
161    pub accent_text: Option<Rgba>,
162    /// General separator or frame color.
163    pub border: Option<Rgba>,
164    /// Text used by disabled controls.
165    pub disabled_text: Option<Rgba>,
166    /// Tooltip or popover background.
167    pub tooltip_background: Option<Rgba>,
168    /// Tooltip or popover text.
169    pub tooltip_text: Option<Rgba>,
170    /// Hyperlink foreground.
171    pub link: Option<Rgba>,
172    /// Destructive or error foreground.
173    pub error: Option<Rgba>,
174    /// Warning foreground.
175    pub warning: Option<Rgba>,
176    /// Success foreground.
177    pub success: Option<Rgba>,
178}
179
180/// Computed visual state for a representative GTK widget.
181#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
182pub struct WidgetState {
183    /// Portable state name such as `hovered` or `disabled`.
184    pub state: String,
185    /// Effective foreground color reported by GTK.
186    pub foreground: Rgba,
187}
188
189/// GTK's preferred dimensions for a representative widget.
190#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
191pub struct WidgetMetrics {
192    /// Minimum width in logical pixels.
193    pub minimum_width: i32,
194    /// Natural width in logical pixels.
195    pub natural_width: i32,
196    /// Minimum height in logical pixels.
197    pub minimum_height: i32,
198    /// Natural height in logical pixels.
199    pub natural_height: i32,
200}
201
202/// Effective information collected for one representative control.
203#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
204pub struct WidgetSnapshot {
205    /// Stable generic control name.
206    pub control: String,
207    /// Root GTK CSS node name.
208    pub css_name: String,
209    /// Preferred widget dimensions.
210    pub metrics: WidgetMetrics,
211    /// Foreground color across GTK interaction states.
212    pub states: Vec<WidgetState>,
213}
214
215/// A complete GTK theme probe result.
216#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
217pub struct ThemeSnapshot {
218    /// Snapshot schema version.
219    pub schema_version: u32,
220    /// Backend discriminator. Always `gtk4` for this crate.
221    pub backend: String,
222    /// Theme identity and toolkit runtime details.
223    pub identity: ThemeIdentity,
224    /// Desktop preferences exposed through GTK.
225    pub settings: GtkSettingsSnapshot,
226    /// Symbolic colors understood by the active theme.
227    pub named_colors: Vec<NamedColor>,
228    /// Toolkit-neutral projection of the symbolic colors.
229    pub semantic_palette: SemanticPalette,
230    /// Representative control metrics and state colors.
231    pub widgets: Vec<WidgetSnapshot>,
232    /// Non-fatal limitations encountered by the probe.
233    pub diagnostics: Vec<String>,
234}
235
236/// Explanation of why a theme snapshot is not safe to consume.
237#[derive(Debug, Error, PartialEq, Eq)]
238#[error("invalid GTK theme snapshot: {reason}")]
239pub struct SnapshotValidationError {
240    reason: String,
241}
242
243impl SnapshotValidationError {
244    /// Human-readable validation failure.
245    pub fn reason(&self) -> &str {
246        &self.reason
247    }
248}
249
250fn validation_error(reason: impl Into<String>) -> SnapshotValidationError {
251    SnapshotValidationError {
252        reason: reason.into(),
253    }
254}
255
256fn validate_rgba(path: &str, color: Rgba) -> Result<(), SnapshotValidationError> {
257    for (channel, value) in [
258        ("red", color.red),
259        ("green", color.green),
260        ("blue", color.blue),
261        ("alpha", color.alpha),
262    ] {
263        if !value.is_finite() || !(0.0..=1.0).contains(&value) {
264            return Err(validation_error(format!(
265                "{path}.{channel} must be finite and in 0..=1, got {value}"
266            )));
267        }
268    }
269    Ok(())
270}
271
272impl ThemeSnapshot {
273    /// Check schema, identity, dimensions, uniqueness, and every color channel.
274    pub fn validate(&self) -> Result<(), SnapshotValidationError> {
275        if self.schema_version != SCHEMA_VERSION {
276            return Err(validation_error(format!(
277                "unsupported schema version {}; expected {SCHEMA_VERSION}",
278                self.schema_version
279            )));
280        }
281        if self.backend != "gtk4" {
282            return Err(validation_error(format!(
283                "backend must be gtk4, got {:?}",
284                self.backend
285            )));
286        }
287        if self.identity.theme_name.trim().is_empty()
288            || self.identity.toolkit_version.trim().is_empty()
289        {
290            return Err(validation_error(
291                "theme name and toolkit version must not be empty",
292            ));
293        }
294
295        let mut color_names = HashSet::new();
296        for color in &self.named_colors {
297            if color.name.is_empty() || !color_names.insert(color.name.as_str()) {
298                return Err(validation_error(format!(
299                    "symbolic color name {:?} is empty or duplicated",
300                    color.name
301                )));
302            }
303            validate_rgba(&format!("named_colors.{}", color.name), color.value)?;
304        }
305
306        for (name, color) in [
307            ("window_background", self.semantic_palette.window_background),
308            ("window_text", self.semantic_palette.window_text),
309            (
310                "surface_background",
311                self.semantic_palette.surface_background,
312            ),
313            ("surface_text", self.semantic_palette.surface_text),
314            ("input_background", self.semantic_palette.input_background),
315            ("input_text", self.semantic_palette.input_text),
316            (
317                "selection_background",
318                self.semantic_palette.selection_background,
319            ),
320            ("selection_text", self.semantic_palette.selection_text),
321            ("accent", self.semantic_palette.accent),
322            ("accent_text", self.semantic_palette.accent_text),
323            ("border", self.semantic_palette.border),
324            ("disabled_text", self.semantic_palette.disabled_text),
325            (
326                "tooltip_background",
327                self.semantic_palette.tooltip_background,
328            ),
329            ("tooltip_text", self.semantic_palette.tooltip_text),
330            ("link", self.semantic_palette.link),
331            ("error", self.semantic_palette.error),
332            ("warning", self.semantic_palette.warning),
333            ("success", self.semantic_palette.success),
334        ] {
335            if let Some(color) = color {
336                validate_rgba(&format!("semantic_palette.{name}"), color)?;
337            }
338        }
339        if let Some(color) = self.settings.interface_accent_color {
340            validate_rgba("settings.interface_accent_color", color)?;
341        }
342
343        let mut controls = HashSet::new();
344        for widget in &self.widgets {
345            if widget.control.is_empty() || !controls.insert(widget.control.as_str()) {
346                return Err(validation_error(format!(
347                    "widget name {:?} is empty or duplicated",
348                    widget.control
349                )));
350            }
351            if widget.css_name.is_empty() {
352                return Err(validation_error(format!(
353                    "widget {} has an empty CSS node name",
354                    widget.control
355                )));
356            }
357            let metrics = widget.metrics;
358            if metrics.minimum_width < 0
359                || metrics.natural_width < metrics.minimum_width
360                || metrics.minimum_height < 0
361                || metrics.natural_height < metrics.minimum_height
362            {
363                return Err(validation_error(format!(
364                    "widget {} has inconsistent preferred dimensions",
365                    widget.control
366                )));
367            }
368            let mut states = HashSet::new();
369            for state in &widget.states {
370                if state.state.is_empty() || !states.insert(state.state.as_str()) {
371                    return Err(validation_error(format!(
372                        "widget {} has an empty or duplicated state {:?}",
373                        widget.control, state.state
374                    )));
375                }
376                validate_rgba(
377                    &format!("widgets.{}.{}", widget.control, state.state),
378                    state.foreground,
379                )?;
380            }
381        }
382        for required in [
383            "window",
384            "button",
385            "input",
386            "checkbox",
387            "switch",
388            "progress-bar",
389            "slider",
390        ] {
391            if !controls.contains(required) {
392                return Err(validation_error(format!(
393                    "missing representative widget {required}"
394                )));
395            }
396        }
397        Ok(())
398    }
399}
400
401/// A GTK snapshot resolved through `native-theme`, ready for framework connectors.
402#[derive(Clone, Debug)]
403pub struct NativeThemeBridge {
404    /// Display name for the detected theme.
405    pub name: String,
406    /// Light or dark mode inferred from the effective window background.
407    pub mode: native_theme::theme::ColorMode,
408    /// Fully populated theme accepted by `native_theme_gpui::to_theme`.
409    pub resolved: native_theme::theme::ResolvedTheme,
410    /// Whether transparent effects should be reduced.
411    pub reduce_transparency: bool,
412    /// Whether the user requested reduced motion.
413    pub reduce_motion: bool,
414    /// Whether the user requested increased contrast.
415    pub high_contrast: bool,
416}
417
418impl NativeThemeBridge {
419    /// Convert the resolved bridge into a `gpui-component` theme.
420    #[cfg(feature = "gpui")]
421    #[must_use = "this returns the GPUI theme; it does not install it globally"]
422    pub fn to_gpui_theme(&self) -> gpui_component::theme::Theme {
423        native_theme_gpui::to_theme(
424            &self.resolved,
425            &self.name,
426            self.mode.is_dark(),
427            self.reduce_transparency,
428        )
429    }
430}
431
432/// Failure to translate a GTK snapshot into the `native-theme` model.
433#[derive(Debug, Error)]
434pub enum NativeThemeBridgeError {
435    /// The source snapshot is malformed or incomplete.
436    #[error(transparent)]
437    InvalidSnapshot(#[from] SnapshotValidationError),
438    /// A semantic role required for a faithful base theme was unavailable.
439    #[error("GTK snapshot is missing required semantic color {0}")]
440    MissingColor(&'static str),
441    /// The `native-theme` inheritance or validation pipeline failed.
442    #[error("native-theme resolution failed: {0}")]
443    Resolution(#[from] native_theme::error::Error),
444}
445
446fn to_native_color(color: Rgba) -> native_theme::color::Rgba {
447    native_theme::color::Rgba::from_f32(color.red, color.green, color.blue, color.alpha)
448}
449
450fn native_font(name: &str, color: Rgba) -> Option<native_theme::theme::FontSpec> {
451    use gtk::glib::translate::IntoGlib;
452    use native_theme::theme::{FontSize, FontSpec, FontStyle, intern_font_family};
453
454    let description = gtk::pango::FontDescription::from_string(name);
455    let family = description.family()?;
456    let size = description.size();
457    Some(FontSpec {
458        family: Some(intern_font_family(&family)),
459        size: (size > 0).then(|| {
460            let value = size as f32 / gtk::pango::SCALE as f32;
461            if description.is_size_absolute() {
462                FontSize::Px(value)
463            } else {
464                FontSize::Pt(value)
465            }
466        }),
467        weight: u16::try_from(description.weight().into_glib()).ok(),
468        style: Some(match description.style() {
469            gtk::pango::Style::Italic => FontStyle::Italic,
470            gtk::pango::Style::Oblique => FontStyle::Oblique,
471            _ => FontStyle::Normal,
472        }),
473        color: Some(to_native_color(color)),
474    })
475}
476
477fn relative_luminance(color: Rgba) -> f32 {
478    fn linear(channel: f32) -> f32 {
479        if channel <= 0.04045 {
480            channel / 12.92
481        } else {
482            ((channel + 0.055) / 1.055).powf(2.4)
483        }
484    }
485    0.2126 * linear(color.red) + 0.7152 * linear(color.green) + 0.0722 * linear(color.blue)
486}
487
488impl ThemeSnapshot {
489    fn widget(&self, control: &str) -> Option<&WidgetSnapshot> {
490        self.widgets.iter().find(|widget| widget.control == control)
491    }
492
493    fn state_color(&self, control: &str, state: &str) -> Option<Rgba> {
494        self.widget(control)?
495            .states
496            .iter()
497            .find(|item| item.state == state)
498            .map(|item| item.foreground)
499    }
500
501    /// Translate resolved GTK values into a sparse `native-theme` mode.
502    ///
503    /// The result can be merged over any `native-theme` preset. Prefer
504    /// [`resolve_native_theme`](Self::resolve_native_theme) for the ready-to-use
505    /// value expected by `native_theme_gpui::to_theme`.
506    pub fn to_native_theme_mode(&self) -> native_theme::theme::ThemeMode {
507        use native_theme::theme::ThemeMode;
508
509        let mut mode = ThemeMode::default();
510        let semantic = &self.semantic_palette;
511        let native = |color: Option<Rgba>| color.map(to_native_color);
512
513        mode.defaults.background_color = native(semantic.window_background);
514        mode.defaults.text_color = native(semantic.window_text);
515        mode.defaults.accent_color = native(semantic.accent);
516        mode.defaults.accent_text_color = native(semantic.accent_text);
517        mode.defaults.surface_color = native(semantic.surface_background);
518        mode.defaults.muted_color = native(semantic.disabled_text.or(semantic.window_text));
519        mode.defaults.link_color = native(semantic.link);
520        mode.defaults.selection_background = native(semantic.selection_background);
521        mode.defaults.selection_text_color = native(semantic.selection_text);
522        mode.defaults.selection_inactive_background = native(semantic.selection_background);
523        mode.defaults.text_selection_background = native(semantic.selection_background);
524        mode.defaults.text_selection_color = native(semantic.selection_text);
525        mode.defaults.disabled_text_color = native(semantic.disabled_text);
526        mode.defaults.danger_color = native(semantic.error);
527        mode.defaults.warning_color = native(semantic.warning);
528        mode.defaults.success_color = native(semantic.success);
529        mode.defaults.info_color = native(semantic.accent);
530        mode.defaults.focus_ring_color = native(semantic.accent);
531        mode.defaults.border.color = native(semantic.border);
532        mode.defaults.icon_theme = self
533            .settings
534            .icon_theme_name
535            .as_ref()
536            .map(|name| name.clone().into());
537        if let (Some(font_name), Some(text)) = (&self.settings.font_name, semantic.window_text)
538            && let Some(font) = native_font(font_name, text)
539        {
540            mode.defaults.font = font;
541        }
542
543        mode.window.background_color = native(semantic.window_background);
544        mode.window.title_bar_background = first_color(
545            &self.named_colors,
546            &["headerbar_bg_color", "window_bg_color", "theme_bg_color"],
547        )
548        .map(to_native_color);
549        mode.window.inactive_title_bar_background = mode.window.title_bar_background;
550        mode.window.inactive_title_bar_text_color = native(semantic.window_text);
551
552        mode.button.background_color = native(semantic.surface_background);
553        mode.button.primary_background = native(semantic.accent);
554        mode.button.primary_text_color = native(semantic.accent_text);
555        mode.button.hover_text_color = native(self.state_color("button", "hovered"));
556        mode.button.active_text_color = native(self.state_color("button", "pressed"));
557        mode.button.disabled_text_color = native(
558            self.state_color("button", "disabled")
559                .or(semantic.disabled_text),
560        );
561        if let Some(widget) = self.widget("button") {
562            mode.button.min_width = Some(widget.metrics.minimum_width as f32);
563            mode.button.min_height = Some(widget.metrics.minimum_height as f32);
564            if let (Some(font_name), Some(text)) = (
565                &self.settings.font_name,
566                self.state_color("button", "normal"),
567            ) {
568                mode.button.font = native_font(font_name, text);
569            }
570        }
571
572        mode.input.background_color = native(semantic.input_background);
573        mode.input.caret_color = native(semantic.input_text);
574        mode.input.selection_background = native(semantic.selection_background);
575        mode.input.selection_text_color = native(semantic.selection_text);
576        mode.input.disabled_text_color = native(
577            self.state_color("input", "disabled")
578                .or(semantic.disabled_text),
579        );
580        mode.input.focus_border_color = native(semantic.accent);
581        if let Some(widget) = self.widget("input") {
582            mode.input.min_height = Some(widget.metrics.minimum_height as f32);
583        }
584
585        mode.checkbox.background_color = native(semantic.window_background);
586        mode.checkbox.checked_background = native(semantic.accent);
587        mode.checkbox.indicator_color = native(semantic.accent_text);
588        mode.checkbox.disabled_text_color = native(
589            self.state_color("checkbox", "disabled")
590                .or(semantic.disabled_text),
591        );
592
593        mode.menu.background_color = native(semantic.surface_background);
594        mode.menu.separator_color = native(semantic.border);
595        mode.menu.hover_background = native(semantic.selection_background);
596        mode.menu.hover_text_color = native(semantic.selection_text);
597        mode.menu.disabled_text_color = native(semantic.disabled_text);
598        mode.tooltip.background_color = native(semantic.tooltip_background);
599        if let (Some(font_name), Some(text)) = (&self.settings.font_name, semantic.tooltip_text) {
600            mode.tooltip.font = native_font(font_name, text);
601        }
602
603        mode.scrollbar.track_color = native(semantic.window_background);
604        mode.scrollbar.thumb_color = native(semantic.border.or(semantic.disabled_text));
605        mode.scrollbar.thumb_hover_color = native(semantic.accent);
606        mode.scrollbar.overlay_mode = self.settings.overlay_scrolling;
607        if let Some(widget) = self.widget("scrollbar") {
608            mode.scrollbar.groove_width = Some(widget.metrics.natural_width as f32);
609        }
610
611        mode.slider.fill_color = native(semantic.accent);
612        mode.slider.track_color = native(semantic.border);
613        mode.slider.thumb_color = native(semantic.surface_background);
614        mode.progress_bar.fill_color = native(semantic.accent);
615        mode.progress_bar.track_color = native(semantic.window_background);
616        if let Some(widget) = self.widget("progress-bar") {
617            mode.progress_bar.track_height = Some(widget.metrics.natural_height as f32);
618            mode.progress_bar.min_width = Some(widget.metrics.minimum_width as f32);
619        }
620        mode.switch.checked_background = native(semantic.accent);
621        mode.switch.unchecked_background = native(semantic.border);
622        mode.switch.thumb_background = native(semantic.surface_background);
623        if let Some(widget) = self.widget("switch") {
624            mode.switch.track_width = Some(widget.metrics.natural_width as f32);
625            mode.switch.track_height = Some(widget.metrics.natural_height as f32);
626        }
627        mode.separator.line_color = native(semantic.border);
628        mode.combo_box.background_color = native(semantic.surface_background);
629        mode.combo_box.disabled_text_color = native(semantic.disabled_text);
630        mode
631    }
632
633    /// Resolve this GTK snapshot into the exact input accepted by
634    /// `native_theme_gpui::to_theme`.
635    pub fn resolve_native_theme(&self) -> Result<NativeThemeBridge, NativeThemeBridgeError> {
636        use native_theme::resolve::ResolutionContext;
637        use native_theme::theme::{ColorMode, Theme};
638
639        self.validate()?;
640        let background = self
641            .semantic_palette
642            .window_background
643            .ok_or(NativeThemeBridgeError::MissingColor("window_background"))?;
644        self.semantic_palette
645            .window_text
646            .ok_or(NativeThemeBridgeError::MissingColor("window_text"))?;
647        let mode = if relative_luminance(background) < 0.5 {
648            ColorMode::Dark
649        } else {
650            ColorMode::Light
651        };
652        let mut variant = Theme::preset("adwaita")?.into_variant(mode)?;
653        variant.merge(&self.to_native_theme_mode());
654        let resolved = variant.into_resolved(&ResolutionContext::from_system())?;
655        Ok(NativeThemeBridge {
656            name: format!("GTK {}", self.identity.theme_name),
657            mode,
658            resolved,
659            reduce_transparency: false,
660            reduce_motion: self
661                .settings
662                .interface_reduced_motion
663                .as_ref()
664                .is_some_and(|setting| setting.value != 0),
665            high_contrast: self
666                .settings
667                .interface_contrast
668                .as_ref()
669                .is_some_and(|setting| setting.nick != "no-preference"),
670        })
671    }
672
673    /// Resolve and convert this snapshot into a `gpui-component` theme.
674    #[cfg(feature = "gpui")]
675    pub fn to_gpui_theme(&self) -> Result<gpui_component::theme::Theme, NativeThemeBridgeError> {
676        Ok(self.resolve_native_theme()?.to_gpui_theme())
677    }
678}
679
680fn first_color(colors: &[NamedColor], names: &[&str]) -> Option<Rgba> {
681    names.iter().find_map(|name| {
682        colors
683            .iter()
684            .find(|color| color.name == *name)
685            .map(|color| color.value)
686    })
687}
688
689fn semantic_palette(colors: &[NamedColor]) -> SemanticPalette {
690    SemanticPalette {
691        window_background: first_color(colors, &["window_bg_color", "theme_bg_color"]),
692        window_text: first_color(colors, &["window_fg_color", "theme_fg_color"]),
693        surface_background: first_color(
694            colors,
695            &[
696                "card_bg_color",
697                "popover_bg_color",
698                "window_bg_color",
699                "theme_bg_color",
700            ],
701        ),
702        surface_text: first_color(
703            colors,
704            &[
705                "card_fg_color",
706                "popover_fg_color",
707                "window_fg_color",
708                "theme_fg_color",
709            ],
710        ),
711        input_background: first_color(colors, &["view_bg_color", "theme_base_color"]),
712        input_text: first_color(colors, &["view_fg_color", "theme_text_color"]),
713        selection_background: first_color(colors, &["accent_bg_color", "theme_selected_bg_color"]),
714        selection_text: first_color(colors, &["accent_fg_color", "theme_selected_fg_color"]),
715        accent: first_color(
716            colors,
717            &["accent_bg_color", "accent_color", "theme_selected_bg_color"],
718        ),
719        accent_text: first_color(colors, &["accent_fg_color", "theme_selected_fg_color"]),
720        border: first_color(colors, &["borders"]),
721        disabled_text: first_color(colors, &["insensitive_fg_color"]),
722        tooltip_background: first_color(
723            colors,
724            &[
725                "popover_bg_color",
726                "card_bg_color",
727                "window_bg_color",
728                "theme_bg_color",
729            ],
730        ),
731        tooltip_text: first_color(
732            colors,
733            &[
734                "popover_fg_color",
735                "card_fg_color",
736                "window_fg_color",
737                "theme_fg_color",
738            ],
739        ),
740        link: first_color(colors, &["link_color", "accent_color"]),
741        error: first_color(colors, &["error_color", "destructive_color"]),
742        warning: first_color(colors, &["warning_color"]),
743        success: first_color(colors, &["success_color"]),
744    }
745}
746
747/// Failure to initialize or query GTK.
748#[derive(Debug, Error)]
749pub enum ProbeError {
750    /// GTK could not connect to a display or initialize its backend.
751    #[error("failed to initialize GTK: {0}")]
752    Initialization(String),
753    /// No default GTK settings object was available.
754    #[error("GTK did not provide a default settings object")]
755    MissingSettings,
756    /// GTK produced a snapshot that violates the public contract.
757    #[error(transparent)]
758    InvalidSnapshot(#[from] SnapshotValidationError),
759}
760
761fn setting<T>(settings: &gtk::Settings, name: &str) -> Option<T>
762where
763    for<'a> T: glib::value::FromValue<'a> + 'static,
764{
765    settings
766        .find_property(name)
767        .and_then(|_| settings.property_value(name).get::<T>().ok())
768}
769
770fn enum_setting(settings: &gtk::Settings, name: &str) -> Option<EnumSetting> {
771    settings.find_property(name)?;
772    let value = settings.property_value(name);
773    let (_, value) = glib::EnumValue::from_value(&value)?;
774    Some(EnumSetting {
775        value: value.value(),
776        name: value.name().to_owned(),
777        nick: value.nick().to_owned(),
778    })
779}
780
781fn requested_dark_variant(color_scheme: Option<&EnumSetting>) -> Option<bool> {
782    match color_scheme?.nick.as_str() {
783        "dark" => Some(true),
784        "light" => Some(false),
785        _ => None,
786    }
787}
788
789fn apply_interface_color_scheme(settings: &gtk::Settings) -> Option<bool> {
790    // GTK_THEME is an explicit per-process override and must remain authoritative.
791    if std::env::var_os("GTK_THEME").is_some() {
792        return None;
793    }
794
795    let prefer_dark =
796        requested_dark_variant(enum_setting(settings, "gtk-interface-color-scheme").as_ref())?;
797
798    // GTK 4.20 exposes the desktop preference separately from the CSS scheme
799    // actually used by the application. Requesting the matching theme variant
800    // before creating widgets makes the probe observe the effective colors.
801    // This compatibility property is available on all GTK 4 versions supported
802    // by this crate, including runtimes predating GtkCssProvider media queries.
803    settings.set_property("gtk-application-prefer-dark-theme", prefer_dark);
804    Some(prefer_dark)
805}
806
807#[allow(deprecated)]
808fn named_colors(widget: &gtk::Widget) -> Vec<NamedColor> {
809    const NAMES: &[&str] = &[
810        "theme_fg_color",
811        "theme_bg_color",
812        "theme_base_color",
813        "theme_text_color",
814        "theme_selected_bg_color",
815        "theme_selected_fg_color",
816        "link_color",
817        "insensitive_bg_color",
818        "insensitive_fg_color",
819        "borders",
820        "warning_color",
821        "error_color",
822        "destructive_color",
823        "success_color",
824        "accent_color",
825        "accent_bg_color",
826        "accent_fg_color",
827        "window_bg_color",
828        "window_fg_color",
829        "view_bg_color",
830        "view_fg_color",
831        "headerbar_bg_color",
832        "headerbar_fg_color",
833        "card_bg_color",
834        "card_fg_color",
835        "popover_bg_color",
836        "popover_fg_color",
837        "dialog_bg_color",
838        "dialog_fg_color",
839    ];
840
841    let context = widget.style_context();
842    NAMES
843        .iter()
844        .filter_map(|name| {
845            context.lookup_color(name).map(|value| NamedColor {
846                name: (*name).to_owned(),
847                value: value.into(),
848            })
849        })
850        .collect()
851}
852
853fn widget_metrics(widget: &gtk::Widget) -> WidgetMetrics {
854    let (minimum_width, natural_width, _, _) = widget.measure(gtk::Orientation::Horizontal, -1);
855    let (minimum_height, natural_height, _, _) =
856        widget.measure(gtk::Orientation::Vertical, natural_width);
857    WidgetMetrics {
858        minimum_width,
859        natural_width,
860        minimum_height,
861        natural_height,
862    }
863}
864
865fn widget_states(widget: &gtk::Widget) -> Vec<WidgetState> {
866    const STATES: &[(&str, gtk::StateFlags)] = &[
867        ("normal", gtk::StateFlags::NORMAL),
868        ("hovered", gtk::StateFlags::PRELIGHT),
869        ("pressed", gtk::StateFlags::ACTIVE),
870        ("focused", gtk::StateFlags::FOCUSED),
871        ("focus-visible", gtk::StateFlags::FOCUS_VISIBLE),
872        ("checked", gtk::StateFlags::CHECKED),
873        ("selected", gtk::StateFlags::SELECTED),
874        ("disabled", gtk::StateFlags::INSENSITIVE),
875        ("inactive", gtk::StateFlags::BACKDROP),
876    ];
877
878    let previous = widget.state_flags();
879    let all = gtk::StateFlags::all();
880    let mut result = Vec::with_capacity(STATES.len());
881    for (name, flags) in STATES {
882        widget.unset_state_flags(all);
883        widget.set_state_flags(*flags, true);
884        result.push(WidgetState {
885            state: (*name).to_owned(),
886            foreground: widget.color().into(),
887        });
888    }
889    widget.unset_state_flags(all);
890    widget.set_state_flags(previous, true);
891    result
892}
893
894fn widget_snapshot(control: &str, widget: &gtk::Widget) -> WidgetSnapshot {
895    WidgetSnapshot {
896        control: control.to_owned(),
897        css_name: widget.css_name().to_string(),
898        metrics: widget_metrics(widget),
899        states: widget_states(widget),
900    }
901}
902
903/// Resolve the current GTK 4 theme.
904///
905/// This function initializes GTK and therefore must run on the process's main
906/// thread before another GUI toolkit claims it. Applications that already run
907/// another event loop should invoke the `native-theme-gtk` CLI as a subprocess.
908pub fn probe() -> Result<ThemeSnapshot, ProbeError> {
909    gtk::init().map_err(|error| ProbeError::Initialization(error.to_string()))?;
910    let settings = gtk::Settings::default().ok_or(ProbeError::MissingSettings)?;
911    let applied_interface_scheme = apply_interface_color_scheme(&settings);
912
913    let window = gtk::Window::new();
914    let container = gtk::Box::new(gtk::Orientation::Vertical, 0);
915    let button = gtk::Button::with_label("Button");
916    let entry = gtk::Entry::new();
917    entry.set_text("Text");
918    let checkbox = gtk::CheckButton::with_label("Check box");
919    let toggle = gtk::Switch::new();
920    let progress = gtk::ProgressBar::new();
921    progress.set_fraction(0.5);
922    let scale = gtk::Scale::with_range(gtk::Orientation::Horizontal, 0.0, 100.0, 1.0);
923    let scrollbar = gtk::Scrollbar::new(gtk::Orientation::Vertical, None::<&gtk::Adjustment>);
924
925    for widget in [
926        button.upcast_ref::<gtk::Widget>(),
927        entry.upcast_ref(),
928        checkbox.upcast_ref(),
929        toggle.upcast_ref(),
930        progress.upcast_ref(),
931        scale.upcast_ref(),
932        scrollbar.upcast_ref(),
933    ] {
934        container.append(widget);
935    }
936    window.set_child(Some(&container));
937
938    let display_backend = gdk::Display::default().map(|display| {
939        let type_name = display.type_().name();
940        type_name
941            .strip_suffix("Display")
942            .unwrap_or(type_name)
943            .to_ascii_lowercase()
944    });
945    let theme_name =
946        setting::<String>(&settings, "gtk-theme-name").unwrap_or_else(|| "Default".to_owned());
947
948    let widgets = [
949        ("window", window.upcast_ref::<gtk::Widget>()),
950        ("button", button.upcast_ref()),
951        ("input", entry.upcast_ref()),
952        ("checkbox", checkbox.upcast_ref()),
953        ("switch", toggle.upcast_ref()),
954        ("progress-bar", progress.upcast_ref()),
955        ("slider", scale.upcast_ref()),
956        ("scrollbar", scrollbar.upcast_ref()),
957    ]
958    .into_iter()
959    .map(|(name, widget)| widget_snapshot(name, widget))
960    .collect();
961
962    let named_colors = named_colors(window.upcast_ref());
963    let semantic_palette = semantic_palette(&named_colors);
964    let mut diagnostics = Vec::new();
965    if named_colors.is_empty() {
966        diagnostics
967            .push("the active theme did not expose any recognized symbolic colors".to_owned());
968    }
969    if let Some(prefer_dark) = applied_interface_scheme {
970        let scheme = if prefer_dark { "dark" } else { "light" };
971        diagnostics.push(format!(
972            "applied the desktop {scheme} color scheme before sampling GTK styles"
973        ));
974    }
975
976    let snapshot = ThemeSnapshot {
977        schema_version: SCHEMA_VERSION,
978        backend: "gtk4".to_owned(),
979        identity: ThemeIdentity {
980            theme_name,
981            toolkit_version: format!(
982                "{}.{}.{}",
983                gtk::major_version(),
984                gtk::minor_version(),
985                gtk::micro_version()
986            ),
987            display_backend,
988        },
989        settings: GtkSettingsSnapshot {
990            font_name: setting(&settings, "gtk-font-name"),
991            icon_theme_name: setting(&settings, "gtk-icon-theme-name"),
992            cursor_theme_name: setting(&settings, "gtk-cursor-theme-name"),
993            cursor_theme_size: setting(&settings, "gtk-cursor-theme-size"),
994            enable_animations: setting(&settings, "gtk-enable-animations"),
995            overlay_scrolling: setting(&settings, "gtk-overlay-scrolling"),
996            primary_button_warps_slider: setting(&settings, "gtk-primary-button-warps-slider"),
997            double_click_time_ms: setting(&settings, "gtk-double-click-time"),
998            cursor_blink_time_ms: setting(&settings, "gtk-cursor-blink-time"),
999            prefer_dark: setting(&settings, "gtk-application-prefer-dark-theme"),
1000            interface_color_scheme: enum_setting(&settings, "gtk-interface-color-scheme"),
1001            interface_contrast: enum_setting(&settings, "gtk-interface-contrast"),
1002            interface_reduced_motion: enum_setting(&settings, "gtk-interface-reduced-motion"),
1003            interface_accent_color: setting::<gdk::RGBA>(&settings, "gtk-accent-color")
1004                .map(Into::into),
1005        },
1006        named_colors,
1007        semantic_palette,
1008        widgets,
1009        diagnostics,
1010    };
1011    snapshot.validate()?;
1012    Ok(snapshot)
1013}
1014
1015#[cfg(test)]
1016mod tests {
1017    use super::*;
1018
1019    #[test]
1020    fn rgba_serializes_with_explicit_channels() {
1021        let json = serde_json::to_value(Rgba {
1022            red: 0.1,
1023            green: 0.2,
1024            blue: 0.3,
1025            alpha: 1.0,
1026        })
1027        .unwrap();
1028        assert_eq!(json["alpha"], 1.0);
1029        let red = json["red"].as_f64().unwrap();
1030        assert!((red - 0.1).abs() < f64::from(f32::EPSILON));
1031    }
1032
1033    #[test]
1034    fn explicit_interface_color_schemes_select_the_matching_variant() {
1035        let setting = |nick: &str| EnumSetting {
1036            value: 0,
1037            name: String::new(),
1038            nick: nick.to_owned(),
1039        };
1040
1041        assert_eq!(requested_dark_variant(Some(&setting("dark"))), Some(true));
1042        assert_eq!(requested_dark_variant(Some(&setting("light"))), Some(false));
1043        assert_eq!(requested_dark_variant(Some(&setting("default"))), None);
1044        assert_eq!(requested_dark_variant(None), None);
1045    }
1046
1047    #[test]
1048    fn snapshot_contract_round_trips() {
1049        let snapshot = ThemeSnapshot {
1050            schema_version: SCHEMA_VERSION,
1051            backend: "gtk4".to_owned(),
1052            identity: ThemeIdentity {
1053                theme_name: "Test".to_owned(),
1054                toolkit_version: "4.0.0".to_owned(),
1055                display_backend: None,
1056            },
1057            settings: GtkSettingsSnapshot {
1058                font_name: None,
1059                icon_theme_name: None,
1060                cursor_theme_name: None,
1061                cursor_theme_size: None,
1062                enable_animations: None,
1063                overlay_scrolling: None,
1064                primary_button_warps_slider: None,
1065                double_click_time_ms: None,
1066                cursor_blink_time_ms: None,
1067                prefer_dark: None,
1068                interface_color_scheme: None,
1069                interface_contrast: None,
1070                interface_reduced_motion: None,
1071                interface_accent_color: None,
1072            },
1073            named_colors: Vec::new(),
1074            semantic_palette: SemanticPalette::default(),
1075            widgets: Vec::new(),
1076            diagnostics: Vec::new(),
1077        };
1078        let json = serde_json::to_string(&snapshot).unwrap();
1079        assert_eq!(
1080            serde_json::from_str::<ThemeSnapshot>(&json).unwrap(),
1081            snapshot
1082        );
1083    }
1084
1085    #[test]
1086    fn semantic_palette_prefers_modern_gtk_names() {
1087        let modern = Rgba {
1088            red: 1.0,
1089            green: 0.0,
1090            blue: 0.0,
1091            alpha: 1.0,
1092        };
1093        let legacy = Rgba {
1094            red: 0.0,
1095            green: 0.0,
1096            blue: 1.0,
1097            alpha: 1.0,
1098        };
1099        let palette = semantic_palette(&[
1100            NamedColor {
1101                name: "theme_bg_color".to_owned(),
1102                value: legacy,
1103            },
1104            NamedColor {
1105                name: "window_bg_color".to_owned(),
1106                value: modern,
1107            },
1108        ]);
1109        assert_eq!(palette.window_background, Some(modern));
1110    }
1111
1112    #[test]
1113    fn semantic_palette_contract_has_stable_role_names() {
1114        let value = serde_json::to_value(SemanticPalette::default()).unwrap();
1115        let mut actual: Vec<_> = value
1116            .as_object()
1117            .unwrap()
1118            .keys()
1119            .map(String::as_str)
1120            .collect();
1121        let mut expected = SEMANTIC_COLOR_ROLES.to_vec();
1122        actual.sort_unstable();
1123        expected.sort_unstable();
1124        assert_eq!(actual, expected);
1125    }
1126
1127    #[test]
1128    fn invalid_color_channels_are_rejected() {
1129        let error = validate_rgba(
1130            "test",
1131            Rgba {
1132                red: f32::NAN,
1133                green: 0.0,
1134                blue: 0.0,
1135                alpha: 1.0,
1136            },
1137        )
1138        .unwrap_err();
1139        assert!(error.reason().contains("test.red"));
1140    }
1141
1142    #[test]
1143    fn incomplete_snapshot_is_rejected() {
1144        let snapshot = ThemeSnapshot {
1145            schema_version: SCHEMA_VERSION,
1146            backend: "gtk4".to_owned(),
1147            identity: ThemeIdentity {
1148                theme_name: "Test".to_owned(),
1149                toolkit_version: "4.22.0".to_owned(),
1150                display_backend: None,
1151            },
1152            settings: GtkSettingsSnapshot {
1153                font_name: None,
1154                icon_theme_name: None,
1155                cursor_theme_name: None,
1156                cursor_theme_size: None,
1157                enable_animations: None,
1158                overlay_scrolling: None,
1159                primary_button_warps_slider: None,
1160                double_click_time_ms: None,
1161                cursor_blink_time_ms: None,
1162                prefer_dark: None,
1163                interface_color_scheme: None,
1164                interface_contrast: None,
1165                interface_reduced_motion: None,
1166                interface_accent_color: None,
1167            },
1168            named_colors: Vec::new(),
1169            semantic_palette: SemanticPalette::default(),
1170            widgets: Vec::new(),
1171            diagnostics: Vec::new(),
1172        };
1173        assert!(
1174            snapshot
1175                .validate()
1176                .unwrap_err()
1177                .reason()
1178                .contains("missing representative widget")
1179        );
1180    }
1181}