Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 53 additions & 105 deletions src/font.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::cell::OnceCell;
use std::collections::HashMap;
use std::fs;
use std::sync::{Mutex, OnceLock};
Expand Down Expand Up @@ -199,14 +198,6 @@ impl FontSet {

// ─── Font Loading ───────────────────────────────────────────────────────────

fn weight_for_level(level: u8) -> Weight {
match level {
1 | 2 => Weight::BLACK,
3 => Weight::EXTRA_BOLD,
_ => Weight::BOLD,
}
}

static FONT_DATA_CACHE: OnceLock<Mutex<HashMap<String, &'static [u8]>>> = OnceLock::new();

fn load_from_handle(handle: &Handle) -> Option<FontRef<'static>> {
Expand Down Expand Up @@ -247,32 +238,19 @@ fn try_load(source: &SystemSource, family: &str, props: &Properties) -> Option<F
load_from_handle(&handle)
}

/// Try to load a font at the requested weight.
///
/// macOS registers bold variants as separate families (e.g. "Avenir Black"),
/// so requesting "Avenir" with Weight::BLACK may return the regular weight.
/// We work around this by trying explicit variant family names first.
/// Try explicit Black and Heavy family names first because macOS can register
/// them separately from the regular family.
fn try_font(source: &SystemSource, family: &str, props: &Properties) -> Option<FontRef<'static>> {
// For bold weights, try explicit variant family names first
let suffixes: &[&str] = if props.weight.0 >= Weight::BLACK.0 {
&["Black", "Heavy"]
} else if props.weight.0 >= Weight::EXTRA_BOLD.0 {
&["ExtraBold", "Heavy", "Bold"]
} else if props.weight.0 >= Weight::BOLD.0 {
&["Bold", "Demi Bold"]
} else {
&[]
};

let normal_props = Properties {
weight: Weight::NORMAL,
..*props
};

for suffix in suffixes {
let variant = format!("{family} {suffix}");
if let Some(font) = try_load(source, &variant, &normal_props) {
return Some(font);
if props.weight == Weight::BLACK {
let normal_props = Properties {
weight: Weight::NORMAL,
..*props
};
for suffix in ["Black", "Heavy"] {
let variant = format!("{family} {suffix}");
if let Some(font) = try_load(source, &variant, &normal_props) {
return Some(font);
}
}
}

Expand Down Expand Up @@ -323,41 +301,13 @@ fn resolve_optional_font(
None
}

/// Per-level cache of resolved font sets. `Config` is loaded once at startup
/// and is constant for the process lifetime, so a level → FontSet mapping is
/// safe to memoize. `SystemSource::new()` and the family-resolution walk are
/// the dominant cost in heading rasterization (~30–40ms each on macOS), and
/// without this cache they were re-paid for every H1–H3 in the document.
static FONT_SETS: [OnceLock<Option<FontSet>>; 6] = [
OnceLock::new(),
OnceLock::new(),
OnceLock::new(),
OnceLock::new(),
OnceLock::new(),
OnceLock::new(),
];

/// Resolve a Latin + CJK + optional emoji font set for the given heading level.
/// Cached per-level for the process lifetime — the first call's `config` wins;
/// subsequent calls with a different `config` return the originally-resolved
/// fonts. Safe today because `Config` is loaded once at startup, but callers
/// shouldn't rely on per-call config.
pub fn get_fonts(level: u8, config: &Config) -> Option<&'static FontSet> {
let idx = level.saturating_sub(1).min(5) as usize;
FONT_SETS[idx]
.get_or_init(|| resolve_font_set(level, config))
.as_ref()
}
static HEADING_FONTS: OnceLock<Option<FontSet>> = OnceLock::new();

// Shared across heading levels within a thread. `SystemSource::new()` walks
// the OS font registry (CoreText / fontconfig / DirectWrite), ~20-30ms per
// call, and we'd otherwise pay it once per heading level. Thread-local
// instead of `static` because on Linux `SystemSource` wraps a raw
// `*mut FcConfig` pointer and is neither `Send` nor `Sync`. The value is
// `Option` because on Linux fontconfig may be unavailable at runtime (see
// `new_system_source`), in which case we render with the bundled font only.
thread_local! {
static SYSTEM_SOURCE: OnceCell<Option<SystemSource>> = const { OnceCell::new() };
/// Resolve the shared heading fonts once using the startup configuration.
pub fn get_fonts(config: &Config) -> Option<&'static FontSet> {
HEADING_FONTS
.get_or_init(|| resolve_font_set(config))
.as_ref()
}

/// Build the system font source, returning `None` when it can't be used.
Expand Down Expand Up @@ -388,43 +338,41 @@ fn fontconfig_available() -> bool {
false
}

fn resolve_font_set(level: u8, config: &Config) -> Option<FontSet> {
SYSTEM_SOURCE.with(|cell| {
let source = cell.get_or_init(new_system_source).as_ref();
let props = Properties {
style: Style::Normal,
weight: weight_for_level(level),
stretch: Stretch::NORMAL,
};
let emoji_props = Properties {
style: Style::Normal,
weight: Weight::NORMAL,
stretch: Stretch::NORMAL,
};

let latin = resolve_font(
source,
&props,
config.font.heading.latin.as_deref(),
preferred_latin_families(),
)?;

let cjk = resolve_font(
source,
&props,
config.font.heading.cjk.as_deref(),
preferred_cjk_families(),
)?;

let emoji = resolve_optional_font(
source,
&emoji_props,
config.font.heading.emoji.as_deref(),
preferred_emoji_families(),
);
fn resolve_font_set(config: &Config) -> Option<FontSet> {
let source = new_system_source();
let props = Properties {
style: Style::Normal,
weight: Weight::BLACK,
stretch: Stretch::NORMAL,
};
let emoji_props = Properties {
style: Style::Normal,
weight: Weight::NORMAL,
stretch: Stretch::NORMAL,
};

Some(FontSet { latin, cjk, emoji })
})
let latin = resolve_font(
source.as_ref(),
&props,
config.font.heading.latin.as_deref(),
preferred_latin_families(),
)?;

let cjk = resolve_font(
source.as_ref(),
&props,
config.font.heading.cjk.as_deref(),
preferred_cjk_families(),
)?;

let emoji = resolve_optional_font(
source.as_ref(),
&emoji_props,
config.font.heading.emoji.as_deref(),
preferred_emoji_families(),
);

Some(FontSet { latin, cjk, emoji })
}

#[cfg(test)]
Expand All @@ -451,7 +399,7 @@ mod tests {
#[test]
fn emoji_font_prefers_renderable_emoji_glyph() {
let config = Config::default();
let fonts = get_fonts(1, &config).expect("fonts should resolve");
let fonts = get_fonts(&config).expect("fonts should resolve");
let glyph = fonts.for_char('😀');
let raster = glyph.font.glyph_raster_image2(glyph.glyph_id, u16::MAX);

Expand Down
2 changes: 1 addition & 1 deletion src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ pub fn render_heading(
}

let st = style::heading_style(level, theme);
let fonts = font::get_fonts(level, config)?;
let fonts = font::get_fonts(config)?;
let scale = PxScale {
x: st.size,
y: st.size,
Expand Down
Loading