Auto merge of #21652 - chansuke:format_style, r=emilio

Format component `style`

<!-- Please describe your changes on the following line: -->
Format `components/style` with:
```
rustfmt components/style/*.rs
```

---
<!-- Thank you for contributing to Servo! Please replace each `[ ]` by `[X]` when the step is complete, and replace `__` with appropriate data: -->
- [x] `./mach build -d` does not report any errors
- [x] `./mach test-tidy` does not report any errors
- [x] These changes fix part of #21373.
- [x] These changes do not require tests because they format the components only.

<!-- Also, please make sure that "Allow edits from maintainers" checkbox is checked, so that we can help you if you get stuck somewhere along the way.-->

<!-- Pull requests that do not address these steps are welcome, but they will require additional verification as part of the review process. -->

<!-- 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/21652)
<!-- Reviewable:end -->
This commit is contained in:
bors-servo 2018-09-09 12:40:12 -04:00 committed by GitHub
commit c8fd63802e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
120 changed files with 2207 additions and 1417 deletions

View file

@ -213,7 +213,12 @@ pub enum Animation {
/// node-dependent state (i.e. iteration count, etc.). /// node-dependent state (i.e. iteration count, etc.).
/// ///
/// TODO(emilio): The animation object could be refcounted. /// TODO(emilio): The animation object could be refcounted.
Keyframes(OpaqueNode, KeyframesAnimation, Atom, KeyframesAnimationState), Keyframes(
OpaqueNode,
KeyframesAnimation,
Atom,
KeyframesAnimationState,
),
} }
impl Animation { impl Animation {
@ -304,8 +309,7 @@ impl PropertyAnimation {
let duration = box_style.transition_duration_mod(transition_index); let duration = box_style.transition_duration_mod(transition_index);
match transition_property { match transition_property {
TransitionProperty::Custom(..) | TransitionProperty::Custom(..) | TransitionProperty::Unsupported(..) => result,
TransitionProperty::Unsupported(..) => result,
TransitionProperty::Shorthand(ref shorthand_id) => shorthand_id TransitionProperty::Shorthand(ref shorthand_id) => shorthand_id
.longhands() .longhands()
.filter_map(|longhand| { .filter_map(|longhand| {
@ -316,8 +320,7 @@ impl PropertyAnimation {
old_style, old_style,
new_style, new_style,
) )
}) }).collect(),
.collect(),
TransitionProperty::Longhand(longhand_id) => { TransitionProperty::Longhand(longhand_id) => {
let animation = PropertyAnimation::from_longhand( let animation = PropertyAnimation::from_longhand(
longhand_id, longhand_id,
@ -455,8 +458,7 @@ pub fn start_transitions_if_applicable(
property_animation: property_animation, property_animation: property_animation,
}, },
/* is_expired = */ false, /* is_expired = */ false,
)) )).unwrap();
.unwrap();
had_animations = true; had_animations = true;
} }
@ -505,7 +507,9 @@ where
Some(previous_style), Some(previous_style),
Some(previous_style), Some(previous_style),
font_metrics_provider, font_metrics_provider,
CascadeMode::Unvisited { visited_rules: None }, CascadeMode::Unvisited {
visited_rules: None,
},
context.quirks_mode(), context.quirks_mode(),
/* rule_cache = */ None, /* rule_cache = */ None,
&mut Default::default(), &mut Default::default(),
@ -596,8 +600,7 @@ where
expired: false, expired: false,
cascade_style: new_style.clone(), cascade_style: new_style.clone(),
}, },
)) )).unwrap();
.unwrap();
had_animations = true; had_animations = true;
} }
} }
@ -735,8 +738,7 @@ pub fn update_style_for_animation<E>(
} else { } else {
None None
} }
}) }).unwrap_or(animation.steps.len() - 1);
.unwrap_or(animation.steps.len() - 1);
}, },
_ => unreachable!(), _ => unreachable!(),
} }

View file

@ -38,7 +38,8 @@ const SOURCE_ORDER_MASK: u32 = SOURCE_ORDER_MAX << SOURCE_ORDER_SHIFT;
const SHADOW_CASCADE_ORDER_SHIFT: usize = SOURCE_ORDER_BITS; const SHADOW_CASCADE_ORDER_SHIFT: usize = SOURCE_ORDER_BITS;
const SHADOW_CASCADE_ORDER_BITS: usize = 4; const SHADOW_CASCADE_ORDER_BITS: usize = 4;
const SHADOW_CASCADE_ORDER_MAX: u8 = (1 << SHADOW_CASCADE_ORDER_BITS) - 1; const SHADOW_CASCADE_ORDER_MAX: u8 = (1 << SHADOW_CASCADE_ORDER_BITS) - 1;
const SHADOW_CASCADE_ORDER_MASK: u32 = (SHADOW_CASCADE_ORDER_MAX as u32) << SHADOW_CASCADE_ORDER_SHIFT; const SHADOW_CASCADE_ORDER_MASK: u32 =
(SHADOW_CASCADE_ORDER_MAX as u32) << SHADOW_CASCADE_ORDER_SHIFT;
const CASCADE_LEVEL_SHIFT: usize = SOURCE_ORDER_BITS + SHADOW_CASCADE_ORDER_BITS; const CASCADE_LEVEL_SHIFT: usize = SOURCE_ORDER_BITS + SHADOW_CASCADE_ORDER_BITS;
const CASCADE_LEVEL_BITS: usize = 4; const CASCADE_LEVEL_BITS: usize = 4;
@ -61,7 +62,8 @@ impl ApplicableDeclarationBits {
"Gotta find more bits!" "Gotta find more bits!"
); );
let mut bits = ::std::cmp::min(source_order, SOURCE_ORDER_MAX); let mut bits = ::std::cmp::min(source_order, SOURCE_ORDER_MAX);
bits |= ((shadow_cascade_order & SHADOW_CASCADE_ORDER_MAX) as u32) << SHADOW_CASCADE_ORDER_SHIFT; bits |= ((shadow_cascade_order & SHADOW_CASCADE_ORDER_MAX) as u32) <<
SHADOW_CASCADE_ORDER_SHIFT;
bits |= (cascade_level as u8 as u32) << CASCADE_LEVEL_SHIFT; bits |= (cascade_level as u8 as u32) << CASCADE_LEVEL_SHIFT;
ApplicableDeclarationBits(bits) ApplicableDeclarationBits(bits)
} }

View file

@ -158,15 +158,15 @@ pub fn parse_double(string: &str) -> Result<f64, ()> {
impl AttrValue { impl AttrValue {
pub fn from_serialized_tokenlist(tokens: String) -> AttrValue { pub fn from_serialized_tokenlist(tokens: String) -> AttrValue {
let atoms = split_html_space_chars(&tokens).map(Atom::from).fold( let atoms =
vec![], split_html_space_chars(&tokens)
|mut acc, atom| { .map(Atom::from)
if !acc.contains(&atom) { .fold(vec![], |mut acc, atom| {
acc.push(atom) if !acc.contains(&atom) {
} acc.push(atom)
acc }
}, acc
); });
AttrValue::TokenList(tokens, atoms) AttrValue::TokenList(tokens, atoms)
} }

View file

@ -60,7 +60,8 @@ where
E: TElement, E: TElement,
S: ToMediaListKey, S: ToMediaListKey,
{ {
let flusher = self.stylesheets let flusher = self
.stylesheets
.flush::<E>(/* host = */ None, /* snapshot_map = */ None); .flush::<E>(/* host = */ None, /* snapshot_map = */ None);
if flusher.sheets.dirty() { if flusher.sheets.dirty() {
@ -68,7 +69,8 @@ where
} }
// Ignore OOM. // Ignore OOM.
let _ = self.data let _ = self
.data
.rebuild(device, quirks_mode, flusher.sheets, guard); .rebuild(device, quirks_mode, flusher.sheets, guard);
} }
} }

View file

@ -322,13 +322,11 @@ mod bindings {
.expect(&format!( .expect(&format!(
"Unrecognized line in ServoArcTypeList.h: '{}'", "Unrecognized line in ServoArcTypeList.h: '{}'",
line line
)) )).get(1)
.get(1)
.unwrap() .unwrap()
.as_str() .as_str()
.to_string() .to_string()
}) }).collect()
.collect()
} }
struct BuilderWithConfig<'a> { struct BuilderWithConfig<'a> {
@ -436,8 +434,7 @@ mod bindings {
servo, servo,
if generic { "<T>" } else { "" } if generic { "<T>" } else { "" }
)) ))
}) }).get_builder();
.get_builder();
write_binding_file(builder, STRUCTS_FILE, &fixups); write_binding_file(builder, STRUCTS_FILE, &fixups);
} }
@ -553,8 +550,7 @@ mod bindings {
.raw_line(format!( .raw_line(format!(
"pub type {0}Strong = ::gecko_bindings::sugar::ownership::Strong<{0}>;", "pub type {0}Strong = ::gecko_bindings::sugar::ownership::Strong<{0}>;",
ty ty
)) )).borrowed_type(ty)
.borrowed_type(ty)
.zero_size_type(ty, &structs_types); .zero_size_type(ty, &structs_types);
} }
write_binding_file(builder, BINDINGS_FILE, &fixups); write_binding_file(builder, BINDINGS_FILE, &fixups);

View file

@ -91,8 +91,7 @@ pub fn parse_counter_style_body<'i, 't>(
if let Err((error, slice)) = declaration { if let Err((error, slice)) = declaration {
let location = error.location; let location = error.location;
let error = ContextualParseError::UnsupportedCounterStyleDescriptorDeclaration( let error = ContextualParseError::UnsupportedCounterStyleDescriptorDeclaration(
slice, slice, error,
error,
); );
context.log_css_error(location, error) context.log_css_error(location, error)
} }
@ -103,7 +102,8 @@ pub fn parse_counter_style_body<'i, 't>(
ref system @ System::Fixed { .. } | ref system @ System::Fixed { .. } |
ref system @ System::Symbolic | ref system @ System::Symbolic |
ref system @ System::Alphabetic | ref system @ System::Alphabetic |
ref system @ System::Numeric if rule.symbols.is_none() => ref system @ System::Numeric
if rule.symbols.is_none() =>
{ {
let system = system.to_css_string(); let system = system.to_css_string();
Some(ContextualParseError::InvalidCounterStyleWithoutSymbols( Some(ContextualParseError::InvalidCounterStyleWithoutSymbols(
@ -496,12 +496,13 @@ impl Parse for Ranges {
(opt_start, opt_end) (opt_start, opt_end)
{ {
if start > end { if start > end {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); return Err(
input.new_custom_error(StyleParseErrorKind::UnspecifiedError)
);
} }
} }
Ok(opt_start..opt_end) Ok(opt_start..opt_end)
}) }).map(Ranges)
.map(Ranges)
} }
} }
} }

View file

@ -243,7 +243,8 @@ impl VariableValue {
self.first_token_type.set_if_nothing(css_first_token_type); self.first_token_type.set_if_nothing(css_first_token_type);
// If self.first_token_type was nothing, // If self.first_token_type was nothing,
// self.last_token_type is also nothing and this will be false: // self.last_token_type is also nothing and this will be false:
if self.last_token_type if self
.last_token_type
.needs_separator_when_before(css_first_token_type) .needs_separator_when_before(css_first_token_type)
{ {
self.css.push_str("/**/") self.css.push_str("/**/")
@ -569,7 +570,8 @@ impl<'a> CustomPropertiesBuilder<'a> {
_ => {}, _ => {},
} }
let existing_value = self.custom_properties let existing_value = self
.custom_properties
.as_ref() .as_ref()
.and_then(|m| m.get(name)) .and_then(|m| m.get(name))
.or_else(|| self.inherited.and_then(|m| m.get(name))); .or_else(|| self.inherited.and_then(|m| m.get(name)));

View file

@ -272,12 +272,8 @@ impl ElementData {
return InvalidationResult::empty(); return InvalidationResult::empty();
} }
let mut processor = StateAndAttrInvalidationProcessor::new( let mut processor =
shared_context, StateAndAttrInvalidationProcessor::new(shared_context, element, self, nth_index_cache);
element,
self,
nth_index_cache,
);
let invalidator = TreeStyleInvalidator::new(element, stack_limit_checker, &mut processor); let invalidator = TreeStyleInvalidator::new(element, stack_limit_checker, &mut processor);
@ -305,7 +301,8 @@ impl ElementData {
/// Returns this element's primary style as a resolved style to use for sharing. /// Returns this element's primary style as a resolved style to use for sharing.
pub fn share_primary_style(&self) -> PrimaryStyle { pub fn share_primary_style(&self) -> PrimaryStyle {
let reused_via_rule_node = self.flags let reused_via_rule_node = self
.flags
.contains(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE); .contains(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
PrimaryStyle { PrimaryStyle {
@ -390,7 +387,8 @@ impl ElementData {
guards: &StylesheetGuards, guards: &StylesheetGuards,
) -> bool { ) -> bool {
debug_assert!(self.has_styles()); debug_assert!(self.has_styles());
let (important_rules, _custom) = self.styles let (important_rules, _custom) = self
.styles
.primary() .primary()
.rules() .rules()
.get_properties_overriding_animations(&guards); .get_properties_overriding_animations(&guards);

View file

@ -42,7 +42,10 @@ use traversal_flags::TraversalFlags;
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for /// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant. /// locality reasons. Using `OpaqueNode` enforces this invariant.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf, Deserialize, Serialize))] #[cfg_attr(
feature = "servo",
derive(MallocSizeOf, Deserialize, Serialize)
)]
pub struct OpaqueNode(pub usize); pub struct OpaqueNode(pub usize);
impl OpaqueNode { impl OpaqueNode {
@ -459,7 +462,9 @@ pub trait TElement:
fn is_svg_element(&self) -> bool; fn is_svg_element(&self) -> bool;
/// Return whether this element is an element in the XUL namespace. /// Return whether this element is an element in the XUL namespace.
fn is_xul_element(&self) -> bool { false } fn is_xul_element(&self) -> bool {
false
}
/// Return the list of slotted nodes of this node. /// Return the list of slotted nodes of this node.
fn slotted_nodes(&self) -> &[Self::ConcreteNode] { fn slotted_nodes(&self) -> &[Self::ConcreteNode] {
@ -892,11 +897,7 @@ pub trait TElement:
/// of the `xml:lang=""` or `lang=""` attribute to use in place of /// of the `xml:lang=""` or `lang=""` attribute to use in place of
/// looking at the element and its ancestors. (This argument is used /// looking at the element and its ancestors. (This argument is used
/// to implement matching of `:lang()` against snapshots.) /// to implement matching of `:lang()` against snapshots.)
fn match_element_lang( fn match_element_lang(&self, override_lang: Option<Option<AttrValue>>, value: &Lang) -> bool;
&self,
override_lang: Option<Option<AttrValue>>,
value: &Lang,
) -> bool;
/// Returns whether this element is the main body element of the HTML /// Returns whether this element is the main body element of the HTML
/// document it is on. /// document it is on.

View file

@ -426,8 +426,7 @@ where
return Ok(()); return Ok(());
} }
let elements = let elements = fast_connected_elements_with_id(root, id, quirks_mode)?;
fast_connected_elements_with_id(root, id, quirks_mode)?;
if elements.is_empty() { if elements.is_empty() {
return Ok(()); return Ok(());
} }

View file

@ -104,8 +104,9 @@ impl Parse for FontWeight {
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
let first = AbsoluteFontWeight::parse(context, input)?; let first = AbsoluteFontWeight::parse(context, input)?;
let second = let second = input
input.try(|input| AbsoluteFontWeight::parse(context, input)).ok(); .try(|input| AbsoluteFontWeight::parse(context, input))
.ok();
Ok(FontWeight(first, second)) Ok(FontWeight(first, second))
} }
} }
@ -122,8 +123,9 @@ impl Parse for FontStretch {
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
let first = SpecifiedFontStretch::parse(context, input)?; let first = SpecifiedFontStretch::parse(context, input)?;
let second = let second = input
input.try(|input| SpecifiedFontStretch::parse(context, input)).ok(); .try(|input| SpecifiedFontStretch::parse(context, input))
.ok();
Ok(FontStretch(first, second)) Ok(FontStretch(first, second))
} }
} }
@ -149,12 +151,12 @@ impl Parse for FontStyle {
GenericFontStyle::Normal => FontStyle::Normal, GenericFontStyle::Normal => FontStyle::Normal,
GenericFontStyle::Italic => FontStyle::Italic, GenericFontStyle::Italic => FontStyle::Italic,
GenericFontStyle::Oblique(angle) => { GenericFontStyle::Oblique(angle) => {
let second_angle = input.try(|input| { let second_angle = input
SpecifiedFontStyle::parse_angle(context, input) .try(|input| SpecifiedFontStyle::parse_angle(context, input))
}).unwrap_or_else(|_| angle.clone()); .unwrap_or_else(|_| angle.clone());
FontStyle::Oblique(angle, second_angle) FontStyle::Oblique(angle, second_angle)
} },
}) })
} }
} }
@ -178,7 +180,7 @@ impl ToCss for FontStyle {
second.to_css(dest)?; second.to_css(dest)?;
} }
Ok(()) Ok(())
} },
} }
} }
} }
@ -235,15 +237,13 @@ impl<'a> FontFace<'a> {
// We support only opentype fonts and truetype is an alias for // We support only opentype fonts and truetype is an alias for
// that format. Sources without format hints need to be // that format. Sources without format hints need to be
// downloaded in case we support them. // downloaded in case we support them.
hints.is_empty() || hints.is_empty() || hints
hints.iter().any(|hint| { .iter()
hint == "truetype" || hint == "opentype" || hint == "woff" .any(|hint| hint == "truetype" || hint == "opentype" || hint == "woff")
})
} else { } else {
true true
} }
}) }).cloned()
.cloned()
.collect(), .collect(),
) )
} }

View file

@ -140,10 +140,7 @@ impl Angle {
} }
} }
fn line_direction( fn line_direction(horizontal: LengthOrPercentage, vertical: LengthOrPercentage) -> LineDirection {
horizontal: LengthOrPercentage,
vertical: LengthOrPercentage,
) -> LineDirection {
use values::computed::position::Position; use values::computed::position::Position;
use values::specified::position::{X, Y}; use values::specified::position::{X, Y};
@ -178,18 +175,18 @@ fn line_direction(
}); });
if let (Some(hc), Some(vc)) = (horizontal_as_corner, vertical_as_corner) { if let (Some(hc), Some(vc)) = (horizontal_as_corner, vertical_as_corner) {
return LineDirection::Corner(hc, vc) return LineDirection::Corner(hc, vc);
} }
if let Some(hc) = horizontal_as_corner { if let Some(hc) = horizontal_as_corner {
if vertical_percentage == Some(0.5) { if vertical_percentage == Some(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(0.5) {
return LineDirection::Vertical(vc) return LineDirection::Vertical(vc);
} }
} }
@ -212,7 +209,10 @@ impl nsStyleImage {
}, },
GenericImage::Rect(ref image_rect) => { GenericImage::Rect(ref image_rect) => {
unsafe { unsafe {
bindings::Gecko_SetLayerImageImageValue(self, image_rect.url.0.image_value.get()); bindings::Gecko_SetLayerImageImageValue(
self,
image_rect.url.0.image_value.get(),
);
bindings::Gecko_InitializeImageCropRect(self); bindings::Gecko_InitializeImageCropRect(self);
// Set CropRect // Set CropRect
@ -491,7 +491,8 @@ impl nsStyleImage {
unsafe fn get_image_url(&self) -> ComputedImageUrl { unsafe fn get_image_url(&self) -> ComputedImageUrl {
let image_request = bindings::Gecko_GetImageRequest(self) let image_request = bindings::Gecko_GetImageRequest(self)
.as_ref().expect("Null image request?"); .as_ref()
.expect("Null image request?");
ComputedImageUrl::from_image_request(image_request) ComputedImageUrl::from_image_request(image_request)
} }
@ -555,9 +556,9 @@ impl nsStyleImage {
structs::NS_STYLE_GRADIENT_SHAPE_CIRCULAR => { structs::NS_STYLE_GRADIENT_SHAPE_CIRCULAR => {
let circle = match gecko_gradient.mSize as u32 { let circle = match gecko_gradient.mSize as u32 {
structs::NS_STYLE_GRADIENT_SIZE_EXPLICIT_SIZE => { structs::NS_STYLE_GRADIENT_SIZE_EXPLICIT_SIZE => {
let radius = Length::from_gecko_style_coord( let radius =
&gecko_gradient.mRadiusX, Length::from_gecko_style_coord(&gecko_gradient.mRadiusX)
).expect("mRadiusX could not convert to Length"); .expect("mRadiusX could not convert to Length");
debug_assert_eq!( debug_assert_eq!(
radius, radius,
Length::from_gecko_style_coord(&gecko_gradient.mRadiusY) Length::from_gecko_style_coord(&gecko_gradient.mRadiusY)
@ -632,8 +633,7 @@ impl nsStyleImage {
position: LengthOrPercentage::from_gecko_style_coord(&stop.mLocation), position: LengthOrPercentage::from_gecko_style_coord(&stop.mLocation),
}) })
} }
}) }).collect();
.collect();
let compat_mode = if gecko_gradient.mMozLegacySyntax { let compat_mode = if gecko_gradient.mMozLegacySyntax {
CompatMode::Moz CompatMode::Moz
@ -719,8 +719,10 @@ pub mod basic_shape {
match self.mType { match self.mType {
StyleShapeSourceType::Path => { StyleShapeSourceType::Path => {
let gecko_path = unsafe { &*self.__bindgen_anon_1.mSVGPath.as_ref().mPtr }; let gecko_path = unsafe { &*self.__bindgen_anon_1.mSVGPath.as_ref().mPtr };
let result: Vec<PathCommand> = let result: Vec<PathCommand> = gecko_path
gecko_path.mPath.iter().map(|gecko: &StylePathCommand| { .mPath
.iter()
.map(|gecko: &StylePathCommand| {
// unsafe: cbindgen ensures the representation is the same. // unsafe: cbindgen ensures the representation is the same.
unsafe { ::std::mem::transmute(*gecko) } unsafe { ::std::mem::transmute(*gecko) }
}).collect(); }).collect();
@ -822,11 +824,15 @@ pub mod basic_shape {
let y = x + 1; let y = x + 1;
coords.push(PolygonCoord( coords.push(PolygonCoord(
LengthOrPercentage::from_gecko_style_coord(&other.mCoordinates[x]) LengthOrPercentage::from_gecko_style_coord(&other.mCoordinates[x])
.expect("polygon() coordinate should be a length, percentage, \ .expect(
or calc value"), "polygon() coordinate should be a length, percentage, \
or calc value",
),
LengthOrPercentage::from_gecko_style_coord(&other.mCoordinates[y]) LengthOrPercentage::from_gecko_style_coord(&other.mCoordinates[y])
.expect("polygon() coordinate should be a length, percentage, \ .expect(
or calc value") "polygon() coordinate should be a length, percentage, \
or calc value",
),
)) ))
} }
GenericBasicShape::Polygon(Polygon { GenericBasicShape::Polygon(Polygon {

View file

@ -29,7 +29,8 @@ pub struct GeckoStyleSheet(*const DomStyleSheet);
impl fmt::Debug for GeckoStyleSheet { impl fmt::Debug for GeckoStyleSheet {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let contents = self.contents(); let contents = self.contents();
formatter.debug_struct("GeckoStyleSheet") formatter
.debug_struct("GeckoStyleSheet")
.field("origin", &contents.origin) .field("origin", &contents.origin)
.field("url_data", &*contents.url_data.read()) .field("url_data", &*contents.url_data.read())
.finish() .finish()
@ -66,9 +67,7 @@ impl GeckoStyleSheet {
} }
fn inner(&self) -> &StyleSheetInfo { fn inner(&self) -> &StyleSheetInfo {
unsafe { unsafe { &*(self.raw().mInner as *const StyleSheetInfo) }
&*(self.raw().mInner as *const StyleSheetInfo)
}
} }
/// Gets the StylesheetContents for this stylesheet. /// Gets the StylesheetContents for this stylesheet.
@ -193,7 +192,8 @@ impl PerDocumentStyleDataImpl {
/// Returns whether visited styles are enabled. /// Returns whether visited styles are enabled.
#[inline] #[inline]
pub fn visited_styles_enabled(&self) -> bool { pub fn visited_styles_enabled(&self) -> bool {
let doc = self.stylist let doc = self
.stylist
.device() .device()
.pres_context() .pres_context()
.mDocument .mDocument

View file

@ -21,7 +21,7 @@ fn viewport_size(device: &Device) -> Size2D<Au> {
// We want the page size, including unprintable areas and margins. // We want the page size, including unprintable areas and margins.
// FIXME(emilio, bug 1414600): Not quite! // FIXME(emilio, bug 1414600): Not quite!
let area = &pc.mPageSize; let area = &pc.mPageSize;
return Size2D::new(Au(area.width), Au(area.height)) return Size2D::new(Au(area.width), Au(area.height));
} }
device.au_viewport_size() device.au_viewport_size()
} }
@ -30,11 +30,7 @@ fn device_size(device: &Device) -> Size2D<Au> {
let mut width = 0; let mut width = 0;
let mut height = 0; let mut height = 0;
unsafe { unsafe {
bindings::Gecko_MediaFeatures_GetDeviceSize( bindings::Gecko_MediaFeatures_GetDeviceSize(device.document(), &mut width, &mut height);
device.document(),
&mut width,
&mut height,
);
} }
Size2D::new(Au(width), Au(height)) Size2D::new(Au(width), Au(height))
} }
@ -152,11 +148,7 @@ enum Orientation {
Portrait, Portrait,
} }
fn eval_orientation_for<F>( fn eval_orientation_for<F>(device: &Device, value: Option<Orientation>, get_size: F) -> bool
device: &Device,
value: Option<Orientation>,
get_size: F,
) -> bool
where where
F: FnOnce(&Device) -> Size2D<Au>, F: FnOnce(&Device) -> Size2D<Au>,
{ {
@ -176,18 +168,12 @@ where
} }
/// https://drafts.csswg.org/mediaqueries-4/#orientation /// https://drafts.csswg.org/mediaqueries-4/#orientation
fn eval_orientation( fn eval_orientation(device: &Device, value: Option<Orientation>) -> bool {
device: &Device,
value: Option<Orientation>,
) -> bool {
eval_orientation_for(device, value, viewport_size) eval_orientation_for(device, value, viewport_size)
} }
/// FIXME: There's no spec for `-moz-device-orientation`. /// FIXME: There's no spec for `-moz-device-orientation`.
fn eval_device_orientation( fn eval_device_orientation(device: &Device, value: Option<Orientation>) -> bool {
device: &Device,
value: Option<Orientation>,
) -> bool {
eval_orientation_for(device, value, device_size) eval_orientation_for(device, value, device_size)
} }
@ -196,25 +182,21 @@ fn eval_device_orientation(
#[repr(u8)] #[repr(u8)]
#[allow(missing_docs)] #[allow(missing_docs)]
pub enum DisplayMode { pub enum DisplayMode {
Browser = 0, Browser = 0,
MinimalUi, MinimalUi,
Standalone, Standalone,
Fullscreen, Fullscreen,
} }
/// https://w3c.github.io/manifest/#the-display-mode-media-feature /// https://w3c.github.io/manifest/#the-display-mode-media-feature
fn eval_display_mode( fn eval_display_mode(device: &Device, query_value: Option<DisplayMode>) -> bool {
device: &Device,
query_value: Option<DisplayMode>,
) -> bool {
let query_value = match query_value { let query_value = match query_value {
Some(v) => v, Some(v) => v,
None => return true, None => return true,
}; };
let gecko_display_mode = unsafe { let gecko_display_mode =
bindings::Gecko_MediaFeatures_GetDisplayMode(device.document()) unsafe { bindings::Gecko_MediaFeatures_GetDisplayMode(device.document()) };
};
// NOTE: cbindgen guarantees the same representation. // NOTE: cbindgen guarantees the same representation.
gecko_display_mode as u8 == query_value as u8 gecko_display_mode as u8 == query_value as u8
@ -229,11 +211,7 @@ fn eval_grid(_: &Device, query_value: Option<bool>, _: Option<RangeOrOperator>)
} }
/// https://compat.spec.whatwg.org/#css-media-queries-webkit-transform-3d /// https://compat.spec.whatwg.org/#css-media-queries-webkit-transform-3d
fn eval_transform_3d( fn eval_transform_3d(_: &Device, query_value: Option<bool>, _: Option<RangeOrOperator>) -> bool {
_: &Device,
query_value: Option<bool>,
_: Option<RangeOrOperator>,
) -> bool {
let supports_transforms = true; let supports_transforms = true;
query_value.map_or(supports_transforms, |v| v == supports_transforms) query_value.map_or(supports_transforms, |v| v == supports_transforms)
} }
@ -260,11 +238,7 @@ fn eval_color(
) -> bool { ) -> bool {
let color_bits_per_channel = let color_bits_per_channel =
unsafe { bindings::Gecko_MediaFeatures_GetColorDepth(device.document()) }; unsafe { bindings::Gecko_MediaFeatures_GetColorDepth(device.document()) };
RangeOrOperator::evaluate( RangeOrOperator::evaluate(range_or_operator, query_value, color_bits_per_channel)
range_or_operator,
query_value,
color_bits_per_channel,
)
} }
/// https://drafts.csswg.org/mediaqueries-4/#color-index /// https://drafts.csswg.org/mediaqueries-4/#color-index
@ -275,11 +249,7 @@ fn eval_color_index(
) -> bool { ) -> bool {
// We should return zero if the device does not use a color lookup table. // We should return zero if the device does not use a color lookup table.
let index = 0; let index = 0;
RangeOrOperator::evaluate( RangeOrOperator::evaluate(range_or_operator, query_value, index)
range_or_operator,
query_value,
index,
)
} }
/// https://drafts.csswg.org/mediaqueries-4/#monochrome /// https://drafts.csswg.org/mediaqueries-4/#monochrome
@ -291,11 +261,7 @@ fn eval_monochrome(
// For color devices we should return 0. // For color devices we should return 0.
// FIXME: On a monochrome device, return the actual color depth, not 0! // FIXME: On a monochrome device, return the actual color depth, not 0!
let depth = 0; let depth = 0;
RangeOrOperator::evaluate( RangeOrOperator::evaluate(range_or_operator, query_value, depth)
range_or_operator,
query_value,
depth,
)
} }
/// https://drafts.csswg.org/mediaqueries-4/#resolution /// https://drafts.csswg.org/mediaqueries-4/#resolution
@ -304,8 +270,7 @@ fn eval_resolution(
query_value: Option<Resolution>, query_value: Option<Resolution>,
range_or_operator: Option<RangeOrOperator>, range_or_operator: Option<RangeOrOperator>,
) -> bool { ) -> bool {
let resolution_dppx = let resolution_dppx = unsafe { bindings::Gecko_MediaFeatures_GetResolution(device.document()) };
unsafe { bindings::Gecko_MediaFeatures_GetResolution(device.document()) };
RangeOrOperator::evaluate( RangeOrOperator::evaluate(
range_or_operator, range_or_operator,
query_value.map(|r| r.dppx()), query_value.map(|r| r.dppx()),
@ -321,10 +286,7 @@ enum PrefersReducedMotion {
} }
/// https://drafts.csswg.org/mediaqueries-5/#prefers-reduced-motion /// https://drafts.csswg.org/mediaqueries-5/#prefers-reduced-motion
fn eval_prefers_reduced_motion( fn eval_prefers_reduced_motion(device: &Device, query_value: Option<PrefersReducedMotion>) -> bool {
device: &Device,
query_value: Option<PrefersReducedMotion>,
) -> bool {
let prefers_reduced = let prefers_reduced =
unsafe { bindings::Gecko_MediaFeatures_PrefersReducedMotion(device.document()) }; unsafe { bindings::Gecko_MediaFeatures_PrefersReducedMotion(device.document()) };
let query_value = match query_value { let query_value = match query_value {
@ -352,9 +314,8 @@ fn eval_moz_is_resource_document(
query_value: Option<bool>, query_value: Option<bool>,
_: Option<RangeOrOperator>, _: Option<RangeOrOperator>,
) -> bool { ) -> bool {
let is_resource_doc = unsafe { let is_resource_doc =
bindings::Gecko_MediaFeatures_IsResourceDocument(device.document()) unsafe { bindings::Gecko_MediaFeatures_IsResourceDocument(device.document()) };
};
query_value.map_or(is_resource_doc, |v| v == is_resource_doc) query_value.map_or(is_resource_doc, |v| v == is_resource_doc)
} }
@ -397,37 +358,30 @@ fn eval_moz_os_version(
None => return false, None => return false,
}; };
let os_version = unsafe { let os_version =
bindings::Gecko_MediaFeatures_GetOperatingSystemVersion(device.document()) unsafe { bindings::Gecko_MediaFeatures_GetOperatingSystemVersion(device.document()) };
};
query_value.as_ptr() == os_version query_value.as_ptr() == os_version
} }
macro_rules! system_metric_feature { macro_rules! system_metric_feature {
($feature_name:expr) => { ($feature_name:expr) => {{
{ fn __eval(device: &Device, query_value: Option<bool>, _: Option<RangeOrOperator>) -> bool {
fn __eval( eval_system_metric(
device: &Device, device,
query_value: Option<bool>, query_value,
_: Option<RangeOrOperator>,
) -> bool {
eval_system_metric(
device,
query_value,
$feature_name,
/* accessible_from_content = */ false,
)
}
feature!(
$feature_name, $feature_name,
AllowsRanges::No, /* accessible_from_content = */ false,
Evaluator::BoolInteger(__eval),
ParsingRequirements::CHROME_AND_UA_ONLY,
) )
} }
}
feature!(
$feature_name,
AllowsRanges::No,
Evaluator::BoolInteger(__eval),
ParsingRequirements::CHROME_AND_UA_ONLY,
)
}};
} }
lazy_static! { lazy_static! {

View file

@ -126,7 +126,8 @@ impl Device {
/// Set the font size of the root element (for rem) /// Set the font size of the root element (for rem)
pub fn set_root_font_size(&self, size: Au) { pub fn set_root_font_size(&self, size: Au) {
self.root_font_size.store(size.0 as isize, Ordering::Relaxed) self.root_font_size
.store(size.0 as isize, Ordering::Relaxed)
} }
/// Sets the body text color for the "inherit color from body" quirk. /// Sets the body text color for the "inherit color from body" quirk.

View file

@ -62,7 +62,9 @@ impl PseudoElement {
/// ///
/// This is used in Servo for anonymous boxes, though it's likely broken. /// This is used in Servo for anonymous boxes, though it's likely broken.
#[inline] #[inline]
pub fn inherits_all(&self) -> bool { false } pub fn inherits_all(&self) -> bool {
false
}
/// Whether the pseudo-element should inherit from the default computed /// Whether the pseudo-element should inherit from the default computed
/// values instead of from the parent element. /// values instead of from the parent element.

View file

@ -88,7 +88,7 @@ macro_rules! descriptor_range_conversion {
None => { None => {
nscssvalue.set_from(first); nscssvalue.set_from(first);
return; return;
} },
Some(ref second) => second, Some(ref second) => second,
}; };
@ -101,7 +101,7 @@ macro_rules! descriptor_range_conversion {
nscssvalue.set_pair(&a, &b); nscssvalue.set_pair(&a, &b);
} }
} }
} };
} }
descriptor_range_conversion!(FontWeight); descriptor_range_conversion!(FontWeight);
@ -120,7 +120,7 @@ impl<'a> ToNsCssValue for &'a FontStyle {
b.set_font_style(SpecifiedFontStyle::compute_angle(second).degrees()); b.set_font_style(SpecifiedFontStyle::compute_angle(second).degrees());
nscssvalue.set_pair(&a, &b); nscssvalue.set_pair(&a, &b);
} },
} }
} }
} }

View file

@ -181,9 +181,8 @@ impl NonTSPseudoClass {
}, },
// Otherwise, a pseudo-class is enabled in content when it // Otherwise, a pseudo-class is enabled in content when it
// doesn't have any enabled flag. // doesn't have any enabled flag.
_ => !self.has_any_flag( _ => !self
NonTSPseudoClassFlag::PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME, .has_any_flag(NonTSPseudoClassFlag::PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
),
} }
} }
@ -233,8 +232,7 @@ impl NonTSPseudoClass {
/// Returns true if the given pseudoclass should trigger style sharing cache /// Returns true if the given pseudoclass should trigger style sharing cache
/// revalidation. /// revalidation.
pub fn needs_cache_revalidation(&self) -> bool { pub fn needs_cache_revalidation(&self) -> bool {
self.state_flag().is_empty() && self.state_flag().is_empty() && !matches!(*self,
!matches!(*self,
// :-moz-any is handled by the revalidation visitor walking // :-moz-any is handled by the revalidation visitor walking
// the things inside it; it does not need to cause // the things inside it; it does not need to cause
// revalidation on its own. // revalidation on its own.
@ -268,7 +266,8 @@ impl NonTSPseudoClass {
pub fn is_attr_based(&self) -> bool { pub fn is_attr_based(&self) -> bool {
matches!( matches!(
*self, *self,
NonTSPseudoClass::MozTableBorderNonzero | NonTSPseudoClass::MozBrowserFrame | NonTSPseudoClass::MozTableBorderNonzero |
NonTSPseudoClass::MozBrowserFrame |
NonTSPseudoClass::Lang(..) NonTSPseudoClass::Lang(..)
) )
} }

View file

@ -41,15 +41,26 @@ unsafe fn get_class_from_attr(attr: &structs::nsAttrValue) -> Class {
debug_assert_eq!(base_type, structs::nsAttrValue_ValueBaseType_eOtherBase); debug_assert_eq!(base_type, structs::nsAttrValue_ValueBaseType_eOtherBase);
let container = ptr::<structs::MiscContainer>(attr); let container = ptr::<structs::MiscContainer>(attr);
debug_assert_eq!((*container).mType, structs::nsAttrValue_ValueType_eAtomArray); debug_assert_eq!(
let array = (*container).mType,
(*container).__bindgen_anon_1.mValue.as_ref().__bindgen_anon_1.mAtomArray.as_ref(); structs::nsAttrValue_ValueType_eAtomArray
);
let array = (*container)
.__bindgen_anon_1
.mValue
.as_ref()
.__bindgen_anon_1
.mAtomArray
.as_ref();
Class::More(&***array) Class::More(&***array)
} }
#[inline(always)] #[inline(always)]
unsafe fn get_id_from_attr(attr: &structs::nsAttrValue) -> &WeakAtom { unsafe fn get_id_from_attr(attr: &structs::nsAttrValue) -> &WeakAtom {
debug_assert_eq!(base_type(attr), structs::nsAttrValue_ValueBaseType_eAtomBase); debug_assert_eq!(
base_type(attr),
structs::nsAttrValue_ValueBaseType_eAtomBase
);
WeakAtom::new(ptr::<nsAtom>(attr)) WeakAtom::new(ptr::<nsAtom>(attr))
} }
@ -59,7 +70,8 @@ pub fn find_attr<'a>(
attrs: &'a [structs::AttrArray_InternalAttr], attrs: &'a [structs::AttrArray_InternalAttr],
name: &Atom, name: &Atom,
) -> Option<&'a structs::nsAttrValue> { ) -> Option<&'a structs::nsAttrValue> {
attrs.iter() attrs
.iter()
.find(|attr| attr.mName.mBits == name.as_ptr() as usize) .find(|attr| attr.mName.mBits == name.as_ptr() as usize)
.map(|attr| &attr.mValue) .map(|attr| &attr.mValue)
} }
@ -80,19 +92,17 @@ pub fn has_class(
) -> bool { ) -> bool {
match unsafe { get_class_from_attr(attr) } { match unsafe { get_class_from_attr(attr) } {
Class::None => false, Class::None => false,
Class::One(atom) => unsafe { Class::One(atom) => unsafe { case_sensitivity.eq_atom(name, WeakAtom::new(atom)) },
case_sensitivity.eq_atom(name, WeakAtom::new(atom)) Class::More(atoms) => match case_sensitivity {
CaseSensitivity::CaseSensitive => {
atoms.iter().any(|atom| atom.mRawPtr == name.as_ptr())
},
CaseSensitivity::AsciiCaseInsensitive => unsafe {
atoms
.iter()
.any(|atom| WeakAtom::new(atom.mRawPtr).eq_ignore_ascii_case(name))
},
}, },
Class::More(atoms) => {
match case_sensitivity {
CaseSensitivity::CaseSensitive => {
atoms.iter().any(|atom| atom.mRawPtr == name.as_ptr())
}
CaseSensitivity::AsciiCaseInsensitive => unsafe {
atoms.iter().any(|atom| WeakAtom::new(atom.mRawPtr).eq_ignore_ascii_case(name))
}
}
}
} }
} }
@ -111,7 +121,7 @@ where
for atom in atoms { for atom in atoms {
Atom::with(atom.mRawPtr, &mut callback) Atom::with(atom.mRawPtr, &mut callback)
} }
} },
} }
} }
} }

View file

@ -55,8 +55,7 @@ impl CssUrl {
/// Convert from URLValueData to SpecifiedUrl. /// Convert from URLValueData to SpecifiedUrl.
unsafe fn from_url_value_data(url: &URLValueData) -> Self { unsafe fn from_url_value_data(url: &URLValueData) -> Self {
let arc_type = let arc_type = &url.mString as *const _ as *const RawOffsetArc<String>;
&url.mString as *const _ as *const RawOffsetArc<String>;
CssUrl { CssUrl {
serialization: Arc::from_raw_offset((*arc_type).clone()), serialization: Arc::from_raw_offset((*arc_type).clone()),
extra_data: UrlExtraData(url.mExtraData.to_safe()), extra_data: UrlExtraData(url.mExtraData.to_safe()),
@ -140,7 +139,6 @@ impl SpecifiedUrl {
} }
} }
impl PartialEq for SpecifiedUrl { impl PartialEq for SpecifiedUrl {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.url.eq(&other.url) self.url.eq(&other.url)
@ -255,10 +253,7 @@ impl ToComputedValue for SpecifiedImageUrl {
} }
} }
fn serialize_computed_url<W>( fn serialize_computed_url<W>(url_value_data: &URLValueData, dest: &mut CssWriter<W>) -> fmt::Result
url_value_data: &URLValueData,
dest: &mut CssWriter<W>,
) -> fmt::Result
where where
W: Write, W: Write,
{ {
@ -281,7 +276,7 @@ pub struct ComputedUrl(pub SpecifiedUrl);
impl ToCss for ComputedUrl { impl ToCss for ComputedUrl {
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,
{ {
serialize_computed_url(&self.0.url_value._base, dest) serialize_computed_url(&self.0.url_value._base, dest)
} }
@ -302,7 +297,7 @@ pub struct ComputedImageUrl(pub SpecifiedImageUrl);
impl ToCss for ComputedImageUrl { impl ToCss for ComputedImageUrl {
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,
{ {
serialize_computed_url(&self.0.image_value._base, dest) serialize_computed_url(&self.0.image_value._base, dest)
} }

View file

@ -488,7 +488,9 @@ where
/// Convert a given RGBA value to `nscolor`. /// Convert a given RGBA value to `nscolor`.
pub fn convert_rgba_to_nscolor(rgba: &RGBA) -> u32 { pub fn convert_rgba_to_nscolor(rgba: &RGBA) -> u32 {
((rgba.alpha as u32) << 24) | ((rgba.blue as u32) << 16) | ((rgba.green as u32) << 8) | ((rgba.alpha as u32) << 24) |
((rgba.blue as u32) << 16) |
((rgba.green as u32) << 8) |
(rgba.red as u32) (rgba.red as u32)
} }
@ -537,8 +539,7 @@ impl CounterStyleOrNone {
.map(|symbol| match *symbol { .map(|symbol| match *symbol {
Symbol::String(ref s) => nsCStr::from(s), Symbol::String(ref s) => nsCStr::from(s),
Symbol::Ident(_) => unreachable!("Should not have identifier in symbols()"), Symbol::Ident(_) => unreachable!("Should not have identifier in symbols()"),
}) }).collect();
.collect();
let symbols: Vec<_> = symbols let symbols: Vec<_> = symbols
.iter() .iter()
.map(|symbol| symbol as &nsACString as *const _) .map(|symbol| symbol as &nsACString as *const _)

View file

@ -86,7 +86,6 @@ use std::ptr;
use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace}; use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace};
use stylist::CascadeData; use stylist::CascadeData;
#[inline] #[inline]
fn elements_with_id<'a, 'le>( fn elements_with_id<'a, 'le>(
array: *const structs::nsTArray<*mut RawGeckoElement>, array: *const structs::nsTArray<*mut RawGeckoElement>,
@ -172,12 +171,11 @@ impl<'lr> TShadowRoot for GeckoShadowRoot<'lr> {
Self: 'a, Self: 'a,
{ {
let author_styles = unsafe { let author_styles = unsafe {
(self.0.mServoStyles.mPtr (self.0.mServoStyles.mPtr as *const structs::RawServoAuthorStyles
as *const structs::RawServoAuthorStyles as *const bindings::RawServoAuthorStyles)
as *const bindings::RawServoAuthorStyles).as_ref()? .as_ref()?
}; };
let author_styles = AuthorStyles::<GeckoStyleSheet>::from_ffi(author_styles); let author_styles = AuthorStyles::<GeckoStyleSheet>::from_ffi(author_styles);
debug_assert!( debug_assert!(
@ -375,7 +373,8 @@ impl<'ln> TNode for GeckoNode<'ln> {
fn first_child(&self) -> Option<Self> { fn first_child(&self) -> Option<Self> {
unsafe { unsafe {
self.0 self.0
.mFirstChild.raw::<nsIContent>() .mFirstChild
.raw::<nsIContent>()
.as_ref() .as_ref()
.map(GeckoNode::from_content) .map(GeckoNode::from_content)
} }
@ -395,7 +394,8 @@ impl<'ln> TNode for GeckoNode<'ln> {
fn next_sibling(&self) -> Option<Self> { fn next_sibling(&self) -> Option<Self> {
unsafe { unsafe {
self.0 self.0
.mNextSibling.raw::<nsIContent>() .mNextSibling
.raw::<nsIContent>()
.as_ref() .as_ref()
.map(GeckoNode::from_content) .map(GeckoNode::from_content)
} }
@ -600,7 +600,7 @@ impl<'le> GeckoElement<'le> {
if self.is_svg_element() { if self.is_svg_element() {
let svg_class = unsafe { bindings::Gecko_GetSVGAnimatedClass(self.0).as_ref() }; let svg_class = unsafe { bindings::Gecko_GetSVGAnimatedClass(self.0).as_ref() };
if let Some(c) = svg_class { if let Some(c) = svg_class {
return Some(c) return Some(c);
} }
} }
@ -672,8 +672,7 @@ impl<'le> GeckoElement<'le> {
// For the bit usage, see nsContentSlots::GetExtendedSlots. // For the bit usage, see nsContentSlots::GetExtendedSlots.
let e_slots = s._base.mExtendedSlots & let e_slots = s._base.mExtendedSlots &
!structs::nsIContent_nsContentSlots_sNonOwningExtendedSlotsFlag; !structs::nsIContent_nsContentSlots_sNonOwningExtendedSlotsFlag;
(e_slots as *const structs::FragmentOrElement_nsExtendedDOMSlots) (e_slots as *const structs::FragmentOrElement_nsExtendedDOMSlots).as_ref()
.as_ref()
}) })
} }
@ -719,9 +718,8 @@ impl<'le> GeckoElement<'le> {
.and_then(|n| n.as_element()); .and_then(|n| n.as_element());
debug_assert!( debug_assert!(
binding_parent == unsafe { binding_parent ==
bindings::Gecko_GetBindingParent(self.0).map(GeckoElement) unsafe { bindings::Gecko_GetBindingParent(self.0).map(GeckoElement) }
}
); );
binding_parent binding_parent
} }
@ -730,8 +728,9 @@ impl<'le> GeckoElement<'le> {
#[inline] #[inline]
fn non_xul_xbl_binding_parent_raw_content(&self) -> *mut nsIContent { fn non_xul_xbl_binding_parent_raw_content(&self) -> *mut nsIContent {
debug_assert!(!self.is_xul_element()); debug_assert!(!self.is_xul_element());
self.extended_slots() self.extended_slots().map_or(ptr::null_mut(), |slots| {
.map_or(ptr::null_mut(), |slots| slots._base.mBindingParent.raw::<nsIContent>()) slots._base.mBindingParent.raw::<nsIContent>()
})
} }
#[inline] #[inline]
@ -747,7 +746,8 @@ impl<'le> GeckoElement<'le> {
#[inline] #[inline]
fn state_internal(&self) -> u64 { fn state_internal(&self) -> u64 {
if !self.as_node() if !self
.as_node()
.get_bool_flag(nsINode_BooleanFlag::ElementHasLockedStyleStates) .get_bool_flag(nsINode_BooleanFlag::ElementHasLockedStyleStates)
{ {
return self.0.mState.mStates; return self.0.mState.mStates;
@ -878,9 +878,7 @@ impl<'le> GeckoElement<'le> {
return false; return false;
} }
match self.containing_shadow_host() { match self.containing_shadow_host() {
Some(e) => { Some(e) => e.is_svg_element() && e.local_name() == &*local_name!("use"),
e.is_svg_element() && e.local_name() == &*local_name!("use")
},
None => false, None => false,
} }
} }
@ -934,13 +932,12 @@ impl<'le> GeckoElement<'le> {
debug_assert_eq!(to.is_some(), from.is_some()); debug_assert_eq!(to.is_some(), from.is_some());
combined_duration > 0.0f32 && from != to && combined_duration > 0.0f32 && from != to && from
from.unwrap() .unwrap()
.animate( .animate(
to.as_ref().unwrap(), to.as_ref().unwrap(),
Procedure::Interpolate { progress: 0.5 }, Procedure::Interpolate { progress: 0.5 },
) ).is_ok()
.is_ok()
} }
} }
@ -980,7 +977,9 @@ fn get_animation_rule(
let effect_count = unsafe { Gecko_GetAnimationEffectCount(element.0) }; let effect_count = unsafe { Gecko_GetAnimationEffectCount(element.0) };
// Also, we should try to reuse the PDB, to avoid creating extra rule nodes. // Also, we should try to reuse the PDB, to avoid creating extra rule nodes.
let mut animation_values = AnimationValueMap::with_capacity_and_hasher( let mut animation_values = AnimationValueMap::with_capacity_and_hasher(
effect_count.min(ANIMATABLE_PROPERTY_COUNT), Default::default()); effect_count.min(ANIMATABLE_PROPERTY_COUNT),
Default::default(),
);
if unsafe { if unsafe {
Gecko_GetAnimationRule( Gecko_GetAnimationRule(
element.0, element.0,
@ -1084,10 +1083,12 @@ impl<'le> TElement for GeckoElement<'le> {
fn inheritance_parent(&self) -> Option<Self> { fn inheritance_parent(&self) -> Option<Self> {
if self.implemented_pseudo_element().is_some() { if self.implemented_pseudo_element().is_some() {
return self.pseudo_element_originating_element() return self.pseudo_element_originating_element();
} }
self.as_node().flattened_tree_parent().and_then(|n| n.as_element()) self.as_node()
.flattened_tree_parent()
.and_then(|n| n.as_element())
} }
fn traversal_children(&self) -> LayoutIterator<GeckoChildrenIterator<'le>> { fn traversal_children(&self) -> LayoutIterator<GeckoChildrenIterator<'le>> {
@ -1095,8 +1096,10 @@ impl<'le> TElement for GeckoElement<'le> {
// StyleChildrenIterator::IsNeeded does, except that it might return // StyleChildrenIterator::IsNeeded does, except that it might return
// true if we used to (but no longer) have anonymous content from // true if we used to (but no longer) have anonymous content from
// ::before/::after, XBL bindings, or nsIAnonymousContentCreators. // ::before/::after, XBL bindings, or nsIAnonymousContentCreators.
if self.is_in_anonymous_subtree() || self.has_xbl_binding_with_content() || if self.is_in_anonymous_subtree() ||
self.is_html_slot_element() || self.shadow_root().is_some() || self.has_xbl_binding_with_content() ||
self.is_html_slot_element() ||
self.shadow_root().is_some() ||
self.may_have_anonymous_children() self.may_have_anonymous_children()
{ {
unsafe { unsafe {
@ -1157,17 +1160,16 @@ impl<'le> TElement for GeckoElement<'le> {
// Bug 1466580 tracks running the Android layout tests on automation. // Bug 1466580 tracks running the Android layout tests on automation.
// //
// The actual bindgen bug still needs reduction. // The actual bindgen bug still needs reduction.
let assigned_nodes: &[structs::RefPtr<structs::nsINode>] = let assigned_nodes: &[structs::RefPtr<structs::nsINode>] = if !cfg!(target_os = "android") {
if !cfg!(target_os = "android") { debug_assert_eq!(
debug_assert_eq!( unsafe { bindings::Gecko_GetAssignedNodes(self.0) },
unsafe { bindings::Gecko_GetAssignedNodes(self.0) }, &slot.mAssignedNodes as *const _,
&slot.mAssignedNodes as *const _, );
);
&*slot.mAssignedNodes &*slot.mAssignedNodes
} else { } else {
unsafe { &**bindings::Gecko_GetAssignedNodes(self.0) } unsafe { &**bindings::Gecko_GetAssignedNodes(self.0) }
}; };
debug_assert_eq!( debug_assert_eq!(
mem::size_of::<structs::RefPtr<structs::nsINode>>(), mem::size_of::<structs::RefPtr<structs::nsINode>>(),
@ -1239,11 +1241,10 @@ impl<'le> TElement for GeckoElement<'le> {
} }
fn owner_doc_matches_for_testing(&self, device: &Device) -> bool { fn owner_doc_matches_for_testing(&self, device: &Device) -> bool {
self.as_node().owner_doc().0 as *const structs::nsIDocument == self.as_node().owner_doc().0 as *const structs::nsIDocument == device
device .pres_context()
.pres_context() .mDocument
.mDocument .raw::<structs::nsIDocument>()
.raw::<structs::nsIDocument>()
} }
fn style_attribute(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>> { fn style_attribute(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>> {
@ -1378,7 +1379,8 @@ impl<'le> TElement for GeckoElement<'le> {
self.unset_flags( self.unset_flags(
ELEMENT_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32 | ELEMENT_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32 |
ELEMENT_HAS_ANIMATION_ONLY_DIRTY_DESCENDANTS_FOR_SERVO as u32 | ELEMENT_HAS_ANIMATION_ONLY_DIRTY_DESCENDANTS_FOR_SERVO as u32 |
NODE_DESCENDANTS_NEED_FRAMES as u32 | NODE_NEEDS_FRAME as u32, NODE_DESCENDANTS_NEED_FRAMES as u32 |
NODE_NEEDS_FRAME as u32,
) )
} }
@ -1438,8 +1440,10 @@ impl<'le> TElement for GeckoElement<'le> {
unsafe fn clear_data(&self) { unsafe fn clear_data(&self) {
let ptr = self.0.mServoData.get(); let ptr = self.0.mServoData.get();
self.unset_flags( self.unset_flags(
ELEMENT_HAS_SNAPSHOT as u32 | ELEMENT_HANDLED_SNAPSHOT as u32 | ELEMENT_HAS_SNAPSHOT as u32 |
structs::Element_kAllServoDescendantBits | NODE_NEEDS_FRAME as u32, ELEMENT_HANDLED_SNAPSHOT as u32 |
structs::Element_kAllServoDescendantBits |
NODE_NEEDS_FRAME as u32,
); );
if !ptr.is_null() { if !ptr.is_null() {
debug!("Dropping ElementData for {:?}", self); debug!("Dropping ElementData for {:?}", self);
@ -1668,8 +1672,7 @@ impl<'le> TElement for GeckoElement<'le> {
let transition_property: TransitionProperty = property.into(); let transition_property: TransitionProperty = property.into();
let mut property_check_helper = |property: LonghandId| -> bool { let mut property_check_helper = |property: LonghandId| -> bool {
let property = let property = property.to_physical(after_change_style.writing_mode);
property.to_physical(after_change_style.writing_mode);
transitions_to_keep.insert(property); transitions_to_keep.insert(property);
self.needs_transitions_update_per_property( self.needs_transitions_update_per_property(
property, property,
@ -1681,8 +1684,7 @@ impl<'le> TElement for GeckoElement<'le> {
}; };
match transition_property { match transition_property {
TransitionProperty::Custom(..) | TransitionProperty::Custom(..) | TransitionProperty::Unsupported(..) => {},
TransitionProperty::Unsupported(..) => {},
TransitionProperty::Shorthand(ref shorthand) => { TransitionProperty::Shorthand(ref shorthand) => {
if shorthand.longhands().any(property_check_helper) { if shorthand.longhands().any(property_check_helper) {
return true; return true;
@ -1713,11 +1715,7 @@ impl<'le> TElement for GeckoElement<'le> {
} }
} }
fn match_element_lang( fn match_element_lang(&self, override_lang: Option<Option<AttrValue>>, value: &Lang) -> bool {
&self,
override_lang: Option<Option<AttrValue>>,
value: &Lang,
) -> bool {
// Gecko supports :lang() from CSS Selectors 3, which only accepts a // Gecko supports :lang() from CSS Selectors 3, which only accepts a
// single language tag, and which performs simple dash-prefix matching // single language tag, and which performs simple dash-prefix matching
// on it. // on it.
@ -1860,7 +1858,8 @@ impl<'le> TElement for GeckoElement<'le> {
)); ));
} }
let active = self.state() let active = self
.state()
.intersects(NonTSPseudoClass::Active.state_flag()); .intersects(NonTSPseudoClass::Active.state_flag());
if active { if active {
let declarations = unsafe { Gecko_GetActiveLinkAttrDeclarationBlock(self.0) }; let declarations = unsafe { Gecko_GetActiveLinkAttrDeclarationBlock(self.0) };
@ -2070,7 +2069,10 @@ impl<'le> ::selectors::Element for GeckoElement<'le> {
#[inline] #[inline]
fn is_root(&self) -> bool { fn is_root(&self) -> bool {
if self.as_node().get_bool_flag(nsINode_BooleanFlag::ParentIsContent) { if self
.as_node()
.get_bool_flag(nsINode_BooleanFlag::ParentIsContent)
{
return false; return false;
} }
@ -2078,12 +2080,17 @@ impl<'le> ::selectors::Element for GeckoElement<'le> {
return false; return false;
} }
debug_assert!(self.as_node().parent_node().map_or(false, |p| p.is_document())); debug_assert!(
self.as_node()
.parent_node()
.map_or(false, |p| p.is_document())
);
unsafe { bindings::Gecko_IsRootElement(self.0) } unsafe { bindings::Gecko_IsRootElement(self.0) }
} }
fn is_empty(&self) -> bool { fn is_empty(&self) -> bool {
!self.as_node() !self
.as_node()
.dom_children() .dom_children()
.any(|child| unsafe { Gecko_IsSignificantChild(child.0, true) }) .any(|child| unsafe { Gecko_IsSignificantChild(child.0, true) })
} }
@ -2194,7 +2201,8 @@ impl<'le> ::selectors::Element for GeckoElement<'le> {
}, },
NonTSPseudoClass::MozOnlyWhitespace => { NonTSPseudoClass::MozOnlyWhitespace => {
flags_setter(self, ElementSelectorFlags::HAS_EMPTY_SELECTOR); flags_setter(self, ElementSelectorFlags::HAS_EMPTY_SELECTOR);
if self.as_node() if self
.as_node()
.dom_children() .dom_children()
.any(|c| c.contains_non_whitespace_content()) .any(|c| c.contains_non_whitespace_content())
{ {
@ -2246,9 +2254,7 @@ impl<'le> ::selectors::Element for GeckoElement<'le> {
None => false, None => false,
} }
}, },
NonTSPseudoClass::Dir(ref dir) => { NonTSPseudoClass::Dir(ref dir) => self.state().intersects(dir.element_state()),
self.state().intersects(dir.element_state())
}
} }
} }

View file

@ -4,7 +4,12 @@
//! Gecko's C++ bindings, along with some rust helpers to ease its use. //! Gecko's C++ bindings, along with some rust helpers to ease its use.
#[allow(dead_code, improper_ctypes, non_camel_case_types, missing_docs)] #[allow(
dead_code,
improper_ctypes,
non_camel_case_types,
missing_docs
)]
pub mod bindings { pub mod bindings {
include!(concat!(env!("OUT_DIR"), "/gecko/bindings.rs")); include!(concat!(env!("OUT_DIR"), "/gecko/bindings.rs"));
} }
@ -13,8 +18,14 @@ pub mod bindings {
// foreign structs to have `PhantomData`. We should remove this once the lint // foreign structs to have `PhantomData`. We should remove this once the lint
// ignores this case. // ignores this case.
#[allow(dead_code, improper_ctypes, non_camel_case_types, non_snake_case, non_upper_case_globals, #[allow(
missing_docs)] dead_code,
improper_ctypes,
non_camel_case_types,
non_snake_case,
non_upper_case_globals,
missing_docs
)]
pub mod structs { pub mod structs {
include!(concat!(env!("OUT_DIR"), "/gecko/structs.rs")); include!(concat!(env!("OUT_DIR"), "/gecko/structs.rs"));
} }

View file

@ -52,7 +52,8 @@ impl nsStyleCoord_CalcValue {
impl PartialEq for nsStyleCoord_CalcValue { impl PartialEq for nsStyleCoord_CalcValue {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.mLength == other.mLength && self.mPercent == other.mPercent && self.mLength == other.mLength &&
self.mPercent == other.mPercent &&
self.mHasPercent == other.mHasPercent self.mHasPercent == other.mHasPercent
} }
} }
@ -409,9 +410,12 @@ pub unsafe trait CoordData {
unsafe fn get_float(&self) -> f32 { unsafe fn get_float(&self) -> f32 {
use gecko_bindings::structs::nsStyleUnit::*; use gecko_bindings::structs::nsStyleUnit::*;
debug_assert!( debug_assert!(
self.unit() == eStyleUnit_Percent || self.unit() == eStyleUnit_Factor || self.unit() == eStyleUnit_Percent ||
self.unit() == eStyleUnit_Degree || self.unit() == eStyleUnit_Grad || self.unit() == eStyleUnit_Factor ||
self.unit() == eStyleUnit_Radian || self.unit() == eStyleUnit_Turn || self.unit() == eStyleUnit_Degree ||
self.unit() == eStyleUnit_Grad ||
self.unit() == eStyleUnit_Radian ||
self.unit() == eStyleUnit_Turn ||
self.unit() == eStyleUnit_FlexFraction self.unit() == eStyleUnit_FlexFraction
); );
*self.union().mFloat.as_ref() *self.union().mFloat.as_ref()
@ -422,7 +426,8 @@ pub unsafe trait CoordData {
unsafe fn get_integer(&self) -> i32 { unsafe fn get_integer(&self) -> i32 {
use gecko_bindings::structs::nsStyleUnit::*; use gecko_bindings::structs::nsStyleUnit::*;
debug_assert!( debug_assert!(
self.unit() == eStyleUnit_Coord || self.unit() == eStyleUnit_Integer || self.unit() == eStyleUnit_Coord ||
self.unit() == eStyleUnit_Integer ||
self.unit() == eStyleUnit_Enumerated self.unit() == eStyleUnit_Enumerated
); );
*self.union().mInt.as_ref() *self.union().mInt.as_ref()

View file

@ -321,8 +321,4 @@ unsafe fn addref_atom(atom: *mut structs::nsAtom) {
unsafe fn release_atom(atom: *mut structs::nsAtom) { unsafe fn release_atom(atom: *mut structs::nsAtom) {
let _ = Atom::from_addrefed(atom); let _ = Atom::from_addrefed(atom);
} }
impl_threadsafe_refcount!( impl_threadsafe_refcount!(structs::nsAtom, addref_atom, release_atom);
structs::nsAtom,
addref_atom,
release_atom
);

View file

@ -59,7 +59,7 @@ impl From<ComputedColor> for StyleComplexColor {
mFgRatio: ratios.fg, mFgRatio: ratios.fg,
mTag: Tag::eComplex, mTag: Tag::eComplex,
} }
} },
} }
} }
} }
@ -70,11 +70,11 @@ impl From<StyleComplexColor> for ComputedColor {
Tag::eNumeric => { Tag::eNumeric => {
debug_assert!(other.mBgRatio == 1. && other.mFgRatio == 0.); debug_assert!(other.mBgRatio == 1. && other.mFgRatio == 0.);
GenericColor::Numeric(convert_nscolor_to_rgba(other.mColor)) GenericColor::Numeric(convert_nscolor_to_rgba(other.mColor))
} },
Tag::eForeground => { Tag::eForeground => {
debug_assert!(other.mBgRatio == 0. && other.mFgRatio == 1.); debug_assert!(other.mBgRatio == 0. && other.mFgRatio == 1.);
GenericColor::Foreground GenericColor::Foreground
} },
Tag::eComplex => { Tag::eComplex => {
debug_assert!(other.mBgRatio != 1. || other.mFgRatio != 0.); debug_assert!(other.mBgRatio != 1. || other.mFgRatio != 0.);
debug_assert!(other.mBgRatio != 0. || other.mFgRatio != 1.); debug_assert!(other.mBgRatio != 0. || other.mFgRatio != 1.);
@ -85,7 +85,7 @@ impl From<StyleComplexColor> for ComputedColor {
fg: other.mFgRatio, fg: other.mFgRatio,
}, },
) )
} },
Tag::eAuto => unreachable!("Unsupport StyleComplexColor with tag eAuto"), Tag::eAuto => unreachable!("Unsupport StyleComplexColor with tag eAuto"),
} }
} }

View file

@ -46,7 +46,9 @@ pub trait ElementSnapshot: Sized {
/// Gets the attribute information of the snapshot as a string. /// Gets the attribute information of the snapshot as a string.
/// ///
/// Only for debugging purposes. /// Only for debugging purposes.
fn debug_list_attributes(&self) -> String { String::new() } fn debug_list_attributes(&self) -> String {
String::new()
}
/// The ID attribute per this snapshot. Should only be called if /// The ID attribute per this snapshot. Should only be called if
/// `has_attrs()` returns true. /// `has_attrs()` returns true.
@ -233,7 +235,8 @@ where
// :lang() needs to match using the closest ancestor xml:lang="" or // :lang() needs to match using the closest ancestor xml:lang="" or
// lang="" attribtue from snapshots. // lang="" attribtue from snapshots.
NonTSPseudoClass::Lang(ref lang_arg) => { NonTSPseudoClass::Lang(ref lang_arg) => {
return self.element return self
.element
.match_element_lang(Some(self.get_lang()), lang_arg); .match_element_lang(Some(self.get_lang()), lang_arg);
}, },
@ -242,12 +245,14 @@ where
let flag = pseudo_class.state_flag(); let flag = pseudo_class.state_flag();
if flag.is_empty() { if flag.is_empty() {
return self.element return self
.element
.match_non_ts_pseudo_class(pseudo_class, context, &mut |_, _| {}); .match_non_ts_pseudo_class(pseudo_class, context, &mut |_, _| {});
} }
match self.snapshot().and_then(|s| s.state()) { match self.snapshot().and_then(|s| s.state()) {
Some(snapshot_state) => snapshot_state.intersects(flag), Some(snapshot_state) => snapshot_state.intersects(flag),
None => self.element None => self
.element
.match_non_ts_pseudo_class(pseudo_class, context, &mut |_, _| {}), .match_non_ts_pseudo_class(pseudo_class, context, &mut |_, _| {}),
} }
} }

View file

@ -38,8 +38,10 @@ use smallvec::SmallVec;
#[derive(Clone, Debug, MallocSizeOf)] #[derive(Clone, Debug, MallocSizeOf)]
pub struct Dependency { pub struct Dependency {
/// The dependency selector. /// The dependency selector.
#[cfg_attr(feature = "gecko", #[cfg_attr(
ignore_malloc_size_of = "CssRules have primary refs, we measure there")] feature = "gecko",
ignore_malloc_size_of = "CssRules have primary refs, we measure there"
)]
#[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")] #[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")]
pub selector: Selector<SelectorImpl>, pub selector: Selector<SelectorImpl>,
@ -127,8 +129,10 @@ impl SelectorMapEntry for StateDependency {
pub struct DocumentStateDependency { pub struct DocumentStateDependency {
/// The selector that is affected. We don't need to track an offset, since /// The selector that is affected. We don't need to track an offset, since
/// when it changes it changes for the whole document anyway. /// when it changes it changes for the whole document anyway.
#[cfg_attr(feature = "gecko", #[cfg_attr(
ignore_malloc_size_of = "CssRules have primary refs, we measure there")] feature = "gecko",
ignore_malloc_size_of = "CssRules have primary refs, we measure there"
)]
#[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")] #[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")]
pub selector: Selector<SelectorImpl>, pub selector: Selector<SelectorImpl>,
/// The state this dependency is affected by. /// The state this dependency is affected by.
@ -185,7 +189,8 @@ impl InvalidationMap {
/// Returns the number of dependencies stored in the invalidation map. /// Returns the number of dependencies stored in the invalidation map.
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.state_affecting_selectors.len() + self.document_state_selectors.len() + self.state_affecting_selectors.len() +
self.document_state_selectors.len() +
self.other_attribute_affecting_selectors.len() + self.other_attribute_affecting_selectors.len() +
self.id_to_selector self.id_to_selector
.iter() .iter()

View file

@ -67,7 +67,8 @@ impl RestyleHint {
/// Returns whether we need to restyle this element. /// Returns whether we need to restyle this element.
pub fn has_non_animation_invalidations(&self) -> bool { pub fn has_non_animation_invalidations(&self) -> bool {
self.intersects( self.intersects(
RestyleHint::RESTYLE_SELF | RestyleHint::RECASCADE_SELF | RestyleHint::RESTYLE_SELF |
RestyleHint::RECASCADE_SELF |
(Self::replacements() & !Self::for_animations()), (Self::replacements() & !Self::for_animations()),
) )
} }
@ -119,7 +120,8 @@ impl RestyleHint {
/// The replacements for the animation cascade levels. /// The replacements for the animation cascade levels.
#[inline] #[inline]
pub fn for_animations() -> Self { pub fn for_animations() -> Self {
RestyleHint::RESTYLE_SMIL | RestyleHint::RESTYLE_CSS_ANIMATIONS | RestyleHint::RESTYLE_SMIL |
RestyleHint::RESTYLE_CSS_ANIMATIONS |
RestyleHint::RESTYLE_CSS_TRANSITIONS RestyleHint::RESTYLE_CSS_TRANSITIONS
} }

View file

@ -200,17 +200,12 @@ where
debug!(" > state: {:?}", state_changes); debug!(" > state: {:?}", state_changes);
} }
if snapshot.id_changed() { if snapshot.id_changed() {
debug!( debug!(" > id changed: +{:?} -{:?}", id_added, id_removed);
" > id changed: +{:?} -{:?}",
id_added,
id_removed
);
} }
if snapshot.class_changed() { if snapshot.class_changed() {
debug!( debug!(
" > class changed: +{:?} -{:?}", " > class changed: +{:?} -{:?}",
classes_added, classes_added, classes_removed
classes_removed
); );
} }
if snapshot.other_attr_changed() { if snapshot.other_attr_changed() {
@ -233,7 +228,6 @@ where
shadow_rule_datas.push((data, quirks_mode, host.map(|h| h.opaque()))) shadow_rule_datas.push((data, quirks_mode, host.map(|h| h.opaque())))
}); });
let invalidated_self = { let invalidated_self = {
let mut collector = Collector { let mut collector = Collector {
wrapper, wrapper,
@ -410,10 +404,7 @@ where
} }
/// Check whether a dependency should be taken into account. /// Check whether a dependency should be taken into account.
fn check_dependency( fn check_dependency(&mut self, dependency: &Dependency) -> bool {
&mut self,
dependency: &Dependency,
) -> bool {
let element = &self.element; let element = &self.element;
let wrapper = &self.wrapper; let wrapper = &self.wrapper;
let matches_now = matches_selector( let matches_now = matches_selector(

View file

@ -200,7 +200,6 @@ pub mod gecko;
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub mod servo; pub mod servo;
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
#[allow(unsafe_code, missing_docs)] #[allow(unsafe_code, missing_docs)]
pub mod gecko_properties { pub mod gecko_properties {

View file

@ -957,8 +957,10 @@ impl<T: Copy> LogicalMargin<T> {
impl<T: PartialEq + Zero> LogicalMargin<T> { impl<T: PartialEq + Zero> LogicalMargin<T> {
#[inline] #[inline]
pub fn is_zero(&self) -> bool { pub fn is_zero(&self) -> bool {
self.block_start == Zero::zero() && self.inline_end == Zero::zero() && self.block_start == Zero::zero() &&
self.block_end == Zero::zero() && self.inline_start == Zero::zero() self.inline_end == Zero::zero() &&
self.block_end == Zero::zero() &&
self.inline_start == Zero::zero()
} }
} }

View file

@ -68,9 +68,19 @@ macro_rules! try_match_ident_ignore_ascii_case {
macro_rules! define_keyword_type { macro_rules! define_keyword_type {
($name:ident, $css:expr) => { ($name:ident, $css:expr) => {
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, Animate,
ToComputedValue, ToCss)] Clone,
ComputeSquaredDistance,
Copy,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub struct $name; pub struct $name;
impl fmt::Debug for $name { impl fmt::Debug for $name {

View file

@ -356,10 +356,9 @@ trait PrivateMatchMethods: TElement {
tasks.insert(UpdateAnimationsTasks::CSS_ANIMATIONS); tasks.insert(UpdateAnimationsTasks::CSS_ANIMATIONS);
} }
let before_change_style = if self.might_need_transitions_update( let before_change_style = if self
old_values.as_ref().map(|s| &**s), .might_need_transitions_update(old_values.as_ref().map(|s| &**s), new_values)
new_values, {
) {
let after_change_style = if self.has_css_transitions() { let after_change_style = if self.has_css_transitions() {
self.after_change_style(context, new_values) self.after_change_style(context, new_values)
} else { } else {
@ -469,9 +468,11 @@ trait PrivateMatchMethods: TElement {
pseudo: Option<&PseudoElement>, pseudo: Option<&PseudoElement>,
) -> ChildCascadeRequirement { ) -> ChildCascadeRequirement {
debug!("accumulate_damage_for: {:?}", self); debug!("accumulate_damage_for: {:?}", self);
debug_assert!(!shared_context debug_assert!(
.traversal_flags !shared_context
.contains(TraversalFlags::Forgetful)); .traversal_flags
.contains(TraversalFlags::Forgetful)
);
let difference = self.compute_style_difference(old_values, new_values, pseudo); let difference = self.compute_style_difference(old_values, new_values, pseudo);

View file

@ -53,12 +53,12 @@ impl ToCss for MediaCondition {
MediaCondition::Not(ref c) => { MediaCondition::Not(ref c) => {
dest.write_str("not ")?; dest.write_str("not ")?;
c.to_css(dest) c.to_css(dest)
} },
MediaCondition::InParens(ref c) => { MediaCondition::InParens(ref c) => {
dest.write_char('(')?; dest.write_char('(')?;
c.to_css(dest)?; c.to_css(dest)?;
dest.write_char(')') dest.write_char(')')
} },
MediaCondition::Operation(ref list, op) => { MediaCondition::Operation(ref list, op) => {
let mut iter = list.iter(); let mut iter = list.iter();
iter.next().unwrap().to_css(dest)?; iter.next().unwrap().to_css(dest)?;
@ -69,7 +69,7 @@ impl ToCss for MediaCondition {
item.to_css(dest)?; item.to_css(dest)?;
} }
Ok(()) Ok(())
} },
} }
} }
} }
@ -104,14 +104,12 @@ impl MediaCondition {
let is_negation = match *input.next()? { let is_negation = match *input.next()? {
Token::ParenthesisBlock => false, Token::ParenthesisBlock => false,
Token::Ident(ref ident) if ident.eq_ignore_ascii_case("not") => true, Token::Ident(ref ident) if ident.eq_ignore_ascii_case("not") => true,
ref t => { ref t => return Err(location.new_unexpected_token_error(t.clone())),
return Err(location.new_unexpected_token_error(t.clone()))
}
}; };
if is_negation { if is_negation {
let inner_condition = Self::parse_in_parens(context, input)?; let inner_condition = Self::parse_in_parens(context, input)?;
return Ok(MediaCondition::Not(Box::new(inner_condition))) return Ok(MediaCondition::Not(Box::new(inner_condition)));
} }
// ParenthesisBlock. // ParenthesisBlock.
@ -162,7 +160,7 @@ impl MediaCondition {
input.parse_nested_block(|input| { input.parse_nested_block(|input| {
// Base case. // Base case.
if let Ok(inner) = input.try(|i| Self::parse(context, i)) { if let Ok(inner) = input.try(|i| Self::parse(context, i)) {
return Ok(MediaCondition::InParens(Box::new(inner))) return Ok(MediaCondition::InParens(Box::new(inner)));
} }
let expr = MediaFeatureExpression::parse_in_parenthesis_block(context, input)?; let expr = MediaFeatureExpression::parse_in_parenthesis_block(context, input)?;
Ok(MediaCondition::Feature(expr)) Ok(MediaCondition::Feature(expr))
@ -178,14 +176,10 @@ impl MediaCondition {
MediaCondition::Operation(ref conditions, op) => { MediaCondition::Operation(ref conditions, op) => {
let mut iter = conditions.iter(); let mut iter = conditions.iter();
match op { match op {
Operator::And => { Operator::And => iter.all(|c| c.matches(device, quirks_mode)),
iter.all(|c| c.matches(device, quirks_mode)) Operator::Or => iter.any(|c| c.matches(device, quirks_mode)),
}
Operator::Or => {
iter.any(|c| c.matches(device, quirks_mode))
}
} }
} },
} }
} }
} }

View file

@ -30,10 +30,9 @@ type MediaFeatureEvaluator<T> = fn(
pub type KeywordSerializer = fn(KeywordDiscriminant) -> String; pub type KeywordSerializer = fn(KeywordDiscriminant) -> String;
/// Parses a given identifier. /// Parses a given identifier.
pub type KeywordParser = for <'a, 'i, 't> fn( pub type KeywordParser =
context: &'a ParserContext, for<'a, 'i, 't> fn(context: &'a ParserContext, input: &'a mut Parser<'i, 't>)
input: &'a mut Parser<'i, 't>, -> Result<KeywordDiscriminant, ParseError<'i>>;
) -> Result<KeywordDiscriminant, ParseError<'i>>;
/// An evaluator for a given media feature. /// An evaluator for a given media feature.
/// ///
@ -70,50 +69,49 @@ pub enum Evaluator {
/// asserts if that's not true. As of today there's nothing like that (does that /// asserts if that's not true. As of today there's nothing like that (does that
/// even make sense?). /// even make sense?).
macro_rules! keyword_evaluator { macro_rules! keyword_evaluator {
($actual_evaluator:ident, $keyword_type:ty) => { ($actual_evaluator:ident, $keyword_type:ty) => {{
{ fn __parse<'i, 't>(
fn __parse<'i, 't>( context: &$crate::parser::ParserContext,
context: &$crate::parser::ParserContext, input: &mut $crate::cssparser::Parser<'i, 't>,
input: &mut $crate::cssparser::Parser<'i, 't>, ) -> Result<
) -> Result< $crate::media_queries::media_feature::KeywordDiscriminant,
$crate::media_queries::media_feature::KeywordDiscriminant, ::style_traits::ParseError<'i>,
::style_traits::ParseError<'i>, > {
> { let kw = <$keyword_type as $crate::parser::Parse>::parse(context, input)?;
let kw = <$keyword_type as $crate::parser::Parse>::parse(context, input)?; Ok(kw as $crate::media_queries::media_feature::KeywordDiscriminant)
Ok(kw as $crate::media_queries::media_feature::KeywordDiscriminant)
}
fn __serialize(kw: $crate::media_queries::media_feature::KeywordDiscriminant) -> String {
// This unwrap is ok because the only discriminants that get
// back to us is the ones that `parse` produces.
let value: $keyword_type =
::num_traits::cast::FromPrimitive::from_u8(kw).unwrap();
<$keyword_type as ::style_traits::ToCss>::to_css_string(&value)
}
fn __evaluate(
device: &$crate::media_queries::Device,
value: Option<$crate::media_queries::media_feature::KeywordDiscriminant>,
range_or_operator: Option<$crate::media_queries::media_feature_expression::RangeOrOperator>,
) -> bool {
debug_assert!(
range_or_operator.is_none(),
"Since when do keywords accept ranges?"
);
// This unwrap is ok because the only discriminants that get
// back to us is the ones that `parse` produces.
let value: Option<$keyword_type> =
value.map(|kw| ::num_traits::cast::FromPrimitive::from_u8(kw).unwrap());
$actual_evaluator(device, value)
}
$crate::media_queries::media_feature::Evaluator::Enumerated {
parser: __parse,
serializer: __serialize,
evaluator: __evaluate,
}
} }
}
fn __serialize(kw: $crate::media_queries::media_feature::KeywordDiscriminant) -> String {
// This unwrap is ok because the only discriminants that get
// back to us is the ones that `parse` produces.
let value: $keyword_type = ::num_traits::cast::FromPrimitive::from_u8(kw).unwrap();
<$keyword_type as ::style_traits::ToCss>::to_css_string(&value)
}
fn __evaluate(
device: &$crate::media_queries::Device,
value: Option<$crate::media_queries::media_feature::KeywordDiscriminant>,
range_or_operator: Option<
$crate::media_queries::media_feature_expression::RangeOrOperator,
>,
) -> bool {
debug_assert!(
range_or_operator.is_none(),
"Since when do keywords accept ranges?"
);
// This unwrap is ok because the only discriminants that get
// back to us is the ones that `parse` produces.
let value: Option<$keyword_type> =
value.map(|kw| ::num_traits::cast::FromPrimitive::from_u8(kw).unwrap());
$actual_evaluator(device, value)
}
$crate::media_queries::media_feature::Evaluator::Enumerated {
parser: __parse,
serializer: __serialize,
evaluator: __evaluate,
}
}};
} }
bitflags! { bitflags! {
@ -169,7 +167,7 @@ macro_rules! feature {
evaluator: $evaluator, evaluator: $evaluator,
requirements: $reqs, requirements: $reqs,
} }
} };
} }
impl fmt::Debug for MediaFeatureDescription { impl fmt::Debug for MediaFeatureDescription {

View file

@ -102,13 +102,9 @@ pub enum RangeOrOperator {
impl RangeOrOperator { impl RangeOrOperator {
/// Evaluate a given range given an optional query value and a value from /// Evaluate a given range given an optional query value and a value from
/// the browser. /// the browser.
pub fn evaluate<T>( pub fn evaluate<T>(range_or_op: Option<Self>, query_value: Option<T>, value: T) -> bool
range_or_op: Option<Self>,
query_value: Option<T>,
value: T,
) -> bool
where where
T: PartialOrd + Zero T: PartialOrd + Zero,
{ {
match query_value { match query_value {
Some(v) => Self::evaluate_with_query_value(range_or_op, v, value), Some(v) => Self::evaluate_with_query_value(range_or_op, v, value),
@ -118,11 +114,7 @@ impl RangeOrOperator {
/// Evaluate a given range given a non-optional query value and a value from /// Evaluate a given range given a non-optional query value and a value from
/// the browser. /// the browser.
pub fn evaluate_with_query_value<T>( pub fn evaluate_with_query_value<T>(range_or_op: Option<Self>, query_value: T, value: T) -> bool
range_or_op: Option<Self>,
query_value: T,
value: T,
) -> bool
where where
T: PartialOrd, T: PartialOrd,
{ {
@ -142,20 +134,14 @@ impl RangeOrOperator {
Range::Min => cmp == Ordering::Greater, Range::Min => cmp == Ordering::Greater,
Range::Max => cmp == Ordering::Less, Range::Max => cmp == Ordering::Less,
} }
} },
RangeOrOperator::Operator(op) => { RangeOrOperator::Operator(op) => match op {
match op { Operator::Equal => cmp == Ordering::Equal,
Operator::Equal => cmp == Ordering::Equal, Operator::GreaterThan => cmp == Ordering::Greater,
Operator::GreaterThan => cmp == Ordering::Greater, Operator::GreaterThanEqual => cmp == Ordering::Equal || cmp == Ordering::Greater,
Operator::GreaterThanEqual => { Operator::LessThan => cmp == Ordering::Less,
cmp == Ordering::Equal || cmp == Ordering::Greater Operator::LessThanEqual => cmp == Ordering::Equal || cmp == Ordering::Less,
} },
Operator::LessThan => cmp == Ordering::Less,
Operator::LessThanEqual => {
cmp == Ordering::Equal || cmp == Ordering::Less
}
}
}
} }
} }
} }
@ -172,8 +158,8 @@ pub struct MediaFeatureExpression {
impl PartialEq for MediaFeatureExpression { impl PartialEq for MediaFeatureExpression {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.feature as *const _ == other.feature as *const _ && self.feature as *const _ == other.feature as *const _ &&
self.value == other.value && self.value == other.value &&
self.range_or_operator == other.range_or_operator self.range_or_operator == other.range_or_operator
} }
} }
@ -184,7 +170,11 @@ impl ToCss for MediaFeatureExpression {
{ {
dest.write_str("(")?; dest.write_str("(")?;
if self.feature.requirements.contains(ParsingRequirements::WEBKIT_PREFIX) { if self
.feature
.requirements
.contains(ParsingRequirements::WEBKIT_PREFIX)
{
dest.write_str("-webkit-")?; dest.write_str("-webkit-")?;
} }
@ -215,9 +205,7 @@ impl ToCss for MediaFeatureExpression {
} }
/// Consumes an operation or a colon, or returns an error. /// Consumes an operation or a colon, or returns an error.
fn consume_operation_or_colon( fn consume_operation_or_colon(input: &mut Parser) -> Result<Option<Operator>, ()> {
input: &mut Parser,
) -> Result<Option<Operator>, ()> {
let first_delim = { let first_delim = {
let next_token = match input.next() { let next_token = match input.next() {
Ok(t) => t, Ok(t) => t,
@ -238,14 +226,14 @@ fn consume_operation_or_colon(
} else { } else {
Operator::GreaterThan Operator::GreaterThan
} }
} },
'<' => { '<' => {
if input.try(|i| i.expect_delim('=')).is_ok() { if input.try(|i| i.expect_delim('=')).is_ok() {
Operator::LessThanEqual Operator::LessThanEqual
} else { } else {
Operator::LessThan Operator::LessThan
} }
} },
_ => return Err(()), _ => return Err(()),
})) }))
} }
@ -256,7 +244,11 @@ impl MediaFeatureExpression {
value: Option<MediaExpressionValue>, value: Option<MediaExpressionValue>,
range_or_operator: Option<RangeOrOperator>, range_or_operator: Option<RangeOrOperator>,
) -> Self { ) -> Self {
Self { feature, value, range_or_operator } Self {
feature,
value,
range_or_operator,
}
} }
/// Parse a media expression of the form: /// Parse a media expression of the form:
@ -269,9 +261,7 @@ impl MediaFeatureExpression {
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
input.expect_parenthesis_block()?; input.expect_parenthesis_block()?;
input.parse_nested_block(|input| { input.parse_nested_block(|input| Self::parse_in_parenthesis_block(context, input))
Self::parse_in_parenthesis_block(context, input)
})
} }
/// Parse a media feature expression where we've already consumed the /// Parse a media feature expression where we've already consumed the
@ -294,9 +284,7 @@ impl MediaFeatureExpression {
let mut requirements = ParsingRequirements::empty(); let mut requirements = ParsingRequirements::empty();
if context.chrome_rules_enabled() || if context.chrome_rules_enabled() || context.stylesheet_origin == Origin::UserAgent {
context.stylesheet_origin == Origin::UserAgent
{
requirements.insert(ParsingRequirements::CHROME_AND_UA_ONLY); requirements.insert(ParsingRequirements::CHROME_AND_UA_ONLY);
} }
@ -313,7 +301,9 @@ impl MediaFeatureExpression {
if unsafe { if unsafe {
structs::StaticPrefs_sVarCache_layout_css_prefixes_device_pixel_ratio_webkit structs::StaticPrefs_sVarCache_layout_css_prefixes_device_pixel_ratio_webkit
} { } {
requirements.insert(ParsingRequirements::WEBKIT_DEVICE_PIXEL_RATIO_PREF_ENABLED); requirements.insert(
ParsingRequirements::WEBKIT_DEVICE_PIXEL_RATIO_PREF_ENABLED,
);
} }
} }
} }
@ -370,45 +360,41 @@ impl MediaFeatureExpression {
// Gecko doesn't allow ranged expressions without a // Gecko doesn't allow ranged expressions without a
// value, so just reject them here too. // value, so just reject them here too.
if range.is_some() { if range.is_some() {
return Err(input.new_custom_error( return Err(
StyleParseErrorKind::RangedExpressionWithNoValue input.new_custom_error(StyleParseErrorKind::RangedExpressionWithNoValue)
)); );
} }
return Ok(Self::new(feature, None, None)); return Ok(Self::new(feature, None, None));
} },
Ok(operator) => operator, Ok(operator) => operator,
}; };
let range_or_operator = match range { let range_or_operator = match range {
Some(range) => { Some(range) => {
if operator.is_some() { if operator.is_some() {
return Err(input.new_custom_error( return Err(
StyleParseErrorKind::MediaQueryUnexpectedOperator input.new_custom_error(StyleParseErrorKind::MediaQueryUnexpectedOperator)
)); );
} }
Some(RangeOrOperator::Range(range)) Some(RangeOrOperator::Range(range))
} },
None => { None => match operator {
match operator { Some(operator) => {
Some(operator) => { if !feature.allows_ranges() {
if !feature.allows_ranges() { return Err(input
return Err(input.new_custom_error( .new_custom_error(StyleParseErrorKind::MediaQueryUnexpectedOperator));
StyleParseErrorKind::MediaQueryUnexpectedOperator
));
}
Some(RangeOrOperator::Operator(operator))
} }
None => None, Some(RangeOrOperator::Operator(operator))
} },
} None => None,
},
}; };
let value = let value = MediaExpressionValue::parse(feature, context, input).map_err(|err| {
MediaExpressionValue::parse(feature, context, input).map_err(|err| { err.location
err.location .new_custom_error(StyleParseErrorKind::MediaQueryExpectedFeatureValue)
.new_custom_error(StyleParseErrorKind::MediaQueryExpectedFeatureValue) })?;
})?;
Ok(Self::new(feature, Some(value), range_or_operator)) Ok(Self::new(feature, Some(value), range_or_operator))
} }
@ -419,13 +405,11 @@ impl MediaFeatureExpression {
macro_rules! expect { macro_rules! expect {
($variant:ident) => { ($variant:ident) => {
value.map(|value| { value.map(|value| match *value {
match *value { MediaExpressionValue::$variant(ref v) => v,
MediaExpressionValue::$variant(ref v) => v, _ => unreachable!("Unexpected MediaExpressionValue"),
_ => unreachable!("Unexpected MediaExpressionValue"),
}
}) })
} };
} }
match self.feature.evaluator { match self.feature.evaluator {
@ -436,13 +420,11 @@ impl MediaFeatureExpression {
}) })
}); });
eval(device, computed, self.range_or_operator) eval(device, computed, self.range_or_operator)
} },
Evaluator::Integer(eval) => { Evaluator::Integer(eval) => {
eval(device, expect!(Integer).cloned(), self.range_or_operator) eval(device, expect!(Integer).cloned(), self.range_or_operator)
} },
Evaluator::Float(eval) => { Evaluator::Float(eval) => eval(device, expect!(Float).cloned(), self.range_or_operator),
eval(device, expect!(Float).cloned(), self.range_or_operator)
}
Evaluator::IntRatio(eval) => { Evaluator::IntRatio(eval) => {
eval(device, expect!(IntRatio).cloned(), self.range_or_operator) eval(device, expect!(IntRatio).cloned(), self.range_or_operator)
}, },
@ -453,20 +435,16 @@ impl MediaFeatureExpression {
}) })
}); });
eval(device, computed, self.range_or_operator) eval(device, computed, self.range_or_operator)
} },
Evaluator::Enumerated { evaluator, .. } => { Evaluator::Enumerated { evaluator, .. } => {
evaluator( evaluator(device, expect!(Enumerated).cloned(), self.range_or_operator)
device, },
expect!(Enumerated).cloned(), Evaluator::Ident(eval) => eval(device, expect!(Ident).cloned(), self.range_or_operator),
self.range_or_operator, Evaluator::BoolInteger(eval) => eval(
) device,
} expect!(BoolInteger).cloned(),
Evaluator::Ident(eval) => { self.range_or_operator,
eval(device, expect!(Ident).cloned(), self.range_or_operator) ),
}
Evaluator::BoolInteger(eval) => {
eval(device, expect!(BoolInteger).cloned(), self.range_or_operator)
}
} }
} }
} }
@ -502,11 +480,7 @@ pub enum MediaExpressionValue {
} }
impl MediaExpressionValue { impl MediaExpressionValue {
fn to_css<W>( fn to_css<W>(&self, dest: &mut CssWriter<W>, for_expr: &MediaFeatureExpression) -> fmt::Result
&self,
dest: &mut CssWriter<W>,
for_expr: &MediaFeatureExpression,
) -> fmt::Result
where where
W: fmt::Write, W: fmt::Write,
{ {
@ -515,18 +489,12 @@ impl MediaExpressionValue {
MediaExpressionValue::Integer(v) => v.to_css(dest), MediaExpressionValue::Integer(v) => v.to_css(dest),
MediaExpressionValue::Float(v) => v.to_css(dest), MediaExpressionValue::Float(v) => v.to_css(dest),
MediaExpressionValue::BoolInteger(v) => dest.write_str(if v { "1" } else { "0" }), MediaExpressionValue::BoolInteger(v) => dest.write_str(if v { "1" } else { "0" }),
MediaExpressionValue::IntRatio(ratio) => { MediaExpressionValue::IntRatio(ratio) => ratio.to_css(dest),
ratio.to_css(dest)
},
MediaExpressionValue::Resolution(ref r) => r.to_css(dest), MediaExpressionValue::Resolution(ref r) => r.to_css(dest),
MediaExpressionValue::Ident(ref ident) => serialize_atom_identifier(ident, dest), MediaExpressionValue::Ident(ref ident) => serialize_atom_identifier(ident, dest),
MediaExpressionValue::Enumerated(value) => { MediaExpressionValue::Enumerated(value) => match for_expr.feature.evaluator {
match for_expr.feature.evaluator { Evaluator::Enumerated { serializer, .. } => dest.write_str(&*serializer(value)),
Evaluator::Enumerated { serializer, .. } => { _ => unreachable!(),
dest.write_str(&*serializer(value))
}
_ => unreachable!(),
}
}, },
} }
} }
@ -540,11 +508,11 @@ impl MediaExpressionValue {
Evaluator::Length(..) => { Evaluator::Length(..) => {
let length = Length::parse_non_negative(context, input)?; let length = Length::parse_non_negative(context, input)?;
MediaExpressionValue::Length(length) MediaExpressionValue::Length(length)
} },
Evaluator::Integer(..) => { Evaluator::Integer(..) => {
let integer = Integer::parse_non_negative(context, input)?; let integer = Integer::parse_non_negative(context, input)?;
MediaExpressionValue::Integer(integer.value() as u32) MediaExpressionValue::Integer(integer.value() as u32)
} },
Evaluator::BoolInteger(..) => { Evaluator::BoolInteger(..) => {
let integer = Integer::parse_non_negative(context, input)?; let integer = Integer::parse_non_negative(context, input)?;
let value = integer.value(); let value = integer.value();
@ -552,29 +520,26 @@ impl MediaExpressionValue {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
} }
MediaExpressionValue::BoolInteger(value == 1) MediaExpressionValue::BoolInteger(value == 1)
} },
Evaluator::Float(..) => { Evaluator::Float(..) => {
let number = Number::parse(context, input)?; let number = Number::parse(context, input)?;
MediaExpressionValue::Float(number.get()) MediaExpressionValue::Float(number.get())
} },
Evaluator::IntRatio(..) => { Evaluator::IntRatio(..) => {
let a = Integer::parse_positive(context, input)?; let a = Integer::parse_positive(context, input)?;
input.expect_delim('/')?; input.expect_delim('/')?;
let b = Integer::parse_positive(context, input)?; let b = Integer::parse_positive(context, input)?;
MediaExpressionValue::IntRatio(AspectRatio( MediaExpressionValue::IntRatio(AspectRatio(a.value() as u32, b.value() as u32))
a.value() as u32, },
b.value() as u32
))
}
Evaluator::Resolution(..) => { Evaluator::Resolution(..) => {
MediaExpressionValue::Resolution(Resolution::parse(context, input)?) MediaExpressionValue::Resolution(Resolution::parse(context, input)?)
} },
Evaluator::Enumerated { parser, .. } => { Evaluator::Enumerated { parser, .. } => {
MediaExpressionValue::Enumerated(parser(context, input)?) MediaExpressionValue::Enumerated(parser(context, input)?)
} },
Evaluator::Ident(..) => { Evaluator::Ident(..) => {
MediaExpressionValue::Ident(Atom::from(input.expect_ident()?.as_ref())) MediaExpressionValue::Ident(Atom::from(input.expect_ident()?.as_ref()))
} },
}) })
} }
} }

View file

@ -30,10 +30,7 @@ impl MediaList {
/// "not all", see: /// "not all", see:
/// ///
/// <https://drafts.csswg.org/mediaqueries/#error-handling> /// <https://drafts.csswg.org/mediaqueries/#error-handling>
pub fn parse( pub fn parse(context: &ParserContext, input: &mut Parser) -> Self {
context: &ParserContext,
input: &mut Parser,
) -> Self {
if input.is_exhausted() { if input.is_exhausted() {
return Self::empty(); return Self::empty();
} }
@ -48,8 +45,10 @@ impl MediaList {
Err(err) => { Err(err) => {
media_queries.push(MediaQuery::never_matching()); media_queries.push(MediaQuery::never_matching());
let location = err.location; let location = err.location;
let error = let error = ContextualParseError::InvalidMediaRule(
ContextualParseError::InvalidMediaRule(input.slice_from(start_position), err); input.slice_from(start_position),
err,
);
context.log_css_error(location, error); context.log_css_error(location, error);
}, },
} }
@ -79,8 +78,10 @@ impl MediaList {
let media_match = mq.media_type.matches(device.media_type()); let media_match = mq.media_type.matches(device.media_type());
// Check if the media condition match. // Check if the media condition match.
let query_match = media_match && let query_match = media_match && mq
mq.condition.as_ref().map_or(true, |c| c.matches(device, quirks_mode)); .condition
.as_ref()
.map_or(true, |c| c.matches(device, quirks_mode));
// Apply the logical NOT qualifier to the result // Apply the logical NOT qualifier to the result
match mq.qualifier { match mq.qualifier {

View file

@ -15,7 +15,6 @@ use style_traits::{CssWriter, ParseError, ToCss};
use super::media_condition::MediaCondition; use super::media_condition::MediaCondition;
use values::CustomIdent; use values::CustomIdent;
/// <https://drafts.csswg.org/mediaqueries/#mq-prefix> /// <https://drafts.csswg.org/mediaqueries/#mq-prefix>
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToCss)] #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToCss)]
pub enum Qualifier { pub enum Qualifier {
@ -125,12 +124,13 @@ impl MediaQuery {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
let (qualifier, explicit_media_type) = input.try(|input| -> Result<_, ()> { let (qualifier, explicit_media_type) = input
let qualifier = input.try(Qualifier::parse).ok(); .try(|input| -> Result<_, ()> {
let ident = input.expect_ident().map_err(|_| ())?; let qualifier = input.try(Qualifier::parse).ok();
let media_type = MediaQueryType::parse(&ident)?; let ident = input.expect_ident().map_err(|_| ())?;
Ok((qualifier, Some(media_type))) let media_type = MediaQueryType::parse(&ident)?;
}).unwrap_or_default(); Ok((qualifier, Some(media_type)))
}).unwrap_or_default();
let condition = if explicit_media_type.is_none() { let condition = if explicit_media_type.is_none() {
Some(MediaCondition::parse(context, input)?) Some(MediaCondition::parse(context, input)?)
@ -141,7 +141,11 @@ impl MediaQuery {
}; };
let media_type = explicit_media_type.unwrap_or(MediaQueryType::All); let media_type = explicit_media_type.unwrap_or(MediaQueryType::All);
Ok(Self { qualifier, media_type, condition }) Ok(Self {
qualifier,
media_type,
condition,
})
} }
} }

View file

@ -137,11 +137,7 @@ impl<'a> ParserContext<'a> {
} }
/// Record a CSS parse error with this contexts error reporting. /// Record a CSS parse error with this contexts error reporting.
pub fn log_css_error( pub fn log_css_error(&self, location: SourceLocation, error: ContextualParseError) {
&self,
location: SourceLocation,
error: ContextualParseError,
) {
let error_reporter = match self.error_reporter { let error_reporter = match self.error_reporter {
Some(r) => r, Some(r) => r,
None => return, None => return,

View file

@ -488,7 +488,8 @@ impl RuleTree {
return path.clone(); return path.clone();
} }
let iter = path.self_and_ancestors() let iter = path
.self_and_ancestors()
.take_while(|node| node.cascade_level() >= CascadeLevel::SMILOverride); .take_while(|node| node.cascade_level() >= CascadeLevel::SMILOverride);
let mut last = path; let mut last = path;
let mut children = SmallVec::<[_; 10]>::new(); let mut children = SmallVec::<[_; 10]>::new();
@ -1452,7 +1453,8 @@ impl StrongRuleNode {
// transitions and animations are present for a given element and // transitions and animations are present for a given element and
// property, transitions are suppressed so that they don't actually // property, transitions are suppressed so that they don't actually
// override animations. // override animations.
let iter = self.self_and_ancestors() let iter = self
.self_and_ancestors()
.skip_while(|node| node.cascade_level() == CascadeLevel::Transitions) .skip_while(|node| node.cascade_level() == CascadeLevel::Transitions)
.take_while(|node| node.cascade_level() > CascadeLevel::Animations); .take_while(|node| node.cascade_level() > CascadeLevel::Animations);
let mut result = (LonghandIdSet::new(), false); let mut result = (LonghandIdSet::new(), false);

View file

@ -287,7 +287,9 @@ impl SelectorMap<Rule> {
context, context,
flags_setter, flags_setter,
) { ) {
matching_rules.push(rule.to_applicable_declaration_block(cascade_level, shadow_cascade_order)); matching_rules.push(
rule.to_applicable_declaration_block(cascade_level, shadow_cascade_order),
);
} }
} }
} }
@ -305,10 +307,12 @@ impl<T: SelectorMapEntry> SelectorMap<T> {
let vector = match find_bucket(entry.selector()) { let vector = match find_bucket(entry.selector()) {
Bucket::Root => &mut self.root, Bucket::Root => &mut self.root,
Bucket::ID(id) => self.id_hash Bucket::ID(id) => self
.id_hash
.try_entry(id.clone(), quirks_mode)? .try_entry(id.clone(), quirks_mode)?
.or_insert_with(SmallVec::new), .or_insert_with(SmallVec::new),
Bucket::Class(class) => self.class_hash Bucket::Class(class) => self
.class_hash
.try_entry(class.clone(), quirks_mode)? .try_entry(class.clone(), quirks_mode)?
.or_insert_with(SmallVec::new), .or_insert_with(SmallVec::new),
Bucket::LocalName { name, lower_name } => { Bucket::LocalName { name, lower_name } => {
@ -333,7 +337,8 @@ impl<T: SelectorMapEntry> SelectorMap<T> {
.try_entry(name.clone())? .try_entry(name.clone())?
.or_insert_with(SmallVec::new) .or_insert_with(SmallVec::new)
}, },
Bucket::Namespace(url) => self.namespace_hash Bucket::Namespace(url) => self
.namespace_hash
.try_entry(url.clone())? .try_entry(url.clone())?
.or_insert_with(SmallVec::new), .or_insert_with(SmallVec::new),
Bucket::Universal => &mut self.other, Bucket::Universal => &mut self.other,
@ -490,8 +495,9 @@ fn specific_bucket_for<'a>(component: &'a Component<SelectorImpl>) -> Bucket<'a>
name: &selector.name, name: &selector.name,
lower_name: &selector.lower_name, lower_name: &selector.lower_name,
}, },
Component::Namespace(_, ref url) | Component::Namespace(_, ref url) | Component::DefaultNamespace(ref url) => {
Component::DefaultNamespace(ref url) => Bucket::Namespace(url), Bucket::Namespace(url)
},
// ::slotted(..) isn't a normal pseudo-element, so we can insert it on // ::slotted(..) isn't a normal pseudo-element, so we can insert it on
// the rule hash normally without much problem. For example, in a // the rule hash normally without much problem. For example, in a
// selector like: // selector like:
@ -534,7 +540,7 @@ fn find_bucket<'a>(mut iter: SelectorIter<'a, SelectorImpl>) -> Bucket<'a> {
Bucket::Root => return new_bucket, Bucket::Root => return new_bucket,
Bucket::ID(..) => { Bucket::ID(..) => {
current_bucket = new_bucket; current_bucket = new_bucket;
} },
Bucket::Class(..) => { Bucket::Class(..) => {
if !matches!(current_bucket, Bucket::ID(..)) { if !matches!(current_bucket, Bucket::ID(..)) {
current_bucket = new_bucket; current_bucket = new_bucket;
@ -549,7 +555,7 @@ fn find_bucket<'a>(mut iter: SelectorIter<'a, SelectorImpl>) -> Bucket<'a> {
if matches!(current_bucket, Bucket::Universal) { if matches!(current_bucket, Bucket::Universal) {
current_bucket = new_bucket; current_bucket = new_bucket;
} }
} },
Bucket::Universal => {}, Bucket::Universal => {},
} }
} }

View file

@ -80,9 +80,12 @@ impl ServoRestyleDamage {
/// FIXME(bholley): Do we ever actually need this? Shouldn't /// FIXME(bholley): Do we ever actually need this? Shouldn't
/// RECONSTRUCT_FLOW imply everything else? /// RECONSTRUCT_FLOW imply everything else?
pub fn rebuild_and_reflow() -> ServoRestyleDamage { pub fn rebuild_and_reflow() -> ServoRestyleDamage {
ServoRestyleDamage::REPAINT | ServoRestyleDamage::REPOSITION | ServoRestyleDamage::REPAINT |
ServoRestyleDamage::STORE_OVERFLOW | ServoRestyleDamage::BUBBLE_ISIZES | ServoRestyleDamage::REPOSITION |
ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW | ServoRestyleDamage::STORE_OVERFLOW |
ServoRestyleDamage::BUBBLE_ISIZES |
ServoRestyleDamage::REFLOW_OUT_OF_FLOW |
ServoRestyleDamage::REFLOW |
ServoRestyleDamage::RECONSTRUCT_FLOW ServoRestyleDamage::RECONSTRUCT_FLOW
} }
@ -95,12 +98,14 @@ impl ServoRestyleDamage {
/// returns the damage that we should add to the *parent* of this flow. /// returns the damage that we should add to the *parent* of this flow.
pub fn damage_for_parent(self, child_is_absolutely_positioned: bool) -> ServoRestyleDamage { pub fn damage_for_parent(self, child_is_absolutely_positioned: bool) -> ServoRestyleDamage {
if child_is_absolutely_positioned { if child_is_absolutely_positioned {
self & (ServoRestyleDamage::REPAINT | ServoRestyleDamage::REPOSITION | self & (ServoRestyleDamage::REPAINT |
ServoRestyleDamage::REPOSITION |
ServoRestyleDamage::STORE_OVERFLOW | ServoRestyleDamage::STORE_OVERFLOW |
ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW_OUT_OF_FLOW |
ServoRestyleDamage::RESOLVE_GENERATED_CONTENT) ServoRestyleDamage::RESOLVE_GENERATED_CONTENT)
} else { } else {
self & (ServoRestyleDamage::REPAINT | ServoRestyleDamage::REPOSITION | self & (ServoRestyleDamage::REPAINT |
ServoRestyleDamage::REPOSITION |
ServoRestyleDamage::STORE_OVERFLOW | ServoRestyleDamage::STORE_OVERFLOW |
ServoRestyleDamage::REFLOW | ServoRestyleDamage::REFLOW |
ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW_OUT_OF_FLOW |
@ -136,7 +141,8 @@ impl ServoRestyleDamage {
}, },
_ => { _ => {
// TODO(pcwalton): Take floatedness into account. // TODO(pcwalton): Take floatedness into account.
self & (ServoRestyleDamage::REPAINT | ServoRestyleDamage::REPOSITION | self & (ServoRestyleDamage::REPAINT |
ServoRestyleDamage::REPOSITION |
ServoRestyleDamage::REFLOW) ServoRestyleDamage::REFLOW)
}, },
} }
@ -205,22 +211,21 @@ fn compute_damage(old: &ComputedValues, new: &ComputedValues) -> ServoRestyleDam
ServoRestyleDamage::REFLOW, ServoRestyleDamage::REFLOW,
ServoRestyleDamage::RECONSTRUCT_FLOW ServoRestyleDamage::RECONSTRUCT_FLOW
] ]
) || ) || (new.get_box().display == Display::Inline &&
(new.get_box().display == Display::Inline && restyle_damage_rebuild_and_reflow_inline!(
restyle_damage_rebuild_and_reflow_inline!( old,
old, new,
new, damage,
damage, [
[ ServoRestyleDamage::REPAINT,
ServoRestyleDamage::REPAINT, ServoRestyleDamage::REPOSITION,
ServoRestyleDamage::REPOSITION, ServoRestyleDamage::STORE_OVERFLOW,
ServoRestyleDamage::STORE_OVERFLOW, ServoRestyleDamage::BUBBLE_ISIZES,
ServoRestyleDamage::BUBBLE_ISIZES, ServoRestyleDamage::REFLOW_OUT_OF_FLOW,
ServoRestyleDamage::REFLOW_OUT_OF_FLOW, ServoRestyleDamage::REFLOW,
ServoRestyleDamage::REFLOW, ServoRestyleDamage::RECONSTRUCT_FLOW
ServoRestyleDamage::RECONSTRUCT_FLOW ]
] )) ||
)) ||
restyle_damage_reflow!( restyle_damage_reflow!(
old, old,
new, new,
@ -244,7 +249,8 @@ fn compute_damage(old: &ComputedValues, new: &ComputedValues) -> ServoRestyleDam
ServoRestyleDamage::STORE_OVERFLOW, ServoRestyleDamage::STORE_OVERFLOW,
ServoRestyleDamage::REFLOW_OUT_OF_FLOW ServoRestyleDamage::REFLOW_OUT_OF_FLOW
] ]
) || restyle_damage_repaint!(old, new, damage, [ServoRestyleDamage::REPAINT]); ) ||
restyle_damage_repaint!(old, new, damage, [ServoRestyleDamage::REPAINT]);
// Paint worklets may depend on custom properties, // Paint worklets may depend on custom properties,
// so if they have changed we should repaint. // so if they have changed we should repaint.

View file

@ -137,7 +137,9 @@ impl PseudoElement {
/// Whether this is an unknown ::-webkit- pseudo-element. /// Whether this is an unknown ::-webkit- pseudo-element.
#[inline] #[inline]
pub fn is_unknown_webkit_pseudo_element(&self) -> bool { false } pub fn is_unknown_webkit_pseudo_element(&self) -> bool {
false
}
/// Whether this pseudo-element is the ::before pseudo. /// Whether this pseudo-element is the ::before pseudo.
#[inline] #[inline]
@ -766,7 +768,8 @@ impl ServoElementSnapshot {
operation: &AttrSelectorOperation<&String>, operation: &AttrSelectorOperation<&String>,
) -> bool { ) -> bool {
match *ns { match *ns {
NamespaceConstraint::Specific(ref ns) => self.get_attr(ns, local_name) NamespaceConstraint::Specific(ref ns) => self
.get_attr(ns, local_name)
.map_or(false, |value| value.eval_selector(operation)), .map_or(false, |value| value.eval_selector(operation)),
NamespaceConstraint::Any => { NamespaceConstraint::Any => {
self.any_attr_ignore_ns(local_name, |value| value.eval_selector(operation)) self.any_attr_ignore_ns(local_name, |value| value.eval_selector(operation))

View file

@ -197,8 +197,7 @@ impl ValidationData {
let values = let values =
OpaqueComputedValues::from(parent.borrow_data().unwrap().styles.primary()); OpaqueComputedValues::from(parent.borrow_data().unwrap().styles.primary());
values values
}) }).clone()
.clone()
} }
/// Computes the revalidation results if needed, and returns it. /// Computes the revalidation results if needed, and returns it.

View file

@ -64,10 +64,21 @@ where
// FIXME(emilio): This should be an actual static. // FIXME(emilio): This should be an actual static.
lazy_static! { lazy_static! {
static ref SPECIAL_HTML_ELEMENTS: [Atom; 16] = [ static ref SPECIAL_HTML_ELEMENTS: [Atom; 16] = [
atom!("br"), atom!("wbr"), atom!("meter"), atom!("progress"), atom!("br"),
atom!("canvas"), atom!("embed"), atom!("object"), atom!("audio"), atom!("wbr"),
atom!("iframe"), atom!("img"), atom!("video"), atom!("frame"), atom!("meter"),
atom!("frameset"), atom!("input"), atom!("textarea"), atom!("progress"),
atom!("canvas"),
atom!("embed"),
atom!("object"),
atom!("audio"),
atom!("iframe"),
atom!("img"),
atom!("video"),
atom!("frame"),
atom!("frameset"),
atom!("input"),
atom!("textarea"),
atom!("select"), atom!("select"),
]; ];
} }
@ -79,15 +90,21 @@ where
// UA implements this either. // UA implements this either.
lazy_static! { lazy_static! {
static ref SPECIAL_SVG_ELEMENTS: [Atom; 6] = [ static ref SPECIAL_SVG_ELEMENTS: [Atom; 6] = [
atom!("svg"), atom!("a"), atom!("g"), atom!("use"), atom!("svg"),
atom!("tspan"), atom!("textPath"), atom!("a"),
atom!("g"),
atom!("use"),
atom!("tspan"),
atom!("textPath"),
]; ];
} }
// https://drafts.csswg.org/css-display/#unbox-html // https://drafts.csswg.org/css-display/#unbox-html
if element.is_html_element() { if element.is_html_element() {
let local_name = element.local_name(); let local_name = element.local_name();
return SPECIAL_HTML_ELEMENTS.iter().any(|name| &**name == local_name); return SPECIAL_HTML_ELEMENTS
.iter()
.any(|name| &**name == local_name);
} }
// https://drafts.csswg.org/css-display/#unbox-svg // https://drafts.csswg.org/css-display/#unbox-svg
@ -96,7 +113,9 @@ where
return true; return true;
} }
let local_name = element.local_name(); let local_name = element.local_name();
return !SPECIAL_SVG_ELEMENTS.iter().any(|name| &**name == local_name); return !SPECIAL_SVG_ELEMENTS
.iter()
.any(|name| &**name == local_name);
} }
// https://drafts.csswg.org/css-display/#unbox-mathml // https://drafts.csswg.org/css-display/#unbox-mathml
@ -201,11 +220,11 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
pub fn set_bits(&mut self) { pub fn set_bits(&mut self) {
let display = self.style.get_box().clone_display(); let display = self.style.get_box().clone_display();
if !display.is_contents() && if !display.is_contents() && !self
!self.style .style
.get_text() .get_text()
.clone_text_decoration_line() .clone_text_decoration_line()
.is_empty() .is_empty()
{ {
self.style self.style
.flags .flags
@ -280,10 +299,10 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
fn adjust_for_text_in_ruby(&mut self) { fn adjust_for_text_in_ruby(&mut self) {
let parent_display = self.style.get_parent_box().clone_display(); let parent_display = self.style.get_parent_box().clone_display();
if parent_display.is_ruby_type() || if parent_display.is_ruby_type() || self
self.style .style
.get_parent_flags() .get_parent_flags()
.contains(ComputedValueFlags::SHOULD_SUPPRESS_LINEBREAK) .contains(ComputedValueFlags::SHOULD_SUPPRESS_LINEBREAK)
{ {
self.style self.style
.flags .flags
@ -370,10 +389,12 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
/// The initial value of outline-width may be changed at computed value time. /// The initial value of outline-width may be changed at computed value time.
fn adjust_for_outline(&mut self) { fn adjust_for_outline(&mut self) {
if self.style if self
.style
.get_outline() .get_outline()
.clone_outline_style() .clone_outline_style()
.none_or_hidden() && self.style.get_outline().outline_has_nonzero_width() .none_or_hidden() &&
self.style.get_outline().outline_has_nonzero_width()
{ {
self.style.mutate_outline().set_outline_width(Au(0).into()); self.style.mutate_outline().set_outline_width(Au(0).into());
} }
@ -517,7 +538,9 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
let decorations_in_effect = TextDecorationsInEffect::from_style(&self.style); let decorations_in_effect = TextDecorationsInEffect::from_style(&self.style);
if self.style.get_inherited_text().text_decorations_in_effect != decorations_in_effect { if self.style.get_inherited_text().text_decorations_in_effect != decorations_in_effect {
self.style.mutate_inherited_text().text_decorations_in_effect = decorations_in_effect; self.style
.mutate_inherited_text()
.text_decorations_in_effect = decorations_in_effect;
} }
} }
@ -677,11 +700,8 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
/// When comparing to Gecko, this is similar to the work done by /// When comparing to Gecko, this is similar to the work done by
/// `ComputedStyle::ApplyStyleFixups`, plus some parts of /// `ComputedStyle::ApplyStyleFixups`, plus some parts of
/// `nsStyleSet::GetContext`. /// `nsStyleSet::GetContext`.
pub fn adjust<E>( pub fn adjust<E>(&mut self, layout_parent_style: &ComputedValues, element: Option<E>)
&mut self, where
layout_parent_style: &ComputedValues,
element: Option<E>,
) where
E: TElement, E: TElement,
{ {
if cfg!(debug_assertions) { if cfg!(debug_assertions) {

View file

@ -190,8 +190,7 @@ where
) -> PrimaryStyle { ) -> PrimaryStyle {
// Before doing the cascade, check the sharing cache and see if we can // Before doing the cascade, check the sharing cache and see if we can
// reuse the style via rule node identity. // reuse the style via rule node identity.
let may_reuse = let may_reuse = !self.element.is_in_native_anonymous_subtree() &&
!self.element.is_in_native_anonymous_subtree() &&
parent_style.is_some() && parent_style.is_some() &&
inputs.rules.is_some(); inputs.rules.is_some();
@ -485,7 +484,8 @@ where
let stylist = &self.context.shared.stylist; let stylist = &self.context.shared.stylist;
if !self.element if !self
.element
.may_generate_pseudo(pseudo_element, originating_element_style) .may_generate_pseudo(pseudo_element, originating_element_style)
{ {
return None; return None;

View file

@ -324,7 +324,8 @@ where
fn insert_before(&mut self, sheet: S, before_sheet: &S) { fn insert_before(&mut self, sheet: S, before_sheet: &S) {
debug_assert!(!self.contains(&sheet)); debug_assert!(!self.contains(&sheet));
let index = self.entries let index = self
.entries
.iter() .iter()
.position(|entry| entry.sheet == *before_sheet) .position(|entry| entry.sheet == *before_sheet)
.expect("`before_sheet` stylesheet not found"); .expect("`before_sheet` stylesheet not found");

View file

@ -109,7 +109,7 @@ pub enum DocumentMatchingFunction {
Regexp(String), Regexp(String),
/// Matching function for a media document. /// Matching function for a media document.
#[css(function)] #[css(function)]
MediaDocument(MediaDocumentKind) MediaDocument(MediaDocumentKind),
} }
macro_rules! parse_quoted_or_unquoted_string { macro_rules! parse_quoted_or_unquoted_string {
@ -120,8 +120,7 @@ macro_rules! parse_quoted_or_unquoted_string {
.parse_entirely(|input| { .parse_entirely(|input| {
let string = input.expect_string()?; let string = input.expect_string()?;
Ok($url_matching_function(string.as_ref().to_owned())) Ok($url_matching_function(string.as_ref().to_owned()))
}) }).or_else(|_: ParseError| {
.or_else(|_: ParseError| {
while let Ok(_) = input.next() {} while let Ok(_) = input.next() {}
Ok($url_matching_function(input.slice_from(start).to_string())) Ok($url_matching_function(input.slice_from(start).to_string()))
}) })
@ -136,7 +135,7 @@ impl DocumentMatchingFunction {
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
if let Ok(url) = input.try(|input| CssUrl::parse(context, input)) { if let Ok(url) = input.try(|input| CssUrl::parse(context, input)) {
return Ok(DocumentMatchingFunction::Url(url)) return Ok(DocumentMatchingFunction::Url(url));
} }
let location = input.current_source_location(); let location = input.current_source_location();
@ -181,7 +180,9 @@ impl DocumentMatchingFunction {
DocumentMatchingFunction::UrlPrefix(_) => GeckoDocumentMatchingFunction::URLPrefix, DocumentMatchingFunction::UrlPrefix(_) => GeckoDocumentMatchingFunction::URLPrefix,
DocumentMatchingFunction::Domain(_) => GeckoDocumentMatchingFunction::Domain, DocumentMatchingFunction::Domain(_) => GeckoDocumentMatchingFunction::Domain,
DocumentMatchingFunction::Regexp(_) => GeckoDocumentMatchingFunction::RegExp, DocumentMatchingFunction::Regexp(_) => GeckoDocumentMatchingFunction::RegExp,
DocumentMatchingFunction::MediaDocument(_) => GeckoDocumentMatchingFunction::MediaDocument, DocumentMatchingFunction::MediaDocument(_) => {
GeckoDocumentMatchingFunction::MediaDocument
},
}; };
let pattern = nsCStr::from(match *self { let pattern = nsCStr::from(match *self {
@ -189,14 +190,12 @@ impl DocumentMatchingFunction {
DocumentMatchingFunction::UrlPrefix(ref pat) | DocumentMatchingFunction::UrlPrefix(ref pat) |
DocumentMatchingFunction::Domain(ref pat) | DocumentMatchingFunction::Domain(ref pat) |
DocumentMatchingFunction::Regexp(ref pat) => pat, DocumentMatchingFunction::Regexp(ref pat) => pat,
DocumentMatchingFunction::MediaDocument(kind) => { DocumentMatchingFunction::MediaDocument(kind) => match kind {
match kind { MediaDocumentKind::All => "all",
MediaDocumentKind::All => "all", MediaDocumentKind::Image => "image",
MediaDocumentKind::Image => "image", MediaDocumentKind::Plugin => "plugin",
MediaDocumentKind::Plugin => "plugin", MediaDocumentKind::Video => "video",
MediaDocumentKind::Video => "video", },
}
}
}); });
unsafe { Gecko_DocumentRule_UseForPresentation(device.pres_context(), &*pattern, func) } unsafe { Gecko_DocumentRule_UseForPresentation(device.pres_context(), &*pattern, func) }
} }

View file

@ -70,7 +70,8 @@ impl Parse for SingleValue {
match *input.next()? { match *input.next()? {
Token::Number { Token::Number {
int_value: Some(v), .. int_value: Some(v), ..
} if v >= 0 => }
if v >= 0 =>
{ {
Ok(SingleValue(v as u32)) Ok(SingleValue(v as u32))
}, },
@ -102,7 +103,8 @@ impl Parse for PairValues {
let first = match *input.next()? { let first = match *input.next()? {
Token::Number { Token::Number {
int_value: Some(a), .. int_value: Some(a), ..
} if a >= 0 => }
if a >= 0 =>
{ {
a as u32 a as u32
}, },
@ -112,7 +114,8 @@ impl Parse for PairValues {
match input.next() { match input.next() {
Ok(&Token::Number { Ok(&Token::Number {
int_value: Some(b), .. int_value: Some(b), ..
}) if b >= 0 => })
if b >= 0 =>
{ {
Ok(PairValues(first, Some(b as u32))) Ok(PairValues(first, Some(b as u32)))
}, },
@ -154,7 +157,8 @@ impl Parse for VectorValues {
match input.next() { match input.next() {
Ok(&Token::Number { Ok(&Token::Number {
int_value: Some(a), .. int_value: Some(a), ..
}) if a >= 0 => })
if a >= 0 =>
{ {
vec.push(a as u32); vec.push(a as u32);
} }

View file

@ -82,16 +82,14 @@ impl DeepCloneWithLock for KeyframesRule {
) -> Self { ) -> Self {
KeyframesRule { KeyframesRule {
name: self.name.clone(), name: self.name.clone(),
keyframes: self.keyframes keyframes: self
.keyframes
.iter() .iter()
.map(|x| { .map(|x| {
Arc::new(lock.wrap(x.read_with(guard).deep_clone_with_lock( Arc::new(
lock, lock.wrap(x.read_with(guard).deep_clone_with_lock(lock, guard, params)),
guard, )
params, }).collect(),
)))
})
.collect(),
vendor_prefix: self.vendor_prefix.clone(), vendor_prefix: self.vendor_prefix.clone(),
source_location: self.source_location.clone(), source_location: self.source_location.clone(),
} }
@ -142,7 +140,8 @@ impl KeyframePercentage {
Token::Percentage { Token::Percentage {
unit_value: percentage, unit_value: percentage,
.. ..
} if percentage >= 0. && percentage <= 1. => }
if percentage >= 0. && percentage <= 1. =>
{ {
Ok(KeyframePercentage::new(percentage)) Ok(KeyframePercentage::new(percentage))
}, },
@ -261,8 +260,10 @@ pub enum KeyframesStepValue {
/// A step formed by a declaration block specified by the CSS. /// A step formed by a declaration block specified by the CSS.
Declarations { Declarations {
/// The declaration block per se. /// The declaration block per se.
#[cfg_attr(feature = "gecko", #[cfg_attr(
ignore_malloc_size_of = "XXX: Primary ref, measure if DMD says it's worthwhile")] feature = "gecko",
ignore_malloc_size_of = "XXX: Primary ref, measure if DMD says it's worthwhile"
)]
#[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")] #[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")]
block: Arc<Locked<PropertyDeclarationBlock>>, block: Arc<Locked<PropertyDeclarationBlock>>,
}, },
@ -326,8 +327,7 @@ impl KeyframesStep {
let (declaration, _) = guard let (declaration, _) = guard
.get(PropertyDeclarationId::Longhand( .get(PropertyDeclarationId::Longhand(
LonghandId::AnimationTimingFunction, LonghandId::AnimationTimingFunction,
)) )).unwrap();
.unwrap();
match *declaration { match *declaration {
PropertyDeclaration::AnimationTimingFunction(ref value) => { PropertyDeclaration::AnimationTimingFunction(ref value) => {
// Use the first value. // Use the first value.
@ -500,7 +500,7 @@ pub fn parse_keyframe_list(
declarations: &mut declarations, declarations: &mut declarations,
}, },
).filter_map(Result::ok) ).filter_map(Result::ok)
.collect() .collect()
} }
impl<'a, 'i> AtRuleParser<'i> for KeyframeListParser<'a> { impl<'a, 'i> AtRuleParser<'i> for KeyframeListParser<'a> {
@ -525,7 +525,7 @@ impl<'a, 'i> QualifiedRuleParser<'i> for KeyframeListParser<'a> {
let error = ContextualParseError::InvalidKeyframeRule( let error = ContextualParseError::InvalidKeyframeRule(
input.slice_from(start_position), input.slice_from(start_position),
e.clone(), e.clone(),
); );
self.context.log_css_error(location, error); self.context.log_css_error(location, error);
e e
}) })
@ -552,10 +552,7 @@ impl<'a, 'i> QualifiedRuleParser<'i> for KeyframeListParser<'a> {
while let Some(declaration) = iter.next() { while let Some(declaration) = iter.next() {
match declaration { match declaration {
Ok(()) => { Ok(()) => {
block.extend( block.extend(iter.parser.declarations.drain(), Importance::Normal);
iter.parser.declarations.drain(),
Importance::Normal,
);
}, },
Err((error, slice)) => { Err((error, slice)) => {
iter.parser.declarations.clear(); iter.parser.declarations.clear();
@ -599,9 +596,9 @@ impl<'a, 'b, 'i> DeclarationParser<'i> for KeyframeDeclarationParser<'a, 'b> {
) -> Result<(), ParseError<'i>> { ) -> Result<(), ParseError<'i>> {
let id = match PropertyId::parse(&name, self.context) { let id = match PropertyId::parse(&name, self.context) {
Ok(id) => id, Ok(id) => id,
Err(()) => return Err(input.new_custom_error( Err(()) => {
StyleParseErrorKind::UnknownProperty(name) return Err(input.new_custom_error(StyleParseErrorKind::UnknownProperty(name)))
)), },
}; };
// TODO(emilio): Shouldn't this use parse_entirely? // TODO(emilio): Shouldn't this use parse_entirely?

View file

@ -63,7 +63,7 @@ pub type UrlExtraData = ::servo_url::ServoUrl;
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
#[derive(Clone, PartialEq)] #[derive(Clone, PartialEq)]
pub struct UrlExtraData( pub struct UrlExtraData(
pub ::gecko_bindings::sugar::refptr::RefPtr<::gecko_bindings::structs::URLExtraData> pub ::gecko_bindings::sugar::refptr::RefPtr<::gecko_bindings::structs::URLExtraData>,
); );
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
@ -102,11 +102,14 @@ impl fmt::Debug for UrlExtraData {
} }
} }
formatter.debug_struct("URLExtraData") formatter
.debug_struct("URLExtraData")
.field("is_chrome", &self.is_chrome()) .field("is_chrome", &self.is_chrome())
.field("base", &DebugURI(self.0.mBaseURI.raw::<structs::nsIURI>())) .field("base", &DebugURI(self.0.mBaseURI.raw::<structs::nsIURI>()))
.field("referrer", &DebugURI(self.0.mReferrer.raw::<structs::nsIURI>())) .field(
.finish() "referrer",
&DebugURI(self.0.mReferrer.raw::<structs::nsIURI>()),
).finish()
} }
} }
@ -285,9 +288,7 @@ impl CssRule {
}; };
parse_one_rule(&mut input, &mut rule_parser) parse_one_rule(&mut input, &mut rule_parser)
.map_err(|_| { .map_err(|_| rule_parser.dom_error.unwrap_or(RulesMutateError::Syntax))
rule_parser.dom_error.unwrap_or(RulesMutateError::Syntax)
})
} }
} }
@ -305,25 +306,22 @@ impl DeepCloneWithLock for CssRule {
CssRule::Namespace(Arc::new(lock.wrap(rule.clone()))) CssRule::Namespace(Arc::new(lock.wrap(rule.clone())))
}, },
CssRule::Import(ref arc) => { CssRule::Import(ref arc) => {
let rule = arc.read_with(guard) let rule = arc
.read_with(guard)
.deep_clone_with_lock(lock, guard, params); .deep_clone_with_lock(lock, guard, params);
CssRule::Import(Arc::new(lock.wrap(rule))) CssRule::Import(Arc::new(lock.wrap(rule)))
}, },
CssRule::Style(ref arc) => { CssRule::Style(ref arc) => {
let rule = arc.read_with(guard); let rule = arc.read_with(guard);
CssRule::Style(Arc::new(lock.wrap(rule.deep_clone_with_lock( CssRule::Style(Arc::new(
lock, lock.wrap(rule.deep_clone_with_lock(lock, guard, params)),
guard, ))
params,
))))
}, },
CssRule::Media(ref arc) => { CssRule::Media(ref arc) => {
let rule = arc.read_with(guard); let rule = arc.read_with(guard);
CssRule::Media(Arc::new(lock.wrap(rule.deep_clone_with_lock( CssRule::Media(Arc::new(
lock, lock.wrap(rule.deep_clone_with_lock(lock, guard, params)),
guard, ))
params,
))))
}, },
CssRule::FontFace(ref arc) => { CssRule::FontFace(ref arc) => {
let rule = arc.read_with(guard); let rule = arc.read_with(guard);
@ -343,35 +341,27 @@ impl DeepCloneWithLock for CssRule {
}, },
CssRule::Keyframes(ref arc) => { CssRule::Keyframes(ref arc) => {
let rule = arc.read_with(guard); let rule = arc.read_with(guard);
CssRule::Keyframes(Arc::new(lock.wrap(rule.deep_clone_with_lock( CssRule::Keyframes(Arc::new(
lock, lock.wrap(rule.deep_clone_with_lock(lock, guard, params)),
guard, ))
params,
))))
}, },
CssRule::Supports(ref arc) => { CssRule::Supports(ref arc) => {
let rule = arc.read_with(guard); let rule = arc.read_with(guard);
CssRule::Supports(Arc::new(lock.wrap(rule.deep_clone_with_lock( CssRule::Supports(Arc::new(
lock, lock.wrap(rule.deep_clone_with_lock(lock, guard, params)),
guard, ))
params,
))))
}, },
CssRule::Page(ref arc) => { CssRule::Page(ref arc) => {
let rule = arc.read_with(guard); let rule = arc.read_with(guard);
CssRule::Page(Arc::new(lock.wrap(rule.deep_clone_with_lock( CssRule::Page(Arc::new(
lock, lock.wrap(rule.deep_clone_with_lock(lock, guard, params)),
guard, ))
params,
))))
}, },
CssRule::Document(ref arc) => { CssRule::Document(ref arc) => {
let rule = arc.read_with(guard); let rule = arc.read_with(guard);
CssRule::Document(Arc::new(lock.wrap(rule.deep_clone_with_lock( CssRule::Document(Arc::new(
lock, lock.wrap(rule.deep_clone_with_lock(lock, guard, params)),
guard, ))
params,
))))
}, },
} }
} }

View file

@ -156,7 +156,11 @@ impl CssRulesHelpers for RawOffsetArc<Locked<CssRules>> {
} else if index == 0 { } else if index == 0 {
State::Start State::Start
} else { } else {
rules.0.get(index - 1).map(CssRule::rule_state).unwrap_or(State::Body) rules
.0
.get(index - 1)
.map(CssRule::rule_state)
.unwrap_or(State::Body)
}; };
let insert_rule_context = InsertRuleContext { let insert_rule_context = InsertRuleContext {

View file

@ -110,8 +110,9 @@ impl<'b> TopLevelRuleParser<'b> {
// If there's anything that isn't a namespace rule (or import rule, but // If there's anything that isn't a namespace rule (or import rule, but
// we checked that already at the beginning), reject with a // we checked that already at the beginning), reject with a
// StateError. // StateError.
if new_state == State::Namespaces && if new_state == State::Namespaces && ctx.rule_list[ctx.index..]
ctx.rule_list[ctx.index..].iter().any(|r| !matches!(*r, CssRule::Namespace(..))) .iter()
.any(|r| !matches!(*r, CssRule::Namespace(..)))
{ {
self.dom_error = Some(RulesMutateError::InvalidState); self.dom_error = Some(RulesMutateError::InvalidState);
return false; return false;
@ -227,7 +228,7 @@ impl<'a, 'i> AtRuleParser<'i> for TopLevelRuleParser<'a> {
} }
if !self.check_state(State::Body) { if !self.check_state(State::Body) {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
} }
AtRuleParser::parse_prelude(&mut self.nested(), name, input) AtRuleParser::parse_prelude(&mut self.nested(), name, input)
@ -254,7 +255,8 @@ impl<'a, 'i> AtRuleParser<'i> for TopLevelRuleParser<'a> {
) -> CssRule { ) -> CssRule {
match prelude { match prelude {
AtRuleNonBlockPrelude::Import(url, media) => { AtRuleNonBlockPrelude::Import(url, media) => {
let loader = self.loader let loader = self
.loader
.expect("Expected a stylesheet loader for @import"); .expect("Expected a stylesheet loader for @import");
let import_rule = loader.request_stylesheet( let import_rule = loader.request_stylesheet(
@ -299,7 +301,7 @@ impl<'a, 'i> QualifiedRuleParser<'i> for TopLevelRuleParser<'a> {
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self::Prelude, ParseError<'i>> { ) -> Result<Self::Prelude, ParseError<'i>> {
if !self.check_state(State::Body) { if !self.check_state(State::Body) {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
} }
QualifiedRuleParser::parse_prelude(&mut self.nested(), input) QualifiedRuleParser::parse_prelude(&mut self.nested(), input)
@ -312,15 +314,12 @@ impl<'a, 'i> QualifiedRuleParser<'i> for TopLevelRuleParser<'a> {
location: SourceLocation, location: SourceLocation,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<CssRule, ParseError<'i>> { ) -> Result<CssRule, ParseError<'i>> {
QualifiedRuleParser::parse_block( QualifiedRuleParser::parse_block(&mut self.nested(), prelude, location, input).map(
&mut self.nested(), |result| {
prelude, self.state = State::Body;
location, result
input, },
).map(|result| { )
self.state = State::Body;
result
})
} }
} }
@ -338,11 +337,7 @@ impl<'a, 'b> NestedRuleParser<'a, 'b> {
input: &mut Parser, input: &mut Parser,
rule_type: CssRuleType, rule_type: CssRuleType,
) -> Arc<Locked<CssRules>> { ) -> Arc<Locked<CssRules>> {
let context = ParserContext::new_with_rule_type( let context = ParserContext::new_with_rule_type(self.context, rule_type, self.namespaces);
self.context,
rule_type,
self.namespaces,
);
let nested_parser = NestedRuleParser { let nested_parser = NestedRuleParser {
stylesheet_origin: self.stylesheet_origin, stylesheet_origin: self.stylesheet_origin,
@ -478,12 +473,7 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> {
); );
Ok(CssRule::FontFeatureValues(Arc::new(self.shared_lock.wrap( Ok(CssRule::FontFeatureValues(Arc::new(self.shared_lock.wrap(
FontFeatureValuesRule::parse( FontFeatureValuesRule::parse(&context, input, family_names, source_location),
&context,
input,
family_names,
source_location,
),
)))) ))))
}, },
AtRuleBlockPrelude::CounterStyle(name) => { AtRuleBlockPrelude::CounterStyle(name) => {
@ -493,16 +483,9 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> {
self.namespaces, self.namespaces,
); );
Ok(CssRule::CounterStyle(Arc::new( Ok(CssRule::CounterStyle(Arc::new(self.shared_lock.wrap(
self.shared_lock.wrap( parse_counter_style_body(name, &context, input, source_location)?.into(),
parse_counter_style_body( ))))
name,
&context,
input,
source_location,
)?.into(),
),
)))
}, },
AtRuleBlockPrelude::Media(media_queries) => { AtRuleBlockPrelude::Media(media_queries) => {
Ok(CssRule::Media(Arc::new(self.shared_lock.wrap(MediaRule { Ok(CssRule::Media(Arc::new(self.shared_lock.wrap(MediaRule {
@ -535,9 +518,9 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> {
self.namespaces, self.namespaces,
); );
Ok(CssRule::Viewport(Arc::new(self.shared_lock.wrap( Ok(CssRule::Viewport(Arc::new(
ViewportRule::parse(&context, input)?, self.shared_lock.wrap(ViewportRule::parse(&context, input)?),
)))) )))
}, },
AtRuleBlockPrelude::Keyframes(name, vendor_prefix) => { AtRuleBlockPrelude::Keyframes(name, vendor_prefix) => {
let context = ParserContext::new_with_rule_type( let context = ParserContext::new_with_rule_type(
@ -549,11 +532,7 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> {
Ok(CssRule::Keyframes(Arc::new(self.shared_lock.wrap( Ok(CssRule::Keyframes(Arc::new(self.shared_lock.wrap(
KeyframesRule { KeyframesRule {
name, name,
keyframes: parse_keyframe_list( keyframes: parse_keyframe_list(&context, input, self.shared_lock),
&context,
input,
self.shared_lock,
),
vendor_prefix, vendor_prefix,
source_location, source_location,
}, },
@ -566,8 +545,7 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> {
self.namespaces, self.namespaces,
); );
let declarations = let declarations = parse_property_declaration_list(&context, input);
parse_property_declaration_list(&context, input);
Ok(CssRule::Page(Arc::new(self.shared_lock.wrap(PageRule { Ok(CssRule::Page(Arc::new(self.shared_lock.wrap(PageRule {
block: Arc::new(self.shared_lock.wrap(declarations)), block: Arc::new(self.shared_lock.wrap(declarations)),
source_location, source_location,

View file

@ -100,10 +100,7 @@ where
) { ) {
continue; continue;
} }
import_rule import_rule.stylesheet.rules(self.guard).iter()
.stylesheet
.rules(self.guard)
.iter()
}, },
CssRule::Document(ref doc_rule) => { CssRule::Document(ref doc_rule) => {
let doc_rule = doc_rule.read_with(self.guard); let doc_rule = doc_rule.read_with(self.guard);

View file

@ -129,7 +129,8 @@ impl DeepCloneWithLock for StylesheetContents {
params: &DeepCloneParams, params: &DeepCloneParams,
) -> Self { ) -> Self {
// Make a deep clone of the rules, using the new lock. // Make a deep clone of the rules, using the new lock.
let rules = self.rules let rules = self
.rules
.read_with(guard) .read_with(guard)
.deep_clone_with_lock(lock, guard, params); .deep_clone_with_lock(lock, guard, params);
@ -179,7 +180,7 @@ macro_rules! rule_filter {
} }
/// A trait to represent a given stylesheet in a document. /// A trait to represent a given stylesheet in a document.
pub trait StylesheetInDocument : ::std::fmt::Debug { pub trait StylesheetInDocument: ::std::fmt::Debug {
/// Get the stylesheet origin. /// Get the stylesheet origin.
fn origin(&self, guard: &SharedRwLockReadGuard) -> Origin; fn origin(&self, guard: &SharedRwLockReadGuard) -> Origin;
@ -399,10 +400,7 @@ impl Stylesheet {
Err((error, slice)) => { Err((error, slice)) => {
let location = error.location; let location = error.location;
let error = ContextualParseError::InvalidRule(slice, error); let error = ContextualParseError::InvalidRule(slice, error);
iter.parser.context.log_css_error( iter.parser.context.log_css_error(location, error);
location,
error,
);
}, },
} }
} }
@ -478,7 +476,8 @@ impl Clone for Stylesheet {
// Make a deep clone of the media, using the new lock. // Make a deep clone of the media, using the new lock.
let media = self.media.read_with(&guard).clone(); let media = self.media.read_with(&guard).clone();
let media = Arc::new(lock.wrap(media)); let media = Arc::new(lock.wrap(media));
let contents = self.contents let contents = self
.contents
.deep_clone_with_lock(&lock, &guard, &DeepCloneParams); .deep_clone_with_lock(&lock, &guard, &DeepCloneParams);
Stylesheet { Stylesheet {

View file

@ -168,9 +168,7 @@ impl SupportsCondition {
i.expect_string() i.expect_string()
.map(|s| s.to_string()) .map(|s| s.to_string())
.map_err(CssParseError::<()>::from) .map_err(CssParseError::<()>::from)
}).and_then(|s| { }).and_then(|s| CString::new(s).map_err(|_| location.new_custom_error(())))
CString::new(s).map_err(|_| location.new_custom_error(()))
})
}) { }) {
return Ok(SupportsCondition::MozBoolPref(name)); return Ok(SupportsCondition::MozBoolPref(name));
} }
@ -315,24 +313,21 @@ impl Declaration {
let mut input = ParserInput::new(&self.0); let mut input = ParserInput::new(&self.0);
let mut input = Parser::new(&mut input); let mut input = Parser::new(&mut input);
input.parse_entirely(|input| -> Result<(), CssParseError<()>> { input
let prop = input.expect_ident_cloned().unwrap(); .parse_entirely(|input| -> Result<(), CssParseError<()>> {
input.expect_colon().unwrap(); let prop = input.expect_ident_cloned().unwrap();
input.expect_colon().unwrap();
let id = PropertyId::parse(&prop, context) let id =
.map_err(|_| input.new_custom_error(()))?; PropertyId::parse(&prop, context).map_err(|_| input.new_custom_error(()))?;
let mut declarations = SourcePropertyDeclaration::new(); let mut declarations = SourcePropertyDeclaration::new();
input.parse_until_before(Delimiter::Bang, |input| { input.parse_until_before(Delimiter::Bang, |input| {
PropertyDeclaration::parse_into( PropertyDeclaration::parse_into(&mut declarations, id, &context, input)
&mut declarations, .map_err(|_| input.new_custom_error(()))
id, })?;
&context, let _ = input.try(parse_important);
input, Ok(())
).map_err(|_| input.new_custom_error(())) }).is_ok()
})?;
let _ = input.try(parse_important);
Ok(())
}).is_ok()
} }
} }

View file

@ -375,8 +375,7 @@ impl ViewportRule {
Err((error, slice)) => { Err((error, slice)) => {
let location = error.location; let location = error.location;
let error = ContextualParseError::UnsupportedViewportDescriptorDeclaration( let error = ContextualParseError::UnsupportedViewportDescriptorDeclaration(
slice, slice, error,
error,
); );
context.log_css_error(location, error); context.log_css_error(location, error);
}, },
@ -760,9 +759,9 @@ impl MaybeNew for ViewportConstraints {
Some(initial_viewport.$dimension.scale_by(value.0)) Some(initial_viewport.$dimension.scale_by(value.0))
}, },
LengthOrPercentageOrAuto::Auto => None, LengthOrPercentageOrAuto::Auto => None,
LengthOrPercentageOrAuto::Calc(ref calc) => calc.to_computed_value( LengthOrPercentageOrAuto::Calc(ref calc) => calc
&context, .to_computed_value(&context)
).to_used_value(Some(initial_viewport.$dimension)), .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

@ -184,8 +184,10 @@ impl UserAgentCascadeData {
#[derive(Default)] #[derive(Default)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))] #[cfg_attr(feature = "servo", derive(MallocSizeOf))]
struct DocumentCascadeData { struct DocumentCascadeData {
#[cfg_attr(feature = "servo", #[cfg_attr(
ignore_malloc_size_of = "Arc, owned by UserAgentCascadeDataCache")] feature = "servo",
ignore_malloc_size_of = "Arc, owned by UserAgentCascadeDataCache"
)]
user_agent: Arc<UserAgentCascadeData>, user_agent: Arc<UserAgentCascadeData>,
user: CascadeData, user: CascadeData,
author: CascadeData, author: CascadeData,
@ -350,7 +352,10 @@ pub struct Stylist {
stylesheets: StylistStylesheetSet, stylesheets: StylistStylesheetSet,
/// If true, the quirks-mode stylesheet is applied. /// If true, the quirks-mode stylesheet is applied.
#[cfg_attr(feature = "servo", ignore_malloc_size_of = "defined in selectors")] #[cfg_attr(
feature = "servo",
ignore_malloc_size_of = "defined in selectors"
)]
quirks_mode: QuirksMode, quirks_mode: QuirksMode,
/// Selector maps for all of the style sheets in the stylist, after /// Selector maps for all of the style sheets in the stylist, after
@ -681,7 +686,8 @@ impl Stylist {
extra_declarations: Option<Vec<ApplicableDeclarationBlock>>, extra_declarations: Option<Vec<ApplicableDeclarationBlock>>,
) -> StrongRuleNode { ) -> StrongRuleNode {
let mut decl; let mut decl;
let declarations = match self.cascade_data let declarations = match self
.cascade_data
.user_agent .user_agent
.precomputed_pseudo_element_decls .precomputed_pseudo_element_decls
.get(pseudo) .get(pseudo)
@ -852,7 +858,7 @@ impl Stylist {
} else { } else {
None None
} }
} },
}; };
// Read the comment on `precomputed_values_for_pseudo` to see why it's // Read the comment on `precomputed_values_for_pseudo` to see why it's
@ -1131,7 +1137,8 @@ impl Stylist {
let matches_user_rules = rule_hash_target.matches_user_and_author_rules(); let matches_user_rules = rule_hash_target.matches_user_and_author_rules();
// Normal user-agent rules. // Normal user-agent rules.
if let Some(map) = self.cascade_data if let Some(map) = self
.cascade_data
.user_agent .user_agent
.cascade_data .cascade_data
.normal_rules(pseudo_element) .normal_rules(pseudo_element)
@ -1207,7 +1214,10 @@ impl Stylist {
// for !important it should be the other way around. So probably we need // for !important it should be the other way around. So probably we need
// to add some sort of AuthorScoped cascade level or something. // to add some sort of AuthorScoped cascade level or something.
if let Some(shadow) = rule_hash_target.shadow_root() { if let Some(shadow) = rule_hash_target.shadow_root() {
if let Some(map) = shadow.style_data().and_then(|data| data.host_rules(pseudo_element)) { if let Some(map) = shadow
.style_data()
.and_then(|data| data.host_rules(pseudo_element))
{
context.with_shadow_host(Some(rule_hash_target), |context| { context.with_shadow_host(Some(rule_hash_target), |context| {
map.get_all_matching_rules( map.get_all_matching_rules(
element, element,
@ -1234,7 +1244,10 @@ impl Stylist {
for slot in slots.iter().rev() { for slot in slots.iter().rev() {
let shadow = slot.containing_shadow().unwrap(); let shadow = slot.containing_shadow().unwrap();
if let Some(map) = shadow.style_data().and_then(|data| data.slotted_rules(pseudo_element)) { if let Some(map) = shadow
.style_data()
.and_then(|data| data.slotted_rules(pseudo_element))
{
context.with_shadow_host(Some(shadow.host()), |context| { context.with_shadow_host(Some(shadow.host()), |context| {
map.get_all_matching_rules( map.get_all_matching_rules(
element, element,
@ -1270,8 +1283,7 @@ impl Stylist {
} }
let host_is_svg_use_element = let host_is_svg_use_element =
host.is_svg_element() && host.is_svg_element() && host.local_name() == &*local_name!("use");
host.local_name() == &*local_name!("use");
if !host_is_svg_use_element { if !host_is_svg_use_element {
match_document_author_rules = false; match_document_author_rules = false;
@ -1406,11 +1418,7 @@ impl Stylist {
/// Returns the registered `@keyframes` animation for the specified name. /// Returns the registered `@keyframes` animation for the specified name.
#[inline] #[inline]
pub fn get_animation<'a, E>( pub fn get_animation<'a, E>(&'a self, name: &Atom, element: E) -> Option<&'a KeyframesAnimation>
&'a self,
name: &Atom,
element: E,
) -> Option<&'a KeyframesAnimation>
where where
E: TElement + 'a, E: TElement + 'a,
{ {
@ -1419,7 +1427,7 @@ impl Stylist {
if let Some(animation) = $data.animations.get(name) { if let Some(animation) = $data.animations.get(name) {
return Some(animation); return Some(animation);
} }
} };
} }
// NOTE(emilio): We implement basically what Blink does for this case, // NOTE(emilio): We implement basically what Blink does for this case,
@ -1547,10 +1555,12 @@ impl Stylist {
let block = declarations.read_with(guards.author); let block = declarations.read_with(guards.author);
let iter_declarations = || { let iter_declarations = || {
block.declaration_importance_iter().map(|(declaration, importance)| { block
debug_assert!(!importance.important()); .declaration_importance_iter()
(declaration, CascadeLevel::StyleAttributeNormal) .map(|(declaration, importance)| {
}) debug_assert!(!importance.important());
(declaration, CascadeLevel::StyleAttributeNormal)
})
}; };
let metrics = get_metrics_provider_for_product(); let metrics = get_metrics_provider_for_product();
@ -1567,7 +1577,9 @@ impl Stylist {
Some(parent_style), Some(parent_style),
Some(parent_style), Some(parent_style),
&metrics, &metrics,
CascadeMode::Unvisited { visited_rules: None }, CascadeMode::Unvisited {
visited_rules: None,
},
self.quirks_mode, self.quirks_mode,
/* rule_cache = */ None, /* rule_cache = */ None,
&mut Default::default(), &mut Default::default(),
@ -1703,8 +1715,10 @@ impl MallocSizeOf for ExtraStyleData {
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
struct RevalidationSelectorAndHashes { struct RevalidationSelectorAndHashes {
#[cfg_attr(feature = "gecko", #[cfg_attr(
ignore_malloc_size_of = "CssRules have primary refs, we measure there")] feature = "gecko",
ignore_malloc_size_of = "CssRules have primary refs, we measure there"
)]
selector: Selector<SelectorImpl>, selector: Selector<SelectorImpl>,
selector_offset: usize, selector_offset: usize,
hashes: AncestorHashes, hashes: AncestorHashes,
@ -1812,8 +1826,9 @@ impl<'a> SelectorVisitor for StylistSelectorVisitor<'a> {
// Also, note that this call happens before we visit any of the simple // Also, note that this call happens before we visit any of the simple
// selectors in the next ComplexSelector, so we can use this to skip // selectors in the next ComplexSelector, so we can use this to skip
// looking at them. // looking at them.
self.passed_rightmost_selector = self.passed_rightmost_selector || self.passed_rightmost_selector =
!matches!(combinator, None | Some(Combinator::PseudoElement)); self.passed_rightmost_selector ||
!matches!(combinator, None | Some(Combinator::PseudoElement));
true true
} }
@ -1830,8 +1845,9 @@ impl<'a> SelectorVisitor for StylistSelectorVisitor<'a> {
} }
fn visit_simple_selector(&mut self, s: &Component<SelectorImpl>) -> bool { fn visit_simple_selector(&mut self, s: &Component<SelectorImpl>) -> bool {
self.needs_revalidation = self.needs_revalidation || self.needs_revalidation =
component_needs_revalidation(s, self.passed_rightmost_selector); self.needs_revalidation ||
component_needs_revalidation(s, self.passed_rightmost_selector);
match *s { match *s {
Component::NonTSPseudoClass(ref p) => { Component::NonTSPseudoClass(ref p) => {
@ -1883,13 +1899,15 @@ impl ElementAndPseudoRules {
pseudo_element: Option<&PseudoElement>, pseudo_element: Option<&PseudoElement>,
quirks_mode: QuirksMode, quirks_mode: QuirksMode,
) -> Result<(), FailedAllocationError> { ) -> Result<(), FailedAllocationError> {
debug_assert!(pseudo_element.map_or(true, |pseudo| { debug_assert!(
!pseudo.is_precomputed() && !pseudo.is_unknown_webkit_pseudo_element() pseudo_element.map_or(true, |pseudo| !pseudo.is_precomputed() &&
})); !pseudo.is_unknown_webkit_pseudo_element())
);
let map = match pseudo_element { let map = match pseudo_element {
None => &mut self.element_map, None => &mut self.element_map,
Some(pseudo) => self.pseudos_map Some(pseudo) => self
.pseudos_map
.get_or_insert_with(pseudo, || Box::new(SelectorMap::new())), .get_or_insert_with(pseudo, || Box::new(SelectorMap::new())),
}; };
@ -2259,10 +2277,10 @@ impl CascadeData {
debug!("Found valid keyframes rule: {:?}", *keyframes_rule); debug!("Found valid keyframes rule: {:?}", *keyframes_rule);
// Don't let a prefixed keyframes animation override a non-prefixed one. // Don't let a prefixed keyframes animation override a non-prefixed one.
let needs_insertion = keyframes_rule.vendor_prefix.is_none() || let needs_insertion = keyframes_rule.vendor_prefix.is_none() || self
self.animations .animations
.get(keyframes_rule.name.as_atom()) .get(keyframes_rule.name.as_atom())
.map_or(true, |rule| rule.vendor_prefix.is_some()); .map_or(true, |rule| rule.vendor_prefix.is_some());
if needs_insertion { if needs_insertion {
let animation = KeyframesAnimation::from_keyframes( let animation = KeyframesAnimation::from_keyframes(
&keyframes_rule.keyframes, &keyframes_rule.keyframes,
@ -2352,7 +2370,8 @@ impl CascadeData {
let effective_now = import_rule let effective_now = import_rule
.stylesheet .stylesheet
.is_effective_for_device(&device, guard); .is_effective_for_device(&device, guard);
let effective_then = self.effective_media_query_results let effective_then = self
.effective_media_query_results
.was_effective(import_rule); .was_effective(import_rule);
if effective_now != effective_then { if effective_now != effective_then {
debug!( debug!(
@ -2378,9 +2397,7 @@ impl CascadeData {
if effective_now != effective_then { if effective_now != effective_then {
debug!( debug!(
" > @media rule {:?} changed {} -> {}", " > @media rule {:?} changed {} -> {}",
mq, mq, effective_then, effective_now
effective_then,
effective_now
); );
return false; return false;
} }
@ -2460,8 +2477,10 @@ pub struct Rule {
pub source_order: u32, pub source_order: u32,
/// The actual style rule. /// The actual style rule.
#[cfg_attr(feature = "gecko", #[cfg_attr(
ignore_malloc_size_of = "Secondary ref. Primary ref is in StyleRule under Stylesheet.")] feature = "gecko",
ignore_malloc_size_of = "Secondary ref. Primary ref is in StyleRule under Stylesheet."
)]
#[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")] #[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")]
pub style_rule: Arc<Locked<StyleRule>>, pub style_rule: Arc<Locked<StyleRule>>,
} }
@ -2486,7 +2505,13 @@ impl Rule {
shadow_cascade_order: ShadowCascadeOrder, shadow_cascade_order: ShadowCascadeOrder,
) -> ApplicableDeclarationBlock { ) -> ApplicableDeclarationBlock {
let source = StyleSource::from_rule(self.style_rule.clone()); let source = StyleSource::from_rule(self.style_rule.clone());
ApplicableDeclarationBlock::new(source, self.source_order, level, self.specificity(), shadow_cascade_order) ApplicableDeclarationBlock::new(
source,
self.source_order,
level,
self.specificity(),
shadow_cascade_order,
)
} }
/// Creates a new Rule. /// Creates a new Rule.

View file

@ -208,11 +208,11 @@ pub trait DomTraversal<E: TElement>: Sync {
// animation-only restyle hint or recascade. // animation-only restyle hint or recascade.
if traversal_flags.for_animation_only() { if traversal_flags.for_animation_only() {
return data.map_or(false, |d| d.has_styles()) && return data.map_or(false, |d| d.has_styles()) &&
(el.has_animation_only_dirty_descendants() || (el.has_animation_only_dirty_descendants() || data
data.as_ref() .as_ref()
.unwrap() .unwrap()
.hint .hint
.has_animation_hint_or_recascade()); .has_animation_hint_or_recascade());
} }
// Non-incremental layout visits every node. // Non-incremental layout visits every node.
@ -279,7 +279,8 @@ pub trait DomTraversal<E: TElement>: Sync {
// likely to load valid bindings, we avoid wasted work here, which may // likely to load valid bindings, we avoid wasted work here, which may
// be a very big perf hit when elements with bindings are nested // be a very big perf hit when elements with bindings are nested
// heavily. // heavily.
if cfg!(feature = "gecko") && is_initial_style && if cfg!(feature = "gecko") &&
is_initial_style &&
parent_data.styles.primary().has_moz_binding() parent_data.styles.primary().has_moz_binding()
{ {
debug!("Parent {:?} has XBL binding, deferring traversal", parent); debug!("Parent {:?} has XBL binding, deferring traversal", parent);
@ -384,8 +385,7 @@ where
).resolve_style( ).resolve_style(
style.as_ref().map(|s| &**s), style.as_ref().map(|s| &**s),
layout_parent_style.as_ref().map(|s| &**s), layout_parent_style.as_ref().map(|s| &**s),
) ).into()
.into()
} }
/// Calculates the style for a single node. /// Calculates the style for a single node.
@ -411,7 +411,8 @@ pub fn recalc_style_at<E, D, F>(
context.thread_local.statistics.elements_traversed += 1; context.thread_local.statistics.elements_traversed += 1;
debug_assert!( debug_assert!(
flags.intersects(TraversalFlags::AnimationOnly) || !element.has_snapshot() || flags.intersects(TraversalFlags::AnimationOnly) ||
!element.has_snapshot() ||
element.handled_snapshot(), element.handled_snapshot(),
"Should've handled snapshots here already" "Should've handled snapshots here already"
); );
@ -512,8 +513,9 @@ pub fn recalc_style_at<E, D, F>(
!child_cascade_requirement.can_skip_cascade() || !child_cascade_requirement.can_skip_cascade() ||
is_servo_nonincremental_layout(); is_servo_nonincremental_layout();
traverse_children = traverse_children && traverse_children =
!traversal.should_cull_subtree(context, element, &data, is_initial_style); traverse_children &&
!traversal.should_cull_subtree(context, element, &data, is_initial_style);
// Examine our children, and enqueue the appropriate ones for traversal. // Examine our children, and enqueue the appropriate ones for traversal.
if traverse_children { if traverse_children {
@ -535,7 +537,8 @@ pub fn recalc_style_at<E, D, F>(
} }
debug_assert!( debug_assert!(
flags.for_animation_only() || !flags.contains(TraversalFlags::ClearDirtyBits) || flags.for_animation_only() ||
!flags.contains(TraversalFlags::ClearDirtyBits) ||
!element.has_animation_only_dirty_descendants(), !element.has_animation_only_dirty_descendants(),
"Should have cleared animation bits already" "Should have cleared animation bits already"
); );

View file

@ -71,7 +71,8 @@ impl UseCounters {
/// Used for parallel parsing, where we parse off-main-thread. /// Used for parallel parsing, where we parse off-main-thread.
#[inline] #[inline]
pub fn merge(&self, other: &Self) { pub fn merge(&self, other: &Self) {
self.non_custom_properties.merge(&other.non_custom_properties) self.non_custom_properties
.merge(&other.non_custom_properties)
} }
} }

View file

@ -61,7 +61,8 @@ impl Animate for RGBA {
let red = let red =
(self.red * self.alpha).animate(&(other.red * other.alpha), procedure)? * 1. / alpha; (self.red * self.alpha).animate(&(other.red * other.alpha), procedure)? * 1. / alpha;
let green = (self.green * self.alpha).animate(&(other.green * other.alpha), procedure)? * let green = (self.green * self.alpha).animate(&(other.green * other.alpha), procedure)? *
1. / alpha; 1. /
alpha;
let blue = let blue =
(self.blue * self.alpha).animate(&(other.blue * other.alpha), procedure)? * 1. / alpha; (self.blue * self.alpha).animate(&(other.blue * other.alpha), procedure)? * 1. / alpha;
@ -223,7 +224,7 @@ impl Animate for Color {
let fg = fg1.animate(&fg2, procedure)?; let fg = fg1.animate(&fg2, procedure)?;
Self::with_ratios(bg_color, ComplexColorRatios { bg: 1., fg }) Self::with_ratios(bg_color, ComplexColorRatios { bg: 1., fg })
} },
}) })
} }
} }
@ -239,19 +240,19 @@ impl ComputeSquaredDistance for Color {
(Numeric(c1), Numeric(c2)) => c1.compute_squared_distance(&c2)?, (Numeric(c1), Numeric(c2)) => c1.compute_squared_distance(&c2)?,
(Foreground, Numeric(color)) | (Numeric(color), Foreground) => { (Foreground, Numeric(color)) | (Numeric(color), Foreground) => {
// `computed_squared_distance` is symmetric. // `computed_squared_distance` is symmetric.
color.compute_squared_distance(&RGBA::transparent())? color.compute_squared_distance(&RGBA::transparent())? +
+ SquaredDistance::from_sqrt(1.) SquaredDistance::from_sqrt(1.)
} },
(_, _) => { (_, _) => {
let self_color = self.effective_intermediate_rgba(); let self_color = self.effective_intermediate_rgba();
let other_color = other.effective_intermediate_rgba(); let other_color = other.effective_intermediate_rgba();
let self_ratios = self.effective_ratios(); let self_ratios = self.effective_ratios();
let other_ratios = other.effective_ratios(); let other_ratios = other.effective_ratios();
self_color.compute_squared_distance(&other_color)? self_color.compute_squared_distance(&other_color)? +
+ self_ratios.bg.compute_squared_distance(&other_ratios.bg)? self_ratios.bg.compute_squared_distance(&other_ratios.bg)? +
+ self_ratios.fg.compute_squared_distance(&other_ratios.fg)? self_ratios.fg.compute_squared_distance(&other_ratios.fg)?
} },
}) })
} }
} }

View file

@ -399,7 +399,10 @@ where
{ {
#[inline] #[inline]
fn to_animated_zero(&self) -> Result<Self, ()> { fn to_animated_zero(&self) -> Result<Self, ()> {
let v = self.iter().map(|v| v.to_animated_zero()).collect::<Result<Vec<_>, _>>()?; let v = self
.iter()
.map(|v| v.to_animated_zero())
.collect::<Result<Vec<_>, _>>()?;
Ok(v.into_boxed_slice()) Ok(v.into_boxed_slice())
} }
} }

View file

@ -15,7 +15,9 @@ use values::distance::{ComputeSquaredDistance, SquaredDistance};
/// A computed angle. /// A computed angle.
#[animate(fallback = "Self::animate_fallback")] #[animate(fallback = "Self::animate_fallback")]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd, ToAnimatedZero, ToCss)] #[derive(
Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd, ToAnimatedZero, ToCss,
)]
pub enum Angle { pub enum Angle {
/// An angle with degree unit. /// An angle with degree unit.
#[css(dimension)] #[css(dimension)]
@ -73,7 +75,9 @@ impl Angle {
/// <https://drafts.csswg.org/css-transitions/#animtype-number> /// <https://drafts.csswg.org/css-transitions/#animtype-number>
#[inline] #[inline]
fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
Ok(Angle::from_radians(self.radians().animate(&other.radians(), procedure)?)) Ok(Angle::from_radians(
self.radians().animate(&other.radians(), procedure)?,
))
} }
} }

View file

@ -34,13 +34,14 @@ pub type Perspective = GenericPerspective<NonNegativeLength>;
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, #[derive(
SpecifiedValueInfo, ToCss)] Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss,
)]
/// A computed value for the `float` property. /// A computed value for the `float` property.
pub enum Float { pub enum Float {
Left, Left,
Right, Right,
None None,
} }
impl ToComputedValue for SpecifiedFloat { impl ToComputedValue for SpecifiedFloat {
@ -52,7 +53,9 @@ impl ToComputedValue for SpecifiedFloat {
// https://drafts.csswg.org/css-logical-props/#float-clear // https://drafts.csswg.org/css-logical-props/#float-clear
match *self { match *self {
SpecifiedFloat::InlineStart => { SpecifiedFloat::InlineStart => {
context.rule_cache_conditions.borrow_mut() context
.rule_cache_conditions
.borrow_mut()
.set_writing_mode_dependency(context.builder.writing_mode); .set_writing_mode_dependency(context.builder.writing_mode);
if ltr { if ltr {
Float::Left Float::Left
@ -61,7 +64,9 @@ impl ToComputedValue for SpecifiedFloat {
} }
}, },
SpecifiedFloat::InlineEnd => { SpecifiedFloat::InlineEnd => {
context.rule_cache_conditions.borrow_mut() context
.rule_cache_conditions
.borrow_mut()
.set_writing_mode_dependency(context.builder.writing_mode); .set_writing_mode_dependency(context.builder.writing_mode);
if ltr { if ltr {
Float::Right Float::Right
@ -71,7 +76,7 @@ impl ToComputedValue for SpecifiedFloat {
}, },
SpecifiedFloat::Left => Float::Left, SpecifiedFloat::Left => Float::Left,
SpecifiedFloat::Right => Float::Right, SpecifiedFloat::Right => Float::Right,
SpecifiedFloat::None => Float::None SpecifiedFloat::None => Float::None,
} }
} }
@ -80,21 +85,22 @@ impl ToComputedValue for SpecifiedFloat {
match *computed { match *computed {
Float::Left => SpecifiedFloat::Left, Float::Left => SpecifiedFloat::Left,
Float::Right => SpecifiedFloat::Right, Float::Right => SpecifiedFloat::Right,
Float::None => SpecifiedFloat::None Float::None => SpecifiedFloat::None,
} }
} }
} }
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, #[derive(
SpecifiedValueInfo, ToCss)] Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss,
)]
/// A computed value for the `clear` property. /// A computed value for the `clear` property.
pub enum Clear { pub enum Clear {
None, None,
Left, Left,
Right, Right,
Both Both,
} }
impl ToComputedValue for SpecifiedClear { impl ToComputedValue for SpecifiedClear {
@ -106,7 +112,9 @@ impl ToComputedValue for SpecifiedClear {
// https://drafts.csswg.org/css-logical-props/#float-clear // https://drafts.csswg.org/css-logical-props/#float-clear
match *self { match *self {
SpecifiedClear::InlineStart => { SpecifiedClear::InlineStart => {
context.rule_cache_conditions.borrow_mut() context
.rule_cache_conditions
.borrow_mut()
.set_writing_mode_dependency(context.builder.writing_mode); .set_writing_mode_dependency(context.builder.writing_mode);
if ltr { if ltr {
Clear::Left Clear::Left
@ -115,7 +123,9 @@ impl ToComputedValue for SpecifiedClear {
} }
}, },
SpecifiedClear::InlineEnd => { SpecifiedClear::InlineEnd => {
context.rule_cache_conditions.borrow_mut() context
.rule_cache_conditions
.borrow_mut()
.set_writing_mode_dependency(context.builder.writing_mode); .set_writing_mode_dependency(context.builder.writing_mode);
if ltr { if ltr {
Clear::Right Clear::Right
@ -126,7 +136,7 @@ impl ToComputedValue for SpecifiedClear {
SpecifiedClear::None => Clear::None, SpecifiedClear::None => Clear::None,
SpecifiedClear::Left => Clear::Left, SpecifiedClear::Left => Clear::Left,
SpecifiedClear::Right => Clear::Right, SpecifiedClear::Right => Clear::Right,
SpecifiedClear::Both => Clear::Both SpecifiedClear::Both => Clear::Both,
} }
} }
@ -160,23 +170,27 @@ impl ToComputedValue for specified::Resize {
let is_vertical = context.style().writing_mode.is_vertical(); let is_vertical = context.style().writing_mode.is_vertical();
match self { match self {
specified::Resize::Inline => { specified::Resize::Inline => {
context.rule_cache_conditions.borrow_mut() context
.rule_cache_conditions
.borrow_mut()
.set_writing_mode_dependency(context.builder.writing_mode); .set_writing_mode_dependency(context.builder.writing_mode);
if is_vertical { if is_vertical {
Resize::Vertical Resize::Vertical
} else { } else {
Resize::Horizontal Resize::Horizontal
} }
} },
specified::Resize::Block => { specified::Resize::Block => {
context.rule_cache_conditions.borrow_mut() context
.rule_cache_conditions
.borrow_mut()
.set_writing_mode_dependency(context.builder.writing_mode); .set_writing_mode_dependency(context.builder.writing_mode);
if is_vertical { if is_vertical {
Resize::Horizontal Resize::Horizontal
} else { } else {
Resize::Vertical Resize::Vertical
} }
} },
specified::Resize::None => Resize::None, specified::Resize::None => Resize::None,
specified::Resize::Both => Resize::Both, specified::Resize::Both => Resize::Both,
specified::Resize::Horizontal => Resize::Horizontal, specified::Resize::Horizontal => Resize::Horizontal,

View file

@ -20,4 +20,3 @@ pub type Content = generics::Content<ComputedImageUrl>;
/// A computed content item. /// A computed content item.
pub type ContentItem = generics::ContentItem<ComputedImageUrl>; pub type ContentItem = generics::ContentItem<ComputedImageUrl>;

View file

@ -20,11 +20,13 @@ pub type BoxShadow = GenericBoxShadow<Color, Length, NonNegativeLength, Length>;
/// A computed value for a single `filter`. /// A computed value for a single `filter`.
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
pub type Filter = GenericFilter<Angle, NonNegativeNumber, NonNegativeLength, SimpleShadow, ComputedUrl>; pub type Filter =
GenericFilter<Angle, NonNegativeNumber, NonNegativeLength, SimpleShadow, ComputedUrl>;
/// A computed value for a single `filter`. /// A computed value for a single `filter`.
#[cfg(not(feature = "gecko"))] #[cfg(not(feature = "gecko"))]
pub type Filter = GenericFilter<Angle, NonNegativeNumber, NonNegativeLength, Impossible, Impossible>; pub type Filter =
GenericFilter<Angle, NonNegativeNumber, NonNegativeLength, Impossible, Impossible>;
/// A computed value for the `drop-shadow()` filter. /// A computed value for the `drop-shadow()` filter.
pub type SimpleShadow = GenericSimpleShadow<Color, Length, NonNegativeLength>; pub type SimpleShadow = GenericSimpleShadow<Color, Length, NonNegativeLength>;

View file

@ -35,8 +35,7 @@ pub use values::specified::font::{FontSynthesis, MozScriptSizeMultiplier, XLang,
/// https://drafts.csswg.org/css-fonts-4/#propdef-font-weight /// https://drafts.csswg.org/css-fonts-4/#propdef-font-weight
/// ///
/// This is effectively just a `Number`. /// This is effectively just a `Number`.
#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, #[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToCss)]
ToCss)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct FontWeight(pub Number); pub struct FontWeight(pub Number);
@ -60,8 +59,17 @@ impl ToAnimatedValue for FontWeight {
} }
} }
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, #[derive(
ToAnimatedZero, ToCss)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
ToAnimatedZero,
ToCss,
)]
/// The computed value of font-size /// The computed value of font-size
pub struct FontSize { pub struct FontSize {
/// The size. /// The size.
@ -217,9 +225,9 @@ impl FontFamily {
#[inline] #[inline]
/// Get default font family as `serif` which is a generic font-family /// Get default font family as `serif` which is a generic font-family
pub fn serif() -> Self { pub fn serif() -> Self {
FontFamily(FontFamilyList::new(Box::new([ FontFamily(FontFamilyList::new(Box::new([SingleFontFamily::Generic(
SingleFontFamily::Generic(atom!("serif")), atom!("serif"),
]))) )])))
} }
} }
@ -473,9 +481,7 @@ impl SingleFontFamily {
FontFamilyType::eFamily_monospace => SingleFontFamily::Generic(atom!("monospace")), FontFamilyType::eFamily_monospace => SingleFontFamily::Generic(atom!("monospace")),
FontFamilyType::eFamily_cursive => SingleFontFamily::Generic(atom!("cursive")), FontFamilyType::eFamily_cursive => SingleFontFamily::Generic(atom!("cursive")),
FontFamilyType::eFamily_fantasy => SingleFontFamily::Generic(atom!("fantasy")), FontFamilyType::eFamily_fantasy => SingleFontFamily::Generic(atom!("fantasy")),
FontFamilyType::eFamily_moz_fixed => { FontFamilyType::eFamily_moz_fixed => SingleFontFamily::Generic(atom!("-moz-fixed")),
SingleFontFamily::Generic(atom!("-moz-fixed"))
},
FontFamilyType::eFamily_named => { FontFamilyType::eFamily_named => {
let name = Atom::from(&*family.mName); let name = Atom::from(&*family.mName);
SingleFontFamily::FamilyName(FamilyName { SingleFontFamily::FamilyName(FamilyName {
@ -851,9 +857,10 @@ impl ToAnimatedValue for FontStyleAngle {
#[inline] #[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self { fn from_animated_value(animated: Self::AnimatedValue) -> Self {
FontStyleAngle(Angle::Deg( FontStyleAngle(Angle::Deg(
animated.degrees() animated
.degrees()
.min(specified::FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES) .min(specified::FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES)
.max(specified::FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES) .max(specified::FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES),
)) ))
} }
} }
@ -882,10 +889,11 @@ impl FontStyle {
/// https://drafts.csswg.org/css-fonts-4/#valdef-font-style-oblique-angle /// https://drafts.csswg.org/css-fonts-4/#valdef-font-style-oblique-angle
#[inline] #[inline]
pub fn default_angle() -> FontStyleAngle { pub fn default_angle() -> FontStyleAngle {
FontStyleAngle(Angle::Deg(specified::DEFAULT_FONT_STYLE_OBLIQUE_ANGLE_DEGREES)) FontStyleAngle(Angle::Deg(
specified::DEFAULT_FONT_STYLE_OBLIQUE_ANGLE_DEGREES,
))
} }
/// Get the font style from Gecko's nsFont struct. /// Get the font style from Gecko's nsFont struct.
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
pub fn from_gecko(style: structs::FontSlantStyle) -> Self { pub fn from_gecko(style: structs::FontSlantStyle) -> Self {
@ -923,7 +931,7 @@ impl ToCss for FontStyle {
angle.to_css(dest)?; angle.to_css(dest)?;
} }
Ok(()) Ok(())
} },
} }
} }
} }

View file

@ -80,7 +80,8 @@ impl ComputeSquaredDistance for CalcLengthOrPercentage {
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
// with a distance between percentages. // with a distance between percentages.
Ok(self.unclamped_length() Ok(self
.unclamped_length()
.compute_squared_distance(&other.unclamped_length())? + .compute_squared_distance(&other.unclamped_length())? +
self.percentage() self.percentage()
.compute_squared_distance(&other.percentage())?) .compute_squared_distance(&other.percentage())?)
@ -285,9 +286,15 @@ impl specified::CalcLengthOrPercentage {
/// Compute the value into pixel length as CSSFloat without context, /// Compute the value into pixel length as CSSFloat without context,
/// so it returns Err(()) if there is any non-absolute unit. /// so it returns Err(()) if there is any non-absolute unit.
pub fn to_computed_pixel_length_without_context(&self) -> Result<CSSFloat, ()> { pub fn to_computed_pixel_length_without_context(&self) -> Result<CSSFloat, ()> {
if self.vw.is_some() || self.vh.is_some() || self.vmin.is_some() || self.vmax.is_some() || if self.vw.is_some() ||
self.em.is_some() || self.ex.is_some() || self.ch.is_some() || self.vh.is_some() ||
self.rem.is_some() || self.percentage.is_some() self.vmin.is_some() ||
self.vmax.is_some() ||
self.em.is_some() ||
self.ex.is_some() ||
self.ch.is_some() ||
self.rem.is_some() ||
self.percentage.is_some()
{ {
return Err(()); return Err(());
} }
@ -324,8 +331,17 @@ impl ToComputedValue for specified::CalcLengthOrPercentage {
#[allow(missing_docs)] #[allow(missing_docs)]
#[animate(fallback = "Self::animate_fallback")] #[animate(fallback = "Self::animate_fallback")]
#[css(derive_debug)] #[css(derive_debug)]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, MallocSizeOf, PartialEq, #[derive(
ToAnimatedValue, ToAnimatedZero, ToCss)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
MallocSizeOf,
PartialEq,
ToAnimatedValue,
ToAnimatedZero,
ToCss,
)]
#[distance(fallback = "Self::compute_squared_distance_fallback")] #[distance(fallback = "Self::compute_squared_distance_fallback")]
pub enum LengthOrPercentage { pub enum LengthOrPercentage {
Length(Length), Length(Length),
@ -483,11 +499,9 @@ impl LengthOrPercentageOrAuto {
fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
let this = <Option<CalcLengthOrPercentage>>::from(*self); let this = <Option<CalcLengthOrPercentage>>::from(*self);
let other = <Option<CalcLengthOrPercentage>>::from(*other); let other = <Option<CalcLengthOrPercentage>>::from(*other);
Ok(LengthOrPercentageOrAuto::Calc(this.animate( Ok(LengthOrPercentageOrAuto::Calc(
&other, this.animate(&other, procedure)?.ok_or(())?,
procedure, ))
)?
.ok_or(())?))
} }
#[inline] #[inline]
@ -602,11 +616,9 @@ impl LengthOrPercentageOrNone {
fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
let this = <Option<CalcLengthOrPercentage>>::from(*self); let this = <Option<CalcLengthOrPercentage>>::from(*self);
let other = <Option<CalcLengthOrPercentage>>::from(*other); let other = <Option<CalcLengthOrPercentage>>::from(*other);
Ok(LengthOrPercentageOrNone::Calc(this.animate( Ok(LengthOrPercentageOrNone::Calc(
&other, this.animate(&other, procedure)?.ok_or(())?,
procedure, ))
)?
.ok_or(())?))
} }
fn compute_squared_distance_fallback(&self, other: &Self) -> Result<SquaredDistance, ()> { fn compute_squared_distance_fallback(&self, other: &Self) -> Result<SquaredDistance, ()> {
@ -727,8 +739,18 @@ impl NonNegativeLengthOrPercentage {
/// The computed `<length>` value. /// The computed `<length>` value.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, #[derive(
PartialOrd, ToAnimatedValue, ToAnimatedZero)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
PartialOrd,
ToAnimatedValue,
ToAnimatedZero,
)]
pub struct CSSPixelLength(CSSFloat); pub struct CSSPixelLength(CSSFloat);
impl CSSPixelLength { impl CSSPixelLength {
@ -916,8 +938,7 @@ pub type NonNegativeLengthOrPercentageOrNormal = Either<NonNegativeLengthOrPerce
/// block-size, and inline-size. /// block-size, and inline-size.
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss)]
SpecifiedValueInfo, ToCss)]
pub enum ExtremumLength { pub enum ExtremumLength {
MozMaxContent, MozMaxContent,
MozMinContent, MozMinContent,

View file

@ -7,4 +7,4 @@
/// A computed offset-path. The computed value is as specified value. /// A computed offset-path. The computed value is as specified value.
/// ///
/// https://drafts.fxtf.org/motion-1/#offset-path-property /// https://drafts.fxtf.org/motion-1/#offset-path-property
pub use values::specified::motion::OffsetPath as OffsetPath; pub use values::specified::motion::OffsetPath;

View file

@ -12,9 +12,21 @@ use values::generics::NonNegative;
/// A computed percentage. /// A computed percentage.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, Default, #[derive(
MallocSizeOf, PartialEq, PartialOrd, SpecifiedValueInfo, Animate,
ToAnimatedValue, ToAnimatedZero, ToComputedValue)] Clone,
ComputeSquaredDistance,
Copy,
Debug,
Default,
MallocSizeOf,
PartialEq,
PartialOrd,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
)]
pub struct Percentage(pub CSSFloat); pub struct Percentage(pub CSSFloat);
impl Percentage { impl Percentage {

View file

@ -162,13 +162,13 @@ impl TransformOperation {
generic::TransformOperation::RotateZ(ref angle) | generic::TransformOperation::RotateZ(ref angle) |
generic::TransformOperation::Rotate(ref angle) => { generic::TransformOperation::Rotate(ref angle) => {
generic::TransformOperation::Rotate3D(0., 0., 1., angle.clone()) generic::TransformOperation::Rotate3D(0., 0., 1., angle.clone())
} },
generic::TransformOperation::RotateX(ref angle) => { generic::TransformOperation::RotateX(ref angle) => {
generic::TransformOperation::Rotate3D(1., 0., 0., angle.clone()) generic::TransformOperation::Rotate3D(1., 0., 0., angle.clone())
} },
generic::TransformOperation::RotateY(ref angle) => { generic::TransformOperation::RotateY(ref angle) => {
generic::TransformOperation::Rotate3D(0., 1., 0., angle.clone()) generic::TransformOperation::Rotate3D(0., 1., 0., angle.clone())
} },
_ => unreachable!(), _ => unreachable!(),
} }
} }
@ -273,9 +273,9 @@ impl ToAnimatedZero for TransformOperation {
generic::TransformOperation::Rotate(_) => { generic::TransformOperation::Rotate(_) => {
Ok(generic::TransformOperation::Rotate(Angle::zero())) Ok(generic::TransformOperation::Rotate(Angle::zero()))
}, },
generic::TransformOperation::Perspective(ref l) => { generic::TransformOperation::Perspective(ref l) => Ok(
Ok(generic::TransformOperation::Perspective(l.to_animated_zero()?)) generic::TransformOperation::Perspective(l.to_animated_zero()?),
}, ),
generic::TransformOperation::AccumulateMatrix { .. } | generic::TransformOperation::AccumulateMatrix { .. } |
generic::TransformOperation::InterpolateMatrix { .. } => { generic::TransformOperation::InterpolateMatrix { .. } => {
// AccumulateMatrix/InterpolateMatrix: We do interpolation on // AccumulateMatrix/InterpolateMatrix: We do interpolation on
@ -293,10 +293,12 @@ impl ToAnimatedZero for TransformOperation {
impl ToAnimatedZero for Transform { impl ToAnimatedZero for Transform {
#[inline] #[inline]
fn to_animated_zero(&self) -> Result<Self, ()> { fn to_animated_zero(&self) -> Result<Self, ()> {
Ok(generic::Transform(self.0 Ok(generic::Transform(
.iter() self.0
.map(|op| op.to_animated_zero()) .iter()
.collect::<Result<Vec<_>, _>>()?)) .map(|op| op.to_animated_zero())
.collect::<Result<Vec<_>, _>>()?,
))
} }
} }

View file

@ -5,9 +5,20 @@
//! Generic types for CSS values related to backgrounds. //! Generic types for CSS values related to backgrounds.
/// A generic value for the `background-size` property. /// A generic value for the `background-size` property.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, Animate,
ToComputedValue, ToCss)] Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum BackgroundSize<LengthOrPercentageOrAuto> { pub enum BackgroundSize<LengthOrPercentageOrAuto> {
/// `<width> <height>` /// `<width> <height>`
Explicit { Explicit {

View file

@ -19,8 +19,9 @@ pub type ClippingShape<BasicShape, Url> = ShapeSource<BasicShape, GeometryBox, U
/// <https://drafts.fxtf.org/css-masking-1/#typedef-geometry-box> /// <https://drafts.fxtf.org/css-masking-1/#typedef-geometry-box>
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToComputedValue, ToCss)] Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
pub enum GeometryBox { pub enum GeometryBox {
FillBox, FillBox,
StrokeBox, StrokeBox,
@ -34,8 +35,19 @@ pub type FloatAreaShape<BasicShape, Image> = ShapeSource<BasicShape, ShapeBox, I
/// https://drafts.csswg.org/css-shapes-1/#typedef-shape-box /// https://drafts.csswg.org/css-shapes-1/#typedef-shape-box
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, #[derive(
SpecifiedValueInfo, ToComputedValue, ToCss)] Animate,
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum ShapeBox { pub enum ShapeBox {
MarginBox, MarginBox,
BorderBox, BorderBox,
@ -46,8 +58,9 @@ pub enum ShapeBox {
/// A shape source, for some reference box. /// A shape source, for some reference box.
#[allow(missing_docs)] #[allow(missing_docs)]
#[animation(no_bound(ImageOrUrl))] #[animation(no_bound(ImageOrUrl))]
#[derive(Animate, Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(
ToComputedValue, ToCss)] Animate, Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
pub enum ShapeSource<BasicShape, ReferenceBox, ImageOrUrl> { pub enum ShapeSource<BasicShape, ReferenceBox, ImageOrUrl> {
#[animation(error)] #[animation(error)]
ImageOrUrl(ImageOrUrl), ImageOrUrl(ImageOrUrl),
@ -61,8 +74,17 @@ pub enum ShapeSource<BasicShape, ReferenceBox, ImageOrUrl> {
} }
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToComputedValue, ToCss)] Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum BasicShape<H, V, LengthOrPercentage> { pub enum BasicShape<H, V, LengthOrPercentage> {
Inset(#[css(field_bound)] InsetRect<LengthOrPercentage>), Inset(#[css(field_bound)] InsetRect<LengthOrPercentage>),
Circle(#[css(field_bound)] Circle<H, V, LengthOrPercentage>), Circle(#[css(field_bound)] Circle<H, V, LengthOrPercentage>),
@ -73,8 +95,16 @@ pub enum BasicShape<H, V, LengthOrPercentage> {
/// <https://drafts.csswg.org/css-shapes/#funcdef-inset> /// <https://drafts.csswg.org/css-shapes/#funcdef-inset>
#[allow(missing_docs)] #[allow(missing_docs)]
#[css(function = "inset")] #[css(function = "inset")]
#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToComputedValue)] Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
)]
pub struct InsetRect<LengthOrPercentage> { pub struct InsetRect<LengthOrPercentage> {
pub rect: Rect<LengthOrPercentage>, pub rect: Rect<LengthOrPercentage>,
pub round: Option<BorderRadius<LengthOrPercentage>>, pub round: Option<BorderRadius<LengthOrPercentage>>,
@ -83,8 +113,17 @@ pub struct InsetRect<LengthOrPercentage> {
/// <https://drafts.csswg.org/css-shapes/#funcdef-circle> /// <https://drafts.csswg.org/css-shapes/#funcdef-circle>
#[allow(missing_docs)] #[allow(missing_docs)]
#[css(function)] #[css(function)]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToComputedValue)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
)]
pub struct Circle<H, V, LengthOrPercentage> { pub struct Circle<H, V, LengthOrPercentage> {
pub position: Position<H, V>, pub position: Position<H, V>,
pub radius: ShapeRadius<LengthOrPercentage>, pub radius: ShapeRadius<LengthOrPercentage>,
@ -93,8 +132,17 @@ pub struct Circle<H, V, LengthOrPercentage> {
/// <https://drafts.csswg.org/css-shapes/#funcdef-ellipse> /// <https://drafts.csswg.org/css-shapes/#funcdef-ellipse>
#[allow(missing_docs)] #[allow(missing_docs)]
#[css(function)] #[css(function)]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToComputedValue)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
)]
pub struct Ellipse<H, V, LengthOrPercentage> { pub struct Ellipse<H, V, LengthOrPercentage> {
pub position: Position<H, V>, pub position: Position<H, V>,
pub semiaxis_x: ShapeRadius<LengthOrPercentage>, pub semiaxis_x: ShapeRadius<LengthOrPercentage>,
@ -103,8 +151,18 @@ pub struct Ellipse<H, V, LengthOrPercentage> {
/// <https://drafts.csswg.org/css-shapes/#typedef-shape-radius> /// <https://drafts.csswg.org/css-shapes/#typedef-shape-radius>
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum ShapeRadius<LengthOrPercentage> { pub enum ShapeRadius<LengthOrPercentage> {
Length(LengthOrPercentage), Length(LengthOrPercentage),
#[animation(error)] #[animation(error)]
@ -117,8 +175,7 @@ pub enum ShapeRadius<LengthOrPercentage> {
/// ///
/// <https://drafts.csswg.org/css-shapes/#funcdef-polygon> /// <https://drafts.csswg.org/css-shapes/#funcdef-polygon>
#[css(comma, function)] #[css(comma, function)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToComputedValue, ToCss)]
pub struct Polygon<LengthOrPercentage> { pub struct Polygon<LengthOrPercentage> {
/// The filling rule for a polygon. /// The filling rule for a polygon.
#[css(skip_if = "fill_is_default")] #[css(skip_if = "fill_is_default")]
@ -129,8 +186,7 @@ pub struct Polygon<LengthOrPercentage> {
} }
/// Coordinates for Polygon. /// Coordinates for Polygon.
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToComputedValue, ToCss)]
pub struct PolygonCoord<LengthOrPercentage>(pub LengthOrPercentage, pub LengthOrPercentage); pub struct PolygonCoord<LengthOrPercentage>(pub LengthOrPercentage, pub LengthOrPercentage);
// https://drafts.csswg.org/css-shapes/#typedef-fill-rule // https://drafts.csswg.org/css-shapes/#typedef-fill-rule
@ -139,8 +195,18 @@ pub struct PolygonCoord<LengthOrPercentage>(pub LengthOrPercentage, pub LengthOr
// says that it can also be `inherit` // says that it can also be `inherit`
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, #[derive(
SpecifiedValueInfo, ToComputedValue, ToCss)] Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
#[repr(u8)] #[repr(u8)]
pub enum FillRule { pub enum FillRule {
Nonzero, Nonzero,
@ -151,8 +217,9 @@ pub enum FillRule {
/// ///
/// https://drafts.csswg.org/css-shapes-2/#funcdef-path /// https://drafts.csswg.org/css-shapes-2/#funcdef-path
#[css(comma)] #[css(comma)]
#[derive(Animate, Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(
ToComputedValue, ToCss)] Animate, Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
pub struct Path { pub struct Path {
/// The filling rule for the svg path. /// The filling rule for the svg path.
#[css(skip_if = "fill_is_default")] #[css(skip_if = "fill_is_default")]
@ -174,17 +241,16 @@ where
( (
&ShapeSource::Shape(ref this, ref this_box), &ShapeSource::Shape(ref this, ref this_box),
&ShapeSource::Shape(ref other, ref other_box), &ShapeSource::Shape(ref other, ref other_box),
) if this_box == other_box => )
if this_box == other_box =>
{ {
this.compute_squared_distance(other) this.compute_squared_distance(other)
}, },
( (&ShapeSource::Path(ref this), &ShapeSource::Path(ref other))
&ShapeSource::Path(ref this), if this.fill == other.fill =>
&ShapeSource::Path(ref other),
) if this.fill == other.fill =>
{ {
this.path.compute_squared_distance(&other.path) this.path.compute_squared_distance(&other.path)
} },
_ => Err(()), _ => Err(()),
} }
} }
@ -232,7 +298,8 @@ where
if self.coordinates.len() != other.coordinates.len() { if self.coordinates.len() != other.coordinates.len() {
return Err(()); return Err(());
} }
let coordinates = self.coordinates let coordinates = self
.coordinates
.iter() .iter()
.zip(other.coordinates.iter()) .zip(other.coordinates.iter())
.map(|(this, other)| { .map(|(this, other)| {
@ -240,8 +307,7 @@ where
this.0.animate(&other.0, procedure)?, this.0.animate(&other.0, procedure)?,
this.1.animate(&other.1, procedure)?, this.1.animate(&other.1, procedure)?,
)) ))
}) }).collect::<Result<Vec<_>, _>>()?;
.collect::<Result<Vec<_>, _>>()?;
Ok(Polygon { Ok(Polygon {
fill: self.fill, fill: self.fill,
coordinates, coordinates,
@ -267,8 +333,7 @@ where
let d1 = this.0.compute_squared_distance(&other.0)?; let d1 = this.0.compute_squared_distance(&other.0)?;
let d2 = this.1.compute_squared_distance(&other.1)?; let d2 = this.1.compute_squared_distance(&other.1)?;
Ok(d1 + d2) Ok(d1 + d2)
}) }).sum()
.sum()
} }
} }

View file

@ -10,8 +10,9 @@ use values::generics::rect::Rect;
use values::generics::size::Size; use values::generics::size::Size;
/// A generic value for a single side of a `border-image-width` property. /// A generic value for a single side of a `border-image-width` property.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(
ToComputedValue, ToCss)] Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
pub enum BorderImageSideWidth<LengthOrPercentage, Number> { pub enum BorderImageSideWidth<LengthOrPercentage, Number> {
/// `<length-or-percentage>` /// `<length-or-percentage>`
Length(LengthOrPercentage), Length(LengthOrPercentage),
@ -22,8 +23,9 @@ pub enum BorderImageSideWidth<LengthOrPercentage, Number> {
} }
/// A generic value for the `border-image-slice` property. /// A generic value for the `border-image-slice` property.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(
ToComputedValue, ToCss)] Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
pub struct BorderImageSlice<NumberOrPercentage> { pub struct BorderImageSlice<NumberOrPercentage> {
/// The offsets. /// The offsets.
#[css(field_bound)] #[css(field_bound)]
@ -34,8 +36,18 @@ pub struct BorderImageSlice<NumberOrPercentage> {
} }
/// A generic value for the `border-*-radius` longhand properties. /// A generic value for the `border-*-radius` longhand properties.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub struct BorderCornerRadius<L>(#[css(field_bound)] pub Size<L>); pub struct BorderCornerRadius<L>(#[css(field_bound)] pub Size<L>);
impl<L> BorderCornerRadius<L> { impl<L> BorderCornerRadius<L> {
@ -46,9 +58,20 @@ impl<L> BorderCornerRadius<L> {
} }
/// A generic value for the `border-spacing` property. /// A generic value for the `border-spacing` property.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, Animate,
ToComputedValue, ToCss)] Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub struct BorderSpacing<L>(#[css(field_bound)] pub Size<L>); pub struct BorderSpacing<L>(#[css(field_bound)] pub Size<L>);
impl<L> BorderSpacing<L> { impl<L> BorderSpacing<L> {
@ -61,8 +84,17 @@ impl<L> BorderSpacing<L> {
/// A generic value for `border-radius`, `outline-radius` and `inset()`. /// A generic value for `border-radius`, `outline-radius` and `inset()`.
/// ///
/// <https://drafts.csswg.org/css-backgrounds-3/#border-radius> /// <https://drafts.csswg.org/css-backgrounds-3/#border-radius>
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToComputedValue)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
)]
pub struct BorderRadius<LengthOrPercentage> { pub struct BorderRadius<LengthOrPercentage> {
/// The top left radius. /// The top left radius.
pub top_left: BorderCornerRadius<LengthOrPercentage>, pub top_left: BorderCornerRadius<LengthOrPercentage>,
@ -120,7 +152,9 @@ where
W: Write, W: Write,
{ {
widths.to_css(dest)?; widths.to_css(dest)?;
if widths.0 != heights.0 || widths.1 != heights.1 || widths.2 != heights.2 || if widths.0 != heights.0 ||
widths.1 != heights.1 ||
widths.2 != heights.2 ||
widths.3 != heights.3 widths.3 != heights.3
{ {
dest.write_str(" / ")?; dest.write_str(" / ")?;

View file

@ -7,8 +7,18 @@
use values::animated::ToAnimatedZero; use values::animated::ToAnimatedZero;
/// A generic value for the `vertical-align` property. /// A generic value for the `vertical-align` property.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum VerticalAlign<LengthOrPercentage> { pub enum VerticalAlign<LengthOrPercentage> {
/// `baseline` /// `baseline`
Baseline, Baseline,
@ -48,8 +58,7 @@ impl<L> ToAnimatedZero for VerticalAlign<L> {
} }
/// https://drafts.csswg.org/css-animations/#animation-iteration-count /// https://drafts.csswg.org/css-animations/#animation-iteration-count
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToComputedValue, ToCss)]
pub enum AnimationIterationCount<Number> { pub enum AnimationIterationCount<Number> {
/// A `<number>` value. /// A `<number>` value.
Number(Number), Number(Number),
@ -58,9 +67,20 @@ pub enum AnimationIterationCount<Number> {
} }
/// A generic value for the `perspective` property. /// A generic value for the `perspective` property.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, Animate,
ToComputedValue, ToCss)] Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum Perspective<NonNegativeLength> { pub enum Perspective<NonNegativeLength> {
/// A non-negative length. /// A non-negative length.
Length(NonNegativeLength), Length(NonNegativeLength),

View file

@ -5,9 +5,20 @@
//! Generic types for the column properties. //! Generic types for the column properties.
/// A generic type for `column-count` values. /// A generic type for `column-count` values.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, Animate,
ToComputedValue, ToCss)] Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum ColumnCount<PositiveInteger> { pub enum ColumnCount<PositiveInteger> {
/// A positive integer. /// A positive integer.
Integer(PositiveInteger), Integer(PositiveInteger),

View file

@ -14,8 +14,7 @@ use values::generics::CounterStyleOrNone;
use values::specified::Attr; use values::specified::Attr;
/// A name / value pair for counters. /// A name / value pair for counters.
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToComputedValue, ToCss)]
pub struct CounterPair<Integer> { pub struct CounterPair<Integer> {
/// The name of the counter. /// The name of the counter.
pub name: CustomIdent, pub name: CustomIdent,
@ -24,8 +23,9 @@ pub struct CounterPair<Integer> {
} }
/// A generic value for the `counter-increment` property. /// A generic value for the `counter-increment` property.
#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(
ToComputedValue, ToCss)] Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
pub struct CounterIncrement<I>(Counters<I>); pub struct CounterIncrement<I>(Counters<I>);
impl<I> CounterIncrement<I> { impl<I> CounterIncrement<I> {
@ -46,8 +46,9 @@ impl<I> Deref for CounterIncrement<I> {
} }
/// A generic value for the `counter-reset` property. /// A generic value for the `counter-reset` property.
#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(
ToComputedValue, ToCss)] Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
pub struct CounterReset<I>(Counters<I>); pub struct CounterReset<I>(Counters<I>);
impl<I> CounterReset<I> { impl<I> CounterReset<I> {
@ -70,8 +71,7 @@ impl<I> Deref for CounterReset<I> {
/// A generic value for lists of counters. /// A generic value for lists of counters.
/// ///
/// Keyword `none` is represented by an empty vector. /// Keyword `none` is represented by an empty vector.
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToComputedValue, ToCss)]
pub struct Counters<I>(#[css(iterable, if_empty = "none")] Box<[CounterPair<I>]>); pub struct Counters<I>(#[css(iterable, if_empty = "none")] Box<[CounterPair<I>]>);
impl<I> Default for Counters<I> { impl<I> Default for Counters<I> {
@ -102,8 +102,7 @@ fn is_decimal(counter_type: &CounterStyleType) -> bool {
/// The specified value for the `content` property. /// The specified value for the `content` property.
/// ///
/// https://drafts.csswg.org/css-content/#propdef-content /// https://drafts.csswg.org/css-content/#propdef-content
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToComputedValue, ToCss)]
pub enum Content<ImageUrl> { pub enum Content<ImageUrl> {
/// `normal` reserved keyword. /// `normal` reserved keyword.
Normal, Normal,
@ -125,8 +124,7 @@ impl<ImageUrl> Content<ImageUrl> {
} }
/// Items for the `content` property. /// Items for the `content` property.
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToComputedValue, ToCss)]
pub enum ContentItem<ImageUrl> { pub enum ContentItem<ImageUrl> {
/// Literal string content. /// Literal string content.
String(Box<str>), String(Box<str>),

View file

@ -5,8 +5,17 @@
//! Generic types for CSS values related to effects. //! Generic types for CSS values related to effects.
/// A generic value for a single `box-shadow`. /// A generic value for a single `box-shadow`.
#[derive(Animate, Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(
ToAnimatedValue, ToAnimatedZero, ToCss)] Animate,
Clone,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToCss,
)]
pub struct BoxShadow<Color, SizeLength, BlurShapeLength, ShapeLength> { pub struct BoxShadow<Color, SizeLength, BlurShapeLength, ShapeLength> {
/// The base shadow. /// The base shadow.
pub base: SimpleShadow<Color, SizeLength, BlurShapeLength>, pub base: SimpleShadow<Color, SizeLength, BlurShapeLength>,
@ -21,8 +30,17 @@ pub struct BoxShadow<Color, SizeLength, BlurShapeLength, ShapeLength> {
/// A generic value for a single `filter`. /// A generic value for a single `filter`.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[animation(no_bound(Url))] #[animation(no_bound(Url))]
#[derive(Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss)] Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToComputedValue,
ToCss,
)]
pub enum Filter<Angle, Factor, Length, DropShadow, Url> { pub enum Filter<Angle, Factor, Length, DropShadow, Url> {
/// `blur(<length>)` /// `blur(<length>)`
#[css(function)] #[css(function)]
@ -63,8 +81,18 @@ pub enum Filter<Angle, Factor, Length, DropShadow, Url> {
/// ///
/// Contrary to the canonical order from the spec, the color is serialised /// Contrary to the canonical order from the spec, the color is serialised
/// first, like in Gecko and Webkit. /// first, like in Gecko and Webkit.
#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToCss)] Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToCss,
)]
pub struct SimpleShadow<Color, SizeLength, ShapeLength> { pub struct SimpleShadow<Color, SizeLength, ShapeLength> {
/// Color. /// Color.
pub color: Color, pub color: Color,

View file

@ -6,9 +6,19 @@
/// A generic value for the `flex-basis` property. /// A generic value for the `flex-basis` property.
#[cfg_attr(feature = "servo", derive(MallocSizeOf))] #[cfg_attr(feature = "servo", derive(MallocSizeOf))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, PartialEq, #[derive(
SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, Animate,
ToCss)] Clone,
ComputeSquaredDistance,
Copy,
Debug,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum FlexBasis<Width> { pub enum FlexBasis<Width> {
/// `content` /// `content`
Content, Content,

View file

@ -16,8 +16,7 @@ use style_traits::{SpecifiedValueInfo, StyleParseErrorKind, ToCss};
use values::distance::{ComputeSquaredDistance, SquaredDistance}; use values::distance::{ComputeSquaredDistance, SquaredDistance};
/// https://drafts.csswg.org/css-fonts-4/#feature-tag-value /// https://drafts.csswg.org/css-fonts-4/#feature-tag-value
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
ToComputedValue)]
pub struct FeatureTagValue<Integer> { pub struct FeatureTagValue<Integer> {
/// A four-character tag, packed into a u32 (one byte per character). /// A four-character tag, packed into a u32 (one byte per character).
pub tag: FontTag, pub tag: FontTag,
@ -47,8 +46,9 @@ where
/// Variation setting for a single feature, see: /// Variation setting for a single feature, see:
/// ///
/// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def
#[derive(Animate, Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(
ToComputedValue, ToCss)] Animate, Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
pub struct VariationValue<Number> { pub struct VariationValue<Number> {
/// A four-character tag, packed into a u32 (one byte per character). /// A four-character tag, packed into a u32 (one byte per character).
#[animation(constant)] #[animation(constant)]
@ -72,8 +72,7 @@ where
/// A value both for font-variation-settings and font-feature-settings. /// A value both for font-variation-settings and font-feature-settings.
#[css(comma)] #[css(comma)]
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToComputedValue, ToCss)]
pub struct FontSettings<T>(#[css(if_empty = "normal", iterable)] pub Box<[T]>); pub struct FontSettings<T>(#[css(if_empty = "normal", iterable)] pub Box<[T]>);
impl<T> FontSettings<T> { impl<T> FontSettings<T> {
@ -109,8 +108,7 @@ impl<T: Parse> Parse for FontSettings<T> {
/// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def /// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def
/// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings
/// ///
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
ToComputedValue)]
pub struct FontTag(pub u32); pub struct FontTag(pub u32);
impl ToCss for FontTag { impl ToCss for FontTag {
@ -145,8 +143,18 @@ impl Parse for FontTag {
} }
} }
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, #[derive(
ToAnimatedValue, ToAnimatedZero, ToCss)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
ToAnimatedValue,
ToAnimatedZero,
ToCss,
)]
/// Additional information for keyword-derived font sizes. /// Additional information for keyword-derived font sizes.
pub struct KeywordInfo<Length> { pub struct KeywordInfo<Length> {
/// The keyword used /// The keyword used
@ -189,9 +197,20 @@ impl<L> SpecifiedValueInfo for KeywordInfo<L> {
} }
/// CSS font keywords /// CSS font keywords
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
Parse, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, Animate,
ToCss)] Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToCss,
)]
#[allow(missing_docs)] #[allow(missing_docs)]
pub enum KeywordSize { pub enum KeywordSize {
#[css(keyword = "xx-small")] #[css(keyword = "xx-small")]
@ -228,8 +247,19 @@ impl Default for KeywordSize {
/// https://drafts.csswg.org/css-fonts-4/#font-style-prop /// https://drafts.csswg.org/css-fonts-4/#font-style-prop
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, Hash, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
Hash,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
)]
pub enum FontStyle<Angle> { pub enum FontStyle<Angle> {
#[animation(error)] #[animation(error)]
Normal, Normal,

View file

@ -7,8 +7,7 @@
/// 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, #[derive(Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToCss)]
pub enum ScrollSnapPoint<LengthOrPercentage> { pub enum ScrollSnapPoint<LengthOrPercentage> {
/// `none` /// `none`
None, None,

View file

@ -18,8 +18,7 @@ use values::specified::grid::parse_line_names;
/// A `<grid-line>` type. /// A `<grid-line>` type.
/// ///
/// <https://drafts.csswg.org/css-grid/#typedef-grid-row-start-grid-line> /// <https://drafts.csswg.org/css-grid/#typedef-grid-row-start-grid-line>
#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
ToComputedValue)]
pub struct GridLine<Integer> { pub struct GridLine<Integer> {
/// Flag to check whether it's a `span` keyword. /// Flag to check whether it's a `span` keyword.
pub is_span: bool, pub is_span: bool,
@ -149,8 +148,18 @@ impl Parse for GridLine<specified::Integer> {
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, #[derive(
SpecifiedValueInfo, ToComputedValue, ToCss)] Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum TrackKeyword { pub enum TrackKeyword {
Auto, Auto,
MaxContent, MaxContent,
@ -161,8 +170,7 @@ pub enum TrackKeyword {
/// avoid re-implementing it for the computed type. /// avoid re-implementing it for the computed type.
/// ///
/// <https://drafts.csswg.org/css-grid/#typedef-track-breadth> /// <https://drafts.csswg.org/css-grid/#typedef-track-breadth>
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToComputedValue, ToCss)]
pub enum TrackBreadth<L> { pub enum TrackBreadth<L> {
/// The generic type is almost always a non-negative `<length-percentage>` /// The generic type is almost always a non-negative `<length-percentage>`
Breadth(L), Breadth(L),
@ -383,8 +391,7 @@ impl Parse for RepeatCount<specified::Integer> {
/// ///
/// It can also hold `repeat()` function parameters, which expands into the respective /// It can also hold `repeat()` function parameters, which expands into the respective
/// values in its computed form. /// values in its computed form.
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
ToComputedValue)]
#[css(function = "repeat")] #[css(function = "repeat")]
pub struct TrackRepeat<L, I> { pub struct TrackRepeat<L, I> {
/// The number of times for the value to be repeated (could also be `auto-fit` or `auto-fill`) /// The number of times for the value to be repeated (could also be `auto-fit` or `auto-fill`)
@ -409,7 +416,8 @@ impl<L: ToCss, I: ToCss> ToCss for TrackRepeat<L, I> {
dest.write_str(", ")?; dest.write_str(", ")?;
let mut line_names_iter = self.line_names.iter(); let mut line_names_iter = self.line_names.iter();
for (i, (ref size, ref names)) in self.track_sizes for (i, (ref size, ref names)) in self
.track_sizes
.iter() .iter()
.zip(&mut line_names_iter) .zip(&mut line_names_iter)
.enumerate() .enumerate()
@ -471,8 +479,7 @@ 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, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToComputedValue, ToCss)]
pub enum TrackListValue<LengthOrPercentage, Integer> { pub enum TrackListValue<LengthOrPercentage, Integer> {
/// A <track-size> value. /// A <track-size> value.
TrackSize(TrackSize<LengthOrPercentage>), TrackSize(TrackSize<LengthOrPercentage>),
@ -578,8 +585,7 @@ impl<L: ToCss, I: ToCss> ToCss for TrackList<L, I> {
/// ///
/// `subgrid [ <line-names> | repeat(<positive-integer> | auto-fill, <line-names>+) ]+` /// `subgrid [ <line-names> | repeat(<positive-integer> | auto-fill, <line-names>+) ]+`
/// Old spec: https://www.w3.org/TR/2015/WD-css-grid-1-20150917/#typedef-line-name-list /// Old spec: https://www.w3.org/TR/2015/WD-css-grid-1-20150917/#typedef-line-name-list
#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, Default, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
ToComputedValue)]
pub struct LineNameList { pub struct LineNameList {
/// The optional `<line-name-list>` /// The optional `<line-name-list>`
pub names: Box<[Box<[CustomIdent]>]>, pub names: Box<[Box<[CustomIdent]>]>,
@ -624,7 +630,9 @@ impl Parse for LineNameList {
RepeatCount::AutoFill if fill_idx.is_none() => { RepeatCount::AutoFill if fill_idx.is_none() => {
// `repeat(autof-fill, ..)` should have just one line name. // `repeat(autof-fill, ..)` should have just one line name.
if names_list.len() != 1 { if names_list.len() != 1 {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); return Err(
input.new_custom_error(StyleParseErrorKind::UnspecifiedError)
);
} }
let names = names_list.pop().unwrap(); let names = names_list.pop().unwrap();
@ -682,8 +690,7 @@ impl ToCss for LineNameList {
/// Variants for `<grid-template-rows> | <grid-template-columns>` /// Variants for `<grid-template-rows> | <grid-template-columns>`
/// Subgrid deferred to Level 2 spec due to lack of implementation. /// Subgrid deferred to Level 2 spec due to lack of implementation.
/// But it's implemented in gecko, so we have to as well. /// But it's implemented in gecko, so we have to as well.
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToComputedValue, ToCss)]
pub enum GridTemplateComponent<L, I> { pub enum GridTemplateComponent<L, I> {
/// `none` value. /// `none` value.
None, None,

View file

@ -145,7 +145,7 @@ pub struct PaintWorklet {
pub arguments: Vec<Arc<custom_properties::SpecifiedValue>>, pub arguments: Vec<Arc<custom_properties::SpecifiedValue>>,
} }
impl ::style_traits::SpecifiedValueInfo for PaintWorklet { } impl ::style_traits::SpecifiedValueInfo for PaintWorklet {}
impl ToCss for PaintWorklet { impl ToCss for PaintWorklet {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
@ -167,8 +167,7 @@ impl ToCss for PaintWorklet {
/// `-moz-image-rect(<uri>, top, right, bottom, left);` /// `-moz-image-rect(<uri>, top, right, bottom, left);`
#[allow(missing_docs)] #[allow(missing_docs)]
#[css(comma, function)] #[css(comma, function)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToComputedValue, ToCss)]
pub struct MozImageRect<NumberOrPercentage, MozImageRectUrl> { pub struct MozImageRect<NumberOrPercentage, MozImageRectUrl> {
pub url: MozImageRectUrl, pub url: MozImageRectUrl,
pub top: NumberOrPercentage, pub top: NumberOrPercentage,

View file

@ -157,14 +157,37 @@ impl SpecifiedValueInfo for CounterStyleOrNone {
/// A wrapper of Non-negative values. /// A wrapper of Non-negative values.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, Hash, MallocSizeOf, #[derive(
PartialEq, PartialOrd, SpecifiedValueInfo, ToAnimatedZero, Animate,
ToComputedValue, ToCss)] Clone,
ComputeSquaredDistance,
Copy,
Debug,
Hash,
MallocSizeOf,
PartialEq,
PartialOrd,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub struct NonNegative<T>(pub T); pub struct NonNegative<T>(pub T);
/// A wrapper of greater-than-or-equal-to-one values. /// A wrapper of greater-than-or-equal-to-one values.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, PartialOrd, SpecifiedValueInfo, ToAnimatedZero, Animate,
ToComputedValue, ToCss)] Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
PartialOrd,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub struct GreaterThanOrEqualToOne<T>(pub T); pub struct GreaterThanOrEqualToOne<T>(pub T);

View file

@ -6,8 +6,18 @@
//! [`position`](https://drafts.csswg.org/css-backgrounds-3/#position) //! [`position`](https://drafts.csswg.org/css-backgrounds-3/#position)
/// A generic type for representing a CSS [position](https://drafts.csswg.org/css-values/#position). /// A generic type for representing a CSS [position](https://drafts.csswg.org/css-values/#position).
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
)]
pub struct Position<H, V> { pub struct Position<H, V> {
/// The horizontal component of position. /// The horizontal component of position.
pub horizontal: H, pub horizontal: H,
@ -26,8 +36,19 @@ impl<H, V> Position<H, V> {
} }
/// A generic value for the `z-index` property. /// A generic value for the `z-index` property.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum ZIndex<Integer> { pub enum ZIndex<Integer> {
/// An integer value. /// An integer value.
Integer(Integer), Integer(Integer),

View file

@ -11,8 +11,17 @@ use style_traits::{CssWriter, ParseError, ToCss};
/// A CSS value made of four components, where its `ToCss` impl will try to /// A CSS value made of four components, where its `ToCss` impl will try to
/// serialize as few components as possible, like for example in `border-width`. /// serialize as few components as possible, like for example in `border-width`.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToComputedValue)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
)]
pub struct Rect<T>(pub T, pub T, pub T, pub T); pub struct Rect<T>(pub T, pub T, pub T, pub T);
impl<T> Rect<T> { impl<T> Rect<T> {

View file

@ -13,8 +13,17 @@ use values::animated::ToAnimatedValue;
/// A generic size, for `border-*-radius` longhand properties, or /// A generic size, for `border-*-radius` longhand properties, or
/// `border-spacing`. /// `border-spacing`.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, #[derive(
ToAnimatedZero, ToComputedValue)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
ToAnimatedZero,
ToComputedValue,
)]
pub struct Size<L>(pub Size2D<L>); pub struct Size<L>(pub Size2D<L>);
impl<L> Size<L> { impl<L> Size<L> {

View file

@ -16,8 +16,18 @@ use values::distance::{ComputeSquaredDistance, SquaredDistance};
/// ///
/// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint> /// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint>
#[animation(no_bound(UrlPaintServer))] #[animation(no_bound(UrlPaintServer))]
#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss)] Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToComputedValue,
ToCss,
)]
pub struct SVGPaint<ColorType, UrlPaintServer> { pub struct SVGPaint<ColorType, UrlPaintServer> {
/// The paint source /// The paint source
pub kind: SVGPaintKind<ColorType, UrlPaintServer>, pub kind: SVGPaintKind<ColorType, UrlPaintServer>,
@ -31,9 +41,19 @@ pub struct SVGPaint<ColorType, UrlPaintServer> {
/// to have a fallback, Gecko lets the context /// to have a fallback, Gecko lets the context
/// properties have a fallback as well. /// properties have a fallback as well.
#[animation(no_bound(UrlPaintServer))] #[animation(no_bound(UrlPaintServer))]
#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, Animate,
ToCss)] Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum SVGPaintKind<ColorType, UrlPaintServer> { pub enum SVGPaintKind<ColorType, UrlPaintServer> {
/// `none` /// `none`
#[animation(error)] #[animation(error)]
@ -113,8 +133,18 @@ impl<ColorType: Parse, UrlPaintServer: Parse> Parse for SVGPaint<ColorType, UrlP
/// A value of <length> | <percentage> | <number> for svg which allow unitless length. /// A value of <length> | <percentage> | <number> for svg which allow unitless length.
/// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(
ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)] Clone,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number> { pub enum SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number> {
/// <length> | <percentage> /// <length> | <percentage>
LengthOrPercentage(LengthOrPercentage), LengthOrPercentage(LengthOrPercentage),
@ -191,9 +221,19 @@ impl<LengthOrPercentageType: Parse, NumberType: Parse> Parse
} }
/// An SVG length value supports `context-value` in addition to length. /// An SVG length value supports `context-value` in addition to length.
#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, Clone,
ToCss)] ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum SVGLength<LengthType> { pub enum SVGLength<LengthType> {
/// `<length> | <percentage> | <number>` /// `<length> | <percentage> | <number>`
Length(LengthType), Length(LengthType),
@ -202,23 +242,38 @@ pub enum SVGLength<LengthType> {
} }
/// Generic value for stroke-dasharray. /// Generic value for stroke-dasharray.
#[derive(Clone, Debug, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss)] Clone,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToComputedValue,
ToCss,
)]
pub enum SVGStrokeDashArray<LengthType> { pub enum SVGStrokeDashArray<LengthType> {
/// `[ <length> | <percentage> | <number> ]#` /// `[ <length> | <percentage> | <number> ]#`
#[css(comma)] #[css(comma)]
Values( Values(#[css(if_empty = "none", iterable)] Vec<LengthType>),
#[css(if_empty = "none", iterable)]
Vec<LengthType>,
),
/// `context-value` /// `context-value`
ContextValue, ContextValue,
} }
/// An SVG opacity value accepts `context-{fill,stroke}-opacity` in /// An SVG opacity value accepts `context-{fill,stroke}-opacity` in
/// addition to opacity value. /// addition to opacity value.
#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)] Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum SVGOpacity<OpacityType> { pub enum SVGOpacity<OpacityType> {
/// `<opacity-value>` /// `<opacity-value>`
Opacity(OpacityType), Opacity(OpacityType),

View file

@ -12,8 +12,9 @@ use values::animated::{Animate, Procedure, ToAnimatedZero};
use values::distance::{ComputeSquaredDistance, SquaredDistance}; use values::distance::{ComputeSquaredDistance, SquaredDistance};
/// A generic value for the `initial-letter` property. /// A generic value for the `initial-letter` property.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(
ToComputedValue, ToCss)] Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
pub enum InitialLetter<Number, Integer> { pub enum InitialLetter<Number, Integer> {
/// `normal` /// `normal`
Normal, Normal,
@ -30,8 +31,9 @@ impl<N, I> InitialLetter<N, I> {
} }
/// A generic spacing value for the `letter-spacing` and `word-spacing` properties. /// A generic spacing value for the `letter-spacing` and `word-spacing` properties.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(
ToComputedValue, ToCss)] Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
pub enum Spacing<Value> { pub enum Spacing<Value> {
/// `normal` /// `normal`
Normal, Normal,
@ -112,8 +114,18 @@ where
} }
/// A generic value for the `line-height` property. /// A generic value for the `line-height` property.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToCss)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToCss,
)]
pub enum LineHeight<Number, LengthOrPercentage> { pub enum LineHeight<Number, LengthOrPercentage> {
/// `normal` /// `normal`
Normal, Normal,
@ -142,9 +154,20 @@ impl<N, L> LineHeight<N, L> {
} }
/// A generic value for the `-moz-tab-size` property. /// A generic value for the `-moz-tab-size` property.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, Animate,
ToComputedValue, ToCss)] Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum MozTabSize<Number, Length> { pub enum MozTabSize<Number, Length> {
/// A number. /// A number.
Number(Number), Number(Number),

View file

@ -15,8 +15,9 @@ use values::specified::length::LengthOrPercentage as SpecifiedLengthOrPercentage
/// A generic 2D transformation matrix. /// A generic 2D transformation matrix.
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(
ToComputedValue, ToCss)] Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
#[css(comma, function)] #[css(comma, function)]
pub struct Matrix<T> { pub struct Matrix<T> {
pub a: T, pub a: T,
@ -66,8 +67,19 @@ impl<T: Into<f64>> From<Matrix3D<T>> for Transform3D<f64> {
} }
/// A generic transform origin. /// A generic transform origin.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, #[derive(
PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)] Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub struct TransformOrigin<H, V, Depth> { pub struct TransformOrigin<H, V, Depth> {
/// The horizontal origin. /// The horizontal origin.
pub horizontal: H, pub horizontal: H,
@ -80,8 +92,7 @@ pub struct TransformOrigin<H, V, Depth> {
/// A generic timing function. /// A generic timing function.
/// ///
/// <https://drafts.csswg.org/css-timing-1/#single-timing-function-production> /// <https://drafts.csswg.org/css-timing-1/#single-timing-function-production>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)]
ToCss)]
#[value_info(ty = "TIMING_FUNCTION")] #[value_info(ty = "TIMING_FUNCTION")]
pub enum TimingFunction<Integer, Number> { pub enum TimingFunction<Integer, Number> {
/// `linear | ease | ease-in | ease-out | ease-in-out` /// `linear | ease | ease-in | ease-out | ease-in-out`
@ -106,8 +117,18 @@ pub enum TimingFunction<Integer, Number> {
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, #[derive(
SpecifiedValueInfo, ToComputedValue, ToCss)] Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum TimingKeyword { pub enum TimingKeyword {
Linear, Linear,
Ease, Ease,
@ -163,8 +184,7 @@ impl TimingKeyword {
} }
} }
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
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, LengthOrPercentage> {
/// Represents a 2D 2x3 matrix. /// Represents a 2D 2x3 matrix.
@ -268,8 +288,7 @@ pub enum TransformOperation<Angle, Number, Length, Integer, LengthOrPercentage>
}, },
} }
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToComputedValue, ToCss)]
/// 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>);
@ -281,11 +300,7 @@ impl<Angle, Number, Length, Integer, LengthOrPercentage>
use self::TransformOperation::*; use self::TransformOperation::*;
matches!( matches!(
*self, *self,
Rotate(..) | Rotate(..) | Rotate3D(..) | RotateX(..) | RotateY(..) | RotateZ(..)
Rotate3D(..) |
RotateX(..) |
RotateY(..) |
RotateZ(..)
) )
} }
@ -574,8 +589,18 @@ pub fn get_normalized_vector_and_angle<T: Zero>(
} }
} }
#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)] Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
/// A value of the `Rotate` property /// A value of the `Rotate` property
/// ///
/// <https://drafts.csswg.org/css-transforms-2/#individual-transforms> /// <https://drafts.csswg.org/css-transforms-2/#individual-transforms>
@ -588,8 +613,18 @@ pub enum Rotate<Number, Angle> {
Rotate3D(Number, Number, Number, Angle), Rotate3D(Number, Number, Number, Angle),
} }
#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)] Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
/// A value of the `Scale` property /// A value of the `Scale` property
/// ///
/// <https://drafts.csswg.org/css-transforms-2/#individual-transforms> /// <https://drafts.csswg.org/css-transforms-2/#individual-transforms>
@ -604,8 +639,17 @@ pub enum Scale<Number> {
Scale3D(Number, Number, Number), Scale3D(Number, Number, Number),
} }
#[derive(Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)] Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
/// 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>
@ -621,8 +665,9 @@ pub enum Translate<LengthOrPercentage, Length> {
} }
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, #[derive(
ToComputedValue, ToCss)] Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
pub enum TransformStyle { pub enum TransformStyle {
#[cfg(feature = "servo")] #[cfg(feature = "servo")]
Auto, Auto,

View file

@ -11,8 +11,7 @@ use style_traits::cursor::CursorKind;
/// A generic value for the `cursor` property. /// A generic value for the `cursor` property.
/// ///
/// https://drafts.csswg.org/css-ui/#cursor /// https://drafts.csswg.org/css-ui/#cursor
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
ToComputedValue)]
pub struct Cursor<Image> { pub struct Cursor<Image> {
/// The parsed images for the cursor. /// The parsed images for the cursor.
pub images: Box<[Image]>, pub images: Box<[Image]>,
@ -45,8 +44,7 @@ impl<Image: ToCss> ToCss for Cursor<Image> {
} }
/// A generic value for item of `image cursors`. /// A generic value for item of `image cursors`.
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
ToComputedValue)]
pub struct CursorImage<ImageUrl, Number> { pub struct CursorImage<ImageUrl, Number> {
/// The url to parse images from. /// The url to parse images from.
pub url: ImageUrl, pub url: ImageUrl,

View file

@ -9,9 +9,19 @@ use parser::{Parse, ParserContext};
use style_traits::ParseError; use style_traits::ParseError;
/// An image url or none, used for example in list-style-image /// An image url or none, used for example in list-style-image
#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, Animate,
ToCss)] Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum UrlOrNone<Url> { pub enum UrlOrNone<Url> {
/// `none` /// `none`
None, None,

View file

@ -92,8 +92,13 @@ where
} }
/// Convenience void type to disable some properties and values through types. /// Convenience void type to disable some properties and values through types.
#[cfg_attr(feature = "servo", derive(Deserialize, MallocSizeOf, Serialize))] #[cfg_attr(
#[derive(Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss)] feature = "servo",
derive(Deserialize, MallocSizeOf, Serialize)
)]
#[derive(
Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss,
)]
pub enum Impossible {} pub enum Impossible {}
// FIXME(nox): This should be derived but the derive code cannot cope // FIXME(nox): This should be derived but the derive code cannot cope
@ -115,9 +120,19 @@ impl Parse for Impossible {
} }
/// A struct representing one of two kinds of values. /// A struct representing one of two kinds of values.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, MallocSizeOf, PartialEq, #[derive(
SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, Animate,
ToCss)] Clone,
ComputeSquaredDistance,
Copy,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum Either<A, B> { pub enum Either<A, B> {
/// The first value. /// The first value.
First(A), First(A),
@ -148,8 +163,7 @@ impl<A: Parse, B: Parse> Parse for Either<A, B> {
} }
/// <https://drafts.csswg.org/css-values-4/#custom-idents> /// <https://drafts.csswg.org/css-values-4/#custom-idents>
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
ToComputedValue)]
pub struct CustomIdent(pub Atom); pub struct CustomIdent(pub Atom);
impl CustomIdent { impl CustomIdent {
@ -164,7 +178,9 @@ impl CustomIdent {
_ => true _ => true
}; };
if !valid { if !valid {
return Err(location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))); return Err(
location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))
);
} }
if excluding.iter().any(|s| ident.eq_ignore_ascii_case(s)) { if excluding.iter().any(|s| ident.eq_ignore_ascii_case(s)) {
Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)) Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError))

View file

@ -683,8 +683,13 @@ fn parse_self_position<'i, 't>(
fn list_self_position_keywords(f: KeywordsCollectFn, axis: AxisDirection) { fn list_self_position_keywords(f: KeywordsCollectFn, axis: AxisDirection) {
f(&[ f(&[
"start", "end", "flex-start", "flex-end", "start",
"center", "self-start", "self-end", "end",
"flex-start",
"flex-end",
"center",
"self-start",
"self-end",
]); ]);
if axis == AxisDirection::Inline { if axis == AxisDirection::Inline {
f(&["left", "right"]); f(&["left", "right"]);

View file

@ -43,8 +43,18 @@ impl BackgroundSize {
} }
/// One of the keywords for `background-repeat`. /// One of the keywords for `background-repeat`.
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, #[derive(
SpecifiedValueInfo, ToComputedValue, ToCss)] Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
#[allow(missing_docs)] #[allow(missing_docs)]
pub enum BackgroundRepeatKeyword { pub enum BackgroundRepeatKeyword {
Repeat, Repeat,
@ -56,8 +66,7 @@ pub enum BackgroundRepeatKeyword {
/// The specified value for the `background-repeat` property. /// The specified value for the `background-repeat` property.
/// ///
/// https://drafts.csswg.org/css-backgrounds/#the-background-repeat /// https://drafts.csswg.org/css-backgrounds/#the-background-repeat
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)]
ToCss)]
pub enum BackgroundRepeat { pub enum BackgroundRepeat {
/// `repeat-x` /// `repeat-x`
RepeatX, RepeatX,
@ -91,7 +100,9 @@ impl Parse for BackgroundRepeat {
let horizontal = match BackgroundRepeatKeyword::from_ident(&ident) { let horizontal = match BackgroundRepeatKeyword::from_ident(&ident) {
Ok(h) => h, Ok(h) => h,
Err(()) => { Err(()) => {
return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))); return Err(
input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))
);
}, },
}; };

View file

@ -268,8 +268,7 @@ impl Ellipse {
ShapeRadius::parse(context, i)?, ShapeRadius::parse(context, i)?,
ShapeRadius::parse(context, i)?, ShapeRadius::parse(context, i)?,
)) ))
}) }).unwrap_or_default();
.unwrap_or_default();
let position = if input.try(|i| i.expect_ident_matching("at")).is_ok() { let position = if input.try(|i| i.expect_ident_matching("at")).is_ok() {
Position::parse(context, input)? Position::parse(context, input)?
} else { } else {
@ -416,8 +415,7 @@ impl Polygon {
let fill = FillRule::parse(i)?; let fill = FillRule::parse(i)?;
i.expect_comma()?; // only eat the comma if there is something before it i.expect_comma()?; // only eat the comma if there is something before it
Ok(fill) Ok(fill)
}) }).unwrap_or_default();
.unwrap_or_default();
let buf = input.parse_comma_separated(|i| { let buf = input.parse_comma_separated(|i| {
Ok(PolygonCoord( Ok(PolygonCoord(
@ -449,11 +447,12 @@ impl Path {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
let fill = input.try(|i| -> Result<_, ParseError> { let fill = input
let fill = FillRule::parse(i)?; .try(|i| -> Result<_, ParseError> {
i.expect_comma()?; let fill = FillRule::parse(i)?;
Ok(fill) i.expect_comma()?;
}).unwrap_or_default(); Ok(fill)
}).unwrap_or_default();
let path = SVGPathData::parse(context, input)?; let path = SVGPathData::parse(context, input)?;
Ok(Path { fill, path }) Ok(Path { fill, path })
} }

View file

@ -189,8 +189,7 @@ impl Parse for BorderSpacing {
/// A single border-image-repeat keyword. /// A single border-image-repeat keyword.
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss)]
SpecifiedValueInfo, ToCss)]
pub enum BorderImageRepeatKeyword { pub enum BorderImageRepeatKeyword {
Stretch, Stretch,
Repeat, Repeat,
@ -201,8 +200,7 @@ pub enum BorderImageRepeatKeyword {
/// The specified value for the `border-image-repeat` property. /// The specified value for the `border-image-repeat` property.
/// ///
/// https://drafts.csswg.org/css-backgrounds/#the-border-image-repeat /// https://drafts.csswg.org/css-backgrounds/#the-border-image-repeat
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
ToComputedValue)]
pub struct BorderImageRepeat(pub BorderImageRepeatKeyword, pub BorderImageRepeatKeyword); pub struct BorderImageRepeat(pub BorderImageRepeatKeyword, pub BorderImageRepeatKeyword);
impl ToCss for BorderImageRepeat { impl ToCss for BorderImageRepeat {

View file

@ -21,26 +21,23 @@ use values::specified::length::{LengthOrPercentage, NonNegativeLength};
fn in_ua_or_chrome_sheet(context: &ParserContext) -> bool { fn in_ua_or_chrome_sheet(context: &ParserContext) -> bool {
use stylesheets::Origin; use stylesheets::Origin;
context.stylesheet_origin == Origin::UserAgent || context.stylesheet_origin == Origin::UserAgent || context.chrome_rules_enabled()
context.chrome_rules_enabled()
} }
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
fn moz_display_values_enabled(context: &ParserContext) -> bool { fn moz_display_values_enabled(context: &ParserContext) -> bool {
use gecko_bindings::structs; use gecko_bindings::structs;
in_ua_or_chrome_sheet(context) || in_ua_or_chrome_sheet(context) ||
unsafe { unsafe { structs::StaticPrefs_sVarCache_layout_css_xul_display_values_content_enabled }
structs::StaticPrefs_sVarCache_layout_css_xul_display_values_content_enabled
}
} }
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
fn moz_box_display_values_enabled(context: &ParserContext) -> bool { fn moz_box_display_values_enabled(context: &ParserContext) -> bool {
use gecko_bindings::structs; use gecko_bindings::structs;
in_ua_or_chrome_sheet(context) || in_ua_or_chrome_sheet(context) ||
unsafe { unsafe {
structs::StaticPrefs_sVarCache_layout_css_xul_box_display_values_content_enabled structs::StaticPrefs_sVarCache_layout_css_xul_box_display_values_content_enabled
} }
} }
/// Defines an elements display type, which consists of /// Defines an elements display type, which consists of
@ -57,8 +54,20 @@ fn moz_box_display_values_enabled(context: &ParserContext) -> bool {
/// Also, when you change this from Gecko you may need to regenerate the /// Also, when you change this from Gecko you may need to regenerate the
/// C++-side bindings (see components/style/cbindgen.toml). /// C++-side bindings (see components/style/cbindgen.toml).
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Clone, Copy, Debug, Eq, FromPrimitive, Hash, MallocSizeOf, Parse, #[derive(
PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] Clone,
Copy,
Debug,
Eq,
FromPrimitive,
Hash,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[repr(u8)] #[repr(u8)]
pub enum Display { pub enum Display {
@ -200,7 +209,10 @@ impl Display {
pub fn is_ruby_type(&self) -> bool { pub fn is_ruby_type(&self) -> bool {
matches!( matches!(
*self, *self,
Display::Ruby | Display::RubyBase | Display::RubyText | Display::RubyBaseContainer | Display::Ruby |
Display::RubyBase |
Display::RubyText |
Display::RubyBaseContainer |
Display::RubyTextContainer Display::RubyTextContainer
) )
} }
@ -346,8 +358,7 @@ impl AnimationIterationCount {
} }
/// A value for the `animation-name` property. /// A value for the `animation-name` property.
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
ToComputedValue)]
#[value_info(other_values = "none")] #[value_info(other_values = "none")]
pub struct AnimationName(pub Option<KeyframesName>); pub struct AnimationName(pub Option<KeyframesName>);
@ -391,8 +402,18 @@ impl Parse for AnimationName {
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, #[derive(
SpecifiedValueInfo, ToComputedValue, ToCss)] Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum ScrollSnapType { pub enum ScrollSnapType {
None, None,
Mandatory, Mandatory,
@ -401,8 +422,18 @@ pub enum ScrollSnapType {
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, #[derive(
SpecifiedValueInfo, ToComputedValue, ToCss)] Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum OverscrollBehavior { pub enum OverscrollBehavior {
Auto, Auto,
Contain, Contain,
@ -411,15 +442,24 @@ pub enum OverscrollBehavior {
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, #[derive(
SpecifiedValueInfo, ToComputedValue, ToCss)] Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum OverflowClipBox { pub enum OverflowClipBox {
PaddingBox, PaddingBox,
ContentBox, ContentBox,
} }
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, #[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
ToComputedValue, ToCss)]
/// Provides a rendering hint to the user agent, /// Provides a rendering hint to the user agent,
/// stating what kinds of changes the author expects /// stating what kinds of changes the author expects
/// to perform on the element /// to perform on the element
@ -497,11 +537,11 @@ fn change_bits_for_maybe_property(ident: &str, context: &ParserContext) -> WillC
}; };
match id.as_shorthand() { match id.as_shorthand() {
Ok(shorthand) => { Ok(shorthand) => shorthand
shorthand.longhands().fold(WillChangeBits::empty(), |flags, p| { .longhands()
.fold(WillChangeBits::empty(), |flags, p| {
flags | change_bits_for_longhand(p) flags | change_bits_for_longhand(p)
}) }),
}
Err(PropertyDeclarationId::Longhand(longhand)) => change_bits_for_longhand(longhand), Err(PropertyDeclarationId::Longhand(longhand)) => change_bits_for_longhand(longhand),
Err(PropertyDeclarationId::Custom(..)) => WillChangeBits::empty(), Err(PropertyDeclarationId::Custom(..)) => WillChangeBits::empty(),
} }
@ -581,9 +621,8 @@ impl ToCss for TouchAction {
TouchAction::TOUCH_ACTION_NONE => dest.write_str("none"), TouchAction::TOUCH_ACTION_NONE => dest.write_str("none"),
TouchAction::TOUCH_ACTION_AUTO => dest.write_str("auto"), TouchAction::TOUCH_ACTION_AUTO => dest.write_str("auto"),
TouchAction::TOUCH_ACTION_MANIPULATION => dest.write_str("manipulation"), TouchAction::TOUCH_ACTION_MANIPULATION => dest.write_str("manipulation"),
_ if self.contains( _ if self
TouchAction::TOUCH_ACTION_PAN_X | TouchAction::TOUCH_ACTION_PAN_Y, .contains(TouchAction::TOUCH_ACTION_PAN_X | TouchAction::TOUCH_ACTION_PAN_Y) =>
) =>
{ {
dest.write_str("pan-x pan-y") dest.write_str("pan-x pan-y")
}, },
@ -756,8 +795,7 @@ impl Parse for Perspective {
return Ok(GenericPerspective::None); return Ok(GenericPerspective::None);
} }
Ok(GenericPerspective::Length(NonNegativeLength::parse( Ok(GenericPerspective::Length(NonNegativeLength::parse(
context, context, input,
input,
)?)) )?))
} }
} }
@ -789,7 +827,7 @@ impl ToCss for TransitionProperty {
TransitionProperty::Custom(ref name) => { TransitionProperty::Custom(ref name) => {
dest.write_str("--")?; dest.write_str("--")?;
serialize_atom_name(name, dest) serialize_atom_name(name, dest)
} },
TransitionProperty::Unsupported(ref i) => i.to_css(dest), TransitionProperty::Unsupported(ref i) => i.to_css(dest),
} }
} }
@ -805,21 +843,21 @@ impl Parse for TransitionProperty {
let id = match PropertyId::parse_ignoring_rule_type(&ident, context) { let id = match PropertyId::parse_ignoring_rule_type(&ident, context) {
Ok(id) => id, Ok(id) => id,
Err(..) => return Ok(TransitionProperty::Unsupported( Err(..) => {
CustomIdent::from_ident(location, ident, &["none"])?, return Ok(TransitionProperty::Unsupported(CustomIdent::from_ident(
)), location,
ident,
&["none"],
)?))
},
}; };
Ok(match id.as_shorthand() { Ok(match id.as_shorthand() {
Ok(s) => TransitionProperty::Shorthand(s), Ok(s) => TransitionProperty::Shorthand(s),
Err(longhand_or_custom) => { Err(longhand_or_custom) => match longhand_or_custom {
match longhand_or_custom { PropertyDeclarationId::Longhand(id) => TransitionProperty::Longhand(id),
PropertyDeclarationId::Longhand(id) => TransitionProperty::Longhand(id), PropertyDeclarationId::Custom(custom) => TransitionProperty::Custom(custom.clone()),
PropertyDeclarationId::Custom(custom) => { },
TransitionProperty::Custom(custom.clone())
}
}
}
}) })
} }
} }
@ -846,19 +884,19 @@ impl TransitionProperty {
Ok(match *self { Ok(match *self {
TransitionProperty::Shorthand(ShorthandId::All) => { TransitionProperty::Shorthand(ShorthandId::All) => {
::gecko_bindings::structs::nsCSSPropertyID::eCSSPropertyExtra_all_properties ::gecko_bindings::structs::nsCSSPropertyID::eCSSPropertyExtra_all_properties
} },
TransitionProperty::Shorthand(ref id) => id.to_nscsspropertyid(), TransitionProperty::Shorthand(ref id) => id.to_nscsspropertyid(),
TransitionProperty::Longhand(ref id) => id.to_nscsspropertyid(), TransitionProperty::Longhand(ref id) => id.to_nscsspropertyid(),
TransitionProperty::Custom(..) | TransitionProperty::Custom(..) | TransitionProperty::Unsupported(..) => return Err(()),
TransitionProperty::Unsupported(..) => return Err(()),
}) })
} }
} }
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, #[derive(
SpecifiedValueInfo, ToCss)] Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss,
)]
/// https://drafts.csswg.org/css-box/#propdef-float /// https://drafts.csswg.org/css-box/#propdef-float
pub enum Float { pub enum Float {
Left, Left,
@ -866,13 +904,14 @@ pub enum Float {
None, None,
// https://drafts.csswg.org/css-logical-props/#float-clear // https://drafts.csswg.org/css-logical-props/#float-clear
InlineStart, InlineStart,
InlineEnd InlineEnd,
} }
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, #[derive(
SpecifiedValueInfo, ToCss)] Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss,
)]
/// https://drafts.csswg.org/css-box/#propdef-clear /// https://drafts.csswg.org/css-box/#propdef-clear
pub enum Clear { pub enum Clear {
None, None,
@ -881,14 +920,15 @@ pub enum Clear {
Both, Both,
// https://drafts.csswg.org/css-logical-props/#float-clear // https://drafts.csswg.org/css-logical-props/#float-clear
InlineStart, InlineStart,
InlineEnd InlineEnd,
} }
/// https://drafts.csswg.org/css-ui/#propdef-resize /// https://drafts.csswg.org/css-ui/#propdef-resize
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, #[derive(
SpecifiedValueInfo, ToCss)] Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss,
)]
pub enum Resize { pub enum Resize {
None, None,
Both, Both,
@ -906,8 +946,19 @@ pub enum Resize {
/// NOTE(emilio): When changing this you may want to regenerate the C++ bindings /// NOTE(emilio): When changing this you may want to regenerate the C++ bindings
/// (see components/style/cbindgen.toml) /// (see components/style/cbindgen.toml)
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, #[derive(
SpecifiedValueInfo, ToCss, ToComputedValue)] Clone,
Copy,
Debug,
Eq,
Hash,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToCss,
ToComputedValue,
)]
#[repr(u8)] #[repr(u8)]
pub enum Appearance { pub enum Appearance {
/// No appearance at all. /// No appearance at all.

View file

@ -89,11 +89,11 @@ impl<'a, 'b: 'a, 'i: 'a> ::cssparser::ColorComponentParser<'i> for ColorComponen
}; };
Ok(AngleOrNumber::Angle { degrees }) Ok(AngleOrNumber::Angle { degrees })
} },
Token::Number { value, .. } => Ok(AngleOrNumber::Number { value }), Token::Number { value, .. } => Ok(AngleOrNumber::Number { value }),
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
input.parse_nested_block(|i| CalcNode::parse_angle_or_number(self.0, i)) input.parse_nested_block(|i| CalcNode::parse_angle_or_number(self.0, i))
} },
t => return Err(location.new_unexpected_token_error(t)), t => return Err(location.new_unexpected_token_error(t)),
} }
} }
@ -120,10 +120,10 @@ impl<'a, 'b: 'a, 'i: 'a> ::cssparser::ColorComponentParser<'i> for ColorComponen
Token::Number { value, .. } => Ok(NumberOrPercentage::Number { value }), Token::Number { value, .. } => Ok(NumberOrPercentage::Number { value }),
Token::Percentage { unit_value, .. } => { Token::Percentage { unit_value, .. } => {
Ok(NumberOrPercentage::Percentage { unit_value }) Ok(NumberOrPercentage::Percentage { unit_value })
} },
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
input.parse_nested_block(|i| CalcNode::parse_number_or_percentage(self.0, i)) input.parse_nested_block(|i| CalcNode::parse_number_or_percentage(self.0, i))
} },
t => return Err(location.new_unexpected_token_error(t)), t => return Err(location.new_unexpected_token_error(t)),
} }
} }
@ -169,10 +169,10 @@ impl Parse for Color {
Err(e.location.new_custom_error(StyleParseErrorKind::ValueError( Err(e.location.new_custom_error(StyleParseErrorKind::ValueError(
ValueParseErrorKind::InvalidColor(t), ValueParseErrorKind::InvalidColor(t),
))) )))
} },
_ => Err(e), _ => Err(e),
} }
} },
} }
} }
} }
@ -276,10 +276,10 @@ impl Color {
} }
return parse_hash_color(ident.as_bytes()) return parse_hash_color(ident.as_bytes())
.map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); .map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
} },
ref t => { ref t => {
return Err(location.new_unexpected_token_error(t.clone())); return Err(location.new_unexpected_token_error(t.clone()));
} },
}; };
if value < 0 { if value < 0 {
return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
@ -359,11 +359,11 @@ impl Color {
Keyword::MozVisitedhyperlinktext => pres_context.mVisitedLinkColor, Keyword::MozVisitedhyperlinktext => pres_context.mVisitedLinkColor,
}) })
}) })
} },
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
Color::InheritFromBodyQuirk => { Color::InheritFromBodyQuirk => {
_context.map(|context| ComputedColor::rgba(context.device().body_text_color())) _context.map(|context| ComputedColor::rgba(context.device().body_text_color()))
} },
} }
} }
} }

Some files were not shown because too many files have changed in this diff Show more