Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

42.2 KB
Raw Blame
//! Fonts shared by canvas text and the UI engine: bundled font registration, the CSS `font`
//! shorthand, and CSS font matching on CoreText that behaves like Chrome on macOS.
//!
//! * Family lists are walked in order; the first family that exists supplies the *primary* font
//!   (metrics, baselines). Characters it lacks fall back through the remaining families, then the
//!   system (CoreText's per-character fallback, which is what Chrome calls too).
//! * Faces within a family are chosen with the CSS Fonts 4 weight/style algorithm. Requests of
//!   weight ≥ 600 that land on a lighter face get Chrome's synthetic bold (a Skia-style outline
//!   stroke, see [`fake_bold_stroke`]); italic requests on upright-only families get a −¼ skew.
//! * Generic families resolve like Chrome's macOS defaults (verified against Chrome 158):
//!   `serif` → Times, `sans-serif` → Helvetica, `monospace` → Courier, `cursive` → Apple Chancery,
//!   `fantasy` → Papyrus, `system-ui` / `BlinkMacSystemFont` → the system UI font. Chrome does not
//!   support `-apple-system` or `ui-monospace`; like Chrome they match nothing (and fall through).
//! * Bundled fonts (`<bundle>/fonts`, Nunito 600/800 and ZCOOL KuaiLe, the game's Google Fonts)
//!   take precedence over installed fonts of the same family name, as @font-face rules do.
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::PathBuf;
use std::ptr::NonNull;
use std::rc::Rc;
use std::sync::{Mutex, Once};

use objc2_core_foundation::{CFArray, CFDictionary, CFNumber, CFRange, CFRetained, CFSet, CFString, CFType, CFURL, CGAffineTransform, CGFloat};
use objc2_core_text::{
    kCTFontCascadeListAttribute, kCTFontFamilyNameAttribute, kCTFontTraitsAttribute, kCTFontWeightTrait, kCTFontWidthTrait, CTFont,
    CTFontDescriptor, CTFontManagerCopyAvailableFontFamilyNames, CTFontManagerCreateFontDescriptorsFromURL, CTFontManagerRegisterFontsForURL,
    CTFontManagerScope, CTFontSymbolicTraits, CTFontTableOptions, CTFontUIFontType,
};

/// What to look up: a CSS family list plus weight/style/size.
pub struct FontQuery<'a> {
    pub families: &'a [String],
    pub weight: u16,
    pub italic: bool,
    pub size: f64,
}

/// A resolved font at a size.
pub struct Font {
    /// The primary face at `size`, with a cascade list for the remaining CSS families and the
    /// system fallbacks (emoji, CJK) — for consumers that let CoreText do fallback. For
    /// Chrome-exact fallback (which face, synthetic bold per face) itemize with [`Font::runs`].
    pub ct: CFRetained<CTFont>,
    /// requested weight ≥ 600 but the face is lighter: embolden like Skia (see [`fake_bold_stroke`])
    pub synthetic_bold: bool,
    /// italic requested but the family has no italic/oblique face: skew x by −¼ (y-down)
    pub synthetic_italic: bool,
    /// CoreText metrics of the primary face (unrounded, px)
    pub ascent: f64,
    pub descent: f64,
    pub line_gap: f64,
    pub x_height: f64,
    pub cap_height: f64,
    // ---- extensions
    pub size: f64,
    /// the weight that was asked for
    pub weight: u16,
    pub italic: bool,
    /// family name of the primary face
    pub family: String,
    /// `ct` without a cascade list (what glyph runs are drawn with)
    pub plain: CFRetained<CTFont>,
    /// a color (emoji) font: glyphs are bitmaps, never emboldened
    pub color: bool,
    /// the rest of the CSS family list, already matched (fallback order)
    chain: Vec<Rc<Font>>,
    /// OS/2 typo ascender/descender in px, when the face has them
    typo: Option<(f64, f64)>,
    /// cache for system fallback fonts by PostScript name
    fallbacks: RefCell<HashMap<String, Rc<Font>>>,
}

/// One run of text that uses one face (see [`Font::runs`]).
pub struct FontRun {
    /// UTF-16 range in the text
    pub start: usize,
    pub end: usize,
    pub font: Rc<Font>,
}

/// Blink's line metrics for a font (what `line-height: normal` and canvas text metrics use).
#[derive(Clone, Copy, Debug)]
pub struct LineMetrics {
    pub ascent: f64,
    pub descent: f64,
    pub line_gap: f64,
}

impl LineMetrics {
    /// `line-height: normal`
    pub fn line_spacing(&self) -> f64 {
        self.ascent + self.descent + self.line_gap
    }
}

impl Font {
    /// Ascent/descent rounded the way Blink's `FontMetrics` does on macOS (including the
    /// Times/Helvetica/Courier ascent hack that keeps line heights compatible with Safari).
    pub fn line_metrics(&self) -> LineMetrics {
        let mut ascent = self.ascent.round();
        let descent = self.descent.round();
        let line_gap = self.line_gap.round();
        if matches!(self.family.as_str(), "Times" | "Helvetica" | "Courier") {
            ascent += ((ascent + descent) * 0.15 + 0.5).floor();
        }
        LineMetrics { ascent, descent, line_gap }
    }

    /// Normalized OS/2 typo ascent/descent summing to the em size (Blink's
    /// `NormalizedTypoAscentAndDescent`, used for canvas `top`/`middle`/`bottom` baselines and the
    /// em-height text metrics). Values are LayoutUnit-rounded (1/64 px) like Blink.
    pub fn em_ascent_descent(&self) -> (f64, f64) {
        let lu = |v: f64| (v * 64.0).round() / 64.0;
        let (asc, height) = match self.typo {
            Some((a, d)) => (a, a + d),
            None => {
                let m = self.line_metrics();
                (m.ascent, m.ascent + m.descent)
            }
        };
        if height <= 0.0 || asc < 0.0 || asc > height {
            let half = lu(self.size / 2.0);
            return (half, half);
        }
        let a = lu(asc * self.size / height);
        (a, lu(self.size) - a)
    }

    /// Split `text` (UTF-16) into runs by the face that renders them, the way Chrome's font
    /// fallback does: each grapheme goes to the first font in the CSS list that has all its
    /// characters (emoji-presentation graphemes prefer color fonts), else to the system fallback
    /// font for it. Fallback faces get synthetic bold/italic by the same rules as the primary.
    pub fn runs(self: &Rc<Self>, text: &[u16]) -> Vec<FontRun> {
        let mut runs: Vec<FontRun> = Vec::new();
        let mut i = 0;
        while i < text.len() {
            let end = grapheme_end(text, i);
            let cluster = &text[i..end];
            let font = self.font_for(cluster, text, i);
            match runs.last_mut() {
                Some(r) if Rc::ptr_eq(&r.font, &font) => r.end = end,
                _ => runs.push(FontRun { start: i, end, font }),
            }
            i = end;
        }
        runs
    }

    fn font_for(self: &Rc<Self>, cluster: &[u16], text: &[u16], at: usize) -> Rc<Font> {
        // Whitespace and controls stay with the current font (Chrome keeps spaces in the primary
        // font's run unless it lacks a space glyph).
        let first = decode_utf16_at(cluster, 0).0;
        let emoji = is_emoji_cluster(cluster);
        let candidates = std::iter::once(self).chain(self.chain.iter());
        let mut first_with_glyphs: Option<&Rc<Font>> = None;
        for f in candidates {
            if has_glyphs(&f.plain, cluster) {
                if !emoji || f.color {
                    return f.clone();
                }
                first_with_glyphs.get_or_insert(f);
            }
        }
        if emoji {
            if let Some(e) = self.emoji_font() {
                if has_glyphs(&e.plain, cluster) {
                    return e;
                }
            }
        }
        if let Some(f) = first_with_glyphs {
            return f.clone();
        }
        if first < 0x20 || (0x7f..0xa0).contains(&first) || is_default_ignorable(first) {
            return self.clone();
        }
        self.system_fallback(text, at, cluster.len())
    }

    fn emoji_font(self: &Rc<Self>) -> Option<Rc<Font>> {
        let key = "AppleColorEmoji".to_string();
        if let Some(f) = self.fallbacks.borrow().get(&key) {
            return Some(f.clone());
        }
        let fam = family("Apple Color Emoji")?;
        let face = fam.faces.first()?.clone();
        let f = Rc::new(make_font(&face, self.size, self.weight, self.italic, false, Vec::new()));
        self.fallbacks.borrow_mut().insert(key, f.clone());
        Some(f)
    }

    fn system_fallback(self: &Rc<Self>, text: &[u16], at: usize, len: usize) -> Rc<Font> {
        let s = cfstring_utf16(text);
        let ct = unsafe { self.plain.for_string_with_language(&s, CFRange { location: at as isize, length: len as isize }, None) };
        let ps = unsafe { ct.post_script_name() }.to_string();
        if ps == unsafe { self.plain.post_script_name() }.to_string() {
            return self.clone();
        }
        if let Some(f) = self.fallbacks.borrow().get(&ps) {
            return f.clone();
        }
        let desc = unsafe { ct.font_descriptor() };
        let face = face_from_descriptor(desc).unwrap_or_else(|| Face { desc: unsafe { ct.font_descriptor() }, weight: 400, italic: false, normal_width: true, system_ui: None });
        let synth_bold = self.weight >= 600 && face.weight < 600;
        let synth_italic = self.italic && !face.italic;
        let f = Rc::new(make_font(&face, self.size, self.weight, self.italic, synth_bold || self.synthetic_bold && synth_bold, Vec::new()).with_synthetic_italic(synth_italic));
        self.fallbacks.borrow_mut().insert(ps, f.clone());
        f
    }

    fn with_synthetic_italic(mut self, on: bool) -> Self {
        self.synthetic_italic = on;
        self
    }
}

impl std::fmt::Debug for Font {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Font({} {}px w{} sb={} si={})", self.family, self.size, self.weight, self.synthetic_bold, self.synthetic_italic)
    }
}

/// A parsed CSS `font` shorthand.
#[derive(Clone, Debug, PartialEq)]
pub struct ParsedFont {
    pub families: Vec<String>,
    pub weight: u16,
    pub italic: bool,
    /// px
    pub size: f64,
    pub line_height: Option<String>,
    // ---- extensions
    pub small_caps: bool,
    /// font-stretch keyword other than `normal`, as written
    pub stretch: Option<String>,
    /// `oblique` (vs `italic`) — both select slanted faces
    pub oblique: bool,
}

impl ParsedFont {
    /// Chrome's serialization of `ctx.font` (style, weight, variant, size, families).
    pub fn to_css(&self) -> String {
        let mut s = String::new();
        if self.italic {
            s.push_str(if self.oblique { "oblique " } else { "italic " });
        }
        match self.weight {
            400 => {}
            700 => s.push_str("bold "),
            w => {
                s.push_str(&w.to_string());
                s.push(' ');
            }
        }
        if self.small_caps {
            s.push_str("small-caps ");
        }
        s.push_str(&fmt_num(self.size));
        s.push_str("px ");
        for (i, f) in self.families.iter().enumerate() {
            if i > 0 {
                s.push_str(", ");
            }
            if is_generic(f) || (is_identifier_sequence(f) && !f.contains(' ')) {
                s.push_str(f);
            } else {
                s.push('"');
                s.push_str(&f.replace('\\', "\\\\").replace('"', "\\\""));
                s.push('"');
            }
        }
        s
    }
}

/// Shortest decimal for a CSS number (Chrome prints up to 6 significant digits).
pub fn fmt_num(v: f64) -> String {
    if v == v.trunc() && v.abs() < 1e15 {
        return format!("{}", v as i64);
    }
    let s = format!("{:.6}", v);
    let s = s.trim_end_matches('0').trim_end_matches('.');
    s.to_string()
}

fn is_generic(f: &str) -> bool {
    matches!(f, "serif" | "sans-serif" | "monospace" | "cursive" | "fantasy" | "system-ui" | "math" | "emoji" | "fangsong" | "ui-serif" | "ui-sans-serif" | "ui-monospace" | "ui-rounded")
}

fn is_identifier_sequence(f: &str) -> bool {
    f.split(' ').all(|w| {
        let mut ch = w.chars();
        match ch.next() {
            None => false,
            Some(c) if c.is_ascii_digit() => false,
            Some('-') => {
                let rest: Vec<char> = w.chars().skip(1).collect();
                !rest.is_empty() && !rest[0].is_ascii_digit() && rest.iter().all(|c| c.is_alphanumeric() || *c == '-' || *c == '_' || !c.is_ascii())
            }
            Some(c) => (c.is_alphabetic() || c == '_' || !c.is_ascii()) && ch.all(|c| c.is_alphanumeric() || c == '-' || c == '_' || !c.is_ascii()),
        }
    })
}

/// Parse a CSS `font` shorthand (as accepted by `ctx.font` and the `font` property). Relative
/// sizes resolve against the canvas default (10px); keywords use Chrome's defaults (medium 16px).
pub fn parse_shorthand(css_font: &str) -> Option<ParsedFont> {
    let s = css_font.trim();
    if s.is_empty() {
        return None;
    }
    let lower = s.to_ascii_lowercase();
    if matches!(lower.as_str(), "inherit" | "initial" | "unset" | "revert" | "revert-layer") {
        return None;
    }
    // System font keywords (Chrome on macOS: the system font at 13px).
    if matches!(lower.as_str(), "caption" | "icon" | "menu" | "message-box" | "small-caption" | "status-bar") {
        return Some(ParsedFont { families: vec!["system-ui".into()], weight: 400, italic: false, size: 13.0, line_height: None, small_caps: false, stretch: None, oblique: false });
    }
    let mut p = ParsedFont { families: Vec::new(), weight: 400, italic: false, size: 0.0, line_height: None, small_caps: false, stretch: None, oblique: false };
    let mut rest = s;
    let mut seen_style = false;
    let mut seen_weight = false;
    let mut seen_variant = false;
    let mut seen_stretch = false;
    let mut normals = 0;
    loop {
        rest = rest.trim_start();
        let tok_end = rest.find(|c: char| c.is_whitespace()).unwrap_or(rest.len());
        let tok = &rest[..tok_end];
        if tok.is_empty() {
            return None;
        }
        let t = tok.to_ascii_lowercase();
        // A size token (possibly "12px/1.5") ends the prefix.
        let size_part = t.split('/').next().unwrap_or("");
        if let Some(px) = parse_font_size(size_part) {
            p.size = px;
            let mut after = &rest[tok_end..];
            if let Some(slash) = tok.find('/') {
                let lh = &tok[slash + 1..];
                if lh.is_empty() {
                    after = after.trim_start();
                    let e = after.find(|c: char| c.is_whitespace()).unwrap_or(after.len());
                    p.line_height = Some(after[..e].to_string());
                    after = &after[e..];
                } else {
                    p.line_height = Some(lh.to_string());
                }
            } else {
                let a = after.trim_start();
                if let Some(lh) = a.strip_prefix('/') {
                    let lh = lh.trim_start();
                    let e = lh.find(|c: char| c.is_whitespace()).unwrap_or(lh.len());
                    if e == 0 {
                        return None;
                    }
                    p.line_height = Some(lh[..e].to_string());
                    after = &lh[e..];
                }
            }
            p.families = parse_families(after)?;
            return Some(p);
        }
        match t.as_str() {
            "normal" => normals += 1,
            "italic" if !seen_style => {
                seen_style = true;
                p.italic = true;
            }
            "oblique" if !seen_style => {
                seen_style = true;
                p.italic = true;
                p.oblique = true;
            }
            "small-caps" if !seen_variant => {
                seen_variant = true;
                p.small_caps = true;
            }
            "bold" if !seen_weight => {
                seen_weight = true;
                p.weight = 700;
            }
            "bolder" if !seen_weight => {
                seen_weight = true;
                p.weight = 700;
            }
            "lighter" if !seen_weight => {
                seen_weight = true;
                p.weight = 100;
            }
            "ultra-condensed" | "extra-condensed" | "condensed" | "semi-condensed" | "semi-expanded" | "expanded" | "extra-expanded" | "ultra-expanded" if !seen_stretch => {
                seen_stretch = true;
                p.stretch = Some(t.clone());
            }
            _ => {
                if !seen_weight {
                    if let Ok(w) = t.parse::<f64>() {
                        if (1.0..=1000.0).contains(&w) && !t.starts_with('+') {
                            seen_weight = true;
                            p.weight = w.round() as u16;
                            rest = &rest[tok_end..];
                            continue;
                        }
                    }
                }
                return None;
            }
        }
        if normals > 4 {
            return None;
        }
        rest = &rest[tok_end..];
    }
}

fn parse_font_size(t: &str) -> Option<f64> {
    let kw = match t {
        "xx-small" => Some(9.0),
        "x-small" => Some(10.0),
        "small" => Some(13.0),
        "medium" => Some(16.0),
        "large" => Some(18.0),
        "x-large" => Some(24.0),
        "xx-large" => Some(32.0),
        "xxx-large" => Some(48.0),
        "larger" => Some(12.0),
        "smaller" => Some(8.333333),
        _ => None,
    };
    if kw.is_some() {
        return kw;
    }
    let num_end = t.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E')).unwrap_or(t.len());
    // "e" may begin a unit ("em", "ex"): back off if what follows is a letter
    let mut num_end = num_end;
    while num_end > 0 && matches!(t.as_bytes()[num_end - 1], b'e' | b'E') {
        num_end -= 1;
    }
    let (n, unit) = t.split_at(num_end);
    let v: f64 = n.parse().ok()?;
    if !v.is_finite() || v < 0.0 {
        return None;
    }
    let px = match unit {
        "px" => v,
        "pt" => v * 4.0 / 3.0,
        "pc" => v * 16.0,
        "in" => v * 96.0,
        "cm" => v * 96.0 / 2.54,
        "mm" => v * 96.0 / 25.4,
        "q" => v * 96.0 / 101.6,
        "em" | "%" if unit == "%" => v * 10.0 / 100.0,
        "em" => v * 10.0,
        "rem" => v * 16.0,
        "ex" => v * 5.0,
        "ch" => v * 5.0,
        "" if v == 0.0 => 0.0,
        _ => return None,
    };
    Some(px)
}

fn parse_families(s: &str) -> Option<Vec<String>> {
    let mut out = Vec::new();
    let mut chars = s.trim().chars().peekable();
    loop {
        while chars.peek().is_some_and(|c| c.is_whitespace()) {
            chars.next();
        }
        let Some(&c) = chars.peek() else { break };
        if c == '"' || c == '\'' {
            chars.next();
            let mut name = String::new();
            let mut closed = false;
            while let Some(ch) = chars.next() {
                if ch == '\\' {
                    if let Some(n) = chars.next() {
                        name.push(n);
                    }
                } else if ch == c {
                    closed = true;
                    break;
                } else {
                    name.push(ch);
                }
            }
            if !closed {
                return None;
            }
            out.push(name);
            while chars.peek().is_some_and(|c| c.is_whitespace()) {
                chars.next();
            }
            match chars.next() {
                None => break,
                Some(',') => continue,
                Some(_) => return None,
            }
        } else {
            let mut name = String::new();
            for ch in chars.by_ref() {
                if ch == ',' {
                    break;
                }
                name.push(ch);
            }
            let words: Vec<&str> = name.split_whitespace().collect();
            if words.is_empty() {
                return None;
            }
            let joined = words.join(" ");
            if !is_identifier_sequence(&joined) {
                return None;
            }
            let lower = joined.to_ascii_lowercase();
            if words.len() == 1 && (is_generic(&lower) || lower == "-webkit-body" || lower == "-webkit-standard") {
                out.push(lower);
            } else if words.len() == 1 && matches!(lower.as_str(), "inherit" | "initial" | "unset" | "default" | "revert") {
                return None;
            } else {
                out.push(joined);
            }
        }
    }
    if out.is_empty() { None } else { Some(out) }
}

/// Stroke width (px) that reproduces Skia's fake bold at `size`: Skia strokes glyph outlines with
/// `size × k`, k interpolated from 1/24 at 9px to 1/32 at 36px (clamped outside).
pub fn fake_bold_stroke(size: f64) -> f64 {
    let k = if size <= 9.0 {
        1.0 / 24.0
    } else if size >= 36.0 {
        1.0 / 32.0
    } else {
        let t = (size - 9.0) / (36.0 - 9.0);
        1.0 / 24.0 + t * (1.0 / 32.0 - 1.0 / 24.0)
    };
    size * k
}

// ------------------------------------------------------------------------------------ registry

static FONT_DIR: Mutex<Option<PathBuf>> = Mutex::new(None);
static REGISTER: Once = Once::new();
static FONT_FILES: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());

pub(crate) fn set_dir(dir: PathBuf) {
    *FONT_DIR.lock().unwrap() = Some(dir);
}

/// Register the bundled fonts with CoreText for this process (idempotent, any thread).
pub(crate) fn register() {
    REGISTER.call_once(|| {
        let Some(dir) = FONT_DIR.lock().unwrap().clone() else { return };
        let Ok(rd) = std::fs::read_dir(&dir) else { return };
        let mut files: Vec<PathBuf> = rd
            .filter_map(|e| e.ok().map(|e| e.path()))
            .filter(|p| matches!(p.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase()).as_deref(), Some("ttf" | "otf" | "ttc")))
            .collect();
        files.sort();
        for f in &files {
            if let Some(url) = CFURL::from_file_path(f) {
                let ok = unsafe { CTFontManagerRegisterFontsForURL(&url, CTFontManagerScope::Process, std::ptr::null_mut()) };
                if !ok {
                    // Already registered (e.g. a second page) is fine; anything else is worth a note.
                    let _ = ok;
                }
            }
        }
        *FONT_FILES.lock().unwrap() = files;
    });
}

#[derive(Clone)]
struct Face {
    desc: CFRetained<CTFontDescriptor>,
    weight: u16,
    /// italic or oblique
    italic: bool,
    normal_width: bool,
    /// system UI font: weight is applied through the weight trait at creation
    system_ui: Option<f64>,
}

struct Family {
    #[allow(dead_code)]
    name: String,
    faces: Vec<Face>,
}

thread_local! {
    static BUNDLED: RefCell<Option<HashMap<String, Rc<Family>>>> = const { RefCell::new(None) };
    static SYSTEM_NAMES: RefCell<Option<HashMap<String, String>>> = const { RefCell::new(None) };
    static FAMILIES: RefCell<HashMap<String, Option<Rc<Family>>>> = RefCell::new(HashMap::new());
    static FONTS: RefCell<HashMap<(String, u16, bool, u64), Rc<Font>>> = RefCell::new(HashMap::new());
}

fn bundled() -> HashMap<String, Rc<Family>> {
    BUNDLED.with(|b| {
        if let Some(m) = b.borrow().as_ref() {
            return m.clone();
        }
        register();
        let mut fams: HashMap<String, Family> = HashMap::new();
        for f in FONT_FILES.lock().unwrap().iter() {
            let Some(url) = CFURL::from_file_path(f) else { continue };
            let Some(descs) = (unsafe { CTFontManagerCreateFontDescriptorsFromURL(&url) }) else { continue };
            let descs: CFRetained<CFArray<CTFontDescriptor>> = unsafe { CFRetained::cast_unchecked(descs) };
            for d in descs.iter() {
                let Some(name) = (unsafe { d.attribute(kCTFontFamilyNameAttribute) }).and_then(|v| v.downcast::<CFString>().ok()) else { continue };
                let name = name.to_string();
                let Some(face) = face_from_descriptor(d) else { continue };
                fams.entry(name.to_lowercase()).or_insert_with(|| Family { name: name.clone(), faces: Vec::new() }).faces.push(face);
            }
        }
        let m: HashMap<String, Rc<Family>> = fams.into_iter().map(|(k, v)| (k, Rc::new(v))).collect();
        *b.borrow_mut() = Some(m.clone());
        m
    })
}

fn system_family_name(lower: &str) -> Option<String> {
    SYSTEM_NAMES.with(|s| {
        if s.borrow().is_none() {
            let names = unsafe { CTFontManagerCopyAvailableFontFamilyNames() };
            let names: CFRetained<CFArray<CFString>> = unsafe { CFRetained::cast_unchecked(names) };
            let mut m = HashMap::new();
            for n in names.iter() {
                let n = n.to_string();
                m.entry(n.to_lowercase()).or_insert(n);
            }
            *s.borrow_mut() = Some(m);
        }
        s.borrow().as_ref().unwrap().get(lower).cloned()
    })
}

const OS2: u32 = u32::from_be_bytes(*b"OS/2");

fn os2(ct: &CTFont) -> Option<Vec<u8>> {
    let d = unsafe { ct.table(OS2, CTFontTableOptions::NoOptions) }?;
    Some(d.to_vec())
}

fn be_u16(b: &[u8], at: usize) -> Option<u16> {
    Some(u16::from_be_bytes([*b.get(at)?, *b.get(at + 1)?]))
}

/// Weight/style/width of a face, from its OS/2 table (what Chrome's matcher sees) with CoreText
/// traits as the fallback.
fn face_from_descriptor(desc: CFRetained<CTFontDescriptor>) -> Option<Face> {
    let ct = unsafe { CTFont::with_font_descriptor(&desc, 16.0, std::ptr::null()) };
    let traits = unsafe { ct.symbolic_traits() };
    let mut italic = traits.contains(CTFontSymbolicTraits::TraitItalic);
    let mut weight = None;
    let mut width_class = 5u16;
    if let Some(t) = os2(&ct) {
        weight = be_u16(&t, 4).filter(|w| (1..=1000).contains(w));
        width_class = be_u16(&t, 6).unwrap_or(5);
        if let Some(sel) = be_u16(&t, 62) {
            italic |= sel & 1 != 0 || sel & (1 << 9) != 0;
        }
    }
    let weight = weight.unwrap_or_else(|| ct_weight_to_css(ct_weight_trait(&desc)));
    // Some fonts use 1..9 in usWeightClass (old convention).
    let weight = if weight < 10 { weight * 100 } else { weight };
    let normal_width = width_class == 5 || {
        let w = ct_trait(&desc, unsafe { kCTFontWidthTrait }).unwrap_or(0.0);
        w.abs() < 0.05
    };
    Some(Face { desc, weight, italic, normal_width, system_ui: None })
}

fn ct_trait(desc: &CTFontDescriptor, key: &CFString) -> Option<f64> {
    let traits = unsafe { desc.attribute(kCTFontTraitsAttribute) }?.downcast::<CFDictionary>().ok()?;
    let traits: CFRetained<CFDictionary<CFString, CFNumber>> = unsafe { CFRetained::cast_unchecked(traits) };
    traits.get(key)?.as_f64()
}

fn ct_weight_trait(desc: &CTFontDescriptor) -> f64 {
    ct_trait(desc, unsafe { kCTFontWeightTrait }).unwrap_or(0.0)
}

// CoreText weight trait ↔ CSS weight (AppKit's NSFontWeight constants).
const CT_WEIGHTS: [(f64, f64); 9] = [(-0.8, 100.0), (-0.6, 200.0), (-0.4, 300.0), (0.0, 400.0), (0.23, 500.0), (0.3, 600.0), (0.4, 700.0), (0.56, 800.0), (0.62, 900.0)];

fn ct_weight_to_css(w: f64) -> u16 {
    if w <= CT_WEIGHTS[0].0 {
        return 100;
    }
    for pair in CT_WEIGHTS.windows(2) {
        let (a, b) = (pair[0], pair[1]);
        if w <= b.0 {
            let t = (w - a.0) / (b.0 - a.0);
            return (a.1 + t * (b.1 - a.1)).round() as u16;
        }
    }
    900
}

fn css_weight_to_ct(w: u16) -> f64 {
    let w = w as f64;
    if w <= 100.0 {
        return -0.8;
    }
    for pair in CT_WEIGHTS.windows(2) {
        let (a, b) = (pair[0], pair[1]);
        if w <= b.1 {
            let t = (w - a.1) / (b.1 - a.1);
            return a.0 + t * (b.0 - a.0);
        }
    }
    0.62
}

fn generic_family(name: &str) -> Option<&'static str> {
    Some(match name {
        "serif" | "-webkit-standard" | "-webkit-body" => "Times",
        "sans-serif" => "Helvetica",
        "monospace" => "Courier",
        "cursive" => "Apple Chancery",
        "fantasy" => "Papyrus",
        _ => return None,
    })
}

fn family(name: &str) -> Option<Rc<Family>> {
    let lower = name.to_lowercase();
    if let Some(f) = FAMILIES.with(|m| m.borrow().get(&lower).cloned()) {
        return f;
    }
    let found = lookup_family(name, &lower);
    FAMILIES.with(|m| m.borrow_mut().insert(lower, found.clone()));
    found
}

fn lookup_family(original: &str, lower: &str) -> Option<Rc<Family>> {
    if lower == "system-ui" || lower == "blinkmacsystemfont" {
        let ui = unsafe { CTFont::new_ui_font_for_language(CTFontUIFontType::System, 16.0, None) }?;
        let desc = unsafe { ui.font_descriptor() };
        let faces = [100u16, 200, 300, 400, 500, 600, 700, 800, 900]
            .iter()
            .map(|&w| Face { desc: desc.clone(), weight: w, italic: false, normal_width: true, system_ui: Some(css_weight_to_ct(w)) })
            .collect();
        return Some(Rc::new(Family { name: "system-ui".into(), faces }));
    }
    if let Some(g) = generic_family(lower) {
        return family(g);
    }
    if let Some(f) = bundled().get(lower) {
        return Some(f.clone());
    }
    // Some installed families (Times, Courier on macOS 26) are hidden from the family list but
    // match by name, as they do in Chrome: try the listed spelling, then the name as written.
    let mut names: Vec<String> = Vec::new();
    if let Some(c) = system_family_name(lower) {
        names.push(c);
    }
    names.push(original.to_string());
    for candidate in names {
        let cfname = CFString::from_str(&candidate);
        let attrs = CFDictionary::<CFString, CFType>::from_slices(&[unsafe { kCTFontFamilyNameAttribute }], &[&*cfname as &CFType]);
        let desc = unsafe { CTFontDescriptor::with_attributes(attrs.as_opaque()) };
        let mut key = unsafe { kCTFontFamilyNameAttribute } as *const CFString as *const std::ffi::c_void;
        let Some(mandatory) = (unsafe { CFSet::new(None, &mut key, 1, &objc2_core_foundation::kCFTypeSetCallBacks) }) else { continue };
        let Some(list) = (unsafe { desc.matching_font_descriptors(Some(&mandatory)) }) else { continue };
        let list: CFRetained<CFArray<CTFontDescriptor>> = unsafe { CFRetained::cast_unchecked(list) };
        let faces: Vec<Face> = list
            .iter()
            .filter(|d| unsafe { d.attribute(kCTFontFamilyNameAttribute) }.and_then(|v| v.downcast::<CFString>().ok()).is_some_and(|f| f.to_string().to_lowercase() == lower))
            .filter_map(face_from_descriptor)
            .collect();
        if !faces.is_empty() {
            return Some(Rc::new(Family { name: candidate, faces }));
        }
    }
    None
}

/// CSS Fonts 4 §5.2 font matching for weight and style (stretch: prefer normal widths).
fn match_face(fam: &Family, weight: u16, italic: bool) -> Face {
    let mut pool: Vec<&Face> = fam.faces.iter().filter(|f| f.normal_width).collect();
    if pool.is_empty() {
        pool = fam.faces.iter().collect();
    }
    let styled: Vec<&Face> = pool.iter().copied().filter(|f| f.italic == italic).collect();
    let pool = if styled.is_empty() { pool } else { styled };
    let weights: Vec<u16> = pool.iter().map(|f| f.weight).collect();
    let w = pick_weight(weight, &weights);
    // Several faces with the same weight (e.g. duplicates across files): first wins.
    pool.into_iter().find(|f| f.weight == w).cloned().unwrap_or_else(|| fam.faces[0].clone())
}

fn pick_weight(desired: u16, available: &[u16]) -> u16 {
    if available.contains(&desired) {
        return desired;
    }
    let mut asc: Vec<u16> = available.to_vec();
    asc.sort_unstable();
    asc.dedup();
    let below_desc = || asc.iter().rev().copied().find(|&w| w < desired);
    let above_asc = |min: u16| asc.iter().copied().find(|&w| w > min);
    if (400..=500).contains(&desired) {
        if let Some(w) = asc.iter().copied().find(|&w| w > desired && w <= 500) {
            return w;
        }
        if let Some(w) = below_desc() {
            return w;
        }
        if let Some(w) = above_asc(500) {
            return w;
        }
    } else if desired < 400 {
        if let Some(w) = below_desc() {
            return w;
        }
        if let Some(w) = above_asc(desired) {
            return w;
        }
    } else {
        if let Some(w) = above_asc(desired) {
            return w;
        }
        if let Some(w) = below_desc() {
            return w;
        }
    }
    asc.first().copied().unwrap_or(400)
}

fn make_font(face: &Face, size: f64, weight: u16, italic: bool, synthetic_bold: bool, chain: Vec<Rc<Font>>) -> Font {
    let desc = match face.system_ui {
        Some(ctw) => {
            let num = CFNumber::new_f64(ctw);
            let traits = CFDictionary::<CFString, CFType>::from_slices(&[unsafe { kCTFontWeightTrait }], &[&*num as &CFType]);
            let attrs = CFDictionary::<CFString, CFType>::from_slices(&[unsafe { kCTFontTraitsAttribute }], &[&*traits as &CFType]);
            unsafe { face.desc.copy_with_attributes(attrs.as_opaque()) }
        }
        None => face.desc.clone(),
    };
    let plain = unsafe { CTFont::with_font_descriptor(&desc, size as CGFloat, std::ptr::null()) };
    // Cascade list: remaining CSS families in order, then the system defaults.
    let mut cascade: Vec<CFRetained<CTFontDescriptor>> = chain.iter().map(|f| unsafe { f.plain.font_descriptor() }).collect();
    if let Some(sys) = unsafe { plain.default_cascade_list_for_languages(None) } {
        let sys: CFRetained<CFArray<CTFontDescriptor>> = unsafe { CFRetained::cast_unchecked(sys) };
        cascade.extend(sys.iter());
    }
    let ct = if cascade.is_empty() {
        plain.clone()
    } else {
        let arr = CFArray::from_retained_objects(&cascade);
        let attrs = CFDictionary::<CFString, CFType>::from_slices(&[unsafe { kCTFontCascadeListAttribute }], &[arr.as_opaque() as &CFType]);
        let d = unsafe { desc.copy_with_attributes(attrs.as_opaque()) };
        unsafe { CTFont::with_font_descriptor(&d, size as CGFloat, std::ptr::null()) }
    };
    let typo = os2(&plain).and_then(|t| {
        let asc = be_u16(&t, 68)? as i16 as f64;
        let desc = be_u16(&t, 70)? as i16 as f64;
        let upem = unsafe { plain.units_per_em() } as f64;
        (upem > 0.0).then(|| (asc * size / upem, -desc * size / upem))
    });
    let color = unsafe { plain.symbolic_traits() }.contains(CTFontSymbolicTraits::TraitColorGlyphs);
    Font {
        family: unsafe { plain.family_name() }.to_string(),
        ascent: unsafe { plain.ascent() },
        descent: unsafe { plain.descent() },
        line_gap: unsafe { plain.leading() },
        x_height: unsafe { plain.x_height() },
        cap_height: unsafe { plain.cap_height() },
        ct,
        plain,
        synthetic_bold: synthetic_bold && !color,
        synthetic_italic: italic && !face.italic,
        size,
        weight,
        italic,
        color,
        chain,
        typo,
        fallbacks: RefCell::new(HashMap::new()),
    }
}

/// Resolve a CSS font (cached). Never fails: with no usable family the default (Times) is used,
/// as in Chrome.
pub fn resolve(q: &FontQuery) -> Rc<Font> {
    let key = (q.families.join("\u{1}"), q.weight, q.italic, q.size.to_bits());
    if let Some(f) = FONTS.with(|m| m.borrow().get(&key).cloned()) {
        return f;
    }
    let mut matched: Vec<Face> = Vec::new();
    for name in q.families {
        if let Some(fam) = family(name) {
            matched.push(match_face(&fam, q.weight, q.italic));
        }
    }
    if matched.is_empty() {
        // Chrome's standard font; if even that is missing, any font CoreText will give us.
        match family("Times").or_else(|| family("Helvetica")) {
            Some(fam) => matched.push(match_face(&fam, q.weight, q.italic)),
            None => {
                let ct = unsafe { CTFont::with_name(&CFString::from_str("Times-Roman"), q.size, std::ptr::null()) };
                matched.push(Face { desc: unsafe { ct.font_descriptor() }, weight: 400, italic: false, normal_width: true, system_ui: None });
            }
        }
    }
    let synth = |f: &Face| q.weight >= 600 && f.weight < 600 && f.system_ui.is_none();
    let chain: Vec<Rc<Font>> = matched[1..].iter().map(|f| Rc::new(make_font(f, q.size, q.weight, q.italic, synth(f), Vec::new()))).collect();
    let font = Rc::new(make_font(&matched[0], q.size, q.weight, q.italic, synth(&matched[0]), chain));
    FONTS.with(|m| {
        let mut m = m.borrow_mut();
        if m.len() > 512 {
            m.clear();
        }
        m.insert(key, font.clone());
    });
    font
}

/// Resolve a parsed shorthand.
pub fn resolve_parsed(p: &ParsedFont) -> Rc<Font> {
    resolve(&FontQuery { families: &p.families, weight: p.weight, italic: p.italic, size: p.size })
}

// ------------------------------------------------------------------------------- text helpers

pub(crate) fn cfstring_utf16(text: &[u16]) -> CFRetained<CFString> {
    unsafe { CFString::with_characters(None, text.as_ptr(), text.len() as isize) }.unwrap_or_else(|| CFString::from_str(""))
}

fn has_glyphs(ct: &CTFont, cluster: &[u16]) -> bool {
    // Variation selectors, ZWJ and tag characters are consumed by shaping; only real characters
    // need glyphs.
    let mut i = 0;
    while i < cluster.len() {
        let (cp, n) = decode_utf16_at(cluster, i);
        if !is_default_ignorable(cp) && !(0x1F3FB..=0x1F3FF).contains(&cp) || i == 0 {
            let units = &cluster[i..i + n];
            let mut glyphs = [0u16; 2];
            let ok = unsafe { ct.glyphs_for_characters(NonNull::new_unchecked(units.as_ptr() as *mut u16), NonNull::new_unchecked(glyphs.as_mut_ptr()), n as isize) };
            if !ok || glyphs[0] == 0 {
                return false;
            }
        }
        i += n;
    }
    true
}

pub(crate) fn decode_utf16_at(s: &[u16], i: usize) -> (u32, usize) {
    let c = s[i] as u32;
    if (0xD800..0xDC00).contains(&c) && i + 1 < s.len() {
        let d = s[i + 1] as u32;
        if (0xDC00..0xE000).contains(&d) {
            return (0x10000 + ((c - 0xD800) << 10) + (d - 0xDC00), 2);
        }
    }
    (c, 1)
}

fn is_default_ignorable(cp: u32) -> bool {
    matches!(cp, 0x200B..=0x200F | 0x2028..=0x202E | 0x2060..=0x206F | 0xFE00..=0xFE0F | 0xFEFF | 0xE0000..=0xE0FFF | 0x00AD | 0x034F)
}

fn is_combining(cp: u32) -> bool {
    matches!(cp, 0x0300..=0x036F | 0x1AB0..=0x1AFF | 0x1DC0..=0x1DFF | 0x20D0..=0x20FF | 0xFE20..=0xFE2F | 0x3099..=0x309A)
}

/// End of the grapheme starting at `i` (a simplified UAX #29: combining marks, variation
/// selectors, emoji modifiers, ZWJ sequences, keycaps, flags and tag sequences).
pub fn grapheme_end(s: &[u16], i: usize) -> usize {
    let (first, n) = decode_utf16_at(s, i);
    let mut j = i + n;
    if (0x1F1E6..=0x1F1FF).contains(&first) && j < s.len() {
        let (next, m) = decode_utf16_at(s, j);
        if (0x1F1E6..=0x1F1FF).contains(&next) {
            return j + m;
        }
    }
    if first == 0x0D && j < s.len() && s[j] == 0x0A {
        return j + 1;
    }
    while j < s.len() {
        let (cp, m) = decode_utf16_at(s, j);
        if is_combining(cp) || (0xFE00..=0xFE0F).contains(&cp) || (0x1F3FB..=0x1F3FF).contains(&cp) || (0xE0020..=0xE007F).contains(&cp) || cp == 0x20E3 {
            j += m;
        } else if cp == 0x200D {
            j += m;
            if j < s.len() {
                let (_, k) = decode_utf16_at(s, j);
                j += k;
            }
        } else {
            break;
        }
    }
    j
}

/// Graphemes Chrome renders with emoji presentation (default emoji presentation characters,
/// VS16 / keycap / ZWJ / modifier / flag sequences).
fn is_emoji_cluster(cluster: &[u16]) -> bool {
    let (first, n) = decode_utf16_at(cluster, 0);
    let rest = &cluster[n..];
    if rest.contains(&0xFE0E) {
        return false;
    }
    if rest.contains(&0xFE0F) || rest.contains(&0x200D) || rest.contains(&0x20E3) {
        return true;
    }
    if rest.len() >= 2 && (0x1F1E6..=0x1F1FF).contains(&first) {
        return true;
    }
    emoji_presentation(first)
}

fn emoji_presentation(cp: u32) -> bool {
    const BMP: &[(u32, u32)] = &[
        (0x231A, 0x231B), (0x23E9, 0x23EC), (0x23F0, 0x23F0), (0x23F3, 0x23F3), (0x25FD, 0x25FE), (0x2614, 0x2615), (0x2648, 0x2653), (0x267F, 0x267F),
        (0x2693, 0x2693), (0x26A1, 0x26A1), (0x26AA, 0x26AB), (0x26BD, 0x26BE), (0x26C4, 0x26C5), (0x26CE, 0x26CE), (0x26D4, 0x26D4), (0x26EA, 0x26EA),
        (0x26F2, 0x26F3), (0x26F5, 0x26F5), (0x26FA, 0x26FA), (0x26FD, 0x26FD), (0x2705, 0x2705), (0x270A, 0x270B), (0x2728, 0x2728), (0x274C, 0x274C),
        (0x274E, 0x274E), (0x2753, 0x2755), (0x2757, 0x2757), (0x2795, 0x2797), (0x27B0, 0x27B0), (0x27BF, 0x27BF), (0x2B1B, 0x2B1C), (0x2B50, 0x2B50),
        (0x2B55, 0x2B55),
    ];
    if cp < 0x10000 {
        return BMP.iter().any(|&(a, b)| (a..=b).contains(&cp));
    }
    // Supplementary emoji blocks: nearly everything there defaults to emoji presentation; the
    // text-default exceptions are rare symbols that text fonts lack anyway.
    matches!(cp, 0x1F004 | 0x1F0CF | 0x1F18E | 0x1F191..=0x1F19A | 0x1F1E6..=0x1F1FF | 0x1F201 | 0x1F21A | 0x1F22F | 0x1F232..=0x1F236 | 0x1F238..=0x1F23A | 0x1F250..=0x1F251)
        || (0x1F300..=0x1F64F).contains(&cp) && !matches!(cp, 0x1F321..=0x1F32C | 0x1F336 | 0x1F37D | 0x1F394..=0x1F39F | 0x1F3CB..=0x1F3CE | 0x1F3D4..=0x1F3DF | 0x1F3F1..=0x1F3F3 | 0x1F3F5..=0x1F3F7 | 0x1F43F | 0x1F441 | 0x1F4FD..=0x1F4FE | 0x1F53E..=0x1F54A | 0x1F54F | 0x1F568..=0x1F579 | 0x1F57B..=0x1F594 | 0x1F597..=0x1F5A3 | 0x1F5A5..=0x1F5FA)
        || (0x1F680..=0x1F6FF).contains(&cp) && !matches!(cp, 0x1F6C6..=0x1F6CB | 0x1F6CD..=0x1F6CF | 0x1F6D3..=0x1F6D4 | 0x1F6E0..=0x1F6EA | 0x1F6F0..=0x1F6F3)
        || (0x1F7E0..=0x1F7F0).contains(&cp)
        || (0x1F90C..=0x1FAFF).contains(&cp) && cp != 0x1F93B && cp != 0x1F946
}

#[allow(dead_code)]
fn _assert_types(_: CGAffineTransform) {}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn families() {
        for name in ["Times", "Courier", "courier", "times new roman", "Helvetica", "PingFang SC", "Apple Color Emoji", "sans-serif", "system-ui"] {
            let lower = name.to_lowercase();
            let canon = system_family_name(&lower);
            let fam = family(name);
            eprintln!("{name}: canon={canon:?} faces={:?}", fam.map(|f| f.faces.iter().map(|f| (f.weight, f.italic, f.normal_width)).collect::<Vec<_>>()));
        }
        let names = unsafe { CTFontManagerCopyAvailableFontFamilyNames() };
        let names: CFRetained<CFArray<CFString>> = unsafe { CFRetained::cast_unchecked(names) };
        let v: Vec<String> = names.iter().map(|n| n.to_string()).filter(|n| n.starts_with("Tim") || n.starts_with("Cour") || n.starts_with("Apple Ch") || n.starts_with("Papy")).collect();
        eprintln!("{v:?} total {}", names.len());
        let t = unsafe { CTFont::with_name(&CFString::from_str("Times"), 12.0, std::ptr::null()) };
        eprintln!("Times by name: family={} ps={}", unsafe { t.family_name() }, unsafe { t.post_script_name() });
    }
}