DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #295: Text: Split Columns sets a paragraph in sub-columns within its column
aiongg57801d86a577
diff --cc crates/compose/src/lib.rsindex ab8b36f5a,ebf65a08b..89f5646e9--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -813,17 -753,23 +824,32 @@@ fn compose_with_db(doc: &Document, stor// the next column.let spanning = matches!(pp.span_columns, SpanColumns::Span(n) if n != 1);span_paras[pi] = spanning;- let next_column = |cur: &mut Cursor| if spanning { cur.next_frame() } else { cur.next_column(&cols) };+ // Consecutive paragraphs with the same Split Columns settings share a split block; within+ // it, a paragraph moves on to the next sub-column.+ let split_cfg = SplitCfg::of(&pp);+ split_paras[pi] = split_cfg.is_some();+ if cur.split.is_some_and(|s| Some(s.cfg) != split_cfg) {+ cur.split = None;+ }+ let next_column = |cur: &mut Cursor| {+ if spanning {+ cur.next_frame()+ } else if cur.can_next_sub() {+ cur.next_sub()+ } else {+ cur.next_column(&cols)+ }+ };+ let go = |cur: &mut Cursor, start| match start {+ StartParagraph::NextColumn => next_column(cur),+ start => cur.start(start, &cols, frames, doc),+ };// Paragraph start options.+ if let Some(start) = after_break+ && cur.last_baseline.is_some()+ {+ go(&mut cur, start);+ }if force_col[pi] {next_column(&mut cur);}@@@ -905,23 -858,13 +938,24 @@@let col = cur.clip(base);// A spanning paragraph isn't held to the balanced bottom of the columns above it.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_first = cur.next_baseline(f, col, base_leading, base_chars.size * 0.75, &pp);- let slots = estimate_slots(f, col, est_first, base_leading, base_chars.size, &glyphs[g0..], &pp, line_no);+ 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 };+ let est_first = cur.next_baseline(f, col, base_leading, est_asc, est_tops, &pp);+ 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 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..];@@@ -966,50 -886,70 +1000,75 @@@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;- }- // Wrap: push the line down until a slot exists.+ baseline = snap(baseline);+ // 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, lead, asc, tops);let mut tries = 0;loop {- match free_slot(f, col, baseline - asc, baseline + desc, base_size) {- Some((a, b)) => {- x0 = a;- x1 = b;- break;- }- None => {- baseline += 1.0;- tries += 1;- if baseline > col.y1 || tries > 4000 {- break;- }- }+ 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;}+ baseline = snap(baseline);}}- let capped = line_cap[pi] == Some(line_no) && line_no > col_first_line;+ 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).let line_notes = if notes.active() { notes.refs_in(line_glyphs) } else { Vec::new() };let col_w = cols[cur.fi][cur.col.min(cols[cur.fi].len() - 1)].width();let reserve = notes.reserve(doc, cur.fi, cur.col, &line_notes, col_w, f, opts);let reserve = if cur.last_baseline.is_none() { notes.reserve(doc, cur.fi, cur.col, &[], col_w, f, opts) } else { reserve };- let fits = baseline + desc <= col.y1 - reserve + 0.01 && !capped;+ // A horizontal text frame's bottom inset limits the last baseline, not+ // the font's descender box. Descenders remain in the line metrics and may+ // hang below that edge. Paths, vertical text, inline objects and text above+ // reserved footnotes keep the full extent to prevent collisions.+ let fit_descent = if f.opts.path.is_some()+ || f.vertical+ || reserve > 0.0+ || line_glyphs.iter().any(|g| sub_objects.get(&g.byte).is_some_and(|o| !o.custom))+ {+ desc+ } else {+ 0.0+ };+ let fits = baseline + fit_descent <= col.y1 - reserve + 0.01 && !capped;if !fits {- if !capped {+ if cur.can_next_sub() {+ g0 = s;+ cur.next_sub();+ col_first_line = line_no;+ moved = true;+ break;+ }+ // A split block that doesn't fit above its trial bottom: re-lay it lower.+ if let Some(key) = cur.split_key()+ && limit_of(&split_limits, key).is_some_and(f64::is_finite)+ {+ let j = if split_trial.as_ref().is_some_and(|t| t.key == key) {+ trial_failed(&mut split_trial, &mut split_limits, split_runs < split_budget)+ } else {+ set_limit(&mut split_limits, key, Some(f64::INFINITY));+ Some(key.2)+ };+ if let Some(j) = j {+ split_runs += 1;+ rewind(j, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap);+ pi = j;+ continue 'paras;+ }+ }+ // Keep options don't apply between a split block's lines.+ if !capped && cur.split.is_none_or(|s| s.part_lines == 0) {let ctx = KeepCtx {pi,line_no,@@@ -1238,9 -1131,49 +1302,50 @@@let r = &pp.rule_below;let y = l.baseline + r.offset;let (x0, x1) = if r.column_width { (l.x0, l.x1) } else { (l.x0, l.end_x) };- ft.decos.push(Deco { rect: Rect::new(x0 + r.left_indent, y, x1 - r.right_indent, y + r.weight), color: r.color.clone(), tint: r.tint });+ let (color, tint) = rule_color(r, &below);+ ft.decos.push(Deco { rect: Rect::new(x0 + r.left_indent, y, x1 - r.right_indent, y + r.weight), color, tint });}+ // The end of a split block: text after it continues below its deepest sub-column, which+ // are balanced first. A block that ends the story fills its sub-columns in turn.+ if let Some(sb) = cur.split {+ let next =+ story.paras.get(pi + 1).filter(|_| story.para_table(pi + 1).is_none()).and_then(|p| SplitCfg::of(&doc.styles.resolve_para(p).0));+ if next != Some(sb.cfg) {+ cur.split = None;+ let part = out.frames.get(cur.fi).and_then(|ft| {+ let lines = ft.lines.get(sb.line0?..)?;+ let top = lines.first().map(|l| l.baseline - l.ascent)?;+ let deepest = lines.iter().map(|l| (l.baseline, l.descent)).max_by(|a, b| (a.0 + a.1).total_cmp(&(b.0 + b.1)))?;+ Some((sb.top.unwrap_or(top), deepest))+ });+ if pi + 1 < np+ && let Some((top, (baseline, descent))) = part+ {+ let key = (cur.fi, cur.col, sb.para);+ let active = split_trial.as_ref().is_some_and(|t| t.key == key);+ if !active && let Some(t) = split_trial.take() {+ set_limit(&mut split_limits, t.key, None);+ }+ if sb.part_lines > 1 && (active || limit_of(&split_limits, key).is_none() && split_runs < split_budget) {+ let bottom = baseline + descent;+ let mut t = split_trial.take().unwrap_or(Trial { key, span: pi, lo: top, hi: bottom, tries: 0, done: false });+ // This layout fits: its bottom is the best so far.+ t.hi = t.hi.min(bottom);+ let next = if t.done { t.hi } else { t.next() };+ set_limit(&mut split_limits, key, Some(next));+ if !t.done {+ split_trial = Some(t);+ split_runs += 1;+ rewind(key.2, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap);+ pi = key.2;+ continue 'paras;+ }+ }+ cur.last_baseline = Some(baseline);+ cur.last_descent = descent;+ }+ }+ }cur.pending += pp.space_after;pi += 1;}diff --cc crates/compose/src/tests.rsindex 3f726d033,e40d91889..f34ae4cd2--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -3968,221 -2072,101 +3968,320 @@@ fn spanning_paragraph_in_rtl_and_verticassert!(cs.frames[0].lines.iter().any(|l| l.para == h));}+/// A heading spanning the columns mid-frame: text above it is balanced over the columns, text+/// after it flows below it, and each gutter's rule stops above the heading and resumes below it.+#[test]+fn column_rules_break_around_a_spanning_paragraph_between_bands() {+ let (mut d, sid, fid, h) = span_doc(2, 4, Rect::new(0.0, 0.0, 450.0, 700.0));+ {+ let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options;+ o.column_rule = true;+ o.column_rule_weight = 1.0;+ o.column_rule_color = "[Black]".into();+ }+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let ft = &cs.frames[0];+ assert_no_overlap(ft);+ let span: Vec<&Line> = ft.lines.iter().filter(|l| l.para == h).collect();+ assert!(!span.is_empty());+ let top = span.iter().map(|l| l.baseline - l.ascent).fold(f64::INFINITY, f64::min);+ let bottom = span.iter().map(|l| l.baseline + l.descent).fold(f64::NEG_INFINITY, f64::max);+ assert!(ft.lines.iter().any(|l| l.para < h), "text above the heading");+ assert!(ft.lines.iter().any(|l| l.para > h && l.column > 0 && l.baseline > bottom), "text after the heading flows below it");+ let rules: Vec<Rect> = ft.decos.iter().filter(|dc| dc.color == "[Black]").map(|dc| dc.rect).collect();+ let mut gutters: Vec<f64> = rules.iter().map(|r| r.center().x).collect();+ gutters.sort_by(f64::total_cmp);+ gutters.dedup_by(|a, b| (*a - *b).abs() < 1e-6);+ assert_eq!(gutters.len(), 2, "{rules:?}");+ for x in gutters {+ let here: Vec<&Rect> = rules.iter().filter(|r| (r.center().x - x).abs() < 1e-6).collect();+ assert!(here.iter().all(|r| r.y1 <= top + 1e-9 || r.y0 >= bottom - 1e-9), "a rule cuts the heading {top}..{bottom}: {here:?}");+ assert!(here.iter().any(|r| r.y1 <= top + 1e-9), "rule above the heading at {x}: {here:?}");+ assert!(here.iter().any(|r| (r.y0 - bottom).abs() < 1e-9), "rule resumes below the heading at {x}: {here:?}");+ }+}++#[test]+fn justified_line_with_a_tab_justifies_the_text_after_its_last_tab() {+ // InDesign justifies only the text after a line's last (left) tab; tab stops stay aligned.+ let stop = |align| designcraft_doc::TabStop { position: 100.0, align, leader: String::new(), align_on: String::new() };+ let text = "Name\t42 and some words\u{2028}more";+ let x_of = |l: &Line, byte: usize| l.glyphs.iter().find(|g| g.byte == byte && g.len > 0).map(|g| g.x).unwrap();+ let left = ParaAttrs { align: Some(Align::LeftJustified), tabs: Some(vec![stop(TabAlign::Left)]), ..Default::default() };+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), left.clone());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = all_lines(&cs)[0];+ assert!((l.end_x - l.x1).abs() < 0.6, "line with a left tab ends at {} not {}", l.end_x, l.x1);+ assert!((x_of(l, 5) - 100.0).abs() < 0.5, "text after the tab starts at the stop: {}", x_of(l, 5));+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs { align: Some(Align::Left), ..left });+ let ragged = compose_story(&d, sid, &ComposeOptions::default());+ let r = all_lines(&ragged)[0];+ for byte in 0..4 {+ assert!((x_of(l, byte) - x_of(r, byte)).abs() < 1e-6, "text before the tab keeps its natural position");+ }++ // After a right tab the line stays as set.+ let right = ParaAttrs { align: Some(Align::LeftJustified), tabs: Some(vec![stop(TabAlign::Right)]), ..Default::default() };+ let (d, sid, _) = doc_with("Name\t42\u{2028}more", Rect::new(0.0, 0.0, 300.0, 100.0), right);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = all_lines(&cs)[0];+ assert!((l.end_x - 100.0).abs() < 0.5, "right-tab line ends at its stop: {}", l.end_x);++ // A footnote's number and tab separator: its first line is justified like the others.+ let (mut d, sid, fid) = doc_with("Body text.", Rect::new(0.0, 0.0, 200.0, 400.0), ParaAttrs::default());+ let note = ParaFormat { para: ParaAttrs { align: Some(Align::LeftJustified), ..Default::default() }, ..Default::default() };+ d.story_mut(sid).unwrap().insert_note(4, LOREM, note);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let n = &cs.frame(fid).unwrap().notes[0];+ let lines = all_lines(&n.text);+ assert!(lines.len() > 2);+ for l in &lines[..lines.len() - 1] {+ assert!((l.end_x - l.x1).abs() < 0.6, "footnote line ends at {} not {}", l.end_x, l.x1);+ }+ assert!((x_of(lines[0], 0) - 36.0).abs() < 0.5, "note text starts at the default tab stop: {}", x_of(lines[0], 0));+}++#[test]+fn mojikumi_justification_after_a_tab_keeps_the_text_before_it() {+ // Justification (mojikumi included) adjusts only the text after a line's last tab.+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};+ let stop = designcraft_doc::TabStop { position: 100.0, align: TabAlign::Left, leader: String::new(), align_on: String::new() };+ let compose = |align| {+ let para =+ ParaAttrs { align: Some(align), mojikumi: Some("MojikumiTable/Elastic".into()), tabs: Some(vec![stop.clone()]), ..Default::default() };+ let (mut d, sid, _) = doc_with("A1A1\tA1A1", Rect::new(0.0, 0.0, 300.0, 100.0), para);+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {+ name: "Elastic".into(),+ based_on: "SimpChineseDefault".into(),+ overrides: vec![MojikumiAki {+ target_class: 18,+ side_class: 25,+ after: true,+ minimum: 0.0,+ desired: 0.0,+ maximum: 5.0,+ priority: 1,+ ..Default::default()+ }],+ });+ compose_story(&d, sid, &ComposeOptions::default())+ };+ let justified = compose(Align::FullyJustified);+ let ragged = compose(Align::Left);+ let (l, r) = (all_lines(&justified)[0], all_lines(&ragged)[0]);+ assert!(l.end_x > r.end_x + 1.0, "the text after the tab stretches: {} vs {}", l.end_x, r.end_x);+ let x_of = |l: &Line, byte: usize| l.glyphs.iter().find(|g| g.byte == byte && g.len > 0).map(|g| g.x).unwrap();+ for byte in 0..5 {+ assert!((x_of(l, byte) - x_of(r, byte)).abs() < 1e-6, "byte {byte} before the tab moved: {} vs {}", x_of(l, byte), x_of(r, byte));+ }+}++#[test]+fn list_first_line_wraps_at_the_column_edge_after_its_label() {+ use designcraft_doc::{ListType, TabStop};+ // A hanging indent (left 18, first line −18): the label sits at the column start, a tab+ // after it reaches the left indent (an implicit stop when no explicit stop comes first), and+ // the first line wraps at the same right edge as the others.+ let right_edge = |l: &Line, source: &str| {+ let space = |g: &&PlacedGlyph| g.len > 0 && source.get(g.byte..).and_then(|s| s.chars().next()).is_some_and(char::is_whitespace);+ l.glyphs.iter().filter(|g| g.visible && !space(g)).map(|g| g.x + g.adv).fold(0.0, f64::max)+ };+ let text_start = |l: &Line| l.glyphs.iter().find(|g| g.len > 0 && g.visible).map_or(f64::NAN, |g| g.x);+ let stop = |position: f64| TabStop { position, align: TabAlign::Left, leader: String::new(), align_on: String::new() };+ let text = format!("{LOREM}\n{LOREM}");+ // (list, separator, explicit tab stops, where line 0's text starts past the column start:+ // None = right after the label, wherever that is).+ let cases = [+ (ListType::Bullets, "\t", None, Some(18.0)),+ (ListType::Numbers, "\t", None, Some(18.0)),+ (ListType::Numbers, "\t", Some(vec![stop(12.0)]), Some(12.0)),+ (ListType::Numbers, "\t", Some(vec![stop(30.0)]), Some(18.0)),+ (ListType::Bullets, " ", None, None),+ (ListType::Numbers, "\u{2003}", None, None),+ ];+ // Justified too: only the text after the tab stretches (#284).+ for (align, (list, sep, tabs, first_at)) in [Align::Left, Align::LeftJustified].into_iter().flat_map(|a| cases.clone().map(|c| (a, c))) {+ let para = ParaAttrs {+ align: Some(align),+ list_type: Some(list),+ list_separator: Some(sep.into()),+ left_indent: Some(18.0),+ first_line_indent: Some(-18.0),+ tabs: tabs.clone(),+ ..Default::default()+ };+ let (d, sid, _) = doc_with(&text, Rect::new(36.0, 36.0, 300.0, 400.0), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let col = cs.frames[0].columns[0];+ let lines = &cs.frames[0].lines;+ let what = format!("{align:?} {list:?} {sep:?} {tabs:?}");+ assert!(lines.len() >= 6, "{what}: {} lines", lines.len());+ for (i, l) in lines.iter().enumerate() {+ let right = right_edge(l, &text);+ assert!(right <= col.x1 + 0.01, "{what}: line {i} ends at {right}, past the column's {}", col.x1);+ let start = text_start(l) - col.x0;+ if !l.first_in_para {+ assert!((start - 18.0).abs() < 0.01, "{what}: line {i} text starts at {start}, not the left indent");+ } else if let Some(at) = first_at {+ assert!((start - at).abs() < 0.01, "{what}: line {i} text starts at {start}, not {at}");+ } else {+ assert!(start > 0.0, "{what}: line {i} text starts at {start}");+ }+ if l.first_in_para {+ assert!(l.glyphs.first().is_some_and(|g| g.len == 0 && (g.x - col.x0).abs() < 0.01), "{what}: the label leads line {i}");+ }+ }+ }+}++/// Lines of `text` set in a frame `width` wide, with `tracking` on every character.+fn tracked_lines(text: &str, width: f64, para: ParaAttrs, tracking: f64) -> Vec<Line> {+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, width, 4000.0), para);+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.tracking = Some(tracking));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset(), "overset at width {width}");+ all_lines(&cs).into_iter().cloned().collect()+}++#[test]+fn a_word_longer_than_the_line_breaks_at_the_column_edge() {+ use designcraft_doc::Composer;+ let word = "n".repeat(60);+ let long = format!("Then {word} and on");+ for tracking in [0.0, 740.0] {+ // Natural advances, from one unbroken line.+ let natural: HashMap<usize, f64> =+ tracked_lines(&long, 1e5, ParaAttrs::default(), tracking)[0].glyphs.iter().map(|g| (g.byte, g.adv)).collect();+ for composer in [Composer::Paragraph, Composer::SingleLine] {+ for align in [Align::Left, Align::LeftJustified] {+ let para = ParaAttrs { composer: Some(composer), align: Some(align), hyphenate: Some(false), ..Default::default() };+ let lines = tracked_lines(&long, 72.0, para, tracking);+ let what = format!("{composer:?} {align:?} tracking {tracking}");+ assert!(lines.len() >= 4, "{what}: {} lines", lines.len());+ for l in &lines {+ let ink: Vec<_> = l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).collect();+ let right = ink.iter().map(|g| g.x + g.adv.min(natural[&g.byte])).fold(l.x0, f64::max);+ assert!(l.end_x <= l.x1 + 0.02 && right <= l.x1 + 0.02, "{what}: line {:?} ends at {} past {}", l.range, l.end_x, l.x1);+ for w in ink.windows(2) {+ assert!(w[1].x >= w[0].x + natural[&w[0].byte] - 1e-6, "{what}: glyphs overlap at {}", w[1].byte);+ }+ }+ }+ }+ }+}++#[test]+fn a_line_that_exactly_fills_the_measure_fits() {+ use designcraft_doc::Composer;+ let text = "#knowyourplastic";+ let one = &tracked_lines(text, 1e5, ParaAttrs::default(), 0.0)[0];+ // The measure a rounding error short of the natural width.+ let width = one.end_x - one.x0 - 0.005;+ for composer in [Composer::Paragraph, Composer::SingleLine] {+ for align in [Align::Left, Align::LeftJustified] {+ let para = ParaAttrs { composer: Some(composer), align: Some(align), ..Default::default() };+ let lines = tracked_lines(text, width, para, 0.0);+ assert_eq!(lines.len(), 1, "{composer:?} {align:?}: {:?}", lines.iter().map(|l| l.range.clone()).collect::<Vec<_>>());+ }+ }+}+++ // ---------- split columns ----------++ /// A story of a body paragraph, `split` paragraphs in split columns and `after` body paragraphs.+ /// Returns the index of the first split paragraph.+ fn split_doc(split: usize, after: usize, rect: Rect, cfg: (u32, f64, f64)) -> (Document, StoryId, ItemId, usize) {+ let mut paras: Vec<&str> = vec![LOREM; 1 + split + after];+ paras[0] = "An introduction set at the full measure of the column, before the split block.";+ let (mut d, sid, fid) = doc_with(¶s.join("\n"), rect, ParaAttrs::default());+ let st = d.story_mut(sid).unwrap();+ for p in &mut st.paras[1..=split] {+ p.para.span_columns = Some(SpanColumns::Split(cfg.0));+ p.para.split_inside_gutter = Some(cfg.1);+ p.para.split_outside_gutter = Some(cfg.2);+ }+ (d, sid, fid, 1)+ }++ /// The sub-columns of `col`: (x0, x1) of each.+ fn sub_columns(col: Rect, (n, inside, outside): (u32, f64, f64)) -> Vec<(f64, f64)> {+ let w = (col.width() - 2.0 * outside - inside * (n - 1) as f64) / n as f64;+ (0..n).map(|k| col.x0 + outside + k as f64 * (w + inside)).map(|x| (x, x + w)).collect()+ }++ /// The split paragraphs' lines, by sub-column.+ fn split_lines<'a>(ft: &'a FrameText, paras: std::ops::Range<usize>, subs: &[(f64, f64)]) -> Vec<Vec<&'a Line>> {+ let mut by_sub = vec![Vec::new(); subs.len()];+ for l in ft.lines.iter().filter(|l| paras.contains(&l.para)) {+ let k = subs.iter().position(|&(x0, x1)| (l.x0 - x0).abs() < 1e-6 && (l.x1 - x1).abs() < 1e-6);+ let k = k.unwrap_or_else(|| panic!("line of para {} at {}..{} is in no sub-column of {subs:?}", l.para, l.x0, l.x1));+ by_sub[k].push(l);+ }+ by_sub+ }++ #[test]+ fn split_paragraphs_are_set_in_balanced_sub_columns() {+ for cfg in [(2, 12.0, 10.0), (3, 6.0, 0.0)] {+ let (d, sid, _, s) = split_doc(2, 1, Rect::new(0.0, 0.0, 400.0, 700.0), cfg);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ let ft = &cs.frames[0];+ assert_no_overlap(ft);+ let by_sub = split_lines(ft, s..s + 2, &sub_columns(ft.columns[0], cfg));+ let counts: Vec<usize> = by_sub.iter().map(Vec::len).collect();+ assert!(counts.iter().all(|&n| n > 0), "{cfg:?}: {counts:?}");+ assert!(counts.iter().max().unwrap() - counts.iter().min().unwrap() <= 1, "{cfg:?}: balanced {counts:?}");+ // Every sub-column starts on the same baseline, below the paragraph before the block.+ let firsts: Vec<f64> = by_sub.iter().map(|v| v[0].baseline).collect();+ assert!(firsts.iter().all(|b| (b - firsts[0]).abs() < 1e-6), "{cfg:?}: {firsts:?}");+ let intro = ft.lines.iter().filter(|l| l.para == 0).map(|l| line_box(l).1).fold(f64::NEG_INFINITY, f64::max);+ assert!(firsts[0] > intro && firsts[0] < intro + 20.0, "{cfg:?}: block at {} after {intro}", firsts[0]);+ // The text after the block continues at the full measure below its deepest sub-column.+ let bottom = by_sub.iter().flatten().map(|l| line_box(l).1).fold(f64::NEG_INFINITY, f64::max);+ let next = ft.lines.iter().find(|l| l.para == s + 2).unwrap();+ assert!(line_box(next).0 >= bottom - 0.5 && line_box(next).0 < bottom + 20.0, "{cfg:?}: {} after {bottom}", line_box(next).0);+ assert!((next.x0 - ft.columns[0].x0).abs() < 1e-6 && (next.x1 - ft.columns[0].x1).abs() < 1e-6);+ }+ }++ #[test]+ fn split_block_in_the_second_column_and_at_the_story_end() {+ let cfg = (2, 12.0, 0.0);+ let (mut d, sid, fid, s) = split_doc(3, 0, Rect::new(0.0, 0.0, 540.0, 400.0), cfg);+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;+ d.story_mut(sid).unwrap().paras[s].para.start_paragraph = Some(StartParagraph::NextColumn);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ let ft = &cs.frames[0];+ assert_no_overlap(ft);+ assert!(ft.lines.iter().filter(|l| l.para >= s).all(|l| l.column == 1));+ let by_sub = split_lines(ft, s..s + 3, &sub_columns(ft.columns[1], cfg));+ // Nothing follows the block: it fills its first sub-column to the bottom of the frame, then+ // the next.+ let (a, b) = (&by_sub[0], &by_sub[1]);+ assert!(!a.is_empty() && !b.is_empty() && a.len() > b.len() + 1, "{} and {} lines", a.len(), b.len());+ let low = a.last().unwrap();+ assert!(low.baseline + low.descent > 400.0 - low.leading, "the first sub-column ends at {}", low.baseline);+ assert!((a[0].baseline - b[0].baseline).abs() < 1e-6);+ }++ #[test]+ fn split_block_flows_into_the_next_column() {+ let cfg = (2, 12.0, 0.0);+ let (mut d, sid, fid, s) = split_doc(6, 1, Rect::new(0.0, 0.0, 540.0, 200.0), cfg);+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let ft = &cs.frames[0];+ assert_no_overlap(ft);+ for c in 0..2 {+ let in_col: Vec<&Line> = ft.lines.iter().filter(|l| l.column == c as u32).collect();+ let lines: Vec<&Line> = in_col.iter().copied().filter(|l| (s..s + 6).contains(&l.para)).collect();+ let subs = sub_columns(ft.columns[c], cfg);+ assert!(subs.iter().all(|&(x0, x1)| lines.iter().any(|l| (l.x0 - x0).abs() < 1e-6 && (l.x1 - x1).abs() < 1e-6)), "column {c}");+ }+ // The block continues at the top of the second column.+ let top = ft.lines.iter().find(|l| l.column == 1).unwrap();+ assert!((s..s + 6).contains(&top.para) && top.baseline < 20.0);+ }diff --cc crates/idml/src/tests.rsindex 85878c24d,3eb4a1fbb..51c9a071b--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -1452,501 -895,19 +1452,518 @@@ fn layers_import_and_export_in_stackingassert_eq!(back.spreads[0].items[0].layer, back.layers[1].id);}+/// Synthetic forward references: both a body anchor and a footnote anchor own+/// a group containing a text frame whose story is serialized later.+#[test]+fn round_trips_anchored_text_frames_in_body_and_footnotes() {+ use designcraft_doc::{AnchorPosition, AnchoredObject, Content, Item, ItemId};+ use std::sync::Arc;+ let mut d = Document::new(&NewDocument::default());+ let layer = d.default_layer();+ let (_, body) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(20.0, 20.0, 400.0, 600.0), layer, "Body", ParaFormat::default()).unwrap();+ d.story_mut(body).unwrap().insert_note(4, "Note", ParaFormat::default());+ for in_note in [false, true] {+ let (frame, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 60.0, 30.0), layer, "Symbol", ParaFormat::default()).unwrap();+ let child = d.item(frame).unwrap().clone();+ d.spread_mut(SpreadRef::Doc(0)).unwrap().items.retain(|i| i.id != frame);+ let mut group = Item::new(ItemId(d.alloc()), layer, Shape::Group, Default::default());+ group.content = Content::Group { items: vec![Arc::new(child)] };+ let anchor = AnchoredObject::new(group, AnchorPosition::Inline { y_offset: 2.0 });+ let story = d.story_mut(body).unwrap();+ if in_note {+ Arc::make_mut(&mut story.notes[0]).text.insert_object(0, anchor);+ } else {+ story.insert_object(0, anchor);+ }+ }+ d.check().unwrap();+ for _ in 0..2 {+ d = import_idml(&export_idml(&d)).unwrap();+ d.check().unwrap();+ assert_eq!(d.stories.len(), 3);+ let body = d.stories.values().find(|s| !s.notes.is_empty()).unwrap();+ assert_eq!(body.notes.len(), 1);+ assert_eq!(body.objects.len(), 1);+ assert_eq!(body.notes[0].text.objects.len(), 1);+ let children: Vec<_> = d.anchored_items().into_iter().filter(|(_, i)| i.text_frame().is_some()).collect();+ assert_eq!(children.len(), 2);+ for (_, item) in children {+ let story = d.story(item.text_frame().unwrap().story).unwrap();+ assert_eq!(story.text, "Symbol");+ assert_eq!(story.frames, vec![item.id]);+ }+ }+}++#[test]+fn composite_references_resolve_by_identity_and_export_as_objects() {+ let map = DESIGNMAP.replace("</Document>", r#"+ <CompositeFont Self="CompositeFont/opaque%3a17" Name="Mixed%3a literal">+ <CompositeFontEntry Name="Base" FontStyle="$ID/Regular"><Properties><AppliedFont type="string">Source Serif 4</AppliedFont></Properties></CompositeFontEntry>+ <CompositeFontEntry Name="Digits" CustomCharacters="0123456789" FontStyle="$ID/Bold" RelativeSize="80" HorizontalScale="90" VerticalScale="110" BaselineShift="5" ScaleOption="false"><Properties><AppliedFont type="string">Source Sans 3</AppliedFont></Properties></CompositeFontEntry>+ </CompositeFont></Document>"#);+ let styles = STYLES+ .replace("<AppliedFont type=\"string\">Source Serif 4</AppliedFont>", "<AppliedFont type=\"object\">CompositeFont/opaque%3a17</AppliedFont>");+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Content>A1</Content><Footnote><ParagraphStyleRange><CharacterStyleRange><Content>B2</Content></CharacterStyleRange></ParagraphStyleRange></Footnote></CharacterStyleRange></ParagraphStyleRange></Story></idPkg:Story>"#;+ let bytes = zip_files(&[+ ("designmap.xml", &map),+ ("Resources/Styles.xml", &styles),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", SPREAD),+ ("Stories/Story_s1.xml", story),+ ]);+ let d = import_idml(&bytes).unwrap();+ let f = &d.styles.composite_fonts[0];+ assert_eq!(f.name, "Mixed%3a literal", "display names are not encoded identifiers");+ let body = d.stories.values().find(|s| !s.notes.is_empty()).unwrap();+ for text in [body.as_ref(), &body.notes[0].text] {+ let (_, base) = d.styles.resolve_para(&text.paras[0]);+ let p = d.styles.resolve_char(&base, &text.chars[0].format);+ assert_eq!(d.styles.composite_font(&p.font_family), Some(f));+ }+ let output = export_idml(&d);+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&output)).unwrap();+ let mut xml = String::new();+ std::io::Read::read_to_string(&mut zip.by_name("Resources/Styles.xml").unwrap(), &mut xml).unwrap();+ assert!(xml.contains("<AppliedFont type=\"object\">CompositeFont/Mixed%253a literal</AppliedFont>"), "{xml}");+ let back = import_idml(&output).unwrap();+ assert_eq!(back.styles.composite_fonts, d.styles.composite_fonts);+}++#[test]+fn malformed_mojikumi_rows_are_not_silently_coerced() {+ let good = r#"<OverrideMojikumiAkiType TargetMojikumiClass="12" SideMojikumiClass="18" SideIsAfterTarget="true" Minimum="0" Desired="0.25" Maximum="0.5" CompressionPriority="3" AkiDoesNotFloat="false"/>"#;+ for (key, value) in [+ ("TargetMojikumiClass", "12.9"),+ ("SideMojikumiClass", "65536"),+ ("Minimum", "NaN"),+ ("Desired", "oops"),+ ("Minimum", "0.4"),+ ("Maximum", "0.1"),+ ("Maximum", "101"),+ ("CompressionPriority", "10"),+ ("AkiDoesNotFloat", "maybe"),+ ] {+ let mut row = crate::xml::parse(good.as_bytes()).unwrap();+ row.set(key, value);+ let mut xml = String::new();+ row.write(&mut xml, 0);+ let map = DESIGNMAP.replace("</Document>", &format!("<MojikumiTable Name=\"Bad\" BasedOnMojikumiSet=\"SimpChineseDefault\"><Properties><OverrideMojikumiAkiList>{xml}</OverrideMojikumiAkiList></Properties></MojikumiTable></Document>"));+ let bytes = zip_files(&[+ ("designmap.xml", &map),+ ("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),+ ]);+ if matches!((key, value), ("Minimum", "0.4") | ("Maximum", "0.1" | "101") | ("CompressionPriority", "10")) {+ // Finite, representable rules survive import even if composition+ // cannot apply them. The resolver supplies a diagnostic instead.+ let document = import_idml(&bytes).unwrap();+ document.check().unwrap();+ assert!(designcraft_doc::mojikumi::Rules::resolve(&document.styles, "MojikumiTable/Bad").is_err());+ let restored = import_idml(&export_idml(&document)).unwrap();+ assert_eq!(restored.styles.mojikumi_tables, document.styles.mojikumi_tables);+ } else {+ let err = import_idml(&bytes).unwrap_err().to_string();+ assert!(err.contains("Mojikumi"), "{key}={value}: {err}");+ }+ }+}++#[test]+fn imports_column_rules_from_frames_and_object_styles() {+ let rule = r#"ColumnRuleOverride="true" ColumnRuleStrokeWidth="2.5" ColumnRuleStrokeColor="Color/Black" ColumnRuleStrokeTint="40"+ ColumnRuleStrokeType="StrokeStyle/$ID/Solid" ColumnRuleOverprintOverride="false" ColumnRuleOffset="-3" ColumnRuleTopInset="6"+ ColumnRuleBottomInset="9" ColumnRuleInsetChainOverride="false""#;+ let styles = format!(+ r#"<ObjectStyle Self="ObjectStyle/Padded" Name="Padded" EnableTextFrameGeneralOptions="true"><TextFramePreference TextColumnCount="2" {rule}/></ObjectStyle>"#+ );+ let d = inset_fixture(&format!(r#"<TextFramePreference TextColumnCount="3" {rule}/>"#), &styles);+ let style = d.styles.object.iter().find(|s| s.name == "Padded").unwrap().text_frame.clone().unwrap();+ for o in [d.spreads[0].items[0].text_frame().unwrap().options.clone(), style] {+ assert!(o.column_rule, "{o:?}");+ assert_eq!(o.column_rule_weight, 2.5);+ assert_eq!(o.column_rule_color, designcraft_color::swatch::BLACK);+ assert!((o.column_rule_tint - 0.4).abs() < 1e-6);+ assert_eq!((o.column_rule_offset, o.column_rule_top_inset, o.column_rule_bottom_inset), (-3.0, 6.0, 9.0));+ }+ // Absent attributes: no rule, InDesign's defaults.+ let d = inset_fixture(r#"<TextFramePreference TextColumnCount="3"/>"#, "");+ assert_eq!(d.spreads[0].items[0].text_frame().unwrap().options, designcraft_doc::TextFrameOptions { columns: 3, ..Default::default() });+}++#[test]+fn column_rules_round_trip() {+ let mut d = small_doc();+ let fid = d.spreads[0].items[0].id;+ let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options;+ o.columns = 2;+ o.column_rule = true;+ o.column_rule_weight = 0.75;+ o.column_rule_color = "Brand".into();+ o.column_rule_tint = 0.5;+ o.column_rule_offset = 1.5;+ o.column_rule_top_inset = 4.0;+ o.column_rule_bottom_inset = 2.0;+ let want = o.clone();+ let bytes = export_idml(&d);+ let back = import_idml(&bytes).unwrap();+ let got = back.spreads[0].items.iter().find_map(|i| i.text_frame().filter(|t| t.options.column_rule)).unwrap().options.clone();+ assert_eq!(got, want);+ // Frames without a rule stay without one.+ let plain = export_idml(&small_doc());+ let back = import_idml(&plain).unwrap();+ assert!(back.spreads.iter().flat_map(|s| &s.items).filter_map(|i| i.text_frame()).all(|t| !t.options.column_rule));+}+/// Fully synthetic style-only table, including sparse based-on attributes and local overrides.+const CASCADE_STYLES: &str = r#"<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">+<RootCellStyleGroup>+ <CellStyle Self="CellStyle/$ID/[None]" Name="$ID/[None]"/>+ <CellStyle Self="cs-base" Name="Base" FillColor="Color/Brand" FillTint="25"+ TopInset="2" LeftInset="3" BottomInset="4" RightInset="5" VerticalJustification="CenterAlign"+ TopEdgeStrokeWeight="2" TopEdgeStrokeColor="Color/Brand" TopEdgeStrokeTint="40" TopEdgeStrokeType="StrokeStyle/$ID/Dashed"+ LeftEdgeStrokeWeight="3" BottomEdgeStrokeWeight="4" RightEdgeStrokeWeight="5"+ AppliedParagraphStyle="ParagraphStyle/CellParagraph"/>+ <CellStyle Self="cs-body" Name="Body" FillTint="50"><Properties><BasedOn type="object">cs-base</BasedOn></Properties></CellStyle>+ <CellStyle Self="cs-left" Name="Left" FillColor="Color/Black" LeftEdgeStrokeWeight="0"><Properties><BasedOn type="object">cs-body</BasedOn></Properties></CellStyle>+ <CellStyle Self="cs-header" Name="Header" FillColor="Color/Paper" BottomEdgeStrokeColor="Color/Brand" BottomEdgeStrokeWeight="6">+ <Properties><BasedOn type="object">cs-body</BasedOn></Properties>+ </CellStyle>+ <CellStyle Self="cs-explicit" Name="Explicit" FillColor="Color/Brand" FillTint="75" TopInset="0"+ TopEdgeStrokeColor="Swatch/None" RightEdgeStrokeTint="30"/>+</RootCellStyleGroup>+<RootParagraphStyleGroup><ParagraphStyle Self="ParagraphStyle/CellParagraph" Name="CellParagraph" PointSize="9"/></RootParagraphStyleGroup>+<RootTableStyleGroup>+ <TableStyle Self="TableStyle/$ID/[No table style]" Name="$ID/[No table style]"+ TopBorderStrokeWeight="7" LeftBorderStrokeWeight="8" BottomBorderStrokeWeight="9" RightBorderStrokeWeight="10"+ StartRowFillCount="0" StartRowFillColor="Color/Brand" StartRowFillTint="20" EndRowFillCount="0" EndRowFillColor="Swatch/None"+ HeaderRegionSameAsBodyRegion="true" FooterRegionSameAsBodyRegion="true"+ LeftColumnRegionSameAsBodyRegion="true" RightColumnRegionSameAsBodyRegion="true"/>+ <TableStyle Self="ts-base" Name="BaseTable" BodyRegionCellStyle="cs-body" HeaderRegionCellStyle="cs-header"+ LeftColumnRegionCellStyle="cs-left" HeaderRegionSameAsBodyRegion="false" LeftColumnRegionSameAsBodyRegion="false">+ <Properties><BasedOn type="string">$ID/[No table style]</BasedOn></Properties>+ </TableStyle>+ <TableStyle Self="ts-child" Name="Table" SpaceBefore="12" StartRowFillCount="1" EndRowFillCount="1">+ <Properties><BasedOn type="object">ts-base</BasedOn></Properties>+ </TableStyle>+ <TableStyle Self="TableStyle/$ID/[Basic Table]" Name="$ID/[Basic Table]" SpaceAfter="17">+ <Properties><BasedOn type="object">ts-child</BasedOn></Properties>+ </TableStyle>+</RootTableStyleGroup></idPkg:Styles>"#;++const CASCADE_STORY: &str = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">+<Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Table AppliedTableStyle="ts-child" HeaderRowCount="1" SpaceBefore="19" RightBorderStrokeColor="Color/Brand">+<Row Name="0" MinimumHeight="24"/><Row Name="1" MinimumHeight="24"/>+<Column Name="0" SingleColumnWidth="60"/><Column Name="1" SingleColumnWidth="60"/><Column Name="2" SingleColumnWidth="60"/>+<Cell Name="0:0" AppliedCellStyle="CellStyle/$ID/[None]"><ParagraphStyleRange><CharacterStyleRange><Content>Header left</Content></CharacterStyleRange></ParagraphStyleRange></Cell>+<Cell Name="1:0" AppliedCellStyle="cs-explicit"><ParagraphStyleRange><CharacterStyleRange><Content>Explicit</Content></CharacterStyleRange></ParagraphStyleRange></Cell>+<Cell Name="2:0" AppliedCellStyle="cs-explicit" FillColor="Swatch/None" FillTint="0" LeftInset="0" VerticalJustification="BottomAlign"+ TopEdgeStrokeWeight="0" RightEdgeStrokeColor="Swatch/None" RightEdgeStrokePriority="7">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle"><CharacterStyleRange><Content>Local</Content></CharacterStyleRange></ParagraphStyleRange>+</Cell>+<Cell Name="0:1" AppliedCellStyle="CellStyle/$ID/[None]"><ParagraphStyleRange><CharacterStyleRange><Content>Left</Content></CharacterStyleRange></ParagraphStyleRange></Cell>+<Cell Name="1:1"><ParagraphStyleRange><CharacterStyleRange><Content>Body</Content></CharacterStyleRange></ParagraphStyleRange></Cell>+<Cell Name="2:1"><ParagraphStyleRange><CharacterStyleRange><Content>Body right</Content></CharacterStyleRange></ParagraphStyleRange></Cell>+</Table></CharacterStyleRange></ParagraphStyleRange></Story></idPkg:Story>"#;++fn fixture_with_table_styles(styles: &str, story: &str) -> Vec<u8> {+ 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),+ ])+}++#[test]+fn table_style_cascade_preserves_sparse_edges_and_local_overrides() {+ let d = import_idml(&fixture_with_table_styles(CASCADE_STYLES, CASCADE_STORY)).unwrap();+ d.check().unwrap();+ let table = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!((table.nrows(), table.ncols()), (2, 3));+ assert_eq!(table.style, "Table");+ assert_eq!(table.options.space_before, 19.0);+ assert_eq!(std::array::from_fn::<_, 4, _>(|i| table.options.border_for(i).weight), [7.0, 8.0, 9.0, 10.0]);+ assert_eq!(table.options.border_for(3).color, "Brand");+ let fills = table.options.alt_rows.as_ref().unwrap();+ assert_eq!((fills.first, fills.next, fills.first_tint), (1, 1, 0.2));+ assert_eq!(fills.first_color, "Brand");+ let header = table.cell(0, 0).unwrap();+ assert_eq!(header.fill, designcraft_color::swatch::PAPER, "header takes precedence over left region");+ assert!(header.style.is_empty(), "a table region does not become AppliedCellStyle");+ assert_eq!(header.insets, [2.0, 3.0, 4.0, 5.0]);+ assert_eq!(header.vj, designcraft_doc::VerticalJustification::Center);+ assert_eq!(header.text.paras[0].style, "CellParagraph");+ assert_eq!(header.strokes[0].weight, 2.0);+ assert_eq!(header.strokes[0].tint, 0.4);+ assert_ne!(header.strokes[0].kind, designcraft_doc::StrokeType::Solid);+ assert_eq!(header.strokes[2].weight, 6.0);+ assert_eq!(header.border_overrides, [true; 4]);+ assert_eq!(header.stroke_defined, [true; 4]);+ assert_eq!(header.stroke_priorities, [0; 4]);+ let explicit = table.cell(0, 1).unwrap();+ assert_eq!(explicit.fill, "Brand");+ assert_eq!(explicit.fill_tint, 0.75);+ assert_eq!(explicit.insets, [0.0, 3.0, 4.0, 5.0]);+ assert_eq!(explicit.strokes[0].weight, 2.0, "color-only override inherits weight");+ assert_eq!(explicit.strokes[0].color, designcraft_color::swatch::NONE);+ assert_eq!(explicit.strokes[3].weight, 5.0);+ assert_eq!(explicit.strokes[3].tint, 0.3);+ let local = table.cell(0, 2).unwrap();+ assert_eq!(local.fill, designcraft_color::swatch::NONE);+ assert_eq!(local.fill_tint, 0.0);+ assert_eq!(local.insets[1], 0.0);+ assert_eq!(local.vj, designcraft_doc::VerticalJustification::Bottom);+ assert_eq!(local.strokes[0].weight, 0.0);+ assert_eq!(local.strokes[3].color, designcraft_color::swatch::NONE);+ assert_eq!(local.stroke_priorities, [0, 0, 0, 7]);+ assert_eq!(local.text.paras[0].style, st::BASIC_PARAGRAPH, "explicit paragraph style wins");+ assert_eq!(table.cell(1, 0).unwrap().fill, designcraft_color::swatch::BLACK);+ assert_eq!(table.cell(1, 0).unwrap().strokes[1].weight, 0.0);+ assert_eq!(table.cell(1, 1).unwrap().fill_tint, 0.5);+ assert_eq!(table.cell(1, 2).unwrap().fill, "Brand");++ let back = import_idml(&export_idml(&d)).unwrap();+ let roundtrip = back.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ for (before, after) in table.cells.iter().zip(&roundtrip.cells) {+ assert_eq!(after.strokes, before.strokes);+ assert_eq!(after.border_overrides, before.border_overrides);+ assert_eq!(after.stroke_priorities, before.stroke_priorities);+ assert_eq!(after.style, before.style);+ assert_eq!(after.fill, before.fill);+ assert_eq!(after.insets, before.insets);+ }+ for i in 0..4 {+ assert_eq!(roundtrip.options.border_for(i), table.options.border_for(i));+ }+ let style = back.styles.cell.iter().find(|s| s.name == "Explicit").unwrap();+ assert_eq!(style.strokes[0].weight, None, "style export keeps absence distinct from zero");+ assert_eq!(style.strokes[0].color.as_deref(), Some(designcraft_color::swatch::NONE));+ assert_eq!(back.styles.table.iter().find(|s| s.name == "Table").unwrap().based_on.as_deref(), Some("BaseTable"));+}++#[test]+fn table_style_same_as_body_flags_and_editable_basic_table_are_inherited() {+ let styles = CASCADE_STYLES.replace(+ "Name=\"Table\" SpaceBefore",+ "Name=\"Table\" HeaderRegionSameAsBodyRegion=\"true\" LeftColumnRegionSameAsBodyRegion=\"true\" SpaceBefore",+ );+ let story = CASCADE_STORY.replace("AppliedTableStyle=\"ts-child\"", "AppliedTableStyle=\"TableStyle/$ID/[Basic Table]\"");+ let d = import_idml(&fixture_with_table_styles(&styles, &story)).unwrap();+ let table = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert!(table.style.is_empty());+ assert_eq!(table.options.space_after, 17.0);+ assert_eq!(table.cell(0, 0).unwrap().fill, "Brand");+ assert_eq!(table.cell(0, 0).unwrap().strokes[2].weight, 4.0);+ assert_eq!(table.cell(1, 0).unwrap().fill, "Brand");+ assert_eq!(table.cell(1, 0).unwrap().strokes[1].weight, 3.0);+}++#[test]+fn table_style_cycles_and_missing_bases_terminate_without_losing_nearest_values() {+ let styles = r#"<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">+<RootCellStyleGroup>+<CellStyle Self="CellStyle/A" Name="A" TopEdgeStrokeWeight="0"><Properties><BasedOn type="object">CellStyle/B</BasedOn></Properties></CellStyle>+<CellStyle Self="CellStyle/B" Name="B" TopEdgeStrokeColor="Color/Brand"><Properties><BasedOn type="object">CellStyle/A</BasedOn></Properties></CellStyle>+<CellStyle Self="CellStyle/Missing" Name="Missing" LeftInset="0"><Properties><BasedOn type="object">CellStyle/Unknown</BasedOn></Properties></CellStyle>+</RootCellStyleGroup><RootTableStyleGroup>+<TableStyle Self="ts-child" Name="A" BodyRegionCellStyle="CellStyle/A"><Properties><BasedOn type="object">TableStyle/B</BasedOn></Properties></TableStyle>+<TableStyle Self="TableStyle/B" Name="B" SpaceAfter="20"><Properties><BasedOn type="object">ts-child</BasedOn></Properties></TableStyle>+</RootTableStyleGroup></idPkg:Styles>"#;+ let d = import_idml(&fixture_with_table_styles(styles, CASCADE_STORY)).unwrap();+ let table = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!(table.options.space_after, 20.0);+ assert_eq!(table.cell(1, 1).unwrap().strokes[0].weight, 0.0);+ assert_eq!(table.cell(1, 1).unwrap().strokes[0].color, "Brand");+ let missing = designcraft_doc::resolve_cell_style(&d.styles.cell, "Missing");+ assert_eq!(missing.inset_overrides[1], Some(0.0));+}++#[test]+fn table_local_alternating_fill_off_survives_named_style_roundtrip() {+ let styles = CASCADE_STYLES.replace(+ "Name=\"Table\" SpaceBefore",+ "Name=\"Table\" StartColumnFillCount=\"1\" EndColumnFillCount=\"1\" StartColumnFillColor=\"Color/Brand\" SpaceBefore",+ );+ let story = CASCADE_STORY.replace("HeaderRowCount=\"1\"", "HeaderRowCount=\"1\" StartRowFillCount=\"0\" StartColumnFillCount=\"0\"");+ let document = import_idml(&fixture_with_table_styles(&styles, &story)).unwrap();+ for document in [&document, &import_idml(&export_idml(&document)).unwrap()] {+ let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert!(table.options.alt_rows.is_none());+ assert!(table.options.alt_cols.is_none());+ }+}++#[test]+fn table_local_fill_counts_enable_inherited_disabled_pattern_colors() {+ let story =+ CASCADE_STORY.replace("AppliedTableStyle=\"ts-child\"", "AppliedTableStyle=\"ts-base\" StartRowFillCount=\"1\" EndRowFillCount=\"1\"");+ let document = import_idml(&fixture_with_table_styles(CASCADE_STYLES, &story)).unwrap();+ let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ let fills = table.options.alt_rows.as_ref().unwrap();+ assert_eq!((fills.first, fills.next), (1, 1));+ assert_eq!(fills.first_color, "Brand");+ assert_eq!(fills.first_tint, 0.2);+}++#[test]+fn table_absent_and_explicit_default_edges_remain_distinct_on_idml_roundtrip() {+ let story = CASCADE_STORY+ .replace("AppliedTableStyle=\"ts-child\"", "AppliedTableStyle=\"Missing\"")+ .replace("Name=\"1:1\"", "Name=\"1:1\" TopEdgeStrokeWeight=\"1\" TopEdgeStrokePriority=\"0\"");+ let document = import_idml(&fixture_with_table_styles(STYLES, &story)).unwrap();+ for document in [&document, &import_idml(&export_idml(&document)).unwrap()] {+ let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!(table.cell(1, 0).unwrap().stroke_defined, [false; 4]);+ assert_eq!(table.cell(1, 1).unwrap().stroke_defined, [true, false, false, false]);+ assert_eq!(table.cell(1, 1).unwrap().border_overrides, [false; 4]);+ assert_eq!(table.cell(1, 1).unwrap().stroke_priorities, [0; 4]);+ }+}++#[test]+fn multiline_table_and_cell_style_bases_resolve() {+ let styles = CASCADE_STYLES.replace(">cs-base</BasedOn>", ">\n cs-base \n</BasedOn>").replace(">ts-base</BasedOn>", ">\n ts-base \n</BasedOn>");+ let document = import_idml(&fixture_with_table_styles(&styles, CASCADE_STORY)).unwrap();+ let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!(table.cell(1, 1).unwrap().strokes[0].weight, 2.0);+ assert_eq!(table.options.border_for(0).weight, 7.0);+}++#[test]+fn legacy_native_documents_export_both_builtin_table_styles_when_missing() {+ let story = CASCADE_STORY.replace("AppliedTableStyle=\"ts-child\"", "AppliedTableStyle=\"TableStyle/$ID/[Basic Table]\"");+ let mut document = import_idml(&fixture_with_story(&story)).unwrap();+ document.styles_mut().table.clear();+ let bytes = export_idml(&document);+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();+ let mut styles = String::new();+ std::io::Read::read_to_string(&mut zip.by_name("Resources/Styles.xml").unwrap(), &mut styles).unwrap();+ assert_eq!(styles.matches("Self=\"TableStyle/$ID/[Basic Table]\"").count(), 1);+ assert_eq!(styles.matches("Self=\"TableStyle/$ID/[No table style]\"").count(), 1);+ let back = import_idml(&bytes).unwrap();+ assert!(back.styles.table.iter().any(|s| s.name == designcraft_doc::BASIC_TABLE));+}++#[test]+fn hostile_table_spans_are_clamped_before_arithmetic() {+ let story = CASCADE_STORY.replace("Name=\"1:1\"", "Name=\"1:1\" RowSpan=\"inf\" ColumnSpan=\"inf\"");+ let document = import_idml(&fixture_with_table_styles(CASCADE_STYLES, &story)).unwrap();+ document.check().unwrap();+ let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!(table.cell(1, 1).unwrap().row_span, 1);+ assert_eq!(table.cell(1, 1).unwrap().col_span, 2);+}++#[test]+fn signed_idml_edge_priorities_roundtrip_without_clamping() {+ let story = CASCADE_STORY.replace(+ "Name=\"1:1\"",+ "Name=\"1:1\" TopEdgeStrokePriority=\"-5\" LeftEdgeStrokePriority=\"-2147483648\" RightEdgeStrokePriority=\"2147483647\"",+ );+ let document = import_idml(&fixture_with_table_styles(CASCADE_STYLES, &story)).unwrap();+ for document in [&document, &import_idml(&export_idml(&document)).unwrap()] {+ let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!(table.cell(1, 1).unwrap().stroke_priorities, [-5, i32::MIN, 0, i32::MAX]);+ }+}++#[test]+fn alternating_table_strokes_inherit_and_roundtrip_without_flattening_cell_edges() {+ let styles = CASCADE_STYLES.replace(+ "Name=\"BaseTable\"",+ "Name=\"BaseTable\" StartRowStrokeCount=\"1\" EndRowStrokeCount=\"1\" StartRowStrokeWeight=\"0\" EndRowStrokeWeight=\"0\" StartRowStrokeColor=\"Color/Paper\" EndRowStrokeColor=\"Color/Brand\" StartColumnStrokeCount=\"2\" EndColumnStrokeCount=\"1\" StartColumnStrokeWeight=\"1\" EndColumnStrokeWeight=\"2\" EndColumnLineStyle=\"StrokeStyle/$ID/Dotted\" SkipFirstAlternatingStrokeColumns=\"1\"",+ ).replace("Name=\"Table\"", "Name=\"Table\" StartRowStrokeTint=\"25\"");+ let story = CASCADE_STORY.replace("HeaderRowCount=\"1\"", "HeaderRowCount=\"1\" EndRowStrokeColor=\"Swatch/None\"");+ let document = import_idml(&fixture_with_table_styles(&styles, &story)).unwrap();+ let before = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ let row = before.options.row_strokes.as_ref().unwrap();+ assert_eq!((row.first, row.next), (1, 1));+ assert_eq!(row.first_stroke.tint, 0.25);+ assert_eq!(row.first_stroke.color, designcraft_color::swatch::PAPER);+ assert_eq!(row.next_stroke.color, designcraft_color::swatch::NONE);+ assert!(!row.uniform_stroke().unwrap().is_visible(), "zero patterns are uniform even when their colors differ");+ let column = before.options.column_strokes.as_ref().unwrap();+ assert_eq!((column.first, column.next, column.skip_first), (2, 1, 1));+ assert_eq!(column.next_stroke.kind, designcraft_doc::StrokeType::Dotted);+ assert!(column.uniform_stroke().is_none(), "nonuniform/skipped patterns are preserved without guessing their phase");+ assert_eq!(before.cell(0, 0).unwrap().strokes[2].weight, 6.0, "cell styles remain higher-precedence edges");+ let back = import_idml(&export_idml(&document)).unwrap();+ let after = back.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!(after.options.row_strokes, before.options.row_strokes);+ assert_eq!(after.options.column_strokes, before.options.column_strokes);+ let style = back.styles.table.iter().find(|s| s.name == "Table").unwrap();+ assert_eq!(style.row_strokes.first_stroke.weight, None);+ assert_eq!(style.row_strokes.first_stroke.tint, Some(0.25));+}++#[test]+fn alternating_table_strokes_local_off_overrides_named_style_on_roundtrip() {+ let styles = CASCADE_STYLES.replace(+ "Name=\"Table\"",+ "Name=\"Table\" StartRowStrokeCount=\"1\" EndRowStrokeCount=\"1\" StartColumnStrokeCount=\"1\" EndColumnStrokeCount=\"1\"",+ );+ let story = CASCADE_STORY.replace(+ "HeaderRowCount=\"1\"",+ "HeaderRowCount=\"1\" StartRowStrokeCount=\"0\" EndRowStrokeCount=\"0\" StartRowStrokeWeight=\"4\" EndRowStrokeColor=\"Color/Brand\" StartColumnStrokeCount=\"0\" EndColumnStrokeCount=\"0\" SkipFirstAlternatingStrokeColumns=\"3\" EndColumnLineStyle=\"StrokeStyle/$ID/Dotted\"",+ );+ let document = import_idml(&fixture_with_table_styles(&styles, &story)).unwrap();+ for document in [&document, &import_idml(&export_idml(&document)).unwrap()] {+ let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ let row = table.options.row_strokes.as_ref().unwrap();+ let column = table.options.column_strokes.as_ref().unwrap();+ assert_eq!((row.first, row.next, column.first, column.next), (0, 0, 0, 0));+ assert!(row.uniform_stroke().is_none());+ assert!(column.uniform_stroke().is_none());+ assert_eq!(row.first_stroke.weight, 4.0);+ assert_eq!(row.next_stroke.color, "Brand");+ assert_eq!(column.skip_first, 3);+ assert_eq!(column.next_stroke.kind, designcraft_doc::StrokeType::Dotted);+ }+}++#[test]+fn complete_uniform_native_style_fields_keep_legacy_identity_on_idml_roundtrip() {+ let mut document = import_idml(&fixture()).unwrap();+ let stroke = designcraft_doc::CellStroke { weight: 3.0, tint: 0.5, ..Default::default() };+ document.styles_mut().cell.push(designcraft_doc::CellStyle {+ name: "Uniform".into(),+ insets: Some([5.0; 4]),+ stroke: Some(stroke.clone()),+ ..Default::default()+ });+ document.styles_mut().table.push(designcraft_doc::TableStyle { name: "Uniform".into(), border: Some(stroke.clone()), ..Default::default() });+ let back = import_idml(&export_idml(&document)).unwrap();+ let cell = back.styles.cell.iter().find(|s| s.name == "Uniform").unwrap();+ assert_eq!(cell.insets, Some([5.0; 4]));+ assert_eq!(cell.stroke.as_ref(), Some(&stroke));+ assert!(cell.strokes.iter().all(designcraft_doc::CellStrokeAttrs::is_empty));+ let table = back.styles.table.iter().find(|s| s.name == "Uniform").unwrap();+ assert_eq!(table.border.as_ref(), Some(&stroke));+ assert!(table.borders.iter().all(designcraft_doc::CellStrokeAttrs::is_empty));+}+++ #[test]+ fn split_columns_import_and_round_trip() {+ 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]" SpanColumnType="SplitColumns" SplitColumnInsideGutter="27" SplitColumnOutsideGutter="4.5">+ <Properties><SpanSplitColumnCount type="short">3</SpanSplitColumnCount></Properties>+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Split list</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#;+ let doc = import_idml(&fixture_with_story(story)).unwrap();+ let para = |d: &Document| d.stories.values().find(|s| s.text.contains("Split list")).unwrap().paras[0].para.clone();+ let a = para(&doc);+ assert_eq!(a.span_columns, Some(designcraft_doc::SpanColumns::Split(3)));+ assert_eq!(a.split_inside_gutter, Some(27.0));+ assert_eq!(a.split_outside_gutter, Some(4.5));+ let b = para(&import_idml(&export_idml(&doc)).unwrap());+ assert_eq!((b.span_columns, b.split_inside_gutter, b.split_outside_gutter), (a.span_columns, a.split_inside_gutter, a.split_outside_gutter));+ }