Skip to main content

FcFontCache

Struct FcFontCache 

Source
pub struct FcFontCache { /* private fields */ }
Expand description

Font cache, initialized at startup.

Thread-safe, shared font cache.

As of v4.1 the cache internally owns its state via Arc<RwLock<FcFontCacheInner>>: cloning an FcFontCache returns a handle that shares the same underlying data. Writes by one holder (typically the background builder inside FcFontRegistry) become immediately visible to every other holder (layout engines, shape-time resolvers, etc.).

Before 4.1 the clone deep-copied every map, so external holders were frozen at the moment they took the snapshot — the mismatch between “live registry cache” and “frozen font manager cache” was the root of the silent-text regression when lazy scout mode was enabled. The shared-state design eliminates that entire class of staleness bugs by construction.

Implementations§

Source§

impl FcFontCache

Source

pub fn with_memory_fonts(&self, fonts: Vec<(FcPattern, FcFont)>) -> &Self

Adds in-memory font files.

Note: takes &self — the shared cache handles interior mutability via the RwLock.

Source

pub fn with_memory_font_with_id( &self, id: FontId, pattern: FcPattern, font: FcFont, ) -> &Self

Adds a memory font with a specific ID (for testing).

Source

pub fn insert_builder_font(&self, pattern: FcPattern, path: FcFontPath)

Register a newly-parsed on-disk font. Called by the builder thread inside FcFontRegistry. Allocates a fresh FontId, inserts the pattern + path + metadata in one write lock, and invalidates the chain cache so subsequent resolutions pick up the new font.

Source

pub fn get_font_by_id(&self, id: &FontId) -> Option<OwnedFontSource>

Get font data for a given font ID.

Returns owned values (not references) because the underlying maps live behind an RwLock — a reference could not outlive the read guard. In-memory fonts come back as cloned FcFont instances; disk fonts return their FcFontPath.

Source

pub fn get_metadata_by_id(&self, id: &FontId) -> Option<FcPattern>

Get metadata for a font ID. Returns an owned FcPattern (cloned out of the shared map) because we can’t return a reference across the RwLock boundary.

Source

pub fn get_font_bytes(&self, id: &FontId) -> Option<Arc<FontBytes>>

Get the font bytes for id as a shared FontBytes.

On disk the returned Arc<FontBytes> wraps an mmap of the file (FontBytes::Mmapped). Untouched pages of the file never count toward the process’s RSS — for a font where layout shapes only a handful of glyphs, this is the difference between paying for the whole 4 MiB .ttc and paying for the cmap + a few glyf pages.

In-memory fonts (FontSource::Memory) come back as FontBytes::Owned, since the bytes are already on the heap.

Multiple FontIds backed by the same file content (every face of a .ttc, or two paths with identical bytes) return the same Arc<FontBytes> thanks to a content-hash → Weak cache. Bytes get unmapped automatically when the last consumer drops the Arc.

FontBytes derefs to [u8], so callers that only need &[u8] (allsorts, ttf-parser, …) can pass it through without thinking about the backing.

Failure modes: returns None if the path is unknown, or the file no longer exists / cannot be opened, or the mmap call fails. Callers may retry with a fresh get_font_bytes if they suspect the file was replaced underneath them; the next call re-opens cleanly.

Source

pub fn build() -> Self

Scans system font directories using filename heuristics (no allsorts).

Source

pub fn is_memory_font(&self, id: &FontId) -> bool

Check if a font ID is a memory font (preferred over disk fonts)

Source

pub fn list(&self) -> Vec<(FcPattern, FontId)>

Returns the list of fonts and font patterns.

Returns owned FcPattern values (cloned out of the shared state) — this is the v4.1 API change described on FcFontCache. Callers that need to iterate without cloning should use FcFontCache::for_each_pattern.

Source

pub fn for_each_pattern<F: FnMut(&FcPattern, &FontId)>(&self, f: F)

Iterate over every (pattern, id) pair under a single read guard. f is called once per entry — avoids the per-entry clone that [list] incurs.

Source

pub fn is_empty(&self) -> bool

Returns true if the cache contains no font patterns

Source

pub fn len(&self) -> usize

Returns the number of font patterns in the cache

Source

pub fn query( &self, pattern: &FcPattern, trace: &mut Vec<TraceMsg>, ) -> Option<FontMatch>

Queries a font from the in-memory cache, returns the first found font (early return) Memory fonts are always preferred over disk fonts with the same match quality.

Source

pub fn compute_fallbacks( &self, font_id: &FontId, trace: &mut Vec<TraceMsg>, ) -> Vec<FontMatchNoFallback>

Compute fallback fonts for a given font This is a lazy operation that can be expensive - only call when actually needed (e.g., for FFI or debugging, not needed for resolve_char)

Source

pub fn get_memory_font(&self, id: &FontId) -> Option<FcFont>

Get in-memory font data (cloned out of the shared state).

Source

pub fn query_matches_internal( k: &FcPattern, pattern: &FcPattern, trace: &mut Vec<TraceMsg>, ) -> bool

Source

pub fn resolve_font_chain( &self, font_families: &[String], weight: FcWeight, italic: PatternMatch, oblique: PatternMatch, trace: &mut Vec<TraceMsg>, ) -> FontFallbackChain

Resolve a complete font fallback chain for a CSS font-family stack This is the main entry point for font resolution with caching Automatically expands generic CSS families (serif, sans-serif, monospace) to OS-specific fonts

§Arguments
  • font_families - CSS font-family stack (e.g., [“Arial”, “sans-serif”])
  • text - The text to render (used to extract Unicode ranges)
  • weight - Font weight
  • italic - Italic style requirement
  • oblique - Oblique style requirement
  • trace - Debug trace messages
§Returns

A complete font fallback chain with CSS fallbacks and Unicode fallbacks

§Example
let cache = FcFontCache::build();
let families = vec!["Arial".to_string(), "sans-serif".to_string()];
let chain = cache.resolve_font_chain(&families, FcWeight::Normal, 
                                      PatternMatch::DontCare, PatternMatch::DontCare, 
                                      &mut Vec::new());
// On macOS: families expanded to ["Arial", "San Francisco", "Helvetica Neue", "Lucida Grande"]
Source

pub fn resolve_font_chain_with_os( &self, font_families: &[String], weight: FcWeight, italic: PatternMatch, oblique: PatternMatch, trace: &mut Vec<TraceMsg>, os: OperatingSystem, ) -> FontFallbackChain

Resolve font chain with explicit OS specification (useful for testing)

Source

pub fn resolve_font_chain_with_scripts( &self, font_families: &[String], weight: FcWeight, italic: PatternMatch, oblique: PatternMatch, scripts_hint: Option<&[UnicodeRange]>, trace: &mut Vec<TraceMsg>, ) -> FontFallbackChain

Resolve a font fallback chain, restricting Unicode fallbacks to the caller-supplied set of scripts (usually derived from the actual text content of the document).

  • scripts_hint: None → back-compat behaviour, equivalent to FcFontCache::resolve_font_chain: pulls in fallback fonts for the full DEFAULT_UNICODE_FALLBACK_SCRIPTS set.
  • scripts_hint: Some(&[]) → no Unicode fallbacks attached. For an ASCII-only page this avoids pulling Arial Unicode MS, CJK fonts, etc. into memory when they’re not needed.
  • scripts_hint: Some(&[CJK]) → only CJK fallback attached.

The chain cache is keyed so an ASCII-only resolution cannot be served from a slot populated by a default/all-scripts resolution.

Source

pub fn extract_font_name_tokens(name: &str) -> Vec<String>

Extract tokens from a font name E.g., “NotoSansJP” -> [“Noto”, “Sans”, “JP”] E.g., “Noto Sans CJK JP” -> [“Noto”, “Sans”, “CJK”, “JP”]

Source

pub fn calculate_unicode_coverage(ranges: &[UnicodeRange]) -> u64

Find fallback fonts for a given pattern

Source

pub fn calculate_unicode_compatibility( requested: &[UnicodeRange], available: &[UnicodeRange], ) -> i32

Calculate how well a font’s Unicode ranges cover the requested ranges Returns a compatibility score (higher is better, 0 means no overlap)

Source

pub fn calculate_style_score(original: &FcPattern, candidate: &FcPattern) -> i32

Trait Implementations§

Source§

impl Clone for FcFontCache

Source§

fn clone(&self) -> Self

Shallow clone — the returned handle shares the same underlying state as self. Writes through either are visible to both. This is the whole point of the v4.1 redesign; callers that need an isolated frozen copy must explicitly request one (e.g. via snapshot_state, which is intentionally not provided because we no longer have a use case for it).

1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for FcFontCache

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for FcFontCache

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.