style_traits/
lib.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//! This module contains shared types and messages for use by devtools/script.
6//! The traits are here instead of in script so that the devtools crate can be
7//! modified independently of the rest of Servo.
8
9#![crate_name = "style_traits"]
10#![crate_type = "rlib"]
11#![deny(unsafe_code, missing_docs)]
12
13#[macro_use]
14extern crate malloc_size_of_derive;
15#[macro_use]
16extern crate serde;
17#[macro_use]
18extern crate to_shmem_derive;
19#[cfg(feature = "servo")]
20extern crate url;
21
22use bitflags::bitflags;
23use cssparser::{CowRcStr, Token};
24use selectors::parser::SelectorParseErrorKind;
25#[cfg(feature = "servo")]
26use stylo_atoms::Atom;
27
28/// One hardware pixel.
29///
30/// This unit corresponds to the smallest addressable element of the display hardware.
31#[derive(Clone, Copy, Debug)]
32pub enum DevicePixel {}
33
34/// Represents a mobile style pinch zoom factor.
35#[derive(Clone, Copy, Debug, PartialEq)]
36#[cfg_attr(feature = "servo", derive(Deserialize, Serialize, MallocSizeOf))]
37pub struct PinchZoomFactor(f32);
38
39impl PinchZoomFactor {
40    /// Construct a new pinch zoom factor.
41    pub fn new(scale: f32) -> PinchZoomFactor {
42        PinchZoomFactor(scale)
43    }
44
45    /// Get the pinch zoom factor as an untyped float.
46    pub fn get(&self) -> f32 {
47        self.0
48    }
49}
50
51/// One CSS "px" in the coordinate system of the "initial viewport":
52/// <http://www.w3.org/TR/css-device-adapt/#initial-viewport>
53///
54/// `CSSPixel` is equal to `DeviceIndependentPixel` times a "page zoom" factor controlled by the user.  This is
55/// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport
56/// so it still exactly fits the visible area.
57///
58/// At the default zoom level of 100%, one `CSSPixel` is equal to one `DeviceIndependentPixel`.  However, if the
59/// document is zoomed in or out then this scale may be larger or smaller.
60#[derive(Clone, Copy, Debug)]
61pub enum CSSPixel {}
62
63// In summary, the hierarchy of pixel units and the factors to convert from one to the next:
64//
65// DevicePixel
66//   / hidpi_ratio => DeviceIndependentPixel
67//     / desktop_zoom => CSSPixel
68
69pub mod arc_slice;
70pub mod dom;
71pub mod specified_value_info;
72#[macro_use]
73pub mod values;
74pub mod owned_slice;
75pub mod owned_str;
76
77pub use crate::specified_value_info::{CssType, KeywordsCollectFn, SpecifiedValueInfo};
78pub use crate::values::{
79    Comma, CommaWithSpace, CssWriter, OneOrMoreSeparated, Separator, Space, ToCss,
80};
81
82/// The error type for all CSS parsing routines.
83pub type ParseError<'i> = cssparser::ParseError<'i, StyleParseErrorKind<'i>>;
84
85/// Error in property value parsing
86pub type ValueParseError<'i> = cssparser::ParseError<'i, ValueParseErrorKind<'i>>;
87
88#[derive(Clone, Debug, PartialEq)]
89/// Errors that can be encountered while parsing CSS values.
90pub enum StyleParseErrorKind<'i> {
91    /// A bad URL token in a DVB.
92    BadUrlInDeclarationValueBlock(CowRcStr<'i>),
93    /// A bad string token in a DVB.
94    BadStringInDeclarationValueBlock(CowRcStr<'i>),
95    /// Unexpected closing parenthesis in a DVB.
96    UnbalancedCloseParenthesisInDeclarationValueBlock,
97    /// Unexpected closing bracket in a DVB.
98    UnbalancedCloseSquareBracketInDeclarationValueBlock,
99    /// Unexpected closing curly bracket in a DVB.
100    UnbalancedCloseCurlyBracketInDeclarationValueBlock,
101    /// A property declaration value had input remaining after successfully parsing.
102    PropertyDeclarationValueNotExhausted,
103    /// An unexpected dimension token was encountered.
104    UnexpectedDimension(CowRcStr<'i>),
105    /// Missing or invalid media feature name.
106    MediaQueryExpectedFeatureName(CowRcStr<'i>),
107    /// Missing or invalid media feature value.
108    MediaQueryExpectedFeatureValue,
109    /// A media feature range operator was not expected.
110    MediaQueryUnexpectedOperator,
111    /// min- or max- properties must have a value.
112    RangedExpressionWithNoValue,
113    /// A function was encountered that was not expected.
114    UnexpectedFunction(CowRcStr<'i>),
115    /// Error encountered parsing a @property's `syntax` descriptor
116    PropertySyntaxField(PropertySyntaxParseError),
117    /// Error encountered parsing a @property's `inherits` descriptor.
118    ///
119    /// TODO(zrhoffman, bug 1920365): Include the custom property name in error messages.
120    PropertyInheritsField(PropertyInheritsParseError),
121    /// @namespace must be before any rule but @charset and @import
122    UnexpectedNamespaceRule,
123    /// @import must be before any rule but @charset
124    UnexpectedImportRule,
125    /// @import rules are disallowed in the parser.
126    DisallowedImportRule,
127    /// Unexpected @charset rule encountered.
128    UnexpectedCharsetRule,
129    /// The @property `<custom-property-name>` must start with `--`
130    UnexpectedIdent(CowRcStr<'i>),
131    /// A placeholder for many sources of errors that require more specific variants.
132    UnspecifiedError,
133    /// An unexpected token was found within a namespace rule.
134    UnexpectedTokenWithinNamespace(Token<'i>),
135    /// An error was encountered while parsing a property value.
136    ValueError(ValueParseErrorKind<'i>),
137    /// An error was encountered while parsing a selector
138    SelectorError(SelectorParseErrorKind<'i>),
139    /// The property declaration was for an unknown property.
140    UnknownProperty(CowRcStr<'i>),
141    /// The property declaration was for a disabled experimental property.
142    ExperimentalProperty,
143    /// The property declaration contained an invalid color value.
144    InvalidColor(CowRcStr<'i>, Token<'i>),
145    /// The property declaration contained an invalid filter value.
146    InvalidFilter(CowRcStr<'i>, Token<'i>),
147    /// The property declaration contained an invalid value.
148    OtherInvalidValue(CowRcStr<'i>),
149    /// `!important` declarations are disallowed in `@position-try` or keyframes.
150    UnexpectedImportantDeclaration,
151}
152
153impl<'i> From<ValueParseErrorKind<'i>> for StyleParseErrorKind<'i> {
154    fn from(this: ValueParseErrorKind<'i>) -> Self {
155        StyleParseErrorKind::ValueError(this)
156    }
157}
158
159impl<'i> From<SelectorParseErrorKind<'i>> for StyleParseErrorKind<'i> {
160    fn from(this: SelectorParseErrorKind<'i>) -> Self {
161        StyleParseErrorKind::SelectorError(this)
162    }
163}
164
165/// Specific errors that can be encountered while parsing property values.
166#[derive(Clone, Debug, PartialEq)]
167pub enum ValueParseErrorKind<'i> {
168    /// An invalid token was encountered while parsing a color value.
169    InvalidColor(Token<'i>),
170    /// An invalid filter value was encountered.
171    InvalidFilter(Token<'i>),
172}
173
174impl<'i> StyleParseErrorKind<'i> {
175    /// Create an InvalidValue parse error
176    pub fn new_invalid<S>(name: S, value_error: ParseError<'i>) -> ParseError<'i>
177    where
178        S: Into<CowRcStr<'i>>,
179    {
180        let name = name.into();
181        let variant = match value_error.kind {
182            cssparser::ParseErrorKind::Custom(StyleParseErrorKind::ValueError(e)) => match e {
183                ValueParseErrorKind::InvalidColor(token) => {
184                    StyleParseErrorKind::InvalidColor(name, token)
185                },
186                ValueParseErrorKind::InvalidFilter(token) => {
187                    StyleParseErrorKind::InvalidFilter(name, token)
188                },
189            },
190            _ => StyleParseErrorKind::OtherInvalidValue(name),
191        };
192        cssparser::ParseError {
193            kind: cssparser::ParseErrorKind::Custom(variant),
194            location: value_error.location,
195        }
196    }
197}
198
199/// Errors that can be encountered while parsing the @property rule's syntax descriptor.
200#[derive(Clone, Debug, PartialEq)]
201pub enum PropertySyntaxParseError {
202    /// The syntax descriptor is required for the @property rule to be valid; if it’s missing, the
203    /// @property rule is invalid.
204    ///
205    /// <https://drafts.css-houdini.org/css-properties-values-api-1/#ref-for-descdef-property-syntax②>
206    NoSyntax,
207    /// The string's length was 0.
208    EmptyInput,
209    /// A non-whitespace, non-pipe character was fount after parsing a component.
210    ExpectedPipeBetweenComponents,
211    /// The start of an identifier was expected but not found.
212    ///
213    /// <https://drafts.csswg.org/css-syntax-3/#name-start-code-point>
214    InvalidNameStart,
215    /// The name is not a valid `<ident>`.
216    InvalidName,
217    /// The data type name was not closed.
218    ///
219    /// <https://drafts.css-houdini.org/css-properties-values-api-1/#consume-data-type-name>
220    UnclosedDataTypeName,
221    /// The next byte was expected while parsing, but EOF was found instead.
222    UnexpectedEOF,
223    /// The data type is not a supported syntax component name.
224    ///
225    /// <https://drafts.css-houdini.org/css-properties-values-api-1/#supported-names>
226    UnknownDataTypeName,
227}
228
229/// Errors that can be encountered while parsing the @property rule's inherits descriptor.
230#[derive(Clone, Debug, PartialEq)]
231pub enum PropertyInheritsParseError {
232    /// The inherits descriptor is required for the @property rule to be valid; if it’s missing,
233    /// the @property rule is invalid.
234    ///
235    /// <https://drafts.css-houdini.org/css-properties-values-api-1/#ref-for-descdef-property-inherits②>
236    NoInherits,
237
238    /// The inherits descriptor must successfully parse as `true` or `false`.
239    InvalidInherits,
240}
241
242bitflags! {
243    /// The mode to use when parsing values.
244    #[derive(Clone, Copy, Eq, PartialEq)]
245    #[repr(C)]
246    pub struct ParsingMode: u8 {
247        /// In CSS; lengths must have units, except for zero values, where the unit can be omitted.
248        /// <https://www.w3.org/TR/css3-values/#lengths>
249        const DEFAULT = 0;
250        /// In SVG; a coordinate or length value without a unit identifier (e.g., "25") is assumed
251        /// to be in user units (px).
252        /// <https://www.w3.org/TR/SVG/coords.html#Units>
253        const ALLOW_UNITLESS_LENGTH = 1;
254        /// In SVG; out-of-range values are not treated as an error in parsing.
255        /// <https://www.w3.org/TR/SVG/implnote.html#RangeClamping>
256        const ALLOW_ALL_NUMERIC_VALUES = 1 << 1;
257        /// In CSS Properties and Values, the initial value must be computationally
258        /// independent.
259        /// <https://drafts.css-houdini.org/css-properties-values-api-1/#ref-for-computationally-independent%E2%91%A0>
260        const DISALLOW_COMPUTATIONALLY_DEPENDENT = 1 << 2;
261    }
262}
263
264impl ParsingMode {
265    /// Whether the parsing mode allows unitless lengths for non-zero values to be intpreted as px.
266    #[inline]
267    pub fn allows_unitless_lengths(&self) -> bool {
268        self.intersects(ParsingMode::ALLOW_UNITLESS_LENGTH)
269    }
270
271    /// Whether the parsing mode allows all numeric values.
272    #[inline]
273    pub fn allows_all_numeric_values(&self) -> bool {
274        self.intersects(ParsingMode::ALLOW_ALL_NUMERIC_VALUES)
275    }
276
277    /// Whether the parsing mode allows units or functions that are not computationally independent.
278    #[inline]
279    pub fn allows_computational_dependence(&self) -> bool {
280        !self.intersects(ParsingMode::DISALLOW_COMPUTATIONALLY_DEPENDENT)
281    }
282}
283
284#[cfg(feature = "servo")]
285/// Speculatively execute paint code in the worklet thread pool.
286pub trait SpeculativePainter: Send + Sync {
287    /// <https://drafts.css-houdini.org/css-paint-api/#draw-a-paint-image>
288    fn speculatively_draw_a_paint_image(
289        &self,
290        properties: Vec<(Atom, String)>,
291        arguments: Vec<String>,
292    );
293}