Auto merge of #22645 - emilio:gecko-sync, r=emilio,mbrubeck

style: Sync changes from mozilla-central.

See each individual commit for details.

<!-- 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/22645)
<!-- Reviewable:end -->
This commit is contained in:
bors-servo 2019-01-08 06:33:28 -05:00 committed by GitHub
commit a0ba56cdf0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
82 changed files with 1277 additions and 1844 deletions

View file

@ -66,8 +66,7 @@ use style::context::SharedStyleContext;
use style::logical_geometry::{LogicalMargin, LogicalPoint, LogicalRect, LogicalSize, WritingMode}; use style::logical_geometry::{LogicalMargin, LogicalPoint, LogicalRect, LogicalSize, WritingMode};
use style::properties::ComputedValues; use style::properties::ComputedValues;
use style::servo::restyle_damage::ServoRestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage;
use style::values::computed::LengthOrPercentageOrAuto; use style::values::computed::{LengthPercentageOrAuto, LengthPercentageOrNone};
use style::values::computed::{LengthOrPercentage, LengthOrPercentageOrNone};
/// Information specific to floated blocks. /// Information specific to floated blocks.
#[derive(Clone, Serialize)] #[derive(Clone, Serialize)]
@ -418,42 +417,26 @@ impl CandidateBSizeIterator {
// If that is not determined yet by the time we need to resolve // If that is not determined yet by the time we need to resolve
// `min-height` and `max-height`, percentage values are ignored. // `min-height` and `max-height`, percentage values are ignored.
let block_size = match ( let block_size = match fragment.style.content_block_size() {
fragment.style.content_block_size(), LengthPercentageOrAuto::Auto => MaybeAuto::Auto,
block_container_block_size, LengthPercentageOrAuto::LengthPercentage(ref lp) => {
) { MaybeAuto::from_option(lp.maybe_to_used_value(block_container_block_size))
(LengthOrPercentageOrAuto::Percentage(percent), Some(block_container_block_size)) => {
MaybeAuto::Specified(block_container_block_size.scale_by(percent.0))
}, },
(LengthOrPercentageOrAuto::Calc(calc), _) => {
MaybeAuto::from_option(calc.to_used_value(block_container_block_size))
},
(LengthOrPercentageOrAuto::Percentage(_), None) |
(LengthOrPercentageOrAuto::Auto, _) => MaybeAuto::Auto,
(LengthOrPercentageOrAuto::Length(length), _) => MaybeAuto::Specified(Au::from(length)),
}; };
let max_block_size = match (fragment.style.max_block_size(), block_container_block_size) {
(LengthOrPercentageOrNone::Percentage(percent), Some(block_container_block_size)) => { let max_block_size = match fragment.style.max_block_size() {
Some(block_container_block_size.scale_by(percent.0)) LengthPercentageOrNone::None => None,
LengthPercentageOrNone::LengthPercentage(ref lp) => {
lp.maybe_to_used_value(block_container_block_size)
}, },
(LengthOrPercentageOrNone::Calc(calc), _) => {
calc.to_used_value(block_container_block_size)
},
(LengthOrPercentageOrNone::Percentage(_), None) |
(LengthOrPercentageOrNone::None, _) => None,
(LengthOrPercentageOrNone::Length(length), _) => Some(Au::from(length)),
};
let min_block_size = match (fragment.style.min_block_size(), block_container_block_size) {
(LengthOrPercentage::Percentage(percent), Some(block_container_block_size)) => {
block_container_block_size.scale_by(percent.0)
},
(LengthOrPercentage::Calc(calc), _) => calc
.to_used_value(block_container_block_size)
.unwrap_or(Au(0)),
(LengthOrPercentage::Percentage(_), None) => Au(0),
(LengthOrPercentage::Length(length), _) => Au::from(length),
}; };
let min_block_size = fragment
.style
.min_block_size()
.maybe_to_used_value(block_container_block_size)
.unwrap_or(Au(0));
// If the style includes `box-sizing: border-box`, subtract the border and padding. // If the style includes `box-sizing: border-box`, subtract the border and padding.
let adjustment_for_box_sizing = match fragment.style.get_position().box_sizing { let adjustment_for_box_sizing = match fragment.style.get_position().box_sizing {
BoxSizing::BorderBox => fragment.border_padding.block_start_end(), BoxSizing::BorderBox => fragment.border_padding.block_start_end(),
@ -1415,15 +1398,9 @@ impl BlockFlow {
pub fn explicit_block_size(&self, containing_block_size: Option<Au>) -> Option<Au> { pub fn explicit_block_size(&self, containing_block_size: Option<Au>) -> Option<Au> {
let content_block_size = self.fragment.style().content_block_size(); let content_block_size = self.fragment.style().content_block_size();
match (content_block_size, containing_block_size) { match content_block_size {
(LengthOrPercentageOrAuto::Calc(calc), _) => calc.to_used_value(containing_block_size), LengthPercentageOrAuto::Auto => {
(LengthOrPercentageOrAuto::Length(length), _) => Some(Au::from(length)), let container_size = containing_block_size?;
(LengthOrPercentageOrAuto::Percentage(percent), Some(container_size)) => {
Some(container_size.scale_by(percent.0))
},
(LengthOrPercentageOrAuto::Percentage(_), None) |
(LengthOrPercentageOrAuto::Auto, None) => None,
(LengthOrPercentageOrAuto::Auto, Some(container_size)) => {
let (block_start, block_end) = { let (block_start, block_end) = {
let position = self.fragment.style().logical_position(); let position = self.fragment.style().logical_position();
( (
@ -1441,11 +1418,11 @@ impl BlockFlow {
// calculated during assign-inline-size. // calculated during assign-inline-size.
let margin = self.fragment.style().logical_margin(); let margin = self.fragment.style().logical_margin();
let margin_block_start = match margin.block_start { let margin_block_start = match margin.block_start {
LengthOrPercentageOrAuto::Auto => MaybeAuto::Auto, LengthPercentageOrAuto::Auto => MaybeAuto::Auto,
_ => MaybeAuto::Specified(self.fragment.margin.block_start), _ => MaybeAuto::Specified(self.fragment.margin.block_start),
}; };
let margin_block_end = match margin.block_end { let margin_block_end = match margin.block_end {
LengthOrPercentageOrAuto::Auto => MaybeAuto::Auto, LengthPercentageOrAuto::Auto => MaybeAuto::Auto,
_ => MaybeAuto::Specified(self.fragment.margin.block_end), _ => MaybeAuto::Specified(self.fragment.margin.block_end),
}; };
@ -1454,10 +1431,12 @@ impl BlockFlow {
let sum = block_start + block_end + margin_block_start + margin_block_end; let sum = block_start + block_end + margin_block_start + margin_block_end;
Some(available_block_size - sum) Some(available_block_size - sum)
}, },
(_, _) => None, (_, _) => None,
} }
}, },
LengthPercentageOrAuto::LengthPercentage(ref lp) => {
lp.maybe_to_used_value(containing_block_size)
},
} }
} }
@ -1476,11 +1455,11 @@ impl BlockFlow {
// calculated during assign-inline-size. // calculated during assign-inline-size.
let margin = self.fragment.style().logical_margin(); let margin = self.fragment.style().logical_margin();
let margin_block_start = match margin.block_start { let margin_block_start = match margin.block_start {
LengthOrPercentageOrAuto::Auto => MaybeAuto::Auto, LengthPercentageOrAuto::Auto => MaybeAuto::Auto,
_ => MaybeAuto::Specified(self.fragment.margin.block_start), _ => MaybeAuto::Specified(self.fragment.margin.block_start),
}; };
let margin_block_end = match margin.block_end { let margin_block_end = match margin.block_end {
LengthOrPercentageOrAuto::Auto => MaybeAuto::Auto, LengthPercentageOrAuto::Auto => MaybeAuto::Auto,
_ => MaybeAuto::Specified(self.fragment.margin.block_end), _ => MaybeAuto::Specified(self.fragment.margin.block_end),
}; };
@ -2046,7 +2025,7 @@ impl BlockFlow {
// If `max-width` is set, then don't perform this speculation. We guess that the // If `max-width` is set, then don't perform this speculation. We guess that the
// page set `max-width` in order to avoid hitting floats. The search box on Google // page set `max-width` in order to avoid hitting floats. The search box on Google
// SERPs falls into this category. // SERPs falls into this category.
if self.fragment.style.max_inline_size() != LengthOrPercentageOrNone::None { if self.fragment.style.max_inline_size() != LengthPercentageOrNone::None {
return; return;
} }
@ -2177,8 +2156,10 @@ impl Flow for BlockFlow {
// If this block has a fixed width, just use that for the minimum and preferred width, // If this block has a fixed width, just use that for the minimum and preferred width,
// rather than bubbling up children inline width. // rather than bubbling up children inline width.
let consult_children = match self.fragment.style().get_position().width { let consult_children = match self.fragment.style().get_position().width {
LengthOrPercentageOrAuto::Length(_) => false, LengthPercentageOrAuto::Auto => true,
_ => true, LengthPercentageOrAuto::LengthPercentage(ref lp) => {
lp.maybe_to_used_value(None).is_none()
},
}; };
self.bubble_inline_sizes_for_block(consult_children); self.bubble_inline_sizes_for_block(consult_children);
self.fragment self.fragment
@ -2564,9 +2545,8 @@ impl Flow for BlockFlow {
.base .base
.flags .flags
.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) && .contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) &&
self.fragment.style().logical_position().inline_start == self.fragment.style().logical_position().inline_start == LengthPercentageOrAuto::Auto &&
LengthOrPercentageOrAuto::Auto && self.fragment.style().logical_position().inline_end == LengthPercentageOrAuto::Auto
self.fragment.style().logical_position().inline_end == LengthOrPercentageOrAuto::Auto
{ {
self.base.position.start.i = inline_position self.base.position.start.i = inline_position
} }
@ -2577,9 +2557,8 @@ impl Flow for BlockFlow {
.base .base
.flags .flags
.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) && .contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) &&
self.fragment.style().logical_position().block_start == self.fragment.style().logical_position().block_start == LengthPercentageOrAuto::Auto &&
LengthOrPercentageOrAuto::Auto && self.fragment.style().logical_position().block_end == LengthPercentageOrAuto::Auto
self.fragment.style().logical_position().block_end == LengthOrPercentageOrAuto::Auto
{ {
self.base.position.start.b = block_position self.base.position.start.b = block_position
} }

View file

@ -12,7 +12,7 @@ use style::computed_values::background_attachment::single_value::T as Background
use style::computed_values::background_clip::single_value::T as BackgroundClip; use style::computed_values::background_clip::single_value::T as BackgroundClip;
use style::computed_values::background_origin::single_value::T as BackgroundOrigin; use style::computed_values::background_origin::single_value::T as BackgroundOrigin;
use style::properties::style_structs::Background; use style::properties::style_structs::Background;
use style::values::computed::{BackgroundSize, LengthOrPercentageOrAuto}; use style::values::computed::{BackgroundSize, LengthPercentageOrAuto};
use style::values::generics::background::BackgroundSize as GenericBackgroundSize; use style::values::generics::background::BackgroundSize as GenericBackgroundSize;
use style::values::generics::NonNegative; use style::values::generics::NonNegative;
use style::values::specified::background::BackgroundRepeatKeyword; use style::values::specified::background::BackgroundRepeatKeyword;
@ -88,7 +88,7 @@ fn compute_background_image_size(
( (
GenericBackgroundSize::Explicit { GenericBackgroundSize::Explicit {
width, width,
height: NonNegative(LengthOrPercentageOrAuto::Auto), height: NonNegative(LengthPercentageOrAuto::Auto),
}, },
_, _,
) => { ) => {
@ -98,7 +98,7 @@ fn compute_background_image_size(
}, },
( (
GenericBackgroundSize::Explicit { GenericBackgroundSize::Explicit {
width: NonNegative(LengthOrPercentageOrAuto::Auto), width: NonNegative(LengthPercentageOrAuto::Auto),
height, height,
}, },
_, _,

View file

@ -9,7 +9,7 @@ use app_units::Au;
use euclid::{Point2D, Size2D, Vector2D}; use euclid::{Point2D, Size2D, Vector2D};
use style::properties::ComputedValues; use style::properties::ComputedValues;
use style::values::computed::image::{EndingShape, LineDirection}; use style::values::computed::image::{EndingShape, LineDirection};
use style::values::computed::{Angle, GradientItem, LengthOrPercentage, Percentage, Position}; use style::values::computed::{Angle, GradientItem, LengthPercentage, Percentage, Position};
use style::values::generics::image::EndingShape as GenericEndingShape; use style::values::generics::image::EndingShape as GenericEndingShape;
use style::values::generics::image::GradientItem as GenericGradientItem; use style::values::generics::image::GradientItem as GenericGradientItem;
use style::values::generics::image::{Circle, Ellipse, ShapeExtent}; use style::values::generics::image::{Circle, Ellipse, ShapeExtent};
@ -107,14 +107,14 @@ fn convert_gradient_stops(
{ {
let first = stop_items.first_mut().unwrap(); let first = stop_items.first_mut().unwrap();
if first.position.is_none() { if first.position.is_none() {
first.position = Some(LengthOrPercentage::Percentage(Percentage(0.0))); first.position = Some(LengthPercentage::new_percent(Percentage(0.)));
} }
} }
// If the last color stop does not have a position, set its position to 100%. // If the last color stop does not have a position, set its position to 100%.
{ {
let last = stop_items.last_mut().unwrap(); let last = stop_items.last_mut().unwrap();
if last.position.is_none() { if last.position.is_none() {
last.position = Some(LengthOrPercentage::Percentage(Percentage(1.0))); last.position = Some(LengthPercentage::new_percent(Percentage(1.0)));
} }
} }
@ -210,17 +210,11 @@ where
Size2D::new(cmp(left_side, right_side), cmp(top_side, bottom_side)) Size2D::new(cmp(left_side, right_side), cmp(top_side, bottom_side))
} }
fn position_to_offset(position: LengthOrPercentage, total_length: Au) -> f32 { fn position_to_offset(position: LengthPercentage, total_length: Au) -> f32 {
if total_length == Au(0) { if total_length == Au(0) {
return 0.0; return 0.0;
} }
match position { position.to_used_value(total_length).0 as f32 / total_length.0 as f32
LengthOrPercentage::Length(l) => l.to_i32_au() as f32 / total_length.0 as f32,
LengthOrPercentage::Percentage(percentage) => percentage.0 as f32,
LengthOrPercentage::Calc(calc) => {
calc.to_used_value(Some(total_length)).unwrap().0 as f32 / total_length.0 as f32
},
}
} }
pub fn linear( pub fn linear(

View file

@ -12,7 +12,7 @@ use crate::floats::FloatKind;
use crate::flow::{Flow, FlowClass, FlowFlags, GetBaseFlow, ImmutableFlowUtils, OpaqueFlow}; use crate::flow::{Flow, FlowClass, FlowFlags, GetBaseFlow, ImmutableFlowUtils, OpaqueFlow};
use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow};
use crate::layout_debug; use crate::layout_debug;
use crate::model::{AdjoiningMargins, CollapsibleMargins}; use crate::model::{self, AdjoiningMargins, CollapsibleMargins};
use crate::model::{IntrinsicISizes, MaybeAuto, SizeConstraint}; use crate::model::{IntrinsicISizes, MaybeAuto, SizeConstraint};
use crate::traversal::PreorderFlowTraversal; use crate::traversal::PreorderFlowTraversal;
use app_units::{Au, MAX_AU}; use app_units::{Au, MAX_AU};
@ -28,9 +28,7 @@ use style::logical_geometry::{Direction, LogicalSize};
use style::properties::ComputedValues; use style::properties::ComputedValues;
use style::servo::restyle_damage::ServoRestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage;
use style::values::computed::flex::FlexBasis; use style::values::computed::flex::FlexBasis;
use style::values::computed::{ use style::values::computed::{LengthPercentage, LengthPercentageOrAuto, LengthPercentageOrNone};
LengthOrPercentage, LengthOrPercentageOrAuto, LengthOrPercentageOrNone,
};
use style::values::generics::flex::FlexBasis as GenericFlexBasis; use style::values::generics::flex::FlexBasis as GenericFlexBasis;
/// The size of an axis. May be a specified size, a min/max /// The size of an axis. May be a specified size, a min/max
@ -46,23 +44,20 @@ impl AxisSize {
/// Generate a new available cross or main axis size from the specified size of the container, /// Generate a new available cross or main axis size from the specified size of the container,
/// containing block size, min constraint, and max constraint /// containing block size, min constraint, and max constraint
pub fn new( pub fn new(
size: LengthOrPercentageOrAuto, size: LengthPercentageOrAuto,
content_size: Option<Au>, content_size: Option<Au>,
min: LengthOrPercentage, min: LengthPercentage,
max: LengthOrPercentageOrNone, max: LengthPercentageOrNone,
) -> AxisSize { ) -> AxisSize {
match size { match size {
LengthOrPercentageOrAuto::Length(length) => AxisSize::Definite(Au::from(length)), LengthPercentageOrAuto::Auto => {
LengthOrPercentageOrAuto::Percentage(percent) => match content_size { AxisSize::MinMax(SizeConstraint::new(content_size, min, max, None))
Some(size) => AxisSize::Definite(size.scale_by(percent.0)),
None => AxisSize::Infinite,
}, },
LengthOrPercentageOrAuto::Calc(calc) => match calc.to_used_value(content_size) { LengthPercentageOrAuto::LengthPercentage(ref lp) => {
match lp.maybe_to_used_value(content_size) {
Some(length) => AxisSize::Definite(length), Some(length) => AxisSize::Definite(length),
None => AxisSize::Infinite, None => AxisSize::Infinite,
}, }
LengthOrPercentageOrAuto::Auto => {
AxisSize::MinMax(SizeConstraint::new(content_size, min, max, None))
}, },
} }
} }
@ -74,7 +69,7 @@ impl AxisSize {
/// is definite after flex size resolving. /// is definite after flex size resolving.
fn from_flex_basis( fn from_flex_basis(
flex_basis: FlexBasis, flex_basis: FlexBasis,
main_length: LengthOrPercentageOrAuto, main_length: LengthPercentageOrAuto,
containing_length: Au, containing_length: Au,
) -> MaybeAuto { ) -> MaybeAuto {
let width = match flex_basis { let width = match flex_basis {
@ -83,7 +78,7 @@ fn from_flex_basis(
}; };
match width.0 { match width.0 {
LengthOrPercentageOrAuto::Auto => MaybeAuto::from_style(main_length, containing_length), LengthPercentageOrAuto::Auto => MaybeAuto::from_style(main_length, containing_length),
other => MaybeAuto::from_style(other, containing_length), other => MaybeAuto::from_style(other, containing_length),
} }
} }
@ -144,7 +139,7 @@ impl FlexItem {
let block = flow.as_mut_block(); let block = flow.as_mut_block();
match direction { match direction {
// TODO(stshine): the definition of min-{width, height} in style component // TODO(stshine): the definition of min-{width, height} in style component
// should change to LengthOrPercentageOrAuto for automatic implied minimal size. // should change to LengthPercentageOrAuto for automatic implied minimal size.
// https://drafts.csswg.org/css-flexbox-1/#min-size-auto // https://drafts.csswg.org/css-flexbox-1/#min-size-auto
Direction::Inline => { Direction::Inline => {
let basis = from_flex_basis( let basis = from_flex_basis(
@ -228,18 +223,18 @@ impl FlexItem {
let mut margin_count = 0; let mut margin_count = 0;
match direction { match direction {
Direction::Inline => { Direction::Inline => {
if margin.inline_start == LengthOrPercentageOrAuto::Auto { if margin.inline_start == LengthPercentageOrAuto::Auto {
margin_count += 1; margin_count += 1;
} }
if margin.inline_end == LengthOrPercentageOrAuto::Auto { if margin.inline_end == LengthPercentageOrAuto::Auto {
margin_count += 1; margin_count += 1;
} }
}, },
Direction::Block => { Direction::Block => {
if margin.block_start == LengthOrPercentageOrAuto::Auto { if margin.block_start == LengthPercentageOrAuto::Auto {
margin_count += 1; margin_count += 1;
} }
if margin.block_end == LengthOrPercentageOrAuto::Auto { if margin.block_end == LengthPercentageOrAuto::Auto {
margin_count += 1; margin_count += 1;
} }
}, },
@ -461,10 +456,10 @@ impl FlexFlow {
// Currently, this is the core of BlockFlow::bubble_inline_sizes() with all float logic // Currently, this is the core of BlockFlow::bubble_inline_sizes() with all float logic
// stripped out, and max replaced with union_nonbreaking_inline. // stripped out, and max replaced with union_nonbreaking_inline.
fn inline_mode_bubble_inline_sizes(&mut self) { fn inline_mode_bubble_inline_sizes(&mut self) {
let fixed_width = match self.block_flow.fragment.style().get_position().width { // FIXME(emilio): This doesn't handle at all writing-modes.
LengthOrPercentageOrAuto::Length(_) => true, let fixed_width =
_ => false, !model::style_length(self.block_flow.fragment.style().get_position().width, None)
}; .is_auto();
let mut computation = self.block_flow.fragment.compute_intrinsic_inline_sizes(); let mut computation = self.block_flow.fragment.compute_intrinsic_inline_sizes();
if !fixed_width { if !fixed_width {
@ -488,10 +483,9 @@ impl FlexFlow {
// Currently, this is the core of BlockFlow::bubble_inline_sizes() with all float logic // Currently, this is the core of BlockFlow::bubble_inline_sizes() with all float logic
// stripped out. // stripped out.
fn block_mode_bubble_inline_sizes(&mut self) { fn block_mode_bubble_inline_sizes(&mut self) {
let fixed_width = match self.block_flow.fragment.style().get_position().width { let fixed_width =
LengthOrPercentageOrAuto::Length(_) => true, !model::style_length(self.block_flow.fragment.style().get_position().width, None)
_ => false, .is_auto();
};
let mut computation = self.block_flow.fragment.compute_intrinsic_inline_sizes(); let mut computation = self.block_flow.fragment.compute_intrinsic_inline_sizes();
if !fixed_width { if !fixed_width {
@ -821,7 +815,7 @@ impl FlexFlow {
// cross size of item should equal to the line size if any auto margin exists. // cross size of item should equal to the line size if any auto margin exists.
// https://drafts.csswg.org/css-flexbox/#algo-cross-margins // https://drafts.csswg.org/css-flexbox/#algo-cross-margins
if auto_margin_count > 0 { if auto_margin_count > 0 {
if margin.block_start == LengthOrPercentageOrAuto::Auto { if margin.block_start == LengthPercentageOrAuto::Auto {
margin_block_start = if free_space < Au(0) { margin_block_start = if free_space < Au(0) {
Au(0) Au(0)
} else { } else {
@ -835,7 +829,7 @@ impl FlexFlow {
let self_align = block.fragment.style().get_position().align_self; let self_align = block.fragment.style().get_position().align_self;
if self_align == AlignSelf::Stretch && if self_align == AlignSelf::Stretch &&
block.fragment.style().content_block_size() == LengthOrPercentageOrAuto::Auto block.fragment.style().content_block_size() == LengthPercentageOrAuto::Auto
{ {
free_space = Au(0); free_space = Au(0);
block.base.block_container_explicit_block_size = Some(line.cross_size); block.base.block_container_explicit_block_size = Some(line.cross_size);

View file

@ -10,7 +10,7 @@ use std::cmp::{max, min};
use std::fmt; use std::fmt;
use style::computed_values::float::T as StyleFloat; use style::computed_values::float::T as StyleFloat;
use style::logical_geometry::{LogicalRect, LogicalSize, WritingMode}; use style::logical_geometry::{LogicalRect, LogicalSize, WritingMode};
use style::values::computed::LengthOrPercentageOrAuto; use style::values::computed::LengthPercentageOrAuto;
/// The kind of float: left or right. /// The kind of float: left or right.
#[derive(Clone, Copy, Debug, Serialize)] #[derive(Clone, Copy, Debug, Serialize)]
@ -542,19 +542,23 @@ impl SpeculatedFloatPlacement {
let mut float_inline_size = base_flow.intrinsic_inline_sizes.preferred_inline_size; let mut float_inline_size = base_flow.intrinsic_inline_sizes.preferred_inline_size;
if float_inline_size == Au(0) { if float_inline_size == Au(0) {
if flow.is_block_like() { if flow.is_block_like() {
// Hack: If the size of the float is a percentage, then there's no way we can guess // Hack: If the size of the float is not fixed, then there's no
// at its size now. So just pick an arbitrary nonzero value (in this case, 1px) so // way we can guess at its size now. So just pick an arbitrary
// that the layout traversal logic will know that objects later in the document // nonzero value (in this case, 1px) so that the layout
// traversal logic will know that objects later in the document
// might flow around this float. // might flow around this float.
if let LengthOrPercentageOrAuto::Percentage(percentage) = let inline_size = flow.as_block().fragment.style.content_inline_size();
flow.as_block().fragment.style.content_inline_size() let fixed = match inline_size {
{ LengthPercentageOrAuto::Auto => false,
if percentage.0 > 0.0 { LengthPercentageOrAuto::LengthPercentage(ref lp) => {
lp.is_definitely_zero() || lp.maybe_to_used_value(None).is_some()
},
};
if !fixed {
float_inline_size = Au::from_px(1) float_inline_size = Au::from_px(1)
} }
} }
} }
}
match base_flow.flags.float_kind() { match base_flow.flags.float_kind() {
StyleFloat::None => {}, StyleFloat::None => {},

View file

@ -67,7 +67,7 @@ use style::logical_geometry::{LogicalRect, LogicalSize, WritingMode};
use style::properties::ComputedValues; use style::properties::ComputedValues;
use style::selector_parser::RestyleDamage; use style::selector_parser::RestyleDamage;
use style::servo::restyle_damage::ServoRestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage;
use style::values::computed::LengthOrPercentageOrAuto; use style::values::computed::LengthPercentageOrAuto;
use webrender_api::LayoutTransform; use webrender_api::LayoutTransform;
/// This marker trait indicates that a type is a struct with `#[repr(C)]` whose first field /// This marker trait indicates that a type is a struct with `#[repr(C)]` whose first field
@ -1068,13 +1068,13 @@ impl BaseFlow {
flags.insert(FlowFlags::IS_ABSOLUTELY_POSITIONED); flags.insert(FlowFlags::IS_ABSOLUTELY_POSITIONED);
let logical_position = style.logical_position(); let logical_position = style.logical_position();
if logical_position.inline_start == LengthOrPercentageOrAuto::Auto && if logical_position.inline_start == LengthPercentageOrAuto::Auto &&
logical_position.inline_end == LengthOrPercentageOrAuto::Auto logical_position.inline_end == LengthPercentageOrAuto::Auto
{ {
flags.insert(FlowFlags::INLINE_POSITION_IS_STATIC); flags.insert(FlowFlags::INLINE_POSITION_IS_STATIC);
} }
if logical_position.block_start == LengthOrPercentageOrAuto::Auto && if logical_position.block_start == LengthPercentageOrAuto::Auto &&
logical_position.block_end == LengthOrPercentageOrAuto::Auto logical_position.block_end == LengthPercentageOrAuto::Auto
{ {
flags.insert(FlowFlags::BLOCK_POSITION_IS_STATIC); flags.insert(FlowFlags::BLOCK_POSITION_IS_STATIC);
} }
@ -1161,13 +1161,13 @@ impl BaseFlow {
let logical_position = style.logical_position(); let logical_position = style.logical_position();
self.flags.set( self.flags.set(
FlowFlags::INLINE_POSITION_IS_STATIC, FlowFlags::INLINE_POSITION_IS_STATIC,
logical_position.inline_start == LengthOrPercentageOrAuto::Auto && logical_position.inline_start == LengthPercentageOrAuto::Auto &&
logical_position.inline_end == LengthOrPercentageOrAuto::Auto, logical_position.inline_end == LengthPercentageOrAuto::Auto,
); );
self.flags.set( self.flags.set(
FlowFlags::BLOCK_POSITION_IS_STATIC, FlowFlags::BLOCK_POSITION_IS_STATIC,
logical_position.block_start == LengthOrPercentageOrAuto::Auto && logical_position.block_start == LengthPercentageOrAuto::Auto &&
logical_position.block_end == LengthOrPercentageOrAuto::Auto, logical_position.block_end == LengthPercentageOrAuto::Auto,
); );
} }
} }

View file

@ -61,7 +61,7 @@ use style::selector_parser::RestyleDamage;
use style::servo::restyle_damage::ServoRestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage;
use style::str::char_is_whitespace; use style::str::char_is_whitespace;
use style::values::computed::counters::ContentItem; use style::values::computed::counters::ContentItem;
use style::values::computed::{Length, LengthOrPercentage, LengthOrPercentageOrAuto}; use style::values::computed::{LengthPercentage, LengthPercentageOrAuto};
use style::values::generics::box_::{Perspective, VerticalAlign}; use style::values::generics::box_::{Perspective, VerticalAlign};
use style::values::generics::transform; use style::values::generics::transform;
use webrender_api::{self, LayoutTransform}; use webrender_api::{self, LayoutTransform};
@ -1448,14 +1448,14 @@ impl Fragment {
pub fn relative_position(&self, containing_block_size: &LogicalSize<Au>) -> LogicalSize<Au> { pub fn relative_position(&self, containing_block_size: &LogicalSize<Au>) -> LogicalSize<Au> {
fn from_style(style: &ComputedValues, container_size: &LogicalSize<Au>) -> LogicalSize<Au> { fn from_style(style: &ComputedValues, container_size: &LogicalSize<Au>) -> LogicalSize<Au> {
let offsets = style.logical_position(); let offsets = style.logical_position();
let offset_i = if offsets.inline_start != LengthOrPercentageOrAuto::Auto { let offset_i = if offsets.inline_start != LengthPercentageOrAuto::Auto {
MaybeAuto::from_style(offsets.inline_start, container_size.inline) MaybeAuto::from_style(offsets.inline_start, container_size.inline)
.specified_or_zero() .specified_or_zero()
} else { } else {
-MaybeAuto::from_style(offsets.inline_end, container_size.inline) -MaybeAuto::from_style(offsets.inline_end, container_size.inline)
.specified_or_zero() .specified_or_zero()
}; };
let offset_b = if offsets.block_start != LengthOrPercentageOrAuto::Auto { let offset_b = if offsets.block_start != LengthPercentageOrAuto::Auto {
MaybeAuto::from_style(offsets.block_start, container_size.block).specified_or_zero() MaybeAuto::from_style(offsets.block_start, container_size.block).specified_or_zero()
} else { } else {
-MaybeAuto::from_style(offsets.block_end, container_size.block).specified_or_zero() -MaybeAuto::from_style(offsets.block_end, container_size.block).specified_or_zero()
@ -1610,14 +1610,19 @@ impl Fragment {
SpecificFragmentInfo::Canvas(_) | SpecificFragmentInfo::Canvas(_) |
SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Iframe(_) |
SpecificFragmentInfo::Svg(_) => { SpecificFragmentInfo::Svg(_) => {
let mut inline_size = match self.style.content_inline_size() { let inline_size = match self.style.content_inline_size() {
LengthOrPercentageOrAuto::Auto | LengthOrPercentageOrAuto::Percentage(_) => { LengthPercentageOrAuto::Auto => None,
LengthPercentageOrAuto::LengthPercentage(ref lp) => {
lp.maybe_to_used_value(None)
},
};
let mut inline_size = inline_size.unwrap_or_else(|| {
// We have to initialize the `border_padding` field first to make // We have to initialize the `border_padding` field first to make
// the size constraints work properly. // the size constraints work properly.
// TODO(stshine): Find a cleaner way to do this. // TODO(stshine): Find a cleaner way to do this.
let padding = self.style.logical_padding(); let padding = self.style.logical_padding();
self.border_padding.inline_start = self.border_padding.inline_start = padding.inline_start.to_used_value(Au(0));
padding.inline_start.to_used_value(Au(0));
self.border_padding.inline_end = padding.inline_end.to_used_value(Au(0)); self.border_padding.inline_end = padding.inline_end.to_used_value(Au(0));
self.border_padding.block_start = padding.block_start.to_used_value(Au(0)); self.border_padding.block_start = padding.block_start.to_used_value(Au(0));
self.border_padding.block_end = padding.block_end.to_used_value(Au(0)); self.border_padding.block_end = padding.block_end.to_used_value(Au(0));
@ -1628,14 +1633,7 @@ impl Fragment {
self.border_padding.block_end += border.block_end; self.border_padding.block_end += border.block_end;
let (result_inline, _) = self.calculate_replaced_sizes(None, None); let (result_inline, _) = self.calculate_replaced_sizes(None, None);
result_inline result_inline
}, });
LengthOrPercentageOrAuto::Length(length) => Au::from(length),
LengthOrPercentageOrAuto::Calc(calc) => {
// TODO(nox): This is probably wrong, because it accounts neither for
// clamping (not sure if necessary here) nor percentage.
Au::from(calc.unclamped_length())
},
};
let size_constraint = self.size_constraint(None, Direction::Inline); let size_constraint = self.size_constraint(None, Direction::Inline);
inline_size = size_constraint.clamp(inline_size); inline_size = size_constraint.clamp(inline_size);
@ -2432,16 +2430,8 @@ impl Fragment {
content_inline_metrics.space_below_baseline content_inline_metrics.space_below_baseline
} }
}, },
VerticalAlign::Length(LengthOrPercentage::Length(length)) => { VerticalAlign::Length(ref lp) => {
offset -= Au::from(length) offset -= lp.to_used_value(minimum_line_metrics.space_needed());
},
VerticalAlign::Length(LengthOrPercentage::Percentage(percentage)) => {
offset -= minimum_line_metrics.space_needed().scale_by(percentage.0)
},
VerticalAlign::Length(LengthOrPercentage::Calc(formula)) => {
offset -= formula
.to_used_value(Some(minimum_line_metrics.space_needed()))
.unwrap()
}, },
} }
} }
@ -2519,12 +2509,12 @@ impl Fragment {
continue; continue;
} }
if inline_context_node.style.logical_margin().inline_end != if inline_context_node.style.logical_margin().inline_end !=
LengthOrPercentageOrAuto::Length(Length::new(0.)) LengthPercentageOrAuto::zero()
{ {
return false; return false;
} }
if inline_context_node.style.logical_padding().inline_end != if inline_context_node.style.logical_padding().inline_end !=
LengthOrPercentage::Length(Length::new(0.)) LengthPercentage::zero()
{ {
return false; return false;
} }
@ -2545,12 +2535,12 @@ impl Fragment {
continue; continue;
} }
if inline_context_node.style.logical_margin().inline_start != if inline_context_node.style.logical_margin().inline_start !=
LengthOrPercentageOrAuto::Length(Length::new(0.)) LengthPercentageOrAuto::zero()
{ {
return false; return false;
} }
if inline_context_node.style.logical_padding().inline_start != if inline_context_node.style.logical_padding().inline_start !=
LengthOrPercentage::Length(Length::new(0.)) LengthPercentage::zero()
{ {
return false; return false;
} }

View file

@ -11,8 +11,8 @@ use std::cmp::{max, min};
use std::fmt; use std::fmt;
use style::logical_geometry::{LogicalMargin, WritingMode}; use style::logical_geometry::{LogicalMargin, WritingMode};
use style::properties::ComputedValues; use style::properties::ComputedValues;
use style::values::computed::LengthOrPercentageOrNone; use style::values::computed::LengthPercentageOrNone;
use style::values::computed::{LengthOrPercentage, LengthOrPercentageOrAuto}; use style::values::computed::{LengthPercentage, LengthPercentageOrAuto};
/// A collapsible margin. See CSS 2.1 § 8.3.1. /// A collapsible margin. See CSS 2.1 § 8.3.1.
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
@ -135,27 +135,20 @@ impl MarginCollapseInfo {
MarginCollapseState::AccumulatingCollapsibleTopMargin => { MarginCollapseState::AccumulatingCollapsibleTopMargin => {
may_collapse_through = may_collapse_through && may_collapse_through = may_collapse_through &&
match fragment.style().content_block_size() { match fragment.style().content_block_size() {
LengthOrPercentageOrAuto::Auto => true, LengthPercentageOrAuto::Auto => true,
LengthOrPercentageOrAuto::Length(l) => l.px() == 0., LengthPercentageOrAuto::LengthPercentage(ref lp) => {
LengthOrPercentageOrAuto::Percentage(v) => { lp.is_definitely_zero() ||
v.0 == 0. || containing_block_size.is_none() lp.maybe_to_used_value(containing_block_size).is_none()
}, },
LengthOrPercentageOrAuto::Calc(_) => false,
}; };
if may_collapse_through { if may_collapse_through {
match fragment.style().min_block_size() { if fragment.style().min_block_size().is_definitely_zero() {
LengthOrPercentage::Length(l) if l.px() == 0. => {
FinalMarginState::MarginsCollapseThrough FinalMarginState::MarginsCollapseThrough
}, } else {
LengthOrPercentage::Percentage(v) if v.0 == 0. => {
FinalMarginState::MarginsCollapseThrough
},
_ => {
// If the fragment has non-zero min-block-size, margins may not // If the fragment has non-zero min-block-size, margins may not
// collapse through it. // collapse through it.
FinalMarginState::BottomMarginCollapses FinalMarginState::BottomMarginCollapses
},
} }
} else { } else {
// If the fragment has an explicitly specified block-size, margins may not // If the fragment has an explicitly specified block-size, margins may not
@ -442,16 +435,12 @@ pub enum MaybeAuto {
impl MaybeAuto { impl MaybeAuto {
#[inline] #[inline]
pub fn from_style(length: LengthOrPercentageOrAuto, containing_length: Au) -> MaybeAuto { pub fn from_style(length: LengthPercentageOrAuto, containing_length: Au) -> MaybeAuto {
match length { match length {
LengthOrPercentageOrAuto::Auto => MaybeAuto::Auto, LengthPercentageOrAuto::Auto => MaybeAuto::Auto,
LengthOrPercentageOrAuto::Percentage(percent) => { LengthPercentageOrAuto::LengthPercentage(ref lp) => {
MaybeAuto::Specified(containing_length.scale_by(percent.0)) MaybeAuto::Specified(lp.to_used_value(containing_length))
}, },
LengthOrPercentageOrAuto::Calc(calc) => {
MaybeAuto::from_option(calc.to_used_value(Some(containing_length)))
},
LengthOrPercentageOrAuto::Length(length) => MaybeAuto::Specified(Au::from(length)),
} }
} }
@ -484,6 +473,14 @@ impl MaybeAuto {
self.specified_or_default(Au::new(0)) self.specified_or_default(Au::new(0))
} }
#[inline]
pub fn is_auto(&self) -> bool {
match *self {
MaybeAuto::Auto => true,
MaybeAuto::Specified(..) => false,
}
}
#[inline] #[inline]
pub fn map<F>(&self, mapper: F) -> MaybeAuto pub fn map<F>(&self, mapper: F) -> MaybeAuto
where where
@ -499,18 +496,11 @@ impl MaybeAuto {
/// Receive an optional container size and return used value for width or height. /// Receive an optional container size and return used value for width or height.
/// ///
/// `style_length`: content size as given in the CSS. /// `style_length`: content size as given in the CSS.
pub fn style_length( pub fn style_length(style_length: LengthPercentageOrAuto, container_size: Option<Au>) -> MaybeAuto {
style_length: LengthOrPercentageOrAuto, match style_length {
container_size: Option<Au>, LengthPercentageOrAuto::Auto => MaybeAuto::Auto,
) -> MaybeAuto { LengthPercentageOrAuto::LengthPercentage(ref lp) => {
match container_size { MaybeAuto::from_option(lp.maybe_to_used_value(container_size))
Some(length) => MaybeAuto::from_style(style_length, length),
None => {
if let LengthOrPercentageOrAuto::Length(length) = style_length {
MaybeAuto::Specified(Au::from(length))
} else {
MaybeAuto::Auto
}
}, },
} }
} }
@ -576,31 +566,21 @@ impl SizeConstraint {
/// Create a `SizeConstraint` for an axis. /// Create a `SizeConstraint` for an axis.
pub fn new( pub fn new(
container_size: Option<Au>, container_size: Option<Au>,
min_size: LengthOrPercentage, min_size: LengthPercentage,
max_size: LengthOrPercentageOrNone, max_size: LengthPercentageOrNone,
border: Option<Au>, border: Option<Au>,
) -> SizeConstraint { ) -> SizeConstraint {
let mut min_size = match container_size { let mut min_size = min_size
Some(container_size) => min_size.to_used_value(container_size), .maybe_to_used_value(container_size)
None => { .unwrap_or(Au(0));
if let LengthOrPercentage::Length(length) = min_size {
Au::from(length) let mut max_size = match max_size {
} else { LengthPercentageOrNone::None => None,
Au(0) LengthPercentageOrNone::LengthPercentage(ref lp) => {
} lp.maybe_to_used_value(container_size)
}, },
}; };
let mut max_size = match container_size {
Some(container_size) => max_size.to_used_value(container_size),
None => {
if let LengthOrPercentageOrNone::Length(length) = max_size {
Some(Au::from(length))
} else {
None
}
},
};
// Make sure max size is not smaller than min size. // Make sure max size is not smaller than min size.
max_size = max_size.map(|x| max(x, min_size)); max_size = max_size.map(|x| max(x, min_size));
@ -609,10 +589,7 @@ impl SizeConstraint {
max_size = max_size.map(|x| max(x - border, Au(0))); max_size = max_size.map(|x| max(x - border, Au(0)));
} }
SizeConstraint { SizeConstraint { min_size, max_size }
min_size: min_size,
max_size: max_size,
}
} }
/// Clamp the given size by the given min size and max size constraint. /// Clamp the given size by the given min size and max size constraint.

View file

@ -19,7 +19,7 @@ use std::fmt;
use std::sync::Arc; use std::sync::Arc;
use style::logical_geometry::LogicalSize; use style::logical_geometry::LogicalSize;
use style::properties::ComputedValues; use style::properties::ComputedValues;
use style::values::computed::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone}; use style::values::computed::{LengthPercentageOrAuto, LengthPercentageOrNone};
use style::values::generics::column::ColumnCount; use style::values::generics::column::ColumnCount;
use style::values::Either; use style::values::Either;
@ -154,11 +154,20 @@ impl Flow for MulticolFlow {
this_fragment_is_empty: true, this_fragment_is_empty: true,
available_block_size: { available_block_size: {
let style = &self.block_flow.fragment.style; let style = &self.block_flow.fragment.style;
if let LengthOrPercentageOrAuto::Length(length) = style.content_block_size() { let size = match style.content_block_size() {
Au::from(length) LengthPercentageOrAuto::Auto => None,
} else if let LengthOrPercentageOrNone::Length(length) = style.max_block_size() { LengthPercentageOrAuto::LengthPercentage(ref lp) => {
Au::from(length) lp.maybe_to_used_value(None)
} else { },
};
let size = size.or_else(|| match style.max_block_size() {
LengthPercentageOrNone::None => None,
LengthPercentageOrNone::LengthPercentage(ref lp) => {
lp.maybe_to_used_value(None)
},
});
size.unwrap_or_else(|| {
// FIXME: do column balancing instead // FIXME: do column balancing instead
// FIXME: (until column balancing) substract margins/borders/padding // FIXME: (until column balancing) substract margins/borders/padding
LogicalSize::from_physical( LogicalSize::from_physical(
@ -166,7 +175,7 @@ impl Flow for MulticolFlow {
ctx.shared_context().viewport_size(), ctx.shared_context().viewport_size(),
) )
.block .block
} })
}, },
}); });

View file

@ -33,7 +33,7 @@ use style::logical_geometry::LogicalSize;
use style::properties::style_structs::Background; use style::properties::style_structs::Background;
use style::properties::ComputedValues; use style::properties::ComputedValues;
use style::servo::restyle_damage::ServoRestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage;
use style::values::computed::LengthOrPercentageOrAuto; use style::values::computed::LengthPercentageOrAuto;
use style::values::CSSFloat; use style::values::CSSFloat;
#[allow(unsafe_code)] #[allow(unsafe_code)]
@ -301,16 +301,16 @@ impl Flow for TableFlow {
self.column_intrinsic_inline_sizes self.column_intrinsic_inline_sizes
.push(ColumnIntrinsicInlineSize { .push(ColumnIntrinsicInlineSize {
minimum_length: match *specified_inline_size { minimum_length: match *specified_inline_size {
LengthOrPercentageOrAuto::Auto | LengthPercentageOrAuto::Auto => Au(0),
LengthOrPercentageOrAuto::Calc(_) | LengthPercentageOrAuto::LengthPercentage(ref lp) => {
LengthOrPercentageOrAuto::Percentage(_) => Au(0), lp.maybe_to_used_value(None).unwrap_or(Au(0))
LengthOrPercentageOrAuto::Length(length) => Au::from(length), },
}, },
percentage: match *specified_inline_size { percentage: match *specified_inline_size {
LengthOrPercentageOrAuto::Auto | LengthPercentageOrAuto::Auto => 0.0,
LengthOrPercentageOrAuto::Calc(_) | LengthPercentageOrAuto::LengthPercentage(ref lp) => {
LengthOrPercentageOrAuto::Length(_) => 0.0, lp.as_percentage().map_or(0.0, |p| p.0)
LengthOrPercentageOrAuto::Percentage(percentage) => percentage.0, },
}, },
preferred: Au(0), preferred: Au(0),
constrained: false, constrained: false,

View file

@ -14,7 +14,7 @@ use euclid::Point2D;
use std::fmt; use std::fmt;
use style::logical_geometry::LogicalSize; use style::logical_geometry::LogicalSize;
use style::properties::ComputedValues; use style::properties::ComputedValues;
use style::values::computed::LengthOrPercentageOrAuto; use style::values::computed::LengthPercentageOrAuto;
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe impl crate::flow::HasBaseFlow for TableColGroupFlow {} unsafe impl crate::flow::HasBaseFlow for TableColGroupFlow {}
@ -31,10 +31,10 @@ pub struct TableColGroupFlow {
/// The table column fragments /// The table column fragments
pub cols: Vec<Fragment>, pub cols: Vec<Fragment>,
/// The specified inline-sizes of table columns. (We use `LengthOrPercentageOrAuto` here in /// The specified inline-sizes of table columns. (We use `LengthPercentageOrAuto` here in
/// lieu of `ColumnInlineSize` because column groups do not establish minimum or preferred /// lieu of `ColumnInlineSize` because column groups do not establish minimum or preferred
/// inline sizes.) /// inline sizes.)
pub inline_sizes: Vec<LengthOrPercentageOrAuto>, pub inline_sizes: Vec<LengthPercentageOrAuto>,
} }
impl TableColGroupFlow { impl TableColGroupFlow {

View file

@ -29,7 +29,7 @@ use style::computed_values::border_spacing::T as BorderSpacing;
use style::computed_values::border_top_style::T as BorderStyle; use style::computed_values::border_top_style::T as BorderStyle;
use style::logical_geometry::{LogicalSize, PhysicalSide, WritingMode}; use style::logical_geometry::{LogicalSize, PhysicalSide, WritingMode};
use style::properties::ComputedValues; use style::properties::ComputedValues;
use style::values::computed::{Color, LengthOrPercentageOrAuto}; use style::values::computed::{Color, LengthPercentageOrAuto};
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe impl crate::flow::HasBaseFlow for TableRowFlow {} unsafe impl crate::flow::HasBaseFlow for TableRowFlow {}
@ -430,25 +430,24 @@ impl Flow for TableRowFlow {
let child_base = kid.mut_base(); let child_base = kid.mut_base();
let child_column_inline_size = ColumnIntrinsicInlineSize { let child_column_inline_size = ColumnIntrinsicInlineSize {
minimum_length: match child_specified_inline_size { minimum_length: match child_specified_inline_size {
LengthOrPercentageOrAuto::Auto | LengthPercentageOrAuto::Auto => None,
LengthOrPercentageOrAuto::Calc(_) | LengthPercentageOrAuto::LengthPercentage(ref lp) => {
LengthOrPercentageOrAuto::Percentage(_) => { lp.maybe_to_used_value(None)
child_base.intrinsic_inline_sizes.minimum_inline_size
},
LengthOrPercentageOrAuto::Length(length) => Au::from(length),
}, },
}
.unwrap_or(child_base.intrinsic_inline_sizes.minimum_inline_size),
percentage: match child_specified_inline_size { percentage: match child_specified_inline_size {
LengthOrPercentageOrAuto::Auto | LengthPercentageOrAuto::Auto => 0.0,
LengthOrPercentageOrAuto::Calc(_) | LengthPercentageOrAuto::LengthPercentage(ref lp) => {
LengthOrPercentageOrAuto::Length(_) => 0.0, lp.as_percentage().map_or(0.0, |p| p.0)
LengthOrPercentageOrAuto::Percentage(percentage) => percentage.0, },
}, },
preferred: child_base.intrinsic_inline_sizes.preferred_inline_size, preferred: child_base.intrinsic_inline_sizes.preferred_inline_size,
constrained: match child_specified_inline_size { constrained: match child_specified_inline_size {
LengthOrPercentageOrAuto::Length(_) => true, LengthPercentageOrAuto::Auto => false,
LengthOrPercentageOrAuto::Auto | LengthPercentageOrAuto::LengthPercentage(ref lp) => {
LengthOrPercentageOrAuto::Calc(_) | lp.maybe_to_used_value(None).is_some()
LengthOrPercentageOrAuto::Percentage(_) => false, },
}, },
}; };
min_inline_size = min_inline_size + child_column_inline_size.minimum_length; min_inline_size = min_inline_size + child_column_inline_size.minimum_length;

View file

@ -35,7 +35,7 @@ use style::computed_values::{position, table_layout};
use style::context::SharedStyleContext; use style::context::SharedStyleContext;
use style::logical_geometry::{LogicalRect, LogicalSize}; use style::logical_geometry::{LogicalRect, LogicalSize};
use style::properties::ComputedValues; use style::properties::ComputedValues;
use style::values::computed::LengthOrPercentageOrAuto; use style::values::computed::LengthPercentageOrAuto;
use style::values::CSSFloat; use style::values::CSSFloat;
#[derive(Clone, Copy, Debug, Serialize)] #[derive(Clone, Copy, Debug, Serialize)]
@ -203,7 +203,7 @@ impl TableWrapperFlow {
// says "the basic idea is the same as the shrink-to-fit width that CSS2.1 defines". So we // says "the basic idea is the same as the shrink-to-fit width that CSS2.1 defines". So we
// just use the shrink-to-fit inline size. // just use the shrink-to-fit inline size.
let available_inline_size = match self.block_flow.fragment.style().content_inline_size() { let available_inline_size = match self.block_flow.fragment.style().content_inline_size() {
LengthOrPercentageOrAuto::Auto => { LengthPercentageOrAuto::Auto => {
self.block_flow self.block_flow
.get_shrink_to_fit_inline_size(available_inline_size) - .get_shrink_to_fit_inline_size(available_inline_size) -
table_border_padding table_border_padding

View file

@ -718,7 +718,9 @@ impl LayoutElementHelpers for LayoutDom<Element> {
specified::NoCalcLength::ServoCharacterWidth(specified::CharacterWidth(size)); specified::NoCalcLength::ServoCharacterWidth(specified::CharacterWidth(size));
hints.push(from_declaration( hints.push(from_declaration(
shared_lock, shared_lock,
PropertyDeclaration::Width(specified::LengthOrPercentageOrAuto::Length(value)), PropertyDeclaration::Width(specified::LengthPercentageOrAuto::LengthPercentage(
specified::LengthPercentage::Length(value),
)),
)); ));
} }
@ -743,8 +745,8 @@ impl LayoutElementHelpers for LayoutDom<Element> {
match width { match width {
LengthOrPercentageOrAuto::Auto => {}, LengthOrPercentageOrAuto::Auto => {},
LengthOrPercentageOrAuto::Percentage(percentage) => { LengthOrPercentageOrAuto::Percentage(percentage) => {
let width_value = specified::LengthOrPercentageOrAuto::Percentage( let width_value = specified::LengthPercentageOrAuto::LengthPercentage(
computed::Percentage(percentage), specified::LengthPercentage::Percentage(computed::Percentage(percentage)),
); );
hints.push(from_declaration( hints.push(from_declaration(
shared_lock, shared_lock,
@ -752,10 +754,11 @@ impl LayoutElementHelpers for LayoutDom<Element> {
)); ));
}, },
LengthOrPercentageOrAuto::Length(length) => { LengthOrPercentageOrAuto::Length(length) => {
let width_value = let width_value = specified::LengthPercentageOrAuto::LengthPercentage(
specified::LengthOrPercentageOrAuto::Length(specified::NoCalcLength::Absolute( specified::LengthPercentage::Length(specified::NoCalcLength::Absolute(
specified::AbsoluteLength::Px(length.to_f32_px()), specified::AbsoluteLength::Px(length.to_f32_px()),
)); )),
);
hints.push(from_declaration( hints.push(from_declaration(
shared_lock, shared_lock,
PropertyDeclaration::Width(width_value), PropertyDeclaration::Width(width_value),
@ -776,8 +779,8 @@ impl LayoutElementHelpers for LayoutDom<Element> {
match height { match height {
LengthOrPercentageOrAuto::Auto => {}, LengthOrPercentageOrAuto::Auto => {},
LengthOrPercentageOrAuto::Percentage(percentage) => { LengthOrPercentageOrAuto::Percentage(percentage) => {
let height_value = specified::LengthOrPercentageOrAuto::Percentage( let height_value = specified::LengthPercentageOrAuto::LengthPercentage(
computed::Percentage(percentage), specified::LengthPercentage::Percentage(computed::Percentage(percentage)),
); );
hints.push(from_declaration( hints.push(from_declaration(
shared_lock, shared_lock,
@ -785,10 +788,11 @@ impl LayoutElementHelpers for LayoutDom<Element> {
)); ));
}, },
LengthOrPercentageOrAuto::Length(length) => { LengthOrPercentageOrAuto::Length(length) => {
let height_value = let height_value = specified::LengthPercentageOrAuto::LengthPercentage(
specified::LengthOrPercentageOrAuto::Length(specified::NoCalcLength::Absolute( specified::LengthPercentage::Length(specified::NoCalcLength::Absolute(
specified::AbsoluteLength::Px(length.to_f32_px()), specified::AbsoluteLength::Px(length.to_f32_px()),
)); )),
);
hints.push(from_declaration( hints.push(from_declaration(
shared_lock, shared_lock,
PropertyDeclaration::Height(height_value), PropertyDeclaration::Height(height_value),
@ -815,7 +819,9 @@ impl LayoutElementHelpers for LayoutDom<Element> {
specified::NoCalcLength::ServoCharacterWidth(specified::CharacterWidth(cols)); specified::NoCalcLength::ServoCharacterWidth(specified::CharacterWidth(cols));
hints.push(from_declaration( hints.push(from_declaration(
shared_lock, shared_lock,
PropertyDeclaration::Width(specified::LengthOrPercentageOrAuto::Length(value)), PropertyDeclaration::Width(specified::LengthPercentageOrAuto::LengthPercentage(
specified::LengthPercentage::Length(value),
)),
)); ));
} }
@ -837,7 +843,9 @@ impl LayoutElementHelpers for LayoutDom<Element> {
)); ));
hints.push(from_declaration( hints.push(from_declaration(
shared_lock, shared_lock,
PropertyDeclaration::Height(specified::LengthOrPercentageOrAuto::Length(value)), PropertyDeclaration::Height(specified::LengthPercentageOrAuto::LengthPercentage(
specified::LengthPercentage::Length(value),
)),
)); ));
} }

View file

@ -543,7 +543,7 @@ pub fn parse_legacy_color(mut input: &str) -> Result<RGBA, ()> {
/// Parses a [dimension value][dim]. If unparseable, `Auto` is returned. /// Parses a [dimension value][dim]. If unparseable, `Auto` is returned.
/// ///
/// [dim]: https://html.spec.whatwg.org/multipage/#rules-for-parsing-dimension-values /// [dim]: https://html.spec.whatwg.org/multipage/#rules-for-parsing-dimension-values
// TODO: this function can be rewritten to return Result<LengthOrPercentage, _> // TODO: this function can be rewritten to return Result<LengthPercentage, _>
pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto { pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto {
// Steps 1 & 2 are not relevant // Steps 1 & 2 are not relevant

View file

@ -20,9 +20,9 @@ use crate::stylesheets::{Origin, RulesMutateError};
use crate::values::computed::image::LineDirection; use crate::values::computed::image::LineDirection;
use crate::values::computed::transform::Matrix3D; use crate::values::computed::transform::Matrix3D;
use crate::values::computed::url::ComputedImageUrl; use crate::values::computed::url::ComputedImageUrl;
use crate::values::computed::{Angle, CalcLengthOrPercentage, Gradient, Image}; use crate::values::computed::{Angle, Gradient, Image};
use crate::values::computed::{Integer, LengthOrPercentage}; use crate::values::computed::{Integer, LengthPercentage};
use crate::values::computed::{LengthOrPercentageOrAuto, NonNegativeLengthOrPercentageOrAuto}; use crate::values::computed::{LengthPercentageOrAuto, NonNegativeLengthPercentageOrAuto};
use crate::values::computed::{Percentage, TextAlign}; use crate::values::computed::{Percentage, TextAlign};
use crate::values::generics::box_::VerticalAlign; use crate::values::generics::box_::VerticalAlign;
use crate::values::generics::grid::{TrackListValue, TrackSize}; use crate::values::generics::grid::{TrackListValue, TrackSize};
@ -31,9 +31,10 @@ use crate::values::generics::rect::Rect;
use crate::values::generics::NonNegative; use crate::values::generics::NonNegative;
use app_units::Au; use app_units::Au;
use std::f32::consts::PI; use std::f32::consts::PI;
use style_traits::values::specified::AllowedNumericType;
impl From<CalcLengthOrPercentage> for nsStyleCoord_CalcValue { impl From<LengthPercentage> for nsStyleCoord_CalcValue {
fn from(other: CalcLengthOrPercentage) -> nsStyleCoord_CalcValue { fn from(other: LengthPercentage) -> nsStyleCoord_CalcValue {
let has_percentage = other.percentage.is_some(); let has_percentage = other.percentage.is_some();
nsStyleCoord_CalcValue { nsStyleCoord_CalcValue {
mLength: other.unclamped_length().to_i32_au(), mLength: other.unclamped_length().to_i32_au(),
@ -43,82 +44,44 @@ impl From<CalcLengthOrPercentage> for nsStyleCoord_CalcValue {
} }
} }
impl From<nsStyleCoord_CalcValue> for CalcLengthOrPercentage { impl From<nsStyleCoord_CalcValue> for LengthPercentage {
fn from(other: nsStyleCoord_CalcValue) -> CalcLengthOrPercentage { fn from(other: nsStyleCoord_CalcValue) -> LengthPercentage {
let percentage = if other.mHasPercent { let percentage = if other.mHasPercent {
Some(Percentage(other.mPercent)) Some(Percentage(other.mPercent))
} else { } else {
None None
}; };
Self::new(Au(other.mLength).into(), percentage) Self::with_clamping_mode(
Au(other.mLength).into(),
percentage,
AllowedNumericType::All,
/* was_calc = */ true,
)
} }
} }
impl From<LengthOrPercentage> for nsStyleCoord_CalcValue { impl LengthPercentageOrAuto {
fn from(other: LengthOrPercentage) -> nsStyleCoord_CalcValue {
match other {
LengthOrPercentage::Length(px) => nsStyleCoord_CalcValue {
mLength: px.to_i32_au(),
mPercent: 0.0,
mHasPercent: false,
},
LengthOrPercentage::Percentage(pc) => nsStyleCoord_CalcValue {
mLength: 0,
mPercent: pc.0,
mHasPercent: true,
},
LengthOrPercentage::Calc(calc) => calc.into(),
}
}
}
impl LengthOrPercentageOrAuto {
/// Convert this value in an appropriate `nsStyleCoord::CalcValue`. /// Convert this value in an appropriate `nsStyleCoord::CalcValue`.
pub fn to_calc_value(&self) -> Option<nsStyleCoord_CalcValue> { pub fn to_calc_value(&self) -> Option<nsStyleCoord_CalcValue> {
match *self { match *self {
LengthOrPercentageOrAuto::Length(px) => Some(nsStyleCoord_CalcValue { LengthPercentageOrAuto::LengthPercentage(len) => Some(From::from(len)),
mLength: px.to_i32_au(), LengthPercentageOrAuto::Auto => None,
mPercent: 0.0,
mHasPercent: false,
}),
LengthOrPercentageOrAuto::Percentage(pc) => Some(nsStyleCoord_CalcValue {
mLength: 0,
mPercent: pc.0,
mHasPercent: true,
}),
LengthOrPercentageOrAuto::Calc(calc) => Some(calc.into()),
LengthOrPercentageOrAuto::Auto => None,
} }
} }
} }
impl From<nsStyleCoord_CalcValue> for LengthOrPercentage { impl From<nsStyleCoord_CalcValue> for LengthPercentageOrAuto {
fn from(other: nsStyleCoord_CalcValue) -> LengthOrPercentage { fn from(other: nsStyleCoord_CalcValue) -> LengthPercentageOrAuto {
match (other.mHasPercent, other.mLength) { LengthPercentageOrAuto::LengthPercentage(LengthPercentage::from(other))
(false, _) => LengthOrPercentage::Length(Au(other.mLength).into()),
(true, 0) => LengthOrPercentage::Percentage(Percentage(other.mPercent)),
_ => LengthOrPercentage::Calc(other.into()),
}
}
}
impl From<nsStyleCoord_CalcValue> for LengthOrPercentageOrAuto {
fn from(other: nsStyleCoord_CalcValue) -> LengthOrPercentageOrAuto {
match (other.mHasPercent, other.mLength) {
(false, _) => LengthOrPercentageOrAuto::Length(Au(other.mLength).into()),
(true, 0) => LengthOrPercentageOrAuto::Percentage(Percentage(other.mPercent)),
_ => LengthOrPercentageOrAuto::Calc(other.into()),
}
} }
} }
// FIXME(emilio): A lot of these impl From should probably become explicit or // FIXME(emilio): A lot of these impl From should probably become explicit or
// disappear as we move more stuff to cbindgen. // disappear as we move more stuff to cbindgen.
impl From<nsStyleCoord_CalcValue> for NonNegativeLengthOrPercentageOrAuto { impl From<nsStyleCoord_CalcValue> for NonNegativeLengthPercentageOrAuto {
fn from(other: nsStyleCoord_CalcValue) -> Self { fn from(other: nsStyleCoord_CalcValue) -> Self {
use style_traits::values::specified::AllowedNumericType; NonNegative(LengthPercentageOrAuto::LengthPercentage(
NonNegative(if other.mLength < 0 || other.mPercent < 0. { LengthPercentage::with_clamping_mode(
LengthOrPercentageOrAuto::Calc(CalcLengthOrPercentage::with_clamping_mode(
Au(other.mLength).into(), Au(other.mLength).into(),
if other.mHasPercent { if other.mHasPercent {
Some(Percentage(other.mPercent)) Some(Percentage(other.mPercent))
@ -126,10 +89,9 @@ impl From<nsStyleCoord_CalcValue> for NonNegativeLengthOrPercentageOrAuto {
None None
}, },
AllowedNumericType::NonNegative, AllowedNumericType::NonNegative,
/* was_calc = */ true,
),
)) ))
} else {
other.into()
})
} }
} }
@ -139,24 +101,17 @@ impl From<Angle> for CoordDataValue {
} }
} }
fn line_direction(horizontal: LengthOrPercentage, vertical: LengthOrPercentage) -> LineDirection { fn line_direction(horizontal: LengthPercentage, vertical: LengthPercentage) -> LineDirection {
use crate::values::computed::position::Position; use crate::values::computed::position::Position;
use crate::values::specified::position::{X, Y}; use crate::values::specified::position::{X, Y};
let horizontal_percentage = match horizontal { let horizontal_percentage = horizontal.as_percentage();
LengthOrPercentage::Percentage(percentage) => Some(percentage.0), let vertical_percentage = vertical.as_percentage();
_ => None,
};
let vertical_percentage = match vertical {
LengthOrPercentage::Percentage(percentage) => Some(percentage.0),
_ => None,
};
let horizontal_as_corner = horizontal_percentage.and_then(|percentage| { let horizontal_as_corner = horizontal_percentage.and_then(|percentage| {
if percentage == 0.0 { if percentage.0 == 0.0 {
Some(X::Left) Some(X::Left)
} else if percentage == 1.0 { } else if percentage.0 == 1.0 {
Some(X::Right) Some(X::Right)
} else { } else {
None None
@ -164,9 +119,9 @@ fn line_direction(horizontal: LengthOrPercentage, vertical: LengthOrPercentage)
}); });
let vertical_as_corner = vertical_percentage.and_then(|percentage| { let vertical_as_corner = vertical_percentage.and_then(|percentage| {
if percentage == 0.0 { if percentage.0 == 0.0 {
Some(Y::Top) Some(Y::Top)
} else if percentage == 1.0 { } else if percentage.0 == 1.0 {
Some(Y::Bottom) Some(Y::Bottom)
} else { } else {
None None
@ -178,13 +133,13 @@ fn line_direction(horizontal: LengthOrPercentage, vertical: LengthOrPercentage)
} }
if let Some(hc) = horizontal_as_corner { if let Some(hc) = horizontal_as_corner {
if vertical_percentage == Some(0.5) { if vertical_percentage == Some(Percentage(0.5)) {
return LineDirection::Horizontal(hc); return LineDirection::Horizontal(hc);
} }
} }
if let Some(vc) = vertical_as_corner { if let Some(vc) = vertical_as_corner {
if horizontal_percentage == Some(0.5) { if horizontal_percentage == Some(Percentage(0.5)) {
return LineDirection::Vertical(vc); return LineDirection::Vertical(vc);
} }
} }
@ -512,8 +467,8 @@ impl nsStyleImage {
.as_ref() .as_ref()
.unwrap(); .unwrap();
let angle = Angle::from_gecko_style_coord(&gecko_gradient.mAngle); let angle = Angle::from_gecko_style_coord(&gecko_gradient.mAngle);
let horizontal_style = LengthOrPercentage::from_gecko_style_coord(&gecko_gradient.mBgPosX); let horizontal_style = LengthPercentage::from_gecko_style_coord(&gecko_gradient.mBgPosX);
let vertical_style = LengthOrPercentage::from_gecko_style_coord(&gecko_gradient.mBgPosY); let vertical_style = LengthPercentage::from_gecko_style_coord(&gecko_gradient.mBgPosY);
let kind = match gecko_gradient.mShape as u32 { let kind = match gecko_gradient.mShape as u32 {
structs::NS_STYLE_GRADIENT_SHAPE_LINEAR => { structs::NS_STYLE_GRADIENT_SHAPE_LINEAR => {
@ -574,20 +529,18 @@ impl nsStyleImage {
structs::NS_STYLE_GRADIENT_SHAPE_ELLIPTICAL => { structs::NS_STYLE_GRADIENT_SHAPE_ELLIPTICAL => {
let length_percentage_keyword = match gecko_gradient.mSize as u32 { let length_percentage_keyword = match gecko_gradient.mSize as u32 {
structs::NS_STYLE_GRADIENT_SIZE_EXPLICIT_SIZE => match ( structs::NS_STYLE_GRADIENT_SIZE_EXPLICIT_SIZE => match (
LengthOrPercentage::from_gecko_style_coord( LengthPercentage::from_gecko_style_coord(&gecko_gradient.mRadiusX),
&gecko_gradient.mRadiusX, LengthPercentage::from_gecko_style_coord(&gecko_gradient.mRadiusY),
),
LengthOrPercentage::from_gecko_style_coord(
&gecko_gradient.mRadiusY,
),
) { ) {
(Some(x), Some(y)) => Ellipse::Radii(x, y), (Some(x), Some(y)) => Ellipse::Radii(x, y),
_ => { _ => {
debug_assert!(false, debug_assert!(
"mRadiusX, mRadiusY could not convert to LengthOrPercentage"); false,
"mRadiusX, mRadiusY could not convert to LengthPercentage"
);
Ellipse::Radii( Ellipse::Radii(
LengthOrPercentage::zero(), LengthPercentage::zero(),
LengthOrPercentage::zero(), LengthPercentage::zero(),
) )
}, },
}, },
@ -606,11 +559,11 @@ impl nsStyleImage {
_ => { _ => {
debug_assert!( debug_assert!(
false, false,
"mRadiusX, mRadiusY could not convert to LengthOrPercentage" "mRadiusX, mRadiusY could not convert to LengthPercentage"
); );
Position { Position {
horizontal: LengthOrPercentage::zero(), horizontal: LengthPercentage::zero(),
vertical: LengthOrPercentage::zero(), vertical: LengthPercentage::zero(),
} }
}, },
}; };
@ -625,13 +578,13 @@ impl nsStyleImage {
.map(|ref stop| { .map(|ref stop| {
if stop.mIsInterpolationHint { if stop.mIsInterpolationHint {
GradientItem::InterpolationHint( GradientItem::InterpolationHint(
LengthOrPercentage::from_gecko_style_coord(&stop.mLocation) LengthPercentage::from_gecko_style_coord(&stop.mLocation)
.expect("mLocation could not convert to LengthOrPercentage"), .expect("mLocation could not convert to LengthPercentage"),
) )
} else { } else {
GradientItem::ColorStop(ColorStop { GradientItem::ColorStop(ColorStop {
color: stop.mColor.into(), color: stop.mColor.into(),
position: LengthOrPercentage::from_gecko_style_coord(&stop.mLocation), position: LengthPercentage::from_gecko_style_coord(&stop.mLocation),
}) })
} }
}) })
@ -670,7 +623,7 @@ pub mod basic_shape {
BasicShape, ClippingShape, FloatAreaShape, ShapeRadius, BasicShape, ClippingShape, FloatAreaShape, ShapeRadius,
}; };
use crate::values::computed::border::{BorderCornerRadius, BorderRadius}; use crate::values::computed::border::{BorderCornerRadius, BorderRadius};
use crate::values::computed::length::LengthOrPercentage; use crate::values::computed::length::LengthPercentage;
use crate::values::computed::motion::OffsetPath; use crate::values::computed::motion::OffsetPath;
use crate::values::computed::position; use crate::values::computed::position;
use crate::values::computed::url::ComputedUrl; use crate::values::computed::url::ComputedUrl;
@ -787,10 +740,10 @@ pub mod basic_shape {
fn from(other: &'a StyleBasicShape) -> Self { fn from(other: &'a StyleBasicShape) -> Self {
match other.mType { match other.mType {
StyleBasicShapeType::Inset => { StyleBasicShapeType::Inset => {
let t = LengthOrPercentage::from_gecko_style_coord(&other.mCoordinates[0]); let t = LengthPercentage::from_gecko_style_coord(&other.mCoordinates[0]);
let r = LengthOrPercentage::from_gecko_style_coord(&other.mCoordinates[1]); let r = LengthPercentage::from_gecko_style_coord(&other.mCoordinates[1]);
let b = LengthOrPercentage::from_gecko_style_coord(&other.mCoordinates[2]); let b = LengthPercentage::from_gecko_style_coord(&other.mCoordinates[2]);
let l = LengthOrPercentage::from_gecko_style_coord(&other.mCoordinates[3]); let l = LengthPercentage::from_gecko_style_coord(&other.mCoordinates[3]);
let round: BorderRadius = (&other.mRadius).into(); let round: BorderRadius = (&other.mRadius).into();
let round = if round.all_zero() { None } else { Some(round) }; let round = if round.all_zero() { None } else { Some(round) };
let rect = Rect::new( let rect = Rect::new(
@ -816,12 +769,12 @@ pub mod basic_shape {
let x = 2 * i; let x = 2 * i;
let y = x + 1; let y = x + 1;
coords.push(PolygonCoord( coords.push(PolygonCoord(
LengthOrPercentage::from_gecko_style_coord(&other.mCoordinates[x]) LengthPercentage::from_gecko_style_coord(&other.mCoordinates[x])
.expect( .expect(
"polygon() coordinate should be a length, percentage, \ "polygon() coordinate should be a length, percentage, \
or calc value", or calc value",
), ),
LengthOrPercentage::from_gecko_style_coord(&other.mCoordinates[y]) LengthPercentage::from_gecko_style_coord(&other.mCoordinates[y])
.expect( .expect(
"polygon() coordinate should be a length, percentage, \ "polygon() coordinate should be a length, percentage, \
or calc value", or calc value",
@ -842,13 +795,12 @@ pub mod basic_shape {
let get_corner = |index| { let get_corner = |index| {
BorderCornerRadius::new( BorderCornerRadius::new(
NonNegative( NonNegative(
LengthOrPercentage::from_gecko_style_coord(&other.data_at(index)).expect( LengthPercentage::from_gecko_style_coord(&other.data_at(index)).expect(
"<border-radius> should be a length, percentage, or calc value", "<border-radius> should be a length, percentage, or calc value",
), ),
), ),
NonNegative( NonNegative(
LengthOrPercentage::from_gecko_style_coord(&other.data_at(index + 1)) LengthPercentage::from_gecko_style_coord(&other.data_at(index + 1)).expect(
.expect(
"<border-radius> should be a length, percentage, or calc value", "<border-radius> should be a length, percentage, or calc value",
), ),
), ),
@ -1003,11 +955,11 @@ impl From<Origin> for SheetType {
} }
} }
impl TrackSize<LengthOrPercentage> { impl TrackSize<LengthPercentage> {
/// Return TrackSize from given two nsStyleCoord /// Return TrackSize from given two nsStyleCoord
pub fn from_gecko_style_coords<T: CoordData>(gecko_min: &T, gecko_max: &T) -> Self { pub fn from_gecko_style_coords<T: CoordData>(gecko_min: &T, gecko_max: &T) -> Self {
use crate::gecko_bindings::structs::root::nsStyleUnit; use crate::gecko_bindings::structs::root::nsStyleUnit;
use crate::values::computed::length::LengthOrPercentage; use crate::values::computed::length::LengthPercentage;
use crate::values::generics::grid::{TrackBreadth, TrackSize}; use crate::values::generics::grid::{TrackBreadth, TrackSize};
if gecko_min.unit() == nsStyleUnit::eStyleUnit_None { if gecko_min.unit() == nsStyleUnit::eStyleUnit_None {
@ -1017,8 +969,8 @@ impl TrackSize<LengthOrPercentage> {
gecko_max.unit() == nsStyleUnit::eStyleUnit_Calc gecko_max.unit() == nsStyleUnit::eStyleUnit_Calc
); );
return TrackSize::FitContent( return TrackSize::FitContent(
LengthOrPercentage::from_gecko_style_coord(gecko_max) LengthPercentage::from_gecko_style_coord(gecko_max)
.expect("gecko_max could not convert to LengthOrPercentage"), .expect("gecko_max could not convert to LengthPercentage"),
); );
} }
@ -1058,7 +1010,7 @@ impl TrackSize<LengthOrPercentage> {
} }
} }
impl TrackListValue<LengthOrPercentage, Integer> { impl TrackListValue<LengthPercentage, Integer> {
/// Return TrackSize from given two nsStyleCoord /// Return TrackSize from given two nsStyleCoord
pub fn from_gecko_style_coords<T: CoordData>(gecko_min: &T, gecko_max: &T) -> Self { pub fn from_gecko_style_coords<T: CoordData>(gecko_min: &T, gecko_max: &T) -> Self {
TrackListValue::TrackSize(TrackSize::from_gecko_style_coords(gecko_min, gecko_max)) TrackListValue::TrackSize(TrackSize::from_gecko_style_coords(gecko_min, gecko_max))

View file

@ -13,9 +13,9 @@ use crate::gecko_bindings::sugar::ns_style_coord::{CoordData, CoordDataMut, Coor
use crate::media_queries::Device; use crate::media_queries::Device;
use crate::values::computed::basic_shape::ShapeRadius as ComputedShapeRadius; use crate::values::computed::basic_shape::ShapeRadius as ComputedShapeRadius;
use crate::values::computed::FlexBasis as ComputedFlexBasis; use crate::values::computed::FlexBasis as ComputedFlexBasis;
use crate::values::computed::{Angle, ExtremumLength, Length, LengthOrPercentage}; use crate::values::computed::{Angle, ExtremumLength, Length, LengthPercentage};
use crate::values::computed::{LengthOrPercentageOrAuto, Percentage}; use crate::values::computed::{LengthPercentageOrAuto, Percentage};
use crate::values::computed::{LengthOrPercentageOrNone, Number, NumberOrPercentage}; use crate::values::computed::{LengthPercentageOrNone, Number, NumberOrPercentage};
use crate::values::computed::{MaxLength as ComputedMaxLength, MozLength as ComputedMozLength}; use crate::values::computed::{MaxLength as ComputedMaxLength, MozLength as ComputedMozLength};
use crate::values::generics::basic_shape::ShapeRadius; use crate::values::generics::basic_shape::ShapeRadius;
use crate::values::generics::box_::Perspective; use crate::values::generics::box_::Perspective;
@ -146,21 +146,25 @@ impl GeckoStyleCoordConvertible for NumberOrPercentage {
} }
} }
impl GeckoStyleCoordConvertible for LengthOrPercentage { impl GeckoStyleCoordConvertible for LengthPercentage {
fn to_gecko_style_coord<T: CoordDataMut>(&self, coord: &mut T) { fn to_gecko_style_coord<T: CoordDataMut>(&self, coord: &mut T) {
let value = match *self { if self.was_calc {
LengthOrPercentage::Length(px) => CoordDataValue::Coord(px.to_i32_au()), return coord.set_value(CoordDataValue::Calc((*self).into()));
LengthOrPercentage::Percentage(p) => CoordDataValue::Percent(p.0), }
LengthOrPercentage::Calc(calc) => CoordDataValue::Calc(calc.into()), debug_assert!(self.percentage.is_none() || self.unclamped_length() == Length::zero());
}; if let Some(p) = self.percentage {
coord.set_value(value); return coord.set_value(CoordDataValue::Percent(p.0));
}
coord.set_value(CoordDataValue::Coord(self.unclamped_length().to_i32_au()))
} }
fn from_gecko_style_coord<T: CoordData>(coord: &T) -> Option<Self> { fn from_gecko_style_coord<T: CoordData>(coord: &T) -> Option<Self> {
match coord.as_value() { match coord.as_value() {
CoordDataValue::Coord(coord) => Some(LengthOrPercentage::Length(Au(coord).into())), CoordDataValue::Coord(coord) => Some(LengthPercentage::new(Au(coord).into(), None)),
CoordDataValue::Percent(p) => Some(LengthOrPercentage::Percentage(Percentage(p))), CoordDataValue::Percent(p) => {
CoordDataValue::Calc(calc) => Some(LengthOrPercentage::Calc(calc.into())), Some(LengthPercentage::new(Au(0).into(), Some(Percentage(p))))
},
CoordDataValue::Calc(calc) => Some(calc.into()),
_ => None, _ => None,
} }
} }
@ -179,50 +183,36 @@ impl GeckoStyleCoordConvertible for Length {
} }
} }
impl GeckoStyleCoordConvertible for LengthOrPercentageOrAuto { impl GeckoStyleCoordConvertible for LengthPercentageOrAuto {
fn to_gecko_style_coord<T: CoordDataMut>(&self, coord: &mut T) { fn to_gecko_style_coord<T: CoordDataMut>(&self, coord: &mut T) {
let value = match *self { match *self {
LengthOrPercentageOrAuto::Length(px) => CoordDataValue::Coord(px.to_i32_au()), LengthPercentageOrAuto::Auto => coord.set_value(CoordDataValue::Auto),
LengthOrPercentageOrAuto::Percentage(p) => CoordDataValue::Percent(p.0), LengthPercentageOrAuto::LengthPercentage(ref lp) => lp.to_gecko_style_coord(coord),
LengthOrPercentageOrAuto::Auto => CoordDataValue::Auto, }
LengthOrPercentageOrAuto::Calc(calc) => CoordDataValue::Calc(calc.into()),
};
coord.set_value(value);
} }
fn from_gecko_style_coord<T: CoordData>(coord: &T) -> Option<Self> { fn from_gecko_style_coord<T: CoordData>(coord: &T) -> Option<Self> {
match coord.as_value() { match coord.as_value() {
CoordDataValue::Coord(coord) => { CoordDataValue::Auto => Some(LengthPercentageOrAuto::Auto),
Some(LengthOrPercentageOrAuto::Length(Au(coord).into())) _ => LengthPercentage::from_gecko_style_coord(coord)
}, .map(LengthPercentageOrAuto::LengthPercentage),
CoordDataValue::Percent(p) => Some(LengthOrPercentageOrAuto::Percentage(Percentage(p))),
CoordDataValue::Auto => Some(LengthOrPercentageOrAuto::Auto),
CoordDataValue::Calc(calc) => Some(LengthOrPercentageOrAuto::Calc(calc.into())),
_ => None,
} }
} }
} }
impl GeckoStyleCoordConvertible for LengthOrPercentageOrNone { impl GeckoStyleCoordConvertible for LengthPercentageOrNone {
fn to_gecko_style_coord<T: CoordDataMut>(&self, coord: &mut T) { fn to_gecko_style_coord<T: CoordDataMut>(&self, coord: &mut T) {
let value = match *self { match *self {
LengthOrPercentageOrNone::Length(px) => CoordDataValue::Coord(px.to_i32_au()), LengthPercentageOrNone::None => coord.set_value(CoordDataValue::None),
LengthOrPercentageOrNone::Percentage(p) => CoordDataValue::Percent(p.0), LengthPercentageOrNone::LengthPercentage(ref lp) => lp.to_gecko_style_coord(coord),
LengthOrPercentageOrNone::None => CoordDataValue::None, }
LengthOrPercentageOrNone::Calc(calc) => CoordDataValue::Calc(calc.into()),
};
coord.set_value(value);
} }
fn from_gecko_style_coord<T: CoordData>(coord: &T) -> Option<Self> { fn from_gecko_style_coord<T: CoordData>(coord: &T) -> Option<Self> {
match coord.as_value() { match coord.as_value() {
CoordDataValue::Coord(coord) => { CoordDataValue::None => Some(LengthPercentageOrNone::None),
Some(LengthOrPercentageOrNone::Length(Au(coord).into())) _ => LengthPercentage::from_gecko_style_coord(coord)
}, .map(LengthPercentageOrNone::LengthPercentage),
CoordDataValue::Percent(p) => Some(LengthOrPercentageOrNone::Percentage(Percentage(p))),
CoordDataValue::None => Some(LengthOrPercentageOrNone::None),
CoordDataValue::Calc(calc) => Some(LengthOrPercentageOrNone::Calc(calc.into())),
_ => None,
} }
} }
} }
@ -230,7 +220,7 @@ impl GeckoStyleCoordConvertible for LengthOrPercentageOrNone {
impl<L: GeckoStyleCoordConvertible> GeckoStyleCoordConvertible for TrackBreadth<L> { impl<L: GeckoStyleCoordConvertible> GeckoStyleCoordConvertible for TrackBreadth<L> {
fn to_gecko_style_coord<T: CoordDataMut>(&self, coord: &mut T) { fn to_gecko_style_coord<T: CoordDataMut>(&self, coord: &mut T) {
match *self { match *self {
TrackBreadth::Breadth(ref lop) => lop.to_gecko_style_coord(coord), TrackBreadth::Breadth(ref lp) => lp.to_gecko_style_coord(coord),
TrackBreadth::Fr(fr) => coord.set_value(CoordDataValue::FlexFraction(fr)), TrackBreadth::Fr(fr) => coord.set_value(CoordDataValue::FlexFraction(fr)),
TrackBreadth::Keyword(TrackKeyword::Auto) => coord.set_value(CoordDataValue::Auto), TrackBreadth::Keyword(TrackKeyword::Auto) => coord.set_value(CoordDataValue::Auto),
TrackBreadth::Keyword(TrackKeyword::MinContent) => coord.set_value( TrackBreadth::Keyword(TrackKeyword::MinContent) => coord.set_value(
@ -271,7 +261,7 @@ impl GeckoStyleCoordConvertible for ComputedShapeRadius {
ShapeRadius::FarthestSide => coord.set_value(CoordDataValue::Enumerated( ShapeRadius::FarthestSide => coord.set_value(CoordDataValue::Enumerated(
StyleShapeRadius::FarthestSide as u32, StyleShapeRadius::FarthestSide as u32,
)), )),
ShapeRadius::Length(lop) => lop.to_gecko_style_coord(coord), ShapeRadius::Length(lp) => lp.to_gecko_style_coord(coord),
} }
} }
@ -377,14 +367,14 @@ impl GeckoStyleCoordConvertible for ExtremumLength {
impl GeckoStyleCoordConvertible for ComputedMozLength { impl GeckoStyleCoordConvertible for ComputedMozLength {
fn to_gecko_style_coord<T: CoordDataMut>(&self, coord: &mut T) { fn to_gecko_style_coord<T: CoordDataMut>(&self, coord: &mut T) {
match *self { match *self {
MozLength::LengthOrPercentageOrAuto(ref lopoa) => lopoa.to_gecko_style_coord(coord), MozLength::LengthPercentageOrAuto(ref lpoa) => lpoa.to_gecko_style_coord(coord),
MozLength::ExtremumLength(ref e) => e.to_gecko_style_coord(coord), MozLength::ExtremumLength(ref e) => e.to_gecko_style_coord(coord),
} }
} }
fn from_gecko_style_coord<T: CoordData>(coord: &T) -> Option<Self> { fn from_gecko_style_coord<T: CoordData>(coord: &T) -> Option<Self> {
LengthOrPercentageOrAuto::from_gecko_style_coord(coord) LengthPercentageOrAuto::from_gecko_style_coord(coord)
.map(MozLength::LengthOrPercentageOrAuto) .map(MozLength::LengthPercentageOrAuto)
.or_else(|| { .or_else(|| {
ExtremumLength::from_gecko_style_coord(coord).map(MozLength::ExtremumLength) ExtremumLength::from_gecko_style_coord(coord).map(MozLength::ExtremumLength)
}) })
@ -394,21 +384,21 @@ impl GeckoStyleCoordConvertible for ComputedMozLength {
impl GeckoStyleCoordConvertible for ComputedMaxLength { impl GeckoStyleCoordConvertible for ComputedMaxLength {
fn to_gecko_style_coord<T: CoordDataMut>(&self, coord: &mut T) { fn to_gecko_style_coord<T: CoordDataMut>(&self, coord: &mut T) {
match *self { match *self {
MaxLength::LengthOrPercentageOrNone(ref lopon) => lopon.to_gecko_style_coord(coord), MaxLength::LengthPercentageOrNone(ref lpon) => lpon.to_gecko_style_coord(coord),
MaxLength::ExtremumLength(ref e) => e.to_gecko_style_coord(coord), MaxLength::ExtremumLength(ref e) => e.to_gecko_style_coord(coord),
} }
} }
fn from_gecko_style_coord<T: CoordData>(coord: &T) -> Option<Self> { fn from_gecko_style_coord<T: CoordData>(coord: &T) -> Option<Self> {
LengthOrPercentageOrNone::from_gecko_style_coord(coord) LengthPercentageOrNone::from_gecko_style_coord(coord)
.map(MaxLength::LengthOrPercentageOrNone) .map(MaxLength::LengthPercentageOrNone)
.or_else(|| { .or_else(|| {
ExtremumLength::from_gecko_style_coord(coord).map(MaxLength::ExtremumLength) ExtremumLength::from_gecko_style_coord(coord).map(MaxLength::ExtremumLength)
}) })
} }
} }
impl GeckoStyleCoordConvertible for ScrollSnapPoint<LengthOrPercentage> { impl GeckoStyleCoordConvertible for ScrollSnapPoint<LengthPercentage> {
fn to_gecko_style_coord<T: CoordDataMut>(&self, coord: &mut T) { fn to_gecko_style_coord<T: CoordDataMut>(&self, coord: &mut T) {
match self.repeated() { match self.repeated() {
None => coord.set_value(CoordDataValue::None), None => coord.set_value(CoordDataValue::None),
@ -423,8 +413,8 @@ impl GeckoStyleCoordConvertible for ScrollSnapPoint<LengthOrPercentage> {
Some(match coord.unit() { Some(match coord.unit() {
nsStyleUnit::eStyleUnit_None => ScrollSnapPoint::None, nsStyleUnit::eStyleUnit_None => ScrollSnapPoint::None,
_ => ScrollSnapPoint::Repeat( _ => ScrollSnapPoint::Repeat(
LengthOrPercentage::from_gecko_style_coord(coord) LengthPercentage::from_gecko_style_coord(coord)
.expect("coord could not convert to LengthOrPercentage"), .expect("coord could not convert to LengthPercentage"),
), ),
}) })
} }

View file

@ -9,7 +9,7 @@ use crate::gecko_bindings::structs;
use crate::gecko_bindings::structs::{nsCSSUnit, nsCSSValue}; use crate::gecko_bindings::structs::{nsCSSUnit, nsCSSValue};
use crate::gecko_bindings::structs::{nsCSSValueList, nsCSSValue_Array}; use crate::gecko_bindings::structs::{nsCSSValueList, nsCSSValue_Array};
use crate::gecko_string_cache::Atom; use crate::gecko_string_cache::Atom;
use crate::values::computed::{Angle, Length, LengthOrPercentage, Percentage}; use crate::values::computed::{Angle, Length, LengthPercentage, Percentage};
use std::marker::PhantomData; use std::marker::PhantomData;
use std::mem; use std::mem;
use std::ops::{Index, IndexMut}; use std::ops::{Index, IndexMut};
@ -67,13 +67,16 @@ impl nsCSSValue {
&*array &*array
} }
/// Sets LengthOrPercentage value to this nsCSSValue. /// Sets LengthPercentage value to this nsCSSValue.
pub unsafe fn set_lop(&mut self, lop: LengthOrPercentage) { pub unsafe fn set_length_percentage(&mut self, lp: LengthPercentage) {
match lop { if lp.was_calc {
LengthOrPercentage::Length(px) => self.set_px(px.px()), return bindings::Gecko_CSSValue_SetCalc(self, lp.into());
LengthOrPercentage::Percentage(pc) => self.set_percentage(pc.0),
LengthOrPercentage::Calc(calc) => bindings::Gecko_CSSValue_SetCalc(self, calc.into()),
} }
debug_assert!(lp.percentage.is_none() || lp.unclamped_length() == Length::zero());
if let Some(p) = lp.percentage {
return self.set_percentage(p.0);
}
self.set_px(lp.unclamped_length().px());
} }
/// Sets a px value to this nsCSSValue. /// Sets a px value to this nsCSSValue.
@ -86,18 +89,16 @@ impl nsCSSValue {
bindings::Gecko_CSSValue_SetPercentage(self, unit_value) bindings::Gecko_CSSValue_SetPercentage(self, unit_value)
} }
/// Returns LengthOrPercentage value. /// Returns LengthPercentage value.
pub unsafe fn get_lop(&self) -> LengthOrPercentage { pub unsafe fn get_length_percentage(&self) -> LengthPercentage {
match self.mUnit { match self.mUnit {
nsCSSUnit::eCSSUnit_Pixel => { nsCSSUnit::eCSSUnit_Pixel => {
LengthOrPercentage::Length(Length::new(bindings::Gecko_CSSValue_GetNumber(self))) LengthPercentage::new(Length::new(bindings::Gecko_CSSValue_GetNumber(self)), None)
}, },
nsCSSUnit::eCSSUnit_Percent => LengthOrPercentage::Percentage(Percentage( nsCSSUnit::eCSSUnit_Percent => LengthPercentage::new_percent(Percentage(
bindings::Gecko_CSSValue_GetPercentage(self), bindings::Gecko_CSSValue_GetPercentage(self),
)), )),
nsCSSUnit::eCSSUnit_Calc => { nsCSSUnit::eCSSUnit_Calc => bindings::Gecko_CSSValue_GetCalc(self).into(),
LengthOrPercentage::Calc(bindings::Gecko_CSSValue_GetCalc(self).into())
},
_ => panic!("Unexpected unit"), _ => panic!("Unexpected unit"),
} }
} }

View file

@ -510,7 +510,7 @@ def set_gecko_property(ffi_name, expr):
// set on mContextFlags, and the length field is set to the initial value. // set on mContextFlags, and the length field is set to the initial value.
pub fn set_${ident}(&mut self, v: longhands::${ident}::computed_value::T) { pub fn set_${ident}(&mut self, v: longhands::${ident}::computed_value::T) {
use crate::values::generics::svg::{SVGLength, SvgLengthOrPercentageOrNumber}; use crate::values::generics::svg::{SVGLength, SvgLengthPercentageOrNumber};
use crate::gecko_bindings::structs::nsStyleSVG_${ident.upper()}_CONTEXT as CONTEXT_VALUE; use crate::gecko_bindings::structs::nsStyleSVG_${ident.upper()}_CONTEXT as CONTEXT_VALUE;
let length = match v { let length = match v {
SVGLength::Length(length) => { SVGLength::Length(length) => {
@ -526,9 +526,9 @@ def set_gecko_property(ffi_name, expr):
} }
}; };
match length { match length {
SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop) => SvgLengthPercentageOrNumber::LengthPercentage(lp) =>
self.gecko.${gecko_ffi_name}.set(lop), self.gecko.${gecko_ffi_name}.set(lp),
SvgLengthOrPercentageOrNumber::Number(num) => SvgLengthPercentageOrNumber::Number(num) =>
self.gecko.${gecko_ffi_name}.set_value(CoordDataValue::Factor(num.into())), self.gecko.${gecko_ffi_name}.set_value(CoordDataValue::Factor(num.into())),
} }
} }
@ -546,30 +546,28 @@ def set_gecko_property(ffi_name, expr):
} }
pub fn clone_${ident}(&self) -> longhands::${ident}::computed_value::T { pub fn clone_${ident}(&self) -> longhands::${ident}::computed_value::T {
use crate::values::generics::svg::{SVGLength, SvgLengthOrPercentageOrNumber}; use crate::values::generics::svg::{SVGLength, SvgLengthPercentageOrNumber};
use crate::values::computed::LengthOrPercentage; use crate::values::computed::LengthPercentage;
use crate::gecko_bindings::structs::nsStyleSVG_${ident.upper()}_CONTEXT as CONTEXT_VALUE; use crate::gecko_bindings::structs::nsStyleSVG_${ident.upper()}_CONTEXT as CONTEXT_VALUE;
if (self.gecko.mContextFlags & CONTEXT_VALUE) != 0 { if (self.gecko.mContextFlags & CONTEXT_VALUE) != 0 {
return SVGLength::ContextValue; return SVGLength::ContextValue;
} }
let length = match self.gecko.${gecko_ffi_name}.as_value() { let length = match self.gecko.${gecko_ffi_name}.as_value() {
CoordDataValue::Factor(number) => { CoordDataValue::Factor(number) => {
SvgLengthOrPercentageOrNumber::Number(number) SvgLengthPercentageOrNumber::Number(number)
}, },
CoordDataValue::Coord(coord) => { CoordDataValue::Coord(coord) => {
SvgLengthOrPercentageOrNumber::LengthOrPercentage( SvgLengthPercentageOrNumber::LengthPercentage(
LengthOrPercentage::Length(Au(coord).into()) LengthPercentage::new(Au(coord).into(), None)
) )
}, },
CoordDataValue::Percent(p) => { CoordDataValue::Percent(p) => {
SvgLengthOrPercentageOrNumber::LengthOrPercentage( SvgLengthPercentageOrNumber::LengthPercentage(
LengthOrPercentage::Percentage(Percentage(p)) LengthPercentage::new(Au(0).into(), Some(Percentage(p)))
) )
}, },
CoordDataValue::Calc(calc) => { CoordDataValue::Calc(calc) => {
SvgLengthOrPercentageOrNumber::LengthOrPercentage( SvgLengthPercentageOrNumber::LengthPercentage(calc.into())
LengthOrPercentage::Calc(calc.into())
)
}, },
_ => unreachable!("Unexpected coordinate in ${ident}"), _ => unreachable!("Unexpected coordinate in ${ident}"),
}; };
@ -941,10 +939,10 @@ def set_gecko_property(ffi_name, expr):
transform_functions = [ transform_functions = [
("Matrix3D", "matrix3d", ["number"] * 16), ("Matrix3D", "matrix3d", ["number"] * 16),
("Matrix", "matrix", ["number"] * 6), ("Matrix", "matrix", ["number"] * 6),
("Translate", "translate", ["lop", "optional_lop"]), ("Translate", "translate", ["lp", "optional_lp"]),
("Translate3D", "translate3d", ["lop", "lop", "length"]), ("Translate3D", "translate3d", ["lp", "lp", "length"]),
("TranslateX", "translatex", ["lop"]), ("TranslateX", "translatex", ["lp"]),
("TranslateY", "translatey", ["lop"]), ("TranslateY", "translatey", ["lp"]),
("TranslateZ", "translatez", ["length"]), ("TranslateZ", "translatez", ["length"]),
("Scale3D", "scale3d", ["number"] * 3), ("Scale3D", "scale3d", ["number"] * 3),
("Scale", "scale", ["number", "optional_number"]), ("Scale", "scale", ["number", "optional_number"]),
@ -995,7 +993,7 @@ transform_functions = [
# Note: This is an integer type, but we use it as a percentage value in Gecko, so # Note: This is an integer type, but we use it as a percentage value in Gecko, so
# need to cast it to f32. # need to cast it to f32.
"integer_to_percentage" : "bindings::Gecko_CSSValue_SetPercentage(%s, %s as f32)", "integer_to_percentage" : "bindings::Gecko_CSSValue_SetPercentage(%s, %s as f32)",
"lop" : "%s.set_lop(%s)", "lp" : "%s.set_length_percentage(%s)",
"angle" : "%s.set_angle(%s)", "angle" : "%s.set_angle(%s)",
"number" : "bindings::Gecko_CSSValue_SetNumber(%s, %s)", "number" : "bindings::Gecko_CSSValue_SetNumber(%s, %s)",
# Note: We use nsCSSValueSharedList here, instead of nsCSSValueList_heap # Note: We use nsCSSValueSharedList here, instead of nsCSSValueList_heap
@ -1044,8 +1042,8 @@ transform_functions = [
# %s is substituted with the call to GetArrayItem. # %s is substituted with the call to GetArrayItem.
css_value_getters = { css_value_getters = {
"length" : "Length::new(bindings::Gecko_CSSValue_GetNumber(%s))", "length" : "Length::new(bindings::Gecko_CSSValue_GetNumber(%s))",
"lop" : "%s.get_lop()", "lp" : "%s.get_length_percentage()",
"lopon" : "Either::Second(%s.get_lop())", "lpon" : "Either::Second(%s.get_length_percentage())",
"lon" : "Either::First(%s.get_length())", "lon" : "Either::First(%s.get_length())",
"angle" : "%s.get_angle()", "angle" : "%s.get_angle()",
"number" : "bindings::Gecko_CSSValue_GetNumber(%s)", "number" : "bindings::Gecko_CSSValue_GetNumber(%s)",
@ -1271,12 +1269,12 @@ pub fn clone_transform_from_list(
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub fn clone_${ident}(&self) -> values::computed::TransformOrigin { pub fn clone_${ident}(&self) -> values::computed::TransformOrigin {
use crate::values::computed::{Length, LengthOrPercentage, TransformOrigin}; use crate::values::computed::{Length, LengthPercentage, TransformOrigin};
TransformOrigin { TransformOrigin {
horizontal: LengthOrPercentage::from_gecko_style_coord(&self.gecko.${gecko_ffi_name}[0]) horizontal: LengthPercentage::from_gecko_style_coord(&self.gecko.${gecko_ffi_name}[0])
.expect("clone for LengthOrPercentage failed"), .expect("clone for LengthPercentage failed"),
vertical: LengthOrPercentage::from_gecko_style_coord(&self.gecko.${gecko_ffi_name}[1]) vertical: LengthPercentage::from_gecko_style_coord(&self.gecko.${gecko_ffi_name}[1])
.expect("clone for LengthOrPercentage failed"), .expect("clone for LengthPercentage failed"),
depth: if let Some(third) = self.gecko.${gecko_ffi_name}.get(2) { depth: if let Some(third) = self.gecko.${gecko_ffi_name}.get(2) {
Length::from_gecko_style_coord(third) Length::from_gecko_style_coord(third)
.expect("clone for Length failed") .expect("clone for Length failed")
@ -1404,19 +1402,19 @@ impl Clone for ${style_struct.gecko_struct_name} {
"length::LengthOrAuto": impl_style_coord, "length::LengthOrAuto": impl_style_coord,
"length::LengthOrNormal": impl_style_coord, "length::LengthOrNormal": impl_style_coord,
"length::NonNegativeLengthOrAuto": impl_style_coord, "length::NonNegativeLengthOrAuto": impl_style_coord,
"length::NonNegativeLengthOrPercentageOrNormal": impl_style_coord, "length::NonNegativeLengthPercentageOrNormal": impl_style_coord,
"FillRule": impl_simple, "FillRule": impl_simple,
"FlexBasis": impl_style_coord, "FlexBasis": impl_style_coord,
"Length": impl_absolute_length, "Length": impl_absolute_length,
"LengthOrNormal": impl_style_coord, "LengthOrNormal": impl_style_coord,
"LengthOrPercentage": impl_style_coord, "LengthPercentage": impl_style_coord,
"LengthOrPercentageOrAuto": impl_style_coord, "LengthPercentageOrAuto": impl_style_coord,
"LengthOrPercentageOrNone": impl_style_coord, "LengthPercentageOrNone": impl_style_coord,
"MaxLength": impl_style_coord, "MaxLength": impl_style_coord,
"MozLength": impl_style_coord, "MozLength": impl_style_coord,
"MozScriptMinSize": impl_absolute_length, "MozScriptMinSize": impl_absolute_length,
"MozScriptSizeMultiplier": impl_simple, "MozScriptSizeMultiplier": impl_simple,
"NonNegativeLengthOrPercentage": impl_style_coord, "NonNegativeLengthPercentage": impl_style_coord,
"NonNegativeNumber": impl_simple, "NonNegativeNumber": impl_simple,
"Number": impl_simple, "Number": impl_simple,
"Opacity": impl_simple, "Opacity": impl_simple,
@ -3086,7 +3084,7 @@ fn static_assert() {
} }
pub fn clone_vertical_align(&self) -> longhands::vertical_align::computed_value::T { pub fn clone_vertical_align(&self) -> longhands::vertical_align::computed_value::T {
use crate::values::computed::LengthOrPercentage; use crate::values::computed::LengthPercentage;
use crate::values::generics::box_::VerticalAlign; use crate::values::generics::box_::VerticalAlign;
let gecko = &self.gecko.mVerticalAlign; let gecko = &self.gecko.mVerticalAlign;
@ -3094,7 +3092,7 @@ fn static_assert() {
CoordDataValue::Enumerated(value) => VerticalAlign::from_gecko_keyword(value), CoordDataValue::Enumerated(value) => VerticalAlign::from_gecko_keyword(value),
_ => { _ => {
VerticalAlign::Length( VerticalAlign::Length(
LengthOrPercentage::from_gecko_style_coord(gecko).expect( LengthPercentage::from_gecko_style_coord(gecko).expect(
"expected <length-percentage> for vertical-align", "expected <length-percentage> for vertical-align",
), ),
) )
@ -3388,11 +3386,11 @@ fn static_assert() {
pub fn clone_perspective_origin(&self) -> longhands::perspective_origin::computed_value::T { pub fn clone_perspective_origin(&self) -> longhands::perspective_origin::computed_value::T {
use crate::properties::longhands::perspective_origin::computed_value::T; use crate::properties::longhands::perspective_origin::computed_value::T;
use crate::values::computed::LengthOrPercentage; use crate::values::computed::LengthPercentage;
T { T {
horizontal: LengthOrPercentage::from_gecko_style_coord(&self.gecko.mPerspectiveOrigin[0]) horizontal: LengthPercentage::from_gecko_style_coord(&self.gecko.mPerspectiveOrigin[0])
.expect("Expected length or percentage for horizontal value of perspective-origin"), .expect("Expected length or percentage for horizontal value of perspective-origin"),
vertical: LengthOrPercentage::from_gecko_style_coord(&self.gecko.mPerspectiveOrigin[1]) vertical: LengthPercentage::from_gecko_style_coord(&self.gecko.mPerspectiveOrigin[1])
.expect("Expected length or percentage for vertical value of perspective-origin"), .expect("Expected length or percentage for vertical value of perspective-origin"),
} }
} }
@ -3881,12 +3879,12 @@ fn static_assert() {
pub fn clone_${shorthand}_size(&self) -> longhands::${shorthand}_size::computed_value::T { pub fn clone_${shorthand}_size(&self) -> longhands::${shorthand}_size::computed_value::T {
use crate::gecko_bindings::structs::nsStyleCoord_CalcValue as CalcValue; use crate::gecko_bindings::structs::nsStyleCoord_CalcValue as CalcValue;
use crate::gecko_bindings::structs::nsStyleImageLayers_Size_DimensionType as DimensionType; use crate::gecko_bindings::structs::nsStyleImageLayers_Size_DimensionType as DimensionType;
use crate::values::computed::NonNegativeLengthOrPercentageOrAuto; use crate::values::computed::NonNegativeLengthPercentageOrAuto;
use crate::values::generics::background::BackgroundSize; use crate::values::generics::background::BackgroundSize;
fn to_servo(value: CalcValue, ty: u8) -> NonNegativeLengthOrPercentageOrAuto { fn to_servo(value: CalcValue, ty: u8) -> NonNegativeLengthPercentageOrAuto {
if ty == DimensionType::eAuto as u8 { if ty == DimensionType::eAuto as u8 {
NonNegativeLengthOrPercentageOrAuto::auto() NonNegativeLengthPercentageOrAuto::auto()
} else { } else {
debug_assert_eq!(ty, DimensionType::eLengthPercentage as u8); debug_assert_eq!(ty, DimensionType::eLengthPercentage as u8);
value.into() value.into()
@ -4570,14 +4568,14 @@ fn static_assert() {
pub fn set_word_spacing(&mut self, v: longhands::word_spacing::computed_value::T) { pub fn set_word_spacing(&mut self, v: longhands::word_spacing::computed_value::T) {
use crate::values::generics::text::Spacing; use crate::values::generics::text::Spacing;
match v { match v {
Spacing::Value(lop) => self.gecko.mWordSpacing.set(lop), Spacing::Value(lp) => self.gecko.mWordSpacing.set(lp),
// https://drafts.csswg.org/css-text-3/#valdef-word-spacing-normal // https://drafts.csswg.org/css-text-3/#valdef-word-spacing-normal
Spacing::Normal => self.gecko.mWordSpacing.set_value(CoordDataValue::Coord(0)), Spacing::Normal => self.gecko.mWordSpacing.set_value(CoordDataValue::Coord(0)),
} }
} }
pub fn clone_word_spacing(&self) -> longhands::word_spacing::computed_value::T { pub fn clone_word_spacing(&self) -> longhands::word_spacing::computed_value::T {
use crate::values::computed::LengthOrPercentage; use crate::values::computed::LengthPercentage;
use crate::values::generics::text::Spacing; use crate::values::generics::text::Spacing;
debug_assert!( debug_assert!(
matches!(self.gecko.mWordSpacing.as_value(), matches!(self.gecko.mWordSpacing.as_value(),
@ -4586,7 +4584,7 @@ fn static_assert() {
CoordDataValue::Percent(_) | CoordDataValue::Percent(_) |
CoordDataValue::Calc(_)), CoordDataValue::Calc(_)),
"Unexpected computed value for word-spacing"); "Unexpected computed value for word-spacing");
LengthOrPercentage::from_gecko_style_coord(&self.gecko.mWordSpacing).map_or(Spacing::Normal, Spacing::Value) LengthPercentage::from_gecko_style_coord(&self.gecko.mWordSpacing).map_or(Spacing::Normal, Spacing::Value)
} }
<%call expr="impl_coord_copy('word_spacing', 'mWordSpacing')"></%call> <%call expr="impl_coord_copy('word_spacing', 'mWordSpacing')"></%call>
@ -5018,7 +5016,7 @@ clip-path
pub fn set_stroke_dasharray(&mut self, v: longhands::stroke_dasharray::computed_value::T) { pub fn set_stroke_dasharray(&mut self, v: longhands::stroke_dasharray::computed_value::T) {
use crate::gecko_bindings::structs::nsStyleSVG_STROKE_DASHARRAY_CONTEXT as CONTEXT_VALUE; use crate::gecko_bindings::structs::nsStyleSVG_STROKE_DASHARRAY_CONTEXT as CONTEXT_VALUE;
use crate::values::generics::svg::{SVGStrokeDashArray, SvgLengthOrPercentageOrNumber}; use crate::values::generics::svg::{SVGStrokeDashArray, SvgLengthPercentageOrNumber};
match v { match v {
SVGStrokeDashArray::Values(v) => { SVGStrokeDashArray::Values(v) => {
@ -5029,9 +5027,9 @@ clip-path
} }
for (gecko, servo) in self.gecko.mStrokeDasharray.iter_mut().zip(v) { for (gecko, servo) in self.gecko.mStrokeDasharray.iter_mut().zip(v) {
match servo { match servo {
SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop) => SvgLengthPercentageOrNumber::LengthPercentage(lp) =>
gecko.set(lop), gecko.set(lp),
SvgLengthOrPercentageOrNumber::Number(num) => SvgLengthPercentageOrNumber::Number(num) =>
gecko.set_value(CoordDataValue::Factor(num.into())), gecko.set_value(CoordDataValue::Factor(num.into())),
} }
} }
@ -5061,8 +5059,9 @@ clip-path
pub fn clone_stroke_dasharray(&self) -> longhands::stroke_dasharray::computed_value::T { pub fn clone_stroke_dasharray(&self) -> longhands::stroke_dasharray::computed_value::T {
use crate::gecko_bindings::structs::nsStyleSVG_STROKE_DASHARRAY_CONTEXT as CONTEXT_VALUE; use crate::gecko_bindings::structs::nsStyleSVG_STROKE_DASHARRAY_CONTEXT as CONTEXT_VALUE;
use crate::values::computed::LengthOrPercentage; use crate::values::computed::LengthPercentage;
use crate::values::generics::svg::{SVGStrokeDashArray, SvgLengthOrPercentageOrNumber}; use crate::values::generics::NonNegative;
use crate::values::generics::svg::{SVGStrokeDashArray, SvgLengthPercentageOrNumber};
if self.gecko.mContextFlags & CONTEXT_VALUE != 0 { if self.gecko.mContextFlags & CONTEXT_VALUE != 0 {
debug_assert_eq!(self.gecko.mStrokeDasharray.len(), 0); debug_assert_eq!(self.gecko.mStrokeDasharray.len(), 0);
@ -5072,16 +5071,16 @@ clip-path
for gecko in self.gecko.mStrokeDasharray.iter() { for gecko in self.gecko.mStrokeDasharray.iter() {
match gecko.as_value() { match gecko.as_value() {
CoordDataValue::Factor(number) => CoordDataValue::Factor(number) =>
vec.push(SvgLengthOrPercentageOrNumber::Number(number.into())), vec.push(SvgLengthPercentageOrNumber::Number(number.into())),
CoordDataValue::Coord(coord) => CoordDataValue::Coord(coord) =>
vec.push(SvgLengthOrPercentageOrNumber::LengthOrPercentage( vec.push(SvgLengthPercentageOrNumber::LengthPercentage(
LengthOrPercentage::Length(Au(coord).into()).into())), NonNegative(LengthPercentage::new(Au(coord).into(), None).into()))),
CoordDataValue::Percent(p) => CoordDataValue::Percent(p) =>
vec.push(SvgLengthOrPercentageOrNumber::LengthOrPercentage( vec.push(SvgLengthPercentageOrNumber::LengthPercentage(
LengthOrPercentage::Percentage(Percentage(p)).into())), NonNegative(LengthPercentage::new_percent(Percentage(p)).into()))),
CoordDataValue::Calc(calc) => CoordDataValue::Calc(calc) =>
vec.push(SvgLengthOrPercentageOrNumber::LengthOrPercentage( vec.push(SvgLengthPercentageOrNumber::LengthPercentage(
LengthOrPercentage::Calc(calc.into()).into())), NonNegative(LengthPercentage::from(calc).clamp_to_non_negative()))),
_ => unreachable!(), _ => unreachable!(),
} }
} }

View file

@ -35,7 +35,7 @@ ${helpers.predefined_type(
${helpers.predefined_type( ${helpers.predefined_type(
"background-position-" + axis, "background-position-" + axis,
"position::" + direction + "Position", "position::" + direction + "Position",
initial_value="computed::LengthOrPercentage::zero()", initial_value="computed::LengthPercentage::zero()",
initial_specified_value="SpecifiedValue::initial_specified_value()", initial_specified_value="SpecifiedValue::initial_specified_value()",
spec="https://drafts.csswg.org/css-backgrounds-4/#propdef-background-position-" + axis, spec="https://drafts.csswg.org/css-backgrounds-4/#propdef-background-position-" + axis,
animation_value_type="ComputedValue", animation_value_type="ComputedValue",

View file

@ -69,7 +69,7 @@ ${helpers.gecko_keyword_conversion(
type="crate::values::specified::BorderStyle", type="crate::values::specified::BorderStyle",
)} )}
// FIXME(#4126): when gfx supports painting it, make this Size2D<LengthOrPercentage> // FIXME(#4126): when gfx supports painting it, make this Size2D<LengthPercentage>
% for corner in ["top-left", "top-right", "bottom-right", "bottom-left"]: % for corner in ["top-left", "top-right", "bottom-right", "bottom-left"]:
${helpers.predefined_type( ${helpers.predefined_type(
"border-" + corner + "-radius", "border-" + corner + "-radius",
@ -189,7 +189,7 @@ impl crate::values::computed::BorderImageWidth {
use crate::gecko_bindings::structs::nsStyleUnit::{eStyleUnit_Factor, eStyleUnit_Auto}; use crate::gecko_bindings::structs::nsStyleUnit::{eStyleUnit_Factor, eStyleUnit_Auto};
use crate::gecko_bindings::sugar::ns_style_coord::CoordData; use crate::gecko_bindings::sugar::ns_style_coord::CoordData;
use crate::gecko::values::GeckoStyleCoordConvertible; use crate::gecko::values::GeckoStyleCoordConvertible;
use crate::values::computed::{LengthOrPercentage, Number}; use crate::values::computed::{LengthPercentage, Number};
use crate::values::generics::border::BorderImageSideWidth; use crate::values::generics::border::BorderImageSideWidth;
use crate::values::generics::NonNegative; use crate::values::generics::NonNegative;
@ -207,8 +207,8 @@ impl crate::values::computed::BorderImageWidth {
}, },
_ => { _ => {
BorderImageSideWidth::Length( BorderImageSideWidth::Length(
NonNegative(LengthOrPercentage::from_gecko_style_coord(&sides.data_at(${i})) NonNegative(LengthPercentage::from_gecko_style_coord(&sides.data_at(${i}))
.expect("sides[${i}] could not convert to LengthOrPercentage"))) .expect("sides[${i}] could not convert to LengthPercentage")))
}, },
}, },
% endfor % endfor

View file

@ -611,10 +611,10 @@ ${helpers.predefined_type(
${helpers.predefined_type( ${helpers.predefined_type(
"shape-margin", "shape-margin",
"NonNegativeLengthOrPercentage", "NonNegativeLengthPercentage",
"computed::NonNegativeLengthOrPercentage::zero()", "computed::NonNegativeLengthPercentage::zero()",
products="gecko", products="gecko",
animation_value_type="NonNegativeLengthOrPercentage", animation_value_type="NonNegativeLengthPercentage",
flags="APPLIES_TO_FIRST_LETTER", flags="APPLIES_TO_FIRST_LETTER",
spec="https://drafts.csswg.org/css-shapes/#shape-margin-property", spec="https://drafts.csswg.org/css-shapes/#shape-margin-property",
)} )}

View file

@ -53,8 +53,8 @@ ${helpers.single_keyword(
${helpers.predefined_type( ${helpers.predefined_type(
"text-indent", "text-indent",
"LengthOrPercentage", "LengthPercentage",
"computed::LengthOrPercentage::Length(computed::Length::new(0.))", "computed::LengthPercentage::zero()",
animation_value_type="ComputedValue", animation_value_type="ComputedValue",
spec="https://drafts.csswg.org/css-text/#propdef-text-indent", spec="https://drafts.csswg.org/css-text/#propdef-text-indent",
allow_quirks=True, allow_quirks=True,

View file

@ -14,8 +14,8 @@
%> %>
${helpers.predefined_type( ${helpers.predefined_type(
"margin-%s" % side[0], "margin-%s" % side[0],
"LengthOrPercentageOrAuto", "LengthPercentageOrAuto",
"computed::LengthOrPercentageOrAuto::Length(computed::Length::new(0.))", "computed::LengthPercentageOrAuto::zero()",
alias=maybe_moz_logical_alias(product, side, "-moz-margin-%s"), alias=maybe_moz_logical_alias(product, side, "-moz-margin-%s"),
allow_quirks=not side[1], allow_quirks=not side[1],
animation_value_type="ComputedValue", animation_value_type="ComputedValue",

View file

@ -16,10 +16,10 @@
%> %>
${helpers.predefined_type( ${helpers.predefined_type(
"padding-%s" % side[0], "padding-%s" % side[0],
"NonNegativeLengthOrPercentage", "NonNegativeLengthPercentage",
"computed::NonNegativeLengthOrPercentage::zero()", "computed::NonNegativeLengthPercentage::zero()",
alias=maybe_moz_logical_alias(product, side, "-moz-padding-%s"), alias=maybe_moz_logical_alias(product, side, "-moz-padding-%s"),
animation_value_type="NonNegativeLengthOrPercentage", animation_value_type="NonNegativeLengthPercentage",
logical=side[1], logical=side[1],
logical_group="padding", logical_group="padding",
spec=spec, spec=spec,

View file

@ -12,8 +12,8 @@
% for side in PHYSICAL_SIDES: % for side in PHYSICAL_SIDES:
${helpers.predefined_type( ${helpers.predefined_type(
side, side,
"LengthOrPercentageOrAuto", "LengthPercentageOrAuto",
"computed::LengthOrPercentageOrAuto::Auto", "computed::LengthPercentageOrAuto::Auto",
spec="https://www.w3.org/TR/CSS2/visuren.html#propdef-%s" % side, spec="https://www.w3.org/TR/CSS2/visuren.html#propdef-%s" % side,
flags="GETCS_NEEDS_LAYOUT_FLUSH", flags="GETCS_NEEDS_LAYOUT_FLUSH",
animation_value_type="ComputedValue", animation_value_type="ComputedValue",
@ -26,8 +26,8 @@
% for side in LOGICAL_SIDES: % for side in LOGICAL_SIDES:
${helpers.predefined_type( ${helpers.predefined_type(
"inset-%s" % side, "inset-%s" % side,
"LengthOrPercentageOrAuto", "LengthPercentageOrAuto",
"computed::LengthOrPercentageOrAuto::Auto", "computed::LengthPercentageOrAuto::Auto",
spec="https://drafts.csswg.org/css-logical-props/#propdef-inset-%s" % side, spec="https://drafts.csswg.org/css-logical-props/#propdef-inset-%s" % side,
flags="GETCS_NEEDS_LAYOUT_FLUSH", flags="GETCS_NEEDS_LAYOUT_FLUSH",
alias="offset-%s:layout.css.offset-logical-properties.enabled" % side, alias="offset-%s:layout.css.offset-logical-properties.enabled" % side,
@ -285,8 +285,8 @@ ${helpers.predefined_type(
// servo versions (no keyword support) // servo versions (no keyword support)
${helpers.predefined_type( ${helpers.predefined_type(
size, size,
"LengthOrPercentageOrAuto", "LengthPercentageOrAuto",
"computed::LengthOrPercentageOrAuto::Auto", "computed::LengthPercentageOrAuto::Auto",
"parse_non_negative", "parse_non_negative",
spec=spec % size, spec=spec % size,
logical_group="size", logical_group="size",
@ -296,8 +296,8 @@ ${helpers.predefined_type(
)} )}
${helpers.predefined_type( ${helpers.predefined_type(
"min-%s" % size, "min-%s" % size,
"LengthOrPercentage", "LengthPercentage",
"computed::LengthOrPercentage::Length(computed::Length::new(0.))", "computed::LengthPercentage::zero()",
"parse_non_negative", "parse_non_negative",
spec=spec % ("min-%s" % size), spec=spec % ("min-%s" % size),
logical_group="min-size", logical_group="min-size",
@ -308,8 +308,8 @@ ${helpers.predefined_type(
)} )}
${helpers.predefined_type( ${helpers.predefined_type(
"max-%s" % size, "max-%s" % size,
"LengthOrPercentageOrNone", "LengthPercentageOrNone",
"computed::LengthOrPercentageOrNone::None", "computed::LengthPercentageOrNone::None",
"parse_non_negative", "parse_non_negative",
spec=spec % ("max-%s" % size), spec=spec % ("max-%s" % size),
logical_group="max-size", logical_group="max-size",
@ -408,24 +408,24 @@ ${helpers.predefined_type(
${helpers.predefined_type( ${helpers.predefined_type(
"column-gap", "column-gap",
"length::NonNegativeLengthOrPercentageOrNormal", "length::NonNegativeLengthPercentageOrNormal",
"Either::Second(Normal)", "Either::Second(Normal)",
alias="grid-column-gap" if product == "gecko" else "", alias="grid-column-gap" if product == "gecko" else "",
extra_prefixes="moz", extra_prefixes="moz",
servo_pref="layout.columns.enabled", servo_pref="layout.columns.enabled",
spec="https://drafts.csswg.org/css-align-3/#propdef-column-gap", spec="https://drafts.csswg.org/css-align-3/#propdef-column-gap",
animation_value_type="NonNegativeLengthOrPercentageOrNormal", animation_value_type="NonNegativeLengthPercentageOrNormal",
servo_restyle_damage="reflow", servo_restyle_damage="reflow",
)} )}
// no need for -moz- prefixed alias for this property // no need for -moz- prefixed alias for this property
${helpers.predefined_type( ${helpers.predefined_type(
"row-gap", "row-gap",
"length::NonNegativeLengthOrPercentageOrNormal", "length::NonNegativeLengthPercentageOrNormal",
"Either::Second(Normal)", "Either::Second(Normal)",
alias="grid-row-gap", alias="grid-row-gap",
products="gecko", products="gecko",
spec="https://drafts.csswg.org/css-align-3/#propdef-row-gap", spec="https://drafts.csswg.org/css-align-3/#propdef-row-gap",
animation_value_type="NonNegativeLengthOrPercentageOrNormal", animation_value_type="NonNegativeLengthPercentageOrNormal",
servo_restyle_damage="reflow", servo_restyle_damage="reflow",
)} )}

View file

@ -118,7 +118,7 @@ ${helpers.predefined_type(
${helpers.predefined_type( ${helpers.predefined_type(
"mask-position-" + axis, "mask-position-" + axis,
"position::" + direction + "Position", "position::" + direction + "Position",
"computed::LengthOrPercentage::zero()", "computed::LengthPercentage::zero()",
products="gecko", products="gecko",
extra_prefixes="webkit", extra_prefixes="webkit",
initial_specified_value="specified::PositionComponent::Center", initial_specified_value="specified::PositionComponent::Center",

View file

@ -3017,7 +3017,7 @@ impl ComputedValuesInner {
/// Get the logical computed inline size. /// Get the logical computed inline size.
#[inline] #[inline]
pub fn content_inline_size(&self) -> computed::LengthOrPercentageOrAuto { pub fn content_inline_size(&self) -> computed::LengthPercentageOrAuto {
let position_style = self.get_position(); let position_style = self.get_position();
if self.writing_mode.is_vertical() { if self.writing_mode.is_vertical() {
position_style.height position_style.height
@ -3028,42 +3028,42 @@ impl ComputedValuesInner {
/// Get the logical computed block size. /// Get the logical computed block size.
#[inline] #[inline]
pub fn content_block_size(&self) -> computed::LengthOrPercentageOrAuto { pub fn content_block_size(&self) -> computed::LengthPercentageOrAuto {
let position_style = self.get_position(); let position_style = self.get_position();
if self.writing_mode.is_vertical() { position_style.width } else { position_style.height } if self.writing_mode.is_vertical() { position_style.width } else { position_style.height }
} }
/// Get the logical computed min inline size. /// Get the logical computed min inline size.
#[inline] #[inline]
pub fn min_inline_size(&self) -> computed::LengthOrPercentage { pub fn min_inline_size(&self) -> computed::LengthPercentage {
let position_style = self.get_position(); let position_style = self.get_position();
if self.writing_mode.is_vertical() { position_style.min_height } else { position_style.min_width } if self.writing_mode.is_vertical() { position_style.min_height } else { position_style.min_width }
} }
/// Get the logical computed min block size. /// Get the logical computed min block size.
#[inline] #[inline]
pub fn min_block_size(&self) -> computed::LengthOrPercentage { pub fn min_block_size(&self) -> computed::LengthPercentage {
let position_style = self.get_position(); let position_style = self.get_position();
if self.writing_mode.is_vertical() { position_style.min_width } else { position_style.min_height } if self.writing_mode.is_vertical() { position_style.min_width } else { position_style.min_height }
} }
/// Get the logical computed max inline size. /// Get the logical computed max inline size.
#[inline] #[inline]
pub fn max_inline_size(&self) -> computed::LengthOrPercentageOrNone { pub fn max_inline_size(&self) -> computed::LengthPercentageOrNone {
let position_style = self.get_position(); let position_style = self.get_position();
if self.writing_mode.is_vertical() { position_style.max_height } else { position_style.max_width } if self.writing_mode.is_vertical() { position_style.max_height } else { position_style.max_width }
} }
/// Get the logical computed max block size. /// Get the logical computed max block size.
#[inline] #[inline]
pub fn max_block_size(&self) -> computed::LengthOrPercentageOrNone { pub fn max_block_size(&self) -> computed::LengthPercentageOrNone {
let position_style = self.get_position(); let position_style = self.get_position();
if self.writing_mode.is_vertical() { position_style.max_width } else { position_style.max_height } if self.writing_mode.is_vertical() { position_style.max_width } else { position_style.max_height }
} }
/// Get the logical computed padding for this writing mode. /// Get the logical computed padding for this writing mode.
#[inline] #[inline]
pub fn logical_padding(&self) -> LogicalMargin<computed::LengthOrPercentage> { pub fn logical_padding(&self) -> LogicalMargin<computed::LengthPercentage> {
let padding_style = self.get_padding(); let padding_style = self.get_padding();
LogicalMargin::from_physical(self.writing_mode, SideOffsets2D::new( LogicalMargin::from_physical(self.writing_mode, SideOffsets2D::new(
padding_style.padding_top.0, padding_style.padding_top.0,
@ -3093,7 +3093,7 @@ impl ComputedValuesInner {
/// Gets the logical computed margin from this style. /// Gets the logical computed margin from this style.
#[inline] #[inline]
pub fn logical_margin(&self) -> LogicalMargin<computed::LengthOrPercentageOrAuto> { pub fn logical_margin(&self) -> LogicalMargin<computed::LengthPercentageOrAuto> {
let margin_style = self.get_margin(); let margin_style = self.get_margin();
LogicalMargin::from_physical(self.writing_mode, SideOffsets2D::new( LogicalMargin::from_physical(self.writing_mode, SideOffsets2D::new(
margin_style.margin_top, margin_style.margin_top,
@ -3105,7 +3105,7 @@ impl ComputedValuesInner {
/// Gets the logical position from this style. /// Gets the logical position from this style.
#[inline] #[inline]
pub fn logical_position(&self) -> LogicalMargin<computed::LengthOrPercentageOrAuto> { pub fn logical_position(&self) -> LogicalMargin<computed::LengthPercentageOrAuto> {
// FIXME(SimonSapin): should be the writing mode of the containing block, maybe? // FIXME(SimonSapin): should be the writing mode of the containing block, maybe?
let position_style = self.get_position(); let position_style = self.get_position();
LogicalMargin::from_physical(self.writing_mode, SideOffsets2D::new( LogicalMargin::from_physical(self.writing_mode, SideOffsets2D::new(

View file

@ -4,7 +4,7 @@
<%namespace name="helpers" file="/helpers.mako.rs" /> <%namespace name="helpers" file="/helpers.mako.rs" />
${helpers.four_sides_shorthand("margin", "margin-%s", "specified::LengthOrPercentageOrAuto::parse", ${helpers.four_sides_shorthand("margin", "margin-%s", "specified::LengthPercentageOrAuto::parse",
spec="https://drafts.csswg.org/css-box/#propdef-margin", spec="https://drafts.csswg.org/css-box/#propdef-margin",
allowed_in_page_rule=True, allowed_in_page_rule=True,
allow_quirks=True)} allow_quirks=True)}

View file

@ -4,6 +4,6 @@
<%namespace name="helpers" file="/helpers.mako.rs" /> <%namespace name="helpers" file="/helpers.mako.rs" />
${helpers.four_sides_shorthand("padding", "padding-%s", "specified::NonNegativeLengthOrPercentage::parse", ${helpers.four_sides_shorthand("padding", "padding-%s", "specified::NonNegativeLengthPercentage::parse",
spec="https://drafts.csswg.org/css-box-3/#propdef-padding", spec="https://drafts.csswg.org/css-box-3/#propdef-padding",
allow_quirks=True)} allow_quirks=True)}

View file

@ -18,7 +18,9 @@ use crate::shared_lock::{SharedRwLockReadGuard, StylesheetGuards, ToCssWithGuard
use crate::str::CssStringWriter; use crate::str::CssStringWriter;
use crate::stylesheets::{Origin, StylesheetInDocument}; use crate::stylesheets::{Origin, StylesheetInDocument};
use crate::values::computed::{Context, ToComputedValue}; use crate::values::computed::{Context, ToComputedValue};
use crate::values::specified::{LengthOrPercentageOrAuto, NoCalcLength, ViewportPercentageLength}; use crate::values::specified::{
self, LengthPercentageOrAuto, NoCalcLength, ViewportPercentageLength,
};
use app_units::Au; use app_units::Au;
use cssparser::CowRcStr; use cssparser::CowRcStr;
use cssparser::{parse_important, AtRuleParser, DeclarationListParser, DeclarationParser, Parser}; use cssparser::{parse_important, AtRuleParser, DeclarationListParser, DeclarationParser, Parser};
@ -149,7 +151,7 @@ trait FromMeta: Sized {
#[cfg_attr(feature = "servo", derive(MallocSizeOf))] #[cfg_attr(feature = "servo", derive(MallocSizeOf))]
#[derive(Clone, Debug, PartialEq, ToCss)] #[derive(Clone, Debug, PartialEq, ToCss)]
pub enum ViewportLength { pub enum ViewportLength {
Specified(LengthOrPercentageOrAuto), Specified(LengthPercentageOrAuto),
ExtendToZoom, ExtendToZoom,
} }
@ -157,7 +159,9 @@ impl FromMeta for ViewportLength {
fn from_meta(value: &str) -> Option<ViewportLength> { fn from_meta(value: &str) -> Option<ViewportLength> {
macro_rules! specified { macro_rules! specified {
($value:expr) => { ($value:expr) => {
ViewportLength::Specified(LengthOrPercentageOrAuto::Length($value)) ViewportLength::Specified(LengthPercentageOrAuto::LengthPercentage(
specified::LengthPercentage::Length($value),
))
}; };
} }
@ -184,7 +188,7 @@ impl ViewportLength {
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
// we explicitly do not accept 'extend-to-zoom', since it is a UA // we explicitly do not accept 'extend-to-zoom', since it is a UA
// internal value for <META> viewport translation // internal value for <META> viewport translation
LengthOrPercentageOrAuto::parse_non_negative(context, input).map(ViewportLength::Specified) LengthPercentageOrAuto::parse_non_negative(context, input).map(ViewportLength::Specified)
} }
} }
@ -466,10 +470,10 @@ impl ViewportRule {
if !has_width && has_zoom { if !has_width && has_zoom {
if has_height { if has_height {
push_descriptor!(MinWidth(ViewportLength::Specified( push_descriptor!(MinWidth(ViewportLength::Specified(
LengthOrPercentageOrAuto::Auto LengthPercentageOrAuto::Auto
))); )));
push_descriptor!(MaxWidth(ViewportLength::Specified( push_descriptor!(MaxWidth(ViewportLength::Specified(
LengthOrPercentageOrAuto::Auto LengthPercentageOrAuto::Auto
))); )));
} else { } else {
push_descriptor!(MinWidth(ViewportLength::ExtendToZoom)); push_descriptor!(MinWidth(ViewportLength::ExtendToZoom));
@ -752,16 +756,11 @@ impl MaybeNew for ViewportConstraints {
if let Some($value) = $value { if let Some($value) = $value {
match *$value { match *$value {
ViewportLength::Specified(ref length) => match *length { ViewportLength::Specified(ref length) => match *length {
LengthOrPercentageOrAuto::Length(ref value) => { LengthPercentageOrAuto::Auto => None,
Some(Au::from(value.to_computed_value(&context))) LengthPercentageOrAuto::LengthPercentage(ref lop) => Some(
}, lop.to_computed_value(&context)
LengthOrPercentageOrAuto::Percentage(value) => { .to_used_value(initial_viewport.$dimension),
Some(initial_viewport.$dimension.scale_by(value.0)) ),
},
LengthOrPercentageOrAuto::Auto => None,
LengthOrPercentageOrAuto::Calc(ref calc) => calc
.to_computed_value(&context)
.to_used_value(Some(initial_viewport.$dimension)),
}, },
ViewportLength::ExtendToZoom => { ViewportLength::ExtendToZoom => {
// $extend_to will be 'None' if 'extend-to-zoom' is 'auto' // $extend_to will be 'None' if 'extend-to-zoom' is 'auto'

View file

@ -4,15 +4,14 @@
//! Animation implementation for various length-related types. //! Animation implementation for various length-related types.
use super::{Animate, Procedure, ToAnimatedValue, ToAnimatedZero}; use super::{Animate, Procedure, ToAnimatedValue};
use crate::values::computed::length::{CalcLengthOrPercentage, Length}; use crate::values::computed::length::LengthPercentage;
use crate::values::computed::length::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone};
use crate::values::computed::MaxLength as ComputedMaxLength; use crate::values::computed::MaxLength as ComputedMaxLength;
use crate::values::computed::MozLength as ComputedMozLength; use crate::values::computed::MozLength as ComputedMozLength;
use crate::values::computed::Percentage; use crate::values::computed::Percentage;
/// <https://drafts.csswg.org/css-transitions/#animtype-lpcalc> /// <https://drafts.csswg.org/css-transitions/#animtype-lpcalc>
impl Animate for CalcLengthOrPercentage { impl Animate for LengthPercentage {
#[inline] #[inline]
fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
let animate_percentage_half = |this: Option<Percentage>, other: Option<Percentage>| { let animate_percentage_half = |this: Option<Percentage>, other: Option<Percentage>| {
@ -28,42 +27,19 @@ impl Animate for CalcLengthOrPercentage {
.unclamped_length() .unclamped_length()
.animate(&other.unclamped_length(), procedure)?; .animate(&other.unclamped_length(), procedure)?;
let percentage = animate_percentage_half(self.percentage, other.percentage)?; let percentage = animate_percentage_half(self.percentage, other.percentage)?;
Ok(CalcLengthOrPercentage::with_clamping_mode( let is_calc = self.was_calc ||
other.was_calc ||
self.percentage.is_some() != other.percentage.is_some();
Ok(Self::with_clamping_mode(
length, length,
percentage, percentage,
self.clamping_mode, self.clamping_mode,
is_calc,
)) ))
} }
} }
impl ToAnimatedZero for LengthOrPercentageOrAuto { // FIXME(emilio): These should use NonNegative<> instead.
#[inline]
fn to_animated_zero(&self) -> Result<Self, ()> {
match *self {
LengthOrPercentageOrAuto::Length(_) |
LengthOrPercentageOrAuto::Percentage(_) |
LengthOrPercentageOrAuto::Calc(_) => {
Ok(LengthOrPercentageOrAuto::Length(Length::new(0.)))
},
LengthOrPercentageOrAuto::Auto => Err(()),
}
}
}
impl ToAnimatedZero for LengthOrPercentageOrNone {
#[inline]
fn to_animated_zero(&self) -> Result<Self, ()> {
match *self {
LengthOrPercentageOrNone::Length(_) |
LengthOrPercentageOrNone::Percentage(_) |
LengthOrPercentageOrNone::Calc(_) => {
Ok(LengthOrPercentageOrNone::Length(Length::new(0.)))
},
LengthOrPercentageOrNone::None => Err(()),
}
}
}
impl ToAnimatedValue for ComputedMaxLength { impl ToAnimatedValue for ComputedMaxLength {
type AnimatedValue = Self; type AnimatedValue = Self;
@ -74,20 +50,17 @@ impl ToAnimatedValue for ComputedMaxLength {
#[inline] #[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self { fn from_animated_value(animated: Self::AnimatedValue) -> Self {
use crate::values::computed::{Length, LengthOrPercentageOrNone, Percentage}; use crate::values::computed::LengthPercentageOrNone;
use crate::values::generics::length::MaxLength as GenericMaxLength; use crate::values::generics::length::MaxLength as GenericMaxLength;
match animated { match animated {
GenericMaxLength::LengthOrPercentageOrNone(lopn) => { GenericMaxLength::LengthPercentageOrNone(lpn) => {
let result = match lopn { let result = match lpn {
LengthOrPercentageOrNone::Length(px) => { LengthPercentageOrNone::LengthPercentage(len) => {
LengthOrPercentageOrNone::Length(Length::new(px.px().max(0.))) LengthPercentageOrNone::LengthPercentage(len.clamp_to_non_negative())
}, },
LengthOrPercentageOrNone::Percentage(percentage) => { LengthPercentageOrNone::None => lpn,
LengthOrPercentageOrNone::Percentage(Percentage(percentage.0.max(0.)))
},
_ => lopn,
}; };
GenericMaxLength::LengthOrPercentageOrNone(result) GenericMaxLength::LengthPercentageOrNone(result)
}, },
_ => animated, _ => animated,
} }
@ -104,20 +77,10 @@ impl ToAnimatedValue for ComputedMozLength {
#[inline] #[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self { fn from_animated_value(animated: Self::AnimatedValue) -> Self {
use crate::values::computed::{Length, LengthOrPercentageOrAuto, Percentage};
use crate::values::generics::length::MozLength as GenericMozLength; use crate::values::generics::length::MozLength as GenericMozLength;
match animated { match animated {
GenericMozLength::LengthOrPercentageOrAuto(lopa) => { GenericMozLength::LengthPercentageOrAuto(lpa) => {
let result = match lopa { GenericMozLength::LengthPercentageOrAuto(lpa.clamp_to_non_negative())
LengthOrPercentageOrAuto::Length(px) => {
LengthOrPercentageOrAuto::Length(Length::new(px.px().max(0.)))
},
LengthOrPercentageOrAuto::Percentage(percentage) => {
LengthOrPercentageOrAuto::Percentage(Percentage(percentage.0.max(0.)))
},
_ => lopa,
};
GenericMozLength::LengthOrPercentageOrAuto(result)
}, },
_ => animated, _ => animated,
} }

View file

@ -9,7 +9,7 @@
//! module's raison d'être is to ultimately contain all these types. //! module's raison d'être is to ultimately contain all these types.
use crate::properties::PropertyId; use crate::properties::PropertyId;
use crate::values::computed::length::CalcLengthOrPercentage; use crate::values::computed::length::LengthPercentage;
use crate::values::computed::url::ComputedUrl; use crate::values::computed::url::ComputedUrl;
use crate::values::computed::Angle as ComputedAngle; use crate::values::computed::Angle as ComputedAngle;
use crate::values::computed::Image; use crate::values::computed::Image;
@ -335,7 +335,7 @@ macro_rules! trivial_to_animated_value {
} }
trivial_to_animated_value!(Au); trivial_to_animated_value!(Au);
trivial_to_animated_value!(CalcLengthOrPercentage); trivial_to_animated_value!(LengthPercentage);
trivial_to_animated_value!(ComputedAngle); trivial_to_animated_value!(ComputedAngle);
trivial_to_animated_value!(ComputedUrl); trivial_to_animated_value!(ComputedUrl);
trivial_to_animated_value!(bool); trivial_to_animated_value!(bool);

View file

@ -8,9 +8,9 @@ use super::{Animate, Procedure, ToAnimatedZero};
use crate::properties::animated_properties::ListAnimation; use crate::properties::animated_properties::ListAnimation;
use crate::values::animated::color::Color as AnimatedColor; use crate::values::animated::color::Color as AnimatedColor;
use crate::values::computed::url::ComputedUrl; use crate::values::computed::url::ComputedUrl;
use crate::values::computed::{LengthOrPercentage, Number, NumberOrPercentage}; use crate::values::computed::{LengthPercentage, Number, NumberOrPercentage};
use crate::values::distance::{ComputeSquaredDistance, SquaredDistance}; use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
use crate::values::generics::svg::{SVGLength, SVGPaint, SvgLengthOrPercentageOrNumber}; use crate::values::generics::svg::{SVGLength, SVGPaint, SvgLengthPercentageOrNumber};
use crate::values::generics::svg::{SVGOpacity, SVGStrokeDashArray}; use crate::values::generics::svg::{SVGOpacity, SVGStrokeDashArray};
/// Animated SVGPaint. /// Animated SVGPaint.
@ -29,19 +29,23 @@ impl ToAnimatedZero for IntermediateSVGPaint {
// FIXME: We need to handle calc here properly, see // FIXME: We need to handle calc here properly, see
// https://bugzilla.mozilla.org/show_bug.cgi?id=1386967 // https://bugzilla.mozilla.org/show_bug.cgi?id=1386967
fn to_number_or_percentage( fn to_number_or_percentage(
value: &SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number>, value: &SvgLengthPercentageOrNumber<LengthPercentage, Number>,
) -> Result<NumberOrPercentage, ()> { ) -> Result<NumberOrPercentage, ()> {
Ok(match *value { Ok(match *value {
SvgLengthOrPercentageOrNumber::LengthOrPercentage(ref l) => match *l { SvgLengthPercentageOrNumber::LengthPercentage(ref l) => match l.percentage {
LengthOrPercentage::Length(ref l) => NumberOrPercentage::Number(l.px()), Some(p) => {
LengthOrPercentage::Percentage(ref p) => NumberOrPercentage::Percentage(*p), if l.unclamped_length().px() != 0. {
LengthOrPercentage::Calc(..) => return Err(()), return Err(());
}
NumberOrPercentage::Percentage(p)
}, },
SvgLengthOrPercentageOrNumber::Number(ref n) => NumberOrPercentage::Number(*n), None => NumberOrPercentage::Number(l.length().px()),
},
SvgLengthPercentageOrNumber::Number(ref n) => NumberOrPercentage::Number(*n),
}) })
} }
impl Animate for SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number> { impl Animate for SvgLengthPercentageOrNumber<LengthPercentage, Number> {
#[inline] #[inline]
fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
let this = to_number_or_percentage(self)?; let this = to_number_or_percentage(self)?;
@ -49,20 +53,20 @@ impl Animate for SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number> {
match (this, other) { match (this, other) {
(NumberOrPercentage::Number(ref this), NumberOrPercentage::Number(ref other)) => Ok( (NumberOrPercentage::Number(ref this), NumberOrPercentage::Number(ref other)) => Ok(
SvgLengthOrPercentageOrNumber::Number(this.animate(other, procedure)?), SvgLengthPercentageOrNumber::Number(this.animate(other, procedure)?),
), ),
( (
NumberOrPercentage::Percentage(ref this), NumberOrPercentage::Percentage(ref this),
NumberOrPercentage::Percentage(ref other), NumberOrPercentage::Percentage(ref other),
) => Ok(SvgLengthOrPercentageOrNumber::LengthOrPercentage( ) => Ok(SvgLengthPercentageOrNumber::LengthPercentage(
LengthOrPercentage::Percentage(this.animate(other, procedure)?), LengthPercentage::new_percent(this.animate(other, procedure)?),
)), )),
_ => Err(()), _ => Err(()),
} }
} }
} }
impl ComputeSquaredDistance for SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number> { impl ComputeSquaredDistance for SvgLengthPercentageOrNumber<LengthPercentage, Number> {
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {
to_number_or_percentage(self)?.compute_squared_distance(&to_number_or_percentage(other)?) to_number_or_percentage(self)?.compute_squared_distance(&to_number_or_percentage(other)?)
} }

View file

@ -16,7 +16,7 @@ use crate::values::computed::transform::TransformOperation as ComputedTransformO
use crate::values::computed::transform::Translate as ComputedTranslate; use crate::values::computed::transform::Translate as ComputedTranslate;
use crate::values::computed::transform::{DirectionVector, Matrix, Matrix3D}; use crate::values::computed::transform::{DirectionVector, Matrix, Matrix3D};
use crate::values::computed::Angle; use crate::values::computed::Angle;
use crate::values::computed::{Length, LengthOrPercentage}; use crate::values::computed::{Length, LengthPercentage};
use crate::values::computed::{Number, Percentage}; use crate::values::computed::{Number, Percentage};
use crate::values::distance::{ComputeSquaredDistance, SquaredDistance}; use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
use crate::values::generics::transform::{self, Transform, TransformOperation}; use crate::values::generics::transform::{self, Transform, TransformOperation};
@ -1043,8 +1043,8 @@ impl Animate for ComputedTransformOperation {
) => Ok(TransformOperation::Translate( ) => Ok(TransformOperation::Translate(
fx.animate(tx, procedure)?, fx.animate(tx, procedure)?,
Some( Some(
fy.unwrap_or(LengthOrPercentage::zero()) fy.unwrap_or(LengthPercentage::zero())
.animate(&ty.unwrap_or(LengthOrPercentage::zero()), procedure)?, .animate(&ty.unwrap_or(LengthPercentage::zero()), procedure)?,
), ),
)), )),
(&TransformOperation::TranslateX(ref f), &TransformOperation::TranslateX(ref t)) => { (&TransformOperation::TranslateX(ref f), &TransformOperation::TranslateX(ref t)) => {
@ -1167,17 +1167,6 @@ impl Animate for ComputedTransformOperation {
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1318591#c0. // See https://bugzilla.mozilla.org/show_bug.cgi?id=1318591#c0.
impl ComputeSquaredDistance for ComputedTransformOperation { impl ComputeSquaredDistance for ComputedTransformOperation {
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { 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) { match (self, other) {
(&TransformOperation::Matrix3D(ref this), &TransformOperation::Matrix3D(ref other)) => { (&TransformOperation::Matrix3D(ref this), &TransformOperation::Matrix3D(ref other)) => {
this.compute_squared_distance(other) this.compute_squared_distance(other)
@ -1199,10 +1188,16 @@ impl ComputeSquaredDistance for ComputedTransformOperation {
&TransformOperation::Translate3D(ref fx, ref fy, ref fz), &TransformOperation::Translate3D(ref fx, ref fy, ref fz),
&TransformOperation::Translate3D(ref tx, ref ty, ref tz), &TransformOperation::Translate3D(ref tx, ref ty, ref tz),
) => { ) => {
let fx = extract_pixel_length(&fx); // For translate, We don't want to require doing layout in order
let fy = extract_pixel_length(&fy); // to calculate the result, so drop the percentage part.
let tx = extract_pixel_length(&tx); //
let ty = extract_pixel_length(&ty); // 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.
let fx = fx.length_component().px();
let fy = fy.length_component().px();
let tx = tx.length_component().px();
let ty = ty.length_component().px();
Ok(fx.compute_squared_distance(&tx)? + Ok(fx.compute_squared_distance(&tx)? +
fy.compute_squared_distance(&ty)? + fy.compute_squared_distance(&ty)? +
@ -1388,15 +1383,15 @@ impl ComputeSquaredDistance for ComputedRotate {
/// <https://drafts.csswg.org/css-transforms-2/#propdef-translate> /// <https://drafts.csswg.org/css-transforms-2/#propdef-translate>
impl ComputedTranslate { impl ComputedTranslate {
fn resolve(&self) -> (LengthOrPercentage, LengthOrPercentage, Length) { fn resolve(&self) -> (LengthPercentage, LengthPercentage, Length) {
// According to the spec: // According to the spec:
// https://drafts.csswg.org/css-transforms-2/#individual-transforms // https://drafts.csswg.org/css-transforms-2/#individual-transforms
// //
// Unspecified translations default to 0px // Unspecified translations default to 0px
match *self { match *self {
Translate::None => ( Translate::None => (
LengthOrPercentage::zero(), LengthPercentage::zero(),
LengthOrPercentage::zero(), LengthPercentage::zero(),
Length::zero(), Length::zero(),
), ),
Translate::Translate3D(tx, ty, tz) => (tx, ty, tz), Translate::Translate3D(tx, ty, tz) => (tx, ty, tz),

View file

@ -4,20 +4,20 @@
//! Computed types for CSS values related to backgrounds. //! Computed types for CSS values related to backgrounds.
use crate::values::computed::length::NonNegativeLengthOrPercentageOrAuto; use crate::values::computed::length::NonNegativeLengthPercentageOrAuto;
use crate::values::generics::background::BackgroundSize as GenericBackgroundSize; use crate::values::generics::background::BackgroundSize as GenericBackgroundSize;
pub use crate::values::specified::background::BackgroundRepeat; pub use crate::values::specified::background::BackgroundRepeat;
/// A computed value for the `background-size` property. /// A computed value for the `background-size` property.
pub type BackgroundSize = GenericBackgroundSize<NonNegativeLengthOrPercentageOrAuto>; pub type BackgroundSize = GenericBackgroundSize<NonNegativeLengthPercentageOrAuto>;
impl BackgroundSize { impl BackgroundSize {
/// Returns `auto auto`. /// Returns `auto auto`.
pub fn auto() -> Self { pub fn auto() -> Self {
GenericBackgroundSize::Explicit { GenericBackgroundSize::Explicit {
width: NonNegativeLengthOrPercentageOrAuto::auto(), width: NonNegativeLengthPercentageOrAuto::auto(),
height: NonNegativeLengthOrPercentageOrAuto::auto(), height: NonNegativeLengthPercentageOrAuto::auto(),
} }
} }
} }

View file

@ -8,7 +8,7 @@
//! [basic-shape]: https://drafts.csswg.org/css-shapes/#typedef-basic-shape //! [basic-shape]: https://drafts.csswg.org/css-shapes/#typedef-basic-shape
use crate::values::computed::url::ComputedUrl; use crate::values::computed::url::ComputedUrl;
use crate::values::computed::{Image, LengthOrPercentage, NonNegativeLengthOrPercentage}; use crate::values::computed::{Image, LengthPercentage, NonNegativeLengthPercentage};
use crate::values::generics::basic_shape as generic; use crate::values::generics::basic_shape as generic;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss}; use style_traits::{CssWriter, ToCss};
@ -24,25 +24,24 @@ pub type FloatAreaShape = generic::FloatAreaShape<BasicShape, Image>;
/// A computed basic shape. /// A computed basic shape.
pub type BasicShape = generic::BasicShape< pub type BasicShape = generic::BasicShape<
LengthOrPercentage, LengthPercentage,
LengthOrPercentage, LengthPercentage,
LengthOrPercentage, LengthPercentage,
NonNegativeLengthOrPercentage, NonNegativeLengthPercentage,
>; >;
/// The computed value of `inset()` /// The computed value of `inset()`
pub type InsetRect = generic::InsetRect<LengthOrPercentage, NonNegativeLengthOrPercentage>; pub type InsetRect = generic::InsetRect<LengthPercentage, NonNegativeLengthPercentage>;
/// A computed circle. /// A computed circle.
pub type Circle = pub type Circle = generic::Circle<LengthPercentage, LengthPercentage, NonNegativeLengthPercentage>;
generic::Circle<LengthOrPercentage, LengthOrPercentage, NonNegativeLengthOrPercentage>;
/// A computed ellipse. /// A computed ellipse.
pub type Ellipse = pub type Ellipse =
generic::Ellipse<LengthOrPercentage, LengthOrPercentage, NonNegativeLengthOrPercentage>; generic::Ellipse<LengthPercentage, LengthPercentage, NonNegativeLengthPercentage>;
/// The computed value of `ShapeRadius` /// The computed value of `ShapeRadius`
pub type ShapeRadius = generic::ShapeRadius<NonNegativeLengthOrPercentage>; pub type ShapeRadius = generic::ShapeRadius<NonNegativeLengthPercentage>;
impl ToCss for Circle { impl ToCss for Circle {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result

View file

@ -4,7 +4,7 @@
//! Computed types for CSS values related to borders. //! Computed types for CSS values related to borders.
use crate::values::computed::length::{NonNegativeLength, NonNegativeLengthOrPercentage}; use crate::values::computed::length::{NonNegativeLength, NonNegativeLengthPercentage};
use crate::values::computed::{NonNegativeNumber, NonNegativeNumberOrPercentage}; use crate::values::computed::{NonNegativeNumber, NonNegativeNumberOrPercentage};
use crate::values::generics::border::BorderCornerRadius as GenericBorderCornerRadius; use crate::values::generics::border::BorderCornerRadius as GenericBorderCornerRadius;
use crate::values::generics::border::BorderImageSideWidth as GenericBorderImageSideWidth; use crate::values::generics::border::BorderImageSideWidth as GenericBorderImageSideWidth;
@ -23,16 +23,16 @@ pub type BorderImageWidth = Rect<BorderImageSideWidth>;
/// A computed value for a single side of a `border-image-width` property. /// A computed value for a single side of a `border-image-width` property.
pub type BorderImageSideWidth = pub type BorderImageSideWidth =
GenericBorderImageSideWidth<NonNegativeLengthOrPercentage, NonNegativeNumber>; GenericBorderImageSideWidth<NonNegativeLengthPercentage, NonNegativeNumber>;
/// A computed value for the `border-image-slice` property. /// A computed value for the `border-image-slice` property.
pub type BorderImageSlice = GenericBorderImageSlice<NonNegativeNumberOrPercentage>; pub type BorderImageSlice = GenericBorderImageSlice<NonNegativeNumberOrPercentage>;
/// A computed value for the `border-radius` property. /// A computed value for the `border-radius` property.
pub type BorderRadius = GenericBorderRadius<NonNegativeLengthOrPercentage>; pub type BorderRadius = GenericBorderRadius<NonNegativeLengthPercentage>;
/// A computed value for the `border-*-radius` longhand properties. /// A computed value for the `border-*-radius` longhand properties.
pub type BorderCornerRadius = GenericBorderCornerRadius<NonNegativeLengthOrPercentage>; pub type BorderCornerRadius = GenericBorderCornerRadius<NonNegativeLengthPercentage>;
/// A computed value for the `border-spacing` longhand property. /// A computed value for the `border-spacing` longhand property.
pub type BorderSpacing = GenericBorderSpacing<NonNegativeLength>; pub type BorderSpacing = GenericBorderSpacing<NonNegativeLength>;
@ -80,8 +80,8 @@ impl BorderCornerRadius {
/// Returns `0 0`. /// Returns `0 0`.
pub fn zero() -> Self { pub fn zero() -> Self {
GenericBorderCornerRadius(Size::new( GenericBorderCornerRadius(Size::new(
NonNegativeLengthOrPercentage::zero(), NonNegativeLengthPercentage::zero(),
NonNegativeLengthOrPercentage::zero(), NonNegativeLengthPercentage::zero(),
)) ))
} }
} }
@ -90,8 +90,8 @@ impl BorderRadius {
/// Returns whether all the values are `0px`. /// Returns whether all the values are `0px`.
pub fn all_zero(&self) -> bool { pub fn all_zero(&self) -> bool {
fn all(corner: &BorderCornerRadius) -> bool { fn all(corner: &BorderCornerRadius) -> bool {
fn is_zero(l: &NonNegativeLengthOrPercentage) -> bool { fn is_zero(l: &NonNegativeLengthPercentage) -> bool {
*l == NonNegativeLengthOrPercentage::zero() *l == NonNegativeLengthPercentage::zero()
} }
is_zero(corner.0.width()) && is_zero(corner.0.height()) is_zero(corner.0.width()) && is_zero(corner.0.height())
} }

View file

@ -4,7 +4,7 @@
//! Computed types for box properties. //! Computed types for box properties.
use crate::values::computed::length::{LengthOrPercentage, NonNegativeLength}; use crate::values::computed::length::{LengthPercentage, NonNegativeLength};
use crate::values::computed::{Context, Number, ToComputedValue}; use crate::values::computed::{Context, Number, ToComputedValue};
use crate::values::generics::box_::AnimationIterationCount as GenericAnimationIterationCount; use crate::values::generics::box_::AnimationIterationCount as GenericAnimationIterationCount;
use crate::values::generics::box_::Perspective as GenericPerspective; use crate::values::generics::box_::Perspective as GenericPerspective;
@ -18,7 +18,7 @@ pub use crate::values::specified::box_::{OverscrollBehavior, ScrollSnapType};
pub use crate::values::specified::box_::{TouchAction, TransitionProperty, WillChange}; pub use crate::values::specified::box_::{TouchAction, TransitionProperty, WillChange};
/// A computed value for the `vertical-align` property. /// A computed value for the `vertical-align` property.
pub type VerticalAlign = GenericVerticalAlign<LengthOrPercentage>; pub type VerticalAlign = GenericVerticalAlign<LengthPercentage>;
/// A computed value for the `animation-iteration-count` property. /// A computed value for the `animation-iteration-count` property.
pub type AnimationIterationCount = GenericAnimationIterationCount<Number>; pub type AnimationIterationCount = GenericAnimationIterationCount<Number>;

View file

@ -8,7 +8,7 @@ use crate::values::generics::flex::FlexBasis as GenericFlexBasis;
/// The `width` value type. /// The `width` value type.
#[cfg(feature = "servo")] #[cfg(feature = "servo")]
pub type Width = crate::values::computed::NonNegativeLengthOrPercentageOrAuto; pub type Width = crate::values::computed::NonNegativeLengthPercentageOrAuto;
/// The `width` value type. /// The `width` value type.
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]

View file

@ -4,8 +4,8 @@
//! Computed types for legacy Gecko-only properties. //! Computed types for legacy Gecko-only properties.
use crate::values::computed::length::LengthOrPercentage; use crate::values::computed::length::LengthPercentage;
use crate::values::generics::gecko::ScrollSnapPoint as GenericScrollSnapPoint; use crate::values::generics::gecko::ScrollSnapPoint as GenericScrollSnapPoint;
/// A computed type for scroll snap points. /// A computed type for scroll snap points.
pub type ScrollSnapPoint = GenericScrollSnapPoint<LengthOrPercentage>; pub type ScrollSnapPoint = GenericScrollSnapPoint<LengthPercentage>;

View file

@ -9,10 +9,8 @@
use crate::values::computed::position::Position; use crate::values::computed::position::Position;
use crate::values::computed::url::ComputedImageUrl; use crate::values::computed::url::ComputedImageUrl;
#[cfg(feature = "gecko")]
use crate::values::computed::Percentage;
use crate::values::computed::{Angle, Color, Context}; use crate::values::computed::{Angle, Color, Context};
use crate::values::computed::{Length, LengthOrPercentage, NumberOrPercentage, ToComputedValue}; use crate::values::computed::{Length, LengthPercentage, NumberOrPercentage, ToComputedValue};
use crate::values::generics::image::{self as generic, CompatMode}; use crate::values::generics::image::{self as generic, CompatMode};
use crate::values::specified::image::LineDirection as SpecifiedLineDirection; use crate::values::specified::image::LineDirection as SpecifiedLineDirection;
use crate::values::specified::position::{X, Y}; use crate::values::specified::position::{X, Y};
@ -31,11 +29,11 @@ pub type Image = generic::Image<Gradient, MozImageRect, ComputedImageUrl>;
/// Computed values for a CSS gradient. /// Computed values for a CSS gradient.
/// <https://drafts.csswg.org/css-images/#gradients> /// <https://drafts.csswg.org/css-images/#gradients>
pub type Gradient = pub type Gradient =
generic::Gradient<LineDirection, Length, LengthOrPercentage, Position, Color, Angle>; generic::Gradient<LineDirection, Length, LengthPercentage, Position, Color, Angle>;
/// A computed gradient kind. /// A computed gradient kind.
pub type GradientKind = pub type GradientKind =
generic::GradientKind<LineDirection, Length, LengthOrPercentage, Position, Angle>; generic::GradientKind<LineDirection, Length, LengthPercentage, Position, Angle>;
/// A computed gradient line direction. /// A computed gradient line direction.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)] #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)]
@ -54,13 +52,13 @@ pub enum LineDirection {
} }
/// A computed radial gradient ending shape. /// A computed radial gradient ending shape.
pub type EndingShape = generic::EndingShape<Length, LengthOrPercentage>; pub type EndingShape = generic::EndingShape<Length, LengthPercentage>;
/// A computed gradient item. /// A computed gradient item.
pub type GradientItem = generic::GradientItem<Color, LengthOrPercentage>; pub type GradientItem = generic::GradientItem<Color, LengthPercentage>;
/// A computed color stop. /// A computed color stop.
pub type ColorStop = generic::ColorStop<Color, LengthOrPercentage>; pub type ColorStop = generic::ColorStop<Color, LengthPercentage>;
/// Computed values for `-moz-image-rect(...)`. /// Computed values for `-moz-image-rect(...)`.
pub type MozImageRect = generic::MozImageRect<NumberOrPercentage, ComputedImageUrl>; pub type MozImageRect = generic::MozImageRect<NumberOrPercentage, ComputedImageUrl>;
@ -75,13 +73,14 @@ impl generic::LineDirection for LineDirection {
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
LineDirection::MozPosition( LineDirection::MozPosition(
Some(Position { Some(Position {
horizontal: LengthOrPercentage::Percentage(Percentage(x)), ref vertical,
vertical: LengthOrPercentage::Percentage(Percentage(y)), ref horizontal,
}), }),
None, None,
) => { ) => {
// `50% 0%` is the default value for line direction. // `50% 0%` is the default value for line direction.
x == 0.5 && y == 0.0 horizontal.as_percentage().map_or(false, |p| p.0 == 0.5) &&
vertical.as_percentage().map_or(false, |p| p.0 == 0.0)
}, },
_ => false, _ => false,
} }

View file

@ -5,7 +5,7 @@
//! `<length>` computed values, and related ones. //! `<length>` computed values, and related ones.
use super::{Context, Number, Percentage, ToComputedValue}; use super::{Context, Number, Percentage, ToComputedValue};
use crate::values::animated::{Animate, Procedure, ToAnimatedValue, ToAnimatedZero}; use crate::values::animated::ToAnimatedValue;
use crate::values::distance::{ComputeSquaredDistance, SquaredDistance}; use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
use crate::values::generics::length::MaxLength as GenericMaxLength; use crate::values::generics::length::MaxLength as GenericMaxLength;
use crate::values::generics::length::MozLength as GenericMozLength; use crate::values::generics::length::MozLength as GenericMozLength;
@ -67,16 +67,43 @@ impl ToComputedValue for specified::Length {
} }
} }
/// A `<length-percentage>` value. This can be either a `<length>`, a
/// `<percentage>`, or a combination of both via `calc()`.
///
/// https://drafts.csswg.org/css-values-4/#typedef-length-percentage
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedZero)] #[derive(Clone, Copy, Debug, MallocSizeOf, ToAnimatedZero)]
pub struct CalcLengthOrPercentage { pub struct LengthPercentage {
#[animation(constant)] #[animation(constant)]
pub clamping_mode: AllowedNumericType, pub clamping_mode: AllowedNumericType,
length: Length, length: Length,
pub percentage: Option<Percentage>, pub percentage: Option<Percentage>,
/// Whether this was from a calc() expression. This is needed because right
/// now we don't treat calc() the same way as non-calc everywhere, but
/// that's a bug in most cases.
///
/// Please don't add new uses of this that aren't for converting to Gecko's
/// representation, or to interpolate values.
///
/// See https://github.com/w3c/csswg-drafts/issues/3482.
#[animation(constant)]
pub was_calc: bool,
} }
impl ComputeSquaredDistance for CalcLengthOrPercentage { // FIXME(emilio): This is a bit of a hack that can disappear as soon as we share
// representation of LengthPercentage with Gecko. The issue here is that Gecko
// uses CalcValue to represent position components, so they always come back as
// was_calc == true, and we mess up in the transitions code.
//
// This was a pre-existing bug, though arguably so only in pretty obscure cases
// like calc(0px + 5%) and such.
impl PartialEq for LengthPercentage {
fn eq(&self, other: &Self) -> bool {
self.length == other.length && self.percentage == other.percentage
}
}
impl ComputeSquaredDistance for LengthPercentage {
#[inline] #[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {
// FIXME(nox): This looks incorrect to me, to add a distance between lengths // FIXME(nox): This looks incorrect to me, to add a distance between lengths
@ -89,24 +116,36 @@ impl ComputeSquaredDistance for CalcLengthOrPercentage {
} }
} }
impl CalcLengthOrPercentage { impl LengthPercentage {
/// Returns a new `CalcLengthOrPercentage`. /// Returns a new `LengthPercentage`.
#[inline] #[inline]
pub fn new(length: Length, percentage: Option<Percentage>) -> Self { pub fn new(length: Length, percentage: Option<Percentage>) -> Self {
Self::with_clamping_mode(length, percentage, AllowedNumericType::All) Self::with_clamping_mode(
length,
percentage,
AllowedNumericType::All,
/* was_calc = */ false,
)
} }
/// Returns a new `CalcLengthOrPercentage` with a specific clamping mode. /// Returns a new `LengthPercentage` with zero length and some percentage.
pub fn new_percent(percentage: Percentage) -> Self {
Self::new(Length::zero(), Some(percentage))
}
/// Returns a new `LengthPercentage` with a specific clamping mode.
#[inline] #[inline]
pub fn with_clamping_mode( pub fn with_clamping_mode(
length: Length, length: Length,
percentage: Option<Percentage>, percentage: Option<Percentage>,
clamping_mode: AllowedNumericType, clamping_mode: AllowedNumericType,
was_calc: bool,
) -> Self { ) -> Self {
Self { Self {
clamping_mode, clamping_mode,
length, length,
percentage, percentage,
was_calc,
} }
} }
@ -137,16 +176,31 @@ impl CalcLengthOrPercentage {
self.percentage.map_or(0., |p| p.0) self.percentage.map_or(0., |p| p.0)
} }
/// Returns the percentage component if this could be represented as a
/// non-calc percentage.
pub fn as_percentage(&self) -> Option<Percentage> {
if self.length.px() != 0. {
return None;
}
let p = self.percentage?;
if self.clamping_mode.clamp(p.0) != p.0 {
return None;
}
Some(p)
}
/// Convert the computed value into used value. /// Convert the computed value into used value.
#[inline] #[inline]
pub fn to_used_value(&self, container_len: Option<Au>) -> Option<Au> { pub fn maybe_to_used_value(&self, container_len: Option<Au>) -> Option<Au> {
self.to_pixel_length(container_len).map(Au::from) self.maybe_to_pixel_length(container_len).map(Au::from)
} }
/// If there are special rules for computing percentages in a value (e.g. /// If there are special rules for computing percentages in a value (e.g.
/// the height property), they apply whenever a calc() expression contains /// the height property), they apply whenever a calc() expression contains
/// percentages. /// percentages.
pub fn to_pixel_length(&self, container_len: Option<Au>) -> Option<Length> { pub fn maybe_to_pixel_length(&self, container_len: Option<Au>) -> Option<Length> {
match (container_len, self.percentage) { match (container_len, self.percentage) {
(Some(len), Some(percent)) => { (Some(len), Some(percent)) => {
let pixel = self.length.px() + len.scale_by(percent.0).to_f32_px(); let pixel = self.length.px() + len.scale_by(percent.0).to_f32_px();
@ -158,92 +212,23 @@ impl CalcLengthOrPercentage {
} }
} }
impl From<LengthOrPercentage> for CalcLengthOrPercentage { impl ToCss for LengthPercentage {
fn from(len: LengthOrPercentage) -> CalcLengthOrPercentage {
match len {
LengthOrPercentage::Percentage(this) => {
CalcLengthOrPercentage::new(Length::new(0.), Some(this))
},
LengthOrPercentage::Length(this) => CalcLengthOrPercentage::new(this, None),
LengthOrPercentage::Calc(this) => this,
}
}
}
impl From<LengthOrPercentageOrAuto> for Option<CalcLengthOrPercentage> {
fn from(len: LengthOrPercentageOrAuto) -> Option<CalcLengthOrPercentage> {
match len {
LengthOrPercentageOrAuto::Percentage(this) => {
Some(CalcLengthOrPercentage::new(Length::new(0.), Some(this)))
},
LengthOrPercentageOrAuto::Length(this) => Some(CalcLengthOrPercentage::new(this, None)),
LengthOrPercentageOrAuto::Calc(this) => Some(this),
LengthOrPercentageOrAuto::Auto => None,
}
}
}
impl From<LengthOrPercentageOrNone> for Option<CalcLengthOrPercentage> {
fn from(len: LengthOrPercentageOrNone) -> Option<CalcLengthOrPercentage> {
match len {
LengthOrPercentageOrNone::Percentage(this) => {
Some(CalcLengthOrPercentage::new(Length::new(0.), Some(this)))
},
LengthOrPercentageOrNone::Length(this) => Some(CalcLengthOrPercentage::new(this, None)),
LengthOrPercentageOrNone::Calc(this) => Some(this),
LengthOrPercentageOrNone::None => None,
}
}
}
impl ToCss for CalcLengthOrPercentage {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
W: Write, W: Write,
{ {
use num_traits::Zero; specified::LengthPercentage::from_computed_value(self).to_css(dest)
let length = self.unclamped_length();
match self.percentage {
Some(p) => {
if length.px() == 0. && self.clamping_mode.clamp(p.0) == p.0 {
return p.to_css(dest);
}
},
None => {
if self.clamping_mode.clamp(length.px()) == length.px() {
return length.to_css(dest);
}
},
}
dest.write_str("calc(")?;
if let Some(percentage) = self.percentage {
percentage.to_css(dest)?;
if length.px() != 0. {
dest.write_str(if length.px() < Zero::zero() {
" - "
} else {
" + "
})?;
length.abs().to_css(dest)?;
}
} else {
length.to_css(dest)?;
}
dest.write_str(")")
} }
} }
impl specified::CalcLengthOrPercentage { impl specified::CalcLengthPercentage {
/// Compute the value, zooming any absolute units by the zoom function. /// Compute the value, zooming any absolute units by the zoom function.
fn to_computed_value_with_zoom<F>( fn to_computed_value_with_zoom<F>(
&self, &self,
context: &Context, context: &Context,
zoom_fn: F, zoom_fn: F,
base_size: FontBaseSize, base_size: FontBaseSize,
) -> CalcLengthOrPercentage ) -> LengthPercentage
where where
F: Fn(Length) -> Length, F: Fn(Length) -> Length,
{ {
@ -277,10 +262,11 @@ impl specified::CalcLengthOrPercentage {
} }
} }
CalcLengthOrPercentage { LengthPercentage {
clamping_mode: self.clamping_mode, clamping_mode: self.clamping_mode,
length: Length::new(length.min(f32::MAX).max(f32::MIN)), length: Length::new(length.min(f32::MAX).max(f32::MIN)),
percentage: self.percentage, percentage: self.percentage,
was_calc: true,
} }
} }
@ -289,7 +275,7 @@ impl specified::CalcLengthOrPercentage {
&self, &self,
context: &Context, context: &Context,
base_size: FontBaseSize, base_size: FontBaseSize,
) -> CalcLengthOrPercentage { ) -> LengthPercentage {
self.to_computed_value_with_zoom( self.to_computed_value_with_zoom(
context, context,
|abs| context.maybe_zoom_text(abs.into()).0, |abs| context.maybe_zoom_text(abs.into()).0,
@ -323,17 +309,17 @@ impl specified::CalcLengthOrPercentage {
} }
} }
impl ToComputedValue for specified::CalcLengthOrPercentage { impl ToComputedValue for specified::CalcLengthPercentage {
type ComputedValue = CalcLengthOrPercentage; type ComputedValue = LengthPercentage;
fn to_computed_value(&self, context: &Context) -> CalcLengthOrPercentage { fn to_computed_value(&self, context: &Context) -> LengthPercentage {
// normal properties don't zoom, and compute em units against the current style's font-size // normal properties don't zoom, and compute em units against the current style's font-size
self.to_computed_value_with_zoom(context, |abs| abs, FontBaseSize::CurrentStyle) self.to_computed_value_with_zoom(context, |abs| abs, FontBaseSize::CurrentStyle)
} }
#[inline] #[inline]
fn from_computed_value(computed: &CalcLengthOrPercentage) -> Self { fn from_computed_value(computed: &LengthPercentage) -> Self {
specified::CalcLengthOrPercentage { specified::CalcLengthPercentage {
clamping_mode: computed.clamping_mode, clamping_mode: computed.clamping_mode,
absolute: Some(AbsoluteLength::from_computed_value(&computed.length)), absolute: Some(AbsoluteLength::from_computed_value(&computed.length)),
percentage: computed.percentage, percentage: computed.percentage,
@ -342,95 +328,33 @@ impl ToComputedValue for specified::CalcLengthOrPercentage {
} }
} }
#[allow(missing_docs)] impl LengthPercentage {
#[animate(fallback = "Self::animate_fallback")]
#[css(derive_debug)]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
MallocSizeOf,
PartialEq,
ToAnimatedValue,
ToAnimatedZero,
ToCss,
)]
#[distance(fallback = "Self::compute_squared_distance_fallback")]
pub enum LengthOrPercentage {
Length(Length),
Percentage(Percentage),
Calc(CalcLengthOrPercentage),
}
impl LengthOrPercentage {
/// <https://drafts.csswg.org/css-transitions/#animtype-lpcalc>
fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
// Special handling for zero values since these should not require calc().
if self.is_definitely_zero() {
return other.to_animated_zero()?.animate(other, procedure);
}
if other.is_definitely_zero() {
return self.animate(&self.to_animated_zero()?, procedure);
}
let this = CalcLengthOrPercentage::from(*self);
let other = CalcLengthOrPercentage::from(*other);
Ok(LengthOrPercentage::Calc(this.animate(&other, procedure)?))
}
#[inline]
fn compute_squared_distance_fallback(&self, other: &Self) -> Result<SquaredDistance, ()> {
CalcLengthOrPercentage::compute_squared_distance(&(*self).into(), &(*other).into())
}
}
impl From<Au> for LengthOrPercentage {
#[inline]
fn from(length: Au) -> Self {
LengthOrPercentage::Length(length.into())
}
}
impl LengthOrPercentage {
#[inline] #[inline]
#[allow(missing_docs)] #[allow(missing_docs)]
pub fn zero() -> LengthOrPercentage { pub fn zero() -> LengthPercentage {
LengthOrPercentage::Length(Length::new(0.)) LengthPercentage::new(Length::new(0.), None)
} }
#[inline]
/// 1px length value for SVG defaults /// 1px length value for SVG defaults
pub fn one() -> LengthOrPercentage { #[inline]
LengthOrPercentage::Length(Length::new(1.)) pub fn one() -> LengthPercentage {
LengthPercentage::new(Length::new(1.), None)
} }
/// Returns true if the computed value is absolute 0 or 0%. /// Returns true if the computed value is absolute 0 or 0%.
///
/// (Returns false for calc() values, even if ones that may resolve to zero.)
#[inline] #[inline]
pub fn is_definitely_zero(&self) -> bool { pub fn is_definitely_zero(&self) -> bool {
use self::LengthOrPercentage::*; self.unclamped_length().px() == 0.0 && self.percentage.map_or(true, |p| p.0 == 0.0)
match *self {
Length(l) => l.px() == 0.0,
Percentage(p) => p.0 == 0.0,
Calc(_) => false,
}
} }
// CSSFloat doesn't implement Hash, so does CSSPixelLength. Therefore, we still use Au as the // CSSFloat doesn't implement Hash, so does CSSPixelLength. Therefore, we still use Au as the
// hash key. // hash key.
#[allow(missing_docs)] #[allow(missing_docs)]
pub fn to_hash_key(&self) -> (Au, NotNan<f32>) { pub fn to_hash_key(&self) -> (Au, NotNan<f32>) {
use self::LengthOrPercentage::*; (
match *self { Au::from(self.unclamped_length()),
Length(l) => (Au::from(l), NotNan::new(0.0).unwrap()), NotNan::new(self.percentage()).unwrap(),
Percentage(p) => (Au(0), NotNan::new(p.0).unwrap()), )
Calc(c) => (
Au::from(c.unclamped_length()),
NotNan::new(c.percentage()).unwrap(),
),
}
} }
/// Returns the used value. /// Returns the used value.
@ -440,124 +364,118 @@ impl LengthOrPercentage {
/// Returns the used value as CSSPixelLength. /// Returns the used value as CSSPixelLength.
pub fn to_pixel_length(&self, containing_length: Au) -> Length { pub fn to_pixel_length(&self, containing_length: Au) -> Length {
match *self { self.maybe_to_pixel_length(Some(containing_length)).unwrap()
LengthOrPercentage::Length(length) => length,
LengthOrPercentage::Percentage(p) => containing_length.scale_by(p.0).into(),
LengthOrPercentage::Calc(ref calc) => {
calc.to_pixel_length(Some(containing_length)).unwrap()
},
}
} }
/// Returns the clamped non-negative values. /// Returns the clamped non-negative values.
///
/// TODO(emilio): It's a bit unfortunate that this depends on whether the
/// value was a `calc()` value or not. Should it?
#[inline] #[inline]
pub fn clamp_to_non_negative(self) -> Self { pub fn clamp_to_non_negative(self) -> Self {
match self { if self.was_calc {
LengthOrPercentage::Length(length) => { return Self::with_clamping_mode(
LengthOrPercentage::Length(length.clamp_to_non_negative()) self.length,
}, self.percentage,
LengthOrPercentage::Percentage(percentage) => { AllowedNumericType::NonNegative,
LengthOrPercentage::Percentage(percentage.clamp_to_non_negative()) self.was_calc,
}, );
_ => self,
}
}
}
impl ToComputedValue for specified::LengthOrPercentage {
type ComputedValue = LengthOrPercentage;
fn to_computed_value(&self, context: &Context) -> LengthOrPercentage {
match *self {
specified::LengthOrPercentage::Length(ref value) => {
LengthOrPercentage::Length(value.to_computed_value(context))
},
specified::LengthOrPercentage::Percentage(value) => {
LengthOrPercentage::Percentage(value)
},
specified::LengthOrPercentage::Calc(ref calc) => {
LengthOrPercentage::Calc((**calc).to_computed_value(context))
},
}
} }
fn from_computed_value(computed: &LengthOrPercentage) -> Self { debug_assert!(self.percentage.is_none() || self.unclamped_length() == Length::zero());
match *computed { if let Some(p) = self.percentage {
LengthOrPercentage::Length(value) => { return Self::with_clamping_mode(
specified::LengthOrPercentage::Length(ToComputedValue::from_computed_value(&value)) Length::zero(),
}, Some(p.clamp_to_non_negative()),
LengthOrPercentage::Percentage(value) => { AllowedNumericType::NonNegative,
specified::LengthOrPercentage::Percentage(value) self.was_calc,
}, );
LengthOrPercentage::Calc(ref calc) => specified::LengthOrPercentage::Calc(Box::new(
ToComputedValue::from_computed_value(calc),
)),
}
}
}
impl IsZeroLength for LengthOrPercentage {
#[inline]
fn is_zero_length(&self) -> bool {
match *self {
LengthOrPercentage::Length(l) => l.0 == 0.0,
LengthOrPercentage::Percentage(p) => p.0 == 0.0,
LengthOrPercentage::Calc(c) => c.unclamped_length().0 == 0.0 && c.percentage() == 0.0,
}
}
}
#[allow(missing_docs)]
#[animate(fallback = "Self::animate_fallback")]
#[css(derive_debug)]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, MallocSizeOf, PartialEq, ToCss)]
#[distance(fallback = "Self::compute_squared_distance_fallback")]
pub enum LengthOrPercentageOrAuto {
Length(Length),
Percentage(Percentage),
Auto,
Calc(CalcLengthOrPercentage),
}
impl LengthOrPercentageOrAuto {
/// <https://drafts.csswg.org/css-transitions/#animtype-lpcalc>
fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
let this = <Option<CalcLengthOrPercentage>>::from(*self);
let other = <Option<CalcLengthOrPercentage>>::from(*other);
Ok(LengthOrPercentageOrAuto::Calc(
this.animate(&other, procedure)?.ok_or(())?,
))
} }
#[inline] Self::with_clamping_mode(
fn compute_squared_distance_fallback(&self, other: &Self) -> Result<SquaredDistance, ()> { self.length.clamp_to_non_negative(),
<Option<CalcLengthOrPercentage>>::compute_squared_distance( None,
&(*self).into(), AllowedNumericType::NonNegative,
&(*other).into(), self.was_calc,
) )
} }
} }
/// A wrapper of LengthOrPercentageOrAuto, whose value must be >= 0. impl ToComputedValue for specified::LengthPercentage {
pub type NonNegativeLengthOrPercentageOrAuto = NonNegative<LengthOrPercentageOrAuto>; type ComputedValue = LengthPercentage;
impl IsAuto for NonNegativeLengthOrPercentageOrAuto { fn to_computed_value(&self, context: &Context) -> LengthPercentage {
match *self {
specified::LengthPercentage::Length(ref value) => {
LengthPercentage::new(value.to_computed_value(context), None)
},
specified::LengthPercentage::Percentage(value) => LengthPercentage::new_percent(value),
specified::LengthPercentage::Calc(ref calc) => (**calc).to_computed_value(context),
}
}
fn from_computed_value(computed: &LengthPercentage) -> Self {
let length = computed.unclamped_length();
if let Some(p) = computed.as_percentage() {
return specified::LengthPercentage::Percentage(p);
}
let percentage = computed.percentage;
if percentage.is_none() && computed.clamping_mode.clamp(length.px()) == length.px() {
return specified::LengthPercentage::Length(ToComputedValue::from_computed_value(
&length,
));
}
specified::LengthPercentage::Calc(Box::new(ToComputedValue::from_computed_value(computed)))
}
}
impl IsZeroLength for LengthPercentage {
#[inline]
fn is_zero_length(&self) -> bool {
self.is_definitely_zero()
}
}
#[allow(missing_docs)]
#[css(derive_debug)]
#[derive(
Animate, Clone, ComputeSquaredDistance, Copy, MallocSizeOf, PartialEq, ToAnimatedZero, ToCss,
)]
pub enum LengthPercentageOrAuto {
LengthPercentage(LengthPercentage),
Auto,
}
impl LengthPercentageOrAuto {
/// Returns the `0` value.
#[inline]
pub fn zero() -> Self {
LengthPercentageOrAuto::LengthPercentage(LengthPercentage::zero())
}
}
/// A wrapper of LengthPercentageOrAuto, whose value must be >= 0.
pub type NonNegativeLengthPercentageOrAuto = NonNegative<LengthPercentageOrAuto>;
impl IsAuto for NonNegativeLengthPercentageOrAuto {
#[inline] #[inline]
fn is_auto(&self) -> bool { fn is_auto(&self) -> bool {
*self == Self::auto() *self == Self::auto()
} }
} }
impl NonNegativeLengthOrPercentageOrAuto { impl NonNegativeLengthPercentageOrAuto {
/// `auto` /// `auto`
#[inline] #[inline]
pub fn auto() -> Self { pub fn auto() -> Self {
NonNegative(LengthOrPercentageOrAuto::Auto) NonNegative(LengthPercentageOrAuto::Auto)
} }
} }
impl ToAnimatedValue for NonNegativeLengthOrPercentageOrAuto { impl ToAnimatedValue for NonNegativeLengthPercentageOrAuto {
type AnimatedValue = LengthOrPercentageOrAuto; type AnimatedValue = LengthPercentageOrAuto;
#[inline] #[inline]
fn to_animated_value(self) -> Self::AnimatedValue { fn to_animated_value(self) -> Self::AnimatedValue {
@ -570,190 +488,154 @@ impl ToAnimatedValue for NonNegativeLengthOrPercentageOrAuto {
} }
} }
impl LengthOrPercentageOrAuto { impl LengthPercentageOrAuto {
/// Returns true if the computed value is absolute 0 or 0%. /// Returns true if the computed value is absolute 0 or 0%.
///
/// (Returns false for calc() values, even if ones that may resolve to zero.)
#[inline] #[inline]
pub fn is_definitely_zero(&self) -> bool { pub fn is_definitely_zero(&self) -> bool {
use self::LengthOrPercentageOrAuto::*; use self::LengthPercentageOrAuto::*;
match *self { match *self {
Length(l) => l.px() == 0.0, LengthPercentage(ref l) => l.is_definitely_zero(),
Percentage(p) => p.0 == 0.0, Auto => false,
Calc(_) | Auto => false,
} }
} }
fn clamp_to_non_negative(self) -> Self { /// Clamps the value to a non-negative value.
use self::LengthOrPercentageOrAuto::*; pub fn clamp_to_non_negative(self) -> Self {
use self::LengthPercentageOrAuto::*;
match self { match self {
Length(l) => Length(l.clamp_to_non_negative()), LengthPercentage(l) => LengthPercentage(l.clamp_to_non_negative()),
Percentage(p) => Percentage(p.clamp_to_non_negative()), Auto => Auto,
_ => self,
} }
} }
} }
impl ToComputedValue for specified::LengthOrPercentageOrAuto { impl ToComputedValue for specified::LengthPercentageOrAuto {
type ComputedValue = LengthOrPercentageOrAuto; type ComputedValue = LengthPercentageOrAuto;
#[inline] #[inline]
fn to_computed_value(&self, context: &Context) -> LengthOrPercentageOrAuto { fn to_computed_value(&self, context: &Context) -> LengthPercentageOrAuto {
match *self { match *self {
specified::LengthOrPercentageOrAuto::Length(ref value) => { specified::LengthPercentageOrAuto::LengthPercentage(ref value) => {
LengthOrPercentageOrAuto::Length(value.to_computed_value(context)) LengthPercentageOrAuto::LengthPercentage(value.to_computed_value(context))
},
specified::LengthOrPercentageOrAuto::Percentage(value) => {
LengthOrPercentageOrAuto::Percentage(value)
},
specified::LengthOrPercentageOrAuto::Auto => LengthOrPercentageOrAuto::Auto,
specified::LengthOrPercentageOrAuto::Calc(ref calc) => {
LengthOrPercentageOrAuto::Calc((**calc).to_computed_value(context))
}, },
specified::LengthPercentageOrAuto::Auto => LengthPercentageOrAuto::Auto,
} }
} }
#[inline] #[inline]
fn from_computed_value(computed: &LengthOrPercentageOrAuto) -> Self { fn from_computed_value(computed: &LengthPercentageOrAuto) -> Self {
match *computed { match *computed {
LengthOrPercentageOrAuto::Auto => specified::LengthOrPercentageOrAuto::Auto, LengthPercentageOrAuto::Auto => specified::LengthPercentageOrAuto::Auto,
LengthOrPercentageOrAuto::Length(value) => specified::LengthOrPercentageOrAuto::Length( LengthPercentageOrAuto::LengthPercentage(ref value) => {
ToComputedValue::from_computed_value(&value), specified::LengthPercentageOrAuto::LengthPercentage(
), ToComputedValue::from_computed_value(value),
LengthOrPercentageOrAuto::Percentage(value) => { )
specified::LengthOrPercentageOrAuto::Percentage(value)
}, },
LengthOrPercentageOrAuto::Calc(calc) => specified::LengthOrPercentageOrAuto::Calc(
Box::new(ToComputedValue::from_computed_value(&calc)),
),
} }
} }
} }
#[allow(missing_docs)] #[allow(missing_docs)]
#[animate(fallback = "Self::animate_fallback")]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
#[css(derive_debug)] #[css(derive_debug)]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, PartialEq, ToCss)] #[derive(
#[distance(fallback = "Self::compute_squared_distance_fallback")] Animate, Clone, ComputeSquaredDistance, Copy, MallocSizeOf, PartialEq, ToAnimatedZero, ToCss,
pub enum LengthOrPercentageOrNone { )]
Length(Length), pub enum LengthPercentageOrNone {
Percentage(Percentage), LengthPercentage(LengthPercentage),
Calc(CalcLengthOrPercentage),
None, None,
} }
impl LengthOrPercentageOrNone { impl LengthPercentageOrNone {
/// <https://drafts.csswg.org/css-transitions/#animtype-lpcalc>
fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
let this = <Option<CalcLengthOrPercentage>>::from(*self);
let other = <Option<CalcLengthOrPercentage>>::from(*other);
Ok(LengthOrPercentageOrNone::Calc(
this.animate(&other, procedure)?.ok_or(())?,
))
}
fn compute_squared_distance_fallback(&self, other: &Self) -> Result<SquaredDistance, ()> {
<Option<CalcLengthOrPercentage>>::compute_squared_distance(
&(*self).into(),
&(*other).into(),
)
}
}
impl LengthOrPercentageOrNone {
/// Returns the used value. /// Returns the used value.
pub fn to_used_value(&self, containing_length: Au) -> Option<Au> { pub fn to_used_value(&self, containing_length: Au) -> Option<Au> {
match *self { match *self {
LengthOrPercentageOrNone::None => None, LengthPercentageOrNone::None => None,
LengthOrPercentageOrNone::Length(length) => Some(Au::from(length)), LengthPercentageOrNone::LengthPercentage(ref lp) => {
LengthOrPercentageOrNone::Percentage(percent) => { Some(lp.to_used_value(containing_length))
Some(containing_length.scale_by(percent.0))
}, },
LengthOrPercentageOrNone::Calc(ref calc) => calc.to_used_value(Some(containing_length)),
} }
} }
} }
impl ToComputedValue for specified::LengthOrPercentageOrNone { // FIXME(emilio): Derive this.
type ComputedValue = LengthOrPercentageOrNone; impl ToComputedValue for specified::LengthPercentageOrNone {
type ComputedValue = LengthPercentageOrNone;
#[inline] #[inline]
fn to_computed_value(&self, context: &Context) -> LengthOrPercentageOrNone { fn to_computed_value(&self, context: &Context) -> LengthPercentageOrNone {
match *self { match *self {
specified::LengthOrPercentageOrNone::Length(ref value) => { specified::LengthPercentageOrNone::LengthPercentage(ref value) => {
LengthOrPercentageOrNone::Length(value.to_computed_value(context)) LengthPercentageOrNone::LengthPercentage(value.to_computed_value(context))
}, },
specified::LengthOrPercentageOrNone::Percentage(value) => { specified::LengthPercentageOrNone::None => LengthPercentageOrNone::None,
LengthOrPercentageOrNone::Percentage(value)
},
specified::LengthOrPercentageOrNone::Calc(ref calc) => {
LengthOrPercentageOrNone::Calc((**calc).to_computed_value(context))
},
specified::LengthOrPercentageOrNone::None => LengthOrPercentageOrNone::None,
} }
} }
#[inline] #[inline]
fn from_computed_value(computed: &LengthOrPercentageOrNone) -> Self { fn from_computed_value(computed: &LengthPercentageOrNone) -> Self {
match *computed { match *computed {
LengthOrPercentageOrNone::None => specified::LengthOrPercentageOrNone::None, LengthPercentageOrNone::None => specified::LengthPercentageOrNone::None,
LengthOrPercentageOrNone::Length(value) => specified::LengthOrPercentageOrNone::Length( LengthPercentageOrNone::LengthPercentage(value) => {
specified::LengthPercentageOrNone::LengthPercentage(
ToComputedValue::from_computed_value(&value), ToComputedValue::from_computed_value(&value),
), )
LengthOrPercentageOrNone::Percentage(value) => {
specified::LengthOrPercentageOrNone::Percentage(value)
}, },
LengthOrPercentageOrNone::Calc(calc) => specified::LengthOrPercentageOrNone::Calc(
Box::new(ToComputedValue::from_computed_value(&calc)),
),
} }
} }
} }
/// A wrapper of LengthOrPercentage, whose value must be >= 0. /// A wrapper of LengthPercentage, whose value must be >= 0.
pub type NonNegativeLengthOrPercentage = NonNegative<LengthOrPercentage>; pub type NonNegativeLengthPercentage = NonNegative<LengthPercentage>;
impl ToAnimatedValue for NonNegativeLengthOrPercentage { impl ToAnimatedValue for NonNegativeLengthPercentage {
type AnimatedValue = LengthOrPercentage; type AnimatedValue = LengthPercentage;
#[inline] #[inline]
fn to_animated_value(self) -> Self::AnimatedValue { fn to_animated_value(self) -> Self::AnimatedValue {
self.into() self.0
} }
#[inline] #[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self { fn from_animated_value(animated: Self::AnimatedValue) -> Self {
animated.clamp_to_non_negative().into() NonNegative(animated.clamp_to_non_negative())
} }
} }
impl From<NonNegativeLength> for NonNegativeLengthOrPercentage { impl From<NonNegativeLength> for NonNegativeLengthPercentage {
#[inline] #[inline]
fn from(length: NonNegativeLength) -> Self { fn from(length: NonNegativeLength) -> Self {
LengthOrPercentage::Length(length.0).into() LengthPercentage::new(length.0, None).into()
} }
} }
impl From<LengthOrPercentage> for NonNegativeLengthOrPercentage { impl From<LengthPercentage> for NonNegativeLengthPercentage {
#[inline] #[inline]
fn from(lop: LengthOrPercentage) -> Self { fn from(lp: LengthPercentage) -> Self {
NonNegative::<LengthOrPercentage>(lop) NonNegative::<LengthPercentage>(lp)
} }
} }
impl From<NonNegativeLengthOrPercentage> for LengthOrPercentage { impl From<NonNegativeLengthPercentage> for LengthPercentage {
#[inline] #[inline]
fn from(lop: NonNegativeLengthOrPercentage) -> LengthOrPercentage { fn from(lp: NonNegativeLengthPercentage) -> LengthPercentage {
lop.0 lp.0
} }
} }
impl NonNegativeLengthOrPercentage { // TODO(emilio): This is a really generic impl which is only needed to implement
// Animated and co for Spacing<>. Get rid of this, probably?
impl From<Au> for LengthPercentage {
#[inline]
fn from(length: Au) -> Self {
LengthPercentage::new(length.into(), None)
}
}
impl NonNegativeLengthPercentage {
/// Get zero value. /// Get zero value.
#[inline] #[inline]
pub fn zero() -> Self { pub fn zero() -> Self {
NonNegative::<LengthOrPercentage>(LengthOrPercentage::zero()) NonNegative::<LengthPercentage>(LengthPercentage::zero())
} }
/// Returns true if the computed value is absolute 0 or 0%. /// Returns true if the computed value is absolute 0 or 0%.
@ -798,11 +680,6 @@ impl CSSPixelLength {
self.0 self.0
} }
#[inline]
fn clamp_to_non_negative(self) -> Self {
Self::new(self.px().max(0.))
}
/// Return the length with app_unit i32 type. /// Return the length with app_unit i32 type.
#[inline] #[inline]
pub fn to_i32_au(&self) -> i32 { pub fn to_i32_au(&self) -> i32 {
@ -810,11 +687,19 @@ impl CSSPixelLength {
} }
/// Return the absolute value of this length. /// Return the absolute value of this length.
#[inline]
pub fn abs(self) -> Self { pub fn abs(self) -> Self {
CSSPixelLength::new(self.0.abs()) CSSPixelLength::new(self.0.abs())
} }
/// Return the clamped value of this length.
#[inline]
pub fn clamp_to_non_negative(self) -> Self {
CSSPixelLength::new(self.0.max(0.))
}
/// Zero value /// Zero value
#[inline]
pub fn zero() -> Self { pub fn zero() -> Self {
CSSPixelLength::new(0.) CSSPixelLength::new(0.)
} }
@ -963,8 +848,8 @@ pub type NonNegativeLengthOrAuto = Either<NonNegativeLength, Auto>;
/// Either a computed NonNegativeLength or the `normal` keyword. /// Either a computed NonNegativeLength or the `normal` keyword.
pub type NonNegativeLengthOrNormal = Either<NonNegativeLength, Normal>; pub type NonNegativeLengthOrNormal = Either<NonNegativeLength, Normal>;
/// Either a computed NonNegativeLengthOrPercentage or the `normal` keyword. /// Either a computed NonNegativeLengthPercentage or the `normal` keyword.
pub type NonNegativeLengthOrPercentageOrNormal = Either<NonNegativeLengthOrPercentage, Normal>; pub type NonNegativeLengthPercentageOrNormal = Either<NonNegativeLengthPercentage, Normal>;
/// A type for possible values for min- and max- flavors of width, height, /// A type for possible values for min- and max- flavors of width, height,
/// block-size, and inline-size. /// block-size, and inline-size.
@ -994,23 +879,23 @@ pub enum ExtremumLength {
} }
/// A computed value for `min-width`, `min-height`, `width` or `height` property. /// A computed value for `min-width`, `min-height`, `width` or `height` property.
pub type MozLength = GenericMozLength<LengthOrPercentageOrAuto>; pub type MozLength = GenericMozLength<LengthPercentageOrAuto>;
impl MozLength { impl MozLength {
/// Returns the `auto` value. /// Returns the `auto` value.
#[inline] #[inline]
pub fn auto() -> Self { pub fn auto() -> Self {
GenericMozLength::LengthOrPercentageOrAuto(LengthOrPercentageOrAuto::Auto) GenericMozLength::LengthPercentageOrAuto(LengthPercentageOrAuto::Auto)
} }
} }
/// A computed value for `max-width` or `min-height` property. /// A computed value for `max-width` or `min-height` property.
pub type MaxLength = GenericMaxLength<LengthOrPercentageOrNone>; pub type MaxLength = GenericMaxLength<LengthPercentageOrNone>;
impl MaxLength { impl MaxLength {
/// Returns the `none` value. /// Returns the `none` value.
#[inline] #[inline]
pub fn none() -> Self { pub fn none() -> Self {
GenericMaxLength::LengthOrPercentageOrNone(LengthOrPercentageOrNone::None) GenericMaxLength::LengthPercentageOrNone(LengthPercentageOrNone::None)
} }
} }

View file

@ -62,9 +62,9 @@ pub use self::font::{MozScriptLevel, MozScriptMinSize, MozScriptSizeMultiplier,
pub use self::gecko::ScrollSnapPoint; pub use self::gecko::ScrollSnapPoint;
pub use self::image::{Gradient, GradientItem, Image, ImageLayer, LineDirection, MozImageRect}; pub use self::image::{Gradient, GradientItem, Image, ImageLayer, LineDirection, MozImageRect};
pub use self::length::{CSSPixelLength, ExtremumLength, NonNegativeLength}; pub use self::length::{CSSPixelLength, ExtremumLength, NonNegativeLength};
pub use self::length::{CalcLengthOrPercentage, Length, LengthOrNumber, LengthOrPercentage}; pub use self::length::{Length, LengthOrNumber, LengthPercentage};
pub use self::length::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone, MaxLength, MozLength}; pub use self::length::{LengthPercentageOrAuto, LengthPercentageOrNone, MaxLength, MozLength};
pub use self::length::{NonNegativeLengthOrPercentage, NonNegativeLengthOrPercentageOrAuto}; pub use self::length::{NonNegativeLengthPercentage, NonNegativeLengthPercentageOrAuto};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
pub use self::list::ListStyleType; pub use self::list::ListStyleType;
pub use self::list::{QuotePair, Quotes}; pub use self::list::{QuotePair, Quotes};
@ -689,20 +689,20 @@ impl ToCss for ClipRect {
pub type ClipRectOrAuto = Either<ClipRect, Auto>; pub type ClipRectOrAuto = Either<ClipRect, Auto>;
/// The computed value of a grid `<track-breadth>` /// The computed value of a grid `<track-breadth>`
pub type TrackBreadth = GenericTrackBreadth<LengthOrPercentage>; pub type TrackBreadth = GenericTrackBreadth<LengthPercentage>;
/// The computed value of a grid `<track-size>` /// The computed value of a grid `<track-size>`
pub type TrackSize = GenericTrackSize<LengthOrPercentage>; pub type TrackSize = GenericTrackSize<LengthPercentage>;
/// The computed value of a grid `<track-list>` /// The computed value of a grid `<track-list>`
/// (could also be `<auto-track-list>` or `<explicit-track-list>`) /// (could also be `<auto-track-list>` or `<explicit-track-list>`)
pub type TrackList = GenericTrackList<LengthOrPercentage, Integer>; pub type TrackList = GenericTrackList<LengthPercentage, Integer>;
/// The computed value of a `<grid-line>`. /// The computed value of a `<grid-line>`.
pub type GridLine = GenericGridLine<Integer>; pub type GridLine = GenericGridLine<Integer>;
/// `<grid-template-rows> | <grid-template-columns>` /// `<grid-template-rows> | <grid-template-columns>`
pub type GridTemplateComponent = GenericGridTemplateComponent<LengthOrPercentage, Integer>; pub type GridTemplateComponent = GenericGridTemplateComponent<LengthPercentage, Integer>;
impl ClipRectOrAuto { impl ClipRectOrAuto {
/// Return an auto (default for clip-rect and image-region) value /// Return an auto (default for clip-rect and image-region) value

View file

@ -7,7 +7,7 @@
//! //!
//! [position]: https://drafts.csswg.org/css-backgrounds-3/#position //! [position]: https://drafts.csswg.org/css-backgrounds-3/#position
use crate::values::computed::{Integer, LengthOrPercentage, Percentage}; use crate::values::computed::{Integer, LengthPercentage, Percentage};
use crate::values::generics::position::Position as GenericPosition; use crate::values::generics::position::Position as GenericPosition;
use crate::values::generics::position::ZIndex as GenericZIndex; use crate::values::generics::position::ZIndex as GenericZIndex;
pub use crate::values::specified::position::{GridAutoFlow, GridTemplateAreas}; pub use crate::values::specified::position::{GridAutoFlow, GridTemplateAreas};
@ -18,25 +18,25 @@ use style_traits::{CssWriter, ToCss};
pub type Position = GenericPosition<HorizontalPosition, VerticalPosition>; pub type Position = GenericPosition<HorizontalPosition, VerticalPosition>;
/// The computed value of a CSS horizontal position. /// The computed value of a CSS horizontal position.
pub type HorizontalPosition = LengthOrPercentage; pub type HorizontalPosition = LengthPercentage;
/// The computed value of a CSS vertical position. /// The computed value of a CSS vertical position.
pub type VerticalPosition = LengthOrPercentage; pub type VerticalPosition = LengthPercentage;
impl Position { impl Position {
/// `50% 50%` /// `50% 50%`
#[inline] #[inline]
pub fn center() -> Self { pub fn center() -> Self {
Self::new( Self::new(
LengthOrPercentage::Percentage(Percentage(0.5)), LengthPercentage::new_percent(Percentage(0.5)),
LengthOrPercentage::Percentage(Percentage(0.5)), LengthPercentage::new_percent(Percentage(0.5)),
) )
} }
/// `0% 0%` /// `0% 0%`
#[inline] #[inline]
pub fn zero() -> Self { pub fn zero() -> Self {
Self::new(LengthOrPercentage::zero(), LengthOrPercentage::zero()) Self::new(LengthPercentage::zero(), LengthPercentage::zero())
} }
} }

View file

@ -6,7 +6,7 @@
use crate::values::computed::color::Color; use crate::values::computed::color::Color;
use crate::values::computed::url::ComputedUrl; use crate::values::computed::url::ComputedUrl;
use crate::values::computed::{LengthOrPercentage, NonNegativeLengthOrPercentage}; use crate::values::computed::{LengthPercentage, NonNegativeLengthPercentage};
use crate::values::computed::{NonNegativeNumber, Number, Opacity}; use crate::values::computed::{NonNegativeNumber, Number, Opacity};
use crate::values::generics::svg as generic; use crate::values::generics::svg as generic;
use crate::values::RGBA; use crate::values::RGBA;
@ -42,56 +42,56 @@ impl SVGPaint {
/// A value of <length> | <percentage> | <number> for stroke-dashoffset. /// A value of <length> | <percentage> | <number> for stroke-dashoffset.
/// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties>
pub type SvgLengthOrPercentageOrNumber = pub type SvgLengthPercentageOrNumber =
generic::SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number>; generic::SvgLengthPercentageOrNumber<LengthPercentage, Number>;
/// <length> | <percentage> | <number> | context-value /// <length> | <percentage> | <number> | context-value
pub type SVGLength = generic::SVGLength<SvgLengthOrPercentageOrNumber>; pub type SVGLength = generic::SVGLength<SvgLengthPercentageOrNumber>;
impl SVGLength { impl SVGLength {
/// `0px` /// `0px`
pub fn zero() -> Self { pub fn zero() -> Self {
generic::SVGLength::Length(generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage( generic::SVGLength::Length(generic::SvgLengthPercentageOrNumber::LengthPercentage(
LengthOrPercentage::zero(), LengthPercentage::zero(),
)) ))
} }
} }
/// A value of <length> | <percentage> | <number> for stroke-width/stroke-dasharray. /// A value of <length> | <percentage> | <number> for stroke-width/stroke-dasharray.
/// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties>
pub type NonNegativeSvgLengthOrPercentageOrNumber = pub type NonNegativeSvgLengthPercentageOrNumber =
generic::SvgLengthOrPercentageOrNumber<NonNegativeLengthOrPercentage, NonNegativeNumber>; generic::SvgLengthPercentageOrNumber<NonNegativeLengthPercentage, NonNegativeNumber>;
// FIXME(emilio): This is really hacky, and can go away with a bit of work on // FIXME(emilio): This is really hacky, and can go away with a bit of work on
// the clone_stroke_width code in gecko.mako.rs. // the clone_stroke_width code in gecko.mako.rs.
impl Into<NonNegativeSvgLengthOrPercentageOrNumber> for SvgLengthOrPercentageOrNumber { impl Into<NonNegativeSvgLengthPercentageOrNumber> for SvgLengthPercentageOrNumber {
fn into(self) -> NonNegativeSvgLengthOrPercentageOrNumber { fn into(self) -> NonNegativeSvgLengthPercentageOrNumber {
match self { match self {
generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop) => { generic::SvgLengthPercentageOrNumber::LengthPercentage(lop) => {
generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop.into()) generic::SvgLengthPercentageOrNumber::LengthPercentage(lop.into())
}, },
generic::SvgLengthOrPercentageOrNumber::Number(num) => { generic::SvgLengthPercentageOrNumber::Number(num) => {
generic::SvgLengthOrPercentageOrNumber::Number(num.into()) generic::SvgLengthPercentageOrNumber::Number(num.into())
}, },
} }
} }
} }
/// An non-negative wrapper of SVGLength. /// An non-negative wrapper of SVGLength.
pub type SVGWidth = generic::SVGLength<NonNegativeSvgLengthOrPercentageOrNumber>; pub type SVGWidth = generic::SVGLength<NonNegativeSvgLengthPercentageOrNumber>;
impl SVGWidth { impl SVGWidth {
/// `1px`. /// `1px`.
pub fn one() -> Self { pub fn one() -> Self {
use crate::values::generics::NonNegative; use crate::values::generics::NonNegative;
generic::SVGLength::Length(generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage( generic::SVGLength::Length(generic::SvgLengthPercentageOrNumber::LengthPercentage(
NonNegative(LengthOrPercentage::one()), NonNegative(LengthPercentage::one()),
)) ))
} }
} }
/// [ <length> | <percentage> | <number> ]# | context-value /// [ <length> | <percentage> | <number> ]# | context-value
pub type SVGStrokeDashArray = generic::SVGStrokeDashArray<NonNegativeSvgLengthOrPercentageOrNumber>; pub type SVGStrokeDashArray = generic::SVGStrokeDashArray<NonNegativeSvgLengthPercentageOrNumber>;
impl Default for SVGStrokeDashArray { impl Default for SVGStrokeDashArray {
fn default() -> Self { fn default() -> Self {

View file

@ -6,7 +6,7 @@
#[cfg(feature = "servo")] #[cfg(feature = "servo")]
use crate::properties::StyleBuilder; use crate::properties::StyleBuilder;
use crate::values::computed::length::{Length, LengthOrPercentage}; use crate::values::computed::length::{Length, LengthPercentage};
use crate::values::computed::{NonNegativeLength, NonNegativeNumber}; use crate::values::computed::{NonNegativeLength, NonNegativeNumber};
use crate::values::generics::text::InitialLetter as GenericInitialLetter; use crate::values::generics::text::InitialLetter as GenericInitialLetter;
use crate::values::generics::text::LineHeight as GenericLineHeight; use crate::values::generics::text::LineHeight as GenericLineHeight;
@ -29,7 +29,7 @@ pub type InitialLetter = GenericInitialLetter<CSSFloat, CSSInteger>;
pub type LetterSpacing = Spacing<Length>; pub type LetterSpacing = Spacing<Length>;
/// A computed value for the `word-spacing` property. /// A computed value for the `word-spacing` property.
pub type WordSpacing = Spacing<LengthOrPercentage>; pub type WordSpacing = Spacing<LengthPercentage>;
/// A computed value for the `line-height` property. /// A computed value for the `line-height` property.
pub type LineHeight = GenericLineHeight<NonNegativeNumber, NonNegativeLength>; pub type LineHeight = GenericLineHeight<NonNegativeNumber, NonNegativeLength>;

View file

@ -7,7 +7,7 @@
use super::CSSFloat; use super::CSSFloat;
use crate::values::animated::transform::{Perspective, Scale3D, Translate3D}; use crate::values::animated::transform::{Perspective, Scale3D, Translate3D};
use crate::values::animated::ToAnimatedZero; use crate::values::animated::ToAnimatedZero;
use crate::values::computed::{Angle, Integer, Length, LengthOrPercentage, Number, Percentage}; use crate::values::computed::{Angle, Integer, Length, LengthPercentage, Number, Percentage};
use crate::values::generics::transform as generic; use crate::values::generics::transform as generic;
use euclid::{Transform3D, Vector3D}; use euclid::{Transform3D, Vector3D};
use num_traits::Zero; use num_traits::Zero;
@ -16,12 +16,12 @@ pub use crate::values::generics::transform::TransformStyle;
/// A single operation in a computed CSS `transform` /// A single operation in a computed CSS `transform`
pub type TransformOperation = pub type TransformOperation =
generic::TransformOperation<Angle, Number, Length, Integer, LengthOrPercentage>; generic::TransformOperation<Angle, Number, Length, Integer, LengthPercentage>;
/// A computed CSS `transform` /// A computed CSS `transform`
pub type Transform = generic::Transform<TransformOperation>; pub type Transform = generic::Transform<TransformOperation>;
/// The computed value of a CSS `<transform-origin>` /// The computed value of a CSS `<transform-origin>`
pub type TransformOrigin = generic::TransformOrigin<LengthOrPercentage, LengthOrPercentage, Length>; pub type TransformOrigin = generic::TransformOrigin<LengthPercentage, LengthPercentage, Length>;
/// A vector to represent the direction vector (rotate axis) for Rotate3D. /// A vector to represent the direction vector (rotate axis) for Rotate3D.
pub type DirectionVector = Vector3D<CSSFloat>; pub type DirectionVector = Vector3D<CSSFloat>;
@ -31,8 +31,8 @@ impl TransformOrigin {
#[inline] #[inline]
pub fn initial_value() -> Self { pub fn initial_value() -> Self {
Self::new( Self::new(
LengthOrPercentage::Percentage(Percentage(0.5)), LengthPercentage::new_percent(Percentage(0.5)),
LengthOrPercentage::Percentage(Percentage(0.5)), LengthPercentage::new_percent(Percentage(0.5)),
Length::new(0.), Length::new(0.),
) )
} }
@ -374,7 +374,7 @@ impl TransformOperation {
generic::TransformOperation::Translate(ref x, None) => { generic::TransformOperation::Translate(ref x, None) => {
generic::TransformOperation::Translate3D( generic::TransformOperation::Translate3D(
x.clone(), x.clone(),
LengthOrPercentage::zero(), LengthPercentage::zero(),
Length::zero(), Length::zero(),
) )
}, },
@ -383,15 +383,15 @@ impl TransformOperation {
}, },
generic::TransformOperation::TranslateY(ref y) => { generic::TransformOperation::TranslateY(ref y) => {
generic::TransformOperation::Translate3D( generic::TransformOperation::Translate3D(
LengthOrPercentage::zero(), LengthPercentage::zero(),
y.clone(), y.clone(),
Length::zero(), Length::zero(),
) )
}, },
generic::TransformOperation::TranslateZ(ref z) => { generic::TransformOperation::TranslateZ(ref z) => {
generic::TransformOperation::Translate3D( generic::TransformOperation::Translate3D(
LengthOrPercentage::zero(), LengthPercentage::zero(),
LengthOrPercentage::zero(), LengthPercentage::zero(),
z.clone(), z.clone(),
) )
}, },
@ -576,7 +576,7 @@ impl Rotate {
} }
/// A computed CSS `translate` /// A computed CSS `translate`
pub type Translate = generic::Translate<LengthOrPercentage, Length>; pub type Translate = generic::Translate<LengthPercentage, Length>;
impl Translate { impl Translate {
/// Convert TransformOperation to Translate. /// Convert TransformOperation to Translate.

View file

@ -22,13 +22,13 @@ use style_traits::{CssWriter, ToCss};
ToAnimatedZero, ToAnimatedZero,
ToComputedValue, ToComputedValue,
)] )]
pub enum BackgroundSize<LengthOrPercentageOrAuto> { pub enum BackgroundSize<LengthPercentageOrAuto> {
/// `<width> <height>` /// `<width> <height>`
Explicit { Explicit {
/// Explicit width. /// Explicit width.
width: LengthOrPercentageOrAuto, width: LengthPercentageOrAuto,
/// Explicit height. /// Explicit height.
height: LengthOrPercentageOrAuto, height: LengthPercentageOrAuto,
}, },
/// `cover` /// `cover`
#[animation(error)] #[animation(error)]
@ -38,9 +38,9 @@ pub enum BackgroundSize<LengthOrPercentageOrAuto> {
Contain, Contain,
} }
impl<LengthOrPercentageOrAuto> ToCss for BackgroundSize<LengthOrPercentageOrAuto> impl<LengthPercentageOrAuto> ToCss for BackgroundSize<LengthPercentageOrAuto>
where where
LengthOrPercentageOrAuto: ToCss + IsAuto, LengthPercentageOrAuto: ToCss + IsAuto,
{ {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where

View file

@ -104,11 +104,11 @@ pub enum ShapeSource<BasicShape, ReferenceBox, ImageOrUrl> {
ToComputedValue, ToComputedValue,
ToCss, ToCss,
)] )]
pub enum BasicShape<H, V, LengthOrPercentage, NonNegativeLengthOrPercentage> { pub enum BasicShape<H, V, LengthPercentage, NonNegativeLengthPercentage> {
Inset(#[css(field_bound)] InsetRect<LengthOrPercentage, NonNegativeLengthOrPercentage>), Inset(#[css(field_bound)] InsetRect<LengthPercentage, NonNegativeLengthPercentage>),
Circle(#[css(field_bound)] Circle<H, V, NonNegativeLengthOrPercentage>), Circle(#[css(field_bound)] Circle<H, V, NonNegativeLengthPercentage>),
Ellipse(#[css(field_bound)] Ellipse<H, V, NonNegativeLengthOrPercentage>), Ellipse(#[css(field_bound)] Ellipse<H, V, NonNegativeLengthPercentage>),
Polygon(Polygon<LengthOrPercentage>), Polygon(Polygon<LengthPercentage>),
} }
/// <https://drafts.csswg.org/css-shapes/#funcdef-inset> /// <https://drafts.csswg.org/css-shapes/#funcdef-inset>
@ -125,9 +125,9 @@ pub enum BasicShape<H, V, LengthOrPercentage, NonNegativeLengthOrPercentage> {
ToAnimatedValue, ToAnimatedValue,
ToComputedValue, ToComputedValue,
)] )]
pub struct InsetRect<LengthOrPercentage, NonNegativeLengthOrPercentage> { pub struct InsetRect<LengthPercentage, NonNegativeLengthPercentage> {
pub rect: Rect<LengthOrPercentage>, pub rect: Rect<LengthPercentage>,
pub round: Option<BorderRadius<NonNegativeLengthOrPercentage>>, pub round: Option<BorderRadius<NonNegativeLengthPercentage>>,
} }
/// <https://drafts.csswg.org/css-shapes/#funcdef-circle> /// <https://drafts.csswg.org/css-shapes/#funcdef-circle>
@ -145,9 +145,9 @@ pub struct InsetRect<LengthOrPercentage, NonNegativeLengthOrPercentage> {
ToAnimatedValue, ToAnimatedValue,
ToComputedValue, ToComputedValue,
)] )]
pub struct Circle<H, V, NonNegativeLengthOrPercentage> { pub struct Circle<H, V, NonNegativeLengthPercentage> {
pub position: Position<H, V>, pub position: Position<H, V>,
pub radius: ShapeRadius<NonNegativeLengthOrPercentage>, pub radius: ShapeRadius<NonNegativeLengthPercentage>,
} }
/// <https://drafts.csswg.org/css-shapes/#funcdef-ellipse> /// <https://drafts.csswg.org/css-shapes/#funcdef-ellipse>
@ -165,10 +165,10 @@ pub struct Circle<H, V, NonNegativeLengthOrPercentage> {
ToAnimatedValue, ToAnimatedValue,
ToComputedValue, ToComputedValue,
)] )]
pub struct Ellipse<H, V, NonNegativeLengthOrPercentage> { pub struct Ellipse<H, V, NonNegativeLengthPercentage> {
pub position: Position<H, V>, pub position: Position<H, V>,
pub semiaxis_x: ShapeRadius<NonNegativeLengthOrPercentage>, pub semiaxis_x: ShapeRadius<NonNegativeLengthPercentage>,
pub semiaxis_y: ShapeRadius<NonNegativeLengthOrPercentage>, pub semiaxis_y: ShapeRadius<NonNegativeLengthPercentage>,
} }
/// <https://drafts.csswg.org/css-shapes/#typedef-shape-radius> /// <https://drafts.csswg.org/css-shapes/#typedef-shape-radius>
@ -186,8 +186,8 @@ pub struct Ellipse<H, V, NonNegativeLengthOrPercentage> {
ToComputedValue, ToComputedValue,
ToCss, ToCss,
)] )]
pub enum ShapeRadius<NonNegativeLengthOrPercentage> { pub enum ShapeRadius<NonNegativeLengthPercentage> {
Length(NonNegativeLengthOrPercentage), Length(NonNegativeLengthPercentage),
#[animation(error)] #[animation(error)]
ClosestSide, ClosestSide,
#[animation(error)] #[animation(error)]
@ -208,13 +208,13 @@ pub enum ShapeRadius<NonNegativeLengthOrPercentage> {
ToComputedValue, ToComputedValue,
ToCss, ToCss,
)] )]
pub struct Polygon<LengthOrPercentage> { pub struct Polygon<LengthPercentage> {
/// The filling rule for a polygon. /// The filling rule for a polygon.
#[css(skip_if = "fill_is_default")] #[css(skip_if = "fill_is_default")]
pub fill: FillRule, pub fill: FillRule,
/// A collection of (x, y) coordinates to draw the polygon. /// A collection of (x, y) coordinates to draw the polygon.
#[css(iterable)] #[css(iterable)]
pub coordinates: Vec<PolygonCoord<LengthOrPercentage>>, pub coordinates: Vec<PolygonCoord<LengthPercentage>>,
} }
/// Coordinates for Polygon. /// Coordinates for Polygon.
@ -228,7 +228,7 @@ pub struct Polygon<LengthOrPercentage> {
ToComputedValue, ToComputedValue,
ToCss, ToCss,
)] )]
pub struct PolygonCoord<LengthOrPercentage>(pub LengthOrPercentage, pub LengthOrPercentage); pub struct PolygonCoord<LengthPercentage>(pub LengthPercentage, pub LengthPercentage);
// https://drafts.csswg.org/css-shapes/#typedef-fill-rule // https://drafts.csswg.org/css-shapes/#typedef-fill-rule
// NOTE: Basic shapes spec says that these are the only two values, however // NOTE: Basic shapes spec says that these are the only two values, however

View file

@ -13,9 +13,9 @@ use style_traits::{CssWriter, ToCss};
#[derive( #[derive(
Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)] )]
pub enum BorderImageSideWidth<LengthOrPercentage, Number> { pub enum BorderImageSideWidth<LengthPercentage, Number> {
/// `<length-or-percentage>` /// `<length-or-percentage>`
Length(LengthOrPercentage), Length(LengthPercentage),
/// `<number>` /// `<number>`
Number(Number), Number(Number),
/// `auto` /// `auto`
@ -98,15 +98,15 @@ impl<L> BorderSpacing<L> {
ToAnimatedValue, ToAnimatedValue,
ToComputedValue, ToComputedValue,
)] )]
pub struct BorderRadius<LengthOrPercentage> { pub struct BorderRadius<LengthPercentage> {
/// The top left radius. /// The top left radius.
pub top_left: BorderCornerRadius<LengthOrPercentage>, pub top_left: BorderCornerRadius<LengthPercentage>,
/// The top right radius. /// The top right radius.
pub top_right: BorderCornerRadius<LengthOrPercentage>, pub top_right: BorderCornerRadius<LengthPercentage>,
/// The bottom right radius. /// The bottom right radius.
pub bottom_right: BorderCornerRadius<LengthOrPercentage>, pub bottom_right: BorderCornerRadius<LengthPercentage>,
/// The bottom left radius. /// The bottom left radius.
pub bottom_left: BorderCornerRadius<LengthOrPercentage>, pub bottom_left: BorderCornerRadius<LengthPercentage>,
} }
impl<L> BorderRadius<L> { impl<L> BorderRadius<L> {

View file

@ -19,7 +19,7 @@ use crate::values::animated::ToAnimatedZero;
ToComputedValue, ToComputedValue,
ToCss, ToCss,
)] )]
pub enum VerticalAlign<LengthOrPercentage> { pub enum VerticalAlign<LengthPercentage> {
/// `baseline` /// `baseline`
Baseline, Baseline,
/// `sub` /// `sub`
@ -40,7 +40,7 @@ pub enum VerticalAlign<LengthOrPercentage> {
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
MozMiddleWithBaseline, MozMiddleWithBaseline,
/// `<length-percentage>` /// `<length-percentage>`
Length(LengthOrPercentage), Length(LengthPercentage),
} }
impl<L> VerticalAlign<L> { impl<L> VerticalAlign<L> {

View file

@ -8,12 +8,12 @@
/// A generic value for scroll snap points. /// A generic value for scroll snap points.
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[derive(Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] #[derive(Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
pub enum ScrollSnapPoint<LengthOrPercentage> { pub enum ScrollSnapPoint<LengthPercentage> {
/// `none` /// `none`
None, None,
/// `repeat(<length-or-percentage>)` /// `repeat(<length-or-percentage>)`
#[css(function)] #[css(function)]
Repeat(LengthOrPercentage), Repeat(LengthPercentage),
} }
impl<L> ScrollSnapPoint<L> { impl<L> ScrollSnapPoint<L> {

View file

@ -190,7 +190,7 @@ impl<L> TrackBreadth<L> {
#[inline] #[inline]
pub fn is_fixed(&self) -> bool { pub fn is_fixed(&self) -> bool {
match *self { match *self {
TrackBreadth::Breadth(ref _lop) => true, TrackBreadth::Breadth(ref _lp) => true,
_ => false, _ => false,
} }
} }
@ -278,9 +278,9 @@ impl<L: ToCss> ToCss for TrackSize<L> {
max.to_css(dest)?; max.to_css(dest)?;
dest.write_str(")") dest.write_str(")")
}, },
TrackSize::FitContent(ref lop) => { TrackSize::FitContent(ref lp) => {
dest.write_str("fit-content(")?; dest.write_str("fit-content(")?;
lop.to_css(dest)?; lp.to_css(dest)?;
dest.write_str(")") dest.write_str(")")
}, },
} }
@ -308,7 +308,7 @@ impl<L: ToComputedValue> ToComputedValue for TrackSize<L> {
TrackSize::Minmax(ref b1, ref b2) => { TrackSize::Minmax(ref b1, ref b2) => {
TrackSize::Minmax(b1.to_computed_value(context), b2.to_computed_value(context)) TrackSize::Minmax(b1.to_computed_value(context), b2.to_computed_value(context))
}, },
TrackSize::FitContent(ref lop) => TrackSize::FitContent(lop.to_computed_value(context)), TrackSize::FitContent(ref lp) => TrackSize::FitContent(lp.to_computed_value(context)),
} }
} }
@ -322,8 +322,8 @@ impl<L: ToComputedValue> ToComputedValue for TrackSize<L> {
ToComputedValue::from_computed_value(b1), ToComputedValue::from_computed_value(b1),
ToComputedValue::from_computed_value(b2), ToComputedValue::from_computed_value(b2),
), ),
TrackSize::FitContent(ref lop) => { TrackSize::FitContent(ref lp) => {
TrackSize::FitContent(ToComputedValue::from_computed_value(lop)) TrackSize::FitContent(ToComputedValue::from_computed_value(lp))
}, },
} }
} }
@ -482,11 +482,11 @@ impl<L: Clone> TrackRepeat<L, specified::Integer> {
/// Track list values. Can be <track-size> or <track-repeat> /// Track list values. Can be <track-size> or <track-repeat>
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
pub enum TrackListValue<LengthOrPercentage, Integer> { pub enum TrackListValue<LengthPercentage, Integer> {
/// A <track-size> value. /// A <track-size> value.
TrackSize(TrackSize<LengthOrPercentage>), TrackSize(TrackSize<LengthPercentage>),
/// A <track-repeat> value. /// A <track-repeat> value.
TrackRepeat(TrackRepeat<LengthOrPercentage, Integer>), TrackRepeat(TrackRepeat<LengthPercentage, Integer>),
} }
/// The type of a `<track-list>` as determined during parsing. /// The type of a `<track-list>` as determined during parsing.
@ -515,7 +515,7 @@ pub enum TrackListType {
/// ///
/// <https://drafts.csswg.org/css-grid/#typedef-track-list> /// <https://drafts.csswg.org/css-grid/#typedef-track-list>
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo)] #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo)]
pub struct TrackList<LengthOrPercentage, Integer> { pub struct TrackList<LengthPercentage, Integer> {
/// The type of this `<track-list>` (auto, explicit or general). /// The type of this `<track-list>` (auto, explicit or general).
/// ///
/// In order to avoid parsing the same value multiple times, this does a single traversal /// In order to avoid parsing the same value multiple times, this does a single traversal
@ -523,7 +523,7 @@ pub struct TrackList<LengthOrPercentage, Integer> {
#[css(skip)] #[css(skip)]
pub list_type: TrackListType, pub list_type: TrackListType,
/// A vector of `<track-size> | <track-repeat>` values. /// A vector of `<track-size> | <track-repeat>` values.
pub values: Vec<TrackListValue<LengthOrPercentage, Integer>>, pub values: Vec<TrackListValue<LengthPercentage, Integer>>,
/// `<line-names>` accompanying `<track-size> | <track-repeat>` values. /// `<line-names>` accompanying `<track-size> | <track-repeat>` values.
/// ///
/// If there's no `<line-names>`, then it's represented by an empty vector. /// If there's no `<line-names>`, then it's represented by an empty vector.
@ -531,7 +531,7 @@ pub struct TrackList<LengthOrPercentage, Integer> {
/// length is always one value more than that of the `<track-size>`. /// length is always one value more than that of the `<track-size>`.
pub line_names: Box<[Box<[CustomIdent]>]>, pub line_names: Box<[Box<[CustomIdent]>]>,
/// `<auto-repeat>` value. There can only be one `<auto-repeat>` in a TrackList. /// `<auto-repeat>` value. There can only be one `<auto-repeat>` in a TrackList.
pub auto_repeat: Option<TrackRepeat<LengthOrPercentage, Integer>>, pub auto_repeat: Option<TrackRepeat<LengthPercentage, Integer>>,
} }
impl<L: ToCss, I: ToCss> ToCss for TrackList<L, I> { impl<L: ToCss, I: ToCss> ToCss for TrackList<L, I> {

View file

@ -37,11 +37,11 @@ pub enum Image<Gradient, MozImageRect, ImageUrl> {
/// A CSS gradient. /// A CSS gradient.
/// <https://drafts.csswg.org/css-images/#gradients> /// <https://drafts.csswg.org/css-images/#gradients>
#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)] #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
pub struct Gradient<LineDirection, Length, LengthOrPercentage, Position, Color, Angle> { pub struct Gradient<LineDirection, Length, LengthPercentage, Position, Color, Angle> {
/// Gradients can be linear or radial. /// Gradients can be linear or radial.
pub kind: GradientKind<LineDirection, Length, LengthOrPercentage, Position, Angle>, pub kind: GradientKind<LineDirection, Length, LengthPercentage, Position, Angle>,
/// The color stops and interpolation hints. /// The color stops and interpolation hints.
pub items: Vec<GradientItem<Color, LengthOrPercentage>>, pub items: Vec<GradientItem<Color, LengthPercentage>>,
/// True if this is a repeating gradient. /// True if this is a repeating gradient.
pub repeating: bool, pub repeating: bool,
/// Compatibility mode. /// Compatibility mode.
@ -61,12 +61,12 @@ pub enum CompatMode {
/// A gradient kind. /// A gradient kind.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)] #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue)]
pub enum GradientKind<LineDirection, Length, LengthOrPercentage, Position, Angle> { pub enum GradientKind<LineDirection, Length, LengthPercentage, Position, Angle> {
/// A linear gradient. /// A linear gradient.
Linear(LineDirection), Linear(LineDirection),
/// A radial gradient. /// A radial gradient.
Radial( Radial(
EndingShape<Length, LengthOrPercentage>, EndingShape<Length, LengthPercentage>,
Position, Position,
Option<Angle>, Option<Angle>,
), ),
@ -74,11 +74,11 @@ pub enum GradientKind<LineDirection, Length, LengthOrPercentage, Position, Angle
/// A radial gradient's ending shape. /// A radial gradient's ending shape.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum EndingShape<Length, LengthOrPercentage> { pub enum EndingShape<Length, LengthPercentage> {
/// A circular gradient. /// A circular gradient.
Circle(Circle<Length>), Circle(Circle<Length>),
/// An elliptic gradient. /// An elliptic gradient.
Ellipse(Ellipse<LengthOrPercentage>), Ellipse(Ellipse<LengthPercentage>),
} }
/// A circle shape. /// A circle shape.
@ -92,9 +92,9 @@ pub enum Circle<Length> {
/// An ellipse shape. /// An ellipse shape.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum Ellipse<LengthOrPercentage> { pub enum Ellipse<LengthPercentage> {
/// An ellipse pair of radii. /// An ellipse pair of radii.
Radii(LengthOrPercentage, LengthOrPercentage), Radii(LengthPercentage, LengthPercentage),
/// An ellipse extent. /// An ellipse extent.
Extent(ShapeExtent), Extent(ShapeExtent),
} }
@ -115,21 +115,21 @@ pub enum ShapeExtent {
/// A gradient item. /// A gradient item.
/// <https://drafts.csswg.org/css-images-4/#color-stop-syntax> /// <https://drafts.csswg.org/css-images-4/#color-stop-syntax>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum GradientItem<Color, LengthOrPercentage> { pub enum GradientItem<Color, LengthPercentage> {
/// A color stop. /// A color stop.
ColorStop(ColorStop<Color, LengthOrPercentage>), ColorStop(ColorStop<Color, LengthPercentage>),
/// An interpolation hint. /// An interpolation hint.
InterpolationHint(LengthOrPercentage), InterpolationHint(LengthPercentage),
} }
/// A color stop. /// A color stop.
/// <https://drafts.csswg.org/css-images/#typedef-color-stop-list> /// <https://drafts.csswg.org/css-images/#typedef-color-stop-list>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub struct ColorStop<Color, LengthOrPercentage> { pub struct ColorStop<Color, LengthPercentage> {
/// The color of this stop. /// The color of this stop.
pub color: Color, pub color: Color,
/// The position of this stop. /// The position of this stop.
pub position: Option<LengthOrPercentage>, pub position: Option<LengthPercentage>,
} }
/// Specified values for a paint worklet. /// Specified values for a paint worklet.

View file

@ -26,8 +26,8 @@ use crate::values::computed::ExtremumLength;
ToComputedValue, ToComputedValue,
ToCss, ToCss,
)] )]
pub enum MozLength<LengthOrPercentageOrAuto> { pub enum MozLength<LengthPercentageOrAuto> {
LengthOrPercentageOrAuto(LengthOrPercentageOrAuto), LengthPercentageOrAuto(LengthPercentageOrAuto),
#[animation(error)] #[animation(error)]
ExtremumLength(ExtremumLength), ExtremumLength(ExtremumLength),
} }
@ -47,8 +47,8 @@ pub enum MozLength<LengthOrPercentageOrAuto> {
ToComputedValue, ToComputedValue,
ToCss, ToCss,
)] )]
pub enum MaxLength<LengthOrPercentageOrNone> { pub enum MaxLength<LengthPercentageOrNone> {
LengthOrPercentageOrNone(LengthOrPercentageOrNone), LengthPercentageOrNone(LengthPercentageOrNone),
#[animation(error)] #[animation(error)]
ExtremumLength(ExtremumLength), ExtremumLength(ExtremumLength),
} }

View file

@ -142,28 +142,28 @@ impl<ColorType: Parse, UrlPaintServer: Parse> Parse for SVGPaint<ColorType, UrlP
ToComputedValue, ToComputedValue,
ToCss, ToCss,
)] )]
pub enum SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number> { pub enum SvgLengthPercentageOrNumber<LengthPercentage, Number> {
/// <length> | <percentage> /// <length> | <percentage>
LengthOrPercentage(LengthOrPercentage), LengthPercentage(LengthPercentage),
/// <number> /// <number>
Number(Number), Number(Number),
} }
/// Parsing the SvgLengthOrPercentageOrNumber. At first, we need to parse number /// Parsing the SvgLengthPercentageOrNumber. At first, we need to parse number
/// since prevent converting to the length. /// since prevent converting to the length.
impl<LengthOrPercentageType: Parse, NumberType: Parse> Parse impl<LengthPercentageType: Parse, NumberType: Parse> Parse
for SvgLengthOrPercentageOrNumber<LengthOrPercentageType, NumberType> for SvgLengthPercentageOrNumber<LengthPercentageType, NumberType>
{ {
fn parse<'i, 't>( fn parse<'i, 't>(
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
if let Ok(num) = input.try(|i| NumberType::parse(context, i)) { if let Ok(num) = input.try(|i| NumberType::parse(context, i)) {
return Ok(SvgLengthOrPercentageOrNumber::Number(num)); return Ok(SvgLengthPercentageOrNumber::Number(num));
} }
let lop = LengthOrPercentageType::parse(context, input)?; let lp = LengthPercentageType::parse(context, input)?;
Ok(SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop)) Ok(SvgLengthPercentageOrNumber::LengthPercentage(lp))
} }
} }

View file

@ -103,10 +103,7 @@ where
} }
} }
impl<V> ToAnimatedZero for Spacing<V> impl<V> ToAnimatedZero for Spacing<V> {
where
V: From<Au>,
{
#[inline] #[inline]
fn to_animated_zero(&self) -> Result<Self, ()> { fn to_animated_zero(&self) -> Result<Self, ()> {
Err(()) Err(())
@ -126,7 +123,7 @@ where
ToAnimatedValue, ToAnimatedValue,
ToCss, ToCss,
)] )]
pub enum LineHeight<Number, LengthOrPercentage> { pub enum LineHeight<Number, LengthPercentage> {
/// `normal` /// `normal`
Normal, Normal,
/// `-moz-block-height` /// `-moz-block-height`
@ -135,7 +132,7 @@ pub enum LineHeight<Number, LengthOrPercentage> {
/// `<number>` /// `<number>`
Number(Number), Number(Number),
/// `<length-or-percentage>` /// `<length-or-percentage>`
Length(LengthOrPercentage), Length(LengthPercentage),
} }
impl<N, L> ToAnimatedZero for LineHeight<N, L> { impl<N, L> ToAnimatedZero for LineHeight<N, L> {

View file

@ -5,10 +5,10 @@
//! Generic types for CSS values that are related to transformations. //! Generic types for CSS values that are related to transformations.
use crate::values::computed::length::Length as ComputedLength; use crate::values::computed::length::Length as ComputedLength;
use crate::values::computed::length::LengthOrPercentage as ComputedLengthOrPercentage; use crate::values::computed::length::LengthPercentage as ComputedLengthPercentage;
use crate::values::specified::angle::Angle as SpecifiedAngle; use crate::values::specified::angle::Angle as SpecifiedAngle;
use crate::values::specified::length::Length as SpecifiedLength; use crate::values::specified::length::Length as SpecifiedLength;
use crate::values::specified::length::LengthOrPercentage as SpecifiedLengthOrPercentage; use crate::values::specified::length::LengthPercentage as SpecifiedLengthPercentage;
use crate::values::{computed, CSSFloat}; use crate::values::{computed, CSSFloat};
use app_units::Au; use app_units::Au;
use euclid::{self, Rect, Transform3D}; use euclid::{self, Rect, Transform3D};
@ -105,7 +105,7 @@ impl<H, V, D> TransformOrigin<H, V, D> {
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
/// A single operation in the list of a `transform` value /// A single operation in the list of a `transform` value
pub enum TransformOperation<Angle, Number, Length, Integer, LengthOrPercentage> { pub enum TransformOperation<Angle, Number, Length, Integer, LengthPercentage> {
/// Represents a 2D 2x3 matrix. /// Represents a 2D 2x3 matrix.
Matrix(Matrix<Number>), Matrix(Matrix<Number>),
/// Represents a 3D 4x4 matrix. /// Represents a 3D 4x4 matrix.
@ -125,19 +125,19 @@ pub enum TransformOperation<Angle, Number, Length, Integer, LengthOrPercentage>
SkewY(Angle), SkewY(Angle),
/// translate(x, y) or translate(x) /// translate(x, y) or translate(x)
#[css(comma, function)] #[css(comma, function)]
Translate(LengthOrPercentage, Option<LengthOrPercentage>), Translate(LengthPercentage, Option<LengthPercentage>),
/// translateX(x) /// translateX(x)
#[css(function = "translateX")] #[css(function = "translateX")]
TranslateX(LengthOrPercentage), TranslateX(LengthPercentage),
/// translateY(y) /// translateY(y)
#[css(function = "translateY")] #[css(function = "translateY")]
TranslateY(LengthOrPercentage), TranslateY(LengthPercentage),
/// translateZ(z) /// translateZ(z)
#[css(function = "translateZ")] #[css(function = "translateZ")]
TranslateZ(Length), TranslateZ(Length),
/// translate3d(x, y, z) /// translate3d(x, y, z)
#[css(comma, function = "translate3d")] #[css(comma, function = "translate3d")]
Translate3D(LengthOrPercentage, LengthOrPercentage, Length), Translate3D(LengthPercentage, LengthPercentage, Length),
/// A 2D scaling factor. /// A 2D scaling factor.
/// ///
/// `scale(2)` is parsed as `Scale(Number::new(2.0), None)` and is equivalent to /// `scale(2)` is parsed as `Scale(Number::new(2.0), None)` and is equivalent to
@ -191,18 +191,16 @@ pub enum TransformOperation<Angle, Number, Length, Integer, LengthOrPercentage>
#[allow(missing_docs)] #[allow(missing_docs)]
#[css(comma, function = "interpolatematrix")] #[css(comma, function = "interpolatematrix")]
InterpolateMatrix { InterpolateMatrix {
from_list: from_list: Transform<TransformOperation<Angle, Number, Length, Integer, LengthPercentage>>,
Transform<TransformOperation<Angle, Number, Length, Integer, LengthOrPercentage>>, to_list: Transform<TransformOperation<Angle, Number, Length, Integer, LengthPercentage>>,
to_list: Transform<TransformOperation<Angle, Number, Length, Integer, LengthOrPercentage>>,
progress: computed::Percentage, progress: computed::Percentage,
}, },
/// A intermediate type for accumulation of mismatched transform lists. /// A intermediate type for accumulation of mismatched transform lists.
#[allow(missing_docs)] #[allow(missing_docs)]
#[css(comma, function = "accumulatematrix")] #[css(comma, function = "accumulatematrix")]
AccumulateMatrix { AccumulateMatrix {
from_list: from_list: Transform<TransformOperation<Angle, Number, Length, Integer, LengthPercentage>>,
Transform<TransformOperation<Angle, Number, Length, Integer, LengthOrPercentage>>, to_list: Transform<TransformOperation<Angle, Number, Length, Integer, LengthPercentage>>,
to_list: Transform<TransformOperation<Angle, Number, Length, Integer, LengthOrPercentage>>,
count: Integer, count: Integer,
}, },
} }
@ -211,8 +209,8 @@ pub enum TransformOperation<Angle, Number, Length, Integer, LengthOrPercentage>
/// A value of the `transform` property /// A value of the `transform` property
pub struct Transform<T>(#[css(if_empty = "none", iterable)] pub Vec<T>); pub struct Transform<T>(#[css(if_empty = "none", iterable)] pub Vec<T>);
impl<Angle, Number, Length, Integer, LengthOrPercentage> impl<Angle, Number, Length, Integer, LengthPercentage>
TransformOperation<Angle, Number, Length, Integer, LengthOrPercentage> TransformOperation<Angle, Number, Length, Integer, LengthPercentage>
{ {
/// Check if it is any rotate function. /// Check if it is any rotate function.
pub fn is_rotate(&self) -> bool { pub fn is_rotate(&self) -> bool {
@ -263,13 +261,13 @@ impl ToAbsoluteLength for SpecifiedLength {
} }
} }
impl ToAbsoluteLength for SpecifiedLengthOrPercentage { impl ToAbsoluteLength for SpecifiedLengthPercentage {
// This returns Err(()) if there is any relative length or percentage. We use this when // This returns Err(()) if there is any relative length or percentage. We use this when
// parsing a transform list of DOMMatrix because we want to return a DOM Exception // parsing a transform list of DOMMatrix because we want to return a DOM Exception
// if there is relative length. // if there is relative length.
#[inline] #[inline]
fn to_pixel_length(&self, _containing_len: Option<Au>) -> Result<CSSFloat, ()> { fn to_pixel_length(&self, _containing_len: Option<Au>) -> Result<CSSFloat, ()> {
use self::SpecifiedLengthOrPercentage::*; use self::SpecifiedLengthPercentage::*;
match *self { match *self {
Length(len) => len.to_computed_pixel_length_without_context(), Length(len) => len.to_computed_pixel_length_without_context(),
Calc(ref calc) => calc.to_computed_pixel_length_without_context(), Calc(ref calc) => calc.to_computed_pixel_length_without_context(),
@ -285,21 +283,17 @@ impl ToAbsoluteLength for ComputedLength {
} }
} }
impl ToAbsoluteLength for ComputedLengthOrPercentage { impl ToAbsoluteLength for ComputedLengthPercentage {
#[inline] #[inline]
fn to_pixel_length(&self, containing_len: Option<Au>) -> Result<CSSFloat, ()> { fn to_pixel_length(&self, containing_len: Option<Au>) -> Result<CSSFloat, ()> {
let extract_pixel_length = |lop: &ComputedLengthOrPercentage| match *lop {
ComputedLengthOrPercentage::Length(px) => px.px(),
ComputedLengthOrPercentage::Percentage(_) => 0.,
ComputedLengthOrPercentage::Calc(calc) => calc.length().px(),
};
match containing_len { match containing_len {
Some(relative_len) => Ok(self.to_pixel_length(relative_len).px()), Some(relative_len) => Ok(self.to_pixel_length(relative_len).px()),
// If we don't have reference box, we cannot resolve the used value, // 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 // so only retrieve the length part. This will be used for computing
// distance without any layout info. // distance without any layout info.
None => Ok(extract_pixel_length(self)), //
// FIXME(emilio): This looks wrong.
None => Ok(self.length_component().px()),
} }
} }
} }
@ -637,18 +631,18 @@ impl<Number: ToCss + PartialEq> ToCss for Scale<Number> {
/// A value of the `Translate` property /// A value of the `Translate` property
/// ///
/// <https://drafts.csswg.org/css-transforms-2/#individual-transforms> /// <https://drafts.csswg.org/css-transforms-2/#individual-transforms>
pub enum Translate<LengthOrPercentage, Length> { pub enum Translate<LengthPercentage, Length> {
/// 'none' /// 'none'
None, None,
/// '<length-percentage>' or '<length-percentage> <length-percentage>' /// '<length-percentage>' or '<length-percentage> <length-percentage>'
Translate(LengthOrPercentage, LengthOrPercentage), Translate(LengthPercentage, LengthPercentage),
/// '<length-percentage> <length-percentage> <length>' /// '<length-percentage> <length-percentage> <length>'
Translate3D(LengthOrPercentage, LengthOrPercentage, Length), Translate3D(LengthPercentage, LengthPercentage, Length),
} }
/// A trait to check if this is a zero length. /// A trait to check if this is a zero length.
/// An alternative way is use num_traits::Zero. However, in order to implement num_traits::Zero, /// An alternative way is use num_traits::Zero. However, in order to implement num_traits::Zero,
/// we also have to implement Add, which may be complicated for LengthOrPercentage::Calc. /// we also have to implement Add, which may be complicated for LengthPercentage::Calc.
/// We could do this if other types also need it. If so, we could drop this trait. /// We could do this if other types also need it. If so, we could drop this trait.
pub trait IsZeroLength { pub trait IsZeroLength {
/// Returns true if this is a zero length. /// Returns true if this is a zero length.

View file

@ -6,24 +6,24 @@
use crate::parser::{Parse, ParserContext}; use crate::parser::{Parse, ParserContext};
use crate::values::generics::background::BackgroundSize as GenericBackgroundSize; use crate::values::generics::background::BackgroundSize as GenericBackgroundSize;
use crate::values::specified::length::NonNegativeLengthOrPercentageOrAuto; use crate::values::specified::length::NonNegativeLengthPercentageOrAuto;
use cssparser::Parser; use cssparser::Parser;
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, ToCss}; use style_traits::{CssWriter, ParseError, ToCss};
/// A specified value for the `background-size` property. /// A specified value for the `background-size` property.
pub type BackgroundSize = GenericBackgroundSize<NonNegativeLengthOrPercentageOrAuto>; pub type BackgroundSize = GenericBackgroundSize<NonNegativeLengthPercentageOrAuto>;
impl Parse for BackgroundSize { impl Parse for BackgroundSize {
fn parse<'i, 't>( fn parse<'i, 't>(
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
if let Ok(width) = input.try(|i| NonNegativeLengthOrPercentageOrAuto::parse(context, i)) { if let Ok(width) = input.try(|i| NonNegativeLengthPercentageOrAuto::parse(context, i)) {
let height = input let height = input
.try(|i| NonNegativeLengthOrPercentageOrAuto::parse(context, i)) .try(|i| NonNegativeLengthPercentageOrAuto::parse(context, i))
.unwrap_or(NonNegativeLengthOrPercentageOrAuto::auto()); .unwrap_or(NonNegativeLengthPercentageOrAuto::auto());
return Ok(GenericBackgroundSize::Explicit { width, height }); return Ok(GenericBackgroundSize::Explicit { width, height });
} }
Ok(try_match_ident_ignore_ascii_case! { input, Ok(try_match_ident_ignore_ascii_case! { input,
@ -37,8 +37,8 @@ impl BackgroundSize {
/// Returns `auto auto`. /// Returns `auto auto`.
pub fn auto() -> Self { pub fn auto() -> Self {
GenericBackgroundSize::Explicit { GenericBackgroundSize::Explicit {
width: NonNegativeLengthOrPercentageOrAuto::auto(), width: NonNegativeLengthPercentageOrAuto::auto(),
height: NonNegativeLengthOrPercentageOrAuto::auto(), height: NonNegativeLengthPercentageOrAuto::auto(),
} }
} }
} }

View file

@ -17,7 +17,7 @@ use crate::values::specified::image::Image;
use crate::values::specified::position::{HorizontalPosition, Position, VerticalPosition}; use crate::values::specified::position::{HorizontalPosition, Position, VerticalPosition};
use crate::values::specified::url::SpecifiedUrl; use crate::values::specified::url::SpecifiedUrl;
use crate::values::specified::SVGPathData; use crate::values::specified::SVGPathData;
use crate::values::specified::{LengthOrPercentage, NonNegativeLengthOrPercentage}; use crate::values::specified::{LengthPercentage, NonNegativeLengthPercentage};
use cssparser::Parser; use cssparser::Parser;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
@ -35,26 +35,26 @@ pub type FloatAreaShape = generic::FloatAreaShape<BasicShape, Image>;
pub type BasicShape = generic::BasicShape< pub type BasicShape = generic::BasicShape<
HorizontalPosition, HorizontalPosition,
VerticalPosition, VerticalPosition,
LengthOrPercentage, LengthPercentage,
NonNegativeLengthOrPercentage, NonNegativeLengthPercentage,
>; >;
/// The specified value of `inset()` /// The specified value of `inset()`
pub type InsetRect = generic::InsetRect<LengthOrPercentage, NonNegativeLengthOrPercentage>; pub type InsetRect = generic::InsetRect<LengthPercentage, NonNegativeLengthPercentage>;
/// A specified circle. /// A specified circle.
pub type Circle = pub type Circle =
generic::Circle<HorizontalPosition, VerticalPosition, NonNegativeLengthOrPercentage>; generic::Circle<HorizontalPosition, VerticalPosition, NonNegativeLengthPercentage>;
/// A specified ellipse. /// A specified ellipse.
pub type Ellipse = pub type Ellipse =
generic::Ellipse<HorizontalPosition, VerticalPosition, NonNegativeLengthOrPercentage>; generic::Ellipse<HorizontalPosition, VerticalPosition, NonNegativeLengthPercentage>;
/// The specified value of `ShapeRadius` /// The specified value of `ShapeRadius`
pub type ShapeRadius = generic::ShapeRadius<NonNegativeLengthOrPercentage>; pub type ShapeRadius = generic::ShapeRadius<NonNegativeLengthPercentage>;
/// The specified value of `Polygon` /// The specified value of `Polygon`
pub type Polygon = generic::Polygon<LengthOrPercentage>; pub type Polygon = generic::Polygon<LengthPercentage>;
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
fn is_clip_path_path_enabled(context: &ParserContext) -> bool { fn is_clip_path_path_enabled(context: &ParserContext) -> bool {
@ -200,7 +200,7 @@ impl InsetRect {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
let rect = Rect::parse_with(context, input, LengthOrPercentage::parse)?; let rect = Rect::parse_with(context, input, LengthPercentage::parse)?;
let round = if input.try(|i| i.expect_ident_matching("round")).is_ok() { let round = if input.try(|i| i.expect_ident_matching("round")).is_ok() {
Some(BorderRadius::parse(context, input)?) Some(BorderRadius::parse(context, input)?)
} else { } else {
@ -316,8 +316,8 @@ impl Parse for ShapeRadius {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
if let Ok(lop) = input.try(|i| NonNegativeLengthOrPercentage::parse(context, i)) { if let Ok(lp) = input.try(|i| NonNegativeLengthPercentage::parse(context, i)) {
return Ok(generic::ShapeRadius::Length(lop)); return Ok(generic::ShapeRadius::Length(lp));
} }
try_match_ident_ignore_ascii_case! { input, try_match_ident_ignore_ascii_case! { input,
@ -353,8 +353,8 @@ impl Polygon {
let buf = input.parse_comma_separated(|i| { let buf = input.parse_comma_separated(|i| {
Ok(PolygonCoord( Ok(PolygonCoord(
LengthOrPercentage::parse(context, i)?, LengthPercentage::parse(context, i)?,
LengthOrPercentage::parse(context, i)?, LengthPercentage::parse(context, i)?,
)) ))
})?; })?;

View file

@ -13,7 +13,7 @@ use crate::values::generics::border::BorderRadius as GenericBorderRadius;
use crate::values::generics::border::BorderSpacing as GenericBorderSpacing; use crate::values::generics::border::BorderSpacing as GenericBorderSpacing;
use crate::values::generics::rect::Rect; use crate::values::generics::rect::Rect;
use crate::values::generics::size::Size; use crate::values::generics::size::Size;
use crate::values::specified::length::{NonNegativeLength, NonNegativeLengthOrPercentage}; use crate::values::specified::length::{NonNegativeLength, NonNegativeLengthPercentage};
use crate::values::specified::{AllowQuirks, NonNegativeNumber, NonNegativeNumberOrPercentage}; use crate::values::specified::{AllowQuirks, NonNegativeNumber, NonNegativeNumberOrPercentage};
use cssparser::Parser; use cssparser::Parser;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
@ -79,16 +79,16 @@ pub type BorderImageWidth = Rect<BorderImageSideWidth>;
/// A specified value for a single side of a `border-image-width` property. /// A specified value for a single side of a `border-image-width` property.
pub type BorderImageSideWidth = pub type BorderImageSideWidth =
GenericBorderImageSideWidth<NonNegativeLengthOrPercentage, NonNegativeNumber>; GenericBorderImageSideWidth<NonNegativeLengthPercentage, NonNegativeNumber>;
/// A specified value for the `border-image-slice` property. /// A specified value for the `border-image-slice` property.
pub type BorderImageSlice = GenericBorderImageSlice<NonNegativeNumberOrPercentage>; pub type BorderImageSlice = GenericBorderImageSlice<NonNegativeNumberOrPercentage>;
/// A specified value for the `border-radius` property. /// A specified value for the `border-radius` property.
pub type BorderRadius = GenericBorderRadius<NonNegativeLengthOrPercentage>; pub type BorderRadius = GenericBorderRadius<NonNegativeLengthPercentage>;
/// A specified value for the `border-*-radius` longhand properties. /// A specified value for the `border-*-radius` longhand properties.
pub type BorderCornerRadius = GenericBorderCornerRadius<NonNegativeLengthOrPercentage>; pub type BorderCornerRadius = GenericBorderCornerRadius<NonNegativeLengthPercentage>;
/// A specified value for the `border-spacing` longhand properties. /// A specified value for the `border-spacing` longhand properties.
pub type BorderSpacing = GenericBorderSpacing<NonNegativeLength>; pub type BorderSpacing = GenericBorderSpacing<NonNegativeLength>;
@ -178,7 +178,7 @@ impl Parse for BorderImageSideWidth {
return Ok(GenericBorderImageSideWidth::Auto); return Ok(GenericBorderImageSideWidth::Auto);
} }
if let Ok(len) = input.try(|i| NonNegativeLengthOrPercentage::parse(context, i)) { if let Ok(len) = input.try(|i| NonNegativeLengthPercentage::parse(context, i)) {
return Ok(GenericBorderImageSideWidth::Length(len)); return Ok(GenericBorderImageSideWidth::Length(len));
} }
@ -206,9 +206,9 @@ impl Parse for BorderRadius {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
let widths = Rect::parse_with(context, input, NonNegativeLengthOrPercentage::parse)?; let widths = Rect::parse_with(context, input, NonNegativeLengthPercentage::parse)?;
let heights = if input.try(|i| i.expect_delim('/')).is_ok() { let heights = if input.try(|i| i.expect_delim('/')).is_ok() {
Rect::parse_with(context, input, NonNegativeLengthOrPercentage::parse)? Rect::parse_with(context, input, NonNegativeLengthPercentage::parse)?
} else { } else {
widths.clone() widths.clone()
}; };
@ -227,7 +227,7 @@ impl Parse for BorderCornerRadius {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
Size::parse_with(context, input, NonNegativeLengthOrPercentage::parse) Size::parse_with(context, input, NonNegativeLengthPercentage::parse)
.map(GenericBorderCornerRadius) .map(GenericBorderCornerRadius)
} }
} }

View file

@ -11,7 +11,7 @@ use crate::properties::{PropertyId, ShorthandId};
use crate::values::generics::box_::AnimationIterationCount as GenericAnimationIterationCount; use crate::values::generics::box_::AnimationIterationCount as GenericAnimationIterationCount;
use crate::values::generics::box_::Perspective as GenericPerspective; use crate::values::generics::box_::Perspective as GenericPerspective;
use crate::values::generics::box_::VerticalAlign as GenericVerticalAlign; use crate::values::generics::box_::VerticalAlign as GenericVerticalAlign;
use crate::values::specified::length::{LengthOrPercentage, NonNegativeLength}; use crate::values::specified::length::{LengthPercentage, NonNegativeLength};
use crate::values::specified::{AllowQuirks, Number}; use crate::values::specified::{AllowQuirks, Number};
use crate::values::{CustomIdent, KeyframesName}; use crate::values::{CustomIdent, KeyframesName};
use crate::Atom; use crate::Atom;
@ -271,17 +271,16 @@ impl Display {
} }
/// A specified value for the `vertical-align` property. /// A specified value for the `vertical-align` property.
pub type VerticalAlign = GenericVerticalAlign<LengthOrPercentage>; pub type VerticalAlign = GenericVerticalAlign<LengthPercentage>;
impl Parse for VerticalAlign { impl Parse for VerticalAlign {
fn parse<'i, 't>( fn parse<'i, 't>(
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
if let Ok(lop) = if let Ok(lp) = input.try(|i| LengthPercentage::parse_quirky(context, i, AllowQuirks::Yes))
input.try(|i| LengthOrPercentage::parse_quirky(context, i, AllowQuirks::Yes))
{ {
return Ok(GenericVerticalAlign::Length(lop)); return Ok(GenericVerticalAlign::Length(lp));
} }
try_match_ident_ignore_ascii_case! { input, try_match_ident_ignore_ascii_case! { input,

View file

@ -52,7 +52,7 @@ pub enum CalcUnit {
/// `<percentage>` /// `<percentage>`
Percentage, Percentage,
/// `<length> | <percentage>` /// `<length> | <percentage>`
LengthOrPercentage, LengthPercentage,
/// `<angle>` /// `<angle>`
Angle, Angle,
/// `<time>` /// `<time>`
@ -67,7 +67,7 @@ pub enum CalcUnit {
/// function work properly. /// function work properly.
#[derive(Clone, Copy, Debug, Default, MallocSizeOf, PartialEq)] #[derive(Clone, Copy, Debug, Default, MallocSizeOf, PartialEq)]
#[allow(missing_docs)] #[allow(missing_docs)]
pub struct CalcLengthOrPercentage { pub struct CalcLengthPercentage {
pub clamping_mode: AllowedNumericType, pub clamping_mode: AllowedNumericType,
pub absolute: Option<AbsoluteLength>, pub absolute: Option<AbsoluteLength>,
pub vw: Option<CSSFloat>, pub vw: Option<CSSFloat>,
@ -81,7 +81,7 @@ pub struct CalcLengthOrPercentage {
pub percentage: Option<computed::Percentage>, pub percentage: Option<computed::Percentage>,
} }
impl ToCss for CalcLengthOrPercentage { impl ToCss for CalcLengthPercentage {
/// <https://drafts.csswg.org/css-values/#calc-serialize> /// <https://drafts.csswg.org/css-values/#calc-serialize>
/// ///
/// FIXME(emilio): Should this simplify away zeros? /// FIXME(emilio): Should this simplify away zeros?
@ -148,7 +148,7 @@ impl ToCss for CalcLengthOrPercentage {
} }
} }
impl SpecifiedValueInfo for CalcLengthOrPercentage {} impl SpecifiedValueInfo for CalcLengthPercentage {}
impl CalcNode { impl CalcNode {
/// Tries to parse a single element in the expression, that is, a /// Tries to parse a single element in the expression, that is, a
@ -176,7 +176,7 @@ impl CalcNode {
&Token::Dimension { &Token::Dimension {
value, ref unit, .. value, ref unit, ..
}, },
CalcUnit::LengthOrPercentage, CalcUnit::LengthPercentage,
) => { ) => {
return NoCalcLength::parse_dimension(context, value, unit) return NoCalcLength::parse_dimension(context, value, unit)
.map(CalcNode::Length) .map(CalcNode::Length)
@ -202,7 +202,7 @@ impl CalcNode {
.map(CalcNode::Time) .map(CalcNode::Time)
.map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); .map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}, },
(&Token::Percentage { unit_value, .. }, CalcUnit::LengthOrPercentage) | (&Token::Percentage { unit_value, .. }, CalcUnit::LengthPercentage) |
(&Token::Percentage { unit_value, .. }, CalcUnit::Percentage) => { (&Token::Percentage { unit_value, .. }, CalcUnit::Percentage) => {
return Ok(CalcNode::Percentage(unit_value)); return Ok(CalcNode::Percentage(unit_value));
}, },
@ -299,8 +299,8 @@ impl CalcNode {
fn to_length_or_percentage( fn to_length_or_percentage(
&self, &self,
clamping_mode: AllowedNumericType, clamping_mode: AllowedNumericType,
) -> Result<CalcLengthOrPercentage, ()> { ) -> Result<CalcLengthPercentage, ()> {
let mut ret = CalcLengthOrPercentage { let mut ret = CalcLengthPercentage {
clamping_mode: clamping_mode, clamping_mode: clamping_mode,
..Default::default() ..Default::default()
}; };
@ -346,7 +346,7 @@ impl CalcNode {
/// (this allows adding and substracting into the return value). /// (this allows adding and substracting into the return value).
fn add_length_or_percentage_to( fn add_length_or_percentage_to(
&self, &self,
ret: &mut CalcLengthOrPercentage, ret: &mut CalcLengthPercentage,
factor: CSSFloat, factor: CSSFloat,
) -> Result<(), ()> { ) -> Result<(), ()> {
match *self { match *self {
@ -537,8 +537,8 @@ impl CalcNode {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType, clamping_mode: AllowedNumericType,
) -> Result<CalcLengthOrPercentage, ParseError<'i>> { ) -> Result<CalcLengthPercentage, ParseError<'i>> {
Self::parse(context, input, CalcUnit::LengthOrPercentage)? Self::parse(context, input, CalcUnit::LengthPercentage)?
.to_length_or_percentage(clamping_mode) .to_length_or_percentage(clamping_mode)
.map_err(|()| input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) .map_err(|()| input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
} }
@ -558,7 +558,7 @@ impl CalcNode {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType, clamping_mode: AllowedNumericType,
) -> Result<CalcLengthOrPercentage, ParseError<'i>> { ) -> Result<CalcLengthPercentage, ParseError<'i>> {
Self::parse(context, input, CalcUnit::Length)? Self::parse(context, input, CalcUnit::Length)?
.to_length_or_percentage(clamping_mode) .to_length_or_percentage(clamping_mode)
.map_err(|()| input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) .map_err(|()| input.new_custom_error(StyleParseErrorKind::UnspecifiedError))

View file

@ -11,7 +11,7 @@ use style_traits::ParseError;
/// The `width` value type. /// The `width` value type.
#[cfg(feature = "servo")] #[cfg(feature = "servo")]
pub type Width = crate::values::specified::NonNegativeLengthOrPercentageOrAuto; pub type Width = crate::values::specified::NonNegativeLengthPercentageOrAuto;
/// The `width` value type. /// The `width` value type.
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]

View file

@ -16,7 +16,7 @@ use crate::values::generics::font::{self as generics, FeatureTagValue, FontSetti
use crate::values::generics::font::{KeywordSize, VariationValue}; use crate::values::generics::font::{KeywordSize, VariationValue};
use crate::values::generics::NonNegative; use crate::values::generics::NonNegative;
use crate::values::specified::length::{FontBaseSize, AU_PER_PT, AU_PER_PX}; use crate::values::specified::length::{FontBaseSize, AU_PER_PT, AU_PER_PX};
use crate::values::specified::{AllowQuirks, Angle, Integer, LengthOrPercentage}; use crate::values::specified::{AllowQuirks, Angle, Integer, LengthPercentage};
use crate::values::specified::{NoCalcLength, Number, Percentage}; use crate::values::specified::{NoCalcLength, Number, Percentage};
use crate::values::CustomIdent; use crate::values::CustomIdent;
use crate::Atom; use crate::Atom;
@ -510,7 +510,7 @@ impl ToComputedValue for FontStretch {
/// A specified font-size value /// A specified font-size value
pub enum FontSize { pub enum FontSize {
/// A length; e.g. 10px. /// A length; e.g. 10px.
Length(LengthOrPercentage), Length(LengthPercentage),
/// A keyword value, along with a ratio and absolute offset. /// A keyword value, along with a ratio and absolute offset.
/// The ratio in any specified keyword value /// The ratio in any specified keyword value
/// will be 1 (with offset 0), but we cascade keywordness even /// will be 1 (with offset 0), but we cascade keywordness even
@ -531,8 +531,8 @@ pub enum FontSize {
System(SystemFont), System(SystemFont),
} }
impl From<LengthOrPercentage> for FontSize { impl From<LengthPercentage> for FontSize {
fn from(other: LengthOrPercentage) -> Self { fn from(other: LengthPercentage) -> Self {
FontSize::Length(other) FontSize::Length(other)
} }
} }
@ -863,7 +863,7 @@ impl FontSize {
}; };
let mut info = None; let mut info = None;
let size = match *self { let size = match *self {
FontSize::Length(LengthOrPercentage::Length(NoCalcLength::FontRelative(value))) => { FontSize::Length(LengthPercentage::Length(NoCalcLength::FontRelative(value))) => {
if let FontRelativeLength::Em(em) = value { if let FontRelativeLength::Em(em) = value {
// If the parent font was keyword-derived, this is too. // If the parent font was keyword-derived, this is too.
// Tack the em unit onto the factor // Tack the em unit onto the factor
@ -871,22 +871,22 @@ impl FontSize {
} }
value.to_computed_value(context, base_size).into() value.to_computed_value(context, base_size).into()
}, },
FontSize::Length(LengthOrPercentage::Length(NoCalcLength::ServoCharacterWidth( FontSize::Length(LengthPercentage::Length(NoCalcLength::ServoCharacterWidth(
value, value,
))) => value.to_computed_value(base_size.resolve(context)).into(), ))) => value.to_computed_value(base_size.resolve(context)).into(),
FontSize::Length(LengthOrPercentage::Length(NoCalcLength::Absolute(ref l))) => { FontSize::Length(LengthPercentage::Length(NoCalcLength::Absolute(ref l))) => {
context.maybe_zoom_text(l.to_computed_value(context).into()) context.maybe_zoom_text(l.to_computed_value(context).into())
}, },
FontSize::Length(LengthOrPercentage::Length(ref l)) => { FontSize::Length(LengthPercentage::Length(ref l)) => {
l.to_computed_value(context).into() l.to_computed_value(context).into()
}, },
FontSize::Length(LengthOrPercentage::Percentage(pc)) => { FontSize::Length(LengthPercentage::Percentage(pc)) => {
// If the parent font was keyword-derived, this is too. // If the parent font was keyword-derived, this is too.
// Tack the % onto the factor // Tack the % onto the factor
info = compose_keyword(pc.0); info = compose_keyword(pc.0);
base_size.resolve(context).scale_by(pc.0).into() base_size.resolve(context).scale_by(pc.0).into()
}, },
FontSize::Length(LengthOrPercentage::Calc(ref calc)) => { FontSize::Length(LengthPercentage::Calc(ref calc)) => {
let parent = context.style().get_parent_font().clone_font_size(); let parent = context.style().get_parent_font().clone_font_size();
// if we contain em/% units and the parent was keyword derived, this is too // if we contain em/% units and the parent was keyword derived, this is too
// Extract the ratio/offset and compose it // Extract the ratio/offset and compose it
@ -916,9 +916,7 @@ impl FontSize {
info = parent.keyword_info.map(|i| i.compose(ratio, abs.into())); info = parent.keyword_info.map(|i| i.compose(ratio, abs.into()));
} }
let calc = calc.to_computed_value_zoomed(context, base_size); let calc = calc.to_computed_value_zoomed(context, base_size);
calc.to_used_value(Some(base_size.resolve(context))) calc.to_used_value(base_size.resolve(context)).into()
.unwrap()
.into()
}, },
FontSize::Keyword(i) => { FontSize::Keyword(i) => {
// As a specified keyword, this is keyword derived // As a specified keyword, this is keyword derived
@ -966,7 +964,7 @@ impl ToComputedValue for FontSize {
#[inline] #[inline]
fn from_computed_value(computed: &computed::FontSize) -> Self { fn from_computed_value(computed: &computed::FontSize) -> Self {
FontSize::Length(LengthOrPercentage::Length( FontSize::Length(LengthPercentage::Length(
ToComputedValue::from_computed_value(&computed.size.0), ToComputedValue::from_computed_value(&computed.size.0),
)) ))
} }
@ -987,10 +985,10 @@ impl FontSize {
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks, allow_quirks: AllowQuirks,
) -> Result<FontSize, ParseError<'i>> { ) -> Result<FontSize, ParseError<'i>> {
if let Ok(lop) = if let Ok(lp) =
input.try(|i| LengthOrPercentage::parse_non_negative_quirky(context, i, allow_quirks)) input.try(|i| LengthPercentage::parse_non_negative_quirky(context, i, allow_quirks))
{ {
return Ok(FontSize::Length(lop)); return Ok(FontSize::Length(lp));
} }
if let Ok(kw) = input.try(KeywordSize::parse) { if let Ok(kw) = input.try(KeywordSize::parse) {

View file

@ -11,14 +11,14 @@ use crate::values::computed;
use crate::values::computed::length::CSSPixelLength; use crate::values::computed::length::CSSPixelLength;
use crate::values::generics::gecko::ScrollSnapPoint as GenericScrollSnapPoint; use crate::values::generics::gecko::ScrollSnapPoint as GenericScrollSnapPoint;
use crate::values::generics::rect::Rect; use crate::values::generics::rect::Rect;
use crate::values::specified::length::LengthOrPercentage; use crate::values::specified::length::LengthPercentage;
use cssparser::{Parser, Token}; use cssparser::{Parser, Token};
use std::fmt; use std::fmt;
use style_traits::values::SequenceWriter; use style_traits::values::SequenceWriter;
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
/// A specified type for scroll snap points. /// A specified type for scroll snap points.
pub type ScrollSnapPoint = GenericScrollSnapPoint<LengthOrPercentage>; pub type ScrollSnapPoint = GenericScrollSnapPoint<LengthPercentage>;
impl Parse for ScrollSnapPoint { impl Parse for ScrollSnapPoint {
fn parse<'i, 't>( fn parse<'i, 't>(
@ -30,7 +30,7 @@ impl Parse for ScrollSnapPoint {
} }
input.expect_function_matching("repeat")?; input.expect_function_matching("repeat")?;
let length = let length =
input.parse_nested_block(|i| LengthOrPercentage::parse_non_negative(context, i))?; input.parse_nested_block(|i| LengthPercentage::parse_non_negative(context, i))?;
Ok(GenericScrollSnapPoint::Repeat(length)) Ok(GenericScrollSnapPoint::Repeat(length))
} }
} }

View file

@ -10,7 +10,7 @@ use crate::values::computed::{self, Context, ToComputedValue};
use crate::values::generics::grid::{GridTemplateComponent, RepeatCount, TrackBreadth}; use crate::values::generics::grid::{GridTemplateComponent, RepeatCount, TrackBreadth};
use crate::values::generics::grid::{LineNameList, TrackKeyword, TrackRepeat, TrackSize}; use crate::values::generics::grid::{LineNameList, TrackKeyword, TrackRepeat, TrackSize};
use crate::values::generics::grid::{TrackList, TrackListType, TrackListValue}; use crate::values::generics::grid::{TrackList, TrackListType, TrackListValue};
use crate::values::specified::{Integer, LengthOrPercentage}; use crate::values::specified::{Integer, LengthPercentage};
use crate::values::{CSSFloat, CustomIdent}; use crate::values::{CSSFloat, CustomIdent};
use cssparser::{ParseError as CssParseError, Parser, Token}; use cssparser::{ParseError as CssParseError, Parser, Token};
use std::mem; use std::mem;
@ -27,13 +27,13 @@ pub fn parse_flex<'i, 't>(input: &mut Parser<'i, 't>) -> Result<CSSFloat, ParseE
} }
} }
impl Parse for TrackBreadth<LengthOrPercentage> { impl Parse for TrackBreadth<LengthPercentage> {
fn parse<'i, 't>( fn parse<'i, 't>(
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
if let Ok(lop) = input.try(|i| LengthOrPercentage::parse_non_negative(context, i)) { if let Ok(lp) = input.try(|i| LengthPercentage::parse_non_negative(context, i)) {
return Ok(TrackBreadth::Breadth(lop)); return Ok(TrackBreadth::Breadth(lp));
} }
if let Ok(f) = input.try(parse_flex) { if let Ok(f) = input.try(parse_flex) {
@ -44,7 +44,7 @@ impl Parse for TrackBreadth<LengthOrPercentage> {
} }
} }
impl Parse for TrackSize<LengthOrPercentage> { impl Parse for TrackSize<LengthPercentage> {
fn parse<'i, 't>( fn parse<'i, 't>(
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
@ -56,8 +56,8 @@ impl Parse for TrackSize<LengthOrPercentage> {
if input.try(|i| i.expect_function_matching("minmax")).is_ok() { if input.try(|i| i.expect_function_matching("minmax")).is_ok() {
return input.parse_nested_block(|input| { return input.parse_nested_block(|input| {
let inflexible_breadth = let inflexible_breadth =
match input.try(|i| LengthOrPercentage::parse_non_negative(context, i)) { match input.try(|i| LengthPercentage::parse_non_negative(context, i)) {
Ok(lop) => TrackBreadth::Breadth(lop), Ok(lp) => TrackBreadth::Breadth(lp),
Err(..) => { Err(..) => {
let keyword = TrackKeyword::parse(input)?; let keyword = TrackKeyword::parse(input)?;
TrackBreadth::Keyword(keyword) TrackBreadth::Keyword(keyword)
@ -73,9 +73,8 @@ impl Parse for TrackSize<LengthOrPercentage> {
} }
input.expect_function_matching("fit-content")?; input.expect_function_matching("fit-content")?;
let lop = let lp = input.parse_nested_block(|i| LengthPercentage::parse_non_negative(context, i))?;
input.parse_nested_block(|i| LengthOrPercentage::parse_non_negative(context, i))?; Ok(TrackSize::FitContent(lp))
Ok(TrackSize::FitContent(lop))
} }
} }
@ -113,7 +112,7 @@ enum RepeatType {
Fixed, Fixed,
} }
impl TrackRepeat<LengthOrPercentage, Integer> { impl TrackRepeat<LengthPercentage, Integer> {
fn parse_with_repeat_type<'i, 't>( fn parse_with_repeat_type<'i, 't>(
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
@ -195,7 +194,7 @@ impl TrackRepeat<LengthOrPercentage, Integer> {
} }
} }
impl Parse for TrackList<LengthOrPercentage, Integer> { impl Parse for TrackList<LengthPercentage, Integer> {
fn parse<'i, 't>( fn parse<'i, 't>(
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
@ -293,8 +292,8 @@ impl Parse for TrackList<LengthOrPercentage, Integer> {
} }
} }
impl ToComputedValue for TrackList<LengthOrPercentage, Integer> { impl ToComputedValue for TrackList<LengthPercentage, Integer> {
type ComputedValue = TrackList<computed::LengthOrPercentage, computed::Integer>; type ComputedValue = TrackList<computed::LengthPercentage, computed::Integer>;
#[inline] #[inline]
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
@ -391,7 +390,7 @@ fn allow_grid_template_subgrids() -> bool {
false false
} }
impl Parse for GridTemplateComponent<LengthOrPercentage, Integer> { impl Parse for GridTemplateComponent<LengthPercentage, Integer> {
// FIXME: Derive Parse (probably with None_) // FIXME: Derive Parse (probably with None_)
fn parse<'i, 't>( fn parse<'i, 't>(
context: &ParserContext, context: &ParserContext,
@ -405,8 +404,8 @@ impl Parse for GridTemplateComponent<LengthOrPercentage, Integer> {
} }
} }
impl GridTemplateComponent<LengthOrPercentage, Integer> { impl GridTemplateComponent<LengthPercentage, Integer> {
/// Parses a `GridTemplateComponent<LengthOrPercentage>` except `none` keyword. /// Parses a `GridTemplateComponent<LengthPercentage>` except `none` keyword.
pub fn parse_without_none<'i, 't>( pub fn parse_without_none<'i, 't>(
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,

View file

@ -16,7 +16,7 @@ use crate::values::generics::image::{self as generic, Circle, CompatMode, Ellips
use crate::values::generics::position::Position as GenericPosition; use crate::values::generics::position::Position as GenericPosition;
use crate::values::specified::position::{LegacyPosition, Position, PositionComponent, Side, X, Y}; use crate::values::specified::position::{LegacyPosition, Position, PositionComponent, Side, X, Y};
use crate::values::specified::url::SpecifiedImageUrl; use crate::values::specified::url::SpecifiedImageUrl;
use crate::values::specified::{Angle, Color, Length, LengthOrPercentage}; use crate::values::specified::{Angle, Color, Length, LengthPercentage};
use crate::values::specified::{Number, NumberOrPercentage, Percentage}; use crate::values::specified::{Number, NumberOrPercentage, Percentage};
use crate::values::{Either, None_}; use crate::values::{Either, None_};
use crate::Atom; use crate::Atom;
@ -54,13 +54,13 @@ pub type Image = generic::Image<Gradient, MozImageRect, SpecifiedImageUrl>;
/// <https://drafts.csswg.org/css-images/#gradients> /// <https://drafts.csswg.org/css-images/#gradients>
#[cfg(not(feature = "gecko"))] #[cfg(not(feature = "gecko"))]
pub type Gradient = pub type Gradient =
generic::Gradient<LineDirection, Length, LengthOrPercentage, Position, Color, Angle>; generic::Gradient<LineDirection, Length, LengthPercentage, Position, Color, Angle>;
/// Specified values for a CSS gradient. /// Specified values for a CSS gradient.
/// <https://drafts.csswg.org/css-images/#gradients> /// <https://drafts.csswg.org/css-images/#gradients>
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
pub type Gradient = pub type Gradient =
generic::Gradient<LineDirection, Length, LengthOrPercentage, GradientPosition, Color, Angle>; generic::Gradient<LineDirection, Length, LengthPercentage, GradientPosition, Color, Angle>;
impl SpecifiedValueInfo for Gradient { impl SpecifiedValueInfo for Gradient {
const SUPPORTED_TYPES: u8 = CssType::GRADIENT; const SUPPORTED_TYPES: u8 = CssType::GRADIENT;
@ -88,12 +88,12 @@ impl SpecifiedValueInfo for Gradient {
/// A specified gradient kind. /// A specified gradient kind.
#[cfg(not(feature = "gecko"))] #[cfg(not(feature = "gecko"))]
pub type GradientKind = pub type GradientKind =
generic::GradientKind<LineDirection, Length, LengthOrPercentage, Position, Angle>; generic::GradientKind<LineDirection, Length, LengthPercentage, Position, Angle>;
/// A specified gradient kind. /// A specified gradient kind.
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
pub type GradientKind = pub type GradientKind =
generic::GradientKind<LineDirection, Length, LengthOrPercentage, GradientPosition, Angle>; generic::GradientKind<LineDirection, Length, LengthPercentage, GradientPosition, Angle>;
/// A specified gradient line direction. /// A specified gradient line direction.
#[derive(Clone, Debug, MallocSizeOf, PartialEq)] #[derive(Clone, Debug, MallocSizeOf, PartialEq)]
@ -125,13 +125,13 @@ pub enum GradientPosition {
} }
/// A specified ending shape. /// A specified ending shape.
pub type EndingShape = generic::EndingShape<Length, LengthOrPercentage>; pub type EndingShape = generic::EndingShape<Length, LengthPercentage>;
/// A specified gradient item. /// A specified gradient item.
pub type GradientItem = generic::GradientItem<Color, LengthOrPercentage>; pub type GradientItem = generic::GradientItem<Color, LengthPercentage>;
/// A computed color stop. /// A computed color stop.
pub type ColorStop = generic::ColorStop<Color, LengthOrPercentage>; pub type ColorStop = generic::ColorStop<Color, LengthPercentage>;
/// Specified values for `moz-image-rect` /// Specified values for `moz-image-rect`
/// -moz-image-rect(<uri>, top, right, bottom, left); /// -moz-image-rect(<uri>, top, right, bottom, left);
@ -538,8 +538,8 @@ impl Gradient {
&generic::GradientItem::ColorStop(ref b), &generic::GradientItem::ColorStop(ref b),
) => match (&a.position, &b.position) { ) => match (&a.position, &b.position) {
( (
&Some(LengthOrPercentage::Percentage(a)), &Some(LengthPercentage::Percentage(a)),
&Some(LengthOrPercentage::Percentage(b)), &Some(LengthPercentage::Percentage(b)),
) => { ) => {
return a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal); return a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal);
}, },
@ -698,16 +698,16 @@ impl generic::LineDirection for LineDirection {
// These percentage values can also be keywords. // These percentage values can also be keywords.
let x = match *x { let x = match *x {
OriginComponent::Center => true, OriginComponent::Center => true,
OriginComponent::Length(LengthOrPercentage::Percentage( OriginComponent::Length(LengthPercentage::Percentage(ComputedPercentage(
ComputedPercentage(val), val,
)) => val == 0.5, ))) => val == 0.5,
_ => false, _ => false,
}; };
let y = match *y { let y = match *y {
OriginComponent::Side(Y::Top) => true, OriginComponent::Side(Y::Top) => true,
OriginComponent::Length(LengthOrPercentage::Percentage( OriginComponent::Length(LengthPercentage::Percentage(ComputedPercentage(
ComputedPercentage(val), val,
)) => val == 0.0, ))) => val == 0.0,
_ => false, _ => false,
}; };
x && y x && y
@ -876,8 +876,8 @@ impl EndingShape {
} }
if compat_mode == CompatMode::Modern { if compat_mode == CompatMode::Modern {
let pair: Result<_, ParseError> = input.try(|i| { let pair: Result<_, ParseError> = input.try(|i| {
let x = LengthOrPercentage::parse(context, i)?; let x = LengthPercentage::parse(context, i)?;
let y = LengthOrPercentage::parse(context, i)?; let y = LengthPercentage::parse(context, i)?;
Ok((x, y)) Ok((x, y))
}); });
if let Ok((x, y)) = pair { if let Ok((x, y)) = pair {
@ -888,11 +888,11 @@ impl EndingShape {
ShapeExtent::FarthestCorner, ShapeExtent::FarthestCorner,
))); )));
} }
// -moz- prefixed radial gradient doesn't allow EndingShape's Length or LengthOrPercentage // -moz- prefixed radial gradient doesn't allow EndingShape's Length or LengthPercentage
// to come before shape keyword. Otherwise it conflicts with <position>. // to come before shape keyword. Otherwise it conflicts with <position>.
if compat_mode != CompatMode::Moz { if compat_mode != CompatMode::Moz {
if let Ok(length) = input.try(|i| Length::parse(context, i)) { if let Ok(length) = input.try(|i| Length::parse(context, i)) {
if let Ok(y) = input.try(|i| LengthOrPercentage::parse(context, i)) { if let Ok(y) = input.try(|i| LengthPercentage::parse(context, i)) {
if compat_mode == CompatMode::Modern { if compat_mode == CompatMode::Modern {
let _ = input.try(|i| i.expect_ident_matching("ellipse")); let _ = input.try(|i| i.expect_ident_matching("ellipse"));
} }
@ -904,7 +904,7 @@ impl EndingShape {
if compat_mode == CompatMode::Modern { if compat_mode == CompatMode::Modern {
let y = input.try(|i| { let y = input.try(|i| {
i.expect_ident_matching("ellipse")?; i.expect_ident_matching("ellipse")?;
LengthOrPercentage::parse(context, i) LengthPercentage::parse(context, i)
}); });
if let Ok(y) = y { if let Ok(y) = y {
return Ok(generic::EndingShape::Ellipse(Ellipse::Radii( return Ok(generic::EndingShape::Ellipse(Ellipse::Radii(
@ -920,7 +920,7 @@ impl EndingShape {
} }
input.try(|i| { input.try(|i| {
let x = Percentage::parse(context, i)?; let x = Percentage::parse(context, i)?;
let y = if let Ok(y) = i.try(|i| LengthOrPercentage::parse(context, i)) { let y = if let Ok(y) = i.try(|i| LengthPercentage::parse(context, i)) {
if compat_mode == CompatMode::Modern { if compat_mode == CompatMode::Modern {
let _ = i.try(|i| i.expect_ident_matching("ellipse")); let _ = i.try(|i| i.expect_ident_matching("ellipse"));
} }
@ -929,7 +929,7 @@ impl EndingShape {
if compat_mode == CompatMode::Modern { if compat_mode == CompatMode::Modern {
i.expect_ident_matching("ellipse")?; i.expect_ident_matching("ellipse")?;
} }
LengthOrPercentage::parse(context, i)? LengthPercentage::parse(context, i)?
}; };
Ok(generic::EndingShape::Ellipse(Ellipse::Radii(x.into(), y))) Ok(generic::EndingShape::Ellipse(Ellipse::Radii(x.into(), y)))
}) })
@ -963,7 +963,7 @@ impl GradientItem {
loop { loop {
input.parse_until_before(Delimiter::Comma, |input| { input.parse_until_before(Delimiter::Comma, |input| {
if seen_stop { if seen_stop {
if let Ok(hint) = input.try(|i| LengthOrPercentage::parse(context, i)) { if let Ok(hint) = input.try(|i| LengthPercentage::parse(context, i)) {
seen_stop = false; seen_stop = false;
items.push(generic::GradientItem::InterpolationHint(hint)); items.push(generic::GradientItem::InterpolationHint(hint));
return Ok(()); return Ok(());
@ -972,7 +972,7 @@ impl GradientItem {
let stop = ColorStop::parse(context, input)?; let stop = ColorStop::parse(context, input)?;
if let Ok(multi_position) = input.try(|i| LengthOrPercentage::parse(context, i)) { if let Ok(multi_position) = input.try(|i| LengthPercentage::parse(context, i)) {
let stop_color = stop.color.clone(); let stop_color = stop.color.clone();
items.push(generic::GradientItem::ColorStop(stop)); items.push(generic::GradientItem::ColorStop(stop));
items.push(generic::GradientItem::ColorStop(ColorStop { items.push(generic::GradientItem::ColorStop(ColorStop {
@ -1008,7 +1008,7 @@ impl Parse for ColorStop {
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
Ok(ColorStop { Ok(ColorStop {
color: Color::parse(context, input)?, color: Color::parse(context, input)?,
position: input.try(|i| LengthOrPercentage::parse(context, i)).ok(), position: input.try(|i| LengthPercentage::parse(context, i)).ok(),
}) })
} }
} }

View file

@ -26,7 +26,7 @@ use style_traits::{ParseError, SpecifiedValueInfo, StyleParseErrorKind};
pub use super::image::{ColorStop, EndingShape as GradientEndingShape, Gradient}; pub use super::image::{ColorStop, EndingShape as GradientEndingShape, Gradient};
pub use super::image::{GradientKind, Image}; pub use super::image::{GradientKind, Image};
pub use crate::values::specified::calc::CalcLengthOrPercentage; pub use crate::values::specified::calc::CalcLengthPercentage;
/// Number of app units per pixel /// Number of app units per pixel
pub const AU_PER_PX: CSSFloat = 60.; pub const AU_PER_PX: CSSFloat = 60.;
@ -530,7 +530,7 @@ pub enum Length {
/// A calc expression. /// A calc expression.
/// ///
/// <https://drafts.csswg.org/css-values/#calc-notation> /// <https://drafts.csswg.org/css-values/#calc-notation>
Calc(Box<CalcLengthOrPercentage>), Calc(Box<CalcLengthPercentage>),
} }
impl From<NoCalcLength> for Length { impl From<NoCalcLength> for Length {
@ -736,57 +736,66 @@ impl NonNegativeLength {
/// Either a NonNegativeLength or the `auto` keyword. /// Either a NonNegativeLength or the `auto` keyword.
pub type NonNegativeLengthOrAuto = Either<NonNegativeLength, Auto>; pub type NonNegativeLengthOrAuto = Either<NonNegativeLength, Auto>;
/// A length or a percentage value. /// A `<length-percentage>` value. This can be either a `<length>`, a
/// `<percentage>`, or a combination of both via `calc()`.
///
/// https://drafts.csswg.org/css-values-4/#typedef-length-percentage
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)] #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)]
pub enum LengthOrPercentage { pub enum LengthPercentage {
Length(NoCalcLength), Length(NoCalcLength),
Percentage(computed::Percentage), Percentage(computed::Percentage),
Calc(Box<CalcLengthOrPercentage>), Calc(Box<CalcLengthPercentage>),
} }
impl From<Length> for LengthOrPercentage { impl From<Length> for LengthPercentage {
fn from(len: Length) -> LengthOrPercentage { fn from(len: Length) -> LengthPercentage {
match len { match len {
Length::NoCalc(l) => LengthOrPercentage::Length(l), Length::NoCalc(l) => LengthPercentage::Length(l),
Length::Calc(l) => LengthOrPercentage::Calc(l), Length::Calc(l) => LengthPercentage::Calc(l),
} }
} }
} }
impl From<NoCalcLength> for LengthOrPercentage { impl From<NoCalcLength> for LengthPercentage {
#[inline] #[inline]
fn from(len: NoCalcLength) -> Self { fn from(len: NoCalcLength) -> Self {
LengthOrPercentage::Length(len) LengthPercentage::Length(len)
} }
} }
impl From<Percentage> for LengthOrPercentage { impl From<Percentage> for LengthPercentage {
#[inline] #[inline]
fn from(pc: Percentage) -> Self { fn from(pc: Percentage) -> Self {
if pc.is_calc() { if pc.is_calc() {
LengthOrPercentage::Calc(Box::new(CalcLengthOrPercentage { LengthPercentage::Calc(Box::new(CalcLengthPercentage {
percentage: Some(computed::Percentage(pc.get())), percentage: Some(computed::Percentage(pc.get())),
..Default::default() ..Default::default()
})) }))
} else { } else {
LengthOrPercentage::Percentage(computed::Percentage(pc.get())) LengthPercentage::Percentage(computed::Percentage(pc.get()))
} }
} }
} }
impl From<computed::Percentage> for LengthOrPercentage { impl From<computed::Percentage> for LengthPercentage {
#[inline] #[inline]
fn from(pc: computed::Percentage) -> Self { fn from(pc: computed::Percentage) -> Self {
LengthOrPercentage::Percentage(pc) LengthPercentage::Percentage(pc)
} }
} }
impl LengthOrPercentage { impl LengthPercentage {
#[inline] #[inline]
/// Returns a `zero` length. /// Returns a `zero` length.
pub fn zero() -> LengthOrPercentage { pub fn zero() -> LengthPercentage {
LengthOrPercentage::Length(NoCalcLength::zero()) LengthPercentage::Length(NoCalcLength::zero())
}
#[inline]
/// Returns a `0%` value.
pub fn zero_percent() -> LengthPercentage {
LengthPercentage::Percentage(computed::Percentage::zero())
} }
fn parse_internal<'i, 't>( fn parse_internal<'i, 't>(
@ -804,13 +813,13 @@ impl LengthOrPercentage {
value, ref unit, .. value, ref unit, ..
} if num_context.is_ok(context.parsing_mode, value) => { } if num_context.is_ok(context.parsing_mode, value) => {
return NoCalcLength::parse_dimension(context, value, unit) return NoCalcLength::parse_dimension(context, value, unit)
.map(LengthOrPercentage::Length) .map(LengthPercentage::Length)
.map_err(|()| location.new_unexpected_token_error(token.clone())); .map_err(|()| location.new_unexpected_token_error(token.clone()));
}, },
Token::Percentage { unit_value, .. } Token::Percentage { unit_value, .. }
if num_context.is_ok(context.parsing_mode, unit_value) => if num_context.is_ok(context.parsing_mode, unit_value) =>
{ {
return Ok(LengthOrPercentage::Percentage(computed::Percentage( return Ok(LengthPercentage::Percentage(computed::Percentage(
unit_value, unit_value,
))); )));
} }
@ -821,7 +830,7 @@ impl LengthOrPercentage {
{ {
return Err(location.new_unexpected_token_error(token.clone())); return Err(location.new_unexpected_token_error(token.clone()));
} else { } else {
return Ok(LengthOrPercentage::Length(NoCalcLength::from_px(value))); return Ok(LengthPercentage::Length(NoCalcLength::from_px(value)));
} }
}, },
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {}, Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {},
@ -832,7 +841,7 @@ impl LengthOrPercentage {
let calc = input.parse_nested_block(|i| { let calc = input.parse_nested_block(|i| {
CalcNode::parse_length_or_percentage(context, i, num_context) CalcNode::parse_length_or_percentage(context, i, num_context)
})?; })?;
Ok(LengthOrPercentage::Calc(Box::new(calc))) Ok(LengthPercentage::Calc(Box::new(calc)))
} }
/// Parse a non-negative length. /// Parse a non-negative length.
@ -840,7 +849,7 @@ impl LengthOrPercentage {
pub fn parse_non_negative<'i, 't>( pub fn parse_non_negative<'i, 't>(
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<LengthOrPercentage, ParseError<'i>> { ) -> Result<LengthPercentage, ParseError<'i>> {
Self::parse_non_negative_quirky(context, input, AllowQuirks::No) Self::parse_non_negative_quirky(context, input, AllowQuirks::No)
} }
@ -850,7 +859,7 @@ impl LengthOrPercentage {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks, allow_quirks: AllowQuirks,
) -> Result<LengthOrPercentage, ParseError<'i>> { ) -> Result<LengthPercentage, ParseError<'i>> {
Self::parse_internal( Self::parse_internal(
context, context,
input, input,
@ -860,7 +869,7 @@ impl LengthOrPercentage {
} }
} }
impl Parse for LengthOrPercentage { impl Parse for LengthPercentage {
#[inline] #[inline]
fn parse<'i, 't>( fn parse<'i, 't>(
context: &ParserContext, context: &ParserContext,
@ -870,7 +879,7 @@ impl Parse for LengthOrPercentage {
} }
} }
impl LengthOrPercentage { impl LengthPercentage {
/// Parses a length or a percentage, allowing the unitless length quirk. /// Parses a length or a percentage, allowing the unitless length quirk.
/// <https://quirks.spec.whatwg.org/#the-unitless-length-quirk> /// <https://quirks.spec.whatwg.org/#the-unitless-length-quirk>
#[inline] #[inline]
@ -883,13 +892,13 @@ impl LengthOrPercentage {
} }
} }
impl IsZeroLength for LengthOrPercentage { impl IsZeroLength for LengthPercentage {
#[inline] #[inline]
fn is_zero_length(&self) -> bool { fn is_zero_length(&self) -> bool {
match *self { match *self {
LengthOrPercentage::Length(l) => l.is_zero_length(), LengthPercentage::Length(l) => l.is_zero_length(),
LengthOrPercentage::Percentage(p) => p.0 == 0.0, LengthPercentage::Percentage(p) => p.0 == 0.0,
LengthOrPercentage::Calc(_) => false, LengthPercentage::Calc(_) => false,
} }
} }
} }
@ -897,76 +906,25 @@ impl IsZeroLength for LengthOrPercentage {
/// Either a `<length>`, a `<percentage>`, or the `auto` keyword. /// Either a `<length>`, a `<percentage>`, or the `auto` keyword.
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)] #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)]
pub enum LengthOrPercentageOrAuto { pub enum LengthPercentageOrAuto {
Length(NoCalcLength), LengthPercentage(LengthPercentage),
Percentage(computed::Percentage),
Auto, Auto,
Calc(Box<CalcLengthOrPercentage>),
} }
impl From<NoCalcLength> for LengthOrPercentageOrAuto { impl LengthPercentageOrAuto {
#[inline]
fn from(len: NoCalcLength) -> Self {
LengthOrPercentageOrAuto::Length(len)
}
}
impl From<computed::Percentage> for LengthOrPercentageOrAuto {
#[inline]
fn from(pc: computed::Percentage) -> Self {
LengthOrPercentageOrAuto::Percentage(pc)
}
}
impl LengthOrPercentageOrAuto {
fn parse_internal<'i, 't>( fn parse_internal<'i, 't>(
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
num_context: AllowedNumericType, num_context: AllowedNumericType,
allow_quirks: AllowQuirks, allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
// FIXME: remove early returns when lifetimes are non-lexical if input.try(|i| i.expect_ident_matching("auto")).is_ok() {
{ return Ok(LengthPercentageOrAuto::Auto);
let location = input.current_source_location();
let token = input.next()?;
match *token {
Token::Dimension {
value, ref unit, ..
} if num_context.is_ok(context.parsing_mode, value) => {
return NoCalcLength::parse_dimension(context, value, unit)
.map(LengthOrPercentageOrAuto::Length)
.map_err(|()| location.new_unexpected_token_error(token.clone()));
},
Token::Percentage { unit_value, .. }
if num_context.is_ok(context.parsing_mode, unit_value) =>
{
return Ok(LengthOrPercentageOrAuto::Percentage(computed::Percentage(
unit_value,
)));
}
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. &&
!context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode)
{
return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
return Ok(LengthOrPercentageOrAuto::Length(NoCalcLength::Absolute(
AbsoluteLength::Px(value),
)));
},
Token::Ident(ref value) if value.eq_ignore_ascii_case("auto") => {
return Ok(LengthOrPercentageOrAuto::Auto);
},
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {},
_ => return Err(location.new_unexpected_token_error(token.clone())),
}
} }
let calc = input.parse_nested_block(|i| { Ok(LengthPercentageOrAuto::LengthPercentage(
CalcNode::parse_length_or_percentage(context, i, num_context) LengthPercentage::parse_internal(context, input, num_context, allow_quirks)?,
})?; ))
Ok(LengthOrPercentageOrAuto::Calc(Box::new(calc)))
} }
/// Parse a non-negative length, percentage, or auto. /// Parse a non-negative length, percentage, or auto.
@ -974,7 +932,7 @@ impl LengthOrPercentageOrAuto {
pub fn parse_non_negative<'i, 't>( pub fn parse_non_negative<'i, 't>(
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<LengthOrPercentageOrAuto, ParseError<'i>> { ) -> Result<LengthPercentageOrAuto, ParseError<'i>> {
Self::parse_non_negative_quirky(context, input, AllowQuirks::No) Self::parse_non_negative_quirky(context, input, AllowQuirks::No)
} }
@ -995,18 +953,18 @@ impl LengthOrPercentageOrAuto {
/// Returns the `auto` value. /// Returns the `auto` value.
pub fn auto() -> Self { pub fn auto() -> Self {
LengthOrPercentageOrAuto::Auto LengthPercentageOrAuto::Auto
} }
/// Returns a value representing a `0` length. /// Returns a value representing a `0` length.
pub fn zero() -> Self { pub fn zero() -> Self {
LengthOrPercentageOrAuto::Length(NoCalcLength::zero()) LengthPercentageOrAuto::LengthPercentage(LengthPercentage::zero())
} }
/// Returns a value representing `0%`. /// Returns a value representing `0%`.
#[inline] #[inline]
pub fn zero_percent() -> Self { pub fn zero_percent() -> Self {
LengthOrPercentageOrAuto::Percentage(computed::Percentage::zero()) LengthPercentageOrAuto::LengthPercentage(LengthPercentage::zero_percent())
} }
/// Parses, with quirks. /// Parses, with quirks.
@ -1020,7 +978,7 @@ impl LengthOrPercentageOrAuto {
} }
} }
impl Parse for LengthOrPercentageOrAuto { impl Parse for LengthPercentageOrAuto {
#[inline] #[inline]
fn parse<'i, 't>( fn parse<'i, 't>(
context: &ParserContext, context: &ParserContext,
@ -1030,43 +988,43 @@ impl Parse for LengthOrPercentageOrAuto {
} }
} }
/// A wrapper of LengthOrPercentageOrAuto, whose value must be >= 0. /// A wrapper of LengthPercentageOrAuto, whose value must be >= 0.
pub type NonNegativeLengthOrPercentageOrAuto = NonNegative<LengthOrPercentageOrAuto>; pub type NonNegativeLengthPercentageOrAuto = NonNegative<LengthPercentageOrAuto>;
impl IsAuto for NonNegativeLengthOrPercentageOrAuto { impl IsAuto for NonNegativeLengthPercentageOrAuto {
#[inline] #[inline]
fn is_auto(&self) -> bool { fn is_auto(&self) -> bool {
*self == Self::auto() *self == Self::auto()
} }
} }
impl NonNegativeLengthOrPercentageOrAuto { impl NonNegativeLengthPercentageOrAuto {
/// 0 /// 0
#[inline] #[inline]
pub fn zero() -> Self { pub fn zero() -> Self {
NonNegative(LengthOrPercentageOrAuto::zero()) NonNegative(LengthPercentageOrAuto::zero())
} }
/// 0% /// 0%
#[inline] #[inline]
pub fn zero_percent() -> Self { pub fn zero_percent() -> Self {
NonNegative(LengthOrPercentageOrAuto::zero_percent()) NonNegative(LengthPercentageOrAuto::zero_percent())
} }
/// `auto` /// `auto`
#[inline] #[inline]
pub fn auto() -> Self { pub fn auto() -> Self {
NonNegative(LengthOrPercentageOrAuto::Auto) NonNegative(LengthPercentageOrAuto::Auto)
} }
} }
impl Parse for NonNegativeLengthOrPercentageOrAuto { impl Parse for NonNegativeLengthPercentageOrAuto {
#[inline] #[inline]
fn parse<'i, 't>( fn parse<'i, 't>(
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
Ok(NonNegative(LengthOrPercentageOrAuto::parse_non_negative( Ok(NonNegative(LengthPercentageOrAuto::parse_non_negative(
context, input, context, input,
)?)) )?))
} }
@ -1075,65 +1033,28 @@ impl Parse for NonNegativeLengthOrPercentageOrAuto {
/// Either a `<length>`, a `<percentage>`, or the `none` keyword. /// Either a `<length>`, a `<percentage>`, or the `none` keyword.
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)] #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)]
#[allow(missing_docs)] #[allow(missing_docs)]
pub enum LengthOrPercentageOrNone { pub enum LengthPercentageOrNone {
Length(NoCalcLength), LengthPercentage(LengthPercentage),
Percentage(computed::Percentage),
Calc(Box<CalcLengthOrPercentage>),
None, None,
} }
impl LengthOrPercentageOrNone { impl LengthPercentageOrNone {
fn parse_internal<'i, 't>( fn parse_internal<'i, 't>(
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
num_context: AllowedNumericType, num_context: AllowedNumericType,
allow_quirks: AllowQuirks, allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
// FIXME: remove early returns when lifetimes are non-lexical if input.try(|i| i.expect_ident_matching("none")).is_ok() {
{ return Ok(LengthPercentageOrNone::None);
let location = input.current_source_location();
let token = input.next()?;
match *token {
Token::Dimension {
value, ref unit, ..
} if num_context.is_ok(context.parsing_mode, value) => {
return NoCalcLength::parse_dimension(context, value, unit)
.map(LengthOrPercentageOrNone::Length)
.map_err(|()| location.new_unexpected_token_error(token.clone()));
},
Token::Percentage { unit_value, .. }
if num_context.is_ok(context.parsing_mode, unit_value) =>
{
return Ok(LengthOrPercentageOrNone::Percentage(computed::Percentage(
unit_value,
)));
}
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. &&
!context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode)
{
return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
return Ok(LengthOrPercentageOrNone::Length(NoCalcLength::Absolute(
AbsoluteLength::Px(value),
)));
},
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {},
Token::Ident(ref value) if value.eq_ignore_ascii_case("none") => {
return Ok(LengthOrPercentageOrNone::None);
},
_ => return Err(location.new_unexpected_token_error(token.clone())),
}
} }
let calc = input.parse_nested_block(|i| { Ok(LengthPercentageOrNone::LengthPercentage(
CalcNode::parse_length_or_percentage(context, i, num_context) LengthPercentage::parse_internal(context, input, num_context, allow_quirks)?,
})?; ))
Ok(LengthOrPercentageOrNone::Calc(Box::new(calc)))
} }
/// Parse a non-negative LengthOrPercentageOrNone. /// Parse a non-negative LengthPercentageOrNone.
#[inline] #[inline]
pub fn parse_non_negative<'i, 't>( pub fn parse_non_negative<'i, 't>(
context: &ParserContext, context: &ParserContext,
@ -1142,7 +1063,7 @@ impl LengthOrPercentageOrNone {
Self::parse_non_negative_quirky(context, input, AllowQuirks::No) Self::parse_non_negative_quirky(context, input, AllowQuirks::No)
} }
/// Parse a non-negative LengthOrPercentageOrNone, with quirks. /// Parse a non-negative LengthPercentageOrNone, with quirks.
#[inline] #[inline]
pub fn parse_non_negative_quirky<'i, 't>( pub fn parse_non_negative_quirky<'i, 't>(
context: &ParserContext, context: &ParserContext,
@ -1158,7 +1079,7 @@ impl LengthOrPercentageOrNone {
} }
} }
impl Parse for LengthOrPercentageOrNone { impl Parse for LengthPercentageOrNone {
#[inline] #[inline]
fn parse<'i, 't>( fn parse<'i, 't>(
context: &ParserContext, context: &ParserContext,
@ -1168,38 +1089,37 @@ impl Parse for LengthOrPercentageOrNone {
} }
} }
/// A wrapper of LengthOrPercentage, whose value must be >= 0. /// A wrapper of LengthPercentage, whose value must be >= 0.
pub type NonNegativeLengthOrPercentage = NonNegative<LengthOrPercentage>; pub type NonNegativeLengthPercentage = NonNegative<LengthPercentage>;
/// Either a computed NonNegativeLength or the `normal` keyword. /// Either a computed NonNegativeLength or the `normal` keyword.
pub type NonNegativeLengthOrNormal = Either<NonNegativeLength, Normal>; pub type NonNegativeLengthOrNormal = Either<NonNegativeLength, Normal>;
/// Either a NonNegativeLengthOrPercentage or the `normal` keyword. /// Either a NonNegativeLengthPercentage or the `normal` keyword.
pub type NonNegativeLengthOrPercentageOrNormal = Either<NonNegativeLengthOrPercentage, Normal>; pub type NonNegativeLengthPercentageOrNormal = Either<NonNegativeLengthPercentage, Normal>;
impl From<NoCalcLength> for NonNegativeLengthOrPercentage { impl From<NoCalcLength> for NonNegativeLengthPercentage {
#[inline] #[inline]
fn from(len: NoCalcLength) -> Self { fn from(len: NoCalcLength) -> Self {
NonNegative::<LengthOrPercentage>(LengthOrPercentage::from(len)) NonNegative::<LengthPercentage>(LengthPercentage::from(len))
} }
} }
impl Parse for NonNegativeLengthOrPercentage { impl Parse for NonNegativeLengthPercentage {
#[inline] #[inline]
fn parse<'i, 't>( fn parse<'i, 't>(
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
LengthOrPercentage::parse_non_negative(context, input) LengthPercentage::parse_non_negative(context, input).map(NonNegative::<LengthPercentage>)
.map(NonNegative::<LengthOrPercentage>)
} }
} }
impl NonNegativeLengthOrPercentage { impl NonNegativeLengthPercentage {
#[inline] #[inline]
/// Returns a `zero` length. /// Returns a `zero` length.
pub fn zero() -> Self { pub fn zero() -> Self {
NonNegative::<LengthOrPercentage>(LengthOrPercentage::zero()) NonNegative::<LengthPercentage>(LengthPercentage::zero())
} }
/// Parses a length or a percentage, allowing the unitless length quirk. /// Parses a length or a percentage, allowing the unitless length quirk.
@ -1210,8 +1130,8 @@ impl NonNegativeLengthOrPercentage {
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks, allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
LengthOrPercentage::parse_non_negative_quirky(context, input, allow_quirks) LengthPercentage::parse_non_negative_quirky(context, input, allow_quirks)
.map(NonNegative::<LengthOrPercentage>) .map(NonNegative::<LengthPercentage>)
} }
} }
@ -1248,7 +1168,7 @@ impl LengthOrNumber {
} }
/// A specified value for `min-width`, `min-height`, `width` or `height` property. /// A specified value for `min-width`, `min-height`, `width` or `height` property.
pub type MozLength = GenericMozLength<LengthOrPercentageOrAuto>; pub type MozLength = GenericMozLength<LengthPercentageOrAuto>;
impl Parse for MozLength { impl Parse for MozLength {
fn parse<'i, 't>( fn parse<'i, 't>(
@ -1271,25 +1191,25 @@ impl MozLength {
} }
let length = let length =
LengthOrPercentageOrAuto::parse_non_negative_quirky(context, input, allow_quirks)?; LengthPercentageOrAuto::parse_non_negative_quirky(context, input, allow_quirks)?;
Ok(GenericMozLength::LengthOrPercentageOrAuto(length)) Ok(GenericMozLength::LengthPercentageOrAuto(length))
} }
/// Returns `auto`. /// Returns `auto`.
#[inline] #[inline]
pub fn auto() -> Self { pub fn auto() -> Self {
GenericMozLength::LengthOrPercentageOrAuto(LengthOrPercentageOrAuto::auto()) GenericMozLength::LengthPercentageOrAuto(LengthPercentageOrAuto::auto())
} }
/// Returns `0%`. /// Returns `0%`.
#[inline] #[inline]
pub fn zero_percent() -> Self { pub fn zero_percent() -> Self {
GenericMozLength::LengthOrPercentageOrAuto(LengthOrPercentageOrAuto::zero_percent()) GenericMozLength::LengthPercentageOrAuto(LengthPercentageOrAuto::zero_percent())
} }
} }
/// A specified value for `max-width` or `max-height` property. /// A specified value for `max-width` or `max-height` property.
pub type MaxLength = GenericMaxLength<LengthOrPercentageOrNone>; pub type MaxLength = GenericMaxLength<LengthPercentageOrNone>;
impl Parse for MaxLength { impl Parse for MaxLength {
fn parse<'i, 't>( fn parse<'i, 't>(
@ -1312,7 +1232,7 @@ impl MaxLength {
} }
let length = let length =
LengthOrPercentageOrNone::parse_non_negative_quirky(context, input, allow_quirks)?; LengthPercentageOrNone::parse_non_negative_quirky(context, input, allow_quirks)?;
Ok(GenericMaxLength::LengthOrPercentageOrNone(length)) Ok(GenericMaxLength::LengthPercentageOrNone(length))
} }
} }

View file

@ -55,12 +55,12 @@ pub use self::font::{MozScriptLevel, MozScriptMinSize, MozScriptSizeMultiplier,
pub use self::gecko::ScrollSnapPoint; pub use self::gecko::ScrollSnapPoint;
pub use self::image::{ColorStop, EndingShape as GradientEndingShape, Gradient}; pub use self::image::{ColorStop, EndingShape as GradientEndingShape, Gradient};
pub use self::image::{GradientItem, GradientKind, Image, ImageLayer, MozImageRect}; pub use self::image::{GradientItem, GradientKind, Image, ImageLayer, MozImageRect};
pub use self::length::{AbsoluteLength, CalcLengthOrPercentage, CharacterWidth}; pub use self::length::{AbsoluteLength, CalcLengthPercentage, CharacterWidth};
pub use self::length::{FontRelativeLength, Length, LengthOrNumber}; pub use self::length::{FontRelativeLength, Length, LengthOrNumber};
pub use self::length::{LengthOrPercentage, LengthOrPercentageOrAuto}; pub use self::length::{LengthPercentage, LengthPercentageOrAuto};
pub use self::length::{LengthOrPercentageOrNone, MaxLength, MozLength}; pub use self::length::{LengthPercentageOrNone, MaxLength, MozLength};
pub use self::length::{NoCalcLength, ViewportPercentageLength}; pub use self::length::{NoCalcLength, ViewportPercentageLength};
pub use self::length::{NonNegativeLengthOrPercentage, NonNegativeLengthOrPercentageOrAuto}; pub use self::length::{NonNegativeLengthPercentage, NonNegativeLengthPercentageOrAuto};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
pub use self::list::ListStyleType; pub use self::list::ListStyleType;
pub use self::list::{QuotePair, Quotes}; pub use self::list::{QuotePair, Quotes};
@ -567,20 +567,20 @@ impl Parse for PositiveInteger {
} }
/// The specified value of a grid `<track-breadth>` /// The specified value of a grid `<track-breadth>`
pub type TrackBreadth = GenericTrackBreadth<LengthOrPercentage>; pub type TrackBreadth = GenericTrackBreadth<LengthPercentage>;
/// The specified value of a grid `<track-size>` /// The specified value of a grid `<track-size>`
pub type TrackSize = GenericTrackSize<LengthOrPercentage>; pub type TrackSize = GenericTrackSize<LengthPercentage>;
/// The specified value of a grid `<track-list>` /// The specified value of a grid `<track-list>`
/// (could also be `<auto-track-list>` or `<explicit-track-list>`) /// (could also be `<auto-track-list>` or `<explicit-track-list>`)
pub type TrackList = GenericTrackList<LengthOrPercentage, Integer>; pub type TrackList = GenericTrackList<LengthPercentage, Integer>;
/// The specified value of a `<grid-line>`. /// The specified value of a `<grid-line>`.
pub type GridLine = GenericGridLine<Integer>; pub type GridLine = GenericGridLine<Integer>;
/// `<grid-template-rows> | <grid-template-columns>` /// `<grid-template-rows> | <grid-template-columns>`
pub type GridTemplateComponent = GenericGridTemplateComponent<LengthOrPercentage, Integer>; pub type GridTemplateComponent = GenericGridTemplateComponent<LengthPercentage, Integer>;
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo)] #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo)]
/// rect(<top>, <left>, <bottom>, <right>) used by clip and image-region /// rect(<top>, <left>, <bottom>, <right>) used by clip and image-region

View file

@ -10,13 +10,12 @@
use crate::hash::FxHashMap; use crate::hash::FxHashMap;
use crate::parser::{Parse, ParserContext}; use crate::parser::{Parse, ParserContext};
use crate::str::HTML_SPACE_CHARACTERS; use crate::str::HTML_SPACE_CHARACTERS;
use crate::values::computed::CalcLengthOrPercentage; use crate::values::computed::LengthPercentage as ComputedLengthPercentage;
use crate::values::computed::LengthOrPercentage as ComputedLengthOrPercentage;
use crate::values::computed::{Context, Percentage, ToComputedValue}; use crate::values::computed::{Context, Percentage, ToComputedValue};
use crate::values::generics::position::Position as GenericPosition; use crate::values::generics::position::Position as GenericPosition;
use crate::values::generics::position::ZIndex as GenericZIndex; use crate::values::generics::position::ZIndex as GenericZIndex;
use crate::values::specified::transform::OriginComponent; use crate::values::specified::transform::OriginComponent;
use crate::values::specified::{AllowQuirks, Integer, LengthOrPercentage}; use crate::values::specified::{AllowQuirks, Integer, LengthPercentage};
use crate::values::{Either, None_}; use crate::values::{Either, None_};
use cssparser::Parser; use cssparser::Parser;
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
@ -39,10 +38,10 @@ pub type VerticalPosition = PositionComponent<Y>;
pub enum PositionComponent<S> { pub enum PositionComponent<S> {
/// `center` /// `center`
Center, Center,
/// `<lop>` /// `<length-percentage>`
Length(LengthOrPercentage), Length(LengthPercentage),
/// `<side> <lop>?` /// `<side> <length-percentage>?`
Side(S, Option<LengthOrPercentage>), Side(S, Option<LengthPercentage>),
} }
/// A keyword for the X direction. /// A keyword for the X direction.
@ -114,22 +113,22 @@ impl Position {
let y_pos = PositionComponent::Center; let y_pos = PositionComponent::Center;
return Ok(Self::new(x_pos, y_pos)); return Ok(Self::new(x_pos, y_pos));
}, },
Ok(PositionComponent::Side(x_keyword, lop)) => { Ok(PositionComponent::Side(x_keyword, lp)) => {
if input.try(|i| i.expect_ident_matching("center")).is_ok() { if input.try(|i| i.expect_ident_matching("center")).is_ok() {
let x_pos = PositionComponent::Side(x_keyword, lop); let x_pos = PositionComponent::Side(x_keyword, lp);
let y_pos = PositionComponent::Center; let y_pos = PositionComponent::Center;
return Ok(Self::new(x_pos, y_pos)); return Ok(Self::new(x_pos, y_pos));
} }
if let Ok(y_keyword) = input.try(Y::parse) { if let Ok(y_keyword) = input.try(Y::parse) {
let y_lop = input let y_lp = input
.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) .try(|i| LengthPercentage::parse_quirky(context, i, allow_quirks))
.ok(); .ok();
let x_pos = PositionComponent::Side(x_keyword, lop); let x_pos = PositionComponent::Side(x_keyword, lp);
let y_pos = PositionComponent::Side(y_keyword, y_lop); let y_pos = PositionComponent::Side(y_keyword, y_lp);
return Ok(Self::new(x_pos, y_pos)); return Ok(Self::new(x_pos, y_pos));
} }
let x_pos = PositionComponent::Side(x_keyword, None); let x_pos = PositionComponent::Side(x_keyword, None);
let y_pos = lop.map_or(PositionComponent::Center, PositionComponent::Length); let y_pos = lp.map_or(PositionComponent::Center, PositionComponent::Length);
return Ok(Self::new(x_pos, y_pos)); return Ok(Self::new(x_pos, y_pos));
}, },
Ok(x_pos @ PositionComponent::Length(_)) => { Ok(x_pos @ PositionComponent::Length(_)) => {
@ -137,10 +136,10 @@ impl Position {
let y_pos = PositionComponent::Side(y_keyword, None); let y_pos = PositionComponent::Side(y_keyword, None);
return Ok(Self::new(x_pos, y_pos)); return Ok(Self::new(x_pos, y_pos));
} }
if let Ok(y_lop) = if let Ok(y_lp) =
input.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) input.try(|i| LengthPercentage::parse_quirky(context, i, allow_quirks))
{ {
let y_pos = PositionComponent::Length(y_lop); let y_pos = PositionComponent::Length(y_lp);
return Ok(Self::new(x_pos, y_pos)); return Ok(Self::new(x_pos, y_pos));
} }
let y_pos = PositionComponent::Center; let y_pos = PositionComponent::Center;
@ -150,23 +149,23 @@ impl Position {
Err(_) => {}, Err(_) => {},
} }
let y_keyword = Y::parse(input)?; let y_keyword = Y::parse(input)?;
let lop_and_x_pos: Result<_, ParseError> = input.try(|i| { let lp_and_x_pos: Result<_, ParseError> = input.try(|i| {
let y_lop = i let y_lp = i
.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) .try(|i| LengthPercentage::parse_quirky(context, i, allow_quirks))
.ok(); .ok();
if let Ok(x_keyword) = i.try(X::parse) { if let Ok(x_keyword) = i.try(X::parse) {
let x_lop = i let x_lp = i
.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) .try(|i| LengthPercentage::parse_quirky(context, i, allow_quirks))
.ok(); .ok();
let x_pos = PositionComponent::Side(x_keyword, x_lop); let x_pos = PositionComponent::Side(x_keyword, x_lp);
return Ok((y_lop, x_pos)); return Ok((y_lp, x_pos));
}; };
i.expect_ident_matching("center")?; i.expect_ident_matching("center")?;
let x_pos = PositionComponent::Center; let x_pos = PositionComponent::Center;
Ok((y_lop, x_pos)) Ok((y_lp, x_pos))
}); });
if let Ok((y_lop, x_pos)) = lop_and_x_pos { if let Ok((y_lp, x_pos)) = lp_and_x_pos {
let y_pos = PositionComponent::Side(y_keyword, y_lop); let y_pos = PositionComponent::Side(y_keyword, y_lp);
return Ok(Self::new(x_pos, y_pos)); return Ok(Self::new(x_pos, y_pos));
} }
let x_pos = PositionComponent::Center; let x_pos = PositionComponent::Center;
@ -189,18 +188,18 @@ impl ToCss for Position {
match (&self.horizontal, &self.vertical) { match (&self.horizontal, &self.vertical) {
( (
x_pos @ &PositionComponent::Side(_, Some(_)), x_pos @ &PositionComponent::Side(_, Some(_)),
&PositionComponent::Length(ref y_lop), &PositionComponent::Length(ref y_lp),
) => { ) => {
x_pos.to_css(dest)?; x_pos.to_css(dest)?;
dest.write_str(" top ")?; dest.write_str(" top ")?;
y_lop.to_css(dest) y_lp.to_css(dest)
}, },
( (
&PositionComponent::Length(ref x_lop), &PositionComponent::Length(ref x_lp),
y_pos @ &PositionComponent::Side(_, Some(_)), y_pos @ &PositionComponent::Side(_, Some(_)),
) => { ) => {
dest.write_str("left ")?; dest.write_str("left ")?;
x_lop.to_css(dest)?; x_lp.to_css(dest)?;
dest.write_str(" ")?; dest.write_str(" ")?;
y_pos.to_css(dest) y_pos.to_css(dest)
}, },
@ -232,48 +231,44 @@ impl<S: Parse> PositionComponent<S> {
if input.try(|i| i.expect_ident_matching("center")).is_ok() { if input.try(|i| i.expect_ident_matching("center")).is_ok() {
return Ok(PositionComponent::Center); return Ok(PositionComponent::Center);
} }
if let Ok(lop) = input.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) { if let Ok(lp) = input.try(|i| LengthPercentage::parse_quirky(context, i, allow_quirks)) {
return Ok(PositionComponent::Length(lop)); return Ok(PositionComponent::Length(lp));
} }
let keyword = S::parse(context, input)?; let keyword = S::parse(context, input)?;
let lop = input let lp = input
.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) .try(|i| LengthPercentage::parse_quirky(context, i, allow_quirks))
.ok(); .ok();
Ok(PositionComponent::Side(keyword, lop)) Ok(PositionComponent::Side(keyword, lp))
} }
} }
impl<S> PositionComponent<S> { impl<S> PositionComponent<S> {
/// `0%` /// `0%`
pub fn zero() -> Self { pub fn zero() -> Self {
PositionComponent::Length(LengthOrPercentage::Percentage(Percentage::zero())) PositionComponent::Length(LengthPercentage::Percentage(Percentage::zero()))
} }
} }
impl<S: Side> ToComputedValue for PositionComponent<S> { impl<S: Side> ToComputedValue for PositionComponent<S> {
type ComputedValue = ComputedLengthOrPercentage; type ComputedValue = ComputedLengthPercentage;
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
match *self { match *self {
PositionComponent::Center => ComputedLengthOrPercentage::Percentage(Percentage(0.5)), PositionComponent::Center => ComputedLengthPercentage::new_percent(Percentage(0.5)),
PositionComponent::Side(ref keyword, None) => { PositionComponent::Side(ref keyword, None) => {
let p = Percentage(if keyword.is_start() { 0. } else { 1. }); let p = Percentage(if keyword.is_start() { 0. } else { 1. });
ComputedLengthOrPercentage::Percentage(p) ComputedLengthPercentage::new_percent(p)
}, },
PositionComponent::Side(ref keyword, Some(ref length)) if !keyword.is_start() => { PositionComponent::Side(ref keyword, Some(ref length)) if !keyword.is_start() => {
match length.to_computed_value(context) { let length = length.to_computed_value(context);
ComputedLengthOrPercentage::Length(length) => ComputedLengthOrPercentage::Calc( let p = Percentage(1. - length.percentage());
CalcLengthOrPercentage::new(-length, Some(Percentage::hundred())), let l = -length.unclamped_length();
), ComputedLengthPercentage::with_clamping_mode(
ComputedLengthOrPercentage::Percentage(p) => { l,
ComputedLengthOrPercentage::Percentage(Percentage(1.0 - p.0)) Some(p),
}, length.clamping_mode,
ComputedLengthOrPercentage::Calc(calc) => { length.was_calc,
let p = Percentage(1. - calc.percentage.map_or(0., |p| p.0)); )
let l = -calc.unclamped_length();
ComputedLengthOrPercentage::Calc(CalcLengthOrPercentage::new(l, Some(p)))
},
}
}, },
PositionComponent::Side(_, Some(ref length)) | PositionComponent::Side(_, Some(ref length)) |
PositionComponent::Length(ref length) => length.to_computed_value(context), PositionComponent::Length(ref length) => length.to_computed_value(context),
@ -376,10 +371,10 @@ impl LegacyPosition {
return Ok(Self::new(x_pos, y_pos)); return Ok(Self::new(x_pos, y_pos));
} }
let x_pos = OriginComponent::Side(x_keyword); let x_pos = OriginComponent::Side(x_keyword);
if let Ok(y_lop) = if let Ok(y_lp) =
input.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) input.try(|i| LengthPercentage::parse_quirky(context, i, allow_quirks))
{ {
return Ok(Self::new(x_pos, OriginComponent::Length(y_lop))); return Ok(Self::new(x_pos, OriginComponent::Length(y_lp)));
} }
let _ = input.try(|i| i.expect_ident_matching("center")); let _ = input.try(|i| i.expect_ident_matching("center"));
return Ok(Self::new(x_pos, OriginComponent::Center)); return Ok(Self::new(x_pos, OriginComponent::Center));
@ -389,10 +384,10 @@ impl LegacyPosition {
let y_pos = OriginComponent::Side(y_keyword); let y_pos = OriginComponent::Side(y_keyword);
return Ok(Self::new(x_pos, y_pos)); return Ok(Self::new(x_pos, y_pos));
} }
if let Ok(y_lop) = if let Ok(y_lp) =
input.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) input.try(|i| LengthPercentage::parse_quirky(context, i, allow_quirks))
{ {
let y_pos = OriginComponent::Length(y_lop); let y_pos = OriginComponent::Length(y_lp);
return Ok(Self::new(x_pos, y_pos)); return Ok(Self::new(x_pos, y_pos));
} }
let _ = input.try(|i| i.expect_ident_matching("center")); let _ = input.try(|i| i.expect_ident_matching("center"));

View file

@ -8,8 +8,8 @@ use crate::parser::{Parse, ParserContext};
use crate::values::generics::svg as generic; use crate::values::generics::svg as generic;
use crate::values::specified::color::Color; use crate::values::specified::color::Color;
use crate::values::specified::url::SpecifiedUrl; use crate::values::specified::url::SpecifiedUrl;
use crate::values::specified::LengthOrPercentage; use crate::values::specified::LengthPercentage;
use crate::values::specified::{NonNegativeLengthOrPercentage, NonNegativeNumber}; use crate::values::specified::{NonNegativeLengthPercentage, NonNegativeNumber};
use crate::values::specified::{Number, Opacity}; use crate::values::specified::{Number, Opacity};
use crate::values::CustomIdent; use crate::values::CustomIdent;
use cssparser::Parser; use cssparser::Parser;
@ -50,11 +50,11 @@ fn parse_context_value<'i, 't, T>(
/// A value of <length> | <percentage> | <number> for stroke-dashoffset. /// A value of <length> | <percentage> | <number> for stroke-dashoffset.
/// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties>
pub type SvgLengthOrPercentageOrNumber = pub type SvgLengthPercentageOrNumber =
generic::SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number>; generic::SvgLengthPercentageOrNumber<LengthPercentage, Number>;
/// <length> | <percentage> | <number> | context-value /// <length> | <percentage> | <number> | context-value
pub type SVGLength = generic::SVGLength<SvgLengthOrPercentageOrNumber>; pub type SVGLength = generic::SVGLength<SvgLengthPercentageOrNumber>;
impl Parse for SVGLength { impl Parse for SVGLength {
fn parse<'i, 't>( fn parse<'i, 't>(
@ -62,25 +62,25 @@ impl Parse for SVGLength {
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
input input
.try(|i| SvgLengthOrPercentageOrNumber::parse(context, i)) .try(|i| SvgLengthPercentageOrNumber::parse(context, i))
.map(Into::into) .map(Into::into)
.or_else(|_| parse_context_value(input, generic::SVGLength::ContextValue)) .or_else(|_| parse_context_value(input, generic::SVGLength::ContextValue))
} }
} }
impl From<SvgLengthOrPercentageOrNumber> for SVGLength { impl From<SvgLengthPercentageOrNumber> for SVGLength {
fn from(length: SvgLengthOrPercentageOrNumber) -> Self { fn from(length: SvgLengthPercentageOrNumber) -> Self {
generic::SVGLength::Length(length) generic::SVGLength::Length(length)
} }
} }
/// A value of <length> | <percentage> | <number> for stroke-width/stroke-dasharray. /// A value of <length> | <percentage> | <number> for stroke-width/stroke-dasharray.
/// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties>
pub type NonNegativeSvgLengthOrPercentageOrNumber = pub type NonNegativeSvgLengthPercentageOrNumber =
generic::SvgLengthOrPercentageOrNumber<NonNegativeLengthOrPercentage, NonNegativeNumber>; generic::SvgLengthPercentageOrNumber<NonNegativeLengthPercentage, NonNegativeNumber>;
/// A non-negative version of SVGLength. /// A non-negative version of SVGLength.
pub type SVGWidth = generic::SVGLength<NonNegativeSvgLengthOrPercentageOrNumber>; pub type SVGWidth = generic::SVGLength<NonNegativeSvgLengthPercentageOrNumber>;
impl Parse for SVGWidth { impl Parse for SVGWidth {
fn parse<'i, 't>( fn parse<'i, 't>(
@ -88,20 +88,20 @@ impl Parse for SVGWidth {
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
input input
.try(|i| NonNegativeSvgLengthOrPercentageOrNumber::parse(context, i)) .try(|i| NonNegativeSvgLengthPercentageOrNumber::parse(context, i))
.map(Into::into) .map(Into::into)
.or_else(|_| parse_context_value(input, generic::SVGLength::ContextValue)) .or_else(|_| parse_context_value(input, generic::SVGLength::ContextValue))
} }
} }
impl From<NonNegativeSvgLengthOrPercentageOrNumber> for SVGWidth { impl From<NonNegativeSvgLengthPercentageOrNumber> for SVGWidth {
fn from(length: NonNegativeSvgLengthOrPercentageOrNumber) -> Self { fn from(length: NonNegativeSvgLengthPercentageOrNumber) -> Self {
generic::SVGLength::Length(length) generic::SVGLength::Length(length)
} }
} }
/// [ <length> | <percentage> | <number> ]# | context-value /// [ <length> | <percentage> | <number> ]# | context-value
pub type SVGStrokeDashArray = generic::SVGStrokeDashArray<NonNegativeSvgLengthOrPercentageOrNumber>; pub type SVGStrokeDashArray = generic::SVGStrokeDashArray<NonNegativeSvgLengthPercentageOrNumber>;
impl Parse for SVGStrokeDashArray { impl Parse for SVGStrokeDashArray {
fn parse<'i, 't>( fn parse<'i, 't>(
@ -110,7 +110,7 @@ impl Parse for SVGStrokeDashArray {
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
if let Ok(values) = input.try(|i| { if let Ok(values) = input.try(|i| {
CommaWithSpace::parse(i, |i| { CommaWithSpace::parse(i, |i| {
NonNegativeSvgLengthOrPercentageOrNumber::parse(context, i) NonNegativeSvgLengthPercentageOrNumber::parse(context, i)
}) })
}) { }) {
Ok(generic::SVGStrokeDashArray::Values(values)) Ok(generic::SVGStrokeDashArray::Values(values))

View file

@ -16,8 +16,8 @@ use crate::values::generics::text::LineHeight as GenericLineHeight;
use crate::values::generics::text::MozTabSize as GenericMozTabSize; use crate::values::generics::text::MozTabSize as GenericMozTabSize;
use crate::values::generics::text::Spacing; use crate::values::generics::text::Spacing;
use crate::values::specified::length::{FontRelativeLength, Length}; use crate::values::specified::length::{FontRelativeLength, Length};
use crate::values::specified::length::{LengthOrPercentage, NoCalcLength}; use crate::values::specified::length::{LengthPercentage, NoCalcLength};
use crate::values::specified::length::{NonNegativeLength, NonNegativeLengthOrPercentage}; use crate::values::specified::length::{NonNegativeLength, NonNegativeLengthPercentage};
use crate::values::specified::{AllowQuirks, Integer, NonNegativeNumber, Number}; use crate::values::specified::{AllowQuirks, Integer, NonNegativeNumber, Number};
use cssparser::{Parser, Token}; use cssparser::{Parser, Token};
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
@ -34,10 +34,10 @@ pub type InitialLetter = GenericInitialLetter<Number, Integer>;
pub type LetterSpacing = Spacing<Length>; pub type LetterSpacing = Spacing<Length>;
/// A specified value for the `word-spacing` property. /// A specified value for the `word-spacing` property.
pub type WordSpacing = Spacing<LengthOrPercentage>; pub type WordSpacing = Spacing<LengthPercentage>;
/// A specified value for the `line-height` property. /// A specified value for the `line-height` property.
pub type LineHeight = GenericLineHeight<NonNegativeNumber, NonNegativeLengthOrPercentage>; pub type LineHeight = GenericLineHeight<NonNegativeNumber, NonNegativeLengthPercentage>;
impl Parse for InitialLetter { impl Parse for InitialLetter {
fn parse<'i, 't>( fn parse<'i, 't>(
@ -70,7 +70,7 @@ impl Parse for WordSpacing {
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
Spacing::parse_with(context, input, |c, i| { Spacing::parse_with(context, input, |c, i| {
LengthOrPercentage::parse_quirky(c, i, AllowQuirks::Yes) LengthPercentage::parse_quirky(c, i, AllowQuirks::Yes)
}) })
} }
} }
@ -83,8 +83,8 @@ impl Parse for LineHeight {
if let Ok(number) = input.try(|i| NonNegativeNumber::parse(context, i)) { if let Ok(number) = input.try(|i| NonNegativeNumber::parse(context, i)) {
return Ok(GenericLineHeight::Number(number)); return Ok(GenericLineHeight::Number(number));
} }
if let Ok(nlop) = input.try(|i| NonNegativeLengthOrPercentage::parse(context, i)) { if let Ok(nlp) = input.try(|i| NonNegativeLengthPercentage::parse(context, i)) {
return Ok(GenericLineHeight::Length(nlop)); return Ok(GenericLineHeight::Length(nlp));
} }
let location = input.current_source_location(); let location = input.current_source_location();
let ident = input.expect_ident()?; let ident = input.expect_ident()?;
@ -116,17 +116,17 @@ impl ToComputedValue for LineHeight {
GenericLineHeight::Number(number) => { GenericLineHeight::Number(number) => {
GenericLineHeight::Number(number.to_computed_value(context)) GenericLineHeight::Number(number.to_computed_value(context))
}, },
GenericLineHeight::Length(ref non_negative_lop) => { GenericLineHeight::Length(ref non_negative_lp) => {
let result = match non_negative_lop.0 { let result = match non_negative_lp.0 {
LengthOrPercentage::Length(NoCalcLength::Absolute(ref abs)) => { LengthPercentage::Length(NoCalcLength::Absolute(ref abs)) => {
context context
.maybe_zoom_text(abs.to_computed_value(context).into()) .maybe_zoom_text(abs.to_computed_value(context).into())
.0 .0
}, },
LengthOrPercentage::Length(ref length) => length.to_computed_value(context), LengthPercentage::Length(ref length) => length.to_computed_value(context),
LengthOrPercentage::Percentage(ref p) => FontRelativeLength::Em(p.0) LengthPercentage::Percentage(ref p) => FontRelativeLength::Em(p.0)
.to_computed_value(context, FontBaseSize::CurrentStyle), .to_computed_value(context, FontBaseSize::CurrentStyle),
LengthOrPercentage::Calc(ref calc) => { LengthPercentage::Calc(ref calc) => {
let computed_calc = let computed_calc =
calc.to_computed_value_zoomed(context, FontBaseSize::CurrentStyle); calc.to_computed_value_zoomed(context, FontBaseSize::CurrentStyle);
let font_relative_length = let font_relative_length =

View file

@ -5,12 +5,12 @@
//! Specified types for CSS values that are related to transformations. //! Specified types for CSS values that are related to transformations.
use crate::parser::{Parse, ParserContext}; use crate::parser::{Parse, ParserContext};
use crate::values::computed::{Context, LengthOrPercentage as ComputedLengthOrPercentage}; use crate::values::computed::{Context, LengthPercentage as ComputedLengthPercentage};
use crate::values::computed::{Percentage as ComputedPercentage, ToComputedValue}; use crate::values::computed::{Percentage as ComputedPercentage, ToComputedValue};
use crate::values::generics::transform as generic; use crate::values::generics::transform as generic;
use crate::values::generics::transform::{Matrix, Matrix3D}; use crate::values::generics::transform::{Matrix, Matrix3D};
use crate::values::specified::position::{Side, X, Y}; use crate::values::specified::position::{Side, X, Y};
use crate::values::specified::{self, Angle, Integer, Length, LengthOrPercentage, Number}; use crate::values::specified::{self, Angle, Integer, Length, LengthPercentage, Number};
use cssparser::Parser; use cssparser::Parser;
use style_traits::{ParseError, StyleParseErrorKind}; use style_traits::{ParseError, StyleParseErrorKind};
@ -18,7 +18,7 @@ pub use crate::values::generics::transform::TransformStyle;
/// A single operation in a specified CSS `transform` /// A single operation in a specified CSS `transform`
pub type TransformOperation = pub type TransformOperation =
generic::TransformOperation<Angle, Number, Length, Integer, LengthOrPercentage>; generic::TransformOperation<Angle, Number, Length, Integer, LengthPercentage>;
/// A specified CSS `transform` /// A specified CSS `transform`
pub type Transform = generic::Transform<TransformOperation>; pub type Transform = generic::Transform<TransformOperation>;
@ -105,20 +105,20 @@ impl Transform {
})) }))
}, },
"translate" => { "translate" => {
let sx = specified::LengthOrPercentage::parse(context, input)?; let sx = specified::LengthPercentage::parse(context, input)?;
if input.try(|input| input.expect_comma()).is_ok() { if input.try(|input| input.expect_comma()).is_ok() {
let sy = specified::LengthOrPercentage::parse(context, input)?; let sy = specified::LengthPercentage::parse(context, input)?;
Ok(generic::TransformOperation::Translate(sx, Some(sy))) Ok(generic::TransformOperation::Translate(sx, Some(sy)))
} else { } else {
Ok(generic::TransformOperation::Translate(sx, None)) Ok(generic::TransformOperation::Translate(sx, None))
} }
}, },
"translatex" => { "translatex" => {
let tx = specified::LengthOrPercentage::parse(context, input)?; let tx = specified::LengthPercentage::parse(context, input)?;
Ok(generic::TransformOperation::TranslateX(tx)) Ok(generic::TransformOperation::TranslateX(tx))
}, },
"translatey" => { "translatey" => {
let ty = specified::LengthOrPercentage::parse(context, input)?; let ty = specified::LengthPercentage::parse(context, input)?;
Ok(generic::TransformOperation::TranslateY(ty)) Ok(generic::TransformOperation::TranslateY(ty))
}, },
"translatez" => { "translatez" => {
@ -126,9 +126,9 @@ impl Transform {
Ok(generic::TransformOperation::TranslateZ(tz)) Ok(generic::TransformOperation::TranslateZ(tz))
}, },
"translate3d" => { "translate3d" => {
let tx = specified::LengthOrPercentage::parse(context, input)?; let tx = specified::LengthPercentage::parse(context, input)?;
input.expect_comma()?; input.expect_comma()?;
let ty = specified::LengthOrPercentage::parse(context, input)?; let ty = specified::LengthPercentage::parse(context, input)?;
input.expect_comma()?; input.expect_comma()?;
let tz = specified::Length::parse(context, input)?; let tz = specified::Length::parse(context, input)?;
Ok(generic::TransformOperation::Translate3D(tx, ty, tz)) Ok(generic::TransformOperation::Translate3D(tx, ty, tz))
@ -235,8 +235,8 @@ impl Parse for Transform {
pub enum OriginComponent<S> { pub enum OriginComponent<S> {
/// `center` /// `center`
Center, Center,
/// `<lop>` /// `<length-percentage>`
Length(LengthOrPercentage), Length(LengthPercentage),
/// `<side>` /// `<side>`
Side(S), Side(S),
} }
@ -306,8 +306,8 @@ where
if input.try(|i| i.expect_ident_matching("center")).is_ok() { if input.try(|i| i.expect_ident_matching("center")).is_ok() {
return Ok(OriginComponent::Center); return Ok(OriginComponent::Center);
} }
if let Ok(lop) = input.try(|i| LengthOrPercentage::parse(context, i)) { if let Ok(lp) = input.try(|i| LengthPercentage::parse(context, i)) {
return Ok(OriginComponent::Length(lop)); return Ok(OriginComponent::Length(lp));
} }
let keyword = S::parse(context, input)?; let keyword = S::parse(context, input)?;
Ok(OriginComponent::Side(keyword)) Ok(OriginComponent::Side(keyword))
@ -318,17 +318,17 @@ impl<S> ToComputedValue for OriginComponent<S>
where where
S: Side, S: Side,
{ {
type ComputedValue = ComputedLengthOrPercentage; type ComputedValue = ComputedLengthPercentage;
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
match *self { match *self {
OriginComponent::Center => { OriginComponent::Center => {
ComputedLengthOrPercentage::Percentage(ComputedPercentage(0.5)) ComputedLengthPercentage::new_percent(ComputedPercentage(0.5))
}, },
OriginComponent::Length(ref length) => length.to_computed_value(context), OriginComponent::Length(ref length) => length.to_computed_value(context),
OriginComponent::Side(ref keyword) => { OriginComponent::Side(ref keyword) => {
let p = ComputedPercentage(if keyword.is_start() { 0. } else { 1. }); let p = ComputedPercentage(if keyword.is_start() { 0. } else { 1. });
ComputedLengthOrPercentage::Percentage(p) ComputedLengthPercentage::new_percent(p)
}, },
} }
} }
@ -341,7 +341,7 @@ where
impl<S> OriginComponent<S> { impl<S> OriginComponent<S> {
/// `0%` /// `0%`
pub fn zero() -> Self { pub fn zero() -> Self {
OriginComponent::Length(LengthOrPercentage::Percentage(ComputedPercentage::zero())) OriginComponent::Length(LengthPercentage::Percentage(ComputedPercentage::zero()))
} }
} }
@ -393,7 +393,7 @@ impl Parse for Rotate {
} }
/// A specified CSS `translate` /// A specified CSS `translate`
pub type Translate = generic::Translate<LengthOrPercentage, Length>; pub type Translate = generic::Translate<LengthPercentage, Length>;
impl Parse for Translate { impl Parse for Translate {
fn parse<'i, 't>( fn parse<'i, 't>(
@ -404,8 +404,8 @@ impl Parse for Translate {
return Ok(generic::Translate::None); return Ok(generic::Translate::None);
} }
let tx = specified::LengthOrPercentage::parse(context, input)?; let tx = specified::LengthPercentage::parse(context, input)?;
if let Ok(ty) = input.try(|i| specified::LengthOrPercentage::parse(context, i)) { if let Ok(ty) = input.try(|i| specified::LengthPercentage::parse(context, i)) {
if let Ok(tz) = input.try(|i| specified::Length::parse(context, i)) { if let Ok(tz) = input.try(|i| specified::Length::parse(context, i)) {
// 'translate: <length-percentage> <length-percentage> <length>' // 'translate: <length-percentage> <length-percentage> <length>'
return Ok(generic::Translate::Translate3D(tx, ty, tz)); return Ok(generic::Translate::Translate3D(tx, ty, tz));
@ -418,7 +418,7 @@ impl Parse for Translate {
// 'translate: <length-percentage> ' // 'translate: <length-percentage> '
Ok(generic::Translate::Translate( Ok(generic::Translate::Translate(
tx, tx,
specified::LengthOrPercentage::zero(), specified::LengthPercentage::zero(),
)) ))
} }
} }

View file

@ -4,7 +4,6 @@
use cssparser::RGBA; use cssparser::RGBA;
use style::values::animated::{Animate, Procedure, ToAnimatedValue}; use style::values::animated::{Animate, Procedure, ToAnimatedValue};
use style::values::computed::Percentage;
use style::values::generics::transform::{Transform, TransformOperation}; use style::values::generics::transform::{Transform, TransformOperation};
fn interpolate_rgba(from: RGBA, to: RGBA, progress: f64) -> RGBA { fn interpolate_rgba(from: RGBA, to: RGBA, progress: f64) -> RGBA {
@ -83,60 +82,6 @@ fn test_rgba_color_interepolation_out_of_range_clamped_2() {
); );
} }
// Transform
#[test]
fn test_transform_interpolation_on_translate() {
use style::values::computed::{CalcLengthOrPercentage, Length, LengthOrPercentage};
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(),
Transform(vec![TransformOperation::Translate3D(
LengthOrPercentage::Length(Length::new(50.)),
LengthOrPercentage::Length(Length::new(50.)),
Length::new(50.),
)])
);
let from = Transform(vec![TransformOperation::Translate3D(
LengthOrPercentage::Percentage(Percentage(0.5)),
LengthOrPercentage::Percentage(Percentage(1.0)),
Length::new(25.),
)]);
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(),
Transform(vec![TransformOperation::Translate3D(
// calc(50px + 25%)
LengthOrPercentage::Calc(CalcLengthOrPercentage::new(
Length::new(50.),
Some(Percentage(0.25))
)),
// calc(25px + 50%)
LengthOrPercentage::Calc(CalcLengthOrPercentage::new(
Length::new(25.),
Some(Percentage(0.5))
)),
Length::new(50.),
)])
);
}
#[test] #[test]
fn test_transform_interpolation_on_scale() { fn test_transform_interpolation_on_scale() {
let from = Transform(vec![TransformOperation::Scale3D(1.0, 2.0, 1.0)]); let from = Transform(vec![TransformOperation::Scale3D(1.0, 2.0, 1.0)]);
@ -197,29 +142,3 @@ fn test_transform_interpolation_on_skew() {
)]) )])
); );
} }
#[test]
fn test_transform_interpolation_on_mismatched_lists() {
use style::values::computed::{Angle, Length, LengthOrPercentage};
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(),
Transform(vec![TransformOperation::InterpolateMatrix {
from_list: from.clone(),
to_list: to.clone(),
progress: Percentage(0.5),
}])
);
}

View file

@ -4,19 +4,6 @@
use app_units::Au; use app_units::Au;
use style::attr::{parse_length, AttrValue, LengthOrPercentageOrAuto}; use style::attr::{parse_length, AttrValue, LengthOrPercentageOrAuto};
use style::values::computed::{CalcLengthOrPercentage, Percentage};
#[test]
fn test_length_calc() {
let calc = CalcLengthOrPercentage::new(Au(10).into(), Some(Percentage(0.2)));
assert_eq!(calc.to_used_value(Some(Au(10))), Some(Au(12)));
assert_eq!(calc.to_used_value(Some(Au(0))), Some(Au(10)));
assert_eq!(calc.to_used_value(None), None);
let calc = CalcLengthOrPercentage::new(Au(10).into(), None);
assert_eq!(calc.to_used_value(Some(Au(0))), Some(Au(10)));
assert_eq!(calc.to_used_value(None), Some(Au(10)));
}
#[test] #[test]
fn test_parse_double() { fn test_parse_double() {

View file

@ -20,10 +20,10 @@ fn negative_letter_spacing_should_parse_properly() {
#[test] #[test]
fn negative_word_spacing_should_parse_properly() { fn negative_word_spacing_should_parse_properly() {
use style::properties::longhands::word_spacing; use style::properties::longhands::word_spacing;
use style::values::specified::length::{FontRelativeLength, LengthOrPercentage, NoCalcLength}; use style::values::specified::length::{FontRelativeLength, LengthPercentage, NoCalcLength};
let negative_value = parse_longhand!(word_spacing, "-0.5em"); let negative_value = parse_longhand!(word_spacing, "-0.5em");
let expected = Spacing::Value(LengthOrPercentage::Length(NoCalcLength::FontRelative( let expected = Spacing::Value(LengthPercentage::Length(NoCalcLength::FontRelative(
FontRelativeLength::Em(-0.5), FontRelativeLength::Em(-0.5),
))); )));
assert_eq!(negative_value, expected); assert_eq!(negative_value, expected);

View file

@ -4,13 +4,11 @@
use crate::properties::{parse, parse_input}; use crate::properties::{parse, parse_input};
use crate::stylesheets::block_from; use crate::stylesheets::block_from;
use style::computed_values::display::T as Display;
use style::properties::declaration_block::PropertyDeclarationBlock; use style::properties::declaration_block::PropertyDeclarationBlock;
use style::properties::parse_property_declaration_list; use style::properties::parse_property_declaration_list;
use style::properties::{Importance, PropertyDeclaration}; use style::properties::{Importance, PropertyDeclaration};
use style::values::specified::url::SpecifiedUrl; use style::values::specified::url::SpecifiedUrl;
use style::values::specified::NoCalcLength; use style::values::specified::Length;
use style::values::specified::{Length, LengthOrPercentage, LengthOrPercentageOrAuto};
use style_traits::ToCss; use style_traits::ToCss;
trait ToCssString { trait ToCssString {
@ -25,53 +23,6 @@ impl ToCssString for PropertyDeclarationBlock {
} }
} }
#[test]
fn property_declaration_block_should_serialize_correctly() {
use style::properties::longhands::overflow_x::SpecifiedValue as OverflowValue;
let declarations = vec![
(
PropertyDeclaration::Width(LengthOrPercentageOrAuto::Length(NoCalcLength::from_px(
70f32,
))),
Importance::Normal,
),
(
PropertyDeclaration::MinHeight(LengthOrPercentage::Length(NoCalcLength::from_px(
20f32,
))),
Importance::Normal,
),
(
PropertyDeclaration::Height(LengthOrPercentageOrAuto::Length(NoCalcLength::from_px(
20f32,
))),
Importance::Important,
),
(
PropertyDeclaration::Display(Display::InlineBlock),
Importance::Normal,
),
(
PropertyDeclaration::OverflowX(OverflowValue::Auto),
Importance::Normal,
),
(
PropertyDeclaration::OverflowY(OverflowValue::Auto),
Importance::Normal,
),
];
let block = block_from(declarations);
let css_string = block.to_css_string();
assert_eq!(
css_string,
"width: 70px; min-height: 20px; height: 20px !important; display: inline-block; overflow: auto;"
);
}
mod shorthand_serialization { mod shorthand_serialization {
pub use super::*; pub use super::*;

View file

@ -17,20 +17,16 @@ use std::sync::atomic::AtomicBool;
use style::context::QuirksMode; use style::context::QuirksMode;
use style::error_reporting::{ContextualParseError, ParseErrorReporter}; use style::error_reporting::{ContextualParseError, ParseErrorReporter};
use style::media_queries::MediaList; use style::media_queries::MediaList;
use style::properties::longhands::{self, animation_timing_function}; use style::properties::longhands;
use style::properties::{CSSWideKeyword, CustomDeclaration}; use style::properties::{CSSWideKeyword, CustomDeclaration};
use style::properties::{CustomDeclarationValue, Importance}; use style::properties::{CustomDeclarationValue, Importance};
use style::properties::{PropertyDeclaration, PropertyDeclarationBlock}; use style::properties::{PropertyDeclaration, PropertyDeclarationBlock};
use style::shared_lock::SharedRwLock; use style::shared_lock::SharedRwLock;
use style::stylesheets::keyframes_rule::{Keyframe, KeyframePercentage, KeyframeSelector};
use style::stylesheets::{ use style::stylesheets::{
CssRule, CssRules, KeyframesRule, NamespaceRule, StyleRule, Stylesheet, StylesheetContents, CssRule, CssRules, NamespaceRule, StyleRule, Stylesheet, StylesheetContents,
}; };
use style::stylesheets::{Namespaces, Origin}; use style::stylesheets::{Namespaces, Origin};
use style::values::computed::Percentage; use style::values::specified::PositionComponent;
use style::values::specified::TimingFunction;
use style::values::specified::{LengthOrPercentageOrAuto, PositionComponent};
use style::values::{CustomIdent, KeyframesName};
pub fn block_from<I>(iterable: I) -> PropertyDeclarationBlock pub fn block_from<I>(iterable: I) -> PropertyDeclarationBlock
where where
@ -61,14 +57,6 @@ fn test_parse_stylesheet() {
display: block; display: block;
} }
#d1 > .ok { background: blue; } #d1 > .ok { background: blue; }
@keyframes foo {
from { width: 0% }
to {
width: 100%;
width: 50% !important; /* !important not allowed here */
animation-name: 'foo'; /* animation properties not allowed here */
animation-timing-function: ease; /* … except animation-timing-function */
}
}"; }";
let url = ServoUrl::parse("about::test").unwrap(); let url = ServoUrl::parse("about::test").unwrap();
let lock = SharedRwLock::new(); let lock = SharedRwLock::new();
@ -278,56 +266,6 @@ fn test_parse_stylesheet() {
column: 9, column: 9,
}, },
}))), }))),
CssRule::Keyframes(Arc::new(stylesheet.shared_lock.wrap(KeyframesRule {
name: KeyframesName::Ident(CustomIdent("foo".into())),
keyframes: vec![
Arc::new(stylesheet.shared_lock.wrap(Keyframe {
selector: KeyframeSelector::new_for_unit_testing(vec![
KeyframePercentage::new(0.),
]),
block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![(
PropertyDeclaration::Width(
LengthOrPercentageOrAuto::Percentage(Percentage(0.)),
),
Importance::Normal,
)]))),
source_location: SourceLocation {
line: 17,
column: 13,
},
})),
Arc::new(stylesheet.shared_lock.wrap(Keyframe {
selector: KeyframeSelector::new_for_unit_testing(vec![
KeyframePercentage::new(1.),
]),
block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![
(
PropertyDeclaration::Width(
LengthOrPercentageOrAuto::Percentage(Percentage(1.)),
),
Importance::Normal,
),
(
PropertyDeclaration::AnimationTimingFunction(
animation_timing_function::SpecifiedValue(vec![
TimingFunction::ease(),
]),
),
Importance::Normal,
),
]))),
source_location: SourceLocation {
line: 18,
column: 13,
},
})),
],
vendor_prefix: None,
source_location: SourceLocation {
line: 16,
column: 19,
},
}))),
], ],
&stylesheet.shared_lock, &stylesheet.shared_lock,
), ),

View file

@ -14,7 +14,8 @@ use style::parser::ParserContext;
use style::shared_lock::{SharedRwLock, StylesheetGuards}; use style::shared_lock::{SharedRwLock, StylesheetGuards};
use style::stylesheets::viewport_rule::*; use style::stylesheets::viewport_rule::*;
use style::stylesheets::{CssRuleType, Origin, Stylesheet, StylesheetInDocument}; use style::stylesheets::{CssRuleType, Origin, Stylesheet, StylesheetInDocument};
use style::values::specified::LengthOrPercentageOrAuto::{self, Auto}; use style::values::specified::LengthPercentage;
use style::values::specified::LengthPercentageOrAuto::{self, Auto};
use style::values::specified::NoCalcLength::{self, ViewportPercentage}; use style::values::specified::NoCalcLength::{self, ViewportPercentage};
use style::values::specified::ViewportPercentageLength::Vw; use style::values::specified::ViewportPercentageLength::Vw;
use style_traits::viewport::*; use style_traits::viewport::*;
@ -96,14 +97,14 @@ macro_rules! assert_decl_len {
macro_rules! viewport_length { macro_rules! viewport_length {
($value:expr, px) => { ($value:expr, px) => {
ViewportLength::Specified(LengthOrPercentageOrAuto::Length(NoCalcLength::from_px( ViewportLength::Specified(LengthPercentageOrAuto::LengthPercentage(
$value, LengthPercentage::Length(NoCalcLength::from_px($value)),
))) ))
}; };
($value:expr, vw) => { ($value:expr, vw) => {
ViewportLength::Specified(LengthOrPercentageOrAuto::Length(ViewportPercentage(Vw( ViewportLength::Specified(LengthPercentageOrAuto::LengthPercentage(
$value, LengthPercentage::Length(ViewportPercentage(Vw($value))),
)))) ))
}; };
} }

View file

@ -1,6 +1,4 @@
[variable-substitution-replaced-size.html] [variable-substitution-replaced-size.html]
[height on IFRAME]
expected: FAIL
[width on INPUT] [width on INPUT]
expected: FAIL expected: FAIL
@ -8,6 +6,3 @@
[height on INPUT] [height on INPUT]
expected: FAIL expected: FAIL
[height on CANVAS]
expected: FAIL