Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge #83 update: Em Box Height follows the font's typo box or cap height

aiongg2d67dc873707
diff --cc crates/compose/src/tests.rs
index 3d327419e,ff5b836fc..508fed1ac
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@@ -2000,199 -1589,9 +2000,200 @@@ fn only_english_text_gets_english_hyphe
assert_eq!(hyphenated(&d2, sid), 0, "French isn't hyphenated with English rules");
}
+// A text frame's bottom inset constrains its last baseline. The full font descent
+// still belongs to the line metrics, caret geometry and measured content height.
+fn baseline_fit_doc(text: &str, height: f64) -> (Document, StoryId, ItemId) {
+ let (mut d, sid, fid) = doc_with(text, Rect::new(0.0, 0.0, 200.0, height), ParaAttrs::default());
+ let tf = d.item_mut(fid).unwrap().text_frame_mut().unwrap();
+ tf.options.first_baseline = FirstBaseline::Fixed;
+ tf.options.first_baseline_min = 10.0;
+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {
+ f.over.font_family = Some("Source Serif 4".into());
+ f.over.size = Some(8.0);
+ f.over.leading = Some(designcraft_doc::Leading::Points(11.0));
+ });
+ (d, sid, fid)
+}
+
+#[test]
+fn horizontal_text_fits_its_baseline_at_the_bottom_inset() {
+ // Include spaces, a nonprinting anchor and real descenders, rather than only capitals.
+ let text = format!("{}Map gaps ", designcraft_doc::ANCHOR_MARK);
+ let (d, sid, _) = baseline_fit_doc(&text, 10.0);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset());
+ let line = &cs.frames[0].lines[0];
+ assert_eq!(line.baseline, 10.0);
+ assert!(line.descent > 0.0);
+ assert!(cs.frames[0].content_height > 10.0, "measured content must retain descenders");
+ assert!(line.glyphs.iter().any(|g| g.visible && text[g.byte..].starts_with('g')));
+}
+
+#[test]
+fn bottom_baseline_fit_preserves_leading_and_paragraph_spacing() {
+ let text = "Heading\nFirst line\u{2028}Second line\u{2028}Last line.";
+ let (mut d, sid, fid) = baseline_fit_doc(text, 65.5);
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.inset = [9.0; 4];
+ d.story_mut(sid).unwrap().paras[0].para.space_after = Some(4.5);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset());
+ assert_eq!(cs.frames[0].lines.iter().map(|l| l.baseline).collect::<Vec<_>>(), [19.0, 34.5, 45.5, 56.5]);
+ assert_eq!(cs.frames[0].columns[0].y1, 56.5);
+ assert_eq!(cs.frames[0].range.end, text.len());
+}
+
+#[test]
+fn baseline_beyond_bottom_still_oversets_and_threads() {
+ let text = "First\u{2028}Second";
+ let (mut d, sid, f1) = baseline_fit_doc(text, 20.75);
+ let before = compose_story(&d, sid, &ComposeOptions::default());
+ assert_eq!(before.line_count(), 1);
+ assert_eq!(before.overset_at, Some("First\u{2028}".len()));
+ let lid = d.default_layer();
+ let (f2, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 50.0, 200.0, 60.0), lid, "", ParaFormat::default()).unwrap();
+ let options = d.item(f1).unwrap().text_frame().unwrap().options.clone();
+ d.item_mut(f2).unwrap().text_frame_mut().unwrap().options = options;
+ d.thread(f1, f2).unwrap();
+ let after = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!after.is_overset());
+ assert_eq!(after.frames.iter().map(|f| f.lines.len()).collect::<Vec<_>>(), [1, 1]);
+ assert_eq!(after.frames[0].lines[0].baseline, before.frames[0].lines[0].baseline);
+}
+
+#[test]
+fn vertical_text_keeps_its_full_cross_line_extent() {
+ let (mut d, sid, fid) = baseline_fit_doc("Map", 200.0);
+ let it = d.item_mut(fid).unwrap();
+ it.path = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 200.0));
+ d.story_mut(sid).unwrap().vertical = true;
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(cs.is_overset());
+ assert_eq!(cs.line_count(), 0);
+}
+
+#[test]
+fn inline_objects_still_clear_the_bottom_edge() {
+ let (mut d, sid, _) = baseline_fit_doc("Text", 10.0);
+ let it = designcraft_doc::Item::new(
+ ItemId(d.alloc()),
+ d.default_layer(),
+ designcraft_doc::Shape::Rectangle,
+ designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 6.0, 6.0)),
+ );
+ d.story_mut(sid).unwrap().insert_object(0, designcraft_doc::AnchoredObject::new(it, designcraft_doc::AnchorPosition::Inline { y_offset: -3.0 }));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(cs.is_overset());
+ assert_eq!(cs.line_count(), 0);
+}
+
+#[test]
+fn custom_anchors_do_not_change_bottom_baseline_fitting() {
+ let (mut d, sid, _) = baseline_fit_doc("Text", 10.0);
+ let it = designcraft_doc::Item::new(
+ ItemId(d.alloc()),
+ d.default_layer(),
+ designcraft_doc::Shape::Rectangle,
+ designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 6.0, 6.0)),
+ );
+ let pos = designcraft_doc::AnchorPosition::Custom {
+ x_relative: Default::default(),
+ y_relative: Default::default(),
+ x_offset: 0.0,
+ y_offset: 0.0,
+ object_point: 0,
+ ref_point: 0,
+ keep_within_column: false,
+ };
+ d.story_mut(sid).unwrap().insert_object(0, designcraft_doc::AnchoredObject::new(it, pos));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset());
+ assert_eq!(cs.line_count(), 1);
+ assert_eq!(cs.frames[0].objects.len(), 1);
+}
+
+#[test]
+fn baseline_shift_keeps_its_metrics_and_glyph_offset_at_bottom() {
+ let (mut d, sid, _) = baseline_fit_doc("Map", 10.0);
+ let plain = compose_story(&d, sid, &ComposeOptions::default());
+ d.story_mut(sid).unwrap().format_chars(0..3, |f| f.over.baseline_shift = Some(-3.0));
+ let shifted = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!plain.is_overset() && !shifted.is_overset());
+ let (p, s) = (&plain.frames[0].lines[0], &shifted.frames[0].lines[0]);
+ assert_eq!(p.baseline, s.baseline);
+ assert!((s.descent - p.descent - 3.0).abs() < 1e-6);
+ assert!((s.glyphs[0].y - p.glyphs[0].y - 3.0).abs() < 1e-6);
+}
+
+#[test]
+fn path_text_keeps_the_original_vertical_fit_limit() {
+ // A path's synthetic layout area is not an ordinary text frame: admitting a
+ // second line would paint both lines on the same path, regardless of leading.
+ for separator in ['\n', designcraft_doc::story::FORCED_LINE_BREAK] {
+ for leading in [8.0, 10.0] {
+ let text = format!("HELLO{separator}WORLD");
+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default());
+ let it = d.item_mut(fid).unwrap();
+ it.shape = designcraft_doc::Shape::Path;
+ it.path = designcraft_geom::shapes::line(Point::ZERO, Point::new(200.0, 0.0));
+ it.text_frame_mut().unwrap().options.path =
+ Some(designcraft_doc::PathType { start: 0.0, flip: false, align: designcraft_doc::PathAlign::Baseline });
+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {
+ f.over.font_family = Some("Source Serif 4".into());
+ f.over.size = Some(20.0);
+ f.over.leading = Some(designcraft_doc::Leading::Points(leading));
+ });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert_eq!(cs.line_count(), 1, "{separator:?}, leading {leading}");
+ assert_eq!(cs.overset_at, Some("HELLO".len() + separator.len_utf8()));
+ }
+ }
+}
+
+fn two_keep_frames(text: &str) -> (Document, StoryId, ItemId, ItemId) {
+ let (mut d, sid, first) = baseline_fit_doc(text, 48.0);
+ d.item_mut(first).unwrap().path = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 75.0, 48.0));
+ let lid = d.default_layer();
+ let (second, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 0.0, 210.0, 69.0), lid, "", ParaFormat::default()).unwrap();
+ let options = d.item(first).unwrap().text_frame().unwrap().options.clone();
+ d.item_mut(second).unwrap().text_frame_mut().unwrap().options = options;
+ d.thread(first, second).unwrap();
+ (d, sid, first, second)
+}
+
+#[test]
+fn keep_chain_spanning_frames_does_not_empty_its_top_column() {
+ let a = "One\u{2028}Two\u{2028}Three\u{2028}Four\u{2028}Five\u{2028}Six";
+ let b = "Seven\u{2028}Eight\u{2028}Nine\u{2028}Ten";
+ let text = format!("{a}\n{b}\nEnd");
+ let (mut d, sid, first, second) = two_keep_frames(&text);
+ let paras = &mut d.story_mut(sid).unwrap().paras;
+ paras[0].para.keep_with_next = Some(2);
+ paras[0].para.space_after = Some(2.0);
+ paras[1].para.keep_with_next = Some(2);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ // The keep chain cannot fit in either column. Fall back to flowing it, rather
+ // than moving a paragraph already at a column top and throwing that column away.
+ assert_eq!(cs.frame(first).unwrap().lines.len(), 4);
+ assert_eq!(cs.frame(second).unwrap().lines.len(), 6);
+ assert_eq!(cs.overset_at, Some(a.len() + b.len() + 2));
+}
+
+#[test]
+fn satisfiable_keep_chain_still_moves_together_to_the_next_frame() {
+ let text = "One\u{2028}Two\nHeading\nSubheading\nBody";
+ let (mut d, sid, first, second) = two_keep_frames(text);
+ let paras = &mut d.story_mut(sid).unwrap().paras;
+ paras[1].para.keep_with_next = Some(1);
+ paras[2].para.keep_with_next = Some(1);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset());
+ assert_eq!(cs.frame(first).unwrap().lines.len(), 2);
+ assert_eq!(cs.frame(second).unwrap().lines.iter().map(|l| l.para).collect::<Vec<_>>(), [1, 2, 3]);
+}
+
/// OS/2 field offsets: sTypoAscender, sxHeight, sCapHeight.
const TYPO_ASCENDER: usize = 68;
+ const TYPO_DESCENDER: usize = 70;
const X_HEIGHT: usize = 86;
const CAP_HEIGHT: usize = 88;
diff --cc crates/fonts/src/tests_vertical.rs
index ff87011f9,1e3cd4fb4..062437157
--- a/crates/fonts/src/tests_vertical.rs
+++ b/crates/fonts/src/tests_vertical.rs
@@@ -111,30 -111,26 +111,40 @@@ fn fonts_without_vmtx_use_the_em_box()
assert_eq!(face.em_box(), (830.0, -170.0));
assert_eq!(face.v_advance(gid), face.upem);
assert_eq!(face.v_origin(gid), 830.0);
- // Without BASE either: the OS/2 typo ascender and descender (1000, -326), centred on one em.
+ // Without BASE either: the typo ascender and descender (1000, -326) span more than one em, so
+ // the em box is centred on half the OS/2 cap height (660).
let face = face_of(with_table_len(font_with("No Base", &['一']).unwrap(), b"BASE", 0).unwrap());
- assert_eq!(face.em_box(), (837.0, -163.0));
- // Without OS/2: the ascender and descender, the same way.
- let face = face_of(with_table_len(with_table_len(font_with("No OS2", &['一']).unwrap(), b"BASE", 0).unwrap(), b"OS/2", 0).unwrap());
- let (top, bottom) = face.em_box();
- assert_eq!(top - bottom, face.upem);
- assert!((top + bottom - (face.ascent - face.descent)).abs() < 1e-9, "{top} {bottom}");
+ assert_eq!(face.em_box(), (830.0, -170.0));
+ assert_eq!(face.declared_em_box(), Some((830.0, -170.0)));
+ // Typo ascender and descender one em apart: the typo ascender is the top.
+ let typo = with_table_u16(font_with("Typo Em", &['一']).unwrap(), b"OS/2", 68, 860).unwrap();
+ let typo = with_table_u16(typo, b"OS/2", 70, u16::from_be_bytes((-140i16).to_be_bytes())).unwrap();
+ let face = face_of(with_table_len(typo, b"BASE", 0).unwrap());
+ assert_eq!(face.em_box(), (860.0, -140.0));
+ // Without OS/2: centred on half the H glyph's height (656).
+ let no_os2 = |font: Vec<u8>| face_of(with_table_len(with_table_len(font, b"BASE", 0).unwrap(), b"OS/2", 0).unwrap());
+ let face = no_os2(font_mapping("No OS2", &[('一', 'X'), ('H', 'H')]).unwrap());
+ assert_eq!(face.em_box(), (828.0, -172.0));
+ // Without an H either: 0.88 em above the baseline, which the font doesn't declare.
+ let face = no_os2(font_with("No OS2 No H", &['一']).unwrap());
+ assert_eq!(face.em_box(), (880.0, -120.0));
+ assert_eq!(face.declared_em_box(), None);
}
+#[test]
+fn icf_box_comes_from_base_else_an_inset_em_box() {
+ let font = font_with("ICF", &['一']).unwrap();
+ let face = face_of(with_base(&font, &[(*b"ideo", -120), (*b"idtp", 880), (*b"icfb", -80), (*b"icft", 840)]).unwrap());
+ assert_eq!((face.em_box(), face.icf_box()), ((880.0, -120.0), (840.0, -80.0)));
+ // One of the two: mirrored inside the em box.
+ let face = face_of(with_base(&font, &[(*b"ideo", -120), (*b"icfb", -90)]).unwrap());
+ assert_eq!(face.icf_box(), (850.0, -90.0));
+ // No ICF baselines (Source Sans 3's BASE has only ideo and romn): the em box inset by 5% of the em.
+ let face = face_of(font);
+ assert_eq!(face.em_box(), (830.0, -170.0));
+ assert_eq!(face.icf_box(), (780.0, -120.0));
+}
+
#[test]
fn broken_vertical_tables_do_not_panic() {
let mut fonts = vec![("synthetic", vertical_font())];
diff --cc crates/fonts/src/vertical.rs
index a85413332,b9f3002a5..b42159bba
--- a/crates/fonts/src/vertical.rs
+++ b/crates/fonts/src/vertical.rs
@@@ -53,48 -53,29 +53,47 @@@ impl<'a> VMetrics<'a>
}
}
- /// The ideographic em box (top, bottom) in font units, y up: `BASE` `idtp`/`ideo`, else the OS/2
- /// typo ascender and descender, else the ascender and descender; the last two centred on one em.
- /// The flag is true for an em box from `BASE`.
+ /// The ideographic em box (top, bottom) in font units, y up, one em tall: `BASE` `idtp`/`ideo`;
+ /// else topped by the OS/2 typo ascender when the typo ascender and descender span exactly one em;
+ /// else centred on half the cap height (OS/2 `sCapHeight`, else the `H` glyph's top); else 0.88 em
+ /// above the baseline. The flag is false for that last fallback.
pub(crate) fn em_box(face: &FontFace) -> ((f64, f64), bool) {
let upem = face.upem;
- let font = face.skrifa();
- if let Some(b) = font.as_ref().and_then(|f| base_em_box(f, upem)) {
+ let fallback = ((upem * 0.88, upem * -0.12), false);
+ let Some(font) = face.skrifa() else { return fallback };
+ if let Some(b) = base_em_box(&font, upem) {
return (b, true);
}
- let centred = |asc: f64, desc: f64| {
- let span = asc - desc;
- (span > 0.0 && span.is_finite()).then(|| {
- let top = asc - (span - upem) / 2.0;
- (top, top - upem)
- })
- };
- let em = font
- .and_then(|f| f.os2().ok())
- .and_then(|t| centred(f64::from(t.s_typo_ascender()), f64::from(t.s_typo_descender())))
- .or_else(|| centred(face.ascent, -face.descent))
- .unwrap_or((upem * 0.88, upem * -0.12));
- (em, false)
+ let typo_top = font.os2().ok().and_then(|t| {
+ let (asc, desc) = (f64::from(t.s_typo_ascender()), f64::from(t.s_typo_descender()));
+ (asc - desc == upem && asc > 0.0 && asc <= upem).then_some(asc)
+ });
+ let top = typo_top.or_else(|| {
+ let declared = font.metrics(Size::unscaled(), face.location()).cap_height.map(f64::from);
+ let cap = crate::fontdb::plausible(declared, upem).or_else(|| crate::fontdb::measured_top(&font, face.location(), &['H'], upem))?;
+ Some((upem + cap) / 2.0)
+ });
+ top.map_or(fallback, |top| ((top, top - upem), true))
}
+/// The ideographic character face (ICF) box (top, bottom) in font units, y up: `BASE`
+/// `icft`/`icfb` (one of them alone is mirrored inside the em box), else the em box inset by 5% of
+/// the em at the top and bottom.
+pub(crate) fn icf_box(face: &FontFace) -> (f64, f64) {
+ let (top, bottom) = face.em_box();
+ let font = face.skrifa();
+ let base = match font.as_ref().and_then(|f| base_box(f, b"icfb", b"icft")) {
+ Some((Some(b), Some(t))) => Some((t, b)),
+ Some((Some(b), None)) => Some((top - (b - bottom), b)),
+ Some((None, Some(t))) => Some((t, bottom + (top - t))),
+ _ => None,
+ };
+ base.filter(|(t, b)| t.is_finite() && b.is_finite() && t > b).unwrap_or_else(|| {
+ let inset = (top - bottom) * 0.05;
+ (top - inset, bottom + inset)
+ })
+}
+
/// The em box from the `BASE` table's horizontal axis: the Han script's values, else the default
/// script's, else the first script's that has them.
fn base_em_box(font: &skrifa::FontRef<'_>, upem: f64) -> Option<(f64, f64)> {