Skip to content

Truly independent web browser

LibWeb: Prefer the last matching font face within a cascade layer

sideshowbarker9b0603ab09b9
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs b/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs
index 98379b74aae..ada5b3ed5a8 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs
@@ -56,7 +56,7 @@ unsafe extern "C" {
fn web_css_font_face_set_for_each_font_face_rule(
set: *mut c_void,
context: *mut c_void,
- callback: unsafe extern "C" fn(*mut c_void, u64),
+ callback: unsafe extern "C" fn(*mut c_void, u64, usize),
) -> bool;
fn web_css_font_face_set_synchronize_font_computer(set: *mut c_void, font_faces: *const *mut c_void, count: usize);
}
@@ -363,13 +363,16 @@ impl FontFaceSet {
// document order. As @font-face rules are added or removed, the corresponding objects must be added or removed and
// maintain this ordering. Any manually-added FontFace objects must be ordered after the CSS-connected ones.
pub(crate) fn synchronize_css_connected_font_order(&self, vm: &Vm) {
- unsafe extern "C" fn append_identity(context: *mut c_void, identity: u64) {
+ unsafe extern "C" fn append_identity(context: *mut c_void, identity: u64, layer_rank: usize) {
// SAFETY: The context is the list below, which outlives the call.
- unsafe { &mut *context.cast::<Vec<u64>>() }.push(identity);
+ unsafe { &mut *context.cast::<Vec<(u64, usize)>>() }.push((identity, layer_rank));
}
let font_faces = self.entries(vm);
let font_faces = font_faces.values();
+ if font_faces.len() < 2 {
+ return;
+ }
let mut connected_font_faces = HashMap::new();
for (index, font_face) in font_faces.iter().enumerate() {
if let Some(identity) = font_face.css_rule_identity() {
@@ -378,7 +381,7 @@ impl FontFaceSet {
}
// Every sheet added or removed asks again. Without a face from a rule the walk over their rules finds nothing.
- let mut rule_identities = Vec::new();
+ let mut rule_identities: Vec<(u64, usize)> = Vec::new();
if !connected_font_faces.is_empty() {
// SAFETY: The set is live, and the list outlives the call.
let has_window = unsafe {
@@ -395,11 +398,16 @@ impl FontFaceSet {
let ordered_font_faces = MarkedVec::with_capacity(vm, font_faces.len());
let mut seen = HashSet::new();
- for identity in rule_identities {
+ let mut layer_ranks = HashMap::new();
+ for (identity, rank) in rule_identities {
if let Some(index) = connected_font_faces.get(&identity)
&& seen.insert(font_faces[*index].as_ptr())
{
- ordered_font_faces.push(font_faces[*index].clone());
+ let face = &font_faces[*index];
+ if rank != usize::MAX {
+ layer_ranks.insert(face.as_ptr(), rank);
+ }
+ ordered_font_faces.push(face.clone());
}
}
for font_face in font_faces.iter() {
@@ -419,24 +427,26 @@ impl FontFaceSet {
.iter()
.zip(font_faces.iter())
.any(|(ordered, entry)| !ordered.is(entry));
- if !order_changed {
- return;
+ if order_changed {
+ *self.font_faces.borrow_mut(vm) = ordered_font_faces.to_vec();
+ let cx = CallContext::new(vm, self.realm);
+ self.set_entries.for_each_live(vm, |set| {
+ set.set_clear(vm);
+ let cx = context_of_set(&cx, set);
+ for font_face in ordered_font_faces.values().iter() {
+ set.set_add(vm, font_face.wrapper(&cx));
+ }
+ });
}
-
- *self.font_faces.borrow_mut(vm) = ordered_font_faces.to_vec();
- let cx = CallContext::new(vm, self.realm);
- self.set_entries.for_each_live(vm, |set| {
- set.set_clear(vm);
- let cx = context_of_set(&cx, set);
- for font_face in ordered_font_faces.values().iter() {
- set.set_add(vm, font_face.wrapper(&cx));
- }
- });
- let cells: Vec<*mut c_void> = ordered_font_faces
+ let mut cells: Vec<*mut c_void> = ordered_font_faces
.values()
.iter()
.map(CppFontFaceState::as_ptr)
.collect();
+ // Layer precedence affects rendering. FontFaceSet iteration keeps its document order.
+ if !layer_ranks.is_empty() {
+ cells.sort_by_key(|cell| layer_ranks.get(cell).copied().unwrap_or(usize::MAX));
+ }
// SAFETY: The set and the FontFaces are live, and the list outlives the call.
unsafe { web_css_font_face_set_synchronize_font_computer(self.as_abi(), cells.as_ptr(), cells.len()) };
}
diff --git a/Libraries/LibWeb/CSS/FontComputer.cpp b/Libraries/LibWeb/CSS/FontComputer.cpp
index 90c13e20400..0e6ab66506e 100644
--- a/Libraries/LibWeb/CSS/FontComputer.cpp
+++ b/Libraries/LibWeb/CSS/FontComputer.cpp
@@ -553,7 +553,9 @@ NonnullRefPtr<FontFaceSnapshot const> FontComputer::font_face_snapshot() const
for (auto const& [key, faces] : m_font_faces) {
Vector<FontFaceSnapshot::Face> snapshot_faces;
snapshot_faces.ensure_capacity(faces.size());
- for (auto const& face : faces) {
+ // https://drafts.csswg.org/css-fonts-4/#font-style-matching
+ // Try the faces of a composite face in reverse order of definition.
+ for (auto const& face : faces.in_reverse()) {
snapshot_faces.unchecked_append({
.id = face->id(),
.typeface = face->typeface(),
@@ -642,6 +644,10 @@ void FontComputer::register_font_face(NonnullRefPtr<FontFaceState> face)
if (faces.contains_slow(face))
return;
faces.append(face);
+ // Editing a matching descriptor can return an earlier face to a group that already has a later one.
+ // Loading a sheet synchronizes the whole batch once every face has joined the font source.
+ if (faces.size() > 1 && m_document && m_font_face_change_batch_depth == 0)
+ document().fonts()->synchronize_css_connected_font_order();
did_load_font(key);
}
@@ -661,6 +667,8 @@ void FontComputer::unregister_font_face(NonnullRefPtr<FontFaceState> face)
void FontComputer::synchronize_font_face_order(Vector<NonnullRefPtr<FontFaceState>> const& font_source_order)
{
for (auto& entry : m_font_faces) {
+ if (entry.value.size() < 2)
+ continue;
Vector<NonnullRefPtr<FontFaceState>> ordered_faces;
for (auto& font_face : font_source_order) {
if (entry.value.contains_slow(font_face))
diff --git a/Libraries/LibWeb/CSS/FontFaceSet.cpp b/Libraries/LibWeb/CSS/FontFaceSet.cpp
index c0cb42302d2..d1e51a2e171 100644
--- a/Libraries/LibWeb/CSS/FontFaceSet.cpp
+++ b/Libraries/LibWeb/CSS/FontFaceSet.cpp
@@ -56,7 +56,7 @@ void web_css_font_face_did_join_set(void* font_face, void* set);
void web_css_font_face_did_leave_set(void* font_face, void* set);
void web_css_font_face_set_record_loading_fonts(void* set, size_t count);
void web_css_font_face_set_update_layout(void* set, bool skip_if_running);
-bool web_css_font_face_set_for_each_font_face_rule(void* set, void* context, void (*callback)(void*, u64));
+bool web_css_font_face_set_for_each_font_face_rule(void* set, void* context, void (*callback)(void*, u64, size_t));
void web_css_font_face_set_synchronize_font_computer(void* set, void* const* font_faces, size_t count);
}
@@ -239,18 +239,16 @@ void web_css_font_face_set_update_layout(void* set, bool skip_if_running)
document.update_layout(DOM::UpdateLayoutReason::FontFaceSetReady);
}
-bool web_css_font_face_set_for_each_font_face_rule(void* set, void* context, void (*callback)(void*, u64))
+bool web_css_font_face_set_for_each_font_face_rule(void* set, void* context, void (*callback)(void*, u64, size_t))
{
auto* window = HTML::window_from_global_object(set_from_abi(set).relevant_settings_object().global_object());
if (!window)
return false;
- Function<void(StyleSheetState&)> for_each_rule = [&](StyleSheetState& sheet) {
- sheet.for_each_effective_rule_data(TraversalOrder::Preorder, [&](RustRuleView const& rule, Utf16View) {
- if (rule.type() == RustRule::Type::FontFace)
- callback(context, rule.identity());
- });
- };
- window->associated_document().for_each_active_css_style_sheet(for_each_rule);
+ Vector<Parser::ValueParserFFI::NativeStyleSheet const*> sheets;
+ window->associated_document().for_each_active_css_style_sheet([&](StyleSheetState& sheet) {
+ sheets.append(sheet.native_sheet().handle());
+ });
+ Parser::ValueParserFFI::rust_style_sheets_visit_font_face_rules(sheets.data(), sheets.size(), context, callback);
return true;
}
diff --git a/Libraries/LibWeb/CSS/Invalidation/MediaQueryInvalidator.cpp b/Libraries/LibWeb/CSS/Invalidation/MediaQueryInvalidator.cpp
index 54ae9a6578d..fed3e391da1 100644
--- a/Libraries/LibWeb/CSS/Invalidation/MediaQueryInvalidator.cpp
+++ b/Libraries/LibWeb/CSS/Invalidation/MediaQueryInvalidator.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibWeb/CSS/FontFaceSet.h>
#include <LibWeb/CSS/Invalidation/MediaQueryInvalidator.h>
#include <LibWeb/CSS/StyleComputer.h>
#include <LibWeb/CSS/StyleEngineInput.h>
@@ -81,6 +82,8 @@ void evaluate_media_rules_and_publish_conditions(DOM::Document& document)
for (auto* style_scope : scopes_with_changed_layer_order)
style_scope->publish_cascade_layer_order();
+ if (scopes_with_changed_layer_order.contains(&document.style_scope()))
+ document.fonts()->synchronize_css_connected_font_order();
}
}
diff --git a/Libraries/LibWeb/CSS/StyleScope.cpp b/Libraries/LibWeb/CSS/StyleScope.cpp
index 1dc3fc4742e..ba6298886a7 100644
--- a/Libraries/LibWeb/CSS/StyleScope.cpp
+++ b/Libraries/LibWeb/CSS/StyleScope.cpp
@@ -180,6 +180,8 @@ void StyleScope::remove_sheet(StyleSheetState& sheet, StyleEngineUpdate style_en
sheet.remove_owning_document_or_shadow_root(node());
bool did_remove = m_style_sheets.remove_first_matching([&](auto& entry) { return entry.ptr() == &sheet; });
VERIFY(did_remove);
+ if (m_node->is_document())
+ document().fonts()->synchronize_css_connected_font_order();
if (style_engine_update == StyleEngineUpdate::Record)
record_stylesheet_detached(sheet, node());
diff --git a/Libraries/LibWeb/CSS/StyleSheetState.cpp b/Libraries/LibWeb/CSS/StyleSheetState.cpp
index 0f051d95494..d07eeef53e9 100644
--- a/Libraries/LibWeb/CSS/StyleSheetState.cpp
+++ b/Libraries/LibWeb/CSS/StyleSheetState.cpp
@@ -13,6 +13,7 @@
#include <LibWeb/CSS/CSSStyleRule.h>
#include <LibWeb/CSS/CSSStyleSheet.h>
#include <LibWeb/CSS/FontComputer.h>
+#include <LibWeb/CSS/FontFaceSet.h>
#include <LibWeb/CSS/FontFaceState.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/SharedCompiledStyleSheet.h>
@@ -450,6 +451,7 @@ void StyleSheetState::set_disabled(bool disabled)
}
} else if (document && has_document_owner()) {
document->font_computer().unload_fonts_from_sheet(*this);
+ document->fonts()->synchronize_css_connected_font_order();
}
forget_font_feature_values();
diff --git a/Libraries/LibWeb/DOM/AdoptedStyleSheets.cpp b/Libraries/LibWeb/DOM/AdoptedStyleSheets.cpp
index 3d04cae1953..511b3542a79 100644
--- a/Libraries/LibWeb/DOM/AdoptedStyleSheets.cpp
+++ b/Libraries/LibWeb/DOM/AdoptedStyleSheets.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibWeb/CSS/FontFaceSet.h>
#include <LibWeb/CSS/Invalidation/AdoptedStyleSheetInvalidator.h>
#include <LibWeb/CSS/StyleEngineInput.h>
#include <LibWeb/CSS/StyleSheetState.h>
@@ -109,6 +110,12 @@ GC::Ref<WebIDL::ObservableArray> create_adopted_style_sheets_list(Node& document
return {};
}));
+ // The indexed callbacks run before the backing list changes. Font matching needs the resulting sheet order.
+ if (document_or_shadow_root.is_document()) {
+ adopted_style_sheets->set_on_backing_list_changed(GC::create_function(realm.heap(), GC::captures(document_or_shadow_root.document()), [](Document& document) {
+ document.fonts()->synchronize_css_connected_font_order();
+ }));
+ }
return adopted_style_sheets;
}
diff --git a/Libraries/LibWeb/Rust/src/css/style_sheet.rs b/Libraries/LibWeb/Rust/src/css/style_sheet.rs
index 1f71ea02345..a9e1c182da8 100644
--- a/Libraries/LibWeb/Rust/src/css/style_sheet.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_sheet.rs
@@ -656,6 +656,53 @@ fn cascade_layer_order<'a>(sheets: impl IntoIterator<Item = &'a NativeStyleSheet
result
}
+/// Visit font-face rules in document order and report each rule's normal cascade layer precedence.
+///
+/// # Safety
+/// The array and its sheets must be live for this call. The callback must not mutate the sheets.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_style_sheets_visit_font_face_rules(
+ sheets: *const *const NativeStyleSheet,
+ count: usize,
+ context: *mut c_void,
+ visit: unsafe extern "C" fn(*mut c_void, u64, usize),
+) {
+ if count == 0 {
+ return;
+ }
+ let sheets = unsafe { ak::slice_from_raw_parts(sheets, count) };
+ let active_sheets = || {
+ sheets
+ .iter()
+ .map(|&sheet| unsafe { &*sheet })
+ .filter(|sheet| sheet.media.matches())
+ };
+ let mut ranks = None;
+ for sheet in active_sheets() {
+ sheet.visit_effective_rule_data(FfiRuleTraversalOrder::Preorder, &[], &mut |rule, prefix, _| {
+ if rule.rule_type() != NativeRuleType::FontFace {
+ return;
+ }
+ let rank = if prefix.is_empty() {
+ usize::MAX
+ } else {
+ let ranks = ranks.get_or_insert_with(|| {
+ cascade_layer_order(active_sheets())
+ .into_iter()
+ .enumerate()
+ .map(|(rank, name)| (name, rank))
+ .collect::<HashMap<_, _>>()
+ });
+ let Some(&rank) = ranks.get(prefix) else {
+ return;
+ };
+ rank
+ };
+ unsafe { visit(context, rule.identity(), rank) };
+ });
+ }
+}
+
/// Publish the layer order of the host's ordered, active author sheets.
///
/// # Safety
diff --git a/Libraries/LibWeb/WebIDL/ObservableArray.cpp b/Libraries/LibWeb/WebIDL/ObservableArray.cpp
index 908040eec52..2b640f4291c 100644
--- a/Libraries/LibWeb/WebIDL/ObservableArray.cpp
+++ b/Libraries/LibWeb/WebIDL/ObservableArray.cpp
@@ -88,7 +88,10 @@ struct ObservableArrayHostClassTraits {
// 5. Remove the last item from handler.[[BackingList]].
// 6. Return true.
- return array.array_set(vm.names.length, JS::Value(index), &array);
+ if (!TRY(array.array_set(vm.names.length, JS::Value(index), &array)))
+ return false;
+ observable_array.did_change_backing_list();
+ return true;
}
// 4. Return ? O.[[Delete]](P).
@@ -137,6 +140,8 @@ struct ObservableArrayHostClassTraits {
if (!TRY(array.array_set(vm.names.length, JS::Value(index_to_delete), &array)))
return false;
+ observable_array.did_change_backing_list();
+
// 3. Set indexToDelete to indexToDelete − 1.
}
@@ -189,7 +194,10 @@ struct ObservableArrayHostClassTraits {
descriptor.enumerable = true;
descriptor.configurable = true;
}
- return array.internal_define_own_property(property_key, descriptor);
+ if (!TRY(array.internal_define_own_property(property_key, descriptor)))
+ return false;
+ observable_array.did_change_backing_list();
+ return true;
}
};
@@ -218,6 +226,7 @@ void ObservableArray::visit_edges(JS::Cell::Visitor& visitor)
visitor.visit(m_convert_to_idl_value);
visitor.visit(m_on_set_an_indexed_value);
visitor.visit(m_on_delete_an_indexed_value);
+ visitor.visit(m_on_backing_list_changed);
}
void ObservableArray::set_convert_to_idl_value_callback(GC::Ref<GC::Function<ConvertToIDLValueCallbackFunction::FunctionType>> callback)
@@ -278,12 +287,19 @@ JS::ThrowCompletionOr<void> ObservableArray::run_delete_an_indexed_value_callbac
return {};
}
+void ObservableArray::did_change_backing_list()
+{
+ if (m_on_backing_list_changed)
+ m_on_backing_list_changed->function()();
+}
+
JS::ThrowCompletionOr<void> ObservableArray::append(JS::Value value)
{
TRY(run_convert_to_idl_value_callback(value));
TRY(run_set_an_indexed_value_callback(length(), value));
// Unlike CreateDataProperty, this also appends to an array that script has made non-extensible or frozen.
m_array_object->indexed_append(value);
+ did_change_backing_list();
return {};
}
@@ -296,6 +312,7 @@ void ObservableArray::clear()
if (auto deleted_value = element_value(0); deleted_value.has_value() && m_on_delete_an_indexed_value)
MUST(m_on_delete_an_indexed_value->function()(*deleted_value, 0));
m_array_object->indexed_take_first();
+ did_change_backing_list();
}
}
diff --git a/Libraries/LibWeb/WebIDL/ObservableArray.h b/Libraries/LibWeb/WebIDL/ObservableArray.h
index caeeb1278d4..5355225080b 100644
--- a/Libraries/LibWeb/WebIDL/ObservableArray.h
+++ b/Libraries/LibWeb/WebIDL/ObservableArray.h
@@ -40,6 +40,8 @@ public:
void set_on_set_an_indexed_value_callback(GC::Ref<GC::Function<SetAnIndexedValueCallbackFunction::FunctionType>> callback);
void set_on_delete_an_indexed_value_callback(GC::Ref<GC::Function<DeleteAnIndexedValueCallbackFunction::FunctionType>> callback);
+ void set_on_backing_list_changed(GC::Ref<GC::Function<void()>> callback) { m_on_backing_list_changed = callback; }
+
GC::Ref<JS::Object> array_object() const { return m_array_object; }
u32 length() const;
@@ -71,6 +73,8 @@ private:
JS::ThrowCompletionOr<void> run_set_an_indexed_value_callback(u32 index, JS::Value& value);
JS::ThrowCompletionOr<void> run_delete_an_indexed_value_callback(u32 index);
+ void did_change_backing_list();
+
using ConvertToIDLValueCallbackHeapFunction = GC::Function<ConvertToIDLValueCallbackFunction::FunctionType>;
using SetAnIndexedValueCallbackHeapFunction = GC::Function<SetAnIndexedValueCallbackFunction::FunctionType>;
using DeleteAnIndexedValueCallbackHeapFunction = GC::Function<DeleteAnIndexedValueCallbackFunction::FunctionType>;
@@ -80,6 +84,7 @@ private:
GC::Ptr<ConvertToIDLValueCallbackHeapFunction> m_convert_to_idl_value;
GC::Ptr<SetAnIndexedValueCallbackHeapFunction> m_on_set_an_indexed_value;
GC::Ptr<DeleteAnIndexedValueCallbackHeapFunction> m_on_delete_an_indexed_value;
+ GC::Ptr<GC::Function<void()>> m_on_backing_list_changed;
};
}
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 690db52895f..44616740bf6 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -135,6 +135,8 @@ Text/input/wpt-import/html/semantics/scripting-1/the-script-element/module/dynam
; Resource loading tests use WPT Python handlers, substitutions, or .headers files.
Text/input/wpt-import/xhr/progress-events-response-data-gzip.htm
Text/input/wpt-import/css/css-cascade/import-mime-type-quirks.html
+Text/input/wpt-import/css/css-cascade/layer-font-face-override.html
+Text/input/wpt-import/css/css-fonts/font-face-unicode-range-no-match-no-download.html
Text/input/wpt-import/html/semantics/document-metadata/the-style-element/style-error-01.html
Text/input/wpt-import/content-security-policy/script-src/script-src-trusted_types_eval_with_require_trusted_types_eval.html
Text/input/wpt-import/content-security-policy/script-src/script-src-trusted_types_eval_without_require_trusted_types_eval.html
diff --git a/Tests/LibWeb/Text/expected/css/font-face-layer-order-viewport.txt b/Tests/LibWeb/Text/expected/css/font-face-layer-order-viewport.txt
new file mode 100644
index 00000000000..9aa97da02b7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/font-face-layer-order-viewport.txt
@@ -0,0 +1,3 @@
+700px viewport: 80px text
+500px viewport: 23px text
+700px viewport: 80px text
diff --git a/Tests/LibWeb/Text/expected/css/font-face-rendering-order.txt b/Tests/LibWeb/Text/expected/css/font-face-rendering-order.txt
new file mode 100644
index 00000000000..849db5d3178
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/font-face-rendering-order.txt
@@ -0,0 +1,12 @@
+Exact: 80px, unloaded, loaded
+Unused: 80px, unloaded, loaded
+Nearest: 80px, unloaded, loaded
+Subset: 80px, loaded, unloaded
+Fallback: 80px, loaded, error
+editing an earlier descriptor preserves its order: true
+layer order statement wins: true
+disabling the layer order statement changes the winner: true
+enabling the layer order statement restores the winner: true
+removing the layer order statement changes the winner: true
+adopted sheets use the declared layer order: true
+removing an adopted layer order changes the winner: true
diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-cascade/layer-font-face-override.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-cascade/layer-font-face-override.txt
new file mode 100644
index 00000000000..f28653ab9f8
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-cascade/layer-font-face-override.txt
@@ -0,0 +1,9 @@
+Harness status: OK
+
+Found 4 tests
+
+4 Pass
+Pass @font-face unlayered overrides layered
+Pass @font-face override between layers
+Pass @font-face override update with appended sheet 1
+Pass @font-face override update with appended sheet 2
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-fonts/font-face-unicode-range-no-match-no-download.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-fonts/font-face-unicode-range-no-match-no-download.txt
new file mode 100644
index 00000000000..91a31960400
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-fonts/font-face-unicode-range-no-match-no-download.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Font with non-matching unicode-range must not be downloaded
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/css/font-face-layer-order-viewport.html b/Tests/LibWeb/Text/input/css/font-face-layer-order-viewport.html
new file mode 100644
index 00000000000..06ca31fbecb
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/font-face-layer-order-viewport.html
@@ -0,0 +1,27 @@
+<!doctype html>
+<script src="../include.js"></script>
+<iframe width="700" height="90" srcdoc='<!doctype html>
+<style>
+ @media (min-width: 600px) { @layer b, a; }
+ @layer a { @font-face { font-family: Ordered; src: url(../wpt-import/fonts/Ahem.ttf); } }
+ @layer b { @font-face { font-family: Ordered; src: url(../wpt-import/fonts/mplus-1p-regular.woff); } }
+ span { display: inline-block; font: 20px Ordered; }
+</style>
+<span>iiii</span>'></iframe>
+<script>
+ promiseTest(async () => {
+ if (document.readyState !== "complete")
+ await new Promise(resolve => window.addEventListener("load", resolve, { once: true }));
+ const frame = document.querySelector("iframe");
+ const doc = frame.contentDocument;
+ const sample = doc.querySelector("span");
+ sample.offsetWidth;
+ await Promise.all([...doc.fonts].map(face => face.load()));
+ for (const width of [700, 500, 700]) {
+ frame.width = width;
+ const child = frame.contentWindow;
+ await new Promise(resolve => child.requestAnimationFrame(() => child.requestAnimationFrame(resolve)));
+ println(child.innerWidth + "px viewport: " + sample.offsetWidth + "px text");
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/font-face-rendering-order.html b/Tests/LibWeb/Text/input/css/font-face-rendering-order.html
new file mode 100644
index 00000000000..706f2c76d06
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/font-face-rendering-order.html
@@ -0,0 +1,76 @@
+<!doctype html>
+<style>
+ @font-face { font-family: Exact; src: url(../wpt-import/fonts/mplus-1p-regular.woff); }
+ @font-face { font-family: Exact; src: url(../wpt-import/fonts/Ahem.ttf); }
+ @font-face { font-family: Unused; src: url(missing-overridden-font.woff); }
+ @font-face { font-family: Unused; src: url(../wpt-import/fonts/Ahem.ttf); }
+ @font-face { font-family: Nearest; font-weight: 500; src: url(missing-overridden-font.woff); }
+ @font-face { font-family: Nearest; font-weight: 500; src: url(../wpt-import/fonts/Ahem.ttf); }
+ @font-face { font-family: Subset; src: url(../wpt-import/fonts/Ahem.ttf); }
+ @font-face { font-family: Subset; src: url(missing-outside-range.woff); unicode-range: U+005A; }
+ @font-face { font-family: Fallback; src: url(../wpt-import/fonts/Ahem.ttf); }
+ @font-face { font-family: Fallback; src: url(missing-preferred-font.woff); }
+ span { display: inline-block; font-size: 20px; font-synthesis: none; }
+</style>
+<span style="font-family: Exact">iiii</span>
+<span style="font-family: Unused">iiii</span>
+<span style="font-family: Nearest; font-weight: 600">iiii</span>
+<span style="font-family: Subset">iiii</span>
+<span style="font-family: Fallback">iiii</span>
+<script src="../include.js"></script>
+<script>
+ promiseTest(async () => {
+ for (let i = 0; i < 2; ++i) {
+ document.body.offsetWidth;
+ await document.fonts.ready;
+ await new Promise(requestAnimationFrame);
+ }
+ for (const span of document.querySelectorAll("span")) {
+ const family = span.style.fontFamily;
+ const faces = [...document.fonts].filter(face => face.family === family);
+ println(family + ": " + span.offsetWidth + "px, " + faces.map(face => face.status).join(", "));
+ }
+ const firstFace = [...document.fonts].find(face => face.family === "Exact");
+ const exact = document.querySelector("span");
+ firstFace.weight = "500";
+ firstFace.weight = "normal";
+ await document.fonts.load("20px Exact", "iiii");
+ println("editing an earlier descriptor preserves its order: " + (exact.offsetWidth === 80));
+
+ const orderSheet = document.createElement("style");
+ orderSheet.textContent = "@layer second, first;";
+ const rules = document.createElement("style");
+ rules.textContent = `
+ @layer first { @font-face { font-family: Layered; src: url(../wpt-import/fonts/Ahem.ttf); } }
+ @layer second { @font-face { font-family: Layered; src: url(../wpt-import/fonts/mplus-1p-regular.woff); } }
+ `;
+ document.head.append(orderSheet, rules);
+ const layered = document.createElement("span");
+ layered.style.fontFamily = "Layered";
+ layered.textContent = "iiii";
+ document.body.append(layered);
+ await document.fonts.load("20px Layered", "iiii");
+ println("layer order statement wins: " + (layered.offsetWidth === 80));
+ orderSheet.sheet.disabled = true;
+ println("disabling the layer order statement changes the winner: " + (layered.offsetWidth < 80));
+ orderSheet.sheet.disabled = false;
+ println("enabling the layer order statement restores the winner: " + (layered.offsetWidth === 80));
+ orderSheet.remove();
+ println("removing the layer order statement changes the winner: " + (layered.offsetWidth < 80));
+
+ const adoptedOrder = new CSSStyleSheet();
+ adoptedOrder.replaceSync("@layer b, a;");
+ const adoptedRules = new CSSStyleSheet();
+ adoptedRules.replaceSync(`
+ @layer a { @font-face { font-family: Adopted; src: url(../wpt-import/fonts/Ahem.ttf); } }
+ @layer b { @font-face { font-family: Adopted; src: url(../wpt-import/fonts/mplus-1p-regular.woff); } }
+ `);
+ document.adoptedStyleSheets = [adoptedOrder, adoptedRules];
+ layered.style.fontFamily = "Adopted";
+ await document.fonts.load("20px Adopted", "iiii");
+ println("adopted sheets use the declared layer order: " + (layered.offsetWidth === 80));
+ document.adoptedStyleSheets[0] = new CSSStyleSheet();
+ await document.fonts.load("20px Adopted", "iiii");
+ println("removing an adopted layer order changes the winner: " + (layered.offsetWidth < 80));
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/css/css-cascade/layer-font-face-override.html b/Tests/LibWeb/Text/input/wpt-import/css/css-cascade/layer-font-face-override.html
new file mode 100644
index 00000000000..079fdc703d7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/css/css-cascade/layer-font-face-override.html
@@ -0,0 +1,141 @@
+<!DOCTYPE html>
+<title>Resolving @keyframe name conflicts with cascade layers</title>
+<link rel="help" href="https://drafts.csswg.org/css-cascade-5/#layering">
+<link rel="author" href="mailto:[email protected]">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<style>
+#target {
+ font-size: 20px;
+ width: min-content;
+}
+</style>
+
+<div id="target">Test</div>
+
+<script>
+// In all tests, width of #target should be 80px.
+
+const testCases = [
+ {
+ title: '@font-face unlayered overrides layered',
+ style: `
+ #target {
+ font-family: custom-font;
+ }
+
+ @font-face {
+ font-family: custom-font;
+ src: url('/fonts/Ahem.ttf');
+ }
+
+ @layer {
+ @font-face {
+ font-family: custom-font;
+ src: url('/fonts/noto/noto-sans-v8-latin-regular.woff') format('woff');
+ }
+ }
+ `
+ },
+
+ {
+ title: '@font-face override between layers',
+ style: `
+ @layer base, override;
+
+ #target {
+ font-family: custom-font;
+ }
+
+ @layer override {
+ @font-face {
+ font-family: custom-font;
+ src: url('/fonts/Ahem.ttf');
+ }
+ }
+
+ @layer base {
+ @font-face {
+ font-family: custom-font;
+ src: url('/fonts/noto/noto-sans-v8-latin-regular.woff') format('woff');
+ }
+ }
+ `
+ },
+
+ {
+ title: '@font-face override update with appended sheet 1',
+ style: `
+ @layer base, override;
+
+ #target {
+ font-family: custom-font;
+ }
+
+ @layer override {
+ @font-face {
+ font-family: custom-font;
+ src: url('/fonts/Ahem.ttf');
+ }
+ }
+ `,
+ append: `
+ @layer base {
+ @font-face {
+ font-family: custom-font;
+ src: url('/fonts/noto/noto-sans-v8-latin-regular.woff') format('woff');
+ }
+ }
+ `
+ },
+
+ {
+ title: '@font-face override update with appended sheet 2',
+ style: `
+ @layer base, override;
+
+ #target {
+ font-family: custom-font;
+ }
+
+ @layer base {
+ @font-face {
+ font-family: custom-font;
+ src: url('/fonts/noto/noto-sans-v8-latin-regular.woff') format('woff');
+ }
+ }
+ `,
+ append: `
+ @layer override {
+ @font-face {
+ font-family: custom-font;
+ src: url('/fonts/Ahem.ttf');
+ }
+ }
+ `
+ },
+];
+
+for (let testCase of testCases) {
+ promise_test(async () => {
+ var documentStyle = document.createElement('style');
+ documentStyle.appendChild(document.createTextNode(testCase['style']));
+ document.head.appendChild(documentStyle);
+
+ var appendedStyle;
+ if (testCase['append']) {
+ document.body.offsetLeft; // Force style update
+ appendedStyle = document.createElement('style');
+ appendedStyle.appendChild(document.createTextNode(testCase['append']));
+ document.head.appendChild(appendedStyle);
+ }
+
+ await document.fonts.load('20px/1 custom-font');
+ assert_equals(getComputedStyle(target).width, '80px');
+
+ if (appendedStyle)
+ appendedStyle.remove();
+ documentStyle.remove();
+ }, testCase['title']);
+}
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/css/css-fonts/font-face-unicode-range-no-match-no-download.html b/Tests/LibWeb/Text/input/wpt-import/css/css-fonts/font-face-unicode-range-no-match-no-download.html
new file mode 100644
index 00000000000..fbe9511a3a6
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/css/css-fonts/font-face-unicode-range-no-match-no-download.html
@@ -0,0 +1,27 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>CSS Fonts: unicode-range not matching should not trigger font download</title>
+<link rel="author" title="Vitor Roriz" href="https://github.com/vitorroriz">
+<link rel="help" href="https://www.w3.org/TR/css-fonts-4/#descdef-font-face-unicode-range">
+<link rel="help" href="https://www.w3.org/TR/css-fonts-4/#font-style-matching">
+<meta name="assert" content="A font whose unicode-range does not match any character in the document must not be downloaded (spec: 'User agents must not download or use the font for codepoints outside this set.')">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<style>
+@font-face {
+ font-family: "TestFont";
+ /* Query string makes the URL unique for PerformanceResourceTiming lookup. */
+ src: url("../../fonts/Ahem.ttf?unicode-range-no-match");
+ unicode-range: U+FFFF;
+}
+</style>
+<span style="font-family: TestFont">No characters here are in the unicode-range.</span>
+<script>
+promise_test(function() {
+ return document.fonts.ready.then(function() {
+ var absoluteURL = new URL("../../fonts/Ahem.ttf?unicode-range-no-match", location.href).href;
+ var entries = performance.getEntriesByName(absoluteURL);
+ assert_equals(entries.length, 0, "Font should not be downloaded when unicode-range does not match any document character");
+ });
+}, "Font with non-matching unicode-range must not be downloaded");
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/fonts/noto/noto-sans-v8-latin-regular.woff b/Tests/LibWeb/Text/input/wpt-import/fonts/noto/noto-sans-v8-latin-regular.woff
new file mode 100644
index 00000000000..4f1dd100c09
Binary files /dev/null and b/Tests/LibWeb/Text/input/wpt-import/fonts/noto/noto-sans-v8-latin-regular.woff differ