forked from servo/rust-cssparser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolor.rs
More file actions
1593 lines (1435 loc) · 48.6 KB
/
color.rs
File metadata and controls
1593 lines (1435 loc) · 48.6 KB
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Allow text like <color> in docs.
#![allow(rustdoc::invalid_html_tags)]
use std::f32::consts::PI;
use std::fmt;
use std::str::FromStr;
use super::{CowRcStr, ParseError, Parser, ToCss, Token};
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
const OPAQUE: f32 = 1.0;
fn serialize_none_or<T>(dest: &mut impl fmt::Write, value: &Option<T>) -> fmt::Result
where
T: ToCss,
{
match value {
Some(v) => v.to_css(dest),
None => dest.write_str("none"),
}
}
/// Serialize the alpha copmonent of a color according to the specification.
/// <https://drafts.csswg.org/css-color-4/#serializing-alpha-values>
#[inline]
pub fn serialize_color_alpha(
dest: &mut impl fmt::Write,
alpha: Option<f32>,
legacy_syntax: bool,
) -> fmt::Result {
let alpha = match alpha {
None => return dest.write_str(" / none"),
Some(a) => a,
};
// If the alpha component is full opaque, don't emit the alpha value in CSS.
if alpha == OPAQUE {
return Ok(());
}
dest.write_str(if legacy_syntax { ", " } else { " / " })?;
// Try first with two decimal places, then with three.
let mut rounded_alpha = (alpha * 100.).round() / 100.;
if clamp_unit_f32(rounded_alpha) != clamp_unit_f32(alpha) {
rounded_alpha = (alpha * 1000.).round() / 1000.;
}
rounded_alpha.to_css(dest)
}
// Guaratees hue in [0..360)
fn normalize_hue(hue: f32) -> f32 {
// <https://drafts.csswg.org/css-values/#angles>
// Subtract an integer before rounding, to avoid some rounding errors:
hue - 360.0 * (hue / 360.0).floor()
}
/// A color with red, green, blue, and alpha components, in a byte each.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct RGBA {
/// The red component.
pub red: Option<u8>,
/// The green component.
pub green: Option<u8>,
/// The blue component.
pub blue: Option<u8>,
/// The alpha component.
pub alpha: Option<f32>,
}
impl RGBA {
/// Constructs a new RGBA value from float components. It expects the red,
/// green, blue and alpha channels in that order, and all values will be
/// clamped to the 0.0 ... 1.0 range.
#[inline]
pub fn from_floats(
red: Option<f32>,
green: Option<f32>,
blue: Option<f32>,
alpha: Option<f32>,
) -> Self {
Self::new(
red.map(clamp_unit_f32),
green.map(clamp_unit_f32),
blue.map(clamp_unit_f32),
alpha.map(|a| a.clamp(0.0, OPAQUE)),
)
}
/// Same thing, but with `u8` values instead of floats in the 0 to 1 range.
#[inline]
pub const fn new(
red: Option<u8>,
green: Option<u8>,
blue: Option<u8>,
alpha: Option<f32>,
) -> Self {
Self {
red,
green,
blue,
alpha,
}
}
}
#[cfg(feature = "serde")]
impl Serialize for RGBA {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(self.red, self.green, self.blue, self.alpha).serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for RGBA {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (r, g, b, a) = Deserialize::deserialize(deserializer)?;
Ok(RGBA::new(r, g, b, a))
}
}
impl ToCss for RGBA {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
let has_alpha = self.alpha.unwrap_or(0.0) != OPAQUE;
dest.write_str(if has_alpha { "rgba(" } else { "rgb(" })?;
self.red.unwrap_or(0).to_css(dest)?;
dest.write_str(", ")?;
self.green.unwrap_or(0).to_css(dest)?;
dest.write_str(", ")?;
self.blue.unwrap_or(0).to_css(dest)?;
// Legacy syntax does not allow none components.
serialize_color_alpha(dest, Some(self.alpha.unwrap_or(0.0)), true)?;
dest.write_char(')')
}
}
/// Color specified by hue, saturation and lightness components.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Hsl {
/// The hue component.
pub hue: Option<f32>,
/// The saturation component.
pub saturation: Option<f32>,
/// The lightness component.
pub lightness: Option<f32>,
/// The alpha component.
pub alpha: Option<f32>,
}
impl Hsl {
/// Construct a new HSL color from it's components.
pub fn new(
hue: Option<f32>,
saturation: Option<f32>,
lightness: Option<f32>,
alpha: Option<f32>,
) -> Self {
Self {
hue,
saturation,
lightness,
alpha,
}
}
}
impl ToCss for Hsl {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
// HSL serializes to RGB, so we have to convert it.
let (red, green, blue) = hsl_to_rgb(
self.hue.unwrap_or(0.0) / 360.0,
self.saturation.unwrap_or(0.0),
self.lightness.unwrap_or(0.0),
);
RGBA::from_floats(Some(red), Some(green), Some(blue), self.alpha).to_css(dest)
}
}
#[cfg(feature = "serde")]
impl Serialize for Hsl {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(self.hue, self.saturation, self.lightness, self.alpha).serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Hsl {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (lightness, a, b, alpha) = Deserialize::deserialize(deserializer)?;
Ok(Self::new(lightness, a, b, alpha))
}
}
/// Color specified by hue, whiteness and blackness components.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Hwb {
/// The hue component.
pub hue: Option<f32>,
/// The whiteness component.
pub whiteness: Option<f32>,
/// The blackness component.
pub blackness: Option<f32>,
/// The alpha component.
pub alpha: Option<f32>,
}
impl Hwb {
/// Construct a new HWB color from it's components.
pub fn new(
hue: Option<f32>,
whiteness: Option<f32>,
blackness: Option<f32>,
alpha: Option<f32>,
) -> Self {
Self {
hue,
whiteness,
blackness,
alpha,
}
}
}
impl ToCss for Hwb {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
// HWB serializes to RGB, so we have to convert it.
let (red, green, blue) = hwb_to_rgb(
self.hue.unwrap_or(0.0) / 360.0,
self.whiteness.unwrap_or(0.0),
self.blackness.unwrap_or(0.0),
);
RGBA::from_floats(Some(red), Some(green), Some(blue), self.alpha).to_css(dest)
}
}
#[cfg(feature = "serde")]
impl Serialize for Hwb {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(self.hue, self.whiteness, self.blackness, self.alpha).serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Hwb {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (lightness, whiteness, blackness, alpha) = Deserialize::deserialize(deserializer)?;
Ok(Self::new(lightness, whiteness, blackness, alpha))
}
}
// NOTE: LAB and OKLAB is not declared inside the [impl_lab_like] macro,
// because it causes cbindgen to ignore them.
/// Color specified by lightness, a- and b-axis components.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Lab {
/// The lightness component.
pub lightness: Option<f32>,
/// The a-axis component.
pub a: Option<f32>,
/// The b-axis component.
pub b: Option<f32>,
/// The alpha component.
pub alpha: Option<f32>,
}
/// Color specified by lightness, a- and b-axis components.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Oklab {
/// The lightness component.
pub lightness: Option<f32>,
/// The a-axis component.
pub a: Option<f32>,
/// The b-axis component.
pub b: Option<f32>,
/// The alpha component.
pub alpha: Option<f32>,
}
macro_rules! impl_lab_like {
($cls:ident, $fname:literal) => {
impl $cls {
/// Construct a new Lab color format with lightness, a, b and alpha components.
pub fn new(
lightness: Option<f32>,
a: Option<f32>,
b: Option<f32>,
alpha: Option<f32>,
) -> Self {
Self {
lightness,
a,
b,
alpha,
}
}
}
#[cfg(feature = "serde")]
impl Serialize for $cls {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(self.lightness, self.a, self.b, self.alpha).serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for $cls {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (lightness, a, b, alpha) = Deserialize::deserialize(deserializer)?;
Ok(Self::new(lightness, a, b, alpha))
}
}
impl ToCss for $cls {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
dest.write_str($fname)?;
dest.write_str("(")?;
serialize_none_or(dest, &self.lightness)?;
dest.write_char(' ')?;
serialize_none_or(dest, &self.a)?;
dest.write_char(' ')?;
serialize_none_or(dest, &self.b)?;
serialize_color_alpha(dest, self.alpha, false)?;
dest.write_char(')')
}
}
};
}
impl_lab_like!(Lab, "lab");
impl_lab_like!(Oklab, "oklab");
// NOTE: LCH and OKLCH is not declared inside the [impl_lch_like] macro,
// because it causes cbindgen to ignore them.
/// Color specified by lightness, chroma and hue components.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Lch {
/// The lightness component.
pub lightness: Option<f32>,
/// The chroma component.
pub chroma: Option<f32>,
/// The hue component.
pub hue: Option<f32>,
/// The alpha component.
pub alpha: Option<f32>,
}
/// Color specified by lightness, chroma and hue components.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Oklch {
/// The lightness component.
pub lightness: Option<f32>,
/// The chroma component.
pub chroma: Option<f32>,
/// The hue component.
pub hue: Option<f32>,
/// The alpha component.
pub alpha: Option<f32>,
}
macro_rules! impl_lch_like {
($cls:ident, $fname:literal) => {
impl $cls {
/// Construct a new color with lightness, chroma and hue components.
pub fn new(
lightness: Option<f32>,
chroma: Option<f32>,
hue: Option<f32>,
alpha: Option<f32>,
) -> Self {
Self {
lightness,
chroma,
hue,
alpha,
}
}
}
#[cfg(feature = "serde")]
impl Serialize for $cls {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(self.lightness, self.chroma, self.hue, self.alpha).serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for $cls {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (lightness, chroma, hue, alpha) = Deserialize::deserialize(deserializer)?;
Ok(Self::new(lightness, chroma, hue, alpha))
}
}
impl ToCss for $cls {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
dest.write_str($fname)?;
dest.write_str("(")?;
serialize_none_or(dest, &self.lightness)?;
dest.write_char(' ')?;
serialize_none_or(dest, &self.chroma)?;
dest.write_char(' ')?;
serialize_none_or(dest, &self.hue)?;
serialize_color_alpha(dest, self.alpha, false)?;
dest.write_char(')')
}
}
};
}
impl_lch_like!(Lch, "lch");
impl_lch_like!(Oklch, "oklch");
/// A Predefined color space specified in:
/// <https://drafts.csswg.org/css-color-4/#predefined>
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum PredefinedColorSpace {
/// <https://drafts.csswg.org/css-color-4/#predefined-sRGB>
Srgb,
/// <https://drafts.csswg.org/css-color-4/#predefined-sRGB-linear>
SrgbLinear,
/// <https://drafts.csswg.org/css-color-4/#predefined-display-p3>
DisplayP3,
/// <https://drafts.csswg.org/css-color-4/#predefined-a98-rgb>
A98Rgb,
/// <https://drafts.csswg.org/css-color-4/#predefined-prophoto-rgb>
ProphotoRgb,
/// <https://drafts.csswg.org/css-color-4/#predefined-rec2020>
Rec2020,
/// <https://drafts.csswg.org/css-color-4/#predefined-xyz>
XyzD50,
/// <https://drafts.csswg.org/css-color-4/#predefined-xyz>
XyzD65,
}
impl PredefinedColorSpace {
/// Returns the string value of the predefined color space.
pub fn as_str(&self) -> &str {
match self {
PredefinedColorSpace::Srgb => "srgb",
PredefinedColorSpace::SrgbLinear => "srgb-linear",
PredefinedColorSpace::DisplayP3 => "display-p3",
PredefinedColorSpace::A98Rgb => "a98-rgb",
PredefinedColorSpace::ProphotoRgb => "prophoto-rgb",
PredefinedColorSpace::Rec2020 => "rec2020",
PredefinedColorSpace::XyzD50 => "xyz-d50",
PredefinedColorSpace::XyzD65 => "xyz-d65",
}
}
}
impl FromStr for PredefinedColorSpace {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match_ignore_ascii_case! { s,
"srgb" => PredefinedColorSpace::Srgb,
"srgb-linear" => PredefinedColorSpace::SrgbLinear,
"display-p3" => PredefinedColorSpace::DisplayP3,
"a98-rgb" => PredefinedColorSpace::A98Rgb,
"prophoto-rgb" => PredefinedColorSpace::ProphotoRgb,
"rec2020" => PredefinedColorSpace::Rec2020,
"xyz-d50" => PredefinedColorSpace::XyzD50,
"xyz" | "xyz-d65" => PredefinedColorSpace::XyzD65,
_ => return Err(()),
})
}
}
impl ToCss for PredefinedColorSpace {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
dest.write_str(self.as_str())
}
}
/// A color specified by the color() function.
/// <https://drafts.csswg.org/css-color-4/#color-function>
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct ColorFunction {
/// The color space for this color.
pub color_space: PredefinedColorSpace,
/// The first component of the color. Either red or x.
pub c1: Option<f32>,
/// The second component of the color. Either green or y.
pub c2: Option<f32>,
/// The third component of the color. Either blue or z.
pub c3: Option<f32>,
/// The alpha component of the color.
pub alpha: Option<f32>,
}
impl ColorFunction {
/// Construct a new color function definition with the given color space and
/// color components.
pub fn new(
color_space: PredefinedColorSpace,
c1: Option<f32>,
c2: Option<f32>,
c3: Option<f32>,
alpha: Option<f32>,
) -> Self {
Self {
color_space,
c1,
c2,
c3,
alpha,
}
}
}
impl ToCss for ColorFunction {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
dest.write_str("color(")?;
self.color_space.to_css(dest)?;
dest.write_char(' ')?;
serialize_none_or(dest, &self.c1)?;
dest.write_char(' ')?;
serialize_none_or(dest, &self.c2)?;
dest.write_char(' ')?;
serialize_none_or(dest, &self.c3)?;
serialize_color_alpha(dest, self.alpha, false)?;
dest.write_char(')')
}
}
/// Describes one of the value <color> values according to the CSS
/// specification.
///
/// Most components are `Option<_>`, so when the value is `None`, that component
/// serializes to the "none" keyword.
///
/// <https://drafts.csswg.org/css-color-4/#color-type>
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Color {
/// The 'currentcolor' keyword.
CurrentColor,
/// Specify sRGB colors directly by their red/green/blue/alpha chanels.
Rgba(RGBA),
/// Specifies a color in sRGB using hue, saturation and lightness components.
Hsl(Hsl),
/// Specifies a color in sRGB using hue, whiteness and blackness components.
Hwb(Hwb),
/// Specifies a CIELAB color by CIE Lightness and its a- and b-axis hue
/// coordinates (red/green-ness, and yellow/blue-ness) using the CIE LAB
/// rectangular coordinate model.
Lab(Lab),
/// Specifies a CIELAB color by CIE Lightness, Chroma, and hue using the
/// CIE LCH cylindrical coordinate model.
Lch(Lch),
/// Specifies an Oklab color by Oklab Lightness and its a- and b-axis hue
/// coordinates (red/green-ness, and yellow/blue-ness) using the Oklab
/// rectangular coordinate model.
Oklab(Oklab),
/// Specifies an Oklab color by Oklab Lightness, Chroma, and hue using
/// the OKLCH cylindrical coordinate model.
Oklch(Oklch),
/// Specifies a color in a predefined color space.
ColorFunction(ColorFunction),
}
impl ToCss for Color {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
match *self {
Color::CurrentColor => dest.write_str("currentcolor"),
Color::Rgba(rgba) => rgba.to_css(dest),
Color::Hsl(hsl) => hsl.to_css(dest),
Color::Hwb(hwb) => hwb.to_css(dest),
Color::Lab(lab) => lab.to_css(dest),
Color::Lch(lch) => lch.to_css(dest),
Color::Oklab(lab) => lab.to_css(dest),
Color::Oklch(lch) => lch.to_css(dest),
Color::ColorFunction(color_function) => color_function.to_css(dest),
}
}
}
/// Either a number or a percentage.
pub enum NumberOrPercentage {
/// `<number>`.
Number {
/// The numeric value parsed, as a float.
value: f32,
},
/// `<percentage>`
Percentage {
/// The value as a float, divided by 100 so that the nominal range is
/// 0.0 to 1.0.
unit_value: f32,
},
}
impl NumberOrPercentage {
fn unit_value(&self) -> f32 {
match *self {
NumberOrPercentage::Number { value } => value,
NumberOrPercentage::Percentage { unit_value } => unit_value,
}
}
fn value(&self, percentage_basis: f32) -> f32 {
match *self {
Self::Number { value } => value,
Self::Percentage { unit_value } => unit_value * percentage_basis,
}
}
}
/// Either an angle or a number.
pub enum AngleOrNumber {
/// `<number>`.
Number {
/// The numeric value parsed, as a float.
value: f32,
},
/// `<angle>`
Angle {
/// The value as a number of degrees.
degrees: f32,
},
}
impl AngleOrNumber {
fn degrees(&self) -> f32 {
match *self {
AngleOrNumber::Number { value } => value,
AngleOrNumber::Angle { degrees } => degrees,
}
}
}
/// A trait that can be used to hook into how `cssparser` parses color
/// components, with the intention of implementing more complicated behavior.
///
/// For example, this is used by Servo to support calc() in color.
pub trait ColorParser<'i> {
/// The type that the parser will construct on a successful parse.
type Output: FromParsedColor;
/// A custom error type that can be returned from the parsing functions.
type Error: 'i;
/// Parse an `<angle>` or `<number>`.
///
/// Returns the result in degrees.
fn parse_angle_or_number<'t>(
&self,
input: &mut Parser<'i, 't>,
) -> Result<AngleOrNumber, ParseError<'i, Self::Error>> {
let location = input.current_source_location();
Ok(match *input.next()? {
Token::Number { value, .. } => AngleOrNumber::Number { value },
Token::Dimension {
value: v, ref unit, ..
} => {
let degrees = match_ignore_ascii_case! { unit,
"deg" => v,
"grad" => v * 360. / 400.,
"rad" => v * 360. / (2. * PI),
"turn" => v * 360.,
_ => {
return Err(location.new_unexpected_token_error(Token::Ident(unit.clone())))
}
};
AngleOrNumber::Angle { degrees }
}
ref t => return Err(location.new_unexpected_token_error(t.clone())),
})
}
/// Parse a `<percentage>` value.
///
/// Returns the result in a number from 0.0 to 1.0.
fn parse_percentage<'t>(
&self,
input: &mut Parser<'i, 't>,
) -> Result<f32, ParseError<'i, Self::Error>> {
input.expect_percentage().map_err(From::from)
}
/// Parse a `<number>` value.
fn parse_number<'t>(
&self,
input: &mut Parser<'i, 't>,
) -> Result<f32, ParseError<'i, Self::Error>> {
input.expect_number().map_err(From::from)
}
/// Parse a `<number>` value or a `<percentage>` value.
fn parse_number_or_percentage<'t>(
&self,
input: &mut Parser<'i, 't>,
) -> Result<NumberOrPercentage, ParseError<'i, Self::Error>> {
let location = input.current_source_location();
Ok(match *input.next()? {
Token::Number { value, .. } => NumberOrPercentage::Number { value },
Token::Percentage { unit_value, .. } => NumberOrPercentage::Percentage { unit_value },
ref t => return Err(location.new_unexpected_token_error(t.clone())),
})
}
}
/// Default implementation of a [`ColorParser`]
pub struct DefaultColorParser;
impl<'i> ColorParser<'i> for DefaultColorParser {
type Output = Color;
type Error = ();
}
impl Color {
/// Parse a <color> value, per CSS Color Module Level 3.
///
/// FIXME(#2) Deprecated CSS2 System Colors are not supported yet.
pub fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Color, ParseError<'i, ()>> {
parse_color_with(&DefaultColorParser, input)
}
}
/// This trait is used by the [`ColorParser`] to construct colors of any type.
pub trait FromParsedColor {
/// Construct a new color from the CSS `currentcolor` keyword.
fn from_current_color() -> Self;
/// Construct a new color from red, green, blue and alpha components.
fn from_rgba(red: Option<u8>, green: Option<u8>, blue: Option<u8>, alpha: Option<f32>) -> Self;
/// Construct a new color from hue, saturation, lightness and alpha components.
fn from_hsl(
hue: Option<f32>,
saturation: Option<f32>,
lightness: Option<f32>,
alpha: Option<f32>,
) -> Self;
/// Construct a new color from hue, blackness, whiteness and alpha components.
fn from_hwb(
hue: Option<f32>,
whiteness: Option<f32>,
blackness: Option<f32>,
alpha: Option<f32>,
) -> Self;
/// Construct a new color from the `lab` notation.
fn from_lab(lightness: Option<f32>, a: Option<f32>, b: Option<f32>, alpha: Option<f32>)
-> Self;
/// Construct a new color from the `lch` notation.
fn from_lch(
lightness: Option<f32>,
chroma: Option<f32>,
hue: Option<f32>,
alpha: Option<f32>,
) -> Self;
/// Construct a new color from the `oklab` notation.
fn from_oklab(
lightness: Option<f32>,
a: Option<f32>,
b: Option<f32>,
alpha: Option<f32>,
) -> Self;
/// Construct a new color from the `oklch` notation.
fn from_oklch(
lightness: Option<f32>,
chroma: Option<f32>,
hue: Option<f32>,
alpha: Option<f32>,
) -> Self;
/// Construct a new color with a predefined color space.
fn from_color_function(
color_space: PredefinedColorSpace,
c1: Option<f32>,
c2: Option<f32>,
c3: Option<f32>,
alpha: Option<f32>,
) -> Self;
}
/// Parse a color hash, without the leading '#' character.
#[inline]
pub fn parse_hash_color<'i, O>(value: &[u8]) -> Result<O, ()>
where
O: FromParsedColor,
{
Ok(match value.len() {
8 => O::from_rgba(
Some(from_hex(value[0])? * 16 + from_hex(value[1])?),
Some(from_hex(value[2])? * 16 + from_hex(value[3])?),
Some(from_hex(value[4])? * 16 + from_hex(value[5])?),
Some((from_hex(value[6])? * 16 + from_hex(value[7])?) as f32 / 255.0),
),
6 => O::from_rgba(
Some(from_hex(value[0])? * 16 + from_hex(value[1])?),
Some(from_hex(value[2])? * 16 + from_hex(value[3])?),
Some(from_hex(value[4])? * 16 + from_hex(value[5])?),
Some(OPAQUE),
),
4 => O::from_rgba(
Some(from_hex(value[0])? * 17),
Some(from_hex(value[1])? * 17),
Some(from_hex(value[2])? * 17),
Some((from_hex(value[3])? * 17) as f32 / 255.0),
),
3 => O::from_rgba(
Some(from_hex(value[0])? * 17),
Some(from_hex(value[1])? * 17),
Some(from_hex(value[2])? * 17),
Some(OPAQUE),
),
_ => return Err(()),
})
}
/// Parse a CSS color using the specified [`ColorParser`] and return a new color
/// value on success.
pub fn parse_color_with<'i, 't, P>(
color_parser: &P,
input: &mut Parser<'i, 't>,
) -> Result<P::Output, ParseError<'i, P::Error>>
where
P: ColorParser<'i>,
{
let location = input.current_source_location();
let token = input.next()?;
match *token {
Token::Hash(ref value) | Token::IDHash(ref value) => parse_hash_color(value.as_bytes()),
Token::Ident(ref value) => parse_color_keyword(value),
Token::Function(ref name) => {
let name = name.clone();
return input.parse_nested_block(|arguments| {
parse_color_function(color_parser, name, arguments)
});
}
_ => Err(()),
}
.map_err(|()| location.new_unexpected_token_error(token.clone()))
}
impl FromParsedColor for Color {
#[inline]
fn from_current_color() -> Self {
Color::CurrentColor
}
#[inline]
fn from_rgba(red: Option<u8>, green: Option<u8>, blue: Option<u8>, alpha: Option<f32>) -> Self {
Color::Rgba(RGBA::new(red, green, blue, alpha))
}
fn from_hsl(
hue: Option<f32>,
saturation: Option<f32>,
lightness: Option<f32>,
alpha: Option<f32>,
) -> Self {
Color::Hsl(Hsl::new(hue, saturation, lightness, alpha))
}
fn from_hwb(
hue: Option<f32>,
blackness: Option<f32>,
whiteness: Option<f32>,
alpha: Option<f32>,
) -> Self {
Color::Hwb(Hwb::new(hue, blackness, whiteness, alpha))
}
#[inline]
fn from_lab(
lightness: Option<f32>,
a: Option<f32>,
b: Option<f32>,
alpha: Option<f32>,
) -> Self {
Color::Lab(Lab::new(lightness, a, b, alpha))
}
#[inline]
fn from_lch(
lightness: Option<f32>,
chroma: Option<f32>,
hue: Option<f32>,
alpha: Option<f32>,
) -> Self {
Color::Lch(Lch::new(lightness, chroma, hue, alpha))
}
#[inline]
fn from_oklab(
lightness: Option<f32>,
a: Option<f32>,
b: Option<f32>,
alpha: Option<f32>,
) -> Self {
Color::Oklab(Oklab::new(lightness, a, b, alpha))
}
#[inline]
fn from_oklch(
lightness: Option<f32>,
chroma: Option<f32>,
hue: Option<f32>,
alpha: Option<f32>,
) -> Self {
Color::Oklch(Oklch::new(lightness, chroma, hue, alpha))
}
#[inline]
fn from_color_function(
color_space: PredefinedColorSpace,
c1: Option<f32>,
c2: Option<f32>,
c3: Option<f32>,
alpha: Option<f32>,
) -> Self {
Color::ColorFunction(ColorFunction::new(color_space, c1, c2, c3, alpha))
}
}
/// Return the named color with the given name.
///
/// Matching is case-insensitive in the ASCII range.
/// CSS escaping (if relevant) should be resolved before calling this function.
/// (For example, the value of an `Ident` token is fine.)
#[inline]
pub fn parse_color_keyword<Output>(ident: &str) -> Result<Output, ()>