From 14911b96e08c663ad90cff2dd00082ff52417d6a Mon Sep 17 00:00:00 2001 From: Boris Chiou Date: Fri, 7 Sep 2018 22:15:50 +0000 Subject: [PATCH 1/4] style: Make SVGPathData and clip-path: path() animatable. Implement Animate trait for SVGPathData. The basic idea is: we normalize |this| and |other| svg paths, and then do interpolation on the normalized svg paths. The normalization is to convert relative coordinates into absolute coordinates, so we could do real number interpolation on each path command directly. In this patch, we also make |clip-path:path()| animatable. Differential Revision: https://phabricator.services.mozilla.com/D4786 --- components/style/values/animated/mod.rs | 14 ++ components/style/values/distance.rs | 7 + .../style/values/generics/basic_shape.rs | 12 +- components/style/values/specified/svg_path.rs | 146 +++++++++++++++++- 4 files changed, 175 insertions(+), 4 deletions(-) diff --git a/components/style/values/animated/mod.rs b/components/style/values/animated/mod.rs index 53d3719b0213..f09e18861702 100644 --- a/components/style/values/animated/mod.rs +++ b/components/style/values/animated/mod.rs @@ -141,6 +141,20 @@ impl Animate for f64 { } } +/// This is only used in SVG PATH. We return Err(()) if the flags are mismatched. +// FIXME: Bug 653928: If we want to do interpolation on the flags in Arc, we have to update this +// because `absolute`, `large_arc_flag`, and `sweep_flag` are using this implementation for now. +impl Animate for bool { + #[inline] + fn animate(&self, other: &Self, _procedure: Procedure) -> Result { + if *self == *other { + Ok(*other) + } else { + Err(()) + } + } +} + impl Animate for Option where T: Animate, diff --git a/components/style/values/distance.rs b/components/style/values/distance.rs index fbdd4ea00043..07d4c70078f8 100644 --- a/components/style/values/distance.rs +++ b/components/style/values/distance.rs @@ -81,6 +81,13 @@ impl ComputeSquaredDistance for Au { } } +impl ComputeSquaredDistance for bool { + #[inline] + fn compute_squared_distance(&self, other: &Self) -> Result { + (*self as i32).compute_squared_distance(&(*other as i32)) + } +} + impl ComputeSquaredDistance for Option where T: ComputeSquaredDistance, diff --git a/components/style/values/generics/basic_shape.rs b/components/style/values/generics/basic_shape.rs index 0eccf011c716..d2cc98b755d9 100644 --- a/components/style/values/generics/basic_shape.rs +++ b/components/style/values/generics/basic_shape.rs @@ -54,7 +54,6 @@ pub enum ShapeSource { Shape(BasicShape, Option), #[animation(error)] Box(ReferenceBox), - #[animation(error)] #[css(function)] Path(Path), #[animation(error)] @@ -152,10 +151,12 @@ pub enum FillRule { /// /// https://drafts.csswg.org/css-shapes-2/#funcdef-path #[css(comma)] -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive(Animate, Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, + ToComputedValue, ToCss)] pub struct Path { /// The filling rule for the svg path. #[css(skip_if = "fill_is_default")] + #[animation(constant)] pub fill: FillRule, /// The svg path data. pub path: SVGPathData, @@ -177,6 +178,13 @@ where { this.compute_squared_distance(other) }, + ( + &ShapeSource::Path(ref this), + &ShapeSource::Path(ref other), + ) if this.fill == other.fill => + { + this.path.compute_squared_distance(&other.path) + } _ => Err(()), } } diff --git a/components/style/values/specified/svg_path.rs b/components/style/values/specified/svg_path.rs index 48ae185477df..d4583daaad7a 100644 --- a/components/style/values/specified/svg_path.rs +++ b/components/style/values/specified/svg_path.rs @@ -8,10 +8,13 @@ use cssparser::Parser; use parser::{Parse, ParserContext}; use std::fmt::{self, Write}; use std::iter::{Cloned, Peekable}; +use std::ops::AddAssign; use std::slice; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss}; use style_traits::values::SequenceWriter; use values::CSSFloat; +use values::animated::{Animate, Procedure}; +use values::distance::{ComputeSquaredDistance, SquaredDistance}; /// The SVG path data. @@ -34,6 +37,17 @@ impl SVGPathData { debug_assert!(!self.0.is_empty()); &self.0 } + + /// Create a normalized copy of this path by converting each relative command to an absolute + /// command. + fn normalize(&self) -> Self { + let mut state = PathTraversalState { + subpath_start: CoordPair::new(0.0, 0.0), + pos: CoordPair::new(0.0, 0.0), + }; + let result = self.0.iter().map(|seg| seg.normalize(&mut state)).collect::>(); + SVGPathData(result.into_boxed_slice()) + } } impl ToCss for SVGPathData { @@ -82,6 +96,33 @@ impl Parse for SVGPathData { } } +impl Animate for SVGPathData { + fn animate(&self, other: &Self, procedure: Procedure) -> Result { + if self.0.len() != other.0.len() { + return Err(()); + } + + let result = self.normalize().0 + .iter() + .zip(other.normalize().0.iter()) + .map(|(a, b)| a.animate(&b, procedure)) + .collect::, _>>()?; + Ok(SVGPathData::new(result.into_boxed_slice())) + } +} + +impl ComputeSquaredDistance for SVGPathData { + fn compute_squared_distance(&self, other: &Self) -> Result { + if self.0.len() != other.0.len() { + return Err(()); + } + self.normalize().0 + .iter() + .zip(other.normalize().0.iter()) + .map(|(this, other)| this.compute_squared_distance(&other)) + .sum() + } +} /// The SVG path command. /// The fields of these commands are self-explanatory, so we skip the documents. @@ -89,7 +130,8 @@ impl Parse for SVGPathData { /// points of the Bézier curve in the spec. /// /// https://www.w3.org/TR/SVG11/paths.html#PathData -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo)] +#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, + SpecifiedValueInfo)] #[allow(missing_docs)] #[repr(C, u8)] pub enum PathCommand { @@ -126,6 +168,98 @@ pub enum PathCommand { ClosePath, } +/// For internal SVGPath normalization. +#[allow(missing_docs)] +struct PathTraversalState { + subpath_start: CoordPair, + pos: CoordPair, +} + +impl PathCommand { + /// Create a normalized copy of this PathCommand. Absolute commands will be copied as-is while + /// for relative commands an equivalent absolute command will be returned. + /// + /// See discussion: https://github.com/w3c/svgwg/issues/321 + fn normalize(&self, state: &mut PathTraversalState) -> Self { + use self::PathCommand::*; + match *self { + Unknown => Unknown, + ClosePath => { + state.pos = state.subpath_start; + ClosePath + }, + MoveTo { mut point, absolute } => { + if !absolute { + point += state.pos; + } + state.pos = point; + state.subpath_start = point; + MoveTo { point, absolute: true } + }, + LineTo { mut point, absolute } => { + if !absolute { + point += state.pos; + } + state.pos = point; + LineTo { point, absolute: true } + }, + HorizontalLineTo { mut x, absolute } => { + if !absolute { + x += state.pos.0; + } + state.pos.0 = x; + HorizontalLineTo { x, absolute: true } + }, + VerticalLineTo { mut y, absolute } => { + if !absolute { + y += state.pos.1; + } + state.pos.1 = y; + VerticalLineTo { y, absolute: true } + }, + CurveTo { mut control1, mut control2, mut point, absolute } => { + if !absolute { + control1 += state.pos; + control2 += state.pos; + point += state.pos; + } + state.pos = point; + CurveTo { control1, control2, point, absolute: true } + }, + SmoothCurveTo { mut control2, mut point, absolute } => { + if !absolute { + control2 += state.pos; + point += state.pos; + } + state.pos = point; + SmoothCurveTo { control2, point, absolute: true } + }, + QuadBezierCurveTo { mut control1, mut point, absolute } => { + if !absolute { + control1 += state.pos; + point += state.pos; + } + state.pos = point; + QuadBezierCurveTo { control1, point, absolute: true } + }, + SmoothQuadBezierCurveTo { mut point, absolute } => { + if !absolute { + point += state.pos; + } + state.pos = point; + SmoothQuadBezierCurveTo { point, absolute: true } + }, + EllipticalArc { rx, ry, angle, large_arc_flag, sweep_flag, mut point, absolute } => { + if !absolute { + point += state.pos; + } + state.pos = point; + EllipticalArc { rx, ry, angle, large_arc_flag, sweep_flag, point, absolute: true } + }, + } + } +} + impl ToCss for PathCommand { fn to_css(&self, dest: &mut CssWriter) -> fmt::Result where @@ -204,7 +338,8 @@ impl ToCss for PathCommand { /// The path coord type. -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)] +#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, + SpecifiedValueInfo, ToCss)] #[repr(C)] pub struct CoordPair(CSSFloat, CSSFloat); @@ -216,6 +351,13 @@ impl CoordPair { } } +impl AddAssign for CoordPair { + #[inline] + fn add_assign(&mut self, other: Self) { + self.0 += other.0; + self.1 += other.1; + } +} /// SVG Path parser. struct PathParser<'a> { From b0604c9be51b1179ad7008dc4ff2278b9c575af6 Mon Sep 17 00:00:00 2001 From: Boris Chiou Date: Fri, 7 Sep 2018 22:29:12 +0000 Subject: [PATCH 2/4] style: Make offset-path: path() animatable. Here, we change the animation type of offset-path as ComputedValue, so we could do animation on it. Also enable the wpt for offset-path interpolation. In test_transition_per_property.html, we add some basic tests ifor offset-path. ToAnimatedZero for PathCommand will be dropped later. Because the animations of arcs with mismatched flags are fallen back to discrete animations, the result of getComputedValue is not normalized in this case. This makes some wpt failed even though the progress is 100%. Depends on D4786 Differential Revision: https://phabricator.services.mozilla.com/D4787 --- .../style/properties/longhands/box.mako.rs | 2 +- components/style/values/animated/mod.rs | 11 ++++ components/style/values/specified/motion.rs | 4 +- components/style/values/specified/svg_path.rs | 63 ++++++++++++++++++- 4 files changed, 75 insertions(+), 5 deletions(-) diff --git a/components/style/properties/longhands/box.mako.rs b/components/style/properties/longhands/box.mako.rs index 7dfc15cd14e2..ed7839360d97 100644 --- a/components/style/properties/longhands/box.mako.rs +++ b/components/style/properties/longhands/box.mako.rs @@ -379,7 +379,7 @@ ${helpers.predefined_type( "OffsetPath", "computed::OffsetPath::none()", products="gecko", - animation_value_type="none", + animation_value_type="ComputedValue", gecko_pref="layout.css.motion-path.enabled", flags="CREATES_STACKING_CONTEXT FIXPOS_CB", spec="https://drafts.fxtf.org/motion-1/#offset-path-property", diff --git a/components/style/values/animated/mod.rs b/components/style/values/animated/mod.rs index f09e18861702..1d0ccd6904c0 100644 --- a/components/style/values/animated/mod.rs +++ b/components/style/values/animated/mod.rs @@ -406,3 +406,14 @@ where )) } } + +impl ToAnimatedZero for Box<[T]> +where + T: ToAnimatedZero, +{ + #[inline] + fn to_animated_zero(&self) -> Result { + let v = self.iter().map(|v| v.to_animated_zero()).collect::, _>>()?; + Ok(v.into_boxed_slice()) + } +} diff --git a/components/style/values/specified/motion.rs b/components/style/values/specified/motion.rs index 87ff39d9a3ae..762c1dcfdd5f 100644 --- a/components/style/values/specified/motion.rs +++ b/components/style/values/specified/motion.rs @@ -12,7 +12,8 @@ use values::specified::SVGPathData; /// The offset-path value. /// /// https://drafts.fxtf.org/motion-1/#offset-path-property -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, + SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)] pub enum OffsetPath { // We could merge SVGPathData into ShapeSource, so we could reuse them. However, // we don't want to support other value for offset-path, so use SVGPathData only for now. @@ -20,6 +21,7 @@ pub enum OffsetPath { #[css(function)] Path(SVGPathData), /// None value. + #[animation(error)] None, // Bug 1186329: Implement ray(), , , and . } diff --git a/components/style/values/specified/svg_path.rs b/components/style/values/specified/svg_path.rs index d4583daaad7a..d31d182d9413 100644 --- a/components/style/values/specified/svg_path.rs +++ b/components/style/values/specified/svg_path.rs @@ -13,14 +13,15 @@ use std::slice; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss}; use style_traits::values::SequenceWriter; use values::CSSFloat; -use values::animated::{Animate, Procedure}; +use values::animated::{Animate, Procedure, ToAnimatedZero}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; /// The SVG path data. /// /// https://www.w3.org/TR/SVG11/paths.html#PathData -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, + ToComputedValue)] pub struct SVGPathData(Box<[PathCommand]>); impl SVGPathData { @@ -336,10 +337,66 @@ impl ToCss for PathCommand { } } +impl ToAnimatedZero for PathCommand { + #[inline] + fn to_animated_zero(&self) -> Result { + use self::PathCommand::*; + let absolute = true; + match self { + &ClosePath => Ok(ClosePath), + &Unknown => Ok(Unknown), + &MoveTo { ref point, .. } => Ok(MoveTo { point: point.to_animated_zero()?, absolute }), + &LineTo { ref point, .. } => Ok(LineTo { point: point.to_animated_zero()?, absolute }), + &HorizontalLineTo { x, .. } => { + Ok(HorizontalLineTo { x: x.to_animated_zero()?, absolute }) + }, + &VerticalLineTo { y, .. } => { + Ok(VerticalLineTo { y: y.to_animated_zero()?, absolute }) + }, + &CurveTo { ref control1, ref control2, ref point, .. } => { + Ok(CurveTo { + control1: control1.to_animated_zero()?, + control2: control2.to_animated_zero()?, + point: point.to_animated_zero()?, + absolute, + }) + }, + &SmoothCurveTo { ref control2, ref point, .. } => { + Ok(SmoothCurveTo { + control2: control2.to_animated_zero()?, + point: point.to_animated_zero()?, + absolute, + }) + }, + &QuadBezierCurveTo { ref control1, ref point, .. } => { + Ok(QuadBezierCurveTo { + control1: control1.to_animated_zero()?, + point: point.to_animated_zero()?, + absolute, + }) + }, + &SmoothQuadBezierCurveTo { ref point, .. } => { + Ok(SmoothQuadBezierCurveTo { point: point.to_animated_zero()?, absolute }) + }, + &EllipticalArc { rx, ry, angle, large_arc_flag, sweep_flag, ref point, .. } => { + Ok(EllipticalArc { + rx: rx.to_animated_zero()?, + ry: ry.to_animated_zero()?, + angle: angle.to_animated_zero()?, + large_arc_flag, + sweep_flag, + point: point.to_animated_zero()?, + absolute, + }) + }, + } + } +} + /// The path coord type. #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToCss)] + SpecifiedValueInfo, ToAnimatedZero, ToCss)] #[repr(C)] pub struct CoordPair(CSSFloat, CSSFloat); From 31fc6cd565479144b9b0c2d3fff09caad8089df7 Mon Sep 17 00:00:00 2001 From: Boris Chiou Date: Fri, 7 Sep 2018 22:25:59 +0000 Subject: [PATCH 3/4] style: Use the standalone struct and enum for the flags in SVG path. We define the standalone types for using derive macro easily and overriding the behaviors of this traits. This could avoid defining the general behavior of booleans. Depends on D4788 Differential Revision: https://phabricator.services.mozilla.com/D4813 --- components/style/values/animated/mod.rs | 14 -- components/style/values/distance.rs | 7 - components/style/values/specified/svg_path.rs | 210 +++++++++--------- 3 files changed, 101 insertions(+), 130 deletions(-) diff --git a/components/style/values/animated/mod.rs b/components/style/values/animated/mod.rs index 1d0ccd6904c0..24cf40f845e4 100644 --- a/components/style/values/animated/mod.rs +++ b/components/style/values/animated/mod.rs @@ -141,20 +141,6 @@ impl Animate for f64 { } } -/// This is only used in SVG PATH. We return Err(()) if the flags are mismatched. -// FIXME: Bug 653928: If we want to do interpolation on the flags in Arc, we have to update this -// because `absolute`, `large_arc_flag`, and `sweep_flag` are using this implementation for now. -impl Animate for bool { - #[inline] - fn animate(&self, other: &Self, _procedure: Procedure) -> Result { - if *self == *other { - Ok(*other) - } else { - Err(()) - } - } -} - impl Animate for Option where T: Animate, diff --git a/components/style/values/distance.rs b/components/style/values/distance.rs index 07d4c70078f8..fbdd4ea00043 100644 --- a/components/style/values/distance.rs +++ b/components/style/values/distance.rs @@ -81,13 +81,6 @@ impl ComputeSquaredDistance for Au { } } -impl ComputeSquaredDistance for bool { - #[inline] - fn compute_squared_distance(&self, other: &Self) -> Result { - (*self as i32).compute_squared_distance(&(*other as i32)) - } -} - impl ComputeSquaredDistance for Option where T: ComputeSquaredDistance, diff --git a/components/style/values/specified/svg_path.rs b/components/style/values/specified/svg_path.rs index d31d182d9413..490343aa5ce4 100644 --- a/components/style/values/specified/svg_path.rs +++ b/components/style/values/specified/svg_path.rs @@ -13,7 +13,7 @@ use std::slice; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss}; use style_traits::values::SequenceWriter; use values::CSSFloat; -use values::animated::{Animate, Procedure, ToAnimatedZero}; +use values::animated::{Animate, Procedure}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; @@ -132,7 +132,7 @@ impl ComputeSquaredDistance for SVGPathData { /// /// https://www.w3.org/TR/SVG11/paths.html#PathData #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo)] + SpecifiedValueInfo, ToAnimatedZero)] #[allow(missing_docs)] #[repr(C, u8)] pub enum PathCommand { @@ -140,30 +140,32 @@ pub enum PathCommand { /// https://www.w3.org/TR/SVG/paths.html#__svg__SVGPathSeg__PATHSEG_UNKNOWN Unknown, /// The "moveto" command. - MoveTo { point: CoordPair, absolute: bool }, + MoveTo { point: CoordPair, absolute: IsAbsolute }, /// The "lineto" command. - LineTo { point: CoordPair, absolute: bool }, + LineTo { point: CoordPair, absolute: IsAbsolute }, /// The horizontal "lineto" command. - HorizontalLineTo { x: CSSFloat, absolute: bool }, + HorizontalLineTo { x: CSSFloat, absolute: IsAbsolute }, /// The vertical "lineto" command. - VerticalLineTo { y: CSSFloat, absolute: bool }, + VerticalLineTo { y: CSSFloat, absolute: IsAbsolute }, /// The cubic Bézier curve command. - CurveTo { control1: CoordPair, control2: CoordPair, point: CoordPair, absolute: bool }, + CurveTo { control1: CoordPair, control2: CoordPair, point: CoordPair, absolute: IsAbsolute }, /// The smooth curve command. - SmoothCurveTo { control2: CoordPair, point: CoordPair, absolute: bool }, + SmoothCurveTo { control2: CoordPair, point: CoordPair, absolute: IsAbsolute }, /// The quadratic Bézier curve command. - QuadBezierCurveTo { control1: CoordPair, point: CoordPair, absolute: bool }, + QuadBezierCurveTo { control1: CoordPair, point: CoordPair, absolute: IsAbsolute }, /// The smooth quadratic Bézier curve command. - SmoothQuadBezierCurveTo { point: CoordPair, absolute: bool }, + SmoothQuadBezierCurveTo { point: CoordPair, absolute: IsAbsolute }, /// The elliptical arc curve command. EllipticalArc { rx: CSSFloat, ry: CSSFloat, angle: CSSFloat, - large_arc_flag: bool, - sweep_flag: bool, + #[animation(constant)] + large_arc_flag: ArcFlag, + #[animation(constant)] + sweep_flag: ArcFlag, point: CoordPair, - absolute: bool + absolute: IsAbsolute }, /// The "closepath" command. ClosePath, @@ -190,72 +192,74 @@ impl PathCommand { ClosePath }, MoveTo { mut point, absolute } => { - if !absolute { + if !absolute.is_yes() { point += state.pos; } state.pos = point; state.subpath_start = point; - MoveTo { point, absolute: true } + MoveTo { point, absolute: IsAbsolute::Yes } }, LineTo { mut point, absolute } => { - if !absolute { + if !absolute.is_yes() { point += state.pos; } state.pos = point; - LineTo { point, absolute: true } + LineTo { point, absolute: IsAbsolute::Yes } }, HorizontalLineTo { mut x, absolute } => { - if !absolute { + if !absolute.is_yes() { x += state.pos.0; } state.pos.0 = x; - HorizontalLineTo { x, absolute: true } + HorizontalLineTo { x, absolute: IsAbsolute::Yes } }, VerticalLineTo { mut y, absolute } => { - if !absolute { + if !absolute.is_yes() { y += state.pos.1; } state.pos.1 = y; - VerticalLineTo { y, absolute: true } + VerticalLineTo { y, absolute: IsAbsolute::Yes } }, CurveTo { mut control1, mut control2, mut point, absolute } => { - if !absolute { + if !absolute.is_yes() { control1 += state.pos; control2 += state.pos; point += state.pos; } state.pos = point; - CurveTo { control1, control2, point, absolute: true } + CurveTo { control1, control2, point, absolute: IsAbsolute::Yes } }, SmoothCurveTo { mut control2, mut point, absolute } => { - if !absolute { + if !absolute.is_yes() { control2 += state.pos; point += state.pos; } state.pos = point; - SmoothCurveTo { control2, point, absolute: true } + SmoothCurveTo { control2, point, absolute: IsAbsolute::Yes } }, QuadBezierCurveTo { mut control1, mut point, absolute } => { - if !absolute { + if !absolute.is_yes() { control1 += state.pos; point += state.pos; } state.pos = point; - QuadBezierCurveTo { control1, point, absolute: true } + QuadBezierCurveTo { control1, point, absolute: IsAbsolute::Yes } }, SmoothQuadBezierCurveTo { mut point, absolute } => { - if !absolute { + if !absolute.is_yes() { point += state.pos; } state.pos = point; - SmoothQuadBezierCurveTo { point, absolute: true } + SmoothQuadBezierCurveTo { point, absolute: IsAbsolute::Yes } }, EllipticalArc { rx, ry, angle, large_arc_flag, sweep_flag, mut point, absolute } => { - if !absolute { + if !absolute.is_yes() { point += state.pos; } state.pos = point; - EllipticalArc { rx, ry, angle, large_arc_flag, sweep_flag, point, absolute: true } + EllipticalArc { + rx, ry, angle, large_arc_flag, sweep_flag, point, absolute: IsAbsolute::Yes + } }, } } @@ -271,17 +275,17 @@ impl ToCss for PathCommand { Unknown => dest.write_char('X'), ClosePath => dest.write_char('Z'), MoveTo { point, absolute } => { - dest.write_char(if absolute { 'M' } else { 'm' })?; + dest.write_char(if absolute.is_yes() { 'M' } else { 'm' })?; dest.write_char(' ')?; point.to_css(dest) } LineTo { point, absolute } => { - dest.write_char(if absolute { 'L' } else { 'l' })?; + dest.write_char(if absolute.is_yes() { 'L' } else { 'l' })?; dest.write_char(' ')?; point.to_css(dest) } CurveTo { control1, control2, point, absolute } => { - dest.write_char(if absolute { 'C' } else { 'c' })?; + dest.write_char(if absolute.is_yes() { 'C' } else { 'c' })?; dest.write_char(' ')?; control1.to_css(dest)?; dest.write_char(' ')?; @@ -290,14 +294,14 @@ impl ToCss for PathCommand { point.to_css(dest) }, QuadBezierCurveTo { control1, point, absolute } => { - dest.write_char(if absolute { 'Q' } else { 'q' })?; + dest.write_char(if absolute.is_yes() { 'Q' } else { 'q' })?; dest.write_char(' ')?; control1.to_css(dest)?; dest.write_char(' ')?; point.to_css(dest) }, EllipticalArc { rx, ry, angle, large_arc_flag, sweep_flag, point, absolute } => { - dest.write_char(if absolute { 'A' } else { 'a' })?; + dest.write_char(if absolute.is_yes() { 'A' } else { 'a' })?; dest.write_char(' ')?; rx.to_css(dest)?; dest.write_char(' ')?; @@ -305,31 +309,31 @@ impl ToCss for PathCommand { dest.write_char(' ')?; angle.to_css(dest)?; dest.write_char(' ')?; - (large_arc_flag as i32).to_css(dest)?; + large_arc_flag.to_css(dest)?; dest.write_char(' ')?; - (sweep_flag as i32).to_css(dest)?; + sweep_flag.to_css(dest)?; dest.write_char(' ')?; point.to_css(dest) }, HorizontalLineTo { x, absolute } => { - dest.write_char(if absolute { 'H' } else { 'h' })?; + dest.write_char(if absolute.is_yes() { 'H' } else { 'h' })?; dest.write_char(' ')?; x.to_css(dest) }, VerticalLineTo { y, absolute } => { - dest.write_char(if absolute { 'V' } else { 'v' })?; + dest.write_char(if absolute.is_yes() { 'V' } else { 'v' })?; dest.write_char(' ')?; y.to_css(dest) }, SmoothCurveTo { control2, point, absolute } => { - dest.write_char(if absolute { 'S' } else { 's' })?; + dest.write_char(if absolute.is_yes() { 'S' } else { 's' })?; dest.write_char(' ')?; control2.to_css(dest)?; dest.write_char(' ')?; point.to_css(dest) }, SmoothQuadBezierCurveTo { point, absolute } => { - dest.write_char(if absolute { 'T' } else { 't' })?; + dest.write_char(if absolute.is_yes() { 'T' } else { 't' })?; dest.write_char(' ')?; point.to_css(dest) }, @@ -337,63 +341,24 @@ impl ToCss for PathCommand { } } -impl ToAnimatedZero for PathCommand { +/// The path command absolute type. +#[allow(missing_docs)] +#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, + SpecifiedValueInfo, ToAnimatedZero)] +#[repr(u8)] +pub enum IsAbsolute { + Yes, + No, +} + +impl IsAbsolute { + /// Return true if this is IsAbsolute::Yes. #[inline] - fn to_animated_zero(&self) -> Result { - use self::PathCommand::*; - let absolute = true; - match self { - &ClosePath => Ok(ClosePath), - &Unknown => Ok(Unknown), - &MoveTo { ref point, .. } => Ok(MoveTo { point: point.to_animated_zero()?, absolute }), - &LineTo { ref point, .. } => Ok(LineTo { point: point.to_animated_zero()?, absolute }), - &HorizontalLineTo { x, .. } => { - Ok(HorizontalLineTo { x: x.to_animated_zero()?, absolute }) - }, - &VerticalLineTo { y, .. } => { - Ok(VerticalLineTo { y: y.to_animated_zero()?, absolute }) - }, - &CurveTo { ref control1, ref control2, ref point, .. } => { - Ok(CurveTo { - control1: control1.to_animated_zero()?, - control2: control2.to_animated_zero()?, - point: point.to_animated_zero()?, - absolute, - }) - }, - &SmoothCurveTo { ref control2, ref point, .. } => { - Ok(SmoothCurveTo { - control2: control2.to_animated_zero()?, - point: point.to_animated_zero()?, - absolute, - }) - }, - &QuadBezierCurveTo { ref control1, ref point, .. } => { - Ok(QuadBezierCurveTo { - control1: control1.to_animated_zero()?, - point: point.to_animated_zero()?, - absolute, - }) - }, - &SmoothQuadBezierCurveTo { ref point, .. } => { - Ok(SmoothQuadBezierCurveTo { point: point.to_animated_zero()?, absolute }) - }, - &EllipticalArc { rx, ry, angle, large_arc_flag, sweep_flag, ref point, .. } => { - Ok(EllipticalArc { - rx: rx.to_animated_zero()?, - ry: ry.to_animated_zero()?, - angle: angle.to_animated_zero()?, - large_arc_flag, - sweep_flag, - point: point.to_animated_zero()?, - absolute, - }) - }, - } + pub fn is_yes(&self) -> bool { + *self == IsAbsolute::Yes } } - /// The path coord type. #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToCss)] @@ -416,6 +381,29 @@ impl AddAssign for CoordPair { } } +/// The EllipticalArc flag type. +#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo)] +#[repr(C)] +pub struct ArcFlag(bool); + +impl ToCss for ArcFlag { + #[inline] + fn to_css(&self, dest: &mut CssWriter) -> fmt::Result + where + W: fmt::Write + { + (self.0 as i32).to_css(dest) + } +} + +impl ComputeSquaredDistance for ArcFlag { + #[inline] + fn compute_squared_distance(&self, other: &Self) -> Result { + (self.0 as i32).compute_squared_distance(&(other.0 as i32)) + } +} + + /// SVG Path parser. struct PathParser<'a> { chars: Peekable>>, @@ -475,7 +463,11 @@ impl<'a> PathParser<'a> { match self.chars.next() { Some(command) => { - let abs = command.is_ascii_uppercase(); + let abs = if command.is_ascii_uppercase() { + IsAbsolute::Yes + } else { + IsAbsolute::No + }; macro_rules! parse_command { ( $($($p:pat)|+ => $parse_func:ident,)* ) => { match command { @@ -498,7 +490,7 @@ impl<'a> PathParser<'a> { b'S' | b's' => parse_smooth_curveto, b'Q' | b'q' => parse_quadratic_bezier_curveto, b'T' | b't' => parse_smooth_quadratic_bezier_curveto, - b'A' | b'a' => parse_elliprical_arc, + b'A' | b'a' => parse_elliptical_arc, ); }, _ => break, // no more commands. @@ -516,7 +508,7 @@ impl<'a> PathParser<'a> { skip_wsp(&mut self.chars); let point = parse_coord(&mut self.chars)?; - let absolute = command == b'M'; + let absolute = if command == b'M' { IsAbsolute::Yes } else { IsAbsolute::No }; self.path.push(PathCommand::MoveTo { point, absolute } ); // End of string or the next character is a possible new command. @@ -532,58 +524,58 @@ impl<'a> PathParser<'a> { } /// Parse "closepath" command. - fn parse_closepath(&mut self, _absolute: bool) -> Result<(), ()> { + fn parse_closepath(&mut self, _absolute: IsAbsolute) -> Result<(), ()> { self.path.push(PathCommand::ClosePath); Ok(()) } /// Parse "lineto" command. - fn parse_lineto(&mut self, absolute: bool) -> Result<(), ()> { + fn parse_lineto(&mut self, absolute: IsAbsolute) -> Result<(), ()> { parse_arguments!(self, absolute, LineTo, [ point => parse_coord ]) } /// Parse horizontal "lineto" command. - fn parse_h_lineto(&mut self, absolute: bool) -> Result<(), ()> { + fn parse_h_lineto(&mut self, absolute: IsAbsolute) -> Result<(), ()> { parse_arguments!(self, absolute, HorizontalLineTo, [ x => parse_number ]) } /// Parse vertical "lineto" command. - fn parse_v_lineto(&mut self, absolute: bool) -> Result<(), ()> { + fn parse_v_lineto(&mut self, absolute: IsAbsolute) -> Result<(), ()> { parse_arguments!(self, absolute, VerticalLineTo, [ y => parse_number ]) } /// Parse cubic Bézier curve command. - fn parse_curveto(&mut self, absolute: bool) -> Result<(), ()> { + fn parse_curveto(&mut self, absolute: IsAbsolute) -> Result<(), ()> { parse_arguments!(self, absolute, CurveTo, [ control1 => parse_coord, control2 => parse_coord, point => parse_coord ]) } /// Parse smooth "curveto" command. - fn parse_smooth_curveto(&mut self, absolute: bool) -> Result<(), ()> { + fn parse_smooth_curveto(&mut self, absolute: IsAbsolute) -> Result<(), ()> { parse_arguments!(self, absolute, SmoothCurveTo, [ control2 => parse_coord, point => parse_coord ]) } /// Parse quadratic Bézier curve command. - fn parse_quadratic_bezier_curveto(&mut self, absolute: bool) -> Result<(), ()> { + fn parse_quadratic_bezier_curveto(&mut self, absolute: IsAbsolute) -> Result<(), ()> { parse_arguments!(self, absolute, QuadBezierCurveTo, [ control1 => parse_coord, point => parse_coord ]) } /// Parse smooth quadratic Bézier curveto command. - fn parse_smooth_quadratic_bezier_curveto(&mut self, absolute: bool) -> Result<(), ()> { + fn parse_smooth_quadratic_bezier_curveto(&mut self, absolute: IsAbsolute) -> Result<(), ()> { parse_arguments!(self, absolute, SmoothQuadBezierCurveTo, [ point => parse_coord ]) } /// Parse elliptical arc curve command. - fn parse_elliprical_arc(&mut self, absolute: bool) -> Result<(), ()> { + fn parse_elliptical_arc(&mut self, absolute: IsAbsolute) -> Result<(), ()> { // Parse a flag whose value is '0' or '1'; otherwise, return Err(()). - let parse_flag = |iter: &mut Peekable>>| -> Result { + let parse_flag = |iter: &mut Peekable>>| { match iter.next() { - Some(c) if c == b'0' || c == b'1' => Ok(c == b'1'), + Some(c) if c == b'0' || c == b'1' => Ok(ArcFlag(c == b'1')), _ => Err(()), } }; From 8dab4d659aae9fc4954e3a346bd663f60485de31 Mon Sep 17 00:00:00 2001 From: chansuke Date: Sun, 9 Sep 2018 16:24:45 +0200 Subject: [PATCH 4/4] Format style component. --- components/style/animation.rs | 26 +- components/style/applicable_declarations.rs | 6 +- components/style/attr.rs | 18 +- components/style/author_styles.rs | 6 +- components/style/build_gecko.rs | 12 +- components/style/counter_style/mod.rs | 13 +- components/style/custom_properties.rs | 6 +- components/style/data.rs | 14 +- components/style/dom.rs | 15 +- components/style/dom_apis.rs | 3 +- components/style/font_face.rs | 30 +- components/style/gecko/conversions.rs | 46 +-- components/style/gecko/data.rs | 10 +- components/style/gecko/media_features.rs | 118 +++----- components/style/gecko/media_queries.rs | 3 +- components/style/gecko/pseudo_element.rs | 4 +- components/style/gecko/rules.rs | 6 +- components/style/gecko/selector_parser.rs | 11 +- components/style/gecko/snapshot_helpers.rs | 46 +-- components/style/gecko/url.rs | 13 +- components/style/gecko/values.rs | 7 +- components/style/gecko/wrapper.rs | 138 +++++---- components/style/gecko_bindings/mod.rs | 17 +- .../gecko_bindings/sugar/ns_style_coord.rs | 15 +- .../style/gecko_bindings/sugar/refptr.rs | 6 +- .../sugar/style_complex_color.rs | 8 +- .../invalidation/element/element_wrapper.rs | 13 +- .../invalidation/element/invalidation_map.rs | 15 +- .../invalidation/element/restyle_hints.rs | 6 +- .../element/state_and_attributes.rs | 15 +- components/style/lib.rs | 1 - components/style/logical_geometry.rs | 6 +- components/style/macros.rs | 16 +- components/style/matching.rs | 15 +- .../style/media_queries/media_condition.rs | 24 +- .../style/media_queries/media_feature.rs | 94 +++--- .../media_queries/media_feature_expression.rs | 199 +++++------- components/style/media_queries/media_list.rs | 17 +- components/style/media_queries/media_query.rs | 20 +- components/style/parser.rs | 6 +- components/style/rule_tree/mod.rs | 6 +- components/style/selector_map.rs | 22 +- components/style/servo/restyle_damage.rs | 52 ++-- components/style/servo/selector_parser.rs | 7 +- components/style/sharing/mod.rs | 3 +- components/style/style_adjuster.rs | 70 +++-- components/style/style_resolver.rs | 6 +- components/style/stylesheet_set.rs | 3 +- components/style/stylesheets/document_rule.rs | 25 +- .../stylesheets/font_feature_values_rule.rs | 12 +- .../style/stylesheets/keyframes_rule.rs | 41 ++- components/style/stylesheets/mod.rs | 66 ++-- components/style/stylesheets/rule_list.rs | 6 +- components/style/stylesheets/rule_parser.rs | 68 ++--- .../style/stylesheets/rules_iterator.rs | 5 +- components/style/stylesheets/stylesheet.rs | 13 +- components/style/stylesheets/supports_rule.rs | 35 +-- components/style/stylesheets/viewport_rule.rs | 9 +- components/style/stylist.rs | 109 ++++--- components/style/traversal.rs | 27 +- components/style/use_counters/mod.rs | 3 +- components/style/values/animated/color.rs | 19 +- components/style/values/animated/mod.rs | 5 +- components/style/values/computed/angle.rs | 8 +- components/style/values/computed/box.rs | 48 +-- components/style/values/computed/counters.rs | 1 - components/style/values/computed/effects.rs | 6 +- components/style/values/computed/font.rs | 38 ++- components/style/values/computed/length.rs | 61 ++-- components/style/values/computed/motion.rs | 2 +- .../style/values/computed/percentage.rs | 18 +- components/style/values/computed/transform.rs | 22 +- .../style/values/generics/background.rs | 17 +- .../style/values/generics/basic_shape.rs | 135 ++++++--- components/style/values/generics/border.rs | 58 +++- components/style/values/generics/box.rs | 34 ++- components/style/values/generics/column.rs | 17 +- components/style/values/generics/counters.rs | 22 +- components/style/values/generics/effects.rs | 40 ++- components/style/values/generics/flex.rs | 16 +- components/style/values/generics/font.rs | 60 +++- components/style/values/generics/gecko.rs | 3 +- components/style/values/generics/grid.rs | 39 ++- components/style/values/generics/image.rs | 5 +- components/style/values/generics/mod.rs | 35 ++- components/style/values/generics/position.rs | 29 +- components/style/values/generics/rect.rs | 13 +- components/style/values/generics/size.rs | 13 +- components/style/values/generics/svg.rs | 91 ++++-- components/style/values/generics/text.rs | 41 ++- components/style/values/generics/transform.rs | 95 ++++-- components/style/values/generics/ui.rs | 6 +- components/style/values/generics/url.rs | 16 +- components/style/values/mod.rs | 32 +- components/style/values/specified/align.rs | 9 +- .../style/values/specified/background.rs | 21 +- .../style/values/specified/basic_shape.rs | 17 +- components/style/values/specified/border.rs | 6 +- components/style/values/specified/box.rs | 161 ++++++---- components/style/values/specified/color.rs | 20 +- components/style/values/specified/column.rs | 3 +- components/style/values/specified/counters.rs | 6 +- components/style/values/specified/effects.rs | 18 +- components/style/values/specified/font.rs | 80 +++-- components/style/values/specified/grid.rs | 29 +- components/style/values/specified/image.rs | 41 ++- components/style/values/specified/length.rs | 42 ++- components/style/values/specified/list.rs | 6 +- components/style/values/specified/mod.rs | 39 ++- components/style/values/specified/motion.rs | 16 +- components/style/values/specified/outline.rs | 15 +- components/style/values/specified/position.rs | 57 +++- .../style/values/specified/resolution.rs | 6 +- .../values/specified/source_size_list.rs | 3 +- components/style/values/specified/svg.rs | 6 +- components/style/values/specified/svg_path.rs | 283 ++++++++++++++---- components/style/values/specified/table.rs | 5 +- components/style/values/specified/text.rs | 47 ++- components/style/values/specified/time.rs | 3 +- components/style/values/specified/ui.rs | 8 +- 120 files changed, 2207 insertions(+), 1417 deletions(-) diff --git a/components/style/animation.rs b/components/style/animation.rs index 2d421ce06a93..3e501781987e 100644 --- a/components/style/animation.rs +++ b/components/style/animation.rs @@ -213,7 +213,12 @@ pub enum Animation { /// node-dependent state (i.e. iteration count, etc.). /// /// TODO(emilio): The animation object could be refcounted. - Keyframes(OpaqueNode, KeyframesAnimation, Atom, KeyframesAnimationState), + Keyframes( + OpaqueNode, + KeyframesAnimation, + Atom, + KeyframesAnimationState, + ), } impl Animation { @@ -304,8 +309,7 @@ impl PropertyAnimation { let duration = box_style.transition_duration_mod(transition_index); match transition_property { - TransitionProperty::Custom(..) | - TransitionProperty::Unsupported(..) => result, + TransitionProperty::Custom(..) | TransitionProperty::Unsupported(..) => result, TransitionProperty::Shorthand(ref shorthand_id) => shorthand_id .longhands() .filter_map(|longhand| { @@ -316,8 +320,7 @@ impl PropertyAnimation { old_style, new_style, ) - }) - .collect(), + }).collect(), TransitionProperty::Longhand(longhand_id) => { let animation = PropertyAnimation::from_longhand( longhand_id, @@ -455,8 +458,7 @@ pub fn start_transitions_if_applicable( property_animation: property_animation, }, /* is_expired = */ false, - )) - .unwrap(); + )).unwrap(); had_animations = true; } @@ -505,7 +507,9 @@ where Some(previous_style), Some(previous_style), font_metrics_provider, - CascadeMode::Unvisited { visited_rules: None }, + CascadeMode::Unvisited { + visited_rules: None, + }, context.quirks_mode(), /* rule_cache = */ None, &mut Default::default(), @@ -596,8 +600,7 @@ where expired: false, cascade_style: new_style.clone(), }, - )) - .unwrap(); + )).unwrap(); had_animations = true; } } @@ -735,8 +738,7 @@ pub fn update_style_for_animation( } else { None } - }) - .unwrap_or(animation.steps.len() - 1); + }).unwrap_or(animation.steps.len() - 1); }, _ => unreachable!(), } diff --git a/components/style/applicable_declarations.rs b/components/style/applicable_declarations.rs index a1476917fcbd..986dc04c371c 100644 --- a/components/style/applicable_declarations.rs +++ b/components/style/applicable_declarations.rs @@ -38,7 +38,8 @@ const SOURCE_ORDER_MASK: u32 = SOURCE_ORDER_MAX << SOURCE_ORDER_SHIFT; const SHADOW_CASCADE_ORDER_SHIFT: usize = SOURCE_ORDER_BITS; const SHADOW_CASCADE_ORDER_BITS: usize = 4; const SHADOW_CASCADE_ORDER_MAX: u8 = (1 << SHADOW_CASCADE_ORDER_BITS) - 1; -const SHADOW_CASCADE_ORDER_MASK: u32 = (SHADOW_CASCADE_ORDER_MAX as u32) << SHADOW_CASCADE_ORDER_SHIFT; +const SHADOW_CASCADE_ORDER_MASK: u32 = + (SHADOW_CASCADE_ORDER_MAX as u32) << SHADOW_CASCADE_ORDER_SHIFT; const CASCADE_LEVEL_SHIFT: usize = SOURCE_ORDER_BITS + SHADOW_CASCADE_ORDER_BITS; const CASCADE_LEVEL_BITS: usize = 4; @@ -61,7 +62,8 @@ impl ApplicableDeclarationBits { "Gotta find more bits!" ); let mut bits = ::std::cmp::min(source_order, SOURCE_ORDER_MAX); - bits |= ((shadow_cascade_order & SHADOW_CASCADE_ORDER_MAX) as u32) << SHADOW_CASCADE_ORDER_SHIFT; + bits |= ((shadow_cascade_order & SHADOW_CASCADE_ORDER_MAX) as u32) << + SHADOW_CASCADE_ORDER_SHIFT; bits |= (cascade_level as u8 as u32) << CASCADE_LEVEL_SHIFT; ApplicableDeclarationBits(bits) } diff --git a/components/style/attr.rs b/components/style/attr.rs index 5f335472f324..a3b119c3a975 100644 --- a/components/style/attr.rs +++ b/components/style/attr.rs @@ -158,15 +158,15 @@ pub fn parse_double(string: &str) -> Result { impl AttrValue { pub fn from_serialized_tokenlist(tokens: String) -> AttrValue { - let atoms = split_html_space_chars(&tokens).map(Atom::from).fold( - vec![], - |mut acc, atom| { - if !acc.contains(&atom) { - acc.push(atom) - } - acc - }, - ); + let atoms = + split_html_space_chars(&tokens) + .map(Atom::from) + .fold(vec![], |mut acc, atom| { + if !acc.contains(&atom) { + acc.push(atom) + } + acc + }); AttrValue::TokenList(tokens, atoms) } diff --git a/components/style/author_styles.rs b/components/style/author_styles.rs index e8ec621bd92e..837569078c08 100644 --- a/components/style/author_styles.rs +++ b/components/style/author_styles.rs @@ -60,7 +60,8 @@ where E: TElement, S: ToMediaListKey, { - let flusher = self.stylesheets + let flusher = self + .stylesheets .flush::(/* host = */ None, /* snapshot_map = */ None); if flusher.sheets.dirty() { @@ -68,7 +69,8 @@ where } // Ignore OOM. - let _ = self.data + let _ = self + .data .rebuild(device, quirks_mode, flusher.sheets, guard); } } diff --git a/components/style/build_gecko.rs b/components/style/build_gecko.rs index c06556285385..1ecc7ec6fc3f 100644 --- a/components/style/build_gecko.rs +++ b/components/style/build_gecko.rs @@ -322,13 +322,11 @@ mod bindings { .expect(&format!( "Unrecognized line in ServoArcTypeList.h: '{}'", line - )) - .get(1) + )).get(1) .unwrap() .as_str() .to_string() - }) - .collect() + }).collect() } struct BuilderWithConfig<'a> { @@ -436,8 +434,7 @@ mod bindings { servo, if generic { "" } else { "" } )) - }) - .get_builder(); + }).get_builder(); write_binding_file(builder, STRUCTS_FILE, &fixups); } @@ -553,8 +550,7 @@ mod bindings { .raw_line(format!( "pub type {0}Strong = ::gecko_bindings::sugar::ownership::Strong<{0}>;", ty - )) - .borrowed_type(ty) + )).borrowed_type(ty) .zero_size_type(ty, &structs_types); } write_binding_file(builder, BINDINGS_FILE, &fixups); diff --git a/components/style/counter_style/mod.rs b/components/style/counter_style/mod.rs index 2542dee3625a..653d199545c6 100644 --- a/components/style/counter_style/mod.rs +++ b/components/style/counter_style/mod.rs @@ -91,8 +91,7 @@ pub fn parse_counter_style_body<'i, 't>( if let Err((error, slice)) = declaration { let location = error.location; let error = ContextualParseError::UnsupportedCounterStyleDescriptorDeclaration( - slice, - error, + slice, error, ); context.log_css_error(location, error) } @@ -103,7 +102,8 @@ pub fn parse_counter_style_body<'i, 't>( ref system @ System::Fixed { .. } | ref system @ System::Symbolic | ref system @ System::Alphabetic | - ref system @ System::Numeric if rule.symbols.is_none() => + ref system @ System::Numeric + if rule.symbols.is_none() => { let system = system.to_css_string(); Some(ContextualParseError::InvalidCounterStyleWithoutSymbols( @@ -496,12 +496,13 @@ impl Parse for Ranges { (opt_start, opt_end) { if start > end { - return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); + return Err( + input.new_custom_error(StyleParseErrorKind::UnspecifiedError) + ); } } Ok(opt_start..opt_end) - }) - .map(Ranges) + }).map(Ranges) } } } diff --git a/components/style/custom_properties.rs b/components/style/custom_properties.rs index d79a27c5c4d8..985179db0258 100644 --- a/components/style/custom_properties.rs +++ b/components/style/custom_properties.rs @@ -243,7 +243,8 @@ impl VariableValue { self.first_token_type.set_if_nothing(css_first_token_type); // If self.first_token_type was nothing, // self.last_token_type is also nothing and this will be false: - if self.last_token_type + if self + .last_token_type .needs_separator_when_before(css_first_token_type) { self.css.push_str("/**/") @@ -569,7 +570,8 @@ impl<'a> CustomPropertiesBuilder<'a> { _ => {}, } - let existing_value = self.custom_properties + let existing_value = self + .custom_properties .as_ref() .and_then(|m| m.get(name)) .or_else(|| self.inherited.and_then(|m| m.get(name))); diff --git a/components/style/data.rs b/components/style/data.rs index 71a0ac233207..4a9b0c539406 100644 --- a/components/style/data.rs +++ b/components/style/data.rs @@ -272,12 +272,8 @@ impl ElementData { return InvalidationResult::empty(); } - let mut processor = StateAndAttrInvalidationProcessor::new( - shared_context, - element, - self, - nth_index_cache, - ); + let mut processor = + StateAndAttrInvalidationProcessor::new(shared_context, element, self, nth_index_cache); let invalidator = TreeStyleInvalidator::new(element, stack_limit_checker, &mut processor); @@ -305,7 +301,8 @@ impl ElementData { /// Returns this element's primary style as a resolved style to use for sharing. pub fn share_primary_style(&self) -> PrimaryStyle { - let reused_via_rule_node = self.flags + let reused_via_rule_node = self + .flags .contains(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE); PrimaryStyle { @@ -390,7 +387,8 @@ impl ElementData { guards: &StylesheetGuards, ) -> bool { debug_assert!(self.has_styles()); - let (important_rules, _custom) = self.styles + let (important_rules, _custom) = self + .styles .primary() .rules() .get_properties_overriding_animations(&guards); diff --git a/components/style/dom.rs b/components/style/dom.rs index 2f65a266f017..872a55a54b23 100644 --- a/components/style/dom.rs +++ b/components/style/dom.rs @@ -42,7 +42,10 @@ use traversal_flags::TraversalFlags; /// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for /// locality reasons. Using `OpaqueNode` enforces this invariant. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] -#[cfg_attr(feature = "servo", derive(MallocSizeOf, Deserialize, Serialize))] +#[cfg_attr( + feature = "servo", + derive(MallocSizeOf, Deserialize, Serialize) +)] pub struct OpaqueNode(pub usize); impl OpaqueNode { @@ -459,7 +462,9 @@ pub trait TElement: fn is_svg_element(&self) -> bool; /// Return whether this element is an element in the XUL namespace. - fn is_xul_element(&self) -> bool { false } + fn is_xul_element(&self) -> bool { + false + } /// Return the list of slotted nodes of this node. fn slotted_nodes(&self) -> &[Self::ConcreteNode] { @@ -892,11 +897,7 @@ pub trait TElement: /// of the `xml:lang=""` or `lang=""` attribute to use in place of /// looking at the element and its ancestors. (This argument is used /// to implement matching of `:lang()` against snapshots.) - fn match_element_lang( - &self, - override_lang: Option>, - value: &Lang, - ) -> bool; + fn match_element_lang(&self, override_lang: Option>, value: &Lang) -> bool; /// Returns whether this element is the main body element of the HTML /// document it is on. diff --git a/components/style/dom_apis.rs b/components/style/dom_apis.rs index 393fb6e119e4..9d7ab917a914 100644 --- a/components/style/dom_apis.rs +++ b/components/style/dom_apis.rs @@ -426,8 +426,7 @@ where return Ok(()); } - let elements = - fast_connected_elements_with_id(root, id, quirks_mode)?; + let elements = fast_connected_elements_with_id(root, id, quirks_mode)?; if elements.is_empty() { return Ok(()); } diff --git a/components/style/font_face.rs b/components/style/font_face.rs index d7501c1cca7f..fde25f08f6ff 100644 --- a/components/style/font_face.rs +++ b/components/style/font_face.rs @@ -104,8 +104,9 @@ impl Parse for FontWeight { input: &mut Parser<'i, 't>, ) -> Result> { let first = AbsoluteFontWeight::parse(context, input)?; - let second = - input.try(|input| AbsoluteFontWeight::parse(context, input)).ok(); + let second = input + .try(|input| AbsoluteFontWeight::parse(context, input)) + .ok(); Ok(FontWeight(first, second)) } } @@ -122,8 +123,9 @@ impl Parse for FontStretch { input: &mut Parser<'i, 't>, ) -> Result> { let first = SpecifiedFontStretch::parse(context, input)?; - let second = - input.try(|input| SpecifiedFontStretch::parse(context, input)).ok(); + let second = input + .try(|input| SpecifiedFontStretch::parse(context, input)) + .ok(); Ok(FontStretch(first, second)) } } @@ -149,12 +151,12 @@ impl Parse for FontStyle { GenericFontStyle::Normal => FontStyle::Normal, GenericFontStyle::Italic => FontStyle::Italic, GenericFontStyle::Oblique(angle) => { - let second_angle = input.try(|input| { - SpecifiedFontStyle::parse_angle(context, input) - }).unwrap_or_else(|_| angle.clone()); + let second_angle = input + .try(|input| SpecifiedFontStyle::parse_angle(context, input)) + .unwrap_or_else(|_| angle.clone()); FontStyle::Oblique(angle, second_angle) - } + }, }) } } @@ -178,7 +180,7 @@ impl ToCss for FontStyle { second.to_css(dest)?; } Ok(()) - } + }, } } } @@ -235,15 +237,13 @@ impl<'a> FontFace<'a> { // We support only opentype fonts and truetype is an alias for // that format. Sources without format hints need to be // downloaded in case we support them. - hints.is_empty() || - hints.iter().any(|hint| { - hint == "truetype" || hint == "opentype" || hint == "woff" - }) + hints.is_empty() || hints + .iter() + .any(|hint| hint == "truetype" || hint == "opentype" || hint == "woff") } else { true } - }) - .cloned() + }).cloned() .collect(), ) } diff --git a/components/style/gecko/conversions.rs b/components/style/gecko/conversions.rs index 3c1d334f4a87..c6009c96deed 100644 --- a/components/style/gecko/conversions.rs +++ b/components/style/gecko/conversions.rs @@ -140,10 +140,7 @@ impl Angle { } } -fn line_direction( - horizontal: LengthOrPercentage, - vertical: LengthOrPercentage, -) -> LineDirection { +fn line_direction(horizontal: LengthOrPercentage, vertical: LengthOrPercentage) -> LineDirection { use values::computed::position::Position; use values::specified::position::{X, Y}; @@ -178,18 +175,18 @@ fn line_direction( }); if let (Some(hc), Some(vc)) = (horizontal_as_corner, vertical_as_corner) { - return LineDirection::Corner(hc, vc) + return LineDirection::Corner(hc, vc); } if let Some(hc) = horizontal_as_corner { if vertical_percentage == Some(0.5) { - return LineDirection::Horizontal(hc) + return LineDirection::Horizontal(hc); } } if let Some(vc) = vertical_as_corner { if horizontal_percentage == Some(0.5) { - return LineDirection::Vertical(vc) + return LineDirection::Vertical(vc); } } @@ -212,7 +209,10 @@ impl nsStyleImage { }, GenericImage::Rect(ref image_rect) => { unsafe { - bindings::Gecko_SetLayerImageImageValue(self, image_rect.url.0.image_value.get()); + bindings::Gecko_SetLayerImageImageValue( + self, + image_rect.url.0.image_value.get(), + ); bindings::Gecko_InitializeImageCropRect(self); // Set CropRect @@ -491,7 +491,8 @@ impl nsStyleImage { unsafe fn get_image_url(&self) -> ComputedImageUrl { let image_request = bindings::Gecko_GetImageRequest(self) - .as_ref().expect("Null image request?"); + .as_ref() + .expect("Null image request?"); ComputedImageUrl::from_image_request(image_request) } @@ -555,9 +556,9 @@ impl nsStyleImage { structs::NS_STYLE_GRADIENT_SHAPE_CIRCULAR => { let circle = match gecko_gradient.mSize as u32 { structs::NS_STYLE_GRADIENT_SIZE_EXPLICIT_SIZE => { - let radius = Length::from_gecko_style_coord( - &gecko_gradient.mRadiusX, - ).expect("mRadiusX could not convert to Length"); + let radius = + Length::from_gecko_style_coord(&gecko_gradient.mRadiusX) + .expect("mRadiusX could not convert to Length"); debug_assert_eq!( radius, Length::from_gecko_style_coord(&gecko_gradient.mRadiusY) @@ -632,8 +633,7 @@ impl nsStyleImage { position: LengthOrPercentage::from_gecko_style_coord(&stop.mLocation), }) } - }) - .collect(); + }).collect(); let compat_mode = if gecko_gradient.mMozLegacySyntax { CompatMode::Moz @@ -719,8 +719,10 @@ pub mod basic_shape { match self.mType { StyleShapeSourceType::Path => { let gecko_path = unsafe { &*self.__bindgen_anon_1.mSVGPath.as_ref().mPtr }; - let result: Vec = - gecko_path.mPath.iter().map(|gecko: &StylePathCommand| { + let result: Vec = gecko_path + .mPath + .iter() + .map(|gecko: &StylePathCommand| { // unsafe: cbindgen ensures the representation is the same. unsafe { ::std::mem::transmute(*gecko) } }).collect(); @@ -822,11 +824,15 @@ pub mod basic_shape { let y = x + 1; coords.push(PolygonCoord( LengthOrPercentage::from_gecko_style_coord(&other.mCoordinates[x]) - .expect("polygon() coordinate should be a length, percentage, \ - or calc value"), + .expect( + "polygon() coordinate should be a length, percentage, \ + or calc value", + ), LengthOrPercentage::from_gecko_style_coord(&other.mCoordinates[y]) - .expect("polygon() coordinate should be a length, percentage, \ - or calc value") + .expect( + "polygon() coordinate should be a length, percentage, \ + or calc value", + ), )) } GenericBasicShape::Polygon(Polygon { diff --git a/components/style/gecko/data.rs b/components/style/gecko/data.rs index 0bd938c67e8f..d737167c28ac 100644 --- a/components/style/gecko/data.rs +++ b/components/style/gecko/data.rs @@ -29,7 +29,8 @@ pub struct GeckoStyleSheet(*const DomStyleSheet); impl fmt::Debug for GeckoStyleSheet { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let contents = self.contents(); - formatter.debug_struct("GeckoStyleSheet") + formatter + .debug_struct("GeckoStyleSheet") .field("origin", &contents.origin) .field("url_data", &*contents.url_data.read()) .finish() @@ -66,9 +67,7 @@ impl GeckoStyleSheet { } fn inner(&self) -> &StyleSheetInfo { - unsafe { - &*(self.raw().mInner as *const StyleSheetInfo) - } + unsafe { &*(self.raw().mInner as *const StyleSheetInfo) } } /// Gets the StylesheetContents for this stylesheet. @@ -193,7 +192,8 @@ impl PerDocumentStyleDataImpl { /// Returns whether visited styles are enabled. #[inline] pub fn visited_styles_enabled(&self) -> bool { - let doc = self.stylist + let doc = self + .stylist .device() .pres_context() .mDocument diff --git a/components/style/gecko/media_features.rs b/components/style/gecko/media_features.rs index 386d0ad5b43e..85f0ba27d430 100644 --- a/components/style/gecko/media_features.rs +++ b/components/style/gecko/media_features.rs @@ -21,7 +21,7 @@ fn viewport_size(device: &Device) -> Size2D { // We want the page size, including unprintable areas and margins. // FIXME(emilio, bug 1414600): Not quite! let area = &pc.mPageSize; - return Size2D::new(Au(area.width), Au(area.height)) + return Size2D::new(Au(area.width), Au(area.height)); } device.au_viewport_size() } @@ -30,11 +30,7 @@ fn device_size(device: &Device) -> Size2D { let mut width = 0; let mut height = 0; unsafe { - bindings::Gecko_MediaFeatures_GetDeviceSize( - device.document(), - &mut width, - &mut height, - ); + bindings::Gecko_MediaFeatures_GetDeviceSize(device.document(), &mut width, &mut height); } Size2D::new(Au(width), Au(height)) } @@ -152,11 +148,7 @@ enum Orientation { Portrait, } -fn eval_orientation_for( - device: &Device, - value: Option, - get_size: F, -) -> bool +fn eval_orientation_for(device: &Device, value: Option, get_size: F) -> bool where F: FnOnce(&Device) -> Size2D, { @@ -176,18 +168,12 @@ where } /// https://drafts.csswg.org/mediaqueries-4/#orientation -fn eval_orientation( - device: &Device, - value: Option, -) -> bool { +fn eval_orientation(device: &Device, value: Option) -> bool { eval_orientation_for(device, value, viewport_size) } /// FIXME: There's no spec for `-moz-device-orientation`. -fn eval_device_orientation( - device: &Device, - value: Option, -) -> bool { +fn eval_device_orientation(device: &Device, value: Option) -> bool { eval_orientation_for(device, value, device_size) } @@ -196,25 +182,21 @@ fn eval_device_orientation( #[repr(u8)] #[allow(missing_docs)] pub enum DisplayMode { - Browser = 0, - MinimalUi, - Standalone, - Fullscreen, + Browser = 0, + MinimalUi, + Standalone, + Fullscreen, } /// https://w3c.github.io/manifest/#the-display-mode-media-feature -fn eval_display_mode( - device: &Device, - query_value: Option, -) -> bool { +fn eval_display_mode(device: &Device, query_value: Option) -> bool { let query_value = match query_value { Some(v) => v, None => return true, }; - let gecko_display_mode = unsafe { - bindings::Gecko_MediaFeatures_GetDisplayMode(device.document()) - }; + let gecko_display_mode = + unsafe { bindings::Gecko_MediaFeatures_GetDisplayMode(device.document()) }; // NOTE: cbindgen guarantees the same representation. gecko_display_mode as u8 == query_value as u8 @@ -229,11 +211,7 @@ fn eval_grid(_: &Device, query_value: Option, _: Option) } /// https://compat.spec.whatwg.org/#css-media-queries-webkit-transform-3d -fn eval_transform_3d( - _: &Device, - query_value: Option, - _: Option, -) -> bool { +fn eval_transform_3d(_: &Device, query_value: Option, _: Option) -> bool { let supports_transforms = true; query_value.map_or(supports_transforms, |v| v == supports_transforms) } @@ -260,11 +238,7 @@ fn eval_color( ) -> bool { let color_bits_per_channel = unsafe { bindings::Gecko_MediaFeatures_GetColorDepth(device.document()) }; - RangeOrOperator::evaluate( - range_or_operator, - query_value, - color_bits_per_channel, - ) + RangeOrOperator::evaluate(range_or_operator, query_value, color_bits_per_channel) } /// https://drafts.csswg.org/mediaqueries-4/#color-index @@ -275,11 +249,7 @@ fn eval_color_index( ) -> bool { // We should return zero if the device does not use a color lookup table. let index = 0; - RangeOrOperator::evaluate( - range_or_operator, - query_value, - index, - ) + RangeOrOperator::evaluate(range_or_operator, query_value, index) } /// https://drafts.csswg.org/mediaqueries-4/#monochrome @@ -291,11 +261,7 @@ fn eval_monochrome( // For color devices we should return 0. // FIXME: On a monochrome device, return the actual color depth, not 0! let depth = 0; - RangeOrOperator::evaluate( - range_or_operator, - query_value, - depth, - ) + RangeOrOperator::evaluate(range_or_operator, query_value, depth) } /// https://drafts.csswg.org/mediaqueries-4/#resolution @@ -304,8 +270,7 @@ fn eval_resolution( query_value: Option, range_or_operator: Option, ) -> bool { - let resolution_dppx = - unsafe { bindings::Gecko_MediaFeatures_GetResolution(device.document()) }; + let resolution_dppx = unsafe { bindings::Gecko_MediaFeatures_GetResolution(device.document()) }; RangeOrOperator::evaluate( range_or_operator, query_value.map(|r| r.dppx()), @@ -321,10 +286,7 @@ enum PrefersReducedMotion { } /// https://drafts.csswg.org/mediaqueries-5/#prefers-reduced-motion -fn eval_prefers_reduced_motion( - device: &Device, - query_value: Option, -) -> bool { +fn eval_prefers_reduced_motion(device: &Device, query_value: Option) -> bool { let prefers_reduced = unsafe { bindings::Gecko_MediaFeatures_PrefersReducedMotion(device.document()) }; let query_value = match query_value { @@ -352,9 +314,8 @@ fn eval_moz_is_resource_document( query_value: Option, _: Option, ) -> bool { - let is_resource_doc = unsafe { - bindings::Gecko_MediaFeatures_IsResourceDocument(device.document()) - }; + let is_resource_doc = + unsafe { bindings::Gecko_MediaFeatures_IsResourceDocument(device.document()) }; query_value.map_or(is_resource_doc, |v| v == is_resource_doc) } @@ -397,37 +358,30 @@ fn eval_moz_os_version( None => return false, }; - let os_version = unsafe { - bindings::Gecko_MediaFeatures_GetOperatingSystemVersion(device.document()) - }; + let os_version = + unsafe { bindings::Gecko_MediaFeatures_GetOperatingSystemVersion(device.document()) }; query_value.as_ptr() == os_version } macro_rules! system_metric_feature { - ($feature_name:expr) => { - { - fn __eval( - device: &Device, - query_value: Option, - _: Option, - ) -> bool { - eval_system_metric( - device, - query_value, - $feature_name, - /* accessible_from_content = */ false, - ) - } - - feature!( + ($feature_name:expr) => {{ + fn __eval(device: &Device, query_value: Option, _: Option) -> bool { + eval_system_metric( + device, + query_value, $feature_name, - AllowsRanges::No, - Evaluator::BoolInteger(__eval), - ParsingRequirements::CHROME_AND_UA_ONLY, + /* accessible_from_content = */ false, ) } - } + + feature!( + $feature_name, + AllowsRanges::No, + Evaluator::BoolInteger(__eval), + ParsingRequirements::CHROME_AND_UA_ONLY, + ) + }}; } lazy_static! { diff --git a/components/style/gecko/media_queries.rs b/components/style/gecko/media_queries.rs index c41bc4ffd73e..ccf5b7a5180c 100644 --- a/components/style/gecko/media_queries.rs +++ b/components/style/gecko/media_queries.rs @@ -126,7 +126,8 @@ impl Device { /// Set the font size of the root element (for rem) pub fn set_root_font_size(&self, size: Au) { - self.root_font_size.store(size.0 as isize, Ordering::Relaxed) + self.root_font_size + .store(size.0 as isize, Ordering::Relaxed) } /// Sets the body text color for the "inherit color from body" quirk. diff --git a/components/style/gecko/pseudo_element.rs b/components/style/gecko/pseudo_element.rs index b30d7764d176..70b0e112cee1 100644 --- a/components/style/gecko/pseudo_element.rs +++ b/components/style/gecko/pseudo_element.rs @@ -62,7 +62,9 @@ impl PseudoElement { /// /// This is used in Servo for anonymous boxes, though it's likely broken. #[inline] - pub fn inherits_all(&self) -> bool { false } + pub fn inherits_all(&self) -> bool { + false + } /// Whether the pseudo-element should inherit from the default computed /// values instead of from the parent element. diff --git a/components/style/gecko/rules.rs b/components/style/gecko/rules.rs index a57314a418cc..233b1757ef5e 100644 --- a/components/style/gecko/rules.rs +++ b/components/style/gecko/rules.rs @@ -88,7 +88,7 @@ macro_rules! descriptor_range_conversion { None => { nscssvalue.set_from(first); return; - } + }, Some(ref second) => second, }; @@ -101,7 +101,7 @@ macro_rules! descriptor_range_conversion { nscssvalue.set_pair(&a, &b); } } - } + }; } descriptor_range_conversion!(FontWeight); @@ -120,7 +120,7 @@ impl<'a> ToNsCssValue for &'a FontStyle { b.set_font_style(SpecifiedFontStyle::compute_angle(second).degrees()); nscssvalue.set_pair(&a, &b); - } + }, } } } diff --git a/components/style/gecko/selector_parser.rs b/components/style/gecko/selector_parser.rs index 3f6fee3c30e9..2365356f2f8b 100644 --- a/components/style/gecko/selector_parser.rs +++ b/components/style/gecko/selector_parser.rs @@ -181,9 +181,8 @@ impl NonTSPseudoClass { }, // Otherwise, a pseudo-class is enabled in content when it // doesn't have any enabled flag. - _ => !self.has_any_flag( - NonTSPseudoClassFlag::PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME, - ), + _ => !self + .has_any_flag(NonTSPseudoClassFlag::PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME), } } @@ -233,8 +232,7 @@ impl NonTSPseudoClass { /// Returns true if the given pseudoclass should trigger style sharing cache /// revalidation. pub fn needs_cache_revalidation(&self) -> bool { - self.state_flag().is_empty() && - !matches!(*self, + self.state_flag().is_empty() && !matches!(*self, // :-moz-any is handled by the revalidation visitor walking // the things inside it; it does not need to cause // revalidation on its own. @@ -268,7 +266,8 @@ impl NonTSPseudoClass { pub fn is_attr_based(&self) -> bool { matches!( *self, - NonTSPseudoClass::MozTableBorderNonzero | NonTSPseudoClass::MozBrowserFrame | + NonTSPseudoClass::MozTableBorderNonzero | + NonTSPseudoClass::MozBrowserFrame | NonTSPseudoClass::Lang(..) ) } diff --git a/components/style/gecko/snapshot_helpers.rs b/components/style/gecko/snapshot_helpers.rs index 6c40f242d5f0..371a2b78da16 100644 --- a/components/style/gecko/snapshot_helpers.rs +++ b/components/style/gecko/snapshot_helpers.rs @@ -41,15 +41,26 @@ unsafe fn get_class_from_attr(attr: &structs::nsAttrValue) -> Class { debug_assert_eq!(base_type, structs::nsAttrValue_ValueBaseType_eOtherBase); let container = ptr::(attr); - debug_assert_eq!((*container).mType, structs::nsAttrValue_ValueType_eAtomArray); - let array = - (*container).__bindgen_anon_1.mValue.as_ref().__bindgen_anon_1.mAtomArray.as_ref(); + debug_assert_eq!( + (*container).mType, + structs::nsAttrValue_ValueType_eAtomArray + ); + let array = (*container) + .__bindgen_anon_1 + .mValue + .as_ref() + .__bindgen_anon_1 + .mAtomArray + .as_ref(); Class::More(&***array) } #[inline(always)] unsafe fn get_id_from_attr(attr: &structs::nsAttrValue) -> &WeakAtom { - debug_assert_eq!(base_type(attr), structs::nsAttrValue_ValueBaseType_eAtomBase); + debug_assert_eq!( + base_type(attr), + structs::nsAttrValue_ValueBaseType_eAtomBase + ); WeakAtom::new(ptr::(attr)) } @@ -59,7 +70,8 @@ pub fn find_attr<'a>( attrs: &'a [structs::AttrArray_InternalAttr], name: &Atom, ) -> Option<&'a structs::nsAttrValue> { - attrs.iter() + attrs + .iter() .find(|attr| attr.mName.mBits == name.as_ptr() as usize) .map(|attr| &attr.mValue) } @@ -80,19 +92,17 @@ pub fn has_class( ) -> bool { match unsafe { get_class_from_attr(attr) } { Class::None => false, - Class::One(atom) => unsafe { - case_sensitivity.eq_atom(name, WeakAtom::new(atom)) + Class::One(atom) => unsafe { case_sensitivity.eq_atom(name, WeakAtom::new(atom)) }, + Class::More(atoms) => match case_sensitivity { + CaseSensitivity::CaseSensitive => { + atoms.iter().any(|atom| atom.mRawPtr == name.as_ptr()) + }, + CaseSensitivity::AsciiCaseInsensitive => unsafe { + atoms + .iter() + .any(|atom| WeakAtom::new(atom.mRawPtr).eq_ignore_ascii_case(name)) + }, }, - Class::More(atoms) => { - match case_sensitivity { - CaseSensitivity::CaseSensitive => { - atoms.iter().any(|atom| atom.mRawPtr == name.as_ptr()) - } - CaseSensitivity::AsciiCaseInsensitive => unsafe { - atoms.iter().any(|atom| WeakAtom::new(atom.mRawPtr).eq_ignore_ascii_case(name)) - } - } - } } } @@ -111,7 +121,7 @@ where for atom in atoms { Atom::with(atom.mRawPtr, &mut callback) } - } + }, } } } diff --git a/components/style/gecko/url.rs b/components/style/gecko/url.rs index b94d21397648..8d785cae679d 100644 --- a/components/style/gecko/url.rs +++ b/components/style/gecko/url.rs @@ -55,8 +55,7 @@ impl CssUrl { /// Convert from URLValueData to SpecifiedUrl. unsafe fn from_url_value_data(url: &URLValueData) -> Self { - let arc_type = - &url.mString as *const _ as *const RawOffsetArc; + let arc_type = &url.mString as *const _ as *const RawOffsetArc; CssUrl { serialization: Arc::from_raw_offset((*arc_type).clone()), extra_data: UrlExtraData(url.mExtraData.to_safe()), @@ -140,7 +139,6 @@ impl SpecifiedUrl { } } - impl PartialEq for SpecifiedUrl { fn eq(&self, other: &Self) -> bool { self.url.eq(&other.url) @@ -255,10 +253,7 @@ impl ToComputedValue for SpecifiedImageUrl { } } -fn serialize_computed_url( - url_value_data: &URLValueData, - dest: &mut CssWriter, -) -> fmt::Result +fn serialize_computed_url(url_value_data: &URLValueData, dest: &mut CssWriter) -> fmt::Result where W: Write, { @@ -281,7 +276,7 @@ pub struct ComputedUrl(pub SpecifiedUrl); impl ToCss for ComputedUrl { fn to_css(&self, dest: &mut CssWriter) -> fmt::Result where - W: Write + W: Write, { serialize_computed_url(&self.0.url_value._base, dest) } @@ -302,7 +297,7 @@ pub struct ComputedImageUrl(pub SpecifiedImageUrl); impl ToCss for ComputedImageUrl { fn to_css(&self, dest: &mut CssWriter) -> fmt::Result where - W: Write + W: Write, { serialize_computed_url(&self.0.image_value._base, dest) } diff --git a/components/style/gecko/values.rs b/components/style/gecko/values.rs index 3bb22947211d..fed9dc161c0f 100644 --- a/components/style/gecko/values.rs +++ b/components/style/gecko/values.rs @@ -488,7 +488,9 @@ where /// Convert a given RGBA value to `nscolor`. pub fn convert_rgba_to_nscolor(rgba: &RGBA) -> u32 { - ((rgba.alpha as u32) << 24) | ((rgba.blue as u32) << 16) | ((rgba.green as u32) << 8) | + ((rgba.alpha as u32) << 24) | + ((rgba.blue as u32) << 16) | + ((rgba.green as u32) << 8) | (rgba.red as u32) } @@ -537,8 +539,7 @@ impl CounterStyleOrNone { .map(|symbol| match *symbol { Symbol::String(ref s) => nsCStr::from(s), Symbol::Ident(_) => unreachable!("Should not have identifier in symbols()"), - }) - .collect(); + }).collect(); let symbols: Vec<_> = symbols .iter() .map(|symbol| symbol as &nsACString as *const _) diff --git a/components/style/gecko/wrapper.rs b/components/style/gecko/wrapper.rs index ff5ae599fcb8..efe37e647c5e 100644 --- a/components/style/gecko/wrapper.rs +++ b/components/style/gecko/wrapper.rs @@ -86,7 +86,6 @@ use std::ptr; use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace}; use stylist::CascadeData; - #[inline] fn elements_with_id<'a, 'le>( array: *const structs::nsTArray<*mut RawGeckoElement>, @@ -172,12 +171,11 @@ impl<'lr> TShadowRoot for GeckoShadowRoot<'lr> { Self: 'a, { let author_styles = unsafe { - (self.0.mServoStyles.mPtr - as *const structs::RawServoAuthorStyles - as *const bindings::RawServoAuthorStyles).as_ref()? + (self.0.mServoStyles.mPtr as *const structs::RawServoAuthorStyles + as *const bindings::RawServoAuthorStyles) + .as_ref()? }; - let author_styles = AuthorStyles::::from_ffi(author_styles); debug_assert!( @@ -375,7 +373,8 @@ impl<'ln> TNode for GeckoNode<'ln> { fn first_child(&self) -> Option { unsafe { self.0 - .mFirstChild.raw::() + .mFirstChild + .raw::() .as_ref() .map(GeckoNode::from_content) } @@ -395,7 +394,8 @@ impl<'ln> TNode for GeckoNode<'ln> { fn next_sibling(&self) -> Option { unsafe { self.0 - .mNextSibling.raw::() + .mNextSibling + .raw::() .as_ref() .map(GeckoNode::from_content) } @@ -600,7 +600,7 @@ impl<'le> GeckoElement<'le> { if self.is_svg_element() { let svg_class = unsafe { bindings::Gecko_GetSVGAnimatedClass(self.0).as_ref() }; if let Some(c) = svg_class { - return Some(c) + return Some(c); } } @@ -672,8 +672,7 @@ impl<'le> GeckoElement<'le> { // For the bit usage, see nsContentSlots::GetExtendedSlots. let e_slots = s._base.mExtendedSlots & !structs::nsIContent_nsContentSlots_sNonOwningExtendedSlotsFlag; - (e_slots as *const structs::FragmentOrElement_nsExtendedDOMSlots) - .as_ref() + (e_slots as *const structs::FragmentOrElement_nsExtendedDOMSlots).as_ref() }) } @@ -719,9 +718,8 @@ impl<'le> GeckoElement<'le> { .and_then(|n| n.as_element()); debug_assert!( - binding_parent == unsafe { - bindings::Gecko_GetBindingParent(self.0).map(GeckoElement) - } + binding_parent == + unsafe { bindings::Gecko_GetBindingParent(self.0).map(GeckoElement) } ); binding_parent } @@ -730,8 +728,9 @@ impl<'le> GeckoElement<'le> { #[inline] fn non_xul_xbl_binding_parent_raw_content(&self) -> *mut nsIContent { debug_assert!(!self.is_xul_element()); - self.extended_slots() - .map_or(ptr::null_mut(), |slots| slots._base.mBindingParent.raw::()) + self.extended_slots().map_or(ptr::null_mut(), |slots| { + slots._base.mBindingParent.raw::() + }) } #[inline] @@ -747,7 +746,8 @@ impl<'le> GeckoElement<'le> { #[inline] fn state_internal(&self) -> u64 { - if !self.as_node() + if !self + .as_node() .get_bool_flag(nsINode_BooleanFlag::ElementHasLockedStyleStates) { return self.0.mState.mStates; @@ -878,9 +878,7 @@ impl<'le> GeckoElement<'le> { return false; } match self.containing_shadow_host() { - Some(e) => { - e.is_svg_element() && e.local_name() == &*local_name!("use") - }, + Some(e) => e.is_svg_element() && e.local_name() == &*local_name!("use"), None => false, } } @@ -934,13 +932,12 @@ impl<'le> GeckoElement<'le> { debug_assert_eq!(to.is_some(), from.is_some()); - combined_duration > 0.0f32 && from != to && - from.unwrap() - .animate( - to.as_ref().unwrap(), - Procedure::Interpolate { progress: 0.5 }, - ) - .is_ok() + combined_duration > 0.0f32 && from != to && from + .unwrap() + .animate( + to.as_ref().unwrap(), + Procedure::Interpolate { progress: 0.5 }, + ).is_ok() } } @@ -980,7 +977,9 @@ fn get_animation_rule( let effect_count = unsafe { Gecko_GetAnimationEffectCount(element.0) }; // Also, we should try to reuse the PDB, to avoid creating extra rule nodes. let mut animation_values = AnimationValueMap::with_capacity_and_hasher( - effect_count.min(ANIMATABLE_PROPERTY_COUNT), Default::default()); + effect_count.min(ANIMATABLE_PROPERTY_COUNT), + Default::default(), + ); if unsafe { Gecko_GetAnimationRule( element.0, @@ -1084,10 +1083,12 @@ impl<'le> TElement for GeckoElement<'le> { fn inheritance_parent(&self) -> Option { if self.implemented_pseudo_element().is_some() { - return self.pseudo_element_originating_element() + return self.pseudo_element_originating_element(); } - self.as_node().flattened_tree_parent().and_then(|n| n.as_element()) + self.as_node() + .flattened_tree_parent() + .and_then(|n| n.as_element()) } fn traversal_children(&self) -> LayoutIterator> { @@ -1095,8 +1096,10 @@ impl<'le> TElement for GeckoElement<'le> { // StyleChildrenIterator::IsNeeded does, except that it might return // true if we used to (but no longer) have anonymous content from // ::before/::after, XBL bindings, or nsIAnonymousContentCreators. - if self.is_in_anonymous_subtree() || self.has_xbl_binding_with_content() || - self.is_html_slot_element() || self.shadow_root().is_some() || + if self.is_in_anonymous_subtree() || + self.has_xbl_binding_with_content() || + self.is_html_slot_element() || + self.shadow_root().is_some() || self.may_have_anonymous_children() { unsafe { @@ -1157,17 +1160,16 @@ impl<'le> TElement for GeckoElement<'le> { // Bug 1466580 tracks running the Android layout tests on automation. // // The actual bindgen bug still needs reduction. - let assigned_nodes: &[structs::RefPtr] = - if !cfg!(target_os = "android") { - debug_assert_eq!( - unsafe { bindings::Gecko_GetAssignedNodes(self.0) }, - &slot.mAssignedNodes as *const _, - ); + let assigned_nodes: &[structs::RefPtr] = if !cfg!(target_os = "android") { + debug_assert_eq!( + unsafe { bindings::Gecko_GetAssignedNodes(self.0) }, + &slot.mAssignedNodes as *const _, + ); - &*slot.mAssignedNodes - } else { - unsafe { &**bindings::Gecko_GetAssignedNodes(self.0) } - }; + &*slot.mAssignedNodes + } else { + unsafe { &**bindings::Gecko_GetAssignedNodes(self.0) } + }; debug_assert_eq!( mem::size_of::>(), @@ -1239,11 +1241,10 @@ impl<'le> TElement for GeckoElement<'le> { } fn owner_doc_matches_for_testing(&self, device: &Device) -> bool { - self.as_node().owner_doc().0 as *const structs::nsIDocument == - device - .pres_context() - .mDocument - .raw::() + self.as_node().owner_doc().0 as *const structs::nsIDocument == device + .pres_context() + .mDocument + .raw::() } fn style_attribute(&self) -> Option>> { @@ -1378,7 +1379,8 @@ impl<'le> TElement for GeckoElement<'le> { self.unset_flags( ELEMENT_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32 | ELEMENT_HAS_ANIMATION_ONLY_DIRTY_DESCENDANTS_FOR_SERVO as u32 | - NODE_DESCENDANTS_NEED_FRAMES as u32 | NODE_NEEDS_FRAME as u32, + NODE_DESCENDANTS_NEED_FRAMES as u32 | + NODE_NEEDS_FRAME as u32, ) } @@ -1438,8 +1440,10 @@ impl<'le> TElement for GeckoElement<'le> { unsafe fn clear_data(&self) { let ptr = self.0.mServoData.get(); self.unset_flags( - ELEMENT_HAS_SNAPSHOT as u32 | ELEMENT_HANDLED_SNAPSHOT as u32 | - structs::Element_kAllServoDescendantBits | NODE_NEEDS_FRAME as u32, + ELEMENT_HAS_SNAPSHOT as u32 | + ELEMENT_HANDLED_SNAPSHOT as u32 | + structs::Element_kAllServoDescendantBits | + NODE_NEEDS_FRAME as u32, ); if !ptr.is_null() { debug!("Dropping ElementData for {:?}", self); @@ -1668,8 +1672,7 @@ impl<'le> TElement for GeckoElement<'le> { let transition_property: TransitionProperty = property.into(); let mut property_check_helper = |property: LonghandId| -> bool { - let property = - property.to_physical(after_change_style.writing_mode); + let property = property.to_physical(after_change_style.writing_mode); transitions_to_keep.insert(property); self.needs_transitions_update_per_property( property, @@ -1681,8 +1684,7 @@ impl<'le> TElement for GeckoElement<'le> { }; match transition_property { - TransitionProperty::Custom(..) | - TransitionProperty::Unsupported(..) => {}, + TransitionProperty::Custom(..) | TransitionProperty::Unsupported(..) => {}, TransitionProperty::Shorthand(ref shorthand) => { if shorthand.longhands().any(property_check_helper) { return true; @@ -1713,11 +1715,7 @@ impl<'le> TElement for GeckoElement<'le> { } } - fn match_element_lang( - &self, - override_lang: Option>, - value: &Lang, - ) -> bool { + fn match_element_lang(&self, override_lang: Option>, value: &Lang) -> bool { // Gecko supports :lang() from CSS Selectors 3, which only accepts a // single language tag, and which performs simple dash-prefix matching // on it. @@ -1860,7 +1858,8 @@ impl<'le> TElement for GeckoElement<'le> { )); } - let active = self.state() + let active = self + .state() .intersects(NonTSPseudoClass::Active.state_flag()); if active { let declarations = unsafe { Gecko_GetActiveLinkAttrDeclarationBlock(self.0) }; @@ -2070,7 +2069,10 @@ impl<'le> ::selectors::Element for GeckoElement<'le> { #[inline] fn is_root(&self) -> bool { - if self.as_node().get_bool_flag(nsINode_BooleanFlag::ParentIsContent) { + if self + .as_node() + .get_bool_flag(nsINode_BooleanFlag::ParentIsContent) + { return false; } @@ -2078,12 +2080,17 @@ impl<'le> ::selectors::Element for GeckoElement<'le> { return false; } - debug_assert!(self.as_node().parent_node().map_or(false, |p| p.is_document())); + debug_assert!( + self.as_node() + .parent_node() + .map_or(false, |p| p.is_document()) + ); unsafe { bindings::Gecko_IsRootElement(self.0) } } fn is_empty(&self) -> bool { - !self.as_node() + !self + .as_node() .dom_children() .any(|child| unsafe { Gecko_IsSignificantChild(child.0, true) }) } @@ -2194,7 +2201,8 @@ impl<'le> ::selectors::Element for GeckoElement<'le> { }, NonTSPseudoClass::MozOnlyWhitespace => { flags_setter(self, ElementSelectorFlags::HAS_EMPTY_SELECTOR); - if self.as_node() + if self + .as_node() .dom_children() .any(|c| c.contains_non_whitespace_content()) { @@ -2246,9 +2254,7 @@ impl<'le> ::selectors::Element for GeckoElement<'le> { None => false, } }, - NonTSPseudoClass::Dir(ref dir) => { - self.state().intersects(dir.element_state()) - } + NonTSPseudoClass::Dir(ref dir) => self.state().intersects(dir.element_state()), } } diff --git a/components/style/gecko_bindings/mod.rs b/components/style/gecko_bindings/mod.rs index eb3f0d220bf5..166e2f66fd56 100644 --- a/components/style/gecko_bindings/mod.rs +++ b/components/style/gecko_bindings/mod.rs @@ -4,7 +4,12 @@ //! Gecko's C++ bindings, along with some rust helpers to ease its use. -#[allow(dead_code, improper_ctypes, non_camel_case_types, missing_docs)] +#[allow( + dead_code, + improper_ctypes, + non_camel_case_types, + missing_docs +)] pub mod bindings { include!(concat!(env!("OUT_DIR"), "/gecko/bindings.rs")); } @@ -13,8 +18,14 @@ pub mod bindings { // foreign structs to have `PhantomData`. We should remove this once the lint // ignores this case. -#[allow(dead_code, improper_ctypes, non_camel_case_types, non_snake_case, non_upper_case_globals, - missing_docs)] +#[allow( + dead_code, + improper_ctypes, + non_camel_case_types, + non_snake_case, + non_upper_case_globals, + missing_docs +)] pub mod structs { include!(concat!(env!("OUT_DIR"), "/gecko/structs.rs")); } diff --git a/components/style/gecko_bindings/sugar/ns_style_coord.rs b/components/style/gecko_bindings/sugar/ns_style_coord.rs index 3825c5520ecc..bc3b195524d5 100644 --- a/components/style/gecko_bindings/sugar/ns_style_coord.rs +++ b/components/style/gecko_bindings/sugar/ns_style_coord.rs @@ -52,7 +52,8 @@ impl nsStyleCoord_CalcValue { impl PartialEq for nsStyleCoord_CalcValue { fn eq(&self, other: &Self) -> bool { - self.mLength == other.mLength && self.mPercent == other.mPercent && + self.mLength == other.mLength && + self.mPercent == other.mPercent && self.mHasPercent == other.mHasPercent } } @@ -409,9 +410,12 @@ pub unsafe trait CoordData { unsafe fn get_float(&self) -> f32 { use gecko_bindings::structs::nsStyleUnit::*; debug_assert!( - self.unit() == eStyleUnit_Percent || self.unit() == eStyleUnit_Factor || - self.unit() == eStyleUnit_Degree || self.unit() == eStyleUnit_Grad || - self.unit() == eStyleUnit_Radian || self.unit() == eStyleUnit_Turn || + self.unit() == eStyleUnit_Percent || + self.unit() == eStyleUnit_Factor || + self.unit() == eStyleUnit_Degree || + self.unit() == eStyleUnit_Grad || + self.unit() == eStyleUnit_Radian || + self.unit() == eStyleUnit_Turn || self.unit() == eStyleUnit_FlexFraction ); *self.union().mFloat.as_ref() @@ -422,7 +426,8 @@ pub unsafe trait CoordData { unsafe fn get_integer(&self) -> i32 { use gecko_bindings::structs::nsStyleUnit::*; debug_assert!( - self.unit() == eStyleUnit_Coord || self.unit() == eStyleUnit_Integer || + self.unit() == eStyleUnit_Coord || + self.unit() == eStyleUnit_Integer || self.unit() == eStyleUnit_Enumerated ); *self.union().mInt.as_ref() diff --git a/components/style/gecko_bindings/sugar/refptr.rs b/components/style/gecko_bindings/sugar/refptr.rs index 6a32b81430e1..835e77098c93 100644 --- a/components/style/gecko_bindings/sugar/refptr.rs +++ b/components/style/gecko_bindings/sugar/refptr.rs @@ -321,8 +321,4 @@ unsafe fn addref_atom(atom: *mut structs::nsAtom) { unsafe fn release_atom(atom: *mut structs::nsAtom) { let _ = Atom::from_addrefed(atom); } -impl_threadsafe_refcount!( - structs::nsAtom, - addref_atom, - release_atom -); +impl_threadsafe_refcount!(structs::nsAtom, addref_atom, release_atom); diff --git a/components/style/gecko_bindings/sugar/style_complex_color.rs b/components/style/gecko_bindings/sugar/style_complex_color.rs index 90e93b72fd08..c2b3b1c62709 100644 --- a/components/style/gecko_bindings/sugar/style_complex_color.rs +++ b/components/style/gecko_bindings/sugar/style_complex_color.rs @@ -59,7 +59,7 @@ impl From for StyleComplexColor { mFgRatio: ratios.fg, mTag: Tag::eComplex, } - } + }, } } } @@ -70,11 +70,11 @@ impl From for ComputedColor { Tag::eNumeric => { debug_assert!(other.mBgRatio == 1. && other.mFgRatio == 0.); GenericColor::Numeric(convert_nscolor_to_rgba(other.mColor)) - } + }, Tag::eForeground => { debug_assert!(other.mBgRatio == 0. && other.mFgRatio == 1.); GenericColor::Foreground - } + }, Tag::eComplex => { debug_assert!(other.mBgRatio != 1. || other.mFgRatio != 0.); debug_assert!(other.mBgRatio != 0. || other.mFgRatio != 1.); @@ -85,7 +85,7 @@ impl From for ComputedColor { fg: other.mFgRatio, }, ) - } + }, Tag::eAuto => unreachable!("Unsupport StyleComplexColor with tag eAuto"), } } diff --git a/components/style/invalidation/element/element_wrapper.rs b/components/style/invalidation/element/element_wrapper.rs index e788d2dd8761..cd1b1d13a256 100644 --- a/components/style/invalidation/element/element_wrapper.rs +++ b/components/style/invalidation/element/element_wrapper.rs @@ -46,7 +46,9 @@ pub trait ElementSnapshot: Sized { /// Gets the attribute information of the snapshot as a string. /// /// Only for debugging purposes. - fn debug_list_attributes(&self) -> String { String::new() } + fn debug_list_attributes(&self) -> String { + String::new() + } /// The ID attribute per this snapshot. Should only be called if /// `has_attrs()` returns true. @@ -233,7 +235,8 @@ where // :lang() needs to match using the closest ancestor xml:lang="" or // lang="" attribtue from snapshots. NonTSPseudoClass::Lang(ref lang_arg) => { - return self.element + return self + .element .match_element_lang(Some(self.get_lang()), lang_arg); }, @@ -242,12 +245,14 @@ where let flag = pseudo_class.state_flag(); if flag.is_empty() { - return self.element + return self + .element .match_non_ts_pseudo_class(pseudo_class, context, &mut |_, _| {}); } match self.snapshot().and_then(|s| s.state()) { Some(snapshot_state) => snapshot_state.intersects(flag), - None => self.element + None => self + .element .match_non_ts_pseudo_class(pseudo_class, context, &mut |_, _| {}), } } diff --git a/components/style/invalidation/element/invalidation_map.rs b/components/style/invalidation/element/invalidation_map.rs index 26a4609760f1..038852a6dd4a 100644 --- a/components/style/invalidation/element/invalidation_map.rs +++ b/components/style/invalidation/element/invalidation_map.rs @@ -38,8 +38,10 @@ use smallvec::SmallVec; #[derive(Clone, Debug, MallocSizeOf)] pub struct Dependency { /// The dependency selector. - #[cfg_attr(feature = "gecko", - ignore_malloc_size_of = "CssRules have primary refs, we measure there")] + #[cfg_attr( + feature = "gecko", + ignore_malloc_size_of = "CssRules have primary refs, we measure there" + )] #[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")] pub selector: Selector, @@ -127,8 +129,10 @@ impl SelectorMapEntry for StateDependency { pub struct DocumentStateDependency { /// The selector that is affected. We don't need to track an offset, since /// when it changes it changes for the whole document anyway. - #[cfg_attr(feature = "gecko", - ignore_malloc_size_of = "CssRules have primary refs, we measure there")] + #[cfg_attr( + feature = "gecko", + ignore_malloc_size_of = "CssRules have primary refs, we measure there" + )] #[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")] pub selector: Selector, /// The state this dependency is affected by. @@ -185,7 +189,8 @@ impl InvalidationMap { /// Returns the number of dependencies stored in the invalidation map. pub fn len(&self) -> usize { - self.state_affecting_selectors.len() + self.document_state_selectors.len() + + self.state_affecting_selectors.len() + + self.document_state_selectors.len() + self.other_attribute_affecting_selectors.len() + self.id_to_selector .iter() diff --git a/components/style/invalidation/element/restyle_hints.rs b/components/style/invalidation/element/restyle_hints.rs index 4ac06c8b1631..18e2f96470a6 100644 --- a/components/style/invalidation/element/restyle_hints.rs +++ b/components/style/invalidation/element/restyle_hints.rs @@ -67,7 +67,8 @@ impl RestyleHint { /// Returns whether we need to restyle this element. pub fn has_non_animation_invalidations(&self) -> bool { self.intersects( - RestyleHint::RESTYLE_SELF | RestyleHint::RECASCADE_SELF | + RestyleHint::RESTYLE_SELF | + RestyleHint::RECASCADE_SELF | (Self::replacements() & !Self::for_animations()), ) } @@ -119,7 +120,8 @@ impl RestyleHint { /// The replacements for the animation cascade levels. #[inline] pub fn for_animations() -> Self { - RestyleHint::RESTYLE_SMIL | RestyleHint::RESTYLE_CSS_ANIMATIONS | + RestyleHint::RESTYLE_SMIL | + RestyleHint::RESTYLE_CSS_ANIMATIONS | RestyleHint::RESTYLE_CSS_TRANSITIONS } diff --git a/components/style/invalidation/element/state_and_attributes.rs b/components/style/invalidation/element/state_and_attributes.rs index d13da58a89bb..bf259bb6f025 100644 --- a/components/style/invalidation/element/state_and_attributes.rs +++ b/components/style/invalidation/element/state_and_attributes.rs @@ -200,17 +200,12 @@ where debug!(" > state: {:?}", state_changes); } if snapshot.id_changed() { - debug!( - " > id changed: +{:?} -{:?}", - id_added, - id_removed - ); + debug!(" > id changed: +{:?} -{:?}", id_added, id_removed); } if snapshot.class_changed() { debug!( " > class changed: +{:?} -{:?}", - classes_added, - classes_removed + classes_added, classes_removed ); } if snapshot.other_attr_changed() { @@ -233,7 +228,6 @@ where shadow_rule_datas.push((data, quirks_mode, host.map(|h| h.opaque()))) }); - let invalidated_self = { let mut collector = Collector { wrapper, @@ -410,10 +404,7 @@ where } /// Check whether a dependency should be taken into account. - fn check_dependency( - &mut self, - dependency: &Dependency, - ) -> bool { + fn check_dependency(&mut self, dependency: &Dependency) -> bool { let element = &self.element; let wrapper = &self.wrapper; let matches_now = matches_selector( diff --git a/components/style/lib.rs b/components/style/lib.rs index 03caab33e190..57d507a4ab4c 100644 --- a/components/style/lib.rs +++ b/components/style/lib.rs @@ -200,7 +200,6 @@ pub mod gecko; #[allow(unsafe_code)] pub mod servo; - #[cfg(feature = "gecko")] #[allow(unsafe_code, missing_docs)] pub mod gecko_properties { diff --git a/components/style/logical_geometry.rs b/components/style/logical_geometry.rs index b345c2ad3752..8c677c210bfb 100644 --- a/components/style/logical_geometry.rs +++ b/components/style/logical_geometry.rs @@ -957,8 +957,10 @@ impl LogicalMargin { impl LogicalMargin { #[inline] pub fn is_zero(&self) -> bool { - self.block_start == Zero::zero() && self.inline_end == Zero::zero() && - self.block_end == Zero::zero() && self.inline_start == Zero::zero() + self.block_start == Zero::zero() && + self.inline_end == Zero::zero() && + self.block_end == Zero::zero() && + self.inline_start == Zero::zero() } } diff --git a/components/style/macros.rs b/components/style/macros.rs index 671ba35b8bc0..588893893365 100644 --- a/components/style/macros.rs +++ b/components/style/macros.rs @@ -68,9 +68,19 @@ macro_rules! try_match_ident_ignore_ascii_case { macro_rules! define_keyword_type { ($name:ident, $css:expr) => { #[allow(missing_docs)] - #[derive(Animate, Clone, ComputeSquaredDistance, Copy, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, - ToComputedValue, ToCss)] + #[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToComputedValue, + ToCss, + )] pub struct $name; impl fmt::Debug for $name { diff --git a/components/style/matching.rs b/components/style/matching.rs index 6f239d361d86..922ecad9eb4e 100644 --- a/components/style/matching.rs +++ b/components/style/matching.rs @@ -356,10 +356,9 @@ trait PrivateMatchMethods: TElement { tasks.insert(UpdateAnimationsTasks::CSS_ANIMATIONS); } - let before_change_style = if self.might_need_transitions_update( - old_values.as_ref().map(|s| &**s), - new_values, - ) { + let before_change_style = if self + .might_need_transitions_update(old_values.as_ref().map(|s| &**s), new_values) + { let after_change_style = if self.has_css_transitions() { self.after_change_style(context, new_values) } else { @@ -469,9 +468,11 @@ trait PrivateMatchMethods: TElement { pseudo: Option<&PseudoElement>, ) -> ChildCascadeRequirement { debug!("accumulate_damage_for: {:?}", self); - debug_assert!(!shared_context - .traversal_flags - .contains(TraversalFlags::Forgetful)); + debug_assert!( + !shared_context + .traversal_flags + .contains(TraversalFlags::Forgetful) + ); let difference = self.compute_style_difference(old_values, new_values, pseudo); diff --git a/components/style/media_queries/media_condition.rs b/components/style/media_queries/media_condition.rs index dbd677d0aee4..78252db8c0b1 100644 --- a/components/style/media_queries/media_condition.rs +++ b/components/style/media_queries/media_condition.rs @@ -53,12 +53,12 @@ impl ToCss for MediaCondition { MediaCondition::Not(ref c) => { dest.write_str("not ")?; c.to_css(dest) - } + }, MediaCondition::InParens(ref c) => { dest.write_char('(')?; c.to_css(dest)?; dest.write_char(')') - } + }, MediaCondition::Operation(ref list, op) => { let mut iter = list.iter(); iter.next().unwrap().to_css(dest)?; @@ -69,7 +69,7 @@ impl ToCss for MediaCondition { item.to_css(dest)?; } Ok(()) - } + }, } } } @@ -104,14 +104,12 @@ impl MediaCondition { let is_negation = match *input.next()? { Token::ParenthesisBlock => false, Token::Ident(ref ident) if ident.eq_ignore_ascii_case("not") => true, - ref t => { - return Err(location.new_unexpected_token_error(t.clone())) - } + ref t => return Err(location.new_unexpected_token_error(t.clone())), }; if is_negation { let inner_condition = Self::parse_in_parens(context, input)?; - return Ok(MediaCondition::Not(Box::new(inner_condition))) + return Ok(MediaCondition::Not(Box::new(inner_condition))); } // ParenthesisBlock. @@ -162,7 +160,7 @@ impl MediaCondition { input.parse_nested_block(|input| { // Base case. if let Ok(inner) = input.try(|i| Self::parse(context, i)) { - return Ok(MediaCondition::InParens(Box::new(inner))) + return Ok(MediaCondition::InParens(Box::new(inner))); } let expr = MediaFeatureExpression::parse_in_parenthesis_block(context, input)?; Ok(MediaCondition::Feature(expr)) @@ -178,14 +176,10 @@ impl MediaCondition { MediaCondition::Operation(ref conditions, op) => { let mut iter = conditions.iter(); match op { - Operator::And => { - iter.all(|c| c.matches(device, quirks_mode)) - } - Operator::Or => { - iter.any(|c| c.matches(device, quirks_mode)) - } + Operator::And => iter.all(|c| c.matches(device, quirks_mode)), + Operator::Or => iter.any(|c| c.matches(device, quirks_mode)), } - } + }, } } } diff --git a/components/style/media_queries/media_feature.rs b/components/style/media_queries/media_feature.rs index 5a5bc88863e4..771a11e8fbbe 100644 --- a/components/style/media_queries/media_feature.rs +++ b/components/style/media_queries/media_feature.rs @@ -30,10 +30,9 @@ type MediaFeatureEvaluator = fn( pub type KeywordSerializer = fn(KeywordDiscriminant) -> String; /// Parses a given identifier. -pub type KeywordParser = for <'a, 'i, 't> fn( - context: &'a ParserContext, - input: &'a mut Parser<'i, 't>, -) -> Result>; +pub type KeywordParser = + for<'a, 'i, 't> fn(context: &'a ParserContext, input: &'a mut Parser<'i, 't>) + -> Result>; /// An evaluator for a given media feature. /// @@ -70,50 +69,49 @@ pub enum Evaluator { /// asserts if that's not true. As of today there's nothing like that (does that /// even make sense?). macro_rules! keyword_evaluator { - ($actual_evaluator:ident, $keyword_type:ty) => { - { - fn __parse<'i, 't>( - context: &$crate::parser::ParserContext, - input: &mut $crate::cssparser::Parser<'i, 't>, - ) -> Result< - $crate::media_queries::media_feature::KeywordDiscriminant, - ::style_traits::ParseError<'i>, - > { - let kw = <$keyword_type as $crate::parser::Parse>::parse(context, input)?; - Ok(kw as $crate::media_queries::media_feature::KeywordDiscriminant) - } - - fn __serialize(kw: $crate::media_queries::media_feature::KeywordDiscriminant) -> String { - // This unwrap is ok because the only discriminants that get - // back to us is the ones that `parse` produces. - let value: $keyword_type = - ::num_traits::cast::FromPrimitive::from_u8(kw).unwrap(); - <$keyword_type as ::style_traits::ToCss>::to_css_string(&value) - } - - fn __evaluate( - device: &$crate::media_queries::Device, - value: Option<$crate::media_queries::media_feature::KeywordDiscriminant>, - range_or_operator: Option<$crate::media_queries::media_feature_expression::RangeOrOperator>, - ) -> bool { - debug_assert!( - range_or_operator.is_none(), - "Since when do keywords accept ranges?" - ); - // This unwrap is ok because the only discriminants that get - // back to us is the ones that `parse` produces. - let value: Option<$keyword_type> = - value.map(|kw| ::num_traits::cast::FromPrimitive::from_u8(kw).unwrap()); - $actual_evaluator(device, value) - } - - $crate::media_queries::media_feature::Evaluator::Enumerated { - parser: __parse, - serializer: __serialize, - evaluator: __evaluate, - } + ($actual_evaluator:ident, $keyword_type:ty) => {{ + fn __parse<'i, 't>( + context: &$crate::parser::ParserContext, + input: &mut $crate::cssparser::Parser<'i, 't>, + ) -> Result< + $crate::media_queries::media_feature::KeywordDiscriminant, + ::style_traits::ParseError<'i>, + > { + let kw = <$keyword_type as $crate::parser::Parse>::parse(context, input)?; + Ok(kw as $crate::media_queries::media_feature::KeywordDiscriminant) } - } + + fn __serialize(kw: $crate::media_queries::media_feature::KeywordDiscriminant) -> String { + // This unwrap is ok because the only discriminants that get + // back to us is the ones that `parse` produces. + let value: $keyword_type = ::num_traits::cast::FromPrimitive::from_u8(kw).unwrap(); + <$keyword_type as ::style_traits::ToCss>::to_css_string(&value) + } + + fn __evaluate( + device: &$crate::media_queries::Device, + value: Option<$crate::media_queries::media_feature::KeywordDiscriminant>, + range_or_operator: Option< + $crate::media_queries::media_feature_expression::RangeOrOperator, + >, + ) -> bool { + debug_assert!( + range_or_operator.is_none(), + "Since when do keywords accept ranges?" + ); + // This unwrap is ok because the only discriminants that get + // back to us is the ones that `parse` produces. + let value: Option<$keyword_type> = + value.map(|kw| ::num_traits::cast::FromPrimitive::from_u8(kw).unwrap()); + $actual_evaluator(device, value) + } + + $crate::media_queries::media_feature::Evaluator::Enumerated { + parser: __parse, + serializer: __serialize, + evaluator: __evaluate, + } + }}; } bitflags! { @@ -169,7 +167,7 @@ macro_rules! feature { evaluator: $evaluator, requirements: $reqs, } - } + }; } impl fmt::Debug for MediaFeatureDescription { diff --git a/components/style/media_queries/media_feature_expression.rs b/components/style/media_queries/media_feature_expression.rs index f07b8cc27e4b..64406218e889 100644 --- a/components/style/media_queries/media_feature_expression.rs +++ b/components/style/media_queries/media_feature_expression.rs @@ -102,13 +102,9 @@ pub enum RangeOrOperator { impl RangeOrOperator { /// Evaluate a given range given an optional query value and a value from /// the browser. - pub fn evaluate( - range_or_op: Option, - query_value: Option, - value: T, - ) -> bool + pub fn evaluate(range_or_op: Option, query_value: Option, value: T) -> bool where - T: PartialOrd + Zero + T: PartialOrd + Zero, { match query_value { Some(v) => Self::evaluate_with_query_value(range_or_op, v, value), @@ -118,11 +114,7 @@ impl RangeOrOperator { /// Evaluate a given range given a non-optional query value and a value from /// the browser. - pub fn evaluate_with_query_value( - range_or_op: Option, - query_value: T, - value: T, - ) -> bool + pub fn evaluate_with_query_value(range_or_op: Option, query_value: T, value: T) -> bool where T: PartialOrd, { @@ -142,20 +134,14 @@ impl RangeOrOperator { Range::Min => cmp == Ordering::Greater, Range::Max => cmp == Ordering::Less, } - } - RangeOrOperator::Operator(op) => { - match op { - Operator::Equal => cmp == Ordering::Equal, - Operator::GreaterThan => cmp == Ordering::Greater, - Operator::GreaterThanEqual => { - cmp == Ordering::Equal || cmp == Ordering::Greater - } - Operator::LessThan => cmp == Ordering::Less, - Operator::LessThanEqual => { - cmp == Ordering::Equal || cmp == Ordering::Less - } - } - } + }, + RangeOrOperator::Operator(op) => match op { + Operator::Equal => cmp == Ordering::Equal, + Operator::GreaterThan => cmp == Ordering::Greater, + Operator::GreaterThanEqual => cmp == Ordering::Equal || cmp == Ordering::Greater, + Operator::LessThan => cmp == Ordering::Less, + Operator::LessThanEqual => cmp == Ordering::Equal || cmp == Ordering::Less, + }, } } } @@ -172,8 +158,8 @@ pub struct MediaFeatureExpression { impl PartialEq for MediaFeatureExpression { fn eq(&self, other: &Self) -> bool { self.feature as *const _ == other.feature as *const _ && - self.value == other.value && - self.range_or_operator == other.range_or_operator + self.value == other.value && + self.range_or_operator == other.range_or_operator } } @@ -184,7 +170,11 @@ impl ToCss for MediaFeatureExpression { { dest.write_str("(")?; - if self.feature.requirements.contains(ParsingRequirements::WEBKIT_PREFIX) { + if self + .feature + .requirements + .contains(ParsingRequirements::WEBKIT_PREFIX) + { dest.write_str("-webkit-")?; } @@ -215,9 +205,7 @@ impl ToCss for MediaFeatureExpression { } /// Consumes an operation or a colon, or returns an error. -fn consume_operation_or_colon( - input: &mut Parser, -) -> Result, ()> { +fn consume_operation_or_colon(input: &mut Parser) -> Result, ()> { let first_delim = { let next_token = match input.next() { Ok(t) => t, @@ -238,14 +226,14 @@ fn consume_operation_or_colon( } else { Operator::GreaterThan } - } + }, '<' => { if input.try(|i| i.expect_delim('=')).is_ok() { Operator::LessThanEqual } else { Operator::LessThan } - } + }, _ => return Err(()), })) } @@ -256,7 +244,11 @@ impl MediaFeatureExpression { value: Option, range_or_operator: Option, ) -> Self { - Self { feature, value, range_or_operator } + Self { + feature, + value, + range_or_operator, + } } /// Parse a media expression of the form: @@ -269,9 +261,7 @@ impl MediaFeatureExpression { input: &mut Parser<'i, 't>, ) -> Result> { input.expect_parenthesis_block()?; - input.parse_nested_block(|input| { - Self::parse_in_parenthesis_block(context, input) - }) + input.parse_nested_block(|input| Self::parse_in_parenthesis_block(context, input)) } /// Parse a media feature expression where we've already consumed the @@ -294,9 +284,7 @@ impl MediaFeatureExpression { let mut requirements = ParsingRequirements::empty(); - if context.chrome_rules_enabled() || - context.stylesheet_origin == Origin::UserAgent - { + if context.chrome_rules_enabled() || context.stylesheet_origin == Origin::UserAgent { requirements.insert(ParsingRequirements::CHROME_AND_UA_ONLY); } @@ -313,7 +301,9 @@ impl MediaFeatureExpression { if unsafe { structs::StaticPrefs_sVarCache_layout_css_prefixes_device_pixel_ratio_webkit } { - requirements.insert(ParsingRequirements::WEBKIT_DEVICE_PIXEL_RATIO_PREF_ENABLED); + requirements.insert( + ParsingRequirements::WEBKIT_DEVICE_PIXEL_RATIO_PREF_ENABLED, + ); } } } @@ -370,45 +360,41 @@ impl MediaFeatureExpression { // Gecko doesn't allow ranged expressions without a // value, so just reject them here too. if range.is_some() { - return Err(input.new_custom_error( - StyleParseErrorKind::RangedExpressionWithNoValue - )); + return Err( + input.new_custom_error(StyleParseErrorKind::RangedExpressionWithNoValue) + ); } return Ok(Self::new(feature, None, None)); - } + }, Ok(operator) => operator, }; let range_or_operator = match range { Some(range) => { if operator.is_some() { - return Err(input.new_custom_error( - StyleParseErrorKind::MediaQueryUnexpectedOperator - )); + return Err( + input.new_custom_error(StyleParseErrorKind::MediaQueryUnexpectedOperator) + ); } Some(RangeOrOperator::Range(range)) - } - None => { - match operator { - Some(operator) => { - if !feature.allows_ranges() { - return Err(input.new_custom_error( - StyleParseErrorKind::MediaQueryUnexpectedOperator - )); - } - Some(RangeOrOperator::Operator(operator)) + }, + None => match operator { + Some(operator) => { + if !feature.allows_ranges() { + return Err(input + .new_custom_error(StyleParseErrorKind::MediaQueryUnexpectedOperator)); } - None => None, - } - } + Some(RangeOrOperator::Operator(operator)) + }, + None => None, + }, }; - let value = - MediaExpressionValue::parse(feature, context, input).map_err(|err| { - err.location - .new_custom_error(StyleParseErrorKind::MediaQueryExpectedFeatureValue) - })?; + let value = MediaExpressionValue::parse(feature, context, input).map_err(|err| { + err.location + .new_custom_error(StyleParseErrorKind::MediaQueryExpectedFeatureValue) + })?; Ok(Self::new(feature, Some(value), range_or_operator)) } @@ -419,13 +405,11 @@ impl MediaFeatureExpression { macro_rules! expect { ($variant:ident) => { - value.map(|value| { - match *value { - MediaExpressionValue::$variant(ref v) => v, - _ => unreachable!("Unexpected MediaExpressionValue"), - } + value.map(|value| match *value { + MediaExpressionValue::$variant(ref v) => v, + _ => unreachable!("Unexpected MediaExpressionValue"), }) - } + }; } match self.feature.evaluator { @@ -436,13 +420,11 @@ impl MediaFeatureExpression { }) }); eval(device, computed, self.range_or_operator) - } + }, Evaluator::Integer(eval) => { eval(device, expect!(Integer).cloned(), self.range_or_operator) - } - Evaluator::Float(eval) => { - eval(device, expect!(Float).cloned(), self.range_or_operator) - } + }, + Evaluator::Float(eval) => eval(device, expect!(Float).cloned(), self.range_or_operator), Evaluator::IntRatio(eval) => { eval(device, expect!(IntRatio).cloned(), self.range_or_operator) }, @@ -453,20 +435,16 @@ impl MediaFeatureExpression { }) }); eval(device, computed, self.range_or_operator) - } + }, Evaluator::Enumerated { evaluator, .. } => { - evaluator( - device, - expect!(Enumerated).cloned(), - self.range_or_operator, - ) - } - Evaluator::Ident(eval) => { - eval(device, expect!(Ident).cloned(), self.range_or_operator) - } - Evaluator::BoolInteger(eval) => { - eval(device, expect!(BoolInteger).cloned(), self.range_or_operator) - } + evaluator(device, expect!(Enumerated).cloned(), self.range_or_operator) + }, + Evaluator::Ident(eval) => eval(device, expect!(Ident).cloned(), self.range_or_operator), + Evaluator::BoolInteger(eval) => eval( + device, + expect!(BoolInteger).cloned(), + self.range_or_operator, + ), } } } @@ -502,11 +480,7 @@ pub enum MediaExpressionValue { } impl MediaExpressionValue { - fn to_css( - &self, - dest: &mut CssWriter, - for_expr: &MediaFeatureExpression, - ) -> fmt::Result + fn to_css(&self, dest: &mut CssWriter, for_expr: &MediaFeatureExpression) -> fmt::Result where W: fmt::Write, { @@ -515,18 +489,12 @@ impl MediaExpressionValue { MediaExpressionValue::Integer(v) => v.to_css(dest), MediaExpressionValue::Float(v) => v.to_css(dest), MediaExpressionValue::BoolInteger(v) => dest.write_str(if v { "1" } else { "0" }), - MediaExpressionValue::IntRatio(ratio) => { - ratio.to_css(dest) - }, + MediaExpressionValue::IntRatio(ratio) => ratio.to_css(dest), MediaExpressionValue::Resolution(ref r) => r.to_css(dest), MediaExpressionValue::Ident(ref ident) => serialize_atom_identifier(ident, dest), - MediaExpressionValue::Enumerated(value) => { - match for_expr.feature.evaluator { - Evaluator::Enumerated { serializer, .. } => { - dest.write_str(&*serializer(value)) - } - _ => unreachable!(), - } + MediaExpressionValue::Enumerated(value) => match for_expr.feature.evaluator { + Evaluator::Enumerated { serializer, .. } => dest.write_str(&*serializer(value)), + _ => unreachable!(), }, } } @@ -540,11 +508,11 @@ impl MediaExpressionValue { Evaluator::Length(..) => { let length = Length::parse_non_negative(context, input)?; MediaExpressionValue::Length(length) - } + }, Evaluator::Integer(..) => { let integer = Integer::parse_non_negative(context, input)?; MediaExpressionValue::Integer(integer.value() as u32) - } + }, Evaluator::BoolInteger(..) => { let integer = Integer::parse_non_negative(context, input)?; let value = integer.value(); @@ -552,29 +520,26 @@ impl MediaExpressionValue { return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } MediaExpressionValue::BoolInteger(value == 1) - } + }, Evaluator::Float(..) => { let number = Number::parse(context, input)?; MediaExpressionValue::Float(number.get()) - } + }, Evaluator::IntRatio(..) => { let a = Integer::parse_positive(context, input)?; input.expect_delim('/')?; let b = Integer::parse_positive(context, input)?; - MediaExpressionValue::IntRatio(AspectRatio( - a.value() as u32, - b.value() as u32 - )) - } + MediaExpressionValue::IntRatio(AspectRatio(a.value() as u32, b.value() as u32)) + }, Evaluator::Resolution(..) => { MediaExpressionValue::Resolution(Resolution::parse(context, input)?) - } + }, Evaluator::Enumerated { parser, .. } => { MediaExpressionValue::Enumerated(parser(context, input)?) - } + }, Evaluator::Ident(..) => { MediaExpressionValue::Ident(Atom::from(input.expect_ident()?.as_ref())) - } + }, }) } } diff --git a/components/style/media_queries/media_list.rs b/components/style/media_queries/media_list.rs index f8d15df7257d..168671288cfd 100644 --- a/components/style/media_queries/media_list.rs +++ b/components/style/media_queries/media_list.rs @@ -30,10 +30,7 @@ impl MediaList { /// "not all", see: /// /// - pub fn parse( - context: &ParserContext, - input: &mut Parser, - ) -> Self { + pub fn parse(context: &ParserContext, input: &mut Parser) -> Self { if input.is_exhausted() { return Self::empty(); } @@ -48,8 +45,10 @@ impl MediaList { Err(err) => { media_queries.push(MediaQuery::never_matching()); let location = err.location; - let error = - ContextualParseError::InvalidMediaRule(input.slice_from(start_position), err); + let error = ContextualParseError::InvalidMediaRule( + input.slice_from(start_position), + err, + ); context.log_css_error(location, error); }, } @@ -79,8 +78,10 @@ impl MediaList { let media_match = mq.media_type.matches(device.media_type()); // Check if the media condition match. - let query_match = media_match && - mq.condition.as_ref().map_or(true, |c| c.matches(device, quirks_mode)); + let query_match = media_match && mq + .condition + .as_ref() + .map_or(true, |c| c.matches(device, quirks_mode)); // Apply the logical NOT qualifier to the result match mq.qualifier { diff --git a/components/style/media_queries/media_query.rs b/components/style/media_queries/media_query.rs index 089fc9412b24..46c35618b228 100644 --- a/components/style/media_queries/media_query.rs +++ b/components/style/media_queries/media_query.rs @@ -15,7 +15,6 @@ use style_traits::{CssWriter, ParseError, ToCss}; use super::media_condition::MediaCondition; use values::CustomIdent; - /// #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToCss)] pub enum Qualifier { @@ -125,12 +124,13 @@ impl MediaQuery { context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result> { - let (qualifier, explicit_media_type) = input.try(|input| -> Result<_, ()> { - let qualifier = input.try(Qualifier::parse).ok(); - let ident = input.expect_ident().map_err(|_| ())?; - let media_type = MediaQueryType::parse(&ident)?; - Ok((qualifier, Some(media_type))) - }).unwrap_or_default(); + let (qualifier, explicit_media_type) = input + .try(|input| -> Result<_, ()> { + let qualifier = input.try(Qualifier::parse).ok(); + let ident = input.expect_ident().map_err(|_| ())?; + let media_type = MediaQueryType::parse(&ident)?; + Ok((qualifier, Some(media_type))) + }).unwrap_or_default(); let condition = if explicit_media_type.is_none() { Some(MediaCondition::parse(context, input)?) @@ -141,7 +141,11 @@ impl MediaQuery { }; let media_type = explicit_media_type.unwrap_or(MediaQueryType::All); - Ok(Self { qualifier, media_type, condition }) + Ok(Self { + qualifier, + media_type, + condition, + }) } } diff --git a/components/style/parser.rs b/components/style/parser.rs index db5b8f1e7f96..2d667f3f3431 100644 --- a/components/style/parser.rs +++ b/components/style/parser.rs @@ -137,11 +137,7 @@ impl<'a> ParserContext<'a> { } /// Record a CSS parse error with this context’s error reporting. - pub fn log_css_error( - &self, - location: SourceLocation, - error: ContextualParseError, - ) { + pub fn log_css_error(&self, location: SourceLocation, error: ContextualParseError) { let error_reporter = match self.error_reporter { Some(r) => r, None => return, diff --git a/components/style/rule_tree/mod.rs b/components/style/rule_tree/mod.rs index 5414b254aaec..d4fb0d009250 100644 --- a/components/style/rule_tree/mod.rs +++ b/components/style/rule_tree/mod.rs @@ -488,7 +488,8 @@ impl RuleTree { return path.clone(); } - let iter = path.self_and_ancestors() + let iter = path + .self_and_ancestors() .take_while(|node| node.cascade_level() >= CascadeLevel::SMILOverride); let mut last = path; let mut children = SmallVec::<[_; 10]>::new(); @@ -1452,7 +1453,8 @@ impl StrongRuleNode { // transitions and animations are present for a given element and // property, transitions are suppressed so that they don't actually // override animations. - let iter = self.self_and_ancestors() + let iter = self + .self_and_ancestors() .skip_while(|node| node.cascade_level() == CascadeLevel::Transitions) .take_while(|node| node.cascade_level() > CascadeLevel::Animations); let mut result = (LonghandIdSet::new(), false); diff --git a/components/style/selector_map.rs b/components/style/selector_map.rs index 3ab78ce2d87b..1e35f748917e 100644 --- a/components/style/selector_map.rs +++ b/components/style/selector_map.rs @@ -287,7 +287,9 @@ impl SelectorMap { context, flags_setter, ) { - matching_rules.push(rule.to_applicable_declaration_block(cascade_level, shadow_cascade_order)); + matching_rules.push( + rule.to_applicable_declaration_block(cascade_level, shadow_cascade_order), + ); } } } @@ -305,10 +307,12 @@ impl SelectorMap { let vector = match find_bucket(entry.selector()) { Bucket::Root => &mut self.root, - Bucket::ID(id) => self.id_hash + Bucket::ID(id) => self + .id_hash .try_entry(id.clone(), quirks_mode)? .or_insert_with(SmallVec::new), - Bucket::Class(class) => self.class_hash + Bucket::Class(class) => self + .class_hash .try_entry(class.clone(), quirks_mode)? .or_insert_with(SmallVec::new), Bucket::LocalName { name, lower_name } => { @@ -333,7 +337,8 @@ impl SelectorMap { .try_entry(name.clone())? .or_insert_with(SmallVec::new) }, - Bucket::Namespace(url) => self.namespace_hash + Bucket::Namespace(url) => self + .namespace_hash .try_entry(url.clone())? .or_insert_with(SmallVec::new), Bucket::Universal => &mut self.other, @@ -490,8 +495,9 @@ fn specific_bucket_for<'a>(component: &'a Component) -> Bucket<'a> name: &selector.name, lower_name: &selector.lower_name, }, - Component::Namespace(_, ref url) | - Component::DefaultNamespace(ref url) => Bucket::Namespace(url), + Component::Namespace(_, ref url) | Component::DefaultNamespace(ref url) => { + Bucket::Namespace(url) + }, // ::slotted(..) isn't a normal pseudo-element, so we can insert it on // the rule hash normally without much problem. For example, in a // selector like: @@ -534,7 +540,7 @@ fn find_bucket<'a>(mut iter: SelectorIter<'a, SelectorImpl>) -> Bucket<'a> { Bucket::Root => return new_bucket, Bucket::ID(..) => { current_bucket = new_bucket; - } + }, Bucket::Class(..) => { if !matches!(current_bucket, Bucket::ID(..)) { current_bucket = new_bucket; @@ -549,7 +555,7 @@ fn find_bucket<'a>(mut iter: SelectorIter<'a, SelectorImpl>) -> Bucket<'a> { if matches!(current_bucket, Bucket::Universal) { current_bucket = new_bucket; } - } + }, Bucket::Universal => {}, } } diff --git a/components/style/servo/restyle_damage.rs b/components/style/servo/restyle_damage.rs index 5cde20c9658f..7b49a592751e 100644 --- a/components/style/servo/restyle_damage.rs +++ b/components/style/servo/restyle_damage.rs @@ -80,9 +80,12 @@ impl ServoRestyleDamage { /// FIXME(bholley): Do we ever actually need this? Shouldn't /// RECONSTRUCT_FLOW imply everything else? pub fn rebuild_and_reflow() -> ServoRestyleDamage { - ServoRestyleDamage::REPAINT | ServoRestyleDamage::REPOSITION | - ServoRestyleDamage::STORE_OVERFLOW | ServoRestyleDamage::BUBBLE_ISIZES | - ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW | + ServoRestyleDamage::REPAINT | + ServoRestyleDamage::REPOSITION | + ServoRestyleDamage::STORE_OVERFLOW | + ServoRestyleDamage::BUBBLE_ISIZES | + ServoRestyleDamage::REFLOW_OUT_OF_FLOW | + ServoRestyleDamage::REFLOW | ServoRestyleDamage::RECONSTRUCT_FLOW } @@ -95,12 +98,14 @@ impl ServoRestyleDamage { /// returns the damage that we should add to the *parent* of this flow. pub fn damage_for_parent(self, child_is_absolutely_positioned: bool) -> ServoRestyleDamage { if child_is_absolutely_positioned { - self & (ServoRestyleDamage::REPAINT | ServoRestyleDamage::REPOSITION | + self & (ServoRestyleDamage::REPAINT | + ServoRestyleDamage::REPOSITION | ServoRestyleDamage::STORE_OVERFLOW | ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::RESOLVE_GENERATED_CONTENT) } else { - self & (ServoRestyleDamage::REPAINT | ServoRestyleDamage::REPOSITION | + self & (ServoRestyleDamage::REPAINT | + ServoRestyleDamage::REPOSITION | ServoRestyleDamage::STORE_OVERFLOW | ServoRestyleDamage::REFLOW | ServoRestyleDamage::REFLOW_OUT_OF_FLOW | @@ -136,7 +141,8 @@ impl ServoRestyleDamage { }, _ => { // TODO(pcwalton): Take floatedness into account. - self & (ServoRestyleDamage::REPAINT | ServoRestyleDamage::REPOSITION | + self & (ServoRestyleDamage::REPAINT | + ServoRestyleDamage::REPOSITION | ServoRestyleDamage::REFLOW) }, } @@ -205,22 +211,21 @@ fn compute_damage(old: &ComputedValues, new: &ComputedValues) -> ServoRestyleDam ServoRestyleDamage::REFLOW, ServoRestyleDamage::RECONSTRUCT_FLOW ] - ) || - (new.get_box().display == Display::Inline && - restyle_damage_rebuild_and_reflow_inline!( - old, - new, - damage, - [ - ServoRestyleDamage::REPAINT, - ServoRestyleDamage::REPOSITION, - ServoRestyleDamage::STORE_OVERFLOW, - ServoRestyleDamage::BUBBLE_ISIZES, - ServoRestyleDamage::REFLOW_OUT_OF_FLOW, - ServoRestyleDamage::REFLOW, - ServoRestyleDamage::RECONSTRUCT_FLOW - ] - )) || + ) || (new.get_box().display == Display::Inline && + restyle_damage_rebuild_and_reflow_inline!( + old, + new, + damage, + [ + ServoRestyleDamage::REPAINT, + ServoRestyleDamage::REPOSITION, + ServoRestyleDamage::STORE_OVERFLOW, + ServoRestyleDamage::BUBBLE_ISIZES, + ServoRestyleDamage::REFLOW_OUT_OF_FLOW, + ServoRestyleDamage::REFLOW, + ServoRestyleDamage::RECONSTRUCT_FLOW + ] + )) || restyle_damage_reflow!( old, new, @@ -244,7 +249,8 @@ fn compute_damage(old: &ComputedValues, new: &ComputedValues) -> ServoRestyleDam ServoRestyleDamage::STORE_OVERFLOW, ServoRestyleDamage::REFLOW_OUT_OF_FLOW ] - ) || restyle_damage_repaint!(old, new, damage, [ServoRestyleDamage::REPAINT]); + ) || + restyle_damage_repaint!(old, new, damage, [ServoRestyleDamage::REPAINT]); // Paint worklets may depend on custom properties, // so if they have changed we should repaint. diff --git a/components/style/servo/selector_parser.rs b/components/style/servo/selector_parser.rs index c608cd8488d2..7c1e082022d9 100644 --- a/components/style/servo/selector_parser.rs +++ b/components/style/servo/selector_parser.rs @@ -137,7 +137,9 @@ impl PseudoElement { /// Whether this is an unknown ::-webkit- pseudo-element. #[inline] - pub fn is_unknown_webkit_pseudo_element(&self) -> bool { false } + pub fn is_unknown_webkit_pseudo_element(&self) -> bool { + false + } /// Whether this pseudo-element is the ::before pseudo. #[inline] @@ -766,7 +768,8 @@ impl ServoElementSnapshot { operation: &AttrSelectorOperation<&String>, ) -> bool { match *ns { - NamespaceConstraint::Specific(ref ns) => self.get_attr(ns, local_name) + NamespaceConstraint::Specific(ref ns) => self + .get_attr(ns, local_name) .map_or(false, |value| value.eval_selector(operation)), NamespaceConstraint::Any => { self.any_attr_ignore_ns(local_name, |value| value.eval_selector(operation)) diff --git a/components/style/sharing/mod.rs b/components/style/sharing/mod.rs index d6148d16b49c..b3177216f640 100644 --- a/components/style/sharing/mod.rs +++ b/components/style/sharing/mod.rs @@ -197,8 +197,7 @@ impl ValidationData { let values = OpaqueComputedValues::from(parent.borrow_data().unwrap().styles.primary()); values - }) - .clone() + }).clone() } /// Computes the revalidation results if needed, and returns it. diff --git a/components/style/style_adjuster.rs b/components/style/style_adjuster.rs index 704c875a932e..7c65798286e3 100644 --- a/components/style/style_adjuster.rs +++ b/components/style/style_adjuster.rs @@ -64,10 +64,21 @@ where // FIXME(emilio): This should be an actual static. lazy_static! { static ref SPECIAL_HTML_ELEMENTS: [Atom; 16] = [ - atom!("br"), atom!("wbr"), atom!("meter"), atom!("progress"), - atom!("canvas"), atom!("embed"), atom!("object"), atom!("audio"), - atom!("iframe"), atom!("img"), atom!("video"), atom!("frame"), - atom!("frameset"), atom!("input"), atom!("textarea"), + atom!("br"), + atom!("wbr"), + atom!("meter"), + atom!("progress"), + atom!("canvas"), + atom!("embed"), + atom!("object"), + atom!("audio"), + atom!("iframe"), + atom!("img"), + atom!("video"), + atom!("frame"), + atom!("frameset"), + atom!("input"), + atom!("textarea"), atom!("select"), ]; } @@ -79,15 +90,21 @@ where // UA implements this either. lazy_static! { static ref SPECIAL_SVG_ELEMENTS: [Atom; 6] = [ - atom!("svg"), atom!("a"), atom!("g"), atom!("use"), - atom!("tspan"), atom!("textPath"), + atom!("svg"), + atom!("a"), + atom!("g"), + atom!("use"), + atom!("tspan"), + atom!("textPath"), ]; } // https://drafts.csswg.org/css-display/#unbox-html if element.is_html_element() { let local_name = element.local_name(); - return SPECIAL_HTML_ELEMENTS.iter().any(|name| &**name == local_name); + return SPECIAL_HTML_ELEMENTS + .iter() + .any(|name| &**name == local_name); } // https://drafts.csswg.org/css-display/#unbox-svg @@ -96,7 +113,9 @@ where return true; } let local_name = element.local_name(); - return !SPECIAL_SVG_ELEMENTS.iter().any(|name| &**name == local_name); + return !SPECIAL_SVG_ELEMENTS + .iter() + .any(|name| &**name == local_name); } // https://drafts.csswg.org/css-display/#unbox-mathml @@ -201,11 +220,11 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> { pub fn set_bits(&mut self) { let display = self.style.get_box().clone_display(); - if !display.is_contents() && - !self.style - .get_text() - .clone_text_decoration_line() - .is_empty() + if !display.is_contents() && !self + .style + .get_text() + .clone_text_decoration_line() + .is_empty() { self.style .flags @@ -280,10 +299,10 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> { #[cfg(feature = "gecko")] fn adjust_for_text_in_ruby(&mut self) { let parent_display = self.style.get_parent_box().clone_display(); - if parent_display.is_ruby_type() || - self.style - .get_parent_flags() - .contains(ComputedValueFlags::SHOULD_SUPPRESS_LINEBREAK) + if parent_display.is_ruby_type() || self + .style + .get_parent_flags() + .contains(ComputedValueFlags::SHOULD_SUPPRESS_LINEBREAK) { self.style .flags @@ -370,10 +389,12 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> { /// The initial value of outline-width may be changed at computed value time. fn adjust_for_outline(&mut self) { - if self.style + if self + .style .get_outline() .clone_outline_style() - .none_or_hidden() && self.style.get_outline().outline_has_nonzero_width() + .none_or_hidden() && + self.style.get_outline().outline_has_nonzero_width() { self.style.mutate_outline().set_outline_width(Au(0).into()); } @@ -517,7 +538,9 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> { let decorations_in_effect = TextDecorationsInEffect::from_style(&self.style); if self.style.get_inherited_text().text_decorations_in_effect != decorations_in_effect { - self.style.mutate_inherited_text().text_decorations_in_effect = decorations_in_effect; + self.style + .mutate_inherited_text() + .text_decorations_in_effect = decorations_in_effect; } } @@ -677,11 +700,8 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> { /// When comparing to Gecko, this is similar to the work done by /// `ComputedStyle::ApplyStyleFixups`, plus some parts of /// `nsStyleSet::GetContext`. - pub fn adjust( - &mut self, - layout_parent_style: &ComputedValues, - element: Option, - ) where + pub fn adjust(&mut self, layout_parent_style: &ComputedValues, element: Option) + where E: TElement, { if cfg!(debug_assertions) { diff --git a/components/style/style_resolver.rs b/components/style/style_resolver.rs index b31beff74603..0899faa9ce7a 100644 --- a/components/style/style_resolver.rs +++ b/components/style/style_resolver.rs @@ -190,8 +190,7 @@ where ) -> PrimaryStyle { // Before doing the cascade, check the sharing cache and see if we can // reuse the style via rule node identity. - let may_reuse = - !self.element.is_in_native_anonymous_subtree() && + let may_reuse = !self.element.is_in_native_anonymous_subtree() && parent_style.is_some() && inputs.rules.is_some(); @@ -485,7 +484,8 @@ where let stylist = &self.context.shared.stylist; - if !self.element + if !self + .element .may_generate_pseudo(pseudo_element, originating_element_style) { return None; diff --git a/components/style/stylesheet_set.rs b/components/style/stylesheet_set.rs index a3b6e5cdc17e..19790aba9574 100644 --- a/components/style/stylesheet_set.rs +++ b/components/style/stylesheet_set.rs @@ -324,7 +324,8 @@ where fn insert_before(&mut self, sheet: S, before_sheet: &S) { debug_assert!(!self.contains(&sheet)); - let index = self.entries + let index = self + .entries .iter() .position(|entry| entry.sheet == *before_sheet) .expect("`before_sheet` stylesheet not found"); diff --git a/components/style/stylesheets/document_rule.rs b/components/style/stylesheets/document_rule.rs index 56750ae7b66f..9598763e4386 100644 --- a/components/style/stylesheets/document_rule.rs +++ b/components/style/stylesheets/document_rule.rs @@ -109,7 +109,7 @@ pub enum DocumentMatchingFunction { Regexp(String), /// Matching function for a media document. #[css(function)] - MediaDocument(MediaDocumentKind) + MediaDocument(MediaDocumentKind), } macro_rules! parse_quoted_or_unquoted_string { @@ -120,8 +120,7 @@ macro_rules! parse_quoted_or_unquoted_string { .parse_entirely(|input| { let string = input.expect_string()?; Ok($url_matching_function(string.as_ref().to_owned())) - }) - .or_else(|_: ParseError| { + }).or_else(|_: ParseError| { while let Ok(_) = input.next() {} Ok($url_matching_function(input.slice_from(start).to_string())) }) @@ -136,7 +135,7 @@ impl DocumentMatchingFunction { input: &mut Parser<'i, 't>, ) -> Result> { if let Ok(url) = input.try(|input| CssUrl::parse(context, input)) { - return Ok(DocumentMatchingFunction::Url(url)) + return Ok(DocumentMatchingFunction::Url(url)); } let location = input.current_source_location(); @@ -181,7 +180,9 @@ impl DocumentMatchingFunction { DocumentMatchingFunction::UrlPrefix(_) => GeckoDocumentMatchingFunction::URLPrefix, DocumentMatchingFunction::Domain(_) => GeckoDocumentMatchingFunction::Domain, DocumentMatchingFunction::Regexp(_) => GeckoDocumentMatchingFunction::RegExp, - DocumentMatchingFunction::MediaDocument(_) => GeckoDocumentMatchingFunction::MediaDocument, + DocumentMatchingFunction::MediaDocument(_) => { + GeckoDocumentMatchingFunction::MediaDocument + }, }; let pattern = nsCStr::from(match *self { @@ -189,14 +190,12 @@ impl DocumentMatchingFunction { DocumentMatchingFunction::UrlPrefix(ref pat) | DocumentMatchingFunction::Domain(ref pat) | DocumentMatchingFunction::Regexp(ref pat) => pat, - DocumentMatchingFunction::MediaDocument(kind) => { - match kind { - MediaDocumentKind::All => "all", - MediaDocumentKind::Image => "image", - MediaDocumentKind::Plugin => "plugin", - MediaDocumentKind::Video => "video", - } - } + DocumentMatchingFunction::MediaDocument(kind) => match kind { + MediaDocumentKind::All => "all", + MediaDocumentKind::Image => "image", + MediaDocumentKind::Plugin => "plugin", + MediaDocumentKind::Video => "video", + }, }); unsafe { Gecko_DocumentRule_UseForPresentation(device.pres_context(), &*pattern, func) } } diff --git a/components/style/stylesheets/font_feature_values_rule.rs b/components/style/stylesheets/font_feature_values_rule.rs index c70a46c1c9d2..76170151c67b 100644 --- a/components/style/stylesheets/font_feature_values_rule.rs +++ b/components/style/stylesheets/font_feature_values_rule.rs @@ -70,7 +70,8 @@ impl Parse for SingleValue { match *input.next()? { Token::Number { int_value: Some(v), .. - } if v >= 0 => + } + if v >= 0 => { Ok(SingleValue(v as u32)) }, @@ -102,7 +103,8 @@ impl Parse for PairValues { let first = match *input.next()? { Token::Number { int_value: Some(a), .. - } if a >= 0 => + } + if a >= 0 => { a as u32 }, @@ -112,7 +114,8 @@ impl Parse for PairValues { match input.next() { Ok(&Token::Number { int_value: Some(b), .. - }) if b >= 0 => + }) + if b >= 0 => { Ok(PairValues(first, Some(b as u32))) }, @@ -154,7 +157,8 @@ impl Parse for VectorValues { match input.next() { Ok(&Token::Number { int_value: Some(a), .. - }) if a >= 0 => + }) + if a >= 0 => { vec.push(a as u32); } diff --git a/components/style/stylesheets/keyframes_rule.rs b/components/style/stylesheets/keyframes_rule.rs index 0246efa67805..50c61047e529 100644 --- a/components/style/stylesheets/keyframes_rule.rs +++ b/components/style/stylesheets/keyframes_rule.rs @@ -82,16 +82,14 @@ impl DeepCloneWithLock for KeyframesRule { ) -> Self { KeyframesRule { name: self.name.clone(), - keyframes: self.keyframes + keyframes: self + .keyframes .iter() .map(|x| { - Arc::new(lock.wrap(x.read_with(guard).deep_clone_with_lock( - lock, - guard, - params, - ))) - }) - .collect(), + Arc::new( + lock.wrap(x.read_with(guard).deep_clone_with_lock(lock, guard, params)), + ) + }).collect(), vendor_prefix: self.vendor_prefix.clone(), source_location: self.source_location.clone(), } @@ -142,7 +140,8 @@ impl KeyframePercentage { Token::Percentage { unit_value: percentage, .. - } if percentage >= 0. && percentage <= 1. => + } + if percentage >= 0. && percentage <= 1. => { Ok(KeyframePercentage::new(percentage)) }, @@ -261,8 +260,10 @@ pub enum KeyframesStepValue { /// A step formed by a declaration block specified by the CSS. Declarations { /// The declaration block per se. - #[cfg_attr(feature = "gecko", - ignore_malloc_size_of = "XXX: Primary ref, measure if DMD says it's worthwhile")] + #[cfg_attr( + feature = "gecko", + ignore_malloc_size_of = "XXX: Primary ref, measure if DMD says it's worthwhile" + )] #[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")] block: Arc>, }, @@ -326,8 +327,7 @@ impl KeyframesStep { let (declaration, _) = guard .get(PropertyDeclarationId::Longhand( LonghandId::AnimationTimingFunction, - )) - .unwrap(); + )).unwrap(); match *declaration { PropertyDeclaration::AnimationTimingFunction(ref value) => { // Use the first value. @@ -500,7 +500,7 @@ pub fn parse_keyframe_list( declarations: &mut declarations, }, ).filter_map(Result::ok) - .collect() + .collect() } impl<'a, 'i> AtRuleParser<'i> for KeyframeListParser<'a> { @@ -525,7 +525,7 @@ impl<'a, 'i> QualifiedRuleParser<'i> for KeyframeListParser<'a> { let error = ContextualParseError::InvalidKeyframeRule( input.slice_from(start_position), e.clone(), - ); + ); self.context.log_css_error(location, error); e }) @@ -552,10 +552,7 @@ impl<'a, 'i> QualifiedRuleParser<'i> for KeyframeListParser<'a> { while let Some(declaration) = iter.next() { match declaration { Ok(()) => { - block.extend( - iter.parser.declarations.drain(), - Importance::Normal, - ); + block.extend(iter.parser.declarations.drain(), Importance::Normal); }, Err((error, slice)) => { iter.parser.declarations.clear(); @@ -599,9 +596,9 @@ impl<'a, 'b, 'i> DeclarationParser<'i> for KeyframeDeclarationParser<'a, 'b> { ) -> Result<(), ParseError<'i>> { let id = match PropertyId::parse(&name, self.context) { Ok(id) => id, - Err(()) => return Err(input.new_custom_error( - StyleParseErrorKind::UnknownProperty(name) - )), + Err(()) => { + return Err(input.new_custom_error(StyleParseErrorKind::UnknownProperty(name))) + }, }; // TODO(emilio): Shouldn't this use parse_entirely? diff --git a/components/style/stylesheets/mod.rs b/components/style/stylesheets/mod.rs index 80766c289f84..5058ad94e806 100644 --- a/components/style/stylesheets/mod.rs +++ b/components/style/stylesheets/mod.rs @@ -63,7 +63,7 @@ pub type UrlExtraData = ::servo_url::ServoUrl; #[cfg(feature = "gecko")] #[derive(Clone, PartialEq)] pub struct UrlExtraData( - pub ::gecko_bindings::sugar::refptr::RefPtr<::gecko_bindings::structs::URLExtraData> + pub ::gecko_bindings::sugar::refptr::RefPtr<::gecko_bindings::structs::URLExtraData>, ); #[cfg(feature = "gecko")] @@ -102,11 +102,14 @@ impl fmt::Debug for UrlExtraData { } } - formatter.debug_struct("URLExtraData") + formatter + .debug_struct("URLExtraData") .field("is_chrome", &self.is_chrome()) .field("base", &DebugURI(self.0.mBaseURI.raw::())) - .field("referrer", &DebugURI(self.0.mReferrer.raw::())) - .finish() + .field( + "referrer", + &DebugURI(self.0.mReferrer.raw::()), + ).finish() } } @@ -285,9 +288,7 @@ impl CssRule { }; parse_one_rule(&mut input, &mut rule_parser) - .map_err(|_| { - rule_parser.dom_error.unwrap_or(RulesMutateError::Syntax) - }) + .map_err(|_| rule_parser.dom_error.unwrap_or(RulesMutateError::Syntax)) } } @@ -305,25 +306,22 @@ impl DeepCloneWithLock for CssRule { CssRule::Namespace(Arc::new(lock.wrap(rule.clone()))) }, CssRule::Import(ref arc) => { - let rule = arc.read_with(guard) + let rule = arc + .read_with(guard) .deep_clone_with_lock(lock, guard, params); CssRule::Import(Arc::new(lock.wrap(rule))) }, CssRule::Style(ref arc) => { let rule = arc.read_with(guard); - CssRule::Style(Arc::new(lock.wrap(rule.deep_clone_with_lock( - lock, - guard, - params, - )))) + CssRule::Style(Arc::new( + lock.wrap(rule.deep_clone_with_lock(lock, guard, params)), + )) }, CssRule::Media(ref arc) => { let rule = arc.read_with(guard); - CssRule::Media(Arc::new(lock.wrap(rule.deep_clone_with_lock( - lock, - guard, - params, - )))) + CssRule::Media(Arc::new( + lock.wrap(rule.deep_clone_with_lock(lock, guard, params)), + )) }, CssRule::FontFace(ref arc) => { let rule = arc.read_with(guard); @@ -343,35 +341,27 @@ impl DeepCloneWithLock for CssRule { }, CssRule::Keyframes(ref arc) => { let rule = arc.read_with(guard); - CssRule::Keyframes(Arc::new(lock.wrap(rule.deep_clone_with_lock( - lock, - guard, - params, - )))) + CssRule::Keyframes(Arc::new( + lock.wrap(rule.deep_clone_with_lock(lock, guard, params)), + )) }, CssRule::Supports(ref arc) => { let rule = arc.read_with(guard); - CssRule::Supports(Arc::new(lock.wrap(rule.deep_clone_with_lock( - lock, - guard, - params, - )))) + CssRule::Supports(Arc::new( + lock.wrap(rule.deep_clone_with_lock(lock, guard, params)), + )) }, CssRule::Page(ref arc) => { let rule = arc.read_with(guard); - CssRule::Page(Arc::new(lock.wrap(rule.deep_clone_with_lock( - lock, - guard, - params, - )))) + CssRule::Page(Arc::new( + lock.wrap(rule.deep_clone_with_lock(lock, guard, params)), + )) }, CssRule::Document(ref arc) => { let rule = arc.read_with(guard); - CssRule::Document(Arc::new(lock.wrap(rule.deep_clone_with_lock( - lock, - guard, - params, - )))) + CssRule::Document(Arc::new( + lock.wrap(rule.deep_clone_with_lock(lock, guard, params)), + )) }, } } diff --git a/components/style/stylesheets/rule_list.rs b/components/style/stylesheets/rule_list.rs index 35edc22b3dac..cfbf62ea721a 100644 --- a/components/style/stylesheets/rule_list.rs +++ b/components/style/stylesheets/rule_list.rs @@ -156,7 +156,11 @@ impl CssRulesHelpers for RawOffsetArc> { } else if index == 0 { State::Start } else { - rules.0.get(index - 1).map(CssRule::rule_state).unwrap_or(State::Body) + rules + .0 + .get(index - 1) + .map(CssRule::rule_state) + .unwrap_or(State::Body) }; let insert_rule_context = InsertRuleContext { diff --git a/components/style/stylesheets/rule_parser.rs b/components/style/stylesheets/rule_parser.rs index d2f9b691ad4e..683378b9b96b 100644 --- a/components/style/stylesheets/rule_parser.rs +++ b/components/style/stylesheets/rule_parser.rs @@ -110,8 +110,9 @@ impl<'b> TopLevelRuleParser<'b> { // If there's anything that isn't a namespace rule (or import rule, but // we checked that already at the beginning), reject with a // StateError. - if new_state == State::Namespaces && - ctx.rule_list[ctx.index..].iter().any(|r| !matches!(*r, CssRule::Namespace(..))) + if new_state == State::Namespaces && ctx.rule_list[ctx.index..] + .iter() + .any(|r| !matches!(*r, CssRule::Namespace(..))) { self.dom_error = Some(RulesMutateError::InvalidState); return false; @@ -227,7 +228,7 @@ impl<'a, 'i> AtRuleParser<'i> for TopLevelRuleParser<'a> { } if !self.check_state(State::Body) { - return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) + return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } AtRuleParser::parse_prelude(&mut self.nested(), name, input) @@ -254,7 +255,8 @@ impl<'a, 'i> AtRuleParser<'i> for TopLevelRuleParser<'a> { ) -> CssRule { match prelude { AtRuleNonBlockPrelude::Import(url, media) => { - let loader = self.loader + let loader = self + .loader .expect("Expected a stylesheet loader for @import"); let import_rule = loader.request_stylesheet( @@ -299,7 +301,7 @@ impl<'a, 'i> QualifiedRuleParser<'i> for TopLevelRuleParser<'a> { input: &mut Parser<'i, 't>, ) -> Result> { if !self.check_state(State::Body) { - return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) + return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } QualifiedRuleParser::parse_prelude(&mut self.nested(), input) @@ -312,15 +314,12 @@ impl<'a, 'i> QualifiedRuleParser<'i> for TopLevelRuleParser<'a> { location: SourceLocation, input: &mut Parser<'i, 't>, ) -> Result> { - QualifiedRuleParser::parse_block( - &mut self.nested(), - prelude, - location, - input, - ).map(|result| { - self.state = State::Body; - result - }) + QualifiedRuleParser::parse_block(&mut self.nested(), prelude, location, input).map( + |result| { + self.state = State::Body; + result + }, + ) } } @@ -338,11 +337,7 @@ impl<'a, 'b> NestedRuleParser<'a, 'b> { input: &mut Parser, rule_type: CssRuleType, ) -> Arc> { - let context = ParserContext::new_with_rule_type( - self.context, - rule_type, - self.namespaces, - ); + let context = ParserContext::new_with_rule_type(self.context, rule_type, self.namespaces); let nested_parser = NestedRuleParser { stylesheet_origin: self.stylesheet_origin, @@ -478,12 +473,7 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> { ); Ok(CssRule::FontFeatureValues(Arc::new(self.shared_lock.wrap( - FontFeatureValuesRule::parse( - &context, - input, - family_names, - source_location, - ), + FontFeatureValuesRule::parse(&context, input, family_names, source_location), )))) }, AtRuleBlockPrelude::CounterStyle(name) => { @@ -493,16 +483,9 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> { self.namespaces, ); - Ok(CssRule::CounterStyle(Arc::new( - self.shared_lock.wrap( - parse_counter_style_body( - name, - &context, - input, - source_location, - )?.into(), - ), - ))) + Ok(CssRule::CounterStyle(Arc::new(self.shared_lock.wrap( + parse_counter_style_body(name, &context, input, source_location)?.into(), + )))) }, AtRuleBlockPrelude::Media(media_queries) => { Ok(CssRule::Media(Arc::new(self.shared_lock.wrap(MediaRule { @@ -535,9 +518,9 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> { self.namespaces, ); - Ok(CssRule::Viewport(Arc::new(self.shared_lock.wrap( - ViewportRule::parse(&context, input)?, - )))) + Ok(CssRule::Viewport(Arc::new( + self.shared_lock.wrap(ViewportRule::parse(&context, input)?), + ))) }, AtRuleBlockPrelude::Keyframes(name, vendor_prefix) => { let context = ParserContext::new_with_rule_type( @@ -549,11 +532,7 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> { Ok(CssRule::Keyframes(Arc::new(self.shared_lock.wrap( KeyframesRule { name, - keyframes: parse_keyframe_list( - &context, - input, - self.shared_lock, - ), + keyframes: parse_keyframe_list(&context, input, self.shared_lock), vendor_prefix, source_location, }, @@ -566,8 +545,7 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> { self.namespaces, ); - let declarations = - parse_property_declaration_list(&context, input); + let declarations = parse_property_declaration_list(&context, input); Ok(CssRule::Page(Arc::new(self.shared_lock.wrap(PageRule { block: Arc::new(self.shared_lock.wrap(declarations)), source_location, diff --git a/components/style/stylesheets/rules_iterator.rs b/components/style/stylesheets/rules_iterator.rs index b46e24c22c72..eac6d2084e2a 100644 --- a/components/style/stylesheets/rules_iterator.rs +++ b/components/style/stylesheets/rules_iterator.rs @@ -100,10 +100,7 @@ where ) { continue; } - import_rule - .stylesheet - .rules(self.guard) - .iter() + import_rule.stylesheet.rules(self.guard).iter() }, CssRule::Document(ref doc_rule) => { let doc_rule = doc_rule.read_with(self.guard); diff --git a/components/style/stylesheets/stylesheet.rs b/components/style/stylesheets/stylesheet.rs index 1403a1d2547e..e1359cb3722d 100644 --- a/components/style/stylesheets/stylesheet.rs +++ b/components/style/stylesheets/stylesheet.rs @@ -129,7 +129,8 @@ impl DeepCloneWithLock for StylesheetContents { params: &DeepCloneParams, ) -> Self { // Make a deep clone of the rules, using the new lock. - let rules = self.rules + let rules = self + .rules .read_with(guard) .deep_clone_with_lock(lock, guard, params); @@ -179,7 +180,7 @@ macro_rules! rule_filter { } /// A trait to represent a given stylesheet in a document. -pub trait StylesheetInDocument : ::std::fmt::Debug { +pub trait StylesheetInDocument: ::std::fmt::Debug { /// Get the stylesheet origin. fn origin(&self, guard: &SharedRwLockReadGuard) -> Origin; @@ -399,10 +400,7 @@ impl Stylesheet { Err((error, slice)) => { let location = error.location; let error = ContextualParseError::InvalidRule(slice, error); - iter.parser.context.log_css_error( - location, - error, - ); + iter.parser.context.log_css_error(location, error); }, } } @@ -478,7 +476,8 @@ impl Clone for Stylesheet { // Make a deep clone of the media, using the new lock. let media = self.media.read_with(&guard).clone(); let media = Arc::new(lock.wrap(media)); - let contents = self.contents + let contents = self + .contents .deep_clone_with_lock(&lock, &guard, &DeepCloneParams); Stylesheet { diff --git a/components/style/stylesheets/supports_rule.rs b/components/style/stylesheets/supports_rule.rs index f8c3235f2952..2851d8914dd1 100644 --- a/components/style/stylesheets/supports_rule.rs +++ b/components/style/stylesheets/supports_rule.rs @@ -168,9 +168,7 @@ impl SupportsCondition { i.expect_string() .map(|s| s.to_string()) .map_err(CssParseError::<()>::from) - }).and_then(|s| { - CString::new(s).map_err(|_| location.new_custom_error(())) - }) + }).and_then(|s| CString::new(s).map_err(|_| location.new_custom_error(()))) }) { return Ok(SupportsCondition::MozBoolPref(name)); } @@ -315,24 +313,21 @@ impl Declaration { let mut input = ParserInput::new(&self.0); let mut input = Parser::new(&mut input); - input.parse_entirely(|input| -> Result<(), CssParseError<()>> { - let prop = input.expect_ident_cloned().unwrap(); - input.expect_colon().unwrap(); + input + .parse_entirely(|input| -> Result<(), CssParseError<()>> { + let prop = input.expect_ident_cloned().unwrap(); + input.expect_colon().unwrap(); - let id = PropertyId::parse(&prop, context) - .map_err(|_| input.new_custom_error(()))?; + let id = + PropertyId::parse(&prop, context).map_err(|_| input.new_custom_error(()))?; - let mut declarations = SourcePropertyDeclaration::new(); - input.parse_until_before(Delimiter::Bang, |input| { - PropertyDeclaration::parse_into( - &mut declarations, - id, - &context, - input, - ).map_err(|_| input.new_custom_error(())) - })?; - let _ = input.try(parse_important); - Ok(()) - }).is_ok() + let mut declarations = SourcePropertyDeclaration::new(); + input.parse_until_before(Delimiter::Bang, |input| { + PropertyDeclaration::parse_into(&mut declarations, id, &context, input) + .map_err(|_| input.new_custom_error(())) + })?; + let _ = input.try(parse_important); + Ok(()) + }).is_ok() } } diff --git a/components/style/stylesheets/viewport_rule.rs b/components/style/stylesheets/viewport_rule.rs index 1fc6a988c7ca..16bffd14ab29 100644 --- a/components/style/stylesheets/viewport_rule.rs +++ b/components/style/stylesheets/viewport_rule.rs @@ -375,8 +375,7 @@ impl ViewportRule { Err((error, slice)) => { let location = error.location; let error = ContextualParseError::UnsupportedViewportDescriptorDeclaration( - slice, - error, + slice, error, ); context.log_css_error(location, error); }, @@ -760,9 +759,9 @@ impl MaybeNew for ViewportConstraints { Some(initial_viewport.$dimension.scale_by(value.0)) }, LengthOrPercentageOrAuto::Auto => None, - LengthOrPercentageOrAuto::Calc(ref calc) => calc.to_computed_value( - &context, - ).to_used_value(Some(initial_viewport.$dimension)), + LengthOrPercentageOrAuto::Calc(ref calc) => calc + .to_computed_value(&context) + .to_used_value(Some(initial_viewport.$dimension)), }, ViewportLength::ExtendToZoom => { // $extend_to will be 'None' if 'extend-to-zoom' is 'auto' diff --git a/components/style/stylist.rs b/components/style/stylist.rs index e9cd63e738a2..c933897f8580 100644 --- a/components/style/stylist.rs +++ b/components/style/stylist.rs @@ -184,8 +184,10 @@ impl UserAgentCascadeData { #[derive(Default)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] struct DocumentCascadeData { - #[cfg_attr(feature = "servo", - ignore_malloc_size_of = "Arc, owned by UserAgentCascadeDataCache")] + #[cfg_attr( + feature = "servo", + ignore_malloc_size_of = "Arc, owned by UserAgentCascadeDataCache" + )] user_agent: Arc, user: CascadeData, author: CascadeData, @@ -350,7 +352,10 @@ pub struct Stylist { stylesheets: StylistStylesheetSet, /// If true, the quirks-mode stylesheet is applied. - #[cfg_attr(feature = "servo", ignore_malloc_size_of = "defined in selectors")] + #[cfg_attr( + feature = "servo", + ignore_malloc_size_of = "defined in selectors" + )] quirks_mode: QuirksMode, /// Selector maps for all of the style sheets in the stylist, after @@ -681,7 +686,8 @@ impl Stylist { extra_declarations: Option>, ) -> StrongRuleNode { let mut decl; - let declarations = match self.cascade_data + let declarations = match self + .cascade_data .user_agent .precomputed_pseudo_element_decls .get(pseudo) @@ -852,7 +858,7 @@ impl Stylist { } else { None } - } + }, }; // Read the comment on `precomputed_values_for_pseudo` to see why it's @@ -1131,7 +1137,8 @@ impl Stylist { let matches_user_rules = rule_hash_target.matches_user_and_author_rules(); // Normal user-agent rules. - if let Some(map) = self.cascade_data + if let Some(map) = self + .cascade_data .user_agent .cascade_data .normal_rules(pseudo_element) @@ -1207,7 +1214,10 @@ impl Stylist { // for !important it should be the other way around. So probably we need // to add some sort of AuthorScoped cascade level or something. if let Some(shadow) = rule_hash_target.shadow_root() { - if let Some(map) = shadow.style_data().and_then(|data| data.host_rules(pseudo_element)) { + if let Some(map) = shadow + .style_data() + .and_then(|data| data.host_rules(pseudo_element)) + { context.with_shadow_host(Some(rule_hash_target), |context| { map.get_all_matching_rules( element, @@ -1234,7 +1244,10 @@ impl Stylist { for slot in slots.iter().rev() { let shadow = slot.containing_shadow().unwrap(); - if let Some(map) = shadow.style_data().and_then(|data| data.slotted_rules(pseudo_element)) { + if let Some(map) = shadow + .style_data() + .and_then(|data| data.slotted_rules(pseudo_element)) + { context.with_shadow_host(Some(shadow.host()), |context| { map.get_all_matching_rules( element, @@ -1270,8 +1283,7 @@ impl Stylist { } let host_is_svg_use_element = - host.is_svg_element() && - host.local_name() == &*local_name!("use"); + host.is_svg_element() && host.local_name() == &*local_name!("use"); if !host_is_svg_use_element { match_document_author_rules = false; @@ -1406,11 +1418,7 @@ impl Stylist { /// Returns the registered `@keyframes` animation for the specified name. #[inline] - pub fn get_animation<'a, E>( - &'a self, - name: &Atom, - element: E, - ) -> Option<&'a KeyframesAnimation> + pub fn get_animation<'a, E>(&'a self, name: &Atom, element: E) -> Option<&'a KeyframesAnimation> where E: TElement + 'a, { @@ -1419,7 +1427,7 @@ impl Stylist { if let Some(animation) = $data.animations.get(name) { return Some(animation); } - } + }; } // NOTE(emilio): We implement basically what Blink does for this case, @@ -1547,10 +1555,12 @@ impl Stylist { let block = declarations.read_with(guards.author); let iter_declarations = || { - block.declaration_importance_iter().map(|(declaration, importance)| { - debug_assert!(!importance.important()); - (declaration, CascadeLevel::StyleAttributeNormal) - }) + block + .declaration_importance_iter() + .map(|(declaration, importance)| { + debug_assert!(!importance.important()); + (declaration, CascadeLevel::StyleAttributeNormal) + }) }; let metrics = get_metrics_provider_for_product(); @@ -1567,7 +1577,9 @@ impl Stylist { Some(parent_style), Some(parent_style), &metrics, - CascadeMode::Unvisited { visited_rules: None }, + CascadeMode::Unvisited { + visited_rules: None, + }, self.quirks_mode, /* rule_cache = */ None, &mut Default::default(), @@ -1703,8 +1715,10 @@ impl MallocSizeOf for ExtraStyleData { #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[derive(Clone, Debug)] struct RevalidationSelectorAndHashes { - #[cfg_attr(feature = "gecko", - ignore_malloc_size_of = "CssRules have primary refs, we measure there")] + #[cfg_attr( + feature = "gecko", + ignore_malloc_size_of = "CssRules have primary refs, we measure there" + )] selector: Selector, selector_offset: usize, hashes: AncestorHashes, @@ -1812,8 +1826,9 @@ impl<'a> SelectorVisitor for StylistSelectorVisitor<'a> { // Also, note that this call happens before we visit any of the simple // selectors in the next ComplexSelector, so we can use this to skip // looking at them. - self.passed_rightmost_selector = self.passed_rightmost_selector || - !matches!(combinator, None | Some(Combinator::PseudoElement)); + self.passed_rightmost_selector = + self.passed_rightmost_selector || + !matches!(combinator, None | Some(Combinator::PseudoElement)); true } @@ -1830,8 +1845,9 @@ impl<'a> SelectorVisitor for StylistSelectorVisitor<'a> { } fn visit_simple_selector(&mut self, s: &Component) -> bool { - self.needs_revalidation = self.needs_revalidation || - component_needs_revalidation(s, self.passed_rightmost_selector); + self.needs_revalidation = + self.needs_revalidation || + component_needs_revalidation(s, self.passed_rightmost_selector); match *s { Component::NonTSPseudoClass(ref p) => { @@ -1883,13 +1899,15 @@ impl ElementAndPseudoRules { pseudo_element: Option<&PseudoElement>, quirks_mode: QuirksMode, ) -> Result<(), FailedAllocationError> { - debug_assert!(pseudo_element.map_or(true, |pseudo| { - !pseudo.is_precomputed() && !pseudo.is_unknown_webkit_pseudo_element() - })); + debug_assert!( + pseudo_element.map_or(true, |pseudo| !pseudo.is_precomputed() && + !pseudo.is_unknown_webkit_pseudo_element()) + ); let map = match pseudo_element { None => &mut self.element_map, - Some(pseudo) => self.pseudos_map + Some(pseudo) => self + .pseudos_map .get_or_insert_with(pseudo, || Box::new(SelectorMap::new())), }; @@ -2259,10 +2277,10 @@ impl CascadeData { debug!("Found valid keyframes rule: {:?}", *keyframes_rule); // Don't let a prefixed keyframes animation override a non-prefixed one. - let needs_insertion = keyframes_rule.vendor_prefix.is_none() || - self.animations - .get(keyframes_rule.name.as_atom()) - .map_or(true, |rule| rule.vendor_prefix.is_some()); + let needs_insertion = keyframes_rule.vendor_prefix.is_none() || self + .animations + .get(keyframes_rule.name.as_atom()) + .map_or(true, |rule| rule.vendor_prefix.is_some()); if needs_insertion { let animation = KeyframesAnimation::from_keyframes( &keyframes_rule.keyframes, @@ -2352,7 +2370,8 @@ impl CascadeData { let effective_now = import_rule .stylesheet .is_effective_for_device(&device, guard); - let effective_then = self.effective_media_query_results + let effective_then = self + .effective_media_query_results .was_effective(import_rule); if effective_now != effective_then { debug!( @@ -2378,9 +2397,7 @@ impl CascadeData { if effective_now != effective_then { debug!( " > @media rule {:?} changed {} -> {}", - mq, - effective_then, - effective_now + mq, effective_then, effective_now ); return false; } @@ -2460,8 +2477,10 @@ pub struct Rule { pub source_order: u32, /// The actual style rule. - #[cfg_attr(feature = "gecko", - ignore_malloc_size_of = "Secondary ref. Primary ref is in StyleRule under Stylesheet.")] + #[cfg_attr( + feature = "gecko", + ignore_malloc_size_of = "Secondary ref. Primary ref is in StyleRule under Stylesheet." + )] #[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")] pub style_rule: Arc>, } @@ -2486,7 +2505,13 @@ impl Rule { shadow_cascade_order: ShadowCascadeOrder, ) -> ApplicableDeclarationBlock { let source = StyleSource::from_rule(self.style_rule.clone()); - ApplicableDeclarationBlock::new(source, self.source_order, level, self.specificity(), shadow_cascade_order) + ApplicableDeclarationBlock::new( + source, + self.source_order, + level, + self.specificity(), + shadow_cascade_order, + ) } /// Creates a new Rule. diff --git a/components/style/traversal.rs b/components/style/traversal.rs index 0bffd39819c4..5f81f3544a91 100644 --- a/components/style/traversal.rs +++ b/components/style/traversal.rs @@ -208,11 +208,11 @@ pub trait DomTraversal: Sync { // animation-only restyle hint or recascade. if traversal_flags.for_animation_only() { return data.map_or(false, |d| d.has_styles()) && - (el.has_animation_only_dirty_descendants() || - data.as_ref() - .unwrap() - .hint - .has_animation_hint_or_recascade()); + (el.has_animation_only_dirty_descendants() || data + .as_ref() + .unwrap() + .hint + .has_animation_hint_or_recascade()); } // Non-incremental layout visits every node. @@ -279,7 +279,8 @@ pub trait DomTraversal: Sync { // likely to load valid bindings, we avoid wasted work here, which may // be a very big perf hit when elements with bindings are nested // heavily. - if cfg!(feature = "gecko") && is_initial_style && + if cfg!(feature = "gecko") && + is_initial_style && parent_data.styles.primary().has_moz_binding() { debug!("Parent {:?} has XBL binding, deferring traversal", parent); @@ -384,8 +385,7 @@ where ).resolve_style( style.as_ref().map(|s| &**s), layout_parent_style.as_ref().map(|s| &**s), - ) - .into() + ).into() } /// Calculates the style for a single node. @@ -411,7 +411,8 @@ pub fn recalc_style_at( context.thread_local.statistics.elements_traversed += 1; debug_assert!( - flags.intersects(TraversalFlags::AnimationOnly) || !element.has_snapshot() || + flags.intersects(TraversalFlags::AnimationOnly) || + !element.has_snapshot() || element.handled_snapshot(), "Should've handled snapshots here already" ); @@ -512,8 +513,9 @@ pub fn recalc_style_at( !child_cascade_requirement.can_skip_cascade() || is_servo_nonincremental_layout(); - traverse_children = traverse_children && - !traversal.should_cull_subtree(context, element, &data, is_initial_style); + traverse_children = + traverse_children && + !traversal.should_cull_subtree(context, element, &data, is_initial_style); // Examine our children, and enqueue the appropriate ones for traversal. if traverse_children { @@ -535,7 +537,8 @@ pub fn recalc_style_at( } debug_assert!( - flags.for_animation_only() || !flags.contains(TraversalFlags::ClearDirtyBits) || + flags.for_animation_only() || + !flags.contains(TraversalFlags::ClearDirtyBits) || !element.has_animation_only_dirty_descendants(), "Should have cleared animation bits already" ); diff --git a/components/style/use_counters/mod.rs b/components/style/use_counters/mod.rs index 92bc6adb01aa..49c77ae714d9 100644 --- a/components/style/use_counters/mod.rs +++ b/components/style/use_counters/mod.rs @@ -71,7 +71,8 @@ impl UseCounters { /// Used for parallel parsing, where we parse off-main-thread. #[inline] pub fn merge(&self, other: &Self) { - self.non_custom_properties.merge(&other.non_custom_properties) + self.non_custom_properties + .merge(&other.non_custom_properties) } } diff --git a/components/style/values/animated/color.rs b/components/style/values/animated/color.rs index 4356c5a3d9bf..afffce1c7671 100644 --- a/components/style/values/animated/color.rs +++ b/components/style/values/animated/color.rs @@ -61,7 +61,8 @@ impl Animate for RGBA { let red = (self.red * self.alpha).animate(&(other.red * other.alpha), procedure)? * 1. / alpha; let green = (self.green * self.alpha).animate(&(other.green * other.alpha), procedure)? * - 1. / alpha; + 1. / + alpha; let blue = (self.blue * self.alpha).animate(&(other.blue * other.alpha), procedure)? * 1. / alpha; @@ -223,7 +224,7 @@ impl Animate for Color { let fg = fg1.animate(&fg2, procedure)?; Self::with_ratios(bg_color, ComplexColorRatios { bg: 1., fg }) - } + }, }) } } @@ -239,19 +240,19 @@ impl ComputeSquaredDistance for Color { (Numeric(c1), Numeric(c2)) => c1.compute_squared_distance(&c2)?, (Foreground, Numeric(color)) | (Numeric(color), Foreground) => { // `computed_squared_distance` is symmetric. - color.compute_squared_distance(&RGBA::transparent())? - + SquaredDistance::from_sqrt(1.) - } + color.compute_squared_distance(&RGBA::transparent())? + + SquaredDistance::from_sqrt(1.) + }, (_, _) => { let self_color = self.effective_intermediate_rgba(); let other_color = other.effective_intermediate_rgba(); let self_ratios = self.effective_ratios(); let other_ratios = other.effective_ratios(); - self_color.compute_squared_distance(&other_color)? - + self_ratios.bg.compute_squared_distance(&other_ratios.bg)? - + self_ratios.fg.compute_squared_distance(&other_ratios.fg)? - } + self_color.compute_squared_distance(&other_color)? + + self_ratios.bg.compute_squared_distance(&other_ratios.bg)? + + self_ratios.fg.compute_squared_distance(&other_ratios.fg)? + }, }) } } diff --git a/components/style/values/animated/mod.rs b/components/style/values/animated/mod.rs index 24cf40f845e4..b70ef7d66391 100644 --- a/components/style/values/animated/mod.rs +++ b/components/style/values/animated/mod.rs @@ -399,7 +399,10 @@ where { #[inline] fn to_animated_zero(&self) -> Result { - let v = self.iter().map(|v| v.to_animated_zero()).collect::, _>>()?; + let v = self + .iter() + .map(|v| v.to_animated_zero()) + .collect::, _>>()?; Ok(v.into_boxed_slice()) } } diff --git a/components/style/values/computed/angle.rs b/components/style/values/computed/angle.rs index 67ea5d1231bd..e162b7a2499a 100644 --- a/components/style/values/computed/angle.rs +++ b/components/style/values/computed/angle.rs @@ -15,7 +15,9 @@ use values::distance::{ComputeSquaredDistance, SquaredDistance}; /// A computed angle. #[animate(fallback = "Self::animate_fallback")] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd, ToAnimatedZero, ToCss)] +#[derive( + Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd, ToAnimatedZero, ToCss, +)] pub enum Angle { /// An angle with degree unit. #[css(dimension)] @@ -73,7 +75,9 @@ impl Angle { /// #[inline] fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result { - Ok(Angle::from_radians(self.radians().animate(&other.radians(), procedure)?)) + Ok(Angle::from_radians( + self.radians().animate(&other.radians(), procedure)?, + )) } } diff --git a/components/style/values/computed/box.rs b/components/style/values/computed/box.rs index 15e447ea4156..002583b2c214 100644 --- a/components/style/values/computed/box.rs +++ b/components/style/values/computed/box.rs @@ -34,13 +34,14 @@ pub type Perspective = GenericPerspective; #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToCss)] +#[derive( + Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, +)] /// A computed value for the `float` property. pub enum Float { Left, Right, - None + None, } impl ToComputedValue for SpecifiedFloat { @@ -52,7 +53,9 @@ impl ToComputedValue for SpecifiedFloat { // https://drafts.csswg.org/css-logical-props/#float-clear match *self { SpecifiedFloat::InlineStart => { - context.rule_cache_conditions.borrow_mut() + context + .rule_cache_conditions + .borrow_mut() .set_writing_mode_dependency(context.builder.writing_mode); if ltr { Float::Left @@ -61,7 +64,9 @@ impl ToComputedValue for SpecifiedFloat { } }, SpecifiedFloat::InlineEnd => { - context.rule_cache_conditions.borrow_mut() + context + .rule_cache_conditions + .borrow_mut() .set_writing_mode_dependency(context.builder.writing_mode); if ltr { Float::Right @@ -71,7 +76,7 @@ impl ToComputedValue for SpecifiedFloat { }, SpecifiedFloat::Left => Float::Left, SpecifiedFloat::Right => Float::Right, - SpecifiedFloat::None => Float::None + SpecifiedFloat::None => Float::None, } } @@ -80,21 +85,22 @@ impl ToComputedValue for SpecifiedFloat { match *computed { Float::Left => SpecifiedFloat::Left, Float::Right => SpecifiedFloat::Right, - Float::None => SpecifiedFloat::None + Float::None => SpecifiedFloat::None, } } } #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, -SpecifiedValueInfo, ToCss)] +#[derive( + Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, +)] /// A computed value for the `clear` property. pub enum Clear { None, Left, Right, - Both + Both, } impl ToComputedValue for SpecifiedClear { @@ -106,7 +112,9 @@ impl ToComputedValue for SpecifiedClear { // https://drafts.csswg.org/css-logical-props/#float-clear match *self { SpecifiedClear::InlineStart => { - context.rule_cache_conditions.borrow_mut() + context + .rule_cache_conditions + .borrow_mut() .set_writing_mode_dependency(context.builder.writing_mode); if ltr { Clear::Left @@ -115,7 +123,9 @@ impl ToComputedValue for SpecifiedClear { } }, SpecifiedClear::InlineEnd => { - context.rule_cache_conditions.borrow_mut() + context + .rule_cache_conditions + .borrow_mut() .set_writing_mode_dependency(context.builder.writing_mode); if ltr { Clear::Right @@ -126,7 +136,7 @@ impl ToComputedValue for SpecifiedClear { SpecifiedClear::None => Clear::None, SpecifiedClear::Left => Clear::Left, SpecifiedClear::Right => Clear::Right, - SpecifiedClear::Both => Clear::Both + SpecifiedClear::Both => Clear::Both, } } @@ -160,23 +170,27 @@ impl ToComputedValue for specified::Resize { let is_vertical = context.style().writing_mode.is_vertical(); match self { specified::Resize::Inline => { - context.rule_cache_conditions.borrow_mut() + context + .rule_cache_conditions + .borrow_mut() .set_writing_mode_dependency(context.builder.writing_mode); if is_vertical { Resize::Vertical } else { Resize::Horizontal } - } + }, specified::Resize::Block => { - context.rule_cache_conditions.borrow_mut() + context + .rule_cache_conditions + .borrow_mut() .set_writing_mode_dependency(context.builder.writing_mode); if is_vertical { Resize::Horizontal } else { Resize::Vertical } - } + }, specified::Resize::None => Resize::None, specified::Resize::Both => Resize::Both, specified::Resize::Horizontal => Resize::Horizontal, diff --git a/components/style/values/computed/counters.rs b/components/style/values/computed/counters.rs index fd8d7763f1cf..211ca6753e7f 100644 --- a/components/style/values/computed/counters.rs +++ b/components/style/values/computed/counters.rs @@ -20,4 +20,3 @@ pub type Content = generics::Content; /// A computed content item. pub type ContentItem = generics::ContentItem; - diff --git a/components/style/values/computed/effects.rs b/components/style/values/computed/effects.rs index 07ac6441b6c5..b7e8315a6ace 100644 --- a/components/style/values/computed/effects.rs +++ b/components/style/values/computed/effects.rs @@ -20,11 +20,13 @@ pub type BoxShadow = GenericBoxShadow; /// A computed value for a single `filter`. #[cfg(feature = "gecko")] -pub type Filter = GenericFilter; +pub type Filter = + GenericFilter; /// A computed value for a single `filter`. #[cfg(not(feature = "gecko"))] -pub type Filter = GenericFilter; +pub type Filter = + GenericFilter; /// A computed value for the `drop-shadow()` filter. pub type SimpleShadow = GenericSimpleShadow; diff --git a/components/style/values/computed/font.rs b/components/style/values/computed/font.rs index 8db4bd7e9171..2c3d2853e5c8 100644 --- a/components/style/values/computed/font.rs +++ b/components/style/values/computed/font.rs @@ -35,8 +35,7 @@ pub use values::specified::font::{FontSynthesis, MozScriptSizeMultiplier, XLang, /// https://drafts.csswg.org/css-fonts-4/#propdef-font-weight /// /// This is effectively just a `Number`. -#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - ToCss)] +#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToCss)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] pub struct FontWeight(pub Number); @@ -60,8 +59,17 @@ impl ToAnimatedValue for FontWeight { } } -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - ToAnimatedZero, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + ToAnimatedZero, + ToCss, +)] /// The computed value of font-size pub struct FontSize { /// The size. @@ -217,9 +225,9 @@ impl FontFamily { #[inline] /// Get default font family as `serif` which is a generic font-family pub fn serif() -> Self { - FontFamily(FontFamilyList::new(Box::new([ - SingleFontFamily::Generic(atom!("serif")), - ]))) + FontFamily(FontFamilyList::new(Box::new([SingleFontFamily::Generic( + atom!("serif"), + )]))) } } @@ -473,9 +481,7 @@ impl SingleFontFamily { FontFamilyType::eFamily_monospace => SingleFontFamily::Generic(atom!("monospace")), FontFamilyType::eFamily_cursive => SingleFontFamily::Generic(atom!("cursive")), FontFamilyType::eFamily_fantasy => SingleFontFamily::Generic(atom!("fantasy")), - FontFamilyType::eFamily_moz_fixed => { - SingleFontFamily::Generic(atom!("-moz-fixed")) - }, + FontFamilyType::eFamily_moz_fixed => SingleFontFamily::Generic(atom!("-moz-fixed")), FontFamilyType::eFamily_named => { let name = Atom::from(&*family.mName); SingleFontFamily::FamilyName(FamilyName { @@ -851,9 +857,10 @@ impl ToAnimatedValue for FontStyleAngle { #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { FontStyleAngle(Angle::Deg( - animated.degrees() + animated + .degrees() .min(specified::FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES) - .max(specified::FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES) + .max(specified::FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES), )) } } @@ -882,10 +889,11 @@ impl FontStyle { /// https://drafts.csswg.org/css-fonts-4/#valdef-font-style-oblique-angle #[inline] pub fn default_angle() -> FontStyleAngle { - FontStyleAngle(Angle::Deg(specified::DEFAULT_FONT_STYLE_OBLIQUE_ANGLE_DEGREES)) + FontStyleAngle(Angle::Deg( + specified::DEFAULT_FONT_STYLE_OBLIQUE_ANGLE_DEGREES, + )) } - /// Get the font style from Gecko's nsFont struct. #[cfg(feature = "gecko")] pub fn from_gecko(style: structs::FontSlantStyle) -> Self { @@ -923,7 +931,7 @@ impl ToCss for FontStyle { angle.to_css(dest)?; } Ok(()) - } + }, } } } diff --git a/components/style/values/computed/length.rs b/components/style/values/computed/length.rs index 0ff99a08a3fb..f2d43e2ada9d 100644 --- a/components/style/values/computed/length.rs +++ b/components/style/values/computed/length.rs @@ -80,7 +80,8 @@ impl ComputeSquaredDistance for CalcLengthOrPercentage { fn compute_squared_distance(&self, other: &Self) -> Result { // FIXME(nox): This looks incorrect to me, to add a distance between lengths // with a distance between percentages. - Ok(self.unclamped_length() + Ok(self + .unclamped_length() .compute_squared_distance(&other.unclamped_length())? + self.percentage() .compute_squared_distance(&other.percentage())?) @@ -285,9 +286,15 @@ impl specified::CalcLengthOrPercentage { /// Compute the value into pixel length as CSSFloat without context, /// so it returns Err(()) if there is any non-absolute unit. pub fn to_computed_pixel_length_without_context(&self) -> Result { - if self.vw.is_some() || self.vh.is_some() || self.vmin.is_some() || self.vmax.is_some() || - self.em.is_some() || self.ex.is_some() || self.ch.is_some() || - self.rem.is_some() || self.percentage.is_some() + if self.vw.is_some() || + self.vh.is_some() || + self.vmin.is_some() || + self.vmax.is_some() || + self.em.is_some() || + self.ex.is_some() || + self.ch.is_some() || + self.rem.is_some() || + self.percentage.is_some() { return Err(()); } @@ -324,8 +331,17 @@ impl ToComputedValue for specified::CalcLengthOrPercentage { #[allow(missing_docs)] #[animate(fallback = "Self::animate_fallback")] #[css(derive_debug)] -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, MallocSizeOf, PartialEq, - ToAnimatedValue, ToAnimatedZero, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + MallocSizeOf, + PartialEq, + ToAnimatedValue, + ToAnimatedZero, + ToCss, +)] #[distance(fallback = "Self::compute_squared_distance_fallback")] pub enum LengthOrPercentage { Length(Length), @@ -483,11 +499,9 @@ impl LengthOrPercentageOrAuto { fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result { let this = >::from(*self); let other = >::from(*other); - Ok(LengthOrPercentageOrAuto::Calc(this.animate( - &other, - procedure, - )? - .ok_or(())?)) + Ok(LengthOrPercentageOrAuto::Calc( + this.animate(&other, procedure)?.ok_or(())?, + )) } #[inline] @@ -602,11 +616,9 @@ impl LengthOrPercentageOrNone { fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result { let this = >::from(*self); let other = >::from(*other); - Ok(LengthOrPercentageOrNone::Calc(this.animate( - &other, - procedure, - )? - .ok_or(())?)) + Ok(LengthOrPercentageOrNone::Calc( + this.animate(&other, procedure)?.ok_or(())?, + )) } fn compute_squared_distance_fallback(&self, other: &Self) -> Result { @@ -727,8 +739,18 @@ impl NonNegativeLengthOrPercentage { /// The computed `` value. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - PartialOrd, ToAnimatedValue, ToAnimatedZero)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + PartialOrd, + ToAnimatedValue, + ToAnimatedZero, +)] pub struct CSSPixelLength(CSSFloat); impl CSSPixelLength { @@ -916,8 +938,7 @@ pub type NonNegativeLengthOrPercentageOrNormal = Either { generic::TransformOperation::Rotate3D(0., 0., 1., angle.clone()) - } + }, generic::TransformOperation::RotateX(ref angle) => { generic::TransformOperation::Rotate3D(1., 0., 0., angle.clone()) - } + }, generic::TransformOperation::RotateY(ref angle) => { generic::TransformOperation::Rotate3D(0., 1., 0., angle.clone()) - } + }, _ => unreachable!(), } } @@ -273,9 +273,9 @@ impl ToAnimatedZero for TransformOperation { generic::TransformOperation::Rotate(_) => { Ok(generic::TransformOperation::Rotate(Angle::zero())) }, - generic::TransformOperation::Perspective(ref l) => { - Ok(generic::TransformOperation::Perspective(l.to_animated_zero()?)) - }, + generic::TransformOperation::Perspective(ref l) => Ok( + generic::TransformOperation::Perspective(l.to_animated_zero()?), + ), generic::TransformOperation::AccumulateMatrix { .. } | generic::TransformOperation::InterpolateMatrix { .. } => { // AccumulateMatrix/InterpolateMatrix: We do interpolation on @@ -293,10 +293,12 @@ impl ToAnimatedZero for TransformOperation { impl ToAnimatedZero for Transform { #[inline] fn to_animated_zero(&self) -> Result { - Ok(generic::Transform(self.0 - .iter() - .map(|op| op.to_animated_zero()) - .collect::, _>>()?)) + Ok(generic::Transform( + self.0 + .iter() + .map(|op| op.to_animated_zero()) + .collect::, _>>()?, + )) } } diff --git a/components/style/values/generics/background.rs b/components/style/values/generics/background.rs index b25b00514d02..a4f4c58d8cd3 100644 --- a/components/style/values/generics/background.rs +++ b/components/style/values/generics/background.rs @@ -5,9 +5,20 @@ //! Generic types for CSS values related to backgrounds. /// A generic value for the `background-size` property. -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, - ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub enum BackgroundSize { /// ` ` Explicit { diff --git a/components/style/values/generics/basic_shape.rs b/components/style/values/generics/basic_shape.rs index d2cc98b755d9..513e5de0e2bd 100644 --- a/components/style/values/generics/basic_shape.rs +++ b/components/style/values/generics/basic_shape.rs @@ -19,8 +19,9 @@ pub type ClippingShape = ShapeSource #[allow(missing_docs)] -#[derive(Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] pub enum GeometryBox { FillBox, StrokeBox, @@ -34,8 +35,19 @@ pub type FloatAreaShape = ShapeSource { #[animation(error)] ImageOrUrl(ImageOrUrl), @@ -61,8 +74,17 @@ pub enum ShapeSource { } #[allow(missing_docs)] -#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] pub enum BasicShape { Inset(#[css(field_bound)] InsetRect), Circle(#[css(field_bound)] Circle), @@ -73,8 +95,16 @@ pub enum BasicShape { /// #[allow(missing_docs)] #[css(function = "inset")] -#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToComputedValue)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, +)] pub struct InsetRect { pub rect: Rect, pub round: Option>, @@ -83,8 +113,17 @@ pub struct InsetRect { /// #[allow(missing_docs)] #[css(function)] -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToComputedValue)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, +)] pub struct Circle { pub position: Position, pub radius: ShapeRadius, @@ -93,8 +132,17 @@ pub struct Circle { /// #[allow(missing_docs)] #[css(function)] -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToComputedValue)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, +)] pub struct Ellipse { pub position: Position, pub semiaxis_x: ShapeRadius, @@ -103,8 +151,18 @@ pub struct Ellipse { /// #[allow(missing_docs)] -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] pub enum ShapeRadius { Length(LengthOrPercentage), #[animation(error)] @@ -117,8 +175,7 @@ pub enum ShapeRadius { /// /// #[css(comma, function)] -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct Polygon { /// The filling rule for a polygon. #[css(skip_if = "fill_is_default")] @@ -129,8 +186,7 @@ pub struct Polygon { } /// Coordinates for Polygon. -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct PolygonCoord(pub LengthOrPercentage, pub LengthOrPercentage); // https://drafts.csswg.org/css-shapes/#typedef-fill-rule @@ -139,8 +195,18 @@ pub struct PolygonCoord(pub LengthOrPercentage, pub LengthOr // says that it can also be `inherit` #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] #[repr(u8)] pub enum FillRule { Nonzero, @@ -151,8 +217,9 @@ pub enum FillRule { /// /// https://drafts.csswg.org/css-shapes-2/#funcdef-path #[css(comma)] -#[derive(Animate, Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Animate, Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] pub struct Path { /// The filling rule for the svg path. #[css(skip_if = "fill_is_default")] @@ -174,17 +241,16 @@ where ( &ShapeSource::Shape(ref this, ref this_box), &ShapeSource::Shape(ref other, ref other_box), - ) if this_box == other_box => + ) + if this_box == other_box => { this.compute_squared_distance(other) }, - ( - &ShapeSource::Path(ref this), - &ShapeSource::Path(ref other), - ) if this.fill == other.fill => + (&ShapeSource::Path(ref this), &ShapeSource::Path(ref other)) + if this.fill == other.fill => { this.path.compute_squared_distance(&other.path) - } + }, _ => Err(()), } } @@ -232,7 +298,8 @@ where if self.coordinates.len() != other.coordinates.len() { return Err(()); } - let coordinates = self.coordinates + let coordinates = self + .coordinates .iter() .zip(other.coordinates.iter()) .map(|(this, other)| { @@ -240,8 +307,7 @@ where this.0.animate(&other.0, procedure)?, this.1.animate(&other.1, procedure)?, )) - }) - .collect::, _>>()?; + }).collect::, _>>()?; Ok(Polygon { fill: self.fill, coordinates, @@ -267,8 +333,7 @@ where let d1 = this.0.compute_squared_distance(&other.0)?; let d2 = this.1.compute_squared_distance(&other.1)?; Ok(d1 + d2) - }) - .sum() + }).sum() } } diff --git a/components/style/values/generics/border.rs b/components/style/values/generics/border.rs index c25560ed0f15..4f40409843aa 100644 --- a/components/style/values/generics/border.rs +++ b/components/style/values/generics/border.rs @@ -10,8 +10,9 @@ use values::generics::rect::Rect; use values::generics::size::Size; /// A generic value for a single side of a `border-image-width` property. -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] pub enum BorderImageSideWidth { /// `` Length(LengthOrPercentage), @@ -22,8 +23,9 @@ pub enum BorderImageSideWidth { } /// A generic value for the `border-image-slice` property. -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] pub struct BorderImageSlice { /// The offsets. #[css(field_bound)] @@ -34,8 +36,18 @@ pub struct BorderImageSlice { } /// A generic value for the `border-*-radius` longhand properties. -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] pub struct BorderCornerRadius(#[css(field_bound)] pub Size); impl BorderCornerRadius { @@ -46,9 +58,20 @@ impl BorderCornerRadius { } /// A generic value for the `border-spacing` property. -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, - ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub struct BorderSpacing(#[css(field_bound)] pub Size); impl BorderSpacing { @@ -61,8 +84,17 @@ impl BorderSpacing { /// A generic value for `border-radius`, `outline-radius` and `inset()`. /// /// -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToComputedValue)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, +)] pub struct BorderRadius { /// The top left radius. pub top_left: BorderCornerRadius, @@ -120,7 +152,9 @@ where W: Write, { widths.to_css(dest)?; - if widths.0 != heights.0 || widths.1 != heights.1 || widths.2 != heights.2 || + if widths.0 != heights.0 || + widths.1 != heights.1 || + widths.2 != heights.2 || widths.3 != heights.3 { dest.write_str(" / ")?; diff --git a/components/style/values/generics/box.rs b/components/style/values/generics/box.rs index ea79e98eefb8..0b5259742887 100644 --- a/components/style/values/generics/box.rs +++ b/components/style/values/generics/box.rs @@ -7,8 +7,18 @@ use values::animated::ToAnimatedZero; /// A generic value for the `vertical-align` property. -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] pub enum VerticalAlign { /// `baseline` Baseline, @@ -48,8 +58,7 @@ impl ToAnimatedZero for VerticalAlign { } /// https://drafts.csswg.org/css-animations/#animation-iteration-count -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub enum AnimationIterationCount { /// A `` value. Number(Number), @@ -58,9 +67,20 @@ pub enum AnimationIterationCount { } /// A generic value for the `perspective` property. -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, - ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub enum Perspective { /// A non-negative length. Length(NonNegativeLength), diff --git a/components/style/values/generics/column.rs b/components/style/values/generics/column.rs index 1d76f6cb552c..5f96650d3e8d 100644 --- a/components/style/values/generics/column.rs +++ b/components/style/values/generics/column.rs @@ -5,9 +5,20 @@ //! Generic types for the column properties. /// A generic type for `column-count` values. -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, - ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub enum ColumnCount { /// A positive integer. Integer(PositiveInteger), diff --git a/components/style/values/generics/counters.rs b/components/style/values/generics/counters.rs index 779d56d65ee9..4bbf728d457c 100644 --- a/components/style/values/generics/counters.rs +++ b/components/style/values/generics/counters.rs @@ -14,8 +14,7 @@ use values::generics::CounterStyleOrNone; use values::specified::Attr; /// A name / value pair for counters. -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct CounterPair { /// The name of the counter. pub name: CustomIdent, @@ -24,8 +23,9 @@ pub struct CounterPair { } /// A generic value for the `counter-increment` property. -#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] pub struct CounterIncrement(Counters); impl CounterIncrement { @@ -46,8 +46,9 @@ impl Deref for CounterIncrement { } /// A generic value for the `counter-reset` property. -#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] pub struct CounterReset(Counters); impl CounterReset { @@ -70,8 +71,7 @@ impl Deref for CounterReset { /// A generic value for lists of counters. /// /// Keyword `none` is represented by an empty vector. -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct Counters(#[css(iterable, if_empty = "none")] Box<[CounterPair]>); impl Default for Counters { @@ -102,8 +102,7 @@ fn is_decimal(counter_type: &CounterStyleType) -> bool { /// The specified value for the `content` property. /// /// https://drafts.csswg.org/css-content/#propdef-content -#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub enum Content { /// `normal` reserved keyword. Normal, @@ -125,8 +124,7 @@ impl Content { } /// Items for the `content` property. -#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub enum ContentItem { /// Literal string content. String(Box), diff --git a/components/style/values/generics/effects.rs b/components/style/values/generics/effects.rs index f05dfe82d66f..7c7e3f4bef32 100644 --- a/components/style/values/generics/effects.rs +++ b/components/style/values/generics/effects.rs @@ -5,8 +5,17 @@ //! Generic types for CSS values related to effects. /// A generic value for a single `box-shadow`. -#[derive(Animate, Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToAnimatedValue, ToAnimatedZero, ToCss)] +#[derive( + Animate, + Clone, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToCss, +)] pub struct BoxShadow { /// The base shadow. pub base: SimpleShadow, @@ -21,8 +30,17 @@ pub struct BoxShadow { /// A generic value for a single `filter`. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[animation(no_bound(Url))] -#[derive(Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss)] +#[derive( + Clone, + ComputeSquaredDistance, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToComputedValue, + ToCss, +)] pub enum Filter { /// `blur()` #[css(function)] @@ -63,8 +81,18 @@ pub enum Filter { /// /// Contrary to the canonical order from the spec, the color is serialised /// first, like in Gecko and Webkit. -#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToCss, +)] pub struct SimpleShadow { /// Color. pub color: Color, diff --git a/components/style/values/generics/flex.rs b/components/style/values/generics/flex.rs index 1ab53233c446..9cbece2e1bc2 100644 --- a/components/style/values/generics/flex.rs +++ b/components/style/values/generics/flex.rs @@ -6,9 +6,19 @@ /// A generic value for the `flex-basis` property. #[cfg_attr(feature = "servo", derive(MallocSizeOf))] -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, PartialEq, - SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, - ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub enum FlexBasis { /// `content` Content, diff --git a/components/style/values/generics/font.rs b/components/style/values/generics/font.rs index 02df291065f3..03a76c5a32d2 100644 --- a/components/style/values/generics/font.rs +++ b/components/style/values/generics/font.rs @@ -16,8 +16,7 @@ use style_traits::{SpecifiedValueInfo, StyleParseErrorKind, ToCss}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; /// https://drafts.csswg.org/css-fonts-4/#feature-tag-value -#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct FeatureTagValue { /// A four-character tag, packed into a u32 (one byte per character). pub tag: FontTag, @@ -47,8 +46,9 @@ where /// Variation setting for a single feature, see: /// /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def -#[derive(Animate, Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Animate, Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] pub struct VariationValue { /// A four-character tag, packed into a u32 (one byte per character). #[animation(constant)] @@ -72,8 +72,7 @@ where /// A value both for font-variation-settings and font-feature-settings. #[css(comma)] -#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct FontSettings(#[css(if_empty = "normal", iterable)] pub Box<[T]>); impl FontSettings { @@ -109,8 +108,7 @@ impl Parse for FontSettings { /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings /// -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct FontTag(pub u32); impl ToCss for FontTag { @@ -145,8 +143,18 @@ impl Parse for FontTag { } } -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - ToAnimatedValue, ToAnimatedZero, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + ToAnimatedValue, + ToAnimatedZero, + ToCss, +)] /// Additional information for keyword-derived font sizes. pub struct KeywordInfo { /// The keyword used @@ -189,9 +197,20 @@ impl SpecifiedValueInfo for KeywordInfo { } /// CSS font keywords -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - Parse, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, - ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToCss, +)] #[allow(missing_docs)] pub enum KeywordSize { #[css(keyword = "xx-small")] @@ -228,8 +247,19 @@ impl Default for KeywordSize { /// https://drafts.csswg.org/css-fonts-4/#font-style-prop #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, Hash, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + Hash, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, +)] pub enum FontStyle { #[animation(error)] Normal, diff --git a/components/style/values/generics/gecko.rs b/components/style/values/generics/gecko.rs index 72a8b71d073e..d56158750b6b 100644 --- a/components/style/values/generics/gecko.rs +++ b/components/style/values/generics/gecko.rs @@ -7,8 +7,7 @@ /// A generic value for scroll snap points. #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] -#[derive(Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToComputedValue, - ToCss)] +#[derive(Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub enum ScrollSnapPoint { /// `none` None, diff --git a/components/style/values/generics/grid.rs b/components/style/values/generics/grid.rs index b9ec85ace226..56b6f463691d 100644 --- a/components/style/values/generics/grid.rs +++ b/components/style/values/generics/grid.rs @@ -18,8 +18,7 @@ use values::specified::grid::parse_line_names; /// A `` type. /// /// -#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct GridLine { /// Flag to check whether it's a `span` keyword. pub is_span: bool, @@ -149,8 +148,18 @@ impl Parse for GridLine { #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] pub enum TrackKeyword { Auto, MaxContent, @@ -161,8 +170,7 @@ pub enum TrackKeyword { /// avoid re-implementing it for the computed type. /// /// -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub enum TrackBreadth { /// The generic type is almost always a non-negative `` Breadth(L), @@ -383,8 +391,7 @@ impl Parse for RepeatCount { /// /// It can also hold `repeat()` function parameters, which expands into the respective /// values in its computed form. -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] #[css(function = "repeat")] pub struct TrackRepeat { /// The number of times for the value to be repeated (could also be `auto-fit` or `auto-fill`) @@ -409,7 +416,8 @@ impl ToCss for TrackRepeat { dest.write_str(", ")?; let mut line_names_iter = self.line_names.iter(); - for (i, (ref size, ref names)) in self.track_sizes + for (i, (ref size, ref names)) in self + .track_sizes .iter() .zip(&mut line_names_iter) .enumerate() @@ -471,8 +479,7 @@ impl TrackRepeat { } /// Track list values. Can be or -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub enum TrackListValue { /// A value. TrackSize(TrackSize), @@ -578,8 +585,7 @@ impl ToCss for TrackList { /// /// `subgrid [ | repeat( | auto-fill, +) ]+` /// Old spec: https://www.w3.org/TR/2015/WD-css-grid-1-20150917/#typedef-line-name-list -#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct LineNameList { /// The optional `` pub names: Box<[Box<[CustomIdent]>]>, @@ -624,7 +630,9 @@ impl Parse for LineNameList { RepeatCount::AutoFill if fill_idx.is_none() => { // `repeat(autof-fill, ..)` should have just one line name. if names_list.len() != 1 { - return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); + return Err( + input.new_custom_error(StyleParseErrorKind::UnspecifiedError) + ); } let names = names_list.pop().unwrap(); @@ -682,8 +690,7 @@ impl ToCss for LineNameList { /// Variants for ` | ` /// Subgrid deferred to Level 2 spec due to lack of implementation. /// But it's implemented in gecko, so we have to as well. -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub enum GridTemplateComponent { /// `none` value. None, diff --git a/components/style/values/generics/image.rs b/components/style/values/generics/image.rs index 2da4d2900398..16d348ac47ec 100644 --- a/components/style/values/generics/image.rs +++ b/components/style/values/generics/image.rs @@ -145,7 +145,7 @@ pub struct PaintWorklet { pub arguments: Vec>, } -impl ::style_traits::SpecifiedValueInfo for PaintWorklet { } +impl ::style_traits::SpecifiedValueInfo for PaintWorklet {} impl ToCss for PaintWorklet { fn to_css(&self, dest: &mut CssWriter) -> fmt::Result @@ -167,8 +167,7 @@ impl ToCss for PaintWorklet { /// `-moz-image-rect(, top, right, bottom, left);` #[allow(missing_docs)] #[css(comma, function)] -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct MozImageRect { pub url: MozImageRectUrl, pub top: NumberOrPercentage, diff --git a/components/style/values/generics/mod.rs b/components/style/values/generics/mod.rs index e6c1befea9f8..32ea771cf15e 100644 --- a/components/style/values/generics/mod.rs +++ b/components/style/values/generics/mod.rs @@ -157,14 +157,37 @@ impl SpecifiedValueInfo for CounterStyleOrNone { /// A wrapper of Non-negative values. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, Hash, MallocSizeOf, - PartialEq, PartialOrd, SpecifiedValueInfo, ToAnimatedZero, - ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + Hash, + MallocSizeOf, + PartialEq, + PartialOrd, + SpecifiedValueInfo, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub struct NonNegative(pub T); /// A wrapper of greater-than-or-equal-to-one values. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, PartialOrd, SpecifiedValueInfo, ToAnimatedZero, - ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + PartialOrd, + SpecifiedValueInfo, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub struct GreaterThanOrEqualToOne(pub T); diff --git a/components/style/values/generics/position.rs b/components/style/values/generics/position.rs index 67c167c41ab6..83dc48d0905e 100644 --- a/components/style/values/generics/position.rs +++ b/components/style/values/generics/position.rs @@ -6,8 +6,18 @@ //! [`position`](https://drafts.csswg.org/css-backgrounds-3/#position) /// A generic type for representing a CSS [position](https://drafts.csswg.org/css-values/#position). -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedZero, + ToComputedValue, +)] pub struct Position { /// The horizontal component of position. pub horizontal: H, @@ -26,8 +36,19 @@ impl Position { } /// A generic value for the `z-index` property. -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub enum ZIndex { /// An integer value. Integer(Integer), diff --git a/components/style/values/generics/rect.rs b/components/style/values/generics/rect.rs index fb67e48a3954..510cb75a6f8b 100644 --- a/components/style/values/generics/rect.rs +++ b/components/style/values/generics/rect.rs @@ -11,8 +11,17 @@ use style_traits::{CssWriter, ParseError, ToCss}; /// A CSS value made of four components, where its `ToCss` impl will try to /// serialize as few components as possible, like for example in `border-width`. -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToComputedValue)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, +)] pub struct Rect(pub T, pub T, pub T, pub T); impl Rect { diff --git a/components/style/values/generics/size.rs b/components/style/values/generics/size.rs index ad93b94e65ee..d7ef5810f05b 100644 --- a/components/style/values/generics/size.rs +++ b/components/style/values/generics/size.rs @@ -13,8 +13,17 @@ use values::animated::ToAnimatedValue; /// A generic size, for `border-*-radius` longhand properties, or /// `border-spacing`. -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - ToAnimatedZero, ToComputedValue)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + ToAnimatedZero, + ToComputedValue, +)] pub struct Size(pub Size2D); impl Size { diff --git a/components/style/values/generics/svg.rs b/components/style/values/generics/svg.rs index 0fbaacf22833..8b8fa786e8f8 100644 --- a/components/style/values/generics/svg.rs +++ b/components/style/values/generics/svg.rs @@ -16,8 +16,18 @@ use values::distance::{ComputeSquaredDistance, SquaredDistance}; /// /// #[animation(no_bound(UrlPaintServer))] -#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToComputedValue, + ToCss, +)] pub struct SVGPaint { /// The paint source pub kind: SVGPaintKind, @@ -31,9 +41,19 @@ pub struct SVGPaint { /// to have a fallback, Gecko lets the context /// properties have a fallback as well. #[animation(no_bound(UrlPaintServer))] -#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, - ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub enum SVGPaintKind { /// `none` #[animation(error)] @@ -113,8 +133,18 @@ impl Parse for SVGPaint | | for svg which allow unitless length. /// -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub enum SvgLengthOrPercentageOrNumber { /// | LengthOrPercentage(LengthOrPercentage), @@ -191,9 +221,19 @@ impl Parse } /// An SVG length value supports `context-value` in addition to length. -#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, - ToCss)] +#[derive( + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub enum SVGLength { /// ` | | ` Length(LengthType), @@ -202,23 +242,38 @@ pub enum SVGLength { } /// Generic value for stroke-dasharray. -#[derive(Clone, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss)] +#[derive( + Clone, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToComputedValue, + ToCss, +)] pub enum SVGStrokeDashArray { /// `[ | | ]#` #[css(comma)] - Values( - #[css(if_empty = "none", iterable)] - Vec, - ), + Values(#[css(if_empty = "none", iterable)] Vec), /// `context-value` ContextValue, } /// An SVG opacity value accepts `context-{fill,stroke}-opacity` in /// addition to opacity value. -#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)] +#[derive( + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub enum SVGOpacity { /// `` Opacity(OpacityType), diff --git a/components/style/values/generics/text.rs b/components/style/values/generics/text.rs index 6cc5caaac777..e85c444a6956 100644 --- a/components/style/values/generics/text.rs +++ b/components/style/values/generics/text.rs @@ -12,8 +12,9 @@ use values::animated::{Animate, Procedure, ToAnimatedZero}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; /// A generic value for the `initial-letter` property. -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] pub enum InitialLetter { /// `normal` Normal, @@ -30,8 +31,9 @@ impl InitialLetter { } /// A generic spacing value for the `letter-spacing` and `word-spacing` properties. -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] pub enum Spacing { /// `normal` Normal, @@ -112,8 +114,18 @@ where } /// A generic value for the `line-height` property. -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToCss, +)] pub enum LineHeight { /// `normal` Normal, @@ -142,9 +154,20 @@ impl LineHeight { } /// A generic value for the `-moz-tab-size` property. -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, - ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub enum MozTabSize { /// A number. Number(Number), diff --git a/components/style/values/generics/transform.rs b/components/style/values/generics/transform.rs index a0cbc57d6b43..cce0464d2ac9 100644 --- a/components/style/values/generics/transform.rs +++ b/components/style/values/generics/transform.rs @@ -15,8 +15,9 @@ use values::specified::length::LengthOrPercentage as SpecifiedLengthOrPercentage /// A generic 2D transformation matrix. #[allow(missing_docs)] -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] #[css(comma, function)] pub struct Matrix { pub a: T, @@ -66,8 +67,19 @@ impl> From> for Transform3D { } /// A generic transform origin. -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, - PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub struct TransformOrigin { /// The horizontal origin. pub horizontal: H, @@ -80,8 +92,7 @@ pub struct TransformOrigin { /// A generic timing function. /// /// -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToCss)] +#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)] #[value_info(ty = "TIMING_FUNCTION")] pub enum TimingFunction { /// `linear | ease | ease-in | ease-out | ease-in-out` @@ -106,8 +117,18 @@ pub enum TimingFunction { #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] pub enum TimingKeyword { Linear, Ease, @@ -163,8 +184,7 @@ impl TimingKeyword { } } -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] /// A single operation in the list of a `transform` value pub enum TransformOperation { /// Represents a 2D 2x3 matrix. @@ -268,8 +288,7 @@ pub enum TransformOperation }, } -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] /// A value of the `transform` property pub struct Transform(#[css(if_empty = "none", iterable)] pub Vec); @@ -281,11 +300,7 @@ impl use self::TransformOperation::*; matches!( *self, - Rotate(..) | - Rotate3D(..) | - RotateX(..) | - RotateY(..) | - RotateZ(..) + Rotate(..) | Rotate3D(..) | RotateX(..) | RotateY(..) | RotateZ(..) ) } @@ -574,8 +589,18 @@ pub fn get_normalized_vector_and_angle( } } -#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)] +#[derive( + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] /// A value of the `Rotate` property /// /// @@ -588,8 +613,18 @@ pub enum Rotate { Rotate3D(Number, Number, Number, Angle), } -#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)] +#[derive( + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] /// A value of the `Scale` property /// /// @@ -604,8 +639,17 @@ pub enum Scale { Scale3D(Number, Number, Number), } -#[derive(Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)] +#[derive( + Clone, + ComputeSquaredDistance, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] /// A value of the `Translate` property /// /// @@ -621,8 +665,9 @@ pub enum Translate { } #[allow(missing_docs)] -#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] pub enum TransformStyle { #[cfg(feature = "servo")] Auto, diff --git a/components/style/values/generics/ui.rs b/components/style/values/generics/ui.rs index 9ccf1f80d537..bef1926bc904 100644 --- a/components/style/values/generics/ui.rs +++ b/components/style/values/generics/ui.rs @@ -11,8 +11,7 @@ use style_traits::cursor::CursorKind; /// A generic value for the `cursor` property. /// /// https://drafts.csswg.org/css-ui/#cursor -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct Cursor { /// The parsed images for the cursor. pub images: Box<[Image]>, @@ -45,8 +44,7 @@ impl ToCss for Cursor { } /// A generic value for item of `image cursors`. -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct CursorImage { /// The url to parse images from. pub url: ImageUrl, diff --git a/components/style/values/generics/url.rs b/components/style/values/generics/url.rs index 5da74a7b0874..ff9fa16d6655 100644 --- a/components/style/values/generics/url.rs +++ b/components/style/values/generics/url.rs @@ -9,9 +9,19 @@ use parser::{Parse, ParserContext}; use style_traits::ParseError; /// An image url or none, used for example in list-style-image -#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, - ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub enum UrlOrNone { /// `none` None, diff --git a/components/style/values/mod.rs b/components/style/values/mod.rs index a5f8d0abd32e..d3ae6a839715 100644 --- a/components/style/values/mod.rs +++ b/components/style/values/mod.rs @@ -92,8 +92,13 @@ where } /// Convenience void type to disable some properties and values through types. -#[cfg_attr(feature = "servo", derive(Deserialize, MallocSizeOf, Serialize))] -#[derive(Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss)] +#[cfg_attr( + feature = "servo", + derive(Deserialize, MallocSizeOf, Serialize) +)] +#[derive( + Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss, +)] pub enum Impossible {} // FIXME(nox): This should be derived but the derive code cannot cope @@ -115,9 +120,19 @@ impl Parse for Impossible { } /// A struct representing one of two kinds of values. -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, - ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub enum Either { /// The first value. First(A), @@ -148,8 +163,7 @@ impl Parse for Either { } /// -#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct CustomIdent(pub Atom); impl CustomIdent { @@ -164,7 +178,9 @@ impl CustomIdent { _ => true }; if !valid { - return Err(location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))); + return Err( + location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone())) + ); } if excluding.iter().any(|s| ident.eq_ignore_ascii_case(s)) { Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)) diff --git a/components/style/values/specified/align.rs b/components/style/values/specified/align.rs index 731844bcb52c..858ecce065d8 100644 --- a/components/style/values/specified/align.rs +++ b/components/style/values/specified/align.rs @@ -683,8 +683,13 @@ fn parse_self_position<'i, 't>( fn list_self_position_keywords(f: KeywordsCollectFn, axis: AxisDirection) { f(&[ - "start", "end", "flex-start", "flex-end", - "center", "self-start", "self-end", + "start", + "end", + "flex-start", + "flex-end", + "center", + "self-start", + "self-end", ]); if axis == AxisDirection::Inline { f(&["left", "right"]); diff --git a/components/style/values/specified/background.rs b/components/style/values/specified/background.rs index d7c4ec629cad..6c85d6ec5a67 100644 --- a/components/style/values/specified/background.rs +++ b/components/style/values/specified/background.rs @@ -43,8 +43,18 @@ impl BackgroundSize { } /// One of the keywords for `background-repeat`. -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] #[allow(missing_docs)] pub enum BackgroundRepeatKeyword { Repeat, @@ -56,8 +66,7 @@ pub enum BackgroundRepeatKeyword { /// The specified value for the `background-repeat` property. /// /// https://drafts.csswg.org/css-backgrounds/#the-background-repeat -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToCss)] +#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)] pub enum BackgroundRepeat { /// `repeat-x` RepeatX, @@ -91,7 +100,9 @@ impl Parse for BackgroundRepeat { let horizontal = match BackgroundRepeatKeyword::from_ident(&ident) { Ok(h) => h, Err(()) => { - return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))); + return Err( + input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone())) + ); }, }; diff --git a/components/style/values/specified/basic_shape.rs b/components/style/values/specified/basic_shape.rs index 18541b8dbce5..cdafbf14b371 100644 --- a/components/style/values/specified/basic_shape.rs +++ b/components/style/values/specified/basic_shape.rs @@ -268,8 +268,7 @@ impl Ellipse { ShapeRadius::parse(context, i)?, ShapeRadius::parse(context, i)?, )) - }) - .unwrap_or_default(); + }).unwrap_or_default(); let position = if input.try(|i| i.expect_ident_matching("at")).is_ok() { Position::parse(context, input)? } else { @@ -416,8 +415,7 @@ impl Polygon { let fill = FillRule::parse(i)?; i.expect_comma()?; // only eat the comma if there is something before it Ok(fill) - }) - .unwrap_or_default(); + }).unwrap_or_default(); let buf = input.parse_comma_separated(|i| { Ok(PolygonCoord( @@ -449,11 +447,12 @@ impl Path { context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result> { - let fill = input.try(|i| -> Result<_, ParseError> { - let fill = FillRule::parse(i)?; - i.expect_comma()?; - Ok(fill) - }).unwrap_or_default(); + let fill = input + .try(|i| -> Result<_, ParseError> { + let fill = FillRule::parse(i)?; + i.expect_comma()?; + Ok(fill) + }).unwrap_or_default(); let path = SVGPathData::parse(context, input)?; Ok(Path { fill, path }) } diff --git a/components/style/values/specified/border.rs b/components/style/values/specified/border.rs index 0713ed99eb94..7a681c2ef2cf 100644 --- a/components/style/values/specified/border.rs +++ b/components/style/values/specified/border.rs @@ -189,8 +189,7 @@ impl Parse for BorderSpacing { /// A single border-image-repeat keyword. #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToCss)] +#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss)] pub enum BorderImageRepeatKeyword { Stretch, Repeat, @@ -201,8 +200,7 @@ pub enum BorderImageRepeatKeyword { /// The specified value for the `border-image-repeat` property. /// /// https://drafts.csswg.org/css-backgrounds/#the-border-image-repeat -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct BorderImageRepeat(pub BorderImageRepeatKeyword, pub BorderImageRepeatKeyword); impl ToCss for BorderImageRepeat { diff --git a/components/style/values/specified/box.rs b/components/style/values/specified/box.rs index 9554d76890c2..e23ec4a745a9 100644 --- a/components/style/values/specified/box.rs +++ b/components/style/values/specified/box.rs @@ -21,26 +21,23 @@ use values::specified::length::{LengthOrPercentage, NonNegativeLength}; fn in_ua_or_chrome_sheet(context: &ParserContext) -> bool { use stylesheets::Origin; - context.stylesheet_origin == Origin::UserAgent || - context.chrome_rules_enabled() + context.stylesheet_origin == Origin::UserAgent || context.chrome_rules_enabled() } #[cfg(feature = "gecko")] fn moz_display_values_enabled(context: &ParserContext) -> bool { use gecko_bindings::structs; in_ua_or_chrome_sheet(context) || - unsafe { - structs::StaticPrefs_sVarCache_layout_css_xul_display_values_content_enabled - } + unsafe { structs::StaticPrefs_sVarCache_layout_css_xul_display_values_content_enabled } } #[cfg(feature = "gecko")] fn moz_box_display_values_enabled(context: &ParserContext) -> bool { use gecko_bindings::structs; in_ua_or_chrome_sheet(context) || - unsafe { - structs::StaticPrefs_sVarCache_layout_css_xul_box_display_values_content_enabled - } + unsafe { + structs::StaticPrefs_sVarCache_layout_css_xul_box_display_values_content_enabled + } } /// Defines an element’s display type, which consists of @@ -57,8 +54,20 @@ fn moz_box_display_values_enabled(context: &ParserContext) -> bool { /// Also, when you change this from Gecko you may need to regenerate the /// C++-side bindings (see components/style/cbindgen.toml). #[allow(missing_docs)] -#[derive(Clone, Copy, Debug, Eq, FromPrimitive, Hash, MallocSizeOf, Parse, - PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + FromPrimitive, + Hash, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[repr(u8)] pub enum Display { @@ -200,7 +209,10 @@ impl Display { pub fn is_ruby_type(&self) -> bool { matches!( *self, - Display::Ruby | Display::RubyBase | Display::RubyText | Display::RubyBaseContainer | + Display::Ruby | + Display::RubyBase | + Display::RubyText | + Display::RubyBaseContainer | Display::RubyTextContainer ) } @@ -346,8 +358,7 @@ impl AnimationIterationCount { } /// A value for the `animation-name` property. -#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] #[value_info(other_values = "none")] pub struct AnimationName(pub Option); @@ -391,8 +402,18 @@ impl Parse for AnimationName { #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] pub enum ScrollSnapType { None, Mandatory, @@ -401,8 +422,18 @@ pub enum ScrollSnapType { #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] pub enum OverscrollBehavior { Auto, Contain, @@ -411,15 +442,24 @@ pub enum OverscrollBehavior { #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] pub enum OverflowClipBox { PaddingBox, ContentBox, } -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] /// Provides a rendering hint to the user agent, /// stating what kinds of changes the author expects /// to perform on the element @@ -497,11 +537,11 @@ fn change_bits_for_maybe_property(ident: &str, context: &ParserContext) -> WillC }; match id.as_shorthand() { - Ok(shorthand) => { - shorthand.longhands().fold(WillChangeBits::empty(), |flags, p| { + Ok(shorthand) => shorthand + .longhands() + .fold(WillChangeBits::empty(), |flags, p| { flags | change_bits_for_longhand(p) - }) - } + }), Err(PropertyDeclarationId::Longhand(longhand)) => change_bits_for_longhand(longhand), Err(PropertyDeclarationId::Custom(..)) => WillChangeBits::empty(), } @@ -581,9 +621,8 @@ impl ToCss for TouchAction { TouchAction::TOUCH_ACTION_NONE => dest.write_str("none"), TouchAction::TOUCH_ACTION_AUTO => dest.write_str("auto"), TouchAction::TOUCH_ACTION_MANIPULATION => dest.write_str("manipulation"), - _ if self.contains( - TouchAction::TOUCH_ACTION_PAN_X | TouchAction::TOUCH_ACTION_PAN_Y, - ) => + _ if self + .contains(TouchAction::TOUCH_ACTION_PAN_X | TouchAction::TOUCH_ACTION_PAN_Y) => { dest.write_str("pan-x pan-y") }, @@ -756,8 +795,7 @@ impl Parse for Perspective { return Ok(GenericPerspective::None); } Ok(GenericPerspective::Length(NonNegativeLength::parse( - context, - input, + context, input, )?)) } } @@ -789,7 +827,7 @@ impl ToCss for TransitionProperty { TransitionProperty::Custom(ref name) => { dest.write_str("--")?; serialize_atom_name(name, dest) - } + }, TransitionProperty::Unsupported(ref i) => i.to_css(dest), } } @@ -805,21 +843,21 @@ impl Parse for TransitionProperty { let id = match PropertyId::parse_ignoring_rule_type(&ident, context) { Ok(id) => id, - Err(..) => return Ok(TransitionProperty::Unsupported( - CustomIdent::from_ident(location, ident, &["none"])?, - )), + Err(..) => { + return Ok(TransitionProperty::Unsupported(CustomIdent::from_ident( + location, + ident, + &["none"], + )?)) + }, }; Ok(match id.as_shorthand() { Ok(s) => TransitionProperty::Shorthand(s), - Err(longhand_or_custom) => { - match longhand_or_custom { - PropertyDeclarationId::Longhand(id) => TransitionProperty::Longhand(id), - PropertyDeclarationId::Custom(custom) => { - TransitionProperty::Custom(custom.clone()) - } - } - } + Err(longhand_or_custom) => match longhand_or_custom { + PropertyDeclarationId::Longhand(id) => TransitionProperty::Longhand(id), + PropertyDeclarationId::Custom(custom) => TransitionProperty::Custom(custom.clone()), + }, }) } } @@ -846,19 +884,19 @@ impl TransitionProperty { Ok(match *self { TransitionProperty::Shorthand(ShorthandId::All) => { ::gecko_bindings::structs::nsCSSPropertyID::eCSSPropertyExtra_all_properties - } + }, TransitionProperty::Shorthand(ref id) => id.to_nscsspropertyid(), TransitionProperty::Longhand(ref id) => id.to_nscsspropertyid(), - TransitionProperty::Custom(..) | - TransitionProperty::Unsupported(..) => return Err(()), + TransitionProperty::Custom(..) | TransitionProperty::Unsupported(..) => return Err(()), }) } } #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToCss)] +#[derive( + Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, +)] /// https://drafts.csswg.org/css-box/#propdef-float pub enum Float { Left, @@ -866,13 +904,14 @@ pub enum Float { None, // https://drafts.csswg.org/css-logical-props/#float-clear InlineStart, - InlineEnd + InlineEnd, } #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToCss)] +#[derive( + Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, +)] /// https://drafts.csswg.org/css-box/#propdef-clear pub enum Clear { None, @@ -881,14 +920,15 @@ pub enum Clear { Both, // https://drafts.csswg.org/css-logical-props/#float-clear InlineStart, - InlineEnd + InlineEnd, } /// https://drafts.csswg.org/css-ui/#propdef-resize #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToCss)] +#[derive( + Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, +)] pub enum Resize { None, Both, @@ -906,8 +946,19 @@ pub enum Resize { /// NOTE(emilio): When changing this you may want to regenerate the C++ bindings /// (see components/style/cbindgen.toml) #[allow(missing_docs)] -#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToCss, ToComputedValue)] +#[derive( + Clone, + Copy, + Debug, + Eq, + Hash, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToCss, + ToComputedValue, +)] #[repr(u8)] pub enum Appearance { /// No appearance at all. diff --git a/components/style/values/specified/color.rs b/components/style/values/specified/color.rs index c05f0ddce0ef..cce8f3818061 100644 --- a/components/style/values/specified/color.rs +++ b/components/style/values/specified/color.rs @@ -89,11 +89,11 @@ impl<'a, 'b: 'a, 'i: 'a> ::cssparser::ColorComponentParser<'i> for ColorComponen }; Ok(AngleOrNumber::Angle { degrees }) - } + }, Token::Number { value, .. } => Ok(AngleOrNumber::Number { value }), Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { input.parse_nested_block(|i| CalcNode::parse_angle_or_number(self.0, i)) - } + }, t => return Err(location.new_unexpected_token_error(t)), } } @@ -120,10 +120,10 @@ impl<'a, 'b: 'a, 'i: 'a> ::cssparser::ColorComponentParser<'i> for ColorComponen Token::Number { value, .. } => Ok(NumberOrPercentage::Number { value }), Token::Percentage { unit_value, .. } => { Ok(NumberOrPercentage::Percentage { unit_value }) - } + }, Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { input.parse_nested_block(|i| CalcNode::parse_number_or_percentage(self.0, i)) - } + }, t => return Err(location.new_unexpected_token_error(t)), } } @@ -169,10 +169,10 @@ impl Parse for Color { Err(e.location.new_custom_error(StyleParseErrorKind::ValueError( ValueParseErrorKind::InvalidColor(t), ))) - } + }, _ => Err(e), } - } + }, } } } @@ -276,10 +276,10 @@ impl Color { } return parse_hash_color(ident.as_bytes()) .map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); - } + }, ref t => { return Err(location.new_unexpected_token_error(t.clone())); - } + }, }; if value < 0 { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); @@ -359,11 +359,11 @@ impl Color { Keyword::MozVisitedhyperlinktext => pres_context.mVisitedLinkColor, }) }) - } + }, #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => { _context.map(|context| ComputedColor::rgba(context.device().body_text_color())) - } + }, } } } diff --git a/components/style/values/specified/column.rs b/components/style/values/specified/column.rs index d065835423d6..4cd8ad0777f0 100644 --- a/components/style/values/specified/column.rs +++ b/components/style/values/specified/column.rs @@ -22,8 +22,7 @@ impl Parse for ColumnCount { return Ok(GenericColumnCount::Auto); } Ok(GenericColumnCount::Integer(PositiveInteger::parse( - context, - input, + context, input, )?)) } } diff --git a/components/style/values/specified/counters.rs b/components/style/values/specified/counters.rs index ea369f9dec75..ce7e3991227b 100644 --- a/components/style/values/specified/counters.rs +++ b/components/style/values/specified/counters.rs @@ -93,8 +93,7 @@ impl Content { .try(|input| { input.expect_comma()?; ListStyleType::parse(input) - }) - .unwrap_or(ListStyleType::Decimal) + }).unwrap_or(ListStyleType::Decimal) } #[cfg(feature = "gecko")] @@ -103,8 +102,7 @@ impl Content { .try(|input| { input.expect_comma()?; CounterStyleOrNone::parse(context, input) - }) - .unwrap_or(CounterStyleOrNone::decimal()) + }).unwrap_or(CounterStyleOrNone::decimal()) } } diff --git a/components/style/values/specified/effects.rs b/components/style/values/specified/effects.rs index c3304b05af0a..861414ca756d 100644 --- a/components/style/values/specified/effects.rs +++ b/components/style/values/specified/effects.rs @@ -118,9 +118,9 @@ impl Parse for BoxShadow { let value = input.try::<_, _, ParseError>(|i| { let horizontal = Length::parse(context, i)?; let vertical = Length::parse(context, i)?; - let (blur, spread) = match i.try::<_, _, ParseError>(|i| { - Length::parse_non_negative(context, i) - }) { + let (blur, spread) = match i + .try::<_, _, ParseError>(|i| Length::parse_non_negative(context, i)) + { Ok(blur) => { let spread = i.try(|i| Length::parse(context, i)).ok(); (Some(blur.into()), spread) @@ -143,7 +143,8 @@ impl Parse for BoxShadow { break; } - let lengths = lengths.ok_or(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))?; + let lengths = + lengths.ok_or(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))?; Ok(BoxShadow { base: SimpleShadow { color: color, @@ -164,7 +165,8 @@ impl ToComputedValue for BoxShadow { fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { ComputedBoxShadow { base: self.base.to_computed_value(context), - spread: self.spread + spread: self + .spread .as_ref() .unwrap_or(&Length::zero()) .to_computed_value(context), @@ -271,13 +273,15 @@ impl ToComputedValue for SimpleShadow { #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { ComputedSimpleShadow { - color: self.color + color: self + .color .as_ref() .unwrap_or(&Color::currentcolor()) .to_computed_value(context), horizontal: self.horizontal.to_computed_value(context), vertical: self.vertical.to_computed_value(context), - blur: self.blur + blur: self + .blur .as_ref() .unwrap_or(&NonNegativeLength::zero()) .to_computed_value(context), diff --git a/components/style/values/specified/font.rs b/components/style/values/specified/font.rs index 8d8355821e8c..d9cf921bca55 100644 --- a/components/style/values/specified/font.rs +++ b/components/style/values/specified/font.rs @@ -148,9 +148,9 @@ impl ToComputedValue for FontWeight { #[inline] fn from_computed_value(computed: &computed::FontWeight) -> Self { - FontWeight::Absolute(AbsoluteFontWeight::Weight( - Number::from_computed_value(&computed.0) - )) + FontWeight::Absolute(AbsoluteFontWeight::Weight(Number::from_computed_value( + &computed.0, + ))) } } @@ -174,9 +174,7 @@ impl AbsoluteFontWeight { pub fn compute(&self) -> computed::FontWeight { match *self { AbsoluteFontWeight::Weight(weight) => { - computed::FontWeight( - weight.get().max(MIN_FONT_WEIGHT).min(MAX_FONT_WEIGHT) - ) + computed::FontWeight(weight.get().max(MIN_FONT_WEIGHT).min(MAX_FONT_WEIGHT)) }, AbsoluteFontWeight::Normal => computed::FontWeight::normal(), AbsoluteFontWeight::Bold => computed::FontWeight::bold(), @@ -194,12 +192,11 @@ impl Parse for AbsoluteFontWeight { // seem worth it just for a single property with such a weird range, // so we do the clamping here manually. if !number.was_calc() && - (number.get() < MIN_FONT_WEIGHT || number.get() > MAX_FONT_WEIGHT) { - return Err(input.new_custom_error( - StyleParseErrorKind::UnspecifiedError - )) + (number.get() < MIN_FONT_WEIGHT || number.get() > MAX_FONT_WEIGHT) + { + return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } - return Ok(AbsoluteFontWeight::Weight(number)) + return Ok(AbsoluteFontWeight::Weight(number)); } Ok(try_match_ident_ignore_ascii_case! { input, @@ -228,7 +225,7 @@ impl ToCss for SpecifiedFontStyle { angle.to_css(dest)?; } Ok(()) - } + }, } } } @@ -260,7 +257,7 @@ impl ToComputedValue for SpecifiedFontStyle { generics::FontStyle::Italic => generics::FontStyle::Italic, generics::FontStyle::Oblique(ref angle) => { generics::FontStyle::Oblique(FontStyleAngle(Self::compute_angle(angle))) - } + }, } } @@ -270,12 +267,11 @@ impl ToComputedValue for SpecifiedFontStyle { generics::FontStyle::Italic => generics::FontStyle::Italic, generics::FontStyle::Oblique(ref angle) => { generics::FontStyle::Oblique(Angle::from_computed_value(&angle.0)) - } + }, } } } - /// The default angle for `font-style: oblique`. /// /// NOTE(emilio): As of right now this diverges from the spec, which specifies @@ -299,9 +295,10 @@ impl SpecifiedFontStyle { /// Gets a clamped angle from a specified Angle. pub fn compute_angle(angle: &Angle) -> ComputedAngle { ComputedAngle::Deg( - angle.degrees() + angle + .degrees() .max(FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES) - .min(FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES) + .min(FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES), ) } @@ -319,11 +316,9 @@ impl SpecifiedFontStyle { if degrees < FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES || degrees > FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES { - return Err(input.new_custom_error( - StyleParseErrorKind::UnspecifiedError - )); + return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } - return Ok(angle) + return Ok(angle); } /// The default angle for `font-style: oblique`. @@ -336,8 +331,7 @@ impl SpecifiedFontStyle { } /// The specified value of the `font-style` property. -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToCss)] +#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)] #[allow(missing_docs)] pub enum FontStyle { Specified(SpecifiedFontStyle), @@ -375,7 +369,9 @@ impl Parse for FontStyle { context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result> { - Ok(FontStyle::Specified(SpecifiedFontStyle::parse(context, input)?)) + Ok(FontStyle::Specified(SpecifiedFontStyle::parse( + context, input, + )?)) } } @@ -383,8 +379,7 @@ impl Parse for FontStyle { /// /// https://drafts.csswg.org/css-fonts-4/#font-stretch-prop #[allow(missing_docs)] -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToCss)] +#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)] pub enum FontStretch { Stretch(Percentage), Keyword(FontStretchKeyword), @@ -393,8 +388,7 @@ pub enum FontStretch { } /// A keyword value for `font-stretch`. -#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, - ToCss)] +#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss)] #[allow(missing_docs)] pub enum FontStretchKeyword { Normal, @@ -497,9 +491,7 @@ impl ToComputedValue for FontStretch { FontStretch::Stretch(ref percentage) => { computed::FontStretch(NonNegative(percentage.to_computed_value(context))) }, - FontStretch::Keyword(ref kw) => { - computed::FontStretch(NonNegative(kw.compute())) - }, + FontStretch::Keyword(ref kw) => computed::FontStretch(NonNegative(kw.compute())), FontStretch::System(_) => self.compute_system(context), } } @@ -690,8 +682,7 @@ impl Parse for FontSizeAdjust { } Ok(FontSizeAdjust::Number(Number::parse_non_negative( - context, - input, + context, input, )?)) } } @@ -906,10 +897,11 @@ impl FontSize { // new ones. // // This is enough of an edge case to not really matter. - let abs = calc.to_computed_value_zoomed( - context, - FontBaseSize::InheritedStyleButStripEmUnits, - ).length_component(); + let abs = calc + .to_computed_value_zoomed( + context, + FontBaseSize::InheritedStyleButStripEmUnits, + ).length_component(); info = parent.keyword_info.map(|i| i.compose(ratio, abs.into())); } @@ -1939,8 +1931,7 @@ impl Parse for FontFeatureSettings { } } -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] /// Whether user agents are allowed to synthesize bold or oblique font faces /// when a font family lacks bold or italic faces pub struct FontSynthesis { @@ -2217,8 +2208,9 @@ impl Parse for VariationValue { } } -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] /// text-zoom. Enable if true, disable if false pub struct XTextZoom(#[css(skip)] pub bool); @@ -2235,8 +2227,7 @@ impl Parse for XTextZoom { } } -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] /// Internal property that reflects the lang attribute pub struct XLang(#[css(skip)] pub Atom); @@ -2324,8 +2315,7 @@ impl Parse for MozScriptLevel { } #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] -#[derive(Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToComputedValue, - ToCss)] +#[derive(Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] /// Specifies the multiplier to be used to adjust font size /// due to changes in scriptlevel. /// diff --git a/components/style/values/specified/grid.rs b/components/style/values/specified/grid.rs index 830cccaf2e24..ad95264c5958 100644 --- a/components/style/values/specified/grid.rs +++ b/components/style/values/specified/grid.rs @@ -22,7 +22,8 @@ pub fn parse_flex<'i, 't>(input: &mut Parser<'i, 't>) -> Result + } + if unit.eq_ignore_ascii_case("fr") && value.is_sign_positive() => { Ok(value) }, @@ -76,7 +77,8 @@ impl Parse for TrackSize { } input.expect_function_matching("fit-content")?; - let lop = input.parse_nested_block(|i| LengthOrPercentage::parse_non_negative(context, i))?; + let lop = + input.parse_nested_block(|i| LengthOrPercentage::parse_non_negative(context, i))?; Ok(TrackSize::FitContent(lop)) } } @@ -175,7 +177,9 @@ impl TrackRepeat { } else { if values.is_empty() { // expecting at least one - return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); + return Err( + input.new_custom_error(StyleParseErrorKind::UnspecifiedError) + ); } names.push(current_names); // final `` @@ -217,9 +221,11 @@ impl Parse for TrackList { // assume that everything is . This flag is useful when we encounter let mut atleast_one_not_fixed = false; loop { - current_names.extend_from_slice(&mut input - .try(parse_line_names) - .unwrap_or(vec![].into_boxed_slice())); + current_names.extend_from_slice( + &mut input + .try(parse_line_names) + .unwrap_or(vec![].into_boxed_slice()), + ); if let Ok(track_size) = input.try(|i| TrackSize::parse(context, i)) { if !track_size.is_fixed() { atleast_one_not_fixed = true; @@ -244,13 +250,17 @@ impl Parse for TrackList { atleast_one_not_fixed = true; if auto_repeat.is_some() { // only - return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); + return Err( + input.new_custom_error(StyleParseErrorKind::UnspecifiedError) + ); } }, RepeatType::Auto => { if auto_repeat.is_some() || atleast_one_not_fixed { // We've either seen earlier, or there's at least one non-fixed value - return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); + return Err( + input.new_custom_error(StyleParseErrorKind::UnspecifiedError) + ); } list_type = TrackListType::Auto(values.len() as u16 + auto_offset); @@ -342,7 +352,8 @@ impl ToComputedValue for TrackList { list_type: self.list_type.to_computed_value(context), values: values, line_names: line_names.into_boxed_slice(), - auto_repeat: self.auto_repeat + auto_repeat: self + .auto_repeat .clone() .map(|repeat| repeat.to_computed_value(context)), } diff --git a/components/style/values/specified/image.rs b/components/style/values/specified/image.rs index 64d24573f4a7..1c0a613e488a 100644 --- a/components/style/values/specified/image.rs +++ b/components/style/values/specified/image.rs @@ -55,19 +55,19 @@ impl SpecifiedValueInfo for Gradient { fn collect_completion_keywords(f: KeywordsCollectFn) { // This list here should keep sync with that in Gradient::parse. f(&[ - "linear-gradient", - "-webkit-linear-gradient", - "-moz-linear-gradient", - "repeating-linear-gradient", - "-webkit-repeating-linear-gradient", - "-moz-repeating-linear-gradient", - "radial-gradient", - "-webkit-radial-gradient", - "-moz-radial-gradient", - "repeating-radial-gradient", - "-webkit-repeating-radial-gradient", - "-moz-repeating-radial-gradient", - "-webkit-gradient", + "linear-gradient", + "-webkit-linear-gradient", + "-moz-linear-gradient", + "repeating-linear-gradient", + "-webkit-repeating-linear-gradient", + "-moz-repeating-linear-gradient", + "radial-gradient", + "-webkit-radial-gradient", + "-moz-radial-gradient", + "repeating-radial-gradient", + "-webkit-repeating-radial-gradient", + "-moz-repeating-radial-gradient", + "-webkit-gradient", ]); } } @@ -239,9 +239,9 @@ impl Parse for Gradient { #[cfg(feature = "gecko")] { use gecko_bindings::structs; - if compat_mode == CompatMode::Moz && !unsafe { - structs::StaticPrefs_sVarCache_layout_css_prefixes_gradients - } { + if compat_mode == CompatMode::Moz && + !unsafe { structs::StaticPrefs_sVarCache_layout_css_prefixes_gradients } + { return Err(input.new_custom_error(StyleParseErrorKind::UnexpectedFunction(func))); } } @@ -760,9 +760,9 @@ impl LineDirection { // There is no `to` keyword in webkit prefixed syntax. If it's consumed, // parsing should throw an error. CompatMode::WebKit if to_ident.is_ok() => { - return Err(i.new_custom_error(SelectorParseErrorKind::UnexpectedIdent( - "to".into(), - ))) + return Err( + i.new_custom_error(SelectorParseErrorKind::UnexpectedIdent("to".into())) + ) }, _ => {}, } @@ -969,8 +969,7 @@ impl Parse for PaintWorklet { .try(|input| { input.expect_comma()?; input.parse_comma_separated(|input| SpecifiedValue::parse(input)) - }) - .unwrap_or(vec![]); + }).unwrap_or(vec![]); Ok(PaintWorklet { name, arguments }) }) } diff --git a/components/style/values/specified/length.rs b/components/style/values/specified/length.rs index b6fe9bc23463..1b4efc4f00d8 100644 --- a/components/style/values/specified/length.rs +++ b/components/style/values/specified/length.rs @@ -566,14 +566,16 @@ impl Length { match *token { Token::Dimension { value, ref unit, .. - } if num_context.is_ok(context.parsing_mode, value) => + } + if num_context.is_ok(context.parsing_mode, value) => { return NoCalcLength::parse_dimension(context, value, unit) .map(Length::NoCalc) .map_err(|()| location.new_unexpected_token_error(token.clone())) }, Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => { - if value != 0. && !context.parsing_mode.allows_unitless_lengths() && + if value != 0. && + !context.parsing_mode.allows_unitless_lengths() && !allow_quirks.allowed(context.quirks_mode) { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); @@ -753,7 +755,8 @@ impl LengthOrPercentage { match *token { Token::Dimension { value, ref unit, .. - } if num_context.is_ok(context.parsing_mode, value) => + } + if num_context.is_ok(context.parsing_mode, value) => { return NoCalcLength::parse_dimension(context, value, unit) .map(LengthOrPercentage::Length) @@ -767,7 +770,8 @@ impl LengthOrPercentage { ))) }, Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => { - if value != 0. && !context.parsing_mode.allows_unitless_lengths() && + if value != 0. && + !context.parsing_mode.allows_unitless_lengths() && !allow_quirks.allowed(context.quirks_mode) { return Err(location.new_unexpected_token_error(token.clone())); @@ -780,8 +784,9 @@ impl LengthOrPercentage { } } - let calc = input - .parse_nested_block(|i| CalcNode::parse_length_or_percentage(context, i, num_context))?; + let calc = input.parse_nested_block(|i| { + CalcNode::parse_length_or_percentage(context, i, num_context) + })?; Ok(LengthOrPercentage::Calc(Box::new(calc))) } @@ -871,7 +876,8 @@ impl LengthOrPercentageOrAuto { match *token { Token::Dimension { value, ref unit, .. - } if num_context.is_ok(context.parsing_mode, value) => + } + if num_context.is_ok(context.parsing_mode, value) => { return NoCalcLength::parse_dimension(context, value, unit) .map(LengthOrPercentageOrAuto::Length) @@ -885,7 +891,8 @@ impl LengthOrPercentageOrAuto { ))) }, Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => { - if value != 0. && !context.parsing_mode.allows_unitless_lengths() && + if value != 0. && + !context.parsing_mode.allows_unitless_lengths() && !allow_quirks.allowed(context.quirks_mode) { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); @@ -902,8 +909,9 @@ impl LengthOrPercentageOrAuto { } } - let calc = input - .parse_nested_block(|i| CalcNode::parse_length_or_percentage(context, i, num_context))?; + let calc = input.parse_nested_block(|i| { + CalcNode::parse_length_or_percentage(context, i, num_context) + })?; Ok(LengthOrPercentageOrAuto::Calc(Box::new(calc))) } @@ -998,8 +1006,7 @@ impl Parse for NonNegativeLengthOrPercentageOrAuto { input: &mut Parser<'i, 't>, ) -> Result> { Ok(NonNegative(LengthOrPercentageOrAuto::parse_non_negative( - context, - input, + context, input, )?)) } } @@ -1028,7 +1035,8 @@ impl LengthOrPercentageOrNone { match *token { Token::Dimension { value, ref unit, .. - } if num_context.is_ok(context.parsing_mode, value) => + } + if num_context.is_ok(context.parsing_mode, value) => { return NoCalcLength::parse_dimension(context, value, unit) .map(LengthOrPercentageOrNone::Length) @@ -1042,7 +1050,8 @@ impl LengthOrPercentageOrNone { ))) }, Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => { - if value != 0. && !context.parsing_mode.allows_unitless_lengths() && + if value != 0. && + !context.parsing_mode.allows_unitless_lengths() && !allow_quirks.allowed(context.quirks_mode) { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); @@ -1059,8 +1068,9 @@ impl LengthOrPercentageOrNone { } } - let calc = input - .parse_nested_block(|i| CalcNode::parse_length_or_percentage(context, i, num_context))?; + let calc = input.parse_nested_block(|i| { + CalcNode::parse_length_or_percentage(context, i, num_context) + })?; Ok(LengthOrPercentageOrNone::Calc(Box::new(calc))) } diff --git a/components/style/values/specified/list.rs b/components/style/values/specified/list.rs index ae61bb1ae9cb..f1fba44b0802 100644 --- a/components/style/values/specified/list.rs +++ b/components/style/values/specified/list.rs @@ -15,8 +15,7 @@ use values::generics::CounterStyleOrNone; /// Specified and computed `list-style-type` property. #[cfg(feature = "gecko")] -#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub enum ListStyleType { /// | none CounterStyle(CounterStyleOrNone), @@ -79,8 +78,7 @@ impl Parse for ListStyleType { /// FIXME(emilio): It's a shame that this allocates all the time it's computed, /// probably should just be refcounted. /// FIXME This can probably derive ToCss. -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct Quotes(#[css(if_empty = "none")] pub Box<[(Box, Box)]>); impl ToCss for Quotes { diff --git a/components/style/values/specified/mod.rs b/components/style/values/specified/mod.rs index 6a395c21e58f..b8c2cd01fe95 100644 --- a/components/style/values/specified/mod.rs +++ b/components/style/values/specified/mod.rs @@ -151,8 +151,20 @@ fn parse_number_with_clamping_mode<'i, 't>( // FIXME(emilio): Should move to border.rs #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Ord, Parse, PartialEq, - PartialOrd, SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + MallocSizeOf, + Ord, + Parse, + PartialEq, + PartialOrd, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] pub enum BorderStyle { None = -1, Solid = 6, @@ -330,8 +342,7 @@ impl Parse for GreaterThanOrEqualToOneNumber { /// /// FIXME(emilio): Should probably use Either. #[allow(missing_docs)] -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToCss)] +#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)] pub enum NumberOrPercentage { Percentage(Percentage), Number(Number), @@ -369,8 +380,7 @@ impl Parse for NumberOrPercentage { } #[allow(missing_docs)] -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd, - SpecifiedValueInfo, ToCss)] +#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd, SpecifiedValueInfo, ToCss)] pub struct Opacity(Number); impl Parse for Opacity { @@ -630,13 +640,16 @@ impl ToComputedValue for ClipRect { fn to_computed_value(&self, context: &Context) -> super::computed::ClipRect { super::computed::ClipRect { top: self.top.as_ref().map(|top| top.to_computed_value(context)), - right: self.right + right: self + .right .as_ref() .map(|right| right.to_computed_value(context)), - bottom: self.bottom + bottom: self + .bottom .as_ref() .map(|bottom| bottom.to_computed_value(context)), - left: self.left + left: self + .left .as_ref() .map(|left| left.to_computed_value(context)), } @@ -760,8 +773,7 @@ impl AllowQuirks { /// An attr(...) rule /// /// `[namespace? `|`]? ident` -#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] #[css(function)] pub struct Attr { /// Optional namespace prefix and URL. @@ -814,7 +826,10 @@ impl Attr { let prefix = Prefix::from(ns.as_ref()); let ns = match get_namespace_for_prefix(&prefix, context) { Some(ns) => ns, - None => return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)), + None => { + return Err(location + .new_custom_error(StyleParseErrorKind::UnspecifiedError)) + }, }; Some((prefix, ns)) } else { diff --git a/components/style/values/specified/motion.rs b/components/style/values/specified/motion.rs index 762c1dcfdd5f..b591d43a2bbb 100644 --- a/components/style/values/specified/motion.rs +++ b/components/style/values/specified/motion.rs @@ -12,8 +12,18 @@ use values::specified::SVGPathData; /// The offset-path value. /// /// https://drafts.fxtf.org/motion-1/#offset-path-property -#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub enum OffsetPath { // We could merge SVGPathData into ShapeSource, so we could reuse them. However, // we don't want to support other value for offset-path, so use SVGPathData only for now. @@ -37,7 +47,7 @@ impl OffsetPath { impl Parse for OffsetPath { fn parse<'i, 't>( context: &ParserContext, - input: &mut Parser<'i, 't> + input: &mut Parser<'i, 't>, ) -> Result> { // Parse none. if input.try(|i| i.expect_ident_matching("none")).is_ok() { diff --git a/components/style/values/specified/outline.rs b/components/style/values/specified/outline.rs index c3357f87ec22..afe74dc39f39 100644 --- a/components/style/values/specified/outline.rs +++ b/components/style/values/specified/outline.rs @@ -10,8 +10,19 @@ use selectors::parser::SelectorParseErrorKind; use style_traits::ParseError; use values::specified::BorderStyle; -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Ord, PartialEq, PartialOrd, - SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + MallocSizeOf, + Ord, + PartialEq, + PartialOrd, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] /// pub enum OutlineStyle { /// auto diff --git a/components/style/values/specified/position.rs b/components/style/values/specified/position.rs index fcfa07ae1d86..6117436695fd 100644 --- a/components/style/values/specified/position.rs +++ b/components/style/values/specified/position.rs @@ -45,8 +45,19 @@ pub enum PositionComponent { } /// A keyword for the X direction. -#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + Hash, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] #[allow(missing_docs)] pub enum X { Left, @@ -54,8 +65,19 @@ pub enum X { } /// A keyword for the Y direction. -#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + Hash, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] #[allow(missing_docs)] pub enum Y { Top, @@ -128,10 +150,12 @@ impl Position { } let y_keyword = Y::parse(input)?; let lop_and_x_pos: Result<_, ParseError> = input.try(|i| { - let y_lop = i.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) + let y_lop = i + .try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) .ok(); if let Ok(x_keyword) = i.try(X::parse) { - let x_lop = i.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) + let x_lop = i + .try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) .ok(); let x_pos = PositionComponent::Side(x_keyword, x_lop); return Ok((y_lop, x_pos)); @@ -411,8 +435,9 @@ impl ToCss for LegacyPosition { } } -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] /// Auto-placement algorithm Option pub enum AutoFlow { /// The auto-placement algorithm places items by filling each row in turn, @@ -423,8 +448,9 @@ pub enum AutoFlow { Column, } -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] /// Controls how the auto-placement algorithm works /// specifying exactly how auto-placed items get flowed into the grid pub struct GridAutoFlow { @@ -630,8 +656,7 @@ impl Parse for TemplateAreas { } /// Arc type for `Arc` -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct TemplateAreasArc(#[ignore_malloc_size_of = "Arc"] pub Arc); impl Parse for TemplateAreasArc { @@ -685,8 +710,12 @@ impl<'a> Iterator for TemplateAreasTokenizer<'a> { } fn is_name_code_point(c: char) -> bool { - c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '\u{80}' || c == '_' || - c >= '0' && c <= '9' || c == '-' + c >= 'A' && c <= 'Z' || + c >= 'a' && c <= 'z' || + c >= '\u{80}' || + c == '_' || + c >= '0' && c <= '9' || + c == '-' } /// This property specifies named grid areas. diff --git a/components/style/values/specified/resolution.rs b/components/style/values/specified/resolution.rs index 77a269c251b7..0878c7762728 100644 --- a/components/style/values/specified/resolution.rs +++ b/components/style/values/specified/resolution.rs @@ -32,8 +32,7 @@ impl Resolution { /// Convert this resolution value to dppx units. pub fn to_dppx(&self) -> CSSFloat { match *self { - Resolution::X(f) | - Resolution::Dppx(f) => f, + Resolution::X(f) | Resolution::Dppx(f) => f, _ => self.to_dpi() / 96.0, } } @@ -42,8 +41,7 @@ impl Resolution { pub fn to_dpi(&self) -> CSSFloat { match *self { Resolution::Dpi(f) => f, - Resolution::X(f) | - Resolution::Dppx(f) => f * 96.0, + Resolution::X(f) | Resolution::Dppx(f) => f * 96.0, Resolution::Dpcm(f) => f * 2.54, } } diff --git a/components/style/values/specified/source_size_list.rs b/components/style/values/specified/source_size_list.rs index 33078c064840..2d86d5a058f1 100644 --- a/components/style/values/specified/source_size_list.rs +++ b/components/style/values/specified/source_size_list.rs @@ -61,7 +61,8 @@ impl SourceSizeList { /// Evaluate this to get the final viewport length. pub fn evaluate(&self, device: &Device, quirks_mode: QuirksMode) -> Au { - let matching_source_size = self.source_sizes + let matching_source_size = self + .source_sizes .iter() .find(|source_size| source_size.condition.matches(device, quirks_mode)); diff --git a/components/style/values/specified/svg.rs b/components/style/values/specified/svg.rs index e55442d7da82..f91ac511af1e 100644 --- a/components/style/values/specified/svg.rs +++ b/components/style/values/specified/svg.rs @@ -173,8 +173,7 @@ const PAINT_ORDER_MASK: u8 = 0b11; /// /// Higher priority values, i.e. the values specified first, /// will be painted first (and may be covered by paintings of lower priority) -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct SVGPaintOrder(pub u8); impl SVGPaintOrder { @@ -281,8 +280,7 @@ impl ToCss for SVGPaintOrder { /// Specified MozContextProperties value. /// Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-context-properties) -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] pub struct MozContextProperties(pub CustomIdent); impl Parse for MozContextProperties { diff --git a/components/style/values/specified/svg_path.rs b/components/style/values/specified/svg_path.rs index 490343aa5ce4..f0973b545a56 100644 --- a/components/style/values/specified/svg_path.rs +++ b/components/style/values/specified/svg_path.rs @@ -16,12 +16,12 @@ use values::CSSFloat; use values::animated::{Animate, Procedure}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; - /// The SVG path data. /// /// https://www.w3.org/TR/SVG11/paths.html#PathData -#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, - ToComputedValue)] +#[derive( + Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, +)] pub struct SVGPathData(Box<[PathCommand]>); impl SVGPathData { @@ -46,7 +46,11 @@ impl SVGPathData { subpath_start: CoordPair::new(0.0, 0.0), pos: CoordPair::new(0.0, 0.0), }; - let result = self.0.iter().map(|seg| seg.normalize(&mut state)).collect::>(); + let result = self + .0 + .iter() + .map(|seg| seg.normalize(&mut state)) + .collect::>(); SVGPathData(result.into_boxed_slice()) } } @@ -55,7 +59,7 @@ impl ToCss for SVGPathData { #[inline] fn to_css(&self, dest: &mut CssWriter) -> fmt::Result where - W: fmt::Write + W: fmt::Write, { dest.write_char('"')?; { @@ -76,7 +80,7 @@ impl Parse for SVGPathData { // str::Char iterator to check each character. fn parse<'i, 't>( _context: &ParserContext, - input: &mut Parser<'i, 't> + input: &mut Parser<'i, 't>, ) -> Result> { let location = input.current_source_location(); let path_string = input.expect_string()?.as_ref(); @@ -103,7 +107,9 @@ impl Animate for SVGPathData { return Err(()); } - let result = self.normalize().0 + let result = self + .normalize() + .0 .iter() .zip(other.normalize().0.iter()) .map(|(a, b)| a.animate(&b, procedure)) @@ -117,7 +123,8 @@ impl ComputeSquaredDistance for SVGPathData { if self.0.len() != other.0.len() { return Err(()); } - self.normalize().0 + self.normalize() + .0 .iter() .zip(other.normalize().0.iter()) .map(|(this, other)| this.compute_squared_distance(&other)) @@ -131,8 +138,17 @@ impl ComputeSquaredDistance for SVGPathData { /// points of the Bézier curve in the spec. /// /// https://www.w3.org/TR/SVG11/paths.html#PathData -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedZero)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedZero, +)] #[allow(missing_docs)] #[repr(C, u8)] pub enum PathCommand { @@ -140,21 +156,43 @@ pub enum PathCommand { /// https://www.w3.org/TR/SVG/paths.html#__svg__SVGPathSeg__PATHSEG_UNKNOWN Unknown, /// The "moveto" command. - MoveTo { point: CoordPair, absolute: IsAbsolute }, + MoveTo { + point: CoordPair, + absolute: IsAbsolute, + }, /// The "lineto" command. - LineTo { point: CoordPair, absolute: IsAbsolute }, + LineTo { + point: CoordPair, + absolute: IsAbsolute, + }, /// The horizontal "lineto" command. HorizontalLineTo { x: CSSFloat, absolute: IsAbsolute }, /// The vertical "lineto" command. VerticalLineTo { y: CSSFloat, absolute: IsAbsolute }, /// The cubic Bézier curve command. - CurveTo { control1: CoordPair, control2: CoordPair, point: CoordPair, absolute: IsAbsolute }, + CurveTo { + control1: CoordPair, + control2: CoordPair, + point: CoordPair, + absolute: IsAbsolute, + }, /// The smooth curve command. - SmoothCurveTo { control2: CoordPair, point: CoordPair, absolute: IsAbsolute }, + SmoothCurveTo { + control2: CoordPair, + point: CoordPair, + absolute: IsAbsolute, + }, /// The quadratic Bézier curve command. - QuadBezierCurveTo { control1: CoordPair, point: CoordPair, absolute: IsAbsolute }, + QuadBezierCurveTo { + control1: CoordPair, + point: CoordPair, + absolute: IsAbsolute, + }, /// The smooth quadratic Bézier curve command. - SmoothQuadBezierCurveTo { point: CoordPair, absolute: IsAbsolute }, + SmoothQuadBezierCurveTo { + point: CoordPair, + absolute: IsAbsolute, + }, /// The elliptical arc curve command. EllipticalArc { rx: CSSFloat, @@ -165,7 +203,7 @@ pub enum PathCommand { #[animation(constant)] sweep_flag: ArcFlag, point: CoordPair, - absolute: IsAbsolute + absolute: IsAbsolute, }, /// The "closepath" command. ClosePath, @@ -191,74 +229,138 @@ impl PathCommand { state.pos = state.subpath_start; ClosePath }, - MoveTo { mut point, absolute } => { + MoveTo { + mut point, + absolute, + } => { if !absolute.is_yes() { point += state.pos; } state.pos = point; state.subpath_start = point; - MoveTo { point, absolute: IsAbsolute::Yes } + MoveTo { + point, + absolute: IsAbsolute::Yes, + } }, - LineTo { mut point, absolute } => { + LineTo { + mut point, + absolute, + } => { if !absolute.is_yes() { point += state.pos; } state.pos = point; - LineTo { point, absolute: IsAbsolute::Yes } + LineTo { + point, + absolute: IsAbsolute::Yes, + } }, HorizontalLineTo { mut x, absolute } => { if !absolute.is_yes() { x += state.pos.0; } state.pos.0 = x; - HorizontalLineTo { x, absolute: IsAbsolute::Yes } + HorizontalLineTo { + x, + absolute: IsAbsolute::Yes, + } }, VerticalLineTo { mut y, absolute } => { if !absolute.is_yes() { y += state.pos.1; } state.pos.1 = y; - VerticalLineTo { y, absolute: IsAbsolute::Yes } + VerticalLineTo { + y, + absolute: IsAbsolute::Yes, + } }, - CurveTo { mut control1, mut control2, mut point, absolute } => { + CurveTo { + mut control1, + mut control2, + mut point, + absolute, + } => { if !absolute.is_yes() { control1 += state.pos; control2 += state.pos; point += state.pos; } state.pos = point; - CurveTo { control1, control2, point, absolute: IsAbsolute::Yes } + CurveTo { + control1, + control2, + point, + absolute: IsAbsolute::Yes, + } }, - SmoothCurveTo { mut control2, mut point, absolute } => { + SmoothCurveTo { + mut control2, + mut point, + absolute, + } => { if !absolute.is_yes() { control2 += state.pos; point += state.pos; } state.pos = point; - SmoothCurveTo { control2, point, absolute: IsAbsolute::Yes } + SmoothCurveTo { + control2, + point, + absolute: IsAbsolute::Yes, + } }, - QuadBezierCurveTo { mut control1, mut point, absolute } => { + QuadBezierCurveTo { + mut control1, + mut point, + absolute, + } => { if !absolute.is_yes() { control1 += state.pos; point += state.pos; } state.pos = point; - QuadBezierCurveTo { control1, point, absolute: IsAbsolute::Yes } + QuadBezierCurveTo { + control1, + point, + absolute: IsAbsolute::Yes, + } }, - SmoothQuadBezierCurveTo { mut point, absolute } => { + SmoothQuadBezierCurveTo { + mut point, + absolute, + } => { if !absolute.is_yes() { point += state.pos; } state.pos = point; - SmoothQuadBezierCurveTo { point, absolute: IsAbsolute::Yes } + SmoothQuadBezierCurveTo { + point, + absolute: IsAbsolute::Yes, + } }, - EllipticalArc { rx, ry, angle, large_arc_flag, sweep_flag, mut point, absolute } => { + EllipticalArc { + rx, + ry, + angle, + large_arc_flag, + sweep_flag, + mut point, + absolute, + } => { if !absolute.is_yes() { point += state.pos; } state.pos = point; EllipticalArc { - rx, ry, angle, large_arc_flag, sweep_flag, point, absolute: IsAbsolute::Yes + rx, + ry, + angle, + large_arc_flag, + sweep_flag, + point, + absolute: IsAbsolute::Yes, } }, } @@ -268,7 +370,7 @@ impl PathCommand { impl ToCss for PathCommand { fn to_css(&self, dest: &mut CssWriter) -> fmt::Result where - W: fmt::Write + W: fmt::Write, { use self::PathCommand::*; match *self { @@ -278,13 +380,18 @@ impl ToCss for PathCommand { dest.write_char(if absolute.is_yes() { 'M' } else { 'm' })?; dest.write_char(' ')?; point.to_css(dest) - } + }, LineTo { point, absolute } => { dest.write_char(if absolute.is_yes() { 'L' } else { 'l' })?; dest.write_char(' ')?; point.to_css(dest) - } - CurveTo { control1, control2, point, absolute } => { + }, + CurveTo { + control1, + control2, + point, + absolute, + } => { dest.write_char(if absolute.is_yes() { 'C' } else { 'c' })?; dest.write_char(' ')?; control1.to_css(dest)?; @@ -293,14 +400,26 @@ impl ToCss for PathCommand { dest.write_char(' ')?; point.to_css(dest) }, - QuadBezierCurveTo { control1, point, absolute } => { + QuadBezierCurveTo { + control1, + point, + absolute, + } => { dest.write_char(if absolute.is_yes() { 'Q' } else { 'q' })?; dest.write_char(' ')?; control1.to_css(dest)?; dest.write_char(' ')?; point.to_css(dest) }, - EllipticalArc { rx, ry, angle, large_arc_flag, sweep_flag, point, absolute } => { + EllipticalArc { + rx, + ry, + angle, + large_arc_flag, + sweep_flag, + point, + absolute, + } => { dest.write_char(if absolute.is_yes() { 'A' } else { 'a' })?; dest.write_char(' ')?; rx.to_css(dest)?; @@ -325,7 +444,11 @@ impl ToCss for PathCommand { dest.write_char(' ')?; y.to_css(dest) }, - SmoothCurveTo { control2, point, absolute } => { + SmoothCurveTo { + control2, + point, + absolute, + } => { dest.write_char(if absolute.is_yes() { 'S' } else { 's' })?; dest.write_char(' ')?; control2.to_css(dest)?; @@ -343,8 +466,17 @@ impl ToCss for PathCommand { /// The path command absolute type. #[allow(missing_docs)] -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedZero)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedZero, +)] #[repr(u8)] pub enum IsAbsolute { Yes, @@ -360,8 +492,18 @@ impl IsAbsolute { } /// The path coord type. -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedZero, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedZero, + ToCss, +)] #[repr(C)] pub struct CoordPair(CSSFloat, CSSFloat); @@ -390,7 +532,7 @@ impl ToCss for ArcFlag { #[inline] fn to_css(&self, dest: &mut CssWriter) -> fmt::Result where - W: fmt::Write + W: fmt::Write, { (self.0 as i32).to_css(dest) } @@ -403,7 +545,6 @@ impl ComputeSquaredDistance for ArcFlag { } } - /// SVG Path parser. struct PathParser<'a> { chars: Peekable>>, @@ -508,12 +649,16 @@ impl<'a> PathParser<'a> { skip_wsp(&mut self.chars); let point = parse_coord(&mut self.chars)?; - let absolute = if command == b'M' { IsAbsolute::Yes } else { IsAbsolute::No }; - self.path.push(PathCommand::MoveTo { point, absolute } ); + let absolute = if command == b'M' { + IsAbsolute::Yes + } else { + IsAbsolute::No + }; + self.path.push(PathCommand::MoveTo { point, absolute }); // End of string or the next character is a possible new command. - if !skip_wsp(&mut self.chars) || - self.chars.peek().map_or(true, |c| c.is_ascii_alphabetic()) { + if !skip_wsp(&mut self.chars) || self.chars.peek().map_or(true, |c| c.is_ascii_alphabetic()) + { return Ok(()); } skip_comma_wsp(&mut self.chars); @@ -573,11 +718,9 @@ impl<'a> PathParser<'a> { /// Parse elliptical arc curve command. fn parse_elliptical_arc(&mut self, absolute: IsAbsolute) -> Result<(), ()> { // Parse a flag whose value is '0' or '1'; otherwise, return Err(()). - let parse_flag = |iter: &mut Peekable>>| { - match iter.next() { - Some(c) if c == b'0' || c == b'1' => Ok(ArcFlag(c == b'1')), - _ => Err(()), - } + let parse_flag = |iter: &mut Peekable>>| match iter.next() { + Some(c) if c == b'0' || c == b'1' => Ok(ArcFlag(c == b'1')), + _ => Err(()), }; parse_arguments!(self, absolute, EllipticalArc, [ rx => parse_number, @@ -590,7 +733,6 @@ impl<'a> PathParser<'a> { } } - /// Parse a pair of numbers into CoordPair. fn parse_coord(iter: &mut Peekable>>) -> Result { let x = parse_number(iter)?; @@ -608,8 +750,15 @@ fn parse_coord(iter: &mut Peekable>>) -> Result>>) -> Result { // 1. Check optional sign. - let sign = if iter.peek().map_or(false, |&sign| sign == b'+' || sign == b'-') { - if iter.next().unwrap() == b'-' { -1. } else { 1. } + let sign = if iter + .peek() + .map_or(false, |&sign| sign == b'+' || sign == b'-') + { + if iter.next().unwrap() == b'-' { + -1. + } else { + 1. + } } else { 1. }; @@ -623,8 +772,7 @@ fn parse_number(iter: &mut Peekable>>) -> Result>>) -> Result>>) -> Result` pres attr pub struct XSpan(#[css(skip)] pub i32); diff --git a/components/style/values/specified/text.rs b/components/style/values/specified/text.rs index ae01040e45f8..adeab96c984f 100644 --- a/components/style/values/specified/text.rs +++ b/components/style/values/specified/text.rs @@ -94,7 +94,10 @@ impl Parse for LineHeight { { Ok(GenericLineHeight::MozBlockHeight) }, - ident => Err(location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))), + ident => { + Err(location + .new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))) + }, } } } @@ -587,8 +590,7 @@ impl TextEmphasisKeywordValue { } /// Fill mode for the text-emphasis-style property -#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, - ToCss)] +#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss)] pub enum TextEmphasisFillMode { /// `filled` Filled, @@ -597,8 +599,7 @@ pub enum TextEmphasisFillMode { } /// Shape keyword for the text-emphasis-style property -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToCss)] +#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss)] pub enum TextEmphasisShapeKeyword { /// `dot` Dot, @@ -724,8 +725,18 @@ impl Parse for TextEmphasisStyle { } /// The allowed horizontal values for the `text-emphasis-position` property. -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] pub enum TextEmphasisHorizontalWritingModeValue { /// Draw marks over the text in horizontal writing mode. Over, @@ -734,8 +745,18 @@ pub enum TextEmphasisHorizontalWritingModeValue { } /// The allowed vertical values for the `text-emphasis-position` property. -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, - SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] pub enum TextEmphasisVerticalWritingModeValue { /// Draws marks to the right of the text in vertical writing mode. Right, @@ -744,8 +765,9 @@ pub enum TextEmphasisVerticalWritingModeValue { } /// Specified value of `text-emphasis-position` property. -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] pub struct TextEmphasisPosition( pub TextEmphasisHorizontalWritingModeValue, pub TextEmphasisVerticalWritingModeValue, @@ -846,8 +868,7 @@ impl Parse for MozTabSize { return Ok(GenericMozTabSize::Number(number)); } Ok(GenericMozTabSize::Length(NonNegativeLength::parse( - context, - input, + context, input, )?)) } } diff --git a/components/style/values/specified/time.rs b/components/style/values/specified/time.rs index 107c45b2d488..6895a918346e 100644 --- a/components/style/values/specified/time.rs +++ b/components/style/values/specified/time.rs @@ -92,7 +92,8 @@ impl Time { // ParsingMode::DEFAULT directly. Ok(&Token::Dimension { value, ref unit, .. - }) if clamping_mode.is_ok(ParsingMode::DEFAULT, value) => + }) + if clamping_mode.is_ok(ParsingMode::DEFAULT, value) => { return Time::parse_dimension(value, unit, /* from_calc = */ false) .map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); diff --git a/components/style/values/specified/ui.rs b/components/style/values/specified/ui.rs index e912c24b8080..7dc1e0fe1d3d 100644 --- a/components/style/values/specified/ui.rs +++ b/components/style/values/specified/ui.rs @@ -52,9 +52,8 @@ impl Parse for CursorKind { ) -> Result> { let location = input.current_source_location(); let ident = input.expect_ident()?; - CursorKind::from_css_keyword(&ident).map_err(|_| { - location.new_custom_error(StyleParseErrorKind::UnspecifiedError) - }) + CursorKind::from_css_keyword(&ident) + .map_err(|_| location.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } @@ -74,8 +73,7 @@ impl Parse for CursorImage { } /// Specified value of `-moz-force-broken-image-icon` -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, - ToComputedValue)] +#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)] pub struct MozForceBrokenImageIcon(pub bool); impl MozForceBrokenImageIcon {