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)
}
#[cfg(feature = "gecko")]
fn get_content_preferred_color_scheme(device: &Device, url_data: &UrlExtraData) -> VariableValue {
use crate::gecko::media_features::PrefersColorScheme;
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 {
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),
];
#[cfg(feature = "gecko")]
macro_rules! lnf_int {
($id:ident) => {
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 {
($atom:expr, $id:ident, $ctor:ident) => {{
fn __eval(_: &Device, url_data: &UrlExtraData) -> VariableValue {

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

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

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

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

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

@ -29,8 +29,14 @@ use crate::traversal::{DomTraversal, PerLevelTraversalData};
use std::collections::VecDeque;
/// 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;
/// 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
/// 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>,
{
scope.spawn_fifo(move |scope| {
#[cfg(feature = "gecko")]
gecko_profiler_label!(Layout, StyleComputation);
let mut tlc = tls.ensure(create_thread_local_context);
let mut context = StyleContext {

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

@ -11,6 +11,7 @@ use crate::custom_properties::{
CustomPropertiesBuilder, DeferFontRelativeCustomPropertyResolution,
};
use crate::dom::TElement;
#[cfg(feature = "gecko")]
use crate::font_metrics::FontMetricsOrientation;
use crate::logical_geometry::WritingMode;
use crate::properties::{
@ -26,13 +27,13 @@ use crate::style_adjuster::StyleAdjuster;
use crate::stylesheets::container_rule::ContainerSizeQuery;
use crate::stylesheets::{layer_rule::LayerOrder, Origin};
use crate::stylist::Stylist;
#[cfg(feature = "gecko")]
use crate::values::specified::length::FontBaseSize;
use crate::values::{computed, specified};
use fxhash::FxHashMap;
use servo_arc::Arc;
use smallvec::SmallVec;
use std::borrow::Cow;
use std::mem;
/// Whether we're resolving a style with the purposes of reparenting for ::first-line.
#[derive(Copy, Clone)]
@ -418,12 +419,15 @@ fn tweak_when_ignoring_colors(
}
// Always honor colors if forced-color-adjust is set to none.
let forced = context
.builder
.get_inherited_text()
.clone_forced_color_adjust();
if forced == computed::ForcedColorAdjust::None {
return;
#[cfg(feature = "gecko")]
{
let forced = context
.builder
.get_inherited_text()
.clone_forced_color_adjust();
if forced == computed::ForcedColorAdjust::None {
return;
}
}
// 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!(FontStretch);
apply!(FontStyle);
#[cfg(feature = "gecko")]
apply!(FontSizeAdjust);
apply!(ColorScheme);
#[cfg(feature = "gecko")]
apply!(ForcedColorAdjust);
// Compute the line height.
@ -1310,7 +1316,7 @@ impl<'b> Cascade<'b> {
return s;
}
if b < a {
mem::swap(&mut a, &mut b);
std::mem::swap(&mut a, &mut b);
invert_scale_factor = true;
}
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-style")
props.remove("text-emphasis-color")
props.remove("text-wrap-style")
props.remove("overflow-wrap")
props.remove("text-align")
props.remove("text-justify")
props.remove("white-space-collapse")
props.remove("text-wrap-mode")
props.remove("text-wrap-style")
props.remove("word-break")
props.remove("text-indent")

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

@ -12,12 +12,15 @@
#[cfg(feature = "gecko")] use crate::gecko_bindings::structs::nsCSSPropertyID;
use crate::properties::{
longhands::{
self, content_visibility::computed_value::T as ContentVisibility,
visibility::computed_value::T as Visibility,
self, visibility::computed_value::T as Visibility,
},
CSSWideKeyword, NonCustomPropertyId, LonghandId, NonCustomPropertyIterator,
CSSWideKeyword, LonghandId, NonCustomPropertyIterator,
PropertyDeclaration, PropertyDeclarationId,
};
#[cfg(feature = "gecko")] use crate::properties::{
longhands::content_visibility::computed_value::T as ContentVisibility,
NonCustomPropertyId,
};
use std::ptr;
use std::mem;
use fxhash::FxHashMap;
@ -605,6 +608,7 @@ impl ToAnimatedZero for Visibility {
}
/// <https://drafts.csswg.org/css-contain-3/#content-visibility-animation>
#[cfg(feature = "gecko")]
impl Animate for ContentVisibility {
#[inline]
fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
@ -626,6 +630,7 @@ impl Animate for ContentVisibility {
}
}
#[cfg(feature = "gecko")]
impl ComputeSquaredDistance for ContentVisibility {
#[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {
@ -633,6 +638,7 @@ impl ComputeSquaredDistance for ContentVisibility {
}
}
#[cfg(feature = "gecko")]
impl ToAnimatedZero for ContentVisibility {
#[inline]
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)]
pub mod gecko {
<%include file="/gecko.mako.rs" />
}
% endif
macro_rules! unwrap_or_initial {
@ -1615,12 +1616,14 @@ pub mod style_structs {
/// Returns whether there is any named progress timeline specified with
/// scroll-timeline-name other than `none`.
#[cfg(feature = "gecko")]
pub fn specifies_scroll_timelines(&self) -> bool {
self.scroll_timeline_name_iter().any(|name| !name.is_none())
}
/// Returns whether there is any named progress timeline specified with
/// view-timeline-name other than `none`.
#[cfg(feature = "gecko")]
pub fn specifies_view_timelines(&self) -> bool {
self.view_timeline_name_iter().any(|name| !name.is_none())
}

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

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

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

@ -24,7 +24,7 @@ use cssparser::{
AtRuleParser, BasicParseErrorKind, CowRcStr, DeclarationParser, ParseErrorKind, Parser,
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 servo_arc::Arc;
use std::fmt::{self, Write};

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

@ -7,12 +7,15 @@
use crate::computed_value_flags::ComputedValueFlags;
use crate::dom::TElement;
use crate::properties::longhands::contain::computed_value::T as Contain;
use crate::properties::longhands::container_type::computed_value::T as ContainerType;
use crate::properties::longhands::content_visibility::computed_value::T as ContentVisibility;
#[cfg(feature = "gecko")]
use crate::properties::longhands::{
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::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::{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
/// implies, but it should be safe. It matches blink, see
/// https://bugzilla.mozilla.org/show_bug.cgi?id=1786147#c10
#[cfg(feature = "gecko")]
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_::{DisplayInside, DisplayOutside};
@ -281,6 +285,7 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
.add_flags(ComputedValueFlags::IS_ROOT_ELEMENT_STYLE);
}
#[cfg(feature = "gecko")]
if box_style
.clone_effective_containment()
.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
/// at computed value time.
#[cfg(feature = "gecko")]
fn adjust_for_column_rule_width(&mut self) {
let column_style = self.style.get_column();
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) {
let box_style = self.style.get_box();
let container_type = box_style.clone_container_type();
@ -512,6 +519,7 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
/// an auto value
///
/// <https://github.com/w3c/csswg-drafts/issues/8407>
#[cfg(feature = "gecko")]
fn adjust_for_contain_intrinsic_size(&mut self) {
let content_visibility = self.style.get_box().clone_content_visibility();
if content_visibility != ContentVisibility::Auto {
@ -948,17 +956,19 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
}
self.adjust_for_top_layer();
self.blockify_if_necessary(layout_parent_style, element);
#[cfg(feature = "gecko")]
self.adjust_for_webkit_line_clamp();
self.adjust_for_position();
self.adjust_for_overflow();
self.adjust_for_contain();
self.adjust_for_contain_intrinsic_size();
#[cfg(feature = "gecko")]
{
self.adjust_for_contain();
self.adjust_for_contain_intrinsic_size();
self.adjust_for_table_text_align();
self.adjust_for_justify_items();
}
self.adjust_for_border_width();
#[cfg(feature = "gecko")]
self.adjust_for_column_rule_width();
self.adjust_for_outline_width();
self.adjust_for_writing_mode(layout_parent_style);

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

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

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

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

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

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

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

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

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

@ -224,16 +224,28 @@ impl SupportsCondition {
}
}
#[cfg(feature = "gecko")]
fn eval_font_format(kw: &FontFaceSourceFormatKeyword) -> bool {
use crate::gecko_bindings::bindings;
unsafe { bindings::Gecko_IsFontFormatSupported(*kw) }
}
#[cfg(feature = "gecko")]
fn eval_font_tech(flag: &FontFaceSourceTechFlags) -> bool {
use crate::gecko_bindings::bindings;
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
/// <https://drafts.csswg.org/css-conditional/#dom-css-supports-conditiontext-conditiontext>
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> {
fn clear(&mut self) {
self.0.clear();
@ -1829,6 +1830,7 @@ pub struct PageRuleMap {
pub rules: PrecomputedHashMap<Atom, SmallVec<[PageRuleData; 1]>>,
}
#[cfg(feature = "gecko")]
impl PageRuleMap {
#[inline]
fn clear(&mut self) {
@ -3156,6 +3158,7 @@ impl CascadeData {
order.inc();
}
}
#[cfg(feature = "gecko")]
self.extra_data.sort_by_layer(&self.layers);
self.animations
.sort_with(&self.layers, compare_keyframes_in_same_layer);
@ -3890,6 +3893,7 @@ impl CascadeData {
.push(ContainerConditionReference::none());
self.scope_conditions.clear();
self.scope_conditions.push(ScopeConditionReference::none());
#[cfg(feature = "gecko")]
self.extra_data.clear();
self.rules_source_order = 0;
self.num_selectors = 0;

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

@ -21,10 +21,11 @@ use crate::values::specified::font::{
use crate::values::specified::length::{FontBaseSize, LineHeightBase, NoCalcLength};
use crate::Atom;
use cssparser::{serialize_identifier, CssStringWriter, Parser};
#[cfg(feature = "gecko")]
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use num_traits::abs;
use num_traits::cast::AsPrimitive;
#[cfg(feature = "servo")]
use std::hash::{Hash, Hasher};
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, ToCss};
@ -338,7 +339,7 @@ impl ToResolvedValue for FontSize {
}
#[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.
#[repr(C)]
pub struct FontFamily {
@ -373,6 +374,7 @@ impl FontFamily {
}
/// Returns the font family for `-moz-bullet-font`.
#[cfg(feature = "gecko")]
pub(crate) fn moz_bullet() -> &'static Self {
static_font_family!(
MOZ_BULLET,
@ -386,6 +388,7 @@ impl FontFamily {
}
/// Returns a font family for a single system font.
#[cfg(feature = "gecko")]
pub fn for_system_font(name: &str) -> Self {
Self {
families: FontFamilyList {
@ -417,6 +420,7 @@ impl FontFamily {
generic_font_family!(MONOSPACE, Monospace);
generic_font_family!(CURSIVE, Cursive);
generic_font_family!(FANTASY, Fantasy);
#[cfg(feature = "gecko")]
generic_font_family!(MOZ_EMOJI, MozEmoji);
generic_font_family!(SYSTEM_UI, SystemUi);
@ -430,6 +434,7 @@ impl FontFamily {
GenericFontFamily::Monospace => &*MONOSPACE,
GenericFontFamily::Cursive => &*CURSIVE,
GenericFontFamily::Fantasy => &*FANTASY,
#[cfg(feature = "gecko")]
GenericFontFamily::MozEmoji => &*MOZ_EMOJI,
GenericFontFamily::SystemUi => &*SYSTEM_UI,
};
@ -441,7 +446,6 @@ impl FontFamily {
}
}
#[cfg(feature = "gecko")]
impl MallocSizeOf for FontFamily {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
use malloc_size_of::MallocUnconditionalSizeOf;
@ -488,6 +492,7 @@ pub struct FamilyName {
pub syntax: FontFamilyNameSyntax,
}
#[cfg(feature = "gecko")]
impl FamilyName {
fn is_known_icon_font_family(&self) -> bool {
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 {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
@ -615,8 +627,9 @@ impl GenericFontFamily {
/// the user. See bug 789788 and bug 1730098.
pub(crate) fn valid_for_user_font_prioritization(self) -> bool {
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,
}
}
@ -686,12 +699,22 @@ impl Parse for SingleFontFamily {
/// A list of font families.
#[derive(Clone, Debug, ToComputedValue, ToResolvedValue, ToShmem, PartialEq, Eq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[repr(C)]
pub struct FontFamilyList {
/// The actual list of font families specified.
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 {
/// Return iterator of 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.
/// 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.
#[cfg_attr(feature = "servo", allow(unused))]
pub(crate) fn prioritize_first_generic_or_prepend(&mut self, generic: GenericFontFamily) {
let mut index_of_first_generic = None;
let mut target_index = None;
@ -752,6 +776,7 @@ impl FontFamilyList {
}
/// Returns whether we need to prioritize user fonts.
#[cfg_attr(feature = "servo", allow(unused))]
pub(crate) fn needs_user_font_prioritization(&self) -> bool {
self.iter().next().map_or(true, |f| match f {
SingleFontFamily::Generic(f) => !f.valid_for_user_font_prioritization(),
@ -1337,21 +1362,33 @@ impl ToResolvedValue for LineHeight {
type ResolvedValue = Self;
fn to_resolved_value(self, context: &ResolvedContext) -> Self::ResolvedValue {
// Resolve <number> to an absolute <length> based on font size.
if matches!(self, Self::Normal | Self::MozBlockHeight) {
return self;
#[cfg(feature = "gecko")]
{
// 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]

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

@ -25,6 +25,7 @@
//! our expectations.
use super::{Context, Length, Percentage, ToComputedValue};
#[cfg(feature = "gecko")]
use crate::gecko_bindings::structs::GeckoFontMetrics;
use crate::values::animated::{Animate, Context as AnimatedContext, Procedure, ToAnimatedValue, ToAnimatedZero};
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
/// if provided to resolve font-relative dimensions.
#[cfg(feature = "gecko")]
pub fn to_computed_pixel_length_with_font_metrics(
&self,
get_font_metrics: Option<impl Fn() -> GeckoFontMetrics>,

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

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

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

@ -715,12 +715,16 @@ impl ToCss for KeyframesName {
return dest.write_str("none");
}
self.0.with_str(|s| {
if CustomIdent::is_valid(s, &["none"]) {
serialize_identifier(s, dest)
let mut serialize = |string: &_| {
if CustomIdent::is_valid(string, &["none"]) {
serialize_identifier(string, dest)
} 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.
use app_units::Au;
#[cfg(feature = "gecko")]
use crate::media_queries::Device;
use crate::properties::ComputedValues;
use crate::ArcSlice;
@ -18,9 +19,9 @@ mod counters;
use crate::values::computed::{self, Length};
/// Element-specific information needed to resolve property values.
#[cfg(feature = "gecko")]
pub struct ResolvedElementInfo<'a> {
/// Element we're resolving line-height against.
#[cfg(feature = "gecko")]
pub element: crate::gecko::wrapper::GeckoElement<'a>,
}
@ -30,8 +31,10 @@ pub struct Context<'a> {
pub style: &'a ComputedValues,
/// The device / document we're resolving style for. Useful to do font metrics stuff needed for
/// line-height.
#[cfg(feature = "gecko")]
pub device: &'a Device,
/// The element-specific information to resolve the value.
#[cfg(feature = "gecko")]
pub element_info: ResolvedElementInfo<'a>,
}

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

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

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

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

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

@ -576,8 +576,11 @@ impl Color {
/// Returns whether this color is allowed in forced-colors mode.
pub fn honored_in_forced_colors_mode(&self, allow_transparent: bool) -> bool {
match *self {
#[cfg(feature = "gecko")]
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::LightDark(ref ld) => {
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() => {
generics::ContentItem::MozAltContent
},
#[cfg(feature = "gecko")]
"-moz-label-content" if context.chrome_rules_enabled() => {
generics::ContentItem::MozLabelContent
},

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

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

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

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

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

@ -70,6 +70,7 @@ macro_rules! system_font_methods {
Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem,
)]
#[allow(missing_docs)]
#[cfg(feature = "gecko")]
pub enum SystemFont {
/// https://drafts.csswg.org/css-fonts/#valdef-font-caption
Caption,
@ -99,6 +100,26 @@ pub enum SystemFont {
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_SIZE_MULTIPLIER: f64 = 0.71;
@ -557,6 +578,7 @@ impl KeywordInfo {
/// text-zoom.
fn to_computed_value(&self, context: &Context) -> CSSPixelLength {
debug_assert_ne!(self.kw, FontSizeKeyword::None);
#[cfg(feature="gecko")]
debug_assert_ne!(self.kw, FontSizeKeyword::Math);
let base = context.maybe_zoom_text(self.kw.to_length(context).0);
base * self.factor + context.maybe_zoom_text(self.offset)

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

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

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

@ -9,6 +9,7 @@
use super::{AllowQuirks, Number, Percentage, ToComputedValue};
use crate::computed_value_flags::ComputedValueFlags;
use crate::font_metrics::{FontMetrics, FontMetricsOrientation};
#[cfg(feature = "gecko")]
use crate::gecko_bindings::structs::GeckoFontMetrics;
use crate::parser::{Parse, ParserContext};
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.
#[cfg(feature = "gecko")]
pub fn to_computed_pixel_length_with_font_metrics(
&self,
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
/// absolute or (if a font metrics getter is provided) font-relative units.
#[cfg(feature = "gecko")]
#[inline]
pub fn to_computed_pixel_length_with_font_metrics(
&self,
@ -1509,6 +1512,7 @@ impl Length {
}
/// 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(
&self,
get_font_metrics: Option<impl Fn() -> GeckoFontMetrics>,

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

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

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

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

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

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