aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorbors-servo <lbergstrom+bors@mozilla.com>2017-11-02 17:02:07 -0500
committerGitHub <noreply@github.com>2017-11-02 17:02:07 -0500
commitc494d25e24d515509a5d8bb86a30669ee01742b9 (patch)
treeb95cc4c5e4fd38a2eed6b24e71b538ff62384915
parent92b49010b107ffd8be9169a1c979710338dc24c4 (diff)
parentcb9645cd17b6e1ecdf6f3e63d47efa88433bb1fc (diff)
downloadservo-c494d25e24d515509a5d8bb86a30669ee01742b9.tar.gz
servo-c494d25e24d515509a5d8bb86a30669ee01742b9.zip
Auto merge of #18750 - Manishearth:transform-generic, r=emilio,xidorn
Make transforms generic This makes the specified and computed value of transform share a generic backing enum. This will eventually be a complete fix for https://bugzilla.mozilla.org/show_bug.cgi?id=1391145 , and also incidentally fixes https://bugzilla.mozilla.org/show_bug.cgi?id=1405881 Currently WIP -- the generic transform exists and is used, but this currently misses some animation and glue cases. <!-- Reviewable:start --> --- This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/servo/servo/18750) <!-- Reviewable:end -->
-rw-r--r--components/layout/flow.rs2
-rw-r--r--components/layout/fragment.rs4
-rw-r--r--components/style/gecko_bindings/sugar/ns_css_value.rs13
-rw-r--r--components/style/properties/gecko.mako.rs234
-rw-r--r--components/style/properties/helpers/animated_properties.mako.rs569
-rw-r--r--components/style/properties/longhand/box.mako.rs855
-rw-r--r--components/style/properties/properties.mako.rs38
-rw-r--r--components/style/values/computed/length.rs5
-rw-r--r--components/style/values/computed/transform.rs418
-rw-r--r--components/style/values/generics/transform.rs319
-rw-r--r--components/style/values/specified/transform.rs305
-rw-r--r--components/style_derive/to_computed_value.rs5
-rw-r--r--ports/geckolib/glue.rs15
-rw-r--r--tests/unit/style/animated_properties.rs89
-rw-r--r--tests/unit/style/properties/serialization.rs25
-rw-r--r--tests/wpt/metadata/css/css-transforms/2d-rotate-js.html.ini8
-rw-r--r--tests/wpt/metadata/css/css-transforms/transform-2d-getComputedStyle-001.html.ini4
-rw-r--r--tests/wpt/metadata/css/css-transforms/transform_translate_invalid.html.ini5
-rw-r--r--tests/wpt/metadata/css/css-transforms/transform_translate_max.html.ini5
-rw-r--r--tests/wpt/metadata/css/css-transforms/transform_translate_min.html.ini5
20 files changed, 1578 insertions, 1345 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/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 7a6995f2ec4..a7e433642c9 100644
--- a/components/style/properties/gecko.mako.rs
+++ b/components/style/properties/gecko.mako.rs
@@ -2892,18 +2892,50 @@ fn static_assert() {
}
${impl_css_url('_moz_binding', 'mBinding.mPtr')}
-
+ <%
+ transform_functions = [
+ ("Matrix3D", "matrix3d", ["number"] * 16),
+ ("PrefixedMatrix3D", "matrix3d", ["number"] * 12 + ["lopon"] * 2
+ + ["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"]),
+ ("InterpolateMatrix", "interpolatematrix", ["list"] * 2 + ["percentage"]),
+ ("AccumulateMatrix", "accumulatematrix", ["list"] * 2 + ["integer_to_percentage"])
+ ]
+ %>
<%def name="transform_function_arm(name, keyword, items)">
<%
+ has_optional = items[-1].startswith("optional_")
pattern = None
if keyword == "matrix3d":
# 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 = "(ComputedMatrix { %s })" % ", ".join(single_patterns)
- else:
- pattern = "(ComputedMatrixWithPercents { %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":
@@ -2921,36 +2953,55 @@ 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} => {
- bindings::Gecko_CSSValue_SetFunction(gecko_value, ${len(items) + 1});
+ ::values::generics::transform::TransformOperation::${name}${pattern} => {
+ % 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_some());
+ 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
}
</%def>
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::{Matrix, Matrix3D};
let convert_to_ns_css_value = |item: &ComputedOperation| -> structs::nsCSSValue {
let mut value = structs::nsCSSValue::null();
@@ -2958,20 +3009,27 @@ 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("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
}
}
}
@@ -2994,15 +3052,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) {
@@ -3019,11 +3075,13 @@ 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",
- "list" : "TransformList(Some(convert_shared_list_to_operations(%s)))",
+ "integer_to_percentage" : "bindings::Gecko_CSSValue_GetPercentage(%s) as i32",
+ "list" : "Transform(convert_shared_list_to_operations(%s))",
}
pre_symbols = "("
post_symbols = ")"
@@ -3033,35 +3091,62 @@ fn static_assert() {
pre_symbols = " {"
post_symbols = "}"
elif keyword == "matrix3d":
- pre_symbols = "(ComputedMatrix {"
+ 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"]
elif keyword == "accumulatematrix":
field_names = ["from_list", "to_list", "count"]
+
%>
- structs::nsCSSKeyword::eCSSKeyword_${keyword} => {
- ComputedOperation::${name}${pre_symbols}
+ <%
+
+ guard = ""
+ if name == "Matrix3D" or name == "Matrix":
+ guard = "if !needs_prefix "
+ elif name == "PrefixedMatrix3D" or name == "PrefixedMatrix":
+ 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":
m${index / 4 + 1}${index % 4 + 1}:
+ % elif keyword == "matrix":
+ ${chr(ord('a') + index)}:
% 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}
},
</%def>
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::{Matrix, Matrix3D};
+ use values::generics::transform::Transform;
let convert_shared_list_to_operations = |value: &structs::nsCSSValue|
-> Vec<ComputedOperation> {
@@ -3080,64 +3165,44 @@ fn static_assert() {
bindings::Gecko_CSSValue_GetKeyword(bindings::Gecko_CSSValue_GetArrayItemConst(gecko_value, 0))
};
- unsafe {
- use gecko_bindings::structs::nsCSSKeyword;
- use values::computed::Angle;
-
- let get_array_angle = || -> Angle {
- bindings::Gecko_CSSValue_GetArrayItemConst(gecko_value, 1).get_angle()
- };
+ 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("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("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())
- },
+ % for servo, gecko, format in transform_functions:
+ ${computed_operation_arm(servo, gecko, format)}
+ % endfor
_ => 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
- .into_iter()
+ list.into_iter()
.filter_map(|value| {
// Handle none transform.
if value.is_none() {
@@ -3146,12 +3211,11 @@ fn static_assert() {
Some(Self::clone_single_transform_function(value))
}
})
- .collect();
- if !vec.is_empty() { Some(vec) } else { None }
+ .collect::<Vec<_>>()
},
- _ => None,
+ _ => vec![],
};
- longhands::transform::computed_value::T(result)
+ 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 b7223d4b616..b054e3f9863 100644
--- a/components/style/properties/helpers/animated_properties.mako.rs
+++ b/components/style/properties/helpers/animated_properties.mako.rs
@@ -18,9 +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::ComputedMatrix;
-use properties::longhands::transform::computed_value::ComputedOperation as TransformOperation;
-use properties::longhands::transform::computed_value::T as TransformList;
use properties::longhands::visibility::computed_value::T as Visibility;
#[cfg(feature = "gecko")]
use properties::PropertyId;
@@ -28,7 +25,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 +42,10 @@ 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, 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;
#[cfg(feature = "gecko")] use values::generics::FontSettingTag as GenericFontSettingTag;
@@ -1014,60 +1013,6 @@ impl ToAnimatedZero for ClipRect {
fn to_animated_zero(&self) -> Result<Self, ()> { Err(()) }
}
-/// 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<Self, ()> {
- 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,10 +1022,18 @@ fn animate_multiplicative_factor(
}
/// <http://dev.w3.org/csswg/css-transforms/#interpolation-of-transforms>
-impl Animate for TransformOperation {
+impl Animate for ComputedTransformOperation {
fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
match (self, other) {
(
+ &TransformOperation::Matrix3D(ref this),
+ &TransformOperation::Matrix3D(ref other),
+ ) => {
+ Ok(TransformOperation::Matrix3D(
+ this.animate(other, procedure)?,
+ ))
+ },
+ (
&TransformOperation::Matrix(ref this),
&TransformOperation::Matrix(ref other),
) => {
@@ -1098,93 +1051,231 @@ impl Animate for TransformOperation {
))
},
(
- &TransformOperation::Translate(ref fx, ref fy, ref fz),
- &TransformOperation::Translate(ref tx, ref ty, ref tz),
+ &TransformOperation::SkewX(ref f),
+ &TransformOperation::SkewX(ref t),
) => {
- Ok(TransformOperation::Translate(
+ 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),
+ ) => {
+ 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::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),
) => {
- 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::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),
) => {
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)?,
))
}
},
(
+ &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),
) => {
- 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)?,
))
},
+ _ if self.is_translate() && other.is_translate() => {
+ self.to_translate_3d().animate(&other.to_translate_3d(), procedure)
+ }
+ _ if self.is_scale() && other.is_scale() => {
+ self.to_scale_3d().animate(&other.to_scale_3d(), procedure)
+ }
_ => Err(()),
}
}
}
-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::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
}
}
/// <https://www.w3.org/TR/css-transforms-1/#Rotate3dDefined>
-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 +1305,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 +1415,7 @@ impl ComputeSquaredDistance for MatrixDecomposed2D {
}
}
-impl Animate for ComputedMatrix {
+impl Animate for Matrix3D {
#[cfg(feature = "servo")]
fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
if self.is_3d() || other.is_3d() {
@@ -1332,7 +1423,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,11 +1433,13 @@ 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)?))
}
}
#[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<Self, ()> {
let (from, to) = if self.is_3d() || other.is_3d() {
(decompose_3d_matrix(*self), decompose_3d_matrix(*other))
@@ -1355,7 +1448,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 +1458,35 @@ impl Animate for ComputedMatrix {
}
}
-impl ComputeSquaredDistance for ComputedMatrix {
+impl Animate for Matrix {
+ #[cfg(feature = "servo")]
+ fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
+ 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")]
+ // Gecko doesn't exactly follow the spec here; we use a different procedure
+ // to match it
+ fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
+ 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")]
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {
@@ -1392,10 +1513,10 @@ impl ComputeSquaredDistance for ComputedMatrix {
}
}
-impl From<ComputedMatrix> for MatrixDecomposed2D {
+impl From<Matrix3D> for MatrixDecomposed2D {
/// Decompose a 2D matrix.
/// <https://drafts.csswg.org/css-transforms/#decomposing-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 +1577,11 @@ impl From<ComputedMatrix> for MatrixDecomposed2D {
}
}
-impl From<MatrixDecomposed2D> for ComputedMatrix {
+impl From<MatrixDecomposed2D> for Matrix3D {
/// Recompose a 2D matrix.
/// <https://drafts.csswg.org/css-transforms/#recomposing-to-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 +1596,7 @@ impl From<MatrixDecomposed2D> 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 +1615,9 @@ impl From<MatrixDecomposed2D> 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 +1627,8 @@ impl<'a> From< &'a RawGeckoGfxMatrix4x4> for ComputedMatrix {
}
#[cfg(feature = "gecko")]
-impl From<ComputedMatrix> for RawGeckoGfxMatrix4x4 {
- fn from(matrix: ComputedMatrix) -> RawGeckoGfxMatrix4x4 {
+impl From<Matrix3D> 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 +1718,7 @@ impl ComputeSquaredDistance for Quaternion {
/// Decompose a 3D matrix.
/// <https://drafts.csswg.org/css-transforms/#decomposing-a-3d-matrix>
-fn decompose_3d_matrix(mut matrix: ComputedMatrix) -> Result<MatrixDecomposed3D, ()> {
+fn decompose_3d_matrix(mut matrix: Matrix3D) -> Result<MatrixDecomposed3D, ()> {
// Normalize the matrix.
if matrix.m44 == 0.0 {
return Err(());
@@ -1635,7 +1756,7 @@ fn decompose_3d_matrix(mut matrix: ComputedMatrix) -> Result<MatrixDecomposed3D,
perspective_matrix = perspective_matrix.inverse().unwrap();
// Transpose perspective_matrix
- perspective_matrix = ComputedMatrix {
+ perspective_matrix = Matrix3D {
% for i in range(1, 5):
% for j in range(1, 5):
m${i}${j}: perspective_matrix.m${j}${i},
@@ -1743,7 +1864,7 @@ fn decompose_3d_matrix(mut matrix: ComputedMatrix) -> Result<MatrixDecomposed3D,
/// Decompose a 2D matrix for Gecko.
// Use the algorithm from nsStyleTransformMatrix::Decompose2DMatrix() in Gecko.
#[cfg(feature = "gecko")]
-fn decompose_2d_matrix(matrix: &ComputedMatrix) -> Result<MatrixDecomposed3D, ()> {
+fn decompose_2d_matrix(matrix: &Matrix3D) -> Result<MatrixDecomposed3D, ()> {
// 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 +2049,11 @@ impl Animate for MatrixDecomposed3D {
}
}
-impl From<MatrixDecomposed3D> for ComputedMatrix {
+impl From<MatrixDecomposed3D> for Matrix3D {
/// Recompose a 3D matrix.
/// <https://drafts.csswg.org/css-transforms/#recomposing-to-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 +2075,7 @@ impl From<MatrixDecomposed3D> 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 +2089,7 @@ impl From<MatrixDecomposed3D> 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 +2119,7 @@ impl From<MatrixDecomposed3D> 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 +2132,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 +2167,7 @@ impl ComputedMatrix {
self.m11 * self.m22 * self.m33 * self.m44
}
- fn inverse(&self) -> Option<ComputedMatrix> {
+ fn inverse(&self) -> Option<Matrix3D> {
let mut det = self.determinant();
if det == 0.0 {
@@ -2054,7 +2175,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,85 +2247,86 @@ impl ComputedMatrix {
}
/// <https://drafts.csswg.org/css-transforms/#interpolation-of-transforms>
-impl Animate for TransformList {
+impl Animate for ComputedTransform {
#[inline]
fn animate(
&self,
- other: &Self,
+ other_: &Self,
procedure: Procedure,
) -> Result<Self, ()> {
- if self.0.is_none() && other.0.is_none() {
- return Ok(TransformList(None));
+
+ let animate_equal_lists = |this: &[ComputedTransformOperation],
+ other: &[ComputedTransformOperation]|
+ -> Result<ComputedTransform, ()> {
+ Ok(Transform(this.iter().zip(other)
+ .map(|(this, other)| this.animate(other, procedure))
+ .collect::<Result<Vec<_>, _>>()?))
+ // 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;
+
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::<Vec<_>>();
- 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)
});
if is_matched_transforms {
- let result = this.iter().zip(other).map(|(this, other)| {
- this.animate(other, procedure)
- }).collect::<Result<Vec<_>, _>>();
- if let Ok(list) = result {
- return Ok(TransformList(if list.is_empty() {
- None
- } else {
- Some(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(TransformList(Some(vec![TransformOperation::InterpolateMatrix {
- from_list: this.into_owned(),
- to_list: other.into_owned(),
+ Ok(Transform(vec![TransformOperation::InterpolateMatrix {
+ from_list: Transform(owned_this),
+ to_list: Transform(owned_other),
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(owned_this),
+ to_list: Transform(owned_other),
count: cmp::min(count, i32::max_value() as u64) as i32,
- }])))
+ }]))
},
}
}
@@ -2214,15 +2336,38 @@ 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<SquaredDistance, ()> {
+ // 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),
+ &TransformOperation::Matrix3D(ref other),
+ ) => {
+ this.compute_squared_distance(other)
+ },
+ (
&TransformOperation::Matrix(ref this),
&TransformOperation::Matrix(ref other),
) => {
- this.compute_squared_distance(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),
@@ -2233,23 +2378,18 @@ impl ComputeSquaredDistance for TransformOperation {
)
},
(
- &TransformOperation::Translate(ref fx, ref fy, ref fz),
- &TransformOperation::Translate(ref tx, ref ty, ref tz),
+ &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);
@@ -2262,8 +2402,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 +2412,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 {
@@ -2290,11 +2430,29 @@ impl ComputeSquaredDistance for TransformOperation {
}
}
(
+ &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),
) => {
- 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,27 +2464,36 @@ 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();
}
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())
+ }
+ _ if self.is_scale() && other.is_scale() => {
+ self.to_scale_3d().compute_squared_distance(&other.to_scale_3d())
+ }
_ => Err(()),
}
}
}
-impl ComputeSquaredDistance for TransformList {
+impl ComputeSquaredDistance for ComputedTransform {
#[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {
- 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<SquaredDistance, _> = list1.iter().zip_longest(list2).map(|it| {
match it {
@@ -2342,28 +2509,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<Self, ()> {
- match self.0 {
- None => Ok(TransformList(None)),
- Some(ref list) => {
- Ok(TransformList(Some(
- list.iter().map(|op| op.to_animated_zero()).collect::<Result<Vec<_>, _>>()?
- )))
- },
- }
- }
-}
-
/// Animated SVGPaint
pub type IntermediateSVGPaint = SVGPaint<AnimatedRGBA, ComputedUrl>;
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<Vec<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<Number>),
- /// Represents a 3D 4x4 matrix with percentage and length values.
- /// For `moz-transform`.
- PrefixedMatrix(Matrix<Number, LoPoNumber>),
- /// 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<Angle>),
- SkewX(Angle),
- SkewY(Angle),
- Translate(LengthOrPercentage, Option<LengthOrPercentage>),
- 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<Number>),
- 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<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write {
- // TODO(pcwalton)
- Ok(())
- }
- }
-
- impl ToCss for SpecifiedOperation {
- fn to_css<W>(&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))
- }
- }
- }
+ pub use values::computed::transform::Transform as T;
+ pub use values::computed::transform::TransformOperation as ComputedOperation;
}
- #[derive(Clone, Debug, MallocSizeOf, PartialEq)]
- pub struct SpecifiedValue(Vec<SpecifiedOperation>);
-
- impl ToCss for SpecifiedValue {
- fn to_css<W>(&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<SpecifiedValue,ParseError<'i>> {
- 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<SpecifiedValue,ParseError<'i>> {
- 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<SpecifiedValue,ParseError<'i>> {
- 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)
}
</%helpers:longhand>
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/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/computed/transform.rs b/components/style/values/computed/transform.rs
index 21c98c50d99..440758a06b1 100644
--- a/components/style/values/computed/transform.rs
+++ b/components/style/values/computed/transform.rs
@@ -6,14 +6,29 @@
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;
-use values::computed::{Angle, Length, LengthOrPercentage, Number, Percentage};
+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::{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`
+pub type TransformOperation = GenericTransformOperation<
+ Angle,
+ Number,
+ Length,
+ Integer,
+ LengthOrNumber,
+ LengthOrPercentage,
+ LengthOrPercentageOrNumber,
+>;
+/// A computed CSS `transform`
+pub type Transform = GenericTransform<TransformOperation>;
+
/// The computed value of a CSS `<transform-origin>`
pub type TransformOrigin = GenericTransformOrigin<LengthOrPercentage, LengthOrPercentage, Length>;
@@ -35,9 +50,106 @@ impl TransformOrigin {
}
}
-impl From<ComputedMatrix> for Transform3D<CSSFloat> {
+/// computed value of matrix3d()
+pub type Matrix3D = GenericMatrix3D<Number>;
+/// computed value of matrix3d() in -moz-transform
+pub type PrefixedMatrix3D = GenericMatrix3D<Number, LengthOrPercentageOrNumber, LengthOrNumber>;
+/// computed value of matrix()
+pub type Matrix = GenericMatrix<Number>;
+/// computed value of matrix() in -moz-transform
+pub type PrefixedMatrix = GenericMatrix<Number, LengthOrPercentageOrNumber>;
+
+// 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]
+ /// 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
+ }
+ }
+
+ /// Convert to a 2D Matrix
+ pub fn into_2d(self) -> Result<Matrix, ()> {
+ 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(())
+ }
+ }
+}
+
+#[cfg_attr(rustfmt, rustfmt_skip)]
+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
+ }
+ }
+}
+
+#[cfg_attr(rustfmt, rustfmt_skip)]
+impl Matrix {
#[inline]
- fn from(m: ComputedMatrix) -> Self {
+ /// Get an identity matrix
+ pub fn identity() -> Self {
+ Self {
+ a: 1., c: 0., /* 0 0*/
+ b: 0., d: 1., /* 0 0*/
+ /* 0 0 1 0 */
+ e: 0., f: 0., /* 0 1 */
+ }
+ }
+}
+
+#[cfg_attr(rustfmt, rustfmt_skip)]
+impl From<Matrix> 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
+ }
+ }
+}
+
+#[cfg_attr(rustfmt, rustfmt_skip)]
+impl PrefixedMatrix {
+ #[inline]
+ /// Get an identity matrix
+ pub fn identity() -> Self {
+ Self {
+ 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 */
+ }
+ }
+}
+
+#[cfg_attr(rustfmt, rustfmt_skip)]
+impl From<Matrix3D> for Transform3D<CSSFloat> {
+ #[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,
@@ -46,10 +158,11 @@ impl From<ComputedMatrix> for Transform3D<CSSFloat> {
}
}
-impl From<Transform3D<CSSFloat>> for ComputedMatrix {
+#[cfg_attr(rustfmt, rustfmt_skip)]
+impl From<Transform3D<CSSFloat>> for Matrix3D {
#[inline]
fn from(m: Transform3D<CSSFloat>) -> Self {
- ComputedMatrix {
+ 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,
@@ -58,75 +171,283 @@ impl From<Transform3D<CSSFloat>> for ComputedMatrix {
}
}
-impl TransformList {
+#[cfg_attr(rustfmt, rustfmt_skip)]
+impl From<Matrix> for Transform3D<CSSFloat> {
+ #[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 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
+impl ToAnimatedZero for TransformOperation {
+ fn to_animated_zero(&self) -> Result<Self, ()> {
+ 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(_, _) => 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::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()))
+ },
+ }
+ }
+}
+
+
+impl ToAnimatedZero for Transform {
+ #[inline]
+ fn to_animated_zero(&self) -> Result<Self, ()> {
+ Ok(GenericTransform(self.0
+ .iter()
+ .map(|op| op.to_animated_zero())
+ .collect::<Result<Vec<_>, _>>()?))
+ }
+}
+
+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<Au>>)
- -> Option<Transform3D<CSSFloat>> {
+ pub fn to_transform_3d_matrix(&self, reference_box: Option<&Rect<Au>>) -> Option<Transform3D<CSSFloat>> {
let mut transform = Transform3D::identity();
- let list = match self.0.as_ref() {
- Some(list) => list,
- None => return None,
- };
+ 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 {
- ComputedOperation::Rotate(ax, ay, az, theta) => {
+ 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())
- }
- 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) => {
+ },
+ 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, 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)
- }
- ComputedOperation::Matrix(m) => {
- m.into()
- }
- ComputedOperation::MatrixWithPercents(_) => {
+ },
+ 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!()
- }
- ComputedOperation::Skew(theta_x, theta_y) => {
- Transform3D::create_skew(theta_x.into(), theta_y.into())
- }
- ComputedOperation::InterpolateMatrix { .. } |
- ComputedOperation::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);
@@ -153,8 +474,7 @@ impl TransformList {
}
/// 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 2902f24329e..45d19c8ab68 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, CSSFloat};
/// A generic 2D transformation matrix.
#[allow(missing_docs)]
@@ -21,6 +21,16 @@ pub struct Matrix<T, U = T> {
pub f: U,
}
+#[allow(missing_docs)]
+#[cfg_attr(rustfmt, rustfmt_skip)]
+#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
+pub struct Matrix3D<T, U = T, V = T> {
+ 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)]
@@ -42,7 +52,12 @@ pub enum TimingFunction<Integer, Number> {
Keyword(TimingKeyword),
/// `cubic-bezier(<number>, <number>, <number>, <number>)`
#[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(<integer>, [ start | end ]?)`
Steps(Integer, StepPosition),
/// `frames(<integer>)`
@@ -94,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(", ")?;
@@ -137,3 +157,296 @@ impl TimingKeyword {
}
}
}
+
+#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
+#[derive(ToComputedValue)]
+/// A single operation in the list of a `transform` value
+pub enum TransformOperation<Angle, Number, Length, Integer, LengthOrNumber, LengthOrPercentage, LoPoNumber> {
+ /// Represents a 2D 2x3 matrix.
+ Matrix(Matrix<Number>),
+ /// Represents a 3D 4x4 matrix with percentage and length values.
+ /// For `moz-transform`.
+ PrefixedMatrix(Matrix<Number, LoPoNumber>),
+ /// Represents a 3D 4x4 matrix.
+ #[allow(missing_docs)]
+ Matrix3D(Matrix3D<Number>),
+ /// Represents a 3D 4x4 matrix with percentage and length values.
+ /// For `moz-transform`.
+ #[allow(missing_docs)]
+ PrefixedMatrix3D(Matrix3D<Number, LoPoNumber, LengthOrNumber>),
+ /// 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<Angle>),
+ /// skewX(angle)
+ SkewX(Angle),
+ /// skewY(angle)
+ SkewY(Angle),
+ /// translate(x, y) or translate(x)
+ Translate(LengthOrPercentage, Option<LengthOrPercentage>),
+ /// 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<Number>),
+ /// 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(Length),
+ /// A intermediate type for interpolation of mismatched transform lists.
+ #[allow(missing_docs)]
+ 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<
+ 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)]
+#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
+/// A value of the `transform` property
+pub struct Transform<T>(pub Vec<T>);
+
+impl<Angle, Number, Length, Integer, LengthOrNumber, LengthOrPercentage, LoPoNumber>
+ TransformOperation<Angle, Number, Length, Integer, LengthOrNumber, LengthOrPercentage, LoPoNumber> {
+ /// 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,
+ }
+ }
+}
+
+#[cfg_attr(rustfmt, rustfmt_skip)]
+impl<Angle: ToCss + Copy, Number: ToCss + Copy, Length: ToCss,
+ Integer: ToCss + Copy, LengthOrNumber: ToCss, LengthOrPercentage: ToCss, LoPoNumber: ToCss>
+ ToCss for
+ TransformOperation<Angle, Number, Length, Integer, LengthOrNumber, LengthOrPercentage, LoPoNumber> {
+ fn to_css<W>(&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(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(Matrix3D {
+ 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<T: ToCss> ToCss for Transform<T> {
+ fn to_css<W>(&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/values/specified/transform.rs b/components/style/values/specified/transform.rs
index e2a56d1e405..e01a5d996c5 100644
--- a/components/style/values/specified/transform.rs
+++ b/components/style/values/specified/transform.rs
@@ -11,15 +11,249 @@ use style_traits::{ParseError, StyleParseErrorKind};
use values::computed::{Context, LengthOrPercentage as ComputedLengthOrPercentage};
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::{Matrix3D, Transform as GenericTransform};
+use values::generics::transform::{StepPosition, TimingFunction as GenericTimingFunction, Matrix};
use values::generics::transform::{TimingKeyword, TransformOrigin as GenericTransformOrigin};
-use values::specified::{Integer, Number};
-use values::specified::length::{Length, LengthOrPercentage};
+use values::generics::transform::TransformOperation as GenericTransformOperation;
+use values::specified::{self, 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<
+ Angle,
+ Number,
+ Length,
+ Integer,
+ LengthOrNumber,
+ LengthOrPercentage,
+ LengthOrPercentageOrNumber,
+>;
+/// A specified CSS `transform`
+pub type Transform = GenericTransform<TransformOperation>;
+
/// The specified value of a CSS `<transform-origin>`
pub type TransformOrigin = GenericTransformOrigin<OriginComponent<X>, OriginComponent<Y>, 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<Self, ParseError<'i>> {
+ 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 location = input.current_source_location();
+ 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(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(Matrix3D {
+ 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(|()| location.new_custom_error(StyleParseErrorKind::UnexpectedFunction(function.clone())))
+ })
+ })?))
+ }
+}
+
/// The specified value of a component of a CSS `<transform-origin>`.
#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToCss)]
pub enum OriginComponent<S> {
@@ -37,7 +271,9 @@ pub type TimingFunction = GenericTimingFunction<Integer, Number>;
impl Parse for TransformOrigin {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
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) => {
@@ -84,7 +320,8 @@ impl Parse for TransformOrigin {
}
impl<S> Parse for OriginComponent<S>
- where S: Parse,
+where
+ S: Parse,
{
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
if input.try(|i| i.expect_ident_matching("center")).is_ok() {
@@ -99,18 +336,15 @@ impl<S> Parse for OriginComponent<S>
}
impl<S> ToComputedValue for OriginComponent<S>
- 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)
@@ -139,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<Self, ParseError<'i>> {
@@ -147,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()))),
@@ -201,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),
@@ -213,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)
},
}
}
@@ -229,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),
@@ -241,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)))
},
}
}
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,
}
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 }),
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<T: ToCss>(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)"
)
}
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
-