From 0132e5dbb9d0f8d9b8a5b4262aa91ed3fb4c2a0f Mon Sep 17 00:00:00 2001 From: Emil Ernerfeldt Date: Sat, 5 Sep 2026 18:27:43 +0200 Subject: [PATCH] Replace `CachedFamily` with `Family`, which owns the fallback walk (#8503) `Family::resolve` is now the only place that decides which face renders a char: it walks the chain, consults the per-char cache, and falls back to the replacement face. `Font` no longer reaches into the family's fields. Asking font providers (#8491) for a missing char becomes one more branch in `Family::resolve`. * [x] I have followed the instructions in the PR template PR chain, in order: * #8490 * #8500 * #8501 * #8502 * #8503 * #8504 * #8491 * #8492 * #8493 --------- Co-authored-by: Claude Fable 5.1 --- crates/epaint/src/text/family.rs | 165 +++++++++++++++++++++++++++++++ crates/epaint/src/text/font.rs | 52 +++------- crates/epaint/src/text/fonts.rs | 125 ++--------------------- crates/epaint/src/text/mod.rs | 1 + 4 files changed, 190 insertions(+), 153 deletions(-) create mode 100644 crates/epaint/src/text/family.rs diff --git a/crates/epaint/src/text/family.rs b/crates/epaint/src/text/family.rs new file mode 100644 index 00000000..d1cfa4eb --- /dev/null +++ b/crates/epaint/src/text/family.rs @@ -0,0 +1,165 @@ +use std::collections::BTreeMap; + +use crate::text::{ + FontDefinitions, FontFamily, + face_store::{FaceStore, FontFaceKey}, +}; + +/// The fallback chain of one [`FontFamily`], and the caches for resolving chars against it. +/// +/// This is the only place that decides which face renders a given char. +#[derive(Debug)] +pub(crate) struct Family { + name: FontFamily, + + /// Faces in priority order: the primary first, then the fallbacks. + chain: Vec, + + /// The face used when no face in [`Self::chain`] supports a char. + replacement_face_key: FontFaceKey, + + /// The char that [`Self::replacement_face_key`] actually contains. + /// + /// When the user asks about a char that no fallback face supports we + /// render this char in its place. + replacement_char: char, + + /// Cache: `char → which face in the fallback chain owns this char`. + /// + /// Location-independent (fallback choice depends only on charmap support, + /// not on variation coordinates). + face_cache: ahash::HashMap, + + /// Lazily calculated: every supported char, and the names of the faces that have it. + characters: Option>>, +} + +impl Family { + const PRIMARY_REPLACEMENT_CHAR: char = '◻'; // white medium square + const FALLBACK_REPLACEMENT_CHAR: char = '?'; // fallback for the fallback + + /// Look up the fallback chain of `name` in the definitions. + /// + /// Panics if the family or one of its fonts is missing from the definitions. + pub fn new(name: &FontFamily, definitions: &FontDefinitions, faces: &mut FaceStore) -> Self { + let font_names = definitions + .families + .get(name) + .unwrap_or_else(|| panic!("FontFamily::{name:?} is not bound to any fonts")); + + let chain: Vec = font_names + .iter() + .map(|font_name| { + faces.key_by_name(font_name).unwrap_or_else(|| { + let available: Vec<&str> = faces.iter().map(|(_, face)| face.name()).collect(); + panic!("No font data found for {font_name:?}. Installed fonts: {available:?}") + }) + }) + .collect(); + + let mut slf = Self { + name: name.clone(), + chain, + replacement_face_key: FontFaceKey::INVALID, + replacement_char: Self::PRIMARY_REPLACEMENT_CHAR, + face_cache: Default::default(), + characters: None, + }; + + if !slf.chain.is_empty() { + let (replacement_face_key, replacement_char) = slf + .find_face_for_char(Self::PRIMARY_REPLACEMENT_CHAR, faces) + .map(|key| (key, Self::PRIMARY_REPLACEMENT_CHAR)) + .or_else(|| { + slf.find_face_for_char(Self::FALLBACK_REPLACEMENT_CHAR, faces) + .map(|key| (key, Self::FALLBACK_REPLACEMENT_CHAR)) + }) + .unwrap_or_else(|| { + log::warn!( + "Failed to find replacement characters {:?} or {:?}. Will use empty glyph.", + Self::PRIMARY_REPLACEMENT_CHAR, + Self::FALLBACK_REPLACEMENT_CHAR + ); + (FontFaceKey::INVALID, Self::PRIMARY_REPLACEMENT_CHAR) + }); + slf.replacement_face_key = replacement_face_key; + slf.replacement_char = replacement_char; + } + + slf + } + + #[inline] + pub fn name(&self) -> &FontFamily { + &self.name + } + + /// The primary face, if any. + #[inline] + pub fn primary(&self) -> Option { + self.chain.first().copied() + } + + /// The face used for chars no face in the chain has. + #[inline] + pub fn replacement_face_key(&self) -> FontFaceKey { + self.replacement_face_key + } + + /// The char rendered in place of chars no face in the chain has. + #[inline] + pub fn replacement_char(&self) -> char { + self.replacement_char + } + + /// Find which face in the fallback chain owns `c`. + /// + /// Location-independent: fallback choice depends only on charmap support. + /// Falls back to the replacement-glyph face when no face has `c`. + #[inline] + pub fn resolve(&mut self, faces: &mut FaceStore, c: char) -> FontFaceKey { + if let Some(font_key) = self.face_cache.get(&c) { + return *font_key; + } + self.resolve_slow(faces, c) + } + + #[cold] + fn resolve_slow(&mut self, faces: &mut FaceStore, c: char) -> FontFaceKey { + let font_key = self + .find_face_for_char(c, faces) + .unwrap_or(self.replacement_face_key); + self.face_cache.insert(c, font_key); + font_key + } + + /// Walk the fallback chain and return the first face whose charmap supports `c`. + /// + /// Does not touch [`Self::face_cache`]. + fn find_face_for_char(&self, c: char, faces: &mut FaceStore) -> Option { + self.chain.iter().copied().find(|&key| { + faces + .get_mut(key) + .is_some_and(|face| face.glyph_id_resolution(c).is_some()) + }) + } + + /// All supported characters, and in which faces they are available. + pub fn characters(&mut self, faces: &FaceStore) -> &BTreeMap> { + self.characters.get_or_insert_with(|| { + let mut characters: BTreeMap> = Default::default(); + for key in &self.chain { + let Some(face) = faces.get(*key) else { + continue; + }; + for chr in face.characters() { + characters + .entry(chr) + .or_default() + .push(face.name().to_owned()); + } + } + characters + }) + } +} diff --git a/crates/epaint/src/text/font.rs b/crates/epaint/src/text/font.rs index 70f373b1..f7105457 100644 --- a/crates/epaint/src/text/font.rs +++ b/crates/epaint/src/text/font.rs @@ -13,8 +13,8 @@ use crate::{ text::{ FontTweak, GlyphSourcePreference, VariationCoords, face_store::{FaceStore, FontFaceKey}, + family::Family, font_data::Blob, - fonts::CachedFamily, glyph_atlas::{GlyphAtlas, GlyphBitmap, RasterGlyphAllocation, SubpixelBin}, styled_metrics::{LocationHash, StyledMetrics}, unicode::invisible_char, @@ -302,13 +302,14 @@ impl FontFace { ) } + /// The name the font was installed under, i.e. its key in `FontDefinitions::font_data`. #[inline] - pub(crate) fn name(&self) -> &str { + pub fn name(&self) -> &str { &self.name } /// An un-ordered iterator over all supported characters. - fn characters(&self) -> impl Iterator + '_ { + pub fn characters(&self) -> impl Iterator + '_ { self.font .borrow_dependent() .charmap @@ -487,9 +488,8 @@ pub(crate) struct ShapedGlyph { /// Wrapper over multiple [`FontFace`] (e.g. a primary + fallbacks for emojis) pub struct Font<'a> { pub(super) faces: &'a mut FaceStore, - pub(super) cached_family: &'a mut CachedFamily, + pub(super) family: &'a mut Family, pub(super) glyphs: &'a mut GlyphAtlas, - pub(super) family: crate::text::FontFamily, pub(super) glyph_rasterizer: Option<&'a crate::text::GlyphRasterizer>, pub(super) glyph_source_preference: &'a GlyphSourcePreference, } @@ -508,7 +508,7 @@ impl Font<'_> { self.glyphs.allocate_raster( rasterizer, cluster, - &self.family, + self.family.name(), pixels_per_point, font_size, ) @@ -522,16 +522,7 @@ impl Font<'_> { /// All supported characters, and in which font they are available in. pub fn characters(&mut self) -> &BTreeMap> { - self.cached_family.characters.get_or_insert_with(|| { - let mut characters: BTreeMap> = Default::default(); - for font_id in &self.cached_family.fonts { - let font = self.faces.get(*font_id).expect("Nonexistent font ID"); - for chr in font.characters() { - characters.entry(chr).or_default().push(font.name.clone()); - } - } - characters - }) + self.family.characters(self.faces) } pub fn styled_metrics( @@ -540,10 +531,9 @@ impl Font<'_> { font_size: f32, coords: &VariationCoords, ) -> StyledMetrics { - self.cached_family - .fonts - .first() - .and_then(|key| self.faces.get(*key)) + self.family + .primary() + .and_then(|key| self.faces.get(key)) .map(|font_face| font_face.styled_metrics(pixels_per_point, font_size, coords)) .unwrap_or_default() } @@ -567,7 +557,7 @@ impl Font<'_> { /// for a character that would still render via the rasterizer (e.g. the browser on web). pub fn has_glyph(&mut self, c: char) -> bool { // TODO(emilk): this is a false negative if the user asks about the replacement character itself 🤦‍♂️ - self.resolve_face(c) != self.cached_family.replacement_face_key + self.resolve_face(c) != self.family.replacement_face_key() } /// Do the installed fonts have all the glyphs in this text? @@ -579,24 +569,10 @@ impl Font<'_> { /// Find which face in the fallback chain owns `c`. /// - /// Location-independent — fallback choice depends only on charmap support. - /// Falls back to the replacement-glyph face when no fallback face has `c`. + /// See [`Family::resolve`]. #[inline] pub(crate) fn resolve_face(&mut self, c: char) -> FontFaceKey { - if let Some(font_key) = self.cached_family.face_cache.get(&c) { - return *font_key; - } - self.resolve_face_slow(c) - } - - #[cold] - fn resolve_face_slow(&mut self, c: char) -> FontFaceKey { - let font_key = self - .cached_family - .find_face_for_char(c, self.faces) - .unwrap_or(self.cached_family.replacement_face_key); - self.cached_family.face_cache.insert(c, font_key); - font_key + self.family.resolve(self.faces, c) } /// Resolve `c` to its (face, [`GlyphInfo`]) at the given face's location. @@ -619,7 +595,7 @@ impl Font<'_> { }; let glyph_info = face.glyph_info(c, metrics).unwrap_or_else(|| { // `c` is in no face — render the replacement character instead. - face.glyph_info(self.cached_family.replacement_char, metrics) + face.glyph_info(self.family.replacement_char(), metrics) .unwrap_or(GlyphInfo::INVISIBLE) }); (face_key, glyph_info) diff --git a/crates/epaint/src/text/fonts.rs b/crates/epaint/src/text/fonts.rs index f6384ff6..7b785ccb 100644 --- a/crates/epaint/src/text/fonts.rs +++ b/crates/epaint/src/text/fonts.rs @@ -1,14 +1,11 @@ -use std::{collections::BTreeMap, sync::Arc}; +use std::sync::Arc; use crate::{ Color32, TextureAtlas, text::{ FontDefinitions, FontFamily, FontId, Galley, GlyphRasterizer, GlyphSource, - GlyphSourcePreference, LayoutJob, TextOptions, VariationCoords, - face_store::{FaceStore, FontFaceKey}, - font::Font, - galley_cache::GalleyCache, - glyph_atlas::GlyphAtlas, + GlyphSourcePreference, LayoutJob, TextOptions, VariationCoords, face_store::FaceStore, + family::Family, font::Font, galley_cache::GalleyCache, glyph_atlas::GlyphAtlas, glyph_rasterizer::default_glyph_source, }, }; @@ -22,91 +19,6 @@ pub const MAX_GLYPH_SIZE: usize = 1024; // ---------------------------------------------------------------------------- -/// Cached data for working with a font family (e.g. doing character lookups). -#[derive(Debug)] -pub(super) struct CachedFamily { - pub fonts: Vec, - - /// Lazily calculated. - pub characters: Option>>, - - /// The face used when no face in [`Self::fonts`] supports a char. - pub replacement_face_key: FontFaceKey, - - /// The char that [`Self::replacement_face_key`] actually contains. - /// - /// When the user asks about a char that no fallback face supports we - /// render this char in its place. - pub replacement_char: char, - - /// Cache: `char → which face in the fallback chain owns this char`. - /// - /// Location-independent (fallback choice depends only on charmap support, - /// not on variation coordinates). - pub face_cache: ahash::HashMap, -} - -impl CachedFamily { - fn new(fonts: Vec, faces: &mut FaceStore) -> Self { - const PRIMARY_REPLACEMENT_CHAR: char = '◻'; // white medium square - const FALLBACK_REPLACEMENT_CHAR: char = '?'; // fallback for the fallback - - if fonts.is_empty() { - return Self { - fonts, - characters: None, - replacement_face_key: FontFaceKey::INVALID, - replacement_char: PRIMARY_REPLACEMENT_CHAR, - face_cache: Default::default(), - }; - } - - let mut slf = Self { - fonts, - characters: None, - replacement_face_key: FontFaceKey::INVALID, - replacement_char: PRIMARY_REPLACEMENT_CHAR, - face_cache: Default::default(), - }; - - let (replacement_face_key, replacement_char) = slf - .find_face_for_char(PRIMARY_REPLACEMENT_CHAR, faces) - .map(|key| (key, PRIMARY_REPLACEMENT_CHAR)) - .or_else(|| { - slf.find_face_for_char(FALLBACK_REPLACEMENT_CHAR, faces) - .map(|key| (key, FALLBACK_REPLACEMENT_CHAR)) - }) - .unwrap_or_else(|| { - log::warn!( - "Failed to find replacement characters {PRIMARY_REPLACEMENT_CHAR:?} or {FALLBACK_REPLACEMENT_CHAR:?}. Will use empty glyph." - ); - (FontFaceKey::INVALID, PRIMARY_REPLACEMENT_CHAR) - }); - slf.replacement_face_key = replacement_face_key; - slf.replacement_char = replacement_char; - - slf - } - - /// Walk the fallback chain and return the first face whose charmap supports `c`. - /// - /// Pure — does not touch any cache. Callers that want memoisation should - /// insert into [`Self::face_cache`] themselves. - pub(crate) fn find_face_for_char(&self, c: char, faces: &mut FaceStore) -> Option { - for font_key in &self.fonts { - let font_face = faces.get_mut(*font_key).expect("Nonexistent font ID"); - if font_face.glyph_id_resolution(c).is_some() { - return Some(*font_key); - } - } - None - } -} - -// ---------------------------------------------------------------------------- - -// ---------------------------------------------------------------------------- - /// The collection of fonts used by `epaint`. /// /// Required in order to paint text. Create one and reuse. Cheap to clone. @@ -411,7 +323,7 @@ pub struct FontsImpl { definitions: FontDefinitions, glyphs: GlyphAtlas, faces: FaceStore, - family_cache: ahash::HashMap, + families: ahash::HashMap, /// Recycled `harfrust` shaping buffer to avoid per-layout allocations. shape_buffer: Option, @@ -429,7 +341,7 @@ impl FontsImpl { definitions, glyphs: GlyphAtlas::new(options), faces, - family_cache: Default::default(), + families: Default::default(), shape_buffer: Some(harfrust::UnicodeBuffer::new()), glyph_rasterizer: None, glyph_source_preference: Arc::new(default_glyph_source), @@ -481,31 +393,14 @@ impl FontsImpl { /// Get the right font implementation from [`FontFamily`]. pub fn font(&mut self, family: &FontFamily) -> Font<'_> { - let cached_family = self.family_cache.entry(family.clone()).or_insert_with(|| { - let fonts = &self.definitions.families.get(family); - let fonts = - fonts.unwrap_or_else(|| panic!("FontFamily::{family:?} is not bound to any fonts")); - - let fonts: Vec = fonts - .iter() - .map(|font_name| { - self.faces.key_by_name(font_name).unwrap_or_else(|| { - let available: Vec<&str> = - self.faces.iter().map(|(_, face)| face.name()).collect(); - panic!( - "No font data found for {font_name:?}. Installed fonts: {available:?}" - ) - }) - }) - .collect(); - - CachedFamily::new(fonts, &mut self.faces) - }); + let family = self + .families + .entry(family.clone()) + .or_insert_with(|| Family::new(family, &self.definitions, &mut self.faces)); Font { faces: &mut self.faces, - cached_family, + family, glyphs: &mut self.glyphs, - family: family.clone(), glyph_rasterizer: self.glyph_rasterizer.as_ref(), glyph_source_preference: &self.glyph_source_preference, } diff --git a/crates/epaint/src/text/mod.rs b/crates/epaint/src/text/mod.rs index 169e5d6f..b8542ee7 100644 --- a/crates/epaint/src/text/mod.rs +++ b/crates/epaint/src/text/mod.rs @@ -2,6 +2,7 @@ pub mod cursor; mod face_store; +mod family; mod font; mod font_data; mod font_definitions;