layout: Add a FontMetricsProvider for resolving font-relative units (#31966)

The only font relative unit that Servo knows how to resolve currently is
`rem` (relative to the root font size). This is because Stylo cannot do
any font queries. This adds a mechanism to allow this, exposing the
ability to properly render `ex` units in Servo.

This change only allows resolving some font size relative units thoug,
as Servo doesn't collect all the FontMetrics it needs to resolve them
all. This capability will be added in followup changes.

Some new tests fail:
 - ex-unit-001.html: This test fails because Servo does not yet have
   support for setting the weight using @font-face rules on web fonts.
 - ex-unit-004.html: This test fails because Servo does not yet have
   support for setting the Unicode range of a web font using @font-face
   rules.
 - first-available-font-001.html: This test fails because the above
   two feature are missing.
This commit is contained in:
Martin Robinson 2024-04-04 14:35:15 +02:00 committed by GitHub
parent 24c3a2df1e
commit fe8b23d14a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
98 changed files with 208 additions and 232 deletions

26
Cargo.lock generated
View file

@ -1198,7 +1198,7 @@ dependencies = [
[[package]] [[package]]
name = "derive_common" name = "derive_common"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/servo/stylo?branch=2023-10-16#c22dd97c7a826c04a8fb18f99fde5921ec2eea82" source = "git+https://github.com/servo/stylo?branch=2023-10-16#273f49fc586a02ff7601725924d2e30f95cfd9d3"
dependencies = [ dependencies = [
"darling", "darling",
"proc-macro2", "proc-macro2",
@ -3448,7 +3448,7 @@ dependencies = [
[[package]] [[package]]
name = "malloc_size_of" name = "malloc_size_of"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/servo/stylo?branch=2023-10-16#c22dd97c7a826c04a8fb18f99fde5921ec2eea82" source = "git+https://github.com/servo/stylo?branch=2023-10-16#273f49fc586a02ff7601725924d2e30f95cfd9d3"
dependencies = [ dependencies = [
"accountable-refcell", "accountable-refcell",
"app_units", "app_units",
@ -5061,7 +5061,7 @@ dependencies = [
[[package]] [[package]]
name = "selectors" name = "selectors"
version = "0.24.0" version = "0.24.0"
source = "git+https://github.com/servo/stylo?branch=2023-10-16#c22dd97c7a826c04a8fb18f99fde5921ec2eea82" source = "git+https://github.com/servo/stylo?branch=2023-10-16#273f49fc586a02ff7601725924d2e30f95cfd9d3"
dependencies = [ dependencies = [
"bitflags 2.5.0", "bitflags 2.5.0",
"cssparser", "cssparser",
@ -5349,7 +5349,7 @@ dependencies = [
[[package]] [[package]]
name = "servo_arc" name = "servo_arc"
version = "0.2.0" version = "0.2.0"
source = "git+https://github.com/servo/stylo?branch=2023-10-16#c22dd97c7a826c04a8fb18f99fde5921ec2eea82" source = "git+https://github.com/servo/stylo?branch=2023-10-16#273f49fc586a02ff7601725924d2e30f95cfd9d3"
dependencies = [ dependencies = [
"nodrop", "nodrop",
"serde", "serde",
@ -5359,7 +5359,7 @@ dependencies = [
[[package]] [[package]]
name = "servo_atoms" name = "servo_atoms"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/servo/stylo?branch=2023-10-16#c22dd97c7a826c04a8fb18f99fde5921ec2eea82" source = "git+https://github.com/servo/stylo?branch=2023-10-16#273f49fc586a02ff7601725924d2e30f95cfd9d3"
dependencies = [ dependencies = [
"string_cache", "string_cache",
"string_cache_codegen", "string_cache_codegen",
@ -5557,7 +5557,7 @@ checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"
[[package]] [[package]]
name = "size_of_test" name = "size_of_test"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/servo/stylo?branch=2023-10-16#c22dd97c7a826c04a8fb18f99fde5921ec2eea82" source = "git+https://github.com/servo/stylo?branch=2023-10-16#273f49fc586a02ff7601725924d2e30f95cfd9d3"
dependencies = [ dependencies = [
"static_assertions", "static_assertions",
] ]
@ -5683,7 +5683,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]] [[package]]
name = "static_prefs" name = "static_prefs"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/servo/stylo?branch=2023-10-16#c22dd97c7a826c04a8fb18f99fde5921ec2eea82" source = "git+https://github.com/servo/stylo?branch=2023-10-16#273f49fc586a02ff7601725924d2e30f95cfd9d3"
[[package]] [[package]]
name = "strict-num" name = "strict-num"
@ -5720,7 +5720,7 @@ dependencies = [
[[package]] [[package]]
name = "style" name = "style"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/servo/stylo?branch=2023-10-16#c22dd97c7a826c04a8fb18f99fde5921ec2eea82" source = "git+https://github.com/servo/stylo?branch=2023-10-16#273f49fc586a02ff7601725924d2e30f95cfd9d3"
dependencies = [ dependencies = [
"app_units", "app_units",
"arrayvec", "arrayvec",
@ -5779,7 +5779,7 @@ dependencies = [
[[package]] [[package]]
name = "style_config" name = "style_config"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/servo/stylo?branch=2023-10-16#c22dd97c7a826c04a8fb18f99fde5921ec2eea82" source = "git+https://github.com/servo/stylo?branch=2023-10-16#273f49fc586a02ff7601725924d2e30f95cfd9d3"
dependencies = [ dependencies = [
"lazy_static", "lazy_static",
] ]
@ -5787,7 +5787,7 @@ dependencies = [
[[package]] [[package]]
name = "style_derive" name = "style_derive"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/servo/stylo?branch=2023-10-16#c22dd97c7a826c04a8fb18f99fde5921ec2eea82" source = "git+https://github.com/servo/stylo?branch=2023-10-16#273f49fc586a02ff7601725924d2e30f95cfd9d3"
dependencies = [ dependencies = [
"darling", "darling",
"derive_common", "derive_common",
@ -5818,7 +5818,7 @@ dependencies = [
[[package]] [[package]]
name = "style_traits" name = "style_traits"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/servo/stylo?branch=2023-10-16#c22dd97c7a826c04a8fb18f99fde5921ec2eea82" source = "git+https://github.com/servo/stylo?branch=2023-10-16#273f49fc586a02ff7601725924d2e30f95cfd9d3"
dependencies = [ dependencies = [
"app_units", "app_units",
"bitflags 2.5.0", "bitflags 2.5.0",
@ -6172,7 +6172,7 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]] [[package]]
name = "to_shmem" name = "to_shmem"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/servo/stylo?branch=2023-10-16#c22dd97c7a826c04a8fb18f99fde5921ec2eea82" source = "git+https://github.com/servo/stylo?branch=2023-10-16#273f49fc586a02ff7601725924d2e30f95cfd9d3"
dependencies = [ dependencies = [
"cssparser", "cssparser",
"servo_arc", "servo_arc",
@ -6185,7 +6185,7 @@ dependencies = [
[[package]] [[package]]
name = "to_shmem_derive" name = "to_shmem_derive"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/servo/stylo?branch=2023-10-16#c22dd97c7a826c04a8fb18f99fde5921ec2eea82" source = "git+https://github.com/servo/stylo?branch=2023-10-16#273f49fc586a02ff7601725924d2e30f95cfd9d3"
dependencies = [ dependencies = [
"darling", "darling",
"derive_common", "derive_common",

View file

@ -93,12 +93,20 @@ impl<S: FontSource> FontContext<S> {
/// Font groups are cached, so subsequent calls with the same `style` will return a reference /// Font groups are cached, so subsequent calls with the same `style` will return a reference
/// to an existing `FontGroup`. /// to an existing `FontGroup`.
pub fn font_group(&mut self, style: Arc<FontStyleStruct>) -> Rc<RefCell<FontGroup>> { pub fn font_group(&mut self, style: Arc<FontStyleStruct>) -> Rc<RefCell<FontGroup>> {
let font_size = style.font_size.computed_size().into();
self.font_group_with_size(style, font_size)
}
/// Like [`Self::font_group`], but overriding the size found in the [`FontStyleStruct`] with the given size
/// in pixels.
pub fn font_group_with_size(
&mut self,
style: Arc<FontStyleStruct>,
size: Au,
) -> Rc<RefCell<FontGroup>> {
self.expire_font_caches_if_necessary(); self.expire_font_caches_if_necessary();
let cache_key = FontGroupCacheKey { let cache_key = FontGroupCacheKey { size, style };
size: Au::from_f32_px(style.font_size.computed_size().px()),
style,
};
if let Some(font_group) = self.font_group_cache.get(&cache_key) { if let Some(font_group) = self.font_group_cache.get(&cache_key) {
return font_group.clone(); return font_group.clone();

View file

@ -12,7 +12,7 @@ use msg::constellation_msg::PipelineId;
use net_traits::image_cache::{ use net_traits::image_cache::{
ImageCache, ImageCacheResult, ImageOrMetadataAvailable, UsePlaceholder, ImageCache, ImageCacheResult, ImageOrMetadataAvailable, UsePlaceholder,
}; };
use parking_lot::RwLock; use parking_lot::{ReentrantMutex, RwLock};
use script_layout_interface::{PendingImage, PendingImageState}; use script_layout_interface::{PendingImage, PendingImageState};
use servo_url::{ImmutableOrigin, ServoUrl}; use servo_url::{ImmutableOrigin, ServoUrl};
use style::context::SharedStyleContext; use style::context::SharedStyleContext;
@ -20,6 +20,8 @@ use style::dom::OpaqueNode;
use crate::display_list::WebRenderImageInfo; use crate::display_list::WebRenderImageInfo;
thread_local!(static FONT_CONTEXT: RefCell<Option<FontContext<FontCacheThread>>> = RefCell::new(None));
pub struct LayoutContext<'a> { pub struct LayoutContext<'a> {
pub id: PipelineId, pub id: PipelineId,
pub use_rayon: bool, pub use_rayon: bool,
@ -28,8 +30,8 @@ pub struct LayoutContext<'a> {
/// Bits shared by the layout and style system. /// Bits shared by the layout and style system.
pub style_context: SharedStyleContext<'a>, pub style_context: SharedStyleContext<'a>,
/// Interface to the font cache thread. /// A FontContext to be used during layout.
pub font_cache_thread: Mutex<FontCacheThread>, pub font_cache_thread: Arc<ReentrantMutex<FontCacheThread>>,
/// Reference to the script thread image cache. /// Reference to the script thread image cache.
pub image_cache: Arc<dyn ImageCache>, pub image_cache: Arc<dyn ImageCache>,
@ -131,19 +133,27 @@ impl<'a> LayoutContext<'a> {
None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None, None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None,
} }
} }
pub fn with_font_context<F, R>(&self, callback: F) -> R
where
F: FnOnce(&mut FontContext<FontCacheThread>) -> R,
{
with_thread_local_font_context(&self.font_cache_thread, callback)
}
} }
pub(crate) type LayoutFontContext = FontContext<FontCacheThread>; pub fn with_thread_local_font_context<F, R>(
font_cache_thread: &ReentrantMutex<FontCacheThread>,
thread_local!(static FONT_CONTEXT: RefCell<Option<LayoutFontContext>> = RefCell::new(None)); callback: F,
) -> R
pub(crate) fn with_thread_local_font_context<F, R>(layout_context: &LayoutContext, f: F) -> R
where where
F: FnOnce(&mut LayoutFontContext) -> R, F: FnOnce(&mut FontContext<FontCacheThread>) -> R,
{ {
FONT_CONTEXT.with(|font_context| { FONT_CONTEXT.with(|font_context| {
f(font_context.borrow_mut().get_or_insert_with(|| { callback(
FontContext::new(layout_context.font_cache_thread.lock().unwrap().clone()) font_context
})) .borrow_mut()
.get_or_insert_with(|| FontContext::new(font_cache_thread.lock().clone())),
)
}) })
} }

View file

@ -1597,8 +1597,7 @@ impl InlineFormattingContext {
// It's unfortunate that it isn't possible to get this during IFC text processing, but in // It's unfortunate that it isn't possible to get this during IFC text processing, but in
// that situation the style of the containing block is unknown. // that situation the style of the containing block is unknown.
let default_font_metrics = let default_font_metrics = layout_context.with_font_context(|font_context| {
crate::context::with_thread_local_font_context(layout_context, |font_context| {
get_font_for_first_font_for_style(style, font_context) get_font_for_first_font_for_style(style, font_context)
.map(|font| font.borrow().metrics.clone()) .map(|font| font.borrow().metrics.clone())
}); });
@ -1725,7 +1724,7 @@ impl InlineFormattingContext {
// For the purposes of `text-transform: capitalize` the start of the IFC is a word boundary. // For the purposes of `text-transform: capitalize` the start of the IFC is a word boundary.
let mut on_word_boundary = true; let mut on_word_boundary = true;
crate::context::with_thread_local_font_context(layout_context, |font_context| { layout_context.with_font_context(|font_context| {
let mut linebreaker = None; let mut linebreaker = None;
self.foreach(|iter_item| match iter_item { self.foreach(|iter_item| match iter_item {
InlineFormattingContextIterItem::Item(InlineLevelBox::TextRun( InlineFormattingContextIterItem::Item(InlineLevelBox::TextRun(

View file

@ -92,6 +92,7 @@ use style::media_queries::{Device, MediaList, MediaType};
use style::properties::style_structs::Font; use style::properties::style_structs::Font;
use style::properties::PropertyId; use style::properties::PropertyId;
use style::selector_parser::{PseudoElement, SnapshotMap}; use style::selector_parser::{PseudoElement, SnapshotMap};
use style::servo::media_queries::FontMetricsProvider;
use style::servo::restyle_damage::ServoRestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage;
use style::shared_lock::{SharedRwLock, SharedRwLockReadGuard, StylesheetGuards}; use style::shared_lock::{SharedRwLock, SharedRwLockReadGuard, StylesheetGuards};
use style::stylesheets::{ use style::stylesheets::{
@ -263,6 +264,10 @@ impl Layout for LayoutThread {
self.handle_request(Request::FromFontCache); self.handle_request(Request::FromFontCache);
} }
fn device<'a>(&'a self) -> &'a Device {
self.stylist.device()
}
fn waiting_for_web_fonts_to_load(&self) -> bool { fn waiting_for_web_fonts_to_load(&self) -> bool {
self.outstanding_web_fonts.load(Ordering::SeqCst) != 0 self.outstanding_web_fonts.load(Ordering::SeqCst) != 0
} }
@ -506,6 +511,7 @@ impl LayoutThread {
QuirksMode::NoQuirks, QuirksMode::NoQuirks,
window_size.initial_viewport, window_size.initial_viewport,
window_size.device_pixel_ratio, window_size.device_pixel_ratio,
Box::new(LayoutFontMetricsProvider),
); );
// Ask the router to proxy IPC messages from the font cache thread to layout. // Ask the router to proxy IPC messages from the font cache thread to layout.
@ -1477,6 +1483,7 @@ impl LayoutThread {
self.stylist.quirks_mode(), self.stylist.quirks_mode(),
window_size_data.initial_viewport, window_size_data.initial_viewport,
window_size_data.device_pixel_ratio, window_size_data.device_pixel_ratio,
Box::new(LayoutFontMetricsProvider),
); );
// Preserve any previously computed root font size. // Preserve any previously computed root font size.
@ -1684,3 +1691,19 @@ impl RegisteredPainters for RegisteredPaintersImpl {
.map(|painter| painter as &dyn RegisteredPainter) .map(|painter| painter as &dyn RegisteredPainter)
} }
} }
#[derive(Debug)]
struct LayoutFontMetricsProvider;
impl FontMetricsProvider for LayoutFontMetricsProvider {
fn query_font_metrics(
&self,
_vertical: bool,
_font: &Font,
_base_size: style::values::computed::CSSPixelLength,
_in_media_query: bool,
_retrieve_math_scales: bool,
) -> style::font_metrics::FontMetrics {
Default::default()
}
}

View file

@ -42,7 +42,7 @@ use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use metrics::{PaintTimeMetrics, ProfilerMetadataFactory}; use metrics::{PaintTimeMetrics, ProfilerMetadataFactory};
use msg::constellation_msg::{BrowsingContextId, PipelineId}; use msg::constellation_msg::{BrowsingContextId, PipelineId};
use net_traits::image_cache::{ImageCache, UsePlaceholder}; use net_traits::image_cache::{ImageCache, UsePlaceholder};
use parking_lot::RwLock; use parking_lot::{ReentrantMutex, RwLock};
use profile_traits::mem::{Report, ReportKind, ReportsChan}; use profile_traits::mem::{Report, ReportKind, ReportsChan};
use profile_traits::path; use profile_traits::path;
use profile_traits::time::{ use profile_traits::time::{
@ -69,14 +69,15 @@ use style::context::{
QuirksMode, RegisteredSpeculativePainter, RegisteredSpeculativePainters, SharedStyleContext, QuirksMode, RegisteredSpeculativePainter, RegisteredSpeculativePainters, SharedStyleContext,
}; };
use style::dom::{OpaqueNode, TElement, TNode}; use style::dom::{OpaqueNode, TElement, TNode};
use style::driver;
use style::error_reporting::RustLogReporter; use style::error_reporting::RustLogReporter;
use style::font_metrics::FontMetrics;
use style::global_style_data::{GLOBAL_STYLE_DATA, STYLE_THREAD_POOL}; use style::global_style_data::{GLOBAL_STYLE_DATA, STYLE_THREAD_POOL};
use style::invalidation::element::restyle_hints::RestyleHint; use style::invalidation::element::restyle_hints::RestyleHint;
use style::media_queries::{Device, MediaList, MediaType}; use style::media_queries::{Device, MediaList, MediaType};
use style::properties::style_structs::Font; use style::properties::style_structs::Font;
use style::properties::PropertyId; use style::properties::PropertyId;
use style::selector_parser::{PseudoElement, SnapshotMap}; use style::selector_parser::{PseudoElement, SnapshotMap};
use style::servo::media_queries::FontMetricsProvider;
use style::shared_lock::{SharedRwLock, SharedRwLockReadGuard, StylesheetGuards}; use style::shared_lock::{SharedRwLock, SharedRwLockReadGuard, StylesheetGuards};
use style::stylesheets::{ use style::stylesheets::{
DocumentStyleSheet, Origin, Stylesheet, StylesheetInDocument, UrlExtraData, DocumentStyleSheet, Origin, Stylesheet, StylesheetInDocument, UrlExtraData,
@ -85,6 +86,8 @@ use style::stylesheets::{
use style::stylist::Stylist; use style::stylist::Stylist;
use style::traversal::DomTraversal; use style::traversal::DomTraversal;
use style::traversal_flags::TraversalFlags; use style::traversal_flags::TraversalFlags;
use style::values::computed::CSSPixelLength;
use style::{driver, Zero};
use style_traits::{CSSPixel, DevicePixel, SpeculativePainter}; use style_traits::{CSSPixel, DevicePixel, SpeculativePainter};
use url::Url; use url::Url;
use webrender_api::units::LayoutPixel; use webrender_api::units::LayoutPixel;
@ -119,8 +122,9 @@ pub struct LayoutThread {
/// Reference to the script thread image cache. /// Reference to the script thread image cache.
image_cache: Arc<dyn ImageCache>, image_cache: Arc<dyn ImageCache>,
/// Public interface to the font cache thread. /// Public interface to the font cache thread. This needs to be behind a [`ReentrantMutex`],
font_cache_thread: FontCacheThread, /// because some font cache operations can trigger others.
font_cache_thread: Arc<ReentrantMutex<FontCacheThread>>,
/// Is this the first reflow in this LayoutThread? /// Is this the first reflow in this LayoutThread?
first_reflow: Cell<bool>, first_reflow: Cell<bool>,
@ -236,6 +240,10 @@ impl Layout for LayoutThread {
self.handle_request(Request::FromFontCache); self.handle_request(Request::FromFontCache);
} }
fn device<'a>(&'a self) -> &'a Device {
self.stylist.device()
}
fn waiting_for_web_fonts_to_load(&self) -> bool { fn waiting_for_web_fonts_to_load(&self) -> bool {
self.outstanding_web_fonts.load(Ordering::SeqCst) != 0 self.outstanding_web_fonts.load(Ordering::SeqCst) != 0
} }
@ -448,11 +456,13 @@ impl LayoutThread {
// The device pixel ratio is incorrect (it does not have the hidpi value), // The device pixel ratio is incorrect (it does not have the hidpi value),
// but it will be set correctly when the initial reflow takes place. // but it will be set correctly when the initial reflow takes place.
let font_cache_thread = Arc::new(ReentrantMutex::new(font_cache_thread));
let device = Device::new( let device = Device::new(
MediaType::screen(), MediaType::screen(),
QuirksMode::NoQuirks, QuirksMode::NoQuirks,
window_size.initial_viewport, window_size.initial_viewport,
window_size.device_pixel_ratio, window_size.device_pixel_ratio,
Box::new(LayoutFontMetricsProvider(font_cache_thread.clone())),
); );
// Ask the router to proxy IPC messages from the font cache thread to layout. // Ask the router to proxy IPC messages from the font cache thread to layout.
@ -546,7 +556,7 @@ impl LayoutThread {
traversal_flags, traversal_flags,
), ),
image_cache: self.image_cache.clone(), image_cache: self.image_cache.clone(),
font_cache_thread: Mutex::new(self.font_cache_thread.clone()), font_cache_thread: self.font_cache_thread.clone(),
webrender_image_cache: self.webrender_image_cache.clone(), webrender_image_cache: self.webrender_image_cache.clone(),
pending_images: Mutex::new(vec![]), pending_images: Mutex::new(vec![]),
use_rayon, use_rayon,
@ -629,8 +639,10 @@ impl LayoutThread {
// Find all font-face rules and notify the font cache of them. // Find all font-face rules and notify the font cache of them.
// GWTODO: Need to handle unloading web fonts. // GWTODO: Need to handle unloading web fonts.
if stylesheet.is_effective_for_device(self.stylist.device(), &guard) { if stylesheet.is_effective_for_device(self.stylist.device(), &guard) {
let newly_loading_font_count = let newly_loading_font_count = self
self.font_cache_thread.add_all_web_fonts_from_stylesheet( .font_cache_thread
.lock()
.add_all_web_fonts_from_stylesheet(
&*stylesheet, &*stylesheet,
&guard, &guard,
self.stylist.device(), self.stylist.device(),
@ -1092,6 +1104,7 @@ impl LayoutThread {
self.stylist.quirks_mode(), self.stylist.quirks_mode(),
window_size_data.initial_viewport, window_size_data.initial_viewport,
window_size_data.device_pixel_ratio, window_size_data.device_pixel_ratio,
Box::new(LayoutFontMetricsProvider(self.font_cache_thread.clone())),
); );
// Preserve any previously computed root font size. // Preserve any previously computed root font size.
@ -1248,3 +1261,44 @@ impl RegisteredSpeculativePainters for RegisteredPaintersImpl {
.map(|painter| painter as &dyn RegisteredSpeculativePainter) .map(|painter| painter as &dyn RegisteredSpeculativePainter)
} }
} }
#[derive(Debug)]
struct LayoutFontMetricsProvider(Arc<ReentrantMutex<FontCacheThread>>);
impl FontMetricsProvider for LayoutFontMetricsProvider {
fn query_font_metrics(
&self,
_vertical: bool,
font: &Font,
base_size: CSSPixelLength,
_in_media_query: bool,
_retrieve_math_scales: bool,
) -> FontMetrics {
layout::context::with_thread_local_font_context(&self.0, move |font_context| {
let Some(servo_metrics) = font_context
.font_group_with_size(ServoArc::new(font.clone()), base_size.into())
.borrow_mut()
.first(font_context)
.map(|font| font.borrow().metrics.clone())
else {
return Default::default();
};
// Only use the x-height of this font if it is non-zero. Some fonts return
// inaccurate metrics, which shouldn't be used.
let x_height = Some(servo_metrics.x_height)
.filter(|x_height| !x_height.is_zero())
.map(CSSPixelLength::from);
FontMetrics {
x_height,
zero_advance_measure: None,
cap_height: None,
ic_width: None,
ascent: servo_metrics.ascent.into(),
script_percent_scale_down: None,
script_script_percent_scale_down: None,
}
})
}
}

View file

@ -58,7 +58,7 @@ use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
use style::attr::AttrValue; use style::attr::AttrValue;
use style::context::QuirksMode; use style::context::QuirksMode;
use style::invalidation::element::restyle_hints::RestyleHint; use style::invalidation::element::restyle_hints::RestyleHint;
use style::media_queries::{Device, MediaType}; use style::media_queries::Device;
use style::selector_parser::Snapshot; use style::selector_parser::Snapshot;
use style::shared_lock::SharedRwLock as StyleSharedRwLock; use style::shared_lock::SharedRwLock as StyleSharedRwLock;
use style::str::{split_html_space_chars, str_join}; use style::str::{split_html_space_chars, str_join};
@ -3476,20 +3476,14 @@ impl Document {
have_changed have_changed
} }
/// Returns a `Device` suitable for media query evaluation. /// Runs the given closure using the Stylo `Device` suitable for media query evaluation.
/// ///
/// FIXME(emilio): This really needs to be somehow more in sync with layout. /// TODO: This can just become a getter when each Layout is more strongly associated with
/// Feels like a hack. /// its given Document and Window.
pub fn device(&self) -> Device { pub fn with_device<T>(&self, call: impl FnOnce(&Device) -> T) -> T {
let window_size = self.window().window_size(); self.window
let viewport_size = window_size.initial_viewport; .with_layout(move |layout| call(layout.device()))
let device_pixel_ratio = window_size.device_pixel_ratio; .unwrap()
Device::new(
MediaType::screen(),
self.quirks_mode(),
viewport_size,
device_pixel_ratio,
)
} }
pub fn salvageable(&self) -> bool { pub fn salvageable(&self) -> bool {

View file

@ -669,10 +669,8 @@ impl HTMLImageElement {
_width: Option<Length>, _width: Option<Length>,
) -> Au { ) -> Au {
let document = document_from_node(self); let document = document_from_node(self);
let device = document.device();
let quirks_mode = document.quirks_mode(); let quirks_mode = document.quirks_mode();
//FIXME https://github.com/whatwg/html/issues/3832 document.with_device(move |device| source_size_list.evaluate(device, quirks_mode))
source_size_list.evaluate(&device, quirks_mode)
} }
/// <https://html.spec.whatwg.org/multipage/#matches-the-environment> /// <https://html.spec.whatwg.org/multipage/#matches-the-environment>
@ -698,7 +696,7 @@ impl HTMLImageElement {
let mut parserInput = ParserInput::new(&media_query); let mut parserInput = ParserInput::new(&media_query);
let mut parser = Parser::new(&mut parserInput); let mut parser = Parser::new(&mut parserInput);
let media_list = MediaList::parse(&context, &mut parser); let media_list = MediaList::parse(&context, &mut parser);
media_list.evaluate(&document.device(), quirks_mode) document.with_device(move |device| media_list.evaluate(device, quirks_mode))
} }
/// <https://html.spec.whatwg.org/multipage/#normalise-the-source-densities> /// <https://html.spec.whatwg.org/multipage/#normalise-the-source-densities>
@ -769,11 +767,14 @@ impl HTMLImageElement {
// Step 5 // Step 5
let mut best_candidate = max; let mut best_candidate = max;
let device = document_from_node(self).device(); let device_pixel_ratio = document_from_node(self)
let device_den = device.device_pixel_ratio().get() as f64; .window()
.window_size()
.device_pixel_ratio
.get() as f64;
for (index, image_source) in img_sources.iter().enumerate() { for (index, image_source) in img_sources.iter().enumerate() {
let current_den = image_source.descriptor.den.unwrap(); let current_den = image_source.descriptor.den.unwrap();
if current_den < best_candidate.0 && current_den >= device_den { if current_den < best_candidate.0 && current_den >= device_pixel_ratio {
best_candidate = (current_den, index); best_candidate = (current_den, index);
} }
} }

View file

@ -72,8 +72,9 @@ impl MediaQueryList {
} }
pub fn evaluate(&self) -> bool { pub fn evaluate(&self) -> bool {
self.media_query_list let quirks_mode = self.document.quirks_mode();
.evaluate(&self.document.device(), self.document.quirks_mode()) self.document
.with_device(move |device| self.media_query_list.evaluate(device, quirks_mode))
} }
} }

View file

@ -40,6 +40,7 @@ use servo_url::{ImmutableOrigin, ServoUrl};
use style::animation::DocumentAnimationSet; use style::animation::DocumentAnimationSet;
use style::data::ElementData; use style::data::ElementData;
use style::dom::OpaqueNode; use style::dom::OpaqueNode;
use style::media_queries::Device;
use style::properties::style_structs::Font; use style::properties::style_structs::Font;
use style::properties::PropertyId; use style::properties::PropertyId;
use style::selector_parser::PseudoElement; use style::selector_parser::PseudoElement;
@ -179,6 +180,10 @@ pub trait Layout {
/// Handle a a single mesasge from the FontCacheThread. /// Handle a a single mesasge from the FontCacheThread.
fn handle_font_cache_msg(&mut self); fn handle_font_cache_msg(&mut self);
/// Get a reference to this Layout's Stylo `Device` used to handle media queries and
/// resolve font metrics.
fn device<'a>(&'a self) -> &'a Device;
/// Whether or not this layout is waiting for fonts from loaded stylesheets to finish loading. /// Whether or not this layout is waiting for fonts from loaded stylesheets to finish loading.
fn waiting_for_web_fonts_to_load(&self) -> bool; fn waiting_for_web_fonts_to_load(&self) -> bool;

View file

@ -9,13 +9,33 @@ use style::context::QuirksMode;
use style::custom_properties::{ use style::custom_properties::{
ComputedCustomProperties, CustomPropertiesBuilder, Name, SpecifiedValue, ComputedCustomProperties, CustomPropertiesBuilder, Name, SpecifiedValue,
}; };
use style::font_metrics::FontMetrics;
use style::media_queries::{Device, MediaType}; use style::media_queries::{Device, MediaType};
use style::properties::style_structs::Font;
use style::properties::{CustomDeclaration, CustomDeclarationValue}; use style::properties::{CustomDeclaration, CustomDeclarationValue};
use style::rule_tree::CascadeLevel; use style::rule_tree::CascadeLevel;
use style::servo::media_queries::FontMetricsProvider;
use style::stylesheets::layer_rule::LayerOrder; use style::stylesheets::layer_rule::LayerOrder;
use style::stylist::Stylist; use style::stylist::Stylist;
use style::values::computed::Length;
use test::{self, Bencher}; use test::{self, Bencher};
#[derive(Debug)]
struct DummyMetricsProvider;
impl FontMetricsProvider for DummyMetricsProvider {
fn query_font_metrics(
&self,
_vertical: bool,
_font: &Font,
_base_size: Length,
_in_media_query: bool,
_retrieve_math_scales: bool,
) -> FontMetrics {
Default::default()
}
}
fn cascade( fn cascade(
name_and_value: &[(&str, &str)], name_and_value: &[(&str, &str)],
inherited: &ComputedCustomProperties, inherited: &ComputedCustomProperties,
@ -36,6 +56,7 @@ fn cascade(
QuirksMode::NoQuirks, QuirksMode::NoQuirks,
Size2D::new(800., 600.), Size2D::new(800., 600.),
Scale::new(1.0), Scale::new(1.0),
Box::new(DummyMetricsProvider),
); );
let stylist = Stylist::new(device, QuirksMode::NoQuirks); let stylist = Stylist::new(device, QuirksMode::NoQuirks);
let mut builder = CustomPropertiesBuilder::new(inherited, &stylist, false); let mut builder = CustomPropertiesBuilder::new(inherited, &stylist, false);

View file

@ -8,18 +8,38 @@ use selectors::parser::{AncestorHashes, Selector};
use servo_arc::Arc; use servo_arc::Arc;
use servo_atoms::Atom; use servo_atoms::Atom;
use style::context::QuirksMode; use style::context::QuirksMode;
use style::font_metrics::FontMetrics;
use style::media_queries::{Device, MediaType}; use style::media_queries::{Device, MediaType};
use style::properties::style_structs::Font;
use style::properties::{longhands, Importance, PropertyDeclaration, PropertyDeclarationBlock}; use style::properties::{longhands, Importance, PropertyDeclaration, PropertyDeclarationBlock};
use style::selector_map::SelectorMap; use style::selector_map::SelectorMap;
use style::selector_parser::{SelectorImpl, SelectorParser}; use style::selector_parser::{SelectorImpl, SelectorParser};
use style::servo::media_queries::FontMetricsProvider;
use style::shared_lock::SharedRwLock; use style::shared_lock::SharedRwLock;
use style::stylesheets::StyleRule; use style::stylesheets::StyleRule;
use style::stylist::{ use style::stylist::{
needs_revalidation_for_testing, ContainerConditionId, LayerId, Rule, Stylist, needs_revalidation_for_testing, ContainerConditionId, LayerId, Rule, Stylist,
}; };
use style::thread_state::{self, ThreadState}; use style::thread_state::{self, ThreadState};
use style::values::computed::Length;
use url::Url; use url::Url;
#[derive(Debug)]
struct DummyMetricsProvider;
impl FontMetricsProvider for DummyMetricsProvider {
fn query_font_metrics(
&self,
_vertical: bool,
_font: &Font,
_base_size: Length,
_in_media_query: bool,
_retrieve_math_scales: bool,
) -> FontMetrics {
Default::default()
}
}
/// Helper method to get some Rules from selector strings. /// Helper method to get some Rules from selector strings.
/// Each sublist of the result contains the Rules for one StyleRule. /// Each sublist of the result contains the Rules for one StyleRule.
fn get_mock_rules(css_selectors: &[&str]) -> (Vec<Vec<Rule>>, SharedRwLock) { fn get_mock_rules(css_selectors: &[&str]) -> (Vec<Vec<Rule>>, SharedRwLock) {
@ -223,6 +243,7 @@ fn mock_stylist() -> Stylist {
QuirksMode::NoQuirks, QuirksMode::NoQuirks,
Size2D::new(0f32, 0f32), Size2D::new(0f32, 0f32),
Scale::new(1.0), Scale::new(1.0),
Box::new(DummyMetricsProvider),
); );
Stylist::new(device, QuirksMode::NoQuirks) Stylist::new(device, QuirksMode::NoQuirks)
} }

View file

@ -1,2 +0,0 @@
[background-position-001.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[background-position-002.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[border-bottom-width-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[border-bottom-width-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[border-bottom-width-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[border-left-width-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[border-left-width-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[border-left-width-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[border-right-width-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[border-right-width-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[border-right-width-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[border-top-width-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[border-top-width-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[border-top-width-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[c526-font-sz-002.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[c541-word-sp-000.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[c542-letter-sp-000.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[c547-indent-000.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[c548-ln-ht-002.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[c61-ex-len-000.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[c61-rel-len-000.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[font-size-124.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[line-height-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[line-height-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[line-height-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[vertical-align-091.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[vertical-align-092.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[margin-bottom-091.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[margin-bottom-092.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[margin-left-091.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[margin-left-092.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[margin-right-091.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[margin-right-092.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[margin-top-091.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[margin-top-092.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[padding-bottom-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[padding-bottom-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[padding-bottom-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[padding-left-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[padding-left-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[padding-left-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[padding-right-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[padding-right-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[padding-right-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[padding-top-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[padding-top-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[padding-top-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[height-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[height-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[height-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[max-height-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[max-height-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[max-height-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[max-width-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[max-width-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[max-width-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[min-height-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[min-height-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[min-height-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[min-width-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[min-width-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[min-width-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[width-080.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[width-083.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[width-084.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[bottom-091.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[bottom-092.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[left-091.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[left-092.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[right-091.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[right-092.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[top-091.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[top-092.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[numbers-units-018.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[numbers-units-019.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[units-001.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[units-002.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[units-003.xht]
expected: FAIL

View file

@ -1,2 +0,0 @@
[units-004.xht]
expected: FAIL

View file

@ -0,0 +1,2 @@
[first-available-font-001.html]
expected: FAIL

View file

@ -1,3 +0,0 @@
[cap-invalidation.html]
[CSS Values and Units Test: cap invalidation]
expected: FAIL

View file

@ -1,2 +0,0 @@
[cap-unit-001.html]
expected: FAIL

View file

@ -0,0 +1,2 @@
[ex-unit-001.html]
expected: FAIL

View file

@ -1,2 +0,0 @@
[ex-unit-002.html]
expected: FAIL

View file

@ -1,2 +0,0 @@
[ex-unit-003.html]
expected: FAIL

View file

@ -0,0 +1,2 @@
[ex-unit-004.html]
expected: FAIL