Skip to content

Truly independent web browser

LibGfx+LibWeb: Load a web font when a length reads its metrics

sideshowbarker9ee393a54aec
diff --git a/Libraries/LibGfx/Rust/src/font.rs b/Libraries/LibGfx/Rust/src/font.rs
index 5565761915d..dad3fde82ef 100644
--- a/Libraries/LibGfx/Rust/src/font.rs
+++ b/Libraries/LibGfx/Rust/src/font.rs
@@ -1416,6 +1416,23 @@ impl FrozenFontList {
.map(|index| index as u32 | CACHED_FILLED_ENTRY)
}
+ /// https://drafts.csswg.org/css-values-4/#font-relative-lengths
+ /// Wants the loads of the faces still loading ahead of the first available font, as a length
+ /// relative to a metric of that font (ex, cap, ch, ic, lh) reads the first of them that covers
+ /// U+0020 once it loads. The document requests them once the pass ends, as it does those a
+ /// render pass wants.
+ pub fn want_first_available_font_loads(&self) {
+ const SPACE: u32 = 0x20;
+ for entry in self.entries.iter().filter(|entry| entry.covers(SPACE, &self.ranges)) {
+ if entry.font().is_some() {
+ return;
+ }
+ if let Some((face_id, _)) = entry.pending() {
+ self.note_wanted_pending_face(entry, face_id);
+ }
+ }
+ }
+
fn note_wanted_pending_face(&self, entry: &FrozenEntry, face_id: u64) {
if entry.wanted.swap(true, std::sync::atomic::Ordering::Relaxed) {
return;
diff --git a/Libraries/LibWeb/CSS/FontComputer.cpp b/Libraries/LibWeb/CSS/FontComputer.cpp
index 45ea285c3bc..90c13e20400 100644
--- a/Libraries/LibWeb/CSS/FontComputer.cpp
+++ b/Libraries/LibWeb/CSS/FontComputer.cpp
@@ -438,7 +438,6 @@ void FontComputer::invalidate_changed_font_cascades(Vector<Utf16FlyString> const
fill_loaded_font_faces(move(loaded_face_fills));
if (!invalidated_font_lists.is_empty() && m_document)
record_font_input_changes({}, invalidated_font_lists);
- request_wanted_web_faces();
}
// Has the style engine record an input change for every element whose style uses a font that resolves differently
diff --git a/Libraries/LibWeb/CSS/FontFace.cpp b/Libraries/LibWeb/CSS/FontFace.cpp
index 17b0a756cbf..12e391c7723 100644
--- a/Libraries/LibWeb/CSS/FontFace.cpp
+++ b/Libraries/LibWeb/CSS/FontFace.cpp
@@ -9,7 +9,6 @@
#include <AK/ByteBuffer.h>
#include <AK/Diagnostics.h>
#include <AK/Mutex.h>
-#include <AK/NeverDestroyed.h>
#include <AK/ScopeGuard.h>
#include <LibCore/Promise.h>
#include <LibGC/Heap.h>
@@ -434,85 +433,6 @@ RefPtr<FontFaceState> FontFaceState::with_id(u64 id)
return font_faces_by_id().get(id).value_or(nullptr);
}
-// The faces the style computations selected, which the main thread loads. A computation notes them on whichever
-// thread it runs, a frame in flight's included, so the list is shared under a lock. Every style update ends by taking
-// them, and almost always finds none, so whether there are any is read without the lock.
-class WantedWebFaces {
- AK_ALLOC_WITH_KMALLOC;
-
-public:
- void note(u64 face_id)
- {
- MutexLocker locker(m_mutex);
- if (!m_face_ids.contains_slow(face_id))
- m_face_ids.append(face_id);
- m_any.store(true, AK::memory_order_release);
- }
-
- Vector<u64> take()
- {
- if (!m_any.load(AK::memory_order_acquire))
- return {};
- MutexLocker locker(m_mutex);
- m_any.store(false, AK::memory_order_relaxed);
- return exchange(m_face_ids, {});
- }
-
-private:
- Mutex m_mutex;
- Vector<u64> m_face_ids;
- Atomic<bool> m_any { false };
-};
-
-static WantedWebFaces& wanted_web_faces()
-{
- // NB: A thread without a VM is a stage thread, which only ever works for the window agent. The faces of a worker are
- // noted and taken on its own thread.
- if (JS::VM::exists_on_this_thread() && !HTML::surrounding_agent().is_similar_origin_window_agent()) {
- // NB: Free what this thread kept when it exits.
-#ifdef AK_COMPILER_CLANG
- AK_IGNORE_DIAGNOSTIC("-Wexit-time-destructors", static thread_local WantedWebFaces wanted_by_worker)
-#else
- static thread_local WantedWebFaces wanted_by_worker;
-#endif
- return wanted_by_worker;
- }
- static NeverDestroyed<WantedWebFaces> wanted;
- return *wanted;
-}
-
-static thread_local u32 s_deferred_web_face_load_depth { 0 };
-
-void note_wanted_web_face(u64 face_id)
-{
- wanted_web_faces().note(face_id);
-}
-
-void request_wanted_web_faces()
-{
- if (s_deferred_web_face_load_depth != 0)
- return;
- // NB: A face that loads at once invalidates the selections that wanted it, and selecting again can want more.
- for (auto face_ids = wanted_web_faces().take(); !face_ids.is_empty(); face_ids = wanted_web_faces().take()) {
- for (auto face_id : face_ids) {
- if (auto face = FontFaceState::with_id(face_id))
- face->load_for_style();
- }
- }
-}
-
-void begin_deferred_web_face_loads()
-{
- ++s_deferred_web_face_load_depth;
-}
-
-void end_deferred_web_face_loads()
-{
- VERIFY(s_deferred_web_face_load_depth > 0);
- --s_deferred_web_face_load_depth;
- request_wanted_web_faces();
-}
-
bool FontFaceState::should_be_registered_with_font_computer() const
{
return is_css_connected() || has_urls() || status() == FontFaceLoadStatus::Loaded;
diff --git a/Libraries/LibWeb/CSS/FontFaceState.h b/Libraries/LibWeb/CSS/FontFaceState.h
index 3fcfe46465d..b4c2ca08101 100644
--- a/Libraries/LibWeb/CSS/FontFaceState.h
+++ b/Libraries/LibWeb/CSS/FontFaceState.h
@@ -189,16 +189,4 @@ private:
bool font_format_is_supported(Utf16View name);
-// Record that a style update wanted a web face loaded, on any thread. Loading a face changes its status, appends it to
-// every FontFaceSet it is in - under an execution context that runs author callbacks - and starts a fetch, none of
-// which may happen while a style update runs, nor anywhere but the main thread.
-void note_wanted_web_face(u64 face_id);
-
-// Load every face wanted since the last call, unless a style update is running: that one drains them at its end.
-void request_wanted_web_faces();
-
-// A style update defers every load its cascades want to its own end.
-void begin_deferred_web_face_loads();
-void end_deferred_web_face_loads();
-
}
diff --git a/Libraries/LibWeb/CSS/FontResolution.cpp b/Libraries/LibWeb/CSS/FontResolution.cpp
index b96e3899476..d2a66b9f39f 100644
--- a/Libraries/LibWeb/CSS/FontResolution.cpp
+++ b/Libraries/LibWeb/CSS/FontResolution.cpp
@@ -191,16 +191,6 @@ struct MatchingFontCandidate {
auto clamped_variations = variations_clamped_to_weight_descriptor(variations, weight_axis_follows_font_weight, key.weight);
auto font_list = Gfx::FontCascadeList::create();
for (auto const& face : *faces) {
- // https://drafts.csswg.org/css-font-loading/#font-face-load
- // User agents can initiate font loads on their own, whenever they determine that a given font face is
- // necessary to render something on the page. When this happens, they must act as if they had called the
- // corresponding FontFace’s load() method described here.
- // NB: An unloaded face with no subsetting unicode-range starts loading once a style actually selects
- // it. Loading happens via FontFace::load(), which mutates the face, its FontFaceSets and the
- // document, so this only leaves the face's number behind; request_wanted_web_faces() loads it
- // afterwards, and does nothing for a face past "unloaded" already.
- if (face.has_urls && !face.has_non_default_unicode_range)
- note_wanted_web_face(face.id);
if (auto face_fonts = font_for_face(face, key, size, variations_for_face(face, variations, clamped_variations), shape_features, synthesis_request)) {
font_list->extend(*face_fonts);
continue;
@@ -626,10 +616,7 @@ NonnullRefPtr<Gfx::FontCascadeList const> resolve_font_for_style_values(FontComp
// all scopes.
if (!key.feature_values[to_underlying(FontResolutionFeatureInput::FontVariantAlternates)])
key.font_feature_values_scope = {};
- auto font_list = font_computer.font_cascade_memo().resolve(font_computer.font_face_snapshot(), key, font_computer.font_feature_values_provider(key.font_feature_values_scope));
- // Inside a style update the loads wait for its end; everywhere else, such as canvas, they happen right here.
- request_wanted_web_faces();
- return font_list;
+ return font_computer.font_cascade_memo().resolve(font_computer.font_face_snapshot(), key, font_computer.font_feature_values_provider(key.font_feature_values_scope));
}
NonnullRefPtr<Gfx::FontCascadeList const> FontCascadeMemo::resolve(FontFaceSnapshot const& snapshot, ComputedFontCacheKey const& key, FontFeatureValuesProvider const& font_feature_values_for_family) const
diff --git a/Libraries/LibWeb/CSS/FontResolution.h b/Libraries/LibWeb/CSS/FontResolution.h
index c49a803dba1..deee6d4d25e 100644
--- a/Libraries/LibWeb/CSS/FontResolution.h
+++ b/Libraries/LibWeb/CSS/FontResolution.h
@@ -52,8 +52,8 @@ namespace Web::CSS {
// The @font-feature-values a resolution reads for a family, in the tree scope the request comes from.
using FontFeatureValuesProvider = Function<FontFeatureValues const&(Utf16FlyString const&)>;
-// Resolve a font cascade from the @font-face snapshot and the process-wide font services alone. It cannot start a
-// load: a web face it selects is only noted, and request_wanted_web_faces() loads it.
+// Resolve a font cascade from the @font-face snapshot and the process-wide font services alone. It starts no load: a web
+// face it selects waits in the cascade until a rendered code point or a font-relative length wants it.
[[nodiscard]] NonnullRefPtr<Gfx::FontCascadeList const> resolve_font_cascade(FontFaceSnapshot const&, ComputedFontCacheKey const&, FontFeatureValuesProvider const&);
// The font-family list as font matching wants it: generic families kept apart from names, and a name's syntax kept.
diff --git a/Libraries/LibWeb/CSS/StyleComputer.cpp b/Libraries/LibWeb/CSS/StyleComputer.cpp
index 98216b644a2..12967e5edb9 100644
--- a/Libraries/LibWeb/CSS/StyleComputer.cpp
+++ b/Libraries/LibWeb/CSS/StyleComputer.cpp
@@ -128,15 +128,11 @@ StyleComputer::StyleComputer(DOM::Document& document)
void StyleComputer::begin_style_update() const
{
++m_style_update_depth;
- begin_deferred_web_face_loads();
}
void StyleComputer::end_style_update() const
{
VERIFY(m_style_update_depth > 0);
- // Loading a web face a style selected runs author callbacks and starts a fetch, so it waits for the outermost
- // update to finish.
- ScopeGuard load_deferred_web_faces = [] { end_deferred_web_face_loads(); };
if (--m_style_update_depth != 0)
return;
m_style_update_ffi_media_environment.clear();
diff --git a/Libraries/LibWeb/Rust/src/css/animation.rs b/Libraries/LibWeb/Rust/src/css/animation.rs
index a90dec2b5c1..aa7ec6e10ec 100644
--- a/Libraries/LibWeb/Rust/src/css/animation.rs
+++ b/Libraries/LibWeb/Rust/src/css/animation.rs
@@ -695,6 +695,7 @@ fn resolve_animation_declarations(
let mut uses_tree_counting_function = false;
let mut container_relative_length_unit_mask = 0;
+ let mut font_metric_reads = FontMetricReads::default();
let mut needs_document_base_url = false;
let mut random_sharing_sources = Vec::new();
for property in &properties {
@@ -714,6 +715,21 @@ fn resolve_animation_declarations(
let dependencies = crate::css::style_compute::external_value_dependencies(value);
uses_tree_counting_function |= dependencies.uses_tree_counting_function;
container_relative_length_unit_mask |= dependencies.container_relative_length_unit_mask;
+ // NB: A font-size reads the parent's font, and an `lh` in a line-height the parent's line height, which a
+ // `normal` one takes from the parent's font. Any other length reads the element's own font.
+ if dependencies.font_metric_relative_length {
+ match property.physical_property_id {
+ crate::css::property_metadata::property_id::FONT_SIZE => font_metric_reads.parent = true,
+ crate::css::property_metadata::property_id::LINE_HEIGHT => {
+ let (line_height_reads, glyph_metric_reads) =
+ crate::css::style_compute::font_metric_length_reads(value);
+ font_metric_reads.parent |= line_height_reads;
+ font_metric_reads.own |= glyph_metric_reads;
+ }
+ _ => font_metric_reads.own = true,
+ }
+ }
+ font_metric_reads.root |= dependencies.root_font_reads == crate::css::style_compute::RootFontReads::Metrics;
needs_document_base_url |= dependencies.needs_document_base_url;
if dependencies.has_unfixed_random_sharing {
crate::css::style_compute::collect_unfixed_random_sharings_in_value(value, &mut random_sharing_sources);
@@ -740,12 +756,22 @@ fn resolve_animation_declarations(
value_plans,
uses_tree_counting_function,
container_relative_length_unit_mask,
+ font_metric_reads,
needs_document_base_url,
unfixed_random_sharings,
..ResolvedAnimationDeclarations::default()
}
}
+/// Which first available fonts the keyframe values of an element's effects resolve lengths against
+/// a metric of: the element's own, its parent's for its font-size, or the document element's.
+#[derive(Clone, Copy, Default)]
+pub(crate) struct FontMetricReads {
+ pub(crate) own: bool,
+ pub(crate) parent: bool,
+ pub(crate) root: bool,
+}
+
/// The declarations of the effects an element samples, resolved into what the animation core
/// interpolates.
#[derive(Default)]
@@ -757,6 +783,7 @@ pub(crate) struct ResolvedAnimationDeclarations {
value_plans: Vec<AnimationValuePlan>,
pub(crate) uses_tree_counting_function: bool,
pub(crate) container_relative_length_unit_mask: u8,
+ pub(crate) font_metric_reads: FontMetricReads,
pub(crate) needs_document_base_url: bool,
pub(crate) unfixed_random_sharings: Vec<AnimationUnfixedRandomSharing>,
}
@@ -8706,13 +8733,17 @@ impl AnimatedCustomProperties {
/// The computed value of one resolved custom-property declaration: the value its source names,
/// computed against a registration's syntax in the element's computation context, which is
- /// what gives a registered name its typed interpolation, and as written otherwise.
+ /// what gives a registered name its typed interpolation, and as written otherwise. And what
+ /// computing it read of that context.
pub(crate) fn computed_value(
&self,
registry: &Registry,
property: &ResolvedAnimationProperty,
finalization: &crate::css::custom_properties::CustomPropertyFinalization<'_>,
- ) -> RetainedStyleValueData {
+ ) -> (
+ RetainedStyleValueData,
+ crate::css::custom_properties::RegisteredValueReads,
+ ) {
let name_id = property.custom_name_id;
let value = match property.value_source {
FfiAnimationSpecifiedValueSource::Inherited => self.inherited_value(registry, name_id),
@@ -8721,7 +8752,7 @@ impl AnimatedCustomProperties {
FfiAnimationSpecifiedValueSource::Value => property.value.clone(),
};
if !registry.name_has_syntax(self.units(name_id)) {
- return value;
+ return (value, Default::default());
}
// SAFETY: The sample keeps the name alive while it is retained for the lookup.
let name = unsafe { ak::Utf16FlyString::from_raw_borrowed(self.name(name_id).raw()) };
@@ -8733,7 +8764,7 @@ impl AnimatedCustomProperties {
CustomPropertyValueToFinalize::StyleValue(value),
finalization,
)
- .map_or_else(|fallback| fallback, |(value, _)| value)
+ .unwrap_or_else(|fallback| (fallback, Default::default()))
}
}
@@ -9197,6 +9228,7 @@ pub(crate) fn resolve_published_animation_declarations(
.as_ref()
.is_some_and(|dependencies| dependencies.sibling_position);
resolved._base_urls = base_urls;
+ engine.want_first_available_font_loads_for(node, pseudo, resolved.font_metric_reads);
PublishedAnimationDeclarations {
resolved: Box::new(resolved),
custom_properties,
diff --git a/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs
index 6e653e20f26..92d86bd0cb9 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs
@@ -1575,6 +1575,54 @@ pub struct FfiQueryHandle {
}
impl FfiQueryHandle {
+ /// Which first available fonts a container query's size features hold lengths relative to a
+ /// metric of: the container's, through an `ex`, `cap`, `ch` or `lh`, and the document element's,
+ /// through their root-relative forms.
+ pub(crate) fn container_query_font_metric_reads(&self) -> crate::css::animation::FontMetricReads {
+ // NB: A length can sit inside a value of any type a feature takes, a calculated ratio's, e.g.
+ fn read_value(value: &QueryFeatureValue, reads: &mut crate::css::animation::FontMetricReads) {
+ for kind in [
+ FeatureValueParse::Integer,
+ FeatureValueParse::Length,
+ FeatureValueParse::Number,
+ FeatureValueParse::Ratio,
+ FeatureValueParse::Resolution,
+ ] {
+ if let Some(value) = value.parsed_in(kind, FeatureValueQuery::ContainerSize) {
+ let dependencies = crate::css::style_compute::collect_external_value_dependencies(value);
+ reads.own |= dependencies.font_metric_relative_length;
+ reads.root |= dependencies.root_font_reads == crate::css::style_compute::RootFontReads::Metrics;
+ }
+ }
+ }
+ fn read(expression: &Expression, reads: &mut crate::css::animation::FontMetricReads) {
+ match expression {
+ Expression::Not(child)
+ | Expression::InParens(child)
+ | Expression::StyleFunction(child)
+ | Expression::ScrollStateFunction(child) => read(child, reads),
+ Expression::And(children) | Expression::Or(children) => {
+ children.iter().for_each(|child| read(child, reads));
+ }
+ Expression::QueryFeature(QueryFeature::Plain { value, .. }) => read_value(value, reads),
+ Expression::QueryFeature(QueryFeature::Range { left, right, .. }) => {
+ if let Some(left) = left {
+ read_value(&left.0, reads);
+ }
+ if let Some(right) = right {
+ read_value(&right.1, reads);
+ }
+ }
+ _ => {}
+ }
+ }
+ let mut reads = crate::css::animation::FontMetricReads::default();
+ if let QueryTree::Expression { expression, .. } = &self.tree {
+ read(expression, &mut reads);
+ }
+ reads
+ }
+
pub(crate) fn container_requirements(&self) -> u8 {
let QueryTree::Expression {
expression,
diff --git a/Libraries/LibWeb/Rust/src/css/style/container_queries.rs b/Libraries/LibWeb/Rust/src/css/style/container_queries.rs
index aa1dbb2990f..82728a53812 100644
--- a/Libraries/LibWeb/Rust/src/css/style/container_queries.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/container_queries.rs
@@ -523,6 +523,31 @@ impl RetainedState {
let snapshot = self.layout_style_snapshot(candidate).unwrap_or_default();
let document = &self.document_style_computation_inputs;
let view = records.record_view(candidate, inputs)?;
+ // https://drafts.csswg.org/css-values-4/#font-relative-lengths
+ // NB: A length in the query relative to a metric of the container's first available font reads that font,
+ // so the faces still loading ahead of it start loading, as they do for a length in a style.
+ let font_metric_reads = query.container_query_font_metric_reads();
+ if font_metric_reads.own {
+ // SAFETY: The view's font group is live while the query is evaluated.
+ let font = unsafe {
+ view.payloads[crate::css::table_group_builder::group_index::FONT]
+ .cast::<crate::css::computed_value_types::FontValues>()
+ .as_ref()
+ };
+ if let Some(list) = font.and_then(|font| font.frozen_font_list.list()) {
+ list.want_first_available_font_loads();
+ }
+ }
+ if font_metric_reads.root {
+ self.want_first_available_font_loads_for(
+ candidate,
+ None,
+ crate::css::animation::FontMetricReads {
+ root: true,
+ ..Default::default()
+ },
+ );
+ }
let mut length = self.record_length_resolution_context(view.payloads, view.dependency_flags)?;
if let Some(root_font) = records.root_font() {
(
diff --git a/Libraries/LibWeb/Rust/src/css/style/inputs.rs b/Libraries/LibWeb/Rust/src/css/style/inputs.rs
index 7c793f923eb..95d00f8b5fe 100644
--- a/Libraries/LibWeb/Rust/src/css/style/inputs.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/inputs.rs
@@ -596,6 +596,47 @@ impl RetainedState {
self.projection.construction_facts(node)
}
+ /// https://drafts.csswg.org/css-values-4/#font-relative-lengths
+ /// Wants the loads of the faces still loading ahead of the first available fonts that `reads`
+ /// names for `node`, or for its pseudo-element `pseudo`, as the lengths that read their metrics
+ /// would once they load: the element's or pseudo-element's own, its parent's, and the document
+ /// element's.
+ pub(crate) fn want_first_available_font_loads_for(
+ &self,
+ node: StyleNodeID,
+ pseudo: Option<u8>,
+ reads: crate::css::animation::FontMetricReads,
+ ) {
+ let want = |record: Option<u64>| {
+ let font = record
+ .and_then(|record| self.published_record_view(record))
+ .map(|view| view.font());
+ if let Some(list) = font.and_then(|font| font.frozen_font_list.list()) {
+ list.want_first_available_font_loads();
+ }
+ };
+ let element_record =
+ |node: Option<StyleNodeID>| node.and_then(|node| self.element_published_style_record(node));
+ if reads.own {
+ want(match pseudo {
+ Some(kind) => self.published_pseudo_record(node, kind).map(|record| record.raw()),
+ None => element_record(Some(node)),
+ });
+ }
+ // NB: A pseudo-element inherits from its originating element.
+ if reads.parent {
+ want(element_record(match pseudo {
+ Some(_) => Some(node),
+ None => self.inheritance_parent(node),
+ }));
+ }
+ if reads.root {
+ want(element_record(
+ std::iter::successors(Some(node), |&ancestor| self.inheritance_parent(ancestor)).last(),
+ ));
+ }
+ }
+
/// The record the element published, which its box is built from: the one a clock frame shows in its place, the
/// record the element holds, or the one the engine assigned it before it holds one. `None` while the element has
/// no record: a text node, a retired identity, or an element style has not reached yet.
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs
index a9054a3d7e7..35cdb3ef0af 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs
@@ -579,6 +579,7 @@ impl RetainedState {
let dependencies = winner_store::unpack_dependencies(dependencies);
decided.reads.reads_root_font = dependencies.root_font_reads;
decided.reads.reads_font_metric_lengths = dependencies.font_metric_relative_length;
+ decided.reads.reads_own_font_metric_lengths = dependencies.font_metric_relative_length;
decided.reads.environment_reads |= dependency_environment_reads(dependencies);
}
let is_plain = plain_dependencies.is_some();
@@ -616,6 +617,8 @@ impl RetainedState {
reads_sibling_position,
reads_root_font,
reads_font_metric_lengths,
+ reads_own_font_metric_lengths,
+ reads_parent_font_metric_lengths,
mut environment_reads,
substitution_reads,
custom_property_reads,
@@ -1215,6 +1218,49 @@ impl RetainedState {
group_cache.insert(lookup, payloads[lookup.group]);
}
drop(assembled);
+ // https://drafts.csswg.org/css-values-4/#font-relative-lengths
+ // NB: A length relative to a metric of a first available font reads that font, so the faces still loading ahead
+ // of it start loading, as a rendered code point starts the load of the face it falls in. A font-size reads
+ // the parent's font, a root-relative length the document element's, and any other length the element's own.
+ let want_first_available_font_loads = |font: &crate::css::computed_value_types::FontValues| {
+ if let Some(list) = font.frozen_font_list.list() {
+ list.want_first_available_font_loads();
+ }
+ };
+ // SAFETY: The payloads and views hold live font groups.
+ let own_font = || unsafe {
+ payloads[group_index::FONT]
+ .cast::<crate::css::computed_value_types::FontValues>()
+ .as_ref()
+ };
+ let view_font = |view: &computed::StyleRecordView<'_>| unsafe {
+ view.payloads[group_index::FONT]
+ .cast::<crate::css::computed_value_types::FontValues>()
+ .deref()
+ };
+ if reads_own_font_metric_lengths && let Some(font) = own_font() {
+ want_first_available_font_loads(font);
+ }
+ if reads_parent_font_metric_lengths && let Some(parent_view) = &parent_view {
+ want_first_available_font_loads(view_font(parent_view));
+ }
+ if reads_root_font == RootFontReads::Metrics {
+ match &parent_view {
+ None => {
+ if let Some(font) = own_font() {
+ want_first_available_font_loads(font);
+ }
+ }
+ Some(_) => {
+ let document_element =
+ std::iter::successors(Some(node), |&ancestor| self.projection.inheritance_parent(ancestor))
+ .last();
+ if let Some(root_view) = document_element.and_then(|root| records.assigned_record_view(root)) {
+ want_first_available_font_loads(view_font(&root_view));
+ }
+ }
+ }
+ }
let style_bits = values.style_bits();
let value_facts = values.into_facts();
Some(ComputedElement {
@@ -2383,6 +2429,12 @@ struct ElementWinnerReads {
reads_root_font: RootFontReads,
/// Whether a winner resolves a length against a metric of a first available font.
reads_font_metric_lengths: bool,
+ /// Whether a winner other than font-size resolves a length against a metric of the element's
+ /// own first available font.
+ reads_own_font_metric_lengths: bool,
+ /// Whether the winner for font-size resolves a length against a metric of the parent's first
+ /// available font.
+ reads_parent_font_metric_lengths: bool,
/// What the winners compute from of the document's environment.
environment_reads: StyleEnvironment,
/// What the winners' substitutions read beyond the element's custom properties.
@@ -2462,6 +2514,19 @@ impl<'a> DecidedWinners<'_, 'a> {
self.reads.reads_sibling_position |= reads.sibling_position;
self.reads.reads_root_font = self.reads.reads_root_font.max(reads.root_font);
self.reads.reads_font_metric_lengths |= reads.font_metrics;
+ // NB: A font-size reads the parent's font, and an `lh` in a line-height the parent's line height, which a
+ // `normal` one takes from the parent's font. Any other length reads the element's own font.
+ if reads.font_metrics {
+ let is_font_size = property == crate::css::property_metadata::property_id::FONT_SIZE;
+ let (line_height_reads, glyph_metric_reads) =
+ if property == crate::css::property_metadata::property_id::LINE_HEIGHT {
+ crate::css::style_compute::font_metric_length_reads(value.value().data())
+ } else {
+ (false, true)
+ };
+ self.reads.reads_own_font_metric_lengths |= !is_font_size && glyph_metric_reads;
+ self.reads.reads_parent_font_metric_lengths |= is_font_size || line_height_reads;
+ }
self.reads.environment_reads |= reads.environment | property_environment_reads(property);
let written = value.value();
// https://drafts.csswg.org/css-cascade-5/#defaulting-keywords
diff --git a/Libraries/LibWeb/Rust/src/css/style_compute.rs b/Libraries/LibWeb/Rust/src/css/style_compute.rs
index 45933ce1293..b6ac0e0b094 100644
--- a/Libraries/LibWeb/Rust/src/css/style_compute.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_compute.rs
@@ -1203,6 +1203,37 @@ pub(crate) fn viewport_length_unit_axes(unit: u8) -> u8 {
}
}
+/// Which metrics of a first available font the lengths in `value` read: whether one is an `lh`,
+/// relative to a line height, and whether one is an `ex`, `cap` or `ch`, relative to a glyph metric.
+pub(crate) fn font_metric_length_reads(value: &StyleValueData) -> (bool, bool) {
+ fn read_unit(unit: u8, reads: &mut (bool, bool)) {
+ if let Some(LengthUnitKind::FontRelative { metric, root: false }) = length_unit_kinds().get(usize::from(unit)) {
+ match metric {
+ FontMetricSelector::LineHeight => reads.0 = true,
+ FontMetricSelector::FontSize => {}
+ _ => reads.1 = true,
+ }
+ }
+ }
+ fn read_calculation(node: &crate::css::calc::CalcNode, reads: &mut (bool, bool)) {
+ if let crate::css::calc::CalcNode::Numeric(crate::css::calc::CalcNumericValue::Length { unit, .. }) = node {
+ read_unit(*unit, reads);
+ }
+ node.for_each_child(&mut |child| read_calculation(child, reads));
+ }
+ fn read(value: &StyleValueData, reads: &mut (bool, bool)) {
+ match value {
+ StyleValueData::Length { unit, .. } => read_unit(*unit, reads),
+ StyleValueData::Calculated(payload) => read_calculation(payload.rust_calculation.node(), reads),
+ _ => {}
+ }
+ value.for_each_child(&mut |child| read(child, reads));
+ }
+ let mut reads = (false, false);
+ read(value, &mut reads);
+ reads
+}
+
/// Whether `unit` is relative to a metric of the element's or its parent's first available font,
/// rather than to its font size alone.
pub(crate) fn is_font_metric_relative_length_unit(unit: u8) -> bool {
@@ -7569,14 +7600,31 @@ fn finish_animation_sample(
.unwrap_or(environment.color_scheme_input.preferred_color_scheme),
draw_random_base_value: None,
};
+ let mut custom_value_reads = crate::css::custom_properties::RegisteredValueReads::default();
let custom_values = resolved
.properties
.iter()
.map(|property| match property.custom_name_id {
0 => None,
- _ => Some(custom_properties.computed_value(registry, property, &finalization)),
+ _ => {
+ let (value, reads) = custom_properties.computed_value(registry, property, &finalization);
+ custom_value_reads |= reads;
+ Some(value)
+ }
})
.collect::<Vec<_>>();
+ // https://drafts.csswg.org/css-values-4/#font-relative-lengths
+ // NB: A registered custom property's keyframe value relative to a metric of the element's or the document
+ // element's first available font reads that font, as any other keyframe value does.
+ engine.want_first_available_font_loads_for(
+ node,
+ input.pseudo(),
+ crate::css::animation::FontMetricReads {
+ own: custom_value_reads.font_metrics,
+ parent: false,
+ root: custom_value_reads.root_font == RootFontReads::Metrics,
+ },
+ );
let (underlying_values, initial_values) = custom_properties.underlying_and_initial_values(registry);
let computed_keyframes = compute_animation_keyframe_longhands(
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/css-values/reference/cap-unit-001-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/css-values/reference/cap-unit-001-ref.html
new file mode 100644
index 00000000000..b1816deb43c
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/css-values/reference/cap-unit-001-ref.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>CSS Values and Units reference: support for the cap unit</title>
+<link rel="author" title="Jonathan Kew" href="mailto:[email protected]">
+<style>
+div {
+ background: green;
+ height: 100px;
+ width: 100px;
+}
+</style>
+<body>
+ <p>Test passes if there is a <strong>filled green square</strong> and <strong>no red</strong>.</p>
+ <div></div>
+</body>
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/css-values/reference/ex-unit-001-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/css-values/reference/ex-unit-001-ref.html
new file mode 100644
index 00000000000..f815ef0715a
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/css-values/reference/ex-unit-001-ref.html
@@ -0,0 +1,27 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>CSS Test Reference</title>
+<link rel="author" title="Emilio Cobos Álvarez" href="mailto:[email protected]">
+<meta name="flags" content="ahem">
+<link rel="stylesheet" type="text/css" href="../../../fonts/ahem.css" />
+<style>
+ @font-face {
+ font-family: foo;
+ font-weight: 900;
+ src: url('../../../fonts/noto/noto-sans-v8-latin-regular.woff');
+ }
+ div {
+ font-family: foo, sans-serif;
+ font-weight: 900;
+ width: 10ex;
+ height: 20px;
+ background: blue;
+ margin: 20px;
+ font-size: 20px;
+ }
+</style>
+<p>All lines except the first should be the same length</p>
+<div style="font-family: Ahem; font-weight: normal;"></div>
+<div></div>
+<div></div>
+<div></div>
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/css-values/reference/ex-unit-002-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/css-values/reference/ex-unit-002-ref.html
new file mode 100644
index 00000000000..74e304be728
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/css-values/reference/ex-unit-002-ref.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>CSS Values and Units Test Reference File</title>
+<link rel="author" title="Cameron McCormack" href="mailto:[email protected]">
+<style>
+div {
+ height: 10px;
+ background-color: blue;
+ margin-top: 10px;
+ width: 100px;
+}
+</style>
+<p>The test passes if there are two blue rectangles of equal length.</p>
+<div></div>
+<div></div>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/css-values/cap-unit-001.html b/Tests/LibWeb/Ref/input/wpt-import/css/css-values/cap-unit-001.html
new file mode 100644
index 00000000000..c228ed25240
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/css/css-values/cap-unit-001.html
@@ -0,0 +1,32 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>CSS Values and Units Test: support for the cap unit</title>
+<link rel="author" title="Jonathan Kew" href="mailto:[email protected]">
+<link rel="help" href="https://drafts.csswg.org/css-values-4/#font-relative-lengths">
+<link rel="match" href="../../../../expected/wpt-import/css/css-values/reference/cap-unit-001-ref.html">
+<meta name="assert" content="The cap unit is equal to the used cap-height of the first available font.">
+<link rel="stylesheet" type="text/css" href="../../fonts/ahem.css">
+<style>
+span {
+ background: green;
+ color: green;
+ position: absolute;
+}
+div {
+ font: 50px Ahem; /* cap-height of Ahem is 0.8em */
+ background: red;
+ position: relative;
+ height: 180px;
+ height: calc(180px - 2cap); /* reduce to 100px if cap correctly supported */
+ width: 100px;
+}
+
+div span {
+ width: 2.5cap;
+ height: 100px;
+}
+</style>
+<body>
+ <p>Test passes if there is a <strong>filled green square</strong> and <strong>no red</strong>.</p>
+ <div><span></span></div>
+</body>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/css-values/ex-unit-001.html b/Tests/LibWeb/Ref/input/wpt-import/css/css-values/ex-unit-001.html
new file mode 100644
index 00000000000..0256cd219cd
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/css/css-values/ex-unit-001.html
@@ -0,0 +1,36 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>CSS Values and Units Test: ex unit computation and dependencies</title>
+<link rel="author" title="Emilio Cobos Álvarez" href="mailto:[email protected]">
+<link rel="author" title="Mozilla" href="https://mozilla.org">
+<link rel="help" href="https://drafts.csswg.org/css-values/#font-relative-lengths">
+<link rel="help" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1529537">
+<link rel="match" href="../../../../expected/wpt-import/css/css-values/reference/ex-unit-001-ref.html">
+<meta name="flags" content="ahem">
+<style>
+ @font-face {
+ font-family: foo;
+ src: url('../../fonts/Ahem.ttf');
+ }
+
+ @font-face {
+ font-family: foo;
+ font-weight: 900;
+ /* A font with significantly different ex-height metric than Aham. */
+ src: url('../../fonts/noto/noto-sans-v8-latin-regular.woff');
+ }
+
+ div {
+ font-family: foo, sans-serif;
+ width: 10ex;
+ height: 20px;
+ background: blue;
+ margin: 20px;
+ font-size: 20px;
+ }
+</style>
+<p>All lines except the first should be the same length</p>
+<div></div>
+<div style="font-weight: 900"></div>
+<div style="font-weight: 900; width: 10ex;"></div>
+<section style="font-weight: 900"><div></div></section>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/css-values/ex-unit-002.html b/Tests/LibWeb/Ref/input/wpt-import/css/css-values/ex-unit-002.html
new file mode 100644
index 00000000000..eeaebdd8cc5
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/css/css-values/ex-unit-002.html
@@ -0,0 +1,30 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>CSS Values and Units Test: support for the ex unit</title>
+<link rel="author" title="Cameron McCormack" href="mailto:[email protected]">
+<link rel="help" href="https://drafts.csswg.org/css-values-3/#font-relative-lengths">
+<link rel="match" href="../../../../expected/wpt-import/css/css-values/reference/ex-unit-002-ref.html">
+<meta name="assert" content="The ex unit equals the x-height of the first available font if it has reliable metrics for the x-height.">
+<style>
+@font-face {
+ font-family: ExTest;
+ src: url(resources/ExTest.woff);
+}
+div {
+ height: 10px;
+ background-color: blue;
+ margin-top: 10px;
+}
+.test {
+ width: 10ex;
+}
+.ref {
+ width: 100px;
+}
+</style>
+<p>The test passes if there are two blue rectangles of equal length.</p>
+<!-- ExTest is a font whose OS/2 table's sxHeight field is set to an
+ eighth of the font's units per em, so ex units should compute to
+ 0.125em, resulting in the div being 100px wide. -->
+<div class="test" style="font: 80px ExTest;"></div>
+<div class="ref"></div>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/css-values/resources/ExTest.woff b/Tests/LibWeb/Ref/input/wpt-import/css/css-values/resources/ExTest.woff
new file mode 100644
index 00000000000..0dbc17cf2ab
Binary files /dev/null and b/Tests/LibWeb/Ref/input/wpt-import/css/css-values/resources/ExTest.woff differ
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 0f9b2c6df5d..ef6c5031b1f 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -4,6 +4,9 @@ Text/input/PDF/jbig2-image.html
Text/input/PDF/viewer-does-not-take-over-initial-about-blank-window.html
[LoadFromHttpServer]
+Text/input/wpt-import/css/css-values/ch-empty-pseudo-recalc-on-font-load.html
+Text/input/wpt-import/css/css-values/ch-pseudo-recalc-on-font-load.html
+Text/input/wpt-import/css/css-values/ch-recalc-on-font-load.html
Text/input/fragment-scroll-after-stylesheet.html
Text/input/replaced/embed-raster-resource-policy.html
Text/input/replaced/embed-representations.html
diff --git a/Tests/LibWeb/Text/expected/css/font-face-requested-by-style-alone.txt b/Tests/LibWeb/Text/expected/css/font-face-requested-by-style-alone.txt
index 1003a693ae2..7dc5b0bb594 100644
--- a/Tests/LibWeb/Text/expected/css/font-face-requested-by-style-alone.txt
+++ b/Tests/LibWeb/Text/expected/css/font-face-requested-by-style-alone.txt
@@ -1,7 +1,7 @@
exact: before any style is computed, status = unloaded
-exact: computing a style that selects the face makes status = unloaded
+exact: computing a style that selects the face makes status = loading
exact: the pending face keeps the fallback's ex metrics = true
-exact: document.fonts.status = loaded
+exact: document.fonts.status = loading
matched: before any style is computed, status = unloaded
matched: computing a style that selects the face makes status = loading
matched: the pending face keeps the fallback's ex metrics = true
diff --git a/Tests/LibWeb/Text/expected/css/font-relative-length-loads-root-web-font-in-ratio.txt b/Tests/LibWeb/Text/expected/css/font-relative-length-loads-root-web-font-in-ratio.txt
new file mode 100644
index 00000000000..b33ec071b21
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/font-relative-length-loads-root-web-font-in-ratio.txt
@@ -0,0 +1 @@
+RootFace: loaded
diff --git a/Tests/LibWeb/Text/expected/css/font-relative-length-loads-root-web-font.txt b/Tests/LibWeb/Text/expected/css/font-relative-length-loads-root-web-font.txt
new file mode 100644
index 00000000000..b33ec071b21
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/font-relative-length-loads-root-web-font.txt
@@ -0,0 +1 @@
+RootFace: loaded
diff --git a/Tests/LibWeb/Text/expected/css/font-relative-length-loads-web-font.txt b/Tests/LibWeb/Text/expected/css/font-relative-length-loads-web-font.txt
new file mode 100644
index 00000000000..b2b9c6b915f
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/font-relative-length-loads-web-font.txt
@@ -0,0 +1,18 @@
+CapFace: loaded
+ExFace: loaded
+ChFace: loaded
+HiddenCapFace: loaded
+ParentExFace: loaded
+UnusedFace: unloaded
+ChildOfParentExFace: unloaded
+KeyframeFace: loaded
+ContainerFace: loaded
+PseudoKeyframeFace: loaded
+PseudoHostFace: unloaded
+CustomPropertyKeyframeFace: loaded
+LineHeightParentFace: loaded
+LineHeightChildFace: unloaded
+AnimatedLineHeightParentFace: loaded
+AnimatedLineHeightChildFace: unloaded
+cap: 320px
+parent-ex: 32px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/font-refill-rounds.txt b/Tests/LibWeb/Text/expected/css/style-engine/font-refill-rounds.txt
index 0ba9c84ac18..20afbba226b 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/font-refill-rounds.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/font-refill-rounds.txt
@@ -4,7 +4,7 @@ grandchild: 92px, 184px
before: 58px
after: 62px
warm margin: 7px
-metric observation finishes before load: unloaded
+metric observation finishes before load: loading
explicit completion: loaded
loaded metrics replace fallback: true
removal restores fallback: true
diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-values/cap-invalidation.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-values/cap-invalidation.txt
new file mode 100644
index 00000000000..7220d281c60
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-values/cap-invalidation.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass CSS Values and Units Test: cap invalidation
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-values/ch-empty-pseudo-recalc-on-font-load.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-values/ch-empty-pseudo-recalc-on-font-load.txt
new file mode 100644
index 00000000000..c668446a9e7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-values/ch-empty-pseudo-recalc-on-font-load.txt
@@ -0,0 +1,8 @@
+Harness status: OK
+
+Found 3 tests
+
+3 Fail
+Fail ch in pseudo-element ::before should be recalculated after loading a web font
+Fail ch in pseudo-element ::after should be recalculated after loading a web font
+Fail ch in pseudo-element ::backdrop should be recalculated after loading a web font
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-values/ch-pseudo-recalc-on-font-load.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-values/ch-pseudo-recalc-on-font-load.txt
new file mode 100644
index 00000000000..cd5435eaeb2
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-values/ch-pseudo-recalc-on-font-load.txt
@@ -0,0 +1,10 @@
+Harness status: OK
+
+Found 5 tests
+
+5 Pass
+Pass ch in pseudo-element ::before should be recalculated after loading a web font
+Pass ch in pseudo-element ::after should be recalculated after loading a web font
+Pass ch in pseudo-element ::first-letter should be recalculated after loading a web font
+Pass ch in pseudo-element ::first-line should be recalculated after loading a web font
+Pass ch in pseudo-element ::marker should be recalculated after loading a web font
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-values/ch-recalc-on-font-load.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-values/ch-recalc-on-font-load.txt
new file mode 100644
index 00000000000..20e320a74ef
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-values/ch-recalc-on-font-load.txt
@@ -0,0 +1,8 @@
+Harness status: OK
+
+Found 3 tests
+
+3 Pass
+Pass ch in a normal div should be recalculated after loading a web font
+Pass ch in display:contents should be recalculated after loading a web font
+Pass ch in display:none should be recalculated after loading a web font
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-values/rcap-invalidation.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-values/rcap-invalidation.txt
new file mode 100644
index 00000000000..678a5c9429b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-values/rcap-invalidation.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass CSS Values and Units Test: rcap invalidation
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/svg/types/scripted/SVGLength-convertToSpecifiedUnits-font-change.txt b/Tests/LibWeb/Text/expected/wpt-import/svg/types/scripted/SVGLength-convertToSpecifiedUnits-font-change.txt
index 1d39676103d..94c37ace6a4 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/svg/types/scripted/SVGLength-convertToSpecifiedUnits-font-change.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/svg/types/scripted/SVGLength-convertToSpecifiedUnits-font-change.txt
@@ -2,8 +2,9 @@ Harness status: OK
Found 4 tests
-4 Pass
+3 Pass
+1 Fail
Pass SVGLength, value updates after font-size change on em/ex conversion, changing em basis
Pass SVGLength, value updates after font-size change on em/ex conversion, doubling em basis doubles value
-Pass SVGLength, value updates after font-size change on em/ex conversion, changing ex basis
+Fail SVGLength, value updates after font-size change on em/ex conversion, changing ex basis
Pass SVGLength, value updates after font-size change on em/ex conversion, inherited font-size change
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/css/font-face-requested-by-style-alone.html b/Tests/LibWeb/Text/input/css/font-face-requested-by-style-alone.html
index f7b05f26f37..009fd2208d6 100644
--- a/Tests/LibWeb/Text/input/css/font-face-requested-by-style-alone.html
+++ b/Tests/LibWeb/Text/input/css/font-face-requested-by-style-alone.html
@@ -23,9 +23,8 @@ promiseTest(async () => {
const fallbackSpacing = getComputedStyle(probe("MissingFont", 400)).letterSpacing;
- // A face whose declared weight is the one the style asks for is found by the exact lookup,
- // which leaves the load to whoever first renders a code point. A face the style has to reach
- // through the font-matching algorithm is loaded as soon as a style selects it.
+ // Whether the exact lookup finds the face or the font-matching algorithm reaches it, the ex
+ // length reads the metrics the face would give once it loads, so the face starts loading.
for (const [label, declaredWeight, usedWeight] of [["exact", 400, 400], ["matched", 700, 400]]) {
const face = new FontFace(`StyleWanted-${label}`, `url("${url}?${label}")`, { display: "block", weight: `${declaredWeight}` });
internals.setFontDisplayTime(face, 0);
diff --git a/Tests/LibWeb/Text/input/css/font-relative-length-loads-root-web-font-in-ratio.html b/Tests/LibWeb/Text/input/css/font-relative-length-loads-root-web-font-in-ratio.html
new file mode 100644
index 00000000000..bf5a6abb567
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/font-relative-length-loads-root-web-font-in-ratio.html
@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+<style>
+ @font-face { font-family: RootFace; src: url(../wpt-import/fonts/Ahem.ttf?root); }
+ html { font-family: RootFace; }
+ body { font-family: serif; }
+ #container { container-type: size; width: 400px; height: 100px; }
+ @container (aspect-ratio > calc(2 + sign(1rcap - 30px)) / 1) { #container-child { color: green; } }
+</style>
+<!-- Nothing renders text in the document element's font, so only the rcap length in the
+ container query's ratio can want its face. -->
+<div id="container"><div id="container-child"></div></div>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ await document.fonts.ready;
+ for (const face of document.fonts)
+ println(`${face.family}: ${face.status}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/font-relative-length-loads-root-web-font.html b/Tests/LibWeb/Text/input/css/font-relative-length-loads-root-web-font.html
new file mode 100644
index 00000000000..75da741bee3
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/font-relative-length-loads-root-web-font.html
@@ -0,0 +1,19 @@
+<!DOCTYPE html>
+<style>
+ @font-face { font-family: RootFace; src: url(../wpt-import/fonts/Ahem.ttf?root); }
+ html { font-family: RootFace; }
+ body { font-family: serif; }
+ #container { container-type: inline-size; width: 400px; }
+ @container (width > 10rcap) { #container-child { color: green; } }
+</style>
+<!-- Nothing renders text in the document element's font, so only the container query's rcap length can want its face. -->
+<div id="container"><div id="container-child"></div></div>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ await document.fonts.ready;
+ for (const face of document.fonts)
+ println(`${face.family}: ${face.status}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/font-relative-length-loads-web-font.html b/Tests/LibWeb/Text/input/css/font-relative-length-loads-web-font.html
new file mode 100644
index 00000000000..d6a19a2aad5
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/font-relative-length-loads-web-font.html
@@ -0,0 +1,59 @@
+<!DOCTYPE html>
+<style>
+ @font-face { font-family: CapFace; src: url(../wpt-import/fonts/Ahem.ttf?cap); }
+ @font-face { font-family: ExFace; src: url(../wpt-import/fonts/Ahem.ttf?ex); }
+ @font-face { font-family: ChFace; src: url(../wpt-import/fonts/Ahem.ttf?ch); }
+ @font-face { font-family: HiddenCapFace; src: url(../wpt-import/fonts/Ahem.ttf?hidden-cap); }
+ @font-face { font-family: ParentExFace; src: url(../wpt-import/fonts/Ahem.ttf?parent-ex); }
+ @font-face { font-family: UnusedFace; src: url(../wpt-import/fonts/Ahem.ttf?unused); }
+ @font-face { font-family: ChildOfParentExFace; src: url(../wpt-import/fonts/Ahem.ttf?child-of-parent-ex); }
+ @font-face { font-family: KeyframeFace; src: url(../wpt-import/fonts/Ahem.ttf?keyframe); }
+ @font-face { font-family: ContainerFace; src: url(../wpt-import/fonts/Ahem.ttf?container); }
+ @font-face { font-family: PseudoKeyframeFace; src: url(../wpt-import/fonts/Ahem.ttf?pseudo-keyframe); }
+ @font-face { font-family: PseudoHostFace; src: url(../wpt-import/fonts/Ahem.ttf?pseudo-host); }
+ @font-face { font-family: CustomPropertyKeyframeFace; src: url(../wpt-import/fonts/Ahem.ttf?custom-property-keyframe); }
+ @font-face { font-family: LineHeightParentFace; src: url(../wpt-import/fonts/Ahem.ttf?line-height-parent); }
+ @font-face { font-family: LineHeightChildFace; src: url(../wpt-import/fonts/Ahem.ttf?line-height-child); }
+ @font-face { font-family: AnimatedLineHeightParentFace; src: url(../wpt-import/fonts/Ahem.ttf?animated-line-height-parent); }
+ @font-face { font-family: AnimatedLineHeightChildFace; src: url(../wpt-import/fonts/Ahem.ttf?animated-line-height-child); }
+ @property --length { syntax: "<length>"; inherits: false; initial-value: 0px; }
+ @keyframes widen { from { width: 10ch; } to { width: 20ch; } }
+ @keyframes lengthen { from { --length: 10cap; } to { --length: 20cap; } }
+ #custom-property-keyframe { font-family: CustomPropertyKeyframeFace; animation: lengthen 100s paused; width: var(--length); }
+ #line-height-parent { font-family: LineHeightParentFace; }
+ #line-height-child { font-family: LineHeightChildFace, serif; line-height: 1lh; }
+ @keyframes heighten { from { line-height: 1lh; } to { line-height: 2lh; } }
+ #animated-line-height-parent { font-family: AnimatedLineHeightParentFace; }
+ #animated-line-height-child { font-family: AnimatedLineHeightChildFace, serif; animation: heighten 100s paused; }
+ #keyframe { font-family: KeyframeFace; animation: widen 100s paused; }
+ #container { font-family: ContainerFace; container-type: inline-size; width: 400px; }
+ @container (width > 10cap) { #container-child { color: green; } }
+ #pseudo-host { font-family: PseudoHostFace; }
+ #pseudo-host::before { content: ""; display: block; font-family: PseudoKeyframeFace; animation: widen 100s paused; }
+ div { font-size: 40px; height: 1px; }
+</style>
+<!-- None of these elements holds text, so only a font-relative length can want their faces: in a style, in an
+ animation's keyframes, or in a container query. A line-height in lh reads the parent's font. -->
+<div id="cap" style="font-family: CapFace; width: 10cap"></div>
+<div id="ex" style="font-family: ExFace; width: 10ex"></div>
+<div id="ch" style="font-family: ChFace; width: 10ch"></div>
+<div id="hidden-cap" style="font-family: HiddenCapFace; width: 10cap; display: none"></div>
+<div style="font-family: ParentExFace"><div id="parent-ex" style="font-family: ChildOfParentExFace, serif; font-size: 1ex"></div></div>
+<div id="unused" style="font-family: UnusedFace; width: 100px"></div>
+<div id="keyframe"></div>
+<div id="container"><div id="container-child"></div></div>
+<div id="pseudo-host"></div>
+<div id="custom-property-keyframe"></div>
+<div id="line-height-parent"><div id="line-height-child"></div></div>
+<div id="animated-line-height-parent"><div id="animated-line-height-child"></div></div>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ await document.fonts.ready;
+ for (const face of document.fonts)
+ println(`${face.family}: ${face.status}`);
+ println(`cap: ${getComputedStyle(document.getElementById("cap")).width}`);
+ println(`parent-ex: ${getComputedStyle(document.getElementById("parent-ex")).fontSize}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/font-refill-rounds.html b/Tests/LibWeb/Text/input/css/style-engine/font-refill-rounds.html
index a31f4e80905..3431577d864 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/font-refill-rounds.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/font-refill-rounds.html
@@ -30,8 +30,8 @@
internals.updateStyle();
output.push(`warm margin: ${getComputedStyle(target).marginLeft}`);
- // No text is shaped: a synchronous metric probe must keep this face unloaded.
- // Complete loading explicitly, without relying on a network delay or a timer.
+ // No text is shaped, but the probe's ch length reads the face's metrics, so the probe starts
+ // its load. Complete loading explicitly, without relying on a network delay or a timer.
const face = new FontFace("RefillFace", 'url("../../../../Assets/HashSans.woff")', { display: "swap" });
document.fonts.add(face);
const fallbackWidth = getComputedStyle(probe).width;
diff --git a/Tests/LibWeb/Text/input/wpt-import/css/css-values/cap-invalidation.html b/Tests/LibWeb/Text/input/wpt-import/css/css-values/cap-invalidation.html
new file mode 100644
index 00000000000..22c21f7fd2b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/css/css-values/cap-invalidation.html
@@ -0,0 +1,31 @@
+<!DOCTYPE html>
+<title>CSS Values and Units Test: cap invalidation</title>
+<link rel="author" title="Daniil Sakhapov" href="[email protected]">
+<link rel="help" href="https://drafts.csswg.org/css-values/#font-relative-lengths">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<style>
+ @import url("../../fonts/ahem.css");
+ html {
+ font-family: 'Ahem';
+ font-size: 40px;
+ }
+ div {
+ width: 10cap;
+ }
+</style>
+
+<html>
+ <div id="div"></div>
+</html>
+
+<script>
+ setup({ single_test: true });
+ document.fonts.ready.then(() => {
+ let old_width = div.getBoundingClientRect().width;
+ document.documentElement.style.fontFamily = "sans-serif";
+ let new_width = div.getBoundingClientRect().width;
+ assert_not_equals(old_width, new_width, "expect the capital height of Ahem and sans-serif to be different");
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/css/css-values/ch-empty-pseudo-recalc-on-font-load.html b/Tests/LibWeb/Text/input/wpt-import/css/css-values/ch-empty-pseudo-recalc-on-font-load.html
new file mode 100644
index 00000000000..ceb6a2531b2
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/css/css-values/ch-empty-pseudo-recalc-on-font-load.html
@@ -0,0 +1,70 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>Length unit 'ch' used in pseudo elements without text should be recalculated after loading a web font</title>
+<link rel="help" href="https://www.w3.org/TR/css-font-loading-3/#font-face-load">
+<link rel="help" href="https://www.w3.org/TR/css-values-3/#font-relative-lengths">
+<link rel="help" href="https://drafts.csswg.org/css-pseudo-4#generated-content">
+<link rel="author" href="[email protected]">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<style>
+.before::before,
+.after::after,
+.backdrop::backdrop {
+ font: 25px/1 "custom font", monospace;
+ background: linear-gradient(45deg, red, blue);
+ background-size: 1ch 1ch;
+}
+</style>
+
+<div class="container before"></div>
+<div class="container after"></div>
+<dialog class="container backdrop"></dialog>
+
+<script>
+function parseBackgroundSizeInPx(element, pseudoElement) {
+ const x = getComputedStyle(element, pseudoElement).backgroundSize.split(' ')[0];
+ if (!x.endsWith('px'))
+ return NaN;
+ return parseFloat(x);
+}
+
+const testCases = ['before', 'after', 'backdrop'];
+const elements = testCases.map(testCase => document.querySelector('.' + testCase));
+const asyncTests = testCases.map(
+ testCase => async_test(`ch in pseudo-element ::${testCase} should be recalculated after loading a web font`));
+
+// Before loading custom font, tests should be rendered with monospace
+// fallback and have a '1ch' measurement much shorter than 25px.
+for (let i = 0; i < testCases.length; ++i) {
+ asyncTests[i].step(() => {
+ const backgroundSizePx = parseBackgroundSizeInPx(elements[i], '::' + testCases[i]);
+ assert_less_than(backgroundSizePx, 24);
+ });
+}
+
+// Insert custom font into style sheet and load it
+const customFont = new FontFace('custom font', 'url(/fonts/Ahem.ttf)');
+document.fonts.add(customFont);
+
+// After loading custom font, tests should be rendered with the custom font,
+// which is Ahem, and have a '1ch' measurement that equals 25px.
+customFont.load().then(
+ () => {
+ for (let i = 0; i < testCases.length; ++i) {
+ asyncTests[i].step(() => {
+ const backgroundSizePx = parseBackgroundSizeInPx(elements[i], '::' + testCases[i]);
+ assert_equals(backgroundSizePx, 25);
+ asyncTests[i].done();
+ });
+ }
+ },
+ () => {
+ for (let i = 0; i < testCases.length; ++i) {
+ asyncTests[i].step(() => {
+ assert_unreached('Failed to load font');
+ });
+ }
+ }
+);
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/css/css-values/ch-pseudo-recalc-on-font-load.html b/Tests/LibWeb/Text/input/wpt-import/css/css-values/ch-pseudo-recalc-on-font-load.html
new file mode 100644
index 00000000000..aa07e03813d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/css/css-values/ch-pseudo-recalc-on-font-load.html
@@ -0,0 +1,89 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>Length unit 'ch' used in pseudo elements should be recalculated after loading a web font</title>
+<link rel="help" href="https://www.w3.org/TR/css-font-loading-3/#font-face-load">
+<link rel="help" href="https://www.w3.org/TR/css-values-3/#font-relative-lengths">
+<link rel="help" href="https://drafts.csswg.org/css-pseudo-4/#first-letter-styling">
+<link rel="author" href="[email protected]">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<style>
+.container {
+ font: 25px/1 "custom font", monospace;
+}
+
+.before::before,
+.after::after,
+.first-letter::first-letter,
+.first-line::first-line {
+ font-family: monospace;
+ font-size: 1ch; /* Refers to originating element's font metrics, which are different from self font metrics. */
+}
+
+.before::before,
+.after::after {
+ content: 'text';
+}
+
+/* Defined separately so that browsers that haven't shipped it can still pass other tests. */
+.marker::marker {
+ font-family: monospace;
+ font-size: 1ch;
+ content: 'text';
+}
+
+</style>
+
+<div class="container before"></div>
+<div class="container after"></div>
+<div class="container first-letter">text</div>
+<div class="container first-line">text</div>
+<li class="container marker"></li>
+
+<script>
+function parseFontSizeInPx(element, pseudoElement) {
+ const value = getComputedStyle(element, pseudoElement).fontSize;
+ if (!value.endsWith('px'))
+ return NaN;
+ return parseFloat(value);
+}
+
+const testCases = ['before', 'after', 'first-letter', 'first-line', 'marker'];
+const elements = testCases.map(testCase => document.querySelector('.' + testCase));
+const asyncTests = testCases.map(
+ testCase => async_test(`ch in pseudo-element ::${testCase} should be recalculated after loading a web font`));
+
+// Before loading custom font, tests should be rendered with monospace
+// fallback and have a '1ch' measurement much shorter than 25px.
+for (let i = 0; i < testCases.length; ++i) {
+ asyncTests[i].step(() => {
+ const fontSizePx = parseFontSizeInPx(elements[i], '::' + testCases[i]);
+ assert_less_than(fontSizePx, 24);
+ });
+}
+
+// Insert custom font into style sheet and load it
+const customFont = new FontFace('custom font', 'url(/fonts/Ahem.ttf)');
+document.fonts.add(customFont);
+
+// After loading custom font, tests should be rendered with the custom font,
+// which is Ahem, and have a '1ch' measurement that equals 25px.
+customFont.load().then(
+ () => {
+ for (let i = 0; i < testCases.length; ++i) {
+ asyncTests[i].step(() => {
+ const fontSizePx = parseFontSizeInPx(elements[i], '::' + testCases[i]);
+ assert_approx_equals(fontSizePx, 25, 0.1);
+ asyncTests[i].done();
+ });
+ }
+ },
+ () => {
+ for (let i = 0; i < testCases.length; ++i) {
+ asyncTests[i].step(() => {
+ assert_unreached('Failed to load font');
+ });
+ }
+ }
+);
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/css/css-values/ch-recalc-on-font-load.html b/Tests/LibWeb/Text/input/wpt-import/css/css-values/ch-recalc-on-font-load.html
new file mode 100644
index 00000000000..40d694ae2a0
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/css/css-values/ch-recalc-on-font-load.html
@@ -0,0 +1,79 @@
+<!DOCTYPE html>
+<title>Length unit 'ch' should be recalculated after loading a web font</title>
+<link rel="help" href="https://www.w3.org/TR/css-font-loading-3/#font-face-load">
+<link rel="help" href="https://www.w3.org/TR/css-values-3/#font-relative-lengths">
+<link rel="author" href="mailto:[email protected]">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<style>
+.container {
+ font: 25px/1 "custom font", monospace;
+}
+
+.test {
+ width: 1ch;
+}
+</style>
+
+<div class="container">
+ <div class="test"></div>
+</div>
+
+<div class="container" style="display: contents">
+ <div class="test"></div>
+</div>
+
+<div class="container" style="display: none">
+ <div class="test"></div>
+</div>
+
+<script>
+function parseWidthInPx(element) {
+ const value = getComputedStyle(element).width;
+ if (!value.endsWith('px'))
+ return NaN;
+ return parseFloat(value);
+}
+
+const testCases = document.querySelectorAll('.test');
+
+const asyncTests = [
+ async_test('ch in a normal div should be recalculated after loading a web font'),
+ async_test('ch in display:contents should be recalculated after loading a web font'),
+ async_test('ch in display:none should be recalculated after loading a web font')
+];
+
+// Before loading custom font, tests should be rendered with monospace
+// fallback and have a '1ch' measurement much shorter than 25px.
+for (let i = 0; i < testCases.length; ++i) {
+ asyncTests[i].step(() => {
+ const widthPx = parseWidthInPx(testCases[i]);
+ assert_less_than(widthPx, 24);
+ });
+}
+
+// Insert custom font into style sheet and load it
+const customFont = new FontFace('custom font', 'url(/fonts/Ahem.ttf)');
+document.fonts.add(customFont);
+
+// After loading custom font, tests should be rendered with the custom font,
+// which is Ahem, and have a '1ch' measurement that equals 25px.
+customFont.load().then(
+ () => {
+ for (let i = 0; i < testCases.length; ++i) {
+ asyncTests[i].step(() => {
+ const widthPx = parseWidthInPx(testCases[i]);
+ assert_approx_equals(widthPx, 25, 0.1);
+ asyncTests[i].done();
+ });
+ }
+ },
+ () => {
+ for (let i = 0; i < testCases.length; ++i) {
+ asyncTests[i].step(() => {
+ assert_unreached('Failed to load font');
+ });
+ }
+ }
+);
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/css/css-values/rcap-invalidation.html b/Tests/LibWeb/Text/input/wpt-import/css/css-values/rcap-invalidation.html
new file mode 100644
index 00000000000..629923f7a8c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/css/css-values/rcap-invalidation.html
@@ -0,0 +1,39 @@
+<!DOCTYPE html>
+<title>CSS Values and Units Test: rcap invalidation</title>
+<link rel="author" title="Daniil Sakhapov" href="[email protected]">
+<link rel="help" href="https://drafts.csswg.org/css-values/#font-relative-lengths">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<meta name="assert" content="test rcap invalidation">
+<style>
+ @import url("../../fonts/ahem.css");
+ html {
+ font-family: 'Ahem';
+ font-size: 40px;
+ }
+ body {
+ font-family: monospace;
+ font-size: 20px;
+ }
+ div {
+ height: 10rcap;
+ width: 10rcap;
+ }
+</style>
+
+<html>
+ <body>
+ <div id="div"></div>
+ </body>
+</html>
+
+<script>
+ setup({ single_test: true });
+ document.fonts.ready.then(() => {
+ let old_width = div.getBoundingClientRect().width;
+ document.documentElement.style.fontFamily = "sans-serif";
+ let new_width = div.getBoundingClientRect().width;
+ assert_not_equals(old_width, new_width, "expect the capital height of Ahem and sans-serif to be different");
+ done();
+ });
+</script>