/* 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/. */ //! Specified values. //! //! TODO(emilio): Enhance docs. use app_units::Au; use context::QuirksMode; use cssparser::{self, Parser, Token}; use euclid::size::Size2D; use itoa; use parser::{ParserContext, Parse}; use self::grid::TrackSizeOrRepeat; use self::url::SpecifiedUrl; use std::ascii::AsciiExt; use std::f32; use std::fmt; use std::io::Write; use style_traits::ToCss; use style_traits::values::specified::AllowedNumericType; use super::{Auto, CSSFloat, CSSInteger, Either, None_}; use super::computed::{self, Context}; use super::computed::{Shadow as ComputedShadow, ToComputedValue}; use super::generics::BorderRadiusSize as GenericBorderRadiusSize; use super::generics::grid::{TrackBreadth as GenericTrackBreadth, TrackSize as GenericTrackSize}; use super::generics::grid::TrackList as GenericTrackList; use values::specified::calc::CalcNode; #[cfg(feature = "gecko")] pub use self::align::{AlignItems, AlignJustifyContent, AlignJustifySelf, JustifyItems}; pub use self::background::BackgroundSize; pub use self::border::{BorderImageSlice, BorderImageWidth, BorderImageWidthSide}; pub use self::color::Color; pub use self::rect::LengthOrNumberRect; pub use super::generics::grid::GridLine; pub use self::image::{ColorStop, EndingShape as GradientEndingShape, Gradient}; pub use self::image::{GradientItem, GradientKind, Image, ImageRect, ImageLayer}; pub use self::length::AbsoluteLength; pub use self::length::{FontRelativeLength, ViewportPercentageLength, CharacterWidth, Length, CalcLengthOrPercentage}; pub use self::length::{Percentage, LengthOrNone, LengthOrNumber, LengthOrPercentage, LengthOrPercentageOrAuto}; pub use self::length::{LengthOrPercentageOrNone, LengthOrPercentageOrAutoOrContent, NoCalcLength}; pub use self::length::{MaxLength, MozLength}; pub use self::position::{Position, PositionComponent}; #[cfg(feature = "gecko")] pub mod align; pub mod background; pub mod basic_shape; pub mod border; pub mod calc; pub mod color; pub mod grid; pub mod image; pub mod length; pub mod position; pub mod rect; /// Common handling for the specified value CSS url() values. pub mod url { use cssparser::Parser; use parser::{Parse, ParserContext}; use values::computed::ComputedValueAsSpecified; #[cfg(feature = "servo")] pub use ::servo::url::*; #[cfg(feature = "gecko")] pub use ::gecko::url::*; impl Parse for SpecifiedUrl { fn parse(context: &ParserContext, input: &mut Parser) -> Result { let url = try!(input.expect_url()); Self::parse_from_string(url, context) } } impl Eq for SpecifiedUrl {} // TODO(emilio): Maybe consider ComputedUrl to save a word in style structs? impl ComputedValueAsSpecified for SpecifiedUrl {} no_viewport_percentage!(SpecifiedUrl); } #[derive(Clone, PartialEq, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[allow(missing_docs)] pub struct CSSColor { pub parsed: Color, pub authored: Option>, } impl Parse for CSSColor { fn parse(context: &ParserContext, input: &mut Parser) -> Result { Self::parse_quirky(context, input, AllowQuirks::No) } } impl CSSColor { /// Parse a color, with quirks. /// /// https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk pub fn parse_quirky(context: &ParserContext, input: &mut Parser, allow_quirks: AllowQuirks) -> Result { let start_position = input.position(); let authored = match input.next() { Ok(Token::Ident(s)) => Some(s.into_owned().into_boxed_str()), _ => None, }; input.reset(start_position); if let Ok(parsed) = input.try(|i| Parse::parse(context, i)) { return Ok(CSSColor { parsed: parsed, authored: authored, }); } if !allow_quirks.allowed(context.quirks_mode) { return Err(()); } let (number, dimension) = match input.next()? { Token::Number(number) => { (number, None) }, Token::Dimension(number, dimension) => { (number, Some(dimension)) }, Token::Ident(ident) => { if ident.len() != 3 && ident.len() != 6 { return Err(()); } return cssparser::Color::parse_hash(ident.as_bytes()).map(|color| { Self { parsed: color.into(), authored: None } }); } _ => { return Err(()); }, }; let value = number.int_value.ok_or(())?; if value < 0 { return Err(()); } let length = if value <= 9 { 1 } else if value <= 99 { 2 } else if value <= 999 { 3 } else if value <= 9999 { 4 } else if value <= 99999 { 5 } else if value <= 999999 { 6 } else { return Err(()) }; let total = length + dimension.as_ref().map_or(0, |d| d.len()); if total > 6 { return Err(()); } let mut serialization = [b'0'; 6]; let space_padding = 6 - total; let mut written = space_padding; written += itoa::write(&mut serialization[written..], value).unwrap(); if let Some(dimension) = dimension { written += (&mut serialization[written..]).write(dimension.as_bytes()).unwrap(); } debug_assert!(written == 6); Ok(CSSColor { parsed: cssparser::Color::parse_hash(&serialization).map(From::from)?, authored: None, }) } } no_viewport_percentage!(CSSColor); impl ToCss for CSSColor { fn to_css(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match self.authored { Some(ref s) => dest.write_str(s), None => self.parsed.to_css(dest), } } } impl From for CSSColor { fn from(color: Color) -> Self { CSSColor { parsed: color, authored: None, } } } impl CSSColor { #[inline] /// Returns currentcolor value. pub fn currentcolor() -> CSSColor { Color::CurrentColor.into() } #[inline] /// Returns transparent value. pub fn transparent() -> CSSColor { // We should probably set authored to "transparent", but maybe it doesn't matter. Color::RGBA(cssparser::RGBA::transparent()).into() } } #[derive(Clone, PartialEq, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[allow(missing_docs)] pub struct CSSRGBA { pub parsed: cssparser::RGBA, pub authored: Option>, } no_viewport_percentage!(CSSRGBA); impl ToCss for CSSRGBA { fn to_css(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match self.authored { Some(ref s) => dest.write_str(s), None => self.parsed.to_css(dest), } } } /// Parse an `` value, handling `calc()` correctly. pub fn parse_integer(context: &ParserContext, input: &mut Parser) -> Result { match try!(input.next()) { Token::Number(ref value) => value.int_value.ok_or(()).map(Integer::new), Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { let result = try!(input.parse_nested_block(|i| { CalcNode::parse_integer(context, i) })); Ok(Integer::from_calc(result)) } _ => Err(()) } } /// Parse a `` value, handling `calc()` correctly, and without length /// limitations. pub fn parse_number(context: &ParserContext, input: &mut Parser) -> Result { parse_number_with_clamping_mode(context, input, AllowedNumericType::All) } /// Parse a `` value, with a given clamping mode. pub fn parse_number_with_clamping_mode(context: &ParserContext, input: &mut Parser, clamping_mode: AllowedNumericType) -> Result { match try!(input.next()) { Token::Number(ref value) if clamping_mode.is_ok(value.value) => { Ok(Number { value: value.value.min(f32::MAX).max(f32::MIN), calc_clamping_mode: None, }) }, Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { let result = try!(input.parse_nested_block(|i| { CalcNode::parse_number(context, i) })); Ok(Number { value: result.min(f32::MAX).max(f32::MIN), calc_clamping_mode: Some(clamping_mode), }) } _ => Err(()) } } /// The specified value of `BorderRadiusSize` pub type BorderRadiusSize = GenericBorderRadiusSize; impl Parse for BorderRadiusSize { #[inline] fn parse(context: &ParserContext, input: &mut Parser) -> Result { let first = try!(LengthOrPercentage::parse_non_negative(context, input)); let second = input.try(|i| LengthOrPercentage::parse_non_negative(context, i)) .unwrap_or_else(|()| first.clone()); Ok(GenericBorderRadiusSize(Size2D::new(first, second))) } } #[derive(Clone, Copy, Debug, HasViewportPercentage, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf, Deserialize, Serialize))] /// An angle consisting of a value and a unit. /// /// Computed Angle is essentially same as specified angle except calc /// value serialization. Therefore we are using computed Angle enum /// to hold the value and unit type. pub struct Angle { value: computed::Angle, was_calc: bool, } impl ToCss for Angle { fn to_css(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { if self.was_calc { dest.write_str("calc(")?; } self.value.to_css(dest)?; if self.was_calc { dest.write_str(")")?; } Ok(()) } } impl ToComputedValue for Angle { type ComputedValue = computed::Angle; fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue { self.value } fn from_computed_value(computed: &Self::ComputedValue) -> Self { Angle { value: *computed, was_calc: false, } } } impl Angle { /// Returns an angle with the given value in degrees. pub fn from_degrees(value: CSSFloat, was_calc: bool) -> Self { Angle { value: computed::Angle::Degree(value), was_calc: was_calc } } /// Returns an angle with the given value in gradians. pub fn from_gradians(value: CSSFloat, was_calc: bool) -> Self { Angle { value: computed::Angle::Gradian(value), was_calc: was_calc } } /// Returns an angle with the given value in turns. pub fn from_turns(value: CSSFloat, was_calc: bool) -> Self { Angle { value: computed::Angle::Turn(value), was_calc: was_calc } } /// Returns an angle with the given value in radians. pub fn from_radians(value: CSSFloat, was_calc: bool) -> Self { Angle { value: computed::Angle::Radian(value), was_calc: was_calc } } #[inline] #[allow(missing_docs)] pub fn radians(self) -> f32 { self.value.radians() } /// Returns an angle value that represents zero. pub fn zero() -> Self { Self::from_degrees(0.0, false) } /// Returns an `Angle` parsed from a `calc()` expression. pub fn from_calc(radians: CSSFloat) -> Self { Angle { value: computed::Angle::Radian(radians), was_calc: true, } } } impl Parse for Angle { /// Parses an angle according to CSS-VALUES § 6.1. fn parse(context: &ParserContext, input: &mut Parser) -> Result { match try!(input.next()) { Token::Dimension(ref value, ref unit) => { Angle::parse_dimension(value.value, unit, /* from_calc = */ false) } Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { input.parse_nested_block(|i| CalcNode::parse_angle(context, i)) } _ => Err(()) } } } impl Angle { /// Parse an `` value given a value and an unit. pub fn parse_dimension( value: CSSFloat, unit: &str, from_calc: bool) -> Result { let angle = match_ignore_ascii_case! { unit, "deg" => Angle::from_degrees(value, from_calc), "grad" => Angle::from_gradians(value, from_calc), "turn" => Angle::from_turns(value, from_calc), "rad" => Angle::from_radians(value, from_calc), _ => return Err(()) }; Ok(angle) } /// Parse an angle, including unitless 0 degree. /// /// Note that numbers without any AngleUnit, including unitless 0 angle, /// should be invalid. However, some properties still accept unitless 0 /// angle and stores it as '0deg'. /// /// We can remove this and get back to the unified version Angle::parse once /// https://github.com/w3c/csswg-drafts/issues/1162 is resolved. pub fn parse_with_unitless(context: &ParserContext, input: &mut Parser) -> Result { match try!(input.next()) { Token::Dimension(ref value, ref unit) => { Angle::parse_dimension(value.value, unit, /* from_calc = */ false) } Token::Number(ref value) if value.value == 0. => Ok(Angle::zero()), Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { input.parse_nested_block(|i| CalcNode::parse_angle(context, i)) } _ => Err(()) } } } #[allow(missing_docs)] pub fn parse_border_radius(context: &ParserContext, input: &mut Parser) -> Result { input.try(|i| BorderRadiusSize::parse(context, i)).or_else(|_| { match_ignore_ascii_case! { &try!(input.expect_ident()), "thin" => Ok(BorderRadiusSize::circle( LengthOrPercentage::Length(NoCalcLength::from_px(1.)))), "medium" => Ok(BorderRadiusSize::circle( LengthOrPercentage::Length(NoCalcLength::from_px(3.)))), "thick" => Ok(BorderRadiusSize::circle( LengthOrPercentage::Length(NoCalcLength::from_px(5.)))), _ => Err(()) } }) } #[allow(missing_docs)] pub fn parse_border_width(context: &ParserContext, input: &mut Parser) -> Result { input.try(|i| Length::parse_non_negative(context, i)).or_else(|()| { match_ignore_ascii_case! { &try!(input.expect_ident()), "thin" => Ok(Length::from_px(1.)), "medium" => Ok(Length::from_px(3.)), "thick" => Ok(Length::from_px(5.)), _ => Err(()) } }) } #[derive(Clone, Debug, HasViewportPercentage, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[allow(missing_docs)] pub enum BorderWidth { Thin, Medium, Thick, Width(Length), } impl Parse for BorderWidth { fn parse(context: &ParserContext, input: &mut Parser) -> Result { Self::parse_quirky(context, input, AllowQuirks::No) } } impl BorderWidth { /// Parses a border width, allowing quirks. pub fn parse_quirky(context: &ParserContext, input: &mut Parser, allow_quirks: AllowQuirks) -> Result { match input.try(|i| Length::parse_non_negative_quirky(context, i, allow_quirks)) { Ok(length) => Ok(BorderWidth::Width(length)), Err(_) => match_ignore_ascii_case! { &try!(input.expect_ident()), "thin" => Ok(BorderWidth::Thin), "medium" => Ok(BorderWidth::Medium), "thick" => Ok(BorderWidth::Thick), _ => Err(()) } } } } impl BorderWidth { #[allow(missing_docs)] pub fn from_length(length: Length) -> Self { BorderWidth::Width(length) } } impl ToCss for BorderWidth { fn to_css(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { BorderWidth::Thin => dest.write_str("thin"), BorderWidth::Medium => dest.write_str("medium"), BorderWidth::Thick => dest.write_str("thick"), BorderWidth::Width(ref length) => length.to_css(dest) } } } impl ToComputedValue for BorderWidth { type ComputedValue = Au; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { // We choose the pixel length of the keyword values the same as both spec and gecko. // Spec: https://drafts.csswg.org/css-backgrounds-3/#line-width // Gecko: https://bugzilla.mozilla.org/show_bug.cgi?id=1312155#c0 match *self { BorderWidth::Thin => Length::from_px(1.).to_computed_value(context), BorderWidth::Medium => Length::from_px(3.).to_computed_value(context), BorderWidth::Thick => Length::from_px(5.).to_computed_value(context), BorderWidth::Width(ref length) => length.to_computed_value(context) } } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { BorderWidth::Width(ToComputedValue::from_computed_value(computed)) } } // The integer values here correspond to the border conflict resolution rules in CSS 2.1 § // 17.6.2.1. Higher values override lower values. define_numbered_css_keyword_enum! { BorderStyle: "none" => none = -1, "solid" => solid = 6, "double" => double = 7, "dotted" => dotted = 4, "dashed" => dashed = 5, "hidden" => hidden = -2, "groove" => groove = 1, "ridge" => ridge = 3, "inset" => inset = 0, "outset" => outset = 2, } no_viewport_percentage!(BorderStyle); impl BorderStyle { /// Whether this border style is either none or hidden. pub fn none_or_hidden(&self) -> bool { matches!(*self, BorderStyle::none | BorderStyle::hidden) } } /// A time in seconds according to CSS-VALUES § 6.2. #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct Time { seconds: CSSFloat, was_calc: bool, } impl Time { /// Return a `