native-theme-gtk 0.1.1

Resolve the active GTK 4 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
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
//! Resolve the effective GTK 4 theme through GTK itself.
//!
//! The crate intentionally does not parse `gtk.css`. GTK themes have selectors,
//! imports, variables, media queries, user overrides, and version-dependent
//! lookup rules. [`probe`] asks GTK for the effective settings and computed
//! values after those layers have been applied.

use std::collections::HashSet;

use gtk::gdk;
use gtk::glib;
use gtk::prelude::*;
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-qt`.
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",
];

/// 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,
}

impl From<gdk::RGBA> for Rgba {
    fn from(value: gdk::RGBA) -> Self {
        Self {
            red: value.red(),
            green: value.green(),
            blue: value.blue(),
            alpha: value.alpha(),
        }
    }
}

/// Identity of the active GTK theme and display backend.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ThemeIdentity {
    /// GTK theme name selected by the desktop.
    pub theme_name: String,
    /// GTK runtime version used to resolve the theme.
    pub toolkit_version: String,
    /// GDK display backend, when it can be determined.
    pub display_backend: Option<String>,
}

/// A dynamically discovered GTK enum preference.
///
/// This representation lets the crate expose preferences introduced by newer
/// GTK runtimes while retaining its GTK 4.10 build requirement.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct EnumSetting {
    /// Numeric GEnum value.
    pub value: i32,
    /// Stable GEnum constant name.
    pub name: String,
    /// Human-readable GEnum nickname.
    pub nick: String,
}

/// User preferences exposed by `GtkSettings`.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct GtkSettingsSnapshot {
    /// Default interface font description.
    pub font_name: Option<String>,
    /// Active icon theme name.
    pub icon_theme_name: Option<String>,
    /// Active cursor theme name.
    pub cursor_theme_name: Option<String>,
    /// Preferred cursor size in logical pixels.
    pub cursor_theme_size: Option<i32>,
    /// Whether GTK animations are enabled.
    pub enable_animations: Option<bool>,
    /// Whether overlay scrollbars are enabled.
    pub overlay_scrolling: Option<bool>,
    /// Whether the primary mouse button warps a slider to the click position.
    pub primary_button_warps_slider: Option<bool>,
    /// Double-click interval in milliseconds.
    pub double_click_time_ms: Option<i32>,
    /// Cursor blink interval in milliseconds.
    pub cursor_blink_time_ms: Option<i32>,
    /// Whether the application prefers the theme's dark variant.
    pub prefer_dark: Option<bool>,
    /// Desktop light/dark preference, available with GTK 4.20 and newer.
    #[serde(default)]
    pub interface_color_scheme: Option<EnumSetting>,
    /// Desktop contrast preference, available with GTK 4.20 and newer.
    #[serde(default)]
    pub interface_contrast: Option<EnumSetting>,
    /// Desktop reduced-motion preference, available with GTK 4.22 and newer.
    #[serde(default)]
    pub interface_reduced_motion: Option<EnumSetting>,
    /// Desktop accent color, available on GTK runtimes that publish it.
    #[serde(default)]
    pub interface_accent_color: Option<Rgba>,
}

/// A symbolic color resolved by GTK's CSS engine.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct NamedColor {
    /// GTK or libadwaita symbolic color name.
    pub name: String,
    /// Effective value after theme and user overrides.
    pub value: Rgba,
}

/// Toolkit-neutral colors projected from GTK symbolic color roles.
///
/// Fields remain optional because custom themes are not required to publish
/// every conventional GTK or libadwaita symbolic name.
#[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 card 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 or popover background.
    pub tooltip_background: Option<Rgba>,
    /// Tooltip or popover text.
    pub tooltip_text: Option<Rgba>,
    /// Hyperlink foreground.
    pub link: Option<Rgba>,
    /// Destructive or error foreground.
    pub error: Option<Rgba>,
    /// Warning foreground.
    pub warning: Option<Rgba>,
    /// Success foreground.
    pub success: Option<Rgba>,
}

/// Computed visual state for a representative GTK widget.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct WidgetState {
    /// Portable state name such as `hovered` or `disabled`.
    pub state: String,
    /// Effective foreground color reported by GTK.
    pub foreground: Rgba,
}

/// GTK's preferred dimensions for a representative widget.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub struct WidgetMetrics {
    /// Minimum width in logical pixels.
    pub minimum_width: i32,
    /// Natural width in logical pixels.
    pub natural_width: i32,
    /// Minimum height in logical pixels.
    pub minimum_height: i32,
    /// Natural height in logical pixels.
    pub natural_height: i32,
}

/// Effective information collected for one representative control.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct WidgetSnapshot {
    /// Stable generic control name.
    pub control: String,
    /// Root GTK CSS node name.
    pub css_name: String,
    /// Preferred widget dimensions.
    pub metrics: WidgetMetrics,
    /// Foreground color across GTK interaction states.
    pub states: Vec<WidgetState>,
}

/// A complete GTK theme probe result.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ThemeSnapshot {
    /// Snapshot schema version.
    pub schema_version: u32,
    /// Backend discriminator. Always `gtk4` for this crate.
    pub backend: String,
    /// Theme identity and toolkit runtime details.
    pub identity: ThemeIdentity,
    /// Desktop preferences exposed through GTK.
    pub settings: GtkSettingsSnapshot,
    /// Symbolic colors understood by the active theme.
    pub named_colors: Vec<NamedColor>,
    /// Toolkit-neutral projection of the symbolic colors.
    pub semantic_palette: SemanticPalette,
    /// Representative control metrics and state colors.
    pub widgets: Vec<WidgetSnapshot>,
    /// 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 GTK 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(())
}

impl ThemeSnapshot {
    /// Check schema, identity, dimensions, uniqueness, and every color channel.
    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 != "gtk4" {
            return Err(validation_error(format!(
                "backend must be gtk4, got {:?}",
                self.backend
            )));
        }
        if self.identity.theme_name.trim().is_empty()
            || self.identity.toolkit_version.trim().is_empty()
        {
            return Err(validation_error(
                "theme name and toolkit version must not be empty",
            ));
        }

        let mut color_names = HashSet::new();
        for color in &self.named_colors {
            if color.name.is_empty() || !color_names.insert(color.name.as_str()) {
                return Err(validation_error(format!(
                    "symbolic color name {:?} is empty or duplicated",
                    color.name
                )));
            }
            validate_rgba(&format!("named_colors.{}", color.name), color.value)?;
        }

        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)?;
            }
        }
        if let Some(color) = self.settings.interface_accent_color {
            validate_rgba("settings.interface_accent_color", color)?;
        }

        let mut controls = HashSet::new();
        for widget in &self.widgets {
            if widget.control.is_empty() || !controls.insert(widget.control.as_str()) {
                return Err(validation_error(format!(
                    "widget name {:?} is empty or duplicated",
                    widget.control
                )));
            }
            if widget.css_name.is_empty() {
                return Err(validation_error(format!(
                    "widget {} has an empty CSS node name",
                    widget.control
                )));
            }
            let metrics = widget.metrics;
            if metrics.minimum_width < 0
                || metrics.natural_width < metrics.minimum_width
                || metrics.minimum_height < 0
                || metrics.natural_height < metrics.minimum_height
            {
                return Err(validation_error(format!(
                    "widget {} has inconsistent preferred dimensions",
                    widget.control
                )));
            }
            let mut states = HashSet::new();
            for state in &widget.states {
                if state.state.is_empty() || !states.insert(state.state.as_str()) {
                    return Err(validation_error(format!(
                        "widget {} has an empty or duplicated state {:?}",
                        widget.control, state.state
                    )));
                }
                validate_rgba(
                    &format!("widgets.{}.{}", widget.control, state.state),
                    state.foreground,
                )?;
            }
        }
        for required in [
            "window",
            "button",
            "input",
            "checkbox",
            "switch",
            "progress-bar",
            "slider",
        ] {
            if !controls.contains(required) {
                return Err(validation_error(format!(
                    "missing representative widget {required}"
                )));
            }
        }
        Ok(())
    }
}

/// A GTK 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 GTK 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("GTK 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(name: &str, color: Rgba) -> Option<native_theme::theme::FontSpec> {
    use gtk::glib::translate::IntoGlib;
    use native_theme::theme::{FontSize, FontSpec, FontStyle, intern_font_family};

    let description = gtk::pango::FontDescription::from_string(name);
    let family = description.family()?;
    let size = description.size();
    Some(FontSpec {
        family: Some(intern_font_family(&family)),
        size: (size > 0).then(|| {
            let value = size as f32 / gtk::pango::SCALE as f32;
            if description.is_size_absolute() {
                FontSize::Px(value)
            } else {
                FontSize::Pt(value)
            }
        }),
        weight: u16::try_from(description.weight().into_glib()).ok(),
        style: Some(match description.style() {
            gtk::pango::Style::Italic => FontStyle::Italic,
            gtk::pango::Style::Oblique => FontStyle::Oblique,
            _ => 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 {
    fn widget(&self, control: &str) -> Option<&WidgetSnapshot> {
        self.widgets.iter().find(|widget| widget.control == control)
    }

    fn state_color(&self, control: &str, state: &str) -> Option<Rgba> {
        self.widget(control)?
            .states
            .iter()
            .find(|item| item.state == state)
            .map(|item| item.foreground)
    }

    /// Translate resolved GTK 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;

        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 = native(semantic.selection_background);
        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.icon_theme = self
            .settings
            .icon_theme_name
            .as_ref()
            .map(|name| name.clone().into());
        if let (Some(font_name), Some(text)) = (&self.settings.font_name, semantic.window_text)
            && let Some(font) = native_font(font_name, text)
        {
            mode.defaults.font = font;
        }

        mode.window.background_color = native(semantic.window_background);
        mode.window.title_bar_background = first_color(
            &self.named_colors,
            &["headerbar_bg_color", "window_bg_color", "theme_bg_color"],
        )
        .map(to_native_color);
        mode.window.inactive_title_bar_background = mode.window.title_bar_background;
        mode.window.inactive_title_bar_text_color = native(semantic.window_text);

        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.hover_text_color = native(self.state_color("button", "hovered"));
        mode.button.active_text_color = native(self.state_color("button", "pressed"));
        mode.button.disabled_text_color = native(
            self.state_color("button", "disabled")
                .or(semantic.disabled_text),
        );
        if let Some(widget) = self.widget("button") {
            mode.button.min_width = Some(widget.metrics.minimum_width as f32);
            mode.button.min_height = Some(widget.metrics.minimum_height as f32);
            if let (Some(font_name), Some(text)) = (
                &self.settings.font_name,
                self.state_color("button", "normal"),
            ) {
                mode.button.font = native_font(font_name, text);
            }
        }

        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(
            self.state_color("input", "disabled")
                .or(semantic.disabled_text),
        );
        mode.input.focus_border_color = native(semantic.accent);
        if let Some(widget) = self.widget("input") {
            mode.input.min_height = Some(widget.metrics.minimum_height as f32);
        }

        mode.checkbox.background_color = native(semantic.window_background);
        mode.checkbox.checked_background = native(semantic.accent);
        mode.checkbox.indicator_color = native(semantic.accent_text);
        mode.checkbox.disabled_text_color = native(
            self.state_color("checkbox", "disabled")
                .or(semantic.disabled_text),
        );

        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(font_name), Some(text)) = (&self.settings.font_name, semantic.tooltip_text) {
            mode.tooltip.font = native_font(font_name, 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.overlay_mode = self.settings.overlay_scrolling;
        if let Some(widget) = self.widget("scrollbar") {
            mode.scrollbar.groove_width = Some(widget.metrics.natural_width as f32);
        }

        mode.slider.fill_color = native(semantic.accent);
        mode.slider.track_color = native(semantic.border);
        mode.slider.thumb_color = native(semantic.surface_background);
        mode.progress_bar.fill_color = native(semantic.accent);
        mode.progress_bar.track_color = native(semantic.window_background);
        if let Some(widget) = self.widget("progress-bar") {
            mode.progress_bar.track_height = Some(widget.metrics.natural_height as f32);
            mode.progress_bar.min_width = Some(widget.metrics.minimum_width as f32);
        }
        mode.switch.checked_background = native(semantic.accent);
        mode.switch.unchecked_background = native(semantic.border);
        mode.switch.thumb_background = native(semantic.surface_background);
        if let Some(widget) = self.widget("switch") {
            mode.switch.track_width = Some(widget.metrics.natural_width as f32);
            mode.switch.track_height = Some(widget.metrics.natural_height as f32);
        }
        mode.separator.line_color = native(semantic.border);
        mode.combo_box.background_color = native(semantic.surface_background);
        mode.combo_box.disabled_text_color = native(semantic.disabled_text);
        mode
    }

    /// Resolve this GTK 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("adwaita")?.into_variant(mode)?;
        variant.merge(&self.to_native_theme_mode());
        let resolved = variant.into_resolved(&ResolutionContext::from_system())?;
        Ok(NativeThemeBridge {
            name: format!("GTK {}", self.identity.theme_name),
            mode,
            resolved,
            reduce_transparency: false,
            reduce_motion: self
                .settings
                .interface_reduced_motion
                .as_ref()
                .is_some_and(|setting| setting.value != 0),
            high_contrast: self
                .settings
                .interface_contrast
                .as_ref()
                .is_some_and(|setting| setting.nick != "no-preference"),
        })
    }

    /// 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 first_color(colors: &[NamedColor], names: &[&str]) -> Option<Rgba> {
    names.iter().find_map(|name| {
        colors
            .iter()
            .find(|color| color.name == *name)
            .map(|color| color.value)
    })
}

fn semantic_palette(colors: &[NamedColor]) -> SemanticPalette {
    SemanticPalette {
        window_background: first_color(colors, &["window_bg_color", "theme_bg_color"]),
        window_text: first_color(colors, &["window_fg_color", "theme_fg_color"]),
        surface_background: first_color(
            colors,
            &[
                "card_bg_color",
                "popover_bg_color",
                "window_bg_color",
                "theme_bg_color",
            ],
        ),
        surface_text: first_color(
            colors,
            &[
                "card_fg_color",
                "popover_fg_color",
                "window_fg_color",
                "theme_fg_color",
            ],
        ),
        input_background: first_color(colors, &["view_bg_color", "theme_base_color"]),
        input_text: first_color(colors, &["view_fg_color", "theme_text_color"]),
        selection_background: first_color(colors, &["accent_bg_color", "theme_selected_bg_color"]),
        selection_text: first_color(colors, &["accent_fg_color", "theme_selected_fg_color"]),
        accent: first_color(
            colors,
            &["accent_bg_color", "accent_color", "theme_selected_bg_color"],
        ),
        accent_text: first_color(colors, &["accent_fg_color", "theme_selected_fg_color"]),
        border: first_color(colors, &["borders"]),
        disabled_text: first_color(colors, &["insensitive_fg_color"]),
        tooltip_background: first_color(
            colors,
            &[
                "popover_bg_color",
                "card_bg_color",
                "window_bg_color",
                "theme_bg_color",
            ],
        ),
        tooltip_text: first_color(
            colors,
            &[
                "popover_fg_color",
                "card_fg_color",
                "window_fg_color",
                "theme_fg_color",
            ],
        ),
        link: first_color(colors, &["link_color", "accent_color"]),
        error: first_color(colors, &["error_color", "destructive_color"]),
        warning: first_color(colors, &["warning_color"]),
        success: first_color(colors, &["success_color"]),
    }
}

/// Failure to initialize or query GTK.
#[derive(Debug, Error)]
pub enum ProbeError {
    /// GTK could not connect to a display or initialize its backend.
    #[error("failed to initialize GTK: {0}")]
    Initialization(String),
    /// No default GTK settings object was available.
    #[error("GTK did not provide a default settings object")]
    MissingSettings,
    /// GTK produced a snapshot that violates the public contract.
    #[error(transparent)]
    InvalidSnapshot(#[from] SnapshotValidationError),
}

fn setting<T>(settings: &gtk::Settings, name: &str) -> Option<T>
where
    for<'a> T: glib::value::FromValue<'a> + 'static,
{
    settings
        .find_property(name)
        .and_then(|_| settings.property_value(name).get::<T>().ok())
}

fn enum_setting(settings: &gtk::Settings, name: &str) -> Option<EnumSetting> {
    settings.find_property(name)?;
    let value = settings.property_value(name);
    let (_, value) = glib::EnumValue::from_value(&value)?;
    Some(EnumSetting {
        value: value.value(),
        name: value.name().to_owned(),
        nick: value.nick().to_owned(),
    })
}

fn requested_dark_variant(color_scheme: Option<&EnumSetting>) -> Option<bool> {
    match color_scheme?.nick.as_str() {
        "dark" => Some(true),
        "light" => Some(false),
        _ => None,
    }
}

fn apply_interface_color_scheme(settings: &gtk::Settings) -> Option<bool> {
    // GTK_THEME is an explicit per-process override and must remain authoritative.
    if std::env::var_os("GTK_THEME").is_some() {
        return None;
    }

    let prefer_dark =
        requested_dark_variant(enum_setting(settings, "gtk-interface-color-scheme").as_ref())?;

    // GTK 4.20 exposes the desktop preference separately from the CSS scheme
    // actually used by the application. Requesting the matching theme variant
    // before creating widgets makes the probe observe the effective colors.
    // This compatibility property is available on all GTK 4 versions supported
    // by this crate, including runtimes predating GtkCssProvider media queries.
    settings.set_property("gtk-application-prefer-dark-theme", prefer_dark);
    Some(prefer_dark)
}

#[allow(deprecated)]
fn named_colors(widget: &gtk::Widget) -> Vec<NamedColor> {
    const NAMES: &[&str] = &[
        "theme_fg_color",
        "theme_bg_color",
        "theme_base_color",
        "theme_text_color",
        "theme_selected_bg_color",
        "theme_selected_fg_color",
        "link_color",
        "insensitive_bg_color",
        "insensitive_fg_color",
        "borders",
        "warning_color",
        "error_color",
        "destructive_color",
        "success_color",
        "accent_color",
        "accent_bg_color",
        "accent_fg_color",
        "window_bg_color",
        "window_fg_color",
        "view_bg_color",
        "view_fg_color",
        "headerbar_bg_color",
        "headerbar_fg_color",
        "card_bg_color",
        "card_fg_color",
        "popover_bg_color",
        "popover_fg_color",
        "dialog_bg_color",
        "dialog_fg_color",
    ];

    let context = widget.style_context();
    NAMES
        .iter()
        .filter_map(|name| {
            context.lookup_color(name).map(|value| NamedColor {
                name: (*name).to_owned(),
                value: value.into(),
            })
        })
        .collect()
}

fn widget_metrics(widget: &gtk::Widget) -> WidgetMetrics {
    let (minimum_width, natural_width, _, _) = widget.measure(gtk::Orientation::Horizontal, -1);
    let (minimum_height, natural_height, _, _) =
        widget.measure(gtk::Orientation::Vertical, natural_width);
    WidgetMetrics {
        minimum_width,
        natural_width,
        minimum_height,
        natural_height,
    }
}

fn widget_states(widget: &gtk::Widget) -> Vec<WidgetState> {
    const STATES: &[(&str, gtk::StateFlags)] = &[
        ("normal", gtk::StateFlags::NORMAL),
        ("hovered", gtk::StateFlags::PRELIGHT),
        ("pressed", gtk::StateFlags::ACTIVE),
        ("focused", gtk::StateFlags::FOCUSED),
        ("focus-visible", gtk::StateFlags::FOCUS_VISIBLE),
        ("checked", gtk::StateFlags::CHECKED),
        ("selected", gtk::StateFlags::SELECTED),
        ("disabled", gtk::StateFlags::INSENSITIVE),
        ("inactive", gtk::StateFlags::BACKDROP),
    ];

    let previous = widget.state_flags();
    let all = gtk::StateFlags::all();
    let mut result = Vec::with_capacity(STATES.len());
    for (name, flags) in STATES {
        widget.unset_state_flags(all);
        widget.set_state_flags(*flags, true);
        result.push(WidgetState {
            state: (*name).to_owned(),
            foreground: widget.color().into(),
        });
    }
    widget.unset_state_flags(all);
    widget.set_state_flags(previous, true);
    result
}

fn widget_snapshot(control: &str, widget: &gtk::Widget) -> WidgetSnapshot {
    WidgetSnapshot {
        control: control.to_owned(),
        css_name: widget.css_name().to_string(),
        metrics: widget_metrics(widget),
        states: widget_states(widget),
    }
}

/// Resolve the current GTK 4 theme.
///
/// This function initializes GTK and therefore must run on the process's main
/// thread before another GUI toolkit claims it. Applications that already run
/// another event loop should invoke the `native-theme-gtk` CLI as a subprocess.
pub fn probe() -> Result<ThemeSnapshot, ProbeError> {
    gtk::init().map_err(|error| ProbeError::Initialization(error.to_string()))?;
    let settings = gtk::Settings::default().ok_or(ProbeError::MissingSettings)?;
    let applied_interface_scheme = apply_interface_color_scheme(&settings);

    let window = gtk::Window::new();
    let container = gtk::Box::new(gtk::Orientation::Vertical, 0);
    let button = gtk::Button::with_label("Button");
    let entry = gtk::Entry::new();
    entry.set_text("Text");
    let checkbox = gtk::CheckButton::with_label("Check box");
    let toggle = gtk::Switch::new();
    let progress = gtk::ProgressBar::new();
    progress.set_fraction(0.5);
    let scale = gtk::Scale::with_range(gtk::Orientation::Horizontal, 0.0, 100.0, 1.0);
    let scrollbar = gtk::Scrollbar::new(gtk::Orientation::Vertical, None::<&gtk::Adjustment>);

    for widget in [
        button.upcast_ref::<gtk::Widget>(),
        entry.upcast_ref(),
        checkbox.upcast_ref(),
        toggle.upcast_ref(),
        progress.upcast_ref(),
        scale.upcast_ref(),
        scrollbar.upcast_ref(),
    ] {
        container.append(widget);
    }
    window.set_child(Some(&container));

    let display_backend = gdk::Display::default().map(|display| {
        let type_name = display.type_().name();
        type_name
            .strip_suffix("Display")
            .unwrap_or(type_name)
            .to_ascii_lowercase()
    });
    let theme_name =
        setting::<String>(&settings, "gtk-theme-name").unwrap_or_else(|| "Default".to_owned());

    let widgets = [
        ("window", window.upcast_ref::<gtk::Widget>()),
        ("button", button.upcast_ref()),
        ("input", entry.upcast_ref()),
        ("checkbox", checkbox.upcast_ref()),
        ("switch", toggle.upcast_ref()),
        ("progress-bar", progress.upcast_ref()),
        ("slider", scale.upcast_ref()),
        ("scrollbar", scrollbar.upcast_ref()),
    ]
    .into_iter()
    .map(|(name, widget)| widget_snapshot(name, widget))
    .collect();

    let named_colors = named_colors(window.upcast_ref());
    let semantic_palette = semantic_palette(&named_colors);
    let mut diagnostics = Vec::new();
    if named_colors.is_empty() {
        diagnostics
            .push("the active theme did not expose any recognized symbolic colors".to_owned());
    }
    if let Some(prefer_dark) = applied_interface_scheme {
        let scheme = if prefer_dark { "dark" } else { "light" };
        diagnostics.push(format!(
            "applied the desktop {scheme} color scheme before sampling GTK styles"
        ));
    }

    let snapshot = ThemeSnapshot {
        schema_version: SCHEMA_VERSION,
        backend: "gtk4".to_owned(),
        identity: ThemeIdentity {
            theme_name,
            toolkit_version: format!(
                "{}.{}.{}",
                gtk::major_version(),
                gtk::minor_version(),
                gtk::micro_version()
            ),
            display_backend,
        },
        settings: GtkSettingsSnapshot {
            font_name: setting(&settings, "gtk-font-name"),
            icon_theme_name: setting(&settings, "gtk-icon-theme-name"),
            cursor_theme_name: setting(&settings, "gtk-cursor-theme-name"),
            cursor_theme_size: setting(&settings, "gtk-cursor-theme-size"),
            enable_animations: setting(&settings, "gtk-enable-animations"),
            overlay_scrolling: setting(&settings, "gtk-overlay-scrolling"),
            primary_button_warps_slider: setting(&settings, "gtk-primary-button-warps-slider"),
            double_click_time_ms: setting(&settings, "gtk-double-click-time"),
            cursor_blink_time_ms: setting(&settings, "gtk-cursor-blink-time"),
            prefer_dark: setting(&settings, "gtk-application-prefer-dark-theme"),
            interface_color_scheme: enum_setting(&settings, "gtk-interface-color-scheme"),
            interface_contrast: enum_setting(&settings, "gtk-interface-contrast"),
            interface_reduced_motion: enum_setting(&settings, "gtk-interface-reduced-motion"),
            interface_accent_color: setting::<gdk::RGBA>(&settings, "gtk-accent-color")
                .map(Into::into),
        },
        named_colors,
        semantic_palette,
        widgets,
        diagnostics,
    };
    snapshot.validate()?;
    Ok(snapshot)
}

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

    #[test]
    fn rgba_serializes_with_explicit_channels() {
        let json = serde_json::to_value(Rgba {
            red: 0.1,
            green: 0.2,
            blue: 0.3,
            alpha: 1.0,
        })
        .unwrap();
        assert_eq!(json["alpha"], 1.0);
        let red = json["red"].as_f64().unwrap();
        assert!((red - 0.1).abs() < f64::from(f32::EPSILON));
    }

    #[test]
    fn explicit_interface_color_schemes_select_the_matching_variant() {
        let setting = |nick: &str| EnumSetting {
            value: 0,
            name: String::new(),
            nick: nick.to_owned(),
        };

        assert_eq!(requested_dark_variant(Some(&setting("dark"))), Some(true));
        assert_eq!(requested_dark_variant(Some(&setting("light"))), Some(false));
        assert_eq!(requested_dark_variant(Some(&setting("default"))), None);
        assert_eq!(requested_dark_variant(None), None);
    }

    #[test]
    fn snapshot_contract_round_trips() {
        let snapshot = ThemeSnapshot {
            schema_version: SCHEMA_VERSION,
            backend: "gtk4".to_owned(),
            identity: ThemeIdentity {
                theme_name: "Test".to_owned(),
                toolkit_version: "4.0.0".to_owned(),
                display_backend: None,
            },
            settings: GtkSettingsSnapshot {
                font_name: None,
                icon_theme_name: None,
                cursor_theme_name: None,
                cursor_theme_size: None,
                enable_animations: None,
                overlay_scrolling: None,
                primary_button_warps_slider: None,
                double_click_time_ms: None,
                cursor_blink_time_ms: None,
                prefer_dark: None,
                interface_color_scheme: None,
                interface_contrast: None,
                interface_reduced_motion: None,
                interface_accent_color: None,
            },
            named_colors: Vec::new(),
            semantic_palette: SemanticPalette::default(),
            widgets: Vec::new(),
            diagnostics: Vec::new(),
        };
        let json = serde_json::to_string(&snapshot).unwrap();
        assert_eq!(
            serde_json::from_str::<ThemeSnapshot>(&json).unwrap(),
            snapshot
        );
    }

    #[test]
    fn semantic_palette_prefers_modern_gtk_names() {
        let modern = Rgba {
            red: 1.0,
            green: 0.0,
            blue: 0.0,
            alpha: 1.0,
        };
        let legacy = Rgba {
            red: 0.0,
            green: 0.0,
            blue: 1.0,
            alpha: 1.0,
        };
        let palette = semantic_palette(&[
            NamedColor {
                name: "theme_bg_color".to_owned(),
                value: legacy,
            },
            NamedColor {
                name: "window_bg_color".to_owned(),
                value: modern,
            },
        ]);
        assert_eq!(palette.window_background, Some(modern));
    }

    #[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: f32::NAN,
                green: 0.0,
                blue: 0.0,
                alpha: 1.0,
            },
        )
        .unwrap_err();
        assert!(error.reason().contains("test.red"));
    }

    #[test]
    fn incomplete_snapshot_is_rejected() {
        let snapshot = ThemeSnapshot {
            schema_version: SCHEMA_VERSION,
            backend: "gtk4".to_owned(),
            identity: ThemeIdentity {
                theme_name: "Test".to_owned(),
                toolkit_version: "4.22.0".to_owned(),
                display_backend: None,
            },
            settings: GtkSettingsSnapshot {
                font_name: None,
                icon_theme_name: None,
                cursor_theme_name: None,
                cursor_theme_size: None,
                enable_animations: None,
                overlay_scrolling: None,
                primary_button_warps_slider: None,
                double_click_time_ms: None,
                cursor_blink_time_ms: None,
                prefer_dark: None,
                interface_color_scheme: None,
                interface_contrast: None,
                interface_reduced_motion: None,
                interface_accent_color: None,
            },
            named_colors: Vec::new(),
            semantic_palette: SemanticPalette::default(),
            widgets: Vec::new(),
            diagnostics: Vec::new(),
        };
        assert!(
            snapshot
                .validate()
                .unwrap_err()
                .reason()
                .contains("missing representative widget")
        );
    }
}