DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge fix/paragraph-mark-leading: the paragraph mark's size counts in its line's auto leading
aionggd7592ba6e0d1
diff --cc crates/compose/src/lib.rsindex 1d51b3435,4a9cbabac..0ca4f42ea--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -861,20 -762,25 +861,32 @@@ fn compose_with_db(doc: &Document, stor);bidi::resolve_mirroring(&mut glyphs, &bidi_info);apply_desired_spacing(&mut glyphs, &pp);+ mojikumi::apply(&mut glyphs, &doc.styles, &pp.mojikumi);let hyph_after = hyphenation_points(&story.text, &glyphs, &pp, &hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), &base_chars));let base_size = base_chars.size;- let base_leading = match base_chars.leading {- designcraft_doc::Leading::Auto => base_size * pp.auto_leading,+ let spacing = spacing_for(&pp, base_size);+ // An empty paragraph takes its height from its paragraph mark's character format.+ let mark_chars = if glyphs.is_empty() {+ std::borrow::Cow::Owned(doc.styles.resolve_char(&base_chars, story.char_format_of(prange.start)))+ } else {+ std::borrow::Cow::Borrowed(&base_chars)+ };+ let mark_leading = match mark_chars.leading {+ designcraft_doc::Leading::Auto => mark_chars.size * pp.auto_leading,designcraft_doc::Leading::Points(v) => v,};+ // The paragraph mark is a character of the last line: its leading counts there like any+ // other character's. It doesn't set the line's ascent or descent. A hidden or deleted+ // mark takes no room.- let mark_leading = story.text.get(prange.end..).filter(|t| t.starts_with('\n')).and_then(|_| {++ let last_line_mark = story.text.get(prange.end..).filter(|t| t.starts_with('\n')).and_then(|_| {+ let props = doc.styles.resolve_char(&base_chars, story.format_after(prange.end));+ let hidden = props.change == designcraft_doc::ChangeMark::Deleted+ || (!props.conditions.is_empty() && props.conditions.iter().all(|c| sub.hidden_conditions.contains(c)));+ (!hidden).then_some(match props.leading {+ designcraft_doc::Leading::Auto => props.size * pp.auto_leading,+ designcraft_doc::Leading::Points(v) => v,+ })+ });- let spacing = spacing_for(&pp, base_size);// A paragraph set across the columns moves on to the next frame where others move on to// the next column.let spanning = matches!(pp.span_columns, SpanColumns::Span(n) if n != 1);@@@ -1044,14 -925,13 +1056,18 @@@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 lead = match mark_leading {+ 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 = cjk_line_reference(line_glyphs);- let mut baseline = cur.next_baseline(f, col, lead, asc, &pp);+ // Baseline grid: the next grid line at or below.+ let grid = f.grid.filter(|&(_, inc)| {+ inc > 0.0 && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0))+ });+ let snap = |y: f64| grid.map_or(y, |(g_start, inc)| g_start + ((y - g_start) / inc - 1e-6).ceil() * inc);+ let mut baseline = cur.next_baseline(f, col, lead, asc, tops, &pp);if cur.last_baseline.is_some() {baseline += cur.last_reference - reference;}diff --cc crates/compose/src/tests.rsindex 073e0be0f,4380186f9..c7d03b98c--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -4757,288 -2772,21 +4757,307 @@@ fn empty_paragraphs_get_no_bullet_or_nu}}+#[test]+fn tight_word_spacing_does_not_isolate_a_word() {+ // A narrow word-spacing range (100–105%) with some letter spacing and glyph scaling, no+ // hyphenation: lines that need more stretch must open their word spaces, not letter-space a+ // single word across the measure.+ let para = ParaAttrs {+ align: Some(Align::LeftJustified),+ hyphenate: Some(false),+ first_line_indent: Some(9.0),+ word_space_min: Some(1.0),+ word_space_desired: Some(1.03),+ word_space_max: Some(1.05),+ letter_space_min: Some(-0.05),+ letter_space_max: Some(0.05),+ glyph_scale_min: Some(0.99),+ glyph_scale_max: Some(1.01),+ ..Default::default()+ };+ // Short words: any two fit on a line together.+ let text = CORPUS[..2].join(" ");+ for w in (200..=320).step_by(5) {+ let (d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, w as f64, 20000.0), para.clone());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ for l in &lines[..lines.len() - 1] {+ let words = text[l.range.clone()].split_whitespace().count();+ assert!(words > 1, "width {w}: a single-word line {:?}", &text[l.range.clone()]);+ }+ }+}++#[test]+fn fixed_width_spaces_do_not_stretch_on_justified_lines() {+ // Long words in a narrow column: lines stretch past the maximum word spacing. Only the word+ // spaces take that stretch; em, en and thin spaces keep their width.+ let words = ["characteristically", "misunderstanding", "unquestionably", "responsibility", "administration", "photographer"];+ let seps = [" ", "\u{2003}", " ", "\u{2002}", " ", "\u{2009}"];+ let text: String = (0..60).map(|i| format!("{}{}", words[i % words.len()], seps[i % seps.len()])).collect();+ let text = text.trim_end().to_string();+ let fixed = |c: char| matches!(c, '\u{2003}' | '\u{2002}' | '\u{2009}');+ // (character, advance) of each fixed space, per line, and whether the line ends the paragraph.+ let spaces = |align: Align, w: f64| -> Vec<(Vec<(char, f64)>, bool)> {+ let para = ParaAttrs { align: Some(align), hyphenate: Some(false), ..Default::default() };+ let (d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, w, 20000.0), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ all_lines(&cs)+ .iter()+ .map(|l| {+ let found = l.glyphs.iter().filter_map(|g| text[g.byte..].chars().next().filter(|&c| fixed(c)).map(|c| (c, g.adv))).collect();+ (found, l.last_in_para)+ })+ .collect()+ };+ let mut checked = 0;+ for w in [190.0, 230.0, 270.0] {+ let natural: Vec<(char, f64)> = spaces(Align::Left, w).into_iter().flat_map(|l| l.0).collect();+ for (found, last) in spaces(Align::LeftJustified, w) {+ if last {+ continue;+ }+ for (c, a) in found {+ let Some(&(_, n)) = natural.iter().find(|x| x.0 == c) else { continue };+ assert!((a - n).abs() < 1e-6, "width {w}: U+{:04X} is {a:.2} wide, not {n:.2}", c as u32);+ checked += 1;+ }+ }+ }+ assert!(checked > 5, "{checked} fixed spaces on justified lines");+}++#[test]+fn grep_style_in_the_documents_dialect_keeps_short_words_with_the_next() {+ // `\l` (lowercase letter) and `\h` (horizontal space) aren't Rust regex syntax; the style used+ // to be skipped silently.+ let text = "Мы и он в доме и в саду, а она у окна и с книгой в руках у стола.";+ let para = ParaAttrs {+ align: Some(Align::Left),+ grep_styles: Some(vec![designcraft_doc::GrepStyle { style: "nobreak".into(), pattern: r"\b\l{1,2}\h".into() }]),+ ..Default::default()+ };+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 70.0, 1000.0), para);+ let chars = designcraft_doc::CharAttrs { no_break: Some(true), ..Default::default() };+ std::sync::Arc::make_mut(&mut d.styles).character.push(designcraft_doc::CharacterStyle {+ name: "nobreak".into(),+ based_on: None,+ chars,+ shortcut: String::new(),+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!(lines.len() > 3);+ let short = |w: &str| w.chars().count() <= 2 && w.chars().all(char::is_lowercase);+ for l in &lines[..lines.len() - 1] {+ let last = text[l.range.clone()].split_whitespace().last().unwrap_or("");+ assert!(!short(last), "line ends with a short word: {:?}", &text[l.range.clone()]);+ }+}++// ---------- paragraph border and shading ----------++fn bordered(text: &str, rect: Rect, para: ParaAttrs) -> ComposedStory {+ let para = ParaAttrs { border_on: Some(true), border_weights: Some([1.0; 4]), ..para };+ let (d, sid, _) = doc_with(text, rect, para);+ compose_story(&d, sid, &ComposeOptions::default())+}++fn has_curves(bp: &designcraft_geom::BezPath) -> bool {+ bp.elements().iter().any(|e| matches!(e, designcraft_geom::PathEl::CurveTo(..) | designcraft_geom::PathEl::QuadTo(..)))+}++#[test]+fn rounded_border_corners_are_curves_and_dotted_borders_paint_their_gap_first() {+ use designcraft_geom::corners::{Corner, CornerShape};+ let rounded = [Corner { shape: CornerShape::Rounded, size: 6.0 }; 4];+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs { border_corners: Some(rounded), ..Default::default() });+ let paths: Vec<_> = cs.frames[0].decos.iter().filter_map(|dc| dc.path.as_ref()).collect();+ assert_eq!(paths.len(), 1, "one stroked outline");+ assert!(has_curves(paths[0]));+ // Square corners: plain edges, no curves.+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs::default());+ assert!(cs.frames[0].decos.iter().all(|dc| dc.path.is_none()));+ // A dotted border with a gap colour: the gap under the dots.+ let dotted = ParaAttrs { border_type: Some(designcraft_doc::StrokeType::Dotted), border_gap_color: Some("[Paper]".into()), ..Default::default() };+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), dotted);+ let colors: Vec<&str> = cs.frames[0].decos.iter().filter(|dc| dc.path.is_some()).map(|dc| dc.color.as_str()).collect();+ assert_eq!(colors, ["[Paper]", "[Black]"]);+}++/// The width of the widest border edge (the top and bottom edges span the box).+fn border_width(cs: &ComposedStory) -> f64 {+ cs.frames[0].decos.iter().filter(|dc| dc.color == "[Black]").map(|dc| dc.rect.width()).fold(0.0, f64::max)+}++#[test]+fn a_text_width_border_is_narrower_than_a_column_width_one() {+ let rect = Rect::new(0.0, 0.0, 300.0, 200.0);+ let column = border_width(&bordered("Short", rect, ParaAttrs::default()));+ let text = border_width(&bordered("Short", rect, ParaAttrs { border_width: Some(designcraft_doc::BoxWidth::Text), ..Default::default() }));+ assert!((column - 302.0).abs() < 1e-6, "column and both side strokes: {column}");+ assert!(text > 2.0 && text < 60.0, "text: {text}");+}++/// Edges of a plain border by frame column: (column, count).+fn edges_per_column(cs: &ComposedStory) -> Vec<usize> {+ let cols = &cs.frames[0].columns;+ cols.iter()+ .map(|c| {+ cs.frames[0].decos.iter().filter(|dc| dc.color == "[Black]" && dc.rect.center().x > c.x0 - 2.0 && dc.rect.center().x < c.x1 + 2.0).count()+ })+ .collect()+}++#[test]+fn a_split_paragraph_closes_its_border_in_each_column_only_when_set_to() {+ let text = format!("{LOREM} {LOREM}");+ let compose = |display: bool| {+ let para = ParaAttrs { border_on: Some(true), border_weights: Some([1.0; 4]), border_display_if_splits: Some(display), ..Default::default() };+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 400.0, 90.0), para);+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;+ compose_story(&d, sid, &ComposeOptions::default())+ };+ let open = compose(false);+ assert!(open.frames[0].lines.iter().any(|l| l.column == 1), "the paragraph reaches the second column");+ // Open at the split: top and sides in the first column, sides and bottom in the second.+ assert_eq!(edges_per_column(&open), [3, 3]);+ assert_eq!(edges_per_column(&compose(true)), [4, 4]);+}++#[test]+fn consecutive_paragraphs_with_the_same_border_share_one_box() {+ let compose = |merge: bool| {+ let para = ParaAttrs { space_after: Some(10.0), border_merge: Some(merge), ..Default::default() };+ bordered("One\nTwo\nThree", Rect::new(0.0, 0.0, 300.0, 300.0), para)+ };+ let merged = compose(true);+ let edges: Vec<Rect> = merged.frames[0].decos.iter().filter(|dc| dc.color == "[Black]").map(|dc| dc.rect).collect();+ assert_eq!(edges.len(), 4, "one box: {edges:?}");+ let lines = &merged.frames[0].lines;+ let (first, last) = (&lines[0], &lines[lines.len() - 1]);+ let left = edges.iter().find(|r| r.height() > r.width()).unwrap();+ assert!((left.y0 - (first.baseline - first.ascent)).abs() < 1e-6 && (left.y1 - (last.baseline + last.descent)).abs() < 1e-6, "{left:?}");+ assert_eq!(compose(false).frames[0].decos.iter().filter(|dc| dc.color == "[Black]").count(), 12, "a box each");+}++#[test]+fn shading_clips_to_the_frame_and_can_stay_off_print() {+ let para = ParaAttrs {+ shading_on: Some(true),+ shading_offsets: Some([50.0; 4]),+ shading_clip: Some(true),+ shading_nonprinting: Some(true),+ ..Default::default()+ };+ let (d, sid, _) = doc_with("Shaded", Rect::new(0.0, 0.0, 300.0, 200.0), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let area = cs.frames[0].columns[0];+ let shade = &cs.frames[0].decos[0];+ assert!(shade.nonprinting);+ assert!(shade.rect.x0 >= area.x0 - 1e-6 && shade.rect.y0 >= area.y0 - 1e-6 && shade.rect.x1 <= area.x1 + 1e-6, "{:?} in {area:?}", shade.rect);+}++// ---------- span space, bullets and numbering ----------++#[test]+fn space_before_and_after_a_span_moves_the_span_and_the_text_below() {+ let at = |before: f64, after: f64| {+ let (mut d, sid, _, h) = span_doc(1, 1, Rect::new(0.0, 0.0, 600.0, 800.0));+ let p = &mut d.story_mut(sid).unwrap().paras[h].para;+ p.span_space_before = Some(before);+ p.span_space_after = Some(after);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let first = |pi: usize| cs.frames[0].lines.iter().find(|l| l.para == pi).map(|l| l.baseline).unwrap();+ (first(h), first(h + 1))+ };+ let (span0, below0) = at(0.0, 0.0);+ let (span1, below1) = at(24.0, 0.0);+ assert!((span1 - span0 - 24.0).abs() < 0.01, "{span0} → {span1}");+ assert!((below1 - below0 - 24.0).abs() < 0.01, "the text below moves with it");+ let (span2, below2) = at(0.0, 18.0);+ assert!((span2 - span0).abs() < 0.01 && (below2 - below0 - 18.0).abs() < 0.01, "{below0} → {below2}");+}++/// The first line of each paragraph.+fn first_lines(cs: &ComposedStory) -> Vec<&Line> {+ all_lines(cs).into_iter().filter(|l| l.first_in_para).collect()+}++#[test]+fn a_right_aligned_number_ends_at_the_line_start() {+ use designcraft_doc::{ListAlign, ListType};+ let compose = |align: ListAlign| {+ let para = ParaAttrs {+ list_type: Some(ListType::Numbers),+ number_align: Some(align),+ left_indent: Some(36.0),+ first_line_indent: Some(-18.0),+ ..Default::default()+ };+ let (d, sid, _) = doc_with("Item", Rect::new(0.0, 0.0, 300.0, 200.0), para);+ compose_story(&d, sid, &ComposeOptions::default())+ };+ // The label "1.\t": its first two glyphs are the number and the full stop.+ let cs = compose(ListAlign::Left);+ let col = cs.frames[0].columns[0];+ let l = first_lines(&cs)[0];+ assert!((l.glyphs[0].x - (col.x0 + 18.0)).abs() < 0.01, "left: starts at the line start");+ let text_x = l.glyphs.iter().find(|g| g.len > 0).unwrap().x;+ let cs = compose(ListAlign::Right);+ let l = first_lines(&cs)[0];+ let end = l.glyphs[1].x + l.glyphs[1].adv;+ assert!((end - (col.x0 + 18.0)).abs() < 0.01, "right: ends at the line start ({end})");+ assert!((l.glyphs.iter().find(|g| g.len > 0).unwrap().x - text_x).abs() < 0.01, "the text stays at the tab stop");+}++#[test]+fn level_two_numbering_restarts_after_level_one() {+ let para = numbered(designcraft_doc::NumberStyle::Arabic, "^1.^#");+ let (mut d, sid, _) = doc_with("A\nB\nC\nD\nE", Rect::new(0.0, 0.0, 300.0, 300.0), para);+ for (p, level) in d.story_mut(sid).unwrap().paras.iter_mut().zip([1, 2, 2, 1, 2]) {+ p.para.list_level = Some(level);+ }+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ // `^1` is level 1's number, `^#` the paragraph's own level.+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["1.1", "1.1", "1.2", "2.2", "2.1"]);+ // Without the restart, level 2 carries on.+ for p in &mut d.story_mut(sid).unwrap().paras {+ p.para.restart_numbers = Some(false);+ }+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["1.1", "1.1", "1.2", "2.2", "2.3"]);+}++#[test]+fn the_tab_position_places_the_text_after_the_label() {+ use designcraft_doc::ListType;+ let compose = |tab: Option<f64>| {+ let para = ParaAttrs { list_type: Some(ListType::Bullets), list_tab: Some(tab), ..Default::default() };+ let (d, sid, _) = doc_with("Item", Rect::new(0.0, 0.0, 300.0, 200.0), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let col = cs.frames[0].columns[0];+ first_lines(&cs)[0].glyphs.iter().find(|g| g.len > 0).unwrap().x - col.x0+ };+ assert!((compose(Some(50.0)) - 50.0).abs() < 0.01);+ assert!((compose(None) - 36.0).abs() < 0.01, "the default tab stop");+}+++ #[test]+ fn paragraph_mark_size_counts_in_its_line_auto_leading() {+ let gaps = |mark_size: f64| {+ let (mut d, sid, _) = doc_with("One\nTwo\nThree", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(7..8, |f| f.over.size = Some(mark_size));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let b: Vec<f64> = all_lines(&cs).iter().map(|l| l.baseline).collect();+ assert_eq!(b.len(), 3);+ (b[1] - b[0], b[2] - b[1])+ };+ // A 12 pt line ending in a 14 pt return: 14 × 120% above it, the next line unchanged.+ let (above, below) = gaps(14.0);+ assert!((above - 16.8).abs() < 1e-6, "{above}");+ assert!((below - 14.4).abs() < 1e-6, "{below}");+ let (above, below) = gaps(12.0);+ assert!((above - 14.4).abs() < 1e-6, "{above}");+ assert!((below - 14.4).abs() < 1e-6, "{below}");+ }