Skip to content

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

Merge #589: (fix)Small frame wrap for overset small text boxes

aiongg4f16d883092d
diff --cc crates/compose/src/lib.rs
index 90cb4ebd5,5ab809649..113d5ef32
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@@ -602,11 -363,25 +602,19 @@@ pub fn frame_specs(doc: &Document, sid
if doc.layer(other.layer).is_some_and(|l| !l.visible) {
continue;
}
- let o = other.wrap.offsets;
- let b = other.bounds();
- let r = Rect::new(b.x0 - o[1], b.y0 - o[0], b.x1 + o[3], b.y1 + o[2]);
- let inner = inv.transform_rect_bbox(r);
- // Only objects that reach the frame wrap its text: one elsewhere on the spread
- // leaves it alone (a small frame beside it would otherwise lose its gaps to the
- // minimum gap width, see `free_slot`).
- let reach = inner.intersect(item.inner_bounds());
- if !(reach.width() > 0.0 && reach.height() > 0.0) {
- continue;
- }
- exclusions.push(Exclusion { rect: inner, mode: other.wrap.mode });
+ wrap_obstacles(other, Affine::IDENTITY, inv, item.id, &left, 0, &mut exclusions);
}
++ // Only objects that reach the frame's text area wrap its text: one elsewhere on the
++ // spread would otherwise cost a narrow column its room (the 1.5 em minimum segment of
++ // `free_slots` applies once an object cuts the column).
++ let a = item.text_area();
++ exclusions.retain(|e| {
++ let r = e.rect;
++ r.is_finite() && r.x0 < a.x1 && r.x1 > a.x0 && r.y0 < a.y1 && r.y1 > a.y0
++ });
}
- let (page_name, page, left_page) = match (loc.spread, spread) {
- (designcraft_doc::SpreadRef::Doc(si), Some(sp)) => {
+ let (page_name, page, left_page) = match (spread_ref, spread) {
+ (Some(designcraft_doc::SpreadRef::Doc(si)), Some(sp)) => {
let c = item.bounds().center();
let pi = sp.page_at_x(c.x).unwrap_or(0);
let abs = doc.first_page_of_spread(si) + pi;
@@@ -2732,161 -2075,51 +2740,166 @@@ fn line_metrics
desc = desc.max(g.descent - shift.min(0.0));
lead = lead.max(g.leading);
}
- (asc, desc, lead)
+ if !own_text {
+ // Only a label (an empty list paragraph): as an empty paragraph.
+ let face = face();
+ tops.typo_ascent = face.typo_ascent * base_size / face.upem;
+ tops.em = em_box_top(&face, base_size);
+ }
+ (asc, tops, desc, lead)
+}
+
+/// How a line clears Jump Object wraps. The line occupies `[baseline − top, baseline]` (its leading,
+/// or its first baseline offset at the top of a column) and must not overlap the wrap; it may hang its
+/// descenders into the wrap. Below a wrap it moves down from its place in whole `step`s until it clears
+/// the wrap bottom (`step` 0: its top lands on the wrap bottom).
+#[derive(Clone, Copy, Debug)]
+struct Jump {
+ top: f64,
+ step: f64,
+}
+
+/// Slack for float error when a line is tested against a Jump Object wrap's edges.
+const JUMP_EPS: f64 = 1e-6;
+
+/// The first baseline at or below `baseline` where a line with ascent `asc` and descent `desc` has
+/// free segments in `col` one of which `holds` the line (its first word fits), and the segments
+/// from that one on (see [`free_slots`], never empty); None if there are none above the column
+/// bottom. `line_start` is the story byte the line starts at (see
+/// [`Exclusion::wraps_line`]).
+///
+/// A line under a Jump Object wrap moves below it as `jump` says. Around a rectangular wrap the
+/// free space only grows where one in the line's band ends: the search jumps from one such bottom
+/// edge to the next, and a line that clears a wrap has its top exactly on the wrap's bottom. A
+/// contour's width changes within its box, so beside one the search moves down 1 pt at a time.
+#[allow(clippy::too_many_arguments)]
+fn wrap_slot(
+ f: &FrameSpec,
+ col: Rect,
+ baseline: f64,
+ asc: f64,
+ desc: f64,
+ jump: Jump,
+ size: f64,
+ rtl: bool,
+ line_start: usize,
+ holds: &dyn Fn(&(f64, f64)) -> bool,
+) -> Option<(f64, Vec<(f64, f64)>)> {
+ let top = jump.top.max(0.0);
+ let mut b = baseline;
+ // Each step passes at least one wrap; the cap bounds hostile geometry.
+ for _ in 0..4000 {
+ let jumped = f
+ .exclusions
+ .iter()
+ .filter(|e| e.mode == WrapMode::JumpObject && e.wraps_line(line_start))
+ .map(|e| e.rect)
+ .filter(|r| r.x0 < col.x1 && r.x1 > col.x0 && b > r.y0 + JUMP_EPS && b - top < r.y1 - JUMP_EPS)
+ .fold(f64::NEG_INFINITY, |m, r| m.max(r.y1));
+ b = if jumped > f64::NEG_INFINITY {
+ if jump.step > 0.0 {
+ // Whole steps from the line's own place (at least one step past the line above).
+ baseline + ((jumped + top - baseline - JUMP_EPS / 2.0) / jump.step).ceil().max(0.0) * jump.step
+ } else {
+ jumped + top
+ }
+ } else {
+ // Segments before the first that `holds` the line's first word stay empty.
+ let segs: Vec<(f64, f64)> =
+ free_slots(f, col, b - asc, b + desc, size, rtl, line_start).into_iter().skip_while(|seg| !holds(seg)).collect();
+ if !segs.is_empty() {
+ return Some((b, segs));
+ }
+ let (y0, y1) = (b - asc, b + desc);
+ let in_band = || {
+ f.exclusions
+ .iter()
+ .filter(|e| e.mode != WrapMode::JumpObject && e.wraps_line(line_start))
+ .filter(|e| e.rect.y0 < y1 && e.rect.y1 > y0)
+ };
+ let edge = in_band().fold(f64::INFINITY, |m, e| m.min(e.rect.y1)) + asc;
+ if in_band().any(|e| e.contour.is_some()) { edge.min(b + 1.0) } else { edge }
+ };
+ if b.is_nan() || b > col.y1 {
+ return None;
+ }
+ }
+ None
}
-/// Widest free horizontal interval of `col` in the band, or None if blocked. A gap a wrap object
-/// cuts narrower than 1.5 em of `size` is skipped (a sliver beside the object); when no object
-/// reaches the band the whole column is free, however narrow (a one-character frame such as an
-/// article's closing tombstone).
-fn free_slot(f: &FrameSpec, col: Rect, y0: f64, y1: f64, size: f64) -> Option<(f64, f64)> {
+/// Free segments of `col` in the band `y0..y1`, in the order text fills them (left to right, or
+/// right to left for right-to-left paragraphs); empty if the band is blocked. A line beside an
- /// object that lets text through on both sides has a segment on each side. Segments narrower than
- /// 1.5 em of `size` are skipped (the model has no minimum segment width). `line_start` is the story
- /// byte the line starts at (see [`Exclusion::wraps_line`]).
++/// object that lets text through on both sides has a segment on each side. When an object cuts
++/// the column, segments narrower than 1.5 em of `size` are skipped (slivers beside it); a column
++/// no object reaches is free however narrow (a one-character frame such as an article's closing
++/// tombstone). `line_start` is the story byte the line starts at (see [`Exclusion::wraps_line`]).
+#[allow(clippy::too_many_arguments)]
+fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, size: f64, rtl: bool, line_start: usize) -> Vec<(f64, f64)> {
let mut free = vec![(col.x0, col.x1)];
+ let mut cut = false;
- for ex in &f.exclusions {
+ for ex in f.exclusions.iter().filter(|e| e.wraps_line(line_start)) {
let r = ex.rect;
let overlaps_band = r.y0 < y1 && r.y1 > y0;
- match ex.mode {
- WrapMode::JumpToNextColumn if y1 > r.y0 && r.x0 < col.x1 && r.x1 > col.x0 => return None,
- WrapMode::JumpObject if overlaps_band && r.x0 < col.x1 && r.x1 > col.x0 => return None,
- WrapMode::BoundingBox | WrapMode::Contour if overlaps_band => {
- cut = true;
- let mut next = Vec::new();
- for (a, b) in free {
- if r.x1 <= a || r.x0 >= b {
- next.push((a, b));
- continue;
- }
- if r.x0 > a {
- next.push((a, r.x0));
- }
- if r.x1 < b {
- next.push((r.x1, b));
- }
- }
- free = next;
+ let blocked = match ex.mode {
+ WrapMode::JumpToNextColumn if y1 > r.y0 && r.x0 < col.x1 && r.x1 > col.x0 => return vec![],
+ WrapMode::BoundingBox | WrapMode::Contour if overlaps_band => match &ex.contour {
+ Some(c) => c.band_extent(y0, y1),
+ None => Some((r.x0, r.x1)),
+ },
+ _ => None,
+ };
+ let Some((a, b)) = blocked.filter(|&(a, b)| a < col.x1 && b > col.x0) else { continue };
++ cut = true;
+ // One-sided wraps also block the column on the other side of the object.
+ let text_left = match ex.side {
+ WrapSide::LeftSide => Some(true),
+ WrapSide::RightSide => Some(false),
+ WrapSide::LargestArea => Some(r.x0 - col.x0 >= col.x1 - r.x1),
+ WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => None,
+ };
+ let (a, b) = match text_left {
+ Some(true) => (a, b.max(col.x1)),
+ Some(false) => (a.min(col.x0), b),
+ None => (a, b),
+ };
+ let mut next = Vec::with_capacity(free.len() + 1);
+ for (fa, fb) in free {
+ if b <= fa || a >= fb {
+ next.push((fa, fb));
+ continue;
+ }
+ if a > fa {
+ next.push((fa, a));
+ }
+ if b < fb {
+ next.push((b, fb));
}
- _ => {}
}
+ free = next;
+ }
- free.retain(|(a, b)| b - a >= size * 1.5);
++ if cut {
++ free.retain(|(a, b)| b - a >= size * 1.5);
+ }
- if !cut {
- return Some((col.x0, col.x1));
+ if rtl {
+ free.reverse();
}
- free.into_iter().filter(|(a, b)| b - a >= size * 1.5).max_by(|x, y| (x.1 - x.0).total_cmp(&(y.1 - y.0)))
+ free
}
+/// Line slots for the breaker: the free segments of each line from baseline `first` down, `lead`
+/// apart; `carry` holds segments left on the line above (they come first).
#[allow(clippy::too_many_arguments)]
-fn estimate_slots(f: &FrameSpec, col: Rect, first: f64, lead: f64, size: f64, glyphs: &[Glyph], pp: &ParaProps, line_no: usize) -> Vec<(f64, f64)> {
- let _ = (pp, line_no);
+fn estimate_slots(
+ f: &FrameSpec,
+ col: Rect,
+ first: f64,
+ jump: Jump,
+ lead: f64,
+ size: f64,
+ glyphs: &[Glyph],
+ rtl: bool,
+ carry: &[(f64, f64)],
+) -> Vec<(f64, f64)> {
if f.exclusions.is_empty() {
return vec![];
}
diff --cc crates/compose/src/tests.rs
index 213e40c8e,b0cc474c7..e8ef0b421
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@@ -146,415 -146,44 +146,484 @@@ fn wrap_pushes_text_aside()
assert!(below.x0 < 1.0);
}
+ /// A small frame holding one character (a tombstone at the end of an article: a 7.6 pt symbol in
+ /// a 10.5 pt box), in a paragraph whose style is 14 pt, with a text-wrap object on the spread at
+ /// `wrap`.
+ fn tombstone(frame: Rect, wrap: Rect) -> (Document, StoryId) {
+ let (mut d, sid, _) = doc_with("X", frame, ParaAttrs::default());
+ let st = d.story_mut(sid).unwrap();
+ st.paras[0].chars = designcraft_doc::CharAttrs { size: Some(14.0), ..Default::default() };
+ st.format_chars(0..1, |f| f.over.size = Some(7.6));
+ let lid = d.default_layer();
+ let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(wrap));
+ it.wrap.mode = WrapMode::BoundingBox;
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ (d, sid)
+ }
+
+ /// A text-wrap object elsewhere on the spread doesn't affect a frame it doesn't overlap: the small
+ /// frame's one character is set (it was overset: every frame took every wrap object on the
+ /// spread, and then no gap narrower than 1.5 em of the paragraph's size was used).
+ #[test]
+ fn small_single_character_frame_sets_beside_unrelated_text_wrap() {
+ let (d, sid) = tombstone(Rect::new(300.0, 300.0, 310.5, 310.5), Rect::new(0.0, 0.0, 120.0, 60.0));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset(), "the tombstone is set");
+ assert_eq!(cs.line_count(), 1);
+ }
+
+ /// A narrow frame that a text-wrap object overlaps further down sets the lines the object doesn't
+ /// reach: the minimum gap width only applies to gaps a wrap object cuts.
+ #[test]
+ fn narrow_frame_sets_lines_no_wrap_object_reaches() {
+ let (d, sid) = tombstone(Rect::new(300.0, 300.0, 310.5, 340.0), Rect::new(290.0, 330.0, 330.0, 360.0));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset(), "the first line is above the wrap object");
+ assert_eq!(cs.line_count(), 1);
+ let (top, baseline) = (cs.frames[0].columns[0].y0, cs.frames[0].lines[0].baseline);
+ assert!(baseline - top < 20.0, "on the first line: {baseline} (text area from {top})");
+ }
+
++/// A wrap object that cuts a narrow frame leaves the sliver beside it (under 1.5 em) empty: no
++/// line is set beside the object, and the text continues below it.
++#[test]
++fn a_wrap_object_cutting_a_narrow_frame_leaves_its_sliver_empty() {
++ let text = ["of"; 400].join(" ");
++ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 60.0, 400.0), ParaAttrs::default());
++ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.size = Some(6.0));
++ // An 8 pt sliver at 6 pt: narrower than 1.5 em (9 pt), wide enough for a word.
++ add_wrap_objects(&mut d, &[(Rect::new(0.0, 50.0, 52.0, 120.0), [0.0; 4], WrapMode::BoundingBox)]);
++ let cs = compose_story(&d, sid, &ComposeOptions::default());
++ let lines = &cs.frames[0].lines;
++ assert!(lines.iter().all(|l| l.baseline + l.descent <= 50.0 + 1e-6 || l.baseline - l.ascent >= 120.0 - 1e-6), "a line beside the object");
++ assert!(lines.iter().any(|l| l.baseline - l.ascent >= 120.0 - 1e-6), "no text below the object");
++}
++
++/// A wrap object beside the second column of a two-column frame leaves the first column, narrower
++/// than 1.5 em, set in full.
++#[test]
++fn a_wrap_object_beside_column_two_leaves_a_narrow_column_one_set() {
++ let (mut d, sid, fid) = doc_with(&["X"; 12].join(" "), Rect::new(0.0, 0.0, 46.0, 100.0), ParaAttrs::default());
++ let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options;
++ o.columns = 2;
++ o.gutter = 12.0;
++ // 17 pt columns at 14 pt: narrower than 1.5 em (21 pt).
++ d.story_mut(sid).unwrap().format_chars(0..23, |f| f.over.size = Some(14.0));
++ add_wrap_objects(&mut d, &[(Rect::new(35.0, 0.0, 60.0, 100.0), [0.0; 4], WrapMode::BoundingBox)]);
++ let cs = compose_story(&d, sid, &ComposeOptions::default());
++ let first = all_lines(&cs).iter().filter(|l| l.column == 0).count();
++ assert!(first >= 4, "{first} lines in column 1");
++}
++
+/// Insert rectangles with wrap, given as (bounds, [top, left, bottom, right] offsets, mode).
+fn add_wrap_objects(d: &mut Document, objects: &[(Rect, [f64; 4], WrapMode)]) {
+ let lid = d.default_layer();
+ for &(r, offsets, mode) in objects {
+ let id = ItemId(d.alloc());
+ let mut it = designcraft_doc::Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(r));
+ it.wrap.mode = mode;
+ it.wrap.offsets = offsets;
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ }
+}
+
+/// 10 pt on 12 pt text in a 288 × 528 frame at (36, 36), with wrap objects.
+fn wrap_doc(para: ParaAttrs, objects: &[(Rect, [f64; 4], WrapMode)]) -> (Document, StoryId) {
+ let text = [LOREM; 6].join(" ");
+ let (mut d, sid, _) = doc_with(&text, Rect::new(36.0, 36.0, 324.0, 564.0), para);
+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {
+ f.over.size = Some(10.0);
+ f.over.leading = Some(designcraft_doc::Leading::Points(12.0));
+ });
+ add_wrap_objects(&mut d, objects);
+ (d, sid)
+}
+
+/// The first line whose baseline is below the top of `ex`.
+fn first_line_below<'a>(cs: &'a ComposedStory, ex: &Exclusion) -> &'a Line {
+ cs.frames[0].lines.iter().find(|l| l.baseline > ex.rect.y0).unwrap()
+}
+
+/// 14 pt on 18 pt `text` in a frame from y 62.36 to 532.91 with first baseline offset Leading, so lines
+/// sit at 80.36 + n × 18 (the setup measured in InDesign), with Jump Object wraps given as
+/// (bounds, [top, left, bottom, right] offsets).
+fn jump_doc(text: &str, objects: &[(Rect, [f64; 4])]) -> (Document, StoryId, ItemId) {
+ let (mut d, sid, fid) = doc_with(text, Rect::new(36.0, 62.36, 324.0, 532.91), ParaAttrs::default());
+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {
+ f.over.size = Some(14.0);
+ f.over.leading = Some(designcraft_doc::Leading::Points(18.0));
+ });
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.first_baseline = FirstBaseline::Leading;
+ let objects: Vec<_> = objects.iter().map(|&(r, o)| (r, o, WrapMode::JumpObject)).collect();
+ add_wrap_objects(&mut d, &objects);
+ (d, sid, fid)
+}
+
+/// Baselines of the last line above the top of the first wrap and of the first line below it.
+fn around_wrap(d: &Document, sid: StoryId) -> (Option<f64>, f64) {
+ let specs = frame_specs(d, sid);
+ let ex = &specs[0].exclusions[0];
+ let cs = compose_story(d, sid, &ComposeOptions::default());
+ let lines = &cs.frames[0].lines;
+ let above = lines.iter().rev().find(|l| l.baseline <= ex.rect.y0 + 1e-6).map(|l| l.baseline);
+ (above, first_line_below(&cs, ex).baseline)
+}
+
+fn near(a: f64, b: f64) -> bool {
+ (a - b).abs() < 0.01
+}
+
+#[test]
+fn jump_object_moves_the_next_line_down_by_whole_leadings() {
+ // As measured: last baseline above 386.41, wrap bottom 472.77 → 494.40 (6 leadings). Here the last
+ // line above is at 386.36 and the wrap ends 86.36 below it.
+ let text = [LOREM; 8].join(" ");
+ let (d, sid, _) = jump_doc(&text, &[(Rect::new(36.0, 395.0, 200.0, 472.72), [0.0; 4])]);
+ let (above, below) = around_wrap(&d, sid);
+ assert!(near(above.unwrap(), 386.36), "{above:?}");
+ assert!(near(below, 386.36 + 6.0 * 18.0), "{below}");
+ // The lines after it keep the leading.
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let next = cs.frames[0].lines.iter().find(|l| l.baseline > below + 1.0).unwrap();
+ assert!(near(next.baseline, below + 18.0));
+}
+
+#[test]
+fn jump_object_clears_the_wrap_with_the_leading_not_the_ascent() {
+ // As measured: last 152.38, wrap bottom 246.90 → 278.38. Clearing the wrap with the line's ascent
+ // instead of its leading would put the line one leading higher (here the wrap ends a little higher,
+ // as the test font's ascent is larger).
+ let text = [LOREM; 8].join(" ");
+ let (d, sid, _) = jump_doc(&text, &[(Rect::new(36.0, 160.0, 324.0, 244.0), [0.0; 4])]);
+ let (above, below) = around_wrap(&d, sid);
+ assert!(near(above.unwrap(), 152.36), "{above:?}");
+ assert!(near(below, 152.36 + 7.0 * 18.0), "{below}");
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let asc = cs.frames[0].lines[0].ascent;
+ let by_ascent = (1..).map(|k| 152.36 + k as f64 * 18.0).find(|b| b - asc >= 244.0).unwrap();
+ assert!(!near(by_ascent, below), "the case must tell the two rules apart ({asc})");
+}
+
+#[test]
+fn jump_object_adds_space_before_once() {
+ // As measured: a heading at 78.36, then a paragraph with 60 pt space before, wrap bottom 439.71 →
+ // 462.36 = 78.36 + 60 + 18 × 18.
+ let text = format!("Heading\n{}", [LOREM; 6].join(" "));
+ let (mut d, sid, _) = jump_doc(&text, &[(Rect::new(36.0, 90.0, 324.0, 439.71), [0.0; 4])]);
+ d.story_mut(sid).unwrap().format_paras(10..10, |p| p.para.space_before = Some(60.0));
+ let (above, below) = around_wrap(&d, sid);
+ assert!(near(above.unwrap(), 80.36), "{above:?}");
+ assert!(near(below, 80.36 + 60.0 + 18.0 * 18.0), "{below}");
+}
+
+#[test]
+fn jump_object_at_the_frame_top_starts_text_like_a_frame_top() {
+ // As measured: wrap bottom 266.83 → first baseline 284.835 (Leading offset: one leading below).
+ let text = [LOREM; 8].join(" ");
+ let (mut d, sid, fid) = jump_doc(&text, &[(Rect::new(36.0, 50.0, 324.0, 266.83), [0.0; 4])]);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = &cs.frames[0].lines;
+ assert!(near(lines[0].baseline, 266.83 + 18.0), "{}", lines[0].baseline);
+ assert!(near(lines[1].baseline, 266.83 + 36.0), "{}", lines[1].baseline);
+ // Ascent offset: the line's ascent below the wrap.
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.first_baseline = FirstBaseline::Ascent;
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ assert!(near(l.baseline, 266.83 + l.ascent), "{} vs {}", l.baseline, l.ascent);
+}
+
+#[test]
+fn line_above_jump_object_stays_while_its_baseline_is_above_the_wrap() {
+ let text = [LOREM; 8].join(" ");
+ // The line at 386.36 hangs its descenders into the object and stays.
+ let (d, sid, _) = jump_doc(&text, &[(Rect::new(36.0, 386.36, 324.0, 420.0), [0.0; 4])]);
+ let (above, below) = around_wrap(&d, sid);
+ assert!(near(above.unwrap(), 386.36), "{above:?}");
+ assert!(near(below, 440.36), "{below}");
+ // A wrap starting just above its baseline makes it jump.
+ let (d, sid, _) = jump_doc(&text, &[(Rect::new(36.0, 386.3, 324.0, 420.0), [0.0; 4])]);
+ let (above, below) = around_wrap(&d, sid);
+ assert!(near(above.unwrap(), 368.36), "{above:?}");
+ assert!(near(below, 440.36), "{below}");
+}
+
+#[test]
+fn negative_jump_offsets_shrink_the_wrap() {
+ let text = [LOREM; 8].join(" ");
+ let (d, sid, _) = jump_doc(&text, &[(Rect::new(36.0, 300.0, 324.0, 500.0), [-20.0, 0.0, -30.0, 0.0])]);
+ let specs = frame_specs(&d, sid);
+ let r = specs[0].exclusions[0].rect;
+ assert!(near(r.y0, 320.0) && near(r.y1, 470.0), "{r:?}");
+ let (above, below) = around_wrap(&d, sid);
+ assert!(near(above.unwrap(), 314.36), "{above:?}");
+ assert!(near(below, 494.36), "{below}");
+}
+
+#[test]
+fn jump_object_down_to_the_frame_bottom_sends_text_to_the_next_frame() {
+ let text = [LOREM; 8].join(" ");
+ let (mut d, sid, a) = jump_doc(&text, &[(Rect::new(36.0, 300.0, 324.0, 540.0), [0.0; 4])]);
+ let lid = d.default_layer();
+ let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(350.0, 62.36, 550.0, 532.91), lid, "", ParaFormat::default()).unwrap();
+ d.item_mut(b).unwrap().text_frame_mut().unwrap().options.first_baseline = FirstBaseline::Leading;
+ d.thread(a, b).unwrap();
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let last = cs.frames[0].lines.last().unwrap();
+ assert!(near(last.baseline, 296.36), "{}", last.baseline);
+ assert!(near(cs.frames[1].lines[0].baseline, 62.36 + 18.0), "{}", cs.frames[1].lines[0].baseline);
+ assert_eq!(cs.frames[0].range.end, cs.frames[1].range.start);
+}
+
+#[test]
+fn full_width_bounding_box_wrap_resumes_exactly_below() {
+ // A bounding-box wrap across the whole column leaves no slot: the line jumps it like Jump Object.
+ let (d, sid) = wrap_doc(ParaAttrs::default(), &[(Rect::new(20.0, 100.0, 340.0, 150.25), [0.0; 4], WrapMode::BoundingBox)]);
+ let specs = frame_specs(&d, sid);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let ex = &specs[0].exclusions[0];
+ let l = first_line_below(&cs, ex);
+ assert!((l.baseline - l.ascent - ex.rect.y1).abs() < 0.01, "{} vs {}", l.baseline - l.ascent, ex.rect.y1);
+ // A slot narrower than 1.5 × the size is no slot either.
+ let (d, sid) = wrap_doc(ParaAttrs::default(), &[(Rect::new(50.0, 100.0, 340.0, 150.25), [0.0; 4], WrapMode::BoundingBox)]);
+ let specs = frame_specs(&d, sid);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let ex = &specs[0].exclusions[0];
+ let l = first_line_below(&cs, ex);
+ assert!((l.baseline - l.ascent - ex.rect.y1).abs() < 0.01, "{} vs {}", l.baseline - l.ascent, ex.rect.y1);
+}
+
+#[test]
+fn jump_object_keeps_grid_aligned_lines_on_the_grid() {
+ // The wrap ends at 166.5, off the 12 pt grid; a second object blocks the grid line the line jumps
+ // to, so the line moves on to the grid line after that object.
+ let objects = [
+ (Rect::new(36.0, 100.0, 200.0, 160.5), [0.0, 0.0, 6.0, 0.0], WrapMode::JumpObject),
+ (Rect::new(250.0, 178.0, 324.0, 190.0), [0.0; 4], WrapMode::JumpObject),
+ ];
+ let (d, sid) = wrap_doc(ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, &objects);
+ let specs = frame_specs(&d, sid);
+ let (g0, inc) = specs[0].grid.unwrap();
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let on_grid = |b: f64| (((b - g0) / inc).round() * inc + g0 - b).abs() < 1e-6;
+ let lines = &cs.frames[0].lines;
+ assert!(lines.iter().all(|l| on_grid(l.baseline)), "{:?}", lines.iter().map(|l| l.baseline).collect::<Vec<_>>());
+ let exs = &specs[0].exclusions;
+ let l = first_line_below(&cs, &exs[0]);
+ // Naive oracle: the first grid line whose leading band clears the objects.
+ let clear = |b: f64, exs: &[Exclusion]| exs.iter().all(|e| b <= e.rect.y0 || b - l.leading >= e.rect.y1);
+ let want = |exs: &[Exclusion]| (0..).map(|n| g0 + n as f64 * inc).find(|&b| b > exs[0].rect.y0 && clear(b, exs)).unwrap();
+ assert!((l.baseline - want(exs)).abs() < 1e-6, "baseline {} should be on grid line {}", l.baseline, want(exs));
+ assert!(want(&exs[..1]) < want(exs), "the second object pushed the line again");
+
+ // First line only: a later line of the paragraph jumps by whole leadings from the line above.
+ let (d, sid) = wrap_doc(ParaAttrs { grid_align: Some(GridAlign::FirstLineOnly), ..Default::default() }, &objects[..1]);
+ let specs = frame_specs(&d, sid);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let ex = &specs[0].exclusions[0];
+ let l = first_line_below(&cs, ex);
+ assert!(!l.first_in_para);
+ let above = cs.frames[0].lines.iter().rev().find(|a| a.baseline <= ex.rect.y0).unwrap().baseline;
+ let want = (1..).map(|k| above + k as f64 * 12.0).find(|b| b - 12.0 >= ex.rect.y1).unwrap();
+ assert!((l.baseline - want).abs() < 1e-6, "{} vs {want}", l.baseline);
+}
+
+#[test]
+fn hostile_wrap_geometry_terminates() {
+ let (d, sid) = wrap_doc(ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, &[]);
+ let mut specs = frame_specs(&d, sid);
+ let ex = |x0: f64, y0: f64, x1: f64, y1: f64, mode| Exclusion {
+ rect: Rect::new(x0, y0, x1, y1),
+ mode,
+ side: WrapSide::BothSides,
+ contour: None,
+ after: None,
+ };
+ let f = &mut specs[0];
+ f.exclusions.push(ex(f64::NAN, f64::NAN, f64::NAN, f64::NAN, WrapMode::JumpObject));
+ f.exclusions.push(ex(-1e308, 300.0, 1e308, f64::INFINITY, WrapMode::JumpObject));
+ f.exclusions.push(ex(0.0, f64::NEG_INFINITY, 400.0, 40.0, WrapMode::BoundingBox));
+ // A wall of overlapping strips, each ending 0.25 pt below the previous.
+ for i in 0..3000 {
+ let y = 60.0 + i as f64 * 0.25;
+ f.exclusions.push(ex(0.0, y, 400.0, y + 1.0, if i % 2 == 0 { WrapMode::JumpObject } else { WrapMode::BoundingBox }));
+ }
+ f.grid = Some((0.0, 1e-300));
+ let story = d.story(sid).unwrap();
+ let cs = compose(&d, story, &specs, &ComposeOptions::default());
+ assert!(cs.is_overset());
+ for l in &cs.frames[0].lines {
+ assert!(l.baseline.is_finite() && l.baseline - l.ascent >= 40.0 && l.baseline + l.descent <= 300.0, "{}", l.baseline);
+ }
+}
+
+/// A text frame (0,0)-(300,800) with an ellipse (110,100)-(190,200) wrapped as `mode`/`side`.
+fn doc_with_ellipse(mode: WrapMode, side: WrapSide) -> (Document, StoryId) {
+ let (mut d, sid, _) = doc_with(&[LOREM; 4].join(" "), Rect::new(0.0, 0.0, 300.0, 800.0), ParaAttrs::default());
+ let lid = d.default_layer();
+ let id = ItemId(d.alloc());
+ let mut it =
+ designcraft_doc::Item::new(id, lid, designcraft_doc::Shape::Oval, designcraft_geom::shapes::ellipse(Rect::new(110.0, 100.0, 190.0, 200.0)));
+ it.wrap.mode = mode;
+ it.wrap.side = side;
+ it.wrap.offsets = [4.0; 4];
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ (d, sid)
+}
+
+#[test]
+fn wrap_on_both_sides_sets_text_left_then_right_of_the_object() {
+ let (d, sid) = doc_with_ellipse(WrapMode::Contour, WrapSide::BothSides);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = &cs.frames[0].lines;
+ let pairs: Vec<(&Line, &Line)> = lines.windows(2).filter(|w| w[0].baseline == w[1].baseline).map(|w| (&w[0], &w[1])).collect();
+ assert!(pairs.len() >= 4, "{} lines share a baseline", pairs.len());
+ let ex = &frame_specs(&d, sid)[0].exclusions[0];
+ for (l, r) in &pairs {
+ // Left segment, then the right one; the text runs on from one to the other.
+ assert!(l.x1 < 150.0 && r.x0 > 150.0, "{} {}", l.x1, r.x0);
+ assert_eq!(l.range.end, r.range.start);
+ // No glyph inside the wrapped outline at its line.
+ let (a, b) = ex.contour.as_ref().unwrap().band_extent(l.baseline - l.ascent, l.baseline + l.descent).unwrap();
+ let n = l.glyphs.len().saturating_sub(1);
+ // The left segment's last glyph may be the space the line breaks at.
+ for g in l.glyphs.iter().take(n).chain(&r.glyphs).filter(|g| g.visible) {
+ assert!(g.x + g.adv <= a + 0.5 || g.x >= b - 0.5, "glyph at {}..{} in {a}..{b}", g.x, g.x + g.adv);
+ }
+ }
+ // Lines beside the narrow top of the ellipse reach closer to its centre than those at its middle.
+ let mid = pairs.iter().map(|(l, _)| l.x1).fold(f64::INFINITY, f64::min);
+ let top = pairs.first().unwrap().0.x1;
+ assert!(top > mid + 5.0, "top {top}, middle {mid}");
+ assert!(!cs.is_overset());
+}
+
+/// Same As Clipping follows a placed graphic's clipping path: beside a triangle that widens
+/// downwards, text reaches further in at the narrow top than at the wide bottom.
+#[test]
+fn same_as_clipping_wrap_follows_the_clipping_path() {
+ use designcraft_geom::{PathData, Point, SubPath};
+ let (mut d, sid, _) = doc_with(&[LOREM; 4].join(" "), Rect::new(0.0, 0.0, 300.0, 800.0), ParaAttrs::default());
+ let lid = d.default_layer();
+ let id = ItemId(d.alloc());
+ let mut it = designcraft_doc::Item::new(
+ id,
+ lid,
+ designcraft_doc::Shape::Rectangle,
+ designcraft_geom::shapes::rectangle(Rect::new(150.0, 100.0, 300.0, 300.0)),
+ );
+ let triangle = PathData::single(SubPath::polyline(&[Point::new(75.0, 0.0), Point::new(150.0, 200.0), Point::new(0.0, 200.0)], true));
+ it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {
+ asset: designcraft_doc::AssetId(1),
+ size: (150.0, 200.0),
+ xf: designcraft_geom::Affine::translate((150.0, 100.0)),
+ clip: Some(std::sync::Arc::new(designcraft_doc::ClippingPath::new(designcraft_doc::ClippingKind::DetectEdges, triangle))),
+ auto_fit: Default::default(),
+ fit_align: 0,
+ crop: [0.0; 4],
+ wrap: Default::default(),
+ });
+ it.wrap.mode = WrapMode::Contour;
+ it.wrap.side = WrapSide::LeftSide;
+ it.wrap.contour = designcraft_doc::ContourType::SameAsClipping;
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let beside: Vec<&Line> = cs.frames[0].lines.iter().filter(|l| l.baseline - l.ascent > 100.0 && l.baseline + l.descent < 300.0).collect();
+ let (top, bottom) = (beside.first().unwrap().x1, beside.last().unwrap().x1);
+ assert!(top > bottom + 40.0, "top {top}, bottom {bottom}");
+ assert!(bottom < 160.0, "the bottom lines stop near the triangle's base: {bottom}");
+}
+
+/// LOREM beside an ellipse wrapped on both sides along its contour that leaves a sliver (about
+/// 20 pt at its middle) between it and the frame's right edge.
+fn sliver_wrap(para: ParaAttrs) -> (Document, StoryId, String) {
+ let text = [LOREM; 4].join(" ");
+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 800.0), para);
+ let lid = d.default_layer();
+ let id = ItemId(d.alloc());
+ let mut it =
+ designcraft_doc::Item::new(id, lid, designcraft_doc::Shape::Oval, designcraft_geom::shapes::ellipse(Rect::new(150.0, 100.0, 276.0, 220.0)));
+ it.wrap.mode = WrapMode::Contour;
+ it.wrap.side = WrapSide::BothSides;
+ it.wrap.offsets = [4.0; 4];
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ (d, sid, text)
+}
+
+#[test]
+fn words_stay_whole_beside_a_wrap_sliver() {
+ for align in [Align::Left, Align::LeftJustified] {
+ for hyphenate in [true, false] {
+ let (d, sid, text) = sliver_wrap(ParaAttrs { align: Some(align), hyphenate: Some(hyphenate), ..Default::default() });
+ let ex = &frame_specs(&d, sid)[0].exclusions[0];
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ let word = |i: usize| text.as_bytes().get(i).is_some_and(u8::is_ascii_alphanumeric);
+ let mut empty_slivers = 0;
+ for (i, l) in lines.iter().enumerate() {
+ let line = &text[l.range.clone()];
+ // A line ends inside a word only at a hyphenation point.
+ assert!(l.hyphenated || !(word(l.range.end - 1) && word(l.range.end)), "{align:?} {hyphenate}: split word in {line:?}");
+ // Every word fits its segment whole.
+ for g in l.glyphs.iter().filter(|g| g.visible) {
+ assert!(g.x + g.adv <= l.x1 + 0.5, "{align:?} {hyphenate}: {line:?} overflows its {}..{} segment", l.x0, l.x1);
+ }
+ // A left segment beside the object whose sliver stays empty: the next word doesn't fit it.
+ let Some((_, b)) = ex.contour.as_ref().unwrap().band_extent(l.baseline - l.ascent, l.baseline + l.descent) else { continue };
+ let next = lines.get(i + 1);
+ if l.x1 > b || 300.0 - b < 18.0 || next.is_some_and(|n| n.baseline == l.baseline) {
+ continue;
+ }
+ let Some(next) = next else { continue };
+ let first = text[next.range.clone()].split(' ').next().unwrap_or_default();
+ let w: f64 = next.glyphs.iter().filter(|g| g.byte < next.range.start + first.len()).map(|g| g.adv).sum();
+ assert!(w > 300.0 - b, "{align:?} {hyphenate}: {first:?} ({w}) fits the {} pt sliver beside {line:?}", 300.0 - b);
+ empty_slivers += 1;
+ }
+ if !hyphenate {
+ assert!(empty_slivers > 0, "{align:?}: no sliver stays empty");
+ }
+ assert!(!cs.is_overset());
+ }
+ }
+}
+
+#[test]
+fn one_sided_wrap_leaves_the_other_side_empty() {
+ for (side, right) in [(WrapSide::RightSide, true), (WrapSide::LeftSide, false), (WrapSide::LargestArea, false)] {
+ let (d, sid) = doc_with_ellipse(WrapMode::BoundingBox, side);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let beside: Vec<&Line> = cs.frames[0].lines.iter().filter(|l| l.baseline - l.ascent < 200.0 && l.baseline + l.descent > 100.0).collect();
+ assert!(!beside.is_empty());
+ let mut rows: Vec<f64> = beside.iter().map(|l| l.baseline).collect();
+ rows.dedup();
+ assert_eq!(rows.len(), beside.len(), "{side:?}: one segment per line");
+ for l in beside {
+ assert!(if right { l.x0 >= 194.0 - 1e-6 } else { l.x1 <= 106.0 + 1e-6 }, "{side:?}: {}..{}", l.x0, l.x1);
+ }
+ }
+}
+
+#[test]
+fn contour_wrap_follows_the_outline_band_by_band() {
+ let (d, sid) = doc_with_ellipse(WrapMode::Contour, WrapSide::BothSides);
+ let ex = &frame_specs(&d, sid)[0].exclusions[0];
+ let c = ex.contour.as_ref().unwrap();
+ let width = |y0: f64, y1: f64| c.band_extent(y0, y1).map_or(0.0, |(a, b)| b - a);
+ let (top, mid, bottom) = (width(100.0, 104.0), width(146.0, 154.0), width(196.0, 200.0));
+ // 80 wide plus the 4 pt offset each side at the middle; much narrower at the ends.
+ assert!((mid - 88.0).abs() < 0.5, "{mid}");
+ assert!(top < mid - 20.0 && bottom < mid - 20.0, "{top} {mid} {bottom}");
+ // The band is the line's height, not its baseline: a band reaching the middle is full width.
+ assert!((width(120.0, 150.0) - 88.0).abs() < 0.5);
+ // Outside the outline and its offset: no block.
+ assert!(c.band_extent(205.0, 210.0).is_none());
+ // A bounding-box wrap blocks the rectangle at every band.
+ let (d, sid) = doc_with_ellipse(WrapMode::BoundingBox, WrapSide::BothSides);
+ let ex = &frame_specs(&d, sid)[0].exclusions[0];
+ assert!(ex.contour.is_none());
+ assert_eq!(ex.rect, Rect::new(106.0, 96.0, 194.0, 204.0));
+}
+
#[test]
fn paragraph_composer_is_no_worse_than_greedy() {
// Sum of squared slack over lines (excluding last) should not exceed the greedy result.