Bug 1792615 - Run "cargo +nightly fmt" for style components in servo. r=emilio

The directories changed:
* servo/components/selectors/
* servo/components/style/
* servo/components/style_derive/
* servo/ports/geckolib/

Per review request, disable rustfmt in `components_to_transform_3d_matrix()` to
preserve the format for a call to `Transform3D::new`.

My mozilla-central is at
https://hg.mozilla.org/mozilla-central/rev/d1ae84015c22f2034435b47194fdced878072035

My nightly rust is 1.66.0-nightly (8b705839c 2022-09-26).

Differential Revision: https://phabricator.services.mozilla.com/D158234
This commit is contained in:
Ting-Yu Lin
2022-09-28 07:10:52 +00:00
parent c9a338530f
commit a6d1bf0cc4
64 changed files with 768 additions and 570 deletions

View File

@@ -326,9 +326,7 @@ where
Component::NonTSPseudoClass(..) => { Component::NonTSPseudoClass(..) => {
specificity.class_like_selectors += 1; specificity.class_like_selectors += 1;
}, },
Component::Negation(ref list) | Component::Negation(ref list) | Component::Is(ref list) | Component::Has(ref list) => {
Component::Is(ref list) |
Component::Has(ref list) => {
// https://drafts.csswg.org/selectors/#specificity-rules: // https://drafts.csswg.org/selectors/#specificity-rules:
// //
// The specificity of an :is(), :not(), or :has() pseudo-class // The specificity of an :is(), :not(), or :has() pseudo-class

View File

@@ -317,8 +317,7 @@ where
debug_assert_eq!(next_sequence, Combinator::PseudoElement); debug_assert_eq!(next_sequence, Combinator::PseudoElement);
} }
let result = let result = matches_complex_selector_internal(iter, element, context, Rightmost::Yes);
matches_complex_selector_internal(iter, element, context, Rightmost::Yes);
matches!(result, SelectorMatchingResult::Matched) matches!(result, SelectorMatchingResult::Matched)
} }
@@ -478,19 +477,13 @@ where
selector_iter, element selector_iter, element
); );
let matches_compound_selector = matches_compound_selector( let matches_compound_selector =
&mut selector_iter, matches_compound_selector(&mut selector_iter, element, context, rightmost);
element,
context,
rightmost,
);
let combinator = selector_iter.next_sequence(); let combinator = selector_iter.next_sequence();
if combinator.map_or(false, |c| c.is_sibling()) { if combinator.map_or(false, |c| c.is_sibling()) {
if context.needs_selector_flags() { if context.needs_selector_flags() {
element.apply_selector_flags( element.apply_selector_flags(ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS);
ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS
);
} }
} }
@@ -528,7 +521,8 @@ where
visited_handling = VisitedHandlingMode::AllLinksUnvisited; visited_handling = VisitedHandlingMode::AllLinksUnvisited;
} }
element = match next_element_for_combinator(&element, combinator, &selector_iter, &context) { element = match next_element_for_combinator(&element, combinator, &selector_iter, &context)
{
None => return candidate_not_found, None => return candidate_not_found,
Some(next_element) => next_element, Some(next_element) => next_element,
}; };
@@ -768,9 +762,9 @@ where
Component::Slotted(ref selector) => { Component::Slotted(ref selector) => {
// <slots> are never flattened tree slottables. // <slots> are never flattened tree slottables.
!element.is_html_slot_element() && !element.is_html_slot_element() &&
context.shared.nest(|context| { context
matches_complex_selector(selector.iter(), element, context) .shared
}) .nest(|context| matches_complex_selector(selector.iter(), element, context))
}, },
Component::PseudoElement(ref pseudo) => { Component::PseudoElement(ref pseudo) => {
element.match_pseudo_element(pseudo, context.shared) element.match_pseudo_element(pseudo, context.shared)
@@ -785,7 +779,10 @@ where
}, },
Component::NonTSPseudoClass(ref pc) => { Component::NonTSPseudoClass(ref pc) => {
if let Some((ref rightmost, ref iter)) = context.quirks_data { if let Some((ref rightmost, ref iter)) = context.quirks_data {
if pc.is_active_or_hover() && !element.is_link() && hover_and_active_quirk_applies(iter, context.shared, *rightmost) { if pc.is_active_or_hover() &&
!element.is_link() &&
hover_and_active_quirk_applies(iter, context.shared, *rightmost)
{
return false; return false;
} }
} }
@@ -794,7 +791,8 @@ where
Component::FirstChild => matches_first_child(element, context.shared), Component::FirstChild => matches_first_child(element, context.shared),
Component::LastChild => matches_last_child(element, context.shared), Component::LastChild => matches_last_child(element, context.shared),
Component::OnlyChild => { Component::OnlyChild => {
matches_first_child(element, context.shared) && matches_last_child(element, context.shared) matches_first_child(element, context.shared) &&
matches_last_child(element, context.shared)
}, },
Component::Root => element.is_root(), Component::Root => element.is_root(),
Component::Empty => { Component::Empty => {
@@ -809,9 +807,9 @@ where
.shadow_host() .shadow_host()
.map_or(false, |host| host == element.opaque()) && .map_or(false, |host| host == element.opaque()) &&
selector.as_ref().map_or(true, |selector| { selector.as_ref().map_or(true, |selector| {
context.shared.nest(|context| { context
matches_complex_selector(selector.iter(), element, context) .shared
}) .nest(|context| matches_complex_selector(selector.iter(), element, context))
}) })
}, },
Component::Scope => match context.shared.scope_element { Component::Scope => match context.shared.scope_element {
@@ -856,9 +854,9 @@ where
} }
true true
}), }),
Component::Has(ref list) => context.shared.nest(|context| { Component::Has(ref list) => context
has_children_matching(list, element, context) .shared
}), .nest(|context| has_children_matching(list, element, context)),
Component::Combinator(_) => unsafe { Component::Combinator(_) => unsafe {
debug_unreachable!("Shouldn't try to selector-match combinators") debug_unreachable!("Shouldn't try to selector-match combinators")
}, },

View File

@@ -490,12 +490,18 @@ where
Component::Class(ref class) if quirks_mode != QuirksMode::Quirks => { Component::Class(ref class) if quirks_mode != QuirksMode::Quirks => {
class.precomputed_hash() class.precomputed_hash()
}, },
Component::AttributeInNoNamespace { ref local_name, .. } if Impl::should_collect_attr_hash(local_name) => { Component::AttributeInNoNamespace { ref local_name, .. }
if Impl::should_collect_attr_hash(local_name) =>
{
// AttributeInNoNamespace is only used when local_name == // AttributeInNoNamespace is only used when local_name ==
// local_name_lower. // local_name_lower.
local_name.precomputed_hash() local_name.precomputed_hash()
}, },
Component::AttributeInNoNamespaceExists { ref local_name, ref local_name_lower, .. } => { Component::AttributeInNoNamespaceExists {
ref local_name,
ref local_name_lower,
..
} => {
// Only insert the local-name into the filter if it's all // Only insert the local-name into the filter if it's all
// lowercase. Otherwise we would need to test both hashes, and // lowercase. Otherwise we would need to test both hashes, and
// our data structures aren't really set up for that. // our data structures aren't really set up for that.
@@ -505,7 +511,9 @@ where
local_name.precomputed_hash() local_name.precomputed_hash()
}, },
Component::AttributeOther(ref selector) => { Component::AttributeOther(ref selector) => {
if selector.local_name != selector.local_name_lower || !Impl::should_collect_attr_hash(&selector.local_name) { if selector.local_name != selector.local_name_lower ||
!Impl::should_collect_attr_hash(&selector.local_name)
{
continue; continue;
} }
selector.local_name.precomputed_hash() selector.local_name.precomputed_hash()
@@ -1912,7 +1920,7 @@ where
_ if !in_attr_selector => { _ if !in_attr_selector => {
input.reset(&after_star); input.reset(&after_star);
default_namespace(None) default_namespace(None)
} },
result => { result => {
let t = result?; let t = result?;
Err(after_star Err(after_star

View File

@@ -90,7 +90,8 @@ impl PropertyAnimation {
// and whether the iteration is reversed. For now, we skip this calculation // and whether the iteration is reversed. For now, we skip this calculation
// by treating as if the flag is unset at all times. // by treating as if the flag is unset at all times.
// https://drafts.csswg.org/css-easing/#step-timing-function-algo // https://drafts.csswg.org/css-easing/#step-timing-function-algo
self.timing_function.calculate_output(progress, BeforeFlag::Unset, epsilon) self.timing_function
.calculate_output(progress, BeforeFlag::Unset, epsilon)
} }
/// Update the given animation at a given point of progress. /// Update the given animation at a given point of progress.

View File

@@ -42,7 +42,10 @@ pub struct CascadePriority {
layer_order: LayerOrder, layer_order: LayerOrder,
} }
const_assert_eq!(std::mem::size_of::<CascadePriority>(), std::mem::size_of::<u32>()); const_assert_eq!(
std::mem::size_of::<CascadePriority>(),
std::mem::size_of::<u32>()
);
impl PartialOrd for CascadePriority { impl PartialOrd for CascadePriority {
#[inline] #[inline]

View File

@@ -126,7 +126,10 @@ static CHROME_ENVIRONMENT_VARIABLES: [EnvironmentVariable; 6] = [
GTKCSDMaximizeButtonPosition, GTKCSDMaximizeButtonPosition,
integer integer
), ),
make_variable!(atom!("-moz-content-preferred-color-scheme"), get_content_preferred_color_scheme), make_variable!(
atom!("-moz-content-preferred-color-scheme"),
get_content_preferred_color_scheme
),
]; ];
impl CssEnvironment { impl CssEnvironment {
@@ -783,7 +786,11 @@ impl<'a> CustomPropertiesBuilder<'a> {
/// (meaning we should use the inherited value). /// (meaning we should use the inherited value).
/// ///
/// It does cycle dependencies removal at the same time as substitution. /// It does cycle dependencies removal at the same time as substitution.
fn substitute_all(custom_properties_map: &mut CustomPropertiesMap, seen: &PrecomputedHashSet<&Name>, device: &Device) { fn substitute_all(
custom_properties_map: &mut CustomPropertiesMap,
seen: &PrecomputedHashSet<&Name>,
device: &Device,
) {
// The cycle dependencies removal in this function is a variant // The cycle dependencies removal in this function is a variant
// of Tarjan's algorithm. It is mostly based on the pseudo-code // of Tarjan's algorithm. It is mostly based on the pseudo-code
// listed in // listed in

View File

@@ -19,7 +19,9 @@ use crate::values::specified::font::SpecifiedFontFeatureSettings;
use crate::values::specified::font::SpecifiedFontStyle; use crate::values::specified::font::SpecifiedFontStyle;
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use crate::values::specified::font::SpecifiedFontVariationSettings; use crate::values::specified::font::SpecifiedFontVariationSettings;
use crate::values::specified::font::{AbsoluteFontWeight, FontStretch as SpecifiedFontStretch, MetricsOverride}; use crate::values::specified::font::{
AbsoluteFontWeight, FontStretch as SpecifiedFontStretch, MetricsOverride,
};
use crate::values::specified::url::SpecifiedUrl; use crate::values::specified::url::SpecifiedUrl;
use crate::values::specified::{Angle, NonNegativePercentage}; use crate::values::specified::{Angle, NonNegativePercentage};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
@@ -477,8 +479,9 @@ impl<'a> FontFace<'a> {
// We support only opentype fonts and truetype is an alias for // We support only opentype fonts and truetype is an alias for
// that format. Sources without format hints need to be // that format. Sources without format hints need to be
// downloaded in case we support them. // downloaded in case we support them.
url_source.format_hint.as_ref().map_or(true, url_source.format_hint.as_ref().map_or(true, |hint| {
|hint| hint == "truetype" || hint == "opentype" || hint == "woff") hint == "truetype" || hint == "opentype" || hint == "woff"
})
} else { } else {
true true
} }
@@ -547,7 +550,8 @@ impl Parse for Source {
}; };
// Parse optional tech() // Parse optional tech()
let tech_flags = if static_prefs::pref!("layout.css.font-tech.enabled") && input let tech_flags = if static_prefs::pref!("layout.css.font-tech.enabled") &&
input
.try_parse(|input| input.expect_function_matching("tech")) .try_parse(|input| input.expect_function_matching("tech"))
.is_ok() .is_ok()
{ {
@@ -556,7 +560,11 @@ impl Parse for Source {
FontFaceSourceTechFlags::empty() FontFaceSourceTechFlags::empty()
}; };
Ok(Source::Url(UrlSource { url, format_hint, tech_flags })) Ok(Source::Url(UrlSource {
url,
format_hint,
tech_flags,
}))
} }
} }

View File

@@ -6,10 +6,10 @@
use crate::gecko_bindings::bindings; use crate::gecko_bindings::bindings;
use crate::gecko_bindings::structs; use crate::gecko_bindings::structs;
use crate::media_queries::{Device, MediaType};
use crate::queries::feature::{AllowsRanges, Evaluator, FeatureFlags, QueryFeatureDescription}; use crate::queries::feature::{AllowsRanges, Evaluator, FeatureFlags, QueryFeatureDescription};
use crate::queries::values::Orientation; use crate::queries::values::Orientation;
use crate::media_queries::{Device, MediaType}; use crate::values::computed::{CSSPixelLength, Context, Ratio, Resolution};
use crate::values::computed::{Context, CSSPixelLength, Ratio, Resolution};
use app_units::Au; use app_units::Au;
use euclid::default::Size2D; use euclid::default::Size2D;
@@ -89,7 +89,11 @@ pub enum DisplayMode {
/// https://w3c.github.io/manifest/#the-display-mode-media-feature /// https://w3c.github.io/manifest/#the-display-mode-media-feature
fn eval_display_mode(context: &Context, query_value: Option<DisplayMode>) -> bool { fn eval_display_mode(context: &Context, query_value: Option<DisplayMode>) -> bool {
match query_value { match query_value {
Some(v) => v == unsafe { bindings::Gecko_MediaFeatures_GetDisplayMode(context.device().document()) }, Some(v) => {
v == unsafe {
bindings::Gecko_MediaFeatures_GetDisplayMode(context.device().document())
}
},
None => true, None => true,
} }
} }
@@ -139,7 +143,8 @@ fn eval_monochrome(context: &Context) -> u32 {
/// https://drafts.csswg.org/mediaqueries-4/#resolution /// https://drafts.csswg.org/mediaqueries-4/#resolution
fn eval_resolution(context: &Context) -> Resolution { fn eval_resolution(context: &Context) -> Resolution {
let resolution_dppx = unsafe { bindings::Gecko_MediaFeatures_GetResolution(context.device().document()) }; let resolution_dppx =
unsafe { bindings::Gecko_MediaFeatures_GetResolution(context.device().document()) };
Resolution::from_dppx(resolution_dppx) Resolution::from_dppx(resolution_dppx)
} }
@@ -172,7 +177,10 @@ pub enum DynamicRange {
} }
/// https://drafts.csswg.org/mediaqueries-5/#prefers-reduced-motion /// https://drafts.csswg.org/mediaqueries-5/#prefers-reduced-motion
fn eval_prefers_reduced_motion(context: &Context, query_value: Option<PrefersReducedMotion>) -> bool { fn eval_prefers_reduced_motion(
context: &Context,
query_value: Option<PrefersReducedMotion>,
) -> bool {
let prefers_reduced = let prefers_reduced =
unsafe { bindings::Gecko_MediaFeatures_PrefersReducedMotion(context.device().document()) }; unsafe { bindings::Gecko_MediaFeatures_PrefersReducedMotion(context.device().document()) };
let query_value = match query_value { let query_value = match query_value {
@@ -317,8 +325,9 @@ fn do_eval_prefers_color_scheme(
use_content: bool, use_content: bool,
query_value: Option<PrefersColorScheme>, query_value: Option<PrefersColorScheme>,
) -> bool { ) -> bool {
let prefers_color_scheme = let prefers_color_scheme = unsafe {
unsafe { bindings::Gecko_MediaFeatures_PrefersColorScheme(context.device().document(), use_content) }; bindings::Gecko_MediaFeatures_PrefersColorScheme(context.device().document(), use_content)
};
match query_value { match query_value {
Some(v) => prefers_color_scheme == v, Some(v) => prefers_color_scheme == v,
None => true, None => true,
@@ -867,7 +876,13 @@ pub static MEDIA_FEATURES: [QueryFeatureDescription; 61] = [
GTKCSDReversedPlacement GTKCSDReversedPlacement
), ),
lnf_int_feature!(atom!("-moz-system-dark-theme"), SystemUsesDarkTheme), lnf_int_feature!(atom!("-moz-system-dark-theme"), SystemUsesDarkTheme),
bool_pref_feature!(atom!("-moz-box-flexbox-emulation"), "layout.css.moz-box-flexbox-emulation.enabled"), bool_pref_feature!(
atom!("-moz-box-flexbox-emulation"),
"layout.css.moz-box-flexbox-emulation.enabled"
),
// media query for MathML Core's implementation of maction/semantics // media query for MathML Core's implementation of maction/semantics
bool_pref_feature!(atom!("-moz-mathml-core-maction-and-semantics"), "mathml.legacy_maction_and_semantics_implementations.disabled"), bool_pref_feature!(
atom!("-moz-mathml-core-maction-and-semantics"),
"mathml.legacy_maction_and_semantics_implementations.disabled"
),
]; ];

View File

@@ -13,8 +13,8 @@ use crate::gecko_bindings::structs;
use crate::media_queries::MediaType; use crate::media_queries::MediaType;
use crate::properties::ComputedValues; use crate::properties::ComputedValues;
use crate::string_cache::Atom; use crate::string_cache::Atom;
use crate::values::computed::{ColorScheme, Length};
use crate::values::computed::font::GenericFontFamily; use crate::values::computed::font::GenericFontFamily;
use crate::values::computed::{ColorScheme, Length};
use crate::values::specified::color::SystemColor; use crate::values::specified::color::SystemColor;
use crate::values::specified::font::FONT_MEDIUM_PX; use crate::values::specified::font::FONT_MEDIUM_PX;
use crate::values::specified::ViewportVariant; use crate::values::specified::ViewportVariant;
@@ -172,9 +172,7 @@ impl Device {
/// Gets the base size given a generic font family and a language. /// Gets the base size given a generic font family and a language.
pub fn base_size_for_generic(&self, language: &Atom, generic: GenericFontFamily) -> Length { pub fn base_size_for_generic(&self, language: &Atom, generic: GenericFontFamily) -> Length {
unsafe { unsafe { bindings::Gecko_GetBaseSize(self.document(), language.as_ptr(), generic) }
bindings::Gecko_GetBaseSize(self.document(), language.as_ptr(), generic)
}
} }
/// Queries font metrics /// Queries font metrics

View File

@@ -51,7 +51,8 @@ unsafe fn get_class_or_part_from_attr(attr: &structs::nsAttrValue) -> Class {
.__bindgen_anon_1 .__bindgen_anon_1
.mAtomArray .mAtomArray
.as_ref(); .as_ref();
let array = (*attr_array).mArray.as_ptr() as *const structs::nsTArray<structs::RefPtr<nsAtom>>; let array =
(*attr_array).mArray.as_ptr() as *const structs::nsTArray<structs::RefPtr<nsAtom>>;
return Class::More(&**array); return Class::More(&**array);
} }
debug_assert_eq!(base_type, structs::nsAttrValue_ValueBaseType_eStringBase); debug_assert_eq!(base_type, structs::nsAttrValue_ValueBaseType_eStringBase);

View File

@@ -19,7 +19,6 @@ use crate::author_styles::AuthorStyles;
use crate::context::{PostAnimationTasks, QuirksMode, SharedStyleContext, UpdateAnimationsTasks}; use crate::context::{PostAnimationTasks, QuirksMode, SharedStyleContext, UpdateAnimationsTasks};
use crate::data::ElementData; use crate::data::ElementData;
use crate::dom::{LayoutIterator, NodeInfo, OpaqueNode, TDocument, TElement, TNode, TShadowRoot}; use crate::dom::{LayoutIterator, NodeInfo, OpaqueNode, TDocument, TElement, TNode, TShadowRoot};
use dom::{DocumentState, ElementState};
use crate::gecko::data::GeckoStyleSheet; use crate::gecko::data::GeckoStyleSheet;
use crate::gecko::selector_parser::{NonTSPseudoClass, PseudoElement, SelectorImpl}; use crate::gecko::selector_parser::{NonTSPseudoClass, PseudoElement, SelectorImpl};
use crate::gecko::snapshot_helpers; use crate::gecko::snapshot_helpers;
@@ -67,8 +66,9 @@ use crate::values::{AtomIdent, AtomString};
use crate::CaseSensitivityExt; use crate::CaseSensitivityExt;
use crate::LocalName; use crate::LocalName;
use app_units::Au; use app_units::Au;
use euclid::default::Size2D;
use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut}; use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut};
use dom::{DocumentState, ElementState};
use euclid::default::Size2D;
use fxhash::FxHashMap; use fxhash::FxHashMap;
use selectors::attr::{AttrSelectorOperation, AttrSelectorOperator}; use selectors::attr::{AttrSelectorOperation, AttrSelectorOperator};
use selectors::attr::{CaseSensitivity, NamespaceConstraint}; use selectors::attr::{CaseSensitivity, NamespaceConstraint};
@@ -77,11 +77,11 @@ use selectors::matching::{ElementSelectorFlags, MatchingContext};
use selectors::sink::Push; use selectors::sink::Push;
use selectors::{Element, OpaqueElement}; use selectors::{Element, OpaqueElement};
use servo_arc::{Arc, ArcBorrow, RawOffsetArc}; use servo_arc::{Arc, ArcBorrow, RawOffsetArc};
use std::sync::atomic::{AtomicU32, Ordering};
use std::fmt; use std::fmt;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::mem; use std::mem;
use std::ptr; use std::ptr;
use std::sync::atomic::{AtomicU32, Ordering};
#[inline] #[inline]
fn elements_with_id<'a, 'le>( fn elements_with_id<'a, 'le>(
@@ -275,16 +275,15 @@ impl<'ln> GeckoNode<'ln> {
#[allow(dead_code)] #[allow(dead_code)]
fn static_assert() { fn static_assert() {
let _: [u8; std::mem::size_of::<Cell<u32>>()] = [0u8; std::mem::size_of::<AtomicU32>()]; let _: [u8; std::mem::size_of::<Cell<u32>>()] = [0u8; std::mem::size_of::<AtomicU32>()];
let _: [u8; std::mem::align_of::<Cell<u32>>()] = [0u8; std::mem::align_of::<AtomicU32>()]; let _: [u8; std::mem::align_of::<Cell<u32>>()] =
[0u8; std::mem::align_of::<AtomicU32>()];
} }
// Rust doesn't provide standalone atomic functions like GCC/clang do // Rust doesn't provide standalone atomic functions like GCC/clang do
// (via the atomic intrinsics) or via std::atomic_ref, but it guarantees // (via the atomic intrinsics) or via std::atomic_ref, but it guarantees
// that the memory representation of u32 and AtomicU32 matches: // that the memory representation of u32 and AtomicU32 matches:
// https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU32.html // https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU32.html
unsafe { unsafe { std::mem::transmute::<&Cell<u32>, &AtomicU32>(flags) }
std::mem::transmute::<&Cell<u32>, &AtomicU32>(flags)
}
} }
#[inline] #[inline]
@@ -677,12 +676,16 @@ impl<'le> GeckoElement<'le> {
#[inline] #[inline]
fn set_flags(&self, flags: u32) { fn set_flags(&self, flags: u32) {
self.as_node().flags_atomic().fetch_or(flags, Ordering::Relaxed); self.as_node()
.flags_atomic()
.fetch_or(flags, Ordering::Relaxed);
} }
#[inline] #[inline]
unsafe fn unset_flags(&self, flags: u32) { unsafe fn unset_flags(&self, flags: u32) {
self.as_node().flags_atomic().fetch_and(!flags, Ordering::Relaxed); self.as_node()
.flags_atomic()
.fetch_and(!flags, Ordering::Relaxed);
} }
/// Returns true if this element has descendants for lazy frame construction. /// Returns true if this element has descendants for lazy frame construction.
@@ -1044,7 +1047,14 @@ impl<'le> TElement for GeckoElement<'le> {
} }
unsafe { unsafe {
let frame = self.0._base._base._base.__bindgen_anon_1.mPrimaryFrame.as_ref(); let frame = self
.0
._base
._base
._base
.__bindgen_anon_1
.mPrimaryFrame
.as_ref();
if frame.is_null() { if frame.is_null() {
return Size2D::zero(); return Size2D::zero();
} }

View File

@@ -11,7 +11,9 @@ use crate::invalidation::element::invalidator::{Invalidation, InvalidationProces
use crate::invalidation::element::state_and_attributes; use crate::invalidation::element::state_and_attributes;
use crate::stylist::CascadeData; use crate::stylist::CascadeData;
use dom::DocumentState; use dom::DocumentState;
use selectors::matching::{MatchingContext, MatchingMode, QuirksMode, VisitedHandlingMode, NeedsSelectorFlags}; use selectors::matching::{
MatchingContext, MatchingMode, NeedsSelectorFlags, QuirksMode, VisitedHandlingMode,
};
/// A struct holding the members necessary to invalidate document state /// A struct holding the members necessary to invalidate document state
/// selectors. /// selectors.

View File

@@ -19,7 +19,9 @@ use crate::stylesheets::origin::OriginSet;
use crate::{Atom, WeakAtom}; use crate::{Atom, WeakAtom};
use dom::ElementState; use dom::ElementState;
use selectors::attr::CaseSensitivity; use selectors::attr::CaseSensitivity;
use selectors::matching::{matches_selector, MatchingContext, MatchingMode, VisitedHandlingMode, NeedsSelectorFlags}; use selectors::matching::{
matches_selector, MatchingContext, MatchingMode, NeedsSelectorFlags, VisitedHandlingMode,
};
use selectors::NthIndexCache; use selectors::NthIndexCache;
use smallvec::SmallVec; use smallvec::SmallVec;
@@ -410,10 +412,7 @@ where
self.collect_state_dependencies(&map.state_affecting_selectors) self.collect_state_dependencies(&map.state_affecting_selectors)
} }
fn collect_state_dependencies( fn collect_state_dependencies(&mut self, map: &'selectors SelectorMap<StateDependency>) {
&mut self,
map: &'selectors SelectorMap<StateDependency>,
) {
if self.state_changes.is_empty() { if self.state_changes.is_empty() {
return; return;
} }

View File

@@ -18,8 +18,8 @@ use crate::shared_lock::SharedRwLockReadGuard;
use crate::stylesheets::{CssRule, StylesheetInDocument}; use crate::stylesheets::{CssRule, StylesheetInDocument};
use crate::stylesheets::{EffectiveRules, EffectiveRulesIterator}; use crate::stylesheets::{EffectiveRules, EffectiveRulesIterator};
use crate::values::AtomIdent; use crate::values::AtomIdent;
use crate::{Atom, ShrinkIfNeeded};
use crate::LocalName as SelectorLocalName; use crate::LocalName as SelectorLocalName;
use crate::{Atom, ShrinkIfNeeded};
use selectors::parser::{Component, LocalName, Selector}; use selectors::parser::{Component, LocalName, Selector};
/// The kind of change that happened for a given rule. /// The kind of change that happened for a given rule.
@@ -632,10 +632,7 @@ impl StylesheetInvalidationSet {
// existing elements. // existing elements.
} }
}, },
CounterStyle(..) | CounterStyle(..) | Page(..) | Viewport(..) | FontFeatureValues(..) => {
Page(..) |
Viewport(..) |
FontFeatureValues(..) => {
debug!( debug!(
" > Found unsupported rule, marking the whole subtree \ " > Found unsupported rule, marking the whole subtree \
invalid." invalid."

View File

@@ -162,7 +162,7 @@ pub use style_traits::arc_slice::ArcSlice;
pub use style_traits::owned_slice::OwnedSlice; pub use style_traits::owned_slice::OwnedSlice;
pub use style_traits::owned_str::OwnedStr; pub use style_traits::owned_str::OwnedStr;
use std::hash::{Hash, BuildHasher}; use std::hash::{BuildHasher, Hash};
/// The CSS properties supported by the style system. /// The CSS properties supported by the style system.
/// Generated from the properties.mako.rs template by build.rs /// Generated from the properties.mako.rs template by build.rs
@@ -300,7 +300,7 @@ impl From<std::collections::TryReserveError> for AllocErr {
} }
/// Shrink the capacity of the collection if needed. /// Shrink the capacity of the collection if needed.
pub (crate) trait ShrinkIfNeeded { pub(crate) trait ShrinkIfNeeded {
fn shrink_if_needed(&mut self); fn shrink_if_needed(&mut self);
} }

View File

@@ -900,8 +900,13 @@ pub trait MatchMethods: TElement {
let new_primary_style = data.styles.primary.as_ref().unwrap(); let new_primary_style = data.styles.primary.as_ref().unwrap();
let mut restyle_requirement = ChildRestyleRequirement::CanSkipCascade; let mut restyle_requirement = ChildRestyleRequirement::CanSkipCascade;
let is_root = new_primary_style.flags.contains(ComputedValueFlags::IS_ROOT_ELEMENT_STYLE); let is_root = new_primary_style
let is_container = !new_primary_style.get_box().clone_container_type().is_empty(); .flags
.contains(ComputedValueFlags::IS_ROOT_ELEMENT_STYLE);
let is_container = !new_primary_style
.get_box()
.clone_container_type()
.is_empty();
if is_root || is_container { if is_root || is_container {
let new_font_size = new_primary_style.get_font().clone_font_size(); let new_font_size = new_primary_style.get_font().clone_font_size();
let old_font_size = old_styles let old_font_size = old_styles

View File

@@ -84,8 +84,8 @@ impl MediaList {
let media_match = mq.media_type.matches(device.media_type()); let media_match = mq.media_type.matches(device.media_type());
// Check if the media condition match. // Check if the media condition match.
let query_match = media_match && let query_match =
mq.condition.as_ref().map_or(true, |c| c.matches(context)); media_match && mq.condition.as_ref().map_or(true, |c| c.matches(context));
// Apply the logical NOT qualifier to the result // Apply the logical NOT qualifier to the result
match mq.qualifier { match mq.qualifier {

View File

@@ -6,8 +6,8 @@
//! //!
//! https://drafts.csswg.org/mediaqueries/#typedef-media-query //! https://drafts.csswg.org/mediaqueries/#typedef-media-query
use crate::queries::{QueryCondition, FeatureType};
use crate::parser::ParserContext; use crate::parser::ParserContext;
use crate::queries::{FeatureType, QueryCondition};
use crate::str::string_as_ascii_lowercase; use crate::str::string_as_ascii_lowercase;
use crate::values::CustomIdent; use crate::values::CustomIdent;
use crate::Atom; use crate::Atom;
@@ -136,7 +136,11 @@ impl MediaQuery {
let condition = if explicit_media_type.is_none() { let condition = if explicit_media_type.is_none() {
Some(QueryCondition::parse(context, input, FeatureType::Media)?) Some(QueryCondition::parse(context, input, FeatureType::Media)?)
} else if input.try_parse(|i| i.expect_ident_matching("and")).is_ok() { } else if input.try_parse(|i| i.expect_ident_matching("and")).is_ok() {
Some(QueryCondition::parse_disallow_or(context, input, FeatureType::Media)?) Some(QueryCondition::parse_disallow_or(
context,
input,
FeatureType::Media,
)?)
} else { } else {
None None
}; };

View File

@@ -75,9 +75,8 @@ type WorkUnit<N> = ArrayVec<SendNode<N>, WORK_UNIT_MAX>;
/// out of line so we don't allocate stack space for the entire struct /// out of line so we don't allocate stack space for the entire struct
/// in the caller. /// in the caller.
#[inline(never)] #[inline(never)]
fn create_thread_local_context<'scope, E>( fn create_thread_local_context<'scope, E>(slot: &mut Option<ThreadLocalStyleContext<E>>)
slot: &mut Option<ThreadLocalStyleContext<E>>, where
) where
E: TElement + 'scope, E: TElement + 'scope,
{ {
*slot = Some(ThreadLocalStyleContext::new()); *slot = Some(ThreadLocalStyleContext::new());

View File

@@ -230,7 +230,10 @@ impl PiecewiseLinearFunctionBuilder {
} }
// Guaranteed at least two elements. // Guaranteed at least two elements.
// Start element's x value should've been assigned when the first value was pushed. // Start element's x value should've been assigned when the first value was pushed.
debug_assert!(self.entries[0].x.is_some(), "Expected an entry with x defined!"); debug_assert!(
self.entries[0].x.is_some(),
"Expected an entry with x defined!"
);
// Spec asserts that if the last entry does not have an x value, it is assigned the largest seen x value. // Spec asserts that if the last entry does not have an x value, it is assigned the largest seen x value.
self.entries self.entries
.last_mut() .last_mut()

View File

@@ -114,7 +114,6 @@ impl ComputedValueFlags {
Self::HAS_TEXT_DECORATION_LINES | Self::HAS_TEXT_DECORATION_LINES |
Self::IS_IN_OPACITY_ZERO_SUBTREE | Self::IS_IN_OPACITY_ZERO_SUBTREE |
Self::SELF_OR_ANCESTOR_HAS_CONTAIN_STYLE Self::SELF_OR_ANCESTOR_HAS_CONTAIN_STYLE
} }
/// Flags that may be propagated to descendants. /// Flags that may be propagated to descendants.

View File

@@ -7,7 +7,7 @@
//! https://drafts.csswg.org/mediaqueries-4/#typedef-media-condition //! https://drafts.csswg.org/mediaqueries-4/#typedef-media-condition
//! https://drafts.csswg.org/css-contain-3/#typedef-container-condition //! https://drafts.csswg.org/css-contain-3/#typedef-container-condition
use super::{QueryFeatureExpression, FeatureType, FeatureFlags}; use super::{FeatureFlags, FeatureType, QueryFeatureExpression};
use crate::parser::ParserContext; use crate::parser::ParserContext;
use crate::values::computed; use crate::values::computed;
use cssparser::{Parser, Token}; use cssparser::{Parser, Token};
@@ -197,7 +197,8 @@ impl QueryCondition {
if let Ok(inner) = input.try_parse(|i| Self::parse(context, i, feature_type)) { if let Ok(inner) = input.try_parse(|i| Self::parse(context, i, feature_type)) {
return Ok(QueryCondition::InParens(Box::new(inner))); return Ok(QueryCondition::InParens(Box::new(inner)));
} }
let expr = QueryFeatureExpression::parse_in_parenthesis_block(context, input, feature_type)?; let expr =
QueryFeatureExpression::parse_in_parenthesis_block(context, input, feature_type)?;
Ok(QueryCondition::Feature(expr)) Ok(QueryCondition::Feature(expr))
}) })
} }

View File

@@ -5,7 +5,7 @@
//! Query features. //! Query features.
use crate::parser::ParserContext; use crate::parser::ParserContext;
use crate::values::computed::{self, CSSPixelLength, Resolution, Ratio}; use crate::values::computed::{self, CSSPixelLength, Ratio, Resolution};
use crate::Atom; use crate::Atom;
use cssparser::Parser; use cssparser::Parser;
use std::fmt; use std::fmt;
@@ -66,10 +66,8 @@ macro_rules! keyword_evaluator {
fn __parse<'i, 't>( fn __parse<'i, 't>(
context: &$crate::parser::ParserContext, context: &$crate::parser::ParserContext,
input: &mut $crate::cssparser::Parser<'i, 't>, input: &mut $crate::cssparser::Parser<'i, 't>,
) -> Result< ) -> Result<$crate::queries::feature::KeywordDiscriminant, ::style_traits::ParseError<'i>>
$crate::queries::feature::KeywordDiscriminant, {
::style_traits::ParseError<'i>,
> {
let kw = <$keyword_type as $crate::parser::Parse>::parse(context, input)?; let kw = <$keyword_type as $crate::parser::Parse>::parse(context, input)?;
Ok(kw as $crate::queries::feature::KeywordDiscriminant) Ok(kw as $crate::queries::feature::KeywordDiscriminant)
} }

View File

@@ -6,7 +6,7 @@
//! `(width >= 400px)`. //! `(width >= 400px)`.
use super::feature::{Evaluator, QueryFeatureDescription}; use super::feature::{Evaluator, QueryFeatureDescription};
use super::feature::{KeywordDiscriminant, FeatureFlags}; use super::feature::{FeatureFlags, KeywordDiscriminant};
use crate::parser::{Parse, ParserContext}; use crate::parser::{Parse, ParserContext};
use crate::str::{starts_with_ignore_ascii_case, string_as_ascii_lowercase}; use crate::str::{starts_with_ignore_ascii_case, string_as_ascii_lowercase};
use crate::values::computed::{self, Ratio, ToComputedValue}; use crate::values::computed::{self, Ratio, ToComputedValue};
@@ -43,7 +43,10 @@ impl FeatureType {
} }
fn find_feature(&self, name: &Atom) -> Option<(usize, &'static QueryFeatureDescription)> { fn find_feature(&self, name: &Atom) -> Option<(usize, &'static QueryFeatureDescription)> {
self.features().iter().enumerate().find(|(_, f)| f.name == *name) self.features()
.iter()
.enumerate()
.find(|(_, f)| f.name == *name)
} }
} }
@@ -92,8 +95,12 @@ impl Operator {
// context. // context.
match self { match self {
Self::Equal => false, Self::Equal => false,
Self::GreaterThan | Self::GreaterThanEqual => matches!(right_op, Self::GreaterThan | Self::GreaterThanEqual), Self::GreaterThan | Self::GreaterThanEqual => {
Self::LessThan | Self::LessThanEqual => matches!(right_op, Self::LessThan | Self::LessThanEqual), matches!(right_op, Self::GreaterThan | Self::GreaterThanEqual)
},
Self::LessThan | Self::LessThanEqual => {
matches!(right_op, Self::LessThan | Self::LessThanEqual)
},
} }
} }
@@ -478,9 +485,7 @@ impl QueryFeatureExpression {
let right = match right_op { let right = match right_op {
Some(op) => { Some(op) => {
if !left_op.is_compatible_with(op) { if !left_op.is_compatible_with(op) {
return Err( return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
input.new_custom_error(StyleParseErrorKind::UnspecifiedError)
);
} }
Some((op, QueryExpressionValue::parse(feature, context, input)?)) Some((op, QueryExpressionValue::parse(feature, context, input)?))
}, },
@@ -583,9 +588,8 @@ impl QueryFeatureExpression {
match self.feature().evaluator { match self.feature().evaluator {
Evaluator::Length(eval) => { Evaluator::Length(eval) => {
let v = eval(context); let v = eval(context);
self.kind.evaluate(v, |v| { self.kind
expect!(Length, v).to_computed_value(context) .evaluate(v, |v| expect!(Length, v).to_computed_value(context))
})
}, },
Evaluator::Integer(eval) => { Evaluator::Integer(eval) => {
let v = eval(context); let v = eval(context);
@@ -594,14 +598,15 @@ impl QueryFeatureExpression {
Evaluator::Float(eval) => { Evaluator::Float(eval) => {
let v = eval(context); let v = eval(context);
self.kind.evaluate(v, |v| *expect!(Float, v)) self.kind.evaluate(v, |v| *expect!(Float, v))
} },
Evaluator::NumberRatio(eval) => { Evaluator::NumberRatio(eval) => {
let ratio = eval(context); let ratio = eval(context);
// A ratio of 0/0 behaves as the ratio 1/0, so we need to call used_value() // A ratio of 0/0 behaves as the ratio 1/0, so we need to call used_value()
// to convert it if necessary. // to convert it if necessary.
// FIXME: we may need to update here once // FIXME: we may need to update here once
// https://github.com/w3c/csswg-drafts/issues/4954 got resolved. // https://github.com/w3c/csswg-drafts/issues/4954 got resolved.
self.kind.evaluate(ratio, |v| expect!(NumberRatio, v).used_value()) self.kind
.evaluate(ratio, |v| expect!(NumberRatio, v).used_value())
}, },
Evaluator::Resolution(eval) => { Evaluator::Resolution(eval) => {
let v = eval(context).dppx(); let v = eval(context).dppx();
@@ -610,11 +615,17 @@ impl QueryFeatureExpression {
}) })
}, },
Evaluator::Enumerated { evaluator, .. } => { Evaluator::Enumerated { evaluator, .. } => {
let computed = self.kind.non_ranged_value().map(|v| *expect!(Enumerated, v)); let computed = self
.kind
.non_ranged_value()
.map(|v| *expect!(Enumerated, v));
evaluator(context, computed) evaluator(context, computed)
}, },
Evaluator::BoolInteger(eval) => { Evaluator::BoolInteger(eval) => {
let computed = self.kind.non_ranged_value().map(|v| *expect!(BoolInteger, v)); let computed = self
.kind
.non_ranged_value()
.map(|v| *expect!(BoolInteger, v));
let boolean = eval(context); let boolean = eval(context);
computed.map_or(boolean, |v| v == boolean) computed.map_or(boolean, |v| v == boolean)
}, },

View File

@@ -16,4 +16,4 @@ pub mod values;
pub use self::condition::QueryCondition; pub use self::condition::QueryCondition;
pub use self::feature::FeatureFlags; pub use self::feature::FeatureFlags;
pub use self::feature_expression::{QueryFeatureExpression, FeatureType}; pub use self::feature_expression::{FeatureType, QueryFeatureExpression};

View File

@@ -47,7 +47,7 @@ const RARE_PSEUDO_CLASS_STATES: ElementState = ElementState::from_bits_truncate(
ElementState::INERT.bits() | ElementState::INERT.bits() |
ElementState::FOCUS.bits() | ElementState::FOCUS.bits() |
ElementState::FOCUSRING.bits() | ElementState::FOCUSRING.bits() |
ElementState::TOPMOST_MODAL.bits() ElementState::TOPMOST_MODAL.bits(),
); );
/// A simple alias for a hashmap using PrecomputedHasher. /// A simple alias for a hashmap using PrecomputedHasher.
@@ -290,7 +290,10 @@ impl SelectorMap<Rule> {
) )
} }
if rule_hash_target.state().intersects(RARE_PSEUDO_CLASS_STATES) { if rule_hash_target
.state()
.intersects(RARE_PSEUDO_CLASS_STATES)
{
SelectorMap::get_matching_rules( SelectorMap::get_matching_rules(
element, element,
&self.rare_pseudo_classes, &self.rare_pseudo_classes,
@@ -349,13 +352,16 @@ impl SelectorMap<Rule> {
} }
if rule.container_condition_id != ContainerConditionId::none() { if rule.container_condition_id != ContainerConditionId::none() {
if !cascade_data.container_condition_matches(rule.container_condition_id, stylist, element) { if !cascade_data.container_condition_matches(
rule.container_condition_id,
stylist,
element,
) {
continue; continue;
} }
} }
matching_rules matching_rules.push(rule.to_applicable_declaration_block(cascade_level, cascade_data));
.push(rule.to_applicable_declaration_block(cascade_level, cascade_data));
} }
} }
} }
@@ -794,9 +800,7 @@ fn find_bucket<'a>(
/// Wrapper for PrecomputedHashMap that does ASCII-case-insensitive lookup in quirks mode. /// Wrapper for PrecomputedHashMap that does ASCII-case-insensitive lookup in quirks mode.
#[derive(Clone, Debug, MallocSizeOf)] #[derive(Clone, Debug, MallocSizeOf)]
pub struct MaybeCaseInsensitiveHashMap<K: PrecomputedHash + Hash + Eq, V>( pub struct MaybeCaseInsensitiveHashMap<K: PrecomputedHash + Hash + Eq, V>(PrecomputedHashMap<K, V>);
PrecomputedHashMap<K, V>,
);
impl<V> Default for MaybeCaseInsensitiveHashMap<Atom, V> { impl<V> Default for MaybeCaseInsensitiveHashMap<Atom, V> {
#[inline] #[inline]

View File

@@ -126,8 +126,7 @@ where
{ {
let stylist = &shared_context.stylist; let stylist = &shared_context.stylist;
let for_element = let for_element = target.revalidation_match_results(stylist, bloom, nth_index_cache);
target.revalidation_match_results(stylist, bloom, nth_index_cache);
let for_candidate = candidate.revalidation_match_results(stylist, bloom, nth_index_cache); let for_candidate = candidate.revalidation_match_results(stylist, bloom, nth_index_cache);

View File

@@ -75,7 +75,7 @@ use crate::stylist::Stylist;
use crate::values::AtomIdent; use crate::values::AtomIdent;
use atomic_refcell::{AtomicRefCell, AtomicRefMut}; use atomic_refcell::{AtomicRefCell, AtomicRefMut};
use owning_ref::OwningHandle; use owning_ref::OwningHandle;
use selectors::matching::{VisitedHandlingMode, NeedsSelectorFlags}; use selectors::matching::{NeedsSelectorFlags, VisitedHandlingMode};
use selectors::NthIndexCache; use selectors::NthIndexCache;
use servo_arc::Arc; use servo_arc::Arc;
use smallbitvec::SmallBitVec; use smallbitvec::SmallBitVec;
@@ -434,12 +434,7 @@ impl<E: TElement> StyleSharingTarget<E> {
self.element.traversal_parent() self.element.traversal_parent()
); );
cache.share_style_if_possible( cache.share_style_if_possible(shared_context, bloom_filter, nth_index_cache, self)
shared_context,
bloom_filter,
nth_index_cache,
self,
)
} }
/// Gets the validation data used to match against this target, if any. /// Gets the validation data used to match against this target, if any.
@@ -800,13 +795,7 @@ impl<E: TElement> StyleSharingCache<E> {
return None; return None;
} }
if !checks::revalidate( if !checks::revalidate(target, candidate, shared, bloom, nth_index_cache) {
target,
candidate,
shared,
bloom,
nth_index_cache,
) {
trace!("Miss: Revalidation"); trace!("Miss: Revalidation");
return None; return None;
} }

View File

@@ -14,7 +14,6 @@ use crate::properties::longhands::overflow_x::computed_value::T as Overflow;
use crate::properties::longhands::position::computed_value::T as Position; use crate::properties::longhands::position::computed_value::T as Position;
use crate::properties::{self, ComputedValues, StyleBuilder}; use crate::properties::{self, ComputedValues, StyleBuilder};
/// A struct that implements all the adjustment methods. /// A struct that implements all the adjustment methods.
/// ///
/// NOTE(emilio): If new adjustments are introduced that depend on reset /// NOTE(emilio): If new adjustments are introduced that depend on reset
@@ -158,8 +157,8 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
/// https://bugzilla.mozilla.org/show_bug.cgi?id=1786147#c10 /// https://bugzilla.mozilla.org/show_bug.cgi?id=1786147#c10
fn adjust_for_webkit_line_clamp(&mut self) { fn adjust_for_webkit_line_clamp(&mut self) {
use crate::properties::longhands::_moz_box_orient::computed_value::T as BoxOrient; use crate::properties::longhands::_moz_box_orient::computed_value::T as BoxOrient;
use crate::values::specified::box_::{DisplayOutside, DisplayInside}; use crate::values::specified::box_::{DisplayInside, DisplayOutside};
let box_style= self.style.get_box(); let box_style = self.style.get_box();
if box_style.clone__webkit_line_clamp().is_none() { if box_style.clone__webkit_line_clamp().is_none() {
return; return;
} }
@@ -176,7 +175,9 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
debug_assert_eq!(disp.outside(), DisplayOutside::Inline); debug_assert_eq!(disp.outside(), DisplayOutside::Inline);
Display::InlineBlock Display::InlineBlock
}; };
self.style.mutate_box().set_adjusted_display(new_display, false); self.style
.mutate_box()
.set_adjusted_display(new_display, false);
} }
/// CSS 2.1 section 9.7: /// CSS 2.1 section 9.7:
@@ -277,7 +278,8 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
.add_flags(ComputedValueFlags::IS_ROOT_ELEMENT_STYLE); .add_flags(ComputedValueFlags::IS_ROOT_ELEMENT_STYLE);
} }
if self.style if self
.style
.get_box() .get_box()
.clone_contain() .clone_contain()
.contains(SpecifiedValue::STYLE) .contains(SpecifiedValue::STYLE)

View File

@@ -15,7 +15,7 @@ use crate::rule_tree::StrongRuleNode;
use crate::selector_parser::{PseudoElement, SelectorImpl}; use crate::selector_parser::{PseudoElement, SelectorImpl};
use crate::stylist::RuleInclusion; use crate::stylist::RuleInclusion;
use log::Level::Trace; use log::Level::Trace;
use selectors::matching::{NeedsSelectorFlags, MatchingContext}; use selectors::matching::{MatchingContext, NeedsSelectorFlags};
use selectors::matching::{MatchingMode, VisitedHandlingMode}; use selectors::matching::{MatchingMode, VisitedHandlingMode};
use servo_arc::Arc; use servo_arc::Arc;

View File

@@ -6,29 +6,29 @@
//! //!
//! [container]: https://drafts.csswg.org/css-contain-3/#container-rule //! [container]: https://drafts.csswg.org/css-contain-3/#container-rule
use crate::logical_geometry::{WritingMode, LogicalSize};
use crate::dom::TElement; use crate::dom::TElement;
use crate::logical_geometry::{LogicalSize, WritingMode};
use crate::media_queries::Device; use crate::media_queries::Device;
use crate::parser::ParserContext; use crate::parser::ParserContext;
use crate::queries::{QueryCondition, FeatureType}; use crate::properties::ComputedValues;
use crate::queries::feature::{AllowsRanges, Evaluator, FeatureFlags, QueryFeatureDescription}; use crate::queries::feature::{AllowsRanges, Evaluator, FeatureFlags, QueryFeatureDescription};
use crate::queries::values::Orientation; use crate::queries::values::Orientation;
use crate::str::CssStringWriter; use crate::queries::{FeatureType, QueryCondition};
use crate::shared_lock::{ use crate::shared_lock::{
DeepCloneParams, DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard, DeepCloneParams, DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard,
}; };
use crate::values::specified::ContainerName; use crate::str::CssStringWriter;
use crate::values::computed::{Context, CSSPixelLength, Ratio};
use crate::properties::ComputedValues;
use crate::stylesheets::CssRules; use crate::stylesheets::CssRules;
use crate::values::computed::{CSSPixelLength, Context, Ratio};
use crate::values::specified::ContainerName;
use app_units::Au; use app_units::Au;
use cssparser::{SourceLocation, Parser}; use cssparser::{Parser, SourceLocation};
use euclid::default::Size2D; use euclid::default::Size2D;
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use malloc_size_of::{MallocSizeOfOps, MallocUnconditionalShallowSizeOf}; use malloc_size_of::{MallocSizeOfOps, MallocUnconditionalShallowSizeOf};
use servo_arc::Arc; use servo_arc::Arc;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss, ParseError}; use style_traits::{CssWriter, ParseError, ToCss};
/// A container rule. /// A container rule.
#[derive(Debug, ToShmem)] #[derive(Debug, ToShmem)]
@@ -56,8 +56,8 @@ impl ContainerRule {
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize { pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
// Measurement of other fields may be added later. // Measurement of other fields may be added later.
self.rules.unconditional_shallow_size_of(ops) self.rules.unconditional_shallow_size_of(ops) +
+ self.rules.read_with(guard).size_of(guard, ops) self.rules.read_with(guard).size_of(guard, ops)
} }
} }
@@ -122,12 +122,17 @@ impl ContainerCondition {
// FIXME: This is a bit ambiguous: // FIXME: This is a bit ambiguous:
// https://github.com/w3c/csswg-drafts/issues/7203 // https://github.com/w3c/csswg-drafts/issues/7203
let name = input.try_parse(|input| { let name = input
ContainerName::parse(context, input) .try_parse(|input| ContainerName::parse(context, input))
}).ok().unwrap_or_else(ContainerName::none); .ok()
.unwrap_or_else(ContainerName::none);
let condition = QueryCondition::parse(context, input, FeatureType::Container)?; let condition = QueryCondition::parse(context, input, FeatureType::Container)?;
let flags = condition.cumulative_flags(); let flags = condition.cumulative_flags();
Ok(Self { name, condition, flags }) Ok(Self {
name,
condition,
flags,
})
} }
fn valid_container_info<E>(&self, potential_container: E) -> Option<ContainerLookupResult<E>> fn valid_container_info<E>(&self, potential_container: E) -> Option<ContainerLookupResult<E>>
@@ -138,7 +143,7 @@ impl ContainerCondition {
fn container_type_axes(ty_: ContainerType, wm: WritingMode) -> FeatureFlags { fn container_type_axes(ty_: ContainerType, wm: WritingMode) -> FeatureFlags {
if ty_.contains(ContainerType::SIZE) { if ty_.contains(ContainerType::SIZE) {
return FeatureFlags::all_container_axes() return FeatureFlags::all_container_axes();
} }
if ty_.contains(ContainerType::INLINE_SIZE) { if ty_.contains(ContainerType::INLINE_SIZE) {
let physical_axis = if wm.is_vertical() { let physical_axis = if wm.is_vertical() {
@@ -146,7 +151,7 @@ impl ContainerCondition {
} else { } else {
FeatureFlags::CONTAINER_REQUIRES_WIDTH_AXIS FeatureFlags::CONTAINER_REQUIRES_WIDTH_AXIS
}; };
return FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS | physical_axis return FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS | physical_axis;
} }
FeatureFlags::empty() FeatureFlags::empty()
} }
@@ -211,7 +216,6 @@ impl ContainerCondition {
} }
} }
/// Information needed to evaluate an individual container query. /// Information needed to evaluate an individual container query.
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct ContainerInfo { pub struct ContainerInfo {
@@ -221,7 +225,7 @@ pub struct ContainerInfo {
fn get_container(context: &Context) -> ContainerInfo { fn get_container(context: &Context) -> ContainerInfo {
if let Some(ref info) = context.container_info { if let Some(ref info) = context.container_info {
return info.clone() return info.clone();
} }
ContainerInfo { ContainerInfo {
size: context.device().au_viewport_size(), size: context.device().au_viewport_size(),
@@ -241,12 +245,20 @@ fn eval_height(context: &Context) -> CSSPixelLength {
fn eval_inline_size(context: &Context) -> CSSPixelLength { fn eval_inline_size(context: &Context) -> CSSPixelLength {
let info = get_container(context); let info = get_container(context);
CSSPixelLength::new(LogicalSize::from_physical(info.wm, info.size).inline.to_f32_px()) CSSPixelLength::new(
LogicalSize::from_physical(info.wm, info.size)
.inline
.to_f32_px(),
)
} }
fn eval_block_size(context: &Context) -> CSSPixelLength { fn eval_block_size(context: &Context) -> CSSPixelLength {
let info = get_container(context); let info = get_container(context);
CSSPixelLength::new(LogicalSize::from_physical(info.wm, info.size).block.to_f32_px()) CSSPixelLength::new(
LogicalSize::from_physical(info.wm, info.size)
.block
.to_f32_px(),
)
} }
fn eval_aspect_ratio(context: &Context) -> Ratio { fn eval_aspect_ratio(context: &Context) -> Ratio {
@@ -293,12 +305,18 @@ pub static CONTAINER_FEATURES: [QueryFeatureDescription; 6] = [
Evaluator::NumberRatio(eval_aspect_ratio), Evaluator::NumberRatio(eval_aspect_ratio),
// XXX from_bits_truncate is const, but the pipe operator isn't, so this // XXX from_bits_truncate is const, but the pipe operator isn't, so this
// works around it. // works around it.
FeatureFlags::from_bits_truncate(FeatureFlags::CONTAINER_REQUIRES_BLOCK_AXIS.bits() | FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS.bits()), FeatureFlags::from_bits_truncate(
FeatureFlags::CONTAINER_REQUIRES_BLOCK_AXIS.bits() |
FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS.bits()
),
), ),
feature!( feature!(
atom!("orientation"), atom!("orientation"),
AllowsRanges::No, AllowsRanges::No,
keyword_evaluator!(eval_orientation, Orientation), keyword_evaluator!(eval_orientation, Orientation),
FeatureFlags::from_bits_truncate(FeatureFlags::CONTAINER_REQUIRES_BLOCK_AXIS.bits() | FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS.bits()), FeatureFlags::from_bits_truncate(
FeatureFlags::CONTAINER_REQUIRES_BLOCK_AXIS.bits() |
FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS.bits()
),
), ),
]; ];

View File

@@ -5,6 +5,7 @@
//! Style sheets and their CSS rules. //! Style sheets and their CSS rules.
mod cascading_at_rule; mod cascading_at_rule;
pub mod container_rule;
mod counter_style_rule; mod counter_style_rule;
mod document_rule; mod document_rule;
mod font_face_rule; mod font_face_rule;
@@ -12,7 +13,6 @@ pub mod font_feature_values_rule;
pub mod import_rule; pub mod import_rule;
pub mod keyframes_rule; pub mod keyframes_rule;
pub mod layer_rule; pub mod layer_rule;
pub mod container_rule;
mod loader; mod loader;
mod media_rule; mod media_rule;
mod namespace_rule; mod namespace_rule;
@@ -45,6 +45,7 @@ use style_traits::ParsingMode;
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use to_shmem::{self, SharedMemoryBuilder, ToShmem}; use to_shmem::{self, SharedMemoryBuilder, ToShmem};
pub use self::container_rule::ContainerRule;
pub use self::counter_style_rule::CounterStyleRule; pub use self::counter_style_rule::CounterStyleRule;
pub use self::document_rule::DocumentRule; pub use self::document_rule::DocumentRule;
pub use self::font_face_rule::FontFaceRule; pub use self::font_face_rule::FontFaceRule;
@@ -53,7 +54,6 @@ pub use self::import_rule::ImportRule;
pub use self::keyframes_rule::KeyframesRule; pub use self::keyframes_rule::KeyframesRule;
pub use self::layer_rule::{LayerBlockRule, LayerStatementRule}; pub use self::layer_rule::{LayerBlockRule, LayerStatementRule};
pub use self::loader::StylesheetLoader; pub use self::loader::StylesheetLoader;
pub use self::container_rule::ContainerRule;
pub use self::media_rule::MediaRule; pub use self::media_rule::MediaRule;
pub use self::namespace_rule::NamespaceRule; pub use self::namespace_rule::NamespaceRule;
pub use self::origin::{Origin, OriginSet, OriginSetIterator, PerOrigin, PerOriginIter}; pub use self::origin::{Origin, OriginSet, OriginSetIterator, PerOrigin, PerOriginIter};

View File

@@ -25,7 +25,11 @@ pub struct NamespaceRule {
impl ToCssWithGuard for NamespaceRule { impl ToCssWithGuard for NamespaceRule {
// https://drafts.csswg.org/cssom/#serialize-a-css-rule CSSNamespaceRule // https://drafts.csswg.org/cssom/#serialize-a-css-rule CSSNamespaceRule
fn to_css(&self, _guard: &SharedRwLockReadGuard, dest_str: &mut CssStringWriter) -> fmt::Result { fn to_css(
&self,
_guard: &SharedRwLockReadGuard,
dest_str: &mut CssStringWriter,
) -> fmt::Result {
let mut dest = CssWriter::new(dest_str); let mut dest = CssWriter::new(dest_str);
dest.write_str("@namespace ")?; dest.write_str("@namespace ")?;
if let Some(ref prefix) = self.prefix { if let Some(ref prefix) = self.prefix {

View File

@@ -12,12 +12,12 @@ use crate::shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked};
use crate::shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use crate::shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use crate::str::CssStringWriter; use crate::str::CssStringWriter;
use crate::values::{AtomIdent, CustomIdent}; use crate::values::{AtomIdent, CustomIdent};
use style_traits::{CssWriter, ParseError, ToCss};
use cssparser::{Parser, SourceLocation}; use cssparser::{Parser, SourceLocation};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps, MallocUnconditionalShallowSizeOf}; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps, MallocUnconditionalShallowSizeOf};
use servo_arc::Arc; use servo_arc::Arc;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, ToCss};
/// Type of a single [`@page`][page selector] /// Type of a single [`@page`][page selector]
/// ///
@@ -32,7 +32,7 @@ impl PageSelector {
/// This does not currently take pseudo selectors into account. /// This does not currently take pseudo selectors into account.
#[inline] #[inline]
pub fn ident_matches(&self, other: &CustomIdent) -> bool { pub fn ident_matches(&self, other: &CustomIdent) -> bool {
self.0.0 == other.0 self.0 .0 == other.0
} }
} }
@@ -76,7 +76,9 @@ impl Parse for PageSelectors {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
Ok(PageSelectors::new(input.parse_comma_separated(|i| PageSelector::parse(context, i))?)) Ok(PageSelectors::new(input.parse_comma_separated(|i| {
PageSelector::parse(context, i)
})?))
} }
} }
@@ -102,7 +104,9 @@ impl PageRule {
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize { pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
// Measurement of other fields may be added later. // Measurement of other fields may be added later.
self.block.unconditional_shallow_size_of(ops) + self.block.read_with(guard).size_of(ops) + self.selectors.size_of(ops) self.block.unconditional_shallow_size_of(ops) +
self.block.read_with(guard).size_of(ops) +
self.selectors.size_of(ops)
} }
} }

View File

@@ -13,7 +13,7 @@ use crate::properties::parse_property_declaration_list;
use crate::selector_parser::{SelectorImpl, SelectorParser}; use crate::selector_parser::{SelectorImpl, SelectorParser};
use crate::shared_lock::{Locked, SharedRwLock}; use crate::shared_lock::{Locked, SharedRwLock};
use crate::str::starts_with_ignore_ascii_case; use crate::str::starts_with_ignore_ascii_case;
use crate::stylesheets::container_rule::{ContainerRule, ContainerCondition}; use crate::stylesheets::container_rule::{ContainerCondition, ContainerRule};
use crate::stylesheets::document_rule::DocumentCondition; use crate::stylesheets::document_rule::DocumentCondition;
use crate::stylesheets::font_feature_values_rule::parse_family_name_list; use crate::stylesheets::font_feature_values_rule::parse_family_name_list;
use crate::stylesheets::import_rule::ImportLayer; use crate::stylesheets::import_rule::ImportLayer;
@@ -69,7 +69,7 @@ impl<'a> InsertRuleContext<'a> {
} }
} }
State::Body State::Body
} },
_ => State::Body, _ => State::Body,
} }
} }
@@ -648,15 +648,13 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> {
}, },
)))) ))))
}, },
AtRulePrelude::Container(condition) => { AtRulePrelude::Container(condition) => Ok(CssRule::Container(Arc::new(
Ok(CssRule::Container(Arc::new(self.shared_lock.wrap( self.shared_lock.wrap(ContainerRule {
ContainerRule {
condition, condition,
rules: self.parse_nested_rules(input, CssRuleType::Container), rules: self.parse_nested_rules(input, CssRuleType::Container),
source_location: start.source_location(), source_location: start.source_location(),
}, }),
)))) ))),
},
AtRulePrelude::Layer(names) => { AtRulePrelude::Layer(names) => {
let name = match names.len() { let name = match names.len() {
0 | 1 => names.into_iter().next(), 0 | 1 => names.into_iter().next(),

View File

@@ -4,6 +4,7 @@
//! [@supports rules](https://drafts.csswg.org/css-conditional-3/#at-supports) //! [@supports rules](https://drafts.csswg.org/css-conditional-3/#at-supports)
use crate::font_face::{FontFaceSourceFormatKeyword, FontFaceSourceTechFlags};
use crate::parser::ParserContext; use crate::parser::ParserContext;
use crate::properties::{PropertyDeclaration, PropertyId, SourcePropertyDeclaration}; use crate::properties::{PropertyDeclaration, PropertyId, SourcePropertyDeclaration};
use crate::selector_parser::{SelectorImpl, SelectorParser}; use crate::selector_parser::{SelectorImpl, SelectorParser};
@@ -11,7 +12,6 @@ use crate::shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked};
use crate::shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use crate::shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use crate::str::CssStringWriter; use crate::str::CssStringWriter;
use crate::stylesheets::{CssRuleType, CssRules, Namespaces}; use crate::stylesheets::{CssRuleType, CssRules, Namespaces};
use crate::font_face::{FontFaceSourceFormatKeyword, FontFaceSourceTechFlags};
use cssparser::parse_important; use cssparser::parse_important;
use cssparser::{Delimiter, Parser, SourceLocation, Token}; use cssparser::{Delimiter, Parser, SourceLocation, Token};
use cssparser::{ParseError as CssParseError, ParserInput}; use cssparser::{ParseError as CssParseError, ParserInput};

View File

@@ -866,12 +866,7 @@ impl Stylist {
let rule_node = self.rule_node_for_precomputed_pseudo(guards, pseudo, vec![]); let rule_node = self.rule_node_for_precomputed_pseudo(guards, pseudo, vec![]);
self.precomputed_values_for_pseudo_with_rule_node::<E>( self.precomputed_values_for_pseudo_with_rule_node::<E>(guards, pseudo, parent, rule_node)
guards,
pseudo,
parent,
rule_node,
)
} }
/// Computes the style for a given "precomputed" pseudo-element with /// Computes the style for a given "precomputed" pseudo-element with
@@ -951,11 +946,7 @@ impl Stylist {
where where
E: TElement, E: TElement,
{ {
self.precomputed_values_for_pseudo::<E>( self.precomputed_values_for_pseudo::<E>(guards, &pseudo, Some(parent_style))
guards,
&pseudo,
Some(parent_style),
)
} }
/// Computes a pseudo-element style lazily during layout. /// Computes a pseudo-element style lazily during layout.
@@ -1644,8 +1635,7 @@ pub struct PageRuleData {
/// named page rules that match a certain page. /// named page rules that match a certain page.
#[derive(Clone, Debug, Deref, MallocSizeOf)] #[derive(Clone, Debug, Deref, MallocSizeOf)]
pub struct PageRuleDataNoLayer( pub struct PageRuleDataNoLayer(
#[ignore_malloc_size_of = "Arc, stylesheet measures as primary ref"] #[ignore_malloc_size_of = "Arc, stylesheet measures as primary ref"] pub Arc<Locked<PageRule>>,
pub Arc<Locked<PageRule>>,
); );
/// Stores page rules indexed by page names. /// Stores page rules indexed by page names.
@@ -1729,14 +1719,19 @@ impl ExtraStyleData {
) -> Result<(), AllocErr> { ) -> Result<(), AllocErr> {
let page_rule = rule.read_with(guard); let page_rule = rule.read_with(guard);
if page_rule.selectors.0.is_empty() { if page_rule.selectors.0.is_empty() {
self.pages.global.push(PageRuleDataNoLayer(rule.clone()), layer); self.pages
.global
.push(PageRuleDataNoLayer(rule.clone()), layer);
} else { } else {
// TODO: Handle pseudo-classes // TODO: Handle pseudo-classes
self.pages.named.try_reserve(page_rule.selectors.0.len())?; self.pages.named.try_reserve(page_rule.selectors.0.len())?;
for name in page_rule.selectors.as_slice() { for name in page_rule.selectors.as_slice() {
let vec = self.pages.named.entry(name.0.0.clone()).or_default(); let vec = self.pages.named.entry(name.0 .0.clone()).or_default();
vec.try_reserve(1)?; vec.try_reserve(1)?;
vec.push(PageRuleData{layer, rule: rule.clone()}); vec.push(PageRuleData {
layer,
rule: rule.clone(),
});
} }
} }
Ok(()) Ok(())
@@ -2095,7 +2090,6 @@ impl ContainerConditionId {
} }
} }
#[derive(Clone, Debug, MallocSizeOf)] #[derive(Clone, Debug, MallocSizeOf)]
struct ContainerConditionReference { struct ContainerConditionReference {
parent: ContainerConditionId, parent: ContainerConditionId,
@@ -2343,7 +2337,12 @@ impl CascadeData {
self.layers[id.0 as usize].order self.layers[id.0 as usize].order
} }
pub(crate) fn container_condition_matches<E>(&self, mut id: ContainerConditionId, stylist: &Stylist, element: E) -> bool pub(crate) fn container_condition_matches<E>(
&self,
mut id: ContainerConditionId,
stylist: &Stylist,
element: E,
) -> bool
where where
E: TElement, E: TElement,
{ {
@@ -2378,7 +2377,6 @@ impl CascadeData {
self.mapped_ids.shrink_if_needed(); self.mapped_ids.shrink_if_needed();
self.layer_id.shrink_if_needed(); self.layer_id.shrink_if_needed();
self.selectors_for_cache_revalidation.shrink_if_needed(); self.selectors_for_cache_revalidation.shrink_if_needed();
} }
fn compute_layer_order(&mut self) { fn compute_layer_order(&mut self) {
@@ -2623,7 +2621,8 @@ impl CascadeData {
// //
// https://drafts.csswg.org/css-contain-3/#container-rule // https://drafts.csswg.org/css-contain-3/#container-rule
// (Same elsewhere) // (Same elsewhere)
self.extra_data.add_font_face(rule, containing_rule_state.layer_id); self.extra_data
.add_font_face(rule, containing_rule_state.layer_id);
}, },
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
CssRule::FontFeatureValues(ref rule) => { CssRule::FontFeatureValues(ref rule) => {
@@ -2632,12 +2631,16 @@ impl CascadeData {
}, },
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
CssRule::CounterStyle(ref rule) => { CssRule::CounterStyle(ref rule) => {
self.extra_data self.extra_data.add_counter_style(
.add_counter_style(guard, rule, containing_rule_state.layer_id)?; guard,
rule,
containing_rule_state.layer_id,
)?;
}, },
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
CssRule::Page(ref rule) => { CssRule::Page(ref rule) => {
self.extra_data.add_page(guard, rule, containing_rule_state.layer_id)?; self.extra_data
.add_page(guard, rule, containing_rule_state.layer_id)?;
}, },
CssRule::Viewport(..) => {}, CssRule::Viewport(..) => {},
_ => { _ => {
@@ -2721,7 +2724,8 @@ impl CascadeData {
}; };
for name in name.layer_names() { for name in name.layer_names() {
containing_rule_state.layer_name.0.push(name.clone()); containing_rule_state.layer_name.0.push(name.clone());
containing_rule_state.layer_id = maybe_register_layer(data, &containing_rule_state.layer_name); containing_rule_state.layer_id =
maybe_register_layer(data, &containing_rule_state.layer_name);
} }
debug_assert_ne!(containing_rule_state.layer_id, LayerId::root()); debug_assert_ne!(containing_rule_state.layer_id, LayerId::root());
} }
@@ -2735,11 +2739,7 @@ impl CascadeData {
.saw_effective(import_rule); .saw_effective(import_rule);
} }
if let Some(ref layer) = import_rule.layer { if let Some(ref layer) = import_rule.layer {
maybe_register_layers( maybe_register_layers(self, layer.name.as_ref(), containing_rule_state);
self,
layer.name.as_ref(),
containing_rule_state
);
} }
}, },
CssRule::Media(ref lock) => { CssRule::Media(ref lock) => {
@@ -2750,11 +2750,7 @@ impl CascadeData {
}, },
CssRule::LayerBlock(ref lock) => { CssRule::LayerBlock(ref lock) => {
let layer_rule = lock.read_with(guard); let layer_rule = lock.read_with(guard);
maybe_register_layers( maybe_register_layers(self, layer_rule.name.as_ref(), containing_rule_state);
self,
layer_rule.name.as_ref(),
containing_rule_state,
);
}, },
CssRule::LayerStatement(ref lock) => { CssRule::LayerStatement(ref lock) => {
let layer_rule = lock.read_with(guard); let layer_rule = lock.read_with(guard);
@@ -2953,7 +2949,8 @@ impl CascadeData {
self.layers.clear(); self.layers.clear();
self.layers.push(CascadeLayer::root()); self.layers.push(CascadeLayer::root());
self.container_conditions.clear(); self.container_conditions.clear();
self.container_conditions.push(ContainerConditionReference::none()); self.container_conditions
.push(ContainerConditionReference::none());
self.extra_data.clear(); self.extra_data.clear();
self.rules_source_order = 0; self.rules_source_order = 0;
self.num_selectors = 0; self.num_selectors = 0;

View File

@@ -19,10 +19,8 @@ use smallvec::SmallVec;
use std::collections::HashMap; use std::collections::HashMap;
/// A cache from element reference to known-valid computed style. /// A cache from element reference to known-valid computed style.
pub type UndisplayedStyleCache = HashMap< pub type UndisplayedStyleCache =
selectors::OpaqueElement, HashMap<selectors::OpaqueElement, servo_arc::Arc<crate::properties::ComputedValues>>;
servo_arc::Arc<crate::properties::ComputedValues>,
>;
/// A per-traversal-level chunk of data. This is sent down by the traversal, and /// A per-traversal-level chunk of data. This is sent down by the traversal, and
/// currently only holds the dom depth for the bloom filter. /// currently only holds the dom depth for the bloom filter.
@@ -336,9 +334,8 @@ where
} }
ancestor = ancestor.unwrap().traversal_parent(); ancestor = ancestor.unwrap().traversal_parent();
layout_parent_style = ancestor.and_then(|a| { layout_parent_style =
a.borrow_data().map(|data| data.styles.primary().clone()) ancestor.and_then(|a| a.borrow_data().map(|data| data.styles.primary().clone()));
});
} }
for ancestor in ancestors_requiring_style_resolution.iter().rev() { for ancestor in ancestors_requiring_style_resolution.iter().rev() {
@@ -792,7 +789,7 @@ fn note_children<E, D, F>(
}, },
ChildRestyleRequirement::MustMatchDescendants => { ChildRestyleRequirement::MustMatchDescendants => {
child_hint |= RestyleHint::restyle_subtree(); child_hint |= RestyleHint::restyle_subtree();
} },
} }
child_data.hint.insert(child_hint); child_data.hint.insert(child_hint);

View File

@@ -8,7 +8,7 @@ use crate::values::animated::{Animate, Procedure, ToAnimatedZero};
use crate::values::computed::Percentage; use crate::values::computed::Percentage;
use crate::values::distance::{ComputeSquaredDistance, SquaredDistance}; use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
use crate::values::generics::color::{ use crate::values::generics::color::{
GenericColor, GenericColorMix, ColorInterpolationMethod, ColorSpace, HueInterpolationMethod, ColorInterpolationMethod, ColorSpace, GenericColor, GenericColorMix, HueInterpolationMethod,
}; };
use euclid::default::{Transform3D, Vector3D}; use euclid::default::{Transform3D, Vector3D};
use std::f32::consts::PI; use std::f32::consts::PI;
@@ -162,13 +162,7 @@ impl Color {
let left = S::from(*left_color); let left = S::from(*left_color);
let right = S::from(*right_color); let right = S::from(*right_color);
let color = S::lerp( let color = S::lerp(&left, left_weight, &right, right_weight, hue_interpolation);
&left,
left_weight,
&right,
right_weight,
hue_interpolation,
);
let mut rgba = RGBA::from(color.into()); let mut rgba = RGBA::from(color.into());
if alpha_multiplier != 1.0 { if alpha_multiplier != 1.0 {
rgba.alpha *= alpha_multiplier; rgba.alpha *= alpha_multiplier;

View File

@@ -892,7 +892,11 @@ impl Animate for ComputedTransform {
// If there is a remainder from *both* lists we must have had mismatched functions. // If there is a remainder from *both* lists we must have had mismatched functions.
// => Add the remainders to a suitable ___Matrix function. // => Add the remainders to a suitable ___Matrix function.
(Some(this_remainder), Some(other_remainder)) => { (Some(this_remainder), Some(other_remainder)) => {
result.push(TransformOperation::animate_mismatched_transforms(this_remainder, other_remainder, procedure)?); result.push(TransformOperation::animate_mismatched_transforms(
this_remainder,
other_remainder,
procedure,
)?);
}, },
// If there is a remainder from just one list, then one list must be shorter but // If there is a remainder from just one list, then one list must be shorter but
// completely match the type of the corresponding functions in the longer list. // completely match the type of the corresponding functions in the longer list.
@@ -1121,7 +1125,10 @@ impl ComputedTransformOperation {
) -> Result<Self, ()> { ) -> Result<Self, ()> {
let (left, _left_3d) = Transform::components_to_transform_3d_matrix(left, None)?; let (left, _left_3d) = Transform::components_to_transform_3d_matrix(left, None)?;
let (right, _right_3d) = Transform::components_to_transform_3d_matrix(right, None)?; let (right, _right_3d) = Transform::components_to_transform_3d_matrix(right, None)?;
ComputedTransformOperation::Matrix3D(left.into()).animate(&ComputedTransformOperation::Matrix3D(right.into()), procedure) ComputedTransformOperation::Matrix3D(left.into()).animate(
&ComputedTransformOperation::Matrix3D(right.into()),
procedure,
)
} }
fn animate_mismatched_transforms( fn animate_mismatched_transforms(
@@ -1137,22 +1144,18 @@ impl ComputedTransformOperation {
Ok(match procedure { Ok(match procedure {
Procedure::Add => { Procedure::Add => {
debug_assert!(false, "Addition should've been handled earlier"); debug_assert!(false, "Addition should've been handled earlier");
return Err(()) return Err(());
}, },
Procedure::Interpolate { progress } => { Procedure::Interpolate { progress } => Self::InterpolateMatrix {
Self::InterpolateMatrix {
from_list, from_list,
to_list, to_list,
progress: Percentage(progress as f32), progress: Percentage(progress as f32),
} },
} Procedure::Accumulate { count } => Self::AccumulateMatrix {
Procedure::Accumulate { count } => {
Self::AccumulateMatrix {
from_list, from_list,
to_list, to_list,
count: cmp::min(count, i32::max_value() as u64) as i32, count: cmp::min(count, i32::max_value() as u64) as i32,
} },
}
}) })
} }
} }

View File

@@ -8,7 +8,9 @@ use crate::values::animated::{Animate, Procedure};
use crate::values::computed::length::{LengthPercentage, NonNegativeLength}; use crate::values::computed::length::{LengthPercentage, NonNegativeLength};
use crate::values::computed::{Context, Integer, Number, ToComputedValue}; use crate::values::computed::{Context, Integer, Number, ToComputedValue};
use crate::values::generics::box_::AnimationIterationCount as GenericAnimationIterationCount; use crate::values::generics::box_::AnimationIterationCount as GenericAnimationIterationCount;
use crate::values::generics::box_::{GenericLineClamp, GenericPerspective, GenericVerticalAlign, GenericContainIntrinsicSize}; use crate::values::generics::box_::{
GenericContainIntrinsicSize, GenericLineClamp, GenericPerspective, GenericVerticalAlign,
};
use crate::values::specified::box_ as specified; use crate::values::specified::box_ as specified;
pub use crate::values::specified::box_::{ pub use crate::values::specified::box_::{
@@ -39,7 +41,7 @@ impl Animate for LineClamp {
return Err(()); return Err(());
} }
if self.is_none() { if self.is_none() {
return Ok(Self::none()) return Ok(Self::none());
} }
Ok(Self(self.0.animate(&other.0, procedure)?.max(1))) Ok(Self(self.0.animate(&other.0, procedure)?.max(1)))
} }

View File

@@ -6,8 +6,8 @@
use crate::values::animated::color::AnimatedRGBA; use crate::values::animated::color::AnimatedRGBA;
use crate::values::animated::ToAnimatedValue; use crate::values::animated::ToAnimatedValue;
use crate::values::generics::color::{GenericCaretColor, GenericColor, GenericColorOrAuto};
use crate::values::computed::percentage::Percentage; use crate::values::computed::percentage::Percentage;
use crate::values::generics::color::{GenericCaretColor, GenericColor, GenericColorOrAuto};
use cssparser::{Color as CSSParserColor, RGBA}; use cssparser::{Color as CSSParserColor, RGBA};
use std::fmt; use std::fmt;
use style_traits::{CssWriter, ToCss}; use style_traits::{CssWriter, ToCss};

View File

@@ -7,8 +7,8 @@
use crate::parser::{Parse, ParserContext}; use crate::parser::{Parse, ParserContext};
use crate::values::animated::ToAnimatedValue; use crate::values::animated::ToAnimatedValue;
use crate::values::computed::{ use crate::values::computed::{
Angle, Context, Integer, Length, NonNegativeLength, NonNegativeNumber, Angle, Context, Integer, Length, NonNegativeLength, NonNegativeNumber, Number, Percentage,
Number, Percentage, ToComputedValue ToComputedValue,
}; };
use crate::values::generics::font::{FeatureTagValue, FontSettings, VariationValue}; use crate::values::generics::font::{FeatureTagValue, FontSettings, VariationValue};
use crate::values::generics::{font as generics, NonNegative}; use crate::values::generics::{font as generics, NonNegative};
@@ -48,7 +48,15 @@ pub use crate::values::specified::Integer as SpecifiedInteger;
/// cbindgen:derive-gte /// cbindgen:derive-gte
#[repr(C)] #[repr(C)]
#[derive( #[derive(
Clone, ComputeSquaredDistance, Copy, Debug, Hash, MallocSizeOf, PartialEq, PartialOrd, ToResolvedValue, Clone,
ComputeSquaredDistance,
Copy,
Debug,
Hash,
MallocSizeOf,
PartialEq,
PartialOrd,
ToResolvedValue,
)] )]
pub struct FixedPoint<T, const FRACTION_BITS: u16> { pub struct FixedPoint<T, const FRACTION_BITS: u16> {
value: T, value: T,
@@ -95,7 +103,15 @@ pub type FontWeightFixedPoint = FixedPoint<u16, FONT_WEIGHT_FRACTION_BITS>;
/// cbindgen:derive-gt /// cbindgen:derive-gt
/// cbindgen:derive-gte /// cbindgen:derive-gte
#[derive( #[derive(
Clone, ComputeSquaredDistance, Copy, Debug, Hash, MallocSizeOf, PartialEq, PartialOrd, ToResolvedValue, Clone,
ComputeSquaredDistance,
Copy,
Debug,
Hash,
MallocSizeOf,
PartialEq,
PartialOrd,
ToResolvedValue,
)] )]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[repr(C)] #[repr(C)]
@@ -125,13 +141,19 @@ impl ToCss for FontWeight {
impl FontWeight { impl FontWeight {
/// The `normal` keyword. /// The `normal` keyword.
pub const NORMAL: FontWeight = FontWeight(FontWeightFixedPoint { value: 400 << FONT_WEIGHT_FRACTION_BITS }); pub const NORMAL: FontWeight = FontWeight(FontWeightFixedPoint {
value: 400 << FONT_WEIGHT_FRACTION_BITS,
});
/// The `bold` value. /// The `bold` value.
pub const BOLD: FontWeight = FontWeight(FontWeightFixedPoint { value: 700 << FONT_WEIGHT_FRACTION_BITS }); pub const BOLD: FontWeight = FontWeight(FontWeightFixedPoint {
value: 700 << FONT_WEIGHT_FRACTION_BITS,
});
/// The threshold from which we consider a font bold. /// The threshold from which we consider a font bold.
pub const BOLD_THRESHOLD: FontWeight = FontWeight(FontWeightFixedPoint { value: 600 << FONT_WEIGHT_FRACTION_BITS }); pub const BOLD_THRESHOLD: FontWeight = FontWeight(FontWeightFixedPoint {
value: 600 << FONT_WEIGHT_FRACTION_BITS,
});
/// Returns the `normal` keyword value. /// Returns the `normal` keyword value.
pub fn normal() -> Self { pub fn normal() -> Self {
@@ -150,7 +172,9 @@ impl FontWeight {
/// Construct a valid weight from a float value. /// Construct a valid weight from a float value.
pub fn from_float(v: f32) -> Self { pub fn from_float(v: f32) -> Self {
Self(FixedPoint::from_float(v.max(MIN_FONT_WEIGHT).min(MAX_FONT_WEIGHT))) Self(FixedPoint::from_float(
v.max(MIN_FONT_WEIGHT).min(MAX_FONT_WEIGHT),
))
} }
/// Return the bolder weight. /// Return the bolder weight.
@@ -175,7 +199,7 @@ impl FontWeight {
pub fn lighter(self) -> Self { pub fn lighter(self) -> Self {
let value = self.value(); let value = self.value();
if value < 550. { if value < 550. {
return Self::from_float(value.min(100.)) return Self::from_float(value.min(100.));
} }
if value < 750. { if value < 750. {
return Self::NORMAL; return Self::NORMAL;
@@ -860,23 +884,37 @@ pub type FontStyleFixedPoint = FixedPoint<i16, FONT_STYLE_FRACTION_BITS>;
/// cbindgen:derive-gt /// cbindgen:derive-gt
/// cbindgen:derive-gte /// cbindgen:derive-gte
#[derive( #[derive(
Clone, ComputeSquaredDistance, Copy, Debug, Hash, MallocSizeOf, PartialEq, PartialOrd, ToResolvedValue, Clone,
ComputeSquaredDistance,
Copy,
Debug,
Hash,
MallocSizeOf,
PartialEq,
PartialOrd,
ToResolvedValue,
)] )]
#[repr(C)] #[repr(C)]
pub struct FontStyle(FontStyleFixedPoint); pub struct FontStyle(FontStyleFixedPoint);
impl FontStyle { impl FontStyle {
/// The normal keyword. /// The normal keyword.
pub const NORMAL: FontStyle = FontStyle(FontStyleFixedPoint { value: 100 << FONT_STYLE_FRACTION_BITS }); pub const NORMAL: FontStyle = FontStyle(FontStyleFixedPoint {
value: 100 << FONT_STYLE_FRACTION_BITS,
});
/// The italic keyword. /// The italic keyword.
pub const ITALIC: FontStyle = FontStyle(FontStyleFixedPoint { value: 101 << FONT_STYLE_FRACTION_BITS }); pub const ITALIC: FontStyle = FontStyle(FontStyleFixedPoint {
value: 101 << FONT_STYLE_FRACTION_BITS,
});
/// The default angle for `font-style: oblique`. /// The default angle for `font-style: oblique`.
/// See also https://github.com/w3c/csswg-drafts/issues/2295 /// See also https://github.com/w3c/csswg-drafts/issues/2295
pub const DEFAULT_OBLIQUE_DEGREES: i16 = 14; pub const DEFAULT_OBLIQUE_DEGREES: i16 = 14;
/// The `oblique` keyword with the default degrees. /// The `oblique` keyword with the default degrees.
pub const OBLIQUE: FontStyle = FontStyle(FontStyleFixedPoint { value: Self::DEFAULT_OBLIQUE_DEGREES << FONT_STYLE_FRACTION_BITS }); pub const OBLIQUE: FontStyle = FontStyle(FontStyleFixedPoint {
value: Self::DEFAULT_OBLIQUE_DEGREES << FONT_STYLE_FRACTION_BITS,
});
/// The `normal` value. /// The `normal` value.
#[inline] #[inline]
@@ -889,7 +927,7 @@ impl FontStyle {
Self(FixedPoint::from_float( Self(FixedPoint::from_float(
degrees degrees
.max(specified::FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES) .max(specified::FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES)
.min(specified::FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES) .min(specified::FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES),
)) ))
} }
@@ -907,10 +945,10 @@ impl ToCss for FontStyle {
W: fmt::Write, W: fmt::Write,
{ {
if *self == Self::NORMAL { if *self == Self::NORMAL {
return dest.write_str("normal") return dest.write_str("normal");
} }
if *self == Self::ITALIC { if *self == Self::ITALIC {
return dest.write_str("italic") return dest.write_str("italic");
} }
if *self == Self::OBLIQUE { if *self == Self::OBLIQUE {
return dest.write_str("oblique"); return dest.write_str("oblique");
@@ -928,10 +966,10 @@ impl ToAnimatedValue for FontStyle {
#[inline] #[inline]
fn to_animated_value(self) -> Self::AnimatedValue { fn to_animated_value(self) -> Self::AnimatedValue {
if self == Self::NORMAL { if self == Self::NORMAL {
return generics::FontStyle::Normal return generics::FontStyle::Normal;
} }
if self == Self::ITALIC { if self == Self::ITALIC {
return generics::FontStyle::Italic return generics::FontStyle::Italic;
} }
generics::FontStyle::Oblique(Angle::from_degrees(self.oblique_degrees())) generics::FontStyle::Oblique(Angle::from_degrees(self.oblique_degrees()))
} }
@@ -946,7 +984,6 @@ impl ToAnimatedValue for FontStyle {
} }
} }
/// font-stretch is a percentage relative to normal. /// font-stretch is a percentage relative to normal.
/// ///
/// We use an unsigned 10.6 fixed-point value (range 0.0 - 1023.984375) /// We use an unsigned 10.6 fixed-point value (range 0.0 - 1023.984375)
@@ -959,7 +996,6 @@ pub const FONT_STRETCH_FRACTION_BITS: u16 = 6;
/// workaround. /// workaround.
pub type FontStretchFixedPoint = FixedPoint<u16, FONT_STRETCH_FRACTION_BITS>; pub type FontStretchFixedPoint = FixedPoint<u16, FONT_STRETCH_FRACTION_BITS>;
/// A value for the font-stretch property per: /// A value for the font-stretch property per:
/// ///
/// https://drafts.csswg.org/css-fonts-4/#propdef-font-stretch /// https://drafts.csswg.org/css-fonts-4/#propdef-font-stretch
@@ -981,23 +1017,41 @@ impl FontStretch {
pub const HALF: u16 = 1 << (Self::FRACTION_BITS - 1); pub const HALF: u16 = 1 << (Self::FRACTION_BITS - 1);
/// The `ultra-condensed` keyword. /// The `ultra-condensed` keyword.
pub const ULTRA_CONDENSED: FontStretch = FontStretch(FontStretchFixedPoint { value: 50 << Self::FRACTION_BITS }); pub const ULTRA_CONDENSED: FontStretch = FontStretch(FontStretchFixedPoint {
value: 50 << Self::FRACTION_BITS,
});
/// The `extra-condensed` keyword. /// The `extra-condensed` keyword.
pub const EXTRA_CONDENSED: FontStretch = FontStretch(FontStretchFixedPoint { value: (62 << Self::FRACTION_BITS) + Self::HALF }); pub const EXTRA_CONDENSED: FontStretch = FontStretch(FontStretchFixedPoint {
value: (62 << Self::FRACTION_BITS) + Self::HALF,
});
/// The `condensed` keyword. /// The `condensed` keyword.
pub const CONDENSED: FontStretch = FontStretch(FontStretchFixedPoint { value: 75 << Self::FRACTION_BITS }); pub const CONDENSED: FontStretch = FontStretch(FontStretchFixedPoint {
value: 75 << Self::FRACTION_BITS,
});
/// The `semi-condensed` keyword. /// The `semi-condensed` keyword.
pub const SEMI_CONDENSED: FontStretch = FontStretch(FontStretchFixedPoint { value: (87 << Self::FRACTION_BITS) + Self::HALF }); pub const SEMI_CONDENSED: FontStretch = FontStretch(FontStretchFixedPoint {
value: (87 << Self::FRACTION_BITS) + Self::HALF,
});
/// The `normal` keyword. /// The `normal` keyword.
pub const NORMAL: FontStretch = FontStretch(FontStretchFixedPoint { value: 100 << Self::FRACTION_BITS }); pub const NORMAL: FontStretch = FontStretch(FontStretchFixedPoint {
value: 100 << Self::FRACTION_BITS,
});
/// The `semi-expanded` keyword. /// The `semi-expanded` keyword.
pub const SEMI_EXPANDED: FontStretch = FontStretch(FontStretchFixedPoint { value: (112 << Self::FRACTION_BITS) + Self::HALF }); pub const SEMI_EXPANDED: FontStretch = FontStretch(FontStretchFixedPoint {
value: (112 << Self::FRACTION_BITS) + Self::HALF,
});
/// The `expanded` keyword. /// The `expanded` keyword.
pub const EXPANDED: FontStretch = FontStretch(FontStretchFixedPoint { value: 125 << Self::FRACTION_BITS }); pub const EXPANDED: FontStretch = FontStretch(FontStretchFixedPoint {
value: 125 << Self::FRACTION_BITS,
});
/// The `extra-expanded` keyword. /// The `extra-expanded` keyword.
pub const EXTRA_EXPANDED: FontStretch = FontStretch(FontStretchFixedPoint { value: 150 << Self::FRACTION_BITS }); pub const EXTRA_EXPANDED: FontStretch = FontStretch(FontStretchFixedPoint {
value: 150 << Self::FRACTION_BITS,
});
/// The `ultra-expanded` keyword. /// The `ultra-expanded` keyword.
pub const ULTRA_EXPANDED: FontStretch = FontStretch(FontStretchFixedPoint { value: 200 << Self::FRACTION_BITS }); pub const ULTRA_EXPANDED: FontStretch = FontStretch(FontStretchFixedPoint {
value: 200 << Self::FRACTION_BITS,
});
/// 100% /// 100%
pub fn hundred() -> Self { pub fn hundred() -> Self {

View File

@@ -42,7 +42,11 @@ impl ToComputedValue for specified::NoCalcLength {
impl specified::NoCalcLength { impl specified::NoCalcLength {
/// Computes a length with a given font-relative base size. /// Computes a length with a given font-relative base size.
pub fn to_computed_value_with_base_size(&self, context: &Context, base_size: FontBaseSize) -> Length { pub fn to_computed_value_with_base_size(
&self,
context: &Context,
base_size: FontBaseSize,
) -> Length {
match *self { match *self {
specified::NoCalcLength::Absolute(length) => length.to_computed_value(context), specified::NoCalcLength::Absolute(length) => length.to_computed_value(context),
specified::NoCalcLength::FontRelative(length) => { specified::NoCalcLength::FontRelative(length) => {

View File

@@ -762,11 +762,7 @@ impl specified::CalcLengthPercentage {
context: &Context, context: &Context,
base_size: FontBaseSize, base_size: FontBaseSize,
) -> LengthPercentage { ) -> LengthPercentage {
self.to_computed_value_with_zoom( self.to_computed_value_with_zoom(context, |abs| context.maybe_zoom_text(abs), base_size)
context,
|abs| context.maybe_zoom_text(abs),
base_size,
)
} }
/// Compute the value into pixel length as CSSFloat without context, /// Compute the value into pixel length as CSSFloat without context,

View File

@@ -16,13 +16,13 @@ use super::specified;
use super::{CSSFloat, CSSInteger}; use super::{CSSFloat, CSSInteger};
use crate::computed_value_flags::ComputedValueFlags; use crate::computed_value_flags::ComputedValueFlags;
use crate::context::QuirksMode; use crate::context::QuirksMode;
use crate::stylesheets::container_rule::ContainerInfo;
use crate::font_metrics::{FontMetrics, FontMetricsOrientation}; use crate::font_metrics::{FontMetrics, FontMetricsOrientation};
use crate::media_queries::Device; use crate::media_queries::Device;
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use crate::properties; use crate::properties;
use crate::properties::{ComputedValues, LonghandId, StyleBuilder}; use crate::properties::{ComputedValues, LonghandId, StyleBuilder};
use crate::rule_cache::RuleCacheConditions; use crate::rule_cache::RuleCacheConditions;
use crate::stylesheets::container_rule::ContainerInfo;
use crate::values::specified::length::FontBaseSize; use crate::values::specified::length::FontBaseSize;
use crate::{ArcSlice, Atom, One}; use crate::{ArcSlice, Atom, One};
use euclid::{default, Point2D, Rect, Size2D}; use euclid::{default, Point2D, Rect, Size2D};
@@ -45,8 +45,13 @@ pub use self::basic_shape::FillRule;
pub use self::border::{BorderCornerRadius, BorderRadius, BorderSpacing}; pub use self::border::{BorderCornerRadius, BorderRadius, BorderSpacing};
pub use self::border::{BorderImageRepeat, BorderImageSideWidth}; pub use self::border::{BorderImageRepeat, BorderImageSideWidth};
pub use self::border::{BorderImageSlice, BorderImageWidth}; pub use self::border::{BorderImageSlice, BorderImageWidth};
pub use self::box_::{AnimationIterationCount, AnimationName, AnimationTimeline, Contain, ContainerName, ContainerType}; pub use self::box_::{
pub use self::box_::{Appearance, BreakBetween, BreakWithin, Clear, ContentVisibility, ContainIntrinsicSize, Float}; AnimationIterationCount, AnimationName, AnimationTimeline, Contain, ContainerName,
ContainerType,
};
pub use self::box_::{
Appearance, BreakBetween, BreakWithin, Clear, ContainIntrinsicSize, ContentVisibility, Float,
};
pub use self::box_::{Display, LineClamp, Overflow, OverflowAnchor, TransitionProperty}; pub use self::box_::{Display, LineClamp, Overflow, OverflowAnchor, TransitionProperty};
pub use self::box_::{OverflowClipBox, OverscrollBehavior, Perspective, Resize, ScrollbarGutter}; pub use self::box_::{OverflowClipBox, OverscrollBehavior, Perspective, Resize, ScrollbarGutter};
pub use self::box_::{ScrollAxis, ScrollSnapAlign, ScrollSnapAxis, ScrollSnapStop}; pub use self::box_::{ScrollAxis, ScrollSnapAlign, ScrollSnapAxis, ScrollSnapStop};
@@ -74,7 +79,7 @@ pub use self::list::ListStyleType;
pub use self::list::Quotes; pub use self::list::Quotes;
pub use self::motion::{OffsetPath, OffsetRotate}; pub use self::motion::{OffsetPath, OffsetRotate};
pub use self::outline::OutlineStyle; pub use self::outline::OutlineStyle;
pub use self::page::{PageOrientation, PageName, PageSize, PaperSize}; pub use self::page::{PageName, PageOrientation, PageSize, PaperSize};
pub use self::percentage::{NonNegativePercentage, Percentage}; pub use self::percentage::{NonNegativePercentage, Percentage};
pub use self::position::AspectRatio; pub use self::position::AspectRatio;
pub use self::position::{ pub use self::position::{
@@ -97,7 +102,7 @@ pub use self::transform::{Rotate, Scale, Transform, TransformOperation};
pub use self::transform::{TransformOrigin, TransformStyle, Translate}; pub use self::transform::{TransformOrigin, TransformStyle, Translate};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
pub use self::ui::CursorImage; pub use self::ui::CursorImage;
pub use self::ui::{Cursor, BoolInteger, UserSelect}; pub use self::ui::{BoolInteger, Cursor, UserSelect};
pub use super::specified::TextTransform; pub use super::specified::TextTransform;
pub use super::specified::ViewportVariant; pub use super::specified::ViewportVariant;
pub use super::specified::{BorderStyle, TextDecorationLine}; pub use super::specified::{BorderStyle, TextDecorationLine};
@@ -285,7 +290,7 @@ impl<'a> Context<'a> {
font, font,
size, size,
self.in_media_query, self.in_media_query,
retrieve_math_scales retrieve_math_scales,
) )
} }
@@ -339,10 +344,7 @@ pub struct ComputedVecIter<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> {
impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ComputedVecIter<'a, 'cx, 'cx_a, S> { impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ComputedVecIter<'a, 'cx, 'cx_a, S> {
/// Construct an iterator from a slice of specified values and a context /// Construct an iterator from a slice of specified values and a context
pub fn new(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self { pub fn new(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self {
ComputedVecIter { ComputedVecIter { cx, values }
cx,
values,
}
} }
} }

View File

@@ -117,7 +117,7 @@ impl<L: ToCss> ToCss for ContainIntrinsicSize<L> {
Self::AutoLength(ref l) => { Self::AutoLength(ref l) => {
dest.write_str("auto ")?; dest.write_str("auto ")?;
l.to_css(dest) l.to_css(dest)
} },
} }
} }
} }

View File

@@ -4,12 +4,12 @@
//! Generic types for color properties. //! Generic types for color properties.
use crate::values::animated::color::AnimatedRGBA;
use crate::values::animated::ToAnimatedValue;
use crate::values::specified::percentage::ToPercentage;
use crate::values::{Parse, Parser, ParserContext};
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, ToCss}; use style_traits::{CssWriter, ParseError, ToCss};
use crate::values::{Parse, ParserContext, Parser};
use crate::values::specified::percentage::ToPercentage;
use crate::values::animated::ToAnimatedValue;
use crate::values::animated::color::AnimatedRGBA;
/// This struct represents a combined color from a numeric color and /// This struct represents a combined color from a numeric color and
/// the current foreground color (currentcolor keyword). /// the current foreground color (currentcolor keyword).
@@ -27,7 +27,20 @@ pub enum GenericColor<RGBA, Percentage> {
/// A color space as defined in [1]. /// A color space as defined in [1].
/// ///
/// [1]: https://drafts.csswg.org/css-color-4/#typedef-color-space /// [1]: https://drafts.csswg.org/css-color-4/#typedef-color-space
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToAnimatedValue, ToComputedValue, ToCss, ToResolvedValue, ToShmem)] #[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
ToAnimatedValue,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(u8)] #[repr(u8)]
pub enum ColorSpace { pub enum ColorSpace {
/// The sRGB color space. /// The sRGB color space.
@@ -63,7 +76,20 @@ impl ColorSpace {
/// A hue-interpolation-method as defined in [1]. /// A hue-interpolation-method as defined in [1].
/// ///
/// [1]: https://drafts.csswg.org/css-color-4/#typedef-hue-interpolation-method /// [1]: https://drafts.csswg.org/css-color-4/#typedef-hue-interpolation-method
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToAnimatedValue, ToComputedValue, ToCss, ToResolvedValue, ToShmem)] #[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
ToAnimatedValue,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(u8)] #[repr(u8)]
pub enum HueInterpolationMethod { pub enum HueInterpolationMethod {
/// https://drafts.csswg.org/css-color-4/#shorter /// https://drafts.csswg.org/css-color-4/#shorter
@@ -79,7 +105,18 @@ pub enum HueInterpolationMethod {
} }
/// https://drafts.csswg.org/css-color-4/#color-interpolation-method /// https://drafts.csswg.org/css-color-4/#color-interpolation-method
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, ToShmem, ToAnimatedValue, ToComputedValue, ToResolvedValue)] #[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
PartialEq,
ToShmem,
ToAnimatedValue,
ToComputedValue,
ToResolvedValue,
)]
#[repr(C)] #[repr(C)]
pub struct ColorInterpolationMethod { pub struct ColorInterpolationMethod {
/// The color-space the interpolation should be done in. /// The color-space the interpolation should be done in.
@@ -109,11 +146,13 @@ impl Parse for ColorInterpolationMethod {
// Unless otherwise specified, if no specific hue interpolation // Unless otherwise specified, if no specific hue interpolation
// algorithm is selected by the host syntax, the default is shorter. // algorithm is selected by the host syntax, the default is shorter.
let hue = if space.is_polar() { let hue = if space.is_polar() {
input.try_parse(|input| -> Result<_, ParseError<'i>> { input
.try_parse(|input| -> Result<_, ParseError<'i>> {
let hue = HueInterpolationMethod::parse(input)?; let hue = HueInterpolationMethod::parse(input)?;
input.expect_ident_matching("hue")?; input.expect_ident_matching("hue")?;
Ok(hue) Ok(hue)
}).unwrap_or(HueInterpolationMethod::Shorter) })
.unwrap_or(HueInterpolationMethod::Shorter)
} else { } else {
HueInterpolationMethod::Shorter HueInterpolationMethod::Shorter
}; };
@@ -141,7 +180,16 @@ impl ToCss for ColorInterpolationMethod {
/// percentages. /// percentages.
/// ///
/// https://drafts.csswg.org/css-color-5/#color-mix /// https://drafts.csswg.org/css-color-5/#color-mix
#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToComputedValue, ToResolvedValue, ToShmem)] #[derive(
Clone,
Debug,
MallocSizeOf,
PartialEq,
ToAnimatedValue,
ToComputedValue,
ToResolvedValue,
ToShmem,
)]
#[allow(missing_docs)] #[allow(missing_docs)]
#[repr(C)] #[repr(C)]
pub struct GenericColorMix<Color, Percentage> { pub struct GenericColorMix<Color, Percentage> {
@@ -160,7 +208,11 @@ impl<Color: ToCss, Percentage: ToCss + ToPercentage> ToCss for ColorMix<Color, P
where where
W: Write, W: Write,
{ {
fn can_omit<Percentage: ToPercentage>(percent: &Percentage, other: &Percentage, is_left: bool) -> bool { fn can_omit<Percentage: ToPercentage>(
percent: &Percentage,
other: &Percentage,
is_left: bool,
) -> bool {
if percent.is_calc() { if percent.is_calc() {
return false; return false;
} }

View File

@@ -404,7 +404,10 @@ impl ToAbsoluteLength for ComputedLength {
impl ToAbsoluteLength for ComputedLengthPercentage { impl ToAbsoluteLength for ComputedLengthPercentage {
#[inline] #[inline]
fn to_pixel_length(&self, containing_len: Option<ComputedLength>) -> Result<CSSFloat, ()> { fn to_pixel_length(&self, containing_len: Option<ComputedLength>) -> Result<CSSFloat, ()> {
Ok(self.maybe_percentage_relative_to(containing_len).ok_or(())?.px()) Ok(self
.maybe_percentage_relative_to(containing_len)
.ok_or(())?
.px())
} }
} }
@@ -576,13 +579,14 @@ impl<T: ToMatrix> Transform<T> {
} }
/// Converts a series of components to a 3d matrix. /// Converts a series of components to a 3d matrix.
#[cfg_attr(rustfmt, rustfmt_skip)]
pub fn components_to_transform_3d_matrix( pub fn components_to_transform_3d_matrix(
ops: &[T], ops: &[T],
reference_box: Option<&Rect<ComputedLength>> reference_box: Option<&Rect<ComputedLength>>,
) -> Result<(Transform3D<CSSFloat>, bool), ()> { ) -> Result<(Transform3D<CSSFloat>, bool), ()> {
let cast_3d_transform = |m: Transform3D<f64>| -> Transform3D<CSSFloat> { let cast_3d_transform = |m: Transform3D<f64>| -> Transform3D<CSSFloat> {
use std::{f32, f64}; use std::{f32, f64};
let cast = |v: f64| { v.min(f32::MAX as f64).max(f32::MIN as f64) as f32 }; let cast = |v: f64| v.min(f32::MAX as f64).max(f32::MIN as f64) as f32;
Transform3D::new( Transform3D::new(
cast(m.m11), cast(m.m12), cast(m.m13), cast(m.m14), cast(m.m11), cast(m.m12), cast(m.m13), cast(m.m14),
cast(m.m21), cast(m.m22), cast(m.m23), cast(m.m24), cast(m.m21), cast(m.m22), cast(m.m23), cast(m.m24),

View File

@@ -491,7 +491,15 @@ impl ToCss for CustomIdent {
/// We use a single atom for these. Empty atom represents `none` animation. /// We use a single atom for these. Empty atom represents `none` animation.
#[repr(transparent)] #[repr(transparent)]
#[derive( #[derive(
Clone, Debug, Hash, PartialEq, MallocSizeOf, SpecifiedValueInfo, ToComputedValue, ToResolvedValue, ToShmem, Clone,
Debug,
Hash,
PartialEq,
MallocSizeOf,
SpecifiedValueInfo,
ToComputedValue,
ToResolvedValue,
ToShmem,
)] )]
pub struct TimelineOrKeyframesName(Atom); pub struct TimelineOrKeyframesName(Atom);
@@ -539,7 +547,7 @@ impl TimelineOrKeyframesName {
debug_assert!(invalid.contains(&"none")); debug_assert!(invalid.contains(&"none"));
if self.0 == atom!("") { if self.0 == atom!("") {
return dest.write_str("none") return dest.write_str("none");
} }
self.0.with_str(|s| { self.0.with_str(|s| {
@@ -564,7 +572,17 @@ pub trait IsAuto {
/// The typedef of <timeline-name>. /// The typedef of <timeline-name>.
#[repr(transparent)] #[repr(transparent)]
#[derive( #[derive(
Clone, Debug, Deref, Hash, Eq, PartialEq, MallocSizeOf, SpecifiedValueInfo, ToComputedValue, ToResolvedValue, ToShmem, Clone,
Debug,
Deref,
Hash,
Eq,
PartialEq,
MallocSizeOf,
SpecifiedValueInfo,
ToComputedValue,
ToResolvedValue,
ToShmem,
)] )]
pub struct TimelineName(TimelineOrKeyframesName); pub struct TimelineName(TimelineOrKeyframesName);
@@ -582,8 +600,14 @@ impl TimelineName {
} }
impl Parse for TimelineName { impl Parse for TimelineName {
fn parse<'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { fn parse<'i, 't>(
Ok(Self(TimelineOrKeyframesName::parse(input, &["none", "auto"])?)) _: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Ok(Self(TimelineOrKeyframesName::parse(
input,
&["none", "auto"],
)?))
} }
} }
@@ -598,7 +622,17 @@ impl ToCss for TimelineName {
/// The typedef of <keyframes-name>. /// The typedef of <keyframes-name>.
#[derive( #[derive(
Clone, Debug, Deref, Hash, Eq, PartialEq, MallocSizeOf, SpecifiedValueInfo, ToComputedValue, ToResolvedValue, ToShmem, Clone,
Debug,
Deref,
Hash,
Eq,
PartialEq,
MallocSizeOf,
SpecifiedValueInfo,
ToComputedValue,
ToResolvedValue,
ToShmem,
)] )]
pub struct KeyframesName(TimelineOrKeyframesName); pub struct KeyframesName(TimelineOrKeyframesName);
@@ -616,7 +650,10 @@ impl KeyframesName {
} }
impl Parse for KeyframesName { impl Parse for KeyframesName {
fn parse<'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { fn parse<'i, 't>(
_: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Ok(Self(TimelineOrKeyframesName::parse(input, &["none"])?)) Ok(Self(TimelineOrKeyframesName::parse(input, &["none"])?))
} }
} }

View File

@@ -8,10 +8,14 @@ use crate::custom_properties::Name as CustomPropertyName;
use crate::parser::{Parse, ParserContext}; use crate::parser::{Parse, ParserContext};
use crate::properties::{LonghandId, PropertyDeclarationId}; use crate::properties::{LonghandId, PropertyDeclarationId};
use crate::properties::{PropertyId, ShorthandId}; use crate::properties::{PropertyId, ShorthandId};
use crate::values::generics::box_::{GenericAnimationIterationCount, GenericPerspective, GenericLineClamp}; use crate::values::generics::box_::{
use crate::values::generics::box_::{GenericContainIntrinsicSize, GenericVerticalAlign, VerticalAlignKeyword}; GenericAnimationIterationCount, GenericLineClamp, GenericPerspective,
};
use crate::values::generics::box_::{
GenericContainIntrinsicSize, GenericVerticalAlign, VerticalAlignKeyword,
};
use crate::values::specified::length::{LengthPercentage, NonNegativeLength}; use crate::values::specified::length::{LengthPercentage, NonNegativeLength};
use crate::values::specified::{AllowQuirks, Number, Integer}; use crate::values::specified::{AllowQuirks, Integer, Number};
use crate::values::{CustomIdent, KeyframesName, TimelineName}; use crate::values::{CustomIdent, KeyframesName, TimelineName};
use crate::Atom; use crate::Atom;
use cssparser::Parser; use cssparser::Parser;
@@ -885,7 +889,10 @@ impl Parse for AnimationTimeline {
} }
// https://drafts.csswg.org/scroll-animations-1/rewrite#scroll-notation // https://drafts.csswg.org/scroll-animations-1/rewrite#scroll-notation
if input.try_parse(|i| i.expect_function_matching("scroll")).is_ok() { if input
.try_parse(|i| i.expect_function_matching("scroll"))
.is_ok()
{
return input.parse_nested_block(|i| { return input.parse_nested_block(|i| {
Ok(Self::Scroll( Ok(Self::Scroll(
i.try_parse(ScrollAxis::parse).unwrap_or(ScrollAxis::Block), i.try_parse(ScrollAxis::parse).unwrap_or(ScrollAxis::Block),
@@ -1450,9 +1457,7 @@ impl Parse for ContainIntrinsicSize {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
if let Ok(l) = input.try_parse(|i| NonNegativeLength::parse(context, i)) {
if let Ok(l) = input.try_parse(|i| NonNegativeLength::parse(context, i))
{
return Ok(Self::Length(l)); return Ok(Self::Length(l));
} }
@@ -1472,9 +1477,10 @@ impl Parse for LineClamp {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
if let Ok(i) = input.try_parse(|i| crate::values::specified::PositiveInteger::parse(context, i)) if let Ok(i) =
input.try_parse(|i| crate::values::specified::PositiveInteger::parse(context, i))
{ {
return Ok(Self(i.0)) return Ok(Self(i.0));
} }
input.expect_ident_matching("none")?; input.expect_ident_matching("none")?;
Ok(Self::none()) Ok(Self::none())
@@ -1531,7 +1537,17 @@ bitflags! {
/// https://drafts.csswg.org/css-contain-3/#container-name /// https://drafts.csswg.org/css-contain-3/#container-name
#[repr(transparent)] #[repr(transparent)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, ToResolvedValue, ToShmem)] #[derive(
Clone,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
pub struct ContainerName(#[css(iterable, if_empty = "none")] pub crate::OwnedSlice<CustomIdent>); pub struct ContainerName(#[css(iterable, if_empty = "none")] pub crate::OwnedSlice<CustomIdent>);
impl ContainerName { impl ContainerName {
@@ -1547,17 +1563,29 @@ impl ContainerName {
} }
impl Parse for ContainerName { impl Parse for ContainerName {
fn parse<'i, 't>( _: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { fn parse<'i, 't>(
_: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let mut idents = vec![]; let mut idents = vec![];
let location = input.current_source_location(); let location = input.current_source_location();
let first = input.expect_ident()?; let first = input.expect_ident()?;
if first.eq_ignore_ascii_case("none") { if first.eq_ignore_ascii_case("none") {
return Ok(Self::none()) return Ok(Self::none());
} }
const DISALLOWED_CONTAINER_NAMES: &'static [&'static str] = &["none", "not", "or", "and", "auto", "normal"]; const DISALLOWED_CONTAINER_NAMES: &'static [&'static str] =
idents.push(CustomIdent::from_ident(location, first, DISALLOWED_CONTAINER_NAMES)?); &["none", "not", "or", "and", "auto", "normal"];
idents.push(CustomIdent::from_ident(
location,
first,
DISALLOWED_CONTAINER_NAMES,
)?);
while let Ok(ident) = input.try_parse(|input| input.expect_ident_cloned()) { while let Ok(ident) = input.try_parse(|input| input.expect_ident_cloned()) {
idents.push(CustomIdent::from_ident(location, &ident, DISALLOWED_CONTAINER_NAMES)?); idents.push(CustomIdent::from_ident(
location,
&ident,
DISALLOWED_CONTAINER_NAMES,
)?);
} }
Ok(ContainerName(idents.into())) Ok(ContainerName(idents.into()))
} }
@@ -2180,7 +2208,10 @@ pub enum Overflow {
// This can be derived once we remove or keep `-moz-hidden-unscrollable` // This can be derived once we remove or keep `-moz-hidden-unscrollable`
// indefinitely. // indefinitely.
impl Parse for Overflow { impl Parse for Overflow {
fn parse<'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { fn parse<'i, 't>(
_: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Ok(try_match_ident_ignore_ascii_case! { input, Ok(try_match_ident_ignore_ascii_case! { input,
"visible" => Self::Visible, "visible" => Self::Visible,
"hidden" => Self::Hidden, "hidden" => Self::Hidden,

View File

@@ -142,11 +142,10 @@ impl CalcLengthPercentage {
let a = a.as_length()?.unitless_value(); let a = a.as_length()?.unitless_value();
let b = b.as_length()?.unitless_value(); let b = b.as_length()?.unitless_value();
return Some((a, b)) return Some((a, b));
} }
} }
impl SpecifiedValueInfo for CalcLengthPercentage {} impl SpecifiedValueInfo for CalcLengthPercentage {}
impl PartialOrd for Leaf { impl PartialOrd for Leaf {
@@ -321,7 +320,9 @@ impl CalcNode {
let location = input.current_source_location(); let location = input.current_source_location();
match input.next()? { match input.next()? {
&Token::Number { value, .. } => Ok(CalcNode::Leaf(Leaf::Number(value))), &Token::Number { value, .. } => Ok(CalcNode::Leaf(Leaf::Number(value))),
&Token::Dimension { value, ref unit, .. } => { &Token::Dimension {
value, ref unit, ..
} => {
if allowed_units.intersects(CalcUnits::LENGTH) { if allowed_units.intersects(CalcUnits::LENGTH) {
if let Ok(l) = NoCalcLength::parse_dimension(context, value, unit) { if let Ok(l) = NoCalcLength::parse_dimension(context, value, unit) {
return Ok(CalcNode::Leaf(Leaf::Length(l))); return Ok(CalcNode::Leaf(Leaf::Length(l)));
@@ -337,11 +338,13 @@ impl CalcNode {
return Ok(CalcNode::Leaf(Leaf::Time(t))); return Ok(CalcNode::Leaf(Leaf::Time(t)));
} }
} }
return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)) return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}, },
&Token::Percentage { unit_value, .. } if allowed_units.intersects(CalcUnits::PERCENTAGE) => { &Token::Percentage { unit_value, .. }
if allowed_units.intersects(CalcUnits::PERCENTAGE) =>
{
Ok(CalcNode::Leaf(Leaf::Percentage(unit_value))) Ok(CalcNode::Leaf(Leaf::Percentage(unit_value)))
} },
&Token::ParenthesisBlock => input.parse_nested_block(|input| { &Token::ParenthesisBlock => input.parse_nested_block(|input| {
CalcNode::parse_argument(context, input, allowed_units) CalcNode::parse_argument(context, input, allowed_units)
}), }),
@@ -487,9 +490,11 @@ impl CalcNode {
let radians = match resolve_atan2(a, b) { let radians = match resolve_atan2(a, b) {
Ok(v) => v, Ok(v) => v,
Err(()) => return Err( Err(()) => {
return Err(
input.new_custom_error(StyleParseErrorKind::UnspecifiedError) input.new_custom_error(StyleParseErrorKind::UnspecifiedError)
), )
},
}; };
Ok(Self::Leaf(Leaf::Angle(Angle::from_radians(radians)))) Ok(Self::Leaf(Leaf::Angle(Angle::from_radians(radians))))
@@ -581,9 +586,11 @@ impl CalcNode {
// TODO(emilio): Eventually it should be. // TODO(emilio): Eventually it should be.
let number = match rhs.to_number() { let number = match rhs.to_number() {
Ok(n) if n != 0. || nan_inf_enabled() => n, Ok(n) if n != 0. || nan_inf_enabled() => n,
_ => return Err( _ => {
return Err(
input.new_custom_error(StyleParseErrorKind::UnspecifiedError) input.new_custom_error(StyleParseErrorKind::UnspecifiedError)
), )
},
}; };
node.mul_by(1. / number); node.mul_by(1. / number);
}, },

View File

@@ -7,7 +7,9 @@
use super::AllowQuirks; use super::AllowQuirks;
use crate::parser::{Parse, ParserContext}; use crate::parser::{Parse, ParserContext};
use crate::values::computed::{Color as ComputedColor, Context, ToComputedValue}; use crate::values::computed::{Color as ComputedColor, Context, ToComputedValue};
use crate::values::generics::color::{ColorInterpolationMethod, GenericColorMix, GenericCaretColor, GenericColorOrAuto}; use crate::values::generics::color::{
ColorInterpolationMethod, GenericCaretColor, GenericColorMix, GenericColorOrAuto,
};
use crate::values::specified::calc::CalcNode; use crate::values::specified::calc::CalcNode;
use crate::values::specified::Percentage; use crate::values::specified::Percentage;
use crate::values::CustomIdent; use crate::values::CustomIdent;
@@ -618,7 +620,9 @@ impl Color {
let mut written = space_padding; let mut written = space_padding;
let mut buf = itoa::Buffer::new(); let mut buf = itoa::Buffer::new();
let s = buf.format(value); let s = buf.format(value);
(&mut serialization[written..]).write_all(s.as_bytes()).unwrap(); (&mut serialization[written..])
.write_all(s.as_bytes())
.unwrap();
written += s.len(); written += s.len();
if let Some(unit) = unit { if let Some(unit) = unit {
written += (&mut serialization[written..]) written += (&mut serialization[written..])

View File

@@ -110,10 +110,12 @@ impl TimingFunction {
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
let steps = Integer::parse_positive(context, input)?; let steps = Integer::parse_positive(context, input)?;
let position = input.try_parse(|i| { let position = input
.try_parse(|i| {
i.expect_comma()?; i.expect_comma()?;
StepPosition::parse(context, i) StepPosition::parse(context, i)
}).unwrap_or(StepPosition::End); })
.unwrap_or(StepPosition::End);
// jump-none accepts a positive integer greater than 1. // jump-none accepts a positive integer greater than 1.
// FIXME(emilio): The spec asks us to avoid rejecting it at parse // FIXME(emilio): The spec asks us to avoid rejecting it at parse
@@ -149,10 +151,19 @@ impl TimingFunction {
input_start = i.try_parse(|i| Percentage::parse(context, i)).ok(); input_start = i.try_parse(|i| Percentage::parse(context, i)).ok();
input_end = i.try_parse(|i| Percentage::parse(context, i)).ok(); input_end = i.try_parse(|i| Percentage::parse(context, i)).ok();
} }
result.push(LinearStop { output, input: input_start.into() }); result.push(LinearStop {
output,
input: input_start.into(),
});
if input_end.is_some() { if input_end.is_some() {
debug_assert!(input_start.is_some(), "Input end valid but not input start?"); debug_assert!(
result.push(LinearStop { output, input: input_end.into() }); input_start.is_some(),
"Input end valid but not input start?"
);
result.push(LinearStop {
output,
input: input_end.into(),
});
} }
Ok(()) Ok(())

View File

@@ -8,8 +8,8 @@ use crate::context::QuirksMode;
use crate::parser::{Parse, ParserContext}; use crate::parser::{Parse, ParserContext};
use crate::values::computed::font::{FamilyName, FontFamilyList, SingleFontFamily}; use crate::values::computed::font::{FamilyName, FontFamilyList, SingleFontFamily};
use crate::values::computed::FontSizeAdjust as ComputedFontSizeAdjust; use crate::values::computed::FontSizeAdjust as ComputedFontSizeAdjust;
use crate::values::computed::{font as computed, Length, NonNegativeLength};
use crate::values::computed::Percentage as ComputedPercentage; use crate::values::computed::Percentage as ComputedPercentage;
use crate::values::computed::{font as computed, Length, NonNegativeLength};
use crate::values::computed::{CSSPixelLength, Context, ToComputedValue}; use crate::values::computed::{CSSPixelLength, Context, ToComputedValue};
use crate::values::generics::font::VariationValue; use crate::values::generics::font::VariationValue;
use crate::values::generics::font::{ use crate::values::generics::font::{
@@ -187,9 +187,7 @@ impl AbsoluteFontWeight {
/// Returns the computed value for this absolute font weight. /// Returns the computed value for this absolute font weight.
pub fn compute(&self) -> computed::FontWeight { pub fn compute(&self) -> computed::FontWeight {
match *self { match *self {
AbsoluteFontWeight::Weight(weight) => { AbsoluteFontWeight::Weight(weight) => computed::FontWeight::from_float(weight.get()),
computed::FontWeight::from_float(weight.get())
},
AbsoluteFontWeight::Normal => computed::FontWeight::NORMAL, AbsoluteFontWeight::Normal => computed::FontWeight::NORMAL,
AbsoluteFontWeight::Bold => computed::FontWeight::BOLD, AbsoluteFontWeight::Bold => computed::FontWeight::BOLD,
} }
@@ -438,7 +436,7 @@ impl ToComputedValue for FontStretch {
fn from_computed_value(computed: &Self::ComputedValue) -> Self { fn from_computed_value(computed: &Self::ComputedValue) -> Self {
FontStretch::Stretch(NonNegativePercentage::from_computed_value(&NonNegative( FontStretch::Stretch(NonNegativePercentage::from_computed_value(&NonNegative(
computed.to_percentage() computed.to_percentage(),
))) )))
} }
} }
@@ -777,7 +775,9 @@ impl FontSizeKeyword {
fn to_length(&self, cx: &Context) -> NonNegativeLength { fn to_length(&self, cx: &Context) -> NonNegativeLength {
let gecko_font = cx.style().get_font().gecko(); let gecko_font = cx.style().get_font().gecko();
let family = &gecko_font.mFont.family.families; let family = &gecko_font.mFont.family.families;
let generic = family.single_generic().unwrap_or(computed::GenericFontFamily::None); let generic = family
.single_generic()
.unwrap_or(computed::GenericFontFamily::None);
let base_size = unsafe { let base_size = unsafe {
Atom::with(gecko_font.mLanguage.mRawPtr, |language| { Atom::with(gecko_font.mLanguage.mRawPtr, |language| {
cx.device().base_size_for_generic(language, generic) cx.device().base_size_for_generic(language, generic)

View File

@@ -304,12 +304,16 @@ impl CrossFade {
} }
impl CrossFadeElement { impl CrossFadeElement {
fn parse_percentage<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Option<Percentage> { fn parse_percentage<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Option<Percentage> {
// We clamp our values here as this is the way that Safari and Chrome's // We clamp our values here as this is the way that Safari and Chrome's
// implementation handle out-of-bounds percentages but whether or not // implementation handle out-of-bounds percentages but whether or not
// this behavior follows the specification is still being discussed. // this behavior follows the specification is still being discussed.
// See: <https://github.com/w3c/csswg-drafts/issues/5333> // See: <https://github.com/w3c/csswg-drafts/issues/5333>
input.try_parse(|input| Percentage::parse_non_negative(context, input)) input
.try_parse(|input| Percentage::parse_non_negative(context, input))
.ok() .ok()
.map(|p| p.clamp_to_hundred()) .map(|p| p.clamp_to_hundred())
} }

View File

@@ -162,11 +162,7 @@ impl FontRelativeLength {
orientation: FontMetricsOrientation, orientation: FontMetricsOrientation,
) -> FontMetrics { ) -> FontMetrics {
let retrieve_math_scales = false; let retrieve_math_scales = false;
context.query_font_metrics( context.query_font_metrics(base_size, orientation, retrieve_math_scales)
base_size,
orientation,
retrieve_math_scales,
)
} }
let reference_font_size = base_size.resolve(context); let reference_font_size = base_size.resolve(context);
@@ -404,125 +400,34 @@ impl ViewportPercentageLength {
fn unpack(&self) -> (ViewportVariant, ViewportUnit, CSSFloat) { fn unpack(&self) -> (ViewportVariant, ViewportUnit, CSSFloat) {
match *self { match *self {
ViewportPercentageLength::Vw(v) => ( ViewportPercentageLength::Vw(v) => (ViewportVariant::UADefault, ViewportUnit::Vw, v),
ViewportVariant::UADefault, ViewportPercentageLength::Svw(v) => (ViewportVariant::Small, ViewportUnit::Vw, v),
ViewportUnit::Vw, ViewportPercentageLength::Lvw(v) => (ViewportVariant::Large, ViewportUnit::Vw, v),
v, ViewportPercentageLength::Dvw(v) => (ViewportVariant::Dynamic, ViewportUnit::Vw, v),
), ViewportPercentageLength::Vh(v) => (ViewportVariant::UADefault, ViewportUnit::Vh, v),
ViewportPercentageLength::Svw(v) => ( ViewportPercentageLength::Svh(v) => (ViewportVariant::Small, ViewportUnit::Vh, v),
ViewportVariant::Small, ViewportPercentageLength::Lvh(v) => (ViewportVariant::Large, ViewportUnit::Vh, v),
ViewportUnit::Vw, ViewportPercentageLength::Dvh(v) => (ViewportVariant::Dynamic, ViewportUnit::Vh, v),
v, ViewportPercentageLength::Vmin(v) => {
), (ViewportVariant::UADefault, ViewportUnit::Vmin, v)
ViewportPercentageLength::Lvw(v) => ( },
ViewportVariant::Large, ViewportPercentageLength::Svmin(v) => (ViewportVariant::Small, ViewportUnit::Vmin, v),
ViewportUnit::Vw, ViewportPercentageLength::Lvmin(v) => (ViewportVariant::Large, ViewportUnit::Vmin, v),
v, ViewportPercentageLength::Dvmin(v) => (ViewportVariant::Dynamic, ViewportUnit::Vmin, v),
), ViewportPercentageLength::Vmax(v) => {
ViewportPercentageLength::Dvw(v) => ( (ViewportVariant::UADefault, ViewportUnit::Vmax, v)
ViewportVariant::Dynamic, },
ViewportUnit::Vw, ViewportPercentageLength::Svmax(v) => (ViewportVariant::Small, ViewportUnit::Vmax, v),
v, ViewportPercentageLength::Lvmax(v) => (ViewportVariant::Large, ViewportUnit::Vmax, v),
), ViewportPercentageLength::Dvmax(v) => (ViewportVariant::Dynamic, ViewportUnit::Vmax, v),
ViewportPercentageLength::Vh(v) => ( ViewportPercentageLength::Vb(v) => (ViewportVariant::UADefault, ViewportUnit::Vb, v),
ViewportVariant::UADefault, ViewportPercentageLength::Svb(v) => (ViewportVariant::Small, ViewportUnit::Vb, v),
ViewportUnit::Vh, ViewportPercentageLength::Lvb(v) => (ViewportVariant::Large, ViewportUnit::Vb, v),
v, ViewportPercentageLength::Dvb(v) => (ViewportVariant::Dynamic, ViewportUnit::Vb, v),
), ViewportPercentageLength::Vi(v) => (ViewportVariant::UADefault, ViewportUnit::Vi, v),
ViewportPercentageLength::Svh(v) => ( ViewportPercentageLength::Svi(v) => (ViewportVariant::Small, ViewportUnit::Vi, v),
ViewportVariant::Small, ViewportPercentageLength::Lvi(v) => (ViewportVariant::Large, ViewportUnit::Vi, v),
ViewportUnit::Vh, ViewportPercentageLength::Dvi(v) => (ViewportVariant::Dynamic, ViewportUnit::Vi, v),
v,
),
ViewportPercentageLength::Lvh(v) => (
ViewportVariant::Large,
ViewportUnit::Vh,
v),
ViewportPercentageLength::Dvh(v) => (
ViewportVariant::Dynamic,
ViewportUnit::Vh,
v,
),
ViewportPercentageLength::Vmin(v) => (
ViewportVariant::UADefault,
ViewportUnit::Vmin,
v,
),
ViewportPercentageLength::Svmin(v) => (
ViewportVariant::Small,
ViewportUnit::Vmin,
v,
),
ViewportPercentageLength::Lvmin(v) => (
ViewportVariant::Large,
ViewportUnit::Vmin,
v,
),
ViewportPercentageLength::Dvmin(v) => (
ViewportVariant::Dynamic,
ViewportUnit::Vmin,
v,
),
ViewportPercentageLength::Vmax(v) => (
ViewportVariant::UADefault,
ViewportUnit::Vmax,
v,
),
ViewportPercentageLength::Svmax(v) => (
ViewportVariant::Small,
ViewportUnit::Vmax,
v,
),
ViewportPercentageLength::Lvmax(v) => (
ViewportVariant::Large,
ViewportUnit::Vmax,
v,
),
ViewportPercentageLength::Dvmax(v) => (
ViewportVariant::Dynamic,
ViewportUnit::Vmax,
v,
),
ViewportPercentageLength::Vb(v) => (
ViewportVariant::UADefault,
ViewportUnit::Vb,
v,
),
ViewportPercentageLength::Svb(v) => (
ViewportVariant::Small,
ViewportUnit::Vb,
v,
),
ViewportPercentageLength::Lvb(v) => (
ViewportVariant::Large,
ViewportUnit::Vb,
v,
),
ViewportPercentageLength::Dvb(v) => (
ViewportVariant::Dynamic,
ViewportUnit::Vb,
v,
),
ViewportPercentageLength::Vi(v) => (
ViewportVariant::UADefault,
ViewportUnit::Vi,
v,
),
ViewportPercentageLength::Svi(v) => (
ViewportVariant::Small,
ViewportUnit::Vi,
v,
),
ViewportPercentageLength::Lvi(v) => (
ViewportVariant::Large,
ViewportUnit::Vi,
v,
),
ViewportPercentageLength::Dvi(v) => (
ViewportVariant::Dynamic,
ViewportUnit::Vi,
v,
),
} }
} }
@@ -562,11 +467,9 @@ impl ViewportPercentageLength {
// able to figure it own on its own so we help. // able to figure it own on its own so we help.
_ => unsafe { _ => unsafe {
match *self { match *self {
Vw(..) | Svw(..) | Lvw(..) | Dvw(..) | Vw(..) | Svw(..) | Lvw(..) | Dvw(..) | Vh(..) | Svh(..) | Lvh(..) |
Vh(..) | Svh(..) | Lvh(..) | Dvh(..) | Dvh(..) | Vmin(..) | Svmin(..) | Lvmin(..) | Dvmin(..) | Vmax(..) |
Vmin(..) | Svmin(..) | Lvmin(..) | Dvmin(..) | Svmax(..) | Lvmax(..) | Dvmax(..) | Vb(..) | Svb(..) | Lvb(..) | Dvb(..) |
Vmax(..) | Svmax(..) | Lvmax(..) | Dvmax(..) |
Vb(..) | Svb(..) | Lvb(..) | Dvb(..) |
Vi(..) | Svi(..) | Lvi(..) | Dvi(..) => {}, Vi(..) | Svi(..) | Lvi(..) | Dvi(..) => {},
} }
debug_unreachable!("Forgot to handle unit in try_sum()") debug_unreachable!("Forgot to handle unit in try_sum()")
@@ -809,10 +712,8 @@ impl NoCalcLength {
/// because the font they're relative to should be zoomed already. /// because the font they're relative to should be zoomed already.
pub fn should_zoom_text(&self) -> bool { pub fn should_zoom_text(&self) -> bool {
match *self { match *self {
Self::Absolute(..) | Self::Absolute(..) | Self::ViewportPercentage(..) => true,
Self::ViewportPercentage(..) => true, Self::ServoCharacterWidth(..) | Self::FontRelative(..) => false,
Self::ServoCharacterWidth(..) |
Self::FontRelative(..) => false,
} }
} }
@@ -1157,11 +1058,9 @@ impl PartialOrd for ViewportPercentageLength {
// able to figure it own on its own so we help. // able to figure it own on its own so we help.
_ => unsafe { _ => unsafe {
match *self { match *self {
Vw(..) | Svw(..) | Lvw(..) | Dvw(..) | Vw(..) | Svw(..) | Lvw(..) | Dvw(..) | Vh(..) | Svh(..) | Lvh(..) |
Vh(..) | Svh(..) | Lvh(..) | Dvh(..) | Dvh(..) | Vmin(..) | Svmin(..) | Lvmin(..) | Dvmin(..) | Vmax(..) |
Vmin(..) | Svmin(..) | Lvmin(..) | Dvmin(..) | Svmax(..) | Lvmax(..) | Dvmax(..) | Vb(..) | Svb(..) | Lvb(..) | Dvb(..) |
Vmax(..) | Svmax(..) | Lvmax(..) | Dvmax(..) |
Vb(..) | Svb(..) | Lvb(..) | Dvb(..) |
Vi(..) | Svi(..) | Lvi(..) | Dvi(..) => {}, Vi(..) | Svi(..) | Lvi(..) | Dvi(..) => {},
} }
debug_unreachable!("Forgot an arm in partial_cmp?") debug_unreachable!("Forgot an arm in partial_cmp?")

View File

@@ -38,7 +38,9 @@ pub use self::border::{BorderImageRepeat, BorderImageSideWidth};
pub use self::border::{BorderRadius, BorderSideWidth, BorderSpacing, BorderStyle}; pub use self::border::{BorderRadius, BorderSideWidth, BorderSpacing, BorderStyle};
pub use self::box_::{AnimationIterationCount, AnimationName, AnimationTimeline, Contain, Display}; pub use self::box_::{AnimationIterationCount, AnimationName, AnimationTimeline, Contain, Display};
pub use self::box_::{Appearance, BreakBetween, BreakWithin, ContainerName, ContainerType}; pub use self::box_::{Appearance, BreakBetween, BreakWithin, ContainerName, ContainerType};
pub use self::box_::{Clear, ContentVisibility, ContainIntrinsicSize, LineClamp, Float, Overflow, OverflowAnchor}; pub use self::box_::{
Clear, ContainIntrinsicSize, ContentVisibility, Float, LineClamp, Overflow, OverflowAnchor,
};
pub use self::box_::{OverflowClipBox, OverscrollBehavior, Perspective, Resize, ScrollbarGutter}; pub use self::box_::{OverflowClipBox, OverscrollBehavior, Perspective, Resize, ScrollbarGutter};
pub use self::box_::{ScrollAxis, ScrollSnapAlign, ScrollSnapAxis, ScrollSnapStop}; pub use self::box_::{ScrollAxis, ScrollSnapAlign, ScrollSnapAxis, ScrollSnapStop};
pub use self::box_::{ScrollSnapStrictness, ScrollSnapType, ScrollTimelineName}; pub use self::box_::{ScrollSnapStrictness, ScrollSnapType, ScrollTimelineName};
@@ -70,7 +72,7 @@ pub use self::list::ListStyleType;
pub use self::list::Quotes; pub use self::list::Quotes;
pub use self::motion::{OffsetPath, OffsetRotate}; pub use self::motion::{OffsetPath, OffsetRotate};
pub use self::outline::OutlineStyle; pub use self::outline::OutlineStyle;
pub use self::page::{PageOrientation, PageName, PageSize, PaperSize}; pub use self::page::{PageName, PageOrientation, PageSize, PaperSize};
pub use self::percentage::{NonNegativePercentage, Percentage}; pub use self::percentage::{NonNegativePercentage, Percentage};
pub use self::position::AspectRatio; pub use self::position::AspectRatio;
pub use self::position::{ pub use self::position::{
@@ -97,7 +99,7 @@ pub use self::transform::{Rotate, Scale, Transform};
pub use self::transform::{TransformOrigin, TransformStyle, Translate}; pub use self::transform::{TransformOrigin, TransformStyle, Translate};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
pub use self::ui::CursorImage; pub use self::ui::CursorImage;
pub use self::ui::{Cursor, BoolInteger, UserSelect}; pub use self::ui::{BoolInteger, Cursor, UserSelect};
pub use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent; pub use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent;
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]

View File

@@ -186,7 +186,9 @@ impl SpecifiedValueInfo for Percentage {}
/// Turns the percentage into a plain float. /// Turns the percentage into a plain float.
pub trait ToPercentage { pub trait ToPercentage {
/// Returns whether this percentage used to be a calc(). /// Returns whether this percentage used to be a calc().
fn is_calc(&self) -> bool { false } fn is_calc(&self) -> bool {
false
}
/// Turns the percentage into a plain float. /// Turns the percentage into a plain float.
fn to_percentage(&self) -> CSSFloat; fn to_percentage(&self) -> CSSFloat;
} }

View File

@@ -8,7 +8,7 @@
use crate::gecko_bindings::sugar::ownership::{HasBoxFFI, HasFFI, HasSimpleFFI}; use crate::gecko_bindings::sugar::ownership::{HasBoxFFI, HasFFI, HasSimpleFFI};
use crate::media_queries::Device; use crate::media_queries::Device;
use crate::parser::{Parse, ParserContext}; use crate::parser::{Parse, ParserContext};
use crate::queries::{QueryCondition, FeatureType}; use crate::queries::{FeatureType, QueryCondition};
use crate::values::computed::{self, ToComputedValue}; use crate::values::computed::{self, ToComputedValue};
use crate::values::specified::{Length, NoCalcLength, ViewportPercentageLength}; use crate::values::specified::{Length, NoCalcLength, ViewportPercentageLength};
use app_units::Au; use app_units::Au;

View File

@@ -4,9 +4,9 @@
use crate::to_css::{CssBitflagAttrs, CssVariantAttrs}; use crate::to_css::{CssBitflagAttrs, CssVariantAttrs};
use derive_common::cg; use derive_common::cg;
use proc_macro2::{TokenStream, Span}; use proc_macro2::{Span, TokenStream};
use quote::TokenStreamExt; use quote::TokenStreamExt;
use syn::{self, Ident, DeriveInput, Path}; use syn::{self, DeriveInput, Ident, Path};
use synstructure::{Structure, VariantInfo}; use synstructure::{Structure, VariantInfo};
#[derive(Default, FromVariant)] #[derive(Default, FromVariant)]
@@ -109,9 +109,12 @@ fn parse_non_keyword_variant(
if let Some(ref bitflags) = variant_attrs.bitflags { if let Some(ref bitflags) = variant_attrs.bitflags {
assert!(skip_try, "Should be the only variant"); assert!(skip_try, "Should be the only variant");
assert!(parse_attrs.condition.is_none(), "Should be the only variant"); assert!(
parse_attrs.condition.is_none(),
"Should be the only variant"
);
assert!(where_clause.is_none(), "Generic bitflags?"); assert!(where_clause.is_none(), "Generic bitflags?");
return parse_bitflags(bitflags) return parse_bitflags(bitflags);
} }
let field_attrs = cg::parse_field_attrs::<ParseFieldAttrs>(binding_ast); let field_attrs = cg::parse_field_attrs::<ParseFieldAttrs>(binding_ast);

View File

@@ -96,7 +96,10 @@ pub fn derive(mut input: syn::DeriveInput) -> TokenStream {
} }
if let Some(ref bitflags) = input_attrs.bitflags { if let Some(ref bitflags) = input_attrs.bitflags {
assert!(!input_attrs.derive_debug, "Bitflags can derive debug on their own"); assert!(
!input_attrs.derive_debug,
"Bitflags can derive debug on their own"
);
assert!(where_clause.is_none(), "Generic bitflags?"); assert!(where_clause.is_none(), "Generic bitflags?");
return derive_bitflags(&input, bitflags); return derive_bitflags(&input, bitflags);
} }

View File

@@ -28,7 +28,7 @@ use style::data::{self, ElementStyles};
use style::dom::{ShowSubtreeData, TDocument, TElement, TNode}; use style::dom::{ShowSubtreeData, TDocument, TElement, TNode};
use style::driver; use style::driver;
use style::error_reporting::{ContextualParseError, ParseErrorReporter}; use style::error_reporting::{ContextualParseError, ParseErrorReporter};
use style::font_face::{self, FontFaceSourceListComponent, FontFaceSourceFormat, Source}; use style::font_face::{self, FontFaceSourceFormat, FontFaceSourceListComponent, Source};
use style::gecko::data::{GeckoStyleSheet, PerDocumentStyleData, PerDocumentStyleDataImpl}; use style::gecko::data::{GeckoStyleSheet, PerDocumentStyleData, PerDocumentStyleDataImpl};
use style::gecko::restyle_damage::GeckoRestyleDamage; use style::gecko::restyle_damage::GeckoRestyleDamage;
use style::gecko::selector_parser::{NonTSPseudoClass, PseudoElement}; use style::gecko::selector_parser::{NonTSPseudoClass, PseudoElement};
@@ -130,14 +130,16 @@ use style::traversal::resolve_style;
use style::traversal::DomTraversal; use style::traversal::DomTraversal;
use style::traversal_flags::{self, TraversalFlags}; use style::traversal_flags::{self, TraversalFlags};
use style::use_counters::UseCounters; use style::use_counters::UseCounters;
use style::values::animated::{Animate, Procedure, ToAnimatedZero};
use style::values::animated::color::AnimatedRGBA; use style::values::animated::color::AnimatedRGBA;
use style::values::generics::color::ColorInterpolationMethod; use style::values::animated::{Animate, Procedure, ToAnimatedZero};
use style::values::generics::easing::BeforeFlag;
use style::values::computed::font::{FontFamily, FontFamilyList, GenericFontFamily, FontWeight, FontStyle, FontStretch};
use style::values::computed::easing::ComputedTimingFunction; use style::values::computed::easing::ComputedTimingFunction;
use style::values::computed::font::{
FontFamily, FontFamilyList, FontStretch, FontStyle, FontWeight, GenericFontFamily,
};
use style::values::computed::{self, Context, ToComputedValue}; use style::values::computed::{self, Context, ToComputedValue};
use style::values::distance::ComputeSquaredDistance; use style::values::distance::ComputeSquaredDistance;
use style::values::generics::color::ColorInterpolationMethod;
use style::values::generics::easing::BeforeFlag;
use style::values::specified::gecko::IntersectionObserverRootMargin; use style::values::specified::gecko::IntersectionObserverRootMargin;
use style::values::specified::source_size_list::SourceSizeList; use style::values::specified::source_size_list::SourceSizeList;
use style::values::{specified, AtomIdent, CustomIdent, KeyframesName}; use style::values::{specified, AtomIdent, CustomIdent, KeyframesName};
@@ -2453,7 +2455,9 @@ pub extern "C" fn Servo_StyleRule_SelectorMatchesElement(
pseudo_type: PseudoStyleType, pseudo_type: PseudoStyleType,
relevant_link_visited: bool, relevant_link_visited: bool,
) -> bool { ) -> bool {
use selectors::matching::{matches_selector, MatchingContext, MatchingMode, VisitedHandlingMode, NeedsSelectorFlags}; use selectors::matching::{
matches_selector, MatchingContext, MatchingMode, NeedsSelectorFlags, VisitedHandlingMode,
};
read_locked_arc(rule, |rule: &StyleRule| { read_locked_arc(rule, |rule: &StyleRule| {
let index = index as usize; let index = index as usize;
if index >= rule.selectors.0.len() { if index >= rule.selectors.0.len() {
@@ -2834,10 +2838,7 @@ pub extern "C" fn Servo_PageRule_SetStyle(
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn Servo_PageRule_GetSelectorText( pub extern "C" fn Servo_PageRule_GetSelectorText(rule: &RawServoPageRule, result: &mut nsACString) {
rule: &RawServoPageRule,
result: &mut nsACString,
) {
read_locked_arc(rule, |rule: &PageRule| { read_locked_arc(rule, |rule: &PageRule| {
rule.selectors.to_css(&mut CssWriter::new(result)).unwrap(); rule.selectors.to_css(&mut CssWriter::new(result)).unwrap();
}) })
@@ -2849,7 +2850,6 @@ pub extern "C" fn Servo_PageRule_SetSelectorText(
rule: &RawServoPageRule, rule: &RawServoPageRule,
text: &nsACString, text: &nsACString,
) -> bool { ) -> bool {
let value_str = unsafe { text.as_str_unchecked() }; let value_str = unsafe { text.as_str_unchecked() };
write_locked_arc(rule, |rule: &mut PageRule| { write_locked_arc(rule, |rule: &mut PageRule| {
@@ -2886,7 +2886,6 @@ pub extern "C" fn Servo_PageRule_SetSelectorText(
}) })
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn Servo_SupportsRule_GetConditionText( pub extern "C" fn Servo_SupportsRule_GetConditionText(
rule: &RawServoSupportsRule, rule: &RawServoSupportsRule,
@@ -2913,7 +2912,9 @@ pub extern "C" fn Servo_ContainerRule_GetContainerQuery(
result: &mut nsACString, result: &mut nsACString,
) { ) {
read_locked_arc(rule, |rule: &ContainerRule| { read_locked_arc(rule, |rule: &ContainerRule| {
rule.query_condition().to_css(&mut CssWriter::new(result)).unwrap(); rule.query_condition()
.to_css(&mut CssWriter::new(result))
.unwrap();
}) })
} }
@@ -2923,7 +2924,9 @@ pub extern "C" fn Servo_ContainerRule_QueryContainerFor(
element: &RawGeckoElement, element: &RawGeckoElement,
) -> *const RawGeckoElement { ) -> *const RawGeckoElement {
read_locked_arc(rule, |rule: &ContainerRule| { read_locked_arc(rule, |rule: &ContainerRule| {
rule.condition.find_container(GeckoElement(element)).map_or(ptr::null(), |result| result.element.0) rule.condition
.find_container(GeckoElement(element))
.map_or(ptr::null(), |result| result.element.0)
}) })
} }
@@ -3221,9 +3224,10 @@ pub unsafe extern "C" fn Servo_FontFaceRule_GetSources(
}; };
let len = sources.iter().fold(0, |acc, src| { let len = sources.iter().fold(0, |acc, src| {
acc + match *src { acc + match *src {
Source::Url(ref url) => Source::Url(ref url) => {
(if url.format_hint.is_some() { 2 } else { 1 }) + (if url.format_hint.is_some() { 2 } else { 1 }) +
(if url.tech_flags.is_empty() { 0 } else { 1 }), (if url.tech_flags.is_empty() { 0 } else { 1 })
},
Source::Local(_) => 1, Source::Local(_) => 1,
} }
}); });
@@ -3243,13 +3247,15 @@ pub unsafe extern "C" fn Servo_FontFaceRule_GetSources(
set_next(FontFaceSourceListComponent::Url(&url.url)); set_next(FontFaceSourceListComponent::Url(&url.url));
if let Some(hint) = &url.format_hint { if let Some(hint) = &url.format_hint {
match hint { match hint {
FontFaceSourceFormat::Keyword(kw) => FontFaceSourceFormat::Keyword(kw) => {
set_next(FontFaceSourceListComponent::FormatHintKeyword(*kw)), set_next(FontFaceSourceListComponent::FormatHintKeyword(*kw))
FontFaceSourceFormat::String(s) => },
FontFaceSourceFormat::String(s) => {
set_next(FontFaceSourceListComponent::FormatHintString { set_next(FontFaceSourceListComponent::FormatHintString {
length: s.len(), length: s.len(),
utf8_bytes: s.as_ptr(), utf8_bytes: s.as_ptr(),
}), })
},
} }
} }
if !url.tech_flags.is_empty() { if !url.tech_flags.is_empty() {
@@ -4074,11 +4080,7 @@ fn get_pseudo_style(
} }
Some(style.unwrap_or_else(|| { Some(style.unwrap_or_else(|| {
StyleBuilder::for_inheritance( StyleBuilder::for_inheritance(stylist.device(), Some(styles.primary()), Some(pseudo))
stylist.device(),
Some(styles.primary()),
Some(pseudo),
)
.build() .build()
})) }))
} }
@@ -4357,7 +4359,10 @@ pub unsafe extern "C" fn Servo_ParseProperty(
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn Servo_ParseEasing(easing: &nsACString, output: &mut ComputedTimingFunction) -> bool { pub extern "C" fn Servo_ParseEasing(
easing: &nsACString,
output: &mut ComputedTimingFunction,
) -> bool {
use style::properties::longhands::transition_timing_function; use style::properties::longhands::transition_timing_function;
let context = ParserContext::new( let context = ParserContext::new(
@@ -4767,8 +4772,7 @@ pub unsafe extern "C" fn Servo_DeclarationBlock_SetPropertyToAnimationValue(
) -> bool { ) -> bool {
let animation_value = AnimationValue::as_arc(&animation_value); let animation_value = AnimationValue::as_arc(&animation_value);
let non_custom_property_id = animation_value.id().into(); let non_custom_property_id = animation_value.id().into();
let mut source_declarations = let mut source_declarations = SourcePropertyDeclaration::with_one(animation_value.uncompute());
SourcePropertyDeclaration::with_one(animation_value.uncompute());
set_property_to_declarations( set_property_to_declarations(
Some(non_custom_property_id), Some(non_custom_property_id),
@@ -5089,7 +5093,7 @@ pub extern "C" fn Servo_DeclarationBlock_SetKeywordValue(
use style::values::generics::box_::{VerticalAlign, VerticalAlignKeyword}; use style::values::generics::box_::{VerticalAlign, VerticalAlignKeyword};
use style::values::generics::font::FontStyle; use style::values::generics::font::FontStyle;
use style::values::specified::{ use style::values::specified::{
table::CaptionSide, BorderStyle, Clear, Display, Float, TextAlign, TextEmphasisPosition table::CaptionSide, BorderStyle, Clear, Display, Float, TextAlign, TextEmphasisPosition,
}; };
fn get_from_computed<T>(value: u32) -> T fn get_from_computed<T>(value: u32) -> T
@@ -6995,8 +6999,8 @@ pub unsafe extern "C" fn Servo_ParseFontShorthandForMatching(
size: Option<&mut f32>, size: Option<&mut f32>,
) -> bool { ) -> bool {
use style::properties::shorthands::font; use style::properties::shorthands::font;
use style::values::specified::font as specified;
use style::values::generics::font::FontStyle as GenericFontStyle; use style::values::generics::font::FontStyle as GenericFontStyle;
use style::values::specified::font as specified;
let string = value.as_str_unchecked(); let string = value.as_str_unchecked();
let mut input = ParserInput::new(&string); let mut input = ParserInput::new(&string);
@@ -7064,12 +7068,20 @@ pub unsafe extern "C" fn Servo_ParseFontShorthandForMatching(
specified::FontSize::Keyword(info) => { specified::FontSize::Keyword(info) => {
// TODO: Maybe get a meaningful quirks / base size from the caller? // TODO: Maybe get a meaningful quirks / base size from the caller?
let quirks_mode = QuirksMode::NoQuirks; let quirks_mode = QuirksMode::NoQuirks;
info.kw.to_length_without_context(quirks_mode, computed::Length::new(specified::FONT_MEDIUM_PX)).0.px() info.kw
} .to_length_without_context(
quirks_mode,
computed::Length::new(specified::FONT_MEDIUM_PX),
)
.0
.px()
},
// smaller, larger not currently supported // smaller, larger not currently supported
specified::FontSize::Smaller | specified::FontSize::Larger | specified::FontSize::System(_) => { specified::FontSize::Smaller |
specified::FontSize::Larger |
specified::FontSize::System(_) => {
return false; return false;
} },
}; };
} }
@@ -7327,7 +7339,10 @@ pub extern "C" fn Servo_FontStretch_ToCss(s: &FontStretch, result: &mut nsACStri
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn Servo_FontStretch_SerializeKeyword(s: &FontStretch, result: &mut nsACString) -> bool { pub extern "C" fn Servo_FontStretch_SerializeKeyword(
s: &FontStretch,
result: &mut nsACString,
) -> bool {
let kw = match s.as_keyword() { let kw = match s.as_keyword() {
Some(kw) => kw, Some(kw) => kw,
None => return false, None => return false,
@@ -7488,7 +7503,7 @@ pub extern "C" fn Servo_InterpolateColor(
pub extern "C" fn Servo_EasingFunctionAt( pub extern "C" fn Servo_EasingFunctionAt(
easing_function: &ComputedTimingFunction, easing_function: &ComputedTimingFunction,
progress: f64, progress: f64,
before_flag: BeforeFlag before_flag: BeforeFlag,
) -> f64 { ) -> f64 {
easing_function.calculate_output(progress, before_flag, 1e-7) easing_function.calculate_output(progress, before_flag, 1e-7)
} }

View File

@@ -56,15 +56,9 @@ fn implied_input_spacing() {
.push(0.0, None) .push(0.0, None)
.push(1.0, None) .push(1.0, None)
.build(); .build();
assert!(implied_spacing assert!(implied_spacing.at(0.).approx_eq(&explicit_spacing.at(0.)));
.at(0.) assert!(implied_spacing.at(0.5).approx_eq(&explicit_spacing.at(0.5)));
.approx_eq(&explicit_spacing.at(0.))); assert!(implied_spacing.at(1.0).approx_eq(&explicit_spacing.at(1.0)));
assert!(implied_spacing
.at(0.5)
.approx_eq(&explicit_spacing.at(0.5)));
assert!(implied_spacing
.at(1.0)
.approx_eq(&explicit_spacing.at(1.0)));
} }
#[test] #[test]
@@ -136,9 +130,7 @@ fn out_of_bounds_flat() {
.push(1.0, Some(1.0)) .push(1.0, Some(1.0))
.push(1.0, Some(1.0)) .push(1.0, Some(1.0))
.build(); .build();
assert!(oob_flat assert!(oob_flat.at(0.0).approx_eq(&oob_flat.at(-0.25)));
.at(0.0)
.approx_eq(&oob_flat.at(-0.25)));
assert!(oob_flat.at(1.0).approx_eq(&oob_flat.at(1.25))); assert!(oob_flat.at(1.0).approx_eq(&oob_flat.at(1.25)));
} }