Skip to content

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

Merge contour-wrap (update): a line meets the wrap from its top to its baseline; an image's contour stops at its frame (#384)

aionggcb83b6071a31
diff --cc crates/compose/src/lib.rs
index be136c567,5ade72645..5156dbfa9
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@@ -428,67 -415,51 +471,75 @@@ fn rings_band_extent(rings: &[Vec<Point
/// 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>,
++ outline: impl FnOnce() -> Option<(designcraft_geom::BezPath, 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, frame)| {
- let c = Contour::of(&path, inv * xf, other.wrap.offsets[0])?;
- Some(match frame {
- Some(frame) => c.within(&frame, inv * xf),
- None => c,
- })
- },
- );
+ // A custom boundary already includes the offsets.
+ if let Some(custom) = wrap.path.as_ref().and_then(|p| Contour::of(&p.to_bezpath(), inv * xf, 0.0)) {
+ let rect = custom.bounds();
+ let contour = matches!(wrap.mode, WrapMode::BoundingBox | WrapMode::Contour).then_some(custom);
+ return Exclusion { rect, mode: wrap.mode, side, contour, after: None };
+ }
- let contour = if wrap.mode == WrapMode::Contour { outline() } else { None }.and_then(|path| Contour::of(&path, inv * xf, o[0]));
++ let contour = if wrap.mode == WrapMode::Contour { outline() } else { None }.and_then(|(path, frame)| {
++ let c = Contour::of(&path, inv * xf, o[0])?;
++ Some(match frame {
++ Some(frame) => c.within(&frame, inv * xf),
++ None => c,
++ })
++ });
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, after: None }
}
- /// The outline a contour wrap of `kind` around frame `it` follows, in the frame's inner space.
- /// Bounding Box follows the part of the placed graphic the frame shows; Same As Clipping follows
- /// the graphic's clipping path when it has one; detected edges, alpha channels and image paths need
- /// the image, so they follow the frame's path (as other frames do).
- fn contour_path(it: &Item, kind: designcraft_doc::ContourType) -> designcraft_geom::BezPath {
-/// The outline a contour wrap follows, in the item's inner space, and for an outline taken from
-/// the placed graphic, the frame path that clips it. 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, Option<designcraft_geom::BezPath>) {
++/// The outline a contour wrap of `kind` around frame `it` follows, in the frame's inner space, and
++/// for an outline taken from the placed graphic, the frame path that clips it. Bounding Box
++/// follows the part of the placed graphic the frame shows; Same As Clipping follows the graphic's
++/// clipping path when it has one; detected edges, alpha channels and image paths need the image,
++/// so they follow the frame's path (as other frames do).
++fn contour_path(it: &Item, kind: designcraft_doc::ContourType) -> (designcraft_geom::BezPath, Option<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()
+ if kind == designcraft_doc::ContourType::SameAsClipping
+ && let Some((path, _)) = it.graphic().and_then(|g| g.clip_region())
{
- return path;
- 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), Some(frame));
- }
++ return (path, Some(frame));
+ }
+ if kind == designcraft_doc::ContourType::BoundingBox
+ && let Some(r) = it.graphic().and_then(|g| g.shown_bounds(it.inner_bounds()))
+ {
- return designcraft_geom::kurbo::Shape::to_path(&r, 0.1);
++ return (designcraft_geom::kurbo::Shape::to_path(&r, 0.1), Some(frame));
}
- designcraft_geom::corners::apply(&it.path, &it.corners)
+ (frame, None)
}
/// One frame of the thread, ready for composition.
@@@ -1359,72 -1123,20 +1406,72 @@@ fn compose_with_db(doc: &Document, stor
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));
+ }
+ }
+ }
}
- // 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 line_start = glyphs.get(s).map_or(prange.start, |g| g.byte);
let mut tries = 0;
loop {
- let Some((nb, segs)) = wrap_slot(f, col, baseline, asc, desc, jump, base_size, rtl, line_start, &holds) else {
- let segs = free_slots(f, col, baseline - asc, baseline, base_size, rtl);
- let segs: Vec<(f64, f64)> = segs.into_iter().skip_while(|seg| !holds(seg)).collect();
++ let Some((nb, segs)) = wrap_slot(f, col, baseline, asc, jump, base_size, rtl, line_start, &holds) 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();
@@@ -2745,104 -2288,17 +2792,104 @@@ fn line_metrics
desc = desc.max(g.descent - shift.min(0.0));
lead = lead.max(g.leading);
}
- (asc, desc, lead)
+ if !own_text {
+ // Only a label (an empty list paragraph): as an empty paragraph.
+ let face = face();
+ tops.typo_ascent = face.typo_ascent * base_size / face.upem;
+ tops.em = em_box_top(&face, base_size);
+ }
+ (asc, tops, desc, lead)
+}
+
+/// How a line clears Jump Object wraps. The line occupies `[baseline − top, baseline]` (its leading,
+/// or its first baseline offset at the top of a column) and must not overlap the wrap; it may hang its
+/// descenders into the wrap. Below a wrap it moves down from its place in whole `step`s until it clears
+/// the wrap bottom (`step` 0: its top lands on the wrap bottom).
+#[derive(Clone, Copy, Debug)]
+struct Jump {
+ top: f64,
+ step: f64,
+}
+
+/// Slack for float error when a line is tested against a Jump Object wrap's edges.
+const JUMP_EPS: f64 = 1e-6;
+
- /// The first baseline at or below `baseline` where a line with ascent `asc` and descent `desc` has
- /// free segments in `col` one of which `holds` the line (its first word fits), and the segments
- /// from that one on (see [`free_slots`], never empty); None if there are none above the column
- /// bottom. `line_start` is the story byte the line starts at (see
++/// The first baseline at or below `baseline` where a line with ascent `asc` has free segments in
++/// `col`, from its top to its baseline, one of which `holds` the line (its first word fits), and
++/// the segments from that one on (see [`free_slots`], never empty); None if there are none above
++/// the column bottom. `line_start` is the story byte the line starts at (see
+/// [`Exclusion::wraps_line`]).
+///
+/// A line under a Jump Object wrap moves below it as `jump` says. Around a rectangular wrap the
+/// free space only grows where one in the line's band ends: the search jumps from one such bottom
+/// edge to the next, and a line that clears a wrap has its top exactly on the wrap's bottom. A
+/// contour's width changes within its box, so beside one the search moves down 1 pt at a time.
+#[allow(clippy::too_many_arguments)]
+fn wrap_slot(
+ f: &FrameSpec,
+ col: Rect,
+ baseline: f64,
+ asc: f64,
- desc: f64,
+ jump: Jump,
+ size: f64,
+ rtl: bool,
+ line_start: usize,
+ holds: &dyn Fn(&(f64, f64)) -> bool,
+) -> Option<(f64, Vec<(f64, f64)>)> {
+ let top = jump.top.max(0.0);
+ let mut b = baseline;
+ // Each step passes at least one wrap; the cap bounds hostile geometry.
+ for _ in 0..4000 {
+ let jumped = f
+ .exclusions
+ .iter()
+ .filter(|e| e.mode == WrapMode::JumpObject && e.wraps_line(line_start))
+ .map(|e| e.rect)
+ .filter(|r| r.x0 < col.x1 && r.x1 > col.x0 && b > r.y0 + JUMP_EPS && b - top < r.y1 - JUMP_EPS)
+ .fold(f64::NEG_INFINITY, |m, r| m.max(r.y1));
+ b = if jumped > f64::NEG_INFINITY {
+ if jump.step > 0.0 {
+ // Whole steps from the line's own place (at least one step past the line above).
+ baseline + ((jumped + top - baseline - JUMP_EPS / 2.0) / jump.step).ceil().max(0.0) * jump.step
+ } else {
+ jumped + top
+ }
+ } else {
+ // Segments before the first that `holds` the line's first word stay empty.
+ let segs: Vec<(f64, f64)> =
- free_slots(f, col, b - asc, b + desc, size, rtl, line_start).into_iter().skip_while(|seg| !holds(seg)).collect();
++ free_slots(f, col, b - asc, b, size, rtl, line_start).into_iter().skip_while(|seg| !holds(seg)).collect();
+ if !segs.is_empty() {
+ return Some((b, segs));
+ }
- let (y0, y1) = (b - asc, b + desc);
++ let (y0, y1) = (b - asc, b);
+ let in_band = || {
+ f.exclusions
+ .iter()
+ .filter(|e| e.mode != WrapMode::JumpObject && e.wraps_line(line_start))
+ .filter(|e| e.rect.y0 < y1 && e.rect.y1 > y0)
+ };
+ let edge = in_band().fold(f64::INFINITY, |m, e| m.min(e.rect.y1)) + asc;
+ if in_band().any(|e| e.contour.is_some()) { edge.min(b + 1.0) } else { edge }
+ };
+ if b.is_nan() || b > col.y1 {
+ return None;
+ }
+ }
+ None
}
- /// Free segments of `col` in the band `y0..y1`, in the order text fills them (left to right, or
+ /// Free segments of `col` in the band `y0..y1` (a line's top to its baseline: descenders may reach
+ /// into the wrap), 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)> {
+/// object that lets text through on both sides has a segment on each side. When an object cuts
+/// the column, segments narrower than 1.5 em of `size` are skipped (slivers beside it); a column
+/// no object reaches is free however narrow (a one-character frame such as an article's closing
+/// tombstone). `line_start` is the story byte the line starts at (see [`Exclusion::wraps_line`]).
+#[allow(clippy::too_many_arguments)]
+fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, size: f64, rtl: bool, line_start: usize) -> Vec<(f64, f64)> {
let mut free = vec![(col.x0, col.x1)];
- for ex in &f.exclusions {
+ let mut cut = false;
+ for ex in f.exclusions.iter().filter(|e| e.wraps_line(line_start)) {
let r = ex.rect;
let overlaps_band = r.y0 < y1 && r.y1 > y0;
let blocked = match ex.mode {
@@@ -2914,19 -2359,17 +2961,19 @@@ fn estimate_slots
let mut v = Vec::with_capacity(n + carry.len());
v.extend_from_slice(carry);
let mut b = first;
+ let mut jump = jump;
+ // Own-story anchored objects whose anchor is in these lines wrap only the lines after it: the
+ // rest is broken again once that line is set.
+ let line_start = glyphs.first().map_or(0, |g| g.byte);
while v.len() < n + carry.len() {
- let slots = match wrap_slot(f, col, b, size * 0.8, size * 0.25, jump, size, rtl, line_start, &|_| true) {
- let mut tries = 0;
- let slots = loop {
- let s = free_slots(f, col, b - size * 0.8, b, size, rtl);
- if !s.is_empty() {
- break s;
++ let slots = match wrap_slot(f, col, b, size * 0.8, jump, size, rtl, line_start, &|_| true) {
+ 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);
+ vec![(col.x0, col.x1)]
}
};
v.extend(slots);