DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #298: Lists: numbering formats and expressions from IDML; an empty paragraph gets no bullet or number
aiongg8ae759a84899
diff --cc crates/compose/src/lib.rsindex 89f5646e9,3324eec29..2486093ed--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -758,40 -699,27 +759,42 @@@ fn compose_with_db(doc: &Document, stor);}}+ // Rules in Text Color: the colour of the paragraph's first character (rule above) and last+ // character (rule below).+ let text_color = |g: Option<&Glyph>| {+ g.and_then(|g| table.styles.get(g.style as usize))+ .map_or((base_chars.fill.clone(), base_chars.fill_tint), |s| (s.fill.clone(), s.fill_tint))+ };+ let (above, below) = (text_color(sp.glyphs.iter().find(|g| g.len > 0)), text_color(sp.glyphs.iter().rev().find(|g| g.len > 0)));+ let rule_color = |r: &designcraft_doc::Rule, text: &(String, f32)| {+ if r.color == designcraft_doc::TEXT_COLOR { text.clone() } else { (r.color.clone(), r.tint) }+ };+ let drop_cap = split_drop_cap(db, &mut sp.glyphs, drop_end, pp.drop_cap_lines, base_leading, base_cap, drop_grid, drop_align);// List labels take the default super/subscript settings.let label_env = shape::TypeEnv { adv: Default::default(), ..env };- match pp.list_type {+ let list_label = match pp.list_type {+ // An empty paragraph has no bullet or number, and the numbering carries on past it.- designcraft_doc::ListType::Numbers | designcraft_doc::ListType::Bullets if prange.is_empty() => {}++ designcraft_doc::ListType::Numbers | designcraft_doc::ListType::Bullets if prange.is_empty() => None,designcraft_doc::ListType::Numbers if !pp.list_name.is_empty() => {// A named list: carries on past other paragraphs (and from earlier stories).let n = named_numbers.get(pi).copied().flatten().unwrap_or(1);- Some(format!("{}.{}", pp.number_style.format(n), pp.list_separator))- let label = pp.number_label(n);- prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, label_env, &mut table);++ Some(pp.number_label(n))}designcraft_doc::ListType::Numbers => {- list_counter = pp.start_at.map_or(list_counter + 1, |s| s.max(1));- Some(format!("{}.{}", pp.number_style.format(list_counter), pp.list_separator))+ list_counter = pp.start_at.map_or(list_counter.saturating_add(1), |s| s.max(1));- let label = pp.number_label(list_counter);- prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, label_env, &mut table);++ Some(pp.number_label(list_counter))+ }- designcraft_doc::ListType::Bullets => Some(format!("{}{}", pp.bullet_char, pp.list_separator)),++ designcraft_doc::ListType::Bullets => Some(pp.bullet_label()),+ designcraft_doc::ListType::None => {+ list_counter = 0;+ None}- designcraft_doc::ListType::Bullets => {- let label = pp.bullet_label();- prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, label_env, &mut table);+ };+ if let Some(label) = list_label {+ let n = prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, label_env, &mut table);+ for g in sp.glyphs.iter_mut().take(n) {+ g.list_label = true;}- designcraft_doc::ListType::None => list_counter = 0,}if pi == 0&& let Some(label) = &opts.labeldiff --cc crates/compose/src/tests.rsindex f34ae4cd2,948119bd9..d3079f714--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -3968,320 -2210,73 +3968,391 @@@ 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);+}+++ /// Each paragraph's list label as text: its label glyphs (laid before the paragraph's own text)+ /// matched back to characters of the label font; tabs and other invisible glyphs are skipped.+ fn list_labels(cs: &ComposedStory, alphabet: &str) -> Vec<String> {+ all_lines(cs)+ .iter()+ .filter(|l| l.first_in_para)+ .map(|l| {+ l.glyphs+ .iter()+ .take_while(|g| g.len == 0)+ .filter(|g| g.visible)+ .map(|g| alphabet.chars().find(|c| g.face.glyph_for(*c) == g.gid).unwrap_or('?'))+ .collect()+ })+ .collect()+ }++ const LABEL_CHARS: &str = "0123456789ABCDIVXabcdivx.\u{2022} Tabel";++ fn numbered(style: designcraft_doc::NumberStyle, expression: &str) -> ParaAttrs {+ ParaAttrs {+ list_type: Some(designcraft_doc::ListType::Numbers),+ number_style: Some(style),+ number_expression: Some(expression.into()),+ ..Default::default()+ }+ }++ #[test]+ fn numbered_lists_follow_their_format_and_expression() {+ use designcraft_doc::NumberStyle as N;+ let cases: [(N, &str, [&str; 3]); 4] = [+ (N::UpperLetters, "^#.^t", ["A.", "B.", "C."]),+ (N::LowerRoman, "^#.^t", ["i.", "ii.", "iii."]),+ (N::ArabicThreeDigits, "^#.^t", ["001.", "002.", "003."]),+ (N::Arabic, "Tabel ^#^t", ["Tabel 1", "Tabel 2", "Tabel 3"]),+ ];+ for (style, expression, want) in cases {+ let (d, sid, _) = doc_with("One\nTwo\nThree", Rect::new(0.0, 0.0, 300.0, 300.0), numbered(style, expression));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(list_labels(&cs, LABEL_CHARS), want, "{style:?} {expression}");+ }+ }++ #[test]+ fn numbering_from_the_largest_start_number_does_not_overflow() {+ let (mut d, sid, _) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 300.0), numbered(designcraft_doc::NumberStyle::Arabic, "^#."));+ d.story_mut(sid).unwrap().paras[0].para.start_at = Some(Some(u32::MAX));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let max = format!("{}.", u32::MAX);+ assert_eq!(list_labels(&cs, LABEL_CHARS), [max.clone(), max]);+ }++ #[test]+ fn empty_paragraphs_get_no_bullet_or_number() {+ let bullets = ParaAttrs { list_type: Some(designcraft_doc::ListType::Bullets), ..Default::default() };+ let (d, sid, _) = doc_with("One\n\nTwo\n", Rect::new(0.0, 0.0, 300.0, 300.0), bullets);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["\u{2022}", "", "\u{2022}", ""]);+ // An empty paragraph doesn't use up a number, in a story's own list or a named one.+ for name in ["", "Steps"] {+ let attrs = ParaAttrs { list_name: Some(name.into()), ..numbered(designcraft_doc::NumberStyle::Arabic, "^#.^t") };+ let (mut d, sid, _) = doc_with("One\n\nTwo\n", Rect::new(0.0, 0.0, 300.0, 300.0), attrs);+ if !name.is_empty() {+ d.settings.lists.push(designcraft_doc::NumberedList { name: name.into(), continue_across_stories: false });+ }+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["1.", "", "2.", ""], "list `{name}`");+ }+ }diff --cc crates/idml/src/tests.rsindex 51c9a071b,fda15449d..6c9e7d91f--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -1620,350 -905,81 +1620,393 @@@ fn column_rules_round_trip()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),+ ])+}-/// InDesign's designmap lists layers back to front; `Document::layers[0]` is the front layer.#[test]-fn layers_import_and_export_in_stacking_order() {- let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">- <Layer Self="L1" Name="Background"/>- <Layer Self="L2" Name="Content"/>- <idPkg:Spread src="Spreads/Spread_s.xml"/>- </Document>"#;- let spread = r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">- <Spread Self="s">- <Page Self="p" GeometricBounds="0 0 100 100" ItemTransform="1 0 0 1 0 0"/>- <Rectangle Self="r" ItemLayer="L1">- <Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>- <PathPointType Anchor="0 0"/><PathPointType Anchor="0 100"/>- <PathPointType Anchor="100 100"/><PathPointType Anchor="100 0"/>- </PathPointArray></GeometryPathType></PathGeometry></Properties>- </Rectangle>- </Spread>- </idPkg:Spread>"#;- let d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", spread)])).unwrap();- let names = |d: &Document| d.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();- assert_eq!(names(&d), ["Content", "Background"]);- assert_eq!(d.spreads[0].items[0].layer, d.layers[1].id, "the rectangle stays on Background");+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 bytes = export_idml(&d);- let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();- let mut map = String::new();- std::io::Read::read_to_string(&mut zip.by_name("designmap.xml").unwrap(), &mut map).unwrap();- let (bg, content) = (map.find(r#"Name="Background""#).unwrap(), map.find(r#"Name="Content""#).unwrap());- assert!(bg < content, "designmap lists the back layer first");+ 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_eq!(names(&back), ["Content", "Background"]);- assert_eq!(back.spreads[0].items[0].layer, back.layers[1].id);+ 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));}++ #[test]+ fn list_numbering_format_expression_and_bullet_import_and_round_trip() {+ let styles = STYLES.replace(+ " </ParagraphStyleGroup>",+ r#" <ParagraphStyle Self="ParagraphStyle/Text%3aHead" Name="Text:Head" BulletsAndNumberingListType="NumberedList" NumberingExpression="^#.^t">+ <Properties><NumberingFormat type="string">A, B, C, D...</NumberingFormat></Properties>+ </ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/Text%3aTable" Name="Text:Table" BulletsAndNumberingListType="NumberedList" NumberingExpression="Tabel ^#^t">+ <Properties><NumberingFormat type="string">001, 002, 003...</NumberingFormat></Properties>+ </ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/Text%3aKanji" Name="Text:Kanji" BulletsAndNumberingListType="NumberedList">+ <Properties><NumberingFormat type="string">一, 二, 三, 四...</NumberingFormat></Properties>+ </ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/Text%3aPoint" Name="Text:Point" BulletsAndNumberingListType="BulletList" BulletsTextAfter="^>">+ <Properties><BulletChar BulletCharacterType="UnicodeOnly" BulletCharacterValue="9632"/></Properties>+ </ParagraphStyle>+ </ParagraphStyleGroup>"#,+ );+ let bytes = zip_files(&[+ ("designmap.xml", DESIGNMAP),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Styles.xml", &styles),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", SPREAD),+ ("Stories/Story_s1.xml", STORY),+ ]);+ let check = |d: &Document| {+ let (head, _) = d.styles.resolve_para_style("Text/Head");+ assert_eq!(head.number_style, designcraft_doc::NumberStyle::UpperLetters);+ assert_eq!(head.number_label(2), "B.\t");+ let (table, _) = d.styles.resolve_para_style("Text/Table");+ assert_eq!(table.number_label(7), "Tabel 007\t");+ let (kanji, _) = d.styles.resolve_para_style("Text/Kanji");+ assert_eq!(kanji.number_style, designcraft_doc::NumberStyle::Arabic);+ let (point, _) = d.styles.resolve_para_style("Text/Point");+ assert_eq!(point.bullet_label(), "\u{25A0}\u{2002}");+ };+ let d = import_idml(&bytes).unwrap();+ check(&d);+ check(&import_idml(&export_idml(&d)).unwrap());+ }