native-theme-qt 0.1.0

Resolve the active Qt 6 theme into a serializable toolkit-neutral snapshot
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
//! Resolve the effective Qt 6 widget theme through Qt itself.
//!
//! The C++ probe lets Qt load the configured QPA platform theme and `QStyle`
//! plugins, then returns the effective palette, fonts, metrics, and style hints
//! as JSON. This handles configurations that cannot be reproduced by parsing a
//! single `qt6ct.conf` file.

use std::collections::{BTreeMap, HashSet};

use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Version of the JSON snapshot contract.
pub const SCHEMA_VERSION: u32 = 1;

/// Stable toolkit-neutral role names shared with `native-theme-gtk`.
pub const SEMANTIC_COLOR_ROLES: [&str; 18] = [
    "window_background",
    "window_text",
    "surface_background",
    "surface_text",
    "input_background",
    "input_text",
    "selection_background",
    "selection_text",
    "accent",
    "accent_text",
    "border",
    "disabled_text",
    "tooltip_background",
    "tooltip_text",
    "link",
    "error",
    "warning",
    "success",
];

#[cxx::bridge(namespace = "native_theme_qt")]
mod ffi {
    unsafe extern "C++" {
        include!("probe.h");

        fn probe_theme() -> Result<UniquePtr<CxxString>>;
    }
}

/// An RGBA color in the sRGB color space.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub struct Rgba {
    /// Red channel in the inclusive range 0..=1.
    pub red: f32,
    /// Green channel in the inclusive range 0..=1.
    pub green: f32,
    /// Blue channel in the inclusive range 0..=1.
    pub blue: f32,
    /// Alpha channel in the inclusive range 0..=1.
    pub alpha: f32,
}

/// Identity of the active Qt theme and platform backend.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ThemeIdentity {
    /// Name returned by the active `QStyle`.
    pub style_name: String,
    /// Qt runtime version.
    pub toolkit_version: String,
    /// Active QPA platform plugin, such as `wayland` or `xcb`.
    pub platform_backend: String,
    /// `QT_QPA_PLATFORMTHEME`, when set in the environment.
    pub platform_theme: Option<String>,
    /// `QT_STYLE_OVERRIDE`, when set in the environment.
    pub style_override: Option<String>,
}

/// A resolved Qt font.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct FontSnapshot {
    /// Resolved font family.
    pub family: String,
    /// Point size, or a negative value when the font uses pixel sizing.
    pub point_size: f32,
    /// Pixel size, or a negative value when the font uses point sizing.
    pub pixel_size: i32,
    /// Qt font weight.
    pub weight: i32,
    /// Whether the font is italic.
    pub italic: bool,
    /// Font stretch percentage.
    pub stretch: i32,
}

/// Application-wide values resolved by Qt.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct QtSettingsSnapshot {
    /// Default application font.
    pub font: FontSnapshot,
    /// Platform fixed-width font.
    pub fixed_font: FontSnapshot,
    /// Freedesktop icon theme selected by Qt.
    pub icon_theme_name: String,
    /// Cursor blink interval in milliseconds.
    pub cursor_flash_time_ms: i32,
    /// Double-click interval in milliseconds.
    pub double_click_interval_ms: i32,
    /// Number of lines scrolled for each wheel step.
    pub wheel_scroll_lines: i32,
    /// Application-wide QSS after the platform theme has initialized.
    pub application_stylesheet: String,
}

/// One brush from a Qt palette.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct PaletteBrush {
    /// Brush color converted to sRGB RGBA.
    pub color: Rgba,
    /// Qt brush style numeric value. Non-solid brushes may require rendering.
    pub brush_style: i32,
}

/// Toolkit-neutral colors projected from Qt palette roles.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct SemanticPalette {
    /// Main application window background.
    pub window_background: Option<Rgba>,
    /// Text drawn directly on the window background.
    pub window_text: Option<Rgba>,
    /// Raised surface or button background.
    pub surface_background: Option<Rgba>,
    /// Text drawn on raised surfaces.
    pub surface_text: Option<Rgba>,
    /// Editable/view content background.
    pub input_background: Option<Rgba>,
    /// Editable/view content text.
    pub input_text: Option<Rgba>,
    /// Selected item background.
    pub selection_background: Option<Rgba>,
    /// Text drawn on a selected item.
    pub selection_text: Option<Rgba>,
    /// Primary accent background.
    pub accent: Option<Rgba>,
    /// Text drawn over the primary accent.
    pub accent_text: Option<Rgba>,
    /// General separator or frame color.
    pub border: Option<Rgba>,
    /// Text used by disabled controls.
    pub disabled_text: Option<Rgba>,
    /// Tooltip background.
    pub tooltip_background: Option<Rgba>,
    /// Tooltip text.
    pub tooltip_text: Option<Rgba>,
    /// Hyperlink foreground.
    pub link: Option<Rgba>,
    /// Destructive or error foreground, when published by the backend.
    pub error: Option<Rgba>,
    /// Warning foreground, when published by the backend.
    pub warning: Option<Rgba>,
    /// Success foreground, when published by the backend.
    pub success: Option<Rgba>,
}

/// Qt palette groups keyed by `active`, `inactive`, and `disabled`, then role.
pub type PaletteSnapshot = BTreeMap<String, BTreeMap<String, PaletteBrush>>;

/// A two-dimensional size in toolkit logical pixels.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub struct SizeSnapshot {
    /// Horizontal extent, or `-1` if Qt does not provide a hint.
    pub width: i32,
    /// Vertical extent, or `-1` if Qt does not provide a hint.
    pub height: i32,
}

/// Resolved defaults for one representative Qt widget.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ControlSnapshot {
    /// Preferred size for representative content.
    pub size_hint: SizeSnapshot,
    /// Minimum preferred size for representative content.
    pub minimum_size_hint: SizeSnapshot,
    /// Font inherited by this widget after polishing.
    pub font: FontSnapshot,
    /// Widget-specific palette after the active style has polished it.
    pub palette: PaletteSnapshot,
}

/// A complete Qt theme probe result.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ThemeSnapshot {
    /// Snapshot schema version.
    pub schema_version: u32,
    /// Backend discriminator. Always `qt6` for this crate.
    pub backend: String,
    /// Theme identity and toolkit runtime details.
    pub identity: ThemeIdentity,
    /// Application-wide resolved settings.
    pub settings: QtSettingsSnapshot,
    /// Effective application palette.
    pub palette: PaletteSnapshot,
    /// Toolkit-neutral projection of the palette.
    #[serde(default)]
    pub semantic_palette: SemanticPalette,
    /// Polished representative controls keyed by stable control name.
    #[serde(default)]
    pub controls: BTreeMap<String, ControlSnapshot>,
    /// `QStyle::pixelMetric` values in logical pixels.
    pub metrics: BTreeMap<String, i32>,
    /// Selected integer and boolean `QStyle::styleHint` values.
    pub hints: BTreeMap<String, i32>,
    /// Non-fatal limitations encountered by the probe.
    pub diagnostics: Vec<String>,
}

/// Explanation of why a theme snapshot is not safe to consume.
#[derive(Debug, Error, PartialEq, Eq)]
#[error("invalid Qt theme snapshot: {reason}")]
pub struct SnapshotValidationError {
    reason: String,
}

impl SnapshotValidationError {
    /// Human-readable validation failure.
    pub fn reason(&self) -> &str {
        &self.reason
    }
}

fn validation_error(reason: impl Into<String>) -> SnapshotValidationError {
    SnapshotValidationError {
        reason: reason.into(),
    }
}

fn validate_rgba(path: &str, color: Rgba) -> Result<(), SnapshotValidationError> {
    for (channel, value) in [
        ("red", color.red),
        ("green", color.green),
        ("blue", color.blue),
        ("alpha", color.alpha),
    ] {
        if !value.is_finite() || !(0.0..=1.0).contains(&value) {
            return Err(validation_error(format!(
                "{path}.{channel} must be finite and in 0..=1, got {value}"
            )));
        }
    }
    Ok(())
}

fn validate_palette(path: &str, palette: &PaletteSnapshot) -> Result<(), SnapshotValidationError> {
    for required in ["active", "inactive", "disabled"] {
        if !palette.contains_key(required) {
            return Err(validation_error(format!(
                "{path} is missing color group {required}"
            )));
        }
    }
    for (group, roles) in palette {
        for (role, brush) in roles {
            validate_rgba(&format!("{path}.{group}.{role}"), brush.color)?;
            if brush.brush_style < 0 {
                return Err(validation_error(format!(
                    "{path}.{group}.{role}.brush_style must not be negative"
                )));
            }
        }
    }
    Ok(())
}

fn validate_font(path: &str, font: &FontSnapshot) -> Result<(), SnapshotValidationError> {
    if font.family.trim().is_empty() {
        return Err(validation_error(format!("{path}.family must not be empty")));
    }
    if !font.point_size.is_finite() {
        return Err(validation_error(format!(
            "{path}.point_size must be finite"
        )));
    }
    if font.stretch < 0 {
        return Err(validation_error(format!(
            "{path}.stretch must not be negative"
        )));
    }
    Ok(())
}

impl ThemeSnapshot {
    /// Check schema, identity, required palette roles, controls, and colors.
    pub fn validate(&self) -> Result<(), SnapshotValidationError> {
        if self.schema_version != SCHEMA_VERSION {
            return Err(validation_error(format!(
                "unsupported schema version {}; expected {SCHEMA_VERSION}",
                self.schema_version
            )));
        }
        if self.backend != "qt6" {
            return Err(validation_error(format!(
                "backend must be qt6, got {:?}",
                self.backend
            )));
        }
        if self.identity.style_name.trim().is_empty()
            || self.identity.toolkit_version.trim().is_empty()
            || self.identity.platform_backend.trim().is_empty()
        {
            return Err(validation_error(
                "style name, toolkit version, and platform backend must not be empty",
            ));
        }
        validate_font("settings.font", &self.settings.font)?;
        validate_font("settings.fixed_font", &self.settings.fixed_font)?;
        validate_palette("palette", &self.palette)?;
        for role in [
            "window",
            "window_text",
            "button",
            "button_text",
            "base",
            "text",
            "highlight",
            "highlighted_text",
        ] {
            if !self.palette["active"].contains_key(role) {
                return Err(validation_error(format!(
                    "palette.active is missing role {role}"
                )));
            }
        }

        for (name, color) in [
            ("window_background", self.semantic_palette.window_background),
            ("window_text", self.semantic_palette.window_text),
            (
                "surface_background",
                self.semantic_palette.surface_background,
            ),
            ("surface_text", self.semantic_palette.surface_text),
            ("input_background", self.semantic_palette.input_background),
            ("input_text", self.semantic_palette.input_text),
            (
                "selection_background",
                self.semantic_palette.selection_background,
            ),
            ("selection_text", self.semantic_palette.selection_text),
            ("accent", self.semantic_palette.accent),
            ("accent_text", self.semantic_palette.accent_text),
            ("border", self.semantic_palette.border),
            ("disabled_text", self.semantic_palette.disabled_text),
            (
                "tooltip_background",
                self.semantic_palette.tooltip_background,
            ),
            ("tooltip_text", self.semantic_palette.tooltip_text),
            ("link", self.semantic_palette.link),
            ("error", self.semantic_palette.error),
            ("warning", self.semantic_palette.warning),
            ("success", self.semantic_palette.success),
        ] {
            if let Some(color) = color {
                validate_rgba(&format!("semantic_palette.{name}"), color)?;
            }
        }

        let required_controls: HashSet<_> = [
            "button",
            "line_edit",
            "check_box",
            "radio_button",
            "combo_box",
            "spin_box",
            "slider",
            "progress_bar",
            "scroll_bar",
            "tab_bar",
            "tool_button",
        ]
        .into_iter()
        .collect();
        for required in required_controls {
            if !self.controls.contains_key(required) {
                return Err(validation_error(format!(
                    "missing representative control {required}"
                )));
            }
        }
        for (name, control) in &self.controls {
            for (kind, size) in [
                ("size_hint", control.size_hint),
                ("minimum_size_hint", control.minimum_size_hint),
            ] {
                if size.width < -1 || size.height < -1 {
                    return Err(validation_error(format!(
                        "controls.{name}.{kind} contains a dimension below -1"
                    )));
                }
            }
            validate_font(&format!("controls.{name}.font"), &control.font)?;
            validate_palette(&format!("controls.{name}.palette"), &control.palette)?;
        }
        if self.metrics.is_empty() || self.hints.is_empty() {
            return Err(validation_error(
                "style metrics and hints must not be empty",
            ));
        }
        Ok(())
    }
}

/// A Qt snapshot resolved through `native-theme`, ready for framework connectors.
#[derive(Clone, Debug)]
pub struct NativeThemeBridge {
    /// Display name for the detected theme.
    pub name: String,
    /// Light or dark mode inferred from the effective window background.
    pub mode: native_theme::theme::ColorMode,
    /// Fully populated theme accepted by `native_theme_gpui::to_theme`.
    pub resolved: native_theme::theme::ResolvedTheme,
    /// Whether transparent effects should be reduced.
    pub reduce_transparency: bool,
    /// Whether the user requested reduced motion.
    pub reduce_motion: bool,
    /// Whether the user requested increased contrast.
    pub high_contrast: bool,
}

impl NativeThemeBridge {
    /// Convert the resolved bridge into a `gpui-component` theme.
    #[cfg(feature = "gpui")]
    #[must_use = "this returns the GPUI theme; it does not install it globally"]
    pub fn to_gpui_theme(&self) -> gpui_component::theme::Theme {
        native_theme_gpui::to_theme(
            &self.resolved,
            &self.name,
            self.mode.is_dark(),
            self.reduce_transparency,
        )
    }
}

/// Failure to translate a Qt snapshot into the `native-theme` model.
#[derive(Debug, Error)]
pub enum NativeThemeBridgeError {
    /// The source snapshot is malformed or incomplete.
    #[error(transparent)]
    InvalidSnapshot(#[from] SnapshotValidationError),
    /// A semantic role required for a faithful base theme was unavailable.
    #[error("Qt snapshot is missing required semantic color {0}")]
    MissingColor(&'static str),
    /// The `native-theme` inheritance or validation pipeline failed.
    #[error("native-theme resolution failed: {0}")]
    Resolution(#[from] native_theme::error::Error),
}

fn to_native_color(color: Rgba) -> native_theme::color::Rgba {
    native_theme::color::Rgba::from_f32(color.red, color.green, color.blue, color.alpha)
}

fn native_font(font: &FontSnapshot, color: Rgba) -> native_theme::theme::FontSpec {
    use native_theme::theme::{FontSize, FontSpec, FontStyle, intern_font_family};

    FontSpec {
        family: Some(intern_font_family(&font.family)),
        size: if font.point_size > 0.0 {
            Some(FontSize::Pt(font.point_size))
        } else if font.pixel_size > 0 {
            Some(FontSize::Px(font.pixel_size as f32))
        } else {
            None
        },
        weight: u16::try_from(font.weight).ok(),
        style: Some(if font.italic {
            FontStyle::Italic
        } else {
            FontStyle::Normal
        }),
        color: Some(to_native_color(color)),
    }
}

fn relative_luminance(color: Rgba) -> f32 {
    fn linear(channel: f32) -> f32 {
        if channel <= 0.04045 {
            channel / 12.92
        } else {
            ((channel + 0.055) / 1.055).powf(2.4)
        }
    }
    0.2126 * linear(color.red) + 0.7152 * linear(color.green) + 0.0722 * linear(color.blue)
}

impl ThemeSnapshot {
    /// Translate resolved Qt values into a sparse `native-theme` mode.
    ///
    /// The result can be merged over any `native-theme` preset. Prefer
    /// [`resolve_native_theme`](Self::resolve_native_theme) for the ready-to-use
    /// value expected by `native_theme_gpui::to_theme`.
    pub fn to_native_theme_mode(&self) -> native_theme::theme::ThemeMode {
        use native_theme::theme::{ThemeMode, WidgetBorderSpec};

        let mut mode = ThemeMode::default();
        let semantic = &self.semantic_palette;
        let native = |color: Option<Rgba>| color.map(to_native_color);

        mode.defaults.background_color = native(semantic.window_background);
        mode.defaults.text_color = native(semantic.window_text);
        mode.defaults.accent_color = native(semantic.accent);
        mode.defaults.accent_text_color = native(semantic.accent_text);
        mode.defaults.surface_color = native(semantic.surface_background);
        mode.defaults.muted_color = native(semantic.disabled_text.or(semantic.window_text));
        mode.defaults.link_color = native(semantic.link);
        mode.defaults.selection_background = native(semantic.selection_background);
        mode.defaults.selection_text_color = native(semantic.selection_text);
        mode.defaults.selection_inactive_background =
            palette_color(&self.palette, "inactive", "highlight").map(to_native_color);
        mode.defaults.text_selection_background = native(semantic.selection_background);
        mode.defaults.text_selection_color = native(semantic.selection_text);
        mode.defaults.disabled_text_color = native(semantic.disabled_text);
        mode.defaults.danger_color = native(semantic.error);
        mode.defaults.warning_color = native(semantic.warning);
        mode.defaults.success_color = native(semantic.success);
        mode.defaults.info_color = native(semantic.accent);
        mode.defaults.focus_ring_color = native(semantic.accent);
        mode.defaults.border.color = native(semantic.border);
        mode.defaults.border.line_width = self
            .metrics
            .get("default_frame_width")
            .copied()
            .map(|value| value as f32);
        mode.defaults.icon_sizes.toolbar = self
            .metrics
            .get("toolbar_icon_size")
            .copied()
            .map(|value| value as f32);
        mode.defaults.icon_sizes.small = self
            .metrics
            .get("small_icon_size")
            .copied()
            .map(|value| value as f32);
        mode.defaults.icon_sizes.large = self
            .metrics
            .get("large_icon_size")
            .copied()
            .map(|value| value as f32);
        if let Some(text) = semantic.window_text {
            mode.defaults.font = native_font(&self.settings.font, text);
            mode.defaults.mono_font = native_font(&self.settings.fixed_font, text);
        }
        mode.defaults.icon_theme = (!self.settings.icon_theme_name.is_empty())
            .then(|| self.settings.icon_theme_name.clone().into());

        mode.window.background_color = native(semantic.window_background);
        mode.window.title_bar_background = native(semantic.surface_background);
        mode.window.inactive_title_bar_background =
            palette_color(&self.palette, "inactive", "window").map(to_native_color);
        mode.window.inactive_title_bar_text_color =
            palette_color(&self.palette, "inactive", "window_text").map(to_native_color);

        mode.button.background_color = native(semantic.surface_background);
        mode.button.primary_background = native(semantic.accent);
        mode.button.primary_text_color = native(semantic.accent_text);
        mode.button.disabled_text_color = native(semantic.disabled_text);
        if let Some(control) = self.controls.get("button") {
            mode.button.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
            mode.button.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
            mode.button.font = semantic
                .surface_text
                .map(|color| native_font(&control.font, color));
            mode.button.border = Some(WidgetBorderSpec {
                color: native(semantic.border),
                line_width: mode.defaults.border.line_width,
                padding_horizontal: self
                    .metrics
                    .get("button_margin")
                    .map(|value| *value as f32 / 2.0),
                padding_vertical: self
                    .metrics
                    .get("button_margin")
                    .map(|value| *value as f32 / 2.0),
                ..Default::default()
            });
        }

        mode.input.background_color = native(semantic.input_background);
        mode.input.caret_color = native(semantic.input_text);
        mode.input.selection_background = native(semantic.selection_background);
        mode.input.selection_text_color = native(semantic.selection_text);
        mode.input.disabled_text_color = native(semantic.disabled_text);
        mode.input.focus_border_color = native(semantic.accent);
        if let Some(control) = self.controls.get("line_edit") {
            mode.input.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
            mode.input.font = semantic
                .input_text
                .map(|color| native_font(&control.font, color));
        }

        mode.checkbox.checked_background = native(semantic.accent);
        mode.checkbox.indicator_color = native(semantic.accent_text);
        mode.checkbox.disabled_text_color = native(semantic.disabled_text);
        mode.checkbox.indicator_width = self
            .metrics
            .get("indicator_width")
            .copied()
            .map(|value| value as f32);

        mode.menu.background_color = native(semantic.surface_background);
        mode.menu.separator_color = native(semantic.border);
        mode.menu.hover_background = native(semantic.selection_background);
        mode.menu.hover_text_color = native(semantic.selection_text);
        mode.menu.disabled_text_color = native(semantic.disabled_text);
        mode.tooltip.background_color = native(semantic.tooltip_background);
        if let Some(text) = semantic.tooltip_text {
            mode.tooltip.font = Some(native_font(&self.settings.font, text));
        }

        mode.scrollbar.track_color = native(semantic.window_background);
        mode.scrollbar.thumb_color = native(semantic.border.or(semantic.disabled_text));
        mode.scrollbar.thumb_hover_color = native(semantic.accent);
        mode.scrollbar.groove_width = self
            .metrics
            .get("scrollbar_extent")
            .copied()
            .map(|value| value as f32);
        mode.scrollbar.min_thumb_length = self
            .metrics
            .get("scrollbar_slider_min")
            .copied()
            .map(|value| value as f32);
        mode.scrollbar.overlay_mode = Some(false);

        mode.slider.fill_color = native(semantic.accent);
        mode.slider.track_color = native(semantic.border);
        mode.slider.thumb_color = native(semantic.surface_background);
        mode.slider.track_height = self
            .metrics
            .get("slider_control_thickness")
            .copied()
            .map(|value| value as f32);
        mode.slider.thumb_diameter = self
            .metrics
            .get("slider_length")
            .copied()
            .map(|value| value as f32);

        mode.progress_bar.fill_color = native(semantic.accent);
        mode.progress_bar.track_color = native(semantic.window_background);
        if let Some(control) = self.controls.get("progress_bar") {
            mode.progress_bar.track_height = Some(control.size_hint.height.max(0) as f32);
            mode.progress_bar.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
        }
        mode.tab.background_color = native(semantic.window_background);
        mode.tab.active_background = native(semantic.surface_background);
        mode.tab.active_text_color = native(semantic.window_text);
        mode.tab.bar_background = native(semantic.window_background);
        if let Some(control) = self.controls.get("tab_bar") {
            mode.tab.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
            mode.tab.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
        }
        mode.separator.line_color = native(semantic.border);
        mode.separator.line_width = mode.defaults.border.line_width;
        mode.combo_box.background_color = native(semantic.surface_background);
        mode.combo_box.disabled_text_color = native(semantic.disabled_text);
        if let Some(control) = self.controls.get("combo_box") {
            mode.combo_box.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
            mode.combo_box.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
        }
        mode
    }

    /// Resolve this Qt snapshot into the exact input accepted by
    /// `native_theme_gpui::to_theme`.
    pub fn resolve_native_theme(&self) -> Result<NativeThemeBridge, NativeThemeBridgeError> {
        use native_theme::resolve::ResolutionContext;
        use native_theme::theme::{ColorMode, Theme};

        self.validate()?;
        let background = self
            .semantic_palette
            .window_background
            .ok_or(NativeThemeBridgeError::MissingColor("window_background"))?;
        self.semantic_palette
            .window_text
            .ok_or(NativeThemeBridgeError::MissingColor("window_text"))?;
        let mode = if relative_luminance(background) < 0.5 {
            ColorMode::Dark
        } else {
            ColorMode::Light
        };
        let mut variant = Theme::preset("kde-breeze")?.into_variant(mode)?;
        variant.merge(&self.to_native_theme_mode());
        let resolved = variant.into_resolved(&ResolutionContext::from_system())?;
        Ok(NativeThemeBridge {
            name: format!("Qt {}", self.identity.style_name),
            mode,
            resolved,
            reduce_transparency: false,
            reduce_motion: false,
            high_contrast: false,
        })
    }

    /// Resolve and convert this snapshot into a `gpui-component` theme.
    #[cfg(feature = "gpui")]
    pub fn to_gpui_theme(&self) -> Result<gpui_component::theme::Theme, NativeThemeBridgeError> {
        Ok(self.resolve_native_theme()?.to_gpui_theme())
    }
}

fn palette_color(palette: &PaletteSnapshot, group: &str, role: &str) -> Option<Rgba> {
    palette.get(group)?.get(role).map(|brush| brush.color)
}

fn semantic_palette(palette: &PaletteSnapshot) -> SemanticPalette {
    let active = |role| palette_color(palette, "active", role);
    SemanticPalette {
        window_background: active("window"),
        window_text: active("window_text"),
        surface_background: active("button"),
        surface_text: active("button_text"),
        input_background: active("base"),
        input_text: active("text"),
        selection_background: active("highlight"),
        selection_text: active("highlighted_text"),
        accent: active("accent").or_else(|| active("highlight")),
        accent_text: active("highlighted_text"),
        border: active("mid"),
        disabled_text: palette_color(palette, "disabled", "text"),
        tooltip_background: active("tooltip_base"),
        tooltip_text: active("tooltip_text"),
        link: active("link"),
        error: None,
        warning: None,
        success: None,
    }
}

/// Failure to initialize Qt or deserialize its probe output.
#[derive(Debug, Error)]
pub enum ProbeError {
    /// The native Qt probe failed.
    #[error("Qt theme probe failed: {0}")]
    Native(String),
    /// The probe returned a null result.
    #[error("Qt theme probe returned no data")]
    Empty,
    /// The native probe returned malformed JSON.
    #[error("Qt theme probe returned invalid JSON: {0}")]
    InvalidJson(#[from] serde_json::Error),
    /// The native and Rust snapshot schema versions differ.
    #[error("unsupported snapshot schema version {actual}; expected {expected}")]
    SchemaVersion {
        /// Version received from the native probe.
        actual: u32,
        /// Version supported by this Rust crate.
        expected: u32,
    },
    /// Qt produced a snapshot that violates the public contract.
    #[error(transparent)]
    InvalidSnapshot(#[from] SnapshotValidationError),
}

/// Resolve the current Qt 6 widget theme.
///
/// This function constructs a `QApplication` and must run on the process's main
/// thread before another GUI toolkit claims it. Applications that already run
/// GPUI or another event loop should execute the `native-theme-qt` CLI in a
/// subprocess instead.
pub fn probe() -> Result<ThemeSnapshot, ProbeError> {
    let json = ffi::probe_theme().map_err(|error| ProbeError::Native(error.what().to_owned()))?;
    let json = json.as_ref().ok_or(ProbeError::Empty)?.to_string_lossy();
    let mut snapshot: ThemeSnapshot = serde_json::from_str(&json)?;
    if snapshot.schema_version != SCHEMA_VERSION {
        return Err(ProbeError::SchemaVersion {
            actual: snapshot.schema_version,
            expected: SCHEMA_VERSION,
        });
    }
    snapshot.semantic_palette = semantic_palette(&snapshot.palette);
    snapshot.validate()?;
    Ok(snapshot)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn contract_fixture_deserializes() {
        let json = r#"{
          "schema_version": 1,
          "backend": "qt6",
          "identity": {
            "style_name": "fusion",
            "toolkit_version": "6.2.0",
            "platform_backend": "offscreen",
            "platform_theme": null,
            "style_override": null
          },
          "settings": {
            "font": {"family":"Sans","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
            "fixed_font": {"family":"Monospace","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
            "icon_theme_name": "",
            "cursor_flash_time_ms": 1000,
            "double_click_interval_ms": 400,
            "wheel_scroll_lines": 3,
            "application_stylesheet": ""
          },
          "palette": {},
          "semantic_palette": {},
          "controls": {},
          "metrics": {},
          "hints": {},
          "diagnostics": []
        }"#;
        let snapshot: ThemeSnapshot = serde_json::from_str(json).unwrap();
        assert_eq!(snapshot.schema_version, SCHEMA_VERSION);
        assert_eq!(snapshot.identity.style_name, "fusion");
    }

    #[test]
    fn semantic_palette_maps_qt_roles() {
        let red = Rgba {
            red: 1.0,
            green: 0.0,
            blue: 0.0,
            alpha: 1.0,
        };
        let mut roles = BTreeMap::new();
        roles.insert(
            "window".to_owned(),
            PaletteBrush {
                color: red,
                brush_style: 1,
            },
        );
        let palette = BTreeMap::from([("active".to_owned(), roles)]);
        assert_eq!(semantic_palette(&palette).window_background, Some(red));
    }

    #[test]
    fn semantic_palette_contract_has_stable_role_names() {
        let value = serde_json::to_value(SemanticPalette::default()).unwrap();
        let mut actual: Vec<_> = value
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        let mut expected = SEMANTIC_COLOR_ROLES.to_vec();
        actual.sort_unstable();
        expected.sort_unstable();
        assert_eq!(actual, expected);
    }

    #[test]
    fn invalid_color_channels_are_rejected() {
        let error = validate_rgba(
            "test",
            Rgba {
                red: 0.0,
                green: 1.01,
                blue: 0.0,
                alpha: 1.0,
            },
        )
        .unwrap_err();
        assert!(error.reason().contains("test.green"));
    }

    #[test]
    fn incomplete_snapshot_is_rejected() {
        let json = r#"{
          "schema_version": 1,
          "backend": "qt6",
          "identity": {
            "style_name": "fusion", "toolkit_version": "6.2.0",
            "platform_backend": "offscreen", "platform_theme": null,
            "style_override": null
          },
          "settings": {
            "font": {"family":"Sans","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
            "fixed_font": {"family":"Mono","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
            "icon_theme_name":"", "cursor_flash_time_ms":1000,
            "double_click_interval_ms":400, "wheel_scroll_lines":3,
            "application_stylesheet":""
          },
          "palette": {}, "semantic_palette": {}, "controls": {},
          "metrics": {}, "hints": {}, "diagnostics": []
        }"#;
        let snapshot: ThemeSnapshot = serde_json::from_str(json).unwrap();
        assert!(
            snapshot
                .validate()
                .unwrap_err()
                .reason()
                .contains("missing color group")
        );
    }
}