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.).
///
/// TODO(emilio): The animation object could be refcounted.
Keyframes(OpaqueNode, KeyframesAnimation, Atom, KeyframesAnimationState),
Keyframes(
OpaqueNode,
KeyframesAnimation,
Atom,
KeyframesAnimationState,
),
}
impl Animation {
@ -304,8 +309,7 @@ impl PropertyAnimation {
let duration = box_style.transition_duration_mod(transition_index);
match transition_property {
TransitionProperty::Custom(..) |
TransitionProperty::Unsupported(..) => result,
TransitionProperty::Custom(..) | TransitionProperty::Unsupported(..) => result,
TransitionProperty::Shorthand(ref shorthand_id) => shorthand_id
.longhands()
.filter_map(|longhand| {
@ -316,8 +320,7 @@ impl PropertyAnimation {
old_style,
new_style,
)
})
.collect(),
}).collect(),
TransitionProperty::Longhand(longhand_id) => {
let animation = PropertyAnimation::from_longhand(
longhand_id,
@ -455,8 +458,7 @@ pub fn start_transitions_if_applicable(
property_animation: property_animation,
},
/* is_expired = */ false,
))
.unwrap();
)).unwrap();
had_animations = true;
}
@ -505,7 +507,9 @@ where
Some(previous_style),
Some(previous_style),
font_metrics_provider,
CascadeMode::Unvisited { visited_rules: None },
CascadeMode::Unvisited {
visited_rules: None,
},
context.quirks_mode(),
/* rule_cache = */ None,
&mut Default::default(),
@ -596,8 +600,7 @@ where
expired: false,
cascade_style: new_style.clone(),
},
))
.unwrap();
)).unwrap();
had_animations = true;
}
}
@ -735,8 +738,7 @@ pub fn update_style_for_animation<E>(
} else {
None
}
})
.unwrap_or(animation.steps.len() - 1);
}).unwrap_or(animation.steps.len() - 1);
},
_ => 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_BITS: usize = 4;
const SHADOW_CASCADE_ORDER_MAX: u8 = (1 << SHADOW_CASCADE_ORDER_BITS) - 1;
const SHADOW_CASCADE_ORDER_MASK: u32 = (SHADOW_CASCADE_ORDER_MAX as u32) << SHADOW_CASCADE_ORDER_SHIFT;
const SHADOW_CASCADE_ORDER_MASK: u32 =
(SHADOW_CASCADE_ORDER_MAX as u32) << SHADOW_CASCADE_ORDER_SHIFT;
const CASCADE_LEVEL_SHIFT: usize = SOURCE_ORDER_BITS + SHADOW_CASCADE_ORDER_BITS;
const CASCADE_LEVEL_BITS: usize = 4;
@ -61,7 +62,8 @@ impl ApplicableDeclarationBits {
"Gotta find more bits!"
);
let mut bits = ::std::cmp::min(source_order, SOURCE_ORDER_MAX);
bits |= ((shadow_cascade_order & SHADOW_CASCADE_ORDER_MAX) as u32) << SHADOW_CASCADE_ORDER_SHIFT;
bits |= ((shadow_cascade_order & SHADOW_CASCADE_ORDER_MAX) as u32) <<
SHADOW_CASCADE_ORDER_SHIFT;
bits |= (cascade_level as u8 as u32) << CASCADE_LEVEL_SHIFT;
ApplicableDeclarationBits(bits)
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -59,7 +59,7 @@ impl From<ComputedColor> for StyleComplexColor {
mFgRatio: ratios.fg,
mTag: Tag::eComplex,
}
}
},
}
}
}
@ -70,11 +70,11 @@ impl From<StyleComplexColor> for ComputedColor {
Tag::eNumeric => {
debug_assert!(other.mBgRatio == 1. && other.mFgRatio == 0.);
GenericColor::Numeric(convert_nscolor_to_rgba(other.mColor))
}
},
Tag::eForeground => {
debug_assert!(other.mBgRatio == 0. && other.mFgRatio == 1.);
GenericColor::Foreground
}
},
Tag::eComplex => {
debug_assert!(other.mBgRatio != 1. || other.mFgRatio != 0.);
debug_assert!(other.mBgRatio != 0. || other.mFgRatio != 1.);
@ -85,7 +85,7 @@ impl From<StyleComplexColor> for ComputedColor {
fg: other.mFgRatio,
},
)
}
},
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.
///
/// Only for debugging purposes.
fn debug_list_attributes(&self) -> String { String::new() }
fn debug_list_attributes(&self) -> String {
String::new()
}
/// The ID attribute per this snapshot. Should only be called if
/// `has_attrs()` returns true.
@ -233,7 +235,8 @@ where
// :lang() needs to match using the closest ancestor xml:lang="" or
// lang="" attribtue from snapshots.
NonTSPseudoClass::Lang(ref lang_arg) => {
return self.element
return self
.element
.match_element_lang(Some(self.get_lang()), lang_arg);
},
@ -242,12 +245,14 @@ where
let flag = pseudo_class.state_flag();
if flag.is_empty() {
return self.element
return self
.element
.match_non_ts_pseudo_class(pseudo_class, context, &mut |_, _| {});
}
match self.snapshot().and_then(|s| s.state()) {
Some(snapshot_state) => snapshot_state.intersects(flag),
None => self.element
None => self
.element
.match_non_ts_pseudo_class(pseudo_class, context, &mut |_, _| {}),
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -375,8 +375,7 @@ impl ViewportRule {
Err((error, slice)) => {
let location = error.location;
let error = ContextualParseError::UnsupportedViewportDescriptorDeclaration(
slice,
error,
slice, error,
);
context.log_css_error(location, error);
},
@ -760,9 +759,9 @@ impl MaybeNew for ViewportConstraints {
Some(initial_viewport.$dimension.scale_by(value.0))
},
LengthOrPercentageOrAuto::Auto => None,
LengthOrPercentageOrAuto::Calc(ref calc) => calc.to_computed_value(
&context,
).to_used_value(Some(initial_viewport.$dimension)),
LengthOrPercentageOrAuto::Calc(ref calc) => calc
.to_computed_value(&context)
.to_used_value(Some(initial_viewport.$dimension)),
},
ViewportLength::ExtendToZoom => {
// $extend_to will be 'None' if 'extend-to-zoom' is 'auto'

View file

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

View file

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

View file

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

View file

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

View file

@ -399,7 +399,10 @@ where
{
#[inline]
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())
}
}

View file

@ -15,7 +15,9 @@ use values::distance::{ComputeSquaredDistance, SquaredDistance};
/// A computed angle.
#[animate(fallback = "Self::animate_fallback")]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd, ToAnimatedZero, ToCss)]
#[derive(
Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd, ToAnimatedZero, ToCss,
)]
pub enum Angle {
/// An angle with degree unit.
#[css(dimension)]
@ -73,7 +75,9 @@ impl Angle {
/// <https://drafts.csswg.org/css-transitions/#animtype-number>
#[inline]
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)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToCss)]
#[derive(
Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss,
)]
/// A computed value for the `float` property.
pub enum Float {
Left,
Right,
None
None,
}
impl ToComputedValue for SpecifiedFloat {
@ -52,7 +53,9 @@ impl ToComputedValue for SpecifiedFloat {
// https://drafts.csswg.org/css-logical-props/#float-clear
match *self {
SpecifiedFloat::InlineStart => {
context.rule_cache_conditions.borrow_mut()
context
.rule_cache_conditions
.borrow_mut()
.set_writing_mode_dependency(context.builder.writing_mode);
if ltr {
Float::Left
@ -61,7 +64,9 @@ impl ToComputedValue for SpecifiedFloat {
}
},
SpecifiedFloat::InlineEnd => {
context.rule_cache_conditions.borrow_mut()
context
.rule_cache_conditions
.borrow_mut()
.set_writing_mode_dependency(context.builder.writing_mode);
if ltr {
Float::Right
@ -71,7 +76,7 @@ impl ToComputedValue for SpecifiedFloat {
},
SpecifiedFloat::Left => Float::Left,
SpecifiedFloat::Right => Float::Right,
SpecifiedFloat::None => Float::None
SpecifiedFloat::None => Float::None,
}
}
@ -80,21 +85,22 @@ impl ToComputedValue for SpecifiedFloat {
match *computed {
Float::Left => SpecifiedFloat::Left,
Float::Right => SpecifiedFloat::Right,
Float::None => SpecifiedFloat::None
Float::None => SpecifiedFloat::None,
}
}
}
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToCss)]
#[derive(
Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss,
)]
/// A computed value for the `clear` property.
pub enum Clear {
None,
Left,
Right,
Both
Both,
}
impl ToComputedValue for SpecifiedClear {
@ -106,7 +112,9 @@ impl ToComputedValue for SpecifiedClear {
// https://drafts.csswg.org/css-logical-props/#float-clear
match *self {
SpecifiedClear::InlineStart => {
context.rule_cache_conditions.borrow_mut()
context
.rule_cache_conditions
.borrow_mut()
.set_writing_mode_dependency(context.builder.writing_mode);
if ltr {
Clear::Left
@ -115,7 +123,9 @@ impl ToComputedValue for SpecifiedClear {
}
},
SpecifiedClear::InlineEnd => {
context.rule_cache_conditions.borrow_mut()
context
.rule_cache_conditions
.borrow_mut()
.set_writing_mode_dependency(context.builder.writing_mode);
if ltr {
Clear::Right
@ -126,7 +136,7 @@ impl ToComputedValue for SpecifiedClear {
SpecifiedClear::None => Clear::None,
SpecifiedClear::Left => Clear::Left,
SpecifiedClear::Right => Clear::Right,
SpecifiedClear::Both => Clear::Both
SpecifiedClear::Both => Clear::Both,
}
}
@ -160,23 +170,27 @@ impl ToComputedValue for specified::Resize {
let is_vertical = context.style().writing_mode.is_vertical();
match self {
specified::Resize::Inline => {
context.rule_cache_conditions.borrow_mut()
context
.rule_cache_conditions
.borrow_mut()
.set_writing_mode_dependency(context.builder.writing_mode);
if is_vertical {
Resize::Vertical
} else {
Resize::Horizontal
}
}
},
specified::Resize::Block => {
context.rule_cache_conditions.borrow_mut()
context
.rule_cache_conditions
.borrow_mut()
.set_writing_mode_dependency(context.builder.writing_mode);
if is_vertical {
Resize::Horizontal
} else {
Resize::Vertical
}
}
},
specified::Resize::None => Resize::None,
specified::Resize::Both => Resize::Both,
specified::Resize::Horizontal => Resize::Horizontal,

View file

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

View file

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

View file

@ -7,4 +7,4 @@
/// A computed offset-path. The computed value is as specified value.
///
/// 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.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, Default,
MallocSizeOf, PartialEq, PartialOrd, SpecifiedValueInfo,
ToAnimatedValue, ToAnimatedZero, ToComputedValue)]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
Default,
MallocSizeOf,
PartialEq,
PartialOrd,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
)]
pub struct Percentage(pub CSSFloat);
impl Percentage {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -7,8 +7,7 @@
/// A generic value for scroll snap points.
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[derive(Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToComputedValue,
ToCss)]
#[derive(Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
pub enum ScrollSnapPoint<LengthOrPercentage> {
/// `none`
None,

View file

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

View file

@ -145,7 +145,7 @@ pub struct PaintWorklet {
pub arguments: Vec<Arc<custom_properties::SpecifiedValue>>,
}
impl ::style_traits::SpecifiedValueInfo for PaintWorklet { }
impl ::style_traits::SpecifiedValueInfo for PaintWorklet {}
impl ToCss for PaintWorklet {
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);`
#[allow(missing_docs)]
#[css(comma, function)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue, ToCss)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
pub struct MozImageRect<NumberOrPercentage, MozImageRectUrl> {
pub url: MozImageRectUrl,
pub top: NumberOrPercentage,

View file

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

View file

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

View file

@ -13,8 +13,17 @@ use values::animated::ToAnimatedValue;
/// A generic size, for `border-*-radius` longhand properties, or
/// `border-spacing`.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq,
ToAnimatedZero, ToComputedValue)]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
ToAnimatedZero,
ToComputedValue,
)]
pub struct Size<L>(pub Size2D<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>
#[animation(no_bound(UrlPaintServer))]
#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq,
SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss)]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToComputedValue,
ToCss,
)]
pub struct SVGPaint<ColorType, UrlPaintServer> {
/// The paint source
pub kind: SVGPaintKind<ColorType, UrlPaintServer>,
@ -31,9 +41,19 @@ pub struct SVGPaint<ColorType, UrlPaintServer> {
/// to have a fallback, Gecko lets the context
/// properties have a fallback as well.
#[animation(no_bound(UrlPaintServer))]
#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq,
SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue,
ToCss)]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum SVGPaintKind<ColorType, UrlPaintServer> {
/// `none`
#[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.
/// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)]
#[derive(
Clone,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number> {
/// <length> | <percentage>
LengthOrPercentage(LengthOrPercentage),
@ -191,9 +221,19 @@ impl<LengthOrPercentageType: Parse, NumberType: Parse> Parse
}
/// An SVG length value supports `context-value` in addition to length.
#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq,
SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue,
ToCss)]
#[derive(
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum SVGLength<LengthType> {
/// `<length> | <percentage> | <number>`
Length(LengthType),
@ -202,23 +242,38 @@ pub enum SVGLength<LengthType> {
}
/// Generic value for stroke-dasharray.
#[derive(Clone, Debug, MallocSizeOf, PartialEq,
SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss)]
#[derive(
Clone,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToComputedValue,
ToCss,
)]
pub enum SVGStrokeDashArray<LengthType> {
/// `[ <length> | <percentage> | <number> ]#`
#[css(comma)]
Values(
#[css(if_empty = "none", iterable)]
Vec<LengthType>,
),
Values(#[css(if_empty = "none", iterable)] Vec<LengthType>),
/// `context-value`
ContextValue,
}
/// An SVG opacity value accepts `context-{fill,stroke}-opacity` in
/// addition to opacity value.
#[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq,
SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)]
#[derive(
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum SVGOpacity<OpacityType> {
/// `<opacity-value>`
Opacity(OpacityType),

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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