From 337d48aa61bd705ea7bf162a6dc6cf49addb7cb8 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Tue, 3 Oct 2017 14:33:56 -0700 Subject: [PATCH 01/21] Add generic struct for transform --- components/style/values/generics/transform.rs | 105 +++++++++++++++++- 1 file changed, 104 insertions(+), 1 deletion(-) diff --git a/components/style/values/generics/transform.rs b/components/style/values/generics/transform.rs index 2902f24329e..475924921be 100644 --- a/components/style/values/generics/transform.rs +++ b/components/style/values/generics/transform.rs @@ -6,7 +6,7 @@ use std::fmt; use style_traits::ToCss; -use values::CSSFloat; +use values::{computed, specified, CSSFloat}; /// A generic 2D transformation matrix. #[allow(missing_docs)] @@ -137,3 +137,106 @@ impl TimingKeyword { } } } + +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "gecko", derive(MallocSizeOf))] +#[cfg_attr(feature = "servo", derive(HeapSizeOf))] +/// A single operation in the list of a `transform` value +pub enum TransformOperation { + /// Represents a 2D 2x3 matrix. + Matrix(Matrix), + /// Represents a 3D 4x4 matrix with percentage and length values. + /// For `moz-transform`. + PrefixedMatrix(Matrix), + /// Represents a 3D 4x4 matrix. + #[allow(missing_docs)] + Matrix3D { + m11: Number, m12: Number, m13: Number, m14: Number, + m21: Number, m22: Number, m23: Number, m24: Number, + m31: Number, m32: Number, m33: Number, m34: Number, + m41: Number, m42: Number, m43: Number, m44: Number, + }, + /// Represents a 3D 4x4 matrix with percentage and length values. + /// For `moz-transform`. + #[allow(missing_docs)] + PrefixedMatrix3D { + m11: Number, m12: Number, m13: Number, m14: Number, + m21: Number, m22: Number, m23: Number, m24: Number, + m31: Number, m32: Number, m33: Number, m34: Number, + m41: LoPoNumber, m42: LoPoNumber, m43: LengthOrNumber, m44: Number, + }, + /// A 2D skew. + /// + /// If the second angle is not provided it is assumed zero. + /// + /// Syntax can be skew(angle) or skew(angle, angle) + Skew(Angle, Option), + /// skewX(angle) + SkewX(Angle), + /// skewY(angle) + SkewY(Angle), + /// translate(x, y) or translate(x) + Translate(LengthOrPercentage, Option), + /// translateX(x) + TranslateX(LengthOrPercentage), + /// translateY(y) + TranslateY(LengthOrPercentage), + /// translateZ(z) + TranslateZ(Length), + /// translate3d(x, y, z) + Translate3D(LengthOrPercentage, LengthOrPercentage, Length), + /// A 2D scaling factor. + /// + /// `scale(2)` is parsed as `Scale(Number::new(2.0), None)` and is equivalent to + /// writing `scale(2, 2)` (`Scale(Number::new(2.0), Some(Number::new(2.0)))`). + /// + /// Negative values are allowed and flip the element. + /// + /// Syntax can be scale(factor) or scale(factor, factor) + Scale(Number, Option), + /// scaleX(factor) + ScaleX(Number), + /// scaleY(factor) + ScaleY(Number), + /// scaleZ(factor) + ScaleZ(Number), + /// scale3D(factorX, factorY, factorZ) + Scale3D(Number, Number, Number), + /// Describes a 2D Rotation. + /// + /// In a 3D scene `rotate(angle)` is equivalent to `rotateZ(angle)`. + Rotate(Angle), + /// Rotation in 3D space around the x-axis. + RotateX(Angle), + /// Rotation in 3D space around the y-axis. + RotateY(Angle), + /// Rotation in 3D space around the z-axis. + RotateZ(Angle), + /// Rotation in 3D space. + /// + /// Generalization of rotateX, rotateY and rotateZ. + Rotate3D(Number, Number, Number, Angle), + /// Specifies a perspective projection matrix. + /// + /// Part of CSS Transform Module Level 2 and defined at + /// [§ 13.1. 3D Transform Function](https://drafts.csswg.org/css-transforms-2/#funcdef-perspective). + /// + /// The value must be greater than or equal to zero. + Perspective(specified::Length), + /// A intermediate type for interpolation of mismatched transform lists. + #[allow(missing_docs)] + InterpolateMatrix { from_list: Transform>, + to_list: Transform>, + progress: computed::Percentage }, + /// A intermediate type for accumulation of mismatched transform lists. + #[allow(missing_docs)] + AccumulateMatrix { from_list: Transform>, + to_list: Transform>, + count: specified::Integer }, +} + +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "gecko", derive(MallocSizeOf))] +#[cfg_attr(feature = "servo", derive(HeapSizeOf))] +/// A value of the `transform` property +pub struct Transform(Vec); From dcefcc3c225e92c397fe04b42c75c94e94092397 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Tue, 3 Oct 2017 15:06:44 -0700 Subject: [PATCH 02/21] Add ToComputedValue and ToCss impls --- components/style/values/generics/transform.rs | 158 +++++++++++++++++- components/style_derive/to_computed_value.rs | 5 +- 2 files changed, 153 insertions(+), 10 deletions(-) diff --git a/components/style/values/generics/transform.rs b/components/style/values/generics/transform.rs index 475924921be..56d3643404d 100644 --- a/components/style/values/generics/transform.rs +++ b/components/style/values/generics/transform.rs @@ -6,7 +6,7 @@ use std::fmt; use style_traits::ToCss; -use values::{computed, specified, CSSFloat}; +use values::{computed, CSSFloat}; /// A generic 2D transformation matrix. #[allow(missing_docs)] @@ -141,8 +141,9 @@ impl TimingKeyword { #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] +#[derive(ToComputedValue)] /// A single operation in the list of a `transform` value -pub enum TransformOperation { +pub enum TransformOperation { /// Represents a 2D 2x3 matrix. Matrix(Matrix), /// Represents a 3D 4x4 matrix with percentage and length values. @@ -222,21 +223,160 @@ pub enum TransformOperation>, - to_list: Transform>, - progress: computed::Percentage }, + InterpolateMatrix { #[compute(ignore_bound)] + from_list: Transform>, + #[compute(ignore_bound)] + to_list: Transform>, + #[compute(clone)] progress: computed::Percentage }, /// A intermediate type for accumulation of mismatched transform lists. #[allow(missing_docs)] - AccumulateMatrix { from_list: Transform>, - to_list: Transform>, - count: specified::Integer }, + + AccumulateMatrix { #[compute(ignore_bound)] + from_list: Transform>, + #[compute(ignore_bound)] + to_list: Transform>, + count: Integer }, } +#[derive(Animate, ToComputedValue)] #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] /// A value of the `transform` property pub struct Transform(Vec); + + +impl + ToCss for + TransformOperation { + fn to_css(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { + match *self { + TransformOperation::Matrix(ref m) => m.to_css(dest), + TransformOperation::PrefixedMatrix(ref m) => m.to_css(dest), + TransformOperation::Matrix3D { + m11, m12, m13, m14, + m21, m22, m23, m24, + m31, m32, m33, m34, + m41, m42, m43, m44, + } => { + serialize_function!(dest, matrix3d( + m11, m12, m13, m14, + m21, m22, m23, m24, + m31, m32, m33, m34, + m41, m42, m43, m44, + )) + } + TransformOperation::PrefixedMatrix3D { + m11, m12, m13, m14, + m21, m22, m23, m24, + m31, m32, m33, m34, + ref m41, ref m42, ref m43, m44, + } => { + serialize_function!(dest, matrix3d( + m11, m12, m13, m14, + m21, m22, m23, m24, + m31, m32, m33, m34, + m41, m42, m43, m44, + )) + } + TransformOperation::Skew(ax, None) => { + serialize_function!(dest, skew(ax)) + } + TransformOperation::Skew(ax, Some(ay)) => { + serialize_function!(dest, skew(ax, ay)) + } + TransformOperation::SkewX(angle) => { + serialize_function!(dest, skewX(angle)) + } + TransformOperation::SkewY(angle) => { + serialize_function!(dest, skewY(angle)) + } + TransformOperation::Translate(ref tx, None) => { + serialize_function!(dest, translate(tx)) + } + TransformOperation::Translate(ref tx, Some(ref ty)) => { + serialize_function!(dest, translate(tx, ty)) + } + TransformOperation::TranslateX(ref tx) => { + serialize_function!(dest, translateX(tx)) + } + TransformOperation::TranslateY(ref ty) => { + serialize_function!(dest, translateY(ty)) + } + TransformOperation::TranslateZ(ref tz) => { + serialize_function!(dest, translateZ(tz)) + } + TransformOperation::Translate3D(ref tx, ref ty, ref tz) => { + serialize_function!(dest, translate3d(tx, ty, tz)) + } + TransformOperation::Scale(factor, None) => { + serialize_function!(dest, scale(factor)) + } + TransformOperation::Scale(sx, Some(sy)) => { + serialize_function!(dest, scale(sx, sy)) + } + TransformOperation::ScaleX(sx) => { + serialize_function!(dest, scaleX(sx)) + } + TransformOperation::ScaleY(sy) => { + serialize_function!(dest, scaleY(sy)) + } + TransformOperation::ScaleZ(sz) => { + serialize_function!(dest, scaleZ(sz)) + } + TransformOperation::Scale3D(sx, sy, sz) => { + serialize_function!(dest, scale3d(sx, sy, sz)) + } + TransformOperation::Rotate(theta) => { + serialize_function!(dest, rotate(theta)) + } + TransformOperation::RotateX(theta) => { + serialize_function!(dest, rotateX(theta)) + } + TransformOperation::RotateY(theta) => { + serialize_function!(dest, rotateY(theta)) + } + TransformOperation::RotateZ(theta) => { + serialize_function!(dest, rotateZ(theta)) + } + TransformOperation::Rotate3D(x, y, z, theta) => { + serialize_function!(dest, rotate3d(x, y, z, theta)) + } + TransformOperation::Perspective(ref length) => { + serialize_function!(dest, perspective(length)) + } + TransformOperation::InterpolateMatrix { ref from_list, ref to_list, progress } => { + serialize_function!(dest, interpolatematrix(from_list, to_list, progress)) + } + TransformOperation::AccumulateMatrix { ref from_list, ref to_list, count } => { + serialize_function!(dest, accumulatematrix(from_list, to_list, count)) + } + } + } +} + +impl ToCss for Transform { + fn to_css(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { + if self.0.is_empty() { + return dest.write_str("none") + } + + let mut first = true; + for operation in &self.0 { + if !first { + dest.write_str(" ")?; + } + first = false; + operation.to_css(dest)? + } + Ok(()) + } +} diff --git a/components/style_derive/to_computed_value.rs b/components/style_derive/to_computed_value.rs index 7e4db276edd..c53b25408e9 100644 --- a/components/style_derive/to_computed_value.rs +++ b/components/style_derive/to_computed_value.rs @@ -25,7 +25,9 @@ pub fn derive(input: DeriveInput) -> Tokens { } quote! { ::std::clone::Clone::clone(#binding) } } else { - where_clause.add_trait_bound(&binding.field.ty); + if !attrs.ignore_bound { + where_clause.add_trait_bound(&binding.field.ty); + } quote! { ::values::computed::ToComputedValue::to_computed_value(#binding, context) } @@ -68,4 +70,5 @@ pub fn derive(input: DeriveInput) -> Tokens { #[derive(Default, FromField)] struct ComputedValueAttrs { clone: bool, + ignore_bound: bool, } From d6525e030aae08726bd95d9ca329430535355abf Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Tue, 3 Oct 2017 15:51:35 -0700 Subject: [PATCH 03/21] Add specified and computed variants of Transform/TransformOperation --- components/style/values/computed/transform.rs | 10 +++++++++- components/style/values/specified/transform.rs | 11 +++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/components/style/values/computed/transform.rs b/components/style/values/computed/transform.rs index 21c98c50d99..79bf995f520 100644 --- a/components/style/values/computed/transform.rs +++ b/components/style/values/computed/transform.rs @@ -10,10 +10,18 @@ use properties::longhands::transform::computed_value::{ComputedOperation, Comput use properties::longhands::transform::computed_value::T as TransformList; use std::f32; use super::CSSFloat; -use values::computed::{Angle, Length, LengthOrPercentage, Number, Percentage}; +use values::computed::{Angle, Integer, Length, LengthOrPercentage, Number, Percentage}; +use values::computed::{LengthOrNumber, LengthOrPercentageOrNumber}; use values::generics::transform::TimingFunction as GenericTimingFunction; +use values::generics::transform::{Transform as GenericTransform, TransformOperation as GenericTransformOperation}; use values::generics::transform::TransformOrigin as GenericTransformOrigin; +/// A single operation in a computed CSS `transform` +pub type TransformOperation = GenericTransformOperation; +/// A computed CSS `transform` +pub type Transform = GenericTransform; + /// The computed value of a CSS `` pub type TransformOrigin = GenericTransformOrigin; diff --git a/components/style/values/specified/transform.rs b/components/style/values/specified/transform.rs index e2a56d1e405..631db4f482b 100644 --- a/components/style/values/specified/transform.rs +++ b/components/style/values/specified/transform.rs @@ -13,10 +13,17 @@ use values::computed::{Percentage as ComputedPercentage, ToComputedValue}; use values::computed::transform::TimingFunction as ComputedTimingFunction; use values::generics::transform::{StepPosition, TimingFunction as GenericTimingFunction}; use values::generics::transform::{TimingKeyword, TransformOrigin as GenericTransformOrigin}; -use values::specified::{Integer, Number}; -use values::specified::length::{Length, LengthOrPercentage}; +use values::generics::transform::{Transform as GenericTransform, TransformOperation as GenericTransformOperation}; +use values::specified::{Angle, Number, Length, Integer}; +use values::specified::{LengthOrNumber, LengthOrPercentage, LengthOrPercentageOrNumber}; use values::specified::position::{Side, X, Y}; +/// A single operation in a specified CSS `transform` +pub type TransformOperation = GenericTransformOperation; +/// A specified CSS `transform` +pub type Transform = GenericTransform; + /// The specified value of a CSS `` pub type TransformOrigin = GenericTransformOrigin, OriginComponent, Length>; From 544989819d85e1879ca3c34ca79d839a821e0fcf Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Tue, 3 Oct 2017 16:08:32 -0700 Subject: [PATCH 04/21] Add parsing support for transform --- components/style/values/generics/transform.rs | 2 +- .../style/values/specified/transform.rs | 221 +++++++++++++++++- 2 files changed, 219 insertions(+), 4 deletions(-) diff --git a/components/style/values/generics/transform.rs b/components/style/values/generics/transform.rs index 56d3643404d..116a6d8e228 100644 --- a/components/style/values/generics/transform.rs +++ b/components/style/values/generics/transform.rs @@ -250,7 +250,7 @@ pub enum TransformOperation(Vec); +pub struct Transform(pub Vec); impl; /// The specified value of a CSS `` pub type TransformOrigin = GenericTransformOrigin, OriginComponent, Length>; + +impl Transform { + /// Internal parse function for deciding if we wish to accept prefixed values or not + // Allow unitless zero angle for rotate() and skew() to align with gecko + pub fn parse_internal<'i, 't>( + context: &ParserContext, + input: &mut Parser<'i, 't>, + prefixed: bool, + ) -> Result> { + use style_traits::{Separator, Space}; + + if input.try(|input| input.expect_ident_matching("none")).is_ok() { + return Ok(GenericTransform(Vec::new())) + } + + Ok(GenericTransform(Space::parse(input, |input| { + let function = input.expect_function()?.clone(); + input.parse_nested_block(|input| { + let result = match_ignore_ascii_case! { &function, + "matrix" => { + let a = specified::parse_number(context, input)?; + input.expect_comma()?; + let b = specified::parse_number(context, input)?; + input.expect_comma()?; + let c = specified::parse_number(context, input)?; + input.expect_comma()?; + let d = specified::parse_number(context, input)?; + input.expect_comma()?; + if !prefixed { + // Standard matrix parsing. + let e = specified::parse_number(context, input)?; + input.expect_comma()?; + let f = specified::parse_number(context, input)?; + Ok(GenericTransformOperation::Matrix(Matrix { a, b, c, d, e, f })) + } else { + // Non-standard prefixed matrix parsing for -moz-transform. + let e = LengthOrPercentageOrNumber::parse(context, input)?; + input.expect_comma()?; + let f = LengthOrPercentageOrNumber::parse(context, input)?; + Ok(GenericTransformOperation::PrefixedMatrix(Matrix { a, b, c, d, e, f })) + } + }, + "matrix3d" => { + let m11 = specified::parse_number(context, input)?; + input.expect_comma()?; + let m12 = specified::parse_number(context, input)?; + input.expect_comma()?; + let m13 = specified::parse_number(context, input)?; + input.expect_comma()?; + let m14 = specified::parse_number(context, input)?; + input.expect_comma()?; + let m21 = specified::parse_number(context, input)?; + input.expect_comma()?; + let m22 = specified::parse_number(context, input)?; + input.expect_comma()?; + let m23 = specified::parse_number(context, input)?; + input.expect_comma()?; + let m24 = specified::parse_number(context, input)?; + input.expect_comma()?; + let m31 = specified::parse_number(context, input)?; + input.expect_comma()?; + let m32 = specified::parse_number(context, input)?; + input.expect_comma()?; + let m33 = specified::parse_number(context, input)?; + input.expect_comma()?; + let m34 = specified::parse_number(context, input)?; + input.expect_comma()?; + if !prefixed { + // Standard matrix3d parsing. + let m41 = specified::parse_number(context, input)?; + input.expect_comma()?; + let m42 = specified::parse_number(context, input)?; + input.expect_comma()?; + let m43 = specified::parse_number(context, input)?; + input.expect_comma()?; + let m44 = specified::parse_number(context, input)?; + Ok(GenericTransformOperation::Matrix3D { + m11, m12, m13, m14, + m21, m22, m23, m24, + m31, m32, m33, m34, + m41, m42, m43, m44, + }) + } else { + // Non-standard prefixed matrix parsing for -moz-transform. + let m41 = LengthOrPercentageOrNumber::parse(context, input)?; + input.expect_comma()?; + let m42 = LengthOrPercentageOrNumber::parse(context, input)?; + input.expect_comma()?; + let m43 = LengthOrNumber::parse(context, input)?; + input.expect_comma()?; + let m44 = specified::parse_number(context, input)?; + Ok(GenericTransformOperation::PrefixedMatrix3D { + m11, m12, m13, m14, + m21, m22, m23, m24, + m31, m32, m33, m34, + m41, m42, m43, m44, + }) + } + }, + "translate" => { + let sx = specified::LengthOrPercentage::parse(context, input)?; + if input.try(|input| input.expect_comma()).is_ok() { + let sy = specified::LengthOrPercentage::parse(context, input)?; + Ok(GenericTransformOperation::Translate(sx, Some(sy))) + } else { + Ok(GenericTransformOperation::Translate(sx, None)) + } + }, + "translatex" => { + let tx = specified::LengthOrPercentage::parse(context, input)?; + Ok(GenericTransformOperation::TranslateX(tx)) + }, + "translatey" => { + let ty = specified::LengthOrPercentage::parse(context, input)?; + Ok(GenericTransformOperation::TranslateY(ty)) + }, + "translatez" => { + let tz = specified::Length::parse(context, input)?; + Ok(GenericTransformOperation::TranslateZ(tz)) + }, + "translate3d" => { + let tx = specified::LengthOrPercentage::parse(context, input)?; + input.expect_comma()?; + let ty = specified::LengthOrPercentage::parse(context, input)?; + input.expect_comma()?; + let tz = specified::Length::parse(context, input)?; + Ok(GenericTransformOperation::Translate3D(tx, ty, tz)) + }, + "scale" => { + let sx = specified::parse_number(context, input)?; + if input.try(|input| input.expect_comma()).is_ok() { + let sy = specified::parse_number(context, input)?; + Ok(GenericTransformOperation::Scale(sx, Some(sy))) + } else { + Ok(GenericTransformOperation::Scale(sx, None)) + } + }, + "scalex" => { + let sx = specified::parse_number(context, input)?; + Ok(GenericTransformOperation::ScaleX(sx)) + }, + "scaley" => { + let sy = specified::parse_number(context, input)?; + Ok(GenericTransformOperation::ScaleY(sy)) + }, + "scalez" => { + let sz = specified::parse_number(context, input)?; + Ok(GenericTransformOperation::ScaleZ(sz)) + }, + "scale3d" => { + let sx = specified::parse_number(context, input)?; + input.expect_comma()?; + let sy = specified::parse_number(context, input)?; + input.expect_comma()?; + let sz = specified::parse_number(context, input)?; + Ok(GenericTransformOperation::Scale3D(sx, sy, sz)) + }, + "rotate" => { + let theta = specified::Angle::parse_with_unitless(context, input)?; + Ok(GenericTransformOperation::Rotate(theta)) + }, + "rotatex" => { + let theta = specified::Angle::parse_with_unitless(context, input)?; + Ok(GenericTransformOperation::RotateX(theta)) + }, + "rotatey" => { + let theta = specified::Angle::parse_with_unitless(context, input)?; + Ok(GenericTransformOperation::RotateY(theta)) + }, + "rotatez" => { + let theta = specified::Angle::parse_with_unitless(context, input)?; + Ok(GenericTransformOperation::RotateZ(theta)) + }, + "rotate3d" => { + let ax = specified::parse_number(context, input)?; + input.expect_comma()?; + let ay = specified::parse_number(context, input)?; + input.expect_comma()?; + let az = specified::parse_number(context, input)?; + input.expect_comma()?; + let theta = specified::Angle::parse_with_unitless(context, input)?; + // TODO(gw): Check that the axis can be normalized. + Ok(GenericTransformOperation::Rotate3D(ax, ay, az, theta)) + }, + "skew" => { + let ax = specified::Angle::parse_with_unitless(context, input)?; + if input.try(|input| input.expect_comma()).is_ok() { + let ay = specified::Angle::parse_with_unitless(context, input)?; + Ok(GenericTransformOperation::Skew(ax, Some(ay))) + } else { + Ok(GenericTransformOperation::Skew(ax, None)) + } + }, + "skewx" => { + let theta = specified::Angle::parse_with_unitless(context, input)?; + Ok(GenericTransformOperation::SkewX(theta)) + }, + "skewy" => { + let theta = specified::Angle::parse_with_unitless(context, input)?; + Ok(GenericTransformOperation::SkewY(theta)) + }, + "perspective" => { + let d = specified::Length::parse_non_negative(context, input)?; + Ok(GenericTransformOperation::Perspective(d)) + }, + _ => Err(()), + }; + result + .map_err(|()| StyleParseError::UnexpectedFunction(function.clone()).into()) + }) + })?)) + } +} + /// The specified value of a component of a CSS ``. #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToCss)] pub enum OriginComponent { From 5031d14d1b60885d44e3dba0f0bd5b8b6c084921 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Tue, 3 Oct 2017 16:37:07 -0700 Subject: [PATCH 05/21] Use a generic Matrix3D type --- components/style/values/generics/transform.rs | 33 ++++++++++--------- .../style/values/specified/transform.rs | 10 +++--- 2 files changed, 22 insertions(+), 21 deletions(-) diff --git a/components/style/values/generics/transform.rs b/components/style/values/generics/transform.rs index 116a6d8e228..68385fe4aa6 100644 --- a/components/style/values/generics/transform.rs +++ b/components/style/values/generics/transform.rs @@ -21,6 +21,17 @@ pub struct Matrix { pub f: U, } +#[allow(missing_docs)] +#[derive(Clone, Copy, Debug, ToComputedValue, PartialEq)] +#[cfg_attr(feature = "gecko", derive(MallocSizeOf))] +#[cfg_attr(feature = "servo", derive(HeapSizeOf))] +pub struct Matrix3D { + pub m11: T, pub m12: T, pub m13: T, pub m14: T, + pub m21: T, pub m22: T, pub m23: T, pub m24: T, + pub m31: T, pub m32: T, pub m33: T, pub m34: T, + pub m41: U, pub m42: U, pub m43: V, pub m44: T, +} + /// A generic transform origin. #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug)] #[derive(MallocSizeOf, PartialEq, ToAnimatedZero, ToComputedValue, ToCss)] @@ -151,21 +162,11 @@ pub enum TransformOperation), /// Represents a 3D 4x4 matrix. #[allow(missing_docs)] - Matrix3D { - m11: Number, m12: Number, m13: Number, m14: Number, - m21: Number, m22: Number, m23: Number, m24: Number, - m31: Number, m32: Number, m33: Number, m34: Number, - m41: Number, m42: Number, m43: Number, m44: Number, - }, + Matrix3D(Matrix3D), /// Represents a 3D 4x4 matrix with percentage and length values. /// For `moz-transform`. #[allow(missing_docs)] - PrefixedMatrix3D { - m11: Number, m12: Number, m13: Number, m14: Number, - m21: Number, m22: Number, m23: Number, m24: Number, - m31: Number, m32: Number, m33: Number, m34: Number, - m41: LoPoNumber, m42: LoPoNumber, m43: LengthOrNumber, m44: Number, - }, + PrefixedMatrix3D(Matrix3D), /// A 2D skew. /// /// If the second angle is not provided it is assumed zero. @@ -261,12 +262,12 @@ impl m.to_css(dest), TransformOperation::PrefixedMatrix(ref m) => m.to_css(dest), - TransformOperation::Matrix3D { + TransformOperation::Matrix3D(Matrix3D { m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44, - } => { + }) => { serialize_function!(dest, matrix3d( m11, m12, m13, m14, m21, m22, m23, m24, @@ -274,12 +275,12 @@ impl { + }) => { serialize_function!(dest, matrix3d( m11, m12, m13, m14, m21, m22, m23, m24, diff --git a/components/style/values/specified/transform.rs b/components/style/values/specified/transform.rs index 867d7f862af..82f0e0cad1a 100644 --- a/components/style/values/specified/transform.rs +++ b/components/style/values/specified/transform.rs @@ -10,10 +10,10 @@ use selectors::parser::SelectorParseErrorKind; use style_traits::{ParseError, StyleParseErrorKind}; use values::computed::{Context, LengthOrPercentage as ComputedLengthOrPercentage}; use values::computed::{Percentage as ComputedPercentage, ToComputedValue}; +use values::generics::transform::{Matrix3D, Transform as GenericTransform}; use values::computed::transform::TimingFunction as ComputedTimingFunction; use values::generics::transform::{StepPosition, TimingFunction as GenericTimingFunction, Matrix}; use values::generics::transform::{TimingKeyword, TransformOrigin as GenericTransformOrigin}; -use values::generics::transform::Transform as GenericTransform; use values::generics::transform::TransformOperation as GenericTransformOperation; use values::specified::{self, Angle, Number, Length, Integer}; use values::specified::{LengthOrNumber, LengthOrPercentage, LengthOrPercentageOrNumber}; @@ -104,12 +104,12 @@ impl Transform { let m43 = specified::parse_number(context, input)?; input.expect_comma()?; let m44 = specified::parse_number(context, input)?; - Ok(GenericTransformOperation::Matrix3D { + Ok(GenericTransformOperation::Matrix3D(Matrix3D { m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44, - }) + })) } else { // Non-standard prefixed matrix parsing for -moz-transform. let m41 = LengthOrPercentageOrNumber::parse(context, input)?; @@ -119,12 +119,12 @@ impl Transform { let m43 = LengthOrNumber::parse(context, input)?; input.expect_comma()?; let m44 = specified::parse_number(context, input)?; - Ok(GenericTransformOperation::PrefixedMatrix3D { + Ok(GenericTransformOperation::PrefixedMatrix3D(Matrix3D { m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44, - }) + })) } }, "translate" => { From 2de34643743c8f6fca05e5067f4268f4a7e1c8ee Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Tue, 3 Oct 2017 16:58:03 -0700 Subject: [PATCH 06/21] Add ToAnimatedZero implementation --- components/style/values/computed/transform.rs | 179 +++++++++++++++++- 1 file changed, 178 insertions(+), 1 deletion(-) diff --git a/components/style/values/computed/transform.rs b/components/style/values/computed/transform.rs index 79bf995f520..e72d00651bb 100644 --- a/components/style/values/computed/transform.rs +++ b/components/style/values/computed/transform.rs @@ -9,9 +9,11 @@ use euclid::{Rect, Transform3D, Vector3D}; use properties::longhands::transform::computed_value::{ComputedOperation, ComputedMatrix}; use properties::longhands::transform::computed_value::T as TransformList; use std::f32; -use super::CSSFloat; +use super::{CSSFloat, Either}; +use values::animated::ToAnimatedZero; use values::computed::{Angle, Integer, Length, LengthOrPercentage, Number, Percentage}; use values::computed::{LengthOrNumber, LengthOrPercentageOrNumber}; +use values::generics::transform::{Matrix as GenericMatrix, Matrix3D as GenericMatrix3D}; use values::generics::transform::TimingFunction as GenericTimingFunction; use values::generics::transform::{Transform as GenericTransform, TransformOperation as GenericTransformOperation}; use values::generics::transform::TransformOrigin as GenericTransformOrigin; @@ -66,6 +68,68 @@ impl From> for ComputedMatrix { } } +/// computed value of matrix3d() +pub type Matrix3D = GenericMatrix3D; +/// computed value of matrix3d() in -moz-transform +pub type PrefixedMatrix3D = GenericMatrix3D; +/// computed value of matrix() +pub type Matrix = GenericMatrix; +/// computed value of matrix() in -moz-transform +pub type PrefixedMatrix = GenericMatrix; + +impl Matrix3D { + #[inline] + /// Get an identity matrix + pub fn identity() -> Self { + Self { + m11: 1.0, m12: 0.0, m13: 0.0, m14: 0.0, + m21: 0.0, m22: 1.0, m23: 0.0, m24: 0.0, + m31: 0.0, m32: 0.0, m33: 1.0, m34: 0.0, + m41: 0., m42: 0., m43: 0., m44: 1.0 + } + } +} + +impl PrefixedMatrix3D { + #[inline] + /// Get an identity matrix + pub fn identity() -> Self { + Self { + m11: 1.0, m12: 0.0, m13: 0.0, m14: 0.0, + m21: 0.0, m22: 1.0, m23: 0.0, m24: 0.0, + m31: 0.0, m32: 0.0, m33: 1.0, m34: 0.0, + m41: Either::First(0.), m42: Either::First(0.), + m43: Either::First(Length::new(0.)), m44: 1.0 + } + } +} + +impl Matrix { + #[inline] + /// Get an identity matrix + pub fn identity() -> Self { + Self { + a: 1., c: 0., /* 0 */e: 0., + b: 0., d: 1., /* 0 */f: 0., + /* 0 0 1 0 */ + /* 0 0 0 1 */ + } + } +} + +impl PrefixedMatrix { + #[inline] + /// Get an identity matrix + pub fn identity() -> Self { + Self { + a: 1., c: 0., /* 0 */e: Either::First(0.), + b: 0., d: 1., /* 0 */f: Either::First(0.), + /* 0 0 1 0 */ + /* 0 0 0 1 */ + } + } +} + impl TransformList { /// Return the equivalent 3d matrix of this transform list. /// If |reference_box| is None, we will drop the percent part from translate because @@ -177,3 +241,116 @@ impl TransformList { } } } + +/// Build an equivalent 'identity transform function list' based +/// on an existing transform list. +/// http://dev.w3.org/csswg/css-transforms/#none-transform-animation +impl ToAnimatedZero for TransformOperation { + fn to_animated_zero(&self) -> Result { + match *self { + GenericTransformOperation::Matrix3D(..) => { + Ok(GenericTransformOperation::Matrix3D(Matrix3D::identity())) + }, + GenericTransformOperation::PrefixedMatrix3D(..) => { + Ok(GenericTransformOperation::PrefixedMatrix3D(PrefixedMatrix3D::identity())) + }, + GenericTransformOperation::Matrix(..) => { + Ok(GenericTransformOperation::Matrix(Matrix::identity())) + }, + GenericTransformOperation::PrefixedMatrix(..) => { + Ok(GenericTransformOperation::PrefixedMatrix(PrefixedMatrix::identity())) + }, + GenericTransformOperation::Skew(sx, sy) => { + Ok(GenericTransformOperation::Skew( + sx.to_animated_zero()?, + sy.to_animated_zero()?, + )) + }, + GenericTransformOperation::SkewX(s) => { + Ok(GenericTransformOperation::SkewX( + s.to_animated_zero()?, + )) + }, + GenericTransformOperation::SkewY(s) => { + Ok(GenericTransformOperation::SkewY( + s.to_animated_zero()?, + )) + }, + GenericTransformOperation::Translate3D(ref tx, ref ty, ref tz) => { + Ok(GenericTransformOperation::Translate3D( + tx.to_animated_zero()?, + ty.to_animated_zero()?, + tz.to_animated_zero()?, + )) + }, + GenericTransformOperation::Translate(ref tx, ref ty) => { + Ok(GenericTransformOperation::Translate( + tx.to_animated_zero()?, + ty.to_animated_zero()?, + )) + }, + GenericTransformOperation::TranslateX(ref t) => { + Ok(GenericTransformOperation::TranslateX( + t.to_animated_zero()?, + )) + }, + GenericTransformOperation::TranslateY(ref t) => { + Ok(GenericTransformOperation::TranslateY( + t.to_animated_zero()?, + )) + }, + GenericTransformOperation::TranslateZ(ref t) => { + Ok(GenericTransformOperation::TranslateZ( + t.to_animated_zero()?, + )) + }, + GenericTransformOperation::Scale3D(..) => { + Ok(GenericTransformOperation::Scale3D(1.0, 1.0, 1.0)) + }, + GenericTransformOperation::Scale(_, None) => { + Ok(GenericTransformOperation::Scale(1.0, None)) + }, + GenericTransformOperation::Scale(_, Some(_)) => { + Ok(GenericTransformOperation::Scale(1.0, Some(1.0))) + }, + GenericTransformOperation::ScaleX(..) => { + Ok(GenericTransformOperation::ScaleX(1.0)) + }, + GenericTransformOperation::ScaleY(..) => { + Ok(GenericTransformOperation::ScaleY(1.0)) + }, + GenericTransformOperation::ScaleZ(..) => { + Ok(GenericTransformOperation::ScaleZ(1.0)) + }, + GenericTransformOperation::Rotate3D(x, y, z, a) => { + let (x, y, z, _) = TransformList::get_normalized_vector_and_angle(x, y, z, a); + Ok(GenericTransformOperation::Rotate3D(x, y, z, Angle::zero())) + }, + GenericTransformOperation::RotateX(_) => { + Ok(GenericTransformOperation::RotateX(Angle::zero())) + }, + GenericTransformOperation::RotateY(_) => { + Ok(GenericTransformOperation::RotateY(Angle::zero())) + }, + GenericTransformOperation::RotateZ(_) => { + Ok(GenericTransformOperation::RotateZ(Angle::zero())) + }, + GenericTransformOperation::Rotate(_) => { + Ok(GenericTransformOperation::Rotate(Angle::zero())) + }, + GenericTransformOperation::Perspective(..) | + GenericTransformOperation::AccumulateMatrix { .. } | + GenericTransformOperation::InterpolateMatrix { .. } => { + // Perspective: We convert a perspective function into an equivalent + // ComputedMatrix, and then decompose/interpolate/recompose these matrices. + // AccumulateMatrix/InterpolateMatrix: We do interpolation on + // AccumulateMatrix/InterpolateMatrix by reading it as a ComputedMatrix + // (with layout information), and then do matrix interpolation. + // + // Therefore, we use an identity matrix to represent the identity transform list. + // http://dev.w3.org/csswg/css-transforms/#identity-transform-function + Ok(GenericTransformOperation::Matrix3D(Matrix3D::identity())) + }, + } + } +} From 5ce2966bda00fb9bb0195a60b408c874352dc181 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Tue, 3 Oct 2017 17:52:50 -0700 Subject: [PATCH 07/21] Add utilities for converting Transform to euclid types --- components/style/values/computed/transform.rs | 214 ++++++++++++++++++ 1 file changed, 214 insertions(+) diff --git a/components/style/values/computed/transform.rs b/components/style/values/computed/transform.rs index e72d00651bb..5e50a1ab8d4 100644 --- a/components/style/values/computed/transform.rs +++ b/components/style/values/computed/transform.rs @@ -130,6 +130,28 @@ impl PrefixedMatrix { } } +impl From for Transform3D { + #[inline] + fn from(m: Matrix3D) -> Self { + Transform3D::row_major( + m.m11, m.m12, m.m13, m.m14, + m.m21, m.m22, m.m23, m.m24, + m.m31, m.m32, m.m33, m.m34, + m.m41, m.m42, m.m43, m.m44) + } +} + +impl From for Transform3D { + #[inline] + fn from(m: Matrix) -> Self { + Transform3D::row_major( + m.a, m.b, 0.0, 0.0, + m.c, m.d, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + m.e, m.f, 0.0, 1.0) + } +} + impl TransformList { /// Return the equivalent 3d matrix of this transform list. /// If |reference_box| is None, we will drop the percent part from translate because @@ -354,3 +376,195 @@ impl ToAnimatedZero for TransformOperation { } } } + +impl Transform { + /// Return the equivalent 3d matrix of this transform list. + /// If |reference_box| is None, we will drop the percent part from translate because + /// we can resolve it without the layout info. + pub fn to_transform_3d_matrix(&self, reference_box: Option<&Rect>) + -> Option> { + let mut transform = Transform3D::identity(); + let list = &self.0; + if list.len() == 0 { + return None; + } + + let extract_pixel_length = |lop: &LengthOrPercentage| { + match *lop { + LengthOrPercentage::Length(px) => px.px(), + LengthOrPercentage::Percentage(_) => 0., + LengthOrPercentage::Calc(calc) => calc.length().px(), + } + }; + + for operation in list { + let matrix = match *operation { + GenericTransformOperation::Rotate3D(ax, ay, az, theta) => { + let theta = Angle::from_radians(2.0f32 * f32::consts::PI - theta.radians()); + let (ax, ay, az, theta) = + Self::get_normalized_vector_and_angle(ax, ay, az, theta); + Transform3D::create_rotation(ax, ay, az, theta.into()) + } + GenericTransformOperation::RotateX(theta) => { + let theta = Angle::from_radians(2.0f32 * f32::consts::PI - theta.radians()); + Transform3D::create_rotation(1., 0., 0., theta.into()) + } + GenericTransformOperation::RotateY(theta) => { + let theta = Angle::from_radians(2.0f32 * f32::consts::PI - theta.radians()); + Transform3D::create_rotation(0., 1., 0., theta.into()) + } + GenericTransformOperation::RotateZ(theta) | GenericTransformOperation::Rotate(theta) => { + let theta = Angle::from_radians(2.0f32 * f32::consts::PI - theta.radians()); + Transform3D::create_rotation(0., 0., 1., theta.into()) + } + GenericTransformOperation::Perspective(d) => { + Self::create_perspective_matrix(d.px()) + } + GenericTransformOperation::Scale3D(sx, sy, sz) => { + Transform3D::create_scale(sx, sy, sz) + } + GenericTransformOperation::Scale(sx, sy) => { + Transform3D::create_scale(sx, sy.unwrap_or(sx), 1.) + } + GenericTransformOperation::ScaleX(s) => { + Transform3D::create_scale(s, s, 1.) + } + GenericTransformOperation::ScaleY(s) => { + Transform3D::create_scale(1., s, 1.) + } + GenericTransformOperation::ScaleZ(s) => { + Transform3D::create_scale(1., 1., s) + } + GenericTransformOperation::Translate3D(tx, ty, tz) => { + let (tx, ty) = match reference_box { + Some(relative_border_box) => { + (tx.to_pixel_length(relative_border_box.size.width).px(), + ty.to_pixel_length(relative_border_box.size.height).px()) + }, + None => { + // If we don't have reference box, we cannot resolve the used value, + // so only retrieve the length part. This will be used for computing + // distance without any layout info. + (extract_pixel_length(&tx), extract_pixel_length(&ty)) + } + }; + let tz = tz.px(); + Transform3D::create_translation(tx, ty, tz) + } + GenericTransformOperation::Translate(tx, Some(ty)) => { + let (tx, ty) = match reference_box { + Some(relative_border_box) => { + (tx.to_pixel_length(relative_border_box.size.width).px(), + ty.to_pixel_length(relative_border_box.size.height).px()) + }, + None => { + // If we don't have reference box, we cannot resolve the used value, + // so only retrieve the length part. This will be used for computing + // distance without any layout info. + (extract_pixel_length(&tx), extract_pixel_length(&ty)) + } + }; + Transform3D::create_translation(tx, ty, 0.) + } + GenericTransformOperation::TranslateX(t) | GenericTransformOperation::Translate(t, None) => { + let t = match reference_box { + Some(relative_border_box) => { + t.to_pixel_length(relative_border_box.size.width).px() + }, + None => { + // If we don't have reference box, we cannot resolve the used value, + // so only retrieve the length part. This will be used for computing + // distance without any layout info. + extract_pixel_length(&t) + } + }; + Transform3D::create_translation(t, 0., 0.) + } + GenericTransformOperation::TranslateY(t) => { + let t = match reference_box { + Some(relative_border_box) => { + t.to_pixel_length(relative_border_box.size.height).px() + }, + None => { + // If we don't have reference box, we cannot resolve the used value, + // so only retrieve the length part. This will be used for computing + // distance without any layout info. + extract_pixel_length(&t) + } + }; + Transform3D::create_translation(0., t, 0.) + } + GenericTransformOperation::TranslateZ(z) => { + Transform3D::create_translation(0., 0., z.px()) + } + GenericTransformOperation::Skew(theta_x, theta_y) => { + Transform3D::create_skew(theta_x.into(), theta_y.unwrap_or(Angle::zero()).into()) + } + GenericTransformOperation::SkewX(theta) => { + Transform3D::create_skew(theta.into(), Angle::zero().into()) + } + GenericTransformOperation::SkewY(theta) => { + Transform3D::create_skew(Angle::zero().into(), theta.into()) + } + GenericTransformOperation::Matrix3D(m) => { + m.into() + } + GenericTransformOperation::Matrix(m) => { + m.into() + } + GenericTransformOperation::PrefixedMatrix3D(_) | GenericTransformOperation::PrefixedMatrix(_) => { + // `-moz-transform` is not implemented in Servo yet. + unreachable!() + } + GenericTransformOperation::InterpolateMatrix { .. } | + GenericTransformOperation::AccumulateMatrix { .. } => { + // TODO: Convert InterpolateMatrix/AccmulateMatrix into a valid Transform3D by + // the reference box and do interpolation on these two Transform3D matrices. + // Both Gecko and Servo don't support this for computing distance, and Servo + // doesn't support animations on InterpolateMatrix/AccumulateMatrix, so + // return None. + return None; + } + }; + + transform = transform.pre_mul(&matrix); + } + + Some(transform) + } + + /// Return the transform matrix from a perspective length. + #[inline] + pub fn create_perspective_matrix(d: CSSFloat) -> Transform3D { + // TODO(gw): The transforms spec says that perspective length must + // be positive. However, there is some confusion between the spec + // and browser implementations as to handling the case of 0 for the + // perspective value. Until the spec bug is resolved, at least ensure + // that a provided perspective value of <= 0.0 doesn't cause panics + // and behaves as it does in other browsers. + // See https://lists.w3.org/Archives/Public/www-style/2016Jan/0020.html for more details. + if d <= 0.0 { + Transform3D::identity() + } else { + Transform3D::create_perspective(d) + } + } + + /// Return the normalized direction vector and its angle for Rotate3D. + pub fn get_normalized_vector_and_angle(x: f32, y: f32, z: f32, angle: Angle) + -> (f32, f32, f32, Angle) { + use euclid::approxeq::ApproxEq; + use euclid::num::Zero; + let vector = DirectionVector::new(x, y, z); + if vector.square_length().approx_eq(&f32::zero()) { + // https://www.w3.org/TR/css-transforms-1/#funcdef-rotate3d + // A direction vector that cannot be normalized, such as [0, 0, 0], will cause the + // rotation to not be applied, so we use identity matrix (i.e. rotate3d(0, 0, 1, 0)). + (0., 0., 1., Angle::zero()) + } else { + let vector = vector.normalize(); + (vector.x, vector.y, vector.z, angle) + } + } +} + From 6631594e28fd2d834277fe9579b3ae6a56b597a0 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Wed, 4 Oct 2017 10:12:18 -0700 Subject: [PATCH 08/21] Replace old transform code with new generic code --- components/layout/flow.rs | 2 +- components/layout/fragment.rs | 4 +- components/style/properties/gecko.mako.rs | 108 +-- .../helpers/animated_properties.mako.rs | 277 ++---- .../style/properties/longhand/box.mako.rs | 855 +----------------- .../style/properties/properties.mako.rs | 40 +- components/style/values/computed/transform.rs | 162 +--- components/style/values/generics/transform.rs | 12 +- .../style/values/specified/transform.rs | 3 +- ports/geckolib/glue.rs | 15 +- 10 files changed, 210 insertions(+), 1268 deletions(-) diff --git a/components/layout/flow.rs b/components/layout/flow.rs index 9769f2070a4..c881817f398 100644 --- a/components/layout/flow.rs +++ b/components/layout/flow.rs @@ -291,7 +291,7 @@ pub trait Flow: HasBaseFlow + fmt::Debug + Sync + Send + 'static { } if !self.as_block().fragment.establishes_stacking_context() || - self.as_block().fragment.style.get_box().transform.0.is_none() { + self.as_block().fragment.style.get_box().transform.0.is_empty() { overflow.translate(&position.origin.to_vector()); return overflow; } diff --git a/components/layout/fragment.rs b/components/layout/fragment.rs index e8455bff4b9..020c4b65ab3 100644 --- a/components/layout/fragment.rs +++ b/components/layout/fragment.rs @@ -2500,7 +2500,7 @@ impl Fragment { /// Returns true if this fragment has a filter, transform, or perspective property set. pub fn has_filter_transform_or_perspective(&self) -> bool { - self.style().get_box().transform.0.is_some() || + !self.style().get_box().transform.0.is_empty() || !self.style().get_effects().filter.0.is_empty() || self.style().get_box().perspective != Either::Second(values::None_) } @@ -2560,7 +2560,7 @@ impl Fragment { _ => return self.style().get_position().z_index.integer_or(0), } - if self.style().get_box().transform.0.is_some() { + if !self.style().get_box().transform.0.is_empty() { return self.style().get_position().z_index.integer_or(0); } diff --git a/components/style/properties/gecko.mako.rs b/components/style/properties/gecko.mako.rs index 7a6995f2ec4..cee6c61b77b 100644 --- a/components/style/properties/gecko.mako.rs +++ b/components/style/properties/gecko.mako.rs @@ -2901,9 +2901,9 @@ fn static_assert() { single_patterns = ["m%s: %s" % (str(a / 4 + 1) + str(a % 4 + 1), b + str(a + 1)) for (a, b) in enumerate(items)] if name == "Matrix": - pattern = "(ComputedMatrix { %s })" % ", ".join(single_patterns) + pattern = "(Matrix3D { %s })" % ", ".join(single_patterns) else: - pattern = "(ComputedMatrixWithPercents { %s })" % ", ".join(single_patterns) + pattern = "(Matrix3D { %s })" % ", ".join(single_patterns) elif keyword == "interpolatematrix": pattern = " { from_list: ref list1, to_list: ref list2, progress: percentage3 }" elif keyword == "accumulatematrix": @@ -2921,15 +2921,17 @@ fn static_assert() { # need to cast it to f32. "integer_to_percentage" : "bindings::Gecko_CSSValue_SetPercentage(%s, %s as f32)", "lop" : "%s.set_lop(%s)", + "lopon" : "set_lopon(%s, %s)", + "lon" : "set_lon(%s, %s)", "angle" : "%s.set_angle(%s)", "number" : "bindings::Gecko_CSSValue_SetNumber(%s, %s)", # Note: We use nsCSSValueSharedList here, instead of nsCSSValueList_heap # because this function is not called on the main thread and # nsCSSValueList_heap is not thread safe. - "list" : "%s.set_shared_list(%s.0.as_ref().unwrap().into_iter().map(&convert_to_ns_css_value));", + "list" : "%s.set_shared_list(%s.0.iter().map(&convert_to_ns_css_value));", } %> - longhands::transform::computed_value::ComputedOperation::${name}${pattern} => { + ::values::generics::transform::TransformOperation::${name}${pattern} => { bindings::Gecko_CSSValue_SetFunction(gecko_value, ${len(items) + 1}); bindings::Gecko_CSSValue_SetKeyword( bindings::Gecko_CSSValue_GetArrayItem(gecko_value, 0), @@ -2937,7 +2939,7 @@ fn static_assert() { ); % for index, item in enumerate(items): % if item == "list": - debug_assert!(${item}${index + 1}.0.is_some()); + debug_assert!(!${item}${index + 1}.0.is_empty()); % endif ${css_value_setters[item] % ( "bindings::Gecko_CSSValue_GetArrayItem(gecko_value, %d)" % (index + 1), @@ -2948,9 +2950,9 @@ fn static_assert() { fn set_single_transform_function(servo_value: &longhands::transform::computed_value::ComputedOperation, gecko_value: &mut structs::nsCSSValue /* output */) { - use properties::longhands::transform::computed_value::ComputedMatrix; - use properties::longhands::transform::computed_value::ComputedMatrixWithPercents; use properties::longhands::transform::computed_value::ComputedOperation; + use values::computed::{Length, LengthOrNumber, LengthOrPercentage, LengthOrPercentageOrNumber}; + use values::generics::transform::Matrix3D; let convert_to_ns_css_value = |item: &ComputedOperation| -> structs::nsCSSValue { let mut value = structs::nsCSSValue::null(); @@ -2958,20 +2960,36 @@ fn static_assert() { value }; + unsafe fn set_lopon(css: &mut structs::nsCSSValue, lopon: LengthOrPercentageOrNumber) { + let lop = match lopon { + Either::First(number) => LengthOrPercentage::Length(Length::new(number)), + Either::Second(lop) => lop, + }; + css.set_lop(lop); + } + + unsafe fn set_lon(css: &mut structs::nsCSSValue, lopon: LengthOrNumber) { + let length = match lopon { + Either::Second(number) => Length::new(number), + Either::First(l) => l, + }; + bindings::Gecko_CSSValue_SetPixelLength(css, length.px()) + } + unsafe { match *servo_value { - ${transform_function_arm("Matrix", "matrix3d", ["number"] * 16)} - ${transform_function_arm("MatrixWithPercents", "matrix3d", ["number"] * 12 + ["lop"] * 2 - + ["length"] + ["number"])} - ${transform_function_arm("Skew", "skew", ["angle"] * 2)} - ${transform_function_arm("Translate", "translate3d", ["lop", "lop", "length"])} - ${transform_function_arm("Scale", "scale3d", ["number"] * 3)} - ${transform_function_arm("Rotate", "rotate3d", ["number"] * 3 + ["angle"])} + ${transform_function_arm("Matrix3D", "matrix3d", ["number"] * 16)} + ${transform_function_arm("PrefixedMatrix3D", "matrix3d", ["number"] * 12 + ["lopon"] * 2 + + ["lon"] + ["number"])} + ${transform_function_arm("Translate3D", "translate3d", ["lop", "lop", "length"])} + ${transform_function_arm("Scale3D", "scale3d", ["number"] * 3)} + ${transform_function_arm("Rotate3D", "rotate3d", ["number"] * 3 + ["angle"])} ${transform_function_arm("Perspective", "perspective", ["length"])} ${transform_function_arm("InterpolateMatrix", "interpolatematrix", ["list"] * 2 + ["percentage"])} ${transform_function_arm("AccumulateMatrix", "accumulatematrix", ["list"] * 2 + ["integer_to_percentage"])} + _ => unimplemented!() } } } @@ -2994,15 +3012,13 @@ fn static_assert() { } pub fn set_transform(&mut self, other: longhands::transform::computed_value::T) { - let vec = if let Some(v) = other.0 { - v - } else { + if other.0.is_empty() { unsafe { self.gecko.mSpecifiedTransform.clear(); } return; }; - Self::convert_transform(&vec, &mut self.gecko.mSpecifiedTransform); + Self::convert_transform(&other.0, &mut self.gecko.mSpecifiedTransform); } pub fn copy_transform_from(&mut self, other: &Self) { @@ -3023,7 +3039,7 @@ fn static_assert() { "number" : "bindings::Gecko_CSSValue_GetNumber(%s)", "percentage" : "Percentage(bindings::Gecko_CSSValue_GetPercentage(%s))", "percentage_to_integer" : "bindings::Gecko_CSSValue_GetPercentage(%s) as i32", - "list" : "TransformList(Some(convert_shared_list_to_operations(%s)))", + "list" : "Transform(convert_shared_list_to_operations(%s))", } pre_symbols = "(" post_symbols = ")" @@ -3033,7 +3049,7 @@ fn static_assert() { pre_symbols = " {" post_symbols = "}" elif keyword == "matrix3d": - pre_symbols = "(ComputedMatrix {" + pre_symbols = "(Matrix3D {" post_symbols = "})" field_names = None if keyword == "interpolatematrix": @@ -3042,7 +3058,7 @@ fn static_assert() { field_names = ["from_list", "to_list", "count"] %> structs::nsCSSKeyword::eCSSKeyword_${keyword} => { - ComputedOperation::${name}${pre_symbols} + ::values::generics::transform::TransformOperation::${name}${pre_symbols} % for index, item in enumerate(items): % if keyword == "matrix3d": m${index / 4 + 1}${index % 4 + 1}: @@ -3058,10 +3074,10 @@ fn static_assert() { fn clone_single_transform_function(gecko_value: &structs::nsCSSValue) -> longhands::transform::computed_value::ComputedOperation { - use properties::longhands::transform::computed_value::ComputedMatrix; use properties::longhands::transform::computed_value::ComputedOperation; - use properties::longhands::transform::computed_value::T as TransformList; use values::computed::{Length, Percentage}; + use values::generics::transform::Matrix3D; + use values::generics::transform::Transform; let convert_shared_list_to_operations = |value: &structs::nsCSSValue| -> Vec { @@ -3081,59 +3097,33 @@ fn static_assert() { }; unsafe { - use gecko_bindings::structs::nsCSSKeyword; - use values::computed::Angle; - - let get_array_angle = || -> Angle { - bindings::Gecko_CSSValue_GetArrayItemConst(gecko_value, 1).get_angle() - }; - match transform_function { - ${computed_operation_arm("Matrix", "matrix3d", ["number"] * 16)} - ${computed_operation_arm("Skew", "skew", ["angle"] * 2)} - ${computed_operation_arm("Translate", "translate3d", ["lop", "lop", "length"])} - ${computed_operation_arm("Scale", "scale3d", ["number"] * 3)} - ${computed_operation_arm("Rotate", "rotate3d", ["number"] * 3 + ["angle"])} + ${computed_operation_arm("Matrix3D", "matrix3d", ["number"] * 16)} + ${computed_operation_arm("Translate3D", "translate3d", ["lop", "lop", "length"])} + ${computed_operation_arm("Scale3D", "scale3d", ["number"] * 3)} + ${computed_operation_arm("Rotate3D", "rotate3d", ["number"] * 3 + ["angle"])} ${computed_operation_arm("Perspective", "perspective", ["length"])} ${computed_operation_arm("InterpolateMatrix", "interpolatematrix", ["list"] * 2 + ["percentage"])} ${computed_operation_arm("AccumulateMatrix", "accumulatematrix", ["list"] * 2 + ["percentage_to_integer"])} - // FIXME: Bug 1391145 will introduce new types for these keywords. For now, we - // temporarily don't use |computed_operation_arm| because these are special cases - // for compositor animations when we use Gecko style backend on the main thread, - // and I don't want to add too many special cases in |computed_operation_arm|. - // - // Note: Gecko only converts translate and scale into the corresponding primitive - // functions, so we still need to handle the following functions. - nsCSSKeyword::eCSSKeyword_skewx => { - ComputedOperation::Skew(get_array_angle(), Angle::zero()) - }, - nsCSSKeyword::eCSSKeyword_skewy => { - ComputedOperation::Skew(Angle::zero(), get_array_angle()) - }, - nsCSSKeyword::eCSSKeyword_rotatex => { - ComputedOperation::Rotate(1.0, 0.0, 0.0, get_array_angle()) - }, - nsCSSKeyword::eCSSKeyword_rotatey => { - ComputedOperation::Rotate(0.0, 1.0, 0.0, get_array_angle()) - }, - nsCSSKeyword::eCSSKeyword_rotatez | nsCSSKeyword::eCSSKeyword_rotate => { - ComputedOperation::Rotate(0.0, 0.0, 1.0, get_array_angle()) - }, _ => panic!("{:?} is not an acceptable transform function", transform_function), } } } pub fn clone_transform(&self) -> longhands::transform::computed_value::T { + use values::generics::transform::Transform; + if self.gecko.mSpecifiedTransform.mRawPtr.is_null() { - return longhands::transform::computed_value::T(None); + return Transform(vec!()); } let list = unsafe { (*self.gecko.mSpecifiedTransform.to_safe().get()).mHead.as_ref() }; Self::clone_transform_from_list(list) } pub fn clone_transform_from_list(list: Option< &structs::root::nsCSSValueList>) -> longhands::transform::computed_value::T { + use values::generics::transform::Transform; + let result = match list { Some(list) => { let vec: Vec<_> = list @@ -3151,7 +3141,7 @@ fn static_assert() { }, _ => None, }; - longhands::transform::computed_value::T(result) + Transform(result.unwrap_or(vec!())) } ${impl_transition_time_value('delay', 'Delay')} diff --git a/components/style/properties/helpers/animated_properties.mako.rs b/components/style/properties/helpers/animated_properties.mako.rs index b7223d4b616..3c55416b178 100644 --- a/components/style/properties/helpers/animated_properties.mako.rs +++ b/components/style/properties/helpers/animated_properties.mako.rs @@ -18,9 +18,8 @@ use properties::longhands::font_weight::computed_value::T as FontWeight; use properties::longhands::font_stretch::computed_value::T as FontStretch; #[cfg(feature = "gecko")] use properties::longhands::font_variation_settings::computed_value::T as FontVariationSettings; -use properties::longhands::transform::computed_value::ComputedMatrix; -use properties::longhands::transform::computed_value::ComputedOperation as TransformOperation; -use properties::longhands::transform::computed_value::T as TransformList; +use properties::longhands::transform::computed_value::ComputedOperation as ComputedTransformOperation; +use properties::longhands::transform::computed_value::T as ComputedTransform; use properties::longhands::visibility::computed_value::T as Visibility; #[cfg(feature = "gecko")] use properties::PropertyId; @@ -28,7 +27,6 @@ use properties::{LonghandId, ShorthandId}; use selectors::parser::SelectorParseErrorKind; use servo_arc::Arc; use smallvec::SmallVec; -use std::borrow::Cow; use std::cmp; use std::fmt; #[cfg(feature = "gecko")] use hash::FnvHashMap; @@ -46,7 +44,8 @@ use values::computed::{LengthOrPercentageOrNone, MaxLength}; use values::computed::{NonNegativeNumber, Number, NumberOrPercentage, Percentage}; use values::computed::length::NonNegativeLengthOrPercentage; use values::computed::ToComputedValue; -use values::computed::transform::DirectionVector; +use values::computed::transform::{DirectionVector, Matrix3D}; +use values::generics::transform::{Transform, TransformOperation}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; #[cfg(feature = "gecko")] use values::generics::FontSettings as GenericFontSettings; #[cfg(feature = "gecko")] use values::generics::FontSettingTag as GenericFontSettingTag; @@ -1014,60 +1013,6 @@ impl ToAnimatedZero for ClipRect { fn to_animated_zero(&self) -> Result { Err(()) } } -/// Build an equivalent 'identity transform function list' based -/// on an existing transform list. -/// -impl ToAnimatedZero for TransformOperation { - fn to_animated_zero(&self) -> Result { - match *self { - TransformOperation::Matrix(..) => { - Ok(TransformOperation::Matrix(ComputedMatrix::identity())) - }, - TransformOperation::MatrixWithPercents(..) => { - // FIXME(nox): Should be MatrixWithPercents value. - Ok(TransformOperation::Matrix(ComputedMatrix::identity())) - }, - TransformOperation::Skew(sx, sy) => { - Ok(TransformOperation::Skew( - sx.to_animated_zero()?, - sy.to_animated_zero()?, - )) - }, - TransformOperation::Translate(ref tx, ref ty, ref tz) => { - Ok(TransformOperation::Translate( - tx.to_animated_zero()?, - ty.to_animated_zero()?, - tz.to_animated_zero()?, - )) - }, - TransformOperation::Scale(..) => { - Ok(TransformOperation::Scale(1.0, 1.0, 1.0)) - }, - TransformOperation::Rotate(x, y, z, a) => { - let (x, y, z, _) = TransformList::get_normalized_vector_and_angle(x, y, z, a); - Ok(TransformOperation::Rotate(x, y, z, Angle::zero())) - }, - TransformOperation::Perspective(..) | - TransformOperation::AccumulateMatrix { .. } | - TransformOperation::InterpolateMatrix { .. } => { - // Perspective: We convert a perspective function into an equivalent - // ComputedMatrix, and then decompose/interpolate/recompose these matrices. - // AccumulateMatrix/InterpolateMatrix: We do interpolation on - // AccumulateMatrix/InterpolateMatrix by reading it as a ComputedMatrix - // (with layout information), and then do matrix interpolation. - // - // Therefore, we use an identity matrix to represent the identity transform list. - // http://dev.w3.org/csswg/css-transforms/#identity-transform-function - // - // FIXME(nox): This does not actually work, given the impl of - // Animate for TransformOperation bails out if the two given - // values are dissimilar. - Ok(TransformOperation::Matrix(ComputedMatrix::identity())) - }, - } - } -} - fn animate_multiplicative_factor( this: CSSFloat, other: CSSFloat, @@ -1077,14 +1022,14 @@ fn animate_multiplicative_factor( } /// -impl Animate for TransformOperation { +impl Animate for ComputedTransformOperation { fn animate(&self, other: &Self, procedure: Procedure) -> Result { match (self, other) { ( - &TransformOperation::Matrix(ref this), - &TransformOperation::Matrix(ref other), + &TransformOperation::Matrix3D(ref this), + &TransformOperation::Matrix3D(ref other), ) => { - Ok(TransformOperation::Matrix( + Ok(TransformOperation::Matrix3D( this.animate(other, procedure)?, )) }, @@ -1098,40 +1043,40 @@ impl Animate for TransformOperation { )) }, ( - &TransformOperation::Translate(ref fx, ref fy, ref fz), - &TransformOperation::Translate(ref tx, ref ty, ref tz), + &TransformOperation::Translate3D(ref fx, ref fy, ref fz), + &TransformOperation::Translate3D(ref tx, ref ty, ref tz), ) => { - Ok(TransformOperation::Translate( + Ok(TransformOperation::Translate3D( fx.animate(tx, procedure)?, fy.animate(ty, procedure)?, fz.animate(tz, procedure)?, )) }, ( - &TransformOperation::Scale(ref fx, ref fy, ref fz), - &TransformOperation::Scale(ref tx, ref ty, ref tz), + &TransformOperation::Scale3D(ref fx, ref fy, ref fz), + &TransformOperation::Scale3D(ref tx, ref ty, ref tz), ) => { - Ok(TransformOperation::Scale( + Ok(TransformOperation::Scale3D( animate_multiplicative_factor(*fx, *tx, procedure)?, animate_multiplicative_factor(*fy, *ty, procedure)?, animate_multiplicative_factor(*fz, *tz, procedure)?, )) }, ( - &TransformOperation::Rotate(fx, fy, fz, fa), - &TransformOperation::Rotate(tx, ty, tz, ta), + &TransformOperation::Rotate3D(fx, fy, fz, fa), + &TransformOperation::Rotate3D(tx, ty, tz, ta), ) => { let (fx, fy, fz, fa) = - TransformList::get_normalized_vector_and_angle(fx, fy, fz, fa); + ComputedTransform::get_normalized_vector_and_angle(fx, fy, fz, fa); let (tx, ty, tz, ta) = - TransformList::get_normalized_vector_and_angle(tx, ty, tz, ta); + ComputedTransform::get_normalized_vector_and_angle(tx, ty, tz, ta); if (fx, fy, fz) == (tx, ty, tz) { let ia = fa.animate(&ta, procedure)?; - Ok(TransformOperation::Rotate(fx, fy, fz, ia)) + Ok(TransformOperation::Rotate3D(fx, fy, fz, ia)) } else { let matrix_f = rotate_to_matrix(fx, fy, fz, fa); let matrix_t = rotate_to_matrix(tx, ty, tz, ta); - Ok(TransformOperation::Matrix( + Ok(TransformOperation::Matrix3D( matrix_f.animate(&matrix_t, procedure)?, )) } @@ -1140,15 +1085,15 @@ impl Animate for TransformOperation { &TransformOperation::Perspective(ref fd), &TransformOperation::Perspective(ref td), ) => { - let mut fd_matrix = ComputedMatrix::identity(); - let mut td_matrix = ComputedMatrix::identity(); + let mut fd_matrix = Matrix3D::identity(); + let mut td_matrix = Matrix3D::identity(); if fd.px() > 0. { fd_matrix.m34 = -1. / fd.px(); } if td.px() > 0. { td_matrix.m34 = -1. / td.px(); } - Ok(TransformOperation::Matrix( + Ok(TransformOperation::Matrix3D( fd_matrix.animate(&td_matrix, procedure)?, )) }, @@ -1157,12 +1102,12 @@ impl Animate for TransformOperation { } } -fn is_matched_operation(first: &TransformOperation, second: &TransformOperation) -> bool { +fn is_matched_operation(first: &ComputedTransformOperation, second: &ComputedTransformOperation) -> bool { match (first, second) { (&TransformOperation::Matrix(..), &TransformOperation::Matrix(..)) | - (&TransformOperation::MatrixWithPercents(..), - &TransformOperation::MatrixWithPercents(..)) | + (&TransformOperation::PrefixedMatrix(..), + &TransformOperation::PrefixedMatrix(..)) | (&TransformOperation::Skew(..), &TransformOperation::Skew(..)) | (&TransformOperation::Translate(..), @@ -1179,12 +1124,12 @@ fn is_matched_operation(first: &TransformOperation, second: &TransformOperation) } /// -fn rotate_to_matrix(x: f32, y: f32, z: f32, a: Angle) -> ComputedMatrix { +fn rotate_to_matrix(x: f32, y: f32, z: f32, a: Angle) -> Matrix3D { let half_rad = a.radians() / 2.0; let sc = (half_rad).sin() * (half_rad).cos(); let sq = (half_rad).sin().powi(2); - ComputedMatrix { + Matrix3D { m11: 1.0 - 2.0 * (y * y + z * z) * sq, m12: 2.0 * (x * y * sq + z * sc), m13: 2.0 * (x * z * sq - y * sc), @@ -1214,7 +1159,7 @@ fn rotate_to_matrix(x: f32, y: f32, z: f32, a: Angle) -> ComputedMatrix { // FIXME: We use custom derive for ComputeSquaredDistance. However, If possible, we should convert // the InnerMatrix2D into types with physical meaning. This custom derive computes the squared // distance from each matrix item, and this makes the result different from that in Gecko if we -// have skew factor in the ComputedMatrix. +// have skew factor in the Matrix3D. pub struct InnerMatrix2D { pub m11: CSSFloat, pub m12: CSSFloat, pub m21: CSSFloat, pub m22: CSSFloat, @@ -1324,7 +1269,7 @@ impl ComputeSquaredDistance for MatrixDecomposed2D { } } -impl Animate for ComputedMatrix { +impl Animate for Matrix3D { #[cfg(feature = "servo")] fn animate(&self, other: &Self, procedure: Procedure) -> Result { if self.is_3d() || other.is_3d() { @@ -1332,7 +1277,7 @@ impl Animate for ComputedMatrix { let decomposed_to = decompose_3d_matrix(*other); match (decomposed_from, decomposed_to) { (Ok(this), Ok(other)) => { - Ok(ComputedMatrix::from(this.animate(&other, procedure)?)) + Ok(Matrix3D::from(this.animate(&other, procedure)?)) }, // Matrices can be undecomposable due to couple reasons, e.g., // non-invertible matrices. In this case, we should report Err @@ -1342,7 +1287,7 @@ impl Animate for ComputedMatrix { } else { let this = MatrixDecomposed2D::from(*self); let other = MatrixDecomposed2D::from(*other); - Ok(ComputedMatrix::from(this.animate(&other, procedure)?)) + Ok(Matrix3D::from(this.animate(&other, procedure)?)) } } @@ -1355,7 +1300,7 @@ impl Animate for ComputedMatrix { }; match (from, to) { (Ok(from), Ok(to)) => { - Ok(ComputedMatrix::from(from.animate(&to, procedure)?)) + Ok(Matrix3D::from(from.animate(&to, procedure)?)) }, // Matrices can be undecomposable due to couple reasons, e.g., // non-invertible matrices. In this case, we should report Err here, @@ -1365,7 +1310,7 @@ impl Animate for ComputedMatrix { } } -impl ComputeSquaredDistance for ComputedMatrix { +impl ComputeSquaredDistance for Matrix3D { #[inline] #[cfg(feature = "servo")] fn compute_squared_distance(&self, other: &Self) -> Result { @@ -1392,10 +1337,10 @@ impl ComputeSquaredDistance for ComputedMatrix { } } -impl From for MatrixDecomposed2D { +impl From for MatrixDecomposed2D { /// Decompose a 2D matrix. /// - fn from(matrix: ComputedMatrix) -> MatrixDecomposed2D { + fn from(matrix: Matrix3D) -> MatrixDecomposed2D { let mut row0x = matrix.m11; let mut row0y = matrix.m12; let mut row1x = matrix.m21; @@ -1456,11 +1401,11 @@ impl From for MatrixDecomposed2D { } } -impl From for ComputedMatrix { +impl From for Matrix3D { /// Recompose a 2D matrix. /// - fn from(decomposed: MatrixDecomposed2D) -> ComputedMatrix { - let mut computed_matrix = ComputedMatrix::identity(); + fn from(decomposed: MatrixDecomposed2D) -> Matrix3D { + let mut computed_matrix = Matrix3D::identity(); computed_matrix.m11 = decomposed.matrix.m11; computed_matrix.m12 = decomposed.matrix.m12; computed_matrix.m21 = decomposed.matrix.m21; @@ -1475,7 +1420,7 @@ impl From for ComputedMatrix { let cos_angle = angle.cos(); let sin_angle = angle.sin(); - let mut rotate_matrix = ComputedMatrix::identity(); + let mut rotate_matrix = Matrix3D::identity(); rotate_matrix.m11 = cos_angle; rotate_matrix.m12 = sin_angle; rotate_matrix.m21 = -sin_angle; @@ -1494,9 +1439,9 @@ impl From for ComputedMatrix { } #[cfg(feature = "gecko")] -impl<'a> From< &'a RawGeckoGfxMatrix4x4> for ComputedMatrix { - fn from(m: &'a RawGeckoGfxMatrix4x4) -> ComputedMatrix { - ComputedMatrix { +impl<'a> From< &'a RawGeckoGfxMatrix4x4> for Matrix3D { + fn from(m: &'a RawGeckoGfxMatrix4x4) -> Matrix3D { + Matrix3D { m11: m[0], m12: m[1], m13: m[2], m14: m[3], m21: m[4], m22: m[5], m23: m[6], m24: m[7], m31: m[8], m32: m[9], m33: m[10], m34: m[11], @@ -1506,8 +1451,8 @@ impl<'a> From< &'a RawGeckoGfxMatrix4x4> for ComputedMatrix { } #[cfg(feature = "gecko")] -impl From for RawGeckoGfxMatrix4x4 { - fn from(matrix: ComputedMatrix) -> RawGeckoGfxMatrix4x4 { +impl From for RawGeckoGfxMatrix4x4 { + fn from(matrix: Matrix3D) -> RawGeckoGfxMatrix4x4 { [ matrix.m11, matrix.m12, matrix.m13, matrix.m14, matrix.m21, matrix.m22, matrix.m23, matrix.m24, matrix.m31, matrix.m32, matrix.m33, matrix.m34, @@ -1597,7 +1542,7 @@ impl ComputeSquaredDistance for Quaternion { /// Decompose a 3D matrix. /// -fn decompose_3d_matrix(mut matrix: ComputedMatrix) -> Result { +fn decompose_3d_matrix(mut matrix: Matrix3D) -> Result { // Normalize the matrix. if matrix.m44 == 0.0 { return Err(()); @@ -1635,7 +1580,7 @@ fn decompose_3d_matrix(mut matrix: ComputedMatrix) -> Result Result Result { +fn decompose_2d_matrix(matrix: &Matrix3D) -> Result { // The index is column-major, so the equivalent transform matrix is: // | m11 m21 0 m41 | => | m11 m21 | and translate(m41, m42) // | m12 m22 0 m42 | | m12 m22 | @@ -1928,11 +1873,11 @@ impl Animate for MatrixDecomposed3D { } } -impl From for ComputedMatrix { +impl From for Matrix3D { /// Recompose a 3D matrix. /// - fn from(decomposed: MatrixDecomposed3D) -> ComputedMatrix { - let mut matrix = ComputedMatrix::identity(); + fn from(decomposed: MatrixDecomposed3D) -> Matrix3D { + let mut matrix = Matrix3D::identity(); // Apply perspective % for i in range(1, 5): @@ -1954,7 +1899,7 @@ impl From for ComputedMatrix { // Construct a composite rotation matrix from the quaternion values // rotationMatrix is a identity 4x4 matrix initially - let mut rotation_matrix = ComputedMatrix::identity(); + let mut rotation_matrix = Matrix3D::identity(); rotation_matrix.m11 = 1.0 - 2.0 * (y * y + z * z) as f32; rotation_matrix.m12 = 2.0 * (x * y + z * w) as f32; rotation_matrix.m13 = 2.0 * (x * z - y * w) as f32; @@ -1968,7 +1913,7 @@ impl From for ComputedMatrix { matrix = multiply(rotation_matrix, matrix); // Apply skew - let mut temp = ComputedMatrix::identity(); + let mut temp = Matrix3D::identity(); if decomposed.skew.2 != 0.0 { temp.m32 = decomposed.skew.2; matrix = multiply(temp, matrix); @@ -1998,7 +1943,7 @@ impl From for ComputedMatrix { } // Multiplication of two 4x4 matrices. -fn multiply(a: ComputedMatrix, b: ComputedMatrix) -> ComputedMatrix { +fn multiply(a: Matrix3D, b: Matrix3D) -> Matrix3D { let mut a_clone = a; % for i in range(1, 5): % for j in range(1, 5): @@ -2011,7 +1956,7 @@ fn multiply(a: ComputedMatrix, b: ComputedMatrix) -> ComputedMatrix { a_clone } -impl ComputedMatrix { +impl Matrix3D { fn is_3d(&self) -> bool { self.m13 != 0.0 || self.m14 != 0.0 || self.m23 != 0.0 || self.m24 != 0.0 || @@ -2046,7 +1991,7 @@ impl ComputedMatrix { self.m11 * self.m22 * self.m33 * self.m44 } - fn inverse(&self) -> Option { + fn inverse(&self) -> Option { let mut det = self.determinant(); if det == 0.0 { @@ -2054,7 +1999,7 @@ impl ComputedMatrix { } det = 1.0 / det; - let x = ComputedMatrix { + let x = Matrix3D { m11: det * (self.m23*self.m34*self.m42 - self.m24*self.m33*self.m42 + self.m24*self.m32*self.m43 - self.m22*self.m34*self.m43 - @@ -2126,43 +2071,29 @@ impl ComputedMatrix { } /// -impl Animate for TransformList { +impl Animate for ComputedTransform { #[inline] fn animate( &self, other: &Self, procedure: Procedure, ) -> Result { - if self.0.is_none() && other.0.is_none() { - return Ok(TransformList(None)); + if self.0.is_empty() && other.0.is_empty() { + return Ok(Transform(vec![])); } + + let this = &self.0; + let other = &other.0; + if procedure == Procedure::Add { - let this = self.0.as_ref().map_or(&[][..], |l| l); - let other = other.0.as_ref().map_or(&[][..], |l| l); let result = this.iter().chain(other).cloned().collect::>(); - return Ok(TransformList(if result.is_empty() { - None - } else { - Some(result) - })); + return Ok(Transform(result)); } - let this = if self.0.is_some() { - Cow::Borrowed(self) - } else { - Cow::Owned(other.to_animated_zero()?) - }; - let other = if other.0.is_some() { - Cow::Borrowed(other) - } else { - Cow::Owned(self.to_animated_zero()?) - }; // For matched transform lists. { - let this = (*this).0.as_ref().map_or(&[][..], |l| l); - let other = (*other).0.as_ref().map_or(&[][..], |l| l); if this.len() == other.len() { let is_matched_transforms = this.iter().zip(other).all(|(this, other)| { is_matched_operation(this, other) @@ -2173,11 +2104,7 @@ impl Animate for TransformList { this.animate(other, procedure) }).collect::, _>>(); if let Ok(list) = result { - return Ok(TransformList(if list.is_empty() { - None - } else { - Some(list) - })); + return Ok(Transform(list)); } // Can't animate for a pair of matched transform lists? @@ -2193,18 +2120,18 @@ impl Animate for TransformList { match procedure { Procedure::Add => Err(()), Procedure::Interpolate { progress } => { - Ok(TransformList(Some(vec![TransformOperation::InterpolateMatrix { - from_list: this.into_owned(), - to_list: other.into_owned(), + Ok(Transform(vec![TransformOperation::InterpolateMatrix { + from_list: Transform(this.clone()), + to_list: Transform(other.clone()), progress: Percentage(progress as f32), - }]))) + }])) }, Procedure::Accumulate { count } => { - Ok(TransformList(Some(vec![TransformOperation::AccumulateMatrix { - from_list: this.into_owned(), - to_list: other.into_owned(), + Ok(Transform(vec![TransformOperation::AccumulateMatrix { + from_list: Transform(this.clone()), + to_list: Transform(other.clone()), count: cmp::min(count, i32::max_value() as u64) as i32, - }]))) + }])) }, } } @@ -2214,12 +2141,12 @@ impl Animate for TransformList { // to trace the distance travelled by a point as its transform is interpolated between the two // lists. That, however, proves to be quite complicated so we take a simple approach for now. // See https://bugzilla.mozilla.org/show_bug.cgi?id=1318591#c0. -impl ComputeSquaredDistance for TransformOperation { +impl ComputeSquaredDistance for ComputedTransformOperation { fn compute_squared_distance(&self, other: &Self) -> Result { match (self, other) { ( - &TransformOperation::Matrix(ref this), - &TransformOperation::Matrix(ref other), + &TransformOperation::Matrix3D(ref this), + &TransformOperation::Matrix3D(ref other), ) => { this.compute_squared_distance(other) }, @@ -2233,8 +2160,8 @@ impl ComputeSquaredDistance for TransformOperation { ) }, ( - &TransformOperation::Translate(ref fx, ref fy, ref fz), - &TransformOperation::Translate(ref tx, ref ty, ref tz), + &TransformOperation::Translate3D(ref fx, ref fy, ref fz), + &TransformOperation::Translate3D(ref tx, ref ty, ref tz), ) => { // We don't want to require doing layout in order to calculate the result, so // drop the percentage part. However, dropping percentage makes us impossible to @@ -2262,8 +2189,8 @@ impl ComputeSquaredDistance for TransformOperation { ) }, ( - &TransformOperation::Scale(ref fx, ref fy, ref fz), - &TransformOperation::Scale(ref tx, ref ty, ref tz), + &TransformOperation::Scale3D(ref fx, ref fy, ref fz), + &TransformOperation::Scale3D(ref tx, ref ty, ref tz), ) => { Ok( fx.compute_squared_distance(&tx)? + @@ -2272,13 +2199,13 @@ impl ComputeSquaredDistance for TransformOperation { ) }, ( - &TransformOperation::Rotate(fx, fy, fz, fa), - &TransformOperation::Rotate(tx, ty, tz, ta), + &TransformOperation::Rotate3D(fx, fy, fz, fa), + &TransformOperation::Rotate3D(tx, ty, tz, ta), ) => { let (fx, fy, fz, angle1) = - TransformList::get_normalized_vector_and_angle(fx, fy, fz, fa); + ComputedTransform::get_normalized_vector_and_angle(fx, fy, fz, fa); let (tx, ty, tz, angle2) = - TransformList::get_normalized_vector_and_angle(tx, ty, tz, ta); + ComputedTransform::get_normalized_vector_and_angle(tx, ty, tz, ta); if (fx, fy, fz) == (tx, ty, tz) { angle1.compute_squared_distance(&angle2) } else { @@ -2293,8 +2220,8 @@ impl ComputeSquaredDistance for TransformOperation { &TransformOperation::Perspective(ref fd), &TransformOperation::Perspective(ref td), ) => { - let mut fd_matrix = ComputedMatrix::identity(); - let mut td_matrix = ComputedMatrix::identity(); + let mut fd_matrix = Matrix3D::identity(); + let mut td_matrix = Matrix3D::identity(); if fd.px() > 0. { fd_matrix.m34 = -1. / fd.px(); } @@ -2306,12 +2233,12 @@ impl ComputeSquaredDistance for TransformOperation { } ( &TransformOperation::Perspective(ref p), - &TransformOperation::Matrix(ref m), + &TransformOperation::Matrix3D(ref m), ) | ( - &TransformOperation::Matrix(ref m), + &TransformOperation::Matrix3D(ref m), &TransformOperation::Perspective(ref p), ) => { - let mut p_matrix = ComputedMatrix::identity(); + let mut p_matrix = Matrix3D::identity(); if p.px() > 0. { p_matrix.m34 = -1. / p.px(); } @@ -2322,11 +2249,11 @@ impl ComputeSquaredDistance for TransformOperation { } } -impl ComputeSquaredDistance for TransformList { +impl ComputeSquaredDistance for ComputedTransform { #[inline] fn compute_squared_distance(&self, other: &Self) -> Result { - let list1 = self.0.as_ref().map_or(&[][..], |l| l); - let list2 = other.0.as_ref().map_or(&[][..], |l| l); + let list1 = &self.0; + let list2 = &other.0; let squared_dist: Result = list1.iter().zip_longest(list2).map(|it| { match it { @@ -2342,28 +2269,14 @@ impl ComputeSquaredDistance for TransformList { // Roll back to matrix interpolation if there is any Err(()) in the transform lists, such // as mismatched transform functions. if let Err(_) = squared_dist { - let matrix1: ComputedMatrix = self.to_transform_3d_matrix(None).ok_or(())?.into(); - let matrix2: ComputedMatrix = other.to_transform_3d_matrix(None).ok_or(())?.into(); + let matrix1: Matrix3D = self.to_transform_3d_matrix(None).ok_or(())?.into(); + let matrix2: Matrix3D = other.to_transform_3d_matrix(None).ok_or(())?.into(); return matrix1.compute_squared_distance(&matrix2); } squared_dist } } -impl ToAnimatedZero for TransformList { - #[inline] - fn to_animated_zero(&self) -> Result { - match self.0 { - None => Ok(TransformList(None)), - Some(ref list) => { - Ok(TransformList(Some( - list.iter().map(|op| op.to_animated_zero()).collect::, _>>()? - ))) - }, - } - } -} - /// Animated SVGPaint pub type IntermediateSVGPaint = SVGPaint; diff --git a/components/style/properties/longhand/box.mako.rs b/components/style/properties/longhand/box.mako.rs index 71fcbabee3e..4d13abedf06 100644 --- a/components/style/properties/longhand/box.mako.rs +++ b/components/style/properties/longhand/box.mako.rs @@ -571,533 +571,28 @@ ${helpers.predefined_type( animation_value_type="ComputedValue" flags="CREATES_STACKING_CONTEXT FIXPOS_CB" spec="https://drafts.csswg.org/css-transforms/#propdef-transform"> - use values::computed::{LengthOrPercentageOrNumber as ComputedLoPoNumber, LengthOrNumber as ComputedLoN}; - use values::computed::{LengthOrPercentage as ComputedLoP, Length as ComputedLength}; - use values::generics::transform::Matrix; - use values::specified::{Angle, Integer, Length, LengthOrPercentage}; - use values::specified::{LengthOrNumber, LengthOrPercentageOrNumber as LoPoNumber, Number}; - use style_traits::ToCss; + use values::generics::transform::Transform; - use std::fmt; pub mod computed_value { - use values::CSSFloat; - use values::computed; - use values::computed::{Length, LengthOrPercentage}; - - #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)] - pub struct ComputedMatrix { - pub m11: CSSFloat, pub m12: CSSFloat, pub m13: CSSFloat, pub m14: CSSFloat, - pub m21: CSSFloat, pub m22: CSSFloat, pub m23: CSSFloat, pub m24: CSSFloat, - pub m31: CSSFloat, pub m32: CSSFloat, pub m33: CSSFloat, pub m34: CSSFloat, - pub m41: CSSFloat, pub m42: CSSFloat, pub m43: CSSFloat, pub m44: CSSFloat, - } - - #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)] - pub struct ComputedMatrixWithPercents { - pub m11: CSSFloat, pub m12: CSSFloat, pub m13: CSSFloat, pub m14: CSSFloat, - pub m21: CSSFloat, pub m22: CSSFloat, pub m23: CSSFloat, pub m24: CSSFloat, - pub m31: CSSFloat, pub m32: CSSFloat, pub m33: CSSFloat, pub m34: CSSFloat, - pub m41: LengthOrPercentage, pub m42: LengthOrPercentage, - pub m43: Length, pub m44: CSSFloat, - } - - impl ComputedMatrix { - pub fn identity() -> ComputedMatrix { - ComputedMatrix { - m11: 1.0, m12: 0.0, m13: 0.0, m14: 0.0, - m21: 0.0, m22: 1.0, m23: 0.0, m24: 0.0, - m31: 0.0, m32: 0.0, m33: 1.0, m34: 0.0, - m41: 0.0, m42: 0.0, m43: 0.0, m44: 1.0 - } - } - } - - impl ComputedMatrixWithPercents { - pub fn identity() -> ComputedMatrixWithPercents { - ComputedMatrixWithPercents { - m11: 1.0, m12: 0.0, m13: 0.0, m14: 0.0, - m21: 0.0, m22: 1.0, m23: 0.0, m24: 0.0, - m31: 0.0, m32: 0.0, m33: 1.0, m34: 0.0, - m41: LengthOrPercentage::zero(), m42: LengthOrPercentage::zero(), - m43: Length::new(0.), m44: 1.0 - } - } - } - - #[derive(Clone, Debug, MallocSizeOf, PartialEq)] - pub enum ComputedOperation { - Matrix(ComputedMatrix), - // For `-moz-transform` matrix and matrix3d. - MatrixWithPercents(ComputedMatrixWithPercents), - Skew(computed::Angle, computed::Angle), - Translate(computed::LengthOrPercentage, - computed::LengthOrPercentage, - computed::Length), - Scale(CSSFloat, CSSFloat, CSSFloat), - Rotate(CSSFloat, CSSFloat, CSSFloat, computed::Angle), - Perspective(computed::Length), - // For mismatched transform lists. - // A vector of |ComputedOperation| could contain an |InterpolateMatrix| and other - // |ComputedOperation|s, and multiple nested |InterpolateMatrix|s is acceptable. - // e.g. - // [ InterpolateMatrix { from_list: [ InterpolateMatrix { ... }, - // Scale(...) ], - // to_list: [ AccumulateMatrix { from_list: ..., - // to_list: [ InterpolateMatrix, - // ... ], - // count: ... } ], - // progress: ... } ] - InterpolateMatrix { from_list: T, - to_list: T, - progress: computed::Percentage }, - // For accumulate operation of mismatched transform lists. - AccumulateMatrix { from_list: T, - to_list: T, - count: computed::Integer }, - } - - #[derive(Clone, Debug, MallocSizeOf, PartialEq)] - pub struct T(pub Option>); + pub use values::computed::transform::Transform as T; + pub use values::computed::transform::TransformOperation as ComputedOperation; } - /// Describes a single parsed - /// [Transform Function](https://drafts.csswg.org/css-transforms/#typedef-transform-function). - /// - /// Multiple transform functions compose a transformation. - /// - /// Some transformations can be expressed by other more general functions. - #[derive(Clone, Debug, MallocSizeOf, PartialEq)] - pub enum SpecifiedOperation { - /// Represents a 2D 2x3 matrix. - Matrix(Matrix), - /// Represents a 3D 4x4 matrix with percentage and length values. - /// For `moz-transform`. - PrefixedMatrix(Matrix), - /// Represents a 3D 4x4 matrix. - Matrix3D { - m11: Number, m12: Number, m13: Number, m14: Number, - m21: Number, m22: Number, m23: Number, m24: Number, - m31: Number, m32: Number, m33: Number, m34: Number, - m41: Number, m42: Number, m43: Number, m44: Number, - }, - /// Represents a 3D 4x4 matrix with percentage and length values. - /// For `moz-transform`. - PrefixedMatrix3D { - m11: Number, m12: Number, m13: Number, m14: Number, - m21: Number, m22: Number, m23: Number, m24: Number, - m31: Number, m32: Number, m33: Number, m34: Number, - m41: LoPoNumber, m42: LoPoNumber, m43: LengthOrNumber, m44: Number, - }, - /// A 2D skew. - /// - /// If the second angle is not provided it is assumed zero. - Skew(Angle, Option), - SkewX(Angle), - SkewY(Angle), - Translate(LengthOrPercentage, Option), - TranslateX(LengthOrPercentage), - TranslateY(LengthOrPercentage), - TranslateZ(Length), - Translate3D(LengthOrPercentage, LengthOrPercentage, Length), - /// A 2D scaling factor. - /// - /// `scale(2)` is parsed as `Scale(Number::new(2.0), None)` and is equivalent to - /// writing `scale(2, 2)` (`Scale(Number::new(2.0), Some(Number::new(2.0)))`). - /// - /// Negative values are allowed and flip the element. - Scale(Number, Option), - ScaleX(Number), - ScaleY(Number), - ScaleZ(Number), - Scale3D(Number, Number, Number), - /// Describes a 2D Rotation. - /// - /// In a 3D scene `rotate(angle)` is equivalent to `rotateZ(angle)`. - Rotate(Angle), - /// Rotation in 3D space around the x-axis. - RotateX(Angle), - /// Rotation in 3D space around the y-axis. - RotateY(Angle), - /// Rotation in 3D space around the z-axis. - RotateZ(Angle), - /// Rotation in 3D space. - /// - /// Generalization of rotateX, rotateY and rotateZ. - Rotate3D(Number, Number, Number, Angle), - /// Specifies a perspective projection matrix. - /// - /// Part of CSS Transform Module Level 2 and defined at - /// [§ 13.1. 3D Transform Function](https://drafts.csswg.org/css-transforms-2/#funcdef-perspective). - /// - /// The value must be greater than or equal to zero. - Perspective(specified::Length), - /// A intermediate type for interpolation of mismatched transform lists. - InterpolateMatrix { from_list: SpecifiedValue, - to_list: SpecifiedValue, - progress: computed::Percentage }, - /// A intermediate type for accumulation of mismatched transform lists. - AccumulateMatrix { from_list: SpecifiedValue, - to_list: SpecifiedValue, - count: Integer }, - } - - impl ToCss for computed_value::T { - fn to_css(&self, _: &mut W) -> fmt::Result where W: fmt::Write { - // TODO(pcwalton) - Ok(()) - } - } - - impl ToCss for SpecifiedOperation { - fn to_css(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { - match *self { - SpecifiedOperation::Matrix(ref m) => m.to_css(dest), - SpecifiedOperation::PrefixedMatrix(ref m) => m.to_css(dest), - SpecifiedOperation::Matrix3D { - m11, m12, m13, m14, - m21, m22, m23, m24, - m31, m32, m33, m34, - m41, m42, m43, m44, - } => { - serialize_function!(dest, matrix3d( - m11, m12, m13, m14, - m21, m22, m23, m24, - m31, m32, m33, m34, - m41, m42, m43, m44, - )) - } - SpecifiedOperation::PrefixedMatrix3D { - m11, m12, m13, m14, - m21, m22, m23, m24, - m31, m32, m33, m34, - ref m41, ref m42, ref m43, m44, - } => { - serialize_function!(dest, matrix3d( - m11, m12, m13, m14, - m21, m22, m23, m24, - m31, m32, m33, m34, - m41, m42, m43, m44, - )) - } - SpecifiedOperation::Skew(ax, None) => { - serialize_function!(dest, skew(ax)) - } - SpecifiedOperation::Skew(ax, Some(ay)) => { - serialize_function!(dest, skew(ax, ay)) - } - SpecifiedOperation::SkewX(angle) => { - serialize_function!(dest, skewX(angle)) - } - SpecifiedOperation::SkewY(angle) => { - serialize_function!(dest, skewY(angle)) - } - SpecifiedOperation::Translate(ref tx, None) => { - serialize_function!(dest, translate(tx)) - } - SpecifiedOperation::Translate(ref tx, Some(ref ty)) => { - serialize_function!(dest, translate(tx, ty)) - } - SpecifiedOperation::TranslateX(ref tx) => { - serialize_function!(dest, translateX(tx)) - } - SpecifiedOperation::TranslateY(ref ty) => { - serialize_function!(dest, translateY(ty)) - } - SpecifiedOperation::TranslateZ(ref tz) => { - serialize_function!(dest, translateZ(tz)) - } - SpecifiedOperation::Translate3D(ref tx, ref ty, ref tz) => { - serialize_function!(dest, translate3d(tx, ty, tz)) - } - SpecifiedOperation::Scale(factor, None) => { - serialize_function!(dest, scale(factor)) - } - SpecifiedOperation::Scale(sx, Some(sy)) => { - serialize_function!(dest, scale(sx, sy)) - } - SpecifiedOperation::ScaleX(sx) => { - serialize_function!(dest, scaleX(sx)) - } - SpecifiedOperation::ScaleY(sy) => { - serialize_function!(dest, scaleY(sy)) - } - SpecifiedOperation::ScaleZ(sz) => { - serialize_function!(dest, scaleZ(sz)) - } - SpecifiedOperation::Scale3D(sx, sy, sz) => { - serialize_function!(dest, scale3d(sx, sy, sz)) - } - SpecifiedOperation::Rotate(theta) => { - serialize_function!(dest, rotate(theta)) - } - SpecifiedOperation::RotateX(theta) => { - serialize_function!(dest, rotateX(theta)) - } - SpecifiedOperation::RotateY(theta) => { - serialize_function!(dest, rotateY(theta)) - } - SpecifiedOperation::RotateZ(theta) => { - serialize_function!(dest, rotateZ(theta)) - } - SpecifiedOperation::Rotate3D(x, y, z, theta) => { - serialize_function!(dest, rotate3d(x, y, z, theta)) - } - SpecifiedOperation::Perspective(ref length) => { - serialize_function!(dest, perspective(length)) - } - SpecifiedOperation::InterpolateMatrix { ref from_list, ref to_list, progress } => { - serialize_function!(dest, interpolatematrix(from_list, to_list, progress)) - } - SpecifiedOperation::AccumulateMatrix { ref from_list, ref to_list, count } => { - serialize_function!(dest, accumulatematrix(from_list, to_list, count)) - } - } - } - } - - #[derive(Clone, Debug, MallocSizeOf, PartialEq)] - pub struct SpecifiedValue(Vec); - - impl ToCss for SpecifiedValue { - fn to_css(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { - - if self.0.is_empty() { - return dest.write_str("none") - } - - let mut first = true; - for operation in &self.0 { - if !first { - dest.write_str(" ")?; - } - first = false; - operation.to_css(dest)? - } - Ok(()) - } - } + pub use values::specified::transform::Transform as SpecifiedValue; + pub use values::specified::transform::TransformOperation as SpecifiedOperation; #[inline] pub fn get_initial_value() -> computed_value::T { - computed_value::T(None) + Transform(vec![]) } - // Allow unitless zero angle for rotate() and skew() to align with gecko - fn parse_internal<'i, 't>( - context: &ParserContext, - input: &mut Parser<'i, 't>, - prefixed: bool, - ) -> Result> { - use style_traits::{Separator, Space}; - - if input.try(|input| input.expect_ident_matching("none")).is_ok() { - return Ok(SpecifiedValue(Vec::new())) - } - - Ok(SpecifiedValue(Space::parse(input, |input| { - let function = input.expect_function()?.clone(); - input.parse_nested_block(|input| { - let result = match_ignore_ascii_case! { &function, - "matrix" => { - let a = specified::parse_number(context, input)?; - input.expect_comma()?; - let b = specified::parse_number(context, input)?; - input.expect_comma()?; - let c = specified::parse_number(context, input)?; - input.expect_comma()?; - let d = specified::parse_number(context, input)?; - input.expect_comma()?; - if !prefixed { - // Standard matrix parsing. - let e = specified::parse_number(context, input)?; - input.expect_comma()?; - let f = specified::parse_number(context, input)?; - Ok(SpecifiedOperation::Matrix(Matrix { a, b, c, d, e, f })) - } else { - // Non-standard prefixed matrix parsing for -moz-transform. - let e = LoPoNumber::parse(context, input)?; - input.expect_comma()?; - let f = LoPoNumber::parse(context, input)?; - Ok(SpecifiedOperation::PrefixedMatrix(Matrix { a, b, c, d, e, f })) - } - }, - "matrix3d" => { - let m11 = specified::parse_number(context, input)?; - input.expect_comma()?; - let m12 = specified::parse_number(context, input)?; - input.expect_comma()?; - let m13 = specified::parse_number(context, input)?; - input.expect_comma()?; - let m14 = specified::parse_number(context, input)?; - input.expect_comma()?; - let m21 = specified::parse_number(context, input)?; - input.expect_comma()?; - let m22 = specified::parse_number(context, input)?; - input.expect_comma()?; - let m23 = specified::parse_number(context, input)?; - input.expect_comma()?; - let m24 = specified::parse_number(context, input)?; - input.expect_comma()?; - let m31 = specified::parse_number(context, input)?; - input.expect_comma()?; - let m32 = specified::parse_number(context, input)?; - input.expect_comma()?; - let m33 = specified::parse_number(context, input)?; - input.expect_comma()?; - let m34 = specified::parse_number(context, input)?; - input.expect_comma()?; - if !prefixed { - // Standard matrix3d parsing. - let m41 = specified::parse_number(context, input)?; - input.expect_comma()?; - let m42 = specified::parse_number(context, input)?; - input.expect_comma()?; - let m43 = specified::parse_number(context, input)?; - input.expect_comma()?; - let m44 = specified::parse_number(context, input)?; - Ok(SpecifiedOperation::Matrix3D { - m11, m12, m13, m14, - m21, m22, m23, m24, - m31, m32, m33, m34, - m41, m42, m43, m44, - }) - } else { - // Non-standard prefixed matrix parsing for -moz-transform. - let m41 = LoPoNumber::parse(context, input)?; - input.expect_comma()?; - let m42 = LoPoNumber::parse(context, input)?; - input.expect_comma()?; - let m43 = LengthOrNumber::parse(context, input)?; - input.expect_comma()?; - let m44 = specified::parse_number(context, input)?; - Ok(SpecifiedOperation::PrefixedMatrix3D { - m11, m12, m13, m14, - m21, m22, m23, m24, - m31, m32, m33, m34, - m41, m42, m43, m44, - }) - } - }, - "translate" => { - let sx = specified::LengthOrPercentage::parse(context, input)?; - if input.try(|input| input.expect_comma()).is_ok() { - let sy = specified::LengthOrPercentage::parse(context, input)?; - Ok(SpecifiedOperation::Translate(sx, Some(sy))) - } else { - Ok(SpecifiedOperation::Translate(sx, None)) - } - }, - "translatex" => { - let tx = specified::LengthOrPercentage::parse(context, input)?; - Ok(SpecifiedOperation::TranslateX(tx)) - }, - "translatey" => { - let ty = specified::LengthOrPercentage::parse(context, input)?; - Ok(SpecifiedOperation::TranslateY(ty)) - }, - "translatez" => { - let tz = specified::Length::parse(context, input)?; - Ok(SpecifiedOperation::TranslateZ(tz)) - }, - "translate3d" => { - let tx = specified::LengthOrPercentage::parse(context, input)?; - input.expect_comma()?; - let ty = specified::LengthOrPercentage::parse(context, input)?; - input.expect_comma()?; - let tz = specified::Length::parse(context, input)?; - Ok(SpecifiedOperation::Translate3D(tx, ty, tz)) - }, - "scale" => { - let sx = specified::parse_number(context, input)?; - if input.try(|input| input.expect_comma()).is_ok() { - let sy = specified::parse_number(context, input)?; - Ok(SpecifiedOperation::Scale(sx, Some(sy))) - } else { - Ok(SpecifiedOperation::Scale(sx, None)) - } - }, - "scalex" => { - let sx = specified::parse_number(context, input)?; - Ok(SpecifiedOperation::ScaleX(sx)) - }, - "scaley" => { - let sy = specified::parse_number(context, input)?; - Ok(SpecifiedOperation::ScaleY(sy)) - }, - "scalez" => { - let sz = specified::parse_number(context, input)?; - Ok(SpecifiedOperation::ScaleZ(sz)) - }, - "scale3d" => { - let sx = specified::parse_number(context, input)?; - input.expect_comma()?; - let sy = specified::parse_number(context, input)?; - input.expect_comma()?; - let sz = specified::parse_number(context, input)?; - Ok(SpecifiedOperation::Scale3D(sx, sy, sz)) - }, - "rotate" => { - let theta = specified::Angle::parse_with_unitless(context, input)?; - Ok(SpecifiedOperation::Rotate(theta)) - }, - "rotatex" => { - let theta = specified::Angle::parse_with_unitless(context, input)?; - Ok(SpecifiedOperation::RotateX(theta)) - }, - "rotatey" => { - let theta = specified::Angle::parse_with_unitless(context, input)?; - Ok(SpecifiedOperation::RotateY(theta)) - }, - "rotatez" => { - let theta = specified::Angle::parse_with_unitless(context, input)?; - Ok(SpecifiedOperation::RotateZ(theta)) - }, - "rotate3d" => { - let ax = specified::parse_number(context, input)?; - input.expect_comma()?; - let ay = specified::parse_number(context, input)?; - input.expect_comma()?; - let az = specified::parse_number(context, input)?; - input.expect_comma()?; - let theta = specified::Angle::parse_with_unitless(context, input)?; - // TODO(gw): Check that the axis can be normalized. - Ok(SpecifiedOperation::Rotate3D(ax, ay, az, theta)) - }, - "skew" => { - let ax = specified::Angle::parse_with_unitless(context, input)?; - if input.try(|input| input.expect_comma()).is_ok() { - let ay = specified::Angle::parse_with_unitless(context, input)?; - Ok(SpecifiedOperation::Skew(ax, Some(ay))) - } else { - Ok(SpecifiedOperation::Skew(ax, None)) - } - }, - "skewx" => { - let theta = specified::Angle::parse_with_unitless(context, input)?; - Ok(SpecifiedOperation::SkewX(theta)) - }, - "skewy" => { - let theta = specified::Angle::parse_with_unitless(context, input)?; - Ok(SpecifiedOperation::SkewY(theta)) - }, - "perspective" => { - let d = specified::Length::parse_non_negative(context, input)?; - Ok(SpecifiedOperation::Perspective(d)) - }, - _ => Err(()), - }; - result - .map_err(|()| input.new_custom_error(StyleParseErrorKind::UnexpectedFunction(function.clone()))) - }) - })?)) - } /// Parses `transform` property. #[inline] pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result> { - parse_internal(context, input, false) + SpecifiedValue::parse_internal(context, input, false) } /// Parses `-moz-transform` property. This prefixed property also accepts LengthOrPercentage @@ -1105,341 +600,7 @@ ${helpers.predefined_type( #[inline] pub fn parse_prefixed<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result> { - parse_internal(context, input, true) - } - - impl ToComputedValue for SpecifiedValue { - type ComputedValue = computed_value::T; - - #[inline] - fn to_computed_value(&self, context: &Context) -> computed_value::T { - if self.0.is_empty() { - return computed_value::T(None) - } - - let mut result = vec!(); - for operation in &self.0 { - match *operation { - SpecifiedOperation::Matrix(Matrix { a, b, c, d, e, f }) => { - let mut comp = computed_value::ComputedMatrix::identity(); - comp.m11 = a.to_computed_value(context); - comp.m12 = b.to_computed_value(context); - comp.m21 = c.to_computed_value(context); - comp.m22 = d.to_computed_value(context); - comp.m41 = e.to_computed_value(context); - comp.m42 = f.to_computed_value(context); - result.push(computed_value::ComputedOperation::Matrix(comp)); - } - SpecifiedOperation::PrefixedMatrix(Matrix { a, b, c, d, ref e, ref f }) => { - let mut comp = computed_value::ComputedMatrixWithPercents::identity(); - comp.m11 = a.to_computed_value(context); - comp.m12 = b.to_computed_value(context); - comp.m21 = c.to_computed_value(context); - comp.m22 = d.to_computed_value(context); - comp.m41 = lopon_to_lop(&e.to_computed_value(context)); - comp.m42 = lopon_to_lop(&f.to_computed_value(context)); - result.push(computed_value::ComputedOperation::MatrixWithPercents(comp)); - } - SpecifiedOperation::Matrix3D { - m11, m12, m13, m14, - m21, m22, m23, m24, - m31, m32, m33, m34, - ref m41, ref m42, ref m43, m44 } => { - let comp = computed_value::ComputedMatrix { - m11: m11.to_computed_value(context), - m12: m12.to_computed_value(context), - m13: m13.to_computed_value(context), - m14: m14.to_computed_value(context), - m21: m21.to_computed_value(context), - m22: m22.to_computed_value(context), - m23: m23.to_computed_value(context), - m24: m24.to_computed_value(context), - m31: m31.to_computed_value(context), - m32: m32.to_computed_value(context), - m33: m33.to_computed_value(context), - m34: m34.to_computed_value(context), - m41: m41.to_computed_value(context), - m42: m42.to_computed_value(context), - m43: m43.to_computed_value(context), - m44: m44.to_computed_value(context), - }; - result.push(computed_value::ComputedOperation::Matrix(comp)); - } - SpecifiedOperation::PrefixedMatrix3D { - m11, m12, m13, m14, - m21, m22, m23, m24, - m31, m32, m33, m34, - ref m41, ref m42, ref m43, m44 } => { - let comp = computed_value::ComputedMatrixWithPercents { - m11: m11.to_computed_value(context), - m12: m12.to_computed_value(context), - m13: m13.to_computed_value(context), - m14: m14.to_computed_value(context), - m21: m21.to_computed_value(context), - m22: m22.to_computed_value(context), - m23: m23.to_computed_value(context), - m24: m24.to_computed_value(context), - m31: m31.to_computed_value(context), - m32: m32.to_computed_value(context), - m33: m33.to_computed_value(context), - m34: m34.to_computed_value(context), - m41: lopon_to_lop(&m41.to_computed_value(context)), - m42: lopon_to_lop(&m42.to_computed_value(context)), - m43: lon_to_length(&m43.to_computed_value(context)), - m44: m44.to_computed_value(context), - }; - result.push(computed_value::ComputedOperation::MatrixWithPercents(comp)); - } - SpecifiedOperation::Translate(ref tx, None) => { - let tx = tx.to_computed_value(context); - result.push(computed_value::ComputedOperation::Translate( - tx, - computed::length::LengthOrPercentage::zero(), - computed::length::Length::new(0.))); - } - SpecifiedOperation::Translate(ref tx, Some(ref ty)) => { - let tx = tx.to_computed_value(context); - let ty = ty.to_computed_value(context); - result.push(computed_value::ComputedOperation::Translate( - tx, - ty, - computed::length::Length::new(0.))); - } - SpecifiedOperation::TranslateX(ref tx) => { - let tx = tx.to_computed_value(context); - result.push(computed_value::ComputedOperation::Translate( - tx, - computed::length::LengthOrPercentage::zero(), - computed::length::Length::new(0.))); - } - SpecifiedOperation::TranslateY(ref ty) => { - let ty = ty.to_computed_value(context); - result.push(computed_value::ComputedOperation::Translate( - computed::length::LengthOrPercentage::zero(), - ty, - computed::length::Length::new(0.))); - } - SpecifiedOperation::TranslateZ(ref tz) => { - let tz = tz.to_computed_value(context); - result.push(computed_value::ComputedOperation::Translate( - computed::length::LengthOrPercentage::zero(), - computed::length::LengthOrPercentage::zero(), - tz)); - } - SpecifiedOperation::Translate3D(ref tx, ref ty, ref tz) => { - let tx = tx.to_computed_value(context); - let ty = ty.to_computed_value(context); - let tz = tz.to_computed_value(context); - result.push(computed_value::ComputedOperation::Translate(tx, ty, tz)); - } - SpecifiedOperation::Scale(factor, None) => { - let factor = factor.to_computed_value(context); - result.push(computed_value::ComputedOperation::Scale(factor, factor, 1.0)); - } - SpecifiedOperation::Scale(sx, Some(sy)) => { - let sx = sx.to_computed_value(context); - let sy = sy.to_computed_value(context); - result.push(computed_value::ComputedOperation::Scale(sx, sy, 1.0)); - } - SpecifiedOperation::ScaleX(sx) => { - let sx = sx.to_computed_value(context); - result.push(computed_value::ComputedOperation::Scale(sx, 1.0, 1.0)); - } - SpecifiedOperation::ScaleY(sy) => { - let sy = sy.to_computed_value(context); - result.push(computed_value::ComputedOperation::Scale(1.0, sy, 1.0)); - } - SpecifiedOperation::ScaleZ(sz) => { - let sz = sz.to_computed_value(context); - result.push(computed_value::ComputedOperation::Scale(1.0, 1.0, sz)); - } - SpecifiedOperation::Scale3D(sx, sy, sz) => { - let sx = sx.to_computed_value(context); - let sy = sy.to_computed_value(context); - let sz = sz.to_computed_value(context); - result.push(computed_value::ComputedOperation::Scale(sx, sy, sz)); - } - SpecifiedOperation::Rotate(theta) => { - let theta = theta.to_computed_value(context); - result.push(computed_value::ComputedOperation::Rotate(0.0, 0.0, 1.0, theta)); - } - SpecifiedOperation::RotateX(theta) => { - let theta = theta.to_computed_value(context); - result.push(computed_value::ComputedOperation::Rotate(1.0, 0.0, 0.0, theta)); - } - SpecifiedOperation::RotateY(theta) => { - let theta = theta.to_computed_value(context); - result.push(computed_value::ComputedOperation::Rotate(0.0, 1.0, 0.0, theta)); - } - SpecifiedOperation::RotateZ(theta) => { - let theta = theta.to_computed_value(context); - result.push(computed_value::ComputedOperation::Rotate(0.0, 0.0, 1.0, theta)); - } - SpecifiedOperation::Rotate3D(ax, ay, az, theta) => { - let ax = ax.to_computed_value(context); - let ay = ay.to_computed_value(context); - let az = az.to_computed_value(context); - let theta = theta.to_computed_value(context); - result.push(computed_value::ComputedOperation::Rotate(ax, ay, az, theta)); - } - SpecifiedOperation::Skew(theta_x, None) => { - let theta_x = theta_x.to_computed_value(context); - result.push(computed_value::ComputedOperation::Skew(theta_x, computed::Angle::zero())); - } - SpecifiedOperation::Skew(theta_x, Some(theta_y)) => { - let theta_x = theta_x.to_computed_value(context); - let theta_y = theta_y.to_computed_value(context); - result.push(computed_value::ComputedOperation::Skew(theta_x, theta_y)); - } - SpecifiedOperation::SkewX(theta_x) => { - let theta_x = theta_x.to_computed_value(context); - result.push(computed_value::ComputedOperation::Skew(theta_x, computed::Angle::zero())); - } - SpecifiedOperation::SkewY(theta_y) => { - let theta_y = theta_y.to_computed_value(context); - result.push(computed_value::ComputedOperation::Skew(computed::Angle::zero(), theta_y)); - } - SpecifiedOperation::Perspective(ref d) => { - result.push(computed_value::ComputedOperation::Perspective(d.to_computed_value(context))); - } - SpecifiedOperation::InterpolateMatrix { ref from_list, ref to_list, progress } => { - result.push(computed_value::ComputedOperation::InterpolateMatrix { - from_list: from_list.to_computed_value(context), - to_list: to_list.to_computed_value(context), - progress: progress - }); - } - SpecifiedOperation::AccumulateMatrix { ref from_list, ref to_list, count } => { - result.push(computed_value::ComputedOperation::AccumulateMatrix { - from_list: from_list.to_computed_value(context), - to_list: to_list.to_computed_value(context), - count: count.value() - }); - } - }; - } - - computed_value::T(Some(result)) - } - - #[inline] - fn from_computed_value(computed: &computed_value::T) -> Self { - SpecifiedValue(computed.0.as_ref().map(|computed| { - let mut result = vec![]; - for operation in computed { - match *operation { - computed_value::ComputedOperation::Matrix(ref computed) => { - result.push(SpecifiedOperation::Matrix3D { - m11: Number::from_computed_value(&computed.m11), - m12: Number::from_computed_value(&computed.m12), - m13: Number::from_computed_value(&computed.m13), - m14: Number::from_computed_value(&computed.m14), - m21: Number::from_computed_value(&computed.m21), - m22: Number::from_computed_value(&computed.m22), - m23: Number::from_computed_value(&computed.m23), - m24: Number::from_computed_value(&computed.m24), - m31: Number::from_computed_value(&computed.m31), - m32: Number::from_computed_value(&computed.m32), - m33: Number::from_computed_value(&computed.m33), - m34: Number::from_computed_value(&computed.m34), - m41: Number::from_computed_value(&computed.m41), - m42: Number::from_computed_value(&computed.m42), - m43: Number::from_computed_value(&computed.m43), - m44: Number::from_computed_value(&computed.m44), - }); - } - computed_value::ComputedOperation::MatrixWithPercents(ref computed) => { - result.push(SpecifiedOperation::PrefixedMatrix3D { - m11: Number::from_computed_value(&computed.m11), - m12: Number::from_computed_value(&computed.m12), - m13: Number::from_computed_value(&computed.m13), - m14: Number::from_computed_value(&computed.m14), - m21: Number::from_computed_value(&computed.m21), - m22: Number::from_computed_value(&computed.m22), - m23: Number::from_computed_value(&computed.m23), - m24: Number::from_computed_value(&computed.m24), - m31: Number::from_computed_value(&computed.m31), - m32: Number::from_computed_value(&computed.m32), - m33: Number::from_computed_value(&computed.m33), - m34: Number::from_computed_value(&computed.m34), - m41: Either::Second(LengthOrPercentage::from_computed_value(&computed.m41)), - m42: Either::Second(LengthOrPercentage::from_computed_value(&computed.m42)), - m43: LengthOrNumber::from_computed_value(&Either::First(computed.m43)), - m44: Number::from_computed_value(&computed.m44), - }); - } - computed_value::ComputedOperation::Translate(ref tx, ref ty, ref tz) => { - // XXXManishearth we lose information here; perhaps we should try to - // recover the original function? Not sure if this can be observed. - result.push(SpecifiedOperation::Translate3D( - ToComputedValue::from_computed_value(tx), - ToComputedValue::from_computed_value(ty), - ToComputedValue::from_computed_value(tz))); - } - computed_value::ComputedOperation::Scale(ref sx, ref sy, ref sz) => { - result.push(SpecifiedOperation::Scale3D( - Number::from_computed_value(sx), - Number::from_computed_value(sy), - Number::from_computed_value(sz))); - } - computed_value::ComputedOperation::Rotate(ref ax, ref ay, ref az, ref theta) => { - result.push(SpecifiedOperation::Rotate3D( - Number::from_computed_value(ax), - Number::from_computed_value(ay), - Number::from_computed_value(az), - specified::Angle::from_computed_value(theta))); - } - computed_value::ComputedOperation::Skew(ref theta_x, ref theta_y) => { - result.push(SpecifiedOperation::Skew( - specified::Angle::from_computed_value(theta_x), - Some(specified::Angle::from_computed_value(theta_y)))) - } - computed_value::ComputedOperation::Perspective(ref d) => { - result.push(SpecifiedOperation::Perspective( - ToComputedValue::from_computed_value(d) - )); - } - computed_value::ComputedOperation::InterpolateMatrix { ref from_list, - ref to_list, - progress } => { - result.push(SpecifiedOperation::InterpolateMatrix { - from_list: SpecifiedValue::from_computed_value(from_list), - to_list: SpecifiedValue::from_computed_value(to_list), - progress: progress - }); - } - computed_value::ComputedOperation::AccumulateMatrix { ref from_list, - ref to_list, - count } => { - result.push(SpecifiedOperation::AccumulateMatrix { - from_list: SpecifiedValue::from_computed_value(from_list), - to_list: SpecifiedValue::from_computed_value(to_list), - count: Integer::new(count) - }); - } - }; - } - result - }).unwrap_or(Vec::new())) - } - } - - // Converts computed LengthOrPercentageOrNumber into computed - // LengthOrPercentage. Number maps into Length (pixel unit) - fn lopon_to_lop(value: &ComputedLoPoNumber) -> ComputedLoP { - match *value { - Either::First(number) => ComputedLoP::Length(ComputedLength::new(number)), - Either::Second(length_or_percentage) => length_or_percentage, - } - } - - // Converts computed LengthOrNumber into computed Length. - // Number maps into Length. - fn lon_to_length(value: &ComputedLoN) -> ComputedLength { - match *value { - Either::First(length) => length, - Either::Second(number) => ComputedLength::new(number), - } + SpecifiedValue::parse_internal(context, input, true) } diff --git a/components/style/properties/properties.mako.rs b/components/style/properties/properties.mako.rs index f59bb52b05a..bd3ee49c298 100644 --- a/components/style/properties/properties.mako.rs +++ b/components/style/properties/properties.mako.rs @@ -2410,30 +2410,30 @@ impl ComputedValuesInner { /// Whether given this transform value, the compositor would require a /// layer. pub fn transform_requires_layer(&self) -> bool { + use values::generics::transform::TransformOperation; // Check if the transform matrix is 2D or 3D - if let Some(ref transform_list) = self.get_box().transform.0 { - for transform in transform_list { - match *transform { - computed_values::transform::ComputedOperation::Perspective(..) => { + for transform in &self.get_box().transform.0 { + match *transform { + TransformOperation::Perspective(..) => { + return true; + } + TransformOperation::Matrix3D(m) => { + // See http://dev.w3.org/csswg/css-transforms/#2d-matrix + if m.m31 != 0.0 || m.m32 != 0.0 || + m.m13 != 0.0 || m.m23 != 0.0 || + m.m43 != 0.0 || m.m14 != 0.0 || + m.m24 != 0.0 || m.m34 != 0.0 || + m.m33 != 1.0 || m.m44 != 1.0 { return true; } - computed_values::transform::ComputedOperation::Matrix(m) => { - // See http://dev.w3.org/csswg/css-transforms/#2d-matrix - if m.m31 != 0.0 || m.m32 != 0.0 || - m.m13 != 0.0 || m.m23 != 0.0 || - m.m43 != 0.0 || m.m14 != 0.0 || - m.m24 != 0.0 || m.m34 != 0.0 || - m.m33 != 1.0 || m.m44 != 1.0 { - return true; - } - } - computed_values::transform::ComputedOperation::Translate(_, _, z) => { - if z.px() != 0. { - return true; - } - } - _ => {} } + TransformOperation::Translate3D(_, _, z) | + TransformOperation::TranslateZ(z) => { + if z.px() != 0. { + return true; + } + } + _ => {} } } diff --git a/components/style/values/computed/transform.rs b/components/style/values/computed/transform.rs index 5e50a1ab8d4..6a9c7db6dc3 100644 --- a/components/style/values/computed/transform.rs +++ b/components/style/values/computed/transform.rs @@ -6,8 +6,6 @@ use app_units::Au; use euclid::{Rect, Transform3D, Vector3D}; -use properties::longhands::transform::computed_value::{ComputedOperation, ComputedMatrix}; -use properties::longhands::transform::computed_value::T as TransformList; use std::f32; use super::{CSSFloat, Either}; use values::animated::ToAnimatedZero; @@ -45,29 +43,6 @@ impl TransformOrigin { } } -impl From for Transform3D { - #[inline] - fn from(m: ComputedMatrix) -> Self { - Transform3D::row_major( - m.m11, m.m12, m.m13, m.m14, - m.m21, m.m22, m.m23, m.m24, - m.m31, m.m32, m.m33, m.m34, - m.m41, m.m42, m.m43, m.m44) - } -} - -impl From> for ComputedMatrix { - #[inline] - fn from(m: Transform3D) -> Self { - ComputedMatrix { - m11: m.m11, m12: m.m12, m13: m.m13, m14: m.m14, - m21: m.m21, m22: m.m22, m23: m.m23, m24: m.m24, - m31: m.m31, m32: m.m32, m33: m.m33, m34: m.m34, - m41: m.m41, m42: m.m42, m43: m.m43, m44: m.m44 - } - } -} - /// computed value of matrix3d() pub type Matrix3D = GenericMatrix3D; /// computed value of matrix3d() in -moz-transform @@ -141,6 +116,18 @@ impl From for Transform3D { } } +impl From> for Matrix3D { + #[inline] + fn from(m: Transform3D) -> Self { + Matrix3D { + m11: m.m11, m12: m.m12, m13: m.m13, m14: m.m14, + m21: m.m21, m22: m.m22, m23: m.m23, m24: m.m24, + m31: m.m31, m32: m.m32, m33: m.m33, m34: m.m34, + m41: m.m41, m42: m.m42, m43: m.m43, m44: m.m44 + } + } +} + impl From for Transform3D { #[inline] fn from(m: Matrix) -> Self { @@ -152,118 +139,6 @@ impl From for Transform3D { } } -impl TransformList { - /// Return the equivalent 3d matrix of this transform list. - /// If |reference_box| is None, we will drop the percent part from translate because - /// we can resolve it without the layout info. - pub fn to_transform_3d_matrix(&self, reference_box: Option<&Rect>) - -> Option> { - let mut transform = Transform3D::identity(); - let list = match self.0.as_ref() { - Some(list) => list, - None => return None, - }; - - let extract_pixel_length = |lop: &LengthOrPercentage| { - match *lop { - LengthOrPercentage::Length(px) => px.px(), - LengthOrPercentage::Percentage(_) => 0., - LengthOrPercentage::Calc(calc) => calc.length().px(), - } - }; - - for operation in list { - let matrix = match *operation { - ComputedOperation::Rotate(ax, ay, az, theta) => { - let theta = Angle::from_radians(2.0f32 * f32::consts::PI - theta.radians()); - let (ax, ay, az, theta) = - Self::get_normalized_vector_and_angle(ax, ay, az, theta); - Transform3D::create_rotation(ax, ay, az, theta.into()) - } - ComputedOperation::Perspective(d) => { - Self::create_perspective_matrix(d.px()) - } - ComputedOperation::Scale(sx, sy, sz) => { - Transform3D::create_scale(sx, sy, sz) - } - ComputedOperation::Translate(tx, ty, tz) => { - let (tx, ty) = match reference_box { - Some(relative_border_box) => { - (tx.to_pixel_length(relative_border_box.size.width).px(), - ty.to_pixel_length(relative_border_box.size.height).px()) - }, - None => { - // If we don't have reference box, we cannot resolve the used value, - // so only retrieve the length part. This will be used for computing - // distance without any layout info. - (extract_pixel_length(&tx), extract_pixel_length(&ty)) - } - }; - let tz = tz.px(); - Transform3D::create_translation(tx, ty, tz) - } - ComputedOperation::Matrix(m) => { - m.into() - } - ComputedOperation::MatrixWithPercents(_) => { - // `-moz-transform` is not implemented in Servo yet. - unreachable!() - } - ComputedOperation::Skew(theta_x, theta_y) => { - Transform3D::create_skew(theta_x.into(), theta_y.into()) - } - ComputedOperation::InterpolateMatrix { .. } | - ComputedOperation::AccumulateMatrix { .. } => { - // TODO: Convert InterpolateMatrix/AccmulateMatrix into a valid Transform3D by - // the reference box and do interpolation on these two Transform3D matrices. - // Both Gecko and Servo don't support this for computing distance, and Servo - // doesn't support animations on InterpolateMatrix/AccumulateMatrix, so - // return None. - return None; - } - }; - - transform = transform.pre_mul(&matrix); - } - - Some(transform) - } - - /// Return the transform matrix from a perspective length. - #[inline] - pub fn create_perspective_matrix(d: CSSFloat) -> Transform3D { - // TODO(gw): The transforms spec says that perspective length must - // be positive. However, there is some confusion between the spec - // and browser implementations as to handling the case of 0 for the - // perspective value. Until the spec bug is resolved, at least ensure - // that a provided perspective value of <= 0.0 doesn't cause panics - // and behaves as it does in other browsers. - // See https://lists.w3.org/Archives/Public/www-style/2016Jan/0020.html for more details. - if d <= 0.0 { - Transform3D::identity() - } else { - Transform3D::create_perspective(d) - } - } - - /// Return the normalized direction vector and its angle for Rotate3D. - pub fn get_normalized_vector_and_angle(x: f32, y: f32, z: f32, angle: Angle) - -> (f32, f32, f32, Angle) { - use euclid::approxeq::ApproxEq; - use euclid::num::Zero; - let vector = DirectionVector::new(x, y, z); - if vector.square_length().approx_eq(&f32::zero()) { - // https://www.w3.org/TR/css-transforms-1/#funcdef-rotate3d - // A direction vector that cannot be normalized, such as [0, 0, 0], will cause the - // rotation to not be applied, so we use identity matrix (i.e. rotate3d(0, 0, 1, 0)). - (0., 0., 1., Angle::zero()) - } else { - let vector = vector.normalize(); - (vector.x, vector.y, vector.z, angle) - } - } -} - /// Build an equivalent 'identity transform function list' based /// on an existing transform list. /// http://dev.w3.org/csswg/css-transforms/#none-transform-animation @@ -345,7 +220,7 @@ impl ToAnimatedZero for TransformOperation { Ok(GenericTransformOperation::ScaleZ(1.0)) }, GenericTransformOperation::Rotate3D(x, y, z, a) => { - let (x, y, z, _) = TransformList::get_normalized_vector_and_angle(x, y, z, a); + let (x, y, z, _) = Transform::get_normalized_vector_and_angle(x, y, z, a); Ok(GenericTransformOperation::Rotate3D(x, y, z, Angle::zero())) }, GenericTransformOperation::RotateX(_) => { @@ -377,6 +252,16 @@ impl ToAnimatedZero for TransformOperation { } } + +impl ToAnimatedZero for Transform { + #[inline] + fn to_animated_zero(&self) -> Result { + Ok(GenericTransform( + self.0.iter().map(|op| op.to_animated_zero()).collect::, _>>()? + )) + } +} + impl Transform { /// Return the equivalent 3d matrix of this transform list. /// If |reference_box| is None, we will drop the percent part from translate because @@ -567,4 +452,3 @@ impl Transform { } } } - diff --git a/components/style/values/generics/transform.rs b/components/style/values/generics/transform.rs index 68385fe4aa6..f7968e72e0c 100644 --- a/components/style/values/generics/transform.rs +++ b/components/style/values/generics/transform.rs @@ -22,9 +22,7 @@ pub struct Matrix { } #[allow(missing_docs)] -#[derive(Clone, Copy, Debug, ToComputedValue, PartialEq)] -#[cfg_attr(feature = "gecko", derive(MallocSizeOf))] -#[cfg_attr(feature = "servo", derive(HeapSizeOf))] +#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Matrix3D { pub m11: T, pub m12: T, pub m13: T, pub m14: T, pub m21: T, pub m22: T, pub m23: T, pub m24: T, @@ -149,9 +147,7 @@ impl TimingKeyword { } } -#[derive(Clone, Debug, PartialEq)] -#[cfg_attr(feature = "gecko", derive(MallocSizeOf))] -#[cfg_attr(feature = "servo", derive(HeapSizeOf))] +#[derive(Clone, Debug, MallocSizeOf, PartialEq)] #[derive(ToComputedValue)] /// A single operation in the list of a `transform` value pub enum TransformOperation { @@ -247,9 +243,7 @@ pub enum TransformOperation(pub Vec); diff --git a/components/style/values/specified/transform.rs b/components/style/values/specified/transform.rs index 82f0e0cad1a..b7e83cf4e3b 100644 --- a/components/style/values/specified/transform.rs +++ b/components/style/values/specified/transform.rs @@ -46,6 +46,7 @@ impl Transform { Ok(GenericTransform(Space::parse(input, |input| { let function = input.expect_function()?.clone(); input.parse_nested_block(|input| { + let location = input.current_source_location(); let result = match_ignore_ascii_case! { &function, "matrix" => { let a = specified::parse_number(context, input)?; @@ -236,7 +237,7 @@ impl Transform { _ => Err(()), }; result - .map_err(|()| StyleParseError::UnexpectedFunction(function.clone()).into()) + .map_err(|()| location.new_custom_error(StyleParseErrorKind::UnexpectedFunction(function.clone()))) }) })?)) } diff --git a/ports/geckolib/glue.rs b/ports/geckolib/glue.rs index c22aded7b08..cdf98577558 100644 --- a/ports/geckolib/glue.rs +++ b/ports/geckolib/glue.rs @@ -716,13 +716,12 @@ pub extern "C" fn Servo_AnimationValue_GetTransform( let value = AnimationValue::as_arc(&value); if let AnimationValue::Transform(ref servo_list) = **value { let list = unsafe { &mut *list }; - match servo_list.0 { - Some(ref servo_list) => { - style_structs::Box::convert_transform(servo_list, list); - }, - None => unsafe { + if servo_list.0.is_empty() { + unsafe { list.set_move(RefPtr::from_addrefed(Gecko_NewNoneTransform())); } + } else { + style_structs::Box::convert_transform(&servo_list.0, list); } } else { panic!("The AnimationValue should be transform"); @@ -2522,10 +2521,10 @@ pub extern "C" fn Servo_MatrixTransform_Operate(matrix_operator: MatrixTransform progress: f64, output: *mut RawGeckoGfxMatrix4x4) { use self::MatrixTransformOperator::{Accumulate, Interpolate}; - use style::properties::longhands::transform::computed_value::ComputedMatrix; + use style::values::computed::transform::Matrix3D; - let from = ComputedMatrix::from(unsafe { from.as_ref() }.expect("not a valid 'from' matrix")); - let to = ComputedMatrix::from(unsafe { to.as_ref() }.expect("not a valid 'to' matrix")); + let from = Matrix3D::from(unsafe { from.as_ref() }.expect("not a valid 'from' matrix")); + let to = Matrix3D::from(unsafe { to.as_ref() }.expect("not a valid 'to' matrix")); let result = match matrix_operator { Interpolate => from.animate(&to, Procedure::Interpolate { progress }), Accumulate => from.animate(&to, Procedure::Accumulate { count: progress as u64 }), From 079b25db93d47e34277f7c0e01c5559894e06f4c Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Wed, 4 Oct 2017 15:55:37 -0700 Subject: [PATCH 09/21] Share transform function lists between set_transform and clone_transform This will also fix https://bugzilla.mozilla.org/show_bug.cgi?id=1405881 --- .../gecko_bindings/sugar/ns_css_value.rs | 13 +++- components/style/properties/gecko.mako.rs | 69 ++++++++++++------- 2 files changed, 57 insertions(+), 25 deletions(-) diff --git a/components/style/gecko_bindings/sugar/ns_css_value.rs b/components/style/gecko_bindings/sugar/ns_css_value.rs index 2a930b5cd1a..dca0ec98751 100644 --- a/components/style/gecko_bindings/sugar/ns_css_value.rs +++ b/components/style/gecko_bindings/sugar/ns_css_value.rs @@ -13,7 +13,7 @@ use std::marker::PhantomData; use std::mem; use std::ops::{Index, IndexMut}; use std::slice; -use values::computed::{Angle, LengthOrPercentage, Percentage}; +use values::computed::{Angle, Length, LengthOrPercentage, Percentage}; use values::specified::url::SpecifiedUrl; impl nsCSSValue { @@ -104,7 +104,6 @@ impl nsCSSValue { /// Returns LengthOrPercentage value. pub unsafe fn get_lop(&self) -> LengthOrPercentage { - use values::computed::Length; match self.mUnit { nsCSSUnit::eCSSUnit_Pixel => { LengthOrPercentage::Length(Length::new(bindings::Gecko_CSSValue_GetNumber(self))) @@ -119,6 +118,16 @@ impl nsCSSValue { } } + /// Returns Length value. + pub unsafe fn get_length(&self) -> Length { + match self.mUnit { + nsCSSUnit::eCSSUnit_Pixel => { + Length::new(bindings::Gecko_CSSValue_GetNumber(self)) + }, + x => panic!("The unit should not be {:?}", x), + } + } + fn set_valueless_unit(&mut self, unit: nsCSSUnit) { debug_assert_eq!(self.mUnit, nsCSSUnit::eCSSUnit_Null); debug_assert!(unit as u32 <= nsCSSUnit::eCSSUnit_DummyInherit as u32, "Not a valueless unit"); diff --git a/components/style/properties/gecko.mako.rs b/components/style/properties/gecko.mako.rs index cee6c61b77b..ba209b3090f 100644 --- a/components/style/properties/gecko.mako.rs +++ b/components/style/properties/gecko.mako.rs @@ -2892,7 +2892,19 @@ fn static_assert() { } ${impl_css_url('_moz_binding', 'mBinding.mPtr')} - + <% + transform_functions = [ + ("Matrix3D", "matrix3d", ["number"] * 16), + ("PrefixedMatrix3D", "matrix3d", ["number"] * 12 + ["lopon"] * 2 + + ["lon"] + ["number"]), + ("Translate3D", "translate3d", ["lop", "lop", "length"]), + ("Scale3D", "scale3d", ["number"] * 3), + ("Rotate3D", "rotate3d", ["number"] * 3 + ["angle"]), + ("Perspective", "perspective", ["length"]), + ("InterpolateMatrix", "interpolatematrix", ["list"] * 2 + ["percentage"]), + ("AccumulateMatrix", "accumulatematrix", ["list"] * 2 + ["integer_to_percentage"]) + ] + %> <%def name="transform_function_arm(name, keyword, items)"> <% pattern = None @@ -2978,17 +2990,9 @@ fn static_assert() { unsafe { match *servo_value { - ${transform_function_arm("Matrix3D", "matrix3d", ["number"] * 16)} - ${transform_function_arm("PrefixedMatrix3D", "matrix3d", ["number"] * 12 + ["lopon"] * 2 - + ["lon"] + ["number"])} - ${transform_function_arm("Translate3D", "translate3d", ["lop", "lop", "length"])} - ${transform_function_arm("Scale3D", "scale3d", ["number"] * 3)} - ${transform_function_arm("Rotate3D", "rotate3d", ["number"] * 3 + ["angle"])} - ${transform_function_arm("Perspective", "perspective", ["length"])} - ${transform_function_arm("InterpolateMatrix", "interpolatematrix", - ["list"] * 2 + ["percentage"])} - ${transform_function_arm("AccumulateMatrix", "accumulatematrix", - ["list"] * 2 + ["integer_to_percentage"])} + % for servo, gecko, format in transform_functions: + ${transform_function_arm(servo, gecko, format)} + % endfor _ => unimplemented!() } } @@ -3035,10 +3039,12 @@ fn static_assert() { css_value_getters = { "length" : "Length::new(bindings::Gecko_CSSValue_GetNumber(%s))", "lop" : "%s.get_lop()", + "lopon" : "Either::Second(%s.get_lop())", + "lon" : "Either::First(%s.get_length())", "angle" : "%s.get_angle()", "number" : "bindings::Gecko_CSSValue_GetNumber(%s)", "percentage" : "Percentage(bindings::Gecko_CSSValue_GetPercentage(%s))", - "percentage_to_integer" : "bindings::Gecko_CSSValue_GetPercentage(%s) as i32", + "integer_to_percentage" : "bindings::Gecko_CSSValue_GetPercentage(%s) as i32", "list" : "Transform(convert_shared_list_to_operations(%s))", } pre_symbols = "(" @@ -3056,8 +3062,18 @@ fn static_assert() { field_names = ["from_list", "to_list", "progress"] elif keyword == "accumulatematrix": field_names = ["from_list", "to_list", "count"] + %> - structs::nsCSSKeyword::eCSSKeyword_${keyword} => { + <% + + guard = "" + if name == "Matrix3D": + guard = "if !needs_prefix " + elif name == "PrefixedMatrix3D": + guard = "if needs_prefix " + + %> + structs::nsCSSKeyword::eCSSKeyword_${keyword} ${guard}=> { ::values::generics::transform::TransformOperation::${name}${pre_symbols} % for index, item in enumerate(items): % if keyword == "matrix3d": @@ -3096,17 +3112,24 @@ fn static_assert() { bindings::Gecko_CSSValue_GetKeyword(bindings::Gecko_CSSValue_GetArrayItemConst(gecko_value, 0)) }; + let needs_prefix = if transform_function == structs::nsCSSKeyword::eCSSKeyword_matrix3d { + unsafe { + bindings::Gecko_CSSValue_GetArrayItemConst(gecko_value, 13).mUnit + != structs::nsCSSUnit::eCSSUnit_Number || + bindings::Gecko_CSSValue_GetArrayItemConst(gecko_value, 14).mUnit + != structs::nsCSSUnit::eCSSUnit_Number || + bindings::Gecko_CSSValue_GetArrayItemConst(gecko_value, 15).mUnit + != structs::nsCSSUnit::eCSSUnit_Number + } + } else { + false + }; + unsafe { match transform_function { - ${computed_operation_arm("Matrix3D", "matrix3d", ["number"] * 16)} - ${computed_operation_arm("Translate3D", "translate3d", ["lop", "lop", "length"])} - ${computed_operation_arm("Scale3D", "scale3d", ["number"] * 3)} - ${computed_operation_arm("Rotate3D", "rotate3d", ["number"] * 3 + ["angle"])} - ${computed_operation_arm("Perspective", "perspective", ["length"])} - ${computed_operation_arm("InterpolateMatrix", "interpolatematrix", - ["list"] * 2 + ["percentage"])} - ${computed_operation_arm("AccumulateMatrix", "accumulatematrix", - ["list"] * 2 + ["percentage_to_integer"])} + % for servo, gecko, format in transform_functions: + ${computed_operation_arm(servo, gecko, format)} + % endfor _ => panic!("{:?} is not an acceptable transform function", transform_function), } } From fc29de89866d4eafaa057f3690b3c90c12a86c33 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Thu, 5 Oct 2017 18:00:26 -0700 Subject: [PATCH 10/21] Add support for more functions in Gecko glue --- components/style/properties/gecko.mako.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/components/style/properties/gecko.mako.rs b/components/style/properties/gecko.mako.rs index ba209b3090f..ed8fcb710c6 100644 --- a/components/style/properties/gecko.mako.rs +++ b/components/style/properties/gecko.mako.rs @@ -2898,8 +2898,19 @@ fn static_assert() { ("PrefixedMatrix3D", "matrix3d", ["number"] * 12 + ["lopon"] * 2 + ["lon"] + ["number"]), ("Translate3D", "translate3d", ["lop", "lop", "length"]), + ("TranslateX", "translatex", ["lop"]), + ("TranslateY", "translatey", ["lop"]), + ("TranslateZ", "translatez", ["length"]), ("Scale3D", "scale3d", ["number"] * 3), + ("ScaleX", "scalex", ["number"]), + ("ScaleY", "scaley", ["number"]), + ("ScaleZ", "scalez", ["number"]), ("Rotate3D", "rotate3d", ["number"] * 3 + ["angle"]), + ("RotateX", "rotatex", ["angle"]), + ("RotateY", "rotatey", ["angle"]), + ("RotateZ", "rotatez", ["angle"]), + ("SkewX", "skewx", ["angle"]), + ("SkewY", "skewy", ["angle"]), ("Perspective", "perspective", ["length"]), ("InterpolateMatrix", "interpolatematrix", ["list"] * 2 + ["percentage"]), ("AccumulateMatrix", "accumulatematrix", ["list"] * 2 + ["integer_to_percentage"]) From e20c508a6e55d441f89cfeaf47659a91dd0accd1 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Mon, 30 Oct 2017 13:03:16 -0700 Subject: [PATCH 11/21] Add support for 2D matrices in Gecko glue --- components/style/properties/gecko.mako.rs | 25 +++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/components/style/properties/gecko.mako.rs b/components/style/properties/gecko.mako.rs index ed8fcb710c6..8a181fdabde 100644 --- a/components/style/properties/gecko.mako.rs +++ b/components/style/properties/gecko.mako.rs @@ -2897,6 +2897,8 @@ fn static_assert() { ("Matrix3D", "matrix3d", ["number"] * 16), ("PrefixedMatrix3D", "matrix3d", ["number"] * 12 + ["lopon"] * 2 + ["lon"] + ["number"]), + ("Matrix", "matrix", ["number"] * 6), + ("PrefixedMatrix", "matrix", ["number"] * 4 + ["lopon"] * 2), ("Translate3D", "translate3d", ["lop", "lop", "length"]), ("TranslateX", "translatex", ["lop"]), ("TranslateY", "translatey", ["lop"]), @@ -2923,10 +2925,12 @@ fn static_assert() { # m11: number1, m12: number2, .. single_patterns = ["m%s: %s" % (str(a / 4 + 1) + str(a % 4 + 1), b + str(a + 1)) for (a, b) in enumerate(items)] - if name == "Matrix": - pattern = "(Matrix3D { %s })" % ", ".join(single_patterns) - else: - pattern = "(Matrix3D { %s })" % ", ".join(single_patterns) + pattern = "(Matrix3D { %s })" % ", ".join(single_patterns) + elif keyword == "matrix": + # a: number1, b: number2, .. + single_patterns = ["%s: %s" % (chr(ord('a') + a), b + str(a + 1)) for (a, b) + in enumerate(items)] + pattern = "(Matrix { %s })" % ", ".join(single_patterns) elif keyword == "interpolatematrix": pattern = " { from_list: ref list1, to_list: ref list2, progress: percentage3 }" elif keyword == "accumulatematrix": @@ -2975,7 +2979,7 @@ fn static_assert() { gecko_value: &mut structs::nsCSSValue /* output */) { use properties::longhands::transform::computed_value::ComputedOperation; use values::computed::{Length, LengthOrNumber, LengthOrPercentage, LengthOrPercentageOrNumber}; - use values::generics::transform::Matrix3D; + use values::generics::transform::{Matrix, Matrix3D}; let convert_to_ns_css_value = |item: &ComputedOperation| -> structs::nsCSSValue { let mut value = structs::nsCSSValue::null(); @@ -3068,6 +3072,9 @@ fn static_assert() { elif keyword == "matrix3d": pre_symbols = "(Matrix3D {" post_symbols = "})" + elif keyword == "matrix": + pre_symbols = "(Matrix {" + post_symbols = "})" field_names = None if keyword == "interpolatematrix": field_names = ["from_list", "to_list", "progress"] @@ -3078,9 +3085,9 @@ fn static_assert() { <% guard = "" - if name == "Matrix3D": + if name == "Matrix3D" or name == "Matrix": guard = "if !needs_prefix " - elif name == "PrefixedMatrix3D": + elif name == "PrefixedMatrix3D" or name == "PrefixedMatrix": guard = "if needs_prefix " %> @@ -3089,6 +3096,8 @@ fn static_assert() { % for index, item in enumerate(items): % if keyword == "matrix3d": m${index / 4 + 1}${index % 4 + 1}: + % elif keyword == "matrix": + ${chr(ord('a') + index)}: % elif keyword == "interpolatematrix" or keyword == "accumulatematrix": ${field_names[index]}: % endif @@ -3103,7 +3112,7 @@ fn static_assert() { -> longhands::transform::computed_value::ComputedOperation { use properties::longhands::transform::computed_value::ComputedOperation; use values::computed::{Length, Percentage}; - use values::generics::transform::Matrix3D; + use values::generics::transform::{Matrix, Matrix3D}; use values::generics::transform::Transform; let convert_shared_list_to_operations = |value: &structs::nsCSSValue| From e15695289d20480ba8bd459c112db4de3a241009 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Mon, 30 Oct 2017 14:06:04 -0700 Subject: [PATCH 12/21] Add support for transform functions with an optional final argument in gecko glue --- components/style/properties/gecko.mako.rs | 47 +++++++++++++++++++---- 1 file changed, 40 insertions(+), 7 deletions(-) diff --git a/components/style/properties/gecko.mako.rs b/components/style/properties/gecko.mako.rs index 8a181fdabde..21d43c0d009 100644 --- a/components/style/properties/gecko.mako.rs +++ b/components/style/properties/gecko.mako.rs @@ -2899,18 +2899,22 @@ fn static_assert() { + ["lon"] + ["number"]), ("Matrix", "matrix", ["number"] * 6), ("PrefixedMatrix", "matrix", ["number"] * 4 + ["lopon"] * 2), + ("Translate", "translate", ["lop", "optional_lop"]), ("Translate3D", "translate3d", ["lop", "lop", "length"]), ("TranslateX", "translatex", ["lop"]), ("TranslateY", "translatey", ["lop"]), ("TranslateZ", "translatez", ["length"]), ("Scale3D", "scale3d", ["number"] * 3), + ("Scale", "scale", ["number", "optional_number"]), ("ScaleX", "scalex", ["number"]), ("ScaleY", "scaley", ["number"]), ("ScaleZ", "scalez", ["number"]), + ("Rotate", "rotate", ["angle"]), ("Rotate3D", "rotate3d", ["number"] * 3 + ["angle"]), ("RotateX", "rotatex", ["angle"]), ("RotateY", "rotatey", ["angle"]), ("RotateZ", "rotatez", ["angle"]), + ("Skew", "skew", ["angle", "optional_angle"]), ("SkewX", "skewx", ["angle"]), ("SkewY", "skewy", ["angle"]), ("Perspective", "perspective", ["length"]), @@ -2920,6 +2924,7 @@ fn static_assert() { %> <%def name="transform_function_arm(name, keyword, items)"> <% + has_optional = items[-1].startswith("optional_") pattern = None if keyword == "matrix3d": # m11: number1, m12: number2, .. @@ -2959,19 +2964,36 @@ fn static_assert() { } %> ::values::generics::transform::TransformOperation::${name}${pattern} => { - bindings::Gecko_CSSValue_SetFunction(gecko_value, ${len(items) + 1}); + % if has_optional: + let optional_present = ${items[-1] + str(len(items))}.is_some(); + let len = if optional_present { + ${len(items) + 1} + } else { + ${len(items)} + }; + % else: + let len = ${len(items) + 1}; + % endif + bindings::Gecko_CSSValue_SetFunction(gecko_value, len); bindings::Gecko_CSSValue_SetKeyword( bindings::Gecko_CSSValue_GetArrayItem(gecko_value, 0), structs::nsCSSKeyword::eCSSKeyword_${keyword} ); % for index, item in enumerate(items): + <% replaced_item = item.replace("optional_", "") %> + % if item.startswith("optional"): + if let Some(${replaced_item + str(index + 1)}) = ${item + str(index + 1)} { + % endif % if item == "list": debug_assert!(!${item}${index + 1}.0.is_empty()); % endif - ${css_value_setters[item] % ( + ${css_value_setters[replaced_item] % ( "bindings::Gecko_CSSValue_GetArrayItem(gecko_value, %d)" % (index + 1), - item + str(index + 1) + replaced_item + str(index + 1) )}; + % if item.startswith("optional"): + } + % endif % endfor } @@ -3008,7 +3030,6 @@ fn static_assert() { % for servo, gecko, format in transform_functions: ${transform_function_arm(servo, gecko, format)} % endfor - _ => unimplemented!() } } } @@ -3101,9 +3122,21 @@ fn static_assert() { % elif keyword == "interpolatematrix" or keyword == "accumulatematrix": ${field_names[index]}: % endif - ${css_value_getters[item] % ( - "bindings::Gecko_CSSValue_GetArrayItemConst(gecko_value, %d)" % (index + 1) - )}, + <% + getter = css_value_getters[item.replace("optional_", "")] % ( + "bindings::Gecko_CSSValue_GetArrayItemConst(gecko_value, %d)" % (index + 1) + ) + %> + % if item.startswith("optional_"): + if (**gecko_value.mValue.mArray.as_ref()).mCount == ${index + 1} { + None + } else { + Some(${getter}) + } + % else: + ${getter} + % endif +, % endfor ${post_symbols} }, From aba00be52d17ed436571105ffac308da436b3548 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Mon, 30 Oct 2017 16:24:51 -0700 Subject: [PATCH 13/21] Add more operations to animation --- .../helpers/animated_properties.mako.rs | 146 +++++++++++++++++- components/style/values/computed/transform.rs | 36 +++++ components/style/values/generics/transform.rs | 21 +++ 3 files changed, 197 insertions(+), 6 deletions(-) diff --git a/components/style/properties/helpers/animated_properties.mako.rs b/components/style/properties/helpers/animated_properties.mako.rs index 3c55416b178..691b57845da 100644 --- a/components/style/properties/helpers/animated_properties.mako.rs +++ b/components/style/properties/helpers/animated_properties.mako.rs @@ -1033,6 +1033,7 @@ impl Animate for ComputedTransformOperation { this.animate(other, procedure)?, )) }, + // XXXManishearth handle 2D matrix ( &TransformOperation::Skew(ref fx, ref fy), &TransformOperation::Skew(ref tx, ref ty), @@ -1042,6 +1043,22 @@ impl Animate for ComputedTransformOperation { fy.animate(ty, procedure)?, )) }, + ( + &TransformOperation::SkewX(ref f), + &TransformOperation::SkewX(ref t), + ) => { + Ok(TransformOperation::SkewX( + f.animate(t, procedure)?, + )) + }, + ( + &TransformOperation::SkewY(ref f), + &TransformOperation::SkewY(ref t), + ) => { + Ok(TransformOperation::SkewY( + f.animate(t, procedure)?, + )) + }, ( &TransformOperation::Translate3D(ref fx, ref fy, ref fz), &TransformOperation::Translate3D(ref tx, ref ty, ref tz), @@ -1052,6 +1069,39 @@ impl Animate for ComputedTransformOperation { fz.animate(tz, procedure)?, )) }, + ( + &TransformOperation::Translate(ref fx, ref fy), + &TransformOperation::Translate(ref tx, ref ty), + ) => { + Ok(TransformOperation::Translate( + fx.animate(tx, procedure)?, + fy.animate(ty, procedure)? + )) + }, + ( + &TransformOperation::TranslateX(ref f), + &TransformOperation::TranslateX(ref t), + ) => { + Ok(TransformOperation::TranslateX( + f.animate(t, procedure)? + )) + }, + ( + &TransformOperation::TranslateY(ref f), + &TransformOperation::TranslateY(ref t), + ) => { + Ok(TransformOperation::TranslateY( + f.animate(t, procedure)? + )) + }, + ( + &TransformOperation::TranslateZ(ref f), + &TransformOperation::TranslateZ(ref t), + ) => { + Ok(TransformOperation::TranslateZ( + f.animate(t, procedure)? + )) + }, ( &TransformOperation::Scale3D(ref fx, ref fy, ref fz), &TransformOperation::Scale3D(ref tx, ref ty, ref tz), @@ -1062,6 +1112,30 @@ impl Animate for ComputedTransformOperation { animate_multiplicative_factor(*fz, *tz, procedure)?, )) }, + ( + &TransformOperation::ScaleX(ref f), + &TransformOperation::ScaleX(ref t), + ) => { + Ok(TransformOperation::ScaleX( + animate_multiplicative_factor(*f, *t, procedure)? + )) + }, + ( + &TransformOperation::ScaleY(ref f), + &TransformOperation::ScaleY(ref t), + ) => { + Ok(TransformOperation::ScaleY( + animate_multiplicative_factor(*f, *t, procedure)? + )) + }, + ( + &TransformOperation::ScaleZ(ref f), + &TransformOperation::ScaleZ(ref t), + ) => { + Ok(TransformOperation::ScaleZ( + animate_multiplicative_factor(*f, *t, procedure)? + )) + }, ( &TransformOperation::Rotate3D(fx, fy, fz, fa), &TransformOperation::Rotate3D(tx, ty, tz, ta), @@ -1081,6 +1155,54 @@ impl Animate for ComputedTransformOperation { )) } }, + ( + &TransformOperation::RotateX(fa), + &TransformOperation::RotateX(ta), + ) => { + Ok(TransformOperation::RotateX( + fa.animate(&ta, procedure)? + )) + }, + ( + &TransformOperation::RotateY(fa), + &TransformOperation::RotateY(ta), + ) => { + Ok(TransformOperation::RotateY( + fa.animate(&ta, procedure)? + )) + }, + ( + &TransformOperation::RotateZ(fa), + &TransformOperation::RotateZ(ta), + ) => { + Ok(TransformOperation::RotateZ( + fa.animate(&ta, procedure)? + )) + }, + ( + &TransformOperation::Rotate(fa), + &TransformOperation::Rotate(ta), + ) => { + Ok(TransformOperation::Rotate( + fa.animate(&ta, procedure)? + )) + }, + ( + &TransformOperation::Rotate(fa), + &TransformOperation::RotateZ(ta), + ) => { + Ok(TransformOperation::Rotate( + fa.animate(&ta, procedure)? + )) + }, + ( + &TransformOperation::RotateZ(fa), + &TransformOperation::Rotate(ta), + ) => { + Ok(TransformOperation::Rotate( + fa.animate(&ta, procedure)? + )) + }, ( &TransformOperation::Perspective(ref fd), &TransformOperation::Perspective(ref td), @@ -1097,6 +1219,7 @@ impl Animate for ComputedTransformOperation { fd_matrix.animate(&td_matrix, procedure)?, )) }, + // XXXManishearth handle crossover between translate and scale functions _ => Err(()), } } @@ -1106,18 +1229,29 @@ fn is_matched_operation(first: &ComputedTransformOperation, second: &ComputedTra match (first, second) { (&TransformOperation::Matrix(..), &TransformOperation::Matrix(..)) | - (&TransformOperation::PrefixedMatrix(..), - &TransformOperation::PrefixedMatrix(..)) | + (&TransformOperation::Matrix3D(..), + &TransformOperation::Matrix3D(..)) | (&TransformOperation::Skew(..), &TransformOperation::Skew(..)) | - (&TransformOperation::Translate(..), - &TransformOperation::Translate(..)) | - (&TransformOperation::Scale(..), - &TransformOperation::Scale(..)) | + (&TransformOperation::SkewX(..), + &TransformOperation::SkewX(..)) | + (&TransformOperation::SkewY(..), + &TransformOperation::SkewY(..)) | (&TransformOperation::Rotate(..), &TransformOperation::Rotate(..)) | + (&TransformOperation::Rotate3D(..), + &TransformOperation::Rotate3D(..)) | + (&TransformOperation::RotateX(..), + &TransformOperation::RotateX(..)) | + (&TransformOperation::RotateY(..), + &TransformOperation::RotateY(..)) | + (&TransformOperation::RotateZ(..), + &TransformOperation::RotateZ(..)) | (&TransformOperation::Perspective(..), &TransformOperation::Perspective(..)) => true, + // we animate scale and translate operations against each other + (a, b) if a.is_translate() && b.is_translate() => true, + (a, b) if a.is_scale() && b.is_scale() => true, // InterpolateMatrix and AccumulateMatrix are for mismatched transform. _ => false } diff --git a/components/style/values/computed/transform.rs b/components/style/values/computed/transform.rs index 6a9c7db6dc3..4c90a01b3d1 100644 --- a/components/style/values/computed/transform.rs +++ b/components/style/values/computed/transform.rs @@ -139,6 +139,42 @@ impl From for Transform3D { } } +impl TransformOperation { + /// Convert to a Translate3D. + /// + /// Must be called on a Translate function + pub fn to_translate_3d(&self) -> Self { + match *self { + GenericTransformOperation::Translate3D(..) => self.clone(), + GenericTransformOperation::TranslateX(ref x) | + GenericTransformOperation::Translate(ref x, None) => + GenericTransformOperation::Translate3D(x.clone(), LengthOrPercentage::zero(), Length::zero()), + GenericTransformOperation::Translate(ref x, Some(ref y)) => + GenericTransformOperation::Translate3D(x.clone(), y.clone(), Length::zero()), + GenericTransformOperation::TranslateY(ref y) => + GenericTransformOperation::Translate3D(LengthOrPercentage::zero(), y.clone(), Length::zero()), + GenericTransformOperation::TranslateZ(ref z) => + GenericTransformOperation::Translate3D(LengthOrPercentage::zero(), + LengthOrPercentage::zero(), z.clone()), + _ => unreachable!() + } + } + /// Convert to a Scale3D. + /// + /// Must be called on a Scale function + pub fn to_scale_3d(&self) -> Self { + match *self { + GenericTransformOperation::Scale3D(..) => self.clone(), + GenericTransformOperation::Scale(s, None) => GenericTransformOperation::Scale3D(s, s, 1.), + GenericTransformOperation::Scale(x, Some(y)) => GenericTransformOperation::Scale3D(x, y, 1.), + GenericTransformOperation::ScaleX(x) => GenericTransformOperation::Scale3D(x, 1., 1.), + GenericTransformOperation::ScaleY(y) => GenericTransformOperation::Scale3D(1., y, 1.), + GenericTransformOperation::ScaleZ(z) => GenericTransformOperation::Scale3D(1., 1., z), + _ => unreachable!() + } + } +} + /// Build an equivalent 'identity transform function list' based /// on an existing transform list. /// http://dev.w3.org/csswg/css-transforms/#none-transform-animation diff --git a/components/style/values/generics/transform.rs b/components/style/values/generics/transform.rs index f7968e72e0c..b663babf279 100644 --- a/components/style/values/generics/transform.rs +++ b/components/style/values/generics/transform.rs @@ -247,6 +247,27 @@ pub enum TransformOperation(pub Vec); +impl + TransformOperation { + + /// Check if it is any translate function + pub fn is_translate(&self) -> bool { + use self::TransformOperation::*; + match *self { + Translate(..) | Translate3D(..) | TranslateX(..) | TranslateY(..) | TranslateZ(..) => true, + _ => false + } + } + + /// Check if it is any scale function + pub fn is_scale(&self) -> bool { + use self::TransformOperation::*; + match *self { + Scale(..) | Scale3D(..) | ScaleX(..) | ScaleY(..) | ScaleZ(..) => true, + _ => false + } + } +} impl From f699b8cfb265bdd99bf509bce9bd205ce1923c62 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Mon, 30 Oct 2017 17:03:03 -0700 Subject: [PATCH 14/21] Handle animating 2D matrices --- .../helpers/animated_properties.mako.rs | 37 ++++++++++++++- components/style/values/computed/transform.rs | 46 ++++++++++++++----- 2 files changed, 70 insertions(+), 13 deletions(-) diff --git a/components/style/properties/helpers/animated_properties.mako.rs b/components/style/properties/helpers/animated_properties.mako.rs index 691b57845da..7563dc3979e 100644 --- a/components/style/properties/helpers/animated_properties.mako.rs +++ b/components/style/properties/helpers/animated_properties.mako.rs @@ -44,7 +44,7 @@ use values::computed::{LengthOrPercentageOrNone, MaxLength}; use values::computed::{NonNegativeNumber, Number, NumberOrPercentage, Percentage}; use values::computed::length::NonNegativeLengthOrPercentage; use values::computed::ToComputedValue; -use values::computed::transform::{DirectionVector, Matrix3D}; +use values::computed::transform::{DirectionVector, Matrix, Matrix3D}; use values::generics::transform::{Transform, TransformOperation}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; #[cfg(feature = "gecko")] use values::generics::FontSettings as GenericFontSettings; @@ -1033,7 +1033,14 @@ impl Animate for ComputedTransformOperation { this.animate(other, procedure)?, )) }, - // XXXManishearth handle 2D matrix + ( + &TransformOperation::Matrix(ref this), + &TransformOperation::Matrix(ref other), + ) => { + Ok(TransformOperation::Matrix( + this.animate(other, procedure)?, + )) + }, ( &TransformOperation::Skew(ref fx, ref fy), &TransformOperation::Skew(ref tx, ref ty), @@ -1444,6 +1451,32 @@ impl Animate for Matrix3D { } } +impl Animate for Matrix { + #[cfg(feature = "servo")] + fn animate(&self, other: &Self, procedure: Procedure) -> Result { + let this = Matrix3D::from(*self); + let other = Matrix3D::from(*other); + let this = MatrixDecomposed2D::from(this); + let other = MatrixDecomposed2D::from(other); + Ok(Matrix3D::from(this.animate(&other, procedure)?).into_2d()?) + } + + #[cfg(feature = "gecko")] + fn animate(&self, other: &Self, procedure: Procedure) -> Result { + let from = decompose_2d_matrix(&(*self).into()); + let to = decompose_2d_matrix(&(*other).into()); + match (from, to) { + (Ok(from), Ok(to)) => { + Matrix3D::from(from.animate(&to, procedure)?).into_2d() + }, + // Matrices can be undecomposable due to couple reasons, e.g., + // non-invertible matrices. In this case, we should report Err here, + // and let the caller do the fallback procedure. + _ => Err(()) + } + } +} + impl ComputeSquaredDistance for Matrix3D { #[inline] #[cfg(feature = "servo")] diff --git a/components/style/values/computed/transform.rs b/components/style/values/computed/transform.rs index 4c90a01b3d1..4c909a53585 100644 --- a/components/style/values/computed/transform.rs +++ b/components/style/values/computed/transform.rs @@ -63,6 +63,22 @@ impl Matrix3D { m41: 0., m42: 0., m43: 0., m44: 1.0 } } + + /// Convert to a 2D Matrix + pub fn into_2d(self) -> Result { + if self.m13 == 0. && self.m23 == 0. && + self.m31 == 0. && self.m32 == 0. && + self.m33 == 1. && self.m34 == 0. && + self.m14 == 0. && self.m24 == 0. && + self.m43 == 0. && self.m44 == 1. { + Ok(Matrix { + a: self.m11, c: self.m21, e: self.m41, + b: self.m12, d: self.m22, f: self.m42, + }) + } else { + Err(()) + } + } } impl PrefixedMatrix3D { @@ -84,10 +100,21 @@ impl Matrix { /// Get an identity matrix pub fn identity() -> Self { Self { - a: 1., c: 0., /* 0 */e: 0., - b: 0., d: 1., /* 0 */f: 0., + a: 1., c: 0., /* 0 0*/ + b: 0., d: 1., /* 0 0*/ /* 0 0 1 0 */ - /* 0 0 0 1 */ + e: 0., f: 0., /* 0 1 */ + } + } +} + +impl From for Matrix3D { + fn from(m: Matrix) -> Self { + Self { + m11: m.a, m12: m.b, m13: 0.0, m14: 0.0, + m21: m.c, m22: m.d, m23: 0.0, m24: 0.0, + m31: 0.0, m32: 0.0, m33: 1.0, m34: 0.0, + m41: m.e, m42: m.f, m43: 0.0, m44: 1.0 } } } @@ -97,10 +124,10 @@ impl PrefixedMatrix { /// Get an identity matrix pub fn identity() -> Self { Self { - a: 1., c: 0., /* 0 */e: Either::First(0.), - b: 0., d: 1., /* 0 */f: Either::First(0.), - /* 0 0 1 0 */ - /* 0 0 0 1 */ + a: 1., c: 0., /* 0 0 */ + b: 0., d: 1., /* 0 0 */ + /* 0 0 1 0 */ + e: Either::First(0.), f: Either::First(0.), /* 0 1 */ } } } @@ -240,10 +267,7 @@ impl ToAnimatedZero for TransformOperation { GenericTransformOperation::Scale3D(..) => { Ok(GenericTransformOperation::Scale3D(1.0, 1.0, 1.0)) }, - GenericTransformOperation::Scale(_, None) => { - Ok(GenericTransformOperation::Scale(1.0, None)) - }, - GenericTransformOperation::Scale(_, Some(_)) => { + GenericTransformOperation::Scale(_, _) => { Ok(GenericTransformOperation::Scale(1.0, Some(1.0))) }, GenericTransformOperation::ScaleX(..) => { From 9c9a181f35280dabb5e089d9ae5df3fab1f6df1f Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Mon, 30 Oct 2017 18:01:32 -0700 Subject: [PATCH 15/21] Allow cross interpolation between differing translate/scale functions See ToPrimitive() in StyleAnimationValue.cpp --- .../style/properties/helpers/animated_properties.mako.rs | 7 ++++++- components/style/values/computed/length.rs | 5 +++++ components/style/values/generics/transform.rs | 1 - components/style/values/specified/transform.rs | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/components/style/properties/helpers/animated_properties.mako.rs b/components/style/properties/helpers/animated_properties.mako.rs index 7563dc3979e..5a8e766b7e2 100644 --- a/components/style/properties/helpers/animated_properties.mako.rs +++ b/components/style/properties/helpers/animated_properties.mako.rs @@ -1226,7 +1226,12 @@ impl Animate for ComputedTransformOperation { fd_matrix.animate(&td_matrix, procedure)?, )) }, - // XXXManishearth handle crossover between translate and scale functions + (ref f, ref t) if f.is_translate() && t.is_translate() => { + f.to_translate_3d().animate(&t.to_translate_3d(), procedure) + } + (ref f, ref t) if f.is_scale() && t.is_scale() => { + f.to_scale_3d().animate(&t.to_scale_3d(), procedure) + } _ => Err(()), } } diff --git a/components/style/values/computed/length.rs b/components/style/values/computed/length.rs index 8cb69b65b17..ece797dd224 100644 --- a/components/style/values/computed/length.rs +++ b/components/style/values/computed/length.rs @@ -706,6 +706,11 @@ impl CSSPixelLength { pub fn abs(self) -> Self { CSSPixelLength::new(self.0.abs()) } + + /// Zero value + pub fn zero() -> Self { + CSSPixelLength::new(0.) + } } impl ToCss for CSSPixelLength { diff --git a/components/style/values/generics/transform.rs b/components/style/values/generics/transform.rs index b663babf279..2bbf641b834 100644 --- a/components/style/values/generics/transform.rs +++ b/components/style/values/generics/transform.rs @@ -249,7 +249,6 @@ pub struct Transform(pub Vec); impl TransformOperation { - /// Check if it is any translate function pub fn is_translate(&self) -> bool { use self::TransformOperation::*; diff --git a/components/style/values/specified/transform.rs b/components/style/values/specified/transform.rs index b7e83cf4e3b..14bd00a1af5 100644 --- a/components/style/values/specified/transform.rs +++ b/components/style/values/specified/transform.rs @@ -10,8 +10,8 @@ use selectors::parser::SelectorParseErrorKind; use style_traits::{ParseError, StyleParseErrorKind}; use values::computed::{Context, LengthOrPercentage as ComputedLengthOrPercentage}; use values::computed::{Percentage as ComputedPercentage, ToComputedValue}; -use values::generics::transform::{Matrix3D, Transform as GenericTransform}; use values::computed::transform::TimingFunction as ComputedTimingFunction; +use values::generics::transform::{Matrix3D, Transform as GenericTransform}; use values::generics::transform::{StepPosition, TimingFunction as GenericTimingFunction, Matrix}; use values::generics::transform::{TimingKeyword, TransformOrigin as GenericTransformOrigin}; use values::generics::transform::TransformOperation as GenericTransformOperation; From ca02785e0204b8337ab44f476296f6c93d62f0c6 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Mon, 30 Oct 2017 18:52:55 -0700 Subject: [PATCH 16/21] Handle case of empty transform lists --- .../helpers/animated_properties.mako.rs | 57 ++++++++++++------- 1 file changed, 38 insertions(+), 19 deletions(-) diff --git a/components/style/properties/helpers/animated_properties.mako.rs b/components/style/properties/helpers/animated_properties.mako.rs index 5a8e766b7e2..1b7b0d806ad 100644 --- a/components/style/properties/helpers/animated_properties.mako.rs +++ b/components/style/properties/helpers/animated_properties.mako.rs @@ -2247,16 +2247,28 @@ impl Animate for ComputedTransform { #[inline] fn animate( &self, - other: &Self, + other_: &Self, procedure: Procedure, ) -> Result { - if self.0.is_empty() && other.0.is_empty() { + + let animate_equal_lists = |this: &[ComputedTransformOperation], + other: &[ComputedTransformOperation]| + -> Result { + Ok(Transform(this.iter().zip(other) + .map(|(this, other)| this.animate(other, procedure)) + .collect::, _>>()?)) + // If we can't animate for a pair of matched transform lists + // this means we have at least one undecomposable matrix, + // so we should bubble out Err here, and let the caller do + // the fallback procedure. + }; + if self.0.is_empty() && other_.0.is_empty() { return Ok(Transform(vec![])); } let this = &self.0; - let other = &other.0; + let other = &other_.0; if procedure == Procedure::Add { let result = this.iter().chain(other).cloned().collect::>(); @@ -2272,36 +2284,43 @@ impl Animate for ComputedTransform { }); if is_matched_transforms { - let result = this.iter().zip(other).map(|(this, other)| { - this.animate(other, procedure) - }).collect::, _>>(); - if let Ok(list) = result { - return Ok(Transform(list)); - } - - // Can't animate for a pair of matched transform lists? - // This means we have at least one undecomposable matrix, - // so we should report Err here, and let the caller do - // the fallback procedure. - return Err(()); + return animate_equal_lists(this, other); } } } // For mismatched transform lists. + let mut owned_this = this.clone(); + let mut owned_other = other.clone(); + + if this.is_empty() { + let this = other_.to_animated_zero()?.0; + if this.iter().zip(other).all(|(this, other)| is_matched_operation(this, other)) { + return animate_equal_lists(&this, other) + } + owned_this = this; + } + if other.is_empty() { + let other = self.to_animated_zero()?.0; + if this.iter().zip(&other).all(|(this, other)| is_matched_operation(this, other)) { + return animate_equal_lists(this, &other) + } + owned_other = other; + } + match procedure { Procedure::Add => Err(()), Procedure::Interpolate { progress } => { Ok(Transform(vec![TransformOperation::InterpolateMatrix { - from_list: Transform(this.clone()), - to_list: Transform(other.clone()), + from_list: Transform(owned_this), + to_list: Transform(owned_other), progress: Percentage(progress as f32), }])) }, Procedure::Accumulate { count } => { Ok(Transform(vec![TransformOperation::AccumulateMatrix { - from_list: Transform(this.clone()), - to_list: Transform(other.clone()), + from_list: Transform(owned_this), + to_list: Transform(owned_other), count: cmp::min(count, i32::max_value() as u64) as i32, }])) }, From 5098948c0d809082b2e20f7b3433a992ee600d09 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Tue, 31 Oct 2017 00:50:59 -0700 Subject: [PATCH 17/21] Handle distance calculation of new variants --- .../helpers/animated_properties.mako.rs | 82 ++++++++++++++----- 1 file changed, 62 insertions(+), 20 deletions(-) diff --git a/components/style/properties/helpers/animated_properties.mako.rs b/components/style/properties/helpers/animated_properties.mako.rs index 1b7b0d806ad..7f637fa26cd 100644 --- a/components/style/properties/helpers/animated_properties.mako.rs +++ b/components/style/properties/helpers/animated_properties.mako.rs @@ -18,8 +18,6 @@ use properties::longhands::font_weight::computed_value::T as FontWeight; use properties::longhands::font_stretch::computed_value::T as FontStretch; #[cfg(feature = "gecko")] use properties::longhands::font_variation_settings::computed_value::T as FontVariationSettings; -use properties::longhands::transform::computed_value::ComputedOperation as ComputedTransformOperation; -use properties::longhands::transform::computed_value::T as ComputedTransform; use properties::longhands::visibility::computed_value::T as Visibility; #[cfg(feature = "gecko")] use properties::PropertyId; @@ -45,6 +43,8 @@ use values::computed::{NonNegativeNumber, Number, NumberOrPercentage, Percentage use values::computed::length::NonNegativeLengthOrPercentage; use values::computed::ToComputedValue; use values::computed::transform::{DirectionVector, Matrix, Matrix3D}; +use values::computed::transform::TransformOperation as ComputedTransformOperation; +use values::computed::transform::Transform as ComputedTransform; use values::generics::transform::{Transform, TransformOperation}; use values::distance::{ComputeSquaredDistance, SquaredDistance}; #[cfg(feature = "gecko")] use values::generics::FontSettings as GenericFontSettings; @@ -1226,11 +1226,11 @@ impl Animate for ComputedTransformOperation { fd_matrix.animate(&td_matrix, procedure)?, )) }, - (ref f, ref t) if f.is_translate() && t.is_translate() => { - f.to_translate_3d().animate(&t.to_translate_3d(), procedure) + _ if self.is_translate() && other.is_translate() => { + self.to_translate_3d().animate(&other.to_translate_3d(), procedure) } - (ref f, ref t) if f.is_scale() && t.is_scale() => { - f.to_scale_3d().animate(&t.to_scale_3d(), procedure) + _ if self.is_scale() && other.is_scale() => { + self.to_scale_3d().animate(&other.to_scale_3d(), procedure) } _ => Err(()), } @@ -2334,6 +2334,19 @@ impl Animate for ComputedTransform { // See https://bugzilla.mozilla.org/show_bug.cgi?id=1318591#c0. impl ComputeSquaredDistance for ComputedTransformOperation { fn compute_squared_distance(&self, other: &Self) -> Result { + // For translate, We don't want to require doing layout in order to calculate the result, so + // drop the percentage part. However, dropping percentage makes us impossible to + // compute the distance for the percentage-percentage case, but Gecko uses the + // same formula, so it's fine for now. + // Note: We use pixel value to compute the distance for translate, so we have to + // convert Au into px. + let extract_pixel_length = |lop: &LengthOrPercentage| { + match *lop { + LengthOrPercentage::Length(px) => px.px(), + LengthOrPercentage::Percentage(_) => 0., + LengthOrPercentage::Calc(calc) => calc.length().px(), + } + }; match (self, other) { ( &TransformOperation::Matrix3D(ref this), @@ -2341,6 +2354,16 @@ impl ComputeSquaredDistance for ComputedTransformOperation { ) => { this.compute_squared_distance(other) }, + ( + &TransformOperation::Matrix(ref this), + &TransformOperation::Matrix(ref other), + ) => { + let this: Matrix3D = (*this).into(); + let other: Matrix3D = (*other).into(); + this.compute_squared_distance(&other) + }, + + ( &TransformOperation::Skew(ref fx, ref fy), &TransformOperation::Skew(ref tx, ref ty), @@ -2350,24 +2373,19 @@ impl ComputeSquaredDistance for ComputedTransformOperation { fy.compute_squared_distance(&ty)?, ) }, + ( + &TransformOperation::SkewX(ref f), + &TransformOperation::SkewX(ref t), + ) | ( + &TransformOperation::SkewY(ref f), + &TransformOperation::SkewY(ref t), + ) => { + f.compute_squared_distance(&t) + }, ( &TransformOperation::Translate3D(ref fx, ref fy, ref fz), &TransformOperation::Translate3D(ref tx, ref ty, ref tz), ) => { - // We don't want to require doing layout in order to calculate the result, so - // drop the percentage part. However, dropping percentage makes us impossible to - // compute the distance for the percentage-percentage case, but Gecko uses the - // same formula, so it's fine for now. - // Note: We use pixel value to compute the distance for translate, so we have to - // convert Au into px. - let extract_pixel_length = |lop: &LengthOrPercentage| { - match *lop { - LengthOrPercentage::Length(px) => px.px(), - LengthOrPercentage::Percentage(_) => 0., - LengthOrPercentage::Calc(calc) => calc.length().px(), - } - }; - let fx = extract_pixel_length(&fx); let fy = extract_pixel_length(&fy); let tx = extract_pixel_length(&tx); @@ -2407,6 +2425,24 @@ impl ComputeSquaredDistance for ComputedTransformOperation { q1.compute_squared_distance(&q2) } } + ( + &TransformOperation::RotateX(fa), + &TransformOperation::RotateX(ta), + ) | + ( + &TransformOperation::RotateY(fa), + &TransformOperation::RotateY(ta), + ) | + ( + &TransformOperation::RotateZ(fa), + &TransformOperation::RotateZ(ta), + ) | + ( + &TransformOperation::Rotate(fa), + &TransformOperation::Rotate(ta), + ) => { + fa.compute_squared_distance(&ta) + } ( &TransformOperation::Perspective(ref fd), &TransformOperation::Perspective(ref td), @@ -2435,6 +2471,12 @@ impl ComputeSquaredDistance for ComputedTransformOperation { } p_matrix.compute_squared_distance(&m) } + _ if self.is_translate() && other.is_translate() => { + self.to_translate_3d().compute_squared_distance(&other.to_translate_3d()) + } + _ if self.is_scale() && other.is_scale() => { + self.to_scale_3d().compute_squared_distance(&other.to_scale_3d()) + } _ => Err(()), } } From 6415294fd5556c33d17cbd1f87c78d8820e3a994 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Tue, 31 Oct 2017 14:17:48 -0700 Subject: [PATCH 18/21] Fix unit tests --- components/style/values/computed/transform.rs | 2 +- tests/unit/style/animated_properties.rs | 89 +++++++++---------- tests/unit/style/properties/serialization.rs | 25 +++--- 3 files changed, 58 insertions(+), 58 deletions(-) diff --git a/components/style/values/computed/transform.rs b/components/style/values/computed/transform.rs index 4c909a53585..dc5f6de17e1 100644 --- a/components/style/values/computed/transform.rs +++ b/components/style/values/computed/transform.rs @@ -12,8 +12,8 @@ use values::animated::ToAnimatedZero; use values::computed::{Angle, Integer, Length, LengthOrPercentage, Number, Percentage}; use values::computed::{LengthOrNumber, LengthOrPercentageOrNumber}; use values::generics::transform::{Matrix as GenericMatrix, Matrix3D as GenericMatrix3D}; -use values::generics::transform::TimingFunction as GenericTimingFunction; use values::generics::transform::{Transform as GenericTransform, TransformOperation as GenericTransformOperation}; +use values::generics::transform::TimingFunction as GenericTimingFunction; use values::generics::transform::TransformOrigin as GenericTransformOrigin; /// A single operation in a computed CSS `transform` diff --git a/tests/unit/style/animated_properties.rs b/tests/unit/style/animated_properties.rs index bdaa65dde7f..a884321369f 100644 --- a/tests/unit/style/animated_properties.rs +++ b/tests/unit/style/animated_properties.rs @@ -3,10 +3,9 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; -use style::properties::longhands::transform::computed_value::ComputedOperation as TransformOperation; -use style::properties::longhands::transform::computed_value::T as TransformList; use style::values::animated::{Animate, Procedure, ToAnimatedValue}; use style::values::computed::Percentage; +use style::values::generics::transform::{Transform, TransformOperation}; fn interpolate_rgba(from: RGBA, to: RGBA, progress: f64) -> RGBA { let from = from.to_animated_value(); @@ -66,35 +65,35 @@ fn test_rgba_color_interepolation_out_of_range_clamped_2() { fn test_transform_interpolation_on_translate() { use style::values::computed::{CalcLengthOrPercentage, Length, LengthOrPercentage}; - let from = TransformList(Some(vec![ - TransformOperation::Translate(LengthOrPercentage::Length(Length::new(0.)), - LengthOrPercentage::Length(Length::new(100.)), - Length::new(25.))])); - let to = TransformList(Some(vec![ - TransformOperation::Translate(LengthOrPercentage::Length(Length::new(100.)), - LengthOrPercentage::Length(Length::new(0.)), - Length::new(75.))])); + let from = Transform(vec![ + TransformOperation::Translate3D(LengthOrPercentage::Length(Length::new(0.)), + LengthOrPercentage::Length(Length::new(100.)), + Length::new(25.))]); + let to = Transform(vec![ + TransformOperation::Translate3D(LengthOrPercentage::Length(Length::new(100.)), + LengthOrPercentage::Length(Length::new(0.)), + Length::new(75.))]); assert_eq!( from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(), - TransformList(Some(vec![TransformOperation::Translate( + Transform(vec![TransformOperation::Translate3D( LengthOrPercentage::Length(Length::new(50.)), LengthOrPercentage::Length(Length::new(50.)), Length::new(50.), - )])) + )]) ); - let from = TransformList(Some(vec![TransformOperation::Translate( + let from = Transform(vec![TransformOperation::Translate3D( LengthOrPercentage::Percentage(Percentage(0.5)), LengthOrPercentage::Percentage(Percentage(1.0)), Length::new(25.), - )])); - let to = TransformList(Some(vec![ - TransformOperation::Translate(LengthOrPercentage::Length(Length::new(100.)), - LengthOrPercentage::Length(Length::new(50.)), - Length::new(75.))])); + )]); + let to = Transform(vec![ + TransformOperation::Translate3D(LengthOrPercentage::Length(Length::new(100.)), + LengthOrPercentage::Length(Length::new(50.)), + Length::new(75.))]); assert_eq!( from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(), - TransformList(Some(vec![TransformOperation::Translate( + Transform(vec![TransformOperation::Translate3D( // calc(50px + 25%) LengthOrPercentage::Calc(CalcLengthOrPercentage::new(Length::new(50.), Some(Percentage(0.25)))), @@ -102,17 +101,17 @@ fn test_transform_interpolation_on_translate() { LengthOrPercentage::Calc(CalcLengthOrPercentage::new(Length::new(25.), Some(Percentage(0.5)))), Length::new(50.), - )])) + )]) ); } #[test] fn test_transform_interpolation_on_scale() { - let from = TransformList(Some(vec![TransformOperation::Scale(1.0, 2.0, 1.0)])); - let to = TransformList(Some(vec![TransformOperation::Scale(2.0, 4.0, 2.0)])); + let from = Transform(vec![TransformOperation::Scale3D(1.0, 2.0, 1.0)]); + let to = Transform(vec![TransformOperation::Scale3D(2.0, 4.0, 2.0)]); assert_eq!( from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(), - TransformList(Some(vec![TransformOperation::Scale(1.5, 3.0, 1.5)])) + Transform(vec![TransformOperation::Scale3D(1.5, 3.0, 1.5)]) ); } @@ -120,15 +119,15 @@ fn test_transform_interpolation_on_scale() { fn test_transform_interpolation_on_rotate() { use style::values::computed::Angle; - let from = TransformList(Some(vec![TransformOperation::Rotate(0.0, 0.0, 1.0, - Angle::from_radians(0.0))])); - let to = TransformList(Some(vec![TransformOperation::Rotate(0.0, 0.0, 1.0, - Angle::from_radians(100.0))])); + let from = Transform(vec![TransformOperation::Rotate3D(0.0, 0.0, 1.0, + Angle::from_radians(0.0))]); + let to = Transform(vec![TransformOperation::Rotate3D(0.0, 0.0, 1.0, + Angle::from_radians(100.0))]); assert_eq!( from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(), - TransformList(Some(vec![ - TransformOperation::Rotate(0.0, 0.0, 1.0, Angle::from_radians(50.0)), - ])) + Transform(vec![ + TransformOperation::Rotate3D(0.0, 0.0, 1.0, Angle::from_radians(50.0)), + ]) ); } @@ -136,16 +135,16 @@ fn test_transform_interpolation_on_rotate() { fn test_transform_interpolation_on_skew() { use style::values::computed::Angle; - let from = TransformList(Some(vec![TransformOperation::Skew(Angle::from_radians(0.0), - Angle::from_radians(100.0))])); - let to = TransformList(Some(vec![TransformOperation::Skew(Angle::from_radians(100.0), - Angle::from_radians(0.0))])); + let from = Transform(vec![TransformOperation::Skew(Angle::from_radians(0.0), + Some(Angle::from_radians(100.0)))]); + let to = Transform(vec![TransformOperation::Skew(Angle::from_radians(100.0), + Some(Angle::from_radians(0.0)))]); assert_eq!( from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(), - TransformList(Some(vec![TransformOperation::Skew( + Transform(vec![TransformOperation::Skew( Angle::from_radians(50.0), - Angle::from_radians(50.0), - )])) + Some(Angle::from_radians(50.0)), + )]) ); } @@ -153,18 +152,18 @@ fn test_transform_interpolation_on_skew() { fn test_transform_interpolation_on_mismatched_lists() { use style::values::computed::{Angle, Length, LengthOrPercentage}; - let from = TransformList(Some(vec![TransformOperation::Rotate(0.0, 0.0, 1.0, - Angle::from_radians(100.0))])); - let to = TransformList(Some(vec![ - TransformOperation::Translate(LengthOrPercentage::Length(Length::new(100.)), - LengthOrPercentage::Length(Length::new(0.)), - Length::new(0.))])); + let from = Transform(vec![TransformOperation::Rotate3D(0.0, 0.0, 1.0, + Angle::from_radians(100.0))]); + let to = Transform(vec![ + TransformOperation::Translate3D(LengthOrPercentage::Length(Length::new(100.)), + LengthOrPercentage::Length(Length::new(0.)), + Length::new(0.))]); assert_eq!( from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(), - TransformList(Some(vec![TransformOperation::InterpolateMatrix { + Transform(vec![TransformOperation::InterpolateMatrix { from_list: from.clone(), to_list: to.clone(), progress: Percentage(0.5), - }])) + }]) ); } diff --git a/tests/unit/style/properties/serialization.rs b/tests/unit/style/properties/serialization.rs index 3216293ab75..2285cd9c004 100644 --- a/tests/unit/style/properties/serialization.rs +++ b/tests/unit/style/properties/serialization.rs @@ -725,8 +725,9 @@ mod shorthand_serialization { mod transform { pub use super::*; - use style::properties::longhands::transform::SpecifiedOperation; + use style::values::generics::transform::TransformOperation; use style::values::specified::{Angle, Number}; + use style::values::specified::transform::TransformOperation as SpecifiedOperation; #[test] fn should_serialize_none_correctly() { @@ -736,41 +737,41 @@ mod shorthand_serialization { } #[inline(always)] - fn validate_serialization(op: &T, expected_string: &'static str) { + fn validate_serialization(op: &SpecifiedOperation, expected_string: &'static str) { let css_string = op.to_css_string(); assert_eq!(css_string, expected_string); } #[test] fn transform_scale() { - validate_serialization(&SpecifiedOperation::Scale(Number::new(1.3), None), "scale(1.3)"); + validate_serialization(&TransformOperation::Scale(Number::new(1.3), None), "scale(1.3)"); validate_serialization( - &SpecifiedOperation::Scale(Number::new(2.0), Some(Number::new(2.0))), + &TransformOperation::Scale(Number::new(2.0), Some(Number::new(2.0))), "scale(2, 2)"); - validate_serialization(&SpecifiedOperation::ScaleX(Number::new(42.0)), "scaleX(42)"); - validate_serialization(&SpecifiedOperation::ScaleY(Number::new(0.3)), "scaleY(0.3)"); - validate_serialization(&SpecifiedOperation::ScaleZ(Number::new(1.0)), "scaleZ(1)"); + validate_serialization(&TransformOperation::ScaleX(Number::new(42.0)), "scaleX(42)"); + validate_serialization(&TransformOperation::ScaleY(Number::new(0.3)), "scaleY(0.3)"); + validate_serialization(&TransformOperation::ScaleZ(Number::new(1.0)), "scaleZ(1)"); validate_serialization( - &SpecifiedOperation::Scale3D(Number::new(4.0), Number::new(5.0), Number::new(6.0)), + &TransformOperation::Scale3D(Number::new(4.0), Number::new(5.0), Number::new(6.0)), "scale3d(4, 5, 6)"); } #[test] fn transform_skew() { validate_serialization( - &SpecifiedOperation::Skew(Angle::from_degrees(42.3, false), None), + &TransformOperation::Skew(Angle::from_degrees(42.3, false), None), "skew(42.3deg)"); validate_serialization( - &SpecifiedOperation::Skew(Angle::from_gradians(-50.0, false), Some(Angle::from_turns(0.73, false))), + &TransformOperation::Skew(Angle::from_gradians(-50.0, false), Some(Angle::from_turns(0.73, false))), "skew(-50grad, 0.73turn)"); validate_serialization( - &SpecifiedOperation::SkewX(Angle::from_radians(0.31, false)), "skewX(0.31rad)"); + &TransformOperation::SkewX(Angle::from_radians(0.31, false)), "skewX(0.31rad)"); } #[test] fn transform_rotate() { validate_serialization( - &SpecifiedOperation::Rotate(Angle::from_turns(35.0, false)), + &TransformOperation::Rotate(Angle::from_turns(35.0, false)), "rotate(35turn)" ) } From 1c12e0ebc6ac7ffab2391acac5e231589261f26e Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Wed, 1 Nov 2017 15:37:24 -0700 Subject: [PATCH 19/21] Rustfmt the new files --- components/style/values/computed/transform.rs | 269 ++++++++---------- components/style/values/generics/transform.rs | 97 +++++-- .../style/values/specified/transform.rs | 86 +++--- 3 files changed, 246 insertions(+), 206 deletions(-) diff --git a/components/style/values/computed/transform.rs b/components/style/values/computed/transform.rs index dc5f6de17e1..3be9816b34c 100644 --- a/components/style/values/computed/transform.rs +++ b/components/style/values/computed/transform.rs @@ -17,8 +17,15 @@ use values::generics::transform::TimingFunction as GenericTimingFunction; use values::generics::transform::TransformOrigin as GenericTransformOrigin; /// A single operation in a computed CSS `transform` -pub type TransformOperation = GenericTransformOperation; +pub type TransformOperation = GenericTransformOperation< + Angle, + Number, + Length, + Integer, + LengthOrNumber, + LengthOrPercentage, + LengthOrPercentageOrNumber, +>; /// A computed CSS `transform` pub type Transform = GenericTransform; @@ -52,6 +59,7 @@ pub type Matrix = GenericMatrix; /// computed value of matrix() in -moz-transform pub type PrefixedMatrix = GenericMatrix; +#[cfg_attr(rustfmt, rustfmt_skip)] impl Matrix3D { #[inline] /// Get an identity matrix @@ -81,6 +89,7 @@ impl Matrix3D { } } +#[cfg_attr(rustfmt, rustfmt_skip)] impl PrefixedMatrix3D { #[inline] /// Get an identity matrix @@ -95,6 +104,7 @@ impl PrefixedMatrix3D { } } +#[cfg_attr(rustfmt, rustfmt_skip)] impl Matrix { #[inline] /// Get an identity matrix @@ -108,6 +118,7 @@ impl Matrix { } } +#[cfg_attr(rustfmt, rustfmt_skip)] impl From for Matrix3D { fn from(m: Matrix) -> Self { Self { @@ -119,6 +130,7 @@ impl From for Matrix3D { } } +#[cfg_attr(rustfmt, rustfmt_skip)] impl PrefixedMatrix { #[inline] /// Get an identity matrix @@ -132,6 +144,7 @@ impl PrefixedMatrix { } } +#[cfg_attr(rustfmt, rustfmt_skip)] impl From for Transform3D { #[inline] fn from(m: Matrix3D) -> Self { @@ -143,6 +156,7 @@ impl From for Transform3D { } } +#[cfg_attr(rustfmt, rustfmt_skip)] impl From> for Matrix3D { #[inline] fn from(m: Transform3D) -> Self { @@ -155,6 +169,7 @@ impl From> for Matrix3D { } } +#[cfg_attr(rustfmt, rustfmt_skip)] impl From for Transform3D { #[inline] fn from(m: Matrix) -> Self { @@ -174,16 +189,23 @@ impl TransformOperation { match *self { GenericTransformOperation::Translate3D(..) => self.clone(), GenericTransformOperation::TranslateX(ref x) | - GenericTransformOperation::Translate(ref x, None) => - GenericTransformOperation::Translate3D(x.clone(), LengthOrPercentage::zero(), Length::zero()), - GenericTransformOperation::Translate(ref x, Some(ref y)) => - GenericTransformOperation::Translate3D(x.clone(), y.clone(), Length::zero()), - GenericTransformOperation::TranslateY(ref y) => - GenericTransformOperation::Translate3D(LengthOrPercentage::zero(), y.clone(), Length::zero()), - GenericTransformOperation::TranslateZ(ref z) => - GenericTransformOperation::Translate3D(LengthOrPercentage::zero(), - LengthOrPercentage::zero(), z.clone()), - _ => unreachable!() + GenericTransformOperation::Translate(ref x, None) => { + GenericTransformOperation::Translate3D(x.clone(), LengthOrPercentage::zero(), Length::zero()) + }, + GenericTransformOperation::Translate(ref x, Some(ref y)) => { + GenericTransformOperation::Translate3D(x.clone(), y.clone(), Length::zero()) + }, + GenericTransformOperation::TranslateY(ref y) => { + GenericTransformOperation::Translate3D(LengthOrPercentage::zero(), y.clone(), Length::zero()) + }, + GenericTransformOperation::TranslateZ(ref z) => { + GenericTransformOperation::Translate3D( + LengthOrPercentage::zero(), + LengthOrPercentage::zero(), + z.clone(), + ) + }, + _ => unreachable!(), } } /// Convert to a Scale3D. @@ -197,7 +219,7 @@ impl TransformOperation { GenericTransformOperation::ScaleX(x) => GenericTransformOperation::Scale3D(x, 1., 1.), GenericTransformOperation::ScaleY(y) => GenericTransformOperation::Scale3D(1., y, 1.), GenericTransformOperation::ScaleZ(z) => GenericTransformOperation::Scale3D(1., 1., z), - _ => unreachable!() + _ => unreachable!(), } } } @@ -208,17 +230,17 @@ impl TransformOperation { impl ToAnimatedZero for TransformOperation { fn to_animated_zero(&self) -> Result { match *self { - GenericTransformOperation::Matrix3D(..) => { - Ok(GenericTransformOperation::Matrix3D(Matrix3D::identity())) - }, + GenericTransformOperation::Matrix3D(..) => Ok(GenericTransformOperation::Matrix3D(Matrix3D::identity())), GenericTransformOperation::PrefixedMatrix3D(..) => { - Ok(GenericTransformOperation::PrefixedMatrix3D(PrefixedMatrix3D::identity())) - }, - GenericTransformOperation::Matrix(..) => { - Ok(GenericTransformOperation::Matrix(Matrix::identity())) + Ok(GenericTransformOperation::PrefixedMatrix3D( + PrefixedMatrix3D::identity(), + )) }, + GenericTransformOperation::Matrix(..) => Ok(GenericTransformOperation::Matrix(Matrix::identity())), GenericTransformOperation::PrefixedMatrix(..) => { - Ok(GenericTransformOperation::PrefixedMatrix(PrefixedMatrix::identity())) + Ok(GenericTransformOperation::PrefixedMatrix( + PrefixedMatrix::identity(), + )) }, GenericTransformOperation::Skew(sx, sy) => { Ok(GenericTransformOperation::Skew( @@ -226,16 +248,8 @@ impl ToAnimatedZero for TransformOperation { sy.to_animated_zero()?, )) }, - GenericTransformOperation::SkewX(s) => { - Ok(GenericTransformOperation::SkewX( - s.to_animated_zero()?, - )) - }, - GenericTransformOperation::SkewY(s) => { - Ok(GenericTransformOperation::SkewY( - s.to_animated_zero()?, - )) - }, + GenericTransformOperation::SkewX(s) => Ok(GenericTransformOperation::SkewX(s.to_animated_zero()?)), + GenericTransformOperation::SkewY(s) => Ok(GenericTransformOperation::SkewY(s.to_animated_zero()?)), GenericTransformOperation::Translate3D(ref tx, ref ty, ref tz) => { Ok(GenericTransformOperation::Translate3D( tx.to_animated_zero()?, @@ -250,54 +264,34 @@ impl ToAnimatedZero for TransformOperation { )) }, GenericTransformOperation::TranslateX(ref t) => { - Ok(GenericTransformOperation::TranslateX( - t.to_animated_zero()?, - )) + Ok(GenericTransformOperation::TranslateX(t.to_animated_zero()?)) }, GenericTransformOperation::TranslateY(ref t) => { - Ok(GenericTransformOperation::TranslateY( - t.to_animated_zero()?, - )) + Ok(GenericTransformOperation::TranslateY(t.to_animated_zero()?)) }, GenericTransformOperation::TranslateZ(ref t) => { - Ok(GenericTransformOperation::TranslateZ( - t.to_animated_zero()?, - )) - }, - GenericTransformOperation::Scale3D(..) => { - Ok(GenericTransformOperation::Scale3D(1.0, 1.0, 1.0)) - }, - GenericTransformOperation::Scale(_, _) => { - Ok(GenericTransformOperation::Scale(1.0, Some(1.0))) - }, - GenericTransformOperation::ScaleX(..) => { - Ok(GenericTransformOperation::ScaleX(1.0)) - }, - GenericTransformOperation::ScaleY(..) => { - Ok(GenericTransformOperation::ScaleY(1.0)) - }, - GenericTransformOperation::ScaleZ(..) => { - Ok(GenericTransformOperation::ScaleZ(1.0)) + Ok(GenericTransformOperation::TranslateZ(t.to_animated_zero()?)) }, + GenericTransformOperation::Scale3D(..) => Ok(GenericTransformOperation::Scale3D(1.0, 1.0, 1.0)), + GenericTransformOperation::Scale(_, _) => Ok(GenericTransformOperation::Scale(1.0, Some(1.0))), + GenericTransformOperation::ScaleX(..) => Ok(GenericTransformOperation::ScaleX(1.0)), + GenericTransformOperation::ScaleY(..) => Ok(GenericTransformOperation::ScaleY(1.0)), + GenericTransformOperation::ScaleZ(..) => Ok(GenericTransformOperation::ScaleZ(1.0)), GenericTransformOperation::Rotate3D(x, y, z, a) => { let (x, y, z, _) = Transform::get_normalized_vector_and_angle(x, y, z, a); Ok(GenericTransformOperation::Rotate3D(x, y, z, Angle::zero())) }, - GenericTransformOperation::RotateX(_) => { - Ok(GenericTransformOperation::RotateX(Angle::zero())) - }, - GenericTransformOperation::RotateY(_) => { - Ok(GenericTransformOperation::RotateY(Angle::zero())) - }, - GenericTransformOperation::RotateZ(_) => { - Ok(GenericTransformOperation::RotateZ(Angle::zero())) - }, - GenericTransformOperation::Rotate(_) => { - Ok(GenericTransformOperation::Rotate(Angle::zero())) - }, + GenericTransformOperation::RotateX(_) => Ok(GenericTransformOperation::RotateX(Angle::zero())), + GenericTransformOperation::RotateY(_) => Ok(GenericTransformOperation::RotateY(Angle::zero())), + GenericTransformOperation::RotateZ(_) => Ok(GenericTransformOperation::RotateZ(Angle::zero())), + GenericTransformOperation::Rotate(_) => Ok(GenericTransformOperation::Rotate(Angle::zero())), GenericTransformOperation::Perspective(..) | - GenericTransformOperation::AccumulateMatrix { .. } | - GenericTransformOperation::InterpolateMatrix { .. } => { + GenericTransformOperation::AccumulateMatrix { + .. + } | + GenericTransformOperation::InterpolateMatrix { + .. + } => { // Perspective: We convert a perspective function into an equivalent // ComputedMatrix, and then decompose/interpolate/recompose these matrices. // AccumulateMatrix/InterpolateMatrix: We do interpolation on @@ -316,9 +310,10 @@ impl ToAnimatedZero for TransformOperation { impl ToAnimatedZero for Transform { #[inline] fn to_animated_zero(&self) -> Result { - Ok(GenericTransform( - self.0.iter().map(|op| op.to_animated_zero()).collect::, _>>()? - )) + Ok(GenericTransform(self.0 + .iter() + .map(|op| op.to_animated_zero()) + .collect::, _>>()?)) } } @@ -326,150 +321,131 @@ impl Transform { /// Return the equivalent 3d matrix of this transform list. /// If |reference_box| is None, we will drop the percent part from translate because /// we can resolve it without the layout info. - pub fn to_transform_3d_matrix(&self, reference_box: Option<&Rect>) - -> Option> { + pub fn to_transform_3d_matrix(&self, reference_box: Option<&Rect>) -> Option> { let mut transform = Transform3D::identity(); let list = &self.0; if list.len() == 0 { return None; } - let extract_pixel_length = |lop: &LengthOrPercentage| { - match *lop { - LengthOrPercentage::Length(px) => px.px(), - LengthOrPercentage::Percentage(_) => 0., - LengthOrPercentage::Calc(calc) => calc.length().px(), - } + let extract_pixel_length = |lop: &LengthOrPercentage| match *lop { + LengthOrPercentage::Length(px) => px.px(), + LengthOrPercentage::Percentage(_) => 0., + LengthOrPercentage::Calc(calc) => calc.length().px(), }; for operation in list { let matrix = match *operation { GenericTransformOperation::Rotate3D(ax, ay, az, theta) => { let theta = Angle::from_radians(2.0f32 * f32::consts::PI - theta.radians()); - let (ax, ay, az, theta) = - Self::get_normalized_vector_and_angle(ax, ay, az, theta); + let (ax, ay, az, theta) = Self::get_normalized_vector_and_angle(ax, ay, az, theta); Transform3D::create_rotation(ax, ay, az, theta.into()) - } + }, GenericTransformOperation::RotateX(theta) => { let theta = Angle::from_radians(2.0f32 * f32::consts::PI - theta.radians()); Transform3D::create_rotation(1., 0., 0., theta.into()) - } + }, GenericTransformOperation::RotateY(theta) => { let theta = Angle::from_radians(2.0f32 * f32::consts::PI - theta.radians()); Transform3D::create_rotation(0., 1., 0., theta.into()) - } - GenericTransformOperation::RotateZ(theta) | GenericTransformOperation::Rotate(theta) => { + }, + GenericTransformOperation::RotateZ(theta) | + GenericTransformOperation::Rotate(theta) => { let theta = Angle::from_radians(2.0f32 * f32::consts::PI - theta.radians()); Transform3D::create_rotation(0., 0., 1., theta.into()) - } - GenericTransformOperation::Perspective(d) => { - Self::create_perspective_matrix(d.px()) - } - GenericTransformOperation::Scale3D(sx, sy, sz) => { - Transform3D::create_scale(sx, sy, sz) - } - GenericTransformOperation::Scale(sx, sy) => { - Transform3D::create_scale(sx, sy.unwrap_or(sx), 1.) - } - GenericTransformOperation::ScaleX(s) => { - Transform3D::create_scale(s, s, 1.) - } - GenericTransformOperation::ScaleY(s) => { - Transform3D::create_scale(1., s, 1.) - } - GenericTransformOperation::ScaleZ(s) => { - Transform3D::create_scale(1., 1., s) - } + }, + GenericTransformOperation::Perspective(d) => Self::create_perspective_matrix(d.px()), + GenericTransformOperation::Scale3D(sx, sy, sz) => Transform3D::create_scale(sx, sy, sz), + GenericTransformOperation::Scale(sx, sy) => Transform3D::create_scale(sx, sy.unwrap_or(sx), 1.), + GenericTransformOperation::ScaleX(s) => Transform3D::create_scale(s, 1., 1.), + GenericTransformOperation::ScaleY(s) => Transform3D::create_scale(1., s, 1.), + GenericTransformOperation::ScaleZ(s) => Transform3D::create_scale(1., 1., s), GenericTransformOperation::Translate3D(tx, ty, tz) => { let (tx, ty) = match reference_box { Some(relative_border_box) => { - (tx.to_pixel_length(relative_border_box.size.width).px(), - ty.to_pixel_length(relative_border_box.size.height).px()) + ( + tx.to_pixel_length(relative_border_box.size.width).px(), + ty.to_pixel_length(relative_border_box.size.height).px(), + ) }, None => { // If we don't have reference box, we cannot resolve the used value, // so only retrieve the length part. This will be used for computing // distance without any layout info. (extract_pixel_length(&tx), extract_pixel_length(&ty)) - } + }, }; let tz = tz.px(); Transform3D::create_translation(tx, ty, tz) - } + }, GenericTransformOperation::Translate(tx, Some(ty)) => { let (tx, ty) = match reference_box { Some(relative_border_box) => { - (tx.to_pixel_length(relative_border_box.size.width).px(), - ty.to_pixel_length(relative_border_box.size.height).px()) + ( + tx.to_pixel_length(relative_border_box.size.width).px(), + ty.to_pixel_length(relative_border_box.size.height).px(), + ) }, None => { // If we don't have reference box, we cannot resolve the used value, // so only retrieve the length part. This will be used for computing // distance without any layout info. (extract_pixel_length(&tx), extract_pixel_length(&ty)) - } + }, }; Transform3D::create_translation(tx, ty, 0.) - } - GenericTransformOperation::TranslateX(t) | GenericTransformOperation::Translate(t, None) => { + }, + GenericTransformOperation::TranslateX(t) | + GenericTransformOperation::Translate(t, None) => { let t = match reference_box { - Some(relative_border_box) => { - t.to_pixel_length(relative_border_box.size.width).px() - }, + Some(relative_border_box) => t.to_pixel_length(relative_border_box.size.width).px(), None => { // If we don't have reference box, we cannot resolve the used value, // so only retrieve the length part. This will be used for computing // distance without any layout info. extract_pixel_length(&t) - } + }, }; Transform3D::create_translation(t, 0., 0.) - } + }, GenericTransformOperation::TranslateY(t) => { let t = match reference_box { - Some(relative_border_box) => { - t.to_pixel_length(relative_border_box.size.height).px() - }, + Some(relative_border_box) => t.to_pixel_length(relative_border_box.size.height).px(), None => { // If we don't have reference box, we cannot resolve the used value, // so only retrieve the length part. This will be used for computing // distance without any layout info. extract_pixel_length(&t) - } + }, }; Transform3D::create_translation(0., t, 0.) - } - GenericTransformOperation::TranslateZ(z) => { - Transform3D::create_translation(0., 0., z.px()) - } + }, + GenericTransformOperation::TranslateZ(z) => Transform3D::create_translation(0., 0., z.px()), GenericTransformOperation::Skew(theta_x, theta_y) => { Transform3D::create_skew(theta_x.into(), theta_y.unwrap_or(Angle::zero()).into()) - } - GenericTransformOperation::SkewX(theta) => { - Transform3D::create_skew(theta.into(), Angle::zero().into()) - } - GenericTransformOperation::SkewY(theta) => { - Transform3D::create_skew(Angle::zero().into(), theta.into()) - } - GenericTransformOperation::Matrix3D(m) => { - m.into() - } - GenericTransformOperation::Matrix(m) => { - m.into() - } - GenericTransformOperation::PrefixedMatrix3D(_) | GenericTransformOperation::PrefixedMatrix(_) => { + }, + GenericTransformOperation::SkewX(theta) => Transform3D::create_skew(theta.into(), Angle::zero().into()), + GenericTransformOperation::SkewY(theta) => Transform3D::create_skew(Angle::zero().into(), theta.into()), + GenericTransformOperation::Matrix3D(m) => m.into(), + GenericTransformOperation::Matrix(m) => m.into(), + GenericTransformOperation::PrefixedMatrix3D(_) | + GenericTransformOperation::PrefixedMatrix(_) => { // `-moz-transform` is not implemented in Servo yet. unreachable!() - } - GenericTransformOperation::InterpolateMatrix { .. } | - GenericTransformOperation::AccumulateMatrix { .. } => { + }, + GenericTransformOperation::InterpolateMatrix { + .. + } | + GenericTransformOperation::AccumulateMatrix { + .. + } => { // TODO: Convert InterpolateMatrix/AccmulateMatrix into a valid Transform3D by // the reference box and do interpolation on these two Transform3D matrices. // Both Gecko and Servo don't support this for computing distance, and Servo // doesn't support animations on InterpolateMatrix/AccumulateMatrix, so // return None. return None; - } + }, }; transform = transform.pre_mul(&matrix); @@ -496,8 +472,7 @@ impl Transform { } /// Return the normalized direction vector and its angle for Rotate3D. - pub fn get_normalized_vector_and_angle(x: f32, y: f32, z: f32, angle: Angle) - -> (f32, f32, f32, Angle) { + pub fn get_normalized_vector_and_angle(x: f32, y: f32, z: f32, angle: Angle) -> (f32, f32, f32, Angle) { use euclid::approxeq::ApproxEq; use euclid::num::Zero; let vector = DirectionVector::new(x, y, z); diff --git a/components/style/values/generics/transform.rs b/components/style/values/generics/transform.rs index 2bbf641b834..45d19c8ab68 100644 --- a/components/style/values/generics/transform.rs +++ b/components/style/values/generics/transform.rs @@ -22,6 +22,7 @@ pub struct Matrix { } #[allow(missing_docs)] +#[cfg_attr(rustfmt, rustfmt_skip)] #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Matrix3D { pub m11: T, pub m12: T, pub m13: T, pub m14: T, @@ -51,7 +52,12 @@ pub enum TimingFunction { Keyword(TimingKeyword), /// `cubic-bezier(, , , )` #[allow(missing_docs)] - CubicBezier { x1: Number, y1: Number, x2: Number, y2: Number }, + CubicBezier { + x1: Number, + y1: Number, + x2: Number, + y2: Number, + }, /// `step-start | step-end | steps(, [ start | end ]?)` Steps(Integer, StepPosition), /// `frames()` @@ -103,7 +109,12 @@ where { match *self { TimingFunction::Keyword(keyword) => keyword.to_css(dest), - TimingFunction::CubicBezier { ref x1, ref y1, ref x2, ref y2 } => { + TimingFunction::CubicBezier { + ref x1, + ref y1, + ref x2, + ref y2, + } => { dest.write_str("cubic-bezier(")?; x1.to_css(dest)?; dest.write_str(", ")?; @@ -223,23 +234,63 @@ pub enum TransformOperation>, - #[compute(ignore_bound)] - to_list: Transform>, - #[compute(clone)] progress: computed::Percentage }, + InterpolateMatrix { + #[compute(ignore_bound)] + from_list: Transform< + TransformOperation< + Angle, + Number, + Length, + Integer, + LengthOrNumber, + LengthOrPercentage, + LoPoNumber, + >, + >, + #[compute(ignore_bound)] + to_list: Transform< + TransformOperation< + Angle, + Number, + Length, + Integer, + LengthOrNumber, + LengthOrPercentage, + LoPoNumber, + >, + >, + #[compute(clone)] + progress: computed::Percentage, + }, /// A intermediate type for accumulation of mismatched transform lists. #[allow(missing_docs)] - - AccumulateMatrix { #[compute(ignore_bound)] - from_list: Transform>, - #[compute(ignore_bound)] - to_list: Transform>, - count: Integer }, + AccumulateMatrix { + #[compute(ignore_bound)] + from_list: Transform< + TransformOperation< + Angle, + Number, + Length, + Integer, + LengthOrNumber, + LengthOrPercentage, + LoPoNumber, + >, + >, + #[compute(ignore_bound)] + to_list: Transform< + TransformOperation< + Angle, + Number, + Length, + Integer, + LengthOrNumber, + LengthOrPercentage, + LoPoNumber, + >, + >, + count: Integer, + }, } #[derive(Animate, ToComputedValue)] @@ -254,7 +305,7 @@ impl true, - _ => false + _ => false, } } @@ -263,11 +314,12 @@ impl true, - _ => false + _ => false, } } } +#[cfg_attr(rustfmt, rustfmt_skip)] impl ToCss for @@ -379,9 +431,12 @@ impl ToCss for Transform { - fn to_css(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { + fn to_css(&self, dest: &mut W) -> fmt::Result + where + W: fmt::Write, + { if self.0.is_empty() { - return dest.write_str("none") + return dest.write_str("none"); } let mut first = true; diff --git a/components/style/values/specified/transform.rs b/components/style/values/specified/transform.rs index 14bd00a1af5..e01a5d996c5 100644 --- a/components/style/values/specified/transform.rs +++ b/components/style/values/specified/transform.rs @@ -20,8 +20,15 @@ use values::specified::{LengthOrNumber, LengthOrPercentage, LengthOrPercentageOr use values::specified::position::{Side, X, Y}; /// A single operation in a specified CSS `transform` -pub type TransformOperation = GenericTransformOperation; +pub type TransformOperation = GenericTransformOperation< + Angle, + Number, + Length, + Integer, + LengthOrNumber, + LengthOrPercentage, + LengthOrPercentageOrNumber, +>; /// A specified CSS `transform` pub type Transform = GenericTransform; @@ -39,15 +46,19 @@ impl Transform { ) -> Result> { use style_traits::{Separator, Space}; - if input.try(|input| input.expect_ident_matching("none")).is_ok() { - return Ok(GenericTransform(Vec::new())) + if input + .try(|input| input.expect_ident_matching("none")) + .is_ok() + { + return Ok(GenericTransform(Vec::new())); } Ok(GenericTransform(Space::parse(input, |input| { let function = input.expect_function()?.clone(); input.parse_nested_block(|input| { let location = input.current_source_location(); - let result = match_ignore_ascii_case! { &function, + let result = + match_ignore_ascii_case! { &function, "matrix" => { let a = specified::parse_number(context, input)?; input.expect_comma()?; @@ -260,7 +271,9 @@ pub type TimingFunction = GenericTimingFunction; impl Parse for TransformOrigin { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result> { let parse_depth = |input: &mut Parser| { - input.try(|i| Length::parse(context, i)).unwrap_or(Length::from_px(0.)) + input.try(|i| Length::parse(context, i)).unwrap_or( + Length::from_px(0.), + ) }; match input.try(|i| OriginComponent::parse(context, i)) { Ok(x_origin @ OriginComponent::Center) => { @@ -307,7 +320,8 @@ impl Parse for TransformOrigin { } impl Parse for OriginComponent - where S: Parse, +where + S: Parse, { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result> { if input.try(|i| i.expect_ident_matching("center")).is_ok() { @@ -322,18 +336,15 @@ impl Parse for OriginComponent } impl ToComputedValue for OriginComponent - where S: Side, +where + S: Side, { type ComputedValue = ComputedLengthOrPercentage; fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { match *self { - OriginComponent::Center => { - ComputedLengthOrPercentage::Percentage(ComputedPercentage(0.5)) - }, - OriginComponent::Length(ref length) => { - length.to_computed_value(context) - }, + OriginComponent::Center => ComputedLengthOrPercentage::Percentage(ComputedPercentage(0.5)), + OriginComponent::Length(ref length) => length.to_computed_value(context), OriginComponent::Side(ref keyword) => { let p = ComputedPercentage(if keyword.is_start() { 0. } else { 1. }); ComputedLengthOrPercentage::Percentage(p) @@ -362,7 +373,9 @@ fn allow_frames_timing() -> bool { #[cfg(feature = "servo")] #[inline] -fn allow_frames_timing() -> bool { true } +fn allow_frames_timing() -> bool { + true +} impl Parse for TimingFunction { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result> { @@ -370,7 +383,8 @@ impl Parse for TimingFunction { return Ok(GenericTimingFunction::Keyword(keyword)); } if let Ok(ident) = input.try(|i| i.expect_ident_cloned()) { - let position = match_ignore_ascii_case! { &ident, + let position = + match_ignore_ascii_case! { &ident, "step-start" => StepPosition::Start, "step-end" => StepPosition::End, _ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))), @@ -424,10 +438,13 @@ impl ToComputedValue for TimingFunction { #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { match *self { - GenericTimingFunction::Keyword(keyword) => { - GenericTimingFunction::Keyword(keyword) - }, - GenericTimingFunction::CubicBezier { x1, y1, x2, y2 } => { + GenericTimingFunction::Keyword(keyword) => GenericTimingFunction::Keyword(keyword), + GenericTimingFunction::CubicBezier { + x1, + y1, + x2, + y2, + } => { GenericTimingFunction::CubicBezier { x1: x1.to_computed_value(context), y1: y1.to_computed_value(context), @@ -436,15 +453,10 @@ impl ToComputedValue for TimingFunction { } }, GenericTimingFunction::Steps(steps, position) => { - GenericTimingFunction::Steps( - steps.to_computed_value(context) as u32, - position, - ) + GenericTimingFunction::Steps(steps.to_computed_value(context) as u32, position) }, GenericTimingFunction::Frames(frames) => { - GenericTimingFunction::Frames( - frames.to_computed_value(context) as u32, - ) + GenericTimingFunction::Frames(frames.to_computed_value(context) as u32) }, } } @@ -452,10 +464,13 @@ impl ToComputedValue for TimingFunction { #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { match *computed { - GenericTimingFunction::Keyword(keyword) => { - GenericTimingFunction::Keyword(keyword) - }, - GenericTimingFunction::CubicBezier { ref x1, ref y1, ref x2, ref y2 } => { + GenericTimingFunction::Keyword(keyword) => GenericTimingFunction::Keyword(keyword), + GenericTimingFunction::CubicBezier { + ref x1, + ref y1, + ref x2, + ref y2, + } => { GenericTimingFunction::CubicBezier { x1: Number::from_computed_value(x1), y1: Number::from_computed_value(y1), @@ -464,15 +479,10 @@ impl ToComputedValue for TimingFunction { } }, GenericTimingFunction::Steps(steps, position) => { - GenericTimingFunction::Steps( - Integer::from_computed_value(&(steps as i32)), - position, - ) + GenericTimingFunction::Steps(Integer::from_computed_value(&(steps as i32)), position) }, GenericTimingFunction::Frames(frames) => { - GenericTimingFunction::Frames( - Integer::from_computed_value(&(frames as i32)), - ) + GenericTimingFunction::Frames(Integer::from_computed_value(&(frames as i32))) }, } } From 123bc1d6def72c621d86eac05ab96a0e53b53e22 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Wed, 1 Nov 2017 23:15:10 -0700 Subject: [PATCH 20/21] Update test expectations --- .../wpt/metadata/css/css-transforms/2d-rotate-js.html.ini | 8 -------- .../transform-2d-getComputedStyle-001.html.ini | 4 ---- .../css-transforms/transform_translate_invalid.html.ini | 5 ----- .../css/css-transforms/transform_translate_max.html.ini | 5 ----- .../css/css-transforms/transform_translate_min.html.ini | 5 ----- 5 files changed, 27 deletions(-) delete mode 100644 tests/wpt/metadata/css/css-transforms/2d-rotate-js.html.ini delete mode 100644 tests/wpt/metadata/css/css-transforms/transform_translate_invalid.html.ini delete mode 100644 tests/wpt/metadata/css/css-transforms/transform_translate_max.html.ini delete mode 100644 tests/wpt/metadata/css/css-transforms/transform_translate_min.html.ini diff --git a/tests/wpt/metadata/css/css-transforms/2d-rotate-js.html.ini b/tests/wpt/metadata/css/css-transforms/2d-rotate-js.html.ini deleted file mode 100644 index 10bb100e85d..00000000000 --- a/tests/wpt/metadata/css/css-transforms/2d-rotate-js.html.ini +++ /dev/null @@ -1,8 +0,0 @@ -[2d-rotate-js.html] - type: testharness - [this should make a small green square rotated 30 degrees, and the browser should return the rotation as 30 degrees as the computed value NOT a matrix] - expected: FAIL - - [JS test: Rotate via javascript must show the correct computed rotation] - expected: FAIL - diff --git a/tests/wpt/metadata/css/css-transforms/transform-2d-getComputedStyle-001.html.ini b/tests/wpt/metadata/css/css-transforms/transform-2d-getComputedStyle-001.html.ini index 23fac7115a3..ee407f81468 100644 --- a/tests/wpt/metadata/css/css-transforms/transform-2d-getComputedStyle-001.html.ini +++ b/tests/wpt/metadata/css/css-transforms/transform-2d-getComputedStyle-001.html.ini @@ -11,7 +11,3 @@ [Matrix for skew] expected: FAIL - - [Matrix for general transform] - expected: FAIL - diff --git a/tests/wpt/metadata/css/css-transforms/transform_translate_invalid.html.ini b/tests/wpt/metadata/css/css-transforms/transform_translate_invalid.html.ini deleted file mode 100644 index ce54cad42c5..00000000000 --- a/tests/wpt/metadata/css/css-transforms/transform_translate_invalid.html.ini +++ /dev/null @@ -1,5 +0,0 @@ -[transform_translate_invalid.html] - type: testharness - [transform_translate_null_null] - expected: FAIL - diff --git a/tests/wpt/metadata/css/css-transforms/transform_translate_max.html.ini b/tests/wpt/metadata/css/css-transforms/transform_translate_max.html.ini deleted file mode 100644 index b3e3ee75a1e..00000000000 --- a/tests/wpt/metadata/css/css-transforms/transform_translate_max.html.ini +++ /dev/null @@ -1,5 +0,0 @@ -[transform_translate_max.html] - type: testharness - [transform_translate_max] - expected: FAIL - diff --git a/tests/wpt/metadata/css/css-transforms/transform_translate_min.html.ini b/tests/wpt/metadata/css/css-transforms/transform_translate_min.html.ini deleted file mode 100644 index a550e8a4766..00000000000 --- a/tests/wpt/metadata/css/css-transforms/transform_translate_min.html.ini +++ /dev/null @@ -1,5 +0,0 @@ -[transform_translate_min.html] - type: testharness - [transform_translate_min] - expected: FAIL - From cb9645cd17b6e1ecdf6f3e63d47efa88433bb1fc Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Thu, 2 Nov 2017 14:10:28 -0700 Subject: [PATCH 21/21] Comments and minor fixes --- components/style/properties/gecko.mako.rs | 10 ++++------ .../properties/helpers/animated_properties.mako.rs | 7 +++++++ components/style/values/computed/transform.rs | 2 ++ 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/components/style/properties/gecko.mako.rs b/components/style/properties/gecko.mako.rs index 21d43c0d009..a7e433642c9 100644 --- a/components/style/properties/gecko.mako.rs +++ b/components/style/properties/gecko.mako.rs @@ -3202,8 +3202,7 @@ fn static_assert() { let result = match list { Some(list) => { - let vec: Vec<_> = list - .into_iter() + list.into_iter() .filter_map(|value| { // Handle none transform. if value.is_none() { @@ -3212,12 +3211,11 @@ fn static_assert() { Some(Self::clone_single_transform_function(value)) } }) - .collect(); - if !vec.is_empty() { Some(vec) } else { None } + .collect::>() }, - _ => None, + _ => vec![], }; - Transform(result.unwrap_or(vec!())) + Transform(result) } ${impl_transition_time_value('delay', 'Delay')} diff --git a/components/style/properties/helpers/animated_properties.mako.rs b/components/style/properties/helpers/animated_properties.mako.rs index 7f637fa26cd..b054e3f9863 100644 --- a/components/style/properties/helpers/animated_properties.mako.rs +++ b/components/style/properties/helpers/animated_properties.mako.rs @@ -1438,6 +1438,8 @@ impl Animate for Matrix3D { } #[cfg(feature = "gecko")] + // Gecko doesn't exactly follow the spec here; we use a different procedure + // to match it fn animate(&self, other: &Self, procedure: Procedure) -> Result { let (from, to) = if self.is_3d() || other.is_3d() { (decompose_3d_matrix(*self), decompose_3d_matrix(*other)) @@ -1467,6 +1469,8 @@ impl Animate for Matrix { } #[cfg(feature = "gecko")] + // Gecko doesn't exactly follow the spec here; we use a different procedure + // to match it fn animate(&self, other: &Self, procedure: Procedure) -> Result { let from = decompose_2d_matrix(&(*self).into()); let to = decompose_2d_matrix(&(*other).into()); @@ -2471,6 +2475,9 @@ impl ComputeSquaredDistance for ComputedTransformOperation { } p_matrix.compute_squared_distance(&m) } + // Gecko cross-interpolates amongst all translate and all scale + // functions (See ToPrimitive in layout/style/StyleAnimationValue.cpp) + // without falling back to InterpolateMatrix _ if self.is_translate() && other.is_translate() => { self.to_translate_3d().compute_squared_distance(&other.to_translate_3d()) } diff --git a/components/style/values/computed/transform.rs b/components/style/values/computed/transform.rs index 3be9816b34c..440758a06b1 100644 --- a/components/style/values/computed/transform.rs +++ b/components/style/values/computed/transform.rs @@ -59,6 +59,8 @@ pub type Matrix = GenericMatrix; /// computed value of matrix() in -moz-transform pub type PrefixedMatrix = GenericMatrix; +// we rustfmt_skip here because we want the matrices to look like +// matrices instead of being split across lines #[cfg_attr(rustfmt, rustfmt_skip)] impl Matrix3D { #[inline]