Truly independent web browser
/*
* Copyright (c) 2018-2025, Andreas Kling <[email protected]>
* Copyright (c) 2021, the SerenityOS developers.
* Copyright (c) 2021-2025, Sam Atkins <[email protected]>
* Copyright (c) 2024, Matthew Olsson <[email protected]>
* Copyright (c) 2025, Callum Law <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "FontComputer.h"
#include <AK/Platform.h>
#include <AK/ScopeGuard.h>
#include <LibGC/RootHashTable.h>
#include <LibGfx/Font/Font.h>
#include <LibGfx/Font/FontDatabase.h>
#include <LibWeb/CSS/Fetch.h>
#include <LibWeb/CSS/FontFaceSet.h>
#include <LibWeb/CSS/FontFaceSnapshot.h>
#include <LibWeb/CSS/FontFaceState.h>
#include <LibWeb/CSS/FontLoading.h>
#include <LibWeb/CSS/FontResolution.h>
#include <LibWeb/CSS/RustFontFeatureValues.h>
#include <LibWeb/CSS/StyleComputer.h>
#include <LibWeb/CSS/StyleSheetState.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/ShadowRoot.h>
#include <LibWeb/Fetch/Response.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/WorkerGlobalScope.h>
#include <LibWeb/Layout/LayoutRustBridge.h>
#include <LibWeb/Layout/NodeArena.h>
#include <LibWeb/Layout/RenderDocument.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Page/RenderingStats.h>
#include <LibWeb/Platform/FontPlugin.h>
#include <LibWeb/SVG/SVGDecodedImageData.h>
namespace Web::CSS {
GC_DEFINE_ALLOCATOR(FontComputer);
GC_DEFINE_ALLOCATOR(FontLoader);
}
namespace AK {
template<>
struct Traits<Web::CSS::FontFeatureValuesCacheKey> : public DefaultTraits<Web::CSS::FontFeatureValuesCacheKey> {
static unsigned hash(Web::CSS::FontFeatureValuesCacheKey const& key) { return key.hash(); }
};
}
namespace Web::CSS {
FontComputer::FontComputer(HTML::EnvironmentSettingsObject& environment_settings_object)
: m_environment_settings_object(environment_settings_object)
, m_font_cascade_memo(FontCascadeMemo::create())
{
}
FontComputer::FontComputer(DOM::Document& document)
: m_document(document)
, m_font_cascade_memo(FontCascadeMemo::create())
{
}
FontComputer::~FontComputer() = default;
FontLoader::FontLoader(FontComputer& font_computer, RuleOrDeclaration rule_or_declaration, Vector<Source> sources, GC::Ptr<GC::Function<void(RefPtr<Gfx::Typeface const>)>> on_load)
: m_font_computer(font_computer)
, m_rule_or_declaration(rule_or_declaration)
, m_sources(move(sources))
{
if (on_load)
m_subscribers.append(*on_load);
}
FontLoader::~FontLoader() = default;
void FontLoader::subscribe(GC::Ref<GC::Function<void(RefPtr<Gfx::Typeface const>)>> callback)
{
if (m_has_completed) {
callback->function()(m_typeface);
return;
}
m_subscribers.append(callback);
}
void FontLoader::visit_edges(Visitor& visitor)
{
Base::visit_edges(visitor);
visitor.visit(m_font_computer);
if (auto* rule = m_rule_or_declaration.value.get_pointer<RuleOrDeclaration::Rule>())
visitor.visit(rule->parent_style_sheet);
else if (auto* block = m_rule_or_declaration.value.get_pointer<RuleOrDeclaration::StyleDeclaration>())
visitor.visit(block->parent_rule);
visitor.visit(m_fetch_controller);
visitor.visit(m_subscribers);
}
bool FontLoader::is_loading() const
{
return m_fetch_controller && !m_typeface;
}
bool FontLoader::may_finish_from_cache() const
{
return !m_fetch_controller || !m_fetch_controller->requires_network();
}
bool FontLoader::has_started_request() const
{
return m_fetch_controller && m_fetch_controller->has_started_request();
}
void FontLoader::did_request_for_rendering()
{
// INTEROP: Delay the document load event til the fetch for this font has settled. Blink, Gecko, and WebKit all
// keep the document from completing while a font load requested for rendering is pending — so pages
// that measure font-dependent geometry in a load-event handler see the loaded font, not a fallback.
if (is_loading() && !m_document_load_event_delayer.has_value() && m_font_computer->has_document())
m_document_load_event_delayer.emplace(m_font_computer->document());
}
void FontLoader::start_loading_next_source()
{
// A loader that has settled must not consume another source: its typeface is final, and fetching a
// further src would replace it after subscribers already saw the settled one. load_font_face()
// hands back an existing loader for a shared source list, so a second FontFace can reach here after
// the first one finished.
if (m_has_completed)
return;
if (m_fetch_controller && m_fetch_controller->state() == Fetch::Infrastructure::FetchController::State::Ongoing)
return;
while (true) {
// https://drafts.csswg.org/css-fonts-4/#src-desc
// NB: Try local names and URLs in source order, continuing after an unavailable face.
while (!m_sources.is_empty() && m_sources.first().has<Utf16FlyString>()) {
auto name = MUST(m_sources.take_first().get<Utf16FlyString>().view().to_utf8());
if (auto typeface = Gfx::FontDatabase::the().get_typeface_by_local_name(name)) {
font_did_load_or_fail(move(typeface));
return;
}
}
if (m_sources.is_empty()) {
font_did_load_or_fail(nullptr);
return;
}
// https://drafts.csswg.org/css-fonts-4/#fetch-a-font
// To fetch a font given a selected <url> url for @font-face rule, fetch url, with ruleOrDeclaration being rule,
// destination "font", CORS mode "cors", and processResponse being the following steps given response res and null,
// failure or a byte stream stream:
m_has_received_font_data = false;
m_fetch_controller = fetch_a_style_resource(m_sources.take_first().get<URL>(), m_rule_or_declaration, Fetch::Infrastructure::Request::Destination::Font, CorsMode::Cors,
GC::create_function(heap(), GC::captures(this), [](FontLoader* loader, GC::Ref<Fetch::Infrastructure::ResponseView>, Fetch::Infrastructure::FetchAlgorithms::BodyBytes stream) {
// 1. If stream is null, return.
// 2. Load a font from stream according to its type.
auto* immutable_bytes = stream.template get_pointer<Core::ImmutableBytes>();
if (!immutable_bytes) {
if (loader->m_sources.is_empty()) {
loader->font_did_load_or_fail(nullptr);
} else {
loader->m_fetch_controller = nullptr;
loader->start_loading_next_source();
}
return;
}
loader->m_has_received_font_data = true;
auto bytes = immutable_bytes->copy_to_byte_buffer().release_value_but_fixme_should_propagate_errors();
if (!requires_off_thread_vector_font_preparation(bytes)) {
auto maybe_typeface = try_load_vector_font(bytes);
if (maybe_typeface.is_error()) {
if (loader->m_sources.is_empty()) {
loader->font_did_load_or_fail(nullptr);
} else {
loader->m_fetch_controller = nullptr;
loader->start_loading_next_source();
}
return;
}
loader->font_did_load_or_fail(maybe_typeface.release_value());
return;
}
auto loader_handle = GC::make_root(GC::Ref(*loader));
prepare_vector_font_data_off_thread(move(bytes), [loader = move(loader_handle)](auto prepared_font_data) mutable {
// NB: The data comes back outside any task, so an SVG image's document isn't the one its shared window
// is associated with anymore. Restore it, so the font load updates and repaints that document.
GC::Ptr<DOM::Document const> document;
if (loader->m_font_computer->has_document())
document = &loader->m_font_computer->document();
auto svg_image_document_scope = SVG::ScopedSVGImageDocument::create_if_needed(document, SVG::ScopedSVGImageDocument::FrameRequests::RouteToCurrentImage);
if (prepared_font_data.is_error()) {
// NB: If we have other sources available, try the next one.
if (loader->m_sources.is_empty()) {
loader->font_did_load_or_fail(nullptr);
} else {
loader->m_fetch_controller = nullptr;
loader->start_loading_next_source();
}
return;
}
auto prepared = prepared_font_data.release_value();
auto maybe_typeface = Gfx::Typeface::try_load_from_anonymous_buffer(move(prepared));
if (maybe_typeface.is_error()) {
if (loader->m_sources.is_empty()) {
loader->font_did_load_or_fail(nullptr);
} else {
loader->m_fetch_controller = nullptr;
loader->start_loading_next_source();
}
return;
}
loader->font_did_load_or_fail(maybe_typeface.release_value()); });
}));
if (m_fetch_controller || m_has_completed)
return;
}
}
void FontLoader::font_did_load_or_fail(RefPtr<Gfx::Typeface const> typeface)
{
if (typeface)
m_typeface = typeface.release_nonnull();
m_has_completed = true;
m_document_load_event_delayer.clear();
// Each subscriber publishes its now-loaded FontFace to FontComputer. The face's complete
// descriptors are needed to compare the old and new selections, so invalidation happens there.
for (auto& callback : m_subscribers)
callback->function()(m_typeface);
m_subscribers.clear();
m_fetch_controller = nullptr;
}
void FontComputer::visit_edges(Visitor& visitor)
{
Base::visit_edges(visitor);
visitor.visit(m_document);
visitor.visit(m_environment_settings_object);
for (auto& [_, faces] : m_font_faces)
visitor.visit(faces);
for (auto& [_, loader] : m_loaders_by_source)
visitor.visit(loader);
}
static void for_each_nested_font_rule(Parser::ValueParserFFI::NativeRuleList const* rules, Function<void(RustRuleView const&)> const& callback)
{
Parser::ValueParserFFI::rust_rule_list_visit_font_rules(rules, &callback, [](void const* context, Parser::ValueParserFFI::NativeRuleView const* rule) {
(*static_cast<Function<void(RustRuleView const&)> const*>(context))(RustRuleView { *rule });
});
}
static void append_font_feature_values(StyleScope const& style_scope, Utf16FlyString const& family_name, FontFeatureValues& font_feature_values)
{
// https://drafts.csswg.org/css-fonts/#font-feature-values-syntax
// For each <family-name> in the @font-feature-values prelude, each font feature value declaration defines a
// mapping between a (family name, feature block name, declaration name) tuple and the list of one or more
// integers from the declaration’s value. If the same tuple appears more than once in a document (such as if a
// single block), the last-defined one is used.
// FIXME: We only account for Author stylesheets here, we should also account for UserAgent and User
style_scope.for_each_active_css_style_sheet([&](CSS::StyleSheetState const& sheet) {
sheet.for_each_effective_rule_data(TraversalOrder::Preorder, [&](RustRuleView const& rule, Utf16View) {
if (rule.type() != RustRule::Type::FontFeatureValues)
return;
auto values = rule.font_feature_values();
bool matches_family = false;
for (size_t index = 0; index < values.family_count(); ++index) {
if (values.family_at(index) == family_name.view()) {
matches_family = true;
break;
}
}
if (!matches_family)
return;
// NB: We don't include historical-forms since it can't be referenced - it seems like it's inclusion in the syntax
// for @font-feature-values was a mistake and isn't supported by Chrome or Firefox. See
// https://github.com/w3c/csswg-drafts/issues/9926#issuecomment-2017241274
for (auto kind : { FontFeatureValuesRuleKind::Annotation, FontFeatureValuesRuleKind::Ornaments, FontFeatureValuesRuleKind::Stylistic, FontFeatureValuesRuleKind::Swash, FontFeatureValuesRuleKind::CharacterVariant, FontFeatureValuesRuleKind::Styleset }) {
values.for_each_entry(kind, [&](auto key, auto values) {
Vector<u32> copy;
copy.append(values.data(), values.size());
font_feature_values.set({ kind, Utf16FlyString::from_utf16(key) }, move(copy));
});
}
});
});
}
FontFeatureValues FontComputer::font_feature_values_in_scope(Utf16FlyString const& family_name, TreeScopeID tree_scope) const
{
FontFeatureValues font_feature_values;
if (!m_document)
return font_feature_values;
if (tree_scope == TreeScopeID {}) {
append_font_feature_values(m_document->style_scope(), family_name, font_feature_values);
return font_feature_values;
}
// https://drafts.csswg.org/css-scoping/#shadow-names
// Feature value names are global tree-scoped names: a shadow tree sees the names of the tree its host is in,
// and its own declarations take precedence over them.
auto const* scope_root = m_document->style_computer().shadow_root_for_tree_scope(tree_scope);
if (!scope_root)
return font_feature_values;
if (auto const* host = scope_root->host())
font_feature_values = font_feature_values_for_family(family_name, host->style_scope().style_engine_tree_scope());
append_font_feature_values(scope_root->style_scope(), family_name, font_feature_values);
return font_feature_values;
}
NonnullRefPtr<FontFeatureValuesByScope const> FontComputer::font_feature_values_by_scope() const
{
if (m_font_feature_values_by_scope)
return *m_font_feature_values_by_scope;
auto by_scope = adopt_ref(*new FontFeatureValuesByScope);
HashTable<Utf16FlyString> families;
auto declares_any = [&](StyleScope const& style_scope) {
bool declares = false;
style_scope.for_each_active_css_style_sheet([&](CSS::StyleSheetState const& sheet) {
for_each_nested_font_rule(sheet.native_rules().handle(), [&](RustRuleView const& rule) {
if (rule.type() != RustRule::Type::FontFeatureValues)
return;
declares = true;
auto values = rule.font_feature_values();
for (size_t index = 0; index < values.family_count(); ++index)
families.set(Utf16FlyString::from_utf16(values.family_at(index)));
});
});
return declares;
};
if (m_document) {
declares_any(m_document->style_scope());
m_document->style_computer().for_each_shadow_root([&](DOM::ShadowRoot& shadow_root) {
if (declares_any(shadow_root.style_scope()))
by_scope->shadow_scopes.append(shadow_root.style_engine_tree_scope());
});
}
auto add_scope = [&](TreeScopeID tree_scope) {
auto& scope = by_scope->scopes.ensure(tree_scope);
for (auto const& family : families) {
if (auto const& values = font_feature_values_for_family(family, tree_scope); !values.is_empty())
scope.set(family, values);
}
};
add_scope({});
for (auto tree_scope : by_scope->shadow_scopes)
add_scope(tree_scope);
m_font_feature_values_by_scope = by_scope;
return by_scope;
}
Function<FontFeatureValues const&(Utf16FlyString const&)> FontComputer::font_feature_values_provider(TreeScopeID tree_scope) const
{
return [this, tree_scope](Utf16FlyString const& family_name) -> FontFeatureValues const& {
return font_feature_values_for_family(family_name, tree_scope);
};
}
FontFeatureValues const& FontComputer::font_feature_values_for_family(Utf16FlyString const& family_name, TreeScopeID tree_scope) const
{
FontFeatureValuesCacheKey key { tree_scope, family_name };
if (auto it = m_font_feature_values_cache.find(key); it != m_font_feature_values_cache.end())
return it->value;
// NB: Building a shadow tree's values reads its host tree's through this cache, so the entry is set only after.
auto font_feature_values = font_feature_values_in_scope(family_name, tree_scope);
return m_font_feature_values_cache.ensure(move(key), [&] { return move(font_feature_values); });
}
Gfx::Font const& FontComputer::initial_font()
{
// FIXME: This is not correct.
static auto const& font = Platform::FontPlugin::the().default_font(12).release_nonnull().leak_ref();
return font;
}
static bool computed_font_families_reference_any_family(ReadonlySpan<ComputedFontFamily const> font_families, Vector<Utf16FlyString> const& family_names)
{
return any_of(font_families, [&](ComputedFontFamily const& family) {
return family.has<ComputedFontFamilyName>()
&& any_of(family_names, [&](auto const& family_name) { return family.get<ComputedFontFamilyName>().name.equals_ignoring_ascii_case(family_name); });
});
}
void FontComputer::clear_computed_font_cache(Utf16FlyString const& family_name)
{
Vector<Utf16FlyString> family_names;
family_names.append(family_name);
bump_environment_generation();
m_font_cascade_memo->forget_matching(m_environment_generation, [&](auto const& key, auto const&) {
return computed_font_families_reference_any_family(key.font_families, family_names);
});
record_font_input_changes(family_names, {});
}
void FontComputer::invalidate_changed_font_cascades(Vector<Utf16FlyString> const& family_names)
{
VERIFY(!family_names.is_empty());
bump_environment_generation();
// NB: Font-face changes can leave a selection unchanged, including its pending subsets. Compare the frozen
// selections before retiring cascades or invalidating their users.
Vector<Gfx::FontCascadeList const*> invalidated_font_lists;
Vector<LoadedFaceFill> loaded_face_fills;
RefPtr<FontFaceSnapshot const> snapshot;
m_font_cascade_memo->forget_matching(m_environment_generation, [&](auto const& key, auto const& font_list) {
if (!computed_font_families_reference_any_family(key.font_families, family_names))
return false;
if (!snapshot)
snapshot = font_face_snapshot();
auto updated_font_list = resolve_font_cascade(*snapshot, key, font_feature_values_provider(key.font_feature_values_scope));
if (font_list->equals(*updated_font_list))
return false;
// NB: A face that finished its load fills in where the cascade waited on it, as a font fallback list resolves
// a loaded face in place: the cascade stays the memo's answer, and the styles naming it stay.
if (m_document && font_list->fills_toward(*updated_font_list)) {
loaded_face_fills.append({ font_list, move(updated_font_list) });
return false;
}
invalidated_font_lists.append(font_list.ptr());
return true;
});
if (!loaded_face_fills.is_empty())
fill_loaded_font_faces(move(loaded_face_fills));
if (!invalidated_font_lists.is_empty() && m_document)
record_font_input_changes({}, invalidated_font_lists);
}
// Has the style engine record an input change for every element whose style uses a font that resolves differently
// now: one whose font-family names one of the families, or whose cascade is one of the font lists. Beside a style
// transaction that flew, the elements are found once its drain has installed the styles it computed.
void FontComputer::record_font_input_changes(ReadonlySpan<Utf16FlyString> family_names, ReadonlySpan<Gfx::FontCascadeList const*> font_lists)
{
if (document().has_flown_style_update()) {
m_font_families_changed_beside_flown_transaction.append(family_names.data(), family_names.size());
m_font_lists_changed_beside_flown_transaction.append(font_lists.data(), font_lists.size());
return;
}
Vector<u32> family_name_lengths;
Vector<u16> family_name_units;
family_name_lengths.ensure_capacity(family_names.size());
for (auto const& family_name : family_names) {
family_name_lengths.unchecked_append(family_name.length_in_code_units());
for (size_t index = 0; index < family_name.length_in_code_units(); ++index)
family_name_units.append(family_name.code_unit_at(index));
}
// NB: The engine compares the lists by address only: a record that holds a list keeps it alive.
Vector<u64> font_list_addresses;
font_list_addresses.ensure_capacity(font_lists.size());
for (auto const* font_list : font_lists)
font_list_addresses.unchecked_append(bit_cast<FlatPtr>(font_list));
prepare_font_style_inputs();
StyleEngineFFI::style_engine_record_font_input_changes(document().style_computer().style_engine().host(), family_name_lengths, family_name_units, font_list_addresses);
}
// These are style inputs like any other: the transaction a geometry read deferred is flushed before them, and the first
// one asks for a frame.
void FontComputer::prepare_font_style_inputs()
{
auto& style_engine = document().style_computer().style_engine();
if (style_engine.may_have_deferred_geometry_transaction())
document().flush_deferred_style_change_event();
if (!style_engine.has_recorded_input()) {
set_rendering_pending(document(), RenderingPendingReason::NeedsRenderingUpdate, 1);
document().page().client().request_frame();
}
}
// Fills the faces that loaded into the cascades that waited on them. The style engine fills the frozen cascades in, in
// order with the other changes to the document's render state, and computes again only the styles that read the
// metrics of a filled cascade's first available font; every other style keeps its record, and the boxes whose text a
// filled cascade renders lay out again.
void FontComputer::fill_loaded_font_faces(Vector<LoadedFaceFill> fills)
{
if (document().has_flown_style_update()) {
m_loaded_face_fills_beside_flown_transaction.extend(move(fills));
return;
}
// NB: Each filled cascade is followed by the cascade it fills toward, which the engine reads during the call.
Vector<u64> font_list_addresses;
font_list_addresses.ensure_capacity(fills.size() * 2);
for (auto const& fill : fills) {
font_list_addresses.unchecked_append(bit_cast<FlatPtr>(fill.font_list.ptr()));
font_list_addresses.unchecked_append(bit_cast<FlatPtr>(fill.resolved.ptr()));
}
prepare_font_style_inputs();
StyleEngineFFI::style_engine_fill_loaded_font_faces(document().style_computer().style_engine().host(), font_list_addresses);
Vector<u64> filled_font_lists;
filled_font_lists.ensure_capacity(fills.size());
for (auto const& fill : fills)
filled_font_lists.unchecked_append(bit_cast<FlatPtr>(fill.font_list.ptr()));
Layout::RustFFI::render_state_relayout_users_of_font_lists(document().layout_node_arena().host(), filled_font_lists);
}
void FontComputer::take_in_resolutions_against_older_tables()
{
// A style pass resolved fonts against the table the engine was last given, where a change since made that older
// than the memo, into cascades the memo does not hold. The memo takes in the ones that answer the same now, where
// it holds none for their requests; the elements holding any other, which answers differently now, waits on a
// face the memo would no longer find it waiting on, or is not the cascade the memo names for the request, are
// found here.
auto resolutions = m_font_cascade_memo->take_resolutions_against_older_tables();
Vector<Gfx::FontCascadeList const*> font_lists;
for (auto const& resolution : resolutions) {
if (!m_font_cascade_memo->adopt_resolution_against_older_table(*font_face_snapshot(), resolution, font_feature_values_provider(resolution.key.font_feature_values_scope)))
font_lists.append(resolution.font_list.ptr());
}
if (!font_lists.is_empty())
record_font_input_changes({}, font_lists);
}
void FontComputer::did_end_flown_style_drain()
{
take_in_resolutions_against_older_tables();
auto loaded_face_fills = move(m_loaded_face_fills_beside_flown_transaction);
if (!loaded_face_fills.is_empty())
fill_loaded_font_faces(move(loaded_face_fills));
auto family_names = move(m_font_families_changed_beside_flown_transaction);
auto font_lists = move(m_font_lists_changed_beside_flown_transaction);
if (!family_names.is_empty() || !font_lists.is_empty())
record_font_input_changes(family_names, font_lists);
}
// Every change to what a font resolution would answer passes through here. Nothing else may touch
// m_environment_generation.
void FontComputer::bump_environment_generation()
{
++m_environment_generation;
m_font_face_snapshot = nullptr;
}
NonnullRefPtr<FontFaceSnapshot const> FontComputer::font_face_snapshot() const
{
if (m_font_face_snapshot)
return *m_font_face_snapshot;
FontFaceSnapshot::Table table;
table.ensure_capacity(m_font_faces.size());
for (auto const& [key, faces] : m_font_faces) {
Vector<FontFaceSnapshot::Face> snapshot_faces;
snapshot_faces.ensure_capacity(faces.size());
// 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(),
.rendering_typeface = face->rendering_typeface(),
.rendering_state = face->rendering_state_without_requesting(),
.unicode_ranges = face->unicode_ranges(),
.size_adjust = face->size_adjust(),
.has_urls = face->has_urls(),
.is_unusable = face->is_unusable_for_rendering(),
.has_non_default_unicode_range = face->has_non_default_unicode_range(),
.weight_descriptor_is_auto = face->weight_descriptor_is_auto(),
});
}
table.set(key, move(snapshot_faces));
}
m_font_face_snapshot = FontFaceSnapshot::create(m_environment_generation, move(table), font_feature_values_by_scope());
return *m_font_face_snapshot;
}
void FontComputer::clear_font_feature_values_cache(Utf16FlyString const& family_name)
{
m_font_feature_values_cache.remove_all_matching([&](auto const& key, auto const&) { return key.family_name == family_name; });
m_font_feature_values_by_scope = nullptr;
}
bool FontComputer::should_defer_initial_paint()
{
if (m_has_completed_initial_paint)
return false;
bool has_pending_fonts = false;
// OPTIMIZATION: Finish cache lookups and decode cache-resident fonts before the first paint. A cache miss
// releases this wait before any network activity; subsequent paints use the font display timeline.
for (auto const& entry : m_font_faces) {
for (auto const& face : entry.value) {
if (face->is_pending_rendering_from_cache())
return true;
has_pending_fonts |= face->has_pending_rendering();
}
}
m_initial_paint_had_pending_fonts = has_pending_fonts;
m_has_completed_initial_paint = true;
return false;
}
void FontComputer::did_load_font(Utf16FlyString const& family_name)
{
if (m_font_face_change_batch_depth > 0) {
if (!any_of(m_batched_font_face_change_families, [&](auto const& existing_family_name) { return existing_family_name.equals_ignoring_ascii_case(family_name); }))
m_batched_font_face_change_families.append(family_name);
return;
}
Vector<Utf16FlyString> family_names;
family_names.append(family_name);
invalidate_changed_font_cascades(family_names);
}
void FontComputer::did_load_font(FontFaceKey const& changed_face)
{
did_load_font(changed_face.family_name);
}
void FontComputer::begin_font_face_change_batch()
{
++m_font_face_change_batch_depth;
}
void FontComputer::end_font_face_change_batch()
{
VERIFY(m_font_face_change_batch_depth > 0);
--m_font_face_change_batch_depth;
if (m_font_face_change_batch_depth > 0 || m_batched_font_face_change_families.is_empty())
return;
invalidate_changed_font_cascades(m_batched_font_face_change_families);
m_batched_font_face_change_families.clear();
}
void FontComputer::register_font_face(NonnullRefPtr<FontFaceState> face)
{
VERIFY(face->should_be_registered_with_font_computer());
auto key = face->matching_key();
auto& faces = m_font_faces.ensure(key);
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);
}
void FontComputer::unregister_font_face(NonnullRefPtr<FontFaceState> face)
{
VERIFY(face->should_be_registered_with_font_computer());
auto key = face->matching_key();
if (auto it = m_font_faces.find(key); it != m_font_faces.end()) {
it->value.remove_all_matching([&](auto const& entry) { return entry == face; });
if (it->value.is_empty())
m_font_faces.remove(it);
}
did_load_font(key);
}
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))
ordered_faces.append(font_face);
}
for (auto& font_face : entry.value) {
if (!ordered_faces.contains_slow(font_face))
ordered_faces.append(font_face);
}
bool order_changed = ordered_faces.size() != entry.value.size();
if (!order_changed) {
for (size_t index = 0; index < entry.value.size(); ++index) {
if (ordered_faces[index] != entry.value[index]) {
order_changed = true;
break;
}
}
}
if (!order_changed)
continue;
entry.value = move(ordered_faces);
did_load_font(entry.key.family_name);
}
}
GC::Ptr<FontLoader> FontComputer::load_font_face(ReadonlySpan<FontLoader::Source> sources, RefPtr<StyleSheetState> parent_style_sheet, GC::Ptr<GC::Function<void(RefPtr<Gfx::Typeface const>)>> on_load)
{
if (sources.is_empty()) {
if (on_load)
on_load->function()({});
return {};
}
RuleOrDeclaration rule_or_declaration {
.environment_settings_object = m_document ? m_document->relevant_settings_object() : *m_environment_settings_object,
.value = RuleOrDeclaration::Rule {
.parent_style_sheet = parent_style_sheet,
},
.style_resource_base_url = {},
.parent_style_sheet_origin_clean = {},
};
// NB: Identical source text can resolve to different URLs in style sheets with different base URLs.
auto url_source_key = [&](URL const& url) {
if (auto resolved_url = resolve_a_style_resource_url(url, rule_or_declaration); resolved_url.has_value())
return URL { resolved_url->serialize(), url.type(), url.request_url_modifiers() }.to_string();
return url.to_string();
};
StringBuilder key_builder;
if (parent_style_sheet && any_of(sources, [](auto const& source) { return source.template has<URL>(); })) {
// NB: Font fetching uses the sheet's base URL as its referrer, and may inherit its response's referrer policy.
// Equal resolved URLs must not reuse a loader that fetches with another sheet's request context.
auto referrer = style_resource_base_url(rule_or_declaration).serialize();
auto policy = parent_style_sheet->fetched_referrer_policy().value_or(ReferrerPolicy::ReferrerPolicy::EmptyString);
key_builder.appendff("r{}:{}p{};", referrer.bytes_as_string_view().length(), referrer, to_underlying(policy));
}
for (auto const& source : sources) {
auto value = source.has<URL>()
? url_source_key(source.get<URL>())
: MUST(source.get<Utf16FlyString>().view().to_utf8());
key_builder.appendff("{}{}:{}", source.has<URL>() ? 'u' : 'l', value.bytes_as_string_view().length(), value);
}
auto key = MUST(key_builder.to_string());
if (auto it = m_loaders_by_source.find(key); it != m_loaders_by_source.end()) {
// NB: A loader that has settled answers a new subscriber at once, which can load further faces and so add to
// the map, so nothing of the map is read past this.
GC::Ref<FontLoader> loader = *it->value;
if (on_load)
loader->subscribe(*on_load);
return loader;
}
auto loader = GC::Heap::the().allocate<FontLoader>(*this, rule_or_declaration, Vector<FontLoader::Source> { sources }, move(on_load));
m_loaders_by_source.set(move(key), loader);
return loader;
}
void FontComputer::forget_font_feature_values_declared_by(RustRuleView const& rule)
{
auto values = rule.font_feature_values();
for (size_t index = 0; index < values.family_count(); ++index) {
auto family = Utf16FlyString::from_utf16(values.family_at(index));
clear_computed_font_cache(family);
clear_font_feature_values_cache(family);
}
}
void FontComputer::forget_font_feature_values_declared_in(StyleSheetState const& sheet)
{
for_each_nested_font_rule(sheet.native_rules().handle(), [this](RustRuleView const& rule) {
if (rule.type() == RustRule::Type::FontFeatureValues)
forget_font_feature_values_declared_by(rule);
});
}
void FontComputer::load_fonts_from_sheet(StyleSheetState& sheet)
{
begin_font_face_change_batch();
ScopeGuard finish_font_face_change_batch = [&] {
end_font_face_change_batch();
};
HashTable<u64> effective_font_rules;
bool ancestors_match = true;
for (auto* ancestor = &sheet; ancestor; ancestor = ancestor->parent_style_sheet()) {
if (ancestor->disabled() || !ancestor->native_media_list().matches()) {
ancestors_match = false;
break;
}
}
if (ancestors_match) {
sheet.for_each_effective_rule_data(TraversalOrder::Preorder, [&](RustRuleView const& rule, Utf16View) {
// Only this sheet's rules are connected below. Imported sheets synchronize separately.
if (rule.type() == RustRule::Type::FontFace)
effective_font_rules.set(rule.identity());
});
}
for_each_nested_font_rule(sheet.native_rules().handle(), [&](RustRuleView const& rule) {
if (rule.type() == RustRule::Type::FontFace) {
auto descriptors = rule.descriptors();
auto should_be_css_connected = effective_font_rules.contains(rule.identity())
&& descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::FontFamily))
&& descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::Src));
auto connected_font_face = sheet.css_connected_font_face(rule.identity());
if (!should_be_css_connected) {
if (connected_font_face)
connected_font_face->disconnect_from_css_rule();
return;
}
if (connected_font_face)
return;
// https://drafts.csswg.org/css-font-loading/#font-face-css-connection
// A CSS @font-face rule automatically defines a corresponding FontFace object, which is automatically
// placed in the document's font source when the rule is parsed. This FontFace object is CSS-connected.
auto font_face = FontFaceState::create_css_connected(HTML::relevant_realm(document()), rule.identity(), sheet);
document().fonts()->add_css_connected_font(font_face);
}
});
document().fonts()->synchronize_css_connected_font_order();
}
void FontComputer::unload_fonts_from_sheet(StyleSheetState& sheet)
{
begin_font_face_change_batch();
ScopeGuard finish_font_face_change_batch = [&] {
end_font_face_change_batch();
};
// https://drafts.csswg.org/css-font-loading/#font-face-css-connection
// If a @font-face rule is removed from the document, its connected FontFace object is no longer CSS-connected.
for_each_nested_font_rule(sheet.native_rules().handle(), [&](RustRuleView const& rule) {
if (rule.type() == RustRule::Type::FontFace) {
if (auto font_face = sheet.css_connected_font_face(rule.identity()))
font_face->disconnect_from_css_rule();
}
});
}
Optional<FontComputer&> font_computer_for_font_source(JS::Object& global)
{
if (auto* window = HTML::window_from_global_object(global))
return window->associated_document().font_computer();
if (auto* worker_global_scope = Bindings::worker_global_scope_from_global_object(global))
return worker_global_scope->font_computer();
return {};
}
}