DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge contour-wrap (update): Text wrap: words stay whole beside wrap objects; a segment too narrow for its word stays empty
aiongge8d38d13e359
diff --cc crates/compose/src/lib.rsindex fde73582f,55b119701..00097bf4c--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -1288,94 -1048,48 +1288,107 @@@ fn compose_with_db(doc: &Document, storfor (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 x0, mut x1) = (col.x0, col.x1);- let continues = !carry.is_empty();- let mut baseline;+ // A wrap segment that can't hold the line's first word whole stays empty and the+ // text goes on in the next segment or line (a word wider than the column is split+ // wherever it lands).+ let ind = pp.left_indent + pp.right_indent + if line_no == 0 { pp.first_line_indent } else { 0.0 };+ let need = if f.exclusions.is_empty() {+ 0.0+ } else {+ let w = breaker::first_word_width(glyphs.get(s..).unwrap_or_default(), hyph_after.get(s..).unwrap_or_default(), &spacing);+ if w > col.width() - ind { 0.0 } else { w }+ };+ let holds = |&(a, b): &(f64, f64)| b - a - ind + 0.01 >= need;+ // The line takes the next segment of a line already placed, the one the breaker+ // set it for.+ let mut continues = false;+ let mut baseline = carry_baseline;+ let mut grid_end = None;- if continues {- // The next segment of a line already placed.- baseline = carry_baseline;+ if let Some(i) = carry.iter().position(holds) {+ continues = i == 0;+ grid_end = carry_grid;- (x0, x1) = carry.remove(0);+ (x0, x1) = carry.get(i).copied().unwrap_or((x0, x1));+ carry.drain(..=i);} 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));+ }+ }+ }}- // 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) else {- let segs = free_slots(f, col, baseline - asc, baseline + desc, 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, desc, 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();@@@ -2667,87 -2241,7 +2680,90 @@@ fn line_metricsdesc = desc.max(g.descent - shift.min(0.0));lead = lead.max(g.leading);}- (asc, desc, lead)+ if !own_text {+ // Only a label (an empty list paragraph): as an empty paragraph.+ let face = face();+ tops.typo_ascent = face.typo_ascent * base_size / face.upem;+ tops.em = em_box_top(&face, base_size);+ }+ (asc, tops, desc, lead)+}++/// How a line clears Jump Object wraps. The line occupies `[baseline − top, baseline]` (its leading,+/// or its first baseline offset at the top of a column) and must not overlap the wrap; it may hang its+/// descenders into the wrap. Below a wrap it moves down from its place in whole `step`s until it clears+/// the wrap bottom (`step` 0: its top lands on the wrap bottom).+#[derive(Clone, Copy, Debug)]+struct Jump {+ top: f64,+ step: f64,+}++/// Slack for float error when a line is tested against a Jump Object wrap's edges.+const JUMP_EPS: f64 = 1e-6;++/// The first baseline at or below `baseline` where a line with ascent `asc` and descent `desc` has- /// free segments in `col`, and those segments (see [`free_slots`], never empty); None if there are- /// none above the column bottom. `line_start` is the story byte the line starts at (see++/// free segments in `col` one of which `holds` the line (its first word fits), and the segments++/// from that one on (see [`free_slots`], never empty); None if there are none above the column++/// bottom. `line_start` is the story byte the line starts at (see+/// [`Exclusion::wraps_line`]).+///+/// A line under a Jump Object wrap moves below it as `jump` says. Around a rectangular wrap the+/// free space only grows where one in the line's band ends: the search jumps from one such bottom+/// edge to the next, and a line that clears a wrap has its top exactly on the wrap's bottom. A+/// contour's width changes within its box, so beside one the search moves down 1 pt at a time.+#[allow(clippy::too_many_arguments)]+fn wrap_slot(+ f: &FrameSpec,+ col: Rect,+ baseline: f64,+ asc: f64,+ desc: f64,+ jump: Jump,+ size: f64,+ rtl: bool,+ line_start: usize,++ holds: &dyn Fn(&(f64, f64)) -> bool,+) -> Option<(f64, Vec<(f64, f64)>)> {+ let top = jump.top.max(0.0);+ let mut b = baseline;+ // Each step passes at least one wrap; the cap bounds hostile geometry.+ for _ in 0..4000 {+ let jumped = f+ .exclusions+ .iter()+ .filter(|e| e.mode == WrapMode::JumpObject && e.wraps_line(line_start))+ .map(|e| e.rect)+ .filter(|r| r.x0 < col.x1 && r.x1 > col.x0 && b > r.y0 + JUMP_EPS && b - top < r.y1 - JUMP_EPS)+ .fold(f64::NEG_INFINITY, |m, r| m.max(r.y1));+ b = if jumped > f64::NEG_INFINITY {+ if jump.step > 0.0 {+ // Whole steps from the line's own place (at least one step past the line above).+ baseline + ((jumped + top - baseline - JUMP_EPS / 2.0) / jump.step).ceil().max(0.0) * jump.step+ } else {+ jumped + top+ }+ } else {- let segs = free_slots(f, col, b - asc, b + desc, size, rtl, line_start);++ // Segments before the first that `holds` the line's first word stay empty.++ let segs: Vec<(f64, f64)> = free_slots(f, col, b - asc, b + desc, size, rtl, line_start).into_iter().skip_while(|seg| !holds(seg)).collect();+ if !segs.is_empty() {+ return Some((b, segs));+ }+ let (y0, y1) = (b - asc, b + desc);+ let in_band = || {+ f.exclusions+ .iter()+ .filter(|e| e.mode != WrapMode::JumpObject && e.wraps_line(line_start))+ .filter(|e| e.rect.y0 < y1 && e.rect.y1 > y0)+ };+ let edge = in_band().fold(f64::INFINITY, |m, e| m.min(e.rect.y1)) + asc;+ if in_band().any(|e| e.contour.is_some()) { edge.min(b + 1.0) } else { edge }+ };+ if b.is_nan() || b > col.y1 {+ return None;+ }+ }+ None}/// Free segments of `col` in the band `y0..y1`, in the order text fills them (left to right, or@@@ -2827,19 -2311,17 +2843,19 @@@ fn estimate_slotslet 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) {- 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, 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);diff --cc crates/compose/src/tests.rsindex 70b733f67,c5a48558b..7ee7149cc--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -428,42 -187,60 +428,96 @@@ fn wrap_on_both_sides_sets_text_left_thassert!(!cs.is_overset());}+/// Same As Clipping follows a placed graphic's clipping path: beside a triangle that widens+/// downwards, text reaches further in at the narrow top than at the wide bottom.+#[test]+fn same_as_clipping_wrap_follows_the_clipping_path() {+ use designcraft_geom::{PathData, Point, SubPath};+ let (mut d, sid, _) = doc_with(&[LOREM; 4].join(" "), Rect::new(0.0, 0.0, 300.0, 800.0), ParaAttrs::default());+ let lid = d.default_layer();+ let id = ItemId(d.alloc());+ let mut it = designcraft_doc::Item::new(+ id,+ lid,+ designcraft_doc::Shape::Rectangle,+ designcraft_geom::shapes::rectangle(Rect::new(150.0, 100.0, 300.0, 300.0)),+ );+ let triangle = PathData::single(SubPath::polyline(&[Point::new(75.0, 0.0), Point::new(150.0, 200.0), Point::new(0.0, 200.0)], true));+ it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {+ asset: designcraft_doc::AssetId(1),+ size: (150.0, 200.0),+ xf: designcraft_geom::Affine::translate((150.0, 100.0)),+ clip: Some(std::sync::Arc::new(designcraft_doc::ClippingPath::new(designcraft_doc::ClippingKind::DetectEdges, triangle))),+ auto_fit: Default::default(),+ fit_align: 0,+ crop: [0.0; 4],+ wrap: Default::default(),+ });+ it.wrap.mode = WrapMode::Contour;+ it.wrap.side = WrapSide::LeftSide;+ it.wrap.contour = designcraft_doc::ContourType::SameAsClipping;+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let beside: Vec<&Line> = cs.frames[0].lines.iter().filter(|l| l.baseline - l.ascent > 100.0 && l.baseline + l.descent < 300.0).collect();+ let (top, bottom) = (beside.first().unwrap().x1, beside.last().unwrap().x1);+ assert!(top > bottom + 40.0, "top {top}, bottom {bottom}");+ assert!(bottom < 160.0, "the bottom lines stop near the triangle's base: {bottom}");+}++ /// LOREM beside an ellipse wrapped on both sides along its contour that leaves a sliver (about+ /// 20 pt at its middle) between it and the frame's right edge.+ fn sliver_wrap(para: ParaAttrs) -> (Document, StoryId, String) {+ let text = [LOREM; 4].join(" ");+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 800.0), para);+ let lid = d.default_layer();+ let id = ItemId(d.alloc());+ let mut it =+ designcraft_doc::Item::new(id, lid, designcraft_doc::Shape::Oval, designcraft_geom::shapes::ellipse(Rect::new(150.0, 100.0, 276.0, 220.0)));+ it.wrap.mode = WrapMode::Contour;+ it.wrap.side = WrapSide::BothSides;+ it.wrap.offsets = [4.0; 4];+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ (d, sid, text)+ }++ #[test]+ fn words_stay_whole_beside_a_wrap_sliver() {+ for align in [Align::Left, Align::LeftJustified] {+ for hyphenate in [true, false] {+ let (d, sid, text) = sliver_wrap(ParaAttrs { align: Some(align), hyphenate: Some(hyphenate), ..Default::default() });+ let ex = &frame_specs(&d, sid)[0].exclusions[0];+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let word = |i: usize| text.as_bytes().get(i).is_some_and(u8::is_ascii_alphanumeric);+ let mut empty_slivers = 0;+ for (i, l) in lines.iter().enumerate() {+ let line = &text[l.range.clone()];+ // A line ends inside a word only at a hyphenation point.+ assert!(l.hyphenated || !(word(l.range.end - 1) && word(l.range.end)), "{align:?} {hyphenate}: split word in {line:?}");+ // Every word fits its segment whole.+ for g in l.glyphs.iter().filter(|g| g.visible) {+ assert!(g.x + g.adv <= l.x1 + 0.5, "{align:?} {hyphenate}: {line:?} overflows its {}..{} segment", l.x0, l.x1);+ }+ // A left segment beside the object whose sliver stays empty: the next word doesn't fit it.+ let Some((_, b)) = ex.contour.as_ref().unwrap().band_extent(l.baseline - l.ascent, l.baseline + l.descent) else { continue };+ let next = lines.get(i + 1);+ if l.x1 > b || 300.0 - b < 18.0 || next.is_some_and(|n| n.baseline == l.baseline) {+ continue;+ }+ let Some(next) = next else { continue };+ let first = text[next.range.clone()].split(' ').next().unwrap_or_default();+ let w: f64 = next.glyphs.iter().filter(|g| g.byte < next.range.start + first.len()).map(|g| g.adv).sum();+ assert!(w > 300.0 - b, "{align:?} {hyphenate}: {first:?} ({w}) fits the {} pt sliver beside {line:?}", 300.0 - b);+ empty_slivers += 1;+ }+ if !hyphenate {+ assert!(empty_slivers > 0, "{align:?}: no sliver stays empty");+ }+ assert!(!cs.is_overset());+ }+ }+ }+#[test]fn one_sided_wrap_leaves_the_other_side_empty() {for (side, right) in [(WrapSide::RightSide, true), (WrapSide::LeftSide, false), (WrapSide::LargestArea, false)] {