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
Родитель 92f5912f55
Коммит ebd19dfa4a
64 изменённых файлов: 768 добавлений и 570 удалений

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

@ -490,12 +490,18 @@ where
Component::Class(ref class) if quirks_mode != QuirksMode::Quirks => {
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 ==
// local_name_lower.
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
// lowercase. Otherwise we would need to test both hashes, and
// our data structures aren't really set up for that.
@ -505,7 +511,9 @@ where
local_name.precomputed_hash()
},
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;
}
selector.local_name.precomputed_hash()
@ -1912,7 +1920,7 @@ where
_ if !in_attr_selector => {
input.reset(&after_star);
default_namespace(None)
}
},
result => {
let t = result?;
Err(after_star

Просмотреть файл

@ -90,7 +90,8 @@ impl PropertyAnimation {
// and whether the iteration is reversed. For now, we skip this calculation
// by treating as if the flag is unset at all times.
// 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.

Просмотреть файл

@ -42,7 +42,10 @@ pub struct CascadePriority {
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 {
#[inline]

Просмотреть файл

@ -126,7 +126,10 @@ static CHROME_ENVIRONMENT_VARIABLES: [EnvironmentVariable; 6] = [
GTKCSDMaximizeButtonPosition,
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 {
@ -783,7 +786,11 @@ impl<'a> CustomPropertiesBuilder<'a> {
/// (meaning we should use the inherited value).
///
/// 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
// of Tarjan's algorithm. It is mostly based on the pseudo-code
// listed in

Просмотреть файл

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

Просмотреть файл

@ -6,10 +6,10 @@
use crate::gecko_bindings::bindings;
use crate::gecko_bindings::structs;
use crate::media_queries::{Device, MediaType};
use crate::queries::feature::{AllowsRanges, Evaluator, FeatureFlags, QueryFeatureDescription};
use crate::queries::values::Orientation;
use crate::media_queries::{Device, MediaType};
use crate::values::computed::{Context, CSSPixelLength, Ratio, Resolution};
use crate::values::computed::{CSSPixelLength, Context, Ratio, Resolution};
use app_units::Au;
use euclid::default::Size2D;
@ -89,7 +89,11 @@ pub enum DisplayMode {
/// https://w3c.github.io/manifest/#the-display-mode-media-feature
fn eval_display_mode(context: &Context, query_value: Option<DisplayMode>) -> bool {
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,
}
}
@ -139,7 +143,8 @@ fn eval_monochrome(context: &Context) -> u32 {
/// https://drafts.csswg.org/mediaqueries-4/#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)
}
@ -172,7 +177,10 @@ pub enum DynamicRange {
}
/// 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 =
unsafe { bindings::Gecko_MediaFeatures_PrefersReducedMotion(context.device().document()) };
let query_value = match query_value {
@ -317,8 +325,9 @@ fn do_eval_prefers_color_scheme(
use_content: bool,
query_value: Option<PrefersColorScheme>,
) -> bool {
let prefers_color_scheme =
unsafe { bindings::Gecko_MediaFeatures_PrefersColorScheme(context.device().document(), use_content) };
let prefers_color_scheme = unsafe {
bindings::Gecko_MediaFeatures_PrefersColorScheme(context.device().document(), use_content)
};
match query_value {
Some(v) => prefers_color_scheme == v,
None => true,
@ -867,7 +876,13 @@ pub static MEDIA_FEATURES: [QueryFeatureDescription; 61] = [
GTKCSDReversedPlacement
),
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
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"
),
];

Просмотреть файл

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

Просмотреть файл

@ -51,7 +51,8 @@ unsafe fn get_class_or_part_from_attr(attr: &structs::nsAttrValue) -> Class {
.__bindgen_anon_1
.mAtomArray
.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);
}
debug_assert_eq!(base_type, structs::nsAttrValue_ValueBaseType_eStringBase);

Просмотреть файл

@ -19,7 +19,6 @@ use crate::author_styles::AuthorStyles;
use crate::context::{PostAnimationTasks, QuirksMode, SharedStyleContext, UpdateAnimationsTasks};
use crate::data::ElementData;
use crate::dom::{LayoutIterator, NodeInfo, OpaqueNode, TDocument, TElement, TNode, TShadowRoot};
use dom::{DocumentState, ElementState};
use crate::gecko::data::GeckoStyleSheet;
use crate::gecko::selector_parser::{NonTSPseudoClass, PseudoElement, SelectorImpl};
use crate::gecko::snapshot_helpers;
@ -67,8 +66,9 @@ use crate::values::{AtomIdent, AtomString};
use crate::CaseSensitivityExt;
use crate::LocalName;
use app_units::Au;
use euclid::default::Size2D;
use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut};
use dom::{DocumentState, ElementState};
use euclid::default::Size2D;
use fxhash::FxHashMap;
use selectors::attr::{AttrSelectorOperation, AttrSelectorOperator};
use selectors::attr::{CaseSensitivity, NamespaceConstraint};
@ -77,11 +77,11 @@ use selectors::matching::{ElementSelectorFlags, MatchingContext};
use selectors::sink::Push;
use selectors::{Element, OpaqueElement};
use servo_arc::{Arc, ArcBorrow, RawOffsetArc};
use std::sync::atomic::{AtomicU32, Ordering};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::mem;
use std::ptr;
use std::sync::atomic::{AtomicU32, Ordering};
#[inline]
fn elements_with_id<'a, 'le>(
@ -275,16 +275,15 @@ impl<'ln> GeckoNode<'ln> {
#[allow(dead_code)]
fn static_assert() {
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
// (via the atomic intrinsics) or via std::atomic_ref, but it guarantees
// that the memory representation of u32 and AtomicU32 matches:
// https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU32.html
unsafe {
std::mem::transmute::<&Cell<u32>, &AtomicU32>(flags)
}
unsafe { std::mem::transmute::<&Cell<u32>, &AtomicU32>(flags) }
}
#[inline]
@ -677,12 +676,16 @@ impl<'le> GeckoElement<'le> {
#[inline]
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]
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.
@ -1044,7 +1047,14 @@ impl<'le> TElement for GeckoElement<'le> {
}
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() {
return Size2D::zero();
}

Просмотреть файл

@ -11,7 +11,9 @@ use crate::invalidation::element::invalidator::{Invalidation, InvalidationProces
use crate::invalidation::element::state_and_attributes;
use crate::stylist::CascadeData;
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
/// selectors.

Просмотреть файл

@ -19,7 +19,9 @@ use crate::stylesheets::origin::OriginSet;
use crate::{Atom, WeakAtom};
use dom::ElementState;
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 smallvec::SmallVec;
@ -410,10 +412,7 @@ where
self.collect_state_dependencies(&map.state_affecting_selectors)
}
fn collect_state_dependencies(
&mut self,
map: &'selectors SelectorMap<StateDependency>,
) {
fn collect_state_dependencies(&mut self, map: &'selectors SelectorMap<StateDependency>) {
if self.state_changes.is_empty() {
return;
}

Просмотреть файл

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

Просмотреть файл

@ -162,7 +162,7 @@ pub use style_traits::arc_slice::ArcSlice;
pub use style_traits::owned_slice::OwnedSlice;
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.
/// 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.
pub (crate) trait ShrinkIfNeeded {
pub(crate) trait ShrinkIfNeeded {
fn shrink_if_needed(&mut self);
}

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

@ -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
/// in the caller.
#[inline(never)]
fn create_thread_local_context<'scope, E>(
slot: &mut Option<ThreadLocalStyleContext<E>>,
) where
fn create_thread_local_context<'scope, E>(slot: &mut Option<ThreadLocalStyleContext<E>>)
where
E: TElement + 'scope,
{
*slot = Some(ThreadLocalStyleContext::new());

Просмотреть файл

@ -230,7 +230,10 @@ impl PiecewiseLinearFunctionBuilder {
}
// Guaranteed at least two elements.
// 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.
self.entries
.last_mut()

Просмотреть файл

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

Просмотреть файл

@ -7,7 +7,7 @@
//! https://drafts.csswg.org/mediaqueries-4/#typedef-media-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::values::computed;
use cssparser::{Parser, Token};
@ -197,7 +197,8 @@ impl QueryCondition {
if let Ok(inner) = input.try_parse(|i| Self::parse(context, i, feature_type)) {
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))
})
}

Просмотреть файл

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

Просмотреть файл

@ -6,7 +6,7 @@
//! `(width >= 400px)`.
use super::feature::{Evaluator, QueryFeatureDescription};
use super::feature::{KeywordDiscriminant, FeatureFlags};
use super::feature::{FeatureFlags, KeywordDiscriminant};
use crate::parser::{Parse, ParserContext};
use crate::str::{starts_with_ignore_ascii_case, string_as_ascii_lowercase};
use crate::values::computed::{self, Ratio, ToComputedValue};
@ -43,7 +43,10 @@ impl FeatureType {
}
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.
match self {
Self::Equal => false,
Self::GreaterThan | Self::GreaterThanEqual => matches!(right_op, Self::GreaterThan | Self::GreaterThanEqual),
Self::LessThan | Self::LessThanEqual => matches!(right_op, Self::LessThan | Self::LessThanEqual),
Self::GreaterThan | Self::GreaterThanEqual => {
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 {
Some(op) => {
if !left_op.is_compatible_with(op) {
return Err(
input.new_custom_error(StyleParseErrorKind::UnspecifiedError)
);
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
Some((op, QueryExpressionValue::parse(feature, context, input)?))
},
@ -583,9 +588,8 @@ impl QueryFeatureExpression {
match self.feature().evaluator {
Evaluator::Length(eval) => {
let v = eval(context);
self.kind.evaluate(v, |v| {
expect!(Length, v).to_computed_value(context)
})
self.kind
.evaluate(v, |v| expect!(Length, v).to_computed_value(context))
},
Evaluator::Integer(eval) => {
let v = eval(context);
@ -594,14 +598,15 @@ impl QueryFeatureExpression {
Evaluator::Float(eval) => {
let v = eval(context);
self.kind.evaluate(v, |v| *expect!(Float, v))
}
},
Evaluator::NumberRatio(eval) => {
let ratio = eval(context);
// A ratio of 0/0 behaves as the ratio 1/0, so we need to call used_value()
// to convert it if necessary.
// FIXME: we may need to update here once
// 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) => {
let v = eval(context).dppx();
@ -610,11 +615,17 @@ impl QueryFeatureExpression {
})
},
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::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);
computed.map_or(boolean, |v| v == boolean)
},

Просмотреть файл

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

Просмотреть файл

@ -42,12 +42,12 @@ impl Default for PrecomputedHasher {
/// these pseudo-class states.
const RARE_PSEUDO_CLASS_STATES: ElementState = ElementState::from_bits_truncate(
ElementState::FULLSCREEN.bits() |
ElementState::VISITED_OR_UNVISITED.bits() |
ElementState::URLTARGET.bits() |
ElementState::INERT.bits() |
ElementState::FOCUS.bits() |
ElementState::FOCUSRING.bits() |
ElementState::TOPMOST_MODAL.bits()
ElementState::VISITED_OR_UNVISITED.bits() |
ElementState::URLTARGET.bits() |
ElementState::INERT.bits() |
ElementState::FOCUS.bits() |
ElementState::FOCUSRING.bits() |
ElementState::TOPMOST_MODAL.bits(),
);
/// 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(
element,
&self.rare_pseudo_classes,
@ -349,13 +352,16 @@ impl SelectorMap<Rule> {
}
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;
}
}
matching_rules
.push(rule.to_applicable_declaration_block(cascade_level, cascade_data));
matching_rules.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.
#[derive(Clone, Debug, MallocSizeOf)]
pub struct MaybeCaseInsensitiveHashMap<K: PrecomputedHash + Hash + Eq, V>(
PrecomputedHashMap<K, V>,
);
pub struct MaybeCaseInsensitiveHashMap<K: PrecomputedHash + Hash + Eq, V>(PrecomputedHashMap<K, V>);
impl<V> Default for MaybeCaseInsensitiveHashMap<Atom, V> {
#[inline]

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

@ -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::{self, ComputedValues, StyleBuilder};
/// A struct that implements all the adjustment methods.
///
/// 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
fn adjust_for_webkit_line_clamp(&mut self) {
use crate::properties::longhands::_moz_box_orient::computed_value::T as BoxOrient;
use crate::values::specified::box_::{DisplayOutside, DisplayInside};
let box_style= self.style.get_box();
use crate::values::specified::box_::{DisplayInside, DisplayOutside};
let box_style = self.style.get_box();
if box_style.clone__webkit_line_clamp().is_none() {
return;
}
@ -176,7 +175,9 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
debug_assert_eq!(disp.outside(), DisplayOutside::Inline);
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:
@ -277,7 +278,8 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
.add_flags(ComputedValueFlags::IS_ROOT_ELEMENT_STYLE);
}
if self.style
if self
.style
.get_box()
.clone_contain()
.contains(SpecifiedValue::STYLE)

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

@ -25,7 +25,11 @@ pub struct NamespaceRule {
impl ToCssWithGuard for NamespaceRule {
// 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);
dest.write_str("@namespace ")?;
if let Some(ref prefix) = self.prefix {

Просмотреть файл

@ -12,12 +12,12 @@ use crate::shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked};
use crate::shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use crate::str::CssStringWriter;
use crate::values::{AtomIdent, CustomIdent};
use style_traits::{CssWriter, ParseError, ToCss};
use cssparser::{Parser, SourceLocation};
#[cfg(feature = "gecko")]
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps, MallocUnconditionalShallowSizeOf};
use servo_arc::Arc;
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, ToCss};
/// Type of a single [`@page`][page selector]
///
@ -32,7 +32,7 @@ impl PageSelector {
/// This does not currently take pseudo selectors into account.
#[inline]
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,
input: &mut Parser<'i, 't>,
) -> 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")]
pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
// 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)
}
}

Просмотреть файл

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

Просмотреть файл

@ -4,6 +4,7 @@
//! [@supports rules](https://drafts.csswg.org/css-conditional-3/#at-supports)
use crate::font_face::{FontFaceSourceFormatKeyword, FontFaceSourceTechFlags};
use crate::parser::ParserContext;
use crate::properties::{PropertyDeclaration, PropertyId, SourcePropertyDeclaration};
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::str::CssStringWriter;
use crate::stylesheets::{CssRuleType, CssRules, Namespaces};
use crate::font_face::{FontFaceSourceFormatKeyword, FontFaceSourceTechFlags};
use cssparser::parse_important;
use cssparser::{Delimiter, Parser, SourceLocation, Token};
use cssparser::{ParseError as CssParseError, ParserInput};

Просмотреть файл

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

Просмотреть файл

@ -19,10 +19,8 @@ use smallvec::SmallVec;
use std::collections::HashMap;
/// A cache from element reference to known-valid computed style.
pub type UndisplayedStyleCache = HashMap<
selectors::OpaqueElement,
servo_arc::Arc<crate::properties::ComputedValues>,
>;
pub type UndisplayedStyleCache =
HashMap<selectors::OpaqueElement, servo_arc::Arc<crate::properties::ComputedValues>>;
/// 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.
@ -336,9 +334,8 @@ where
}
ancestor = ancestor.unwrap().traversal_parent();
layout_parent_style = ancestor.and_then(|a| {
a.borrow_data().map(|data| data.styles.primary().clone())
});
layout_parent_style =
ancestor.and_then(|a| a.borrow_data().map(|data| data.styles.primary().clone()));
}
for ancestor in ancestors_requiring_style_resolution.iter().rev() {
@ -792,7 +789,7 @@ fn note_children<E, D, F>(
},
ChildRestyleRequirement::MustMatchDescendants => {
child_hint |= RestyleHint::restyle_subtree();
}
},
}
child_data.hint.insert(child_hint);

Просмотреть файл

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

Просмотреть файл

@ -892,7 +892,11 @@ impl Animate for ComputedTransform {
// If there is a remainder from *both* lists we must have had mismatched functions.
// => Add the remainders to a suitable ___Matrix function.
(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
// completely match the type of the corresponding functions in the longer list.
@ -1121,7 +1125,10 @@ impl ComputedTransformOperation {
) -> Result<Self, ()> {
let (left, _left_3d) = Transform::components_to_transform_3d_matrix(left, 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(
@ -1137,22 +1144,18 @@ impl ComputedTransformOperation {
Ok(match procedure {
Procedure::Add => {
debug_assert!(false, "Addition should've been handled earlier");
return Err(())
return Err(());
},
Procedure::Interpolate { progress } => Self::InterpolateMatrix {
from_list,
to_list,
progress: Percentage(progress as f32),
},
Procedure::Accumulate { count } => Self::AccumulateMatrix {
from_list,
to_list,
count: cmp::min(count, i32::max_value() as u64) as i32,
},
Procedure::Interpolate { progress } => {
Self::InterpolateMatrix {
from_list,
to_list,
progress: Percentage(progress as f32),
}
}
Procedure::Accumulate { count } => {
Self::AccumulateMatrix {
from_list,
to_list,
count: cmp::min(count, i32::max_value() as u64) as i32,
}
}
})
}
}

Просмотреть файл

@ -8,7 +8,9 @@ use crate::values::animated::{Animate, Procedure};
use crate::values::computed::length::{LengthPercentage, NonNegativeLength};
use crate::values::computed::{Context, Integer, Number, ToComputedValue};
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;
pub use crate::values::specified::box_::{
@ -39,7 +41,7 @@ impl Animate for LineClamp {
return Err(());
}
if self.is_none() {
return Ok(Self::none())
return Ok(Self::none());
}
Ok(Self(self.0.animate(&other.0, procedure)?.max(1)))
}

Просмотреть файл

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

Просмотреть файл

@ -7,8 +7,8 @@
use crate::parser::{Parse, ParserContext};
use crate::values::animated::ToAnimatedValue;
use crate::values::computed::{
Angle, Context, Integer, Length, NonNegativeLength, NonNegativeNumber,
Number, Percentage, ToComputedValue
Angle, Context, Integer, Length, NonNegativeLength, NonNegativeNumber, Number, Percentage,
ToComputedValue,
};
use crate::values::generics::font::{FeatureTagValue, FontSettings, VariationValue};
use crate::values::generics::{font as generics, NonNegative};
@ -48,7 +48,15 @@ pub use crate::values::specified::Integer as SpecifiedInteger;
/// cbindgen:derive-gte
#[repr(C)]
#[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> {
value: T,
@ -95,7 +103,15 @@ pub type FontWeightFixedPoint = FixedPoint<u16, FONT_WEIGHT_FRACTION_BITS>;
/// cbindgen:derive-gt
/// cbindgen:derive-gte
#[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))]
#[repr(C)]
@ -125,13 +141,19 @@ impl ToCss for FontWeight {
impl FontWeight {
/// 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.
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.
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.
pub fn normal() -> Self {
@ -150,7 +172,9 @@ impl FontWeight {
/// Construct a valid weight from a float value.
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.
@ -175,7 +199,7 @@ impl FontWeight {
pub fn lighter(self) -> Self {
let value = self.value();
if value < 550. {
return Self::from_float(value.min(100.))
return Self::from_float(value.min(100.));
}
if value < 750. {
return Self::NORMAL;
@ -860,23 +884,37 @@ pub type FontStyleFixedPoint = FixedPoint<i16, FONT_STYLE_FRACTION_BITS>;
/// cbindgen:derive-gt
/// cbindgen:derive-gte
#[derive(
Clone, ComputeSquaredDistance, Copy, Debug, Hash, MallocSizeOf, PartialEq, PartialOrd, ToResolvedValue,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
Hash,
MallocSizeOf,
PartialEq,
PartialOrd,
ToResolvedValue,
)]
#[repr(C)]
pub struct FontStyle(FontStyleFixedPoint);
impl FontStyle {
/// 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.
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`.
/// See also https://github.com/w3c/csswg-drafts/issues/2295
pub const DEFAULT_OBLIQUE_DEGREES: i16 = 14;
/// 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.
#[inline]
@ -889,7 +927,7 @@ impl FontStyle {
Self(FixedPoint::from_float(
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,
{
if *self == Self::NORMAL {
return dest.write_str("normal")
return dest.write_str("normal");
}
if *self == Self::ITALIC {
return dest.write_str("italic")
return dest.write_str("italic");
}
if *self == Self::OBLIQUE {
return dest.write_str("oblique");
@ -928,10 +966,10 @@ impl ToAnimatedValue for FontStyle {
#[inline]
fn to_animated_value(self) -> Self::AnimatedValue {
if self == Self::NORMAL {
return generics::FontStyle::Normal
return generics::FontStyle::Normal;
}
if self == Self::ITALIC {
return generics::FontStyle::Italic
return generics::FontStyle::Italic;
}
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.
///
/// 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.
pub type FontStretchFixedPoint = FixedPoint<u16, FONT_STRETCH_FRACTION_BITS>;
/// A value for the font-stretch property per:
///
/// 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);
/// 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.
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.
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.
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.
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.
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.
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.
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.
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%
pub fn hundred() -> Self {

Просмотреть файл

@ -42,7 +42,11 @@ impl ToComputedValue for specified::NoCalcLength {
impl specified::NoCalcLength {
/// 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 {
specified::NoCalcLength::Absolute(length) => length.to_computed_value(context),
specified::NoCalcLength::FontRelative(length) => {

Просмотреть файл

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

Просмотреть файл

@ -16,13 +16,13 @@ use super::specified;
use super::{CSSFloat, CSSInteger};
use crate::computed_value_flags::ComputedValueFlags;
use crate::context::QuirksMode;
use crate::stylesheets::container_rule::ContainerInfo;
use crate::font_metrics::{FontMetrics, FontMetricsOrientation};
use crate::media_queries::Device;
#[cfg(feature = "gecko")]
use crate::properties;
use crate::properties::{ComputedValues, LonghandId, StyleBuilder};
use crate::rule_cache::RuleCacheConditions;
use crate::stylesheets::container_rule::ContainerInfo;
use crate::values::specified::length::FontBaseSize;
use crate::{ArcSlice, Atom, One};
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::{BorderImageRepeat, BorderImageSideWidth};
pub use self::border::{BorderImageSlice, BorderImageWidth};
pub use self::box_::{AnimationIterationCount, AnimationName, AnimationTimeline, Contain, ContainerName, ContainerType};
pub use self::box_::{Appearance, BreakBetween, BreakWithin, Clear, ContentVisibility, ContainIntrinsicSize, Float};
pub use self::box_::{
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_::{OverflowClipBox, OverscrollBehavior, Perspective, Resize, ScrollbarGutter};
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::motion::{OffsetPath, OffsetRotate};
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::position::AspectRatio;
pub use self::position::{
@ -97,7 +102,7 @@ pub use self::transform::{Rotate, Scale, Transform, TransformOperation};
pub use self::transform::{TransformOrigin, TransformStyle, Translate};
#[cfg(feature = "gecko")]
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::ViewportVariant;
pub use super::specified::{BorderStyle, TextDecorationLine};
@ -285,7 +290,7 @@ impl<'a> Context<'a> {
font,
size,
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> {
/// Construct an iterator from a slice of specified values and a context
pub fn new(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self {
ComputedVecIter {
cx,
values,
}
ComputedVecIter { cx, values }
}
}

Просмотреть файл

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

Просмотреть файл

@ -4,12 +4,12 @@
//! 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 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
/// the current foreground color (currentcolor keyword).
@ -27,7 +27,20 @@ pub enum GenericColor<RGBA, Percentage> {
/// A color space as defined in [1].
///
/// [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)]
pub enum ColorSpace {
/// The sRGB color space.
@ -63,7 +76,20 @@ impl ColorSpace {
/// A hue-interpolation-method as defined in [1].
///
/// [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)]
pub enum HueInterpolationMethod {
/// 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
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, ToShmem, ToAnimatedValue, ToComputedValue, ToResolvedValue)]
#[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
PartialEq,
ToShmem,
ToAnimatedValue,
ToComputedValue,
ToResolvedValue,
)]
#[repr(C)]
pub struct ColorInterpolationMethod {
/// 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
// algorithm is selected by the host syntax, the default is shorter.
let hue = if space.is_polar() {
input.try_parse(|input| -> Result<_, ParseError<'i>> {
let hue = HueInterpolationMethod::parse(input)?;
input.expect_ident_matching("hue")?;
Ok(hue)
}).unwrap_or(HueInterpolationMethod::Shorter)
input
.try_parse(|input| -> Result<_, ParseError<'i>> {
let hue = HueInterpolationMethod::parse(input)?;
input.expect_ident_matching("hue")?;
Ok(hue)
})
.unwrap_or(HueInterpolationMethod::Shorter)
} else {
HueInterpolationMethod::Shorter
};
@ -141,7 +180,16 @@ impl ToCss for ColorInterpolationMethod {
/// percentages.
///
/// 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)]
#[repr(C)]
pub struct GenericColorMix<Color, Percentage> {
@ -160,7 +208,11 @@ impl<Color: ToCss, Percentage: ToCss + ToPercentage> ToCss for ColorMix<Color, P
where
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() {
return false;
}

Просмотреть файл

@ -404,7 +404,10 @@ impl ToAbsoluteLength for ComputedLength {
impl ToAbsoluteLength for ComputedLengthPercentage {
#[inline]
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.
#[cfg_attr(rustfmt, rustfmt_skip)]
pub fn components_to_transform_3d_matrix(
ops: &[T],
reference_box: Option<&Rect<ComputedLength>>
reference_box: Option<&Rect<ComputedLength>>,
) -> Result<(Transform3D<CSSFloat>, bool), ()> {
let cast_3d_transform = |m: Transform3D<f64>| -> Transform3D<CSSFloat> {
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(
cast(m.m11), cast(m.m12), cast(m.m13), cast(m.m14),
cast(m.m21), cast(m.m22), cast(m.m23), cast(m.m24),

Просмотреть файл

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

Просмотреть файл

@ -8,10 +8,14 @@ use crate::custom_properties::Name as CustomPropertyName;
use crate::parser::{Parse, ParserContext};
use crate::properties::{LonghandId, PropertyDeclarationId};
use crate::properties::{PropertyId, ShorthandId};
use crate::values::generics::box_::{GenericAnimationIterationCount, GenericPerspective, GenericLineClamp};
use crate::values::generics::box_::{GenericContainIntrinsicSize, GenericVerticalAlign, VerticalAlignKeyword};
use crate::values::generics::box_::{
GenericAnimationIterationCount, GenericLineClamp, GenericPerspective,
};
use crate::values::generics::box_::{
GenericContainIntrinsicSize, GenericVerticalAlign, VerticalAlignKeyword,
};
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::Atom;
use cssparser::Parser;
@ -885,7 +889,10 @@ impl Parse for AnimationTimeline {
}
// 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| {
Ok(Self::Scroll(
i.try_parse(ScrollAxis::parse).unwrap_or(ScrollAxis::Block),
@ -1450,9 +1457,7 @@ impl Parse for ContainIntrinsicSize {
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> 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));
}
@ -1472,9 +1477,10 @@ impl Parse for LineClamp {
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> 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")?;
Ok(Self::none())
@ -1531,7 +1537,17 @@ bitflags! {
/// https://drafts.csswg.org/css-contain-3/#container-name
#[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>);
impl ContainerName {
@ -1547,17 +1563,29 @@ impl 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 location = input.current_source_location();
let first = input.expect_ident()?;
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"];
idents.push(CustomIdent::from_ident(location, first, DISALLOWED_CONTAINER_NAMES)?);
const DISALLOWED_CONTAINER_NAMES: &'static [&'static str] =
&["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()) {
idents.push(CustomIdent::from_ident(location, &ident, DISALLOWED_CONTAINER_NAMES)?);
idents.push(CustomIdent::from_ident(
location,
&ident,
DISALLOWED_CONTAINER_NAMES,
)?);
}
Ok(ContainerName(idents.into()))
}
@ -2180,7 +2208,10 @@ pub enum Overflow {
// This can be derived once we remove or keep `-moz-hidden-unscrollable`
// indefinitely.
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,
"visible" => Self::Visible,
"hidden" => Self::Hidden,

Просмотреть файл

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

Просмотреть файл

@ -7,7 +7,9 @@
use super::AllowQuirks;
use crate::parser::{Parse, ParserContext};
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::Percentage;
use crate::values::CustomIdent;
@ -618,7 +620,9 @@ impl Color {
let mut written = space_padding;
let mut buf = itoa::Buffer::new();
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();
if let Some(unit) = unit {
written += (&mut serialization[written..])

Просмотреть файл

@ -110,10 +110,12 @@ impl TimingFunction {
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let steps = Integer::parse_positive(context, input)?;
let position = input.try_parse(|i| {
i.expect_comma()?;
StepPosition::parse(context, i)
}).unwrap_or(StepPosition::End);
let position = input
.try_parse(|i| {
i.expect_comma()?;
StepPosition::parse(context, i)
})
.unwrap_or(StepPosition::End);
// jump-none accepts a positive integer greater than 1.
// 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_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() {
debug_assert!(input_start.is_some(), "Input end valid but not input start?");
result.push(LinearStop { output, input: input_end.into() });
debug_assert!(
input_start.is_some(),
"Input end valid but not input start?"
);
result.push(LinearStop {
output,
input: input_end.into(),
});
}
Ok(())

Просмотреть файл

@ -8,8 +8,8 @@ use crate::context::QuirksMode;
use crate::parser::{Parse, ParserContext};
use crate::values::computed::font::{FamilyName, FontFamilyList, SingleFontFamily};
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::{font as computed, Length, NonNegativeLength};
use crate::values::computed::{CSSPixelLength, Context, ToComputedValue};
use crate::values::generics::font::VariationValue;
use crate::values::generics::font::{
@ -187,9 +187,7 @@ impl AbsoluteFontWeight {
/// Returns the computed value for this absolute font weight.
pub fn compute(&self) -> computed::FontWeight {
match *self {
AbsoluteFontWeight::Weight(weight) => {
computed::FontWeight::from_float(weight.get())
},
AbsoluteFontWeight::Weight(weight) => computed::FontWeight::from_float(weight.get()),
AbsoluteFontWeight::Normal => computed::FontWeight::NORMAL,
AbsoluteFontWeight::Bold => computed::FontWeight::BOLD,
}
@ -438,7 +436,7 @@ impl ToComputedValue for FontStretch {
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
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 {
let gecko_font = cx.style().get_font().gecko();
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 {
Atom::with(gecko_font.mLanguage.mRawPtr, |language| {
cx.device().base_size_for_generic(language, generic)

Просмотреть файл

@ -304,12 +304,16 @@ impl CrossFade {
}
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
// implementation handle out-of-bounds percentages but whether or not
// this behavior follows the specification is still being discussed.
// 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()
.map(|p| p.clamp_to_hundred())
}

Просмотреть файл

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

Просмотреть файл

@ -38,7 +38,9 @@ pub use self::border::{BorderImageRepeat, BorderImageSideWidth};
pub use self::border::{BorderRadius, BorderSideWidth, BorderSpacing, BorderStyle};
pub use self::box_::{AnimationIterationCount, AnimationName, AnimationTimeline, Contain, Display};
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_::{ScrollAxis, ScrollSnapAlign, ScrollSnapAxis, ScrollSnapStop};
pub use self::box_::{ScrollSnapStrictness, ScrollSnapType, ScrollTimelineName};
@ -70,7 +72,7 @@ pub use self::list::ListStyleType;
pub use self::list::Quotes;
pub use self::motion::{OffsetPath, OffsetRotate};
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::position::AspectRatio;
pub use self::position::{
@ -97,7 +99,7 @@ pub use self::transform::{Rotate, Scale, Transform};
pub use self::transform::{TransformOrigin, TransformStyle, Translate};
#[cfg(feature = "gecko")]
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;
#[cfg(feature = "gecko")]

Просмотреть файл

@ -186,7 +186,9 @@ impl SpecifiedValueInfo for Percentage {}
/// Turns the percentage into a plain float.
pub trait ToPercentage {
/// 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.
fn to_percentage(&self) -> CSSFloat;
}

Просмотреть файл

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

Просмотреть файл

@ -4,9 +4,9 @@
use crate::to_css::{CssBitflagAttrs, CssVariantAttrs};
use derive_common::cg;
use proc_macro2::{TokenStream, Span};
use proc_macro2::{Span, TokenStream};
use quote::TokenStreamExt;
use syn::{self, Ident, DeriveInput, Path};
use syn::{self, DeriveInput, Ident, Path};
use synstructure::{Structure, VariantInfo};
#[derive(Default, FromVariant)]
@ -109,9 +109,12 @@ fn parse_non_keyword_variant(
if let Some(ref bitflags) = variant_attrs.bitflags {
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?");
return parse_bitflags(bitflags)
return parse_bitflags(bitflags);
}
let field_attrs = cg::parse_field_attrs::<ParseFieldAttrs>(binding_ast);

Просмотреть файл

@ -96,7 +96,10 @@ pub fn derive(mut input: syn::DeriveInput) -> TokenStream {
}
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?");
return derive_bitflags(&input, bitflags);
}

Просмотреть файл

@ -28,7 +28,7 @@ use style::data::{self, ElementStyles};
use style::dom::{ShowSubtreeData, TDocument, TElement, TNode};
use style::driver;
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::restyle_damage::GeckoRestyleDamage;
use style::gecko::selector_parser::{NonTSPseudoClass, PseudoElement};
@ -130,14 +130,16 @@ use style::traversal::resolve_style;
use style::traversal::DomTraversal;
use style::traversal_flags::{self, TraversalFlags};
use style::use_counters::UseCounters;
use style::values::animated::{Animate, Procedure, ToAnimatedZero};
use style::values::animated::color::AnimatedRGBA;
use style::values::generics::color::ColorInterpolationMethod;
use style::values::generics::easing::BeforeFlag;
use style::values::computed::font::{FontFamily, FontFamilyList, GenericFontFamily, FontWeight, FontStyle, FontStretch};
use style::values::animated::{Animate, Procedure, ToAnimatedZero};
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::distance::ComputeSquaredDistance;
use style::values::generics::color::ColorInterpolationMethod;
use style::values::generics::easing::BeforeFlag;
use style::values::specified::gecko::IntersectionObserverRootMargin;
use style::values::specified::source_size_list::SourceSizeList;
use style::values::{specified, AtomIdent, CustomIdent, KeyframesName};
@ -2453,7 +2455,9 @@ pub extern "C" fn Servo_StyleRule_SelectorMatchesElement(
pseudo_type: PseudoStyleType,
relevant_link_visited: 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| {
let index = index as usize;
if index >= rule.selectors.0.len() {
@ -2834,10 +2838,7 @@ pub extern "C" fn Servo_PageRule_SetStyle(
}
#[no_mangle]
pub extern "C" fn Servo_PageRule_GetSelectorText(
rule: &RawServoPageRule,
result: &mut nsACString,
) {
pub extern "C" fn Servo_PageRule_GetSelectorText(rule: &RawServoPageRule, result: &mut nsACString) {
read_locked_arc(rule, |rule: &PageRule| {
rule.selectors.to_css(&mut CssWriter::new(result)).unwrap();
})
@ -2849,7 +2850,6 @@ pub extern "C" fn Servo_PageRule_SetSelectorText(
rule: &RawServoPageRule,
text: &nsACString,
) -> bool {
let value_str = unsafe { text.as_str_unchecked() };
write_locked_arc(rule, |rule: &mut PageRule| {
@ -2886,7 +2886,6 @@ pub extern "C" fn Servo_PageRule_SetSelectorText(
})
}
#[no_mangle]
pub extern "C" fn Servo_SupportsRule_GetConditionText(
rule: &RawServoSupportsRule,
@ -2913,7 +2912,9 @@ pub extern "C" fn Servo_ContainerRule_GetContainerQuery(
result: &mut nsACString,
) {
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,
) -> *const RawGeckoElement {
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| {
acc + match *src {
Source::Url(ref url) =>
Source::Url(ref url) => {
(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,
}
});
@ -3243,13 +3247,15 @@ pub unsafe extern "C" fn Servo_FontFaceRule_GetSources(
set_next(FontFaceSourceListComponent::Url(&url.url));
if let Some(hint) = &url.format_hint {
match hint {
FontFaceSourceFormat::Keyword(kw) =>
set_next(FontFaceSourceListComponent::FormatHintKeyword(*kw)),
FontFaceSourceFormat::String(s) =>
FontFaceSourceFormat::Keyword(kw) => {
set_next(FontFaceSourceListComponent::FormatHintKeyword(*kw))
},
FontFaceSourceFormat::String(s) => {
set_next(FontFaceSourceListComponent::FormatHintString {
length: s.len(),
utf8_bytes: s.as_ptr(),
}),
})
},
}
}
if !url.tech_flags.is_empty() {
@ -4074,12 +4080,8 @@ fn get_pseudo_style(
}
Some(style.unwrap_or_else(|| {
StyleBuilder::for_inheritance(
stylist.device(),
Some(styles.primary()),
Some(pseudo),
)
.build()
StyleBuilder::for_inheritance(stylist.device(), Some(styles.primary()), Some(pseudo))
.build()
}))
}
@ -4357,7 +4359,10 @@ pub unsafe extern "C" fn Servo_ParseProperty(
}
#[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;
let context = ParserContext::new(
@ -4767,8 +4772,7 @@ pub unsafe extern "C" fn Servo_DeclarationBlock_SetPropertyToAnimationValue(
) -> bool {
let animation_value = AnimationValue::as_arc(&animation_value);
let non_custom_property_id = animation_value.id().into();
let mut source_declarations =
SourcePropertyDeclaration::with_one(animation_value.uncompute());
let mut source_declarations = SourcePropertyDeclaration::with_one(animation_value.uncompute());
set_property_to_declarations(
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::font::FontStyle;
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
@ -6995,8 +6999,8 @@ pub unsafe extern "C" fn Servo_ParseFontShorthandForMatching(
size: Option<&mut f32>,
) -> bool {
use style::properties::shorthands::font;
use style::values::specified::font as specified;
use style::values::generics::font::FontStyle as GenericFontStyle;
use style::values::specified::font as specified;
let string = value.as_str_unchecked();
let mut input = ParserInput::new(&string);
@ -7064,12 +7068,20 @@ pub unsafe extern "C" fn Servo_ParseFontShorthandForMatching(
specified::FontSize::Keyword(info) => {
// TODO: Maybe get a meaningful quirks / base size from the caller?
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
specified::FontSize::Smaller | specified::FontSize::Larger | specified::FontSize::System(_) => {
specified::FontSize::Smaller |
specified::FontSize::Larger |
specified::FontSize::System(_) => {
return false;
}
},
};
}
@ -7327,7 +7339,10 @@ pub extern "C" fn Servo_FontStretch_ToCss(s: &FontStretch, result: &mut nsACStri
}
#[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() {
Some(kw) => kw,
None => return false,
@ -7488,7 +7503,7 @@ pub extern "C" fn Servo_InterpolateColor(
pub extern "C" fn Servo_EasingFunctionAt(
easing_function: &ComputedTimingFunction,
progress: f64,
before_flag: BeforeFlag
before_flag: BeforeFlag,
) -> f64 {
easing_function.calculate_output(progress, before_flag, 1e-7)
}

Просмотреть файл

@ -56,15 +56,9 @@ fn implied_input_spacing() {
.push(0.0, None)
.push(1.0, None)
.build();
assert!(implied_spacing
.at(0.)
.approx_eq(&explicit_spacing.at(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)));
assert!(implied_spacing.at(0.).approx_eq(&explicit_spacing.at(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]
@ -136,9 +130,7 @@ fn out_of_bounds_flat() {
.push(1.0, Some(1.0))
.push(1.0, Some(1.0))
.build();
assert!(oob_flat
.at(0.0)
.approx_eq(&oob_flat.at(-0.25)));
assert!(oob_flat.at(0.0).approx_eq(&oob_flat.at(-0.25)));
assert!(oob_flat.at(1.0).approx_eq(&oob_flat.at(1.25)));
}