Skip to content

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

Merge fix/span-columns-flow: Text: text after a paragraph that spans columns flows below it

aiongg70edc2399fa8
diff --cc crates/compose/src/lib.rs
index 1bd4b2c59,78228f214..a8e40ec55
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@@ -754,23 -723,21 +790,28 @@@ fn compose_with_db(doc: &Document, stor
);
bidi::resolve_mirroring(&mut glyphs, &bidi_info);
apply_desired_spacing(&mut glyphs, &pp);
+ mojikumi::apply(&mut glyphs, &doc.styles, &pp.mojikumi);
let hyph_after = hyphenation_points(&story.text, &glyphs, &pp, &hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), &base_chars));
let base_size = base_chars.size;
- let base_leading = match base_chars.leading {
- designcraft_doc::Leading::Auto => base_size * pp.auto_leading,
+ let spacing = spacing_for(&pp, base_size);
+ // An empty paragraph takes its height from its paragraph mark's character format.
+ let mark_chars = if glyphs.is_empty() {
+ std::borrow::Cow::Owned(doc.styles.resolve_char(&base_chars, story.char_format_of(prange.start)))
+ } else {
+ std::borrow::Cow::Borrowed(&base_chars)
+ };
+ let mark_leading = match mark_chars.leading {
+ designcraft_doc::Leading::Auto => mark_chars.size * pp.auto_leading,
designcraft_doc::Leading::Points(v) => v,
};
- let spacing = spacing_for(&pp, base_size);
+ // A paragraph set across the columns moves on to the next frame where others move on to
+ // the next column.
+ let spanning = matches!(pp.span_columns, SpanColumns::Span(n) if n != 1);
+ span_paras[pi] = spanning;
+ let next_column = |cur: &mut Cursor| if spanning { cur.next_frame() } else { cur.next_column(&cols) };
// Paragraph start options.
if force_col[pi] {
- cur.next_column(&cols);
+ next_column(&mut cur);
}
if cur.last_baseline.is_some() {
match pp.start_paragraph {
@@@ -791,44 -799,30 +873,45 @@@
let mut col_first_line = 0usize;
let has_tabs = glyphs.iter().any(|g| g.ch == '\t');
let mut first_line_rect: Option<(usize, f64, f64, f64)> = None; // frame, baseline, ascent, x-span
+ let rtl = pp.direction == designcraft_doc::TextDirection::RightToLeft;
+ // The drop cap's line (frame, index) and the baseline it sits on, once that line is set.
+ let mut drop_line: Option<(usize, usize)> = None;
+ let mut drop_baseline: Option<f64> = None;
loop {
if cur.fi >= frames.len() {
+ if let Some(j) = trial_failed(&mut trial, &mut limits, balance_runs < balance_budget) {
+ balance_runs += 1;
+ rewind(j, &snaps, &note_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap);
+ pi = j;
+ continue 'paras;
+ }
out.overset_at = Some(glyphs.get(g0).map(|g| g.byte).unwrap_or(prange.start));
// The part of the paragraph that fits keeps its shading and border.
para_box_decos(&mut out, pi, &pp);
break 'paras;
}
let f = &frames[cur.fi];
- let col = cols[cur.fi][cur.col.min(cols[cur.fi].len() - 1)];
- let col = match pp.span_columns {
- SpanColumns::Span(n) if cur.col == 0 => {
- let n = if n == 0 { cols[cur.fi].len() } else { (n as usize).min(cols[cur.fi].len()) };
- let other = cols[cur.fi][n - 1];
- Rect::new(col.x0.min(other.x0), col.y0, col.x1.max(other.x1), col.y1)
- }
- _ => col,
- };
+ let base = cols[cur.fi][cur.col.min(cols[cur.fi].len() - 1)];
+ let col = cur.clip(base);
+ // A spanning paragraph isn't held to the balanced bottom of the columns above it.
+ let col = if spanning { span_rect(&cols[cur.fi], Rect::new(col.x0, col.y0, col.x1, base.y1), pp.span_columns) } else { col };
// Estimate slots for the breaker with the paragraph's base leading.
- let est_first = cur.next_baseline(f, col, base_leading, base_chars.size * 0.75, &pp);
- let slots = estimate_slots(f, col, est_first, base_leading, base_chars.size, &glyphs[g0..], &pp, line_no);
+ let est_asc = base_chars.size * 0.75;
+ let est_tops = Tops { typo_ascent: est_asc, cap: est_asc * 0.72, xh: est_asc * 0.5 };
+ let est_first = cur.next_baseline(f, col, base_leading, est_asc, est_tops, &pp);
+ let est_jump = cur.jump(f, base_leading, est_asc, est_tops);
+ let slots = estimate_slots(f, col, est_first, est_jump, base_leading, base_chars.size, &glyphs[g0..], &pp, line_no);
let width = |j: usize| -> f64 {
let (x0, x1) = slots.get(j).copied().unwrap_or((col.x0, col.x1));
- let ind = pp.left_indent + pp.right_indent + if line_no + j == 0 { pp.first_line_indent } else { 0.0 };
+ // Beside the drop cap (in the column the paragraph starts in), its width; else the
+ // first-line indent.
+ let ind = pp.left_indent
+ + pp.right_indent
+ + match &drop_cap {
+ Some(dc) if line_no + j < dc.lines && col_first_line == 0 => dc.indent(),
+ _ if line_no + j == 0 => pp.first_line_indent,
+ _ => 0.0,
+ };
(x1 - x0 - ind).max(1.0)
};
let rest = &glyphs[g0..];
@@@ -1612,51 -1588,50 +1829,76 @@@ impl Cursor
fn next_frame(&mut self) {
self.fi += 1;
self.col = 0;
- self.last_baseline = None;
- self.pending = 0.0;
+ self.band = Band { para: self.pi, ..Band::default() };
+ self.resume();
+ }
+ /// Start the current column at the top of the band.
+ fn resume(&mut self) {
+ match self.band.above {
+ Some(a) => {
+ self.last_baseline = Some(a.baseline);
+ self.last_descent = a.descent;
+ self.last_reference = a.reference;
+ self.pending = a.pending;
+ }
+ None => {
+ self.last_baseline = None;
+ self.pending = 0.0;
+ }
+ }
+ }
+ fn band_key(&self) -> BandKey {
+ (self.fi, self.band.para)
+ }
+ /// Column `col` of the current frame limited to the band: below the spanning paragraph above
+ /// it and, while balancing, above the trial bottom.
+ fn clip(&self, col: Rect) -> Rect {
+ let y0 = self.band.above.map_or(col.y0, |a| a.top.max(col.y0).min(col.y1.max(col.y0)));
+ let y1 = limit_of(&self.limits, self.band_key()).map_or(col.y1, |b| b.min(col.y1).max(y0));
+ Rect::new(col.x0, y0, col.x1, y1)
}
- /// Baseline for the next line with leading `lead` and ascent `asc`.
- fn next_baseline(&self, f: &FrameSpec, col: Rect, lead: f64, asc: f64, _pp: &ParaProps) -> f64 {
+ /// Baseline for the next line with leading `lead`, ascent `asc` and first baseline heights
+ /// `tops`.
+ fn next_baseline(&self, f: &FrameSpec, col: Rect, lead: f64, asc: f64, tops: Tops, _pp: &ParaProps) -> f64 {
match self.last_baseline {
Some(b) => b + lead + self.pending,
- None => {
- let off = match f.opts.first_baseline {
- FirstBaseline::Ascent => asc,
- FirstBaseline::CapHeight => asc * 0.72,
- FirstBaseline::XHeight => asc * 0.5,
- FirstBaseline::Leading => lead,
- FirstBaseline::Fixed => 0.0,
- };
- col.y0 + off.max(f.opts.first_baseline_min)
- }
+ None => col.y0 + first_baseline_offset(f, lead, asc, tops),
}
}
+ /// How the next line clears a Jump Object wrap: by whole leadings below the line above, or, first
+ /// in its column, as at the top of a frame whose top is the wrap bottom.
+ fn jump(&self, f: &FrameSpec, lead: f64, asc: f64, tops: Tops) -> Jump {
+ match self.last_baseline {
+ Some(_) => Jump { top: lead, step: lead },
+ None => Jump { top: first_baseline_offset(f, lead, asc, tops), step: 0.0 },
+ }
+ }
+}
+
+/// The frame's first baseline offset below the top of a column, for a line with leading `lead`,
+/// ascent `asc` and first baseline heights `tops`.
+fn first_baseline_offset(f: &FrameSpec, lead: f64, asc: f64, tops: Tops) -> f64 {
+ let off = match f.opts.first_baseline {
+ // Vertical frames measure from the ascent.
+ FirstBaseline::Ascent if f.vertical => asc,
+ FirstBaseline::CapHeight if f.vertical => asc * 0.72,
+ FirstBaseline::XHeight if f.vertical => asc * 0.5,
+ FirstBaseline::Ascent => tops.typo_ascent,
+ FirstBaseline::CapHeight => tops.cap,
+ FirstBaseline::XHeight => tops.xh,
+ FirstBaseline::Leading => lead,
+ FirstBaseline::Fixed => 0.0,
+ };
+ off.max(f.opts.first_baseline_min)
+}
+
+/// A line's tallest typographic ascender, cap height and x height above its baseline: the
+/// first baseline offsets.
+#[derive(Clone, Copy, Default)]
+struct Tops {
+ typo_ascent: f64,
+ cap: f64,
+ xh: f64,
}
/// Em box relative to the baseline. Font ascender/descender proportions locate it;
diff --cc crates/compose/src/tests.rs
index 1d21c3330,349cbebea..f4dd141f3
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@@ -3082,610 -1878,158 +3082,766 @@@ 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 = &note.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 = &note.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(&paras.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));
+ }