Text: Cap Height and x Height first baselines use the font's cap and x heights

This commit is contained in:
aiongg committed 2026-10-07 09:04:59 -04:00
1 parent 84361ca9f9
commit c246f1d34c
4 files changed
+152 -37

No files matched your search

+32 -15
View File
@@ -688,7 +688,9 @@ pub fn compose(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Compo
_ => col,
};
// Estimate slots for the breaker with the paragraph's base leading.
let est_first = cur.next_baseline(f, col, base_leading, base_chars.size * 0.75, base_chars.size * 0.75, &pp);
let est_asc = base_chars.size * 0.75;
let est_tops = Tops { typo_ascent: est_asc, cap: est_asc * 0.72, xh: est_asc * 0.5 };
let est_first = cur.next_baseline(f, col, base_leading, est_asc, est_tops, &pp);
let slots = estimate_slots(f, col, est_first, base_leading, base_chars.size, &glyphs[g0..], &pp, line_no);
let width = |j: usize| -> f64 {
let (x0, x1) = slots.get(j).copied().unwrap_or((col.x0, col.x1));
@@ -708,8 +710,8 @@ pub fn compose(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Compo
for (k, b) in breaks.iter().enumerate() {
let (s, e) = (g0 + b.start, g0 + b.end);
let line_glyphs = &glyphs[s..e.max(s)];
let (asc, typo_asc, desc, lead) = line_metrics(line_glyphs, &glyphs, s, base_leading, base_chars.size, db, &base_chars);
let mut baseline = cur.next_baseline(f, col, lead, asc, typo_asc, &pp);
let (asc, tops, desc, lead) = line_metrics(line_glyphs, &glyphs, s, base_leading, base_chars.size, db, &base_chars);
let mut baseline = cur.next_baseline(f, col, lead, asc, tops, &pp);
// Baseline grid.
if let Some((g_start, inc)) = f.grid
&& (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0))
@@ -1287,18 +1289,20 @@ impl Cursor {
self.last_baseline = None;
self.pending = 0.0;
}
/// Baseline for the next line with leading `lead`, ascent `asc` and typographic ascender
/// `typo_asc`.
fn next_baseline(&self, f: &FrameSpec, col: Rect, lead: f64, asc: f64, typo_asc: f64, _pp: &ParaProps) -> f64 {
/// Baseline for the next line with leading `lead`, ascent `asc` and first baseline heights
/// `tops`.
fn next_baseline(&self, f: &FrameSpec, col: Rect, lead: f64, asc: f64, tops: Tops, _pp: &ParaProps) -> f64 {
match self.last_baseline {
Some(b) => b + lead + self.pending,
None => {
let off = match f.opts.first_baseline {
// Vertical frames keep the ascent.
// Vertical frames measure from the ascent.
FirstBaseline::Ascent if f.opts.vertical => asc,
FirstBaseline::Ascent => typo_asc,
FirstBaseline::CapHeight => asc * 0.72,
FirstBaseline::XHeight => asc * 0.5,
FirstBaseline::CapHeight if f.opts.vertical => asc * 0.72,
FirstBaseline::XHeight if f.opts.vertical => asc * 0.5,
FirstBaseline::Ascent => tops.typo_ascent,
FirstBaseline::CapHeight => tops.cap,
FirstBaseline::XHeight => tops.xh,
FirstBaseline::Leading => lead,
FirstBaseline::Fixed => 0.0,
};
@@ -1308,6 +1312,15 @@ impl Cursor {
}
}
/// A line's tallest typographic ascender, cap height and x height above its baseline: the
/// first baseline offsets.
#[derive(Clone, Copy, Default)]
struct Tops {
typo_ascent: f64,
cap: f64,
xh: f64,
}
fn line_metrics(
line: &[Glyph],
all: &[Glyph],
@@ -1316,25 +1329,29 @@ fn line_metrics(
base_size: f64,
db: &FontDb,
base: &designcraft_doc::CharProps,
) -> (f64, f64, f64, f64) {
) -> (f64, Tops, f64, f64) {
let _ = db;
let src: &[Glyph] = if line.is_empty() { all.get(s..(s + 1).min(all.len())).unwrap_or(&[]) } else { line };
if src.is_empty() {
let face = FontDb::global().face(&base.font_family, &base.font_style);
let k = base_size / face.upem;
return (face.ascent * k, face.typo_ascent * k, face.descent * k, base_leading);
let tops = Tops { typo_ascent: face.typo_ascent * k, cap: face.cap_height * k, xh: face.x_height * k };
return (face.ascent * k, tops, face.descent * k, base_leading);
}
let mut asc: f64 = 0.0;
let mut typo_asc: f64 = 0.0;
let mut tops = Tops::default();
let mut desc: f64 = 0.0;
let mut lead: f64 = 0.0;
for g in src {
asc = asc.max(g.ascent + g.shift.max(0.0));
typo_asc = typo_asc.max(g.typo_ascent + g.shift.max(0.0));
let up = g.shift.max(0.0);
tops.typo_ascent = tops.typo_ascent.max(g.typo_ascent + up);
tops.cap = tops.cap.max(g.cap + up);
tops.xh = tops.xh.max(g.xh + up);
desc = desc.max(g.descent - g.shift.min(0.0));
lead = lead.max(g.leading);
}
(asc, typo_asc, desc, lead)
(asc, tops, desc, lead)
}
/// Widest free horizontal interval of `col` in the band, or None if blocked.
+6
View File
@@ -33,6 +33,8 @@ pub struct Glyph {
pub descent: f64,
/// The leading this character asks for (absolute, or auto = size × auto %).
pub leading: f64,
/// Cap height and x height, scaled like `ascent`: the Cap Height and x Height first baseline
/// offsets.
pub cap: f64,
pub xh: f64,
pub size: f64,
@@ -418,12 +420,16 @@ fn shape_run(
g.adv = o.w;
g.ascent = g.ascent.max(o.h + y);
g.typo_ascent = g.typo_ascent.max(o.h + y);
g.cap = g.cap.max(o.h + y);
g.xh = g.xh.max(o.h + y);
g.descent = g.descent.max(-y);
}
// Pushes its line down by its height and spacing.
None => {
g.ascent += o.h + o.space;
g.typo_ascent += o.h + o.space;
g.cap += o.h + o.space;
g.xh += o.h + o.space;
}
}
if auto || o.y_offset.is_none() {
+97 -10
View File
@@ -1028,10 +1028,15 @@ fn only_english_text_gets_english_hyphenation() {
assert_eq!(hyphenated(&d2, sid), 0, "French isn't hyphenated with English rules");
}
/// Source Sans 3 Regular (OS/2 typo ascender = hhea ascender = 1000/1000 em) renamed to `family`
/// (13 characters, the length of "Source Sans 3"), with OS/2 `sTypoAscender` set to
/// `typo_ascender`, or without an OS/2 table for `None`.
fn typo_test_font(family: &str, typo_ascender: Option<i16>) -> Vec<u8> {
/// OS/2 field offsets: sTypoAscender, sxHeight, sCapHeight.
const TYPO_ASCENDER: usize = 68;
const X_HEIGHT: usize = 86;
const CAP_HEIGHT: usize = 88;
/// Source Sans 3 Regular (1000 units per em; OS/2 typo ascender = hhea ascender = 1000, cap height
/// 660, x height 486) renamed to `family` (13 characters, the length of "Source Sans 3"), with the
/// OS/2 fields at the given offsets set, or without an OS/2 table for `None`.
fn test_font(family: &str, os2_fields: Option<&[(usize, i16)]>) -> Vec<u8> {
let mut b = designcraft_fonts::bundled()[0].to_vec();
assert_eq!(family.len(), "Source Sans 3".len());
let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
@@ -1044,10 +1049,12 @@ fn typo_test_font(family: &str, typo_ascender: Option<i16>) -> Vec<u8> {
}
let tables = u16::from_be_bytes([b[4], b[5]]) as usize;
let rec = (0..tables).map(|t| 12 + 16 * t).find(|&r| &b[r..r + 4] == b"OS/2").unwrap();
match typo_ascender {
Some(v) => {
match os2_fields {
Some(fields) => {
let os2 = u32::from_be_bytes(b[rec + 8..rec + 12].try_into().unwrap()) as usize;
b[os2 + 68..os2 + 70].copy_from_slice(&v.to_be_bytes());
for &(at, v) in fields {
b[os2 + at..os2 + at + 2].copy_from_slice(&v.to_be_bytes());
}
}
// Still sorted between its neighbours, so the table directory stays valid.
None => b[rec..rec + 4].copy_from_slice(b"OS/1"),
@@ -1055,6 +1062,11 @@ fn typo_test_font(family: &str, typo_ascender: Option<i16>) -> Vec<u8> {
b
}
/// [`test_font`] with OS/2 `sTypoAscender` set to `typo_ascender`, or without OS/2 for `None`.
fn typo_test_font(family: &str, typo_ascender: Option<i16>) -> Vec<u8> {
test_font(family, typo_ascender.map(|v| [(TYPO_ASCENDER, v)]).as_ref().map(|f| f.as_slice()))
}
/// First baseline (frame space) of a 20 pt line in `family` in a frame at y = 36 with a 4 pt top
/// inset, set up by `opts`.
fn first_baseline_in(family: &str, opts: impl Fn(&mut designcraft_doc::TextFrameOptions)) -> f64 {
@@ -1092,9 +1104,9 @@ fn ascent_first_baseline_uses_the_typographic_ascender() {
// The minimum offset still wins when it is larger.
assert!(close(at(FirstBaseline::Ascent, 18.0), top + 18.0));
assert!(close(at(FirstBaseline::Ascent, 10.0), top + 14.0));
// The other kinds are unchanged.
assert!(close(at(FirstBaseline::CapHeight, 0.0), top + 20.0 * 0.72));
assert!(close(at(FirstBaseline::XHeight, 0.0), top + 10.0));
// The other kinds don't use it.
assert!(close(at(FirstBaseline::CapHeight, 0.0), top + 0.660 * 20.0));
assert!(close(at(FirstBaseline::XHeight, 0.0), top + 0.486 * 20.0));
assert!(close(at(FirstBaseline::Leading, 0.0), top + 24.0));
assert!(close(at(FirstBaseline::Fixed, 0.0), top));
// Vertical scale scales it like the ascent.
@@ -1153,3 +1165,78 @@ fn vertical_frames_keep_the_ascent_first_baseline() {
// Composed in the turned box (no inset): the hhea ascent, 1 em of 20 pt.
assert!((b - 20.0).abs() < 0.01, "{b}");
}
#[test]
fn cap_height_and_x_height_first_baselines_use_the_fonts_cap_and_x_heights() {
use designcraft_doc::FirstBaseline;
let db = designcraft_fonts::FontDb::global();
db.add_font(test_font("CapXHeight 01", Some(&[(CAP_HEIGHT, 500), (X_HEIGHT, 300)])));
let face = db.face("CapXHeight 01", "Regular");
assert_eq!(face.family, "CapXHeight 01");
assert_eq!((face.ascent, face.cap_height, face.x_height), (1000.0, 500.0, 300.0));
let top = 36.0 + 4.0;
let at = |kind: FirstBaseline, min: f64| {
first_baseline_in("CapXHeight 01", |o| {
o.first_baseline = kind;
o.first_baseline_min = min;
})
};
let close = |a: f64, b: f64| (a - b).abs() < 0.01;
// Cap height 0.5 em and x height 0.3 em of 20 pt, not 0.72 / 0.5 of the 1 em ascent.
assert!(close(at(FirstBaseline::CapHeight, 0.0), top + 10.0), "{}", at(FirstBaseline::CapHeight, 0.0));
assert!(close(at(FirstBaseline::XHeight, 0.0), top + 6.0), "{}", at(FirstBaseline::XHeight, 0.0));
// The minimum offset still wins when it is larger.
assert!(close(at(FirstBaseline::CapHeight, 12.0), top + 12.0));
assert!(close(at(FirstBaseline::XHeight, 5.0), top + 6.0));
// Vertical scale and a raised baseline count, as for the ascent.
let (mut d, sid, fid) = doc_with("Hxg Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());
let st = d.story_mut(sid).unwrap();
st.format_chars(0..7, |f| {
f.over.font_family = Some("CapXHeight 01".into());
f.over.size = Some(20.0);
f.over.v_scale = Some(1.5);
});
st.format_chars(4..5, |f| f.over.baseline_shift = Some(1.0));
let tf = d.item_mut(fid).unwrap().text_frame_mut().unwrap();
tf.options.inset = [4.0, 0.0, 0.0, 0.0];
tf.options.first_baseline = FirstBaseline::CapHeight;
let first = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].baseline;
assert!(close(first(&d), top + 15.0 + 1.0), "{}", first(&d));
d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.first_baseline = FirstBaseline::XHeight;
assert!(close(first(&d), top + 9.0 + 1.0), "{}", first(&d));
}
#[test]
fn cap_height_and_x_height_fall_back_without_usable_os2_values() {
use designcraft_doc::FirstBaseline;
let db = designcraft_fonts::FontDb::global();
// No OS/2 table, zero / negative and absurd values: 0.72 and 0.5 of the (1 em) ascent.
let zero: &[(usize, i16)] = &[(CAP_HEIGHT, 0), (X_HEIGHT, -40)];
let big: &[(usize, i16)] = &[(CAP_HEIGHT, i16::MAX), (X_HEIGHT, i16::MAX)];
for (family, fields) in [("CapXHeightNoO", None), ("CapXHeightNeg", Some(zero)), ("CapXHeightBig", Some(big))] {
db.add_font(test_font(family, fields));
let face = db.face(family, "Regular");
assert_eq!(face.family, family);
assert_eq!((face.cap_height, face.x_height), (face.ascent * 0.72, face.ascent * 0.5), "{family}");
let cap = first_baseline_in(family, |o| o.first_baseline = FirstBaseline::CapHeight);
let x = first_baseline_in(family, |o| o.first_baseline = FirstBaseline::XHeight);
assert!((cap - (40.0 + 14.4)).abs() < 0.01 && (x - (40.0 + 10.0)).abs() < 0.01, "{family}: {cap} {x}");
}
}
#[test]
fn vertical_frames_keep_the_cap_height_and_x_height_first_baselines() {
use designcraft_doc::FirstBaseline;
let db = designcraft_fonts::FontDb::global();
db.add_font(test_font("CapXHeightVrt", Some(&[(CAP_HEIGHT, 500), (X_HEIGHT, 300)])));
let at = |kind: FirstBaseline| {
first_baseline_in("CapXHeightVrt", |o| {
o.first_baseline = kind;
o.vertical = true;
o.inset = [0.0; 4];
})
};
// 0.72 and 0.5 of the 1 em ascent of 20 pt.
assert!((at(FirstBaseline::CapHeight) - 14.4).abs() < 0.01, "{}", at(FirstBaseline::CapHeight));
assert!((at(FirstBaseline::XHeight) - 10.0).abs() < 0.01, "{}", at(FirstBaseline::XHeight));
}
+17 -12
View File
@@ -63,8 +63,8 @@ pub struct FontFace {
pub typo_ascent: f64,
/// Descender in font units (positive = down).
pub descent: f64,
/// Cap height and x height in font units (estimated from the ascent when the font has no OS/2
/// values).
/// Cap height and x height in font units (estimated from the ascent when the font has no
/// plausible OS/2 values): the Cap Height and x Height first baseline offsets.
pub cap_height: f64,
pub x_height: f64,
pub shaper: harfrust::ShaperData,
@@ -433,6 +433,7 @@ fn make_face(bytes: FontBytes, index: u32, family: String, style: String, coords
let settings: Vec<(skrifa::Tag, f32)> = coords.iter().map(|(t, v)| (skrifa::Tag::new(t), *v)).collect();
let location = if coords.is_empty() { Location::default() } else { f.axes().location(settings.iter().copied()) };
let m = f.metrics(Size::unscaled(), &location);
let upem = m.units_per_em.max(1) as f64;
let a = f.attributes();
let hb = harfrust::FontRef::from_index(data, index).ok()?;
let shaper = harfrust::ShaperData::new(&hb);
@@ -450,12 +451,12 @@ fn make_face(bytes: FontBytes, index: u32, family: String, style: String, coords
style,
weight,
italic,
upem: m.units_per_em.max(1) as f64,
upem,
ascent: m.ascent as f64,
typo_ascent: typo_ascent(&f, &location, m.units_per_em.max(1) as f64, m.ascent as f64),
typo_ascent: typo_ascent(&f, &location, upem).unwrap_or(m.ascent as f64),
descent: -(m.descent as f64),
cap_height: m.cap_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.72),
x_height: m.x_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.5),
cap_height: plausible(m.cap_height.map(f64::from), upem).unwrap_or(m.ascent as f64 * 0.72),
x_height: plausible(m.x_height.map(f64::from), upem).unwrap_or(m.ascent as f64 * 0.5),
shaper,
coords,
location,
@@ -466,18 +467,22 @@ fn make_face(bytes: FontBytes, index: u32, family: String, style: String, coords
})
}
/// The OS/2 typographic ascender in font units at `location`, or `fallback` when the font has no
/// OS/2 table or the value isn't a plausible ascender (not above 0, or over 4 em).
fn typo_ascent(f: &skrifa::FontRef<'_>, location: &Location, upem: f64, fallback: f64) -> f64 {
/// A font's height above the baseline (font units) if it is plausible: above 0 and at most 4 em.
fn plausible(v: Option<f64>, upem: f64) -> Option<f64> {
v.filter(|v| *v > 0.0 && *v <= 4.0 * upem)
}
/// The OS/2 typographic ascender in font units at `location`, if the font has an OS/2 table and
/// the value is [`plausible`].
fn typo_ascent(f: &skrifa::FontRef<'_>, location: &Location, upem: f64) -> Option<f64> {
use skrifa::raw::TableProvider;
let Ok(os2) = f.os2() else { return fallback };
let mut v = os2.s_typo_ascender() as f64;
let mut v = f.os2().ok()?.s_typo_ascender() as f64;
if !location.coords().is_empty()
&& let Ok(mvar) = f.mvar()
{
v += mvar.metric_delta(skrifa::raw::tables::mvar::tags::HASC, location.coords()).map_or(0.0, |d| d.to_f64());
}
if v > 0.0 && v <= 4.0 * upem { v } else { fallback }
plausible(Some(v), upem)
}
/// The named style part of a style with axis settings (`Bold {wght:650}` → `Bold`).