Bug 1909165 - Make more stylo code Gecko-specific at compile-time r=emilio

Guard some Gecko-specific code in stylo at compile-time. The goal is to
reduce these as much as possible as Servo gains new features, but some
of these guards prevent compilation failure when trying to use
Gecko-only data structures.

Differential Revision: https://phabricator.services.mozilla.com/D217563
This commit is contained in:
Martin Robinson 2024-08-01 15:30:47 +00:00
Родитель 499a5548e9
Коммит 8644105a4e
34 изменённых файлов: 251 добавлений и 62 удалений

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

@ -79,6 +79,7 @@ fn get_safearea_inset_right(device: &Device, url_data: &UrlExtraData) -> Variabl
VariableValue::pixels(device.safe_area_insets().right, url_data) VariableValue::pixels(device.safe_area_insets().right, url_data)
} }
#[cfg(feature = "gecko")]
fn get_content_preferred_color_scheme(device: &Device, url_data: &UrlExtraData) -> VariableValue { fn get_content_preferred_color_scheme(device: &Device, url_data: &UrlExtraData) -> VariableValue {
use crate::gecko::media_features::PrefersColorScheme; use crate::gecko::media_features::PrefersColorScheme;
let prefers_color_scheme = unsafe { let prefers_color_scheme = unsafe {
@ -96,6 +97,12 @@ fn get_content_preferred_color_scheme(device: &Device, url_data: &UrlExtraData)
) )
} }
#[cfg(feature = "servo")]
fn get_content_preferred_color_scheme(_device: &Device, url_data: &UrlExtraData) -> VariableValue {
// TODO: Add an implementation for Servo.
VariableValue::ident("light", url_data)
}
fn get_scrollbar_inline_size(device: &Device, url_data: &UrlExtraData) -> VariableValue { fn get_scrollbar_inline_size(device: &Device, url_data: &UrlExtraData) -> VariableValue {
VariableValue::pixels(device.scrollbar_inline_size().px(), url_data) VariableValue::pixels(device.scrollbar_inline_size().px(), url_data)
} }
@ -107,6 +114,7 @@ static ENVIRONMENT_VARIABLES: [EnvironmentVariable; 4] = [
make_variable!(atom!("safe-area-inset-right"), get_safearea_inset_right), make_variable!(atom!("safe-area-inset-right"), get_safearea_inset_right),
]; ];
#[cfg(feature = "gecko")]
macro_rules! lnf_int { macro_rules! lnf_int {
($id:ident) => { ($id:ident) => {
unsafe { unsafe {
@ -117,6 +125,14 @@ macro_rules! lnf_int {
}; };
} }
#[cfg(feature = "servo")]
macro_rules! lnf_int {
($id:ident) => {
// TODO: Add an implementation for Servo.
0
};
}
macro_rules! lnf_int_variable { macro_rules! lnf_int_variable {
($atom:expr, $id:ident, $ctor:ident) => {{ ($atom:expr, $id:ident, $ctor:ident) => {{
fn __eval(_: &Device, url_data: &UrlExtraData) -> VariableValue { fn __eval(_: &Device, url_data: &UrlExtraData) -> VariableValue {

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

@ -6,6 +6,7 @@
use crate::data::ElementData; use crate::data::ElementData;
use crate::dom::{TElement, TNode}; use crate::dom::{TElement, TNode};
#[cfg(feature = "gecko")]
use crate::gecko_bindings::structs::ServoElementSnapshotTable; use crate::gecko_bindings::structs::ServoElementSnapshotTable;
use crate::invalidation::element::element_wrapper::ElementWrapper; use crate::invalidation::element::element_wrapper::ElementWrapper;
use crate::invalidation::element::invalidation_map::{ use crate::invalidation::element::invalidation_map::{

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

@ -34,6 +34,7 @@ extern crate debug_unreachable;
#[macro_use] #[macro_use]
extern crate derive_more; extern crate derive_more;
#[macro_use] #[macro_use]
#[cfg(feature = "gecko")]
extern crate gecko_profiler; extern crate gecko_profiler;
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
#[macro_use] #[macro_use]
@ -68,6 +69,7 @@ extern crate servo_atoms;
extern crate static_assertions; extern crate static_assertions;
#[macro_use] #[macro_use]
extern crate style_derive; extern crate style_derive;
#[cfg(feature = "gecko")]
#[macro_use] #[macro_use]
extern crate thin_vec; extern crate thin_vec;
#[macro_use] #[macro_use]

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

@ -29,8 +29,14 @@ use crate::traversal::{DomTraversal, PerLevelTraversalData};
use std::collections::VecDeque; use std::collections::VecDeque;
/// The minimum stack size for a thread in the styling pool, in kilobytes. /// The minimum stack size for a thread in the styling pool, in kilobytes.
#[cfg(feature = "gecko")]
pub const STYLE_THREAD_STACK_SIZE_KB: usize = 256; pub const STYLE_THREAD_STACK_SIZE_KB: usize = 256;
/// The minimum stack size for a thread in the styling pool, in kilobytes.
/// Servo requires a bigger stack in debug builds.
#[cfg(feature = "servo")]
pub const STYLE_THREAD_STACK_SIZE_KB: usize = 512;
/// The stack margin. If we get this deep in the stack, we will skip recursive /// The stack margin. If we get this deep in the stack, we will skip recursive
/// optimizations to ensure that there is sufficient room for non-recursive work. /// optimizations to ensure that there is sufficient room for non-recursive work.
/// ///
@ -74,6 +80,7 @@ fn distribute_one_chunk<'a, 'scope, E, D>(
D: DomTraversal<E>, D: DomTraversal<E>,
{ {
scope.spawn_fifo(move |scope| { scope.spawn_fifo(move |scope| {
#[cfg(feature = "gecko")]
gecko_profiler_label!(Layout, StyleComputation); gecko_profiler_label!(Layout, StyleComputation);
let mut tlc = tls.ensure(create_thread_local_context); let mut tlc = tls.ensure(create_thread_local_context);
let mut context = StyleContext { let mut context = StyleContext {

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

@ -11,6 +11,7 @@ use crate::custom_properties::{
CustomPropertiesBuilder, DeferFontRelativeCustomPropertyResolution, CustomPropertiesBuilder, DeferFontRelativeCustomPropertyResolution,
}; };
use crate::dom::TElement; use crate::dom::TElement;
#[cfg(feature = "gecko")]
use crate::font_metrics::FontMetricsOrientation; use crate::font_metrics::FontMetricsOrientation;
use crate::logical_geometry::WritingMode; use crate::logical_geometry::WritingMode;
use crate::properties::{ use crate::properties::{
@ -26,13 +27,13 @@ use crate::style_adjuster::StyleAdjuster;
use crate::stylesheets::container_rule::ContainerSizeQuery; use crate::stylesheets::container_rule::ContainerSizeQuery;
use crate::stylesheets::{layer_rule::LayerOrder, Origin}; use crate::stylesheets::{layer_rule::LayerOrder, Origin};
use crate::stylist::Stylist; use crate::stylist::Stylist;
#[cfg(feature = "gecko")]
use crate::values::specified::length::FontBaseSize; use crate::values::specified::length::FontBaseSize;
use crate::values::{computed, specified}; use crate::values::{computed, specified};
use fxhash::FxHashMap; use fxhash::FxHashMap;
use servo_arc::Arc; use servo_arc::Arc;
use smallvec::SmallVec; use smallvec::SmallVec;
use std::borrow::Cow; use std::borrow::Cow;
use std::mem;
/// Whether we're resolving a style with the purposes of reparenting for ::first-line. /// Whether we're resolving a style with the purposes of reparenting for ::first-line.
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
@ -418,12 +419,15 @@ fn tweak_when_ignoring_colors(
} }
// Always honor colors if forced-color-adjust is set to none. // Always honor colors if forced-color-adjust is set to none.
let forced = context #[cfg(feature = "gecko")]
.builder {
.get_inherited_text() let forced = context
.clone_forced_color_adjust(); .builder
if forced == computed::ForcedColorAdjust::None { .get_inherited_text()
return; .clone_forced_color_adjust();
if forced == computed::ForcedColorAdjust::None {
return;
}
} }
// Don't override background-color on ::-moz-color-swatch. It is set as an // Don't override background-color on ::-moz-color-swatch. It is set as an
@ -802,9 +806,11 @@ impl<'b> Cascade<'b> {
apply!(FontWeight); apply!(FontWeight);
apply!(FontStretch); apply!(FontStretch);
apply!(FontStyle); apply!(FontStyle);
#[cfg(feature = "gecko")]
apply!(FontSizeAdjust); apply!(FontSizeAdjust);
apply!(ColorScheme); apply!(ColorScheme);
#[cfg(feature = "gecko")]
apply!(ForcedColorAdjust); apply!(ForcedColorAdjust);
// Compute the line height. // Compute the line height.
@ -1310,7 +1316,7 @@ impl<'b> Cascade<'b> {
return s; return s;
} }
if b < a { if b < a {
mem::swap(&mut a, &mut b); std::mem::swap(&mut a, &mut b);
invert_scale_factor = true; invert_scale_factor = true;
} }
let mut e = b - a; let mut e = b - a;

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

@ -867,13 +867,13 @@ def _remove_common_first_line_and_first_letter_properties(props, engine):
props.remove("text-emphasis-position") props.remove("text-emphasis-position")
props.remove("text-emphasis-style") props.remove("text-emphasis-style")
props.remove("text-emphasis-color") props.remove("text-emphasis-color")
props.remove("text-wrap-style")
props.remove("overflow-wrap") props.remove("overflow-wrap")
props.remove("text-align") props.remove("text-align")
props.remove("text-justify") props.remove("text-justify")
props.remove("white-space-collapse") props.remove("white-space-collapse")
props.remove("text-wrap-mode") props.remove("text-wrap-mode")
props.remove("text-wrap-style")
props.remove("word-break") props.remove("word-break")
props.remove("text-indent") props.remove("text-indent")

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

@ -12,12 +12,15 @@
#[cfg(feature = "gecko")] use crate::gecko_bindings::structs::nsCSSPropertyID; #[cfg(feature = "gecko")] use crate::gecko_bindings::structs::nsCSSPropertyID;
use crate::properties::{ use crate::properties::{
longhands::{ longhands::{
self, content_visibility::computed_value::T as ContentVisibility, self, visibility::computed_value::T as Visibility,
visibility::computed_value::T as Visibility,
}, },
CSSWideKeyword, NonCustomPropertyId, LonghandId, NonCustomPropertyIterator, CSSWideKeyword, LonghandId, NonCustomPropertyIterator,
PropertyDeclaration, PropertyDeclarationId, PropertyDeclaration, PropertyDeclarationId,
}; };
#[cfg(feature = "gecko")] use crate::properties::{
longhands::content_visibility::computed_value::T as ContentVisibility,
NonCustomPropertyId,
};
use std::ptr; use std::ptr;
use std::mem; use std::mem;
use fxhash::FxHashMap; use fxhash::FxHashMap;
@ -605,6 +608,7 @@ impl ToAnimatedZero for Visibility {
} }
/// <https://drafts.csswg.org/css-contain-3/#content-visibility-animation> /// <https://drafts.csswg.org/css-contain-3/#content-visibility-animation>
#[cfg(feature = "gecko")]
impl Animate for ContentVisibility { impl Animate for ContentVisibility {
#[inline] #[inline]
fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
@ -626,6 +630,7 @@ impl Animate for ContentVisibility {
} }
} }
#[cfg(feature = "gecko")]
impl ComputeSquaredDistance for ContentVisibility { impl ComputeSquaredDistance for ContentVisibility {
#[inline] #[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {
@ -633,6 +638,7 @@ impl ComputeSquaredDistance for ContentVisibility {
} }
} }
#[cfg(feature = "gecko")]
impl ToAnimatedZero for ContentVisibility { impl ToAnimatedZero for ContentVisibility {
#[inline] #[inline]
fn to_animated_zero(&self) -> Result<Self, ()> { fn to_animated_zero(&self) -> Result<Self, ()> {

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

@ -93,11 +93,12 @@ pub mod longhands {
} }
#[cfg(feature = "gecko")] % if engine == "gecko":
#[allow(unsafe_code, missing_docs)] #[allow(unsafe_code, missing_docs)]
pub mod gecko { pub mod gecko {
<%include file="/gecko.mako.rs" /> <%include file="/gecko.mako.rs" />
} }
% endif
macro_rules! unwrap_or_initial { macro_rules! unwrap_or_initial {
@ -1615,12 +1616,14 @@ pub mod style_structs {
/// Returns whether there is any named progress timeline specified with /// Returns whether there is any named progress timeline specified with
/// scroll-timeline-name other than `none`. /// scroll-timeline-name other than `none`.
#[cfg(feature = "gecko")]
pub fn specifies_scroll_timelines(&self) -> bool { pub fn specifies_scroll_timelines(&self) -> bool {
self.scroll_timeline_name_iter().any(|name| !name.is_none()) self.scroll_timeline_name_iter().any(|name| !name.is_none())
} }
/// Returns whether there is any named progress timeline specified with /// Returns whether there is any named progress timeline specified with
/// view-timeline-name other than `none`. /// view-timeline-name other than `none`.
#[cfg(feature = "gecko")]
pub fn specifies_view_timelines(&self) -> bool { pub fn specifies_view_timelines(&self) -> bool {
self.view_timeline_name_iter().any(|name| !name.is_none()) self.view_timeline_name_iter().any(|name| !name.is_none())
} }

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

@ -128,6 +128,7 @@
"pre-line" => (Wrap::Wrap, Collapse::PreserveBreaks), "pre-line" => (Wrap::Wrap, Collapse::PreserveBreaks),
// TODO: deprecate/remove -moz-pre-space; the white-space-collapse: preserve-spaces value // TODO: deprecate/remove -moz-pre-space; the white-space-collapse: preserve-spaces value
// should serve this purpose? // should serve this purpose?
#[cfg(feature = "gecko")]
"-moz-pre-space" => (Wrap::Wrap, Collapse::PreserveSpaces), "-moz-pre-space" => (Wrap::Wrap, Collapse::PreserveSpaces),
}; };
Ok(expanded! { Ok(expanded! {
@ -180,6 +181,7 @@
Collapse::Collapse => return dest.write_str("normal"), Collapse::Collapse => return dest.write_str("normal"),
Collapse::Preserve => return dest.write_str("pre-wrap"), Collapse::Preserve => return dest.write_str("pre-wrap"),
Collapse::PreserveBreaks => return dest.write_str("pre-line"), Collapse::PreserveBreaks => return dest.write_str("pre-line"),
#[cfg(feature = "gecko")]
Collapse::PreserveSpaces => return dest.write_str("-moz-pre-space"), Collapse::PreserveSpaces => return dest.write_str("-moz-pre-space"),
_ => (), _ => (),
} }

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

@ -24,7 +24,7 @@ use cssparser::{
AtRuleParser, BasicParseErrorKind, CowRcStr, DeclarationParser, ParseErrorKind, Parser, AtRuleParser, BasicParseErrorKind, CowRcStr, DeclarationParser, ParseErrorKind, Parser,
ParserInput, QualifiedRuleParser, RuleBodyItemParser, RuleBodyParser, SourceLocation, ParserInput, QualifiedRuleParser, RuleBodyItemParser, RuleBodyParser, SourceLocation,
}; };
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; #[cfg(feature = "gecko")] use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
use servo_arc::Arc; use servo_arc::Arc;
use std::fmt::{self, Write}; use std::fmt::{self, Write};

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

@ -7,12 +7,15 @@
use crate::computed_value_flags::ComputedValueFlags; use crate::computed_value_flags::ComputedValueFlags;
use crate::dom::TElement; use crate::dom::TElement;
use crate::properties::longhands::contain::computed_value::T as Contain; #[cfg(feature = "gecko")]
use crate::properties::longhands::container_type::computed_value::T as ContainerType; use crate::properties::longhands::{
use crate::properties::longhands::content_visibility::computed_value::T as ContentVisibility; contain::computed_value::T as Contain,
container_type::computed_value::T as ContainerType,
content_visibility::computed_value::T as ContentVisibility,
overflow_x::computed_value::T as Overflow
};
use crate::properties::longhands::display::computed_value::T as Display; use crate::properties::longhands::display::computed_value::T as Display;
use crate::properties::longhands::float::computed_value::T as Float; use crate::properties::longhands::float::computed_value::T as Float;
use crate::properties::longhands::overflow_x::computed_value::T as Overflow;
use crate::properties::longhands::position::computed_value::T as Position; use crate::properties::longhands::position::computed_value::T as Position;
use crate::properties::{self, ComputedValues, StyleBuilder}; use crate::properties::{self, ComputedValues, StyleBuilder};
@ -157,6 +160,7 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
/// This makes the element not be a flex container, with all that it /// This makes the element not be a flex container, with all that it
/// implies, but it should be safe. It matches blink, see /// implies, but it should be safe. It matches blink, see
/// https://bugzilla.mozilla.org/show_bug.cgi?id=1786147#c10 /// https://bugzilla.mozilla.org/show_bug.cgi?id=1786147#c10
#[cfg(feature = "gecko")]
fn adjust_for_webkit_line_clamp(&mut self) { fn adjust_for_webkit_line_clamp(&mut self) {
use crate::properties::longhands::_moz_box_orient::computed_value::T as BoxOrient; use crate::properties::longhands::_moz_box_orient::computed_value::T as BoxOrient;
use crate::values::specified::box_::{DisplayInside, DisplayOutside}; use crate::values::specified::box_::{DisplayInside, DisplayOutside};
@ -281,6 +285,7 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
.add_flags(ComputedValueFlags::IS_ROOT_ELEMENT_STYLE); .add_flags(ComputedValueFlags::IS_ROOT_ELEMENT_STYLE);
} }
#[cfg(feature = "gecko")]
if box_style if box_style
.clone_effective_containment() .clone_effective_containment()
.contains(Contain::STYLE) .contains(Contain::STYLE)
@ -408,6 +413,7 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
/// column-rule-style: none causes a computed column-rule-width of zero /// column-rule-style: none causes a computed column-rule-width of zero
/// at computed value time. /// at computed value time.
#[cfg(feature = "gecko")]
fn adjust_for_column_rule_width(&mut self) { fn adjust_for_column_rule_width(&mut self) {
let column_style = self.style.get_column(); let column_style = self.style.get_column();
if !column_style.clone_column_rule_style().none_or_hidden() { if !column_style.clone_column_rule_style().none_or_hidden() {
@ -455,6 +461,7 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
} }
} }
#[cfg(feature = "gecko")]
fn adjust_for_contain(&mut self) { fn adjust_for_contain(&mut self) {
let box_style = self.style.get_box(); let box_style = self.style.get_box();
let container_type = box_style.clone_container_type(); let container_type = box_style.clone_container_type();
@ -512,6 +519,7 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
/// an auto value /// an auto value
/// ///
/// <https://github.com/w3c/csswg-drafts/issues/8407> /// <https://github.com/w3c/csswg-drafts/issues/8407>
#[cfg(feature = "gecko")]
fn adjust_for_contain_intrinsic_size(&mut self) { fn adjust_for_contain_intrinsic_size(&mut self) {
let content_visibility = self.style.get_box().clone_content_visibility(); let content_visibility = self.style.get_box().clone_content_visibility();
if content_visibility != ContentVisibility::Auto { if content_visibility != ContentVisibility::Auto {
@ -948,17 +956,19 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
} }
self.adjust_for_top_layer(); self.adjust_for_top_layer();
self.blockify_if_necessary(layout_parent_style, element); self.blockify_if_necessary(layout_parent_style, element);
#[cfg(feature = "gecko")]
self.adjust_for_webkit_line_clamp(); self.adjust_for_webkit_line_clamp();
self.adjust_for_position(); self.adjust_for_position();
self.adjust_for_overflow(); self.adjust_for_overflow();
self.adjust_for_contain();
self.adjust_for_contain_intrinsic_size();
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
{ {
self.adjust_for_contain();
self.adjust_for_contain_intrinsic_size();
self.adjust_for_table_text_align(); self.adjust_for_table_text_align();
self.adjust_for_justify_items(); self.adjust_for_justify_items();
} }
self.adjust_for_border_width(); self.adjust_for_border_width();
#[cfg(feature = "gecko")]
self.adjust_for_column_rule_width(); self.adjust_for_column_rule_width();
self.adjust_for_outline_width(); self.adjust_for_outline_width();
self.adjust_for_writing_mode(layout_parent_style); self.adjust_for_writing_mode(layout_parent_style);

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

@ -24,7 +24,7 @@ use cssparser::{
}; };
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss}; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use thin_vec::ThinVec; #[cfg(feature = "gecko")] use thin_vec::ThinVec;
/// A @font-feature-values block declaration. /// A @font-feature-values block declaration.
/// It is `<ident>: <integer>+`. /// It is `<ident>: <integer>+`.

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

@ -7,11 +7,14 @@
//! [font-palette-values]: https://drafts.csswg.org/css-fonts/#font-palette-values //! [font-palette-values]: https://drafts.csswg.org/css-fonts/#font-palette-values
use crate::error_reporting::ContextualParseError; use crate::error_reporting::ContextualParseError;
use crate::gecko_bindings::bindings::Gecko_AppendPaletteValueHashEntry; #[cfg(feature = "gecko")]
use crate::gecko_bindings::bindings::{Gecko_SetFontPaletteBase, Gecko_SetFontPaletteOverride}; use crate::gecko_bindings::{
use crate::gecko_bindings::structs::gfx::FontPaletteValueSet; bindings::Gecko_AppendPaletteValueHashEntry,
use crate::gecko_bindings::structs::gfx::FontPaletteValueSet_PaletteValues_kDark; bindings::{Gecko_SetFontPaletteBase, Gecko_SetFontPaletteOverride},
use crate::gecko_bindings::structs::gfx::FontPaletteValueSet_PaletteValues_kLight; structs::gfx::FontPaletteValueSet,
structs::gfx::FontPaletteValueSet_PaletteValues_kDark,
structs::gfx::FontPaletteValueSet_PaletteValues_kLight,
};
use crate::parser::{Parse, ParserContext}; use crate::parser::{Parse, ParserContext};
use crate::shared_lock::{SharedRwLockReadGuard, ToCssWithGuard}; use crate::shared_lock::{SharedRwLockReadGuard, ToCssWithGuard};
use crate::str::CssStringWriter; use crate::str::CssStringWriter;
@ -164,6 +167,7 @@ impl FontPaletteValuesRule {
} }
/// Convert to Gecko FontPaletteValueSet. /// Convert to Gecko FontPaletteValueSet.
#[cfg(feature = "gecko")]
pub fn to_gecko_palette_value_set(&self, dest: *mut FontPaletteValueSet) { pub fn to_gecko_palette_value_set(&self, dest: *mut FontPaletteValueSet) {
for ref family in self.family_names.iter() { for ref family in self.family_names.iter() {
let family = family.name.to_ascii_lowercase(); let family = family.name.to_ascii_lowercase();

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

@ -667,7 +667,7 @@ impl<'a, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'i> {
"font-face" => { "font-face" => {
AtRulePrelude::FontFace AtRulePrelude::FontFace
}, },
"container" => { "container" if cfg!(feature = "gecko") => {
let condition = Arc::new(ContainerCondition::parse(&self.context, input)?); let condition = Arc::new(ContainerCondition::parse(&self.context, input)?);
AtRulePrelude::Container(condition) AtRulePrelude::Container(condition)
}, },

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

@ -10,6 +10,7 @@ use crate::shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use crate::str::CssStringWriter; use crate::str::CssStringWriter;
use crate::stylesheets::CssRules; use crate::stylesheets::CssRules;
use cssparser::SourceLocation; use cssparser::SourceLocation;
#[cfg(feature = "gecko")]
use malloc_size_of::{MallocSizeOfOps, MallocUnconditionalShallowSizeOf}; use malloc_size_of::{MallocSizeOfOps, MallocUnconditionalShallowSizeOf};
use servo_arc::Arc; use servo_arc::Arc;
use std::fmt::{self, Debug, Write}; use std::fmt::{self, Debug, Write};

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

@ -224,16 +224,28 @@ impl SupportsCondition {
} }
} }
#[cfg(feature = "gecko")]
fn eval_font_format(kw: &FontFaceSourceFormatKeyword) -> bool { fn eval_font_format(kw: &FontFaceSourceFormatKeyword) -> bool {
use crate::gecko_bindings::bindings; use crate::gecko_bindings::bindings;
unsafe { bindings::Gecko_IsFontFormatSupported(*kw) } unsafe { bindings::Gecko_IsFontFormatSupported(*kw) }
} }
#[cfg(feature = "gecko")]
fn eval_font_tech(flag: &FontFaceSourceTechFlags) -> bool { fn eval_font_tech(flag: &FontFaceSourceTechFlags) -> bool {
use crate::gecko_bindings::bindings; use crate::gecko_bindings::bindings;
unsafe { bindings::Gecko_IsFontTechSupported(*flag) } unsafe { bindings::Gecko_IsFontTechSupported(*flag) }
} }
#[cfg(feature = "servo")]
fn eval_font_format(_: &FontFaceSourceFormatKeyword) -> bool {
false
}
#[cfg(feature = "servo")]
fn eval_font_tech(_: &FontFaceSourceTechFlags) -> bool {
false
}
/// supports_condition | declaration /// supports_condition | declaration
/// <https://drafts.csswg.org/css-conditional/#dom-css-supports-conditiontext-conditiontext> /// <https://drafts.csswg.org/css-conditional/#dom-css-supports-conditiontext-conditiontext>
pub fn parse_condition_or_declaration<'i, 't>( pub fn parse_condition_or_declaration<'i, 't>(

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

@ -1748,6 +1748,7 @@ impl<T> Default for LayerOrderedMap<T> {
} }
} }
#[cfg(feature = "gecko")]
impl<T: 'static> LayerOrderedVec<T> { impl<T: 'static> LayerOrderedVec<T> {
fn clear(&mut self) { fn clear(&mut self) {
self.0.clear(); self.0.clear();
@ -1829,6 +1830,7 @@ pub struct PageRuleMap {
pub rules: PrecomputedHashMap<Atom, SmallVec<[PageRuleData; 1]>>, pub rules: PrecomputedHashMap<Atom, SmallVec<[PageRuleData; 1]>>,
} }
#[cfg(feature = "gecko")]
impl PageRuleMap { impl PageRuleMap {
#[inline] #[inline]
fn clear(&mut self) { fn clear(&mut self) {
@ -3156,6 +3158,7 @@ impl CascadeData {
order.inc(); order.inc();
} }
} }
#[cfg(feature = "gecko")]
self.extra_data.sort_by_layer(&self.layers); self.extra_data.sort_by_layer(&self.layers);
self.animations self.animations
.sort_with(&self.layers, compare_keyframes_in_same_layer); .sort_with(&self.layers, compare_keyframes_in_same_layer);
@ -3890,6 +3893,7 @@ impl CascadeData {
.push(ContainerConditionReference::none()); .push(ContainerConditionReference::none());
self.scope_conditions.clear(); self.scope_conditions.clear();
self.scope_conditions.push(ScopeConditionReference::none()); self.scope_conditions.push(ScopeConditionReference::none());
#[cfg(feature = "gecko")]
self.extra_data.clear(); self.extra_data.clear();
self.rules_source_order = 0; self.rules_source_order = 0;
self.num_selectors = 0; self.num_selectors = 0;

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

@ -21,10 +21,11 @@ use crate::values::specified::font::{
use crate::values::specified::length::{FontBaseSize, LineHeightBase, NoCalcLength}; use crate::values::specified::length::{FontBaseSize, LineHeightBase, NoCalcLength};
use crate::Atom; use crate::Atom;
use cssparser::{serialize_identifier, CssStringWriter, Parser}; use cssparser::{serialize_identifier, CssStringWriter, Parser};
#[cfg(feature = "gecko")]
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use num_traits::abs; use num_traits::abs;
use num_traits::cast::AsPrimitive; use num_traits::cast::AsPrimitive;
#[cfg(feature = "servo")]
use std::hash::{Hash, Hasher};
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, ToCss}; use style_traits::{CssWriter, ParseError, ToCss};
@ -338,7 +339,7 @@ impl ToResolvedValue for FontSize {
} }
#[derive(Clone, Debug, Eq, PartialEq, ToComputedValue, ToResolvedValue)] #[derive(Clone, Debug, Eq, PartialEq, ToComputedValue, ToResolvedValue)]
#[cfg_attr(feature = "servo", derive(Hash, MallocSizeOf, Serialize, Deserialize))] #[cfg_attr(feature = "servo", derive(Hash, Serialize, Deserialize))]
/// Specifies a prioritized list of font family names or generic family names. /// Specifies a prioritized list of font family names or generic family names.
#[repr(C)] #[repr(C)]
pub struct FontFamily { pub struct FontFamily {
@ -373,6 +374,7 @@ impl FontFamily {
} }
/// Returns the font family for `-moz-bullet-font`. /// Returns the font family for `-moz-bullet-font`.
#[cfg(feature = "gecko")]
pub(crate) fn moz_bullet() -> &'static Self { pub(crate) fn moz_bullet() -> &'static Self {
static_font_family!( static_font_family!(
MOZ_BULLET, MOZ_BULLET,
@ -386,6 +388,7 @@ impl FontFamily {
} }
/// Returns a font family for a single system font. /// Returns a font family for a single system font.
#[cfg(feature = "gecko")]
pub fn for_system_font(name: &str) -> Self { pub fn for_system_font(name: &str) -> Self {
Self { Self {
families: FontFamilyList { families: FontFamilyList {
@ -417,6 +420,7 @@ impl FontFamily {
generic_font_family!(MONOSPACE, Monospace); generic_font_family!(MONOSPACE, Monospace);
generic_font_family!(CURSIVE, Cursive); generic_font_family!(CURSIVE, Cursive);
generic_font_family!(FANTASY, Fantasy); generic_font_family!(FANTASY, Fantasy);
#[cfg(feature = "gecko")]
generic_font_family!(MOZ_EMOJI, MozEmoji); generic_font_family!(MOZ_EMOJI, MozEmoji);
generic_font_family!(SYSTEM_UI, SystemUi); generic_font_family!(SYSTEM_UI, SystemUi);
@ -430,6 +434,7 @@ impl FontFamily {
GenericFontFamily::Monospace => &*MONOSPACE, GenericFontFamily::Monospace => &*MONOSPACE,
GenericFontFamily::Cursive => &*CURSIVE, GenericFontFamily::Cursive => &*CURSIVE,
GenericFontFamily::Fantasy => &*FANTASY, GenericFontFamily::Fantasy => &*FANTASY,
#[cfg(feature = "gecko")]
GenericFontFamily::MozEmoji => &*MOZ_EMOJI, GenericFontFamily::MozEmoji => &*MOZ_EMOJI,
GenericFontFamily::SystemUi => &*SYSTEM_UI, GenericFontFamily::SystemUi => &*SYSTEM_UI,
}; };
@ -441,7 +446,6 @@ impl FontFamily {
} }
} }
#[cfg(feature = "gecko")]
impl MallocSizeOf for FontFamily { impl MallocSizeOf for FontFamily {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
use malloc_size_of::MallocUnconditionalSizeOf; use malloc_size_of::MallocUnconditionalSizeOf;
@ -488,6 +492,7 @@ pub struct FamilyName {
pub syntax: FontFamilyNameSyntax, pub syntax: FontFamilyNameSyntax,
} }
#[cfg(feature = "gecko")]
impl FamilyName { impl FamilyName {
fn is_known_icon_font_family(&self) -> bool { fn is_known_icon_font_family(&self) -> bool {
use crate::gecko_bindings::bindings; use crate::gecko_bindings::bindings;
@ -495,6 +500,13 @@ impl FamilyName {
} }
} }
#[cfg(feature = "servo")]
impl FamilyName {
fn is_known_icon_font_family(&self) -> bool {
false
}
}
impl ToCss for FamilyName { impl ToCss for FamilyName {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
@ -615,8 +627,9 @@ impl GenericFontFamily {
/// the user. See bug 789788 and bug 1730098. /// the user. See bug 789788 and bug 1730098.
pub(crate) fn valid_for_user_font_prioritization(self) -> bool { pub(crate) fn valid_for_user_font_prioritization(self) -> bool {
match self { match self {
Self::None | Self::Fantasy | Self::Cursive | Self::SystemUi | Self::MozEmoji => false, Self::None | Self::Fantasy | Self::Cursive | Self::SystemUi => false,
#[cfg(feature = "gecko")]
Self::MozEmoji => false,
Self::Serif | Self::SansSerif | Self::Monospace => true, Self::Serif | Self::SansSerif | Self::Monospace => true,
} }
} }
@ -686,12 +699,22 @@ impl Parse for SingleFontFamily {
/// A list of font families. /// A list of font families.
#[derive(Clone, Debug, ToComputedValue, ToResolvedValue, ToShmem, PartialEq, Eq)] #[derive(Clone, Debug, ToComputedValue, ToResolvedValue, ToShmem, PartialEq, Eq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[repr(C)] #[repr(C)]
pub struct FontFamilyList { pub struct FontFamilyList {
/// The actual list of font families specified. /// The actual list of font families specified.
pub list: crate::ArcSlice<SingleFontFamily>, pub list: crate::ArcSlice<SingleFontFamily>,
} }
#[cfg(feature = "servo")]
impl Hash for FontFamilyList {
fn hash<H: Hasher>(&self, state: &mut H) {
for font in self.iter() {
font.hash(state);
}
}
}
impl FontFamilyList { impl FontFamilyList {
/// Return iterator of SingleFontFamily /// Return iterator of SingleFontFamily
pub fn iter(&self) -> impl Iterator<Item = &SingleFontFamily> { pub fn iter(&self) -> impl Iterator<Item = &SingleFontFamily> {
@ -704,6 +727,7 @@ impl FontFamilyList {
/// generic instead of the site's specified font may cause substantial breakage. /// generic instead of the site's specified font may cause substantial breakage.
/// If no suitable generic is found in the list, insert the default generic ahead /// If no suitable generic is found in the list, insert the default generic ahead
/// of all the listed families except for known ligature-based icon fonts. /// of all the listed families except for known ligature-based icon fonts.
#[cfg_attr(feature = "servo", allow(unused))]
pub(crate) fn prioritize_first_generic_or_prepend(&mut self, generic: GenericFontFamily) { pub(crate) fn prioritize_first_generic_or_prepend(&mut self, generic: GenericFontFamily) {
let mut index_of_first_generic = None; let mut index_of_first_generic = None;
let mut target_index = None; let mut target_index = None;
@ -752,6 +776,7 @@ impl FontFamilyList {
} }
/// Returns whether we need to prioritize user fonts. /// Returns whether we need to prioritize user fonts.
#[cfg_attr(feature = "servo", allow(unused))]
pub(crate) fn needs_user_font_prioritization(&self) -> bool { pub(crate) fn needs_user_font_prioritization(&self) -> bool {
self.iter().next().map_or(true, |f| match f { self.iter().next().map_or(true, |f| match f {
SingleFontFamily::Generic(f) => !f.valid_for_user_font_prioritization(), SingleFontFamily::Generic(f) => !f.valid_for_user_font_prioritization(),
@ -1337,21 +1362,33 @@ impl ToResolvedValue for LineHeight {
type ResolvedValue = Self; type ResolvedValue = Self;
fn to_resolved_value(self, context: &ResolvedContext) -> Self::ResolvedValue { fn to_resolved_value(self, context: &ResolvedContext) -> Self::ResolvedValue {
// Resolve <number> to an absolute <length> based on font size. #[cfg(feature = "gecko")]
if matches!(self, Self::Normal | Self::MozBlockHeight) { {
return self; // Resolve <number> to an absolute <length> based on font size.
if matches!(self, Self::Normal | Self::MozBlockHeight) {
return self;
}
let wm = context.style.writing_mode;
Self::Length(
context
.device
.calc_line_height(
context.style.get_font(),
wm,
Some(context.element_info.element),
)
.to_resolved_value(context),
)
}
#[cfg(feature = "servo")]
{
if let LineHeight::Number(num) = &self {
let size = context.style.get_font().clone_font_size().computed_size();
LineHeight::Length(NonNegativeLength::new(size.px() * num.0))
} else {
self
}
} }
let wm = context.style.writing_mode;
Self::Length(
context
.device
.calc_line_height(
context.style.get_font(),
wm,
Some(context.element_info.element),
)
.to_resolved_value(context),
)
} }
#[inline] #[inline]

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

@ -25,6 +25,7 @@
//! our expectations. //! our expectations.
use super::{Context, Length, Percentage, ToComputedValue}; use super::{Context, Length, Percentage, ToComputedValue};
#[cfg(feature = "gecko")]
use crate::gecko_bindings::structs::GeckoFontMetrics; use crate::gecko_bindings::structs::GeckoFontMetrics;
use crate::values::animated::{Animate, Context as AnimatedContext, Procedure, ToAnimatedValue, ToAnimatedZero}; use crate::values::animated::{Animate, Context as AnimatedContext, Procedure, ToAnimatedValue, ToAnimatedZero};
use crate::values::distance::{ComputeSquaredDistance, SquaredDistance}; use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
@ -998,6 +999,7 @@ impl specified::CalcLengthPercentage {
/// Compute the value into pixel length as CSSFloat, using the get_font_metrics function /// Compute the value into pixel length as CSSFloat, using the get_font_metrics function
/// if provided to resolve font-relative dimensions. /// if provided to resolve font-relative dimensions.
#[cfg(feature = "gecko")]
pub fn to_computed_pixel_length_with_font_metrics( pub fn to_computed_pixel_length_with_font_metrics(
&self, &self,
get_font_metrics: Option<impl Fn() -> GeckoFontMetrics>, get_font_metrics: Option<impl Fn() -> GeckoFontMetrics>,

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

@ -151,14 +151,19 @@ impl<LengthPercentage: Parse> Parse for LengthPercentageOrAuto<LengthPercentage>
pub enum GenericSize<LengthPercent> { pub enum GenericSize<LengthPercent> {
LengthPercentage(LengthPercent), LengthPercentage(LengthPercent),
Auto, Auto,
#[cfg(feature = "gecko")]
#[animation(error)] #[animation(error)]
MaxContent, MaxContent,
#[cfg(feature = "gecko")]
#[animation(error)] #[animation(error)]
MinContent, MinContent,
#[cfg(feature = "gecko")]
#[animation(error)] #[animation(error)]
FitContent, FitContent,
#[cfg(feature = "gecko")]
#[animation(error)] #[animation(error)]
MozAvailable, MozAvailable,
#[cfg(feature = "gecko")]
#[animation(error)] #[animation(error)]
WebkitFillAvailable, WebkitFillAvailable,
#[animation(error)] #[animation(error)]
@ -206,14 +211,19 @@ impl<LengthPercentage> Size<LengthPercentage> {
pub enum GenericMaxSize<LengthPercent> { pub enum GenericMaxSize<LengthPercent> {
LengthPercentage(LengthPercent), LengthPercentage(LengthPercent),
None, None,
#[cfg(feature = "gecko")]
#[animation(error)] #[animation(error)]
MaxContent, MaxContent,
#[cfg(feature = "gecko")]
#[animation(error)] #[animation(error)]
MinContent, MinContent,
#[cfg(feature = "gecko")]
#[animation(error)] #[animation(error)]
FitContent, FitContent,
#[cfg(feature = "gecko")]
#[animation(error)] #[animation(error)]
MozAvailable, MozAvailable,
#[cfg(feature = "gecko")]
#[animation(error)] #[animation(error)]
WebkitFillAvailable, WebkitFillAvailable,
#[animation(error)] #[animation(error)]

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

@ -715,12 +715,16 @@ impl ToCss for KeyframesName {
return dest.write_str("none"); return dest.write_str("none");
} }
self.0.with_str(|s| { let mut serialize = |string: &_| {
if CustomIdent::is_valid(s, &["none"]) { if CustomIdent::is_valid(string, &["none"]) {
serialize_identifier(s, dest) serialize_identifier(string, dest)
} else { } else {
s.to_css(dest) string.to_css(dest)
} }
}) };
#[cfg(feature = "gecko")]
return self.0.with_str(serialize);
#[cfg(feature = "servo")]
return serialize(self.0.as_ref());
} }
} }

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

@ -6,6 +6,7 @@
//! there are used values. //! there are used values.
use app_units::Au; use app_units::Au;
#[cfg(feature = "gecko")]
use crate::media_queries::Device; use crate::media_queries::Device;
use crate::properties::ComputedValues; use crate::properties::ComputedValues;
use crate::ArcSlice; use crate::ArcSlice;
@ -18,9 +19,9 @@ mod counters;
use crate::values::computed::{self, Length}; use crate::values::computed::{self, Length};
/// Element-specific information needed to resolve property values. /// Element-specific information needed to resolve property values.
#[cfg(feature = "gecko")]
pub struct ResolvedElementInfo<'a> { pub struct ResolvedElementInfo<'a> {
/// Element we're resolving line-height against. /// Element we're resolving line-height against.
#[cfg(feature = "gecko")]
pub element: crate::gecko::wrapper::GeckoElement<'a>, pub element: crate::gecko::wrapper::GeckoElement<'a>,
} }
@ -30,8 +31,10 @@ pub struct Context<'a> {
pub style: &'a ComputedValues, pub style: &'a ComputedValues,
/// The device / document we're resolving style for. Useful to do font metrics stuff needed for /// The device / document we're resolving style for. Useful to do font metrics stuff needed for
/// line-height. /// line-height.
#[cfg(feature = "gecko")]
pub device: &'a Device, pub device: &'a Device,
/// The element-specific information to resolve the value. /// The element-specific information to resolve the value.
#[cfg(feature = "gecko")]
pub element_info: ResolvedElementInfo<'a>, pub element_info: ResolvedElementInfo<'a>,
} }

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

@ -255,7 +255,10 @@ impl AnimationDirection {
#[inline] #[inline]
pub fn match_keywords(name: &AnimationName) -> bool { pub fn match_keywords(name: &AnimationName) -> bool {
if let Some(name) = name.as_atom() { if let Some(name) = name.as_atom() {
#[cfg(feature = "gecko")]
return name.with_str(|n| Self::from_ident(n).is_ok()); return name.with_str(|n| Self::from_ident(n).is_ok());
#[cfg(feature = "servo")]
return Self::from_ident(name).is_ok();
} }
false false
} }
@ -287,7 +290,10 @@ impl AnimationPlayState {
#[inline] #[inline]
pub fn match_keywords(name: &AnimationName) -> bool { pub fn match_keywords(name: &AnimationName) -> bool {
if let Some(name) = name.as_atom() { if let Some(name) = name.as_atom() {
#[cfg(feature = "gecko")]
return name.with_str(|n| Self::from_ident(n).is_ok()); return name.with_str(|n| Self::from_ident(n).is_ok());
#[cfg(feature = "servo")]
return Self::from_ident(atom).is_ok();
} }
false false
} }

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

@ -5,6 +5,7 @@
//! Specified types for box properties. //! Specified types for box properties.
use crate::parser::{Parse, ParserContext}; use crate::parser::{Parse, ParserContext};
#[cfg(feature = "gecko")]
use crate::properties::{LonghandId, PropertyDeclarationId, PropertyId}; use crate::properties::{LonghandId, PropertyDeclarationId, PropertyId};
use crate::values::generics::box_::{ use crate::values::generics::box_::{
GenericContainIntrinsicSize, GenericLineClamp, GenericPerspective, GenericVerticalAlign, GenericContainIntrinsicSize, GenericLineClamp, GenericPerspective, GenericVerticalAlign,
@ -1023,6 +1024,10 @@ bitflags! {
} }
} }
#[cfg(feature="servo")]
fn change_bits_for_longhand(longhand: LonghandId) -> WillChangeBits { WillChangeBits::empty() }
#[cfg(feature = "gecko")]
fn change_bits_for_longhand(longhand: LonghandId) -> WillChangeBits { fn change_bits_for_longhand(longhand: LonghandId) -> WillChangeBits {
match longhand { match longhand {
LonghandId::Opacity => WillChangeBits::OPACITY, LonghandId::Opacity => WillChangeBits::OPACITY,
@ -1663,6 +1668,7 @@ impl BreakBetween {
/// Parse a legacy break-between value for `page-break-{before,after}`. /// Parse a legacy break-between value for `page-break-{before,after}`.
/// ///
/// See https://drafts.csswg.org/css-break/#page-break-properties. /// See https://drafts.csswg.org/css-break/#page-break-properties.
#[cfg_attr(feature = "servo", allow(unused))]
#[inline] #[inline]
pub(crate) fn parse_legacy<'i>( pub(crate) fn parse_legacy<'i>(
_: &ParserContext, _: &ParserContext,
@ -1683,6 +1689,7 @@ impl BreakBetween {
/// Serialize a legacy break-between value for `page-break-*`. /// Serialize a legacy break-between value for `page-break-*`.
/// ///
/// See https://drafts.csswg.org/css-break/#page-break-properties. /// See https://drafts.csswg.org/css-break/#page-break-properties.
#[cfg_attr(feature = "servo", allow(unused))]
pub(crate) fn to_css_legacy<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result pub(crate) fn to_css_legacy<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
W: Write, W: Write,
@ -1728,6 +1735,7 @@ impl BreakWithin {
/// Parse a legacy break-between value for `page-break-inside`. /// Parse a legacy break-between value for `page-break-inside`.
/// ///
/// See https://drafts.csswg.org/css-break/#page-break-properties. /// See https://drafts.csswg.org/css-break/#page-break-properties.
#[cfg_attr(feature = "servo", allow(unused))]
#[inline] #[inline]
pub(crate) fn parse_legacy<'i>( pub(crate) fn parse_legacy<'i>(
_: &ParserContext, _: &ParserContext,
@ -1745,6 +1753,7 @@ impl BreakWithin {
/// Serialize a legacy break-between value for `page-break-inside`. /// Serialize a legacy break-between value for `page-break-inside`.
/// ///
/// See https://drafts.csswg.org/css-break/#page-break-properties. /// See https://drafts.csswg.org/css-break/#page-break-properties.
#[cfg_attr(feature = "servo", allow(unused))]
pub(crate) fn to_css_legacy<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result pub(crate) fn to_css_legacy<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
W: Write, W: Write,

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

@ -576,8 +576,11 @@ impl Color {
/// Returns whether this color is allowed in forced-colors mode. /// Returns whether this color is allowed in forced-colors mode.
pub fn honored_in_forced_colors_mode(&self, allow_transparent: bool) -> bool { pub fn honored_in_forced_colors_mode(&self, allow_transparent: bool) -> bool {
match *self { match *self {
#[cfg(feature = "gecko")]
Self::InheritFromBodyQuirk => false, Self::InheritFromBodyQuirk => false,
Self::CurrentColor | Color::System(..) => true, Self::CurrentColor => true,
#[cfg(feature = "gecko")]
Self::System(..) => true,
Self::Absolute(ref absolute) => allow_transparent && absolute.color.is_transparent(), Self::Absolute(ref absolute) => allow_transparent && absolute.color.is_transparent(),
Self::LightDark(ref ld) => { Self::LightDark(ref ld) => {
ld.light.honored_in_forced_colors_mode(allow_transparent) && ld.light.honored_in_forced_colors_mode(allow_transparent) &&

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

@ -249,6 +249,7 @@ impl Parse for Content {
"-moz-alt-content" if context.in_ua_sheet() => { "-moz-alt-content" if context.in_ua_sheet() => {
generics::ContentItem::MozAltContent generics::ContentItem::MozAltContent
}, },
#[cfg(feature = "gecko")]
"-moz-label-content" if context.chrome_rules_enabled() => { "-moz-label-content" if context.chrome_rules_enabled() => {
generics::ContentItem::MozLabelContent generics::ContentItem::MozLabelContent
}, },

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

@ -145,7 +145,11 @@ impl TimingFunction {
#[inline] #[inline]
pub fn match_keywords(name: &AnimationName) -> bool { pub fn match_keywords(name: &AnimationName) -> bool {
if let Some(name) = name.as_atom() { if let Some(name) = name.as_atom() {
#[cfg(feature = "gecko")]
return name.with_str(|n| TimingKeyword::from_ident(n).is_ok()); return name.with_str(|n| TimingKeyword::from_ident(n).is_ok());
#[cfg(feature = "servo")]
return TimingKeyword::from_ident(name).is_ok();
} }
false false
} }

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

@ -297,13 +297,10 @@ impl Filter {
Err(()) Err(())
} }
}, },
Filter::Url(ref url) => { #[cfg(feature = "gecko")]
if cfg!(feature = "gecko") { Filter::Url(ref url) => Ok(ComputedFilter::Url(ComputedUrl(url.clone()))),
Ok(ComputedFilter::Url(ComputedUrl(url.clone()))) #[cfg(feature = "servo")]
} else { Filter::Url(_) => Err(()),
Err(())
}
},
} }
} }
} }

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

@ -70,6 +70,7 @@ macro_rules! system_font_methods {
Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem,
)] )]
#[allow(missing_docs)] #[allow(missing_docs)]
#[cfg(feature = "gecko")]
pub enum SystemFont { pub enum SystemFont {
/// https://drafts.csswg.org/css-fonts/#valdef-font-caption /// https://drafts.csswg.org/css-fonts/#valdef-font-caption
Caption, Caption,
@ -99,6 +100,26 @@ pub enum SystemFont {
End, // Just for indexing purposes. End, // Just for indexing purposes.
} }
// We don't parse system fonts in servo, but in the interest of not
// littering a lot of code with `if engine == "gecko"` conditionals,
// we have a dummy system font module that does nothing
#[derive(
Clone, Copy, Debug, Eq, Hash, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem
)]
#[allow(missing_docs)]
#[cfg(feature = "servo")]
/// void enum for system font, can never exist
pub enum SystemFont {}
#[allow(missing_docs)]
#[cfg(feature = "servo")]
impl SystemFont {
pub fn parse(_: &mut Parser) -> Result<Self, ()> {
Err(())
}
}
const DEFAULT_SCRIPT_MIN_SIZE_PT: u32 = 8; const DEFAULT_SCRIPT_MIN_SIZE_PT: u32 = 8;
const DEFAULT_SCRIPT_SIZE_MULTIPLIER: f64 = 0.71; const DEFAULT_SCRIPT_SIZE_MULTIPLIER: f64 = 0.71;
@ -557,6 +578,7 @@ impl KeywordInfo {
/// text-zoom. /// text-zoom.
fn to_computed_value(&self, context: &Context) -> CSSPixelLength { fn to_computed_value(&self, context: &Context) -> CSSPixelLength {
debug_assert_ne!(self.kw, FontSizeKeyword::None); debug_assert_ne!(self.kw, FontSizeKeyword::None);
#[cfg(feature="gecko")]
debug_assert_ne!(self.kw, FontSizeKeyword::Math); debug_assert_ne!(self.kw, FontSizeKeyword::Math);
let base = context.maybe_zoom_text(self.kw.to_length(context).0); let base = context.maybe_zoom_text(self.kw.to_length(context).0);
base * self.factor + context.maybe_zoom_text(self.offset) base * self.factor + context.maybe_zoom_text(self.offset)

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

@ -120,6 +120,7 @@ fn cross_fade_enabled() -> bool {
false false
} }
impl SpecifiedValueInfo for Gradient { impl SpecifiedValueInfo for Gradient {
const SUPPORTED_TYPES: u8 = CssType::GRADIENT; const SUPPORTED_TYPES: u8 = CssType::GRADIENT;
@ -1306,6 +1307,7 @@ impl PaintWorklet {
#[repr(u8)] #[repr(u8)]
pub enum ImageRendering { pub enum ImageRendering {
Auto, Auto,
#[cfg(feature = "gecko")]
Smooth, Smooth,
#[parse(aliases = "-moz-crisp-edges")] #[parse(aliases = "-moz-crisp-edges")]
CrispEdges, CrispEdges,
@ -1318,6 +1320,8 @@ pub enum ImageRendering {
// as crisp-edges and smooth respectively, and authors must not use // as crisp-edges and smooth respectively, and authors must not use
// them. // them.
// //
#[cfg(feature = "gecko")]
Optimizespeed, Optimizespeed,
#[cfg(feature = "gecko")]
Optimizequality, Optimizequality,
} }

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

@ -9,6 +9,7 @@
use super::{AllowQuirks, Number, Percentage, ToComputedValue}; use super::{AllowQuirks, Number, Percentage, ToComputedValue};
use crate::computed_value_flags::ComputedValueFlags; use crate::computed_value_flags::ComputedValueFlags;
use crate::font_metrics::{FontMetrics, FontMetricsOrientation}; use crate::font_metrics::{FontMetrics, FontMetricsOrientation};
#[cfg(feature = "gecko")]
use crate::gecko_bindings::structs::GeckoFontMetrics; use crate::gecko_bindings::structs::GeckoFontMetrics;
use crate::parser::{Parse, ParserContext}; use crate::parser::{Parse, ParserContext};
use crate::values::computed::{self, CSSPixelLength, Context}; use crate::values::computed::{self, CSSPixelLength, Context};
@ -212,6 +213,7 @@ impl FontRelativeLength {
} }
/// Computes the length, given a GeckoFontMetrics getter to resolve font-relative units. /// Computes the length, given a GeckoFontMetrics getter to resolve font-relative units.
#[cfg(feature = "gecko")]
pub fn to_computed_pixel_length_with_font_metrics( pub fn to_computed_pixel_length_with_font_metrics(
&self, &self,
get_font_metrics: impl Fn() -> GeckoFontMetrics, get_font_metrics: impl Fn() -> GeckoFontMetrics,
@ -1220,6 +1222,7 @@ impl NoCalcLength {
/// Get a px value without a full style context; this can handle either /// Get a px value without a full style context; this can handle either
/// absolute or (if a font metrics getter is provided) font-relative units. /// absolute or (if a font metrics getter is provided) font-relative units.
#[cfg(feature = "gecko")]
#[inline] #[inline]
pub fn to_computed_pixel_length_with_font_metrics( pub fn to_computed_pixel_length_with_font_metrics(
&self, &self,
@ -1509,6 +1512,7 @@ impl Length {
} }
/// Get a px value, with an optional GeckoFontMetrics getter to resolve font-relative units. /// Get a px value, with an optional GeckoFontMetrics getter to resolve font-relative units.
#[cfg(feature = "gecko")]
pub fn to_computed_pixel_length_with_font_metrics( pub fn to_computed_pixel_length_with_font_metrics(
&self, &self,
get_font_metrics: Option<impl Fn() -> GeckoFontMetrics>, get_font_metrics: Option<impl Fn() -> GeckoFontMetrics>,

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

@ -278,6 +278,7 @@ pub enum TextTransformCase {
/// Capitalize each word. /// Capitalize each word.
Capitalize, Capitalize,
/// Automatic italicization of math variables. /// Automatic italicization of math variables.
#[cfg(feature = "gecko")]
MathAuto, MathAuto,
} }
@ -296,11 +297,16 @@ pub enum TextTransformCase {
ToResolvedValue, ToResolvedValue,
ToShmem, ToShmem,
)] )]
#[css(bitflags( #[cfg_attr(feature = "gecko", css(bitflags(
single = "none,math-auto", single = "none,math-auto",
mixed = "uppercase,lowercase,capitalize,full-width,full-size-kana", mixed = "uppercase,lowercase,capitalize,full-width,full-size-kana",
validate_mixed = "Self::validate_mixed_flags", validate_mixed = "Self::validate_mixed_flags",
))] )))]
#[cfg_attr(not(feature = "gecko"), css(bitflags(
single = "none",
mixed = "uppercase,lowercase,capitalize,full-width,full-size-kana",
validate_mixed = "Self::validate_mixed_flags",
)))]
#[repr(C)] #[repr(C)]
/// Specified value for the text-transform property. /// Specified value for the text-transform property.
/// (The spec grammar gives /// (The spec grammar gives
@ -798,6 +804,7 @@ pub enum MozControlCharacterVisibility {
Visible, Visible,
} }
#[cfg(feature = "gecko")]
impl Default for MozControlCharacterVisibility { impl Default for MozControlCharacterVisibility {
fn default() -> Self { fn default() -> Self {
if static_prefs::pref!("layout.css.control-characters.visible") { if static_prefs::pref!("layout.css.control-characters.visible") {

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

@ -20,6 +20,7 @@ extern crate lazy_static;
extern crate malloc_size_of; extern crate malloc_size_of;
#[macro_use] #[macro_use]
extern crate malloc_size_of_derive; extern crate malloc_size_of_derive;
#[cfg(feature = "gecko")]
extern crate nsstring; extern crate nsstring;
extern crate selectors; extern crate selectors;
#[macro_use] #[macro_use]

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

@ -7,6 +7,7 @@
use app_units::Au; use app_units::Au;
use cssparser::ToCss as CssparserToCss; use cssparser::ToCss as CssparserToCss;
use cssparser::{serialize_string, ParseError, Parser, Token, UnicodeRange}; use cssparser::{serialize_string, ParseError, Parser, Token, UnicodeRange};
#[cfg(feature = "gecko")]
use nsstring::nsCString; use nsstring::nsCString;
use servo_arc::Arc; use servo_arc::Arc;
use std::fmt::{self, Write}; use std::fmt::{self, Write};