Truly independent web browser
LibGfx: Let loads fill pending faces into frozen font cascades
Andreas Kling7948f5f54a3a
diff --git a/Libraries/LibGfx/Font/SharedFontProvider.cpp b/Libraries/LibGfx/Font/SharedFontProvider.cppindex 1894c2ed56f..5a8ba4c2927 100644--- a/Libraries/LibGfx/Font/SharedFontProvider.cpp+++ b/Libraries/LibGfx/Font/SharedFontProvider.cpp@@ -228,7 +228,17 @@ RefPtr<Typeface> SharedFontProvider::load_brokered_font(BrokeredFont brokered_foif (auto cached = m_typeface_cache.get(brokered_font.face_id); cached.has_value())return *cached;return brokered_font.source.visit(- [](Empty) -> RefPtr<Typeface> { return nullptr; },+ [&](Empty) -> RefPtr<Typeface> {+ // A match names a face the provider does not hold yet, which it opens.+ if (m_failed_face_ids.contains(brokered_font.face_id) || !m_callbacks.open_font)+ return nullptr;+ auto opened = m_callbacks.open_font(m_catalog->generation(), brokered_font.face_id);+ if (opened.face_id != brokered_font.face_id || opened.source.has<Empty>()) {+ m_failed_face_ids.set(brokered_font.face_id);+ return nullptr;+ }+ return load_brokered_font(move(opened));+ },[&](BrokeredFontFile& font_file) { return load_font_file(brokered_font.face_id, font_file.ttc_index, font_file.format, move(font_file.file)); },[&](PlatformFontName const& name) { return load_platform_font(brokered_font.face_id, name); });}diff --git a/Libraries/LibGfx/FontCascadeList.cpp b/Libraries/LibGfx/FontCascadeList.cppindex f8a755b748c..48db9e46583 100644--- a/Libraries/LibGfx/FontCascadeList.cpp+++ b/Libraries/LibGfx/FontCascadeList.cpp@@ -18,6 +18,7 @@ void ladybird_gfx_frozen_font_list_release(void const* frozen);void const* ladybird_gfx_frozen_font_list_font_for_code_point(void const* frozen, u32 code_point, bool is_emoji, bool forced);size_t ladybird_gfx_request_wanted_pending_faces();bool ladybird_gfx_frozen_font_lists_equal(void const*, void const*);+bool ladybird_gfx_font_cascade_list_fills_toward(void const*, void const*);}namespace Gfx {@@ -308,7 +309,7 @@ Gfx::Font const& FontCascadeList::font_for_code_point(u32 code_point, EmojiPrese}if (m_system_font_fallback_callback) {- if (auto fallback = m_system_font_fallback_callback(code_point, emoji_presentation.presentation, first())) {+ if (auto fallback = m_system_font_fallback_callback(code_point, emoji_presentation.presentation, m_system_fallback_request)) {if (presentation_matches(*fallback) || (!author_glyph_match && !fallback_glyph_match)) {auto const& fallback_font = *fallback;m_retained_system_fallback_fonts.set(fallback.release_nonnull());@@ -403,6 +404,12 @@ bool FontCascadeList::equals(FontCascadeList const& other) constreturn true;}+bool FontCascadeList::fills_toward(FontCascadeList const& resolved) const+{+ VERIFY(m_frozen_list && resolved.m_frozen_list);+ return ladybird_gfx_font_cascade_list_fills_toward(this, &resolved);+}+}namespace Gfx::FFI {@@ -540,13 +547,13 @@ extern "C" void const* ladybird_gfx_cascade_snapshot_begin(void const* list).last_resort_font = cascade_list.last_resort_font(),.has_system_fallback = cascade_list.has_system_font_fallback_callback(),};- if (snapshot->has_system_fallback && !cascade_list.is_empty()) {- // The system fallback matches against the cascade's first font, exactly as the lookup does.- auto const& reference_font = cascade_list.first();- snapshot->system_fallback_point_size = reference_font.point_size();- snapshot->system_fallback_weight = static_cast<u16>(reference_font.weight());- snapshot->system_fallback_width = reference_font.width();- snapshot->system_fallback_slope = static_cast<u8>(reference_font.slope());+ if (snapshot->has_system_fallback) {+ // The system fallback matches against the cascade's request, exactly as the lookup does.+ auto const& request = cascade_list.system_fallback_request();+ snapshot->system_fallback_point_size = request.point_size;+ snapshot->system_fallback_weight = request.weight;+ snapshot->system_fallback_width = request.width;+ snapshot->system_fallback_slope = request.slope;}return snapshot;}diff --git a/Libraries/LibGfx/FontCascadeList.h b/Libraries/LibGfx/FontCascadeList.hindex cc42546ea89..21db5bf7042 100644--- a/Libraries/LibGfx/FontCascadeList.h+++ b/Libraries/LibGfx/FontCascadeList.h@@ -52,7 +52,15 @@ size_t request_wanted_pending_faces();class FontCascadeList : public AtomicRefCounted<FontCascadeList> {public:- using SystemFontFallbackCallback = Function<RefPtr<Font const>(u32, EmojiPresentation, Font const&)>;+ // The style a cascade asks the system fallback for, which the cascade's request decides rather than its fonts, so a+ // face finishing its load does not move it.+ struct SystemFallbackRequest {+ float point_size { 0 };+ u16 weight { 0 };+ u16 width { 0 };+ u8 slope { 0 };+ };+ using SystemFontFallbackCallback = Function<RefPtr<Font const>(u32, EmojiPresentation, SystemFallbackRequest const&)>;static NonnullRefPtr<FontCascadeList> create(){@@ -87,6 +95,10 @@ public:bool equals(FontCascadeList const& other) const;+ // Whether loads of the faces this cascade waits on are all that tells it apart from `resolved`, so filling them+ // in makes its frozen list select as that of `resolved` does. Both cascades must have been frozen.+ bool fills_toward(FontCascadeList const& resolved) const;+// One entry of the cascade, flattened into the order font_for_code_point() visits it.struct SnapshotEntry {// The font to use, or null for a pending face that has not produced one yet.@@ -178,7 +190,12 @@ public:m_first_available_font_cache = nullptr;m_last_resort_font = move(font);}- void set_system_font_fallback_callback(SystemFontFallbackCallback callback) { m_system_font_fallback_callback = move(callback); }+ void set_system_font_fallback_callback(SystemFallbackRequest request, SystemFontFallbackCallback callback)+ {+ m_system_fallback_request = request;+ m_system_font_fallback_callback = move(callback);+ }+ [[nodiscard]] SystemFallbackRequest const& system_fallback_request() const { return m_system_fallback_request; }~FontCascadeList();@@ -195,6 +212,7 @@ private:};Vector<PendingEntry> m_pending_faces;mutable HashMap<Font const*, NonnullRefPtr<Font>> m_invisible_fonts;+ SystemFallbackRequest m_system_fallback_request;SystemFontFallbackCallback m_system_font_fallback_callback;// OPTIMIZATION: Cache of resolved fonts for ASCII code points. Since m_fonts only grows and the cascade returnsdiff --git a/Libraries/LibGfx/Rust/src/font.rs b/Libraries/LibGfx/Rust/src/font.rsindex 398e6a2df2f..7a39f47f6fe 100644--- a/Libraries/LibGfx/Rust/src/font.rs+++ b/Libraries/LibGfx/Rust/src/font.rs@@ -491,6 +491,20 @@ struct FrozenEntry {/// Set once a render pass has wanted this face, so the document requests its load only once/// per frozen cascade.wanted: std::sync::atomic::AtomicBool,+ /// The font a pending face's load filled in, after which the entry selects exactly as a loaded+ /// face's would. A cascade keeps its identity across the load, so the styles naming it stay+ /// the same and only what reads its fonts runs again.+ loaded: std::sync::OnceLock<FontHandle>,+}++/// An entry as it selects now: its own font or the one a load filled in, and whether it still+/// waits on a load.+#[derive(Clone, Copy)]+struct EntrySelection<'a> {+ font: Option<&'a FontHandle>,+ pending: Option<(u64, PendingFontState)>,+ source_face_id: u64,+ ranges: &'a [UnicodeRange],}/// How this cascade asks for a font no listed family covers.@@ -502,6 +516,67 @@ struct SystemFallbackStyle {slope: u8,}+/// The index of the first entry with a font and the ASCII code points it resolves, where one does.+type FirstFontAsciiCodePoints = Option<(usize, u128)>;++/// OPTIMIZATION: What text chunking asks of a cascade every time it starts, remembered for a fill generation without a+/// lock. The answer takes more than one word, so its header says when the words after it are being+/// written, and a read that finds the header moved under it counts as a miss. Only one thread at a time+/// writes; another keeps the answer it computed to itself.+#[derive(Default)]+struct FirstFontAsciiCodePointsMemo {+ /// The fill generation in the high half, and in the low half the bits below with the index of the entry.+ header: std::sync::atomic::AtomicU64,+ code_points: [std::sync::atomic::AtomicU64; 2],+}++impl FirstFontAsciiCodePointsMemo {+ const ANSWERED: u64 = 1 << 31;+ const WRITING: u64 = 1 << 30;+ const HAS_FIRST_FONT: u64 = 1 << 29;+ const ENTRY_INDEX_MASK: u64 = Self::HAS_FIRST_FONT - 1;++ fn answer_at(&self, generation: u32) -> Option<FirstFontAsciiCodePoints> {+ use std::sync::atomic::{Ordering, fence};+ let header = self.header.load(Ordering::Acquire);+ if header & (Self::ANSWERED | Self::WRITING) != Self::ANSWERED || (header >> 32) as u32 != generation {+ return None;+ }+ if header & Self::HAS_FIRST_FONT == 0 {+ return Some(None);+ }+ let low = self.code_points[0].load(Ordering::Relaxed);+ let high = self.code_points[1].load(Ordering::Relaxed);+ fence(Ordering::Acquire);+ if self.header.load(Ordering::Relaxed) != header {+ return None;+ }+ let index = (header & Self::ENTRY_INDEX_MASK) as usize;+ Some(Some((index, (u128::from(high) << 64) | u128::from(low))))+ }++ fn remember(&self, generation: u32, answer: FirstFontAsciiCodePoints) {+ use std::sync::atomic::{Ordering, fence};+ let header = self.header.load(Ordering::Relaxed);+ if header & Self::WRITING != 0+ || self+ .header+ .compare_exchange(header, header | Self::WRITING, Ordering::Acquire, Ordering::Relaxed)+ .is_err()+ {+ return;+ }+ fence(Ordering::Release);+ let mut new_header = (u64::from(generation) << 32) | Self::ANSWERED;+ if let Some((index, code_points)) = answer {+ new_header |= Self::HAS_FIRST_FONT | (index as u64 & Self::ENTRY_INDEX_MASK);+ self.code_points[0].store(code_points as u64, Ordering::Relaxed);+ self.code_points[1].store((code_points >> 64) as u64, Ordering::Relaxed);+ }+ self.header.store(new_header, Ordering::Release);+ }+}+/// A cascade list frozen at the moment the document published it: no caches to fill, no faces to/// resolve, nothing to ask the document. Everything a render pass needs to pick a font for a code/// point is here, and everything it decides that the document must act on is a number it leaves@@ -516,15 +591,34 @@ pub struct FrozenFontList {/// Every font reachable without asking the system-fallback service, so an ASCII answer can be/// remembered as an index rather than as a pointer.fonts: Box<[FontHandle]>,- /// OPTIMIZATION: The list is immutable, so an answer for a code point is the same answer- /// forever; a racing write stores the value the other thread computed.- ascii_cache: [std::sync::atomic::AtomicU32; 128],- ascii_code_points_resolved_by_first_font: std::sync::OnceLock<Option<(usize, u128)>>,+ /// OPTIMIZATION: An answer for a code point is the same answer until a load fills a face in, so+ /// each is remembered with the fill generation it was found at; a racing write+ /// stores the value the other thread computed.+ ascii_cache: [std::sync::atomic::AtomicU64; 128],+ /// The first font with a face and the ASCII code points it resolves.+ ascii_code_points_resolved_by_first_font: FirstFontAsciiCodePointsMemo,/// https://drafts.csswg.org/css-fonts-4/#invisible-fallback/// Built on demand, and only for a cascade that has a face in its block period.invisible_variants: std::sync::Mutex<std::collections::HashMap<FontId, FontHandle>>,+ /// The first available font, as an ASCII cache answer is remembered.+ first_available: std::sync::atomic::AtomicU64,+ /// How many times loads filled pending faces in, so a memo of what the cascade answered can+ /// tell an answer from before a fill.+ fill_generation: std::sync::atomic::AtomicU32,}+/// The pending faces of a frozen cascade that loads filled in, each with the font it now selects:+/// what a cascade resolved against the newer @font-face table answers in their places. Made where+/// both cascades are live, and applied wherever the cascade's readers expect its change.+pub struct FrozenFontFills {+ list: Arc<FrozenFontList>,+ fills: Vec<(usize, FontHandle)>,+}++/// A cached answer naming the font a load filled into an entry, by the entry's index, rather than+/// one of [`FrozenFontList::fonts`].+const CACHED_FILLED_ENTRY: u32 = 1 << 31;+const _: () = {const fn assert_send_and_sync<T: Send + Sync>() {}assert_send_and_sync::<FrozenFontList>();@@ -553,6 +647,121 @@ impl FrozenEntry {.iter().any(|range| range.contains(code_point))}++ /// The font the entry selects with: its own, or the one a load filled in.+ fn font(&self) -> Option<&FontHandle> {+ self.font.as_ref().or_else(|| self.loaded.get())+ }++ /// The face's load state while it still waits on its load.+ fn pending(&self) -> Option<(u64, PendingFontState)> {+ self.pending.filter(|_| self.loaded.get().is_none())+ }++ /// Whether the entry waits on a load with no font to select yet, which a fill can change.+ fn awaits_fill(&self) -> bool {+ self.font.is_none() && self.pending().is_some()+ }++ fn selection<'a>(&'a self, ranges: &'a [UnicodeRange]) -> EntrySelection<'a> {+ EntrySelection {+ font: self.font(),+ pending: self.pending(),+ source_face_id: self.source_face_id,+ ranges: &ranges[self.ranges.clone()],+ }+ }+}++/// Whether two cascades' entries, as they select now, render every code point the same.+fn selections_resolve_alike<'a>(+ entries: impl ExactSizeIterator<Item = EntrySelection<'a>>,+ other_entries: impl ExactSizeIterator<Item = EntrySelection<'a>>,+) -> bool {+ let mut has_earlier_pending_selection = false;+ entries.len() == other_entries.len()+ && entries.zip(other_entries).all(|(entry, other_entry)| {+ if entry.font != other_entry.font || entry.ranges != other_entry.ranges {+ return false;+ }+ if entry.font.is_some() {+ // A preceding unresolved face can start fallback, which skips resident pending faces+ // but still considers loaded entries. Without one, both entries render the same font.+ return !has_earlier_pending_selection || entry.pending.is_some() == other_entry.pending.is_some();+ }+ has_earlier_pending_selection |= entry.pending.is_some();+ match (entry.pending, other_entry.pending) {+ (None, None) => true,+ (Some((identity, state)), Some((other_identity, other_state))) => {+ state == other_state+ && if entry.source_face_id != 0 || other_entry.source_face_id != 0 {+ entry.source_face_id == other_entry.source_face_id+ } else {+ identity == other_identity+ }+ }+ _ => false,+ }+ })+}++impl FrozenFontFills {+ /// The fills that make `list` select as `resolved` does, where loads of faces `list` still+ /// waits on are all that tells them apart; none otherwise.+ pub fn toward(list: Arc<FrozenFontList>, resolved: &FrozenFontList) -> Option<Self> {+ if list.entries.len() != resolved.entries.len() {+ return None;+ }+ let fills: Vec<(usize, FontHandle)> = list+ .entries+ .iter()+ .zip(&resolved.entries)+ .enumerate()+ .filter_map(|(index, (entry, resolved_entry))| {+ let font = resolved_entry.font()?;+ (entry.awaits_fill() && resolved_entry.pending().is_none()).then(|| (index, font.clone()))+ })+ .collect();+ if fills.is_empty() {+ return None;+ }+ let filled = list.entries.iter().enumerate().map(|(index, entry)| {+ match fills.binary_search_by_key(&index, |(filled_index, _)| *filled_index) {+ Ok(fill) => EntrySelection {+ font: Some(&fills[fill].1),+ pending: None,+ ..entry.selection(&list.ranges)+ },+ Err(_) => entry.selection(&list.ranges),+ }+ });+ let resolves_alike = list.last_resort == resolved.last_resort+ && list.system_fallback == resolved.system_fallback+ && selections_resolve_alike(+ filled,+ resolved.entries.iter().map(|entry| entry.selection(&resolved.ranges)),+ )+ && selections_resolve_alike(+ list.fallback_entries+ .iter()+ .map(|entry| entry.selection(&list.fallback_ranges)),+ resolved+ .fallback_entries+ .iter()+ .map(|entry| entry.selection(&resolved.fallback_ranges)),+ );+ resolves_alike.then_some(Self { list, fills })+ }++ /// Fills the faces in. A face some earlier fill already filled keeps the font it was given.+ pub fn apply(self) {+ for (index, font) in self.fills {+ let _ = self.list.entries[index].loaded.set(font);+ }+ self.list+ .fill_generation+ .fetch_add(1, std::sync::atomic::Ordering::Release);+ }}/// Drains the faces render passes have wanted since the last call. The document turns each number@@ -582,9 +791,11 @@ impl FrozenFontList {last_resort: None,system_fallback: None,fonts: Box::new([]),- ascii_cache: std::array::from_fn(|_| std::sync::atomic::AtomicU32::new(0)),- ascii_code_points_resolved_by_first_font: std::sync::OnceLock::new(),+ ascii_cache: std::array::from_fn(|_| std::sync::atomic::AtomicU64::new(0)),+ ascii_code_points_resolved_by_first_font: FirstFontAsciiCodePointsMemo::default(),invisible_variants: std::sync::Mutex::new(std::collections::HashMap::new()),+ first_available: std::sync::atomic::AtomicU64::new(0),+ fill_generation: std::sync::atomic::AtomicU32::new(0),}}@@ -667,6 +878,7 @@ impl FrozenFontList {.flatten(),source_face_id: entry.source_face_id,wanted: std::sync::atomic::AtomicBool::new(false),+ loaded: std::sync::OnceLock::new(),}}).collect()@@ -690,9 +902,11 @@ impl FrozenFontList {slope: header.system_fallback_slope,}),fonts: fonts.into_boxed_slice(),- ascii_cache: std::array::from_fn(|_| std::sync::atomic::AtomicU32::new(0)),- ascii_code_points_resolved_by_first_font: std::sync::OnceLock::new(),+ ascii_cache: std::array::from_fn(|_| std::sync::atomic::AtomicU64::new(0)),+ ascii_code_points_resolved_by_first_font: FirstFontAsciiCodePointsMemo::default(),invisible_variants: std::sync::Mutex::new(std::collections::HashMap::new()),+ first_available: std::sync::atomic::AtomicU64::new(0),+ fill_generation: std::sync::atomic::AtomicU32::new(0),}}@@ -704,53 +918,32 @@ impl FrozenFontList {/// mutable faces those selections were built from. Load-request identities and lookup caches do not affect/// which glyphs a snapshot renders.pub fn resolves_like(&self, other: &Self) -> bool {- let entries_equal = |entries: &[FrozenEntry],- ranges: &[UnicodeRange],- other_entries: &[FrozenEntry],- other_ranges: &[UnicodeRange]| {- let mut has_earlier_pending_selection = false;- entries.len() == other_entries.len()- && entries.iter().zip(other_entries).all(|(entry, other_entry)| {- if entry.font != other_entry.font- || ranges[entry.ranges.clone()] != other_ranges[other_entry.ranges.clone()]- {- return false;- }- if entry.font.is_some() {- // A preceding unresolved face can start fallback, which skips resident pending faces- // but still considers loaded entries. Without one, both entries render the same font.- return !has_earlier_pending_selection- || entry.pending.is_some() == other_entry.pending.is_some();- }- has_earlier_pending_selection |= entry.pending.is_some();- match (entry.pending, other_entry.pending) {- (None, None) => true,- (Some((identity, state)), Some((other_identity, other_state))) => {- state == other_state- && if entry.source_face_id != 0 || other_entry.source_face_id != 0 {- entry.source_face_id == other_entry.source_face_id- } else {- identity == other_identity- }- }- _ => false,- }- })- };std::ptr::eq(self, other)|| (self.last_resort == other.last_resort&& self.system_fallback == other.system_fallback- && entries_equal(&self.entries, &self.ranges, &other.entries, &other.ranges)- && entries_equal(- &self.fallback_entries,- &self.fallback_ranges,- &other.fallback_entries,- &other.fallback_ranges,+ && selections_resolve_alike(+ self.entries.iter().map(|entry| entry.selection(&self.ranges)),+ other.entries.iter().map(|entry| entry.selection(&other.ranges)),+ )+ && selections_resolve_alike(+ self.fallback_entries+ .iter()+ .map(|entry| entry.selection(&self.fallback_ranges)),+ other+ .fallback_entries+ .iter()+ .map(|entry| entry.selection(&other.fallback_ranges)),))}+ /// How many times loads filled pending faces of the cascade in. What it answers for a code+ /// point, and its first available font, only move when this does.+ pub fn fill_generation(&self) -> u32 {+ self.fill_generation.load(std::sync::atomic::Ordering::Acquire)+ }+pub fn has_pending_faces(&self) -> bool {- self.entries.iter().any(|entry| entry.pending.is_some())+ self.entries.iter().any(|entry| entry.pending().is_some())}fn invisible_variant(&self, font: &FontHandle) -> FontHandle {@@ -798,44 +991,55 @@ impl FrozenFontList {code_point: u32,presentation: EmojiPresentation,) -> Cow<'_, FontHandle> {- if code_point < 128 && !presentation.is_emoji && !presentation.forced {- let cached = self.ascii_cache[code_point as usize].load(std::sync::atomic::Ordering::Relaxed);- if cached != 0 {- return Cow::Borrowed(&self.fonts[cached as usize - 1]);- }+ if code_point < 128+ && !presentation.is_emoji+ && !presentation.forced+ && let Some(font) = self.cached_font(&self.ascii_cache[code_point as usize])+ {+ return Cow::Borrowed(font);}Cow::Owned(self.resolve_font_for_code_point(code_point, presentation))}pub fn first_font_and_ascii_code_points_it_resolves_in_text_presentation(&self) -> Option<(&FontHandle, u128)> {- let (index, code_points) = (*self.ascii_code_points_resolved_by_first_font.get_or_init(|| {- let index = self.entries.iter().position(|entry| entry.font.is_some())?;- let entry = &self.entries[index];- let font = entry.font.as_ref()?;- if font.is_emoji_font() {- return None;- }- let is_resolved_by_first_font = |code_point: u32| {- entry.covers(code_point, &self.ranges)- && font.contains_glyph(code_point)- && !self.entries[..index]- .iter()- .any(|earlier| earlier.pending.is_some() && earlier.covers(code_point, &self.ranges))- };- let code_points = (0..128)- .filter(|&code_point| is_resolved_by_first_font(code_point))- .fold(0u128, |code_points, code_point| code_points | 1 << code_point);- Some((index, code_points))- }))?;- self.entries[index].font.as_ref().map(|font| (font, code_points))+ let generation = self.fill_generation();+ // NB: Filling a face in moves which font resolves a code point, so an answer holds for its generation.+ let memo = &self.ascii_code_points_resolved_by_first_font;+ let (index, code_points) = memo.answer_at(generation).unwrap_or_else(|| {+ let answer = self.ascii_code_points_resolved_by_the_first_font();+ memo.remember(generation, answer);+ answer+ })?;+ self.entries[index].font().map(|font| (font, code_points))+ }++ fn ascii_code_points_resolved_by_the_first_font(&self) -> Option<(usize, u128)> {+ let index = self.entries.iter().position(|entry| entry.font().is_some())?;+ let entry = &self.entries[index];+ let font = entry.font()?;+ if font.is_emoji_font() {+ return None;+ }+ let is_resolved_by_first_font = |code_point: u32| {+ entry.covers(code_point, &self.ranges)+ && font.contains_glyph(code_point)+ && !self.entries[..index]+ .iter()+ .any(|earlier| earlier.pending.is_some() && earlier.covers(code_point, &self.ranges))+ };+ let code_points = (0..128)+ .filter(|&code_point| is_resolved_by_first_font(code_point))+ .fold(0u128, |code_points, code_point| code_points | 1 << code_point);+ Some((index, code_points))}#[inline(never)]fn resolve_font_for_code_point(&self, code_point: u32, presentation: EmojiPresentation) -> FontHandle {+ let generation = self.fill_generation();let use_ascii_cache = code_point < 128 && !presentation.is_emoji && !presentation.forced;let presentation_matches = |font: &FontHandle| font.is_emoji_font() == presentation.is_emoji;let contains_glyph = |entry: &FrozenEntry, ranges: &[UnicodeRange]| -> bool {- let Some(font) = &entry.font else { return false };+ let Some(font) = entry.font() else { return false };if entry.ranges.is_empty() {return font.contains_glyph(code_point);}@@ -848,7 +1052,7 @@ impl FrozenFontList {let mut selected: Option<&FontHandle> = None;for entry in &self.entries {- if let Some((face_id, state)) = entry.pending {+ if let Some((face_id, state)) = entry.pending() {if rendering_with_fallback || !entry.covers(code_point, &self.ranges) {continue;}@@ -874,7 +1078,7 @@ impl FrozenFontList {if !contains_glyph(entry, &self.ranges) {continue;}- let font = entry.font.as_ref().expect("an entry with a glyph has a font");+ let font = entry.font().expect("an entry with a glyph has a font");if !presentation.forced || presentation_matches(font) {selected = Some(font);break;@@ -888,7 +1092,7 @@ impl FrozenFontList {if !contains_glyph(entry, &self.fallback_ranges) {continue;}- let font = entry.font.as_ref().expect("an entry with a glyph has a font");+ let font = entry.font().expect("an entry with a glyph has a font");if presentation_matches(font) {selected = Some(font);break;@@ -898,13 +1102,13 @@ impl FrozenFontList {}if let Some(font) = selected {- return self.finish(code_point, use_ascii_cache, invisible, font.clone(), true);+ return self.finish(code_point, generation, use_ascii_cache, invisible, font.clone(), true);}if let Some(fallback) = self.system_fallback_font(code_point, presentation)&& (presentation_matches(&fallback) || (author_glyph_match.is_none() && fallback_glyph_match.is_none())){- return self.finish(code_point, use_ascii_cache, invisible, fallback, false);+ return self.finish(code_point, generation, use_ascii_cache, invisible, fallback, false);}let font = author_glyph_match@@ -912,13 +1116,71 @@ impl FrozenFontList {.or(self.last_resort.as_ref()).cloned();match font {- Some(font) => self.finish(code_point, use_ascii_cache, invisible, font, true),+ Some(font) => self.finish(code_point, generation, use_ascii_cache, invisible, font, true),// A cascade with no fonts at all cannot answer; only a list nobody published can be// in that state, and the layout stage never receives one.None => panic!("frozen font cascade has no font for U+{code_point:04X}"),}}+ /// https://drafts.csswg.org/css-fonts/#first-available-font+ /// Mirrors `Gfx::FontCascadeList::first_available_font`: the first font whose `unicode-range`+ /// does not exclude U+0020 SPACE, skipping faces still waiting on their loads, or the last+ /// resort font.+ pub fn first_available_font(&self) -> &FontHandle {+ if let Some(font) = self.cached_font(&self.first_available) {+ return font;+ }+ const SPACE: u32 = 0x20;+ let generation = self.fill_generation();+ let font = self+ .entries+ .iter()+ .filter(|entry| entry.covers(SPACE, &self.ranges))+ .find_map(FrozenEntry::font)+ .or(self.last_resort.as_ref())+ .expect("a published font cascade has a first available font");+ self.remember(&self.first_available, generation, font);+ font+ }++ /// The font a cache word remembers, if it remembers one found since the last fill.+ fn cached_font(&self, cache: &std::sync::atomic::AtomicU64) -> Option<&FontHandle> {+ let word = cache.load(std::sync::atomic::Ordering::Relaxed);+ if (word >> 32) as u32 != self.fill_generation() {+ return None;+ }+ match word as u32 {+ 0 => None,+ token if token & CACHED_FILLED_ENTRY != 0 => {+ self.entries[(token & !CACHED_FILLED_ENTRY) as usize].loaded.get()+ }+ token => Some(&self.fonts[token as usize - 1]),+ }+ }++ /// Remembers `font`, found at the fill generation `generation`, in a cache word, where it is one+ /// of the cascade's own fonts or a font a load filled in.+ fn remember(&self, cache: &std::sync::atomic::AtomicU64, generation: u32, font: &FontHandle) {+ if let Some(token) = self.cache_token(font) {+ cache.store(+ (u64::from(generation) << 32) | u64::from(token),+ std::sync::atomic::Ordering::Relaxed,+ );+ }+ }++ /// How a cache word remembers one of the cascade's own fonts, or a font a load filled in.+ fn cache_token(&self, font: &FontHandle) -> Option<u32> {+ if let Some(index) = self.fonts.iter().position(|owned| owned == font) {+ return Some(index as u32 + 1);+ }+ self.entries+ .iter()+ .position(|entry| entry.loaded.get() == Some(font))+ .map(|index| index as u32 | CACHED_FILLED_ENTRY)+ }+fn note_wanted_pending_face(&self, entry: &FrozenEntry, face_id: u64) {if entry.wanted.swap(true, std::sync::atomic::Ordering::Relaxed) {return;@@ -930,6 +1192,7 @@ impl FrozenFontList {fn finish(&self,code_point: u32,+ generation: u32,use_ascii_cache: bool,invisible: bool,font: FontHandle,@@ -940,11 +1203,8 @@ impl FrozenFontList {// the memo depend on which pending face the walk happened to reach first.return self.invisible_variant(&font);}- if use_ascii_cache- && is_own_font- && let Some(index) = self.fonts.iter().position(|owned| owned == &font)- {- self.ascii_cache[code_point as usize].store(index as u32 + 1, std::sync::atomic::Ordering::Relaxed);+ if use_ascii_cache && is_own_font {+ self.remember(&self.ascii_cache[code_point as usize], generation, &font);}font}@@ -1100,6 +1360,44 @@ pub unsafe fn frozen_font_list_of(list: *const c_void) -> FrozenFontListRef {FrozenFontListRef::new(Arc::clone(&borrowed))}+impl FrozenFontFills {+ /// [`FrozenFontFills::toward`] for the frozen snapshots of two `Gfx::FontCascadeList`s.+ ///+ /// # Safety+ ///+ /// Both pointers must name live `Gfx::FontCascadeList`s.+ pub unsafe fn toward_cascade(list: *const c_void, resolved: *const c_void) -> Option<Self> {+ // SAFETY: The caller guarantees both cascades are live for this call.+ let (frozen, resolved) = unsafe { (frozen_font_list_of(list), frozen_font_list_of(resolved)) };+ let fills = Self::toward(frozen.to_arc()?, resolved.list()?)?;+ // The cascade's own pending faces must resolve to the fonts filled in, so what it answers on the document+ // thread agrees with what its frozen list answers once filled. A face sized by font-size-adjust, which the+ // load moves, does not.+ // SAFETY: As above.+ let live = unsafe { FrozenFontList::from_cascade_list(list) };+ fills+ .fills+ .iter()+ .all(|(index, font)| live.entries.get(*index).and_then(|entry| entry.font.as_ref()) == Some(font))+ .then_some(fills)+ }+}++/// Whether loads of the faces the cascade `list` waits on are all that tells it apart from+/// `resolved`, so filling them in makes it select as `resolved` does.+///+/// # Safety+///+/// Both pointers must name live `Gfx::FontCascadeList`s.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn ladybird_gfx_font_cascade_list_fills_toward(+ list: *const c_void,+ resolved: *const c_void,+) -> bool {+ // SAFETY: Guaranteed by the caller.+ unsafe { FrozenFontFills::toward_cascade(list, resolved) }.is_some()+}+/// Requests the load of a face a render pass wanted, and answers whether the face was still around/// to request. This is the document-thread half of the pending-face handover: a pass records the/// number, and resolving it here is what starts the fetch, arms the display-period timer and@@ -1151,3 +1449,23 @@ pub unsafe extern "C" fn ladybird_gfx_frozen_font_list_font_for_code_point(// The frozen list owns every font it can answer with, so the borrowed pointer stays live.font.as_raw()}++#[cfg(test)]+mod first_font_ascii_code_points_memo_tests {+ use super::FirstFontAsciiCodePointsMemo;++ #[test]+ fn an_answer_holds_for_its_fill_generation() {+ let memo = FirstFontAsciiCodePointsMemo::default();+ assert_eq!(memo.answer_at(0), None);++ let code_points = (7_u128 << 64) | 9;+ memo.remember(3, Some((5, code_points)));+ assert_eq!(memo.answer_at(3), Some(Some((5, code_points))));+ assert_eq!(memo.answer_at(4), None);++ memo.remember(4, None);+ assert_eq!(memo.answer_at(4), Some(None));+ assert_eq!(memo.answer_at(3), None);+ }+}diff --git a/Libraries/LibWeb/CSS/FontComputer.cpp b/Libraries/LibWeb/CSS/FontComputer.cppindex 05467f18226..8095e87861a 100644--- a/Libraries/LibWeb/CSS/FontComputer.cpp+++ b/Libraries/LibWeb/CSS/FontComputer.cpp@@ -29,6 +29,8 @@#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>@@ -420,6 +422,7 @@ void FontComputer::invalidate_changed_font_cascades(Vector<Utf16FlyString> const// 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))@@ -429,9 +432,17 @@ void FontComputer::invalidate_changed_font_cascades(Vector<Utf16FlyString> constauto 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);request_wanted_web_faces();@@ -442,7 +453,7 @@ void FontComputer::invalidate_changed_font_cascades(Vector<Utf16FlyString> const// 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_transaction()) {+ 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;@@ -461,8 +472,14 @@ void FontComputer::record_font_input_changes(ReadonlySpan<Utf16FlyString> familyfor (auto const* font_list : font_lists)font_list_addresses.unchecked_append(bit_cast<FlatPtr>(font_list));- // 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.+ 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();@@ -470,19 +487,57 @@ void FontComputer::record_font_input_changes(ReadonlySpan<Utf16FlyString> familyset_rendering_pending(document(), RenderingPendingReason::NeedsRenderingUpdate, 1);document().page().client().request_frame();}- StyleEngineFFI::style_engine_record_font_input_changes(style_engine.host(), family_name_lengths, family_name_units, font_list_addresses);}-void FontComputer::did_end_flown_style_drain()+// 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){- // The transaction resolved fonts against the table it was sealed with, where a change beside it made that older- // than the memo, into cascades the memo never holds. The elements holding one that answers differently now, or- // waits on a face the memo would no longer find it waiting on, are found here.+ 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();- for (auto const& [key, font_list] : resolutions) {- if (!font_list->equals(*m_font_cascade_memo->resolve(*font_face_snapshot(), key, font_feature_values_provider(key.font_feature_values_scope))))- m_font_lists_changed_beside_flown_transaction.append(font_list.ptr());+ 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())@@ -681,9 +736,12 @@ GC::Ptr<FontLoader> FontComputer::load_font_face(ReadonlySpan<FontLoader::Sourceauto 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)- it->value->subscribe(*on_load);- return it->value;+ loader->subscribe(*on_load);+ return loader;}auto loader = GC::Heap::the().allocate<FontLoader>(*this, rule_or_declaration, Vector<FontLoader::Source> { sources }, move(on_load));diff --git a/Libraries/LibWeb/CSS/FontComputer.h b/Libraries/LibWeb/CSS/FontComputer.hindex b5f6b49a56a..be4289fedb3 100644--- a/Libraries/LibWeb/CSS/FontComputer.h+++ b/Libraries/LibWeb/CSS/FontComputer.h@@ -211,8 +211,9 @@ public:void clear_font_feature_values_cache(Utf16FlyString const& family_name);void did_load_font(Utf16FlyString const& family_name);void did_load_font(FontFaceKey const&);- // The style transaction that flew has been drained, so the styles it computed are the elements' own.+ // The style update that flew has been drained, so the styles it computed are the elements' own.void did_end_flown_style_drain();+ void take_in_resolutions_against_older_tables();void register_font_face(NonnullRefPtr<FontFaceState>);void unregister_font_face(NonnullRefPtr<FontFaceState>);@@ -247,6 +248,14 @@ private:void end_font_face_change_batch();void invalidate_changed_font_cascades(Vector<Utf16FlyString> const& family_names);void record_font_input_changes(ReadonlySpan<Utf16FlyString> family_names, ReadonlySpan<Gfx::FontCascadeList const*> font_lists);+ // A cascade waiting on faces that loaded, and the cascade the newer @font-face table resolves its request to, which+ // filling the loaded faces into the first makes it select as.+ struct LoadedFaceFill {+ NonnullRefPtr<Gfx::FontCascadeList const> font_list;+ NonnullRefPtr<Gfx::FontCascadeList const> resolved;+ };+ void fill_loaded_font_faces(Vector<LoadedFaceFill>);+ void prepare_font_style_inputs();FontFeatureValues const& font_feature_values_for_family(Utf16FlyString const& family_name, TreeScopeID) const;FontFeatureValues font_feature_values_in_scope(Utf16FlyString const& family_name, TreeScopeID) const;@@ -270,10 +279,11 @@ private:u64 m_environment_generation { 1 };mutable RefPtr<FontFaceSnapshot const> m_font_face_snapshot;Vector<Utf16FlyString> m_batched_font_face_change_families;- // What font resolution answers changed beside a style transaction that flew, which computed styles from the old+ // What font resolution answers changed beside a style update that flew, which computed styles from the old// answers: the elements that use the changed fonts are found once the transaction's drain installed them.Vector<Utf16FlyString> m_font_families_changed_beside_flown_transaction;Vector<Gfx::FontCascadeList const*> m_font_lists_changed_beside_flown_transaction;+ Vector<LoadedFaceFill> m_loaded_face_fills_beside_flown_transaction;};WEB_API Optional<FontComputer&> font_computer_for_font_source(JS::Object& global);diff --git a/Libraries/LibWeb/CSS/FontResolution.cpp b/Libraries/LibWeb/CSS/FontResolution.cppindex b313ee2a704..796a90ad02b 100644--- a/Libraries/LibWeb/CSS/FontResolution.cpp+++ b/Libraries/LibWeb/CSS/FontResolution.cpp@@ -521,17 +521,25 @@ NonnullRefPtr<Gfx::FontCascadeList const> resolve_font_cascade(FontFaceSnapshotfont_list->extend_fallback(*other_font_list);}} else {+ // NB: The system fallback is asked for the style the cascade requests, not that of whichever font comes first,+ // so a face finishing its load leaves it as it was.// FIXME: Normalize the size of each system fallback font by font-size-adjust as well, rather than giving it- // the size of the cascade's first font.- font_list->set_system_font_fallback_callback([](u32 code_point, Gfx::EmojiPresentation presentation, Gfx::Font const& reference_font) -> RefPtr<Gfx::Font const> {+ // the requested size.+ Gfx::FontCascadeList::SystemFallbackRequest request {+ .point_size = font_size_in_pt,+ .weight = static_cast<u16>(clamp(weight, 1, 1000)),+ .width = static_cast<u16>(font_width_bucket_from_percentage(font_width.value())),+ .slope = static_cast<u8>(slope),+ };+ font_list->set_system_font_fallback_callback(request, [](u32 code_point, Gfx::EmojiPresentation presentation, Gfx::FontCascadeList::SystemFallbackRequest const& request) -> RefPtr<Gfx::Font const> {Gfx::SystemFallbackFontKey key {.code_point = code_point,- .weight = static_cast<u16>(reference_font.weight()),- .width = reference_font.width(),- .slope = static_cast<u8>(reference_font.slope()),+ .weight = request.weight,+ .width = request.width,+ .slope = request.slope,.prefer_color_emoji = presentation == Gfx::EmojiPresentation::Emoji,};- return Gfx::system_fallback_font(key, reference_font.point_size());+ return Gfx::system_fallback_font(key, request.point_size);});}@@ -577,30 +585,51 @@ NonnullRefPtr<Gfx::FontCascadeList const> resolve_font_for_style_values(FontCompNonnullRefPtr<Gfx::FontCascadeList const> FontCascadeMemo::resolve(FontFaceSnapshot const& snapshot, ComputedFontCacheKey const& key, FontFeatureValuesProvider const& font_feature_values_for_family) const{MutexLocker locker(m_mutex);- // A style transaction that flew resolves against the snapshot it was sealed with, which a change to the- // @font-face table beside it leaves older than the memo: its answers are its own, and stay out of the memo, retired+ // A style update that flew resolves against the snapshot it was sealed with, which a change to the+ // @font-face table beside it leaves older than the memo. Where the memo keeps a cascade that answers for that+ // table as well, it is the answer; any other answer is the transaction's own, and stays out of the memo, retired// with the cascades the change forgot.if (snapshot.generation() < m_generation) {+ if (auto font_list = cascade_resolved_by(snapshot.generation(), key))+ return font_list.release_nonnull();auto font_list = resolve_font_cascade(snapshot, key, font_feature_values_for_family);m_retired.append(font_list);m_resolutions_against_older_tables.append({ key, font_list });return font_list;}- m_generation = snapshot.generation();- return m_cascades.ensure(key, [&] {- return resolve_font_cascade(snapshot, key, font_feature_values_for_family);- });+ return resolve_into_memo(snapshot, key, font_feature_values_for_family);}NonnullRefPtr<Gfx::FontCascadeList const> FontCascadeMemo::resolve_for_fork(FontFaceSnapshot const& snapshot, ComputedFontCacheKey const& key, FontFeatureValuesProvider const& font_feature_values_for_family) const{MutexLocker locker(m_mutex);- if (snapshot.generation() < m_generation)+ if (snapshot.generation() < m_generation) {+ if (auto font_list = cascade_resolved_by(snapshot.generation(), key))+ return font_list.release_nonnull();return resolve_font_cascade(snapshot, key, font_feature_values_for_family);+ }+ return resolve_into_memo(snapshot, key, font_feature_values_for_family);+}++NonnullRefPtr<Gfx::FontCascadeList const> FontCascadeMemo::resolve_into_memo(FontFaceSnapshot const& snapshot, ComputedFontCacheKey const& key, FontFeatureValuesProvider const& font_feature_values_for_family) const+{+ VERIFY(snapshot.generation() >= m_generation);m_generation = snapshot.generation();- return m_cascades.ensure(key, [&] {- return resolve_font_cascade(snapshot, key, font_feature_values_for_family);+ auto const& cascade = m_cascades.ensure(key, [&] {+ return MemoizedCascade { resolve_font_cascade(snapshot, key, font_feature_values_for_family), m_generation };});+ return cascade.font_list;+}++RefPtr<Gfx::FontCascadeList const> FontCascadeMemo::cascade_resolved_by(u64 generation, ComputedFontCacheKey const& key) const+{+ // NB: Each change to the @font-face table since a cascade was resolved forgot it unless it resolves the same under+ // the changed table, so a cascade the memo keeps answers for every table from the one it was resolved against+ // on. A transaction that flew, or a fork of the render state, then names the same cascade as the memo.+ auto it = m_cascades.find(key);+ if (it == m_cascades.end() || it->value.resolved_at_generation > generation)+ return {};+ return it->value.font_list;}void FontCascadeMemo::forget_matching(u64 environment_generation, Function<bool(ComputedFontCacheKey const&, NonnullRefPtr<Gfx::FontCascadeList const> const&)> const& predicate)@@ -608,10 +637,10 @@ void FontCascadeMemo::forget_matching(u64 environment_generation, Function<bool(MutexLocker locker(m_mutex);VERIFY(environment_generation > m_generation);m_generation = environment_generation;- m_cascades.remove_all_matching([&](auto const& key, auto const& font_list) {- if (!predicate(key, font_list))+ m_cascades.remove_all_matching([&](auto const& key, auto const& cascade) {+ if (!predicate(key, cascade.font_list))return false;- m_retired.append(font_list);+ m_retired.append(cascade.font_list);return true;});}@@ -620,11 +649,9 @@ void FontCascadeMemo::release_retired() const{// NB: A cascade's destructor releases fonts into the document thread's caches, so it runs outside the lock.Vector<NonnullRefPtr<Gfx::FontCascadeList const>> retired;- Vector<ResolutionAgainstOlderTable> resolutions_against_older_tables;{MutexLocker locker(m_mutex);retired = move(m_retired);- resolutions_against_older_tables = move(m_resolutions_against_older_tables);}}@@ -634,6 +661,22 @@ Vector<FontCascadeMemo::ResolutionAgainstOlderTable> FontCascadeMemo::take_resolreturn exchange(m_resolutions_against_older_tables, {});}+bool FontCascadeMemo::adopt_resolution_against_older_table(FontFaceSnapshot const& snapshot, ResolutionAgainstOlderTable const& resolution, FontFeatureValuesProvider const& font_feature_values_for_family) const+{+ MutexLocker locker(m_mutex);+ VERIFY(snapshot.generation() >= m_generation);+ if (auto it = m_cascades.find(resolution.key); it != m_cascades.end())+ return it->value.font_list.ptr() == resolution.font_list.ptr();+ // NB: No element holds a cascade of the memo for the request yet, so the one the transaction resolved, where it+ // answers the same under the newest table, is the memo's answer from here on, and the elements holding it keep+ // it.+ m_generation = snapshot.generation();+ auto font_list = resolve_font_cascade(snapshot, resolution.key, font_feature_values_for_family);+ auto adopted = font_list->equals(*resolution.font_list);+ m_cascades.set(resolution.key, MemoizedCascade { adopted ? resolution.font_list : move(font_list), m_generation });+ return adopted;+}+}namespace Web::CSS {diff --git a/Libraries/LibWeb/CSS/FontResolution.h b/Libraries/LibWeb/CSS/FontResolution.hindex 38eebf33aeb..1d4925de46e 100644--- a/Libraries/LibWeb/CSS/FontResolution.h+++ b/Libraries/LibWeb/CSS/FontResolution.h@@ -75,15 +75,16 @@ public:// NB: A memo of a pure function, so filling it does not change what it answers.[[nodiscard]] NonnullRefPtr<Gfx::FontCascadeList const> resolve(FontFaceSnapshot const&, ComputedFontCacheKey const&, FontFeatureValuesProvider const&) const;// Resolves as resolve() does for a fork of a document's render state, which holds a reference to every cascade it- // names: an answer against an older table than the memo's is the fork's alone, which neither the retired cascades- // nor the bookkeeping of answers against older tables take in.+ // names: an answer against an older table than the memo's that the memo does not keep is the fork's alone, which+ // neither the retired cascades nor the bookkeeping of answers against older tables take in.[[nodiscard]] NonnullRefPtr<Gfx::FontCascadeList const> resolve_for_fork(FontFaceSnapshot const&, ComputedFontCacheKey const&, FontFeatureValuesProvider const&) const;// NB: Only under a font environment generation newer than any resolved against: the style engine names the memo's// cascades without holding a reference to them for as long as a generation stands, so the forgotten ones are- // retired, not released, as a style transaction that flew may still name them.+ // retired, not released, as a style update that flew may still name them.void forget_matching(u64 environment_generation, Function<bool(ComputedFontCacheKey const&, NonnullRefPtr<Gfx::FontCascadeList const> const&)> const&);// Releases the retired cascades, on the document thread, where the engine is about to resolve against the newest- // table: what it named from older ones is never read again.+ // table: what it named from older ones is never read again. An element holding one keeps it alive, and the answers+ // against older tables stay to be taken in.void release_retired() const;struct ResolutionAgainstOlderTable {@@ -92,14 +93,30 @@ public:};// The cascades resolved against an older table since last taken, which may answer their requests differently now.[[nodiscard]] Vector<ResolutionAgainstOlderTable> take_resolutions_against_older_tables() const;+ // Whether the memo answers the request of a resolution against an older table with its very cascade, against the+ // newest table: where the memo holds no cascade for the request and that one resolves the same under the newest+ // table, the memo takes it in. Elements holding a cascade the memo does not answer with resolve again.+ [[nodiscard]] bool adopt_resolution_against_older_table(FontFaceSnapshot const&, ResolutionAgainstOlderTable const&, FontFeatureValuesProvider const&) const;private:FontCascadeMemo() = default;+ // Resolves against the newest table, through the memo. Called with m_mutex held.+ NonnullRefPtr<Gfx::FontCascadeList const> resolve_into_memo(FontFaceSnapshot const&, ComputedFontCacheKey const&, FontFeatureValuesProvider const&) const;+ // The memo's cascade for the request where it also answers for the table of the generation, or null. Called with+ // m_mutex held.+ RefPtr<Gfx::FontCascadeList const> cascade_resolved_by(u64 generation, ComputedFontCacheKey const&) const;++ struct MemoizedCascade {+ NonnullRefPtr<Gfx::FontCascadeList const> font_list;+ // The generation of the table the cascade was resolved against.+ u64 resolved_at_generation { 0 };+ };+// Guards the four members below. A resolution runs under it, so a cascade is resolved once however many threads// want it.mutable Mutex m_mutex;- mutable HashMap<ComputedFontCacheKey, NonnullRefPtr<Gfx::FontCascadeList const>> m_cascades;+ mutable HashMap<ComputedFontCacheKey, MemoizedCascade> m_cascades;// The newest snapshot generation resolved against or forgotten under. An older one would write a stale cascade// where every later request reads it.mutable u64 m_generation { 0 };diff --git a/Libraries/LibWebView/FontService.cpp b/Libraries/LibWebView/FontService.cppindex 131422cba8e..33a2526c128 100644--- a/Libraries/LibWebView/FontService.cpp+++ b/Libraries/LibWebView/FontService.cpp@@ -241,6 +241,8 @@ Gfx::BrokeredFont FontService::materialize_file(Gfx::SystemFontFile file, String{// Every code point that a fallback font covers matches it under a key of its own, but the face is one face for all// of them. A face of the catalog keeps its catalog id.+ // NB: A match names the face, which the renderer opens only where it does not hold it yet: most matches are of+ // faces it matched before, for another code point or style.FontSource source { .path = move(file.path), .ttc_index = file.ttc_index, .format = file.format };auto face_id = m_face_id_by_source.ensure(source, [&] {auto new_face_id = m_next_dynamic_face_id++;@@ -248,7 +250,7 @@ Gfx::BrokeredFont FontService::materialize_file(Gfx::SystemFontFile file, Stringreturn new_face_id;});m_dynamic_match_cache.set(move(cache_key), face_id);- return open_font_without_lock(m_generation, face_id);+ return { .face_id = face_id, .source = Empty {} };}Gfx::BrokeredFont FontService::materialize_platform_font(Gfx::PlatformFontName name, String cache_key)@@ -259,7 +261,7 @@ Gfx::BrokeredFont FontService::materialize_platform_font(Gfx::PlatformFontName nreturn new_face_id;});m_dynamic_match_cache.set(move(cache_key), face_id);- return open_font_without_lock(m_generation, face_id);+ return { .face_id = face_id, .source = Empty {} };}Gfx::BrokeredFont FontService::match_local_font(String const& name)@@ -275,7 +277,7 @@ Gfx::BrokeredFont FontService::match_local_font(String const& name)return {};// https://drafts.csswg.org/css-fonts-4/#local-font-fallback// Platform substitutions for a given font name must not be used.- return open_font_without_lock(m_generation, *face_id);+ return { .face_id = *face_id, .source = Empty {} };}Gfx::BrokeredFont FontService::match_font(String const& family, u16 weight, u16 width, u8 slope)@@ -285,7 +287,7 @@ Gfx::BrokeredFont FontService::match_font(String const& family, u16 weight, u16return {};auto cache_key = MUST(String::formatted("family:{}:{}:{}:{}", family, weight, width, slope));if (auto face_id = m_dynamic_match_cache.get(cache_key); face_id.has_value())- return open_font_without_lock(m_generation, *face_id);+ return { .face_id = *face_id, .source = Empty {} };auto match = Gfx::SystemFontMatcher::match_family_style(family, weight, width, slope);if (!match.has_value())@@ -300,7 +302,7 @@ Gfx::BrokeredFont FontService::match_font_for_code_point(u32 code_point, u16 weireturn {};auto cache_key = MUST(String::formatted("character:{}:{}:{}:{}:{}", code_point, weight, width, slope, prefer_color_emoji));if (auto face_id = m_dynamic_match_cache.get(cache_key); face_id.has_value())- return open_font_without_lock(m_generation, *face_id);+ return { .face_id = *face_id, .source = Empty {} };auto match = Gfx::SystemFontMatcher::match_code_point(code_point, weight, width, slope, prefer_color_emoji);if (!match.has_value())diff --git a/Tests/LibGfx/TestFont.cpp b/Tests/LibGfx/TestFont.cppindex 09973f5b0b6..c15136b3509 100644--- a/Tests/LibGfx/TestFont.cpp+++ b/Tests/LibGfx/TestFont.cpp@@ -587,7 +587,7 @@ TEST_CASE(system_fallback_does_not_depend_on_earlier_lookups)auto second_font = load_text_font(24);auto cascade = Gfx::FontCascadeList::create();cascade->set_last_resort_font(first_font);- cascade->set_system_font_fallback_callback([first_font, second_font](u32 code_point, Gfx::EmojiPresentation, Gfx::Font const&) -> RefPtr<Gfx::Font const> {+ cascade->set_system_font_fallback_callback({}, [first_font, second_font](u32 code_point, Gfx::EmojiPresentation, Gfx::FontCascadeList::SystemFallbackRequest const&) -> RefPtr<Gfx::Font const> {return code_point == 'a' ? first_font : second_font;});diff --git a/Tests/LibWeb/Crash/CSS/font-load-adds-loaders-while-subscribing-to-a-settled-one.html b/Tests/LibWeb/Crash/CSS/font-load-adds-loaders-while-subscribing-to-a-settled-one.htmlnew file mode 100644index 00000000000..ec00e39a4dc--- /dev/null+++ b/Tests/LibWeb/Crash/CSS/font-load-adds-loaders-while-subscribing-to-a-settled-one.html@@ -0,0 +1,42 @@+<!DOCTYPE html>+<html class="test-wait">+<style>+@font-face { font-family: Settled; src: url(../../Assets/HashSans.woff); }+@font-face { font-family: Shared; src: url(../../Assets/HashSans.woff); }+@font-face { font-family: First; src: url(../../Assets/HashSans.woff?1); }+@font-face { font-family: Second; src: url(../../Assets/HashSans.woff?2); }+@font-face { font-family: Third; src: url(../../Assets/HashSans.woff?3); }+@font-face { font-family: Fourth; src: url(../../Assets/HashSans.woff?4); }+@font-face { font-family: Fifth; src: url(../../Assets/HashSans.woff?5); }+@font-face { font-family: Sixth; src: url(../../Assets/HashSans.woff?6); }+@font-face { font-family: Seventh; src: url(../../Assets/HashSans.woff?7); }+@font-face { font-family: Eighth; src: url(../../Assets/HashSans.woff?8); }+body { font-weight: 600; }+.shared { font-family: Shared, serif; }+.first { font-family: First, Shared, serif; }+.second { font-family: Second, Shared, serif; }+.third { font-family: Third, Shared, serif; }+.fourth { font-family: Fourth, Shared, serif; }+.fifth { font-family: Fifth, Shared, serif; }+.sixth { font-family: Sixth, Shared, serif; }+.seventh { font-family: Seventh, Shared, serif; }+.eighth { font-family: Eighth, Shared, serif; }+</style>+<body>+<div>text</div><div>text</div><div>text</div><div>text</div><div>text</div><div>text</div><div>text</div><div>text</div><div>text</div>+<script>+ // NB: Shared takes the settled loader of Settled, which answers it at once. That selects again, loading the others+ // from within, and they grow the map of loaders that loader was found in.+ const frames = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));+ window.onload = async () => {+ await document.fonts.load("16px Settled");+ await frames();+ const classes = ["shared", "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth"];+ document.querySelectorAll("div").forEach((element, index) => (element.className = classes[index]));+ await frames();+ await frames();+ document.documentElement.classList.remove("test-wait");+ };+</script>+</body>+</html>diff --git a/Tests/LibWebView/TestFontService.cpp b/Tests/LibWebView/TestFontService.cppindex 95ccc61392b..9948f831fe3 100644--- a/Tests/LibWebView/TestFontService.cpp+++ b/Tests/LibWebView/TestFontService.cpp@@ -63,10 +63,15 @@ TEST_CASE(dynamic_matches_of_one_face_share_its_id)EXPECT_NE(platform_font.face_id, 0u);EXPECT_EQ(platform_font.face_id, repeated_platform_font.face_id);EXPECT_NE(platform_font.face_id, first.face_id);- EXPECT(platform_font.source.has<Gfx::PlatformFontName>());++ // A match names the face, which the renderer opens where it does not hold it yet.+ auto generation = MUST(service->clone_catalog()).generation;+ EXPECT(first.source.has<Empty>());+ EXPECT(service->open_font(generation, platform_font.face_id).source.has<Gfx::PlatformFontName>());// The renderer gets the file itself, not a copy of its data.- auto* font_file = first.source.get_pointer<Gfx::BrokeredFontFile>();+ auto opened = service->open_font(generation, first.face_id);+ auto* font_file = opened.source.get_pointer<Gfx::BrokeredFontFile>();EXPECT(font_file);auto mapped_file = MUST(Core::MappedFile::map_from_fd_and_close(font_file->file.take_fd(), "brokered font"sv));auto original_file = MUST(Core::MappedFile::map("../LibGfx/test-inputs/fonts/text.ttf"sv));