DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #330 update: under the Japanese composers a line sits the upper line's leading below it
aionggbac5b091ae61
diff --cc crates/compose/src/lib.rsindex 0ca4f42ea,239b148f0..d8f5d9330--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -1056,18 -922,10 +1057,19 @@@ fn compose_with_db(doc: &Document, storfor (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, desc, lead) = line_metrics(line_glyphs, &glyphs, s, base_leading, base_chars.size, db, &base_chars);+ let (asc, tops, desc, lead) = line_metrics(line_glyphs, &glyphs, s, mark_leading, mark_chars.size, db, &mark_chars);+ let lead = match last_line_mark {+ Some(m) if k + 1 == breaks.len() => lead.max(m),+ _ => lead,+ };- let reference = cjk_line_reference(line_glyphs);+ let (reference, model) = cjk_line_reference(line_glyphs);+ let advance = if cur.last_baseline.is_some() { cur.aki_below.unwrap_or(lead) } else { lead };- let mut baseline = cur.next_baseline(f, col, advance, asc, &pp);+ // Baseline grid: the next grid line at or below.+ let grid = f.grid.filter(|&(_, inc)| {+ inc > 0.0 && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0))+ });+ let snap = |y: f64| grid.map_or(y, |(g_start, inc)| g_start + ((y - g_start) / inc - 1e-6).ceil() * inc);- let mut baseline = cur.next_baseline(f, col, lead, asc, tops, &pp);++ let mut baseline = cur.next_baseline(f, col, advance, asc, tops, &pp);if cur.last_baseline.is_some() {baseline += cur.last_reference - reference;}@@@ -1327,7 -1141,8 +1330,8 @@@baseline: l.baseline,descent: l.descent,reference: cur.last_reference,+ aki_below: cur.aki_below,- pending: pp.space_after,+ pending: pp.space_after.max(pp.span_space_after),};cur.band = Band { para: pi + 1, line0: ft.lines.len(), above: Some(above) };}diff --cc crates/compose/src/tests.rsindex c7d03b98c,f48f455b4..e8d0f16b4--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -1882,972 -1500,36 +1882,1003 @@@ fn first_baseline_in_dir(family: &str,}#[test]-fn cjk_aki_below_sets_the_upper_lines_leading_below_it() {- let lines_with = |para: ParaAttrs| {- let (mut d, sid, _) = doc_with("A\nB", Rect::new(0.0, 0.0, 300.0, 200.0), para);+fn ascent_first_baseline_uses_the_typographic_ascender() {+ use designcraft_doc::FirstBaseline;+ let db = designcraft_fonts::FontDb::global();+ db.add_font(typo_test_font("TypoAscent 07", Some(700)));+ let face = db.face("TypoAscent 07", "Regular");+ assert_eq!(face.family, "TypoAscent 07");+ assert_eq!((face.ascent, face.typo_ascent), (1000.0, 700.0), "hhea 1 em, typo 0.7 em");+ let top = 36.0 + 4.0;+ let at = |kind: FirstBaseline, min: f64| {+ first_baseline_in("TypoAscent 07", |o| {+ o.first_baseline = kind;+ o.first_baseline_min = min;+ })+ };+ let close = |a: f64, b: f64| (a - b).abs() < 0.01;+ // Ascent: top + typo ascender (0.7 em of 20 pt), not the hhea ascender (1 em).+ assert!(close(at(FirstBaseline::Ascent, 0.0), top + 14.0), "{}", at(FirstBaseline::Ascent, 0.0));+ // 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 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));+ // A mixed first line takes its tallest typographic ascender: 0.7 × 20 pt beats 1 em × 10 pt …+ 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..3, |f| {+ f.over.font_family = Some("TypoAscent 07".into());+ f.over.size = Some(20.0);+ });+ st.format_chars(3..7, |f| {+ f.over.font_family = Some("Source Sans 3".into());+ f.over.size = Some(10.0);+ });+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.inset = [4.0, 0.0, 0.0, 0.0];+ let first = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].baseline;+ assert!(close(first(&d), top + 14.0), "{}", first(&d));+ // … and 1 em × 16 pt beats it.+ d.story_mut(sid).unwrap().format_chars(3..7, |f| f.over.size = Some(16.0));+ assert!(close(first(&d), top + 16.0), "{}", first(&d));+}++#[test]+fn ascent_first_baseline_falls_back_to_the_ascent_without_a_usable_typo_ascender() {+ let db = designcraft_fonts::FontDb::global();+ // No OS/2 table, a negative and an absurd typo ascender: the (hhea) ascent, 1 em.+ for (family, typo) in [("TypoAscentNoO", None), ("TypoAscentNeg", Some(-300)), ("TypoAscentBig", Some(i16::MAX))] {+ db.add_font(typo_test_font(family, typo));+ let face = db.face(family, "Regular");+ assert_eq!(face.family, family);+ assert_eq!(face.typo_ascent, face.ascent, "{family}");+ let b = first_baseline_in(family, |_| {});+ assert!((b - (36.0 + 4.0 + 20.0)).abs() < 0.01, "{family}: {b}");+ }+}++#[test]+fn vertical_frames_keep_the_ascent_first_baseline() {+ let db = designcraft_fonts::FontDb::global();+ db.add_font(typo_test_font("TypoAscentVrt", Some(700)));+ let b = first_baseline_in_dir("TypoAscentVrt", true, |o| {+ o.inset = [0.0; 4];+ });+ // 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 a_visible_frame_stroke_insets_the_text() {+ use designcraft_doc::{Stroke, StrokeAlign};+ let line = |stroke: Option<(StrokeAlign, &str)>| {+ let (mut d, sid, fid) = doc_with("Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());+ let it = d.item_mut(fid).unwrap();+ if let Some((align, swatch)) = stroke {+ it.stroke = Stroke { weight: 4.0, align, swatch: swatch.into(), ..Stroke::default() };+ }+ it.text_frame_mut().unwrap().options.inset = [4.0; 4];+ let l = &compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0];+ (l.baseline, l.x0, l.x1)+ };+ let black = designcraft_color::swatch::BLACK;+ let (b, x0, x1) = line(None);+ // The part of the 4 pt stroke inside the frame: half of it centred, all of it inside, none+ // outside or without a colour; on the left and right as on the top.+ for (stroke, d) in [+ ((StrokeAlign::Center, black), 2.0),+ ((StrokeAlign::Inside, black), 4.0),+ ((StrokeAlign::Outside, black), 0.0),+ ((StrokeAlign::Inside, designcraft_color::swatch::NONE), 0.0),+ ] {+ let (sb, sx0, sx1) = line(Some(stroke));+ assert!((sb - (b + d)).abs() < 1e-6, "{stroke:?}: baseline {sb} vs {b}");+ assert!((sx0 - (x0 + d)).abs() < 1e-6 && (sx1 - (x1 - d)).abs() < 1e-6, "{stroke:?}: {sx0}..{sx1} vs {x0}..{x1}");+ }+}++#[test]+fn list_labels_do_not_raise_the_ascent_first_baseline() {+ use designcraft_doc::{CharAttrs, ListType};+ // The paragraph's own character size (the label's) is 40 pt; its text is 10 pt (Source Sans 3:+ // typo ascender 1 em).+ let line = |text: &str, list: ListType| {+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs { list_type: Some(list), ..Default::default() });+ let st = d.story_mut(sid).unwrap();+ for p in &mut st.paras {+ p.chars = CharAttrs { font_family: Some("Source Sans 3".into()), size: Some(40.0), ..Default::default() };+ }+ st.format_chars(0..text.len(), |f| f.over.size = Some(10.0));+ let l = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].clone();+ (l.baseline, l.ascent, l.leading)+ };+ let (b, asc, lead) = line("Hxg Hxg", ListType::None);+ // 1 em of the 10 pt text below the frame top.+ assert!((b - 46.0).abs() < 0.01, "{b}");+ for list in [ListType::Bullets, ListType::Numbers] {+ let (lb, lasc, llead) = line("Hxg Hxg", list);+ assert!((lb - b).abs() < 1e-6, "{list:?}: {lb} vs {b}");+ // The 40 pt label still sets the line's ascent and leading.+ assert!(lasc > asc + 20.0 && (llead - 48.0).abs() < 1e-6 && (lead - 12.0).abs() < 1e-6, "{list:?}: {lasc} {asc} {llead} {lead}");+ }+ // An empty bulleted paragraph sits like an empty paragraph.+ let (eb, _, _) = line("", ListType::None);+ let (ebl, _, _) = line("", ListType::Bullets);+ assert!((ebl - eb).abs() < 1e-6, "{ebl} vs {eb}");+}++#[test]+fn spaces_count_toward_the_ascent_first_baseline() {+ // 10 pt text with a 40 pt space between its words (Source Sans 3: typo ascender 1 em).+ let (mut d, sid, _) = 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("Source Sans 3".into());+ f.over.size = Some(10.0);+ });+ st.format_chars(3..4, |f| f.over.size = Some(40.0));+ let l = &compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0];+ assert!((l.baseline - (36.0 + 40.0)).abs() < 0.01, "{}", l.baseline);+}++#[test]+fn vertical_scale_does_not_move_the_ascent_first_baseline() {+ let db = designcraft_fonts::FontDb::global();+ db.add_font(typo_test_font("TypoAscentVSc", Some(700)));+ let line = |v_scale: f64| {+ let (mut d, sid, fid) = doc_with("Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..3, |f| {+ f.over.font_family = Some("TypoAscentVSc".into());+ f.over.size = Some(20.0);+ f.over.v_scale = Some(v_scale);+ });+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.inset = [4.0, 0.0, 0.0, 0.0];+ let l = &compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0];+ (l.baseline, l.ascent)+ };+ let ((b100, a100), (b200, a200)) = (line(1.0), line(2.0));+ // The typo ascender of the nominal size (0.7 × 20 pt) at 100 % and at 200 %.+ assert!((b100 - (36.0 + 4.0 + 14.0)).abs() < 0.01, "{b100}");+ assert!((b200 - b100).abs() < 0.01, "{b200} vs {b100}");+ // The line box keeps the scaled ascent.+ assert!((a100 - 20.0).abs() < 0.01 && (a200 - 40.0).abs() < 0.01, "{a100} {a200}");+}++#[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: the top of the H (0.656 em) and of the x+ // (0.486 em).+ 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), (656.0, 486.0), "{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 + 13.12)).abs() < 0.01 && (x - (40.0 + 9.72)).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_dir("CapXHeightVrt", true, |o| {+ o.first_baseline = kind;+ 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));+}++// ---------- drop caps ----------++/// `text` set 10 pt on 12 pt leading in a 300 pt measure, with `para` on top.+fn drop_doc(text: &str, para: ParaAttrs) -> (Document, StoryId, ItemId) {+ drop_doc_in(text, Rect::new(0.0, 0.0, 300.0, 1000.0), para)+}++fn drop_doc_in(text: &str, rect: Rect, para: ParaAttrs) -> (Document, StoryId, ItemId) {+ let (mut d, sid, fid) = doc_with(text, rect, para);+ for p in &mut d.story_mut(sid).unwrap().paras {+ p.chars = designcraft_doc::CharAttrs { size: Some(10.0), leading: Some(designcraft_doc::Leading::Points(12.0)), ..Default::default() };+ }+ (d, sid, fid)+}++fn drop_cap(lines: u32, chars: u32) -> ParaAttrs {+ ParaAttrs { drop_cap_lines: Some(lines), drop_cap_chars: Some(chars), ..Default::default() }+}++/// Cap height of a placed glyph, in points.+fn cap_of(g: &PlacedGlyph) -> f64 {+ g.face.cap_height * g.sy+}++/// x of the first glyph of `l` set from story byte `from` on.+fn text_x(l: &Line, from: usize) -> f64 {+ l.glyphs.iter().find(|g| g.len > 0 && g.byte >= from).map(|g| g.x).unwrap()+}++#[test]+fn drop_cap_spans_lines_and_indents_them() {+ let text = [LOREM; 2].join(" ");+ let (plain, psid, _) = drop_doc(&text, ParaAttrs::default());+ let plain = compose_story(&plain, psid, &ComposeOptions::default());+ let (d, sid, _) = drop_doc(&text, drop_cap(3, 1));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let pl = all_lines(&plain);+ assert!(lines.len() > 4);+ // Baselines don't move.+ for (k, l) in lines.iter().enumerate() {+ assert!((l.baseline - (pl[0].baseline + 12.0 * k as f64)).abs() < 1e-6, "line {k} at {}", l.baseline);+ }+ // The drop cap: the first glyph, on line 1, its baseline on line 3's and its cap top on line 1's.+ let dc = &lines[0].glyphs[0];+ assert_eq!((dc.byte, dc.len), (0, 1));+ assert!((lines[0].baseline + dc.y - lines[2].baseline).abs() < 1e-6, "drop cap baseline {}", lines[0].baseline + dc.y);+ let body = lines[0].glyphs.iter().find(|g| g.byte == 1).unwrap();+ let top = lines[2].baseline - cap_of(dc);+ assert!((top - (lines[0].baseline - cap_of(body))).abs() < 0.01, "cap top {top}");+ assert!(dc.sy > body.sy * 3.0);+ // Lines 1–3 start after it, line 4 at the frame edge.+ let right = dc.x + dc.adv;+ assert!(right > 20.0);+ for l in &lines[..3] {+ assert!(text_x(l, 1) >= right - 1e-6, "{} < {right}", text_x(l, 1));+ assert!(l.end_x <= l.x1 + 0.5);+ }+ assert!(text_x(lines[3], 1) < 0.5);+ // The text stays in order: the drop cap starts line 1 (exports and caret read it there).+ assert_eq!(lines[0].range.start, 0);+}++#[test]+fn tab_beside_a_drop_cap_is_measured_from_the_drop_cap() {+ // The line breaker measures a tab from where the line starts, which beside a drop cap is+ // after the drop cap: measured from the frame edge, the tab looks wider and the line breaks+ // a word early.+ let stop = designcraft_doc::TabStop { position: 100.0, align: TabAlign::Left, leader: String::new(), align_on: String::new() };+ let para = ParaAttrs { tabs: Some(vec![stop]), hyphenate: Some(false), ..drop_cap(3, 1) };+ let text = format!("Wort\t{LOREM}");+ let (d, sid, _) = drop_doc(&text, para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let space = |g: &PlacedGlyph| g.len > 0 && text.get(g.byte..).and_then(|s| s.chars().next()).is_some_and(char::is_whitespace);+ let right = lines[0].glyphs.iter().filter(|g| g.visible && !space(g)).map(|g| g.x + g.adv).fold(0.0, f64::max);+ assert!(right <= lines[0].x1 + 0.01, "line 1 ends at {right}, past {}", lines[0].x1);+ let word: f64 = lines[1].glyphs.iter().filter(|g| g.len > 0).take_while(|g| !space(g)).map(|g| g.adv).sum();+ assert!(right + word + 4.0 > lines[0].x1, "line 2's first word ({word} pt) fits after line 1's end at {right} (edge {})", lines[0].x1);+}++#[test]+fn warichu_on_a_drop_cap_line_leaves_the_drop_cap_alone() {+ let text = format!("WABCDEFGH {LOREM}");+ let (mut d, sid, _) = drop_doc(&text, drop_cap(3, 1));+ let plain = compose_story(&d, sid, &ComposeOptions::default());+ let plain_dc = plain.frames[0].lines[0].glyphs[0].clone();+ // A plain drop cap line has no stacked rows: one selection band, caret on the line.+ let pl = &plain.frames[0].lines[0];+ assert_eq!(highlight_quads(pl, 0, 12, false).len(), 1);+ assert_eq!(caret(&plain, 1).map(|c| (c.2, c.3)), Some((pl.baseline, pl.ascent)));+ d.story_mut(sid).unwrap().format_chars(1..9, |f| {+ f.over.warichu = Some(true);+ f.over.warichu_alignment = Some(designcraft_doc::cjk::WarichuAlignment::Left);+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let dc = &l.glyphs[0];+ assert_eq!((dc.byte, dc.x, dc.y, dc.sy), (0, plain_dc.x, plain_dc.y, plain_dc.sy), "the drop cap is not part of the note");+ let at = |byte: usize| l.glyphs.iter().find(|g| g.byte == byte && g.len > 0).unwrap();+ let (top, bot, after) = (at(1), at(5), at(10));+ assert!(bot.y - top.y > 1.0, "the note is stacked in two rows");+ assert!(top.x >= dc.x + dc.adv - 1e-6, "the note starts after the drop cap");+ assert!((after.x - (at(8).x + at(8).adv + at(9).adv)).abs() < 1e-3, "the line closes up after the note");+ // The caret: in the drop cap as tall as it, on a note row that row's baseline, after the+ // note the parent line's.+ let dc_box = l.drop_cap.unwrap();+ assert_eq!(caret(&cs, 0).map(|c| c.2), Some(dc_box.baseline));+ assert!((caret(&cs, 1).unwrap().2 - (l.baseline + top.y)).abs() < 1e-6);+ assert_eq!(caret(&cs, 10).map(|c| (c.2, c.3)), Some((l.baseline, l.ascent)));+ let click = |g: &PlacedGlyph| hit(&cs, 0, designcraft_geom::Point::new(g.x + g.adv * 0.25, l.baseline + g.y)).unwrap();+ assert_eq!((click(top), click(bot), click(after)), (1, 5, 10));+ // Selecting the drop cap and the note: the drop cap's band and one per row.+ assert_eq!(highlight_quads(l, 0, 9, false).len(), 3);+}++#[test]+fn drop_cap_of_two_characters_as_a_local_override() {+ let (d, sid, _) = drop_doc(LOREM, drop_cap(2, 2));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let (a, b) = (&lines[0].glyphs[0], &lines[0].glyphs[1]);+ assert_eq!((a.byte, b.byte), (0, 1));+ let body = lines[0].glyphs.iter().find(|g| g.byte == 2).unwrap();+ for g in [a, b] {+ assert!((lines[0].baseline + g.y - lines[1].baseline).abs() < 1e-6);+ assert!(g.sy > body.sy * 1.5);+ }+ assert!((b.x - (a.x + a.adv)).abs() < 1e-6, "the drop cap characters sit side by side");+ let right = b.x + b.adv;+ assert!(text_x(lines[0], 2) >= right - 1e-6 && text_x(lines[1], 2) >= right - 1e-6);+ assert!(text_x(lines[2], 2) < 0.5);+}++#[test]+fn short_paragraph_keeps_its_drop_cap_and_the_next_paragraph_is_not_indented() {+ let (mut d, sid, _) = drop_doc(&format!("Short.\n{LOREM}"), drop_cap(3, 1));+ d.story_mut(sid).unwrap().paras[1].para = ParaAttrs::default();+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.iter().filter(|l| l.para == 0).count(), 1);+ let dc = &lines[0].glyphs[0];+ // Still three lines tall (it may overlap the next paragraph, which isn't indented).+ assert!((dc.y - 24.0).abs() < 1e-6, "{}", dc.y);+ assert!(text_x(lines[1], 7) < 0.5);+}++#[test]+fn drop_cap_counts_code_points_without_splitting_clusters_and_clamps_to_the_paragraph() {+ // Four characters: a letter, its combining mark, another letter and a no-break space.+ let (d, sid, _) = drop_doc("A\u{301}B\u{a0}rest of the words", drop_cap(2, 4));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let big: Vec<usize> = l.glyphs.iter().filter(|g| g.len > 0 && g.y > 1.0).map(|g| g.byte).collect();+ assert!(big.contains(&0) && big.contains(&3), "{big:?}");+ assert!(big.iter().all(|b| *b < 6), "the r isn't part of it: {big:?}");+ // One character that has a combining mark after it takes the mark too.+ let (d, sid, _) = drop_doc("e\u{301}tude and more words", drop_cap(2, 1));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let big: Vec<usize> = l.glyphs.iter().filter(|g| g.y > 1.0).map(|g| g.byte).collect();+ assert!(!big.is_empty() && big.iter().all(|b| *b < 3), "{big:?}");+ assert!(l.glyphs.iter().any(|g| g.byte == 0 && g.y > 1.0));+ // More characters than the paragraph has: all of them, and nothing of the next paragraph.+ let (mut d, sid, _) = drop_doc("Hi\nNext", drop_cap(2, 50));+ d.story_mut(sid).unwrap().paras[1].para = ParaAttrs::default();+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!(lines[0].glyphs.iter().filter(|g| g.len > 0).all(|g| g.y > 1.0));+ assert!(lines[1].glyphs.iter().all(|g| g.y.abs() < 1e-6));+}++#[test]+fn hostile_drop_cap_values_do_not_panic() {+ for (lines, chars) in [(u32::MAX, u32::MAX), (1_000_000, 1), (2, 0), (0, 3)] {+ let (d, sid, _) = drop_doc(LOREM, drop_cap(lines, chars));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let g = &cs.frames[0].lines[0].glyphs[0];+ assert!(g.y.is_finite() && g.sy.is_finite() && g.y <= 12.0 * 25.0, "{lines}/{chars}: {}", g.y);+ }+ // No lines or no characters: no drop cap.+ let (d, sid, _) = drop_doc(LOREM, drop_cap(0, 3));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(cs.frames[0].lines[0].glyphs[0].y.abs() < 1e-6);+}++#[test]+fn one_line_drop_cap_is_not_enlarged() {+ let (d, sid, _) = drop_doc(LOREM, drop_cap(1, 1));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let (dc, body) = (&l.glyphs[0], l.glyphs.iter().find(|g| g.byte == 1).unwrap());+ assert!((cap_of(dc) - cap_of(body)).abs() < 0.01 && dc.y.abs() < 1e-6);+}++#[test]+fn drop_cap_stays_with_the_first_line_across_a_column_break() {+ // Two lines fit a column: line 3 starts the second column, at its edge.+ let (mut d, sid, fid) = drop_doc_in(&[LOREM; 2].join(" "), Rect::new(0.0, 0.0, 400.0, 30.0), drop_cap(3, 1));+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let ft = &cs.frames[0];+ let col1: Vec<&Line> = ft.lines.iter().filter(|l| l.column == 1).collect();+ assert_eq!(ft.lines.iter().filter(|l| l.column == 0).count(), 2, "{:?}", ft.lines.iter().map(|l| l.column).collect::<Vec<_>>());+ let dc = &ft.lines[0].glyphs[0];+ assert!((dc.y - 24.0).abs() < 1e-6, "{}", dc.y);+ assert!(text_x(&ft.lines[1], 1) >= dc.x + dc.adv - 1e-6);+ assert!((text_x(col1[0], 1) - ft.columns[1].x0).abs() < 0.5);+}++#[test]+fn drop_cap_in_right_to_left_paragraphs_is_on_the_right() {+ let para = ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::Right), ..drop_cap(2, 1) };+ let (d, sid, _) = drop_doc(LOREM, para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let dc = lines[0].glyphs.iter().find(|g| g.byte == 0).unwrap();+ assert!((dc.x + dc.adv - 300.0).abs() < 0.5, "{}", dc.x + dc.adv);+ for l in &lines[..2] {+ assert!(l.glyphs.iter().filter(|g| g.byte > 0 && g.visible).all(|g| g.x + g.adv <= dc.x + 0.5));+ }+ assert!(lines[2].end_x > 299.0 || lines[2].glyphs.iter().any(|g| g.x + g.adv > 299.0));+}++#[test]+fn vertical_frames_set_no_drop_cap() {+ let (mut d, sid, _) = drop_doc(LOREM, drop_cap(3, 1));+ d.story_mut(sid).unwrap().vertical = true;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(cs.frames[0].lines[0].glyphs[0].y.abs() < 1e-6);+}++#[test]+fn drop_cap_takes_its_character_style_and_nested_styles_count_it() {+ let (mut d, sid, _) = drop_doc(LOREM, ParaAttrs { drop_cap_style: Some("Initial".into()), ..drop_cap(2, 3) });+ for (name, fill) in [("Initial", "Initial Red"), ("Lead", "Lead Blue")] {+ std::sync::Arc::make_mut(&mut d.styles).character.push(designcraft_doc::CharacterStyle {+ name: name.into(),+ based_on: None,+ chars: designcraft_doc::CharAttrs { fill: Some(fill.into()), ..Default::default() },+ shortcut: String::new(),+ });+ }+ let fill = |cs: &ComposedStory, g: &PlacedGlyph| cs.styles[g.style as usize].fill.clone();+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let at = |b: usize| l.glyphs.iter().find(|g| g.byte == b).unwrap();+ assert_eq!(fill(&cs, at(0)), "Initial Red");+ assert_eq!(fill(&cs, at(2)), "Initial Red");+ assert_eq!(fill(&cs, at(3)), "[Black]");+ // The drop cap's style is a leading "through 1 drop cap" nested style: the nested styles start+ // after the drop cap.+ let one = designcraft_doc::NestedStyle { style: "Lead".into(), through: true, count: 1, until: designcraft_doc::NestedUntil::Characters };+ d.story_mut(sid).unwrap().paras[0].para.nested_styles = Some(vec![one]);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let at = |b: usize| l.glyphs.iter().find(|g| g.byte == b).unwrap();+ assert_eq!(fill(&cs, at(0)), "Initial Red");+ assert_eq!((fill(&cs, at(3)), fill(&cs, at(4))), ("Lead Blue".to_string(), "[Black]".to_string()));+ // A nested style "through 1 drop cap" covers the drop cap; the next one starts after it.+ let ns = |style: &str, until: designcraft_doc::NestedUntil| designcraft_doc::NestedStyle { style: style.into(), through: true, count: 1, until };+ d.story_mut(sid).unwrap().paras[0].para = ParaAttrs {+ nested_styles: Some(vec![ns("Lead", designcraft_doc::NestedUntil::Dropcap), ns("Initial", designcraft_doc::NestedUntil::Words)]),+ ..drop_cap(2, 3)+ };+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let at = |b: usize| l.glyphs.iter().find(|g| g.byte == b).unwrap();+ assert_eq!(fill(&cs, at(0)), "Lead Blue");+ assert_eq!(fill(&cs, at(2)), "Lead Blue");+ assert_eq!(fill(&cs, at(3)), "Initial Red", "the second nested style starts after the drop cap");+ let first_space = LOREM.find(' ').unwrap();+ assert_eq!(fill(&cs, at(first_space + 1)), "[Black]");+}++#[test]+fn drop_cap_caret_and_hit_testing() {+ let (d, sid, _) = drop_doc(LOREM, drop_cap(3, 1));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let dc = lines[0].glyphs[0].clone();+ let drop_box = lines[0].drop_cap.unwrap().rect;+ assert!(drop_box.y1 > lines[2].baseline - 0.01 && drop_box.y0 < lines[0].baseline - 5.0, "{drop_box:?}");+ // A click on the lower half of the big letter (beside line 3) is at the drop cap.+ let y = lines[2].baseline - 2.0;+ assert_eq!(hit(&cs, 0, Point::new(dc.x + dc.adv * 0.25, y)), Some(0));+ assert_eq!(hit(&cs, 0, Point::new(dc.x + dc.adv * 0.75, y)), Some(1));+ // A double click there is on the drop cap's character, not on line 3's text.+ assert_eq!(hit_char(&cs, 0, Point::new(dc.x + dc.adv * 0.5, y)), Some(0));+ // The caret before the drop cap is as tall as it; after it, beside line 1's text.+ let (_, x, bl, asc, _) = caret(&cs, 0).unwrap();+ assert!((x - dc.x).abs() < 1e-6 && (bl - lines[2].baseline).abs() < 1e-6 && asc > 24.0, "{x} {bl} {asc}");+ let (_, x, bl, _, _) = caret(&cs, 1).unwrap();+ assert!(x >= dc.x + dc.adv - 1e-6 && (bl - lines[0].baseline).abs() < 1e-6);+}++#[test]+fn drop_cap_on_a_baseline_grid_reaches_down_by_grid_steps() {+ // Lines on a 15 pt baseline grid (not the 12 pt leading): the drop cap reaches down two grid+ // steps, to line 3.+ let (mut d, sid, _) = drop_doc(LOREM, ParaAttrs { grid_align: Some(designcraft_doc::GridAlign::AllLines), ..drop_cap(3, 1) });+ d.settings.baseline_grid.increment = 15.0;+ d.settings.baseline_grid.start = 0.0;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!((lines[1].baseline - lines[0].baseline - 15.0).abs() < 1e-6);+ let dc = &lines[0].glyphs[0];+ assert!((lines[0].baseline + dc.y - lines[2].baseline).abs() < 1e-6);+ let b = lines[0].drop_cap.unwrap();+ assert!((b.baseline - lines[2].baseline).abs() < 1e-6 && b.rect.y1 > lines[2].baseline);+ // Scaled to the grid's line pitch: its cap top is still line 1's.+ let body = lines[0].glyphs.iter().find(|g| g.byte == 1).unwrap();+ assert!((lines[2].baseline - cap_of(dc) - (lines[0].baseline - cap_of(body))).abs() < 0.01);+}++/// A line with a larger auto leading doesn't move the drop cap: it reaches down `lines − 1`+/// leadings of the text after it, not to where line N is set.+#[test]+fn drop_cap_reaches_down_by_the_text_leading_past_a_line_with_larger_leading() {+ use designcraft_doc::{CharAttrs, Composer, Leading};+ let text = [LOREM; 2].join(" ");+ let para = ParaAttrs { composer: Some(Composer::SingleLine), ..drop_cap(3, 1) };+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 1000.0), para);+ d.story_mut(sid).unwrap().paras[0].chars = CharAttrs { size: Some(12.0), leading: Some(Leading::Auto), ..Default::default() };+ // A larger word starts line 2, so lines 2 and 3 are set further down than 2 × 14.4 pt.+ let start2 = all_lines(&compose_story(&d, sid, &ComposeOptions::default()))[1].range.start;+ d.story_mut(sid).unwrap().format_chars(start2..start2 + 3, |f| f.over.size = Some(20.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines[1].range.start, start2);+ assert!(lines[2].baseline - lines[0].baseline > 2.0 * 14.4 + 5.0, "{} {}", lines[0].baseline, lines[2].baseline);+ let dc = &lines[0].glyphs[0];+ assert!((dc.y - 2.0 * 14.4).abs() < 1e-6, "drop cap baseline {} below line 1", dc.y);+ let b = lines[0].drop_cap.unwrap();+ assert!((b.baseline - (lines[0].baseline + 2.0 * 14.4)).abs() < 1e-6, "{}", b.baseline);+}++/// A space after the drop cap is set at its size on its baseline and doesn't widen the indent: the+/// lines beside it start where its characters end.+#[test]+fn space_after_a_drop_cap_does_not_widen_the_indent() {+ let (d, sid, _) = drop_doc(&format!("In 2003 {LOREM}"), drop_cap(2, 2));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let (i, n) = (&lines[0].glyphs[0], &lines[0].glyphs[1]);+ assert_eq!((i.byte, n.byte), (0, 1));+ let end = n.x + n.adv;+ for l in &lines[..2] {+ assert!((text_x(l, 3) - end).abs() < 1e-6, "{} vs {end}", text_x(l, 3));+ }+ let space = lines[0].glyphs.iter().find(|g| g.byte == 2).unwrap();+ assert!((space.sy - n.sy).abs() < 1e-9 && (space.y - n.y).abs() < 1e-9, "the space is set like the drop cap");+ assert_eq!(lines[0].drop_cap.unwrap().end, 3);+}++/// A one-line drop cap keeps its characters' own size (a smaller verse number stays smaller), and+/// the tabs in it advance to the paragraph's tab stops.+#[test]+fn one_line_drop_cap_keeps_its_size_and_sets_its_tabs() {+ let stop = |position, align| designcraft_doc::TabStop { position, align, leader: String::new(), align_on: String::new() };+ let para = ParaAttrs { tabs: Some(vec![stop(30.0, TabAlign::Right), stop(40.0, TabAlign::Left)]), ..drop_cap(1, 3) };+ let (mut d, sid, _) = drop_doc(&format!("\t7\t{LOREM}"), para);+ d.story_mut(sid).unwrap().format_chars(0..3, |f| f.over.size = Some(8.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let at = |b: usize| l.glyphs.iter().find(|g| g.byte == b).unwrap();+ let (seven, body) = (at(1), at(3));+ assert!((seven.sy / body.sy - 0.8).abs() < 1e-9, "{} vs {}", seven.sy, body.sy);+ assert!(seven.y.abs() < 1e-9);+ assert!((seven.x + seven.adv - 30.0).abs() < 1e-6, "the number ends at the right tab: {}", seven.x + seven.adv);+ assert!((text_x(l, 3) - 40.0).abs() < 1e-6, "the text starts at the left tab: {}", text_x(l, 3));+}++/// Right to left, the tabs in a drop cap advance to tab stops measured from the column's right+/// edge.+#[test]+fn right_to_left_drop_cap_sets_its_tabs_from_the_right_edge() {+ let stop = |position, align| designcraft_doc::TabStop { position, align, leader: String::new(), align_on: String::new() };+ let para = ParaAttrs {+ direction: Some(designcraft_doc::TextDirection::RightToLeft),+ align: Some(Align::Right),+ tabs: Some(vec![stop(30.0, TabAlign::Right), stop(40.0, TabAlign::Left)]),+ ..drop_cap(1, 3)+ };+ let (d, sid, _) = drop_doc(&format!("\t7\t{LOREM}"), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let seven = l.glyphs.iter().find(|g| g.byte == 1).unwrap();+ // The 300 pt column's right edge is at 300: the number's far (left) end is 30 pt from it.+ assert!((seven.x - 270.0).abs() < 1e-6, "the number ends at the right tab: {}", seven.x);+ // The text beside it starts at the left tab, 40 pt from the edge.+ let right = l.glyphs.iter().filter(|g| g.byte >= 3 && g.visible).map(|g| g.x + g.adv).fold(f64::NEG_INFINITY, f64::max);+ assert!(right <= 260.0 + 1e-6 && right > 255.0, "text ends at {right}");+}++/// A rule in Text Color takes the colour of the paragraph's text: the first character's for the+/// rule above, the last character's for the rule below. A swatch colour is used as is.+#[test]+fn text_color_rules_follow_the_text() {+ use designcraft_doc::{CharAttrs, CharFormat, Rule, TEXT_COLOR};+ let rule = Rule { on: true, weight: 2.0, ..Default::default() };+ let para = ParaAttrs { rule_above: Some(rule.clone()), rule_below: Some(rule.clone()), ..Default::default() };+ let (mut d, sid, fid) = doc_with("Red then blue", Rect::new(0.0, 0.0, 300.0, 200.0), para);+ {+ let s = d.story_mut(sid).unwrap();+ s.format_chars(0..3, |f: &mut CharFormat| f.over.merge(&CharAttrs { fill: Some("Red".into()), fill_tint: Some(0.5), ..Default::default() }));+ s.format_chars(9..13, |f: &mut CharFormat| f.over.fill = Some("Blue".into()));+ }+ let decos = |d: &Document| {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ let mut v: Vec<(f64, String, f32)> = cs.frame(fid).unwrap().decos.iter().map(|dc| (dc.rect.y0, dc.color.clone(), dc.tint)).collect();+ v.sort_by(|a, b| a.0.total_cmp(&b.0));+ v.into_iter().map(|(_, c, t)| (c, t)).collect::<Vec<_>>()+ };+ assert_eq!(rule.color, TEXT_COLOR);+ assert_eq!(decos(&d), vec![("Red".to_string(), 0.5), ("Blue".to_string(), 1.0)]);+ let swatch = Rule { color: "[Black]".into(), tint: 0.3, ..rule };+ d.story_mut(sid).unwrap().paras[0].para.rule_above = Some(swatch);+ assert_eq!(decos(&d)[0], ("[Black]".to_string(), 0.3));+}++/// Align Left Edge (InDesign's default): the drop cap's origin moves left by its first letter's+/// left side bearing so its ink starts at the indent, and the lines beside it start where its+/// advance ends. Measured case: 14/18 text, two lines, one character.+#[test]+fn drop_cap_aligns_its_left_edge() {+ let text = format!("Once {LOREM}");+ let compose = |align: Option<bool>| {+ let para = ParaAttrs { left_indent: Some(10.0), drop_cap_align_left: align, ..drop_cap(2, 1) };+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 1000.0), para);+ d.story_mut(sid).unwrap().paras[0].chars =+ designcraft_doc::CharAttrs { size: Some(14.0), leading: Some(designcraft_doc::Leading::Points(18.0)), ..Default::default() };+ compose_story(&d, sid, &ComposeOptions::default())+ };+ use designcraft_geom::Shape as _;+ let ink_left = |g: &PlacedGlyph| g.x + designcraft_fonts::FontDb::global().outline(g.face.get(), g.gid).bounding_box().x0 * g.sx;+ for align in [None, Some(true), Some(false)] {+ let cs = compose(align);+ let lines = all_lines(&cs);+ let dc = &lines[0].glyphs[0];+ assert_eq!(dc.byte, 0);+ let lsb = ink_left(dc) - dc.x;+ assert!(lsb > 0.5, "the O has a visible side bearing at this size: {lsb}");+ if align != Some(false) {+ assert!((ink_left(dc) - 10.0).abs() < 1e-6, "{align:?}: ink at {}", ink_left(dc));+ } else {+ assert!((dc.x - 10.0).abs() < 1e-6, "origin at {}", dc.x);+ }+ for l in &lines[..2] {+ assert!((text_x(l, 1) - (dc.x + dc.adv)).abs() < 1e-6, "{align:?}: {} vs {}", text_x(l, 1), dc.x + dc.adv);+ }+ assert!((text_x(lines[2], 1) - 10.0).abs() < 1e-6);+ }+}++#[test]+fn caret_follows_spaces_typed_at_the_end() {+ let x_at_end = |text: &str| {+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let end_x = cs.frames[0].lines[0].end_x;+ (caret(&cs, text.len()).unwrap().1, end_x)+ };+ let (word, word_end) = x_at_end("Word");+ let (one, one_end) = x_at_end("Word ");+ let (two, _) = x_at_end("Word ");+ assert!(one > word + 1.0 && two > one + 1.0, "{word} {one} {two}");+ // The spaces don't count for the line's own length (alignment, justification).+ assert!((one_end - word_end).abs() < 1e-9);+ // Wrapped lines keep their spaces too: a caret between two spaces at a line end sits after+ // the first one.+ let text = "Lorem ipsum dolor sit amet consectetur";+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 140.0, 100.0), ParaAttrs::default());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l0 = &cs.frames[0].lines[0];+ if l0.range.end == text.find("consectetur").unwrap() {+ let mid = text.find(" ").unwrap() + 1;+ assert!(caret(&cs, mid).unwrap().1 > l0.end_x, "between the trailing spaces");+ }+}++#[test]+fn colour_change_keeps_kerning_and_ligatures_keep_colour() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 400.0, 200.0), lid, "ayay", ParaFormat::default()).unwrap();+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.font_style = Some("Bold".into()));+ let line = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].clone();+ let xs = |l: &Line| l.glyphs.iter().map(|g| (g.x, g.adv)).collect::<Vec<_>>();+ let kerned = line(&d);+ // The font kerns "ay" (otherwise this test proves nothing).+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.kerning = Some(designcraft_doc::Kerning::None));+ assert_ne!(xs(&line(&d)), xs(&kerned), "Source Serif 4 Bold kerns a–y");+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.kerning = Some(designcraft_doc::Kerning::Metrics));+ // Colour the first "a": positions are unchanged, only its style differs.+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.fill = Some("Cyan".into()));+ let coloured = line(&d);+ assert_eq!(xs(&coloured), xs(&kerned), "a colour change must not change spacing");+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let fill = |l: &Line, i: usize| cs.styles[l.glyphs[i].style as usize].fill.clone();+ assert_eq!(fill(&coloured, 0), "Cyan");+ assert_ne!(fill(&coloured, 1), "Cyan");++ // A ligature never swallows a differently coloured letter: the "i" of "fi" keeps its colour.+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 300.0, 400.0, 400.0), lid, "fifi", ParaFormat::default()).unwrap();+ d.story_mut(sid).unwrap().format_chars(1..2, |f| f.over.fill = Some("Cyan".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let at = |b: usize| l.glyphs.iter().find(|g| g.len > 0 && g.byte <= b && b < g.byte + g.len).map(|g| cs.styles[g.style as usize].fill.clone());+ assert_eq!(at(1).as_deref(), Some("Cyan"));+ assert_ne!(at(2).as_deref(), Some("Cyan"));+}++/// The emphasis mark drawn over the text only paints: a change of kenten character keeps the+/// kerning across it.+#[test]+fn kenten_character_change_keeps_kerning() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 400.0, 200.0), lid, "ayay", ParaFormat::default()).unwrap();+ d.story_mut(sid).unwrap().format_chars(0..4, |f| {+ f.over.font_style = Some("Bold".into());+ f.over.kenten = Some(true);+ });+ let xs = |d: &Document| {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ cs.frames[0].lines[0].glyphs.iter().filter(|g| g.len > 0).map(|g| (g.byte, g.x, g.adv)).collect::<Vec<_>>()+ };+ let kerned = xs(&d);+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.kerning = Some(designcraft_doc::Kerning::None));+ assert_ne!(xs(&d), kerned, "Source Serif 4 Bold kerns a–y");+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.kerning = Some(designcraft_doc::Kerning::Metrics));+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.kenten_character = Some("●".into()));+ assert_eq!(xs(&d), kerned, "a kenten character change must not change spacing");+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let mark = |b: usize| {+ cs.frames[0].lines[0].glyphs.iter().find(|g| g.len > 0 && g.byte == b).map(|g| cs.styles[g.style as usize].kenten_character.clone())+ };+ assert_eq!((mark(0).as_deref(), mark(1).as_deref()), (Some("●"), Some("")));+}++#[test]+fn empty_paragraph_takes_its_marks_format() {+ // Paragraph style text is 12 pt (auto leading 14.4); every character, including the empty+ // paragraph's mark, is 6 pt with 8 pt leading: the empty line must advance 8, not 14.4.+ let text = "One\n\nTwo";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 200.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {+ f.over.size = Some(6.0);+ f.over.leading = Some(designcraft_doc::Leading::Points(8.0));+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 3);+ assert!((lines[1].baseline - lines[0].baseline - 8.0).abs() < 1e-6, "{} {}", lines[0].baseline, lines[1].baseline);+ assert!((lines[2].baseline - lines[1].baseline - 8.0).abs() < 1e-6, "{} {}", lines[1].baseline, lines[2].baseline);+}++#[test]+fn empty_paragraph_uses_its_own_mark_not_the_previous_one() {+ // "One\n" is 20 pt; the empty paragraph's mark (byte 4) and "Two" are 6 pt with 8 pt leading.+ // The format run boundary sits exactly at the empty paragraph's start: its line must take the+ // 8 pt leading of its own mark, not the previous paragraph's 20 pt (auto 24) mark.+ let text = "One\n\nTwo";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 200.0, 200.0), ParaAttrs::default());+ let st = d.story_mut(sid).unwrap();+ st.format_chars(0..4, |f| f.over.size = Some(20.0));+ st.format_chars(4..text.len(), |f| {+ f.over.size = Some(6.0);+ f.over.leading = Some(designcraft_doc::Leading::Points(8.0));+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 3);+ assert!((lines[1].baseline - lines[0].baseline - 8.0).abs() < 1e-6, "{} {}", lines[0].baseline, lines[1].baseline);+}++#[test]+fn spanish_text_gets_spanish_hyphenation() {+ let text = "La transición democrática fue una construcción colectiva extraordinariamente compleja y desesperadamente necesaria.";+ let narrow = Rect::new(36.0, 36.0, 120.0, 700.0);+ let (mut d, sid, _) = doc_with(text, narrow, ParaAttrs::default());+ let st = d.story_mut(sid).unwrap();+ let n = st.len();+ st.format_chars(0..n, |f| f.over.language = Some("Spanish".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let hy: Vec<&str> = lines.iter().filter(|l| l.hyphenated).map(|l| text[l.range.clone()].trim_end()).collect();+ assert!(!hy.is_empty(), "Spanish hyphenates");+ for l in &hy {+ let last: String = l.chars().rev().take_while(|c| c.is_alphabetic()).collect::<Vec<_>>().into_iter().rev().collect();+ let whole = text[text.find(l).unwrap() + l.len() - last.len()..].split(|c: char| !c.is_alphabetic()).next().unwrap();+ let es = hyphen::Lang::for_language("Spanish").unwrap();+ let pts = hyphen::hyphen_points_in(whole, &hyphen::Limits::default(), es);+ assert!(pts.contains(&last.chars().count()), "break {last}- in {whole} is a Bezos point");+ }+}++#[test]+fn cjk_aki_adds_space_without_scaling_outlines() {+ let (mut d, sid, _) = doc_with("AB", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ let old = compose_story(&d, sid, &ComposeOptions::default());+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {+ f.over.leading_aki = Some(Some(0.25));+ f.over.trailing_aki = Some(Some(0.5));+ });+ let new = compose_story(&d, sid, &ComposeOptions::default());+ let a = &old.frames[0].lines[0];+ let b = &new.frames[0].lines[0];+ assert!((b.end_x - a.end_x - 18.0).abs() < 1e-6);+ assert_eq!(a.glyphs[0].sx, b.glyphs[0].sx);+ assert!((b.glyphs[0].x - a.glyphs[0].x - 3.0).abs() < 1e-6);+}++#[test]+fn cjk_jidori_sets_group_width_and_survives_narrow_frames() {+ for composer in [designcraft_doc::Composer::SingleLine, designcraft_doc::Composer::Paragraph] {+ let (mut d, sid, _) = doc_with(+ "AB",+ Rect::new(0.0, 0.0, 30.0, 150.0),+ ParaAttrs { composer: Some(composer), glyph_scale_desired: Some(1.2), letter_space_desired: Some(0.2), ..Default::default() },+ );+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.jidori = Some(4));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 1, "an indivisible jidori group must not be emergency-split");+ assert!((lines[0].end_x - lines[0].x0 - 48.0).abs() < 1e-6);+ assert_eq!(lines[0].range, 0..2);+ }+}++#[test]+fn cjk_tsume_removes_sidebearings_without_collapsing_ink() {+ let (mut d, sid, _) = doc_with("HH", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ let old = compose_story(&d, sid, &ComposeOptions::default());+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.tsume = Some(1.0));+ let new = compose_story(&d, sid, &ComposeOptions::default());+ let a = &old.frames[0].lines[0];+ let b = &new.frames[0].lines[0];+ let g = &b.glyphs[0];+ let outline = designcraft_fonts::FontDb::global().outline(&g.face, g.gid);+ let ink_width = designcraft_geom::Shape::bounding_box(&*outline).width() * g.sx;+ assert!(ink_width > 0.0);+ assert!((b.end_x - b.x0 - 2.0 * ink_width).abs() < 1e-6);+ assert!(b.end_x < a.end_x);+ assert_eq!(a.glyphs[0].sx, g.sx);+}++#[test]+fn cjk_composite_font_selects_entries_before_shaping() {+ use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry};+ let (mut d, sid, _) = doc_with("A1B", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ std::sync::Arc::make_mut(&mut d.styles).composite_fonts.push(CompositeFont {+ name: "Mixed".into(),+ entries: vec![+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },+ CompositeFontEntry { characters: "0123456789".into(), family: "Source Sans 3".into(), relative_size: 0.5, ..Default::default() },+ ],+ });+ d.story_mut(sid).unwrap().format_chars(0..3, |f| f.over.font_family = Some("CompositeFont/Mixed".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let line = &cs.frames[0].lines[0];+ let a = line.glyphs.iter().find(|g| g.byte == 0).unwrap();+ let n = line.glyphs.iter().find(|g| g.byte == 1).unwrap();+ assert_ne!(a.face.id(), n.face.id());+ assert_eq!(cs.styles[a.style as usize].size, 12.0);+ assert_eq!(cs.styles[n.style as usize].size, 6.0);+ assert!(!cs.styles.iter().any(|s| s.missing_font));+}++#[test]+fn cjk_bunri_does_not_split_double_dash() {+ for composer in [designcraft_doc::Composer::SingleLine, designcraft_doc::Composer::Paragraph] {+ let (d, sid, _) =+ doc_with("--", Rect::new(0.0, 0.0, 5.0, 100.0), ParaAttrs { composer: Some(composer), bunri_kinshi: Some(true), ..Default::default() });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(all_lines(&cs).len(), 1);+ }+}++#[test]+fn cjk_custom_kinsoku_disables_selected_breaks() {+ let (mut d, sid, _) = doc_with(+ "甲乙丙丁",+ Rect::new(0.0, 0.0, 25.0, 200.0),+ ParaAttrs {+ composer: Some(designcraft_doc::Composer::SingleLine),+ kinsoku: Some(Some(designcraft_doc::cjk::Kinsoku { name: "Test".into(), no_start: "乙丙丁".into(), ..Default::default() })),+ ..Default::default()+ },+ );+ d.story_mut(sid).unwrap().format_chars(0.."甲乙丙丁".len(), |f| f.over.size = Some(12.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(all_lines(&cs).len(), 1);+}++fn japanese() -> ParaAttrs {+ ParaAttrs { composer: Some(Composer::Japanese), ..Default::default() }+}++#[test]+fn cjk_center_leading_measures_em_centers_across_different_sizes() {+ let lines_with = |para: ParaAttrs| {+ let (mut d, sid, _) = doc_with("A\nB", Rect::new(0.0, 0.0, 300.0, 200.0), para);+ d.story_mut(sid).unwrap().format_chars(0..3, |f| {+ f.over.leading = Some(designcraft_doc::Leading::Points(30.0));+ f.over.leading_model = Some(designcraft_doc::cjk::LeadingModel::Center);+ });+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.size = Some(24.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ all_lines(&cs).into_iter().cloned().collect::<Vec<_>>()+ };+ let lines = lines_with(japanese());+ assert_eq!(lines.len(), 2);+ let center = |l: &Line| {+ let g = &l.glyphs[0];+ let (a, b) = g.face.vertical_metrics();+ l.baseline + (b - a) / (2.0 * (a + b)) * g.face.units_per_em() * g.sy+ };+ assert!((center(&lines[1]) - center(&lines[0]) - 30.0).abs() < 1e-6);+ assert!((lines[1].baseline - lines[0].baseline - 30.0).abs() > 0.1);+ // The other composers set lines baseline to baseline.+ let lines = lines_with(ParaAttrs::default());+ assert!((lines[1].baseline - lines[0].baseline - 30.0).abs() < 1e-6);+}+++#[test]++fn cjk_aki_below_sets_the_upper_lines_leading_below_it() {++ let lines_with = |para: ParaAttrs| {++ let (mut d, sid, _) = doc_with("A\nB", Rect::new(0.0, 0.0, 300.0, 200.0), para);+ let st = d.story_mut(sid).unwrap();+ st.format_chars(0..3, |f| f.over.leading_model = Some(designcraft_doc::cjk::LeadingModel::AkiBelow));+ st.format_chars(0..2, |f| {+ f.over.size = Some(24.0);+ f.over.leading = Some(designcraft_doc::Leading::Points(40.0));+ });+ st.format_chars(2..3, |f| {+ f.over.size = Some(12.0);+ f.over.leading = Some(designcraft_doc::Leading::Points(20.0));+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ all_lines(&cs).into_iter().cloned().collect::<Vec<_>>()+ };+ let lines = lines_with(japanese());+ assert_eq!(lines.len(), 2);+ let em_bottom = |l: &Line| {+ let g = &l.glyphs[0];+ let (a, b) = g.face.vertical_metrics();+ l.baseline + b / (a + b) * g.face.units_per_em() * g.sy+ };+ let gap = em_bottom(&lines[1]) - em_bottom(&lines[0]);+ assert!((gap - 40.0).abs() < 1e-6, "{gap}");+ // The other composers advance by the lower line's leading, baseline to baseline.+ let lines = lines_with(ParaAttrs::default());+ assert!((lines[1].baseline - lines[0].baseline - 20.0).abs() < 1e-6);+ }+#[test]fn cjk_em_center_alignment_moves_small_characters() {let line_with = |para: ParaAttrs| {