Skip to content

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

Merge anchored-wrap: Text wrap: anchored objects wrap text (#557)

aiongg9a95cee17258
diff --cc ROADMAP.md
index 534533793,a92aff9a6..814c64362
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -128,50 -129,12 +128,51 @@@ list) · [roadmap.md](docs/roadmap.md)
Newest first.
+- **2026-10-12** · Text threads by hand: click a selected text frame's in or out port to load
+ the text cursor, then click a frame to thread it, click empty space for a column-wide frame or
+ drag one (it snaps like frame drawing); Shift-click autoflows, Alt-click stays loaded on the
+ frame just added; click the linked frame or double-click a port to break the thread.
+ `text.thread`, `text.unthread`, `text.removeFromThread` with undo; locked frames and layers
+ refuse threads. The alpha gate now waits only on the Primary Text Frame page fixes (#165). No
+ readiness percentage change.
+- **2026-10-12** · Properties › Transform shows rotation, shear and X/Y scale, and Rotate 90° and Flip Horizontal/Vertical buttons, as InDesign's does. No readiness percentage change.
+- **2026-10-12** · Underlines and strikethroughs are drawn as one bar per stretch of text on screen, as in PDF export: a bar per letter left faint seams between the letters. No readiness percentage change.
+- **2026-10-12** · The section marker character shows its section's marker text on document pages (nothing when the section has none) instead of the word "Section", which stays on parent pages; editing the marker recomposes (#556). No readiness percentage change.
+- **2026-10-12** · IDML import keeps a font family name exactly as written, trailing spaces included, and font lookup falls back to the name without surrounding spaces; `FontStyle="Nothing"` leaves the style to the paragraph (#558). No readiness percentage change.
+- **2026-10-12** · Clipping paths saved with images in IDML (Detect Edges, Alpha Channel, Photoshop Path, User-Modified Path, inverted or not) clip the image on screen and in PDF and survive IDML export; `object.clippingPathOptions` reports, inverts or removes one (#450). No readiness percentage change.
+ - **2026-10-12** · Anchored objects with text wrap push text aside: other stories' text under them and the lines of their own story after the anchor's line (#557). No readiness percentage change.
- **2026-10-12** · Words in capitals hyphenate like capitalized words (FERRUM COM-MODI), as in InDesign; Hyphenate Capitalized Words off keeps them whole. No readiness percentage change.
+- **2026-10-11 (printing):** `file.printers` and `file.print` use craft-libs/craft-print for CUPS and Windows. DesignCraft retains PDF export, page selection, spreads, marks and bleed; dry runs create no temporary PDF or print job. Windows selects matching or default driver paper and shrinks oversized sheets without enlarging smaller ones; queue duplex defaults are preserved. Headless tests exercise exported bytes, job settings, dry runs and refusals; shared native Windows CI passes, including paused-queue submission and cleanup. PostScript, production print controls and physical output validation remain open. No readiness percentage change.
+- **2026-10-11** · The View menu follows InDesign's: proofing first, then zoom, Rotate Spread, Screen Mode, Display Performance, rulers, Extras, Grids & Guides and Structure; the view items that sat at the end of the Type menu moved there. No readiness percentage change.
+- **2026-10-11** · Properties › Appearance's Fill and Stroke menus gain InDesign's Tint field and, for a text frame, Apply To: Frame / Text. No readiness percentage change.
+- **2026-10-11** · `story.replaceRange`, `story.setText`, notes, footnotes, endnotes, type on a path and table cells read `\r` and `\r\n` as paragraph returns, as `frame.create` and `text.insert` already did. No readiness percentage change.
+- **2026-10-11** · Corner Options keep curved sides curved and round every corner point, including where an arc meets a line (a Pathfinder quarter circle with rounded corners stayed a triangle). No readiness percentage change.
+- **2026-10-11:** Type › Justification… (Cmd+Alt+Shift+J, also in the Paragraph panel menu) sets word and letter spacing, glyph scaling and the composer on the selected paragraphs, sharing the Paragraph Style Options section (#531). No readiness percentage change.
+- **2026-10-11** · Properties gains InDesign's Pathfinder section (Add, Subtract, Intersect, Exclude Overlap, Minus Back) with several objects selected; section titles and icon buttons have accessible names. No readiness percentage change.
- **2026-10-11** · `transform.move {copy}`, Edit › Duplicate and Step and Repeat return the copies' ids, so a script can go on with them. No readiness percentage change.
- **2026-10-11** · `object.fill` and `object.stroke` refuse a swatch name the document doesn't have (it painted nothing) and suggest the name meant (`Paper` → `[Paper]`). No readiness percentage change.
-- **2026-10-11 (printing):** `file.printers` and `file.print` use craft-libs/craft-print for CUPS and Windows. DesignCraft retains PDF export, page selection, spreads, marks and bleed; dry runs create no temporary PDF or print job. Windows selects matching or default driver paper and shrinks oversized sheets without enlarging smaller ones; queue duplex defaults are preserved. Headless tests exercise exported bytes, job settings, dry runs and refusals; shared native Windows CI passes, including paused-queue submission and cleanup. PostScript, production print controls and physical output validation remain open. No readiness percentage change.
-
+- **2026-10-11** · Japanese captions now cover print ranges, imported style handling and table
+ row/column movement, including row-height distribution. Existing translation and RTL helpers
+ handle the display; command IDs, stored option values and user-defined style names are unchanged.
+- **2026-10-11** · Moving a sheared and rotated text frame no longer leaves trails of text behind: canvas repaints cover the frame's whole text box, not just its outline. No readiness percentage change.
+- **2026-10-11** · Live corners: the yellow widget on a selected rectangle frame shows corner
+ diamonds; dragging one rounds the corners, Alt-click steps the corner shape (#186).
+- **2026-10-11** · Optical kerning (#181): pairs are spaced from their outlines (ink gap per band,
+ pulled towards the font's stem gap, bounded) instead of silently using the font's kern pairs.
+- **2026-10-11** · New Document laid out like InDesign's (#325): Recent, Saved, Print, Web and
+ Mobile preset tabs beside the preset's details; saved document presets live in the engine
+ (`file.savePreset`, `file.deletePreset`, `file.new {preset}`); `file.new` takes intent, units,
+ start page and per-edge bleed and slug.
+- **2026-10-11** · macOS: fonts that font services and managers activate (Adobe Fonts,
+ RightFont) are listed, read from the files CoreText has available (#261, #327).
+- **2026-10-11:** Document pages take their parent page's margins and columns (left or right parent page by side) and follow its changes unless they have their own; parent ruler guides draw and snap on the pages based on it. IDML import marks a page margin preference that differs from its parent as the page's own. No readiness percentage change.
+- **2026-10-11** · Document Setup laid out like InDesign's: Page Size, Margins (new: every
+ page's, `layout.documentSetup {margins}`), Bleed and Slug with links, Adjust Layout.
+- **2026-10-11** · IDML reads and writes a spread's view rotation (Rotate Spread) as the
+ rotation part of the spread transform (#484).
+- **2026-10-11** · The document grid is drawn (View ▸ Grids & Guides ▸ Show/Hide Document Grid,
+ ⌘'), on the lines Snap to Document Grid uses, behind or in front of page items (#530).
+- **2026-10-12** · Double-clicking the Fill or Stroke box in the Tools panel opens the Color Picker with the selection's colour, as in InDesign (it opened the Swatches panel). No readiness percentage change.
- **2026-10-10 (UI.4–UI.5):** Panel tabs can move into other groups, split the dock, float, resize and return to their saved locations through shared docking transactions. Layouts persist in custom workspaces; UI and control commands share the same validated action path. Shared pane geometry and widget-state theme application retain all five palettes and local fonts. Split panes send keyboard input only to the focused canvas and scope contextual toolbar IDs per pane. No readiness percentage change.
- **2026-10-10** · Version 0.6.0; releases add a Linux riscv64 tar.gz (cross-compiled, CLI
smoke-tested under QEMU).
diff --cc crates/compose/src/cache.rs
index 2e9119922,3dcdc401e..5f59af967
--- a/crates/compose/src/cache.rs
+++ b/crates/compose/src/cache.rs
@@@ -151,10 -159,12 +169,12 @@@ impl Cache
// Parent-page items are composed per page: markers show its name, variables need its index.
let page = page.filter(|_| with_vars);
let running = running.then(|| self.running_index(doc));
- let out = Arc::new(crate::compose_story(
+ let others: Vec<Arc<ComposedStory>> = neighbours.iter().map(|n| self.neighbour(doc, *n)).collect();
+ let out = Arc::new(crate::wrap::compose_among(
doc,
sid,
- &ComposeOptions { page_name, page, running, label: None, xrefs: with_xrefs.then(|| self.xref_index(doc)) },
+ &ComposeOptions { page_name, section_marker, page, running, label: None, xrefs: with_xrefs.then(|| self.xref_index(doc)) },
+ &others.iter().map(|o| &**o).collect::<Vec<_>>(),
));
let mut g = self.map.lock().unwrap_or_else(|e| e.into_inner());
let stamp = g.1;
diff --cc crates/compose/src/lib.rs
index f3034b3fb,2f98b1b9f..d8df8583c
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@@ -331,154 -288,13 +332,165 @@@ impl ComposedStory
/// A text-wrap exclusion in a frame's inner space.
#[derive(Clone, Debug, PartialEq)]
pub struct Exclusion {
+ /// Bounding box, offsets included.
pub rect: Rect,
pub mode: WrapMode,
+ /// Where text may go beside the object. Spine sides are resolved to `LeftSide`/`RightSide`.
+ pub side: WrapSide,
+ /// Contour wrap, or a custom boundary: the outline the text follows (None wraps around `rect`).
+ pub contour: Option<Contour>,
+ /// An anchored object in the frame's own story: it wraps only lines that start after this
+ /// story byte (its anchor).
+ pub after: Option<usize>,
+ }
+
++impl Exclusion {
++ /// Does the exclusion wrap a line starting at story byte `line_start`? An own-story anchored
++ /// object wraps only the lines after its anchor.
++ pub fn wraps_line(&self, line_start: usize) -> bool {
++ self.after.is_none_or(|a| a < line_start)
++ }
+}
+
+/// An object outline for contour wrap: closed polylines in the frame's inner space and the
+/// distance text keeps from them.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Contour {
+ pub rings: Vec<Vec<Point>>,
+ pub offset: f64,
+}
+
+/// Points a contour outline may have; a larger outline wraps around its bounding box.
+const MAX_CONTOUR_POINTS: usize = 8192;
+
+impl Contour {
+ /// The outline of `path` (after `to_inner`), flattened; None if it is empty or too detailed.
+ fn of(path: &designcraft_geom::BezPath, to_inner: designcraft_geom::Affine, offset: f64) -> Option<Contour> {
+ let mut rings: Vec<Vec<Point>> = Vec::new();
+ let mut n = 0usize;
+ let mut too_many = false;
+ designcraft_geom::kurbo::flatten(to_inner * path.clone(), 0.25, |el| {
+ n += 1;
+ too_many |= n > MAX_CONTOUR_POINTS;
+ match el {
+ designcraft_geom::PathEl::MoveTo(p) => rings.push(vec![p]),
+ designcraft_geom::PathEl::LineTo(p) => match rings.last_mut() {
+ Some(r) => r.push(p),
+ None => rings.push(vec![p]),
+ },
+ _ => {}
+ }
+ });
+ rings.retain(|r| r.len() >= 2 && r.iter().all(|p| p.x.is_finite() && p.y.is_finite()));
+ (!too_many && !rings.is_empty() && offset.is_finite()).then_some(Contour { rings, offset: offset.max(0.0) })
+ }
+
+ fn bounds(&self) -> Rect {
+ let mut pts = self.rings.iter().flatten();
+ let Some(&p0) = pts.next() else { return Rect::ZERO };
+ let r = pts.fold(Rect::from_points(p0, p0), |r, &p| r.union_pt(p));
+ r.inflate(self.offset, self.offset)
+ }
+
+ /// Horizontal extent of the outline (offset included) within the band `y0..y1`: the band is
+ /// widened by the offset, and the outline's x-range there is widened by it too.
+ fn band_extent(&self, y0: f64, y1: f64) -> Option<(f64, f64)> {
+ let (y0, y1) = (y0 - self.offset, y1 + self.offset);
+ let mut lo = f64::INFINITY;
+ let mut hi = f64::NEG_INFINITY;
+ for ring in &self.rings {
+ let Some(&last) = ring.last() else { continue };
+ let mut p = last;
+ for &q in ring {
+ let (a, b) = (p, q);
+ p = q;
+ if a.y.max(b.y) < y0 || a.y.min(b.y) > y1 {
+ continue;
+ }
+ let dy = b.y - a.y;
+ let (t0, t1) = if dy.abs() < 1e-12 {
+ (0.0, 1.0)
+ } else {
+ let (ta, tb) = ((y0 - a.y) / dy, (y1 - a.y) / dy);
+ (ta.min(tb).clamp(0.0, 1.0), ta.max(tb).clamp(0.0, 1.0))
+ };
+ for t in [t0, t1] {
+ let x = a.x + t * (b.x - a.x);
+ lo = lo.min(x);
+ hi = hi.max(x);
+ }
+ }
+ }
+ (lo <= hi).then_some((lo - self.offset, hi + self.offset))
+ }
+}
+
+/// The wrap exclusion of `other` (an item whose inner space maps to the spread by `xf`) for a
+/// frame whose inner space is reached from the spread by `inv`. `left_page` places the object on
+/// a left page (for the spine sides).
+pub fn exclusion(other: &Item, xf: Affine, inv: Affine, left_page: bool) -> Exclusion {
+ let group = other.shape == designcraft_doc::Shape::Group;
+ let b =
+ if group { (xf * other.xf.inverse()).transform_rect_bbox(other.bounds()) } else { other.path.transformed(xf).bounds().unwrap_or(Rect::ZERO) };
+ wrap_exclusion(&other.wrap, b, || (!group).then(|| contour_path(other, other.wrap.contour)), xf, inv, left_page)
+}
+
+/// The wrap exclusion of the graphic placed in frame `it` (arguments as for [`exclusion`]): around
+/// the part of the graphic the frame shows. None if there is no graphic or it is not shown.
+pub fn graphic_exclusion(it: &Item, xf: Affine, inv: Affine, left_page: bool) -> Option<Exclusion> {
+ let g = it.graphic()?;
+ let shown = g.shown_bounds(it.inner_bounds())?;
+ Some(wrap_exclusion(&g.wrap, xf.transform_rect_bbox(shown), || Some(contour_path(it, g.wrap.contour)), xf, inv, left_page))
+}
+
+/// The exclusion of `wrap` around an object with spread-space bounds `b`; `outline` gives its
+/// contour in the inner space `xf` maps to the spread (None: around the bounds).
+fn wrap_exclusion(
+ wrap: &designcraft_doc::TextWrap,
+ b: Rect,
+ outline: impl FnOnce() -> Option<designcraft_geom::BezPath>,
+ xf: Affine,
+ inv: Affine,
+ left_page: bool,
+) -> Exclusion {
+ let o = wrap.offsets;
+ let r = Rect::new(b.x0 - o[1], b.y0 - o[0], b.x1 + o[3], b.y1 + o[2]);
+ let side = match wrap.side {
+ WrapSide::TowardsSpine if left_page => WrapSide::RightSide,
+ WrapSide::TowardsSpine => WrapSide::LeftSide,
+ WrapSide::AwayFromSpine if left_page => WrapSide::LeftSide,
+ WrapSide::AwayFromSpine => WrapSide::RightSide,
+ s => s,
+ };
+ // A custom boundary already includes the offsets.
+ if let Some(custom) = wrap.path.as_ref().and_then(|p| Contour::of(&p.to_bezpath(), inv * xf, 0.0)) {
+ let rect = custom.bounds();
+ let contour = matches!(wrap.mode, WrapMode::BoundingBox | WrapMode::Contour).then_some(custom);
- return Exclusion { rect, mode: wrap.mode, side, contour };
++ return Exclusion { rect, mode: wrap.mode, side, contour, after: None };
+ }
+ let contour = if wrap.mode == WrapMode::Contour { outline() } else { None }.and_then(|path| Contour::of(&path, inv * xf, o[0]));
+ let rect = contour.as_ref().map_or_else(|| inv.transform_rect_bbox(r), Contour::bounds);
- Exclusion { rect, mode: wrap.mode, side, contour }
++ Exclusion { rect, mode: wrap.mode, side, contour, after: None }
+}
+
+/// The outline a contour wrap of `kind` around frame `it` follows, in the frame's inner space.
+/// Bounding Box follows the part of the placed graphic the frame shows; Same As Clipping follows
+/// the graphic's clipping path when it has one; detected edges, alpha channels and image paths need
+/// the image, so they follow the frame's path (as other frames do).
+fn contour_path(it: &Item, kind: designcraft_doc::ContourType) -> designcraft_geom::BezPath {
+ if kind == designcraft_doc::ContourType::SameAsClipping
+ && let Some((path, _)) = it.graphic().and_then(|g| g.clip_region())
+ {
+ return path;
+ }
+ if kind == designcraft_doc::ContourType::BoundingBox
+ && let Some(r) = it.graphic().and_then(|g| g.shown_bounds(it.inner_bounds()))
+ {
+ return designcraft_geom::kurbo::Shape::to_path(&r, 0.1);
+ }
+ designcraft_geom::corners::apply(&it.path, &it.corners)
+}
+
/// One frame of the thread, ready for composition.
#[derive(Clone, Debug)]
pub struct FrameSpec {
@@@ -1347,48 -951,6 +1358,49 @@@ fn compose_with_db(doc: &Document, stor
}
}
}
+ // A line a wrap pushes down moves by whole grid lines, keeping its place in its band.
+ let on_grid = baseline;
+ let snap = |y: f64| grid.map_or(y, |(_, inc)| on_grid + ((y - on_grid) / inc - 1e-6).ceil().max(0.0) * inc);
+ // Wrap: push the line down to the first position with a slot (back on the grid).
+ // Segments after the first are carried to the next lines of the paragraph.
+ if !f.exclusions.is_empty() {
+ let jump = cur.jump(f, advance, asc, tops);
++ let line_start = glyphs.get(s).map_or(prange.start, |g| g.byte);
+ let mut tries = 0;
+ loop {
- let Some((nb, segs)) = wrap_slot(f, col, baseline, asc, desc, jump, base_size, rtl) else {
++ let Some((nb, segs)) = wrap_slot(f, col, baseline, asc, desc, jump, base_size, rtl, line_start) else {
+ // No room in this column.
+ baseline = baseline.max(col.y1) + 1.0;
+ carry.clear();
+ break;
+ };
+ let pushed = nb > baseline;
+ baseline = nb;
+ if let Some((&first, rest)) = segs.split_first() {
+ (x0, x1) = first;
+ carry = rest.to_vec();
+ }
+ tries += 1;
+ if !pushed || grid.is_none() || tries > 4000 {
+ break;
+ }
+ baseline = snap(baseline);
+ }
+ }
+ grid_end = grid_end.map(|end| end + baseline - on_grid);
+ carry_baseline = baseline;
+ carry_grid = grid_end;
+ }
+ // The breaker set this line for another segment width: re-break the rest of the
+ // paragraph from here, starting with this line's segments as they are. A pass
+ // re-breaks at its first line only for a new line, whose segments it carries, so
+ // every re-break makes progress; their number is capped too.
+ if (k > 0 || !continues) && rebreaks < 256 && slots.get(k).is_some_and(|&(a, b)| ((b - a) - (x1 - x0)).abs() > 0.5) {
+ rebreaks += 1;
+ carry.insert(0, (x0, x1));
+ g0 = s;
+ moved = true;
+ break;
}
let capped = cur.split.is_none() && line_cap[pi] == Some(line_no) && line_no > col_first_line;
// Footnotes referenced on this line need room at the bottom of the column too
@@@ -2640,163 -2087,69 +2667,179 @@@ 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`, and those segments (see [`free_slots`], never empty); None if there are
- /// none above the column bottom.
++/// 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) -> Option<(f64, Vec<(f64, f64)>)> {
++fn wrap_slot(
++ f: &FrameSpec,
++ col: Rect,
++ baseline: f64,
++ asc: f64,
++ desc: f64,
++ jump: Jump,
++ size: f64,
++ rtl: bool,
++ line_start: usize,
++) -> 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)
++ .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 {
- let segs = free_slots(f, col, b - asc, b + desc, size, rtl);
++ let segs = free_slots(f, col, b - asc, b + desc, size, rtl, line_start);
+ 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).filter(|e| e.rect.y0 < y1 && e.rect.y1 > y0);
++ 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
}
-/// The widest free stretch of `col` between `y0` and `y1` for a line starting at story byte
-/// `line_start` (`None`: the line must move down).
-fn free_slot(f: &FrameSpec, col: Rect, y0: f64, y1: f64, size: f64, line_start: usize) -> 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).
- fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, size: f64, rtl: bool) -> Vec<(f64, f64)> {
++/// 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`]).
++#[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)];
- for ex in &f.exclusions {
- for ex in f.exclusions.iter().filter(|e| e.after.is_none_or(|a| a < line_start)) {
++ 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 => {
- 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 };
+ // 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 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![];
}
// Rough upper bound on lines: total advance / column width × 2.
let total: f64 = glyphs.iter().map(|g| g.adv).sum();
let n = ((total / (col.width().max(10.0) * 0.5)).ceil() as usize + 2).min(2000);
- let mut v = Vec::with_capacity(n);
+ let mut v = Vec::with_capacity(n + carry.len());
+ v.extend_from_slice(carry);
let mut b = first;
+ let mut jump = jump;
+ // Own-story anchored objects whose anchor is in these lines wrap only the lines after it: the
+ // rest is broken again once that line is set.
+ let line_start = glyphs.first().map_or(0, |g| g.byte);
- for _ in 0..n {
- let mut tries = 0;
- let slot = loop {
- if let Some(s) = free_slot(f, col, b - size * 0.8, b + size * 0.25, size, line_start) {
- break s;
+ while v.len() < n + carry.len() {
- let slots = match wrap_slot(f, col, b, size * 0.8, size * 0.25, jump, size, rtl) {
++ let slots = match wrap_slot(f, col, b, size * 0.8, size * 0.25, jump, size, rtl, line_start) {
+ Some((nb, s)) => {
+ b = nb;
+ s
}
- b += 1.0;
- tries += 1;
- if b > col.y1 || tries > 4000 {
- break (col.x0, col.x1);
+ None => {
+ b = b.max(col.y1);
+ vec![(col.x0, col.x1)]
}
};
- v.push(slot);
+ v.extend(slots);
b += lead;
+ jump = Jump { top: lead, step: lead };
}
v
}
diff --cc crates/compose/src/tests.rs
index 5a0c215e7,5af4e83a6..26c170cc7
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@@ -146,355 -146,6 +146,355 @@@ fn wrap_pushes_text_aside()
assert!(below.x0 < 1.0);
}
+/// 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 };
++ 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}");
+}
+
+#[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.
@@@ -5485,611 -2789,117 +5485,726 @@@ fn empty_paragraphs_get_no_bullet_or_nu
}
}
+#[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");
+}
+
+#[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 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]
+fn shatai_matches_the_measured_matrices() {
+ use crate::shatai::Shatai;
+ let close = |a: [f64; 4], b: [f64; 4]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3);
+ let plain = Shatai { magnification: 0.2, angle: 60.0, adjust_rotation: false, adjust_tsume: false };
+ assert!(close(plain.linear(true), [0.850, 0.0866, 0.0866, 0.950]), "{:?}", plain.linear(true));
+ let turned = Shatai { magnification: 0.1, angle: 60.0, adjust_rotation: true, adjust_tsume: false };
+ assert!(close(turned.linear(true), [0.9222, 0.0843, 0.0, 0.9759]), "{:?}", turned.linear(true));
+ // In horizontal text the turn keeps the glyph's horizontal axis horizontal.
+ assert!(turned.linear(false)[1].abs() < 1e-12);
+}
+
+#[test]
+fn shatai_slants_glyphs_about_their_em_centre_and_fits_the_advance() {
+ let (mut d, sid, _) = doc_with("AB", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());
+ let glyph = |d: &Document| {
+ let cs = compose_story(d, sid, &ComposeOptions::default());
+ let l = cs.frames[0].lines[0].clone();
+ (cs.styles[l.glyphs[0].style as usize].clone(), l.glyphs[0].clone(), l.baseline)
+ };
+ let (_, before, _) = glyph(&d);
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {
+ f.over.shatai_magnification = Some(20.0);
+ f.over.shatai_angle = Some(60.0);
+ f.over.shatai_adjust_tsume = Some(false);
+ });
+ let (style, g, baseline) = glyph(&d);
+ assert!((g.adv - before.adv).abs() < 1e-9, "without Adjust Tsume the advance stays");
+ let xf = style.shatai_xf(&g, baseline).unwrap();
+ // y down: the off-diagonal terms change sign.
+ let [a, b, c, dd, _, _] = xf.as_coeffs();
+ assert!((a - 0.85).abs() < 1e-3 && (b + 0.0866).abs() < 1e-3 && (c + 0.0866).abs() < 1e-3 && (dd - 0.95).abs() < 1e-3);
+ let (top, bottom) = g.face.em_box();
+ let centre = Point::new(g.x + g.face.advance(g.gid) * g.sx / 2.0, baseline + g.y - (top + bottom) / 2.0 * g.sy);
+ assert!((xf * centre - centre).hypot() < 1e-9, "the em box centre stays put");
+ // Adjust Tsume: the advance becomes the compressed em box's width.
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.shatai_adjust_tsume = Some(true));
+ let (style, fitted, _) = glyph(&d);
+ let sh = style.shatai.unwrap();
+ let w = g.face.advance(g.gid) * g.sx;
+ let want = before.adv + w * (sh.extent(false, w, (top - bottom) * g.sy) - 1.0);
+ assert!((fitted.adv - want).abs() < 1e-9, "{} vs {want}", fitted.adv);
+ // No shatai without magnification.
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.shatai_magnification = Some(0.0));
+ assert!(glyph(&d).0.shatai.is_none());
+}
+
+#[test]
+fn auto_tate_chu_yoko_takes_short_digit_runs_in_vertical_text() {
+ let text = "令和12年と1234年と123";
+ let (mut d, sid, _) = doc_with(text, Rect::new(100.0, 100.0, 200.0, 400.0), ParaAttrs { auto_tcy: Some(3), ..Default::default() });
+ let glyphs = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();
+ assert!(glyphs(&d).iter().all(|g| g.tcy.is_none()), "horizontal text has none");
+ d.story_mut(sid).unwrap().vertical = true;
+ let gs = glyphs(&d);
+ let at = |s: &str| text.find(s).unwrap();
+ let tcy: Vec<&PlacedGlyph> = gs.iter().filter(|g| g.tcy.is_some()).collect();
+ let two = at("12年");
+ let three = text.rfind("123").unwrap();
+ assert_eq!(tcy.iter().map(|g| g.byte).collect::<Vec<_>>(), [two, two + 1, three, three + 1, three + 2], "2 and 3 digits, not 4");
+ // Each group takes one em along the line; three digits are narrowed to fit across it.
+ let em = tcy[0].tcy.unwrap()[2];
+ assert!((tcy[..2].iter().map(|g| g.adv).sum::<f64>() - em).abs() < 1e-6);
+ let plain = gs.iter().find(|g| g.byte == at("1234")).unwrap();
+ assert!(tcy[2].sx < plain.sx, "{} {}", tcy[2].sx, plain.sx);
+ let [_, left, _] = tcy[2].tcy.unwrap();
+ assert!(left >= -em / 2.0 - 1e-6, "the narrowed group stays within the em");
+ // Roman letters too, with Include Roman.
+ let text2 = "縦AB横";
+ let (mut d, sid, _) = doc_with(text2, Rect::new(100.0, 100.0, 200.0, 400.0), ParaAttrs { auto_tcy: Some(2), ..Default::default() });
+ d.story_mut(sid).unwrap().vertical = true;
+ let count = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.iter().filter(|g| g.tcy.is_some()).count();
+ assert_eq!(count(&d), 0);
+ d.story_mut(sid).unwrap().paras[0].para.auto_tcy_include_roman = Some(true);
+ assert_eq!(count(&d), 2);
+}
+
+#[test]
+fn rotate_roman_stands_half_width_characters_upright() {
+ let (mut d, sid, _) = doc_with("縦書きLatin", Rect::new(100.0, 100.0, 200.0, 400.0), ParaAttrs::default());
+ d.story_mut(sid).unwrap().vertical = true;
+ let latin_upright = |d: &Document| {
+ let cs = compose_story(d, sid, &ComposeOptions::default());
+ cs.frames[0].lines[0].glyphs.iter().filter(|g| g.len > 0 && g.byte >= "縦書き".len()).all(|g| g.upright)
+ };
+ assert!(!latin_upright(&d));
+ d.story_mut(sid).unwrap().paras[0].para.rotate_roman = Some(true);
+ assert!(latin_upright(&d));
+}
+
+#[test]
+fn roman_word_break_breaks_inside_words_without_hyphens() {
+ let para = ParaAttrs { composer: Some(designcraft_doc::Composer::SingleLine), hyphenate: Some(false), ..Default::default() };
+ let first_line = |rwb: bool| {
+ let (d, sid, _) = doc_with("ab cdefghijklm", Rect::new(0.0, 0.0, 40.0, 300.0), ParaAttrs { roman_word_break: Some(rwb), ..para.clone() });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ assert!(lines.iter().all(|l| !l.hyphenated && l.end_x <= l.x1 + 0.5));
+ lines[0].range.clone()
+ };
+ assert_eq!(first_line(false), 0..3, "the word moves down whole");
+ assert!(first_line(true).end > 3, "the line fills with part of the word");
+}
+
+/// Composed lines of a story in a frame with a 12 pt baseline grid; returns them and the grid.
+fn grid_doc(text: &str, para: ParaAttrs, edit: impl FnOnce(&mut Document, StoryId)) -> (Vec<Line>, (f64, f64)) {
+ let (mut d, sid, fid) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 400.0), para);
+ if let Some(tf) = d.item_mut(fid).and_then(|i| i.text_frame_mut()) {
+ tf.options.baseline_grid = Some((12.0, 0.0));
+ }
+ edit(&mut d, sid);
+ // Vertical frames have no baseline grid.
+ let grid = frame_specs(&d, sid)[0].grid.unwrap_or((0.0, 12.0));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ (all_lines(&cs).into_iter().cloned().collect(), grid)
+}
+
+/// The em box centre of a line's first glyph (as the composer measures it), y down.
+fn em_centre(l: &Line) -> f64 {
+ let g = &l.glyphs[0];
+ let (a, b) = g.face.vertical_metrics();
+ l.baseline + g.y + (b - a) / (2.0 * (a + b)) * g.face.units_per_em() * g.sy
+}
+
+fn on_grid(y: f64, (start, inc): (f64, f64)) -> bool {
+ let n = (y - start) / inc;
+ (n - n.round()).abs() < 1e-6
+}
+
+#[test]
+fn grid_alignment_puts_the_chosen_point_on_the_grid() {
+ use designcraft_doc::cjk::CharacterAlignment as R;
+ let para = |r: R| ParaAttrs { grid_align: Some(designcraft_doc::GridAlign::AllLines), grid_reference: Some(r), ..Default::default() };
+ let (roman, grid) = grid_doc("AB\nCD", para(R::Baseline), |_, _| {});
+ assert!(roman.iter().all(|l| on_grid(l.baseline, grid)));
+ let (centred, grid) = grid_doc("AB\nCD", para(R::EmCenter), |_, _| {});
+ assert!(centred.iter().all(|l| on_grid(em_centre(l), grid)));
+ assert!(!on_grid(centred[0].baseline, grid), "the baseline moves off the grid by the em centre's offset");
+ let offset = em_centre(&centred[0]) - centred[0].baseline;
+ let shift = centred[0].baseline - roman[0].baseline;
+ assert!(on_grid(shift + offset, (0.0, grid.1)), "{shift} {offset}");
+}
+
+#[test]
+fn gyoudori_two_lines_centres_a_heading_in_two_grid_lines() {
+ use designcraft_doc::cjk::CharacterAlignment as R;
+ let para = ParaAttrs { grid_align: Some(designcraft_doc::GridAlign::AllLines), grid_reference: Some(R::EmCenter), ..Default::default() };
+ let (lines, grid) = grid_doc("Head\nBody text", para, |d, sid| {
+ let st = d.story_mut(sid).unwrap();
+ st.format_chars(0..4, |f| f.over.size = Some(18.0));
+ st.format_paras(0..4, |p| p.para.grid_gyoudori = Some(2));
+ });
+ let (head, body) = (em_centre(&lines[0]), em_centre(&lines[1]));
+ assert!(on_grid(head - grid.1 / 2.0, grid), "midway between two grid lines: {head}");
+ assert!(on_grid(body, grid));
+ assert!((body - head - 1.5 * grid.1).abs() < 1e-6, "the body takes the grid line after the heading's two: {head} {body}");
+}
+
+#[test]
+fn paragraph_gyoudori_centres_the_whole_paragraph() {
+ use designcraft_doc::cjk::CharacterAlignment as R;
+ let para = ParaAttrs {
+ grid_align: Some(designcraft_doc::GridAlign::AllLines),
+ grid_reference: Some(R::EmCenter),
+ grid_gyoudori: Some(4),
+ paragraph_gyoudori: Some(true),
+ ..Default::default()
+ };
+ let (lines, grid) = grid_doc("One\u{2028}Two\nNext", para, |d, sid| {
+ d.story_mut(sid).unwrap().format_paras(10..14, |p| {
+ p.para.grid_gyoudori = Some(0);
+ p.para.paragraph_gyoudori = Some(false);
+ });
+ });
+ let firsts: Vec<f64> = lines.iter().map(em_centre).collect();
+ assert_eq!(lines.len(), 3, "{firsts:?}");
+ // Two lines a leading apart, centred as a block in four grid lines; the next paragraph on the fifth.
+ let middle = (firsts[0] + firsts[1]) / 2.0;
+ assert!(on_grid(middle - 1.5 * grid.1, grid), "{firsts:?}");
+ assert!((firsts[2] - (middle - 1.5 * grid.1) - 4.0 * grid.1).abs() < 1e-6, "{firsts:?}");
+}
+
+#[test]
+fn hostile_cjk_settings_compose_without_panicking() {
+ let para = ParaAttrs {
+ auto_tcy: Some(u32::MAX),
+ auto_tcy_include_roman: Some(true),
+ rotate_roman: Some(true),
+ roman_word_break: Some(true),
+ grid_align: Some(designcraft_doc::GridAlign::AllLines),
+ grid_reference: Some(designcraft_doc::cjk::CharacterAlignment::IcfBottom),
+ grid_gyoudori: Some(u32::MAX),
+ paragraph_gyoudori: Some(true),
+ ..Default::default()
+ };
+ for vertical in [false, true] {
+ let (_, _) = grid_doc("縦12AB書き\nmore text here", para.clone(), |d, sid| {
+ let st = d.story_mut(sid).unwrap();
+ st.vertical = vertical;
+ let len = st.len();
+ st.format_chars(0..len, |f| {
+ f.over.kenten = Some(true);
+ f.over.kenten_kind = Some(designcraft_doc::cjk_settings::KentenKind::Custom);
+ f.over.kenten_character = Some("★".repeat(100_000));
+ f.over.kenten_font = Some("No Such Font".into());
+ f.over.kenten_size = Some(Some(1e308));
+ f.over.kenten_x_scale = Some(-1e308);
+ f.over.kenten_y_scale = Some(f64::NAN);
+ f.over.kenten_distance = Some(f64::INFINITY);
+ f.over.kenten_fill_tint = Some(Some(f32::NAN));
+ f.over.kenten_stroke_weight = Some(Some(-1e308));
+ f.over.shatai_magnification = Some(1e308);
+ f.over.shatai_angle = Some(f64::NEG_INFINITY);
+ });
+ });
+ }
+}
++
+ /// A 100×60 rectangle anchored at `at` in `sid`, custom-positioned with its top-left at
+ /// (`x`, `y`) from the top-left of the anchor's frame (`y_rel`: from the anchor's baseline).
+ fn anchor_box(d: &mut Document, sid: StoryId, at: usize, x: f64, y: f64, y_rel: bool, wrap: WrapMode) {
+ use designcraft_doc::anchored::AnchorRelative as R;
+ let lid = d.default_layer();
+ let mut it = designcraft_doc::Item::new(
+ ItemId(d.alloc()),
+ lid,
+ designcraft_doc::Shape::Rectangle,
+ designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 60.0)),
+ );
+ it.wrap.mode = wrap;
+ let position = designcraft_doc::AnchorPosition::Custom {
+ x_relative: R::TextFrame,
+ y_relative: if y_rel { R::Anchor } else { R::TextFrame },
+ x_offset: x,
+ y_offset: y,
+ object_point: 0,
+ ref_point: 0,
+ keep_within_column: false,
+ };
+ d.story_mut(sid).unwrap().insert_object(at, designcraft_doc::AnchoredObject::new(it, position));
+ }
+
+ /// Lines whose band meets `y0..y1`.
+ fn lines_in_band(cs: &ComposedStory, y0: f64, y1: f64) -> Vec<&Line> {
+ all_lines(cs).into_iter().filter(|l| l.baseline - l.ascent < y1 && l.baseline + l.descent > y0).collect()
+ }
+
+ fn line_layout(cs: &ComposedStory) -> Vec<(Range<usize>, u64, u64, u64)> {
+ all_lines(cs).iter().map(|l| (l.range.clone(), l.baseline.to_bits(), l.x0.to_bits(), l.x1.to_bits())).collect()
+ }
+
+ #[test]
+ fn anchored_object_wraps_another_storys_text() {
+ let long = [LOREM; 3].join(" ");
+ let (mut d, a, fa) = doc_with("Anchor here.", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default());
+ let lid = d.default_layer();
+ let (_, b) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 0.0, 620.0, 400.0), lid, &long, ParaFormat::default()).unwrap();
+ let plain = compose_story(&d, b, &ComposeOptions::default());
+ let left = all_lines(&plain)[0].x0;
+ // Over the left part of B's frame, 100–160 pt down.
+ let area = d.item(fa).unwrap().text_area();
+ anchor_box(&mut d, a, 0, left - area.x0, 100.0 - area.y0, false, WrapMode::BoundingBox);
+ let cs = compose_story(&d, b, &ComposeOptions::default());
+ let band = lines_in_band(&cs, 100.0, 160.0);
+ assert!(!band.is_empty());
+ assert!(band.iter().all(|l| l.x0 >= left + 100.0 - 1e-6), "{:?}", band.iter().map(|l| l.x0).collect::<Vec<_>>());
+ assert!(lines_in_band(&cs, 0.0, 80.0).iter().all(|l| (l.x0 - left).abs() < 1e-6));
+ // The cache composes the same, and follows the object when it moves.
+ let cache = Cache::new();
+ assert_eq!(line_layout(&cache.get(&d, b, None)), line_layout(&cs));
+ anchor_box(&mut d, a, 0, left - area.x0, 200.0 - area.y0, false, WrapMode::BoundingBox);
+ let st = d.story_mut(a).unwrap();
+ st.delete(OBJECT_LEN..2 * OBJECT_LEN);
+ let moved = cache.get(&d, b, None);
+ assert_eq!(line_layout(&moved), line_layout(&compose_story(&d, b, &ComposeOptions::default())));
+ assert!(lines_in_band(&moved, 100.0, 160.0).iter().any(|l| (l.x0 - left).abs() < 1e-6));
+ assert!(lines_in_band(&moved, 200.0, 260.0).iter().all(|l| l.x0 >= left + 100.0 - 1e-6));
+ }
+
+ const OBJECT_LEN: usize = designcraft_doc::OBJECT_MARK.len_utf8();
+
+ #[test]
+ fn anchored_object_wraps_its_own_storys_later_lines() {
+ let text = [LOREM; 4].join(" ");
+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 600.0), ParaAttrs::default());
+ let plain = compose_story(&d, sid, &ComposeOptions::default());
+ let left = all_lines(&plain)[0].x0;
+ // Anchored in the third line, hanging from its baseline over the lines below.
+ let at = all_lines(&plain)[2].range.start + 3;
+ anchor_box(&mut d, sid, at, 0.0, 0.0, true, WrapMode::BoundingBox);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ let (li, anchor_line) = lines.iter().enumerate().find(|(_, l)| l.range.contains(&at)).unwrap();
+ let top = anchor_line.baseline;
+ // The anchor line and those above it keep the full measure; the lines under the object move right.
+ assert!(lines[..=li].iter().all(|l| (l.x0 - left).abs() < 1e-6));
+ let under: Vec<_> = lines[li + 1..].iter().filter(|l| l.baseline - l.ascent < top + 60.0).collect();
+ assert!(under.len() >= 2);
+ assert!(under.iter().all(|l| l.x0 >= left + 100.0 - 1e-6), "{:?}", under.iter().map(|l| l.x0).collect::<Vec<_>>());
+ assert!(lines.iter().filter(|l| l.baseline - l.ascent > top + 61.0).all(|l| (l.x0 - left).abs() < 1e-6));
+ // Settled: the object is where the final pass wrapped the text around.
+ let o = &cs.frames[0].objects[0];
+ assert!((o.origin.y - top).abs() < 1e-6);
+ }
+
+ #[test]
+ fn anchored_object_without_wrap_leaves_layout_unchanged() {
+ let long = [LOREM; 3].join(" ");
+ let (mut d, a, _) = doc_with(&long, Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default());
+ let lid = d.default_layer();
+ let (_, b) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 0.0, 620.0, 400.0), lid, &long, ParaFormat::default()).unwrap();
+ anchor_box(&mut d, a, 40, 330.0, 0.0, true, WrapMode::None);
+ for sid in [a, b] {
+ let direct = compose(&d, d.story(sid).unwrap(), &frame_specs(&d, sid), &ComposeOptions::default());
+ assert_eq!(line_layout(&compose_story(&d, sid, &ComposeOptions::default())), line_layout(&direct));
+ }
+ }
+
+ #[test]
+ fn anchored_wrap_that_moves_its_own_anchor_terminates() {
+ // Jump Object pushes the lines after the anchor below the object; vertical centring then moves
+ // every line, the anchor's too, and the object with it.
+ let text = [LOREM; 2].join(" ");
+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 500.0), ParaAttrs::default());
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Center;
+ let plain = compose_story(&d, sid, &ComposeOptions::default());
+ let at = all_lines(&plain)[1].range.start + 2;
+ anchor_box(&mut d, sid, at, 0.0, -20.0, true, WrapMode::JumpObject);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(cs.line_count() > 0);
+ assert_eq!(cs.frames[0].objects.len(), 1);
+ }
diff --cc crates/render/src/damage.rs
index 487f2da84,cb353479f..31f9757e0
--- a/crates/render/src/damage.rs
+++ b/crates/render/src/damage.rs
@@@ -220,13 -215,36 +228,32 @@@ mod tests
assert!(dmg.iter().any(|(_, r)| r.contains(designcraft_geom::Point::new(350.0, 100.0))));
}
+ #[test]
+ fn editing_a_wrapping_anchored_object_damages_the_text_it_wraps() {
+ let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() });
+ let lid = d.default_layer();
+ let (_, a) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 200.0, 200.0), lid, "Anchor", ParaFormat::default()).unwrap();
+ let (_, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(300.0, 400.0, 500.0, 600.0), lid, "Wrapped", ParaFormat::default()).unwrap();
+ let mut it = designcraft_doc::Item::new(
+ designcraft_doc::ItemId(d.alloc()),
+ lid,
+ designcraft_doc::Shape::Rectangle,
+ designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)),
+ );
+ it.wrap.mode = designcraft_doc::WrapMode::BoundingBox;
+ let old = d.clone();
+ d.story_mut(a).unwrap().insert_object(0, designcraft_doc::AnchoredObject::new(it, Default::default()));
+ let dmg = damage(&old, &d).unwrap();
+ assert!(dmg.iter().any(|(_, r)| r.contains(designcraft_geom::Point::new(400.0, 500.0))));
+ }
+
- #[test]
- fn patched_render_equals_full_render() {
+ /// Channels where `old`'s render patched over `new`'s damage differs from `new`'s full render.
+ fn patched_diff(old: &Document, new: &Document, (w, h): (u32, u32), zoom: f64) -> usize {
use crate::{Placed, RenderOptions, Renderer};
use designcraft_geom::{Affine, Vec2};
- let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() });
- let lid = d.default_layer();
- let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 300.0, 200.0), lid, "Hello there", ParaFormat::default()).unwrap();
let cache = designcraft_compose::Cache::new();
let placed = [Placed { spread: SpreadRef::Doc(0), xf: Affine::translate(Vec2::ZERO) }];
- let (w, h) = (400u32, 300u32);
- let view = Affine::scale(1.3);
+ let view = Affine::scale(zoom);
let mut r = Renderer::new();
r.threads = 0;
let opts = RenderOptions::default();
diff --cc docs/target-app-parity.md
index 8e10cca55,990c0e03b..07a452880
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@@ -1,6 -1,6 +1,6 @@@
# DesignCraft parity with Adobe InDesign
- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (text threads by hand; image clipping paths from IDML) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (anchored objects wrap text) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)
++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (text threads by hand; image clipping paths from IDML; anchored objects wrap text) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)
The authoritative assessment of how close DesignCraft is to Adobe InDesign. [ROADMAP.md](../ROADMAP.md)
summarizes it; [gaps.md](gaps.md) lists every known shortfall one at a time; the feature-by-feature
diff --cc docs/typography-parity.md
index 8b97da9db,ae0bc3192..4a244fdd2
--- a/docs/typography-parity.md
+++ b/docs/typography-parity.md
@@@ -1,6 -1,6 +1,6 @@@
# Typography and composition parity
- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (Optical kerning from outlines (#181); macOS lists fonts that font services and managers activate; Justification dialog for the selected paragraphs) · **Target:** Adobe InDesign 2026 (21.6)
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (anchored objects wrap text) · **Target:** Adobe InDesign 2026 (21.6)
++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (Optical kerning from outlines (#181); macOS lists fonts that font services and managers activate; Justification dialog for the selected paragraphs; anchored objects wrap text) · **Target:** Adobe InDesign 2026 (21.6)
Typesetting is what InDesign is bought for. A feature can exist and still set text differently
from InDesign: different line breaks, different page count, overset where InDesign fits. This
@@@ -56,7 -56,7 +56,7 @@@ Fidelity: **unmeasured** unless stated
| Paragraph rules, borders, shading | ✓ | ✓ | ✓ | |
| Balance ragged lines | ✓ | ✓ | ✓ | |
| Optical margin alignment | ✓ | ✓ (hang table of our own) | ~ | hang amounts are ours, InDesign's unknown |
- | Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options | ✓ | ~ | Detect Edges, Alpha Channel and Photoshop Path contours follow the frame's path (composition doesn't read the image) |
-| Text wrap | bounding box, shape, jump object/column, contour options, on page items and anchored objects | ✓ | ✓ | |
++| Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options, on page items and anchored objects | ✓ | ~ | Detect Edges, Alpha Channel and Photoshop Path contours follow the frame's path (composition doesn't read the image) |
| Anchored objects | inline, above line, custom | ✓ | ~ | anchored objects in table cells not drawn (#163) |
| Footnotes, endnotes | ✓ | ✓ | ~ | footnotes don't split across columns yet |
| Type on a path | ✓ | ✓ | ✓ | |