Skip to main content

style/values/specified/
effects.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Specified types for CSS values related to effects.
6
7use crate::Zero;
8use crate::derives::*;
9use crate::parser::{Parse, ParserContext};
10use crate::values::computed::Angle as ComputedAngle;
11use crate::values::computed::CSSPixelLength as ComputedCSSPixelLength;
12use crate::values::computed::Filter as ComputedFilter;
13use crate::values::computed::NonNegativeLength as ComputedNonNegativeLength;
14use crate::values::computed::NonNegativeNumber as ComputedNonNegativeNumber;
15use crate::values::computed::Number as ComputedNumber;
16use crate::values::computed::NumberOrPercentage as ComputedNumberOrPercentage;
17use crate::values::computed::ZeroToOneNumber as ComputedZeroToOneNumber;
18use crate::values::computed::effects::BoxShadow as ComputedBoxShadow;
19use crate::values::computed::effects::SimpleShadow as ComputedSimpleShadow;
20#[cfg(feature = "gecko")]
21use crate::values::computed::url::ComputedUrl;
22use crate::values::computed::{Context, ToComputedValue};
23use crate::values::generics::effects::BoxShadow as GenericBoxShadow;
24use crate::values::generics::effects::Filter as GenericFilter;
25use crate::values::generics::effects::SimpleShadow as GenericSimpleShadow;
26use crate::values::generics::{NonNegative, ZeroToOne};
27use crate::values::specified::color::Color;
28use crate::values::specified::length::{Length, NonNegativeLength};
29use crate::values::specified::url::SpecifiedUrl;
30use crate::values::specified::{Angle, NonNegativeNumberOrPercentage, Number, NumberOrPercentage};
31use cssparser::{Parser, match_ignore_ascii_case};
32use style_traits::{ParseError, StyleParseErrorKind};
33
34/// A specified value for a single shadow of the `box-shadow` property.
35pub type BoxShadow =
36    GenericBoxShadow<Option<Color>, Length, Option<NonNegativeLength>, Option<Length>>;
37
38/// A specified value for a single `filter`.
39pub type SpecifiedFilter = GenericFilter<Angle, FilterFactor, Length, SimpleShadow, SpecifiedUrl>;
40
41pub use self::SpecifiedFilter as Filter;
42
43/// The factor for a filter function.
44#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)]
45pub struct FilterFactor(NumberOrPercentage);
46
47impl FilterFactor {
48    fn to_computed_value_without_context(&self) -> Result<ComputedNumberOrPercentage, ()> {
49        self.0.to_computed_value_without_context()
50    }
51}
52
53impl ToComputedValue for FilterFactor {
54    type ComputedValue = ComputedNumber;
55    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
56        self.0.to_computed_value(context).value()
57    }
58    fn from_computed_value(computed: &Self::ComputedValue) -> Self {
59        Self(NumberOrPercentage::Number(Number::new(*computed)))
60    }
61}
62
63/// Clamp the value to 1 if the value is over 100%.
64#[inline]
65fn clamp_to_one(number: NumberOrPercentage) -> NumberOrPercentage {
66    match number {
67        NumberOrPercentage::Percentage(mut percent) => {
68            percent.clamp_to_hundred();
69            NumberOrPercentage::Percentage(percent)
70        },
71        NumberOrPercentage::Number(mut number) => {
72            number.clamp_to_one();
73            NumberOrPercentage::Number(number)
74        },
75    }
76}
77
78type NonNegativeFactor = NonNegative<FilterFactor>;
79impl NonNegativeFactor {
80    fn one() -> Self {
81        Self(FilterFactor(NumberOrPercentage::Number(Number::new(1.))))
82    }
83}
84
85impl Parse for NonNegativeFactor {
86    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
87        Ok(Self(FilterFactor(
88            NonNegativeNumberOrPercentage::parse(context, input)?.0,
89        )))
90    }
91}
92
93type ZeroToOneFactor = ZeroToOne<FilterFactor>;
94impl ZeroToOneFactor {
95    fn one() -> Self {
96        Self(FilterFactor(NumberOrPercentage::Number(Number::new(1.))))
97    }
98}
99
100impl Parse for ZeroToOneFactor {
101    #[inline]
102    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
103        Ok(Self(FilterFactor(clamp_to_one(
104            NumberOrPercentage::parse_non_negative(context, input)?,
105        ))))
106    }
107}
108
109/// A specified value for the `drop-shadow()` filter.
110pub type SimpleShadow = GenericSimpleShadow<Option<Color>, Length, Option<NonNegativeLength>>;
111
112impl Parse for BoxShadow {
113    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
114        let mut lengths = None;
115        let mut color = None;
116        let mut inset = false;
117
118        loop {
119            if !inset
120                && input
121                    .try_parse(|input| input.expect_ident_matching("inset"))
122                    .is_ok()
123            {
124                inset = true;
125                continue;
126            }
127            if lengths.is_none() {
128                let value = input.try_parse::<_, _, ParseError>(|i| {
129                    let horizontal = Length::parse(context, i)?;
130                    let vertical = Length::parse(context, i)?;
131                    let (blur, spread) =
132                        match i.try_parse(|i| Length::parse_non_negative(context, i)) {
133                            Ok(blur) => {
134                                let spread = i.try_parse(|i| Length::parse(context, i)).ok();
135                                (Some(blur.into()), spread)
136                            },
137                            Err(_) => (None, None),
138                        };
139                    Ok((horizontal, vertical, blur, spread))
140                });
141                if let Ok(value) = value {
142                    lengths = Some(value);
143                    continue;
144                }
145            }
146            if color.is_none()
147                && let Ok(value) = input.try_parse(|i| Color::parse(context, i))
148            {
149                color = Some(value);
150                continue;
151            }
152            break;
153        }
154
155        let lengths = lengths.ok_or(ParseError::custom(StyleParseErrorKind::UnspecifiedError))?;
156        Ok(BoxShadow {
157            base: SimpleShadow {
158                color,
159                horizontal: lengths.0,
160                vertical: lengths.1,
161                blur: lengths.2,
162            },
163            spread: lengths.3,
164            inset,
165        })
166    }
167}
168
169impl ToComputedValue for BoxShadow {
170    type ComputedValue = ComputedBoxShadow;
171
172    #[inline]
173    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
174        ComputedBoxShadow {
175            base: self.base.to_computed_value(context),
176            spread: self
177                .spread
178                .as_ref()
179                .unwrap_or(&Length::zero())
180                .to_computed_value(context),
181            inset: self.inset,
182        }
183    }
184
185    #[inline]
186    fn from_computed_value(computed: &ComputedBoxShadow) -> Self {
187        BoxShadow {
188            base: ToComputedValue::from_computed_value(&computed.base),
189            spread: Some(ToComputedValue::from_computed_value(&computed.spread)),
190            inset: computed.inset,
191        }
192    }
193}
194
195// We need this for converting the specified Filter into computed Filter without Context (for
196// some FFIs in glue.rs). This can fail because in some circumstances, we still need Context to
197// determine the computed value.
198impl Filter {
199    /// Generate the ComputedFilter without Context.
200    pub fn to_computed_value_without_context(&self) -> Result<ComputedFilter, ()> {
201        match *self {
202            Filter::Blur(ref length) => Ok(ComputedFilter::Blur(ComputedNonNegativeLength::new(
203                length.0.to_computed_pixel_length_without_context()?,
204            ))),
205            Filter::Brightness(ref factor) => {
206                Ok(ComputedFilter::Brightness(ComputedNonNegativeNumber::from(
207                    factor.0.to_computed_value_without_context()?.value(),
208                )))
209            },
210            Filter::Contrast(ref factor) => {
211                Ok(ComputedFilter::Contrast(ComputedNonNegativeNumber::from(
212                    factor.0.to_computed_value_without_context()?.value(),
213                )))
214            },
215            Filter::Grayscale(ref factor) => {
216                Ok(ComputedFilter::Grayscale(ComputedZeroToOneNumber::from(
217                    factor.0.to_computed_value_without_context()?.value(),
218                )))
219            },
220            Filter::HueRotate(ref angle) => Ok(ComputedFilter::HueRotate(
221                ComputedAngle::from_degrees(angle.degrees().ok_or(())?),
222            )),
223            Filter::Invert(ref factor) => {
224                Ok(ComputedFilter::Invert(ComputedZeroToOneNumber::from(
225                    factor.0.to_computed_value_without_context()?.value(),
226                )))
227            },
228            Filter::Opacity(ref factor) => {
229                Ok(ComputedFilter::Opacity(ComputedZeroToOneNumber::from(
230                    factor.0.to_computed_value_without_context()?.value(),
231                )))
232            },
233            Filter::Saturate(ref factor) => {
234                Ok(ComputedFilter::Saturate(ComputedNonNegativeNumber::from(
235                    factor.0.to_computed_value_without_context()?.value(),
236                )))
237            },
238            Filter::Sepia(ref factor) => Ok(ComputedFilter::Sepia(ComputedZeroToOneNumber::from(
239                factor.0.to_computed_value_without_context()?.value(),
240            ))),
241            Filter::DropShadow(ref shadow) => {
242                let color = shadow
243                    .color
244                    .as_ref()
245                    .unwrap_or(&Color::currentcolor())
246                    .to_computed_color(None)?;
247
248                let horizontal = ComputedCSSPixelLength::new(
249                    shadow
250                        .horizontal
251                        .to_computed_pixel_length_without_context()?,
252                );
253                let vertical = ComputedCSSPixelLength::new(
254                    shadow.vertical.to_computed_pixel_length_without_context()?,
255                );
256                let blur = ComputedNonNegativeLength::new(
257                    shadow
258                        .blur
259                        .as_ref()
260                        .unwrap_or(&NonNegativeLength::zero())
261                        .0
262                        .to_computed_pixel_length_without_context()?,
263                );
264
265                Ok(ComputedFilter::DropShadow(ComputedSimpleShadow {
266                    color,
267                    horizontal,
268                    vertical,
269                    blur,
270                }))
271            },
272            #[cfg(feature = "gecko")]
273            Filter::Url(ref url) => Ok(ComputedFilter::Url(ComputedUrl(url.clone()))),
274            #[cfg(feature = "servo")]
275            Filter::Url(_) => Err(()),
276        }
277    }
278}
279
280fn svg_filter_url_enabled(_: &ParserContext) -> bool {
281    crate::pref!("layout.css.filter-urls.enabled", gecko = true)
282}
283
284impl Parse for Filter {
285    #[inline]
286    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
287        if svg_filter_url_enabled(context) {
288            if let Ok(url) = input.try_parse(|i| SpecifiedUrl::parse(context, i)) {
289                return Ok(GenericFilter::Url(url));
290            }
291        }
292        let function = {
293            let f = input.expect_function()?;
294            f.clone()
295        };
296        input.parse_nested_block(|i| {
297            match_ignore_ascii_case! { &*function,
298                "blur" => Ok(GenericFilter::Blur(
299                    i.try_parse(|i| NonNegativeLength::parse(context, i))
300                     .unwrap_or(Zero::zero()),
301                )),
302                "brightness" => Ok(GenericFilter::Brightness(
303                    i.try_parse(|i| NonNegativeFactor::parse(context, i))
304                     .unwrap_or(NonNegativeFactor::one()),
305                )),
306                "contrast" => Ok(GenericFilter::Contrast(
307                    i.try_parse(|i| NonNegativeFactor::parse(context, i))
308                     .unwrap_or(NonNegativeFactor::one()),
309                )),
310                "grayscale" => {
311                    // Values of amount over 100% are allowed but UAs must clamp the values to 1.
312                    // https://drafts.fxtf.org/filter-effects/#funcdef-filter-grayscale
313                    Ok(GenericFilter::Grayscale(
314                        i.try_parse(|i| ZeroToOneFactor::parse(context, i))
315                         .unwrap_or(ZeroToOneFactor::one()),
316                    ))
317                },
318                "hue-rotate" => {
319                    // We allow unitless zero here, see:
320                    // https://github.com/w3c/fxtf-drafts/issues/228
321                    Ok(GenericFilter::HueRotate(
322                        i.try_parse(|i| Angle::parse_with_unitless(context, i))
323                         .unwrap_or(Zero::zero()),
324                    ))
325                },
326                "invert" => {
327                    // Values of amount over 100% are allowed but UAs must clamp the values to 1.
328                    // https://drafts.fxtf.org/filter-effects/#funcdef-filter-invert
329                    Ok(GenericFilter::Invert(
330                        i.try_parse(|i| ZeroToOneFactor::parse(context, i))
331                         .unwrap_or(ZeroToOneFactor::one()),
332                    ))
333                },
334                "opacity" => {
335                    // Values of amount over 100% are allowed but UAs must clamp the values to 1.
336                    // https://drafts.fxtf.org/filter-effects/#funcdef-filter-opacity
337                    Ok(GenericFilter::Opacity(
338                        i.try_parse(|i| ZeroToOneFactor::parse(context, i))
339                         .unwrap_or(ZeroToOneFactor::one()),
340                    ))
341                },
342                "saturate" => Ok(GenericFilter::Saturate(
343                    i.try_parse(|i| NonNegativeFactor::parse(context, i))
344                     .unwrap_or(NonNegativeFactor::one()),
345                )),
346                "sepia" => {
347                    // Values of amount over 100% are allowed but UAs must clamp the values to 1.
348                    // https://drafts.fxtf.org/filter-effects/#funcdef-filter-sepia
349                    Ok(GenericFilter::Sepia(
350                        i.try_parse(|i| ZeroToOneFactor::parse(context, i))
351                         .unwrap_or(ZeroToOneFactor::one()),
352                    ))
353                },
354                "drop-shadow" => Ok(GenericFilter::DropShadow(Parse::parse(context, i)?)),
355                _ => Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError)),
356            }
357        })
358    }
359}
360
361impl Parse for SimpleShadow {
362    #[inline]
363    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
364        let color = input.try_parse(|i| Color::parse(context, i)).ok();
365        let horizontal = Length::parse(context, input)?;
366        let vertical = Length::parse(context, input)?;
367        let blur = input
368            .try_parse(|i| Length::parse_non_negative(context, i))
369            .ok();
370        let blur = blur.map(NonNegative::<Length>);
371        let color = color.or_else(|| input.try_parse(|i| Color::parse(context, i)).ok());
372
373        Ok(SimpleShadow {
374            color,
375            horizontal,
376            vertical,
377            blur,
378        })
379    }
380}
381
382impl ToComputedValue for SimpleShadow {
383    type ComputedValue = ComputedSimpleShadow;
384
385    #[inline]
386    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
387        ComputedSimpleShadow {
388            color: self
389                .color
390                .as_ref()
391                .unwrap_or(&Color::currentcolor())
392                .to_computed_value(context),
393            horizontal: self.horizontal.to_computed_value(context),
394            vertical: self.vertical.to_computed_value(context),
395            blur: self
396                .blur
397                .as_ref()
398                .unwrap_or(&NonNegativeLength::zero())
399                .to_computed_value(context),
400        }
401    }
402
403    #[inline]
404    fn from_computed_value(computed: &Self::ComputedValue) -> Self {
405        SimpleShadow {
406            color: Some(ToComputedValue::from_computed_value(&computed.color)),
407            horizontal: ToComputedValue::from_computed_value(&computed.horizontal),
408            vertical: ToComputedValue::from_computed_value(&computed.vertical),
409            blur: Some(ToComputedValue::from_computed_value(&computed.blur)),
410        }
411    }
412}
413
414/// https://drafts.fxtf.org/compositing/#propdef-mix-blend-mode
415#[allow(missing_docs)]
416#[derive(
417    Clone,
418    Copy,
419    Debug,
420    Deserialize,
421    Eq,
422    FromPrimitive,
423    Hash,
424    MallocSizeOf,
425    Parse,
426    PartialEq,
427    Serialize,
428    SpecifiedValueInfo,
429    ToComputedValue,
430    ToCss,
431    ToResolvedValue,
432    ToShmem,
433    ToTyped,
434)]
435#[repr(u8)]
436pub enum Blend {
437    Normal,
438    Multiply,
439    Screen,
440    Overlay,
441    Darken,
442    Lighten,
443    ColorDodge,
444    ColorBurn,
445    HardLight,
446    SoftLight,
447    Difference,
448    Exclusion,
449    Hue,
450    Saturation,
451    Color,
452    Luminosity,
453    PlusLighter,
454}