Skip to content

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

Merge mojikumi-base: CJK: mojikumi tables based on Nothing and the one-em line-end set apply their rules

aionggc94d7ce8c893
diff --cc crates/compose/src/tests.rs
index cce32d33e,3df0cfeb4..802f3859b
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@@ -4492,1235 -2165,68 +4492,1258 @@@ fn mojikumi_kinsoku_push_in_and_push_ou
}
#[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");
+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);
+ }
+}
+
++#[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] {
+ // Natural advances, from one unbroken line.
+ let natural: HashMap<usize, f64> =
+ tracked_lines(&long, 1e5, ParaAttrs::default(), tracking)[0].glyphs.iter().map(|g| (g.byte, g.adv)).collect();
+ for composer in [Composer::Paragraph, Composer::SingleLine] {
+ for align in [Align::Left, Align::LeftJustified] {
+ let para = ParaAttrs { composer: Some(composer), align: Some(align), hyphenate: Some(false), ..Default::default() };
+ let lines = tracked_lines(&long, 72.0, para, tracking);
+ let what = format!("{composer:?} {align:?} tracking {tracking}");
+ assert!(lines.len() >= 4, "{what}: {} lines", lines.len());
+ for l in &lines {
+ let ink: Vec<_> = l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).collect();
+ let right = ink.iter().map(|g| g.x + g.adv.min(natural[&g.byte])).fold(l.x0, f64::max);
+ assert!(l.end_x <= l.x1 + 0.02 && right <= l.x1 + 0.02, "{what}: line {:?} ends at {} past {}", l.range, l.end_x, l.x1);
+ for w in ink.windows(2) {
+ assert!(w[1].x >= w[0].x + natural[&w[0].byte] - 1e-6, "{what}: glyphs overlap at {}", w[1].byte);
+ }
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn a_line_that_exactly_fills_the_measure_fits() {
+ use designcraft_doc::Composer;
+ let text = "#knowyourplastic";
+ let one = &tracked_lines(text, 1e5, ParaAttrs::default(), 0.0)[0];
+ // The measure a rounding error short of the natural width.
+ let width = one.end_x - one.x0 - 0.005;
+ for composer in [Composer::Paragraph, Composer::SingleLine] {
+ for align in [Align::Left, Align::LeftJustified] {
+ let para = ParaAttrs { composer: Some(composer), align: Some(align), ..Default::default() };
+ let lines = tracked_lines(text, width, para, 0.0);
+ assert_eq!(lines.len(), 1, "{composer:?} {align:?}: {:?}", lines.iter().map(|l| l.range.clone()).collect::<Vec<_>>());
+ }
+ }
+}
+
+// ---------- split columns ----------
+
+/// A story of a body paragraph, `split` paragraphs in split columns and `after` body paragraphs.
+/// Returns the index of the first split paragraph.
+fn split_doc(split: usize, after: usize, rect: Rect, cfg: (u32, f64, f64)) -> (Document, StoryId, ItemId, usize) {
+ let mut paras: Vec<&str> = vec![LOREM; 1 + split + after];
+ paras[0] = "An introduction set at the full measure of the column, before the split block.";
+ let (mut d, sid, fid) = doc_with(&paras.join("\n"), rect, ParaAttrs::default());
+ let st = d.story_mut(sid).unwrap();
+ for p in &mut st.paras[1..=split] {
+ p.para.span_columns = Some(SpanColumns::Split(cfg.0));
+ p.para.split_inside_gutter = Some(cfg.1);
+ p.para.split_outside_gutter = Some(cfg.2);
+ }
+ (d, sid, fid, 1)
+}
+
+/// The sub-columns of `col`: (x0, x1) of each.
+fn sub_columns(col: Rect, (n, inside, outside): (u32, f64, f64)) -> Vec<(f64, f64)> {
+ let w = (col.width() - 2.0 * outside - inside * (n - 1) as f64) / n as f64;
+ (0..n).map(|k| col.x0 + outside + k as f64 * (w + inside)).map(|x| (x, x + w)).collect()
+}
+
+/// The split paragraphs' lines, by sub-column.
+fn split_lines<'a>(ft: &'a FrameText, paras: std::ops::Range<usize>, subs: &[(f64, f64)]) -> Vec<Vec<&'a Line>> {
+ let mut by_sub = vec![Vec::new(); subs.len()];
+ for l in ft.lines.iter().filter(|l| paras.contains(&l.para)) {
+ let k = subs.iter().position(|&(x0, x1)| (l.x0 - x0).abs() < 1e-6 && (l.x1 - x1).abs() < 1e-6);
+ let k = k.unwrap_or_else(|| panic!("line of para {} at {}..{} is in no sub-column of {subs:?}", l.para, l.x0, l.x1));
+ by_sub[k].push(l);
+ }
+ by_sub
+}
+
+#[test]
+fn split_paragraphs_are_set_in_balanced_sub_columns() {
+ for cfg in [(2, 12.0, 10.0), (3, 6.0, 0.0)] {
+ let (d, sid, _, s) = split_doc(2, 1, Rect::new(0.0, 0.0, 400.0, 700.0), cfg);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset());
+ let ft = &cs.frames[0];
+ assert_no_overlap(ft);
+ let by_sub = split_lines(ft, s..s + 2, &sub_columns(ft.columns[0], cfg));
+ let counts: Vec<usize> = by_sub.iter().map(Vec::len).collect();
+ assert!(counts.iter().all(|&n| n > 0), "{cfg:?}: {counts:?}");
+ assert!(counts.iter().max().unwrap() - counts.iter().min().unwrap() <= 1, "{cfg:?}: balanced {counts:?}");
+ // Every sub-column starts on the same baseline, below the paragraph before the block.
+ let firsts: Vec<f64> = by_sub.iter().map(|v| v[0].baseline).collect();
+ assert!(firsts.iter().all(|b| (b - firsts[0]).abs() < 1e-6), "{cfg:?}: {firsts:?}");
+ let intro = ft.lines.iter().filter(|l| l.para == 0).map(|l| line_box(l).1).fold(f64::NEG_INFINITY, f64::max);
+ assert!(firsts[0] > intro && firsts[0] < intro + 20.0, "{cfg:?}: block at {} after {intro}", firsts[0]);
+ // The text after the block continues at the full measure below its deepest sub-column.
+ let bottom = by_sub.iter().flatten().map(|l| line_box(l).1).fold(f64::NEG_INFINITY, f64::max);
+ let next = ft.lines.iter().find(|l| l.para == s + 2).unwrap();
+ assert!(line_box(next).0 >= bottom - 0.5 && line_box(next).0 < bottom + 20.0, "{cfg:?}: {} after {bottom}", line_box(next).0);
+ assert!((next.x0 - ft.columns[0].x0).abs() < 1e-6 && (next.x1 - ft.columns[0].x1).abs() < 1e-6);
+ }
+}
+
+#[test]
+fn split_block_in_the_second_column_and_at_the_story_end() {
+ let cfg = (2, 12.0, 0.0);
+ let (mut d, sid, fid, s) = split_doc(3, 0, Rect::new(0.0, 0.0, 540.0, 400.0), cfg);
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;
+ d.story_mut(sid).unwrap().paras[s].para.start_paragraph = Some(StartParagraph::NextColumn);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset());
+ let ft = &cs.frames[0];
+ assert_no_overlap(ft);
+ assert!(ft.lines.iter().filter(|l| l.para >= s).all(|l| l.column == 1));
+ let by_sub = split_lines(ft, s..s + 3, &sub_columns(ft.columns[1], cfg));
+ // Nothing follows the block: it fills its first sub-column to the bottom of the frame, then
+ // the next.
+ let (a, b) = (&by_sub[0], &by_sub[1]);
+ assert!(!a.is_empty() && !b.is_empty() && a.len() > b.len() + 1, "{} and {} lines", a.len(), b.len());
+ let low = a.last().unwrap();
+ assert!(low.baseline + low.descent > 400.0 - low.leading, "the first sub-column ends at {}", low.baseline);
+ assert!((a[0].baseline - b[0].baseline).abs() < 1e-6);
+}
+
+#[test]
+fn split_block_flows_into_the_next_column() {
+ let cfg = (2, 12.0, 0.0);
+ let (mut d, sid, fid, s) = split_doc(6, 1, Rect::new(0.0, 0.0, 540.0, 200.0), cfg);
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let ft = &cs.frames[0];
+ assert_no_overlap(ft);
+ for c in 0..2 {
+ let in_col: Vec<&Line> = ft.lines.iter().filter(|l| l.column == c as u32).collect();
+ let lines: Vec<&Line> = in_col.iter().copied().filter(|l| (s..s + 6).contains(&l.para)).collect();
+ let subs = sub_columns(ft.columns[c], cfg);
+ assert!(subs.iter().all(|&(x0, x1)| lines.iter().any(|l| (l.x0 - x0).abs() < 1e-6 && (l.x1 - x1).abs() < 1e-6)), "column {c}");
+ }
+ // The block continues at the top of the second column.
+ let top = ft.lines.iter().find(|l| l.column == 1).unwrap();
+ assert!((s..s + 6).contains(&top.para) && top.baseline < 20.0);
+}
+
+/// Each paragraph's list label as text: its label glyphs (laid before the paragraph's own text)
+/// matched back to characters of the label font; tabs and other invisible glyphs are skipped.
+fn list_labels(cs: &ComposedStory, alphabet: &str) -> Vec<String> {
+ all_lines(cs)
+ .iter()
+ .filter(|l| l.first_in_para)
+ .map(|l| {
+ l.glyphs
+ .iter()
+ .take_while(|g| g.len == 0)
+ .filter(|g| g.visible)
+ .map(|g| alphabet.chars().find(|c| g.face.glyph_for(*c) == g.gid).unwrap_or('?'))
+ .collect()
+ })
+ .collect()
+}
+
+const LABEL_CHARS: &str = "0123456789ABCDIVXabcdivx.\u{2022} Tabel";
+
+fn numbered(style: designcraft_doc::NumberStyle, expression: &str) -> ParaAttrs {
+ ParaAttrs {
+ list_type: Some(designcraft_doc::ListType::Numbers),
+ number_style: Some(style),
+ number_expression: Some(expression.into()),
+ ..Default::default()
+ }
+}
+
+#[test]
+fn numbered_lists_follow_their_format_and_expression() {
+ use designcraft_doc::NumberStyle as N;
+ let cases: [(N, &str, [&str; 3]); 4] = [
+ (N::UpperLetters, "^#.^t", ["A.", "B.", "C."]),
+ (N::LowerRoman, "^#.^t", ["i.", "ii.", "iii."]),
+ (N::ArabicThreeDigits, "^#.^t", ["001.", "002.", "003."]),
+ (N::Arabic, "Tabel ^#^t", ["Tabel 1", "Tabel 2", "Tabel 3"]),
+ ];
+ for (style, expression, want) in cases {
+ let (d, sid, _) = doc_with("One\nTwo\nThree", Rect::new(0.0, 0.0, 300.0, 300.0), numbered(style, expression));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert_eq!(list_labels(&cs, LABEL_CHARS), want, "{style:?} {expression}");
+ }
+}
+
+#[test]
+fn numbering_from_the_largest_start_number_does_not_overflow() {
+ let (mut d, sid, _) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 300.0), numbered(designcraft_doc::NumberStyle::Arabic, "^#."));
+ d.story_mut(sid).unwrap().paras[0].para.start_at = Some(Some(u32::MAX));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let max = format!("{}.", u32::MAX);
+ assert_eq!(list_labels(&cs, LABEL_CHARS), [max.clone(), max]);
+}
+
+#[test]
+fn empty_paragraphs_get_no_bullet_or_number() {
+ let bullets = ParaAttrs { list_type: Some(designcraft_doc::ListType::Bullets), ..Default::default() };
+ let (d, sid, _) = doc_with("One\n\nTwo\n", Rect::new(0.0, 0.0, 300.0, 300.0), bullets);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["\u{2022}", "", "\u{2022}", ""]);
+ // An empty paragraph doesn't use up a number, in a story's own list or a named one.
+ for name in ["", "Steps"] {
+ let attrs = ParaAttrs { list_name: Some(name.into()), ..numbered(designcraft_doc::NumberStyle::Arabic, "^#.^t") };
+ let (mut d, sid, _) = doc_with("One\n\nTwo\n", Rect::new(0.0, 0.0, 300.0, 300.0), attrs);
+ if !name.is_empty() {
+ d.settings.lists.push(designcraft_doc::NumberedList { name: name.into(), continue_across_stories: false });
+ }
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["1.", "", "2.", ""], "list `{name}`");
+ }
+}
+
+#[test]
+fn tight_word_spacing_does_not_isolate_a_word() {
+ // A narrow word-spacing range (100–105%) with some letter spacing and glyph scaling, no
+ // hyphenation: lines that need more stretch must open their word spaces, not letter-space a
+ // single word across the measure.
+ let para = ParaAttrs {
+ align: Some(Align::LeftJustified),
+ hyphenate: Some(false),
+ first_line_indent: Some(9.0),
+ word_space_min: Some(1.0),
+ word_space_desired: Some(1.03),
+ word_space_max: Some(1.05),
+ letter_space_min: Some(-0.05),
+ letter_space_max: Some(0.05),
+ glyph_scale_min: Some(0.99),
+ glyph_scale_max: Some(1.01),
+ ..Default::default()
+ };
+ // Short words: any two fit on a line together.
+ let text = CORPUS[..2].join(" ");
+ for w in (200..=320).step_by(5) {
+ let (d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, w as f64, 20000.0), para.clone());
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ for l in &lines[..lines.len() - 1] {
+ let words = text[l.range.clone()].split_whitespace().count();
+ assert!(words > 1, "width {w}: a single-word line {:?}", &text[l.range.clone()]);
+ }
+ }
+}
+
+#[test]
+fn fixed_width_spaces_do_not_stretch_on_justified_lines() {
+ // Long words in a narrow column: lines stretch past the maximum word spacing. Only the word
+ // spaces take that stretch; em, en and thin spaces keep their width.
+ let words = ["characteristically", "misunderstanding", "unquestionably", "responsibility", "administration", "photographer"];
+ let seps = [" ", "\u{2003}", " ", "\u{2002}", " ", "\u{2009}"];
+ let text: String = (0..60).map(|i| format!("{}{}", words[i % words.len()], seps[i % seps.len()])).collect();
+ let text = text.trim_end().to_string();
+ let fixed = |c: char| matches!(c, '\u{2003}' | '\u{2002}' | '\u{2009}');
+ // (character, advance) of each fixed space, per line, and whether the line ends the paragraph.
+ let spaces = |align: Align, w: f64| -> Vec<(Vec<(char, f64)>, bool)> {
+ let para = ParaAttrs { align: Some(align), hyphenate: Some(false), ..Default::default() };
+ let (d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, w, 20000.0), para);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ all_lines(&cs)
+ .iter()
+ .map(|l| {
+ let found = l.glyphs.iter().filter_map(|g| text[g.byte..].chars().next().filter(|&c| fixed(c)).map(|c| (c, g.adv))).collect();
+ (found, l.last_in_para)
+ })
+ .collect()
+ };
+ let mut checked = 0;
+ for w in [190.0, 230.0, 270.0] {
+ let natural: Vec<(char, f64)> = spaces(Align::Left, w).into_iter().flat_map(|l| l.0).collect();
+ for (found, last) in spaces(Align::LeftJustified, w) {
+ if last {
+ continue;
+ }
+ for (c, a) in found {
+ let Some(&(_, n)) = natural.iter().find(|x| x.0 == c) else { continue };
+ assert!((a - n).abs() < 1e-6, "width {w}: U+{:04X} is {a:.2} wide, not {n:.2}", c as u32);
+ checked += 1;
+ }
+ }
+ }
+ assert!(checked > 5, "{checked} fixed spaces on justified lines");
+}
+
+#[test]
+fn grep_style_in_the_documents_dialect_keeps_short_words_with_the_next() {
+ // `\l` (lowercase letter) and `\h` (horizontal space) aren't Rust regex syntax; the style used
+ // to be skipped silently.
+ let text = "Мы и он в доме и в саду, а она у окна и с книгой в руках у стола.";
+ let para = ParaAttrs {
+ align: Some(Align::Left),
+ grep_styles: Some(vec![designcraft_doc::GrepStyle { style: "nobreak".into(), pattern: r"\b\l{1,2}\h".into() }]),
+ ..Default::default()
+ };
+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 70.0, 1000.0), para);
+ let chars = designcraft_doc::CharAttrs { no_break: Some(true), ..Default::default() };
+ std::sync::Arc::make_mut(&mut d.styles).character.push(designcraft_doc::CharacterStyle {
+ name: "nobreak".into(),
+ based_on: None,
+ chars,
+ shortcut: String::new(),
+ });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ assert!(lines.len() > 3);
+ let short = |w: &str| w.chars().count() <= 2 && w.chars().all(char::is_lowercase);
+ for l in &lines[..lines.len() - 1] {
+ let last = text[l.range.clone()].split_whitespace().last().unwrap_or("");
+ assert!(!short(last), "line ends with a short word: {:?}", &text[l.range.clone()]);
+ }
+}
+
+// ---------- paragraph border and shading ----------
+
+fn bordered(text: &str, rect: Rect, para: ParaAttrs) -> ComposedStory {
+ let para = ParaAttrs { border_on: Some(true), border_weights: Some([1.0; 4]), ..para };
+ let (d, sid, _) = doc_with(text, rect, para);
+ compose_story(&d, sid, &ComposeOptions::default())
+}
+
+fn has_curves(bp: &designcraft_geom::BezPath) -> bool {
+ bp.elements().iter().any(|e| matches!(e, designcraft_geom::PathEl::CurveTo(..) | designcraft_geom::PathEl::QuadTo(..)))
+}
+
+#[test]
+fn rounded_border_corners_are_curves_and_dotted_borders_paint_their_gap_first() {
+ use designcraft_geom::corners::{Corner, CornerShape};
+ let rounded = [Corner { shape: CornerShape::Rounded, size: 6.0 }; 4];
+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs { border_corners: Some(rounded), ..Default::default() });
+ let paths: Vec<_> = cs.frames[0].decos.iter().filter_map(|dc| dc.path.as_ref()).collect();
+ assert_eq!(paths.len(), 1, "one stroked outline");
+ assert!(has_curves(paths[0]));
+ // Square corners: plain edges, no curves.
+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs::default());
+ assert!(cs.frames[0].decos.iter().all(|dc| dc.path.is_none()));
+ // A dotted border with a gap colour: the gap under the dots.
+ let dotted = ParaAttrs { border_type: Some(designcraft_doc::StrokeType::Dotted), border_gap_color: Some("[Paper]".into()), ..Default::default() };
+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), dotted);
+ let colors: Vec<&str> = cs.frames[0].decos.iter().filter(|dc| dc.path.is_some()).map(|dc| dc.color.as_str()).collect();
+ assert_eq!(colors, ["[Paper]", "[Black]"]);
+}
+
+/// The width of the widest border edge (the top and bottom edges span the box).
+fn border_width(cs: &ComposedStory) -> f64 {
+ cs.frames[0].decos.iter().filter(|dc| dc.color == "[Black]").map(|dc| dc.rect.width()).fold(0.0, f64::max)
+}
+
+#[test]
+fn a_text_width_border_is_narrower_than_a_column_width_one() {
+ let rect = Rect::new(0.0, 0.0, 300.0, 200.0);
+ let column = border_width(&bordered("Short", rect, ParaAttrs::default()));
+ let text = border_width(&bordered("Short", rect, ParaAttrs { border_width: Some(designcraft_doc::BoxWidth::Text), ..Default::default() }));
+ assert!((column - 302.0).abs() < 1e-6, "column and both side strokes: {column}");
+ assert!(text > 2.0 && text < 60.0, "text: {text}");
+}
+
+/// Edges of a plain border by frame column: (column, count).
+fn edges_per_column(cs: &ComposedStory) -> Vec<usize> {
+ let cols = &cs.frames[0].columns;
+ cols.iter()
+ .map(|c| {
+ cs.frames[0].decos.iter().filter(|dc| dc.color == "[Black]" && dc.rect.center().x > c.x0 - 2.0 && dc.rect.center().x < c.x1 + 2.0).count()
+ })
+ .collect()
+}
+
+#[test]
+fn a_split_paragraph_closes_its_border_in_each_column_only_when_set_to() {
+ let text = format!("{LOREM} {LOREM}");
+ let compose = |display: bool| {
+ let para = ParaAttrs { border_on: Some(true), border_weights: Some([1.0; 4]), border_display_if_splits: Some(display), ..Default::default() };
+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 400.0, 90.0), para);
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;
+ compose_story(&d, sid, &ComposeOptions::default())
+ };
+ let open = compose(false);
+ assert!(open.frames[0].lines.iter().any(|l| l.column == 1), "the paragraph reaches the second column");
+ // Open at the split: top and sides in the first column, sides and bottom in the second.
+ assert_eq!(edges_per_column(&open), [3, 3]);
+ assert_eq!(edges_per_column(&compose(true)), [4, 4]);
+}
+
+#[test]
+fn consecutive_paragraphs_with_the_same_border_share_one_box() {
+ let compose = |merge: bool| {
+ let para = ParaAttrs { space_after: Some(10.0), border_merge: Some(merge), ..Default::default() };
+ bordered("One\nTwo\nThree", Rect::new(0.0, 0.0, 300.0, 300.0), para)
+ };
+ let merged = compose(true);
+ let edges: Vec<Rect> = merged.frames[0].decos.iter().filter(|dc| dc.color == "[Black]").map(|dc| dc.rect).collect();
+ assert_eq!(edges.len(), 4, "one box: {edges:?}");
+ let lines = &merged.frames[0].lines;
+ let (first, last) = (&lines[0], &lines[lines.len() - 1]);
+ let left = edges.iter().find(|r| r.height() > r.width()).unwrap();
+ assert!((left.y0 - (first.baseline - first.ascent)).abs() < 1e-6 && (left.y1 - (last.baseline + last.descent)).abs() < 1e-6, "{left:?}");
+ assert_eq!(compose(false).frames[0].decos.iter().filter(|dc| dc.color == "[Black]").count(), 12, "a box each");
+}
+
+#[test]
+fn shading_clips_to_the_frame_and_can_stay_off_print() {
+ let para = ParaAttrs {
+ shading_on: Some(true),
+ shading_offsets: Some([50.0; 4]),
+ shading_clip: Some(true),
+ shading_nonprinting: Some(true),
+ ..Default::default()
+ };
+ let (d, sid, _) = doc_with("Shaded", Rect::new(0.0, 0.0, 300.0, 200.0), para);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let area = cs.frames[0].columns[0];
+ let shade = &cs.frames[0].decos[0];
+ assert!(shade.nonprinting);
+ assert!(shade.rect.x0 >= area.x0 - 1e-6 && shade.rect.y0 >= area.y0 - 1e-6 && shade.rect.x1 <= area.x1 + 1e-6, "{:?} in {area:?}", shade.rect);
+}
+
+// ---------- span space, bullets and numbering ----------
+
+#[test]
+fn space_before_and_after_a_span_moves_the_span_and_the_text_below() {
+ let at = |before: f64, after: f64| {
+ let (mut d, sid, _, h) = span_doc(1, 1, Rect::new(0.0, 0.0, 600.0, 800.0));
+ let p = &mut d.story_mut(sid).unwrap().paras[h].para;
+ p.span_space_before = Some(before);
+ p.span_space_after = Some(after);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let first = |pi: usize| cs.frames[0].lines.iter().find(|l| l.para == pi).map(|l| l.baseline).unwrap();
+ (first(h), first(h + 1))
+ };
+ let (span0, below0) = at(0.0, 0.0);
+ let (span1, below1) = at(24.0, 0.0);
+ assert!((span1 - span0 - 24.0).abs() < 0.01, "{span0} → {span1}");
+ assert!((below1 - below0 - 24.0).abs() < 0.01, "the text below moves with it");
+ let (span2, below2) = at(0.0, 18.0);
+ assert!((span2 - span0).abs() < 0.01 && (below2 - below0 - 18.0).abs() < 0.01, "{below0} → {below2}");
+}
+
+#[test]
+fn span_space_applies_only_where_the_paragraph_spans_columns() {
+ // Every paragraph spans with 12 pt span space after; the frame has `columns` columns.
+ let tops = |columns: u32, span: bool| {
+ let (mut d, sid, fid) = doc_with("One\nTwo\nThree", Rect::new(0.0, 0.0, 400.0, 400.0), ParaAttrs::default());
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = columns;
+ for p in &mut d.story_mut(sid).unwrap().paras {
+ if span {
+ p.para.span_columns = Some(SpanColumns::Span(0));
+ }
+ p.para.span_space_after = Some(12.0);
+ }
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ first_lines(&cs).iter().map(|l| l.baseline).collect::<Vec<_>>()
+ };
+ let plain = tops(1, false);
+ assert_eq!(plain.len(), 3);
+ assert_eq!(tops(1, true), plain, "a span in a one-column frame adds no space");
+ let spread = tops(3, true);
+ let gap = |v: &[f64], i: usize| v[i + 1] - v[i];
+ assert!((gap(&spread, 0) - gap(&plain, 0) - 12.0).abs() < 0.01, "{spread:?} vs {plain:?}");
+}
+
+/// The first line of each paragraph.
+fn first_lines(cs: &ComposedStory) -> Vec<&Line> {
+ all_lines(cs).into_iter().filter(|l| l.first_in_para).collect()
+}
+
+#[test]
+fn a_right_aligned_number_ends_at_the_line_start() {
+ use designcraft_doc::{ListAlign, ListType};
+ let compose = |align: ListAlign| {
+ let para = ParaAttrs {
+ list_type: Some(ListType::Numbers),
+ number_align: Some(align),
+ left_indent: Some(36.0),
+ first_line_indent: Some(-18.0),
+ ..Default::default()
+ };
+ let (d, sid, _) = doc_with("Item", Rect::new(0.0, 0.0, 300.0, 200.0), para);
+ compose_story(&d, sid, &ComposeOptions::default())
+ };
+ // The label "1.\t": its first two glyphs are the number and the full stop.
+ let cs = compose(ListAlign::Left);
+ let col = cs.frames[0].columns[0];
+ let l = first_lines(&cs)[0];
+ assert!((l.glyphs[0].x - (col.x0 + 18.0)).abs() < 0.01, "left: starts at the line start");
+ let text_x = l.glyphs.iter().find(|g| g.len > 0).unwrap().x;
+ let cs = compose(ListAlign::Right);
+ let l = first_lines(&cs)[0];
+ let end = l.glyphs[1].x + l.glyphs[1].adv;
+ assert!((end - (col.x0 + 18.0)).abs() < 0.01, "right: ends at the line start ({end})");
+ assert!((l.glyphs.iter().find(|g| g.len > 0).unwrap().x - text_x).abs() < 0.01, "the text stays at the tab stop");
+}
+
+#[test]
+fn level_two_numbering_restarts_after_level_one() {
+ let para = numbered(designcraft_doc::NumberStyle::Arabic, "^1.^#");
+ let (mut d, sid, _) = doc_with("A\nB\nC\nD\nE", Rect::new(0.0, 0.0, 300.0, 300.0), para);
+ for (p, level) in d.story_mut(sid).unwrap().paras.iter_mut().zip([1, 2, 2, 1, 2]) {
+ p.para.list_level = Some(level);
+ }
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ // `^1` is level 1's number, `^#` the paragraph's own level.
+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["1.1", "1.1", "1.2", "2.2", "2.1"]);
+ // Without the restart, level 2 carries on.
+ for p in &mut d.story_mut(sid).unwrap().paras {
+ p.para.restart_numbers = Some(false);
+ }
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["1.1", "1.1", "1.2", "2.2", "2.3"]);
+}
+
+#[test]
+fn the_tab_position_places_the_text_after_the_label() {
+ use designcraft_doc::ListType;
+ let compose = |tab: Option<f64>| {
+ let para = ParaAttrs { list_type: Some(ListType::Bullets), list_tab: Some(tab), ..Default::default() };
+ let (d, sid, _) = doc_with("Item", Rect::new(0.0, 0.0, 300.0, 200.0), para);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let col = cs.frames[0].columns[0];
+ first_lines(&cs)[0].glyphs.iter().find(|g| g.len > 0).unwrap().x - col.x0
+ };
+ assert!((compose(Some(50.0)) - 50.0).abs() < 0.01);
+ assert!((compose(None) - 36.0).abs() < 0.01, "the default tab stop");
+}
- 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()
- }],
+#[test]
+fn paragraph_mark_size_counts_in_its_line_auto_leading() {
+ let gaps = |mark_size: f64| {
+ let (mut d, sid, _) = doc_with("One\nTwo\nThree", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());
+ d.story_mut(sid).unwrap().format_chars(7..8, |f| f.over.size = Some(mark_size));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let b: Vec<f64> = all_lines(&cs).iter().map(|l| l.baseline).collect();
+ assert_eq!(b.len(), 3);
+ (b[1] - b[0], b[2] - b[1])
+ };
+ // A 12 pt line ending in a 14 pt return: 14 × 120% above it, the next line unchanged.
+ let (above, below) = gaps(14.0);
+ assert!((above - 16.8).abs() < 1e-6, "{above}");
+ assert!((below - 14.4).abs() < 1e-6, "{below}");
+ let (above, below) = gaps(12.0);
+ assert!((above - 14.4).abs() < 1e-6, "{above}");
+ assert!((below - 14.4).abs() < 1e-6, "{below}");
+}
+
+// Kenten settings, shatai, auto tate-chu-yoko, rotate roman, roman word break and grid settings.
+
+/// The centre of a placed glyph's ink, relative to its line's baseline.
+fn ink_centre(g: &PlacedGlyph) -> Point {
+ let r = designcraft_geom::Shape::bounding_box(&*FontDb::global().outline(&g.face, g.gid));
+ Point::new(g.x + (r.x0 + r.x1) / 2.0 * g.sx, g.y + (r.y0 + r.y1) / 2.0 * g.sy)
+}
+
+#[test]
+fn kenten_sit_above_or_below_at_their_size_and_distance() {
+ use designcraft_doc::cjk_settings::{KentenKind, KentenPosition};
+ 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();
+ let set = |d: &mut Document, position: KentenPosition| {
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {
+ f.over.kenten = Some(true);
+ f.over.kenten_kind = Some(KentenKind::BlackCircle);
+ f.over.kenten_size = Some(Some(8.0));
+ f.over.kenten_x_scale = Some(1.5);
+ f.over.kenten_distance = Some(2.0);
+ f.over.kenten_position = Some(position);
+ });
+ };
+ for position in [KentenPosition::AboveRight, KentenPosition::BelowLeft] {
+ set(&mut d, position);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let marks = &l.glyphs[plain..];
+ assert_eq!(marks.len(), 2, "one mark per character");
+ for (b, m) in l.glyphs[..plain].iter().zip(marks) {
+ // 8 pt, 150% wide, in a run style of its own.
+ assert!((m.sx - 8.0 / m.face.units_per_em() * 1.5).abs() < 1e-9 && (m.sy - 8.0 / m.face.units_per_em()).abs() < 1e-9);
+ assert_ne!(m.style, b.style);
+ assert_eq!(cs.styles[m.style as usize].size, 8.0);
+ let (top, bottom) = b.face.em_box();
+ let want_y = match position {
+ KentenPosition::AboveRight => b.y - top * b.sy - 2.0 - 4.0,
+ KentenPosition::BelowLeft => b.y - bottom * b.sy + 2.0 + 4.0,
+ };
+ let c = ink_centre(m);
+ assert!((c.y - want_y).abs() < 1e-6, "{position:?}: {} vs {want_y}", c.y);
+ assert!((c.x - (b.x + b.adv / 2.0)).abs() < 1e-6, "centred on its character");
+ }
+ }
+}
+
+#[test]
+fn kenten_colour_is_its_own_run_style() {
+ let (mut d, sid, _) = doc_with("AB", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {
+ f.over.kenten = Some(true);
+ f.over.kenten_fill = Some("[Registration]".into());
+ f.over.kenten_fill_tint = Some(Some(0.5));
});
- 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");
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let mark = l.glyphs.last().unwrap();
+ let st = &cs.styles[mark.style as usize];
+ assert_eq!((st.fill.as_str(), st.fill_tint), ("[Registration]", 0.5));
+ assert!(st.kenten_mark.is_none() && !st.underline);
+ assert_eq!(cs.styles[l.glyphs[0].style as usize].fill, "[Black]", "the text keeps its colour");
}
#[test]