gpuikit 0.9.0

A UI toolkit for GPUI applications
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
//! A trait-based theme system for gpuikit
//!
//! The `Themeable` trait defines the color contract that gpuikit components use,
//! and — since a control's height is as much a design decision as its colour —
//! the shared size scale in [`control`].
//!
//! Consumers can implement this trait for their own theme types.

pub mod control;

pub use control::{ControlMetrics, ControlScale, ControlSize, TrackMetrics};

use gpui::{App, BoxShadow, Global, Hsla, Pixels, SharedString, hsla, px};
use std::sync::Arc;

/// How thick the ring around a keyboard-focused control is.
///
/// One number, in one place, so every control that grows a ring grows the same
/// one.
pub const FOCUS_RING_WIDTH: Pixels = px(2.);

/// The ring a control draws when the keyboard reaches it.
///
/// A **spread shadow rather than a border**, on purpose: a border changes the
/// control's box, so arriving focus would resize it and reflow its neighbours.
/// A spread shadow is painted outside the bounds and moves nothing.
///
/// Apply it through gpui's `focus_visible`, not `focus` — that is the
/// `:focus-visible` rule, so clicking a control does not leave a ring behind
/// it. `crate::a11y` is what makes the control focusable in the first place;
/// this is only what it looks like.
pub fn focus_ring(color: Hsla) -> Vec<BoxShadow> {
    vec![BoxShadow::new(px(0.), px(0.), color).spread_radius(FOCUS_RING_WIDTH)]
}

/// Core theme trait that defines the color contract for UI components.
///
/// Implement this trait for your own theme type to customize colors.
/// Only a small set of "primitive" colors are required - everything else
/// has sensible defaults derived from them.
pub trait Themeable {
    // === Required methods (the primitives) ===

    /// Primary foreground/text color
    fn fg(&self) -> Hsla;

    /// Primary background color
    fn bg(&self) -> Hsla;

    /// Surface color for cards, panels, elevated elements
    fn surface(&self) -> Hsla;

    /// Border color for dividers and boundaries
    fn border(&self) -> Hsla;

    /// Accent color for primary actions and focus states
    fn accent(&self) -> Hsla;

    // === Optional methods with defaults ===

    /// Muted foreground for secondary text
    fn fg_muted(&self) -> Hsla {
        self.fg().opacity(0.7)
    }

    /// Disabled foreground color
    fn fg_disabled(&self) -> Hsla {
        self.fg().opacity(0.4)
    }

    /// Secondary surface for nested panels
    fn surface_secondary(&self) -> Hsla {
        self.surface()
    }

    /// Tertiary surface for deeply nested elements
    fn surface_tertiary(&self) -> Hsla {
        self.surface_secondary()
    }

    /// Secondary border for hover states
    fn border_secondary(&self) -> Hsla {
        self.border()
    }

    /// Subtle border for minimal separation
    fn border_subtle(&self) -> Hsla {
        self.border().opacity(0.5)
    }

    /// Focus outline color
    fn outline(&self) -> Hsla {
        self.accent()
    }

    /// Accent background (for tags, badges)
    fn accent_bg(&self) -> Hsla {
        self.accent().opacity(0.15)
    }

    /// Accent background hover state
    fn accent_bg_hover(&self) -> Hsla {
        self.accent().opacity(0.25)
    }

    /// Info color (blue)
    fn info(&self) -> Hsla {
        hsla(210.0 / 360.0, 0.7, 0.5, 1.0)
    }

    /// Success color (green)
    fn success(&self) -> Hsla {
        hsla(142.0 / 360.0, 0.7, 0.4, 1.0)
    }

    /// Warning color (yellow/orange)
    fn warning(&self) -> Hsla {
        hsla(38.0 / 360.0, 0.9, 0.5, 1.0)
    }

    /// Danger/error color
    fn danger(&self) -> Hsla {
        hsla(0.0, 0.7, 0.5, 1.0)
    }

    /// Selection highlight color
    fn selection(&self) -> Hsla {
        self.accent().opacity(0.3)
    }

    /// Placeholder text color
    fn placeholder(&self) -> Hsla {
        self.fg().opacity(0.5)
    }

    /// Overlay/scrim color for modal backdrops.
    ///
    /// Used by Dialog and other modal components to dim the background.
    /// Defaults to a semi-transparent black, which works for both light and dark themes.
    fn overlay(&self) -> Hsla {
        hsla(0.0, 0.0, 0.0, 0.6)
    }

    // === Component-specific defaults ===

    fn button_bg(&self) -> Hsla {
        self.surface()
    }

    fn button_bg_hover(&self) -> Hsla {
        self.surface_secondary()
    }

    fn button_bg_active(&self) -> Hsla {
        self.surface_tertiary()
    }

    fn button_border(&self) -> Hsla {
        self.border()
    }

    /// Fill of a destructive button — one that deletes, discards or revokes.
    ///
    /// Derived from [`danger`](Themeable::danger) rather than introduced as a
    /// new palette entry: a theme that has already said what its error colour
    /// is has said what a destructive action looks like, and two entries that
    /// could disagree is a way for them to.
    fn destructive_bg(&self) -> Hsla {
        self.danger()
    }

    /// Hover fill of a destructive button: the fill, lightened.
    fn destructive_bg_hover(&self) -> Hsla {
        let base = self.destructive_bg();
        hsla(base.h, base.s, (base.l + 0.08).min(1.0), base.a)
    }

    /// Pressed fill of a destructive button: the fill, darkened.
    fn destructive_bg_active(&self) -> Hsla {
        let base = self.destructive_bg();
        hsla(base.h, base.s, (base.l - 0.08).max(0.0), base.a)
    }

    /// Text on a destructive button: black or white, whichever the fill
    /// actually reads better against.
    ///
    /// Not [`fg`](Themeable::fg) — a light theme's foreground is dark, and
    /// dark text on a saturated red is the one combination this has to avoid
    /// — and not the fill's HSL lightness either, which is what this used to
    /// pick by. HSL lightness is not perceived brightness: a saturated red
    /// sits high on the L axis and low on the luminance one, so the rule
    /// `l > 0.6 → black` chose *white* for Gruvbox Dark's `#fb4934`, which is
    /// 3.4:1 — under WCAG AA — where black on the same fill is 6.1:1. It was
    /// the only theme in the crate the old rule got wrong, and it was the one
    /// whose destructive button looked washed out.
    ///
    /// Comparing contrast ratios picks the same answer as before for every
    /// other built-in theme, and it keeps picking the readable one for a
    /// consumer's `danger` colour whatever hue it is.
    fn destructive_fg(&self) -> Hsla {
        let black = hsla(0.0, 0.0, 0.0, 1.0);
        let white = hsla(0.0, 0.0, 1.0, 1.0);
        let bg = self.destructive_bg();

        if contrast_ratio(bg, white) >= contrast_ratio(bg, black) {
            white
        } else {
            black
        }
    }

    fn input_bg(&self) -> Hsla {
        self.surface()
    }

    fn input_border(&self) -> Hsla {
        self.border()
    }

    fn input_border_hover(&self) -> Hsla {
        self.border_secondary()
    }

    fn input_border_focused(&self) -> Hsla {
        self.accent()
    }

    /// Input text color
    fn input_text(&self) -> Hsla {
        self.fg()
    }

    /// Input placeholder text color
    fn input_placeholder(&self) -> Hsla {
        self.placeholder()
    }

    /// Input selection/highlight color
    fn input_selection(&self) -> Hsla {
        self.selection()
    }

    /// Input cursor/caret color
    fn input_cursor(&self) -> Hsla {
        self.accent()
    }

    // === Badge palette ===
    // Colors for small colored indicators: icon badges, status dots, category tags.
    // Defaults derive from semantic colors but at appropriate saturation for badge fills.

    fn badge_blue(&self) -> Hsla {
        self.info()
    }

    fn badge_gold(&self) -> Hsla {
        self.warning()
    }

    fn badge_red(&self) -> Hsla {
        self.danger()
    }

    fn badge_green(&self) -> Hsla {
        self.success()
    }

    fn badge_teal(&self) -> Hsla {
        hsla(180.0 / 360.0, 0.55, 0.45, 1.0)
    }

    fn badge_amber(&self) -> Hsla {
        hsla(30.0 / 360.0, 0.7, 0.50, 1.0)
    }

    fn badge_gray(&self) -> Hsla {
        self.fg_muted()
    }

    // === Control sizing ===
    // Sits beside the colors deliberately: a control's height is a design
    // decision of the same kind, and putting it anywhere else is how the crate
    // ended up with five different control heights and no way to change them
    // together.

    /// The three rungs of the shared control size scale.
    ///
    /// Override this to rescale every control at once.
    fn control_scale(&self) -> ControlScale {
        ControlScale::default()
    }

    /// The metrics for one rung — height, padding, gap, radius, text size,
    /// line box and ink.
    ///
    /// This is what an element calls; `control_scale` is what a theme
    /// overrides.
    fn control(&self, size: ControlSize) -> ControlMetrics {
        self.control_scale().metrics(size)
    }
}

/// The WCAG 2.1 contrast ratio between two opaque colours, 1.0 to 21.0.
///
/// Alpha is ignored: both callers pass fills, and compositing a translucent
/// one correctly needs the colour behind it, which a theme accessor does not
/// have. A ratio computed against the fill as if it were opaque is the right
/// answer for the fills the crate actually draws, and wrong in the same
/// direction as simply reading the declared colour, which is what the code
/// this replaced did.
fn contrast_ratio(a: Hsla, b: Hsla) -> f32 {
    let lighter = relative_luminance(a).max(relative_luminance(b));
    let darker = relative_luminance(a).min(relative_luminance(b));
    (lighter + 0.05) / (darker + 0.05)
}

/// WCAG relative luminance: sRGB channels linearised, then weighted by how
/// much the eye gets from each.
///
/// This is the quantity HSL's `l` is often mistaken for and is not. `l` is the
/// midpoint of the largest and smallest channel, so it says a fully saturated
/// red and a fully saturated cyan are equally bright; luminance says the cyan
/// is nearly four times brighter, which is what a reader sees.
fn relative_luminance(color: Hsla) -> f32 {
    let rgba = gpui::Rgba::from(color);
    let channel = |c: f32| {
        if c <= 0.03928 {
            c / 12.92
        } else {
            ((c + 0.055) / 1.055).powf(2.4)
        }
    };
    0.2126 * channel(rgba.r) + 0.7152 * channel(rgba.g) + 0.0722 * channel(rgba.b)
}

pub fn init(cx: &mut App) {
    cx.set_global(GlobalTheme::default());
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ThemeVariant {
    #[default]
    Dark,
    Light,
}

/// A concrete theme implementation with stored color values.
#[derive(Debug, Clone)]
pub struct Theme {
    pub name: SharedString,
    pub variant: ThemeVariant,

    // Primitives
    pub fg_color: Hsla,
    pub bg_color: Hsla,
    pub surface_color: Hsla,
    pub border_color: Hsla,
    pub accent_color: Hsla,

    // Overrides (None = use default from trait)
    pub fg_muted_color: Option<Hsla>,
    pub fg_disabled_color: Option<Hsla>,
    pub surface_secondary_color: Option<Hsla>,
    pub surface_tertiary_color: Option<Hsla>,
    pub border_secondary_color: Option<Hsla>,
    pub border_subtle_color: Option<Hsla>,
    pub outline_color: Option<Hsla>,
    pub accent_bg_color: Option<Hsla>,
    pub accent_bg_hover_color: Option<Hsla>,
    pub info_color: Option<Hsla>,
    pub success_color: Option<Hsla>,
    pub warning_color: Option<Hsla>,
    pub danger_color: Option<Hsla>,
    pub selection_color: Option<Hsla>,
    pub button_bg_color: Option<Hsla>,
    pub button_bg_hover_color: Option<Hsla>,
    pub button_bg_active_color: Option<Hsla>,
    pub button_border_color: Option<Hsla>,
    pub input_bg_color: Option<Hsla>,
    pub input_border_color: Option<Hsla>,
    pub input_border_hover_color: Option<Hsla>,
    pub input_border_focused_color: Option<Hsla>,
    pub input_text_color: Option<Hsla>,
    pub input_placeholder_color: Option<Hsla>,
    pub input_selection_color: Option<Hsla>,
    pub input_cursor_color: Option<Hsla>,
    pub overlay_color: Option<Hsla>,
    pub badge_blue_color: Option<Hsla>,
    pub badge_gold_color: Option<Hsla>,
    pub badge_red_color: Option<Hsla>,
    pub badge_green_color: Option<Hsla>,
    pub badge_teal_color: Option<Hsla>,
    pub badge_amber_color: Option<Hsla>,
    pub badge_gray_color: Option<Hsla>,

    /// The shared control size scale. Not an `Option`: every theme has one,
    /// and `ControlScale::default()` is the crate's scale rather than an
    /// absence of one.
    pub controls: ControlScale,
}

impl Themeable for Theme {
    fn fg(&self) -> Hsla {
        self.fg_color
    }
    fn bg(&self) -> Hsla {
        self.bg_color
    }
    fn surface(&self) -> Hsla {
        self.surface_color
    }
    fn border(&self) -> Hsla {
        self.border_color
    }
    fn accent(&self) -> Hsla {
        self.accent_color
    }

    fn fg_muted(&self) -> Hsla {
        self.fg_muted_color
            .unwrap_or_else(|| self.fg().opacity(0.7))
    }
    fn fg_disabled(&self) -> Hsla {
        self.fg_disabled_color
            .unwrap_or_else(|| self.fg().opacity(0.4))
    }
    fn surface_secondary(&self) -> Hsla {
        self.surface_secondary_color
            .unwrap_or_else(|| self.surface())
    }
    fn surface_tertiary(&self) -> Hsla {
        self.surface_tertiary_color
            .unwrap_or_else(|| self.surface_secondary())
    }
    fn border_secondary(&self) -> Hsla {
        self.border_secondary_color.unwrap_or_else(|| self.border())
    }
    fn border_subtle(&self) -> Hsla {
        self.border_subtle_color
            .unwrap_or_else(|| self.border().opacity(0.5))
    }
    fn outline(&self) -> Hsla {
        self.outline_color.unwrap_or_else(|| self.accent())
    }
    fn accent_bg(&self) -> Hsla {
        self.accent_bg_color
            .unwrap_or_else(|| self.accent().opacity(0.15))
    }
    fn accent_bg_hover(&self) -> Hsla {
        self.accent_bg_hover_color
            .unwrap_or_else(|| self.accent().opacity(0.25))
    }
    fn info(&self) -> Hsla {
        self.info_color
            .unwrap_or_else(|| hsla(210.0 / 360.0, 0.7, 0.5, 1.0))
    }
    fn success(&self) -> Hsla {
        self.success_color
            .unwrap_or_else(|| hsla(142.0 / 360.0, 0.7, 0.4, 1.0))
    }
    fn warning(&self) -> Hsla {
        self.warning_color
            .unwrap_or_else(|| hsla(38.0 / 360.0, 0.9, 0.5, 1.0))
    }
    fn danger(&self) -> Hsla {
        self.danger_color
            .unwrap_or_else(|| hsla(0.0, 0.7, 0.5, 1.0))
    }
    fn selection(&self) -> Hsla {
        self.selection_color
            .unwrap_or_else(|| self.accent().opacity(0.3))
    }
    fn placeholder(&self) -> Hsla {
        self.fg().opacity(0.5)
    }
    fn button_bg(&self) -> Hsla {
        self.button_bg_color.unwrap_or_else(|| self.surface())
    }
    fn button_bg_hover(&self) -> Hsla {
        self.button_bg_hover_color
            .unwrap_or_else(|| self.surface_secondary())
    }
    fn button_bg_active(&self) -> Hsla {
        self.button_bg_active_color
            .unwrap_or_else(|| self.surface_tertiary())
    }
    fn button_border(&self) -> Hsla {
        self.button_border_color.unwrap_or_else(|| self.border())
    }
    fn input_bg(&self) -> Hsla {
        self.input_bg_color.unwrap_or_else(|| self.surface())
    }
    fn input_border(&self) -> Hsla {
        self.input_border_color.unwrap_or_else(|| self.border())
    }
    fn input_border_hover(&self) -> Hsla {
        self.input_border_hover_color
            .unwrap_or_else(|| self.border_secondary())
    }
    fn input_border_focused(&self) -> Hsla {
        self.input_border_focused_color
            .unwrap_or_else(|| self.accent())
    }
    fn input_text(&self) -> Hsla {
        self.input_text_color.unwrap_or_else(|| self.fg())
    }
    fn input_placeholder(&self) -> Hsla {
        self.input_placeholder_color
            .unwrap_or_else(|| self.placeholder())
    }
    fn input_selection(&self) -> Hsla {
        self.input_selection_color
            .unwrap_or_else(|| self.selection())
    }
    fn input_cursor(&self) -> Hsla {
        self.input_cursor_color.unwrap_or_else(|| self.accent())
    }
    fn overlay(&self) -> Hsla {
        self.overlay_color
            .unwrap_or_else(|| hsla(0.0, 0.0, 0.0, 0.6))
    }
    fn badge_blue(&self) -> Hsla {
        self.badge_blue_color.unwrap_or_else(|| self.info())
    }
    fn badge_gold(&self) -> Hsla {
        self.badge_gold_color.unwrap_or_else(|| self.warning())
    }
    fn badge_red(&self) -> Hsla {
        self.badge_red_color.unwrap_or_else(|| self.danger())
    }
    fn badge_green(&self) -> Hsla {
        self.badge_green_color.unwrap_or_else(|| self.success())
    }
    fn badge_teal(&self) -> Hsla {
        self.badge_teal_color
            .unwrap_or_else(|| hsla(180.0 / 360.0, 0.55, 0.45, 1.0))
    }
    fn badge_amber(&self) -> Hsla {
        self.badge_amber_color
            .unwrap_or_else(|| hsla(30.0 / 360.0, 0.7, 0.50, 1.0))
    }
    fn badge_gray(&self) -> Hsla {
        self.badge_gray_color.unwrap_or_else(|| self.fg_muted())
    }
    fn control_scale(&self) -> ControlScale {
        self.controls
    }
}

impl Theme {
    /// Create a new theme with just the required primitives.
    /// All other colors will use sensible defaults.
    pub fn new(
        name: impl Into<SharedString>,
        variant: ThemeVariant,
        fg: Hsla,
        bg: Hsla,
        surface: Hsla,
        border: Hsla,
        accent: Hsla,
    ) -> Self {
        Theme {
            name: name.into(),
            variant,
            fg_color: fg,
            bg_color: bg,
            surface_color: surface,
            border_color: border,
            accent_color: accent,
            fg_muted_color: None,
            fg_disabled_color: None,
            surface_secondary_color: None,
            surface_tertiary_color: None,
            border_secondary_color: None,
            border_subtle_color: None,
            outline_color: None,
            accent_bg_color: None,
            accent_bg_hover_color: None,
            info_color: None,
            success_color: None,
            warning_color: None,
            danger_color: None,
            selection_color: None,
            button_bg_color: None,
            button_bg_hover_color: None,
            button_bg_active_color: None,
            button_border_color: None,
            input_bg_color: None,
            input_border_color: None,
            input_border_hover_color: None,
            input_border_focused_color: None,
            input_text_color: None,
            input_placeholder_color: None,
            input_selection_color: None,
            input_cursor_color: None,
            overlay_color: None,
            badge_blue_color: None,
            badge_gold_color: None,
            badge_red_color: None,
            badge_green_color: None,
            badge_teal_color: None,
            badge_amber_color: None,
            badge_gray_color: None,
            controls: ControlScale::default(),
        }
    }

    /// Create a Gruvbox Dark theme
    pub fn gruvbox_dark() -> Self {
        let mut theme = Theme::new(
            "Gruvbox Dark",
            ThemeVariant::Dark,
            parse_hex("#ebdbb2"), // fg
            parse_hex("#282828"), // bg
            parse_hex("#3c3836"), // surface
            parse_hex("#504945"), // border
            parse_hex("#8ec07c"), // accent
        );
        theme.fg_muted_color = Some(parse_hex("#a89984"));
        theme.fg_disabled_color = Some(parse_hex("#7c6f64"));
        theme.surface_secondary_color = Some(parse_hex("#504945"));
        theme.surface_tertiary_color = Some(parse_hex("#665c54"));
        theme.border_secondary_color = Some(parse_hex("#7c6f64"));
        theme.border_subtle_color = Some(parse_hex("#3c3836"));
        theme.outline_color = Some(parse_hex("#458588"));
        theme.info_color = Some(parse_hex("#458588"));
        theme.success_color = Some(parse_hex("#b8bb26"));
        theme.warning_color = Some(parse_hex("#fabd2f"));
        theme.danger_color = Some(parse_hex("#fb4934"));
        theme.selection_color = Some(hsla(55.0 / 360.0, 0.56, 0.64, 0.25));
        theme.button_bg_color = Some(parse_hex("#504945"));
        theme.button_bg_hover_color = Some(parse_hex("#665c54"));
        theme.button_bg_active_color = Some(parse_hex("#7c6f64"));
        theme.button_border_color = Some(parse_hex("#7c6f64"));
        theme.input_border_hover_color = Some(parse_hex("#665c54"));
        theme
    }

    /// Create a Gruvbox Light theme
    pub fn gruvbox_light() -> Self {
        let mut theme = Theme::new(
            "Gruvbox Light",
            ThemeVariant::Light,
            parse_hex("#3c3836"), // fg
            parse_hex("#fbf1c7"), // bg
            parse_hex("#ebdbb2"), // surface
            parse_hex("#d5c4a1"), // border
            parse_hex("#427b58"), // accent
        );
        theme.fg_muted_color = Some(parse_hex("#665c54"));
        theme.fg_disabled_color = Some(parse_hex("#a89984"));
        theme.surface_secondary_color = Some(parse_hex("#d5c4a1"));
        theme.surface_tertiary_color = Some(parse_hex("#bdae93"));
        theme.border_secondary_color = Some(parse_hex("#a89984"));
        theme.border_subtle_color = Some(parse_hex("#ebdbb2"));
        theme.outline_color = Some(parse_hex("#076678"));
        theme.info_color = Some(parse_hex("#076678"));
        theme.success_color = Some(parse_hex("#79740e"));
        theme.warning_color = Some(parse_hex("#b57614"));
        theme.danger_color = Some(parse_hex("#cc241d"));
        theme.selection_color = Some(hsla(48.0 / 360.0, 0.87, 0.61, 0.15));
        theme.button_bg_color = Some(parse_hex("#ebdbb2"));
        theme.button_bg_hover_color = Some(parse_hex("#d5c4a1"));
        theme.button_bg_active_color = Some(parse_hex("#bdae93"));
        theme.button_border_color = Some(parse_hex("#a89984"));
        theme.input_border_hover_color = Some(parse_hex("#bdae93"));
        theme
    }

    /// Create a Catppuccin Latte (light) theme
    pub fn catppuccin_latte() -> Self {
        let mut theme = Theme::new(
            "Catppuccin Latte",
            ThemeVariant::Light,
            parse_hex("#4c4f69"), // text
            parse_hex("#eff1f5"), // base
            parse_hex("#e6e9ef"), // mantle
            parse_hex("#ccd0da"), // surface0
            parse_hex("#8839ef"), // mauve
        );
        theme.fg_muted_color = Some(parse_hex("#6c6f85"));
        theme.fg_disabled_color = Some(parse_hex("#9ca0b0"));
        theme.surface_secondary_color = Some(parse_hex("#ccd0da"));
        theme.surface_tertiary_color = Some(parse_hex("#bcc0cc"));
        theme.border_secondary_color = Some(parse_hex("#acb0be"));
        theme.border_subtle_color = Some(parse_hex("#e6e9ef"));
        theme.info_color = Some(parse_hex("#1e66f5"));
        theme.success_color = Some(parse_hex("#40a02b"));
        theme.warning_color = Some(parse_hex("#df8e1d"));
        theme.danger_color = Some(parse_hex("#d20f39"));
        theme.button_bg_color = Some(parse_hex("#ccd0da"));
        theme.button_bg_hover_color = Some(parse_hex("#bcc0cc"));
        theme.button_bg_active_color = Some(parse_hex("#acb0be"));
        theme.button_border_color = Some(parse_hex("#acb0be"));
        theme.input_border_hover_color = Some(parse_hex("#acb0be"));
        theme.badge_blue_color = Some(parse_hex("#1e66f5"));
        theme.badge_gold_color = Some(parse_hex("#df8e1d"));
        theme.badge_red_color = Some(parse_hex("#d20f39"));
        theme.badge_green_color = Some(parse_hex("#40a02b"));
        theme.badge_teal_color = Some(parse_hex("#179299"));
        theme.badge_amber_color = Some(parse_hex("#fe640b"));
        theme.badge_gray_color = Some(parse_hex("#6c6f85"));
        theme
    }

    /// Create a Catppuccin Frappé theme
    pub fn catppuccin_frappe() -> Self {
        let mut theme = Theme::new(
            "Catppuccin Frappé",
            ThemeVariant::Dark,
            parse_hex("#c6d0f5"), // text
            parse_hex("#303446"), // base
            parse_hex("#292c3c"), // mantle
            parse_hex("#414559"), // surface0
            parse_hex("#ca9ee6"), // mauve
        );
        theme.fg_muted_color = Some(parse_hex("#a5adce"));
        theme.fg_disabled_color = Some(parse_hex("#838ba7"));
        theme.surface_secondary_color = Some(parse_hex("#51576d"));
        theme.surface_tertiary_color = Some(parse_hex("#626880"));
        theme.border_secondary_color = Some(parse_hex("#626880"));
        theme.border_subtle_color = Some(parse_hex("#292c3c"));
        theme.info_color = Some(parse_hex("#8caaee"));
        theme.success_color = Some(parse_hex("#a6d189"));
        theme.warning_color = Some(parse_hex("#e5c890"));
        theme.danger_color = Some(parse_hex("#e78284"));
        theme.button_bg_color = Some(parse_hex("#414559"));
        theme.button_bg_hover_color = Some(parse_hex("#51576d"));
        theme.button_bg_active_color = Some(parse_hex("#626880"));
        theme.button_border_color = Some(parse_hex("#626880"));
        theme.input_border_hover_color = Some(parse_hex("#51576d"));
        theme.badge_blue_color = Some(parse_hex("#8caaee"));
        theme.badge_gold_color = Some(parse_hex("#e5c890"));
        theme.badge_red_color = Some(parse_hex("#e78284"));
        theme.badge_green_color = Some(parse_hex("#a6d189"));
        theme.badge_teal_color = Some(parse_hex("#81c8be"));
        theme.badge_amber_color = Some(parse_hex("#ef9f76"));
        theme.badge_gray_color = Some(parse_hex("#a5adce"));
        theme
    }

    /// Create a Catppuccin Macchiato theme
    pub fn catppuccin_macchiato() -> Self {
        let mut theme = Theme::new(
            "Catppuccin Macchiato",
            ThemeVariant::Dark,
            parse_hex("#cad3f5"), // text
            parse_hex("#24273a"), // base
            parse_hex("#1e2030"), // mantle
            parse_hex("#363a4f"), // surface0
            parse_hex("#c6a0f6"), // mauve
        );
        theme.fg_muted_color = Some(parse_hex("#a5adcb"));
        theme.fg_disabled_color = Some(parse_hex("#8087a2"));
        theme.surface_secondary_color = Some(parse_hex("#494d64"));
        theme.surface_tertiary_color = Some(parse_hex("#5b6078"));
        theme.border_secondary_color = Some(parse_hex("#5b6078"));
        theme.border_subtle_color = Some(parse_hex("#1e2030"));
        theme.info_color = Some(parse_hex("#8aadf4"));
        theme.success_color = Some(parse_hex("#a6da95"));
        theme.warning_color = Some(parse_hex("#eed49f"));
        theme.danger_color = Some(parse_hex("#ed8796"));
        theme.button_bg_color = Some(parse_hex("#363a4f"));
        theme.button_bg_hover_color = Some(parse_hex("#494d64"));
        theme.button_bg_active_color = Some(parse_hex("#5b6078"));
        theme.button_border_color = Some(parse_hex("#5b6078"));
        theme.input_border_hover_color = Some(parse_hex("#494d64"));
        theme.badge_blue_color = Some(parse_hex("#8aadf4"));
        theme.badge_gold_color = Some(parse_hex("#eed49f"));
        theme.badge_red_color = Some(parse_hex("#ed8796"));
        theme.badge_green_color = Some(parse_hex("#a6da95"));
        theme.badge_teal_color = Some(parse_hex("#8bd5ca"));
        theme.badge_amber_color = Some(parse_hex("#f5a97f"));
        theme.badge_gray_color = Some(parse_hex("#a5adcb"));
        theme
    }

    /// Create a Catppuccin Mocha theme
    pub fn catppuccin_mocha() -> Self {
        let mut theme = Theme::new(
            "Catppuccin Mocha",
            ThemeVariant::Dark,
            parse_hex("#cdd6f4"), // text
            parse_hex("#1e1e2e"), // base
            parse_hex("#181825"), // mantle
            parse_hex("#313244"), // surface0
            parse_hex("#cba6f7"), // mauve
        );
        theme.fg_muted_color = Some(parse_hex("#a6adc8"));
        theme.fg_disabled_color = Some(parse_hex("#7f849c"));
        theme.surface_secondary_color = Some(parse_hex("#45475a"));
        theme.surface_tertiary_color = Some(parse_hex("#585b70"));
        theme.border_secondary_color = Some(parse_hex("#585b70"));
        theme.border_subtle_color = Some(parse_hex("#181825"));
        theme.info_color = Some(parse_hex("#89b4fa"));
        theme.success_color = Some(parse_hex("#a6e3a1"));
        theme.warning_color = Some(parse_hex("#f9e2af"));
        theme.danger_color = Some(parse_hex("#f38ba8"));
        theme.button_bg_color = Some(parse_hex("#313244"));
        theme.button_bg_hover_color = Some(parse_hex("#45475a"));
        theme.button_bg_active_color = Some(parse_hex("#585b70"));
        theme.button_border_color = Some(parse_hex("#585b70"));
        theme.input_border_hover_color = Some(parse_hex("#45475a"));
        theme.badge_blue_color = Some(parse_hex("#89b4fa"));
        theme.badge_gold_color = Some(parse_hex("#f9e2af"));
        theme.badge_red_color = Some(parse_hex("#f38ba8"));
        theme.badge_green_color = Some(parse_hex("#a6e3a1"));
        theme.badge_teal_color = Some(parse_hex("#94e2d5"));
        theme.badge_amber_color = Some(parse_hex("#fab387"));
        theme.badge_gray_color = Some(parse_hex("#a6adc8"));
        theme
    }

    pub fn get_global(cx: &App) -> &Arc<Theme> {
        &cx.global::<GlobalTheme>().0
    }
}

impl Default for Theme {
    fn default() -> Self {
        Theme::gruvbox_dark()
    }
}

#[derive(Clone, Debug)]
pub struct GlobalTheme(pub Arc<Theme>);

impl Global for GlobalTheme {}

impl Default for GlobalTheme {
    fn default() -> Self {
        GlobalTheme(Arc::new(Theme::default()))
    }
}

/// Trait for accessing the current theme from an App context
pub trait ActiveTheme {
    fn theme(&self) -> &Arc<Theme>;
}

impl ActiveTheme for App {
    fn theme(&self) -> &Arc<Theme> {
        &self.global::<GlobalTheme>().0
    }
}

pub fn parse_hex(hex: &str) -> Hsla {
    let hex = hex.trim_start_matches('#');

    let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(0);
    let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(0);
    let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(0);

    let r = r as f32 / 255.0;
    let g = g as f32 / 255.0;
    let b = b as f32 / 255.0;

    let max = r.max(g).max(b);
    let min = r.min(g).min(b);
    let delta = max - min;

    let lightness = (max + min) / 2.0;

    let saturation = if delta == 0.0 {
        0.0
    } else {
        delta / (1.0 - (2.0 * lightness - 1.0).abs())
    };

    let hue = if delta == 0.0 {
        0.0
    } else if max == r {
        60.0 * (((g - b) / delta) % 6.0)
    } else if max == g {
        60.0 * ((b - r) / delta + 2.0)
    } else {
        60.0 * ((r - g) / delta + 4.0)
    };

    let hue = if hue < 0.0 { hue + 360.0 } else { hue };

    gpui::hsla(hue / 360.0, saturation, lightness, 1.0)
}

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

    #[test]
    fn test_default_theme() {
        let theme = Theme::default();
        assert_eq!(theme.name, SharedString::from("Gruvbox Dark"));
        assert_eq!(theme.variant, ThemeVariant::Dark);
    }

    #[test]
    fn test_minimal_theme() {
        // Create a theme with just primitives - all else uses defaults
        let theme = Theme::new(
            "Minimal",
            ThemeVariant::Dark,
            parse_hex("#ffffff"),
            parse_hex("#000000"),
            parse_hex("#111111"),
            parse_hex("#333333"),
            parse_hex("#0066cc"),
        );

        // Derived values should work
        assert_eq!(theme.button_bg(), theme.surface());
        assert_eq!(theme.input_border_focused(), theme.accent());
    }

    /// A theme's scale has to actually reach the elements. `Themeable::control`
    /// Every built-in theme, by name, so a new one has to be added here and
    /// is then held to the contrast assertion below.
    fn built_in_themes() -> Vec<(&'static str, Theme)> {
        vec![
            ("default", Theme::default()),
            ("gruvbox_dark", Theme::gruvbox_dark()),
            ("gruvbox_light", Theme::gruvbox_light()),
            ("catppuccin_latte", Theme::catppuccin_latte()),
            ("catppuccin_frappe", Theme::catppuccin_frappe()),
            ("catppuccin_macchiato", Theme::catppuccin_macchiato()),
            ("catppuccin_mocha", Theme::catppuccin_mocha()),
        ]
    }

    /// The defect this replaced: `destructive_fg` picked black or white off
    /// the fill's HSL lightness, and Gruvbox Dark's `#fb4934` sits at `l =
    /// 0.594` — just inside the "dark enough for white text" side of a 0.6
    /// threshold — while its *luminance* puts black nearly twice as far
    /// ahead. The button was legible, badly, and looked washed out.
    ///
    /// 4.5:1 is WCAG AA for body text. Every built-in theme clears it on the
    /// better of the two, so this is a floor the crate already meets rather
    /// than an aspiration.
    #[test]
    fn destructive_text_clears_wcag_aa_on_every_built_in_theme() {
        for (name, theme) in built_in_themes() {
            let ratio = contrast_ratio(theme.destructive_bg(), theme.destructive_fg());
            assert!(
                ratio >= 4.5,
                "{name}: destructive text is {ratio:.2}:1 on its own fill, under WCAG AA"
            );
        }
    }

    /// The rule has to pick the *better* of black and white, not merely one
    /// that happens to pass. A theme whose fill clears 4.5:1 both ways would
    /// satisfy the assertion above with the worse choice.
    #[test]
    fn destructive_text_is_the_better_of_black_and_white() {
        let black = hsla(0.0, 0.0, 0.0, 1.0);
        let white = hsla(0.0, 0.0, 1.0, 1.0);

        for (name, theme) in built_in_themes() {
            let bg = theme.destructive_bg();
            let chosen = contrast_ratio(bg, theme.destructive_fg());
            let best = contrast_ratio(bg, black).max(contrast_ratio(bg, white));
            assert!(
                (chosen - best).abs() < 0.001,
                "{name}: chose {chosen:.2}:1 when {best:.2}:1 was available"
            );
        }
    }

    /// Relative luminance is not HSL lightness, which is the whole reason
    /// `destructive_fg` changed. Saturated red and saturated cyan share an
    /// `l` of 0.5 and are nowhere near each other in luminance.
    #[test]
    fn luminance_and_hsl_lightness_are_different_quantities() {
        let red = hsla(0.0, 1.0, 0.5, 1.0);
        let cyan = hsla(180.0 / 360.0, 1.0, 0.5, 1.0);

        assert_eq!(red.l, cyan.l, "the premise: equal HSL lightness");
        assert!(
            relative_luminance(cyan) > relative_luminance(red) * 3.0,
            "cyan {:.3} is not far brighter than red {:.3}",
            relative_luminance(cyan),
            relative_luminance(red),
        );
    }

    /// has a default impl, so this is the wire between `Theme::controls` and
    /// what a control reads at render time.
    #[test]
    fn a_theme_can_rescale_every_control_at_once() {
        let mut theme = Theme::default();
        assert_eq!(
            theme.control(ControlSize::Medium).height.0,
            ControlScale::default().medium.height.0
        );

        theme.controls.medium.height = gpui::Rems(2.0);
        assert_eq!(theme.control(ControlSize::Medium).height.0, 2.0);
        // The other rungs are untouched by one override.
        assert_eq!(
            theme.control(ControlSize::Small).height.0,
            ControlScale::default().small.height.0
        );
    }

    #[test]
    fn test_hex_parsing() {
        let color = parse_hex("#ffffff");
        assert_eq!(color.l, 1.0);

        let color = parse_hex("#000000");
        assert_eq!(color.l, 0.0);
    }
}