DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge pr/639: Fonts: fall back to a font made for Malayalam (#639)
aiongg14eff698dd15
diff --cc crates/compose/src/tests.rsindex 3e33874e6,dd67c6855..f3eedc074--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -3662,1918 -2214,18 +3662,1935 @@@ fn cjk_jidori_sets_group_width_and_surv}}-/// Lines of `text` set in a frame `width` wide, with `tracking` on every character.-fn tracked_lines(text: &str, width: f64, para: ParaAttrs, tracking: f64) -> Vec<Line> {- let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, width, 4000.0), para);- d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.tracking = Some(tracking));- let cs = compose_story(&d, sid, &ComposeOptions::default());- assert!(!cs.is_overset(), "overset at width {width}");- all_lines(&cs).into_iter().cloned().collect()-}-#[test]-fn a_word_longer_than_the_line_breaks_at_the_column_edge() {- use designcraft_doc::Composer;+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);+ // Aki Below measures from the em box tops: the lower line's sits the upper line's leading+ // below the upper line's.+ let em_top = |l: &Line| {+ let g = &l.glyphs[0];+ let (a, b) = g.face.vertical_metrics();+ l.baseline - a / (a + b) * g.face.units_per_em() * g.sy+ };+ let gap = em_top(&lines[1]) - em_top(&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_aki_below_measures_em_tops_and_aki_above_em_bottoms() {+ use designcraft_doc::cjk::LeadingModel;+ for (model, top) in [(LeadingModel::AkiBelow, true), (LeadingModel::AkiAbove, false)] {+ let (mut d, sid, _) = doc_with("A\nB", Rect::new(0.0, 0.0, 300.0, 200.0), japanese());+ 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(model);+ });+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.size = Some(24.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 2);+ // The em box edge below the baseline (y down): its top, or its bottom one em lower.+ let edge = |l: &Line| {+ let g = &l.glyphs[0];+ let (a, b) = g.face.vertical_metrics();+ let em = g.face.units_per_em() * g.sy;+ let em_top = l.baseline - em * a / (a + b);+ if top { em_top } else { em_top + em }+ };+ assert!((edge(lines[1]) - edge(lines[0]) - 30.0).abs() < 1e-6, "{model:?}");+ }+}++#[test]+fn cjk_em_center_alignment_moves_small_characters() {+ let line_with = |para: ParaAttrs| {+ let (mut d, sid, _) = doc_with("AB", Rect::new(0.0, 0.0, 300.0, 100.0), para);+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.size = Some(24.0));+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.character_alignment = Some(designcraft_doc::cjk::CharacterAlignment::EmCenter));+ compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].clone()+ };+ let line = line_with(japanese());+ // Em box centre (y down): the font's BASE em box, else 0.88/-0.12 em.+ let center = |g: &PlacedGlyph| {+ let upem = g.face.units_per_em();+ let (top, bottom) = g.face.declared_em_box().unwrap_or((upem * 0.88, upem * -0.12));+ g.y - (top + bottom) / 2.0 * g.sy+ };+ assert!((center(&line.glyphs[0]) - center(&line.glyphs[1])).abs() < 1e-6);+ // The other composers keep every character on the baseline.+ let line = line_with(ParaAttrs::default());+ assert!(line.glyphs.iter().all(|g| g.y.abs() < 1e-9), "{:?}", line.glyphs.iter().map(|g| g.y).collect::<Vec<_>>());+}++#[test]+fn smaller_cjk_run_aligns_to_the_line_em_box_centre() {+ use designcraft_doc::cjk::CharacterAlignment;+ let text = "Ab 甲乙 cd";+ let run = "Ab ".len().."Ab 甲乙".len();+ // Em box centre (y down) of a placed glyph: its font's BASE em box, else 0.88/-0.12 em.+ let centre = |l: &Line, g: &PlacedGlyph| {+ let upem = g.face.units_per_em();+ let (top, bottom) = g.face.declared_em_box().unwrap_or((upem * 0.88, upem * -0.12));+ l.baseline + g.y - (top + bottom) / 2.0 * g.sy+ };+ for alignment in [CharacterAlignment::EmCenter, CharacterAlignment::Baseline] {+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), japanese());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {+ f.over.size = Some(10.0);+ f.over.character_alignment = Some(alignment);+ });+ d.story_mut(sid).unwrap().format_chars(run.clone(), |f| f.over.size = Some(6.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let line = &cs.frames[0].lines[0];+ let latin = &line.glyphs[0];+ let cjk: Vec<&PlacedGlyph> = line.glyphs.iter().filter(|g| run.contains(&g.byte)).collect();+ assert_eq!(cjk.len(), 2);+ assert!(latin.y.abs() < 1e-9);+ for g in cjk {+ match alignment {+ CharacterAlignment::EmCenter => {+ assert!((centre(line, g) - centre(line, latin)).abs() < 0.01, "{} vs {}", centre(line, g), centre(line, latin));+ assert!(g.y < -1.0, "a 6 pt run rises in a 10 pt line: {}", g.y);+ }+ _ => assert!(g.y.abs() < 1e-9, "Roman baseline keeps the run on the baseline: {}", g.y),+ }+ }+ }+}++#[test]+fn cjk_hanging_punctuation_uses_frame_edge_without_changing_glyph_size() {+ let k = designcraft_doc::cjk::Kinsoku { name: "Test".into(), no_start: ",".into(), hanging: ",".into(), ..Default::default() };+ let (mut d, sid, fid) = doc_with(+ "AB,",+ Rect::new(0.0, 0.0, 300.0, 100.0),+ ParaAttrs {+ composer: Some(designcraft_doc::Composer::SingleLine),+ kinsoku: Some(Some(k)),+ kinsoku_hang: Some(designcraft_doc::cjk::KinsokuHang::Regular),+ ..Default::default()+ },+ );+ let initial = compose_story(&d, sid, &ComposeOptions::default());+ let line = &initial.frames[0].lines[0];+ let text_w = line.glyphs.iter().take(2).map(|g| g.adv).sum::<f64>();+ // A fresh frame whose measure fits the letters, but not the comma.+ let frame = d.item_mut(fid).unwrap();+ frame.path = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, text_w + 1.0, 100.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(all_lines(&cs).len(), 1);+ assert_eq!(cs.frames[0].lines[0].glyphs.last().unwrap().sx, line.glyphs.last().unwrap().sx);+}++#[test]+fn cjk_fullwidth_space_obeys_the_paragraph_spacing_switch() {+ let text = "A B";+ let (mut d, sid, _) = doc_with(+ text,+ Rect::new(0.0, 0.0, 300.0, 100.0),+ ParaAttrs { word_space_desired: Some(2.0), treat_ideographic_space_as_space: Some(false), ..Default::default() },+ );+ let fixed = compose_story(&d, sid, &ComposeOptions::default());+ d.story_mut(sid).unwrap().paras[0].para.treat_ideographic_space_as_space = Some(true);+ let elastic = compose_story(&d, sid, &ComposeOptions::default());+ let space = fixed.frames[0].lines[0].glyphs.iter().find(|g| g.byte == 1).unwrap().adv;+ assert!((elastic.frames[0].lines[0].end_x - fixed.frames[0].lines[0].end_x - space).abs() < 1e-6);+}++#[test]+fn arabic_bidi_keeps_paragraph_context_across_forced_lines() {+ let text = "مرحبا\u{2028}123 - 456";+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 600.0, 200.0), ParaAttrs::default());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 2);+ let mut gs: Vec<_> = lines[1].glyphs.iter().filter(|g| g.len > 0).collect();+ gs.sort_by(|a, b| a.x.total_cmp(&b.x));+ let actual: String = gs.iter().map(|g| text[g.byte..].chars().next().unwrap()).collect();+ let info = unicode_bidi::BidiInfo::new(text, Some(unicode_bidi::Level::ltr()));+ let start = text.find('1').unwrap();+ let expected = info.reorder_line(&info.paragraphs[0], start..text.len()).to_string();+ assert_eq!(actual, expected);+ assert_ne!(actual, "123 - 456", "the previous Arabic strong character affects number ordering");+}++#[test]+fn arabic_character_direction_override_survives_line_layout() {+ let text = "abc 123 def";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 600.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(4..7, |f| f.over.character_direction = Some(designcraft_doc::arabic::CharacterDirection::RightToLeft));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let line = all_lines(&cs)[0];+ let x = |byte| line.glyphs.iter().find(|g| g.byte == byte).unwrap().x;+ assert!(x(4) > x(5) && x(5) > x(6));+ assert!(x(0) < x(6) && x(4) < x(8));+}++#[test]+fn arabic_fallback_marks_stay_with_bases_and_custom_offsets_move_only_marks() {+ let db = designcraft_fonts::FontDb::global();+ let Some(face) = db.fallback_for('ب', db.face(designcraft_fonts::DEFAULT_FAMILY, "Regular").id(), None) else { return };+ if !face.covers('ُ') {+ return;+ }+ let text = "بُبَ";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 600.0, 200.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ assert!(plain.iter().all(|g| g.face.id() == face.id()), "fallback must not split Arabic marks into the Latin face");+ assert!(plain.iter().all(|g| g.gid != 0));+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {+ f.over.diacritic_x_offset = Some(200.0);+ f.over.diacritic_y_offset = Some(-100.0);+ });+ let shifted = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ let mut marks = 0;+ for (a, b) in plain.iter().zip(&shifted) {+ assert_eq!(a.gid, b.gid);+ assert_eq!(a.adv, b.adv);+ if face.glyph_is_mark(a.gid) {+ marks += 1;+ assert!((b.x - a.x - 2.4).abs() < 1e-6);+ assert!((b.y - a.y - 1.2).abs() < 1e-6);+ } else {+ assert!((a.x - b.x).abs() < 1e-6 && (a.y - b.y).abs() < 1e-6);+ }+ }+ assert!(marks > 0);+}++#[test]+fn arabic_joining_context_crosses_character_style_boundaries() {+ let text = "ببب";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 600.0, 200.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ if plain.iter().any(|g| g.gid == 0) {+ return;+ }+ d.story_mut(sid).unwrap().format_chars(2..4, |f| f.over.fill = Some("Paper".into()));+ let split = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ assert_eq!(plain.iter().map(|g| (g.byte, g.gid)).collect::<Vec<_>>(), split.iter().map(|g| (g.byte, g.gid)).collect::<Vec<_>>());+}++#[test]+fn arabic_character_kashida_switch_prevents_insertion() {+ let text = "بسم الله الرحمن الرحيم الحمد لله رب العالمين";+ let (mut d, sid, _) = doc_with(+ text,+ Rect::new(0.0, 0.0, 160.0, 300.0),+ ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::RightJustified), ..Default::default() },+ );+ d.settings.glyph_fallback = true;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.allow_kashidas = Some(false));+ let off = compose_story(&d, sid, &ComposeOptions::default());+ assert!(all_lines(&off).iter().all(|l| l.glyphs.iter().all(|g| g.len > 0 || g.face.glyph_for('\u{0640}') != g.gid)));+}++#[test]+fn arabic_indic_digit_conversion_retains_original_utf8_ranges() {+ let text = "١٢٣";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.digits = Some(designcraft_doc::Digits::Arabic));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gs = &cs.frames[0].lines[0].glyphs;+ assert_eq!(gs.iter().map(|g| (g.byte, g.len)).collect::<Vec<_>>(), [(0, 2), (2, 2), (4, 2)]);+ for (g, c) in gs.iter().zip("123".chars()) {+ assert_eq!(g.gid, g.face.glyph_for(c));+ }+}++#[test]+fn arabic_contextual_digits_follow_strong_text_across_style_changes() {+ let text = "ب 12 A 34";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ let arabic_digits = text.find('1').unwrap();+ d.story_mut(sid).unwrap().format_chars(arabic_digits..arabic_digits + 2, |f| f.over.fill = Some("Paper".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gs = &cs.frames[0].lines[0].glyphs;+ let g = gs.iter().find(|g| g.byte == arabic_digits).unwrap();+ assert_eq!(g.gid, g.face.glyph_for('١'));+ let g = gs.iter().find(|g| g.byte == text.find('3').unwrap()).unwrap();+ assert_eq!(g.gid, g.face.glyph_for('3'));+}++#[test]+fn arabic_story_direction_flows_right_column_first() {+ let text = format!("first{}second", designcraft_doc::story::COLUMN_BREAK);+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().direction = designcraft_doc::TextDirection::RightToLeft;+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 2);+ assert!(lines[0].x0 > lines[1].x0);+ assert!(cs.frames[0].columns[0].x0 > cs.frames[0].columns[1].x0);+}++#[test]+fn arabic_rtl_table_keeps_logical_indices_and_merged_cell_hit_testing() {+ let mut t = designcraft_doc::Table::new(987, 2, 3, 0, 0, 240.0);+ t.options.direction = designcraft_doc::TextDirection::RightToLeft;+ t.cell_mut(0, 0).unwrap().text = designcraft_doc::Story::with_text(StoryId(0), "Right", ParaFormat::default());+ t.cell_mut(0, 2).unwrap().text = designcraft_doc::Story::with_text(StoryId(0), "Left", ParaFormat::default());+ t.merge(designcraft_doc::CellRange::new(1, 0, 1, 1)).unwrap();+ let (d, sid, _) = table_doc(Rect::new(0.0, 0.0, 400.0, 400.0), t);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let (_, _, right) = table::find_cell(&cs, 987, 0, 0).unwrap();+ let (_, _, left) = table::find_cell(&cs, 987, 0, 2).unwrap();+ assert!(right.rect.x0 > left.rect.x0);+ let (_, _, merged) = table::find_cell(&cs, 987, 1, 0).unwrap();+ assert!((merged.rect.width() - 160.0).abs() < 1e-6);+ assert_eq!(table::hit_cell(&cs, 0, right.rect.center()).map(|(_, r, c, _)| (r, c)), Some((0, 0)));+}++#[test]+fn arabic_kashida_moves_marks_with_their_cluster_and_respects_nonjoiners() {+ let text = "بُسْمِ بُسْمِ";+ let (mut d, sid, _) = doc_with(+ text,+ Rect::new(0.0, 0.0, 180.0, 100.0),+ ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::FullyJustified), ..Default::default() },+ );+ d.settings.glyph_fallback = true;+ let with = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ if with.iter().any(|g| g.gid == 0) {+ return;+ }+ assert!(with.iter().any(|g| g.len == 0 && g.gid == g.face.glyph_for('\u{0640}')));+ d.story_mut(sid).unwrap().paras[0].para.kashidas = Some(false);+ let without = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ for (a, b) in with.iter().zip(&without) {+ assert_eq!((a.gid, a.byte), (b.gid, b.byte));+ let first_a = with.iter().find(|g| g.byte == a.byte).unwrap();+ let first_b = without.iter().find(|g| g.byte == b.byte).unwrap();+ assert!(((a.x - first_a.x) - (b.x - first_b.x)).abs() < 1e-6, "marks detached from their cluster");+ }+ let text = "ب\u{200C}ب ب\u{200C}ب";+ let (mut d, sid, _) = doc_with(+ text,+ Rect::new(0.0, 0.0, 180.0, 100.0),+ ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::FullyJustified), ..Default::default() },+ );+ d.settings.glyph_fallback = true;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(cs.frames[0].lines[0].glyphs.iter().all(|g| g.gid != g.face.glyph_for('\u{0640}') || g.len > 0));+}++#[test]+fn arabic_explicit_isolated_forms_disable_contextual_joining() {+ let text = "بب";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 180.0, 100.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.positional_form = Some("Isolated".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gs = &cs.frames[0].lines[0].glyphs;+ for g in gs {+ assert_eq!(g.gid, g.face.glyph_for('ب'));+ }+}++#[test]+fn arabic_character_overrides_mirror_brackets_using_final_levels() {+ use designcraft_doc::arabic::CharacterDirection as D;+ for (text, direction, mirrored) in [("(123)", D::RightToLeft, true), ("(ب)", D::LeftToRight, false)] {+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.character_direction = Some(direction));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gs = &cs.frames[0].lines[0].glyphs;+ for (byte, ch) in [(0, '('), (text.len() - 1, ')')] {+ let g = gs.iter().find(|g| g.byte == byte).unwrap();+ let expected = if mirrored { unicode_bidi_mirroring::get_mirrored(ch).unwrap() } else { ch };+ assert_eq!(g.gid, g.face.glyph_for(expected), "{text:?} {direction:?} byte {byte}");+ }+ }+}++#[test]+fn language_picks_localized_forms_through_the_word_cache() {+ // Source Serif 4 has a Turkish `locl` form of `i`; the same words in English and Turkish+ // (both shaped word by word through the cache) keep their own forms.+ let text = "in in in in";+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 500.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(6..text.len(), |f| f.over.language = Some("Turkish".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gid_at = |byte: usize| all_lines(&cs).iter().flat_map(|l| l.glyphs.iter()).find(|g| g.byte == byte).map(|g| g.gid).unwrap();+ assert_eq!(gid_at(0), gid_at(3), "English i");+ assert_eq!(gid_at(6), gid_at(9), "Turkish i");+ assert_ne!(gid_at(0), gid_at(6), "Turkish i takes its localized form");+ // A single word is shaped directly, in its language too.+ let (mut d, sid, _) = doc_with("i", Rect::new(36.0, 36.0, 500.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.language = Some("Turkish".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(all_lines(&cs)[0].glyphs[0].gid, gid_at(6), "Turkish i, shaped on its own");+}++#[test]+fn chinese_and_japanese_take_their_localized_forms() {+ // Noto Sans CJK SC (craft-fonts) draws 直 differently for Japanese (`locl`).+ let Some(noto) = designcraft_fonts::CRAFT_FONTS.iter().find(|f| f.family == "Noto Sans CJK SC") else { return };+ FontDb::global().add_font(noto.bytes.to_vec());+ let gid = |language: &str| {+ let (mut d, sid, _) = doc_with("直", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0.."直".len(), |f| {+ f.over.font_family = Some(noto.family.into());+ f.over.language = Some(language.into());+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let g = &all_lines(&cs)[0].glyphs[0];+ assert_eq!(g.face.family, noto.family);+ g.gid+ };+ let chinese = gid("Chinese: Simplified");+ assert_eq!(chinese, FontDb::global().face(noto.family, noto.style).glyph_for('直'));+ assert_ne!(gid("Japanese"), chinese, "Japanese 直");+}++#[test]+fn cjk_fallback_follows_the_language() {+ use designcraft_fonts::testing::font_with;+ // Stand-ins for Hiragino Mincho ProN (the Japanese chain's first system font) and Songti SC+ // (first in the Simplified Chinese chain); the real ones when installed.+ let db = designcraft_fonts::FontDb::global();+ db.add_font(font_with("Hiragino Mincho ProN", &['直']).unwrap());+ db.add_font(font_with("Songti SC", &['直']).unwrap());+ // (face of the Latin letter, face of the ideograph)+ let faces_of = |language: &str| {+ let (mut d, sid, _) = doc_with("a直", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.language = Some(language.into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let face_at = |byte: usize| all_lines(&cs).iter().flat_map(|l| l.glyphs.iter()).find(|g| g.byte == byte).map(|g| g.face).unwrap();+ (face_at(0), face_at(1))+ };+ assert_eq!(faces_of("Chinese: Simplified").1.family, "Songti SC");+ // Japanese: the craft-fonts faces lead the chain (Mincho first), then the system fonts.+ let japanese = designcraft_fonts::japanese_document_fonts().first().map_or("Hiragino Mincho ProN", |f| f.family);+ assert_eq!(faces_of("Japanese").1.family, japanese);+ // Without a CJK language, the language-blind search.+ let (primary, han) = faces_of("English: USA");+ assert_eq!(Some(han.family.clone()), db.fallback_for('直', primary.id(), None).map(|f| f.family.clone()));+}+++#[test]++fn malayalam_falls_back_to_a_font_that_forms_its_conjuncts() {++ // Run against the installed fonts: on macOS the first file mapping Malayalam is Arial++ // Unicode MS, which leaves ക്ഷ as three glyphs.++ let db = designcraft_fonts::FontDb::global();++ if !["Malayalam Sangam MN", "Malayalam MN", "Nirmala UI", "Noto Sans Malayalam"].iter().any(|f| db.has_family(f)) {++ return;++ }++ let text = "ക്ഷ";++ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());++ d.settings.glyph_fallback = true;++ let cs = compose_story(&d, sid, &ComposeOptions::default());++ let glyphs: Vec<_> = all_lines(&cs).iter().flat_map(|l| l.glyphs.iter()).map(|g| (g.face.family.clone(), g.gid)).collect();++ assert_eq!(glyphs.len(), 1, "one conjunct: {glyphs:?}");++ assert_ne!(glyphs[0].1, 0);++}+++#[test]+fn missing_glyphs_are_the_fonts_box_unless_fallback_is_on() {+ use designcraft_fonts::testing::font_with;+ // Some font draws 語 when fallback fonts are allowed (a system CJK font, or this stand-in).+ designcraft_fonts::FontDb::global().add_font(font_with("DC Test Missing Glyph Helper", &['語']).unwrap());+ let text = "a語";+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.language = Some("Japanese".into()));+ let glyph_at = |d: &Document, byte: usize| {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ all_lines(&cs).iter().flat_map(|l| l.glyphs.iter()).find(|g| g.byte == byte).map(|g| (g.face, g.gid, g.adv)).unwrap()+ };+ assert!(!d.settings.glyph_fallback, "new documents draw missing glyphs as InDesign does");+ let (face, gid, adv) = glyph_at(&d, 1);+ assert_eq!((face.family.as_str(), gid), (designcraft_fonts::DEFAULT_FAMILY, 0), "Source Serif 4's .notdef");+ assert!((adv - face.advance(0) * 12.0 / face.upem).abs() < 1e-6, "its advance: {adv}");+ d.settings.glyph_fallback = true;+ let (face, gid, _) = glyph_at(&d, 1);+ assert_ne!(face.family, designcraft_fonts::DEFAULT_FAMILY);+ assert_ne!(gid, 0, "a fallback font draws it");+}++/// A missing font's substitute draws what it lacks from fallback fonts whatever the setting, also+/// in text shaped as one piece across a colour change.+#[test]+fn a_missing_fonts_substitute_takes_fallback_fonts() {+ use designcraft_fonts::testing::font_with;+ designcraft_fonts::FontDb::global().add_font(font_with("DC Test Missing Glyph Helper", &['語']).unwrap());+ let text = "a語b語";+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ {+ let s = d.story_mut(sid).unwrap();+ s.format_chars(0..text.len(), |f| {+ f.over.language = Some("Japanese".into());+ f.over.font_family = Some("DC Test No Such Family".into());+ });+ s.format_chars("a語".len()..text.len(), |f| f.over.fill = Some("Red".into()));+ }+ assert!(!d.settings.glyph_fallback);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let glyphs: Vec<&PlacedGlyph> = all_lines(&cs).into_iter().flat_map(|l| l.glyphs.iter()).filter(|g| text[g.byte..].starts_with('語')).collect();+ assert_eq!(glyphs.len(), 2);+ for g in glyphs {+ assert_ne!(g.face.family, designcraft_fonts::DEFAULT_FAMILY, "byte {}", g.byte);+ assert_ne!(g.gid, 0, "byte {}: a fallback font draws it", g.byte);+ }+}++#[test]+fn a_mark_starting_a_run_is_shaped_with_its_base() {+ use designcraft_fonts::testing::font_with;+ const HEBREW: &str = "DC Test Hebrew Points";+ designcraft_fonts::FontDb::global().add_font(font_with(HEBREW, &['ש', '\u{5C2}', 'ל']).unwrap());+ // Shin, then sin dot and lamed in a run that only turns ligatures off.+ let text = "ש\u{5C2}ל";+ let mark = "ש".len();+ let glyphs = |family: &str, mark_family: Option<&str>| {+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ let story = d.story_mut(sid).unwrap();+ story.format_chars(0..text.len(), |f| f.over.font_family = Some(family.into()));+ story.format_chars(mark..text.len(), |f| {+ f.over.ligatures = Some(false);+ if let Some(m) = mark_family {+ f.over.font_family = Some(m.into());+ }+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ all_lines(&cs).iter().flat_map(|l| l.glyphs.iter()).map(|g| (g.face, g.gid, g.byte)).collect::<Vec<_>>()+ };+ // A missing font: its substitute lacks both, so the letter comes from a fallback font, and the+ // mark from the same font, in its letter's cluster.+ let g = glyphs("DC Test No Such Family", None);+ let (base, dot) = (g[0], g[1]);+ assert_ne!(base.1, 0, "{g:?}");+ assert_eq!((dot.0.family.as_str(), dot.2), (base.0.family.as_str(), 0), "the sin dot goes with its shin: {g:?}");+ assert_ne!(dot.1, 0, "{g:?}");+ // The run's own font lacks the mark: its box, whatever font the letter before it has.+ let g = glyphs(HEBREW, Some(designcraft_fonts::DEFAULT_FAMILY));+ let dot = g.iter().find(|x| x.2 == mark).unwrap();+ assert_eq!((dot.0.family.as_str(), dot.1), (designcraft_fonts::DEFAULT_FAMILY, 0), "{g:?}");+}++#[test]+fn kenten_missing_from_the_font_are_its_box_unless_fallback_is_on() {+ use designcraft_fonts::testing::font_with;+ // Some font draws the sesame dot when fallback fonts are allowed (a system font, or this one).+ designcraft_fonts::FontDb::global().add_font(font_with("DC Test Kenten Helper", &['\u{FE45}']).unwrap());+ let (mut d, sid, _) = doc_with("ab", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.len();+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.kenten = Some(true));+ let marks = |d: &Document| {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ cs.frames[0].lines[0].glyphs[plain..].iter().map(|g| (g.face.family.clone(), g.gid)).collect::<Vec<_>>()+ };+ let missing = marks(&d);+ assert_eq!(missing.len(), 2);+ assert!(missing.iter().all(|(family, gid)| family == designcraft_fonts::DEFAULT_FAMILY && *gid == 0), "{missing:?}");+ d.settings.glyph_fallback = true;+ let drawn = marks(&d);+ assert_eq!(drawn.len(), 2);+ assert!(drawn.iter().all(|(family, gid)| family != designcraft_fonts::DEFAULT_FAMILY && *gid != 0), "{drawn:?}");+}++#[test]+fn each_document_shapes_words_in_its_own_fonts() {+ use designcraft_fonts::testing::font_with_glyph;+ const FAMILY: &str = "DocFont Word Cache";+ // Two documents' fonts of one name: the same words, drawn as `X` in one and `O` in the other.+ let root = std::env::temp_dir().join(format!("dc-compose-docfonts-{}", std::process::id()));+ let mut scopes = Vec::new();+ for (name, glyph) in [("x", 'X'), ("o", 'O')] {+ let folder = root.join(name);+ std::fs::create_dir_all(&folder).unwrap();+ std::fs::write(folder.join("word.ttf"), font_with_glyph(FAMILY, &['a', 'b', ' '], glyph).unwrap()).unwrap();+ scopes.push((designcraft_fonts::FontDb::global().load_document_fonts(&folder).scope, glyph));+ }+ let text = "ab ab ab ab";+ let mut faces = Vec::new();+ for (scope, glyph) in scopes {+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ d.font_scope = scope;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.font_family = Some(FAMILY.into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let glyphs: Vec<&PlacedGlyph> =+ all_lines(&cs).into_iter().flat_map(|l| l.glyphs.iter()).filter(|g| text[g.byte..].starts_with('a')).collect();+ assert_eq!(glyphs.len(), 4);+ let face = glyphs[0].face;+ let drawn = designcraft_fonts::FontDb::global().face(designcraft_fonts::FALLBACK_FAMILY, "Regular").glyph_for(glyph);+ assert!(glyphs.iter().all(|g| g.face == face && g.gid == drawn), "scope {scope}: {glyph}");+ faces.push(face);+ }+ assert!(faces[0] != faces[1] && faces.iter().all(|f| f.family == FAMILY));+ let _ = std::fs::remove_dir_all(&root);+}++#[test]+fn composite_fonts_draw_from_the_documents_fonts() {+ use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry};+ use designcraft_fonts::testing::font_with_glyph;+ const FAMILY: &str = "DocFont Composite Member";+ // A composite font whose digits come from a font only the document has.+ let folder = std::env::temp_dir().join(format!("dc-compose-composite-docfont-{}", std::process::id()));+ std::fs::create_dir_all(&folder).unwrap();+ std::fs::write(folder.join("digits.ttf"), font_with_glyph(FAMILY, &['1'], 'X').unwrap()).unwrap();+ let scope = FontDb::global().load_document_fonts(&folder).scope;+ let (mut d, sid, _) = doc_with("A1B", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ d.font_scope = scope;+ std::sync::Arc::make_mut(&mut d.styles).composite_fonts.push(CompositeFont {+ name: "Mixed".into(),+ entries: vec![+ CompositeFontEntry { family: designcraft_fonts::DEFAULT_FAMILY.into(), ..Default::default() },+ CompositeFontEntry { characters: "0123456789".into(), family: FAMILY.into(), ..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 digit = cs.frames[0].lines[0].glyphs.iter().find(|g| g.byte == 1).unwrap();+ assert_eq!(digit.face.family, FAMILY);+ assert_ne!(digit.gid, 0);+ assert!(!cs.styles.iter().any(|s| s.missing_font), "the document's font isn't missing");+ let _ = std::fs::remove_dir_all(&folder);+}++const KO_WORDS: &str = "한국어 문장은 띄어쓰기 단위로 줄을 바꿉니다 한국어 문장은 띄어쓰기 단위로 줄을 바꿉니다";+const KO_HANJA: &str = "大韓民國 憲法은 國民의 權利를 保障한다 大韓民國 憲法은 國民의 權利를 保障한다";+const KO_PUNCT: &str = "가나다라마。바사아자차」카타파하가、나다라마바。사아자차카」타파하가나、다라마바사。아자차카타」파하가나다、";+/// Syllables for words wider than the frame.+const KO_LONG: &str = "가나다라마바사아자차카타파하」";++/// A Korean paragraph in a narrow frame (70 pt), set in a stand-in font covering the samples.+fn korean_doc(text: &str, language: &str, para: ParaAttrs) -> (Document, StoryId) {+ let chars: Vec<char> = [KO_WORDS, KO_HANJA, KO_PUNCT, KO_LONG].concat().chars().collect();+ let font = designcraft_fonts::testing::font_with("DC Test Korean", &chars).unwrap();+ designcraft_fonts::FontDb::global().add_font(font);+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 106.0, 400.0), para);+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {+ f.over.font_family = Some("DC Test Korean".into());+ f.over.language = Some(language.into());+ });+ (d, sid)+}++/// The lines (after the first) that start inside a space-separated word.+fn lines_starting_mid_word(d: &Document, sid: StoryId, text: &str) -> Vec<String> {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!(lines.len() > 2, "wraps: {} lines", lines.len());+ lines.iter().skip(1).filter(|l| !text[..l.range.start].ends_with(' ')).map(|l| text[l.range.clone()].to_string()).collect()+}++#[test]+fn korean_breaks_at_spaces() {+ for composer in [designcraft_doc::Composer::Paragraph, designcraft_doc::Composer::SingleLine] {+ for align in [Align::Left, Align::LeftJustified] {+ let para = ParaAttrs { composer: Some(composer), align: Some(align), ..Default::default() };+ // By script: Hangul is set word by word whatever the language.+ for language in ["Korean", "English: USA"] {+ let (d, sid) = korean_doc(KO_WORDS, language, para.clone());+ let mid = lines_starting_mid_word(&d, sid, KO_WORDS);+ assert!(mid.is_empty(), "{composer:?} {align:?} {language}: {mid:?}");+ }+ }+ }+}++#[test]+fn korean_breaks_at_spaces_under_a_kinsoku_set() {+ let set = designcraft_doc::cjk::Kinsoku::named("KoreanKinsoku");+ assert!(set.is_some());+ for composer in [designcraft_doc::Composer::Paragraph, designcraft_doc::Composer::SingleLine] {+ let para = ParaAttrs { composer: Some(composer), kinsoku: Some(set.clone()), ..Default::default() };+ let (d, sid) = korean_doc(KO_WORDS, "Korean", para.clone());+ let mid = lines_starting_mid_word(&d, sid, KO_WORDS);+ assert!(mid.is_empty(), "{composer:?}: {mid:?}");+ let (d, sid) = korean_doc(KO_WORDS, "Korean", ParaAttrs { korean_char_breaks: Some(true), ..para });+ assert!(!lines_starting_mid_word(&d, sid, KO_WORDS).is_empty(), "{composer:?}: breaks between syllables on request");+ }+}++#[test]+fn korean_character_breaks_on_request() {+ let para = ParaAttrs { korean_char_breaks: Some(true), composer: Some(designcraft_doc::Composer::SingleLine), ..Default::default() };+ let (d, sid) = korean_doc(KO_WORDS, "Korean", para);+ assert!(!lines_starting_mid_word(&d, sid, KO_WORDS).is_empty(), "breaks between syllables");+}++#[test]+fn korean_by_its_locale_code_breaks_at_spaces() {+ let para = ParaAttrs { composer: Some(designcraft_doc::Composer::SingleLine), ..Default::default() };+ let (d, sid) = korean_doc(KO_HANJA, "ko_KR", para);+ let mid = lines_starting_mid_word(&d, sid, KO_HANJA);+ assert!(mid.is_empty(), "{mid:?}");+}++#[test]+fn hanja_in_korean_text_breaks_at_spaces() {+ let para = ParaAttrs { composer: Some(designcraft_doc::Composer::SingleLine), ..Default::default() };+ let (d, sid) = korean_doc(KO_HANJA, "Korean", para.clone());+ let mid = lines_starting_mid_word(&d, sid, KO_HANJA);+ assert!(mid.is_empty(), "{mid:?}");+ // Han in Japanese text breaks between characters.+ let (d, sid) = korean_doc(KO_HANJA, "Japanese", para);+ assert!(!lines_starting_mid_word(&d, sid, KO_HANJA).is_empty());+}++#[test]+fn korean_lines_keep_kinsoku() {+ // Words of 9 to 14 syllables and a closing bracket: in one of them the bracket is what+ // overflows the frame.+ let syllables: Vec<char> = KO_LONG.chars().collect();+ let long = (9..=14).map(|n| format!("{}」 가나", syllables[..n].iter().collect::<String>()));+ for text in std::iter::once(KO_PUNCT.to_string()).chain(long) {+ let text = text.as_str();+ for char_breaks in [false, true] {+ for composer in [designcraft_doc::Composer::Paragraph, designcraft_doc::Composer::SingleLine] {+ let para = ParaAttrs { korean_char_breaks: Some(char_breaks), composer: Some(composer), ..Default::default() };+ let (d, sid) = korean_doc(text, "Korean", para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!(lines.len() > 1, "wraps");+ let texts: Vec<&str> = lines.iter().map(|l| &text[l.range.clone()]).collect();+ assert!(texts.iter().all(|t| !t.starts_with(['、', '。', '」'])), "kinsoku ({char_breaks}, {composer:?}): {texts:?}");+ }+ }+ }+}++/// A synthetic font for vertical text: Source Sans 3 glyphs (CJK characters drawn as Latin ones)+/// with vertical metrics, every glyph one em down the line and 120 units below its vertical+/// origin, except ヸ (drawn as O): 1.024 em. No vertical forms. Added to the global database once.+fn vertical_test_font() -> &'static str {+ use designcraft_fonts::testing::{font_mapping, with_vmtx};+ const FAMILY: &str = "DC Test Vertical";+ static ADDED: std::sync::Once = std::sync::Once::new();+ ADDED.call_once(|| {+ let glyphs = [('一', 'X'), ('二', 'X'), ('日', 'X'), ('本', 'X'), ('ま', 'o'), ('ヸ', 'O'), ('、', ','), ('A', 'A'), ('b', 'b')];+ let base = font_mapping(FAMILY, &glyphs).unwrap();+ let scratch = designcraft_fonts::FontDb::with_font_dirs(vec![]);+ scratch.add_font(base.clone());+ let wi = u16::try_from(scratch.face(FAMILY, "Regular").glyph_for('ヸ')).unwrap();+ designcraft_fonts::FontDb::global().add_font(with_vmtx(&base, (1000, 120), &[(wi, 1024, 100)]).unwrap());+ });+ FAMILY+}++/// Shippori Mincho (vertical forms, `vpal`) when built with craft-fonts; else `None`, with a note.+fn shippori() -> Option<&'static str> {+ if !designcraft_fonts::japanese_fonts().any(|f| f.family == "Shippori Mincho") {+ eprintln!("skipped Shippori Mincho: built without craft-fonts (set CRAFT_FONTS_DIR to a checkout)");+ return None;+ }+ Some("Shippori Mincho")+}++/// The fonts vertical layout is checked in: the synthetic one, and Shippori Mincho with craft-fonts.+fn vertical_families() -> Vec<&'static str> {+ std::iter::once(vertical_test_font()).chain(shippori()).collect()+}++/// A vertical frame (no inset) with `text` in `family` at 20 pt (and `over`), and its first line+/// with the frame's first column.+fn vertical_line(family: &str, text: &str, over: impl Fn(&mut designcraft_doc::CharFormat)) -> (Line, Rect) {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 200.0, 500.0), lid, text, ParaFormat::default()).unwrap();+ if let Some(tf) = d.item_mut(fid).and_then(|i| i.text_frame_mut()) {+ tf.options.inset = [0.0; 4];+ }+ d.story_mut(sid).unwrap().vertical = true;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {+ f.over.font_family = Some(family.into());+ f.over.size = Some(20.0);+ over(f);+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let ft = &cs.frames[0];+ assert!(ft.vertical);+ let line = ft.lines[0].clone();+ assert!(line.glyphs.iter().all(|g| g.face.family == family), "{family}: {:?}", line.glyphs.iter().map(|g| &g.face.family).collect::<Vec<_>>());+ (line, ft.columns[0])+}++/// Text-space bounds of a glyph's ink as drawn in a vertical frame.+fn vertical_ink(g: &PlacedGlyph, baseline: f64) -> Rect {+ use designcraft_geom::{Affine, Shape};+ let ink = designcraft_fonts::FontDb::global().outline(&g.face, g.gid).bounding_box();+ let mut a = Affine::translate((g.x, baseline + g.y)) * Affine::scale_non_uniform(g.sx, g.sy);+ if let Some(turn) = g.vertical_xf(baseline) {+ a = turn * a;+ }+ a.transform_rect_bbox(ink)+}++/// The em box in text space: along the line from x (page down), across from its top (text -y,+/// page right) to its bottom → (right, left, centre).+fn em_across(l: &Line, g: &PlacedGlyph) -> (f64, f64, f64) {+ let (top, bottom) = g.face.em_box();+ let right = l.baseline + g.y - top * g.sy;+ let left = l.baseline + g.y - bottom * g.sy;+ (right, left, (right + left) / 2.0)+}++#[test]+fn upright_glyphs_hang_on_the_line_centre() {+ for family in vertical_families() {+ let (l, _) = vertical_line(family, "一", |_| {});+ let ichi = &l.glyphs[0];+ assert!(ichi.upright, "{family}");+ // An ideograph is centred across the line and inside its em along it.+ let (_, _, centre) = em_across(&l, ichi);+ let ink = vertical_ink(ichi, l.baseline);+ assert!(((ink.y0 + ink.y1) / 2.0 - centre).abs() < 0.05 * 20.0, "{family}: {ink:?} {centre}");+ assert!(ink.x0 > ichi.x && ink.x1 < ichi.x + ichi.adv, "{family}: {ink:?}");+ }+ // The synthetic glyph's top is its top side bearing (120 units) below its vertical origin.+ let (l, _) = vertical_line(vertical_test_font(), "一", |_| {});+ let ink = vertical_ink(&l.glyphs[0], l.baseline);+ assert!((ink.x0 - l.glyphs[0].x - 2.4).abs() < 1e-6, "{ink:?} {}", l.glyphs[0].x);+}++#[test]+fn upright_punctuation_takes_its_vertical_form_and_place() {+ // A font with vertical forms: Shippori Mincho.+ let Some(family) = shippori() else { return };+ let (l, _) = vertical_line(family, "一、", |_| {});+ let comma = &l.glyphs[1];+ assert!(comma.upright);+ assert_ne!(comma.gid, comma.face.glyph_for('、'), "vertical form (vert)");+ let (right, _, centre) = em_across(&l, comma);+ // The comma's ink sits in the upper right quarter of its em box on the page.+ let ink = vertical_ink(comma, l.baseline);+ assert!(ink.x0 >= comma.x - 1e-6 && ink.x1 < comma.x + comma.adv / 2.0, "upper half: {ink:?} {} {}", comma.x, comma.adv);+ assert!(ink.y0 >= right - 1e-6 && ink.y1 < centre, "right half: {ink:?} {right} {centre}");+}++#[test]+fn latin_in_vertical_text_turns_as_a_run() {+ // Shippori Mincho's `vrt2` has turned Latin forms; a turned run must not use them.+ for family in vertical_families() {+ let (l, _) = vertical_line(family, "日本Ab", |_| {});+ let latin: Vec<_> = l.glyphs.iter().filter(|g| g.byte >= "日本".len()).collect();+ let face = latin[0].face;+ assert_eq!(latin.iter().map(|g| g.gid).collect::<Vec<_>>(), [face.glyph_for('A'), face.glyph_for('b')], "{family}");+ assert!(latin.iter().all(|g| !g.upright && g.vertical_xf(l.baseline).is_none()), "{family}");+ assert!((latin[0].adv - face.advance(latin[0].gid) * latin[0].sx).abs() < 1e-9, "{family}: horizontal advance");+ }+}++#[test]+fn upright_glyphs_advance_by_their_vertical_metrics() {+ // ヸ is 1.024 em tall in both fonts.+ for family in vertical_families() {+ let (l, _) = vertical_line(family, "一ヸ一", |_| {});+ let g = &l.glyphs;+ assert_eq!(g[1].face.v_advance(g[1].gid), 1024.0, "{family}");+ assert!((g[1].x - g[0].x - 20.0).abs() < 1e-9, "{family}");+ assert!((g[2].x - g[1].x - 20.48).abs() < 1e-9, "{family}: {} {}", g[1].x, g[2].x);+ }+ let Some(family) = shippori() else { return };+ // Shippori's ヸ is an em wide.+ let (l, _) = vertical_line(family, "ヸ", |_| {});+ assert_eq!(l.glyphs[0].face.advance(l.glyphs[0].gid), 1000.0);+ // Proportional vertical metrics (`vpal`): ま takes 0.974 em.+ let (l, _) = vertical_line(family, "まま", |f| f.over.otf_features = Some(vec!["vpal".into()]));+ assert!((l.glyphs[1].x - l.glyphs[0].x - 19.48).abs() < 1e-9, "{:?}", l.glyphs.iter().map(|g| g.x).collect::<Vec<_>>());+ let (l, _) = vertical_line(family, "まま", |_| {});+ assert!((l.glyphs[1].x - l.glyphs[0].x - 20.0).abs() < 1e-9);+}++#[test]+fn vertical_lines_fit_the_em_box() {+ // First baseline at the ascent: an upright line's ascent is its em box top, so the em box+ // touches the frame's right edge. The synthetic font's em box is Source Sans 3's BASE one+ // (0.83 em, -0.17 em); Shippori Mincho's its OS/2 typo metrics (0.88 em, -0.12 em).+ let expected = [(vertical_test_font(), 16.6, 3.4)].into_iter().chain(shippori().map(|f| (f, 17.6, 2.4)));+ for (family, ascent, descent) in expected {+ let (l, col) = vertical_line(family, "一二", |_| {});+ assert!((l.ascent - ascent).abs() < 1e-9 && (l.descent - descent).abs() < 1e-9, "{family}: {} {}", l.ascent, l.descent);+ assert!((l.baseline - col.y0 - ascent).abs() < 1e-9, "{family}: {} {}", l.baseline, col.y0);+ }+}++/// A drop cap set in one of the document's own fonts measures its side bearing in that font.+#[test]+fn drop_cap_in_a_document_font_aligns_its_left_edge() {+ use designcraft_geom::Shape as _;+ const FAMILY: &str = "DocFont Drop Cap";+ let text = format!("Once {LOREM}");+ let mut chars: Vec<char> = text.chars().collect();+ chars.sort_unstable();+ chars.dedup();+ let folder = std::env::temp_dir().join(format!("dc-compose-dropcap-docfont-{}", std::process::id()));+ std::fs::create_dir_all(&folder).unwrap();+ std::fs::write(folder.join("dropcap.ttf"), designcraft_fonts::testing::font_with_glyph(FAMILY, &chars, 'O').unwrap()).unwrap();+ let scope = designcraft_fonts::FontDb::global().load_document_fonts(&folder).scope;+ let para = ParaAttrs { left_indent: Some(10.0), ..drop_cap(2, 1) };+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 1000.0), para);+ d.font_scope = scope;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.font_family = Some(FAMILY.into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let dc = &all_lines(&cs)[0].glyphs[0];+ assert_eq!(dc.face.family, FAMILY);+ let ink_left = dc.x + designcraft_fonts::FontDb::global().outline(dc.face.get(), dc.gid).bounding_box().x0 * dc.sx;+ assert!(ink_left - dc.x > 0.5, "the O has a visible side bearing");+ assert!((ink_left - 10.0).abs() < 1e-6, "ink at {ink_left}");+ let _ = std::fs::remove_dir_all(&folder);+}++#[test]+fn embedded_text_frames_compose_and_footnotes_retain_object_sources() {+ use designcraft_doc::{AnchorPosition, AnchoredObject};+ let (mut d, body, _) = doc_with("Body", Rect::new(20.0, 20.0, 400.0, 600.0), ParaAttrs::default());+ let (fid, child) =+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 80.0, 40.0), d.default_layer(), "Embedded", ParaFormat::default()).unwrap();+ let item = d.item(fid).unwrap().clone();+ d.spread_mut(SpreadRef::Doc(0)).unwrap().items.retain(|i| i.id != fid);+ let story = d.story_mut(body).unwrap();+ story.insert_note(4, "Note", ParaFormat::default());+ Arc::make_mut(&mut story.notes[0]).text.insert_object(0, AnchoredObject::new(item, AnchorPosition::Inline { y_offset: 0.0 }));+ d.check().unwrap();+ let child_cs = compose_story(&d, child, &ComposeOptions::default());+ assert!(!child_cs.is_overset());+ assert!(!child_cs.frame(fid).unwrap().lines.is_empty());+ let cs = compose_story(&d, body, &ComposeOptions::default());+ assert!(!cs.is_overset());+ let note = &cs.frames[0].notes[0];+ assert_eq!(note.text.story, StoryId(0));+ assert_eq!(note.text.frames[0].objects[0].object.item.id, fid);++ let cache = Cache::new();+ assert!(!cache.get(&d, child, None).is_overset());+ let note = Arc::make_mut(&mut d.story_mut(body).unwrap().notes[0]);+ let anchor = Arc::make_mut(&mut note.text.objects[0]);+ let original_path = anchor.item.path.clone();+ anchor.item.path = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 80.0, 1.0));+ assert!(cache.get(&d, child, None).is_overset(), "embedded frame geometry must invalidate cached composition");+ Arc::make_mut(&mut Arc::make_mut(&mut d.story_mut(body).unwrap().notes[0]).text.objects[0]).item.path = original_path;++ // A reference back into the owning story must be rejected before rendering.+ let mut cycle = d.anchored_item(fid).unwrap().clone();+ cycle.id = ItemId(d.alloc());+ cycle.text_frame_mut().unwrap().story = body;+ d.story_mut(body).unwrap().frames.push(cycle.id);+ d.story_mut(child).unwrap().insert_object(0, AnchoredObject::new(cycle, AnchorPosition::Inline { y_offset: 0.0 }));+ assert!(d.check().unwrap_err().to_string().contains("cyclic"));+}++#[test]+fn inline_object_only_line_does_not_reserve_phantom_font_descent() {+ use designcraft_doc::{AnchorPosition, AnchoredObject, Item, Shape};+ let (mut d, sid, _) = doc_with("", Rect::new(0.0, 0.0, 10.0, 15.0), ParaAttrs::default());+ let item = Item::new(ItemId(d.alloc()), d.default_layer(), Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 7.0, 9.0)));+ d.story_mut(sid).unwrap().insert_object(0, AnchoredObject::new(item, AnchorPosition::Inline { y_offset: 5.0 }));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ assert_eq!(cs.frames[0].objects.len(), 1);+ assert_eq!(cs.frames[0].lines[0].descent, 0.0);+ // Genuine geometric overflow must still be reported.+ d.story_mut(sid).unwrap().objects[0] =+ Arc::new(AnchoredObject::new(cs.frames[0].objects[0].object.item.clone(), AnchorPosition::Inline { y_offset: 7.0 }));+ assert!(compose_story(&d, sid, &ComposeOptions::default()).is_overset());+}++#[test]+fn composite_metrics_and_character_mappings_apply_inside_footnotes() {+ use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry};+ let (mut d, sid, _) = doc_with("Body", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default());+ d.styles_mut().composite_fonts.push(CompositeFont {+ name: "Mixed".into(),+ entries: vec![+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },+ CompositeFontEntry {+ characters: "12".into(),+ family: "Source Sans 3".into(),+ relative_size: 0.8,+ horizontal_scale: 0.9,+ vertical_scale: 1.1,+ baseline_shift: 0.1,+ scale_option: false,+ ..Default::default()+ },+ CompositeFontEntry { characters: "2".into(), family: "Inter".into(), ..Default::default() },+ ],+ });+ let story = d.story_mut(sid).unwrap();+ story.insert_note(4, "A12", ParaFormat::default());+ let note = Arc::make_mut(&mut story.notes[0]);+ note.text.format_chars(0..3, |f| f.over.font_family = Some("CompositeFont/Mixed".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let note = &cs.frames[0].notes[0];+ let glyphs = ¬e.text.frames[0].lines[0].glyphs;+ let a = glyphs.iter().find(|g| g.byte == 0 && g.len > 0).unwrap();+ let one = glyphs.iter().find(|g| g.byte == 1 && g.len > 0).unwrap();+ let two = glyphs.iter().find(|g| g.byte == 2 && g.len > 0).unwrap();+ assert_eq!(a.face.family, "Source Serif 4");+ assert_eq!(one.face.family, "Source Sans 3");+ assert_eq!(two.face.family, "Inter");+ let style = ¬e.text.styles[one.style as usize];+ assert!((style.size - 9.6).abs() < 1e-8);+ assert!(!note.text.styles.iter().any(|s| s.missing_font));+}++#[test]+fn generated_note_labels_resolve_composite_components_and_keep_one_anchor() {+ use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry};+ let (mut d, sid, _) = doc_with("Body", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default());+ d.styles_mut().composite_fonts.push(CompositeFont {+ name: "Generated Mixed".into(),+ entries: vec![+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },+ CompositeFontEntry { characters: "[]".into(), family: "Inter".into(), relative_size: 0.8, ..Default::default() },+ ],+ });+ d.footnote_options.affix_in = designcraft_doc::notes::AffixIn::Both;+ d.footnote_options.prefix = "[".into();+ d.footnote_options.suffix = "]".into();+ let story = d.story_mut(sid).unwrap();+ story.insert_note(4, "Note", ParaFormat::default());+ story.format_chars(4..7, |f| f.over.font_family = Some("Generated Mixed".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let glyphs: Vec<_> = cs.frames[0].lines.iter().flat_map(|l| &l.glyphs).filter(|g| g.byte == 4).collect();+ assert_eq!(glyphs.iter().filter(|g| g.len > 0).count(), 1);+ assert_eq!(glyphs.iter().map(|g| g.rendered_char).collect::<String>(), "[1]");+ assert!(glyphs.iter().all(|g| g.gid != 0));+ assert!(glyphs.iter().filter(|g| matches!(g.rendered_char, '[' | ']')).all(|g| g.face.family == "Inter"));+ assert_eq!(glyphs.iter().find(|g| g.rendered_char == '1').unwrap().face.family, "Source Serif 4");+ assert_eq!(cs.frames[0].notes.len(), 1);+}++#[test]+fn generated_note_labels_use_coverage_fallback() {+ let font = designcraft_fonts::testing::font_with("Generated Label Coverage", &['\u{E888}']).unwrap();+ designcraft_fonts::FontDb::global().add_font(font);+ let (mut d, sid, _) = doc_with("Body", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default());+ d.footnote_options.affix_in = designcraft_doc::notes::AffixIn::Both;+ d.footnote_options.prefix = "\u{E888}".into();+ d.footnote_options.suffix = "".into();+ d.settings.glyph_fallback = true;+ d.story_mut(sid).unwrap().insert_note(4, "Note", ParaFormat::default());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let glyph = cs.frames[0].lines.iter().flat_map(|l| &l.glyphs).find(|g| g.rendered_char == '\u{E888}').unwrap();+ assert_ne!(glyph.gid, 0);+ assert_eq!(glyph.face.family, "Generated Label Coverage");+}++#[test]+fn mojikumi_custom_pairs_change_positions_and_breaks_without_font_scaling() {+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};+ let (mut d, sid, _) = doc_with(+ "A1A1A1",+ Rect::new(0.0, 0.0, 55.0, 300.0),+ ParaAttrs { hyphenate: Some(false), composer: Some(Composer::SingleLine), ..Default::default() },+ );+ let before = compose_story(&d, sid, &ComposeOptions::default());+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {+ name: "Synthetic".into(),+ based_on: "SimpChineseDefault".into(),+ overrides: vec![+ MojikumiAki { target_class: 18, side_class: 25, after: true, minimum: 1.0, desired: 1.0, maximum: 1.0, ..Default::default() },+ MojikumiAki { target_class: 25, side_class: 18, after: true, minimum: 1.0, desired: 1.0, maximum: 1.0, ..Default::default() },+ ],+ });+ d.story_mut(sid).unwrap().paras[0].para.mojikumi = Some("MojikumiTable/Synthetic".into());+ let after = compose_story(&d, sid, &ComposeOptions::default());+ assert!(all_lines(&after).len() > all_lines(&before).len());+ let a = &all_lines(&after)[0].glyphs;+ let b = &all_lines(&before)[0].glyphs;+ assert!((a[1].x - b[1].x - 12.0).abs() < 0.001);+ assert_eq!(a[0].sx, b[0].sx);+ assert!(all_lines(&after).iter().all(|l| l.end_x <= l.x1 + 0.01));+}++#[test]+fn mojikumi_paragraph_indent_adds_to_paragraph_settings_and_rounds_no_glyphs() {+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};+ let (mut d, sid, _) = doc_with(+ "ABC",+ Rect::new(0.0, 0.0, 200.0, 100.0),+ ParaAttrs { first_line_indent: Some(7.0), mojikumi: Some("MojikumiTable/Indent".into()), ..Default::default() },+ );+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {+ name: "Indent".into(),+ based_on: "SimpChineseDefault".into(),+ overrides: vec![MojikumiAki {+ target_class: 18,+ side_class: 23,+ after: false,+ minimum: 2.0,+ desired: 2.0,+ maximum: 2.0,+ ..Default::default()+ }],+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let line = all_lines(&cs)[0];+ assert!((line.glyphs[0].x - 31.0).abs() < 0.001, "{}", line.glyphs[0].x);+ assert_eq!(line.glyphs.len(), 3);+}++#[test]+fn mojikumi_justifies_cjk_without_spaces_and_respects_fixed_spacing() {+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};+ let (mut d, sid, _) = doc_with(+ "A1A1",+ Rect::new(0.0, 0.0, 100.0, 100.0),+ ParaAttrs { align: Some(Align::FullyJustified), mojikumi: Some("MojikumiTable/Elastic".into()), ..Default::default() },+ );+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {+ name: "Elastic".into(),+ based_on: "SimpChineseDefault".into(),+ overrides: vec![MojikumiAki {+ target_class: 18,+ side_class: 25,+ after: true,+ minimum: 0.0,+ desired: 0.0,+ maximum: 5.0,+ priority: 1,+ ..Default::default()+ }],+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!((all_lines(&cs)[0].end_x - 100.0).abs() < 0.001, "{}", all_lines(&cs)[0].end_x);+}++#[test]+fn mojikumi_fixed_pairs_are_not_stretched_by_single_word_justification() {+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};+ let (mut d, sid, _) = doc_with(+ "A1A1",+ Rect::new(0.0, 0.0, 150.0, 100.0),+ ParaAttrs { align: Some(Align::FullyJustified), mojikumi: Some("MojikumiTable/Fixed".into()), ..Default::default() },+ );+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {+ name: "Fixed".into(),+ based_on: "SimpChineseDefault".into(),+ overrides: [(18, 25), (25, 18)]+ .into_iter()+ .map(|(target_class, side_class)| MojikumiAki {+ target_class,+ side_class,+ after: true,+ minimum: 0.25,+ desired: 0.25,+ maximum: 0.25,+ ..Default::default()+ })+ .collect(),+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let line = all_lines(&cs)[0];+ assert!(line.end_x < 100.0, "Fixed spacing was stretched: {}", line.end_x);+ d.story_mut(sid).unwrap().paras[0].para.align = Some(Align::Left);+ let ragged = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(line.end_x, all_lines(&ragged)[0].end_x);+}++#[test]+fn mojikumi_kinsoku_push_in_and_push_out_select_different_legal_breaks() {+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};+ let text = "甲乙丙丁戊己庚辛";+ let (mut d, sid, _) = doc_with(+ text,+ Rect::new(0.0, 0.0, 45.0, 300.0),+ ParaAttrs {+ composer: Some(Composer::SingleLine),+ mojikumi: Some("MojikumiTable/Compress".into()),+ kinsoku_type: Some("KinsokuPushInFirst".into()),+ ..Default::default()+ },+ );+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {+ name: "Compress".into(),+ based_on: "SimpChineseDefault".into(),+ overrides: vec![MojikumiAki {+ target_class: 12,+ side_class: 12,+ after: true,+ minimum: 0.0,+ desired: 1.0,+ maximum: 1.0,+ priority: 1,+ ..Default::default()+ }],+ });+ let inside = compose_story(&d, sid, &ComposeOptions::default());+ d.story_mut(sid).unwrap().paras[0].para.kinsoku_type = Some("KinsokuPushOutFirst".into());+ let outside = compose_story(&d, sid, &ComposeOptions::default());+ assert!(all_lines(&inside)[0].range.end > all_lines(&outside)[0].range.end);+ for cs in [&inside, &outside] {+ assert!(all_lines(cs).iter().all(|l| l.end_x <= l.x1 + 0.01));+ }+}++#[test]+fn mojikumi_priority_and_elastic_line_start_are_used_in_placement() {+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};+ let (mut d, sid, _) = doc_with("A1B2", Rect::new(0.0, 0.0, 45.0, 100.0), ParaAttrs::default());+ let natural = compose_story(&d, sid, &ComposeOptions::default());+ let middle_gap = all_lines(&natural)[0].glyphs[2].x - all_lines(&natural)[0].glyphs[1].x;+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {+ name: "Priority".into(),+ based_on: "SimpChineseDefault".into(),+ overrides: vec![+ MojikumiAki {+ target_class: 18,+ side_class: 25,+ after: true,+ minimum: 0.0,+ desired: 0.0,+ maximum: 10.0,+ priority: 1,+ ..Default::default()+ },+ MojikumiAki {+ target_class: 25,+ side_class: 18,+ after: true,+ minimum: 0.0,+ desired: 0.0,+ maximum: 10.0,+ priority: 2,+ ..Default::default()+ },+ ],+ });+ let para = &mut d.story_mut(sid).unwrap().paras[0].para;+ para.mojikumi = Some("MojikumiTable/Priority".into());+ para.align = Some(Align::FullyJustified);+ let result = compose_story(&d, sid, &ComposeOptions::default());+ let line = all_lines(&result)[0];+ assert!((line.end_x - 45.0).abs() < 0.001);+ assert!((line.glyphs[2].x - line.glyphs[1].x - middle_gap).abs() < 0.001, "Priority 2 was used before priority 1 was exhausted");++ let (mut d, sid, _) = doc_with(+ "A",+ Rect::new(0.0, 0.0, 30.0, 100.0),+ ParaAttrs { mojikumi: Some("MojikumiTable/Start".into()), align: Some(Align::FullyJustified), ..Default::default() },+ );+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {+ name: "Start".into(),+ based_on: "SimpChineseDefault".into(),+ overrides: vec![MojikumiAki {+ target_class: 18,+ side_class: 23,+ after: false,+ minimum: 0.0,+ desired: 0.0,+ maximum: 5.0,+ priority: 1,+ ..Default::default()+ }],+ });+ let result = compose_story(&d, sid, &ComposeOptions::default());+ let line = all_lines(&result)[0];+ assert!((line.end_x - 30.0).abs() < 0.001);+ assert!(line.glyphs[0].x > 10.0, "Leading gap must move the first outline too");+}++#[test]+fn mojikumi_equal_priority_shares_leading_and_internal_space() {+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};+ let (mut d, sid, _) = doc_with("A1", Rect::new(0.0, 0.0, 40.0, 100.0), ParaAttrs::default());+ let natural = compose_story(&d, sid, &ComposeOptions::default());+ let old = all_lines(&natural)[0];+ let extra = 40.0 - old.end_x;+ let old_second = old.glyphs[1].x;+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {+ name: "Shared".into(),+ based_on: "SimpChineseDefault".into(),+ overrides: [(18, 23, false), (18, 25, true)]+ .into_iter()+ .map(|(target_class, side_class, after)| MojikumiAki {+ target_class,+ side_class,+ after,+ maximum: 10.0,+ priority: 1,+ ..Default::default()+ })+ .collect(),+ });+ let para = &mut d.story_mut(sid).unwrap().paras[0].para;+ para.mojikumi = Some("MojikumiTable/Shared".into());+ para.align = Some(Align::FullyJustified);+ let result = compose_story(&d, sid, &ComposeOptions::default());+ let line = all_lines(&result)[0];+ assert!((line.glyphs[0].x - extra / 2.0).abs() < 0.001);+ assert!((line.glyphs[1].x - old_second - extra).abs() < 0.001);+ assert!((line.end_x - 40.0).abs() < 0.001);+}++#[test]+fn mojikumi_nonfloating_and_leading_only_compression_fit_ragged_lines() {+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};+ for composer in [Composer::SingleLine, Composer::Paragraph] {+ for leading in [true, false] {+ let (mut d, sid, _) = doc_with(+ "A",+ Rect::new(0.0, 0.0, 15.0, 100.0),+ ParaAttrs { composer: Some(composer), mojikumi: Some("MojikumiTable/Endpoint".into()), ..Default::default() },+ );+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {+ name: "Endpoint".into(),+ based_on: "SimpChineseDefault".into(),+ overrides: vec![MojikumiAki {+ target_class: 18,+ side_class: if leading { 23 } else { 22 },+ after: !leading,+ minimum: 0.0,+ desired: 1.0,+ maximum: 1.0,+ priority: 1,+ does_not_float: true,+ }],+ });+ let result = compose_story(&d, sid, &ComposeOptions::default());+ let line = all_lines(&result)[0];+ assert!(line.end_x <= 15.0, "{composer:?}, leading={leading}: {}", line.end_x);+ assert!(line.glyphs[0].x.abs() < 0.001, "Discrete leading gap must reach its endpoint");+ }+ }+}++// ---------- span columns ----------++/// A story of `before` body paragraphs, a heading spanning all columns, and `after` body+/// paragraphs, in a three-column frame. Returns the heading's paragraph index.+fn span_doc(before: usize, after: usize, rect: Rect) -> (Document, StoryId, ItemId, usize) {+ let mut paras: Vec<&str> = vec![LOREM; before];+ paras.push("A heading across the columns");+ paras.extend(vec![LOREM; after]);+ let (mut d, sid, fid) = doc_with(¶s.join("\n"), rect, ParaAttrs::default());+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 3;+ d.story_mut(sid).unwrap().paras[before].para.span_columns = Some(SpanColumns::Span(0));+ (d, sid, fid, before)+}++/// The line's leading slot (glyph ascent and descent may reach into the neighbouring lines).+fn line_box(l: &Line) -> (f64, f64) {+ (l.baseline - 0.75 * l.leading, l.baseline + 0.25 * l.leading)+}++/// No two lines of a frame share any area.+fn assert_no_overlap(ft: &FrameText) {+ for (i, a) in ft.lines.iter().enumerate() {+ for b in &ft.lines[i + 1..] {+ let ((at, ab), (bt, bb)) = (line_box(a), line_box(b));+ let x_overlap = a.x0 < b.x1 - 0.5 && b.x0 < a.x1 - 0.5;+ let y_overlap = at < bb - 0.5 && bt < ab - 0.5;+ assert!(+ !(x_overlap && y_overlap),+ "lines overlap: para {} col {} y {:.1}..{:.1} and para {} col {} y {:.1}..{:.1}",+ a.para,+ a.column,+ at,+ ab,+ b.para,+ b.column,+ bt,+ bb+ );+ }+ }+}++#[test]+fn mojikumi_places_custom_gap_after_combining_marks() {+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};+ let (mut d, sid, _) = doc_with("A\u{0323}\u{0301}1", Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default());+ let natural = compose_story(&d, sid, &ComposeOptions::default());+ let old = &all_lines(&natural)[0].glyphs;+ assert!(old.len() >= 3, "Exercise a cluster with a separate combining glyph");+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {+ name: "Clusters".into(),+ based_on: "SimpChineseDefault".into(),+ overrides: vec![MojikumiAki {+ target_class: 18,+ side_class: 25,+ after: true,+ minimum: 1.0,+ desired: 1.0,+ maximum: 1.0,+ ..Default::default()+ }],+ });+ d.story_mut(sid).unwrap().paras[0].para.mojikumi = Some("MojikumiTable/Clusters".into());+ let result = compose_story(&d, sid, &ComposeOptions::default());+ let new = &all_lines(&result)[0].glyphs;+ assert_eq!(new.len(), old.len());+ for (before, after) in old.iter().zip(new) {+ let expected = if before.rendered_char == '1' { 12.0 } else { 0.0 };+ assert!((after.x - before.x - expected).abs() < 0.001, "Glyph {:?} moved incorrectly", before.rendered_char);+ }+}++#[test]+fn mojikumi_does_not_restore_fullwidth_blanks_to_narrow_tracked_punctuation() {+ let family = "Mojikumi Narrow Body";+ let font = designcraft_fonts::testing::font_mapping(family, &[('(', 'i'), ('A', 'A')]).unwrap();+ designcraft_fonts::FontDb::global().add_font(font);+ let (mut d, sid, _) = doc_with("(A", Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0.."(A".len(), |f| {+ f.over.font_family = Some(family.into());+ f.over.tracking = Some(1000.0);+ });+ let natural = compose_story(&d, sid, &ComposeOptions::default());+ d.story_mut(sid).unwrap().paras[0].para.mojikumi = Some("SimpChineseDefault".into());+ let result = compose_story(&d, sid, &ComposeOptions::default());+ for (a, b) in all_lines(&natural)[0].glyphs.iter().zip(&all_lines(&result)[0].glyphs) {+ assert!((a.x - b.x).abs() < 0.001);+ assert!((a.adv - b.adv).abs() < 0.001);+ }+}++#[test]+fn mojikumi_one_em_line_end_set_sets_closing_punctuation_full_width_at_line_end() {+ let family = "Mojikumi Full Stop";+ let font = designcraft_fonts::testing::font_mapping(family, &[('(', '‰'), ('一', '‰'), ('。', '‰')]).unwrap();+ designcraft_fonts::FontDb::global().add_font(font);+ let text = "(一。";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.font_family = Some(family.into()));+ // Advances of the opening bracket at line start and the full stop at line end.+ let mut edges = |set: &str| {+ d.story_mut(sid).unwrap().paras[0].para.mojikumi = Some(set.into());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let line = all_lines(&cs)[0];+ let adv = |c| line.glyphs.iter().find(|g| g.rendered_char == c).map(|g| (g.adv, g.face.units_per_em() * g.sx)).unwrap();+ (adv('(').0, adv('。').0, adv('。').1)+ };+ let (open, stop, em) = edges("Nothing");+ let half = edges("LineEndAllOneHalfEmEnum");+ let one = edges("LineEndAllOneEmEnum");+ assert!((open - half.0 - em * 0.5).abs() < 0.01 && (stop - half.1 - em * 0.5).abs() < 0.01, "half-em set: {half:?} of {open}/{stop}");+ assert!((open - one.0 - em * 0.5).abs() < 0.01 && (stop - one.1).abs() < 0.01, "one-em set: {one:?} of {open}/{stop}");+}++fn ruled(text: &str, rect: Rect, columns: u32, edit: impl FnOnce(&mut Document, StoryId)) -> (Document, ItemId, Vec<Rect>) {+ let (mut d, sid, fid) = doc_with(text, rect, ParaAttrs::default());+ {+ let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options;+ o.columns = columns;+ o.gutter = 12.0;+ o.inset = [10.0, 6.0, 20.0, 6.0];+ o.column_rule = true;+ o.column_rule_weight = 2.0;+ o.column_rule_color = "[Black]".into();+ }+ edit(&mut d, sid);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let rules = cs.frames[0].decos.iter().filter(|dc| dc.color == "[Black]").map(|dc| dc.rect).collect();+ (d, fid, rules)+}++#[test]+fn column_rules_sit_in_the_gutters_inside_the_insets() {+ // Two columns in 0..300 with 6 pt side insets: the gutter is centred on 150.+ let (_, _, rules) = ruled("Text", Rect::new(0.0, 0.0, 300.0, 200.0), 2, |_, _| {});+ assert_eq!(rules.len(), 1, "{rules:?}");+ let r = rules[0];+ assert!((r.center().x - 150.0).abs() < 1e-9 && (r.width() - 2.0).abs() < 1e-9, "{r:?}");+ assert!((r.y0 - 10.0).abs() < 1e-9 && (r.y1 - 180.0).abs() < 1e-9, "{r:?}");+ // Three columns: one rule per gutter, each centred between its two columns.+ let (_, _, rules) = ruled("Text", Rect::new(0.0, 0.0, 300.0, 200.0), 3, |_, _| {});+ assert_eq!(rules.len(), 2, "{rules:?}");+ let w = (288.0 - 24.0) / 3.0;+ for (i, r) in rules.iter().enumerate() {+ let edge = 6.0 + w * (i + 1) as f64 + 12.0 * i as f64;+ assert!((r.center().x - (edge + 6.0)).abs() < 1e-9, "{i}: {r:?}");+ }+ // Off, or a single column: no rule.+ let (_, _, rules) = ruled("Text", Rect::new(0.0, 0.0, 300.0, 200.0), 1, |_, _| {});+ assert!(rules.is_empty());+ let (_, _, rules) = ruled("Text", Rect::new(0.0, 0.0, 300.0, 200.0), 2, |d, sid| {+ let fid = d.story(sid).unwrap().frames[0];+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.column_rule = false;+ });+ assert!(rules.is_empty());+}++#[test]+fn column_rules_centre_on_unequal_gutters_and_ignore_bad_weights() {+ let cols = [Rect::new(200.0, 0.0, 300.0, 50.0), Rect::new(0.0, 0.0, 100.0, 50.0), Rect::new(110.0, 0.0, 180.0, 50.0)];+ let weight = |w: f64| TextFrameOptions { column_rule_weight: w, ..Default::default() };+ let rules = column_rule_rects(&cols, &[], &weight(1.0));+ let centres: Vec<f64> = rules.iter().map(|r| r.center().x).collect();+ assert_eq!(centres, [105.0, 190.0]);+ assert!(column_rule_rects(&cols, &[], &weight(f64::NAN)).is_empty());+ assert!(column_rule_rects(&cols, &[], &weight(-1.0)).is_empty());+ assert!((column_rule_rects(&cols, &[], &weight(1e12))[0].width() - 1000.0).abs() < 1e-9);+}++#[test]+fn column_rules_in_right_to_left_and_vertical_frames() {+ let (_, _, rules) = ruled("نص", Rect::new(0.0, 0.0, 300.0, 200.0), 2, |d, sid| {+ d.story_mut(sid).unwrap().direction = designcraft_doc::TextDirection::RightToLeft;+ });+ assert_eq!(rules.len(), 1);+ assert!((rules[0].center().x - 150.0).abs() < 1e-9, "{rules:?}");+ // Vertical type: the columns stack top to bottom, so the rule runs across the frame.+ let (d, fid, rules) = ruled("縦書き", Rect::new(100.0, 100.0, 400.0, 300.0), 2, |d, sid| d.story_mut(sid).unwrap().vertical = true);+ assert_eq!(rules.len(), 1);+ let r = d.text_xf(d.item(fid).unwrap()).transform_rect_bbox(rules[0]);+ // Text area: x 106..394, y 110..280; the gutter is centred on y 195.+ assert!((r.x0 - 106.0).abs() < 1e-6 && (r.x1 - 394.0).abs() < 1e-6, "{r:?}");+ assert!((r.center().y - 195.0).abs() < 1e-6 && (r.height() - 2.0).abs() < 1e-6, "{r:?}");+}++#[test]+fn column_rules_break_around_paragraphs_that_span_columns() {+ let text = format!("A heading that spans both columns\n{LOREM} {LOREM}");+ let (d, fid, rules) = ruled(&text, Rect::new(0.0, 0.0, 300.0, 400.0), 2, |d, sid| {+ d.story_mut(sid).unwrap().paras[0].para.span_columns = Some(designcraft_doc::SpanColumns::Span(0));+ });+ let sid = d.item(fid).unwrap().text_frame().unwrap().story;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let span: Vec<&Line> = cs.frames[0].lines.iter().filter(|l| l.para == 0).collect();+ assert!(!span.is_empty() && span.iter().all(|l| l.x0 < 150.0 && l.x1 > 150.0), "the heading spans");+ let (top, bottom) = (span[0].baseline - span[0].ascent, span[span.len() - 1].baseline + span[span.len() - 1].descent);+ assert!(!rules.is_empty());+ for r in &rules {+ assert!(r.y1 <= top + 1e-9 || r.y0 >= bottom - 1e-9, "rule {r:?} cuts the span {top}..{bottom}");+ }+ // The rule resumes below the span and runs to the bottom of the columns.+ assert!(rules.iter().any(|r| (r.y0 - bottom).abs() < 1e-9 && (r.y1 - 380.0).abs() < 1e-9), "{rules:?}");+}++#[test]+fn column_rules_take_their_offset_insets_and_tint() {+ let (d, fid, rules) = ruled("Text", Rect::new(0.0, 0.0, 300.0, 200.0), 2, |d, sid| {+ let fid = d.story(sid).unwrap().frames[0];+ let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options;+ o.column_rule_offset = 3.0;+ o.column_rule_top_inset = 15.0;+ o.column_rule_bottom_inset = 25.0;+ o.column_rule_tint = 0.4;+ });+ // Gutter centre 150 moved 3 pt; columns 10..180 shortened to 25..155.+ assert_eq!(rules.len(), 1, "{rules:?}");+ let r = rules[0];+ assert!((r.center().x - 153.0).abs() < 1e-9 && (r.y0 - 25.0).abs() < 1e-9 && (r.y1 - 155.0).abs() < 1e-9, "{r:?}");+ let sid = d.item(fid).unwrap().text_frame().unwrap().story;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(cs.frames[0].decos.iter().any(|dc| dc.rect == r && (dc.tint - 0.4).abs() < 1e-6));+ // Insets that meet leave no rule.+ let (_, _, rules) = ruled("Text", Rect::new(0.0, 0.0, 300.0, 200.0), 2, |d, sid| {+ let fid = d.story(sid).unwrap().frames[0];+ let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options;+ o.column_rule_top_inset = 100.0;+ o.column_rule_bottom_inset = 100.0;+ });+ assert!(rules.is_empty(), "{rules:?}");+}++/// The heading spans the frame; text before it sits above it and text after it below it.+fn assert_span_layout(ft: &FrameText, h: usize) {+ let heading: Vec<&Line> = ft.lines.iter().filter(|l| l.para == h).collect();+ assert!(!heading.is_empty());+ let (c0, cn) = (ft.columns[0], ft.columns[ft.columns.len() - 1]);+ for l in &heading {+ assert!((l.x0 - c0.x0.min(cn.x0)).abs() < 1e-6 && (l.x1 - c0.x1.max(cn.x1)).abs() < 1e-6, "heading spans {}..{}", l.x0, l.x1);+ }+ let top = heading.iter().map(|l| line_box(l).0).fold(f64::INFINITY, f64::min);+ let bottom = heading.iter().map(|l| line_box(l).1).fold(f64::NEG_INFINITY, f64::max);+ for l in ft.lines.iter().filter(|l| l.para < h) {+ assert!(line_box(l).1 <= top + 0.5, "para {} col {} ends at {} below the heading top {top}", l.para, l.column, line_box(l).1);+ }+ for l in ft.lines.iter().filter(|l| l.para > h) {+ assert!(line_box(l).0 >= bottom - 0.5, "para {} col {} starts at {} above the heading bottom {bottom}", l.para, l.column, line_box(l).0);+ }+ assert_no_overlap(ft);+}++#[test]+fn text_after_a_spanning_paragraph_flows_below_it() {+ let (d, sid, _, h) = span_doc(2, 3, Rect::new(0.0, 0.0, 540.0, 300.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ let ft = &cs.frames[0];+ assert_span_layout(ft, h);+ // The text before is balanced across the three columns above the heading.+ let before: Vec<&Line> = ft.lines.iter().filter(|l| l.para < h).collect();+ let per_col = |c: u32| before.iter().filter(|l| l.column == c).count();+ let counts = [per_col(0), per_col(1), per_col(2)];+ assert!(counts.iter().all(|&n| n > 0), "{counts:?}");+ assert!(counts.iter().max().unwrap() - counts.iter().min().unwrap() <= 1, "{counts:?}");+ // The text after starts right below the heading in every column, on the same baseline.+ let bottom = ft.lines.iter().filter(|l| l.para == h).map(|l| l.baseline).fold(f64::NEG_INFINITY, f64::max);+ let firsts: Vec<f64> = (0..3).map(|c| ft.lines.iter().find(|l| l.para > h && l.column == c).map(|l| l.baseline).unwrap()).collect();+ for b in &firsts {+ assert!(*b > bottom && *b < bottom + 40.0, "{firsts:?} after {bottom}");+ }+ assert!((firsts[1] - firsts[2]).abs() < 1e-6, "{firsts:?}");+}++#[test]+fn spanning_heading_kept_with_next_and_spanning_two_of_three_columns() {+ let (mut d, sid, _, h) = span_doc(2, 3, Rect::new(0.0, 0.0, 540.0, 300.0));+ d.story_mut(sid).unwrap().paras[h].para.keep_with_next = Some(2);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ assert_span_layout(&cs.frames[0], h);+ // Spanning two of three columns: the third column beside the heading stays empty.+ d.story_mut(sid).unwrap().paras[h].para.span_columns = Some(SpanColumns::Span(2));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let ft = &cs.frames[0];+ let heading = ft.lines.iter().find(|l| l.para == h).unwrap();+ assert!((heading.x0 - ft.columns[0].x0).abs() < 1e-6 && (heading.x1 - ft.columns[1].x1).abs() < 1e-6);+ assert_no_overlap(ft);+ let bottom = heading.baseline + 0.25 * heading.leading;+ assert!(ft.lines.iter().filter(|l| l.para > h).all(|l| line_box(l).0 >= bottom - 0.5));+ assert!((0..3).all(|c| ft.lines.iter().any(|l| l.para > h && l.column == c)));+}++#[test]+fn spanning_paragraph_at_the_top_and_end_of_a_frame() {+ let (d, sid, _, h) = span_doc(0, 4, Rect::new(0.0, 0.0, 540.0, 300.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ let ft = &cs.frames[0];+ assert_span_layout(ft, h);+ assert!(ft.lines[0].para == h && ft.lines[0].baseline < 20.0);+ assert!((1..3).all(|c| ft.lines.iter().any(|l| l.column == c)));++ let (d, sid, _, h) = span_doc(3, 0, Rect::new(0.0, 0.0, 540.0, 300.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ assert_span_layout(&cs.frames[0], h);+}++#[test]+fn text_after_a_spanning_paragraph_threads_into_the_next_frame() {+ let (mut d, sid, f1, h) = span_doc(2, 8, Rect::new(0.0, 0.0, 540.0, 200.0));+ let lid = d.default_layer();+ let (f2, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 300.0, 540.0, 700.0), lid, "", ParaFormat::default()).unwrap();+ d.item_mut(f2).unwrap().text_frame_mut().unwrap().options.columns = 3;+ d.thread(f1, f2).unwrap();+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset(), "overset at {:?}", cs.overset_at);+ assert_span_layout(&cs.frames[0], h);+ let (a, b) = (&cs.frames[0], &cs.frames[1]);+ assert!((0..3).all(|c| a.lines.iter().any(|l| l.para > h && l.column == c)));+ assert!(!b.lines.is_empty() && b.lines[0].para > h && b.lines[0].baseline < 320.0);+ assert_no_overlap(b);+ // Every line of the story is set once, in order.+ let lines = all_lines(&cs);+ for w in lines.windows(2) {+ assert!(w[1].range.start >= w[0].range.end, "{:?} then {:?}", w[0].range, w[1].range);+ }+ assert_eq!(lines.last().unwrap().range.end, d.story(sid).unwrap().text.len());+}++#[test]+fn spanning_paragraph_in_rtl_and_vertical_frames() {+ let (mut d, sid, _, h) = span_doc(2, 4, Rect::new(0.0, 0.0, 540.0, 500.0));+ d.story_mut(sid).unwrap().direction = designcraft_doc::TextDirection::RightToLeft;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ assert_span_layout(&cs.frames[0], h);++ let (mut d, sid, _, h) = span_doc(2, 4, Rect::new(0.0, 0.0, 540.0, 540.0));+ d.story_mut(sid).unwrap().vertical = true;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.frames[0].lines.is_empty());+ assert_no_overlap(&cs.frames[0]);+ assert!(cs.frames[0].lines.iter().any(|l| l.para == h));+}++/// A heading spanning the columns mid-frame: text above it is balanced over the columns, text+/// after it flows below it, and each gutter's rule stops above the heading and resumes below it.+#[test]+fn column_rules_break_around_a_spanning_paragraph_between_bands() {+ let (mut d, sid, fid, h) = span_doc(2, 4, Rect::new(0.0, 0.0, 450.0, 700.0));+ {+ let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options;+ o.column_rule = true;+ o.column_rule_weight = 1.0;+ o.column_rule_color = "[Black]".into();+ }+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let ft = &cs.frames[0];+ assert_no_overlap(ft);+ let span: Vec<&Line> = ft.lines.iter().filter(|l| l.para == h).collect();+ assert!(!span.is_empty());+ let top = span.iter().map(|l| l.baseline - l.ascent).fold(f64::INFINITY, f64::min);+ let bottom = span.iter().map(|l| l.baseline + l.descent).fold(f64::NEG_INFINITY, f64::max);+ assert!(ft.lines.iter().any(|l| l.para < h), "text above the heading");+ assert!(ft.lines.iter().any(|l| l.para > h && l.column > 0 && l.baseline > bottom), "text after the heading flows below it");+ let rules: Vec<Rect> = ft.decos.iter().filter(|dc| dc.color == "[Black]").map(|dc| dc.rect).collect();+ let mut gutters: Vec<f64> = rules.iter().map(|r| r.center().x).collect();+ gutters.sort_by(f64::total_cmp);+ gutters.dedup_by(|a, b| (*a - *b).abs() < 1e-6);+ assert_eq!(gutters.len(), 2, "{rules:?}");+ for x in gutters {+ let here: Vec<&Rect> = rules.iter().filter(|r| (r.center().x - x).abs() < 1e-6).collect();+ assert!(here.iter().all(|r| r.y1 <= top + 1e-9 || r.y0 >= bottom - 1e-9), "a rule cuts the heading {top}..{bottom}: {here:?}");+ assert!(here.iter().any(|r| r.y1 <= top + 1e-9), "rule above the heading at {x}: {here:?}");+ assert!(here.iter().any(|r| (r.y0 - bottom).abs() < 1e-9), "rule resumes below the heading at {x}: {here:?}");+ }+}++#[test]+fn justified_line_with_a_tab_justifies_the_text_after_its_last_tab() {+ // InDesign justifies only the text after a line's last (left) tab; tab stops stay aligned.+ let stop = |align| designcraft_doc::TabStop { position: 100.0, align, leader: String::new(), align_on: String::new() };+ let text = "Name\t42 and some words\u{2028}more";+ let x_of = |l: &Line, byte: usize| l.glyphs.iter().find(|g| g.byte == byte && g.len > 0).map(|g| g.x).unwrap();+ let left = ParaAttrs { align: Some(Align::LeftJustified), tabs: Some(vec![stop(TabAlign::Left)]), ..Default::default() };+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), left.clone());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = all_lines(&cs)[0];+ assert!((l.end_x - l.x1).abs() < 0.6, "line with a left tab ends at {} not {}", l.end_x, l.x1);+ assert!((x_of(l, 5) - 100.0).abs() < 0.5, "text after the tab starts at the stop: {}", x_of(l, 5));+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs { align: Some(Align::Left), ..left });+ let ragged = compose_story(&d, sid, &ComposeOptions::default());+ let r = all_lines(&ragged)[0];+ for byte in 0..4 {+ assert!((x_of(l, byte) - x_of(r, byte)).abs() < 1e-6, "text before the tab keeps its natural position");+ }++ // After a right tab the line stays as set.+ let right = ParaAttrs { align: Some(Align::LeftJustified), tabs: Some(vec![stop(TabAlign::Right)]), ..Default::default() };+ let (d, sid, _) = doc_with("Name\t42\u{2028}more", Rect::new(0.0, 0.0, 300.0, 100.0), right);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = all_lines(&cs)[0];+ assert!((l.end_x - 100.0).abs() < 0.5, "right-tab line ends at its stop: {}", l.end_x);++ // A footnote's number and tab separator: its first line is justified like the others.+ let (mut d, sid, fid) = doc_with("Body text.", Rect::new(0.0, 0.0, 200.0, 400.0), ParaAttrs::default());+ let note = ParaFormat { para: ParaAttrs { align: Some(Align::LeftJustified), ..Default::default() }, ..Default::default() };+ d.story_mut(sid).unwrap().insert_note(4, LOREM, note);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let n = &cs.frame(fid).unwrap().notes[0];+ let lines = all_lines(&n.text);+ assert!(lines.len() > 2);+ for l in &lines[..lines.len() - 1] {+ assert!((l.end_x - l.x1).abs() < 0.6, "footnote line ends at {} not {}", l.end_x, l.x1);+ }+ assert!((x_of(lines[0], 0) - 36.0).abs() < 0.5, "note text starts at the default tab stop: {}", x_of(lines[0], 0));+}++#[test]+fn mojikumi_justification_after_a_tab_keeps_the_text_before_it() {+ // Justification (mojikumi included) adjusts only the text after a line's last tab.+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};+ let stop = designcraft_doc::TabStop { position: 100.0, align: TabAlign::Left, leader: String::new(), align_on: String::new() };+ let compose = |align| {+ let para =+ ParaAttrs { align: Some(align), mojikumi: Some("MojikumiTable/Elastic".into()), tabs: Some(vec![stop.clone()]), ..Default::default() };+ let (mut d, sid, _) = doc_with("A1A1\tA1A1", Rect::new(0.0, 0.0, 300.0, 100.0), para);+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {+ name: "Elastic".into(),+ based_on: "SimpChineseDefault".into(),+ overrides: vec![MojikumiAki {+ target_class: 18,+ side_class: 25,+ after: true,+ minimum: 0.0,+ desired: 0.0,+ maximum: 5.0,+ priority: 1,+ ..Default::default()+ }],+ });+ compose_story(&d, sid, &ComposeOptions::default())+ };+ let justified = compose(Align::FullyJustified);+ let ragged = compose(Align::Left);+ let (l, r) = (all_lines(&justified)[0], all_lines(&ragged)[0]);+ assert!(l.end_x > r.end_x + 1.0, "the text after the tab stretches: {} vs {}", l.end_x, r.end_x);+ let x_of = |l: &Line, byte: usize| l.glyphs.iter().find(|g| g.byte == byte && g.len > 0).map(|g| g.x).unwrap();+ for byte in 0..5 {+ assert!((x_of(l, byte) - x_of(r, byte)).abs() < 1e-6, "byte {byte} before the tab moved: {} vs {}", x_of(l, byte), x_of(r, byte));+ }+}++#[test]+fn list_first_line_wraps_at_the_column_edge_after_its_label() {+ use designcraft_doc::{ListType, TabStop};+ // A hanging indent (left 18, first line −18): the label sits at the column start, a tab+ // after it reaches the left indent (an implicit stop when no explicit stop comes first), and+ // the first line wraps at the same right edge as the others.+ let right_edge = |l: &Line, source: &str| {+ let space = |g: &&PlacedGlyph| g.len > 0 && source.get(g.byte..).and_then(|s| s.chars().next()).is_some_and(char::is_whitespace);+ l.glyphs.iter().filter(|g| g.visible && !space(g)).map(|g| g.x + g.adv).fold(0.0, f64::max)+ };+ let text_start = |l: &Line| l.glyphs.iter().find(|g| g.len > 0 && g.visible).map_or(f64::NAN, |g| g.x);+ let stop = |position: f64| TabStop { position, align: TabAlign::Left, leader: String::new(), align_on: String::new() };+ let text = format!("{LOREM}\n{LOREM}");+ // (list, separator, explicit tab stops, where line 0's text starts past the column start:+ // None = right after the label, wherever that is).+ let cases = [+ (ListType::Bullets, "\t", None, Some(18.0)),+ (ListType::Numbers, "\t", None, Some(18.0)),+ (ListType::Numbers, "\t", Some(vec![stop(12.0)]), Some(12.0)),+ (ListType::Numbers, "\t", Some(vec![stop(30.0)]), Some(18.0)),+ (ListType::Bullets, " ", None, None),+ (ListType::Numbers, "\u{2003}", None, None),+ ];+ // Justified too: only the text after the tab stretches (#284).+ for (align, (list, sep, tabs, first_at)) in [Align::Left, Align::LeftJustified].into_iter().flat_map(|a| cases.clone().map(|c| (a, c))) {+ let para = ParaAttrs {+ align: Some(align),+ list_type: Some(list),+ list_separator: Some(sep.into()),+ left_indent: Some(18.0),+ first_line_indent: Some(-18.0),+ tabs: tabs.clone(),+ ..Default::default()+ };+ let (d, sid, _) = doc_with(&text, Rect::new(36.0, 36.0, 300.0, 400.0), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let col = cs.frames[0].columns[0];+ let lines = &cs.frames[0].lines;+ let what = format!("{align:?} {list:?} {sep:?} {tabs:?}");+ assert!(lines.len() >= 6, "{what}: {} lines", lines.len());+ for (i, l) in lines.iter().enumerate() {+ let right = right_edge(l, &text);+ assert!(right <= col.x1 + 0.01, "{what}: line {i} ends at {right}, past the column's {}", col.x1);+ let start = text_start(l) - col.x0;+ if !l.first_in_para {+ assert!((start - 18.0).abs() < 0.01, "{what}: line {i} text starts at {start}, not the left indent");+ } else if let Some(at) = first_at {+ assert!((start - at).abs() < 0.01, "{what}: line {i} text starts at {start}, not {at}");+ } else {+ assert!(start > 0.0, "{what}: line {i} text starts at {start}");+ }+ if l.first_in_para {+ assert!(l.glyphs.first().is_some_and(|g| g.len == 0 && (g.x - col.x0).abs() < 0.01), "{what}: the label leads line {i}");+ }+ }+ }+}++/// Lines of `text` set in a frame `width` wide, with `tracking` on every character.+fn tracked_lines(text: &str, width: f64, para: ParaAttrs, tracking: f64) -> Vec<Line> {+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, width, 4000.0), para);+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.tracking = Some(tracking));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset(), "overset at width {width}");+ all_lines(&cs).into_iter().cloned().collect()+}++#[test]+fn a_word_longer_than_the_line_breaks_at_the_column_edge() {+ use designcraft_doc::Composer;let word = "n".repeat(60);let long = format!("Then {word} and on");for tracking in [0.0, 740.0] {