Skip to main content

native_theme_qt/
lib.rs

1//! Resolve the effective Qt 6 widget theme through Qt itself.
2//!
3//! The C++ probe lets Qt load the configured QPA platform theme and `QStyle`
4//! plugins, then returns the effective palette, fonts, metrics, and style hints
5//! as JSON. This handles configurations that cannot be reproduced by parsing a
6//! single `qt6ct.conf` file.
7
8use std::collections::{BTreeMap, HashSet};
9
10use serde::{Deserialize, Serialize};
11use thiserror::Error;
12
13/// Version of the JSON snapshot contract.
14pub const SCHEMA_VERSION: u32 = 1;
15
16/// Stable toolkit-neutral role names shared with `native-theme-gtk`.
17pub const SEMANTIC_COLOR_ROLES: [&str; 18] = [
18    "window_background",
19    "window_text",
20    "surface_background",
21    "surface_text",
22    "input_background",
23    "input_text",
24    "selection_background",
25    "selection_text",
26    "accent",
27    "accent_text",
28    "border",
29    "disabled_text",
30    "tooltip_background",
31    "tooltip_text",
32    "link",
33    "error",
34    "warning",
35    "success",
36];
37
38#[cxx::bridge(namespace = "native_theme_qt")]
39mod ffi {
40    unsafe extern "C++" {
41        include!("probe.h");
42
43        fn probe_theme() -> Result<UniquePtr<CxxString>>;
44    }
45}
46
47/// An RGBA color in the sRGB color space.
48#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
49pub struct Rgba {
50    /// Red channel in the inclusive range 0..=1.
51    pub red: f32,
52    /// Green channel in the inclusive range 0..=1.
53    pub green: f32,
54    /// Blue channel in the inclusive range 0..=1.
55    pub blue: f32,
56    /// Alpha channel in the inclusive range 0..=1.
57    pub alpha: f32,
58}
59
60/// Identity of the active Qt theme and platform backend.
61#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
62pub struct ThemeIdentity {
63    /// Name returned by the active `QStyle`.
64    pub style_name: String,
65    /// Qt runtime version.
66    pub toolkit_version: String,
67    /// Active QPA platform plugin, such as `wayland` or `xcb`.
68    pub platform_backend: String,
69    /// `QT_QPA_PLATFORMTHEME`, when set in the environment.
70    pub platform_theme: Option<String>,
71    /// `QT_STYLE_OVERRIDE`, when set in the environment.
72    pub style_override: Option<String>,
73}
74
75/// A resolved Qt font.
76#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
77pub struct FontSnapshot {
78    /// Resolved font family.
79    pub family: String,
80    /// Point size, or a negative value when the font uses pixel sizing.
81    pub point_size: f32,
82    /// Pixel size, or a negative value when the font uses point sizing.
83    pub pixel_size: i32,
84    /// Qt font weight.
85    pub weight: i32,
86    /// Whether the font is italic.
87    pub italic: bool,
88    /// Font stretch percentage.
89    pub stretch: i32,
90}
91
92/// Application-wide values resolved by Qt.
93#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
94pub struct QtSettingsSnapshot {
95    /// Default application font.
96    pub font: FontSnapshot,
97    /// Platform fixed-width font.
98    pub fixed_font: FontSnapshot,
99    /// Freedesktop icon theme selected by Qt.
100    pub icon_theme_name: String,
101    /// Cursor blink interval in milliseconds.
102    pub cursor_flash_time_ms: i32,
103    /// Double-click interval in milliseconds.
104    pub double_click_interval_ms: i32,
105    /// Number of lines scrolled for each wheel step.
106    pub wheel_scroll_lines: i32,
107    /// Application-wide QSS after the platform theme has initialized.
108    pub application_stylesheet: String,
109}
110
111/// One brush from a Qt palette.
112#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
113pub struct PaletteBrush {
114    /// Brush color converted to sRGB RGBA.
115    pub color: Rgba,
116    /// Qt brush style numeric value. Non-solid brushes may require rendering.
117    pub brush_style: i32,
118}
119
120/// Toolkit-neutral colors projected from Qt palette roles.
121#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
122pub struct SemanticPalette {
123    /// Main application window background.
124    pub window_background: Option<Rgba>,
125    /// Text drawn directly on the window background.
126    pub window_text: Option<Rgba>,
127    /// Raised surface or button background.
128    pub surface_background: Option<Rgba>,
129    /// Text drawn on raised surfaces.
130    pub surface_text: Option<Rgba>,
131    /// Editable/view content background.
132    pub input_background: Option<Rgba>,
133    /// Editable/view content text.
134    pub input_text: Option<Rgba>,
135    /// Selected item background.
136    pub selection_background: Option<Rgba>,
137    /// Text drawn on a selected item.
138    pub selection_text: Option<Rgba>,
139    /// Primary accent background.
140    pub accent: Option<Rgba>,
141    /// Text drawn over the primary accent.
142    pub accent_text: Option<Rgba>,
143    /// General separator or frame color.
144    pub border: Option<Rgba>,
145    /// Text used by disabled controls.
146    pub disabled_text: Option<Rgba>,
147    /// Tooltip background.
148    pub tooltip_background: Option<Rgba>,
149    /// Tooltip text.
150    pub tooltip_text: Option<Rgba>,
151    /// Hyperlink foreground.
152    pub link: Option<Rgba>,
153    /// Destructive or error foreground, when published by the backend.
154    pub error: Option<Rgba>,
155    /// Warning foreground, when published by the backend.
156    pub warning: Option<Rgba>,
157    /// Success foreground, when published by the backend.
158    pub success: Option<Rgba>,
159}
160
161/// Qt palette groups keyed by `active`, `inactive`, and `disabled`, then role.
162pub type PaletteSnapshot = BTreeMap<String, BTreeMap<String, PaletteBrush>>;
163
164/// A two-dimensional size in toolkit logical pixels.
165#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
166pub struct SizeSnapshot {
167    /// Horizontal extent, or `-1` if Qt does not provide a hint.
168    pub width: i32,
169    /// Vertical extent, or `-1` if Qt does not provide a hint.
170    pub height: i32,
171}
172
173/// Resolved defaults for one representative Qt widget.
174#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
175pub struct ControlSnapshot {
176    /// Preferred size for representative content.
177    pub size_hint: SizeSnapshot,
178    /// Minimum preferred size for representative content.
179    pub minimum_size_hint: SizeSnapshot,
180    /// Font inherited by this widget after polishing.
181    pub font: FontSnapshot,
182    /// Widget-specific palette after the active style has polished it.
183    pub palette: PaletteSnapshot,
184}
185
186/// A complete Qt theme probe result.
187#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
188pub struct ThemeSnapshot {
189    /// Snapshot schema version.
190    pub schema_version: u32,
191    /// Backend discriminator. Always `qt6` for this crate.
192    pub backend: String,
193    /// Theme identity and toolkit runtime details.
194    pub identity: ThemeIdentity,
195    /// Application-wide resolved settings.
196    pub settings: QtSettingsSnapshot,
197    /// Effective application palette.
198    pub palette: PaletteSnapshot,
199    /// Toolkit-neutral projection of the palette.
200    #[serde(default)]
201    pub semantic_palette: SemanticPalette,
202    /// Polished representative controls keyed by stable control name.
203    #[serde(default)]
204    pub controls: BTreeMap<String, ControlSnapshot>,
205    /// `QStyle::pixelMetric` values in logical pixels.
206    pub metrics: BTreeMap<String, i32>,
207    /// Selected integer and boolean `QStyle::styleHint` values.
208    pub hints: BTreeMap<String, i32>,
209    /// Non-fatal limitations encountered by the probe.
210    pub diagnostics: Vec<String>,
211}
212
213/// Explanation of why a theme snapshot is not safe to consume.
214#[derive(Debug, Error, PartialEq, Eq)]
215#[error("invalid Qt theme snapshot: {reason}")]
216pub struct SnapshotValidationError {
217    reason: String,
218}
219
220impl SnapshotValidationError {
221    /// Human-readable validation failure.
222    pub fn reason(&self) -> &str {
223        &self.reason
224    }
225}
226
227fn validation_error(reason: impl Into<String>) -> SnapshotValidationError {
228    SnapshotValidationError {
229        reason: reason.into(),
230    }
231}
232
233fn validate_rgba(path: &str, color: Rgba) -> Result<(), SnapshotValidationError> {
234    for (channel, value) in [
235        ("red", color.red),
236        ("green", color.green),
237        ("blue", color.blue),
238        ("alpha", color.alpha),
239    ] {
240        if !value.is_finite() || !(0.0..=1.0).contains(&value) {
241            return Err(validation_error(format!(
242                "{path}.{channel} must be finite and in 0..=1, got {value}"
243            )));
244        }
245    }
246    Ok(())
247}
248
249fn validate_palette(path: &str, palette: &PaletteSnapshot) -> Result<(), SnapshotValidationError> {
250    for required in ["active", "inactive", "disabled"] {
251        if !palette.contains_key(required) {
252            return Err(validation_error(format!(
253                "{path} is missing color group {required}"
254            )));
255        }
256    }
257    for (group, roles) in palette {
258        for (role, brush) in roles {
259            validate_rgba(&format!("{path}.{group}.{role}"), brush.color)?;
260            if brush.brush_style < 0 {
261                return Err(validation_error(format!(
262                    "{path}.{group}.{role}.brush_style must not be negative"
263                )));
264            }
265        }
266    }
267    Ok(())
268}
269
270fn validate_font(path: &str, font: &FontSnapshot) -> Result<(), SnapshotValidationError> {
271    if font.family.trim().is_empty() {
272        return Err(validation_error(format!("{path}.family must not be empty")));
273    }
274    if !font.point_size.is_finite() {
275        return Err(validation_error(format!(
276            "{path}.point_size must be finite"
277        )));
278    }
279    if font.stretch < 0 {
280        return Err(validation_error(format!(
281            "{path}.stretch must not be negative"
282        )));
283    }
284    Ok(())
285}
286
287impl ThemeSnapshot {
288    /// Check schema, identity, required palette roles, controls, and colors.
289    pub fn validate(&self) -> Result<(), SnapshotValidationError> {
290        if self.schema_version != SCHEMA_VERSION {
291            return Err(validation_error(format!(
292                "unsupported schema version {}; expected {SCHEMA_VERSION}",
293                self.schema_version
294            )));
295        }
296        if self.backend != "qt6" {
297            return Err(validation_error(format!(
298                "backend must be qt6, got {:?}",
299                self.backend
300            )));
301        }
302        if self.identity.style_name.trim().is_empty()
303            || self.identity.toolkit_version.trim().is_empty()
304            || self.identity.platform_backend.trim().is_empty()
305        {
306            return Err(validation_error(
307                "style name, toolkit version, and platform backend must not be empty",
308            ));
309        }
310        validate_font("settings.font", &self.settings.font)?;
311        validate_font("settings.fixed_font", &self.settings.fixed_font)?;
312        validate_palette("palette", &self.palette)?;
313        for role in [
314            "window",
315            "window_text",
316            "button",
317            "button_text",
318            "base",
319            "text",
320            "highlight",
321            "highlighted_text",
322        ] {
323            if !self.palette["active"].contains_key(role) {
324                return Err(validation_error(format!(
325                    "palette.active is missing role {role}"
326                )));
327            }
328        }
329
330        for (name, color) in [
331            ("window_background", self.semantic_palette.window_background),
332            ("window_text", self.semantic_palette.window_text),
333            (
334                "surface_background",
335                self.semantic_palette.surface_background,
336            ),
337            ("surface_text", self.semantic_palette.surface_text),
338            ("input_background", self.semantic_palette.input_background),
339            ("input_text", self.semantic_palette.input_text),
340            (
341                "selection_background",
342                self.semantic_palette.selection_background,
343            ),
344            ("selection_text", self.semantic_palette.selection_text),
345            ("accent", self.semantic_palette.accent),
346            ("accent_text", self.semantic_palette.accent_text),
347            ("border", self.semantic_palette.border),
348            ("disabled_text", self.semantic_palette.disabled_text),
349            (
350                "tooltip_background",
351                self.semantic_palette.tooltip_background,
352            ),
353            ("tooltip_text", self.semantic_palette.tooltip_text),
354            ("link", self.semantic_palette.link),
355            ("error", self.semantic_palette.error),
356            ("warning", self.semantic_palette.warning),
357            ("success", self.semantic_palette.success),
358        ] {
359            if let Some(color) = color {
360                validate_rgba(&format!("semantic_palette.{name}"), color)?;
361            }
362        }
363
364        let required_controls: HashSet<_> = [
365            "button",
366            "line_edit",
367            "check_box",
368            "radio_button",
369            "combo_box",
370            "spin_box",
371            "slider",
372            "progress_bar",
373            "scroll_bar",
374            "tab_bar",
375            "tool_button",
376        ]
377        .into_iter()
378        .collect();
379        for required in required_controls {
380            if !self.controls.contains_key(required) {
381                return Err(validation_error(format!(
382                    "missing representative control {required}"
383                )));
384            }
385        }
386        for (name, control) in &self.controls {
387            for (kind, size) in [
388                ("size_hint", control.size_hint),
389                ("minimum_size_hint", control.minimum_size_hint),
390            ] {
391                if size.width < -1 || size.height < -1 {
392                    return Err(validation_error(format!(
393                        "controls.{name}.{kind} contains a dimension below -1"
394                    )));
395                }
396            }
397            validate_font(&format!("controls.{name}.font"), &control.font)?;
398            validate_palette(&format!("controls.{name}.palette"), &control.palette)?;
399        }
400        if self.metrics.is_empty() || self.hints.is_empty() {
401            return Err(validation_error(
402                "style metrics and hints must not be empty",
403            ));
404        }
405        Ok(())
406    }
407}
408
409/// A Qt snapshot resolved through `native-theme`, ready for framework connectors.
410#[derive(Clone, Debug)]
411pub struct NativeThemeBridge {
412    /// Display name for the detected theme.
413    pub name: String,
414    /// Light or dark mode inferred from the effective window background.
415    pub mode: native_theme::theme::ColorMode,
416    /// Fully populated theme accepted by `native_theme_gpui::to_theme`.
417    pub resolved: native_theme::theme::ResolvedTheme,
418    /// Whether transparent effects should be reduced.
419    pub reduce_transparency: bool,
420    /// Whether the user requested reduced motion.
421    pub reduce_motion: bool,
422    /// Whether the user requested increased contrast.
423    pub high_contrast: bool,
424}
425
426impl NativeThemeBridge {
427    /// Convert the resolved bridge into a `gpui-component` theme.
428    #[cfg(feature = "gpui")]
429    #[must_use = "this returns the GPUI theme; it does not install it globally"]
430    pub fn to_gpui_theme(&self) -> gpui_component::theme::Theme {
431        native_theme_gpui::to_theme(
432            &self.resolved,
433            &self.name,
434            self.mode.is_dark(),
435            self.reduce_transparency,
436        )
437    }
438}
439
440/// Failure to translate a Qt snapshot into the `native-theme` model.
441#[derive(Debug, Error)]
442pub enum NativeThemeBridgeError {
443    /// The source snapshot is malformed or incomplete.
444    #[error(transparent)]
445    InvalidSnapshot(#[from] SnapshotValidationError),
446    /// A semantic role required for a faithful base theme was unavailable.
447    #[error("Qt snapshot is missing required semantic color {0}")]
448    MissingColor(&'static str),
449    /// The `native-theme` inheritance or validation pipeline failed.
450    #[error("native-theme resolution failed: {0}")]
451    Resolution(#[from] native_theme::error::Error),
452}
453
454fn to_native_color(color: Rgba) -> native_theme::color::Rgba {
455    native_theme::color::Rgba::from_f32(color.red, color.green, color.blue, color.alpha)
456}
457
458fn native_font(font: &FontSnapshot, color: Rgba) -> native_theme::theme::FontSpec {
459    use native_theme::theme::{FontSize, FontSpec, FontStyle, intern_font_family};
460
461    FontSpec {
462        family: Some(intern_font_family(&font.family)),
463        size: if font.point_size > 0.0 {
464            Some(FontSize::Pt(font.point_size))
465        } else if font.pixel_size > 0 {
466            Some(FontSize::Px(font.pixel_size as f32))
467        } else {
468            None
469        },
470        weight: u16::try_from(font.weight).ok(),
471        style: Some(if font.italic {
472            FontStyle::Italic
473        } else {
474            FontStyle::Normal
475        }),
476        color: Some(to_native_color(color)),
477    }
478}
479
480fn relative_luminance(color: Rgba) -> f32 {
481    fn linear(channel: f32) -> f32 {
482        if channel <= 0.04045 {
483            channel / 12.92
484        } else {
485            ((channel + 0.055) / 1.055).powf(2.4)
486        }
487    }
488    0.2126 * linear(color.red) + 0.7152 * linear(color.green) + 0.0722 * linear(color.blue)
489}
490
491impl ThemeSnapshot {
492    /// Translate resolved Qt values into a sparse `native-theme` mode.
493    ///
494    /// The result can be merged over any `native-theme` preset. Prefer
495    /// [`resolve_native_theme`](Self::resolve_native_theme) for the ready-to-use
496    /// value expected by `native_theme_gpui::to_theme`.
497    pub fn to_native_theme_mode(&self) -> native_theme::theme::ThemeMode {
498        use native_theme::theme::{ThemeMode, WidgetBorderSpec};
499
500        let mut mode = ThemeMode::default();
501        let semantic = &self.semantic_palette;
502        let native = |color: Option<Rgba>| color.map(to_native_color);
503
504        mode.defaults.background_color = native(semantic.window_background);
505        mode.defaults.text_color = native(semantic.window_text);
506        mode.defaults.accent_color = native(semantic.accent);
507        mode.defaults.accent_text_color = native(semantic.accent_text);
508        mode.defaults.surface_color = native(semantic.surface_background);
509        mode.defaults.muted_color = native(semantic.disabled_text.or(semantic.window_text));
510        mode.defaults.link_color = native(semantic.link);
511        mode.defaults.selection_background = native(semantic.selection_background);
512        mode.defaults.selection_text_color = native(semantic.selection_text);
513        mode.defaults.selection_inactive_background =
514            palette_color(&self.palette, "inactive", "highlight").map(to_native_color);
515        mode.defaults.text_selection_background = native(semantic.selection_background);
516        mode.defaults.text_selection_color = native(semantic.selection_text);
517        mode.defaults.disabled_text_color = native(semantic.disabled_text);
518        mode.defaults.danger_color = native(semantic.error);
519        mode.defaults.warning_color = native(semantic.warning);
520        mode.defaults.success_color = native(semantic.success);
521        mode.defaults.info_color = native(semantic.accent);
522        mode.defaults.focus_ring_color = native(semantic.accent);
523        mode.defaults.border.color = native(semantic.border);
524        mode.defaults.border.line_width = self
525            .metrics
526            .get("default_frame_width")
527            .copied()
528            .map(|value| value as f32);
529        mode.defaults.icon_sizes.toolbar = self
530            .metrics
531            .get("toolbar_icon_size")
532            .copied()
533            .map(|value| value as f32);
534        mode.defaults.icon_sizes.small = self
535            .metrics
536            .get("small_icon_size")
537            .copied()
538            .map(|value| value as f32);
539        mode.defaults.icon_sizes.large = self
540            .metrics
541            .get("large_icon_size")
542            .copied()
543            .map(|value| value as f32);
544        if let Some(text) = semantic.window_text {
545            mode.defaults.font = native_font(&self.settings.font, text);
546            mode.defaults.mono_font = native_font(&self.settings.fixed_font, text);
547        }
548        mode.defaults.icon_theme = (!self.settings.icon_theme_name.is_empty())
549            .then(|| self.settings.icon_theme_name.clone().into());
550
551        mode.window.background_color = native(semantic.window_background);
552        mode.window.title_bar_background = native(semantic.surface_background);
553        mode.window.inactive_title_bar_background =
554            palette_color(&self.palette, "inactive", "window").map(to_native_color);
555        mode.window.inactive_title_bar_text_color =
556            palette_color(&self.palette, "inactive", "window_text").map(to_native_color);
557
558        mode.button.background_color = native(semantic.surface_background);
559        mode.button.primary_background = native(semantic.accent);
560        mode.button.primary_text_color = native(semantic.accent_text);
561        mode.button.disabled_text_color = native(semantic.disabled_text);
562        if let Some(control) = self.controls.get("button") {
563            mode.button.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
564            mode.button.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
565            mode.button.font = semantic
566                .surface_text
567                .map(|color| native_font(&control.font, color));
568            mode.button.border = Some(WidgetBorderSpec {
569                color: native(semantic.border),
570                line_width: mode.defaults.border.line_width,
571                padding_horizontal: self
572                    .metrics
573                    .get("button_margin")
574                    .map(|value| *value as f32 / 2.0),
575                padding_vertical: self
576                    .metrics
577                    .get("button_margin")
578                    .map(|value| *value as f32 / 2.0),
579                ..Default::default()
580            });
581        }
582
583        mode.input.background_color = native(semantic.input_background);
584        mode.input.caret_color = native(semantic.input_text);
585        mode.input.selection_background = native(semantic.selection_background);
586        mode.input.selection_text_color = native(semantic.selection_text);
587        mode.input.disabled_text_color = native(semantic.disabled_text);
588        mode.input.focus_border_color = native(semantic.accent);
589        if let Some(control) = self.controls.get("line_edit") {
590            mode.input.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
591            mode.input.font = semantic
592                .input_text
593                .map(|color| native_font(&control.font, color));
594        }
595
596        mode.checkbox.checked_background = native(semantic.accent);
597        mode.checkbox.indicator_color = native(semantic.accent_text);
598        mode.checkbox.disabled_text_color = native(semantic.disabled_text);
599        mode.checkbox.indicator_width = self
600            .metrics
601            .get("indicator_width")
602            .copied()
603            .map(|value| value as f32);
604
605        mode.menu.background_color = native(semantic.surface_background);
606        mode.menu.separator_color = native(semantic.border);
607        mode.menu.hover_background = native(semantic.selection_background);
608        mode.menu.hover_text_color = native(semantic.selection_text);
609        mode.menu.disabled_text_color = native(semantic.disabled_text);
610        mode.tooltip.background_color = native(semantic.tooltip_background);
611        if let Some(text) = semantic.tooltip_text {
612            mode.tooltip.font = Some(native_font(&self.settings.font, text));
613        }
614
615        mode.scrollbar.track_color = native(semantic.window_background);
616        mode.scrollbar.thumb_color = native(semantic.border.or(semantic.disabled_text));
617        mode.scrollbar.thumb_hover_color = native(semantic.accent);
618        mode.scrollbar.groove_width = self
619            .metrics
620            .get("scrollbar_extent")
621            .copied()
622            .map(|value| value as f32);
623        mode.scrollbar.min_thumb_length = self
624            .metrics
625            .get("scrollbar_slider_min")
626            .copied()
627            .map(|value| value as f32);
628        mode.scrollbar.overlay_mode = Some(false);
629
630        mode.slider.fill_color = native(semantic.accent);
631        mode.slider.track_color = native(semantic.border);
632        mode.slider.thumb_color = native(semantic.surface_background);
633        mode.slider.track_height = self
634            .metrics
635            .get("slider_control_thickness")
636            .copied()
637            .map(|value| value as f32);
638        mode.slider.thumb_diameter = self
639            .metrics
640            .get("slider_length")
641            .copied()
642            .map(|value| value as f32);
643
644        mode.progress_bar.fill_color = native(semantic.accent);
645        mode.progress_bar.track_color = native(semantic.window_background);
646        if let Some(control) = self.controls.get("progress_bar") {
647            mode.progress_bar.track_height = Some(control.size_hint.height.max(0) as f32);
648            mode.progress_bar.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
649        }
650        mode.tab.background_color = native(semantic.window_background);
651        mode.tab.active_background = native(semantic.surface_background);
652        mode.tab.active_text_color = native(semantic.window_text);
653        mode.tab.bar_background = native(semantic.window_background);
654        if let Some(control) = self.controls.get("tab_bar") {
655            mode.tab.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
656            mode.tab.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
657        }
658        mode.separator.line_color = native(semantic.border);
659        mode.separator.line_width = mode.defaults.border.line_width;
660        mode.combo_box.background_color = native(semantic.surface_background);
661        mode.combo_box.disabled_text_color = native(semantic.disabled_text);
662        if let Some(control) = self.controls.get("combo_box") {
663            mode.combo_box.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
664            mode.combo_box.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
665        }
666        mode
667    }
668
669    /// Resolve this Qt snapshot into the exact input accepted by
670    /// `native_theme_gpui::to_theme`.
671    pub fn resolve_native_theme(&self) -> Result<NativeThemeBridge, NativeThemeBridgeError> {
672        use native_theme::resolve::ResolutionContext;
673        use native_theme::theme::{ColorMode, Theme};
674
675        self.validate()?;
676        let background = self
677            .semantic_palette
678            .window_background
679            .ok_or(NativeThemeBridgeError::MissingColor("window_background"))?;
680        self.semantic_palette
681            .window_text
682            .ok_or(NativeThemeBridgeError::MissingColor("window_text"))?;
683        let mode = if relative_luminance(background) < 0.5 {
684            ColorMode::Dark
685        } else {
686            ColorMode::Light
687        };
688        let mut variant = Theme::preset("kde-breeze")?.into_variant(mode)?;
689        variant.merge(&self.to_native_theme_mode());
690        let resolved = variant.into_resolved(&ResolutionContext::from_system())?;
691        Ok(NativeThemeBridge {
692            name: format!("Qt {}", self.identity.style_name),
693            mode,
694            resolved,
695            reduce_transparency: false,
696            reduce_motion: false,
697            high_contrast: false,
698        })
699    }
700
701    /// Resolve and convert this snapshot into a `gpui-component` theme.
702    #[cfg(feature = "gpui")]
703    pub fn to_gpui_theme(&self) -> Result<gpui_component::theme::Theme, NativeThemeBridgeError> {
704        Ok(self.resolve_native_theme()?.to_gpui_theme())
705    }
706}
707
708fn palette_color(palette: &PaletteSnapshot, group: &str, role: &str) -> Option<Rgba> {
709    palette.get(group)?.get(role).map(|brush| brush.color)
710}
711
712fn semantic_palette(palette: &PaletteSnapshot) -> SemanticPalette {
713    let active = |role| palette_color(palette, "active", role);
714    SemanticPalette {
715        window_background: active("window"),
716        window_text: active("window_text"),
717        surface_background: active("button"),
718        surface_text: active("button_text"),
719        input_background: active("base"),
720        input_text: active("text"),
721        selection_background: active("highlight"),
722        selection_text: active("highlighted_text"),
723        accent: active("accent").or_else(|| active("highlight")),
724        accent_text: active("highlighted_text"),
725        border: active("mid"),
726        disabled_text: palette_color(palette, "disabled", "text"),
727        tooltip_background: active("tooltip_base"),
728        tooltip_text: active("tooltip_text"),
729        link: active("link"),
730        error: None,
731        warning: None,
732        success: None,
733    }
734}
735
736/// Failure to initialize Qt or deserialize its probe output.
737#[derive(Debug, Error)]
738pub enum ProbeError {
739    /// The native Qt probe failed.
740    #[error("Qt theme probe failed: {0}")]
741    Native(String),
742    /// The probe returned a null result.
743    #[error("Qt theme probe returned no data")]
744    Empty,
745    /// The native probe returned malformed JSON.
746    #[error("Qt theme probe returned invalid JSON: {0}")]
747    InvalidJson(#[from] serde_json::Error),
748    /// The native and Rust snapshot schema versions differ.
749    #[error("unsupported snapshot schema version {actual}; expected {expected}")]
750    SchemaVersion {
751        /// Version received from the native probe.
752        actual: u32,
753        /// Version supported by this Rust crate.
754        expected: u32,
755    },
756    /// Qt produced a snapshot that violates the public contract.
757    #[error(transparent)]
758    InvalidSnapshot(#[from] SnapshotValidationError),
759}
760
761/// Resolve the current Qt 6 widget theme.
762///
763/// This function constructs a `QApplication` and must run on the process's main
764/// thread before another GUI toolkit claims it. Applications that already run
765/// GPUI or another event loop should execute the `native-theme-qt` CLI in a
766/// subprocess instead.
767pub fn probe() -> Result<ThemeSnapshot, ProbeError> {
768    let json = ffi::probe_theme().map_err(|error| ProbeError::Native(error.what().to_owned()))?;
769    let json = json.as_ref().ok_or(ProbeError::Empty)?.to_string_lossy();
770    let mut snapshot: ThemeSnapshot = serde_json::from_str(&json)?;
771    if snapshot.schema_version != SCHEMA_VERSION {
772        return Err(ProbeError::SchemaVersion {
773            actual: snapshot.schema_version,
774            expected: SCHEMA_VERSION,
775        });
776    }
777    snapshot.semantic_palette = semantic_palette(&snapshot.palette);
778    snapshot.validate()?;
779    Ok(snapshot)
780}
781
782#[cfg(test)]
783mod tests {
784    use super::*;
785
786    #[test]
787    fn contract_fixture_deserializes() {
788        let json = r#"{
789          "schema_version": 1,
790          "backend": "qt6",
791          "identity": {
792            "style_name": "fusion",
793            "toolkit_version": "6.2.0",
794            "platform_backend": "offscreen",
795            "platform_theme": null,
796            "style_override": null
797          },
798          "settings": {
799            "font": {"family":"Sans","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
800            "fixed_font": {"family":"Monospace","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
801            "icon_theme_name": "",
802            "cursor_flash_time_ms": 1000,
803            "double_click_interval_ms": 400,
804            "wheel_scroll_lines": 3,
805            "application_stylesheet": ""
806          },
807          "palette": {},
808          "semantic_palette": {},
809          "controls": {},
810          "metrics": {},
811          "hints": {},
812          "diagnostics": []
813        }"#;
814        let snapshot: ThemeSnapshot = serde_json::from_str(json).unwrap();
815        assert_eq!(snapshot.schema_version, SCHEMA_VERSION);
816        assert_eq!(snapshot.identity.style_name, "fusion");
817    }
818
819    #[test]
820    fn semantic_palette_maps_qt_roles() {
821        let red = Rgba {
822            red: 1.0,
823            green: 0.0,
824            blue: 0.0,
825            alpha: 1.0,
826        };
827        let mut roles = BTreeMap::new();
828        roles.insert(
829            "window".to_owned(),
830            PaletteBrush {
831                color: red,
832                brush_style: 1,
833            },
834        );
835        let palette = BTreeMap::from([("active".to_owned(), roles)]);
836        assert_eq!(semantic_palette(&palette).window_background, Some(red));
837    }
838
839    #[test]
840    fn semantic_palette_contract_has_stable_role_names() {
841        let value = serde_json::to_value(SemanticPalette::default()).unwrap();
842        let mut actual: Vec<_> = value
843            .as_object()
844            .unwrap()
845            .keys()
846            .map(String::as_str)
847            .collect();
848        let mut expected = SEMANTIC_COLOR_ROLES.to_vec();
849        actual.sort_unstable();
850        expected.sort_unstable();
851        assert_eq!(actual, expected);
852    }
853
854    #[test]
855    fn invalid_color_channels_are_rejected() {
856        let error = validate_rgba(
857            "test",
858            Rgba {
859                red: 0.0,
860                green: 1.01,
861                blue: 0.0,
862                alpha: 1.0,
863            },
864        )
865        .unwrap_err();
866        assert!(error.reason().contains("test.green"));
867    }
868
869    #[test]
870    fn incomplete_snapshot_is_rejected() {
871        let json = r#"{
872          "schema_version": 1,
873          "backend": "qt6",
874          "identity": {
875            "style_name": "fusion", "toolkit_version": "6.2.0",
876            "platform_backend": "offscreen", "platform_theme": null,
877            "style_override": null
878          },
879          "settings": {
880            "font": {"family":"Sans","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
881            "fixed_font": {"family":"Mono","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
882            "icon_theme_name":"", "cursor_flash_time_ms":1000,
883            "double_click_interval_ms":400, "wheel_scroll_lines":3,
884            "application_stylesheet":""
885          },
886          "palette": {}, "semantic_palette": {}, "controls": {},
887          "metrics": {}, "hints": {}, "diagnostics": []
888        }"#;
889        let snapshot: ThemeSnapshot = serde_json::from_str(json).unwrap();
890        assert!(
891            snapshot
892                .validate()
893                .unwrap_err()
894                .reason()
895                .contains("missing color group")
896        );
897    }
898}