Skip to content

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

Merge contour-wrap: wrap both sides of an object and around its contour

aiongg17c7bb3fd2f9
diff --cc crates/compose/src/lib.rs
index 3e8f25ec9,30b81c7d6..8e430e47f
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@@ -35,11 -29,11 +35,11 @@@ use std::rc::Rc
use std::sync::{Arc, Mutex};
use designcraft_doc::{
- Align, Composer, Document, FirstBaseline, GridAlign, ItemId, ParaProps, SpanColumns, StartParagraph, Story, StoryId, TabAlign, TextFrameOptions,
- VerticalJustification, WrapMode, WrapSide, story,
+ Align, Content, Document, FirstBaseline, GridAlign, Item, ItemId, ListAlign, ListCounter, ParaProps, SpanColumns, StartParagraph, Story, StoryId,
- TabAlign, TextFrameOptions, VerticalJustification, WrapMode, story,
++ TabAlign, TextFrameOptions, VerticalJustification, WrapMode, WrapSide, story,
};
use designcraft_fonts::{FontDb, ScopedFonts};
-use designcraft_geom::{Point, Rect};
+use designcraft_geom::{Affine, Point, Rect};
use crate::breaker::{Break, Spacing};
pub use crate::cache::Cache;
@@@ -328,8 -287,128 +328,140 @@@ 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: the outline the text follows (None wraps around `rect`).
+ pub contour: Option<Contour>,
+ }
+
+ /// 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: &designcraft_doc::Item, xf: designcraft_geom::Affine, inv: designcraft_geom::Affine, left_page: bool) -> Exclusion {
- let o = other.wrap.offsets;
- let b = if other.shape == designcraft_doc::Shape::Group {
- (xf * other.xf.inverse()).transform_rect_bbox(other.bounds())
- } else {
- other.path.transformed(xf).bounds().unwrap_or(Rect::ZERO)
- };
++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 other.wrap.side {
++ 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,
+ };
- let contour = (other.wrap.mode == WrapMode::Contour && other.shape != designcraft_doc::Shape::Group)
- .then(|| contour_path(other))
- .and_then(|path| Contour::of(&path, inv * xf, other.wrap.offsets[0]));
++ 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: other.wrap.mode, side, contour }
++ Exclusion { rect, mode: wrap.mode, side, contour }
+ }
+
-/// The outline a contour wrap follows, in the item's inner space. Graphic frames follow their contour type; 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: &designcraft_doc::Item) -> designcraft_geom::BezPath {
- let frame = designcraft_geom::corners::apply(&it.path, &it.corners);
- if it.wrap.contour == designcraft_doc::ContourType::BoundingBox
- && let Some(g) = it.graphic()
- && let Some(fb) = it.path.bounds()
++/// 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; 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::BoundingBox
++ && let Some(r) = it.graphic().and_then(|g| g.shown_bounds(it.inner_bounds()))
+ {
- let gb = g.xf.transform_rect_bbox(Rect::new(0.0, 0.0, g.size.0, g.size.1));
- let r = gb.intersect(fb);
- if r.width() > 0.0 && r.height() > 0.0 {
- return designcraft_geom::kurbo::Shape::to_path(&r, 0.1);
- }
++ return designcraft_geom::kurbo::Shape::to_path(&r, 0.1);
+ }
- frame
++ designcraft_geom::corners::apply(&it.path, &it.corners)
}
/// One frame of the thread, ready for composition.
@@@ -385,37 -464,6 +517,34 @@@ pub struct ComposeOptions
pub xrefs: Option<Arc<xref::XrefIndex>>,
}
+/// Nesting depth past which wrap obstacles inside groups are not collected.
+const MAX_WRAP_DEPTH: usize = 64;
+
- /// The text wrap obstacles of a page item, the graphic it holds and the items in it, as
- /// (spread-space box grown by the wrap offsets, mode). `parent` maps the item's parent space to
- /// the spread; `skip` is the text frame being wrapped.
- fn wrap_obstacles(it: &Item, parent: Affine, skip: ItemId, depth: usize, out: &mut Vec<(Rect, WrapMode)>) {
++/// The text wrap exclusions of a page item, the graphic it holds and the items in it, for a frame
++/// whose inner space is reached from the spread by `inv`. `parent` maps the item's parent space to
++/// the spread; `skip` is the text frame being wrapped; `left_page` tells whether a spread x is on
++/// a left page.
++#[allow(clippy::too_many_arguments)]
++fn wrap_obstacles(it: &Item, parent: Affine, inv: Affine, skip: ItemId, left_page: &dyn Fn(f64) -> bool, depth: usize, out: &mut Vec<Exclusion>) {
+ if it.id == skip || it.hidden || depth > MAX_WRAP_DEPTH {
+ return;
+ }
- let grow = |r: Rect, o: [f64; 4]| Rect::new(r.x0 - o[1], r.y0 - o[0], r.x1 + o[3], r.y1 + o[2]);
++ let xf = parent * it.xf;
++ let left = || left_page(parent.transform_rect_bbox(it.bounds()).center().x);
+ if it.wrap.mode != WrapMode::None {
- out.push((grow(parent.transform_rect_bbox(it.bounds()), it.wrap.offsets), it.wrap.mode));
++ out.push(exclusion(it, xf, inv, left()));
+ }
- let xf = parent * it.xf;
+ match &it.content {
- // A wrap on the placed graphic follows the part of it the frame shows.
- Content::Graphic(g) if g.wrap.mode != WrapMode::None => {
- if let Some(r) = g.shown_bounds(it.inner_bounds()) {
- out.push((grow(xf.transform_rect_bbox(r), g.wrap.offsets), g.wrap.mode));
- }
- }
++ Content::Graphic(g) if g.wrap.mode != WrapMode::None => out.extend(graphic_exclusion(it, xf, inv, left())),
+ Content::Group { .. } => {
+ for c in it.shown_children() {
- wrap_obstacles(c, xf, skip, depth + 1, out);
++ wrap_obstacles(c, xf, inv, skip, left_page, depth + 1, out);
+ }
+ }
+ _ => {}
+ }
+}
+
/// Build the frame specs of a story from the document (geometry, wrap, page names, grid).
pub fn frame_specs(doc: &Document, sid: StoryId) -> Vec<FrameSpec> {
let Some(st) = doc.story(sid) else { return vec![] };
@@@ -432,17 -479,22 +561,16 @@@
if !tf.options.ignore_wrap
&& let Some(sp) = spread
{
- let mut obstacles = Vec::new();
++ let left = |x: f64| sp.page_at_x(x).and_then(|pi| sp.pages.get(pi)).is_some_and(|p| p.side == designcraft_doc::PageSide::Left);
for other in &sp.items {
- if other.id == item.id || other.wrap.mode == WrapMode::None || other.hidden {
- continue;
- }
if doc.layer(other.layer).is_some_and(|l| !l.visible) {
continue;
}
- wrap_obstacles(other, Affine::IDENTITY, item.id, 0, &mut obstacles);
- let left = sp
- .page_at_x(other.bounds().center().x)
- .and_then(|pi| sp.pages.get(pi))
- .is_some_and(|p| p.side == designcraft_doc::PageSide::Left);
- exclusions.push(exclusion(other, other.xf, inv, left));
++ wrap_obstacles(other, Affine::IDENTITY, inv, item.id, &left, 0, &mut exclusions);
}
- exclusions.extend(obstacles.into_iter().map(|(r, mode)| Exclusion { rect: inv.transform_rect_bbox(r), mode }));
}
- 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;
@@@ -1035,8 -995,12 +1170,16 @@@ fn compose_with_db(doc: &Document, stor
let has_tabs = glyphs.iter().any(|g| g.ch == '\t');
let mut first_line_rect: Option<(usize, f64, f64, f64)> = None; // frame, baseline, ascent, x-span
let rtl = pp.direction == designcraft_doc::TextDirection::RightToLeft;
+ // Paragraph gyoudori: the (frame, column) of the block and the grid line after it.
+ let mut para_block: Option<((usize, usize), f64)> = None;
+ // Segments of a line already placed (beside an object with text on both sides) that the
+ // next lines of the paragraph fill before a new line starts, and that line's baseline.
+ let mut carry: Vec<(f64, f64)> = Vec::new();
+ let mut carry_baseline = 0.0;
++ // The grid line after the carried line's band (see `grid_end`).
++ let mut carry_grid: Option<f64> = None;
+ // Re-breaks after a line's segment turned out other than the breaker assumed.
+ let mut rebreaks = 0usize;
loop {
if cur.fi >= frames.len() {
if let Some(j) = trial_failed(&mut trial, &mut limits, balance_runs < balance_budget) {
@@@ -1055,22 -1021,12 +1198,23 @@@
let col = if spanning { span_rect(&cols[cur.fi], Rect::new(col.x0, col.y0, col.x1, base.y1), pp.span_columns) } else { col };
let col = cur.split_rect(col);
// Estimate slots for the breaker with the paragraph's base leading.
+ let est_asc = base_chars.size * 0.75;
+ let est_tops = Tops { typo_ascent: est_asc, cap: est_asc * 0.72, xh: est_asc * 0.5, em: base_chars.size * 0.88 };
- let est_first = cur.next_baseline(f, col, base_leading, est_asc, est_tops, &pp);
+ let est_first =
- if carry.is_empty() { cur.next_baseline(f, col, base_leading, base_chars.size * 0.75, &pp) } else { carry_baseline + base_leading };
- let slots = estimate_slots(f, col, est_first, base_leading, base_chars.size, &glyphs[g0..], rtl, &carry);
++ if carry.is_empty() { cur.next_baseline(f, col, base_leading, est_asc, est_tops, &pp) } else { carry_baseline + base_leading };
+ let est_jump = cur.jump(f, base_leading, est_asc, est_tops);
- let slots = estimate_slots(f, col, est_first, est_jump, base_leading, base_chars.size, &glyphs[g0..], &pp, line_no);
++ let slots = estimate_slots(f, col, est_first, est_jump, base_leading, base_chars.size, &glyphs[g0..], rtl, &carry);
let width = |j: usize| -> f64 {
let (x0, x1) = slots.get(j).copied().unwrap_or((col.x0, col.x1));
- let ind = pp.left_indent + pp.right_indent + if line_no + j == 0 { pp.first_line_indent } else { 0.0 };
+ // Beside the drop cap (in the column the paragraph starts in), its width; else the
+ // first-line indent.
+ let ind = pp.left_indent
+ + pp.right_indent
+ + match &drop_cap {
+ Some(dc) if line_no + j < dc.lines && col_first_line == 0 => dc.indent(),
+ _ if line_no + j == 0 => pp.first_line_indent,
+ _ => 0.0,
+ };
(x1 - x0 - ind).max(1.0)
};
let rest = &glyphs[g0..];
@@@ -1104,90 -1048,62 +1248,119 @@@
for (k, b) in breaks.iter().enumerate() {
let (s, e) = (g0 + b.start, g0 + b.end);
let line_glyphs = &glyphs[s..e.max(s)];
- let (asc, desc, lead) = line_metrics(line_glyphs, &glyphs, s, base_leading, base_chars.size, db, &base_chars);
- let reference = cjk_line_reference(line_glyphs);
+ let (asc, tops, desc, lead) = line_metrics(line_glyphs, &glyphs, s, mark_leading, mark_chars.size, db, &mark_chars);
+ let lead = match last_line_mark {
+ Some(m) if k + 1 == breaks.len() => lead.max(m),
+ _ => lead,
+ };
+ let (reference, model) = cjk_line_reference(line_glyphs);
+ let advance = if cur.last_baseline.is_some() { cur.aki_below.unwrap_or(lead) } else { lead };
- let mut baseline = cur.next_baseline(f, col, advance, asc, tops, &pp);
- if cur.last_baseline.is_some() {
- baseline += cur.last_reference - reference;
- }
- // Baseline grid: grid alignment and gyoudori (see `grid`).
- let grid = f.grid.filter(|&(_, inc)| {
- inc > 0.0
- && inc.is_finite()
- && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0))
- });
+ let (mut x0, mut x1) = (col.x0, col.x1);
+ let continues = !carry.is_empty();
+ let mut baseline;
+ let mut grid_end = None;
- if let Some((g_start, inc)) = grid {
- let n = pp.grid_gyoudori.min(grid::MAX_GYOUDORI);
- match para_block.filter(|(at, _)| line_no > 0 && *at == (cur.fi, cur.col)) {
- // Inside a paragraph-gyoudori block, lines after the first keep their leading.
- Some((_, end)) => grid_end = Some(end),
- None => {
- let r = grid::reference_offset(line_glyphs, pp.grid_reference);
- let block = n > 0 && pp.paragraph_gyoudori && line_no == 0;
- let span = if block {
- // From this line's reference point to the paragraph's last line's.
- let aki_below = |model, lead| (model == designcraft_doc::cjk::LeadingModel::AkiBelow).then_some(lead);
- let (mut down, mut prev, mut prev_aki, mut last_r) = (0.0, reference, aki_below(model, lead), r);
- for (j, nb) in breaks.iter().enumerate().skip(k + 1) {
- let (ns, ne) = (g0 + nb.start, g0 + nb.end);
- let lg = glyphs.get(ns..ne.max(ns)).unwrap_or_default();
- let (_, _, _, nlead) = line_metrics(lg, &glyphs, ns, mark_leading, mark_chars.size, db, &mark_chars);
- let nlead = match last_line_mark {
- Some(m) if j + 1 == breaks.len() => nlead.max(m),
- _ => nlead,
- };
- let (nref, nmodel) = cjk_line_reference(lg);
- down += prev_aki.unwrap_or(nlead) + prev - nref;
- prev = nref;
- prev_aki = aki_below(nmodel, nlead);
- last_r = grid::reference_offset(lg, pp.grid_reference);
+ if continues {
+ // The next segment of a line already placed.
+ baseline = carry_baseline;
++ grid_end = carry_grid;
+ (x0, x1) = carry.remove(0);
+ } else {
+ carry.clear();
- baseline = cur.next_baseline(f, col, lead, asc, &pp);
++ baseline = cur.next_baseline(f, col, advance, asc, tops, &pp);
+ if cur.last_baseline.is_some() {
+ baseline += cur.last_reference - reference;
+ }
- // Baseline grid.
- if let Some((g_start, inc)) = f.grid
- && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0))
- && inc > 0.0
- {
- let n = ((baseline - g_start) / inc - 1e-6).ceil();
- baseline = g_start + n * inc;
++ // Baseline grid: grid alignment and gyoudori (see `grid`).
++ let grid = f.grid.filter(|&(_, inc)| {
++ inc > 0.0
++ && inc.is_finite()
++ && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0))
++ });
++ if let Some((g_start, inc)) = grid {
++ let n = pp.grid_gyoudori.min(grid::MAX_GYOUDORI);
++ match para_block.filter(|(at, _)| line_no > 0 && *at == (cur.fi, cur.col)) {
++ // Inside a paragraph-gyoudori block, lines after the first keep their leading.
++ Some((_, end)) => grid_end = Some(end),
++ None => {
++ let r = grid::reference_offset(line_glyphs, pp.grid_reference);
++ let block = n > 0 && pp.paragraph_gyoudori && line_no == 0;
++ let span = if block {
++ // From this line's reference point to the paragraph's last line's.
++ let aki_below = |model, lead| (model == designcraft_doc::cjk::LeadingModel::AkiBelow).then_some(lead);
++ let (mut down, mut prev, mut prev_aki, mut last_r) = (0.0, reference, aki_below(model, lead), r);
++ for (j, nb) in breaks.iter().enumerate().skip(k + 1) {
++ let (ns, ne) = (g0 + nb.start, g0 + nb.end);
++ let lg = glyphs.get(ns..ne.max(ns)).unwrap_or_default();
++ let (_, _, _, nlead) = line_metrics(lg, &glyphs, ns, mark_leading, mark_chars.size, db, &mark_chars);
++ let nlead = match last_line_mark {
++ Some(m) if j + 1 == breaks.len() => nlead.max(m),
++ _ => nlead,
++ };
++ let (nref, nmodel) = cjk_line_reference(lg);
++ down += prev_aki.unwrap_or(nlead) + prev - nref;
++ prev = nref;
++ prev_aki = aki_below(nmodel, nlead);
++ last_r = grid::reference_offset(lg, pp.grid_reference);
++ }
++ (down + last_r - r).max(0.0)
++ } else {
++ 0.0
++ };
++ let lines = if block { grid::lines_for(span, inc, n) } else { n.max(1) };
++ let free = cur.grid_next.filter(|(b, _)| cur.last_baseline == Some(*b)).map(|(_, y)| y);
++ let band = grid::Band { natural: baseline + r, free, pending: cur.pending, fixed: n > 0, lines, span };
++ let (y, end) = grid::place((g_start, inc), pp.grid_reference, band);
++ baseline = y - r;
++ grid_end = Some(end);
++ if block {
++ para_block = Some(((cur.fi, cur.col), end));
+ }
- (down + last_r - r).max(0.0)
- } else {
- 0.0
- };
- let lines = if block { grid::lines_for(span, inc, n) } else { n.max(1) };
- let free = cur.grid_next.filter(|(b, _)| cur.last_baseline == Some(*b)).map(|(_, y)| y);
- let band = grid::Band { natural: baseline + r, free, pending: cur.pending, fixed: n > 0, lines, span };
- let (y, end) = grid::place((g_start, inc), pp.grid_reference, band);
- baseline = y - r;
- grid_end = Some(end);
- if block {
- para_block = Some(((cur.fi, cur.col), end));
+ }
+ }
}
- }
- // 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).
- let (mut x0, mut x1) = (col.x0, col.x1);
- if !f.exclusions.is_empty() {
- let jump = cur.jump(f, advance, asc, tops);
- let mut tries = 0;
- loop {
- let Some((nb, (a, z))) = wrap_slot(f, col, baseline, asc, desc, jump, base_size) else {
- // No room in this column.
- baseline = baseline.max(col.y1) + 1.0;
- break;
- };
- let pushed = nb > baseline;
- (baseline, x0, x1) = (nb, a, z);
- tries += 1;
- if !pushed || grid.is_none() || tries > 4000 {
- break;
- // Wrap: push the line down until a slot exists.
++ // 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 mut tries = 0;
+ loop {
- let segs = free_slots(f, col, baseline - asc, baseline + desc, base_size, rtl);
++ let Some((nb, segs)) = wrap_slot(f, col, baseline, asc, desc, jump, base_size, rtl) 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();
- carry_baseline = baseline;
- break;
+ }
- baseline += 1.0;
+ tries += 1;
- if baseline > col.y1 || tries > 4000 {
++ if !pushed || grid.is_none() || tries > 4000 {
+ break;
+ }
++ baseline = snap(baseline);
}
- 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));
- if !continues {
- carry_baseline = baseline;
- }
+ g0 = s;
+ moved = true;
+ break;
}
- grid_end = grid_end.map(|end| end + baseline - on_grid);
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
// (a line at the top of a column is set anyway).
@@@ -1393,9 -1255,10 +1568,10 @@@
&& k + 1 < breaks.len()
&& let Some(start) = brk.and_then(break_start)
{
- begin_at(&mut cur, start);
+ go(&mut cur, start);
col_first_line = line_no;
g0 += b.next;
+ carry.clear();
moved = true;
break;
}
@@@ -2424,139 -2227,91 +2600,164 @@@ 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 a
- /// free slot in `col`, and that slot; None if there is none above the column bottom.
++/// 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.
+///
- /// A line under a Jump Object wrap moves below it as `jump` says. Other wraps are rectangles, so the
++/// 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.
- fn wrap_slot(f: &FrameSpec, col: Rect, baseline: f64, asc: f64, desc: f64, jump: Jump, size: f64) -> Option<(f64, (f64, f64))> {
++/// 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)>)> {
+ 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)
+ .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 if let Some(slot) = free_slot(f, col, b - asc, b + desc, size) {
- return Some((b, slot));
+ } else {
++ let segs = free_slots(f, col, b - asc, b + desc, size, rtl);
++ if !segs.is_empty() {
++ return Some((b, segs));
++ }
+ let (y0, y1) = (b - asc, b + desc);
- let edge = f
- .exclusions
- .iter()
- .filter(|e| e.mode != WrapMode::JumpObject)
- .map(|e| e.rect)
- .filter(|r| r.y0 < y1 && r.y1 > y0)
- .fold(f64::INFINITY, |m, r| m.min(r.y1));
- edge + asc
++ let in_band = || f.exclusions.iter().filter(|e| e.mode != WrapMode::JumpObject).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.
- 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).
+ fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, size: f64, rtl: bool) -> Vec<(f64, f64)> {
let mut free = vec![(col.x0, col.x1)];
for ex in &f.exclusions {
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::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::JumpObject if overlaps_band && r.x0 < col.x1 && r.x1 > col.x0 => return vec![],
+ WrapMode::BoundingBox if overlaps_band => Some((r.x0, r.x1)),
+ 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], rtl: bool, carry: &[(f64, f64)]) -> Vec<(f64, f64)> {
+fn estimate_slots(
+ f: &FrameSpec,
+ col: Rect,
+ first: f64,
+ jump: Jump,
+ lead: f64,
+ size: f64,
+ glyphs: &[Glyph],
- pp: &ParaProps,
- line_no: usize,
++ rtl: bool,
++ carry: &[(f64, f64)],
+) -> Vec<(f64, f64)> {
- let _ = (pp, line_no);
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;
- for _ in 0..n {
- let slot = match wrap_slot(f, col, b, size * 0.8, size * 0.25, jump, size) {
+ while v.len() < n + carry.len() {
- let mut tries = 0;
- let slots = loop {
- let s = free_slots(f, col, b - size * 0.8, b + size * 0.25, size, rtl);
- if !s.is_empty() {
- break s;
++ let slots = match wrap_slot(f, col, b, size * 0.8, size * 0.25, jump, size, rtl) {
+ Some((nb, s)) => {
+ b = nb;
+ s
}
- b += 1.0;
- tries += 1;
- if b > col.y1 || tries > 4000 {
- break vec![(col.x0, col.x1)];
+ None => {
+ b = b.max(col.y1);
- (col.x0, col.x1)
++ vec![(col.x0, col.x1)]
}
};
- v.push(slot);
+ v.extend(slots);
b += lead;
+ jump = Jump { top: lead, step: lead };
}
v
}
@@@ -3659,40 -3213,6 +3875,42 @@@ pub fn line_rtl(cs: &ComposedStory, pos
caret_line(cs, pos).and_then(|(_, l)| l.glyphs.iter().find(|g| g.len > 0)).is_some_and(|g| g.rtl)
}
- /// The line of frame `ft` closest to point `p` vertically (within its column).
++/// The line of frame `ft` closest to point `p` vertically (within its column), then horizontally
++/// (segments of a line beside an object share its baseline).
+fn hit_line(ft: &FrameText, p: Point) -> Option<&Line> {
++ let x_dist = |l: &Line| (l.x0 - p.x).max(p.x - l.x1).max(0.0);
+ ft.lines
+ .iter()
+ .filter(|l| p.x >= l.x0 - 20.0 && p.x <= l.x1 + 20.0 || ft.columns.len() <= 1)
- .min_by(|a, b| line_dist(a, p.y).total_cmp(&line_dist(b, p.y)))
++ .min_by(|a, b| line_dist(a, p.y).total_cmp(&line_dist(b, p.y)).then(x_dist(a).total_cmp(&x_dist(b))))
+ .or_else(|| ft.lines.first())
+}
+
+/// Story byte of the character drawn under point `p` (frame inner space) in frame `fi`: the
+/// glyph whose advance spans `p.x` on the closest line, else the one nearest it. For selecting
+/// the word (or the spaces) under a double click; [`hit`] finds a caret position instead.
+pub fn hit_char(cs: &ComposedStory, fi: usize, p: Point) -> Option<usize> {
+ let ft = cs.frames.get(fi)?;
+ let Some(l) = hit_line(ft, p) else { return Some(ft.range.start) };
+ let dist = |g: &&PlacedGlyph| {
+ let (a, b) = (g.x.min(g.x + g.adv), g.x.max(g.x + g.adv));
+ if p.x < a {
+ a - p.x
+ } else if p.x >= b {
+ p.x - b
+ } else {
+ 0.0
+ }
+ };
+ // On a drop cap (it reaches down beside the lines after its own): its character under `p`.
+ for dl in &ft.lines {
+ let Some(dc) = dl.drop_cap.filter(|dc| dc.rect.contains(p)) else { continue };
+ return dl.glyphs.iter().filter(|g| g.len > 0 && g.byte < dc.end).min_by(|a, b| dist(a).total_cmp(&dist(b))).map(|g| g.byte);
+ }
+ let under = l.glyphs.iter().filter(|g| g.len > 0).min_by(|a, b| dist(a).total_cmp(&dist(b)));
+ Some(under.map_or(l.range.start, |g| g.byte))
+}
+
/// Story byte nearest to point `p` (frame inner space) in frame `fi`.
pub fn hit(cs: &ComposedStory, fi: usize, p: Point) -> Option<usize> {
let ft = cs.frames.get(fi)?;
diff --cc crates/compose/src/tests.rs
index a3fb4b7a9,3aaa64645..edb89fe63
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@@ -146,241 -146,84 +146,319 @@@ 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 };
++ 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 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());
+ }
+
+ #[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.
diff --cc crates/doc/src/item.rs
index 9466d2ea5,4c480808e..b1ddbf0cb
--- a/crates/doc/src/item.rs
+++ b/crates/doc/src/item.rs
@@@ -426,14 -444,9 +446,15 @@@ pub struct TextWrap
pub offsets: [f64; 4],
pub invert: bool,
pub side: WrapSide,
+ pub contour: ContourType,
}
+impl TextWrap {
+ pub fn is_default(&self) -> bool {
+ *self == TextWrap::default()
+ }
+}
+
/// Frame fitting options (Object → Fitting → Frame Fitting Options).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
diff --cc crates/engine/src/cmd/object.rs
index 62ef99040,2facf6780..7627d5569
--- a/crates/engine/src/cmd/object.rs
+++ b/crates/engine/src/cmd/object.rs
@@@ -512,39 -512,9 +512,9 @@@ pub fn specs() -> Vec<CommandSpec>
"Text Wrap",
["Window"],
Some("Cmd+Alt+W"),
- "{mode: none|boundingBox|contour|jumpObject|jumpToNextColumn, offset?: number|[t,l,b,r], invert?: bool, content?: bool (the placed graphic instead of its frame; default: whether the selection is the frame's content), ids?}",
- "{mode?: none|boundingBox|contour|jumpObject|jumpToNextColumn (boundingBox when absent, unless side or contour is given: then unchanged), offset?: number|[t,l,b,r], invert?: bool, side?: bothSides|leftSide|rightSide|towardsSpine|awayFromSpine|largestArea, contour?: boundingBox|graphicFrame|sameAsClipping, ids?}",
++ "{mode?: none|boundingBox|contour|jumpObject|jumpToNextColumn (boundingBox when absent, unless side or contour is given: then unchanged), offset?: number|[t,l,b,r], invert?: bool, side?: bothSides|leftSide|rightSide|towardsSpine|awayFromSpine|largestArea, contour?: boundingBox|graphicFrame|sameAsClipping, content?: bool (the placed graphic instead of its frame; default: whether the selection is the frame's content), ids?}",
has_selection,
- |s, p| {
- let mode = p.get("mode").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or(designcraft_doc::WrapMode::BoundingBox);
- let off = match p.get("offset") {
- Some(Value::Number(n)) => Some([n.as_f64().unwrap_or(0.0); 4]),
- Some(v) => serde_json::from_value(v.clone()).ok(),
- None => None,
- };
- let invert = p.get("invert").and_then(Value::as_bool);
- let content = match p.get("content").and_then(Value::as_bool) {
- Some(c) => c,
- None => p.get("ids").is_none() && p.get("id").is_none() && s.doc()?.selection.content,
- };
- set_flag(
- s,
- p,
- move |i| {
- let w = match &mut i.content {
- Content::Graphic(g) if content => &mut g.wrap,
- _ => &mut i.wrap,
- };
- w.mode = mode;
- if let Some(o) = off {
- w.offsets = o;
- }
- if let Some(v) = invert {
- w.invert = v;
- }
- },
- false,
- )
- }
+ text_wrap
),
cmd!(
"object.fit",
@@@ -1531,6 -1330,54 +1501,62 @@@ fn ungroup(s: &mut Session, p: &Value)
})
}
+ fn text_wrap(s: &mut Session, p: &Value) -> Result<Value> {
+ use designcraft_doc::{ContourType, WrapMode, WrapSide};
+ let side: Option<WrapSide> = match p.get("side") {
+ Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad("object.textWrap", "unknown side"))?),
+ None => None,
+ };
+ // Detected edges, alpha channels and image paths need the image's pixels or paths, which
+ // composition doesn't read; those types aren't offered.
+ let contour = match p.get("contour").map(|v| serde_json::from_value::<ContourType>(v.clone())) {
+ Some(Ok(c @ (ContourType::BoundingBox | ContourType::GraphicFrame | ContourType::SameAsClipping))) => Some(c),
+ Some(_) => return Err(bad("object.textWrap", "unsupported contour type")),
+ None => None,
+ };
+ let mode: Option<WrapMode> = match p.get("mode") {
+ Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad("object.textWrap", "unknown mode"))?),
+ None if side.is_some() || contour.is_some() => None,
+ None => Some(WrapMode::BoundingBox),
+ };
+ let off = match p.get("offset") {
+ Some(Value::Number(n)) => Some([n.as_f64().unwrap_or(0.0); 4]),
+ Some(v) => serde_json::from_value(v.clone()).ok(),
+ None => None,
+ };
+ let invert = p.get("invert").and_then(Value::as_bool);
++ let content = match p.get("content").and_then(Value::as_bool) {
++ Some(c) => c,
++ None => p.get("ids").is_none() && p.get("id").is_none() && s.doc()?.selection.content,
++ };
+ set_flag(
+ s,
+ p,
+ move |i| {
++ let w = match &mut i.content {
++ Content::Graphic(g) if content => &mut g.wrap,
++ _ => &mut i.wrap,
++ };
+ if let Some(m) = mode {
- i.wrap.mode = m;
++ w.mode = m;
+ }
+ if let Some(o) = off {
- i.wrap.offsets = o;
++ w.offsets = o;
+ }
+ if let Some(v) = invert {
- i.wrap.invert = v;
++ w.invert = v;
+ }
+ if let Some(v) = side {
- i.wrap.side = v;
++ w.side = v;
+ }
+ if let Some(c) = contour {
- i.wrap.contour = c;
++ w.contour = c;
+ }
+ },
+ false,
+ )
+ }
+
fn set_flag(s: &mut Session, p: &Value, f: impl Fn(&mut Item), deselect: bool) -> Result<Value> {
let ids = targets(s, p)?;
s.edit(|d, sel| {
diff --cc crates/engine/src/tests.rs
index 50aee9166,a0c6a66cd..7da76a658
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@@ -511,29 -511,18 +511,39 @@@ fn object_set_flags_and_wrap_invert()
s.execute("selection.set", &json!({"ids": [id]})).unwrap();
s.execute("object.textWrap", &json!({"mode": "boundingBox", "invert": true})).unwrap();
assert!(item(&s).wrap.invert);
+ // Side and contour type keep the mode; contour types that need the image aren't accepted.
+ s.execute("object.textWrap", &json!({"mode": "contour"})).unwrap();
+ s.execute("object.textWrap", &json!({"side": "largestArea", "contour": "graphicFrame"})).unwrap();
+ let w = item(&s).wrap;
+ assert_eq!(
+ (w.mode, w.side, w.contour),
+ (designcraft_doc::WrapMode::Contour, designcraft_doc::WrapSide::LargestArea, designcraft_doc::ContourType::GraphicFrame)
+ );
+ assert!(s.execute("object.textWrap", &json!({"contour": "detectEdges"})).is_err());
+ assert!(s.execute("object.textWrap", &json!({"side": "middle"})).is_err());
}
+#[test]
+fn text_wrap_on_selected_content_sets_the_graphic_wrap() {
+ let mut s = session();
+ let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png();
+ let f = s.execute("frame.create", &json!({"rect": [300, 300, 400, 400], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();
+ s.execute("place.load", &json!({"base64": cmd::base64_encode(&png)})).unwrap();
+ s.execute("place.drop", &json!({"frame": f})).unwrap();
+ let item = |s: &Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).cloned().unwrap();
+ s.execute("selection.set", &json!({"ids": [f], "content": true})).unwrap();
+ s.execute("object.textWrap", &json!({"mode": "boundingBox", "offset": 4})).unwrap();
+ let it = item(&s);
+ assert_eq!(it.wrap.mode, designcraft_doc::WrapMode::None, "the frame keeps no wrap");
+ let g = it.graphic().unwrap();
+ assert_eq!((g.wrap.mode, g.wrap.offsets), (designcraft_doc::WrapMode::BoundingBox, [4.0; 4]));
+ // The frame selected: the frame's own wrap.
+ s.execute("selection.set", &json!({"ids": [f]})).unwrap();
+ s.execute("object.textWrap", &json!({"mode": "jumpObject"})).unwrap();
+ let it = item(&s);
+ assert_eq!((it.wrap.mode, it.graphic().unwrap().wrap.mode), (designcraft_doc::WrapMode::JumpObject, designcraft_doc::WrapMode::BoundingBox));
+}
+
#[test]
fn gridify_while_drawing_frames() {
use designcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
diff --cc crates/idml/src/export.rs
index cc68e6600,84ed20c7c..77baa0be5
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@@ -2669,24 -2471,6 +2669,25 @@@ fn margin_el(pg: &designcraft_doc::Page
}
/// `rule_color` is the IDML reference of the column rule's swatch.
+/// `TextWrapPreference` of a page item or a placed graphic.
+fn text_wrap_pref(w: &designcraft_doc::TextWrap) -> El {
+ with_props(
+ El::new("TextWrapPreference")
+ .attr("Inverse", bool_s(w.invert))
+ .attr("ApplyToMasterPageOnly", "false")
+ .attr("TextWrapSide", names::wrap_side_out(w.side))
+ .attr("TextWrapMode", names::wrap_mode_out(w.mode)),
+ vec![
+ El::new("TextWrapOffset")
+ .attr("Top", num(w.offsets[0]))
+ .attr("Left", num(w.offsets[1]))
+ .attr("Bottom", num(w.offsets[2]))
+ .attr("Right", num(w.offsets[3])),
+ ],
+ )
++ .child(El::new("ContourOption").attr("ContourType", names::contour_type_out(w.contour)).attr("IncludeInsideEdges", "false"))
+}
+
fn text_frame_pref(o: &TextFrameOptions, rule_color: &str) -> El {
let mut inset = El::new("InsetSpacing").attr("type", "list");
for v in o.inset {
diff --cc crates/idml/src/import.rs
index 48ae26093,02ced7940..63cd63b3f
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@@ -2731,20 -2347,6 +2731,21 @@@ impl<'r> Importer<'r>
}
/// Drop-shadow angle (degrees) from IDML offsets (inverse of export's mapping).
+/// A `TextWrapPreference` element (of a page item or a placed graphic).
+fn text_wrap(w: &El) -> TextWrap {
+ let mut tw = TextWrap {
+ mode: names::wrap_mode_in(w.get("TextWrapMode").unwrap_or("None")),
+ invert: w.get("Inverse") == Some("true"),
+ side: names::wrap_side_in(w.get("TextWrapSide").unwrap_or("BothSides")),
++ contour: names::contour_type_in(w.find("ContourOption").and_then(|c| c.get("ContourType")).unwrap_or("SameAsClipping")),
+ ..TextWrap::default()
+ };
+ if let Some(o) = w.prop_el("TextWrapOffset") {
+ tw.offsets = [o.num("Top").unwrap_or(0.0), o.num("Left").unwrap_or(0.0), o.num("Bottom").unwrap_or(0.0), o.num("Right").unwrap_or(0.0)];
+ }
+ tw
+}
+
fn names_angle(x: f64, y: f64) -> f64 {
if x == 0.0 && y == 0.0 {
return 135.0;
diff --cc crates/idml/src/tests.rs
index d4b4cf127,c006ea1ad..3e49dfc5b
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@@ -2383,351 -1400,32 +2383,381 @@@ fn list_numbering_format_expression_and
check(&import_idml(&export_idml(&d)).unwrap());
}
+/// InDesign can write `AppliedFont` with its `$ID/` prefix (`$ID/Source Serif 4`). The text is
+/// set in that family instead of counting as a missing font drawn in the fallback.
+#[test]
+fn applied_font_with_an_id_prefix_names_the_family() {
+ let styles = STYLES.replace(">Source Serif 4</AppliedFont>", ">$ID/Source Serif 4</AppliedFont>");
+ let story = STORY.replace(
+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14">"#,
+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14"><Properties><AppliedFont type="string">$ID/Source Serif 4</AppliedFont></Properties>"#,
+ );
+ let bytes = zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", &styles),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", SPREAD),
+ ("Stories/Story_s1.xml", &story),
+ ]);
+ let d = import_idml_with(&bytes, &|_| None).unwrap();
+ let fonts: Vec<&str> = d.styles.paragraph.iter().filter_map(|s| s.chars.font_family.as_deref()).collect();
+ assert!(!fonts.is_empty() && fonts.iter().all(|f| *f == "Source Serif 4"), "{fonts:?}");
+ let (sid, story) = d.stories.iter().next().unwrap();
+ let bold = story.runs().find(|(r, _)| story.text[r.clone()].starts_with("bold")).unwrap().1;
+ assert_eq!(bold.over.font_family.as_deref(), Some("Source Serif 4"));
+ // The bundled family draws the text (an unknown family would fall back to Source Sans 3).
+ let cs = designcraft_compose::compose_story(&d, *sid, &Default::default());
+ let first_para = story.text.find('\n').unwrap();
+ let families: Vec<&str> = cs
+ .frames
+ .iter()
+ .flat_map(|f| &f.lines)
+ .flat_map(|l| &l.glyphs)
+ .filter(|g| g.visible && g.len > 0 && g.byte < first_para)
+ .map(|g| g.face.get().family.as_str())
+ .collect();
+ assert!(!families.is_empty() && families.iter().all(|f| *f == "Source Serif 4"), "{families:?}");
+}
+
+#[test]
+fn list_tab_position_round_trips_as_a_tab_stop() {
+ use designcraft_doc::{ListType, ParaAttrs, ParagraphStyle, TabAlign, TabStop};
+ let stop = |position, align| TabStop { position, align, leader: String::new(), align_on: String::new() };
+ let mut d = Document::new(&NewDocument::default());
+ std::sync::Arc::make_mut(&mut d.styles).paragraph.push(ParagraphStyle {
+ name: "List".into(),
+ based_on: None,
+ next_style: None,
+ para: ParaAttrs { list_type: Some(ListType::Bullets), list_tab: Some(Some(24.0)), ..Default::default() },
+ chars: CharAttrs::default(),
+ shortcut: String::new(),
+ });
+ let local = ParaAttrs {
+ list_type: Some(ListType::Bullets),
+ list_tab: Some(Some(36.0)),
+ tabs: Some(vec![stop(100.0, TabAlign::Right)]),
+ ..Default::default()
+ };
+ let ended = ParaAttrs { list_type: Some(ListType::None), ..Default::default() };
+ let lid = d.default_layer();
+ for (i, (text, style, para)) in
+ [("Local\tx", "", local), ("Styled\ty", "List", ParaAttrs::default()), ("Ended\tz", "List", ended)].into_iter().enumerate()
+ {
+ let pf = ParaFormat { style: if style.is_empty() { ParaFormat::default().style } else { style.into() }, para, ..Default::default() };
+ let y = 40.0 + 100.0 * i as f64;
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, y, 300.0, y + 80.0), lid, text, pf).unwrap();
+ }
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let tabs = |prefix: &str| {
+ let s = back.stories.values().find(|s| s.text.starts_with(prefix)).unwrap();
+ back.styles.resolve_para(&s.paras[0]).0.tabs
+ };
+ assert_eq!(tabs("Local"), vec![stop(36.0, TabAlign::Left), stop(100.0, TabAlign::Right)]);
+ assert_eq!(tabs("Styled"), vec![stop(24.0, TabAlign::Left)]);
+ assert_eq!(tabs("Ended"), vec![], "a paragraph that ends the list has no list tab stop");
+}
+
+#[test]
+fn round_trips_the_zero_point_and_ruler_origin() {
+ let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });
+ d.settings.zero_point = [36.0, 18.5];
+ let back = import_idml(&export_idml(&d)).unwrap();
+ assert_eq!(back.settings.zero_point, [36.0, 18.5]);
+ for origin in [designcraft_doc::RulerOrigin::Page, designcraft_doc::RulerOrigin::Spine, designcraft_doc::RulerOrigin::Spread] {
+ d.settings.ruler_origin = origin;
+ assert_eq!(import_idml(&export_idml(&d)).unwrap().settings.ruler_origin, origin);
+ }
+ // A hostile ZeroPoint lands on the pasteboard; a malformed one is ignored.
+ let fixture = |zp: &str| {
+ let designmap = format!(
+ r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d" ZeroPoint="{zp}">
+ <idPkg:Spread src="Spreads/Spread_s.xml"/>
+ </Document>"#
+ );
+ let spread = r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">
+ <Spread Self="s"><Page Self="p" GeometricBounds="0 0 100 100" ItemTransform="1 0 0 1 0 0"/></Spread>
+ </idPkg:Spread>"#;
+ import_idml(&zip_files(&[("designmap.xml", &designmap), ("Spreads/Spread_s.xml", spread)])).unwrap()
+ };
+ let [x, y] = fixture("1e300 -1e300").settings.zero_point;
+ assert!(x.is_finite() && y.is_finite() && x < 1e4 && y > -1e4, "{x} {y}");
+ assert_eq!(fixture("12").settings.zero_point, [0.0, 0.0]);
+ assert_eq!(fixture("NaN 4").settings.zero_point, [0.0, 0.0]);
+}
+
+#[test]
+fn kenten_shatai_and_grid_settings_import_and_round_trip() {
+ use designcraft_doc::cjk::CharacterAlignment;
+ use designcraft_doc::cjk_settings::{AdornmentOverprint, KentenAlignment, KentenKind, KentenPosition};
+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" AutoTcy="3" AutoTcyIncludeRoman="true" RotateSingleByteCharacters="true" AllowArbitraryHyphenation="true" GridAlignment="AlignEmCenter" GridAlignFirstLineOnly="true" GridGyoudori="2" ParagraphGyoudori="true">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" KentenKind="KentenSmallBlackCircle" KentenFontSize="6" KentenXScale="80" KentenYScale="120" KentenPlacement="1.5" KentenPosition="BelowLeft" KentenAlignment="AlignKentenLeft" KentenCharacterSet="CharacterInput" KentenTint="50" KentenStrokeTint="-1" KentenWeight="0.5" KentenOverprintFill="OverprintOn" KentenOverprintStroke="Auto" ShataiMagnification="20" ShataiDegreeAngle="6000" ShataiAdjustRotation="true" ShataiAdjustTsume="false"><Properties><KentenFont type="string">$ID/</KentenFont><KentenFontStyle type="enumeration">Nothing</KentenFontStyle><KentenFillColor type="string">Text Color</KentenFillColor></Properties><Content>甲乙</Content></CharacterStyleRange>
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" KentenKind="Custom" KentenCustomCharacter="★"><Content>丙</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#;
+ let doc = import_idml(&fixture_with_story(story)).unwrap();
+ let st = doc.stories.values().find(|s| s.text.contains("甲乙")).unwrap();
+ let runs: Vec<CharAttrs> = st.runs().map(|(_, f)| f.over.clone()).collect();
+ let a = &runs[0];
+ assert_eq!((a.kenten, a.kenten_kind, a.kenten_character.as_deref()), (Some(true), Some(KentenKind::SmallBlackCircle), Some("\u{2022}")));
+ assert_eq!((a.kenten_size, a.kenten_x_scale, a.kenten_y_scale, a.kenten_distance), (Some(Some(6.0)), Some(0.8), Some(1.2), Some(1.5)));
+ assert_eq!((a.kenten_position, a.kenten_alignment), (Some(KentenPosition::BelowLeft), Some(KentenAlignment::Start)));
+ assert_eq!((a.kenten_font.as_deref(), a.kenten_font_style.as_deref(), a.kenten_fill.as_deref()), (Some(""), Some(""), Some("")));
+ assert_eq!((a.kenten_fill_tint, a.kenten_stroke_tint, a.kenten_stroke_weight), (Some(Some(0.5)), Some(None), Some(Some(0.5))));
+ assert_eq!((a.kenten_overprint_fill, a.kenten_overprint_stroke), (Some(AdornmentOverprint::On), Some(AdornmentOverprint::Auto)));
+ assert_eq!(a.kenten_character_set.as_deref(), Some("CharacterInput"));
+ assert_eq!(
+ (a.shatai_magnification, a.shatai_angle, a.shatai_adjust_rotation, a.shatai_adjust_tsume),
+ (Some(20.0), Some(60.0), Some(true), Some(false))
+ );
+ let custom = runs.iter().find(|r| r.kenten_kind == Some(KentenKind::Custom)).unwrap();
+ assert_eq!(custom.kenten_character.as_deref(), Some("★"));
+ let p = &st.paras[0].para;
+ assert_eq!((p.auto_tcy, p.auto_tcy_include_roman, p.rotate_roman, p.roman_word_break), (Some(3), Some(true), Some(true), Some(true)));
+ assert_eq!((p.grid_align, p.grid_reference), (Some(designcraft_doc::GridAlign::FirstLineOnly), Some(CharacterAlignment::EmCenter)));
+ assert_eq!((p.grid_gyoudori, p.paragraph_gyoudori), (Some(2), Some(true)));
+
+ let back = import_idml(&export_idml(&doc)).unwrap();
+ let st2 = back.stories.values().find(|s| s.text.contains("甲乙")).unwrap();
+ let runs2: Vec<CharAttrs> = st2.runs().map(|(_, f)| f.over.clone()).collect();
+ for (a, b) in runs.iter().zip(&runs2) {
+ assert_eq!((a.kenten, a.kenten_kind, &a.kenten_character), (b.kenten, b.kenten_kind, &b.kenten_character));
+ assert_eq!(
+ (a.kenten_size, a.kenten_x_scale, a.kenten_y_scale, a.kenten_distance),
+ (b.kenten_size, b.kenten_x_scale, b.kenten_y_scale, b.kenten_distance)
+ );
+ assert_eq!(
+ (a.kenten_position, a.kenten_alignment, &a.kenten_character_set),
+ (b.kenten_position, b.kenten_alignment, &b.kenten_character_set)
+ );
+ assert_eq!((&a.kenten_font, &a.kenten_font_style, &a.kenten_fill), (&b.kenten_font, &b.kenten_font_style, &b.kenten_fill));
+ assert_eq!(
+ (a.kenten_fill_tint, a.kenten_stroke_tint, a.kenten_stroke_weight),
+ (b.kenten_fill_tint, b.kenten_stroke_tint, b.kenten_stroke_weight)
+ );
+ assert_eq!((a.kenten_overprint_fill, a.kenten_overprint_stroke), (b.kenten_overprint_fill, b.kenten_overprint_stroke));
+ assert_eq!(
+ (a.shatai_magnification, a.shatai_angle, a.shatai_adjust_rotation, a.shatai_adjust_tsume),
+ (b.shatai_magnification, b.shatai_angle, b.shatai_adjust_rotation, b.shatai_adjust_tsume)
+ );
+ }
+ let p2 = &st2.paras[0].para;
+ assert_eq!(
+ (p.auto_tcy, p.auto_tcy_include_roman, p.rotate_roman, p.roman_word_break),
+ (p2.auto_tcy, p2.auto_tcy_include_roman, p2.rotate_roman, p2.roman_word_break)
+ );
+ assert_eq!(
+ (p.grid_align, p.grid_reference, p.grid_gyoudori, p.paragraph_gyoudori),
+ (p2.grid_align, p2.grid_reference, p2.grid_gyoudori, p2.paragraph_gyoudori)
+ );
+}
+
+#[test]
+fn ruby_settings_import_from_idml_and_round_trip() {
+ use designcraft_doc::cjk_settings::AdornmentOverprint;
+ use designcraft_doc::ruby::{RubyAlignment, RubyOverhang, RubyParentSpacing, RubyPosition, RubyType};
+ // InDesign's names: RubyFlag is a number, colours and fonts are properties.
+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" RubyFlag="1" RubyString="かん じ" RubyType="PerCharacterRuby" RubyAlignment="RubyCenter" RubyPosition="BelowLeft" RubyYOffset="-1.4173228" RubyFontSize="-1" RubyXScale="90" RubyParentOverhangAmount="RubyOverhangNoLimit" RubyParentSpacing="RubyParentBothSides" RubyAutoAlign="false" RubyAutoScaling="true" RubyParentScalingPercent="40" RubyAutoTcyDigits="2" RubyTint="-1" RubyOverprintFill="Auto"><Properties><RubyFont type="string">$ID/</RubyFont><RubyFontStyle type="enumeration">Nothing</RubyFontStyle><RubyFill type="string">Text Color</RubyFill></Properties><Content>漢字</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#;
+ let doc = import_idml(&fixture_with_story(story)).unwrap();
+ let a = doc.stories.values().find(|s| s.text.contains("漢字")).unwrap().runs().next().unwrap().1.over.clone();
+ assert_eq!(a.ruby.as_deref(), Some("かん じ"));
+ assert_eq!(a.ruby_type, Some(RubyType::PerCharacter));
+ assert_eq!(a.ruby_alignment, Some(RubyAlignment::Center));
+ assert_eq!(a.ruby_position, Some(RubyPosition::BelowLeft));
+ assert_eq!(a.ruby_y_offset, Some(-1.4173228));
+ assert_eq!(a.ruby_font_size, Some(None));
+ assert_eq!(a.ruby_x_scale, Some(0.9));
+ assert_eq!(a.ruby_overhang_amount, Some(RubyOverhang::NoLimit));
+ assert_eq!(a.ruby_parent_spacing, Some(RubyParentSpacing::BothSides));
+ assert_eq!((a.ruby_auto_align, a.ruby_auto_scaling, a.ruby_scaling_min), (Some(false), Some(true), Some(0.4)));
+ assert_eq!(a.ruby_auto_tcy_digits, Some(2));
+ assert_eq!((a.ruby_font.as_deref(), a.ruby_font_style.as_deref(), a.ruby_fill.as_deref()), (Some(""), Some(""), Some("")));
+ assert_eq!((a.ruby_fill_tint, a.ruby_overprint_fill), (Some(None), Some(AdornmentOverprint::Auto)));
+
+ // Every setting survives export and import.
+ let mut d = Document::new(&NewDocument::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, "漢字", ParaFormat::default()).unwrap();
+ d.story_mut(sid).unwrap().format_chars(0.."漢字".len(), |f| {
+ let o = &mut f.over;
+ o.ruby = Some("かん じ".into());
+ o.ruby_type = Some(RubyType::PerCharacter);
+ o.ruby_alignment = Some(RubyAlignment::OneAki);
+ o.ruby_position = Some(RubyPosition::BelowLeft);
+ o.ruby_x_offset = Some(1.5);
+ o.ruby_y_offset = Some(-1.25);
+ o.ruby_font = Some("Source Sans 3".into());
+ o.ruby_font_style = Some("Bold".into());
+ o.ruby_font_size = Some(Some(7.0));
+ o.ruby_x_scale = Some(0.9);
+ o.ruby_y_scale = Some(1.1);
+ o.ruby_open_type_pro = Some(false);
+ o.ruby_auto_tcy_digits = Some(3);
+ o.ruby_auto_tcy_include_roman = Some(true);
+ o.ruby_auto_tcy_auto_scale = Some(false);
+ o.ruby_overhang = Some(true);
+ o.ruby_overhang_amount = Some(RubyOverhang::HalfChar);
+ o.ruby_parent_spacing = Some(RubyParentSpacing::EqualAki);
+ o.ruby_auto_align = Some(false);
+ o.ruby_auto_scaling = Some(true);
+ o.ruby_scaling_min = Some(0.5);
+ o.ruby_fill = Some("[Black]".into());
+ o.ruby_fill_tint = Some(Some(0.5));
+ o.ruby_stroke = Some(String::new());
+ o.ruby_stroke_tint = Some(None);
+ o.ruby_stroke_weight = Some(Some(0.25));
+ o.ruby_overprint_fill = Some(AdornmentOverprint::On);
+ o.ruby_overprint_stroke = Some(AdornmentOverprint::Off);
+ });
+ let a = d.stories[&sid].runs().next().unwrap().1.over.clone();
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let b = back.stories.values().find(|s| s.text.contains("漢字")).unwrap().runs().next().unwrap().1.over.clone();
+ macro_rules! same {
+ ($($f:ident),*) => { $( assert_eq!(a.$f, b.$f, stringify!($f)); )* };
+ }
+ same!(
+ ruby,
+ ruby_type,
+ ruby_alignment,
+ ruby_position,
+ ruby_x_offset,
+ ruby_y_offset,
+ ruby_font,
+ ruby_font_style,
+ ruby_font_size,
+ ruby_x_scale,
+ ruby_y_scale,
+ ruby_open_type_pro,
+ ruby_auto_tcy_digits,
+ ruby_auto_tcy_include_roman,
+ ruby_auto_tcy_auto_scale,
+ ruby_overhang,
+ ruby_overhang_amount,
+ ruby_parent_spacing,
+ ruby_auto_align,
+ ruby_auto_scaling,
+ ruby_scaling_min,
+ ruby_fill,
+ ruby_fill_tint,
+ ruby_stroke,
+ ruby_stroke_tint,
+ ruby_stroke_weight,
+ ruby_overprint_fill,
+ ruby_overprint_stroke
+ );
+}
+
+/// A file's tab list is sanitized as the Tabs commands check theirs: a hostile one imports
+/// within the limits instead of failing the import.
+#[test]
+fn hostile_tab_lists_import_within_the_limits() {
+ let item = |position: &str, leader: &str| {
+ format!(
+ r#"<ListItem type="record"><Alignment type="enumeration">LeftAlign</Alignment><AlignmentCharacter type="string">.</AlignmentCharacter><Leader type="string">{leader}</Leader><Position type="unit">{position}</Position></ListItem>"#
+ )
+ };
+ let mut items: String = (0..500).rev().map(|i| item(&(i * 3).to_string(), "")).collect();
+ items.push_str(&item("NaN", ""));
+ items.push_str(&item("1e300", "0123456789"));
+ let story = format!(
+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">
+ <Properties><TabList type="list">{items}</TabList></Properties>
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Many tabs</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#
+ );
+ let report = import_idml_report(&fixture_with_story(&story), &|_| None).unwrap();
+ assert!(report.warnings.iter().any(|w| w.starts_with("tab lists repaired to fit the limits") && w.ends_with("): 1")), "{:?}", report.warnings);
+ let doc = report.document;
+ let tabs = doc.stories.values().find(|s| s.text.contains("Many tabs")).unwrap().paras[0].para.tabs.clone().unwrap();
+ assert_eq!(tabs.len(), designcraft_doc::MAX_TAB_STOPS);
+ assert!(tabs.iter().all(|t| t.position.is_finite() && t.leader.chars().count() <= designcraft_doc::MAX_TAB_LEADER));
+ assert!(tabs.windows(2).all(|w| w[0].position < w[1].position), "sorted");
+ assert_eq!((tabs[0].position, tabs[99].position), (0.0, 297.0), "the first stops by position");
+ // A list within the limits, unsorted and with a char stop on `.`, imports without a warning.
+ let fine = format!(
+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">
+ <Properties><TabList type="list">{}{}<ListItem type="record"><Alignment type="enumeration">CharacterAlign</Alignment><AlignmentCharacter type="string">.</AlignmentCharacter><Leader type="string"></Leader><Position type="unit">40</Position></ListItem></TabList></Properties>
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Few tabs</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#,
+ item("90", "."),
+ item("12", "")
+ );
+ let report = import_idml_report(&fixture_with_story(&fine), &|_| None).unwrap();
+ assert!(report.warnings.is_empty(), "{:?}", report.warnings);
+}
+
+#[test]
+fn cell_edge_gap_colours_and_tints_import_and_round_trip_per_edge() {
+ let styles = CASCADE_STYLES.replace(
+ r#"TopEdgeStrokeType="StrokeStyle/$ID/Dashed""#,
+ r#"TopEdgeStrokeType="StrokeStyle/$ID/Dashed" TopEdgeStrokeGapColor="Color/Paper" TopEdgeStrokeGapTint="60" BottomEdgeStrokeGapColor="Color/Brand""#,
+ );
+ let story = CASCADE_STORY.replace(
+ r#"<Cell Name="1:1">"#,
+ r#"<Cell Name="1:1" LeftEdgeStrokeType="StrokeStyle/$ID/Dotted" LeftEdgeStrokeGapColor="Color/Brand" LeftEdgeStrokeGapTint="30" RightEdgeStrokeGapColor="Color/Paper">"#,
+ );
+ let gaps = |d: &Document| {
+ let base = d.styles.cell.iter().find(|s| s.name == "Base").unwrap().strokes.clone();
+ let table = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();
+ let cell = table.cell(1, 1).unwrap().strokes.clone();
+ (base.map(|e| (e.gap_color, e.gap_tint)), cell.map(|e| (e.gap_color, e.gap_tint)))
+ };
+ let d = import_idml(&fixture_with_table_styles(&styles, &story)).unwrap();
+ d.check().unwrap();
+ let (style, cell) = gaps(&d);
+ assert_eq!(style[0], (Some("[Paper]".to_string()), Some(0.6)));
+ assert_eq!(style[2], (Some("Brand".to_string()), None));
+ assert_eq!((style[1].clone(), style[3].clone()), ((None, None), (None, None)));
+ assert_eq!(cell[1], ("Brand".to_string(), 0.3), "left");
+ assert_eq!(cell[3], ("[Paper]".to_string(), 1.0), "right");
+ assert_eq!(cell[0].0, "[Paper]", "the Base style's top gap colour reaches the cell");
+ let back = import_idml(&export_idml(&d)).unwrap();
+ assert_eq!(gaps(&back), (style, cell));
+}
+
+#[test]
+fn em_box_first_baseline_offset_round_trips() {
+ use designcraft_doc::FirstBaseline;
+ let first = |d: &Document| d.spreads[0].items[0].text_frame().unwrap().options.first_baseline;
+ let d = inset_fixture(r#"<TextFramePreference FirstBaselineOffset="EmboxHeight"/>"#, "");
+ assert_eq!(first(&d), FirstBaseline::EmboxHeight);
+ assert_eq!(first(&import_idml(&export_idml(&d)).unwrap()), FirstBaseline::EmboxHeight);
+ let unknown = inset_fixture(r#"<TextFramePreference FirstBaselineOffset="SomethingElse"/>"#, "");
+ assert_eq!(first(&unknown), FirstBaseline::Ascent);
+}
++
+ #[test]
+ fn imports_and_round_trips_text_wrap_side_and_contour_type() {
+ let wrap = r#"<TextWrapPreference TextWrapMode="Contour" TextWrapSide="LeftSide"><ContourOption ContourType="BoundingBox" IncludeInsideEdges="false"/></TextWrapPreference><Image Self="im""#;
+ let spread = SPREAD.replace(r#"<Image Self="im""#, wrap);
+ assert_ne!(spread, SPREAD);
+ let bytes = zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", STYLES),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", &spread),
+ ("Stories/Story_s1.xml", STORY),
+ ]);
+ let mut d = import_idml(&bytes).unwrap();
+ let id = d.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().id;
+ let w = d.item(id).unwrap().wrap;
+ assert_eq!(
+ (w.mode, w.side, w.contour),
+ (designcraft_doc::WrapMode::Contour, designcraft_doc::WrapSide::LeftSide, designcraft_doc::ContourType::BoundingBox)
+ );
+ // Every side and contour type survives export and import (detected edges included, which
+ // composition follows as the frame's path).
+ d.item_mut(id).unwrap().wrap.side = designcraft_doc::WrapSide::AwayFromSpine;
+ d.item_mut(id).unwrap().wrap.contour = designcraft_doc::ContourType::DetectEdges;
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let w = back.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().wrap;
+ assert_eq!((w.side, w.contour), (designcraft_doc::WrapSide::AwayFromSpine, designcraft_doc::ContourType::DetectEdges));
+ }
diff --cc crates/idml/src/tests/wrap.rs
index 0ba76b3e0,000000000..fdddd5957
mode 100644,000000..100644
--- a/crates/idml/src/tests/wrap.rs
+++ b/crates/idml/src/tests/wrap.rs
@@@ -1,114 -1,0 +1,144 @@@
+use super::*;
+
+const NS: &str = r#"xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="14.0""#;
+
+fn wrap_pref(mode: &str, offset: f64) -> String {
+ format!(
+ r#"<TextWrapPreference Inverse="false" ApplyToMasterPageOnly="false" TextWrapSide="BothSides" TextWrapMode="{mode}"><Properties><TextWrapOffset Top="{offset}" Left="{offset}" Bottom="{offset}" Right="{offset}"/></Properties></TextWrapPreference>"#
+ )
+}
+
+fn rect_path(x0: f64, y0: f64, x1: f64, y1: f64) -> String {
+ let pts: String = [(x0, y0), (x0, y1), (x1, y1), (x1, y0)]
+ .iter()
+ .map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))
+ .collect();
+ format!(
+ r#"<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties>"#
+ )
+}
+
+/// A page with a text frame (50, 60)–(370, 540) and a 100 pt square image frame at (160, 150)
+/// over it; the image (60 px scaled to fill the frame) and its frame carry the given wraps.
+fn wrap_doc(frame_wrap: &str, image_wrap: &str) -> Document {
+ let lorem =
+ "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ".repeat(12);
+ let designmap = format!(
+ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<Document {NS} Self="d" StoryList="s1" Name="wrap.indd"><idPkg:Graphic src="Resources/Graphic.xml"/><idPkg:Styles src="Resources/Styles.xml"/><idPkg:Preferences src="Resources/Preferences.xml"/><Layer Self="L1" Name="Layer 1" Visible="true" Locked="false"/><idPkg:Spread src="Spreads/Spread_sp1.xml"/><idPkg:Story src="Stories/Story_s1.xml"/></Document>"#
+ );
+ let prefs = format!(r#"<idPkg:Preferences {NS}><DocumentPreference PageWidth="400" PageHeight="600" FacingPages="false"/></idPkg:Preferences>"#);
+ let spread = format!(
+ r#"<idPkg:Spread {NS}><Spread Self="sp1" PageCount="1" ItemTransform="1 0 0 1 0 0"><Page Self="p1" GeometricBounds="0 0 600 400" ItemTransform="1 0 0 1 0 -300"/>
+<TextFrame Self="t1" ParentStory="s1" PreviousTextFrame="n" NextTextFrame="n" ItemLayer="L1" ItemTransform="1 0 0 1 0 -300">{}<TextFramePreference FirstBaselineOffset="LeadingOffset"/></TextFrame>
+<Rectangle Self="r1" ItemLayer="L1" ContentType="GraphicType" ItemTransform="1 0 0 1 0 -300">{}{frame_wrap}<Image Self="im1" ItemTransform="1.6667 0 0 1.6667 160 150"><Properties><GraphicBounds Left="0" Top="0" Right="60" Bottom="60"/></Properties>{image_wrap}<Link Self="lk1" LinkResourceURI="file:C:/elsewhere/square.png" LinkResourceFormat="$ID/Portable Network Graphics (PNG)" StoredState="Normal"/></Image></Rectangle>
+</Spread></idPkg:Spread>"#,
+ rect_path(50.0, 60.0, 370.0, 540.0),
+ rect_path(160.0, 150.0, 260.0, 250.0)
+ );
+ let story = format!(
+ r#"<idPkg:Story {NS}><Story Self="s1"><ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>{lorem}</Content></CharacterStyleRange></ParagraphStyleRange></Story></idPkg:Story>"#
+ );
+ let bytes = zip_files(&[
+ ("designmap.xml", &designmap),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", STYLES),
+ ("Resources/Preferences.xml", &prefs),
+ ("Spreads/Spread_sp1.xml", &spread),
+ ("Stories/Story_s1.xml", &story),
+ ]);
+ import_idml_with(&bytes, &|_| None).unwrap()
+}
+
+/// Each composed line as (x0, x1, baseline), rounded to 0.01 pt.
+fn lines(d: &Document) -> Vec<(i64, i64, i64)> {
+ let sid = *d.stories.keys().next().unwrap();
+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());
+ let r = |v: f64| (v * 100.0).round() as i64;
+ cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| (r(l.x0), r(l.x1), r(l.baseline))).collect()
+}
+
+#[test]
+fn wrap_on_a_placed_graphic_wraps_text_like_a_wrap_on_its_frame() {
+ let none = wrap_pref("None", 0.0);
+ let bbox = wrap_pref("BoundingBoxTextWrap", 6.0);
+ let on_image = wrap_doc(&none, &bbox);
+ let on_frame = wrap_doc(&bbox, &none);
+ let unwrapped = wrap_doc(&none, &none);
+ let frame = &on_image.spreads[0].items[1];
+ assert_eq!(frame.wrap.mode, designcraft_doc::WrapMode::None);
+ let g = frame.graphic().unwrap();
+ assert_eq!((g.wrap.mode, g.wrap.offsets), (designcraft_doc::WrapMode::BoundingBox, [6.0; 4]));
+ // The image fills its frame, so both wraps make the same obstacle.
+ let wrapped = lines(&on_image);
+ assert_eq!(wrapped, lines(&on_frame));
+ let plain = lines(&unwrapped);
+ assert_ne!(wrapped, plain);
+ let full = plain[0].1 - plain[0].0;
+ assert!(wrapped.iter().any(|l| l.1 - l.0 < full / 2), "some lines run beside the image: {wrapped:?}");
+}
+
+#[test]
+fn wrap_on_a_placed_graphic_follows_its_crop_and_round_trips() {
+ let none = wrap_pref("None", 0.0);
+ let d = wrap_doc(&none, &wrap_pref("BoundingBoxTextWrap", 6.0));
+ // Exported on the image element, not on the frame.
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let f = back.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap();
+ assert_eq!(f.wrap.mode, designcraft_doc::WrapMode::None);
+ assert_eq!(f.graphic().unwrap().wrap, d.spreads[0].items[1].graphic().unwrap().wrap);
+ // Moved half out of the bottom of its frame, the image wraps only the part the frame shows.
+ let mut moved = d.clone();
+ let sp = std::sync::Arc::make_mut(&mut moved.spreads[0]);
+ let fr = std::sync::Arc::make_mut(&mut sp.items[1]);
+ if let designcraft_doc::Content::Graphic(g) = &mut fr.content {
+ g.xf = designcraft_geom::Affine::translate((0.0, 50.0)) * g.xf;
+ }
+ let fr = &moved.spreads[0].items[1];
+ let g = fr.graphic().unwrap();
+ let image = fr.xf.transform_rect_bbox(g.xf.transform_rect_bbox(designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1)));
+ // In the text frame's inner space, where lines are.
+ let inv = moved.spreads[0].items[0].xf.inverse();
+ let shown = inv.transform_rect_bbox(fr.bounds().intersect(image));
+ let image = inv.transform_rect_bbox(image);
+ let sid = *moved.stories.keys().next().unwrap();
+ let cs = designcraft_compose::compose_story(&moved, sid, &Default::default());
+ let beside: Vec<_> = cs.frames[0].lines.iter().filter(|l| l.baseline > shown.y0 && l.baseline - l.ascent < shown.y1).collect();
+ assert!(!beside.is_empty());
+ for l in &beside {
+ assert!(l.x1 <= shown.x0 - 6.0 + 0.01 || l.x0 >= shown.x1 + 6.0 - 0.01, "{:?} vs {shown:?}", (l.x0, l.x1));
+ }
+ // Full lines resume below the shown part (plus the offset), not below the whole image.
+ let full = cs.frames[0].lines.iter().find(|l| l.baseline - l.ascent > shown.y1 + 6.0).unwrap();
+ assert!(full.x1 - full.x0 > 300.0 && full.baseline < image.y1, "{:?} vs {image:?}", (full.x0, full.x1, full.baseline));
+}
++
++#[test]
++fn contour_wrap_on_a_placed_graphic_follows_its_shown_part_on_one_side() {
++ use designcraft_doc::{ContourType, WrapSide};
++ let pref = r#"<TextWrapPreference Inverse="false" ApplyToMasterPageOnly="false" TextWrapSide="RightSide" TextWrapMode="Contour"><Properties><TextWrapOffset Top="4" Left="4" Bottom="4" Right="4"/></Properties><ContourOption ContourType="BoundingBox" IncludeInsideEdges="false"/></TextWrapPreference>"#;
++ let mut d = wrap_doc(&wrap_pref("None", 0.0), pref);
++ let w = d.spreads[0].items[1].graphic().unwrap().wrap;
++ assert_eq!((w.side, w.contour), (WrapSide::RightSide, ContourType::BoundingBox));
++ let back = import_idml(&export_idml(&d)).unwrap();
++ assert_eq!(back.spreads[0].items.iter().find_map(|i| i.graphic()).unwrap().wrap, w);
++ // Half of the image below its frame: the contour is the shown half, 4 pt around it.
++ let sp = std::sync::Arc::make_mut(&mut d.spreads[0]);
++ if let designcraft_doc::Content::Graphic(g) = &mut std::sync::Arc::make_mut(&mut sp.items[1]).content {
++ g.xf = designcraft_geom::Affine::translate((0.0, 50.0)) * g.xf;
++ }
++ let sid = *d.stories.keys().next().unwrap();
++ let specs = designcraft_compose::frame_specs(&d, sid);
++ let [ex] = specs[0].exclusions.as_slice() else { panic!("{:?}", specs[0].exclusions) };
++ assert!(ex.contour.is_some());
++ assert_eq!(ex.side, WrapSide::RightSide);
++ let r = ex.rect;
++ assert!([r.x0 - 156.0, r.y0 - 196.0, r.x1 - 264.0, r.y1 - 254.0].iter().all(|v| v.abs() < 0.05), "{r:?}");
++ // Text runs only to its right.
++ let cs = designcraft_compose::compose_story(&d, sid, &Default::default());
++ let beside: Vec<_> = cs.frames[0].lines.iter().filter(|l| l.baseline + l.descent > 196.0 && l.baseline - l.ascent < 254.0).collect();
++ assert!(!beside.is_empty());
++ for l in beside {
++ assert!(l.x0 >= r.x1 - 0.01, "{:?} vs {r:?}", (l.x0, l.x1));
++ }
++}
diff --cc crates/ui-egui/src/panels/mod.rs
index 169c4b95b,61a0c5b39..d6509efd6
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@@ -140,7 -100,9 +143,9 @@@ pub fn sel_info(app: &DesignApp) -> Opt
.and_then(|v| v.get("kind").and_then(Value::as_str).map(str::to_string).or_else(|| v.as_str().map(str::to_string)))
.unwrap_or_else(|| "solid".into()),
corner: (first.corners.corners[0].shape, first.corners.corners[0].size),
- wrap_invert: first.wrap.invert,
- wrap_side: serde_json::to_value(first.wrap.side).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(),
- wrap_contour: serde_json::to_value(first.wrap.contour).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(),
+ wrap_invert: tw.invert,
++ wrap_side: serde_json::to_value(tw.side).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(),
++ wrap_contour: serde_json::to_value(tw.contour).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(),
locked: first.locked,
})
}