DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #282 (a33e597): Lists: the first line after a bullet or number wraps at the column edge
aiongg26a6b61c2acd
diff --cc crates/compose/src/lib.rsindex fae985652,92adf47a8..e9fa9ac45--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -930,20 -752,8 +930,20 @@@ fn compose_with_db(doc: &Document, stor// Where each line starts relative to the tab origin, as `layout_line` places it.let tab = |j: usize, x: f64, i: usize| {let x0 = slots.get(j).map_or(col.x0, |s| s.0);- let ind = pp.left_indent + if line_no + j == 0 { pp.first_line_indent } else { 0.0 };+ let ind = pp.left_indent+ + match &drop_cap {+ // Beside a drop cap: at its start-side indent (the right side in RTL).+ Some(dc) if line_no + j < dc.lines && col_first_line == 0 => {+ if rtl {+ 0.0+ } else {+ dc.indent()+ }+ }+ _ if line_no + j == 0 => pp.first_line_indent,+ _ => 0.0,+ };- tab_advance(&pp.tabs, x0 + ind + x - col.x0, rest.get(i + 1..).unwrap_or_default()).0+ tab_advance(&pp.tabs, pp.left_indent, x0 + ind + x - col.x0, rest.get(i + 1..).unwrap_or_default()).0};breaker::greedy(rest, rest_h, &spacing, &width, &tab)} else if pp.balance_ragged && !spacing.justify {@@@ -2249,11 -1606,9 +2254,11 @@@ fn layout_linelet mut x = 0.0;let mut i = 0;let mut leaders: Vec<(usize, String)> = Vec::new();+ // The line's last tab and whether it is a left tab (only text after a left tab justifies).+ let mut last_tab: Option<(usize, bool)> = None;while i < line.len() {if line[i].ch == '\t' {- let (w, stop) = tab_advance(&pp.tabs, x0 + x - tab_origin, line.get(i + 1..).unwrap_or_default());+ let (w, stop) = tab_advance(&pp.tabs, pp.left_indent, x0 + x - tab_origin, line.get(i + 1..).unwrap_or_default());if let Some(t) = stop&& !t.leader.is_empty(){diff --cc crates/compose/src/tests.rsindex 62aafe760,ee1227e40..9e89480f6--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -3183,874 -1918,58 +3183,930 @@@ fn vertical_lines_fit_the_em_box()}}+/// 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);+ }+}++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),+ ];+ for (list, sep, tabs, first_at) in cases {+ let para = ParaAttrs {+ 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!("{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}");+ }+ }+ }+ }