skathi-gpui 0.4.1

gpui, Zed's GPU-accelerated UI framework, as Skathi renders with it
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
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
use anyhow::{Context as _, bail};
#[cfg(feature = "schemars")]
use schemars::{JsonSchema, json_schema};
use serde::{
    Deserialize, Deserializer, Serialize, Serializer,
    de::{self, Visitor},
};
#[cfg(feature = "schemars")]
use std::borrow::Cow;
use std::{
    fmt::{self, Display, Formatter},
    hash::{Hash, Hasher},
};

/// Convert an RGB hex color code number to a color type
pub fn rgb(hex: u32) -> Rgba {
    let [_, r, g, b] = hex.to_be_bytes().map(|b| (b as f32) / 255.0);
    Rgba { r, g, b, a: 1.0 }
}

/// Convert an RGBA hex color code number to [`Rgba`]
pub fn rgba(hex: u32) -> Rgba {
    let [r, g, b, a] = hex.to_be_bytes().map(|b| (b as f32) / 255.0);
    Rgba { r, g, b, a }
}

/// Swap from RGBA with premultiplied alpha to BGRA
pub fn swap_rgba_pa_to_bgra(color: &mut [u8]) {
    color.swap(0, 2);
    if color[3] > 0 {
        let a = color[3] as f32 / 255.;
        color[0] = (color[0] as f32 / a) as u8;
        color[1] = (color[1] as f32 / a) as u8;
        color[2] = (color[2] as f32 / a) as u8;
    }
}

/// An RGBA color
#[derive(PartialEq, Clone, Copy, Default)]
#[repr(C)]
pub struct Rgba {
    /// The red component of the color, in the range 0.0 to 1.0
    pub r: f32,
    /// The green component of the color, in the range 0.0 to 1.0
    pub g: f32,
    /// The blue component of the color, in the range 0.0 to 1.0
    pub b: f32,
    /// The alpha component of the color, in the range 0.0 to 1.0
    pub a: f32,
}

impl fmt::Debug for Rgba {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "rgba({:#010x})", u32::from(*self))
    }
}

impl Rgba {
    /// Create a new [`Rgba`] color by blending this and another color together
    pub fn blend(&self, other: Rgba) -> Self {
        if other.a >= 1.0 {
            other
        } else if other.a <= 0.0 {
            *self
        } else {
            Rgba {
                r: (self.r * (1.0 - other.a)) + (other.r * other.a),
                g: (self.g * (1.0 - other.a)) + (other.g * other.a),
                b: (self.b * (1.0 - other.a)) + (other.b * other.a),
                a: self.a,
            }
        }
    }

    /// Returns a new RGBA color with the same red, green and blue channels, but
    /// with a new alpha value.
    ///
    /// Example:
    /// ```
    /// use gpui::rgba;
    /// let color = rgba(0xFF0000FF);
    /// let faded = color.alpha(0.25);
    /// assert_eq!(faded.a, 0.25);
    /// ```
    ///
    /// This will return a red color with 25% opacity.
    ///
    /// Example:
    /// ```
    /// use gpui::rgba;
    /// let color = rgba(0x3399FFCC);
    /// let transparent = color.alpha(0.0);
    /// assert_eq!(transparent.a, 0.0);
    /// ```
    ///
    /// This will return the same blue color, fully transparent.
    pub fn alpha(&self, a: f32) -> Self {
        Rgba {
            r: self.r,
            g: self.g,
            b: self.b,
            a: a.clamp(0., 1.),
        }
    }

    /// Returns a new RGBA color with the same red, green, and blue channels,
    /// but with the alpha channel multiplied by the given factor.
    ///
    /// Example:
    /// ```
    /// use gpui::rgba;
    /// let color = rgba(0xFF0000FF); // Fully opaque red
    /// let faded = color.opacity(0.5);
    /// assert_eq!(faded.a, 0.5);
    /// ```
    ///
    /// This will return a red color with 50% opacity.
    ///
    /// Example:
    /// ```
    /// use gpui::rgba;
    /// let color = rgba(0x3399FFCC); // A light blue with 80% opacity
    /// let faded = color.opacity(0.5);
    /// assert!((faded.a - 0.4).abs() < 1e-6);
    /// ```
    ///
    /// This will return the same blue color scaled down to 40% opacity.
    pub fn opacity(&self, factor: f32) -> Self {
        Rgba {
            r: self.r,
            g: self.g,
            b: self.b,
            a: self.a * factor.clamp(0., 1.),
        }
    }
}

impl From<Rgba> for u32 {
    fn from(rgba: Rgba) -> Self {
        let r = (rgba.r * 255.0) as u32;
        let g = (rgba.g * 255.0) as u32;
        let b = (rgba.b * 255.0) as u32;
        let a = (rgba.a * 255.0) as u32;
        (r << 24) | (g << 16) | (b << 8) | a
    }
}

struct RgbaVisitor;

impl Visitor<'_> for RgbaVisitor {
    type Value = Rgba;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a string in the format #rrggbb or #rrggbbaa")
    }

    fn visit_str<E: de::Error>(self, value: &str) -> Result<Rgba, E> {
        Rgba::try_from(value).map_err(E::custom)
    }
}

#[cfg(feature = "schemars")]
impl JsonSchema for Rgba {
    fn schema_name() -> Cow<'static, str> {
        "Rgba".into()
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        json_schema!({
            "type": "string",
            "pattern": "^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$"
        })
    }
}

impl<'de> Deserialize<'de> for Rgba {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_str(RgbaVisitor)
    }
}

impl Serialize for Rgba {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let r = (self.r * 255.0).round() as u8;
        let g = (self.g * 255.0).round() as u8;
        let b = (self.b * 255.0).round() as u8;
        let a = (self.a * 255.0).round() as u8;

        let s = format!("#{r:02x}{g:02x}{b:02x}{a:02x}");
        serializer.serialize_str(&s)
    }
}

impl From<Hsla> for Rgba {
    fn from(color: Hsla) -> Self {
        let h = color.h;
        let s = color.s;
        let l = color.l;

        let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
        let x = c * (1.0 - ((h * 6.0) % 2.0 - 1.0).abs());
        let m = l - c / 2.0;
        let cm = c + m;
        let xm = x + m;

        let (r, g, b) = match (h * 6.0).floor() as i32 {
            0 | 6 => (cm, xm, m),
            1 => (xm, cm, m),
            2 => (m, cm, xm),
            3 => (m, xm, cm),
            4 => (xm, m, cm),
            _ => (cm, m, xm),
        };

        Rgba {
            r: r.clamp(0., 1.),
            g: g.clamp(0., 1.),
            b: b.clamp(0., 1.),
            a: color.a,
        }
    }
}

impl TryFrom<&'_ str> for Rgba {
    type Error = anyhow::Error;

    fn try_from(value: &'_ str) -> Result<Self, Self::Error> {
        const RGB: usize = "rgb".len();
        const RGBA: usize = "rgba".len();
        const RRGGBB: usize = "rrggbb".len();
        const RRGGBBAA: usize = "rrggbbaa".len();

        const EXPECTED_FORMATS: &str = "Expected #rgb, #rgba, #rrggbb, or #rrggbbaa";
        const INVALID_UNICODE: &str = "invalid unicode characters in color";

        let Some(("", hex)) = value.trim().split_once('#') else {
            bail!("invalid RGBA hex color: '{value}'. {EXPECTED_FORMATS}");
        };

        let (r, g, b, a) = match hex.len() {
            RGB | RGBA => {
                let r = u8::from_str_radix(
                    hex.get(0..1).with_context(|| {
                        format!("{INVALID_UNICODE}: r component of #rgb/#rgba for value: '{value}'")
                    })?,
                    16,
                )?;
                let g = u8::from_str_radix(
                    hex.get(1..2).with_context(|| {
                        format!("{INVALID_UNICODE}: g component of #rgb/#rgba for value: '{value}'")
                    })?,
                    16,
                )?;
                let b = u8::from_str_radix(
                    hex.get(2..3).with_context(|| {
                        format!("{INVALID_UNICODE}: b component of #rgb/#rgba for value: '{value}'")
                    })?,
                    16,
                )?;
                let a = if hex.len() == RGBA {
                    u8::from_str_radix(
                        hex.get(3..4).with_context(|| {
                            format!("{INVALID_UNICODE}: a component of #rgba for value: '{value}'")
                        })?,
                        16,
                    )?
                } else {
                    0xf
                };

                /// Duplicates a given hex digit.
                /// E.g., `0xf` -> `0xff`.
                const fn duplicate(value: u8) -> u8 {
                    (value << 4) | value
                }

                (duplicate(r), duplicate(g), duplicate(b), duplicate(a))
            }
            RRGGBB | RRGGBBAA => {
                let r = u8::from_str_radix(
                    hex.get(0..2).with_context(|| {
                        format!(
                            "{}: r component of #rrggbb/#rrggbbaa for value: '{}'",
                            INVALID_UNICODE, value
                        )
                    })?,
                    16,
                )?;
                let g = u8::from_str_radix(
                    hex.get(2..4).with_context(|| {
                        format!(
                            "{INVALID_UNICODE}: g component of #rrggbb/#rrggbbaa for value: '{value}'"
                        )
                    })?,
                    16,
                )?;
                let b = u8::from_str_radix(
                    hex.get(4..6).with_context(|| {
                        format!(
                            "{INVALID_UNICODE}: b component of #rrggbb/#rrggbbaa for value: '{value}'"
                        )
                    })?,
                    16,
                )?;
                let a = if hex.len() == RRGGBBAA {
                    u8::from_str_radix(
                        hex.get(6..8).with_context(|| {
                            format!(
                                "{INVALID_UNICODE}: a component of #rrggbbaa for value: '{value}'"
                            )
                        })?,
                        16,
                    )?
                } else {
                    0xff
                };
                (r, g, b, a)
            }
            _ => bail!("invalid RGBA hex color: '{value}'. {EXPECTED_FORMATS}"),
        };

        Ok(Rgba {
            r: r as f32 / 255.,
            g: g as f32 / 255.,
            b: b as f32 / 255.,
            a: a as f32 / 255.,
        })
    }
}

/// An HSLA color
#[derive(Default, Copy, Clone, Debug)]
#[repr(C)]
pub struct Hsla {
    /// Hue, in a range from 0 to 1
    pub h: f32,

    /// Saturation, in a range from 0 to 1
    pub s: f32,

    /// Lightness, in a range from 0 to 1
    pub l: f32,

    /// Alpha, in a range from 0 to 1
    pub a: f32,
}

#[cfg(feature = "proptest")]
mod property {
    use super::Hsla;
    use proptest::prelude::*;

    impl Hsla {
        /// Proptest [`Strategy`] that produces opaque colors (i.e. alpha = 1).
        ///
        /// For truly arbitrary colors, use the [`Arbitrary`] implementation.
        pub fn opaque_strategy() -> impl Strategy<Value = Self> {
            (0.0f32..=1.0, 0.0f32..=1.0, 0.0f32..=1.0).prop_map(|(h, s, l)| Hsla { h, s, l, a: 1. })
        }
    }

    impl Arbitrary for Hsla {
        type Strategy = BoxedStrategy<Self>;
        type Parameters = ();

        fn arbitrary_with((): Self::Parameters) -> Self::Strategy {
            (0.0f32..=1.0, 0.0f32..=1.0, 0.0f32..=1.0, 0.0f32..=1.0)
                .prop_map(|(h, s, l, a)| Hsla { h, s, l, a })
                .boxed()
        }
    }
}

impl PartialEq for Hsla {
    fn eq(&self, other: &Self) -> bool {
        self.h
            .total_cmp(&other.h)
            .then(self.s.total_cmp(&other.s))
            .then(self.l.total_cmp(&other.l).then(self.a.total_cmp(&other.a)))
            .is_eq()
    }
}

impl PartialOrd for Hsla {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Hsla {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.h
            .total_cmp(&other.h)
            .then(self.s.total_cmp(&other.s))
            .then(self.l.total_cmp(&other.l).then(self.a.total_cmp(&other.a)))
    }
}

impl Eq for Hsla {}

impl Hash for Hsla {
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write_u32(u32::from_be_bytes(self.h.to_be_bytes()));
        state.write_u32(u32::from_be_bytes(self.s.to_be_bytes()));
        state.write_u32(u32::from_be_bytes(self.l.to_be_bytes()));
        state.write_u32(u32::from_be_bytes(self.a.to_be_bytes()));
    }
}

impl Display for Hsla {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "hsla({:.2}, {:.2}%, {:.2}%, {:.2})",
            self.h * 360.,
            self.s * 100.,
            self.l * 100.,
            self.a
        )
    }
}

/// Construct an [`Hsla`] object from plain values
pub const fn hsla(h: f32, s: f32, l: f32, a: f32) -> Hsla {
    Hsla {
        h: h.clamp(0., 1.),
        s: s.clamp(0., 1.),
        l: l.clamp(0., 1.),
        a: a.clamp(0., 1.),
    }
}

/// Pure black in [`Hsla`]
pub const fn black() -> Hsla {
    Hsla {
        h: 0.,
        s: 0.,
        l: 0.,
        a: 1.,
    }
}

/// Transparent black in [`Hsla`]
pub const fn transparent_black() -> Hsla {
    Hsla {
        h: 0.,
        s: 0.,
        l: 0.,
        a: 0.,
    }
}

/// Transparent white in [`Hsla`]
pub const fn transparent_white() -> Hsla {
    Hsla {
        h: 0.,
        s: 0.,
        l: 1.,
        a: 0.,
    }
}

/// Opaque grey in [`Hsla`], values will be clamped to the range [0, 1]
pub const fn opaque_grey(lightness: f32, opacity: f32) -> Hsla {
    Hsla {
        h: 0.,
        s: 0.,
        l: lightness.clamp(0., 1.),
        a: opacity.clamp(0., 1.),
    }
}

/// Pure white in [`Hsla`]
pub const fn white() -> Hsla {
    Hsla {
        h: 0.,
        s: 0.,
        l: 1.,
        a: 1.,
    }
}

/// The color red in [`Hsla`]
pub const fn red() -> Hsla {
    Hsla {
        h: 0.,
        s: 1.,
        l: 0.5,
        a: 1.,
    }
}

/// The color blue in [`Hsla`]
pub const fn blue() -> Hsla {
    Hsla {
        h: 0.6666666667,
        s: 1.,
        l: 0.5,
        a: 1.,
    }
}

/// The color green in [`Hsla`]
pub const fn green() -> Hsla {
    Hsla {
        h: 0.3333333333,
        s: 1.,
        l: 0.25,
        a: 1.,
    }
}

/// The color yellow in [`Hsla`]
pub const fn yellow() -> Hsla {
    Hsla {
        h: 0.1666666667,
        s: 1.,
        l: 0.5,
        a: 1.,
    }
}

impl Hsla {
    /// Converts this HSLA color to an RGBA color.
    pub fn to_rgb(self) -> Rgba {
        self.into()
    }

    /// The color red
    pub const fn red() -> Self {
        red()
    }

    /// The color green
    pub const fn green() -> Self {
        green()
    }

    /// The color blue
    pub const fn blue() -> Self {
        blue()
    }

    /// The color black
    pub const fn black() -> Self {
        black()
    }

    /// The color white
    pub const fn white() -> Self {
        white()
    }

    /// The color transparent black
    pub const fn transparent_black() -> Self {
        transparent_black()
    }

    /// Returns true if the HSLA color is fully transparent, false otherwise.
    pub fn is_transparent(&self) -> bool {
        self.a == 0.0
    }

    /// Returns true if the HSLA color is fully opaque, false otherwise.
    pub fn is_opaque(&self) -> bool {
        self.a == 1.0
    }

    /// Blends `other` on top of `self` based on `other`'s alpha value. The resulting color is a combination of `self`'s and `other`'s colors.
    ///
    /// If `other`'s alpha value is 1.0 or greater, `other` color is fully opaque, thus `other` is returned as the output color.
    /// If `other`'s alpha value is 0.0 or less, `other` color is fully transparent, thus `self` is returned as the output color.
    /// Else, the output color is calculated as a blend of `self` and `other` based on their weighted alpha values.
    ///
    /// Assumptions:
    /// - Alpha values are contained in the range [0, 1], with 1 as fully opaque and 0 as fully transparent.
    /// - The relative contributions of `self` and `other` is based on `self`'s alpha value (`self.a`) and `other`'s  alpha value (`other.a`), `self` contributing `self.a * (1.0 - other.a)` and `other` contributing its own alpha value.
    /// - RGB color components are contained in the range [0, 1].
    /// - If `self` and `other` colors are out of the valid range, the blend operation's output and behavior is undefined.
    pub fn blend(self, other: Hsla) -> Hsla {
        let alpha = other.a;

        if alpha >= 1.0 {
            other
        } else if alpha <= 0.0 {
            self
        } else {
            let converted_self = Rgba::from(self);
            let converted_other = Rgba::from(other);
            let blended_rgb = converted_self.blend(converted_other);
            Hsla::from(blended_rgb)
        }
    }

    /// Returns a new HSLA color with the same hue, and lightness, but with no saturation.
    pub fn grayscale(&self) -> Self {
        Hsla {
            h: self.h,
            s: 0.,
            l: self.l,
            a: self.a,
        }
    }

    /// Fade out the color by a given factor. This factor should be between 0.0 and 1.0.
    /// Where 0.0 will leave the color unchanged, and 1.0 will completely fade out the color.
    pub fn fade_out(&mut self, factor: f32) {
        self.a *= 1.0 - factor.clamp(0., 1.);
    }

    /// Multiplies the alpha value of the color by a given factor
    /// and returns a new HSLA color.
    ///
    /// Useful for transforming colors with dynamic opacity,
    /// like a color from an external source.
    ///
    /// Example:
    /// ```
    /// let color = gpui::red();
    /// let faded_color = color.opacity(0.5);
    /// assert_eq!(faded_color.a, 0.5);
    /// ```
    ///
    /// This will return a red color with half the opacity.
    ///
    /// Example:
    /// ```
    /// use gpui::hsla;
    /// let color = hsla(0.7, 1.0, 0.5, 0.7); // A saturated blue
    /// let faded_color = color.opacity(0.16);
    /// assert!((faded_color.a - 0.112).abs() < 1e-6);
    /// ```
    ///
    /// This will return a blue color with around ~10% opacity,
    /// suitable for an element's hover or selected state.
    ///
    pub fn opacity(&self, factor: f32) -> Self {
        Hsla {
            h: self.h,
            s: self.s,
            l: self.l,
            a: self.a * factor.clamp(0., 1.),
        }
    }

    /// Returns a new HSLA color with the same hue, saturation,
    /// and lightness, but with a new alpha value.
    ///
    /// Example:
    /// ```
    /// let color = gpui::red();
    /// let red_color = color.alpha(0.25);
    /// assert_eq!(red_color.a, 0.25);
    /// ```
    ///
    /// This will return a red color with 25% opacity.
    ///
    /// Example:
    /// ```
    /// use gpui::hsla;
    /// let color = hsla(0.7, 1.0, 0.5, 0.7); // A saturated blue
    /// let faded_color = color.alpha(0.25);
    /// assert_eq!(faded_color.a, 0.25);
    /// ```
    ///
    /// This will return a blue color with 25% opacity.
    pub fn alpha(&self, a: f32) -> Self {
        Hsla {
            h: self.h,
            s: self.s,
            l: self.l,
            a: a.clamp(0., 1.),
        }
    }
}

impl From<Rgba> for Hsla {
    fn from(color: Rgba) -> Self {
        let r = color.r;
        let g = color.g;
        let b = color.b;

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

        let l = (max + min) / 2.0;
        let s = if l == 0.0 || l == 1.0 {
            0.0
        } else if l < 0.5 {
            delta / (2.0 * l)
        } else {
            delta / (2.0 - 2.0 * l)
        };

        let h = if delta == 0.0 {
            0.0
        } else if max == r {
            ((g - b) / delta).rem_euclid(6.0) / 6.0
        } else if max == g {
            ((b - r) / delta + 2.0) / 6.0
        } else {
            ((r - g) / delta + 4.0) / 6.0
        };

        Hsla {
            h,
            s,
            l,
            a: color.a,
        }
    }
}

#[cfg(feature = "schemars")]
impl JsonSchema for Hsla {
    fn schema_name() -> Cow<'static, str> {
        Rgba::schema_name()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        Rgba::json_schema(generator)
    }
}

impl Serialize for Hsla {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        Rgba::from(*self).serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for Hsla {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Rgba::deserialize(deserializer)?.into())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[repr(C)]
pub(crate) enum BackgroundTag {
    Solid = 0,
    LinearGradient = 1,
    PatternSlash = 2,
    Checkerboard = 3,
    RadialGradient = 4,
    ConicGradient = 5,
}

/// How many colour stops a gradient [`Background`] carries inline.
///
/// The stops live IN the `Background` rather than behind an index into a side
/// buffer, because a side buffer would need a second binding on DirectX, a
/// second storage buffer on wgpu, a second `[[buffer(n)]]` on Metal and — the
/// expensive one — a second instance TEXTURE on WebGL2, where instance data is
/// unpacked by hand. Eight is the smallest power of two that covers everything
/// real CSS in this tree asks for (the widest is a seven-stop hue wheel), and
/// a caller with more stops splits the gradient into layered bands instead
/// (`vn_css`'s `gradient_layers`), which is exact rather than approximate.
pub const GRADIENT_STOPS: usize = 8;

/// `Background::flags` — the ramp restarts every period instead of clamping at
/// the ends (`repeating-linear-gradient()` and friends).
pub(crate) const BG_REPEATING: u32 = 1 << 0;
/// `Background::flags` — `tile` holds a `background-size` / `background-position`
/// pair, and the gradient is evaluated in TILE space rather than box space.
pub(crate) const BG_TILED: u32 = 1 << 1;
/// `Background::flags` — `gradient_angle_or_pattern_height` holds a CORNER index
/// (0 = to top right, 1 = to bottom right, 2 = to bottom left, 3 = to top left)
/// rather than an angle. CSS aims a corner gradient's line at the actual corner,
/// so the angle depends on the box's aspect ratio, which only the shader knows.
pub(crate) const BG_CORNER: u32 = 1 << 2;
/// `Background::flags` — with [`BG_TILED`], the tile does NOT repeat along x
/// (`background-repeat: no-repeat` / `repeat-y`): everything outside the one
/// tile is transparent rather than another copy of it.
pub(crate) const BG_NO_REPEAT_X: u32 = 1 << 3;
/// `Background::flags` — as [`BG_NO_REPEAT_X`], along y.
pub(crate) const BG_NO_REPEAT_Y: u32 = 1 << 4;
/// `Background::flags` — `params[0..2]` is an offset in PIXELS from the box's
/// top left corner rather than a fraction of the box.
pub(crate) const BG_CENTER_PX: u32 = 1 << 5;
/// `Background::flags` — `params[2..4]` is a pair of radii in PIXELS rather
/// than fractions of the box.
pub(crate) const BG_RADIUS_PX: u32 = 1 << 6;
/// `Background::flags` — the tile's WIDTH is a fraction of the box's rather
/// than a length (`background-size: 50% …`).
pub(crate) const BG_TILE_W_FRACTION: u32 = 1 << 7;
/// `Background::flags` — as [`BG_TILE_W_FRACTION`], for the tile's height.
pub(crate) const BG_TILE_H_FRACTION: u32 = 1 << 8;
/// `Background::flags` — the tile's x OFFSET is a fraction of the space the
/// tile leaves in the box, which is how CSS defines a percentage
/// `background-position` (`50%` centres the tile, it does not move it by half
/// the box).
pub(crate) const BG_TILE_X_FRACTION: u32 = 1 << 9;
/// `Background::flags` — as [`BG_TILE_X_FRACTION`], for the y offset.
pub(crate) const BG_TILE_Y_FRACTION: u32 = 1 << 10;
/// `Background::flags` (vue-native fork) — paint this background only in the
/// quad's BORDER area, the ring between the outer edge and the inner edge the
/// border widths make. Inside the inner edge the quad is transparent. The
/// border colour still blends over the ring. This is what [`Style::vn_mask_ring`]
/// paints with: the quad's border widths are the element's border plus its
/// padding, so the ring is the padding and border area, and the content box
/// stays empty.
///
/// [`Style::vn_mask_ring`]: crate::Style::vn_mask_ring
pub(crate) const BG_RING: u32 = 1 << 11;
/// `Background::flags` — bit `BG_STOP_PX_SHIFT + i` marks stop `i`'s
/// `percentage` as an ABSOLUTE length in pixels along the gradient line rather
/// than a fraction of it. `linear-gradient(white 1px, transparent 1px)` — the
/// hard-stop idiom every CSS grid pattern is built from — has no percentage
/// form, and the gradient line's length is a shader-side quantity.
pub(crate) const BG_STOP_PX_SHIFT: u32 = 16;
/// `Background::flags` — bit `BG_STOP_CALC_SHIFT + i` marks stop `i`'s
/// `percentage` as two packed halves, a fraction of the gradient line (high)
/// plus a length in pixels (low): `calc(100% - 20px)`.
pub(crate) const BG_STOP_CALC_SHIFT: u32 = 24;

/// `v` as IEEE half-precision bits, rounded to nearest even; out-of-range
/// values clamp to the largest finite half.
fn f16_bits(v: f32) -> u16 {
    let x = v.to_bits();
    let sign = ((x >> 16) & 0x8000) as u16;
    let exp = ((x >> 23) & 0xff) as i32 - 127 + 15;
    let man = x & 0x7f_ffff;
    let round = |bits: u32, shift: u32| {
        let kept = bits >> shift;
        let rest = bits & ((1 << shift) - 1);
        let mid = 1 << (shift - 1);
        if rest > mid || (rest == mid && kept & 1 == 1) {
            kept + 1
        } else {
            kept
        }
    };
    if !v.is_finite() || exp >= 31 {
        return sign | 0x7bff;
    }
    if exp <= 0 {
        if exp < -10 {
            return sign;
        }
        return sign | round(man | 0x80_0000, (14 - exp) as u32) as u16;
    }
    sign | round(((exp as u32) << 23) | man, 13).min(0x7bff) as u16
}

/// A color space for color interpolation.
///
/// References:
/// - <https://developer.mozilla.org/en-US/docs/Web/CSS/color-interpolation-method>
/// - <https://www.w3.org/TR/css-color-4/#typedef-color-space>
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[repr(C)]
pub enum ColorSpace {
    #[default]
    /// The sRGB color space.
    Srgb = 0,
    /// The Oklab color space.
    Oklab = 1,
}

impl Display for ColorSpace {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ColorSpace::Srgb => write!(f, "sRGB"),
            ColorSpace::Oklab => write!(f, "Oklab"),
        }
    }
}

/// A background: a solid colour, one of the two procedural patterns, or a
/// linear / radial / conic gradient of up to [`GRADIENT_STOPS`] stops,
/// optionally repeating and optionally tiled across the box.
///
/// The layout is the GPU layout — see the `Quad` word map in `scene.rs` and the
/// hand-mirrored `struct Background` in each backend's shader. Adding a field
/// here is a six-file change; the checklist is on `Quad`.
#[derive(Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[repr(C)]
pub struct Background {
    pub(crate) tag: BackgroundTag,
    pub(crate) color_space: ColorSpace,
    pub(crate) solid: Hsla,
    /// The gradient line's angle in degrees for a linear gradient (or a corner
    /// index when [`BG_CORNER`] is set), the start angle for a conic gradient,
    /// and the pattern period for the two procedural tags.
    pub(crate) gradient_angle_or_pattern_height: f32,
    pub(crate) colors: [LinearColorStop; GRADIENT_STOPS],
    /// How many of `colors` are live. Zero for a non-gradient tag.
    pub(crate) stop_count: u32,
    /// `BG_*` bits above.
    pub(crate) flags: u32,
    /// Radial: `[cx, cy, rx, ry]`. The centre is a FRACTION of the box; the
    /// radii are fractions too when `rx >= 0`, and when `rx < 0` the pair is an
    /// extent keyword instead — `-rx` is 1 `closest-side`, 2 `farthest-side`,
    /// 3 `closest-corner`, 4 `farthest-corner`, and `ry` is 0 for a circle and
    /// 1 for an ellipse. Conic: `[cx, cy, _, _]`. Unused otherwise.
    pub(crate) params: [f32; 4],
    /// `[width, height, offset_x, offset_y]` in pixels when [`BG_TILED`] is
    /// set: `background-size` and `background-position`.
    pub(crate) tile: [f32; 4],
}

impl std::fmt::Debug for Background {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let stops = &self.colors[..(self.stop_count as usize).min(GRADIENT_STOPS)];
        match self.tag {
            BackgroundTag::Solid => write!(f, "Solid({:?})", self.solid),
            BackgroundTag::LinearGradient => write!(
                f,
                "LinearGradient({}, {:?}, flags {:#x}, tile {:?})",
                self.gradient_angle_or_pattern_height, stops, self.flags, self.tile
            ),
            BackgroundTag::RadialGradient => write!(
                f,
                "RadialGradient({:?}, {:?}, flags {:#x}, tile {:?})",
                self.params, stops, self.flags, self.tile
            ),
            BackgroundTag::ConicGradient => write!(
                f,
                "ConicGradient({}, {:?}, {:?}, flags {:#x}, tile {:?})",
                self.gradient_angle_or_pattern_height, self.params, stops, self.flags, self.tile
            ),
            BackgroundTag::PatternSlash => write!(
                f,
                "PatternSlash({:?}, {})",
                self.solid, self.gradient_angle_or_pattern_height
            ),
            BackgroundTag::Checkerboard => write!(
                f,
                "Checkerboard({:?}, {})",
                self.solid, self.gradient_angle_or_pattern_height
            ),
        }
    }
}

impl Eq for Background {}
impl Default for Background {
    fn default() -> Self {
        Self {
            tag: BackgroundTag::Solid,
            solid: Hsla::default(),
            color_space: ColorSpace::default(),
            gradient_angle_or_pattern_height: 0.0,
            colors: [LinearColorStop::default(); GRADIENT_STOPS],
            stop_count: 0,
            flags: 0,
            params: [0.0; 4],
            tile: [0.0; 4],
        }
    }
}

/// Creates a hash pattern background
pub fn pattern_slash(color: impl Into<Hsla>, width: f32, interval: f32) -> Background {
    let width_scaled = (width * 255.0) as u32;
    let interval_scaled = (interval * 255.0) as u32;
    let height = ((width_scaled * 0xFFFF) + interval_scaled) as f32;

    Background {
        tag: BackgroundTag::PatternSlash,
        solid: color.into(),
        gradient_angle_or_pattern_height: height,
        ..Default::default()
    }
}

/// Creates a checkerboard pattern background
pub fn checkerboard(color: impl Into<Hsla>, size: f32) -> Background {
    Background {
        tag: BackgroundTag::Checkerboard,
        solid: color.into(),
        gradient_angle_or_pattern_height: size,
        ..Default::default()
    }
}

/// Creates a solid background color.
pub fn solid_background(color: impl Into<Hsla>) -> Background {
    Background {
        solid: color.into(),
        ..Default::default()
    }
}

/// Creates a LinearGradient background color.
///
/// The gradient line's angle of direction. A value of `0.` is equivalent to top; increasing values rotate clockwise from there.
///
/// The `angle` is in degrees value in the range 0.0 to 360.0.
///
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient>
pub fn linear_gradient(
    angle: f32,
    from: impl Into<LinearColorStop>,
    to: impl Into<LinearColorStop>,
) -> Background {
    gradient_with_stops(
        BackgroundTag::LinearGradient,
        angle,
        &[from.into(), to.into()],
    )
}

/// A linear gradient with up to [`GRADIENT_STOPS`] stops. Extra stops are
/// dropped from the middle rather than the ends, so the ramp always starts and
/// finishes on the colours the caller asked for.
pub fn linear_gradient_stops(angle: f32, stops: &[LinearColorStop]) -> Background {
    gradient_with_stops(BackgroundTag::LinearGradient, angle, stops)
}

/// A radial gradient, centred on the box and reaching its farthest corner —
/// CSS's defaults. [`Background::at`], [`Background::with_radii`] and
/// [`Background::with_extent`] change each of those.
pub fn radial_gradient(stops: &[LinearColorStop]) -> Background {
    let mut background = gradient_with_stops(BackgroundTag::RadialGradient, 0.0, stops);
    background.params = [0.5, 0.5, -4.0, 1.0];
    background
}

/// A conic gradient. `from_angle` is in degrees clockwise from twelve o'clock;
/// the centre defaults to the middle of the box.
pub fn conic_gradient(from_angle: f32, stops: &[LinearColorStop]) -> Background {
    let mut background = gradient_with_stops(BackgroundTag::ConicGradient, from_angle, stops);
    background.params = [0.5, 0.5, 0.0, 0.0];
    background
}

fn gradient_with_stops(tag: BackgroundTag, angle: f32, stops: &[LinearColorStop]) -> Background {
    let mut colors = [LinearColorStop::default(); GRADIENT_STOPS];
    let n = stops.len().min(GRADIENT_STOPS);
    if stops.len() <= GRADIENT_STOPS {
        colors[..n].copy_from_slice(&stops[..n]);
    } else {
        // Keep both ends and spread the rest evenly through the middle. A
        // caller that cannot afford the loss splits into bands instead.
        colors[0] = stops[0];
        colors[GRADIENT_STOPS - 1] = stops[stops.len() - 1];
        for (i, slot) in colors[1..GRADIENT_STOPS - 1].iter_mut().enumerate() {
            let t = (i + 1) as f32 / (GRADIENT_STOPS - 1) as f32;
            *slot = stops[((t * (stops.len() - 1) as f32).round() as usize).min(stops.len() - 1)];
        }
    }
    Background {
        tag,
        gradient_angle_or_pattern_height: angle,
        colors,
        stop_count: n as u32,
        ..Default::default()
    }
}

/// A color stop in a linear gradient.
///
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient#linear-color-stop>
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[repr(C)]
pub struct LinearColorStop {
    /// The color of the color stop.
    pub color: Hsla,
    /// The percentage of the gradient, in the range 0.0 to 1.0.
    pub percentage: f32,
}

/// Creates a new linear color stop.
///
/// The percentage of the gradient, in the range 0.0 to 1.0.
pub fn linear_color_stop(color: impl Into<Hsla>, percentage: f32) -> LinearColorStop {
    LinearColorStop {
        color: color.into(),
        percentage,
    }
}

impl LinearColorStop {
    /// Returns a new color stop with the same color, but with a modified alpha value.
    pub fn opacity(&self, factor: f32) -> Self {
        Self {
            percentage: self.percentage,
            color: self.color.opacity(factor),
        }
    }
}

impl Background {
    /// Returns the solid color if this is a solid background, None otherwise.
    pub fn as_solid(&self) -> Option<Hsla> {
        if self.tag == BackgroundTag::Solid {
            Some(self.solid)
        } else {
            None
        }
    }

    /// vue-native fork: this background, painted only in the border area of
    /// the quad it fills ([`BG_RING`]).
    pub(crate) fn ring(mut self) -> Self {
        self.flags |= BG_RING;
        self
    }

    /// vue-native fork: whether this is a [`Self::ring`] background.
    pub(crate) fn is_ring(&self) -> bool {
        self.flags & BG_RING != 0
    }

    /// Use specified color space for color interpolation.
    ///
    /// <https://developer.mozilla.org/en-US/docs/Web/CSS/color-interpolation-method>
    pub fn color_space(mut self, color_space: ColorSpace) -> Self {
        self.color_space = color_space;
        self
    }

    /// Returns a new background color with the same hue, saturation, and lightness, but with a modified alpha value.
    pub fn opacity(&self, factor: f32) -> Self {
        let mut background = *self;
        background.solid = background.solid.opacity(factor);
        for stop in &mut background.colors {
            *stop = stop.opacity(factor);
        }
        background
    }

    /// Returns whether the background color is transparent.
    pub fn is_transparent(&self) -> bool {
        match self.tag {
            BackgroundTag::Solid | BackgroundTag::PatternSlash | BackgroundTag::Checkerboard => {
                self.solid.is_transparent()
            }
            BackgroundTag::LinearGradient
            | BackgroundTag::RadialGradient
            | BackgroundTag::ConicGradient => self.live_stops()
                .iter()
                .all(|c| c.color.is_transparent()),
        }
    }

    /// The stops that actually take part in the ramp.
    pub fn live_stops(&self) -> &[LinearColorStop] {
        &self.colors[..(self.stop_count as usize).min(GRADIENT_STOPS)]
    }

    /// Restarts the ramp every period instead of clamping at the ends —
    /// `repeating-linear-gradient()` and its radial and conic siblings.
    pub fn repeating(mut self, on: bool) -> Self {
        set_flag(&mut self.flags, BG_REPEATING, on);
        self
    }

    /// Evaluates the gradient inside one tile and paves the box with copies of
    /// it — CSS's `background-size` + `background-position` +
    /// `background-repeat`.
    ///
    /// Each of the four numbers is a length in pixels unless its `*_fraction`
    /// flag is set, when a SIZE is a fraction of the box and an OFFSET is a
    /// fraction of the space the tile leaves in it (which is what a percentage
    /// `background-position` means). A zero or negative size clears the tiling.
    pub fn tiled(
        mut self,
        size: (f32, f32),
        size_fraction: (bool, bool),
        offset: (f32, f32),
        offset_fraction: (bool, bool),
        repeat: (bool, bool),
    ) -> Self {
        let on = size.0 > 0.0 && size.1 > 0.0;
        set_flag(&mut self.flags, BG_TILED, on);
        set_flag(&mut self.flags, BG_NO_REPEAT_X, on && !repeat.0);
        set_flag(&mut self.flags, BG_NO_REPEAT_Y, on && !repeat.1);
        set_flag(&mut self.flags, BG_TILE_W_FRACTION, on && size_fraction.0);
        set_flag(&mut self.flags, BG_TILE_H_FRACTION, on && size_fraction.1);
        set_flag(&mut self.flags, BG_TILE_X_FRACTION, on && offset_fraction.0);
        set_flag(&mut self.flags, BG_TILE_Y_FRACTION, on && offset_fraction.1);
        self.tile = if on {
            [size.0, size.1, offset.0, offset.1]
        } else {
            [0.0; 4]
        };
        self
    }

    /// Whether this background is painted as a repeated tile.
    pub fn is_tiled(&self) -> bool {
        self.flags & BG_TILED != 0
    }

    /// Aims a linear gradient's line at one of the box's corners the way CSS
    /// does — `0` top right, `1` bottom right, `2` bottom left, `3` top left.
    /// The angle then depends on the box's aspect ratio, so it is resolved in
    /// the shader rather than here.
    pub fn to_corner(mut self, corner: u8) -> Self {
        set_flag(&mut self.flags, BG_CORNER, true);
        self.gradient_angle_or_pattern_height = corner as f32;
        self
    }

    /// Marks stop `index`'s position as an absolute length in pixels along the
    /// gradient line rather than a fraction of it.
    pub fn stop_in_pixels(mut self, index: usize) -> Self {
        if index < GRADIENT_STOPS {
            self.flags |= 1 << (BG_STOP_PX_SHIFT + index as u32);
        }
        self
    }

    /// Places stop `index` at `fraction` of the gradient line plus `pixels`,
    /// both kept at half precision.
    pub fn stop_at_calc(mut self, index: usize, fraction: f32, pixels: f32) -> Self {
        if index < GRADIENT_STOPS {
            let bits = (u32::from(f16_bits(fraction)) << 16) | u32::from(f16_bits(pixels));
            self.colors[index].percentage = f32::from_bits(bits);
            self.flags &= !(1 << (BG_STOP_PX_SHIFT + index as u32));
            self.flags |= 1 << (BG_STOP_CALC_SHIFT + index as u32);
        }
        self
    }

    /// Moves a radial or conic gradient's centre — `at <position>`. The pair is
    /// a fraction of the box unless `in_pixels`, when it is an offset from the
    /// box's top left corner.
    pub fn at(mut self, center: (f32, f32), in_pixels: bool) -> Self {
        self.params[0] = center.0;
        self.params[1] = center.1;
        set_flag(&mut self.flags, BG_CENTER_PX, in_pixels);
        self
    }

    /// Gives a radial gradient explicit radii — a fraction of the box unless
    /// `in_pixels`. Replaces any [`Background::with_extent`].
    pub fn with_radii(mut self, radii: (f32, f32), in_pixels: bool) -> Self {
        self.params[2] = radii.0.max(0.0);
        self.params[3] = radii.1.max(0.0);
        set_flag(&mut self.flags, BG_RADIUS_PX, in_pixels);
        self
    }

    /// Sizes a radial gradient by one of CSS's four extent keywords: `keyword`
    /// is 1 `closest-side`, 2 `farthest-side`, 3 `closest-corner`, 4
    /// `farthest-corner`. Replaces any [`Background::with_radii`].
    pub fn with_extent(mut self, keyword: u8, ellipse: bool) -> Self {
        self.params[2] = -(keyword.clamp(1, 4) as f32);
        self.params[3] = if ellipse { 1.0 } else { 0.0 };
        set_flag(&mut self.flags, BG_RADIUS_PX, false);
        self
    }

    /// Replaces the colour stops, keeping every other property. Stops beyond
    /// [`GRADIENT_STOPS`] are thinned from the middle.
    pub fn with_stops(mut self, stops: &[LinearColorStop]) -> Self {
        let replacement = gradient_with_stops(self.tag, 0.0, stops);
        self.colors = replacement.colors;
        self.stop_count = replacement.stop_count;
        // A stop list is packed together with its units, so any previous
        // per-stop pixel flags belong to the list being replaced.
        self.flags &= !(0xffu32 << BG_STOP_PX_SHIFT) & !(0xffu32 << BG_STOP_CALC_SHIFT);
        self
    }
}

fn set_flag(flags: &mut u32, bit: u32, on: bool) {
    if on {
        *flags |= bit;
    } else {
        *flags &= !bit;
    }
}

impl From<Hsla> for Background {
    fn from(value: Hsla) -> Self {
        Background {
            tag: BackgroundTag::Solid,
            solid: value,
            ..Default::default()
        }
    }
}

impl From<Rgba> for Background {
    fn from(value: Rgba) -> Self {
        Background {
            tag: BackgroundTag::Solid,
            solid: Hsla::from(value),
            ..Default::default()
        }
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn f16_bits_rounds_to_nearest_and_clamps() {
        let cases = [
            (1.0, 0x3c00),
            (0.5, 0x3800),
            (1.0 / 3.0, 0x3555),
            (-200.0, 0xda40),
            (1e-6, 0x0011),
            (70000.0, 0x7bff),
            (-70000.0, 0xfbff),
        ];
        for (value, bits) in cases {
            assert_eq!(f16_bits(value), bits, "{value}");
        }
    }

    #[test]
    fn test_deserialize_three_value_hex_to_rgba() {
        let actual: Rgba = serde_json::from_value(json!("#f09")).unwrap();

        assert_eq!(actual, rgba(0xff0099ff))
    }

    #[test]
    fn test_deserialize_four_value_hex_to_rgba() {
        let actual: Rgba = serde_json::from_value(json!("#f09f")).unwrap();

        assert_eq!(actual, rgba(0xff0099ff))
    }

    #[test]
    fn test_deserialize_six_value_hex_to_rgba() {
        let actual: Rgba = serde_json::from_value(json!("#ff0099")).unwrap();

        assert_eq!(actual, rgba(0xff0099ff))
    }

    #[test]
    fn test_deserialize_eight_value_hex_to_rgba() {
        let actual: Rgba = serde_json::from_value(json!("#ff0099ff")).unwrap();

        assert_eq!(actual, rgba(0xff0099ff))
    }

    #[test]
    fn test_deserialize_eight_value_hex_with_padding_to_rgba() {
        let actual: Rgba = serde_json::from_value(json!(" #f5f5f5ff   ")).unwrap();

        assert_eq!(actual, rgba(0xf5f5f5ff))
    }

    #[test]
    fn test_deserialize_eight_value_hex_with_mixed_case_to_rgba() {
        let actual: Rgba = serde_json::from_value(json!("#DeAdbEeF")).unwrap();

        assert_eq!(actual, rgba(0xdeadbeef))
    }

    #[test]
    fn test_background_solid() {
        let color = Hsla::from(rgba(0xff0099ff));
        let mut background = Background::from(color);
        assert_eq!(background.tag, BackgroundTag::Solid);
        assert_eq!(background.solid, color);

        assert_eq!(background.opacity(0.5).solid, color.opacity(0.5));
        assert!(!background.is_transparent());
        background.solid = hsla(0.0, 0.0, 0.0, 0.0);
        assert!(background.is_transparent());
    }

    #[test]
    fn test_background_linear_gradient() {
        let from = linear_color_stop(rgba(0xff0099ff), 0.0);
        let to = linear_color_stop(rgba(0x00ff99ff), 1.0);
        let background = linear_gradient(90.0, from, to);
        assert_eq!(background.tag, BackgroundTag::LinearGradient);
        assert_eq!(background.colors[0], from);
        assert_eq!(background.colors[1], to);

        assert_eq!(background.opacity(0.5).colors[0], from.opacity(0.5));
        assert_eq!(background.opacity(0.5).colors[1], to.opacity(0.5));
        assert!(!background.is_transparent());
        assert!(background.opacity(0.0).is_transparent());
    }

    #[test]
    fn test_rgba_alpha() {
        let color = Rgba {
            r: 0.2,
            g: 0.6,
            b: 1.0,
            a: 0.8,
        };

        assert_eq!(color.alpha(0.25).a, 0.25);
        assert_eq!(color.alpha(1.5).a, 1.0);
    }

    #[test]
    fn test_rgba_opacity() {
        let color = Rgba {
            r: 0.2,
            g: 0.6,
            b: 1.0,
            a: 0.8,
        };
        assert!((color.opacity(0.5).a - 0.4).abs() < 1e-6);
        assert_eq!(color.opacity(2.0).a, 0.8);
    }
}