DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #473: Honor IDML SameParaStyleSpacing between same-style paragraphs (#449)
aionggdad91f0c743c
diff --cc crates/compose/src/lib.rsindex ef44533e6,072973d71..be136c567--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -1222,7 -849,12 +1222,12 @@@ fn compose_with_db(doc: &Document, stor}}if cur.last_baseline.is_some() {- cur.pending += if text_above { pp.space_before.max(pp.span_space_before) } else { pp.space_before };+ // Same style as the previous paragraph with a same-style spacing: it replaces space after + before.+ let same_style = pi.checked_sub(1).and_then(|p| story.paras.get(p)).is_some_and(|prev| prev.style == pf.style && prev.table.is_none());+ match pp.same_para_style_spacing {+ Some(gap) if same_style => cur.pending = gap,- _ => cur.pending += pp.space_before,++ _ => cur.pending += if text_above { pp.space_before.max(pp.span_space_before) } else { pp.space_before },+ }}if let Some(cfg) = split_cfg&& cur.split.is_none()diff --cc crates/compose/src/tests.rsindex e8ef0b421,2eccf7d18..ac3c31ed7--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -5684,766 -2772,29 +5684,793 @@@ fn empty_paragraphs_get_no_bullet_or_nu}}+#[test]+fn tight_word_spacing_does_not_isolate_a_word() {+ // A narrow word-spacing range (100–105%) with some letter spacing and glyph scaling, no+ // hyphenation: lines that need more stretch must open their word spaces, not letter-space a+ // single word across the measure.+ let para = ParaAttrs {+ align: Some(Align::LeftJustified),+ hyphenate: Some(false),+ first_line_indent: Some(9.0),+ word_space_min: Some(1.0),+ word_space_desired: Some(1.03),+ word_space_max: Some(1.05),+ letter_space_min: Some(-0.05),+ letter_space_max: Some(0.05),+ glyph_scale_min: Some(0.99),+ glyph_scale_max: Some(1.01),+ ..Default::default()+ };+ // Short words: any two fit on a line together.+ let text = CORPUS[..2].join(" ");+ for w in (200..=320).step_by(5) {+ let (d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, w as f64, 20000.0), para.clone());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ for l in &lines[..lines.len() - 1] {+ let words = text[l.range.clone()].split_whitespace().count();+ assert!(words > 1, "width {w}: a single-word line {:?}", &text[l.range.clone()]);+ }+ }+}++#[test]+fn fixed_width_spaces_do_not_stretch_on_justified_lines() {+ // Long words in a narrow column: lines stretch past the maximum word spacing. Only the word+ // spaces take that stretch; em, en and thin spaces keep their width.+ let words = ["characteristically", "misunderstanding", "unquestionably", "responsibility", "administration", "photographer"];+ let seps = [" ", "\u{2003}", " ", "\u{2002}", " ", "\u{2009}"];+ let text: String = (0..60).map(|i| format!("{}{}", words[i % words.len()], seps[i % seps.len()])).collect();+ let text = text.trim_end().to_string();+ let fixed = |c: char| matches!(c, '\u{2003}' | '\u{2002}' | '\u{2009}');+ // (character, advance) of each fixed space, per line, and whether the line ends the paragraph.+ let spaces = |align: Align, w: f64| -> Vec<(Vec<(char, f64)>, bool)> {+ let para = ParaAttrs { align: Some(align), hyphenate: Some(false), ..Default::default() };+ let (d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, w, 20000.0), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ all_lines(&cs)+ .iter()+ .map(|l| {+ let found = l.glyphs.iter().filter_map(|g| text[g.byte..].chars().next().filter(|&c| fixed(c)).map(|c| (c, g.adv))).collect();+ (found, l.last_in_para)+ })+ .collect()+ };+ let mut checked = 0;+ for w in [190.0, 230.0, 270.0] {+ let natural: Vec<(char, f64)> = spaces(Align::Left, w).into_iter().flat_map(|l| l.0).collect();+ for (found, last) in spaces(Align::LeftJustified, w) {+ if last {+ continue;+ }+ for (c, a) in found {+ let Some(&(_, n)) = natural.iter().find(|x| x.0 == c) else { continue };+ assert!((a - n).abs() < 1e-6, "width {w}: U+{:04X} is {a:.2} wide, not {n:.2}", c as u32);+ checked += 1;+ }+ }+ }+ assert!(checked > 5, "{checked} fixed spaces on justified lines");+}++#[test]+fn grep_style_in_the_documents_dialect_keeps_short_words_with_the_next() {+ // `\l` (lowercase letter) and `\h` (horizontal space) aren't Rust regex syntax; the style used+ // to be skipped silently.+ let text = "Мы и он в доме и в саду, а она у окна и с книгой в руках у стола.";+ let para = ParaAttrs {+ align: Some(Align::Left),+ grep_styles: Some(vec![designcraft_doc::GrepStyle { style: "nobreak".into(), pattern: r"\b\l{1,2}\h".into() }]),+ ..Default::default()+ };+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 70.0, 1000.0), para);+ let chars = designcraft_doc::CharAttrs { no_break: Some(true), ..Default::default() };+ std::sync::Arc::make_mut(&mut d.styles).character.push(designcraft_doc::CharacterStyle {+ name: "nobreak".into(),+ based_on: None,+ chars,+ shortcut: String::new(),+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!(lines.len() > 3);+ let short = |w: &str| w.chars().count() <= 2 && w.chars().all(char::is_lowercase);+ for l in &lines[..lines.len() - 1] {+ let last = text[l.range.clone()].split_whitespace().last().unwrap_or("");+ assert!(!short(last), "line ends with a short word: {:?}", &text[l.range.clone()]);+ }+}++// ---------- paragraph border and shading ----------++fn bordered(text: &str, rect: Rect, para: ParaAttrs) -> ComposedStory {+ let para = ParaAttrs { border_on: Some(true), border_weights: Some([1.0; 4]), ..para };+ let (d, sid, _) = doc_with(text, rect, para);+ compose_story(&d, sid, &ComposeOptions::default())+}++fn has_curves(bp: &designcraft_geom::BezPath) -> bool {+ bp.elements().iter().any(|e| matches!(e, designcraft_geom::PathEl::CurveTo(..) | designcraft_geom::PathEl::QuadTo(..)))+}++#[test]+fn rounded_border_corners_are_curves_and_dotted_borders_paint_their_gap_first() {+ use designcraft_geom::corners::{Corner, CornerShape};+ let rounded = [Corner { shape: CornerShape::Rounded, size: 6.0 }; 4];+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs { border_corners: Some(rounded), ..Default::default() });+ let paths: Vec<_> = cs.frames[0].decos.iter().filter_map(|dc| dc.path.as_ref()).collect();+ assert_eq!(paths.len(), 1, "one stroked outline");+ assert!(has_curves(paths[0]));+ // Square corners: plain edges, no curves.+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs::default());+ assert!(cs.frames[0].decos.iter().all(|dc| dc.path.is_none()));+ // A dotted border with a gap colour: the gap under the dots.+ let dotted = ParaAttrs { border_type: Some(designcraft_doc::StrokeType::Dotted), border_gap_color: Some("[Paper]".into()), ..Default::default() };+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), dotted);+ let colors: Vec<&str> = cs.frames[0].decos.iter().filter(|dc| dc.path.is_some()).map(|dc| dc.color.as_str()).collect();+ assert_eq!(colors, ["[Paper]", "[Black]"]);+}++/// The width of the widest border edge (the top and bottom edges span the box).+fn border_width(cs: &ComposedStory) -> f64 {+ cs.frames[0].decos.iter().filter(|dc| dc.color == "[Black]").map(|dc| dc.rect.width()).fold(0.0, f64::max)+}++#[test]+fn a_text_width_border_is_narrower_than_a_column_width_one() {+ let rect = Rect::new(0.0, 0.0, 300.0, 200.0);+ let column = border_width(&bordered("Short", rect, ParaAttrs::default()));+ let text = border_width(&bordered("Short", rect, ParaAttrs { border_width: Some(designcraft_doc::BoxWidth::Text), ..Default::default() }));+ assert!((column - 302.0).abs() < 1e-6, "column and both side strokes: {column}");+ assert!(text > 2.0 && text < 60.0, "text: {text}");+}++/// Edges of a plain border by frame column: (column, count).+fn edges_per_column(cs: &ComposedStory) -> Vec<usize> {+ let cols = &cs.frames[0].columns;+ cols.iter()+ .map(|c| {+ cs.frames[0].decos.iter().filter(|dc| dc.color == "[Black]" && dc.rect.center().x > c.x0 - 2.0 && dc.rect.center().x < c.x1 + 2.0).count()+ })+ .collect()+}++#[test]+fn a_split_paragraph_closes_its_border_in_each_column_only_when_set_to() {+ let text = format!("{LOREM} {LOREM}");+ let compose = |display: bool| {+ let para = ParaAttrs { border_on: Some(true), border_weights: Some([1.0; 4]), border_display_if_splits: Some(display), ..Default::default() };+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 400.0, 90.0), para);+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;+ compose_story(&d, sid, &ComposeOptions::default())+ };+ let open = compose(false);+ assert!(open.frames[0].lines.iter().any(|l| l.column == 1), "the paragraph reaches the second column");+ // Open at the split: top and sides in the first column, sides and bottom in the second.+ assert_eq!(edges_per_column(&open), [3, 3]);+ assert_eq!(edges_per_column(&compose(true)), [4, 4]);+}++#[test]+fn consecutive_paragraphs_with_the_same_border_share_one_box() {+ let compose = |merge: bool| {+ let para = ParaAttrs { space_after: Some(10.0), border_merge: Some(merge), ..Default::default() };+ bordered("One\nTwo\nThree", Rect::new(0.0, 0.0, 300.0, 300.0), para)+ };+ let merged = compose(true);+ let edges: Vec<Rect> = merged.frames[0].decos.iter().filter(|dc| dc.color == "[Black]").map(|dc| dc.rect).collect();+ assert_eq!(edges.len(), 4, "one box: {edges:?}");+ let lines = &merged.frames[0].lines;+ let (first, last) = (&lines[0], &lines[lines.len() - 1]);+ let left = edges.iter().find(|r| r.height() > r.width()).unwrap();+ assert!((left.y0 - (first.baseline - first.ascent)).abs() < 1e-6 && (left.y1 - (last.baseline + last.descent)).abs() < 1e-6, "{left:?}");+ assert_eq!(compose(false).frames[0].decos.iter().filter(|dc| dc.color == "[Black]").count(), 12, "a box each");+}++#[test]+fn shading_clips_to_the_frame_and_can_stay_off_print() {+ let para = ParaAttrs {+ shading_on: Some(true),+ shading_offsets: Some([50.0; 4]),+ shading_clip: Some(true),+ shading_nonprinting: Some(true),+ ..Default::default()+ };+ let (d, sid, _) = doc_with("Shaded", Rect::new(0.0, 0.0, 300.0, 200.0), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let area = cs.frames[0].columns[0];+ let shade = &cs.frames[0].decos[0];+ assert!(shade.nonprinting);+ assert!(shade.rect.x0 >= area.x0 - 1e-6 && shade.rect.y0 >= area.y0 - 1e-6 && shade.rect.x1 <= area.x1 + 1e-6, "{:?} in {area:?}", shade.rect);+}++// ---------- span space, bullets and numbering ----------++#[test]+fn space_before_and_after_a_span_moves_the_span_and_the_text_below() {+ let at = |before: f64, after: f64| {+ let (mut d, sid, _, h) = span_doc(1, 1, Rect::new(0.0, 0.0, 600.0, 800.0));+ let p = &mut d.story_mut(sid).unwrap().paras[h].para;+ p.span_space_before = Some(before);+ p.span_space_after = Some(after);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let first = |pi: usize| cs.frames[0].lines.iter().find(|l| l.para == pi).map(|l| l.baseline).unwrap();+ (first(h), first(h + 1))+ };+ let (span0, below0) = at(0.0, 0.0);+ let (span1, below1) = at(24.0, 0.0);+ assert!((span1 - span0 - 24.0).abs() < 0.01, "{span0} → {span1}");+ assert!((below1 - below0 - 24.0).abs() < 0.01, "the text below moves with it");+ let (span2, below2) = at(0.0, 18.0);+ assert!((span2 - span0).abs() < 0.01 && (below2 - below0 - 18.0).abs() < 0.01, "{below0} → {below2}");+}++#[test]+fn span_space_applies_only_where_the_paragraph_spans_columns() {+ // Every paragraph spans with 12 pt span space after; the frame has `columns` columns.+ let tops = |columns: u32, span: bool| {+ let (mut d, sid, fid) = doc_with("One\nTwo\nThree", Rect::new(0.0, 0.0, 400.0, 400.0), ParaAttrs::default());+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = columns;+ for p in &mut d.story_mut(sid).unwrap().paras {+ if span {+ p.para.span_columns = Some(SpanColumns::Span(0));+ }+ p.para.span_space_after = Some(12.0);+ }+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ first_lines(&cs).iter().map(|l| l.baseline).collect::<Vec<_>>()+ };+ let plain = tops(1, false);+ assert_eq!(plain.len(), 3);+ assert_eq!(tops(1, true), plain, "a span in a one-column frame adds no space");+ let spread = tops(3, true);+ let gap = |v: &[f64], i: usize| v[i + 1] - v[i];+ assert!((gap(&spread, 0) - gap(&plain, 0) - 12.0).abs() < 0.01, "{spread:?} vs {plain:?}");+}++/// The first line of each paragraph.+fn first_lines(cs: &ComposedStory) -> Vec<&Line> {+ all_lines(cs).into_iter().filter(|l| l.first_in_para).collect()+}++#[test]+fn a_right_aligned_number_ends_at_the_line_start() {+ use designcraft_doc::{ListAlign, ListType};+ let compose = |align: ListAlign| {+ let para = ParaAttrs {+ list_type: Some(ListType::Numbers),+ number_align: Some(align),+ left_indent: Some(36.0),+ first_line_indent: Some(-18.0),+ ..Default::default()+ };+ let (d, sid, _) = doc_with("Item", Rect::new(0.0, 0.0, 300.0, 200.0), para);+ compose_story(&d, sid, &ComposeOptions::default())+ };+ // The label "1.\t": its first two glyphs are the number and the full stop.+ let cs = compose(ListAlign::Left);+ let col = cs.frames[0].columns[0];+ let l = first_lines(&cs)[0];+ assert!((l.glyphs[0].x - (col.x0 + 18.0)).abs() < 0.01, "left: starts at the line start");+ let text_x = l.glyphs.iter().find(|g| g.len > 0).unwrap().x;+ let cs = compose(ListAlign::Right);+ let l = first_lines(&cs)[0];+ let end = l.glyphs[1].x + l.glyphs[1].adv;+ assert!((end - (col.x0 + 18.0)).abs() < 0.01, "right: ends at the line start ({end})");+ assert!((l.glyphs.iter().find(|g| g.len > 0).unwrap().x - text_x).abs() < 0.01, "the text stays at the tab stop");+}++#[test]+fn level_two_numbering_restarts_after_level_one() {+ let para = numbered(designcraft_doc::NumberStyle::Arabic, "^1.^#");+ let (mut d, sid, _) = doc_with("A\nB\nC\nD\nE", Rect::new(0.0, 0.0, 300.0, 300.0), para);+ for (p, level) in d.story_mut(sid).unwrap().paras.iter_mut().zip([1, 2, 2, 1, 2]) {+ p.para.list_level = Some(level);+ }+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ // `^1` is level 1's number, `^#` the paragraph's own level.+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["1.1", "1.1", "1.2", "2.2", "2.1"]);+ // Without the restart, level 2 carries on.+ for p in &mut d.story_mut(sid).unwrap().paras {+ p.para.restart_numbers = Some(false);+ }+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["1.1", "1.1", "1.2", "2.2", "2.3"]);+}++#[test]+fn the_tab_position_places_the_text_after_the_label() {+ use designcraft_doc::ListType;+ let compose = |tab: Option<f64>| {+ let para = ParaAttrs { list_type: Some(ListType::Bullets), list_tab: Some(tab), ..Default::default() };+ let (d, sid, _) = doc_with("Item", Rect::new(0.0, 0.0, 300.0, 200.0), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let col = cs.frames[0].columns[0];+ first_lines(&cs)[0].glyphs.iter().find(|g| g.len > 0).unwrap().x - col.x0+ };+ assert!((compose(Some(50.0)) - 50.0).abs() < 0.01);+ assert!((compose(None) - 36.0).abs() < 0.01, "the default tab stop");+}++#[test]+fn paragraph_mark_size_counts_in_its_line_auto_leading() {+ let gaps = |mark_size: f64| {+ let (mut d, sid, _) = doc_with("One\nTwo\nThree", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(7..8, |f| f.over.size = Some(mark_size));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let b: Vec<f64> = all_lines(&cs).iter().map(|l| l.baseline).collect();+ assert_eq!(b.len(), 3);+ (b[1] - b[0], b[2] - b[1])+ };+ // A 12 pt line ending in a 14 pt return: 14 × 120% above it, the next line unchanged.+ let (above, below) = gaps(14.0);+ assert!((above - 16.8).abs() < 1e-6, "{above}");+ assert!((below - 14.4).abs() < 1e-6, "{below}");+ let (above, below) = gaps(12.0);+ assert!((above - 14.4).abs() < 1e-6, "{above}");+ assert!((below - 14.4).abs() < 1e-6, "{below}");+}++// Kenten settings, shatai, auto tate-chu-yoko, rotate roman, roman word break and grid settings.++/// The centre of a placed glyph's ink, relative to its line's baseline.+fn ink_centre(g: &PlacedGlyph) -> Point {+ let r = designcraft_geom::Shape::bounding_box(&*FontDb::global().outline(&g.face, g.gid));+ Point::new(g.x + (r.x0 + r.x1) / 2.0 * g.sx, g.y + (r.y0 + r.y1) / 2.0 * g.sy)+}++#[test]+fn kenten_sit_above_or_below_at_their_size_and_distance() {+ use designcraft_doc::cjk_settings::{KentenKind, KentenPosition};+ let (mut d, sid, _) = doc_with("AB", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.len();+ let set = |d: &mut Document, position: KentenPosition| {+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {+ f.over.kenten = Some(true);+ f.over.kenten_kind = Some(KentenKind::BlackCircle);+ f.over.kenten_size = Some(Some(8.0));+ f.over.kenten_x_scale = Some(1.5);+ f.over.kenten_distance = Some(2.0);+ f.over.kenten_position = Some(position);+ });+ };+ for position in [KentenPosition::AboveRight, KentenPosition::BelowLeft] {+ set(&mut d, position);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let marks = &l.glyphs[plain..];+ assert_eq!(marks.len(), 2, "one mark per character");+ for (b, m) in l.glyphs[..plain].iter().zip(marks) {+ // 8 pt, 150% wide, in a run style of its own.+ assert!((m.sx - 8.0 / m.face.units_per_em() * 1.5).abs() < 1e-9 && (m.sy - 8.0 / m.face.units_per_em()).abs() < 1e-9);+ assert_ne!(m.style, b.style);+ assert_eq!(cs.styles[m.style as usize].size, 8.0);+ let (top, bottom) = b.face.em_box();+ let want_y = match position {+ KentenPosition::AboveRight => b.y - top * b.sy - 2.0 - 4.0,+ KentenPosition::BelowLeft => b.y - bottom * b.sy + 2.0 + 4.0,+ };+ let c = ink_centre(m);+ assert!((c.y - want_y).abs() < 1e-6, "{position:?}: {} vs {want_y}", c.y);+ assert!((c.x - (b.x + b.adv / 2.0)).abs() < 1e-6, "centred on its character");+ }+ }+}++#[test]+fn kenten_colour_is_its_own_run_style() {+ let (mut d, sid, _) = doc_with("AB", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {+ f.over.kenten = Some(true);+ f.over.kenten_fill = Some("[Registration]".into());+ f.over.kenten_fill_tint = Some(Some(0.5));+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let mark = l.glyphs.last().unwrap();+ let st = &cs.styles[mark.style as usize];+ assert_eq!((st.fill.as_str(), st.fill_tint), ("[Registration]", 0.5));+ assert!(st.kenten_mark.is_none() && !st.underline);+ assert_eq!(cs.styles[l.glyphs[0].style as usize].fill, "[Black]", "the text keeps its colour");+}++#[test]+fn shatai_matches_the_measured_matrices() {+ use crate::shatai::Shatai;+ let close = |a: [f64; 4], b: [f64; 4]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3);+ let plain = Shatai { magnification: 0.2, angle: 60.0, adjust_rotation: false, adjust_tsume: false };+ assert!(close(plain.linear(true), [0.850, 0.0866, 0.0866, 0.950]), "{:?}", plain.linear(true));+ let turned = Shatai { magnification: 0.1, angle: 60.0, adjust_rotation: true, adjust_tsume: false };+ assert!(close(turned.linear(true), [0.9222, 0.0843, 0.0, 0.9759]), "{:?}", turned.linear(true));+ // In horizontal text the turn keeps the glyph's horizontal axis horizontal.+ assert!(turned.linear(false)[1].abs() < 1e-12);+}++#[test]+fn shatai_slants_glyphs_about_their_em_centre_and_fits_the_advance() {+ let (mut d, sid, _) = doc_with("AB", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ let glyph = |d: &Document| {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ let l = cs.frames[0].lines[0].clone();+ (cs.styles[l.glyphs[0].style as usize].clone(), l.glyphs[0].clone(), l.baseline)+ };+ let (_, before, _) = glyph(&d);+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {+ f.over.shatai_magnification = Some(20.0);+ f.over.shatai_angle = Some(60.0);+ f.over.shatai_adjust_tsume = Some(false);+ });+ let (style, g, baseline) = glyph(&d);+ assert!((g.adv - before.adv).abs() < 1e-9, "without Adjust Tsume the advance stays");+ let xf = style.shatai_xf(&g, baseline).unwrap();+ // y down: the off-diagonal terms change sign.+ let [a, b, c, dd, _, _] = xf.as_coeffs();+ assert!((a - 0.85).abs() < 1e-3 && (b + 0.0866).abs() < 1e-3 && (c + 0.0866).abs() < 1e-3 && (dd - 0.95).abs() < 1e-3);+ let (top, bottom) = g.face.em_box();+ let centre = Point::new(g.x + g.face.advance(g.gid) * g.sx / 2.0, baseline + g.y - (top + bottom) / 2.0 * g.sy);+ assert!((xf * centre - centre).hypot() < 1e-9, "the em box centre stays put");+ // Adjust Tsume: the advance becomes the compressed em box's width.+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.shatai_adjust_tsume = Some(true));+ let (style, fitted, _) = glyph(&d);+ let sh = style.shatai.unwrap();+ let w = g.face.advance(g.gid) * g.sx;+ let want = before.adv + w * (sh.extent(false, w, (top - bottom) * g.sy) - 1.0);+ assert!((fitted.adv - want).abs() < 1e-9, "{} vs {want}", fitted.adv);+ // No shatai without magnification.+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.shatai_magnification = Some(0.0));+ assert!(glyph(&d).0.shatai.is_none());+}++#[test]+fn auto_tate_chu_yoko_takes_short_digit_runs_in_vertical_text() {+ let text = "令和12年と1234年と123";+ let (mut d, sid, _) = doc_with(text, Rect::new(100.0, 100.0, 200.0, 400.0), ParaAttrs { auto_tcy: Some(3), ..Default::default() });+ let glyphs = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ assert!(glyphs(&d).iter().all(|g| g.tcy.is_none()), "horizontal text has none");+ d.story_mut(sid).unwrap().vertical = true;+ let gs = glyphs(&d);+ let at = |s: &str| text.find(s).unwrap();+ let tcy: Vec<&PlacedGlyph> = gs.iter().filter(|g| g.tcy.is_some()).collect();+ let two = at("12年");+ let three = text.rfind("123").unwrap();+ assert_eq!(tcy.iter().map(|g| g.byte).collect::<Vec<_>>(), [two, two + 1, three, three + 1, three + 2], "2 and 3 digits, not 4");+ // Each group takes one em along the line; three digits are narrowed to fit across it.+ let em = tcy[0].tcy.unwrap()[2];+ assert!((tcy[..2].iter().map(|g| g.adv).sum::<f64>() - em).abs() < 1e-6);+ let plain = gs.iter().find(|g| g.byte == at("1234")).unwrap();+ assert!(tcy[2].sx < plain.sx, "{} {}", tcy[2].sx, plain.sx);+ let [_, left, _] = tcy[2].tcy.unwrap();+ assert!(left >= -em / 2.0 - 1e-6, "the narrowed group stays within the em");+ // Roman letters too, with Include Roman.+ let text2 = "縦AB横";+ let (mut d, sid, _) = doc_with(text2, Rect::new(100.0, 100.0, 200.0, 400.0), ParaAttrs { auto_tcy: Some(2), ..Default::default() });+ d.story_mut(sid).unwrap().vertical = true;+ let count = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.iter().filter(|g| g.tcy.is_some()).count();+ assert_eq!(count(&d), 0);+ d.story_mut(sid).unwrap().paras[0].para.auto_tcy_include_roman = Some(true);+ assert_eq!(count(&d), 2);+}++#[test]+fn rotate_roman_stands_half_width_characters_upright() {+ let (mut d, sid, _) = doc_with("縦書きLatin", Rect::new(100.0, 100.0, 200.0, 400.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().vertical = true;+ let latin_upright = |d: &Document| {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ cs.frames[0].lines[0].glyphs.iter().filter(|g| g.len > 0 && g.byte >= "縦書き".len()).all(|g| g.upright)+ };+ assert!(!latin_upright(&d));+ d.story_mut(sid).unwrap().paras[0].para.rotate_roman = Some(true);+ assert!(latin_upright(&d));+}++#[test]+fn roman_word_break_breaks_inside_words_without_hyphens() {+ let para = ParaAttrs { composer: Some(designcraft_doc::Composer::SingleLine), hyphenate: Some(false), ..Default::default() };+ let first_line = |rwb: bool| {+ let (d, sid, _) = doc_with("ab cdefghijklm", Rect::new(0.0, 0.0, 40.0, 300.0), ParaAttrs { roman_word_break: Some(rwb), ..para.clone() });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!(lines.iter().all(|l| !l.hyphenated && l.end_x <= l.x1 + 0.5));+ lines[0].range.clone()+ };+ assert_eq!(first_line(false), 0..3, "the word moves down whole");+ assert!(first_line(true).end > 3, "the line fills with part of the word");+}++/// Composed lines of a story in a frame with a 12 pt baseline grid; returns them and the grid.+fn grid_doc(text: &str, para: ParaAttrs, edit: impl FnOnce(&mut Document, StoryId)) -> (Vec<Line>, (f64, f64)) {+ let (mut d, sid, fid) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 400.0), para);+ if let Some(tf) = d.item_mut(fid).and_then(|i| i.text_frame_mut()) {+ tf.options.baseline_grid = Some((12.0, 0.0));+ }+ edit(&mut d, sid);+ // Vertical frames have no baseline grid.+ let grid = frame_specs(&d, sid)[0].grid.unwrap_or((0.0, 12.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ (all_lines(&cs).into_iter().cloned().collect(), grid)+}++/// The em box centre of a line's first glyph (as the composer measures it), y down.+fn em_centre(l: &Line) -> f64 {+ let g = &l.glyphs[0];+ let (a, b) = g.face.vertical_metrics();+ l.baseline + g.y + (b - a) / (2.0 * (a + b)) * g.face.units_per_em() * g.sy+}++fn on_grid(y: f64, (start, inc): (f64, f64)) -> bool {+ let n = (y - start) / inc;+ (n - n.round()).abs() < 1e-6+}++#[test]+fn grid_alignment_puts_the_chosen_point_on_the_grid() {+ use designcraft_doc::cjk::CharacterAlignment as R;+ let para = |r: R| ParaAttrs { grid_align: Some(designcraft_doc::GridAlign::AllLines), grid_reference: Some(r), ..Default::default() };+ let (roman, grid) = grid_doc("AB\nCD", para(R::Baseline), |_, _| {});+ assert!(roman.iter().all(|l| on_grid(l.baseline, grid)));+ let (centred, grid) = grid_doc("AB\nCD", para(R::EmCenter), |_, _| {});+ assert!(centred.iter().all(|l| on_grid(em_centre(l), grid)));+ assert!(!on_grid(centred[0].baseline, grid), "the baseline moves off the grid by the em centre's offset");+ let offset = em_centre(¢red[0]) - centred[0].baseline;+ let shift = centred[0].baseline - roman[0].baseline;+ assert!(on_grid(shift + offset, (0.0, grid.1)), "{shift} {offset}");+}++#[test]+fn gyoudori_two_lines_centres_a_heading_in_two_grid_lines() {+ use designcraft_doc::cjk::CharacterAlignment as R;+ let para = ParaAttrs { grid_align: Some(designcraft_doc::GridAlign::AllLines), grid_reference: Some(R::EmCenter), ..Default::default() };+ let (lines, grid) = grid_doc("Head\nBody text", para, |d, sid| {+ let st = d.story_mut(sid).unwrap();+ st.format_chars(0..4, |f| f.over.size = Some(18.0));+ st.format_paras(0..4, |p| p.para.grid_gyoudori = Some(2));+ });+ let (head, body) = (em_centre(&lines[0]), em_centre(&lines[1]));+ assert!(on_grid(head - grid.1 / 2.0, grid), "midway between two grid lines: {head}");+ assert!(on_grid(body, grid));+ assert!((body - head - 1.5 * grid.1).abs() < 1e-6, "the body takes the grid line after the heading's two: {head} {body}");+}++#[test]+fn paragraph_gyoudori_centres_the_whole_paragraph() {+ use designcraft_doc::cjk::CharacterAlignment as R;+ let para = ParaAttrs {+ grid_align: Some(designcraft_doc::GridAlign::AllLines),+ grid_reference: Some(R::EmCenter),+ grid_gyoudori: Some(4),+ paragraph_gyoudori: Some(true),+ ..Default::default()+ };+ let (lines, grid) = grid_doc("One\u{2028}Two\nNext", para, |d, sid| {+ d.story_mut(sid).unwrap().format_paras(10..14, |p| {+ p.para.grid_gyoudori = Some(0);+ p.para.paragraph_gyoudori = Some(false);+ });+ });+ let firsts: Vec<f64> = lines.iter().map(em_centre).collect();+ assert_eq!(lines.len(), 3, "{firsts:?}");+ // Two lines a leading apart, centred as a block in four grid lines; the next paragraph on the fifth.+ let middle = (firsts[0] + firsts[1]) / 2.0;+ assert!(on_grid(middle - 1.5 * grid.1, grid), "{firsts:?}");+ assert!((firsts[2] - (middle - 1.5 * grid.1) - 4.0 * grid.1).abs() < 1e-6, "{firsts:?}");+}++#[test]+fn hostile_cjk_settings_compose_without_panicking() {+ let para = ParaAttrs {+ auto_tcy: Some(u32::MAX),+ auto_tcy_include_roman: Some(true),+ rotate_roman: Some(true),+ roman_word_break: Some(true),+ grid_align: Some(designcraft_doc::GridAlign::AllLines),+ grid_reference: Some(designcraft_doc::cjk::CharacterAlignment::IcfBottom),+ grid_gyoudori: Some(u32::MAX),+ paragraph_gyoudori: Some(true),+ ..Default::default()+ };+ for vertical in [false, true] {+ let (_, _) = grid_doc("縦12AB書き\nmore text here", para.clone(), |d, sid| {+ let st = d.story_mut(sid).unwrap();+ st.vertical = vertical;+ let len = st.len();+ st.format_chars(0..len, |f| {+ f.over.kenten = Some(true);+ f.over.kenten_kind = Some(designcraft_doc::cjk_settings::KentenKind::Custom);+ f.over.kenten_character = Some("★".repeat(100_000));+ f.over.kenten_font = Some("No Such Font".into());+ f.over.kenten_size = Some(Some(1e308));+ f.over.kenten_x_scale = Some(-1e308);+ f.over.kenten_y_scale = Some(f64::NAN);+ f.over.kenten_distance = Some(f64::INFINITY);+ f.over.kenten_fill_tint = Some(Some(f32::NAN));+ f.over.kenten_stroke_weight = Some(Some(-1e308));+ f.over.shatai_magnification = Some(1e308);+ f.over.shatai_angle = Some(f64::NEG_INFINITY);+ });+ });+ }+}++/// A 100×60 rectangle anchored at `at` in `sid`, custom-positioned with its top-left at+/// (`x`, `y`) from the top-left of the anchor's frame (`y_rel`: from the anchor's baseline).+fn anchor_box(d: &mut Document, sid: StoryId, at: usize, x: f64, y: f64, y_rel: bool, wrap: WrapMode) {+ use designcraft_doc::anchored::AnchorRelative as R;+ let lid = d.default_layer();+ let mut it = designcraft_doc::Item::new(+ ItemId(d.alloc()),+ lid,+ designcraft_doc::Shape::Rectangle,+ designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 60.0)),+ );+ it.wrap.mode = wrap;+ let position = designcraft_doc::AnchorPosition::Custom {+ x_relative: R::TextFrame,+ y_relative: if y_rel { R::Anchor } else { R::TextFrame },+ x_offset: x,+ y_offset: y,+ object_point: 0,+ ref_point: 0,+ keep_within_column: false,+ };+ d.story_mut(sid).unwrap().insert_object(at, designcraft_doc::AnchoredObject::new(it, position));+}++/// Lines whose band meets `y0..y1`.+fn lines_in_band(cs: &ComposedStory, y0: f64, y1: f64) -> Vec<&Line> {+ all_lines(cs).into_iter().filter(|l| l.baseline - l.ascent < y1 && l.baseline + l.descent > y0).collect()+}++fn line_layout(cs: &ComposedStory) -> Vec<(Range<usize>, u64, u64, u64)> {+ all_lines(cs).iter().map(|l| (l.range.clone(), l.baseline.to_bits(), l.x0.to_bits(), l.x1.to_bits())).collect()+}++#[test]+fn anchored_object_wraps_another_storys_text() {+ let long = [LOREM; 3].join(" ");+ let (mut d, a, fa) = doc_with("Anchor here.", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default());+ let lid = d.default_layer();+ let (_, b) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 0.0, 620.0, 400.0), lid, &long, ParaFormat::default()).unwrap();+ let plain = compose_story(&d, b, &ComposeOptions::default());+ let left = all_lines(&plain)[0].x0;+ // Over the left part of B's frame, 100–160 pt down.+ let area = d.item(fa).unwrap().text_area();+ anchor_box(&mut d, a, 0, left - area.x0, 100.0 - area.y0, false, WrapMode::BoundingBox);+ let cs = compose_story(&d, b, &ComposeOptions::default());+ let band = lines_in_band(&cs, 100.0, 160.0);+ assert!(!band.is_empty());+ assert!(band.iter().all(|l| l.x0 >= left + 100.0 - 1e-6), "{:?}", band.iter().map(|l| l.x0).collect::<Vec<_>>());+ assert!(lines_in_band(&cs, 0.0, 80.0).iter().all(|l| (l.x0 - left).abs() < 1e-6));+ // The cache composes the same, and follows the object when it moves.+ let cache = Cache::new();+ assert_eq!(line_layout(&cache.get(&d, b, None)), line_layout(&cs));+ anchor_box(&mut d, a, 0, left - area.x0, 200.0 - area.y0, false, WrapMode::BoundingBox);+ let st = d.story_mut(a).unwrap();+ st.delete(OBJECT_LEN..2 * OBJECT_LEN);+ let moved = cache.get(&d, b, None);+ assert_eq!(line_layout(&moved), line_layout(&compose_story(&d, b, &ComposeOptions::default())));+ assert!(lines_in_band(&moved, 100.0, 160.0).iter().any(|l| (l.x0 - left).abs() < 1e-6));+ assert!(lines_in_band(&moved, 200.0, 260.0).iter().all(|l| l.x0 >= left + 100.0 - 1e-6));+}++/// An anchored object's wrap is built as a page item's: a contour on both sides of an oval sets+/// text left and right of it, closer in where the oval narrows.+#[test]+fn anchored_object_wraps_with_its_contour_and_side() {+ use designcraft_doc::anchored::AnchorRelative as R;+ let long = [LOREM; 4].join(" ");+ let (mut d, a, fa) = doc_with("Anchor here.", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default());+ let lid = d.default_layer();+ let (_, b) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 0.0, 620.0, 400.0), lid, &long, ParaFormat::default()).unwrap();+ let left = all_lines(&compose_story(&d, b, &ComposeOptions::default()))[0].x0;+ let area = d.item(fa).unwrap().text_area();+ let mut it = designcraft_doc::Item::new(+ ItemId(d.alloc()),+ lid,+ designcraft_doc::Shape::Oval,+ designcraft_geom::shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)),+ );+ it.wrap.mode = WrapMode::Contour;+ it.wrap.side = WrapSide::BothSides;+ let position = designcraft_doc::AnchorPosition::Custom {+ x_relative: R::TextFrame,+ y_relative: R::TextFrame,+ x_offset: left + 100.0 - area.x0,+ y_offset: 100.0 - area.y0,+ object_point: 0,+ ref_point: 0,+ keep_within_column: false,+ };+ d.story_mut(a).unwrap().insert_object(0, designcraft_doc::AnchoredObject::new(it, position));+ let cs = compose_story(&d, b, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let pairs: Vec<(&Line, &Line)> = lines.windows(2).filter(|w| w[0].baseline == w[1].baseline).map(|w| (w[0], w[1])).collect();+ assert!(pairs.len() >= 3, "{} lines share a baseline", pairs.len());+ let centre = left + 150.0;+ assert!(pairs.iter().all(|(l, r)| l.x1 < centre && r.x0 > centre), "text on both sides");+ let top = pairs.first().unwrap().0.x1;+ let mid = pairs.iter().map(|(l, _)| l.x1).fold(f64::INFINITY, f64::min);+ assert!(top > mid + 5.0, "top {top}, middle {mid}");+}++const OBJECT_LEN: usize = designcraft_doc::OBJECT_MARK.len_utf8();++#[test]+fn anchored_object_wraps_its_own_storys_later_lines() {+ let text = [LOREM; 4].join(" ");+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 600.0), ParaAttrs::default());+ let plain = compose_story(&d, sid, &ComposeOptions::default());+ let left = all_lines(&plain)[0].x0;+ // Anchored in the third line, hanging from its baseline over the lines below.+ let at = all_lines(&plain)[2].range.start + 3;+ anchor_box(&mut d, sid, at, 0.0, 0.0, true, WrapMode::BoundingBox);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let (li, anchor_line) = lines.iter().enumerate().find(|(_, l)| l.range.contains(&at)).unwrap();+ let top = anchor_line.baseline;+ // The anchor line and those above it keep the full measure; the lines under the object move right.+ assert!(lines[..=li].iter().all(|l| (l.x0 - left).abs() < 1e-6));+ let under: Vec<_> = lines[li + 1..].iter().filter(|l| l.baseline - l.ascent < top + 60.0).collect();+ assert!(under.len() >= 2);+ assert!(under.iter().all(|l| l.x0 >= left + 100.0 - 1e-6), "{:?}", under.iter().map(|l| l.x0).collect::<Vec<_>>());+ assert!(lines.iter().filter(|l| l.baseline - l.ascent > top + 61.0).all(|l| (l.x0 - left).abs() < 1e-6));+ // Settled: the object is where the final pass wrapped the text around.+ let o = &cs.frames[0].objects[0];+ assert!((o.origin.y - top).abs() < 1e-6);+}++#[test]+fn anchored_object_without_wrap_leaves_layout_unchanged() {+ let long = [LOREM; 3].join(" ");+ let (mut d, a, _) = doc_with(&long, Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default());+ let lid = d.default_layer();+ let (_, b) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 0.0, 620.0, 400.0), lid, &long, ParaFormat::default()).unwrap();+ anchor_box(&mut d, a, 40, 330.0, 0.0, true, WrapMode::None);+ for sid in [a, b] {+ let direct = compose(&d, d.story(sid).unwrap(), &frame_specs(&d, sid), &ComposeOptions::default());+ assert_eq!(line_layout(&compose_story(&d, sid, &ComposeOptions::default())), line_layout(&direct));+ }+}++#[test]+fn anchored_wrap_that_moves_its_own_anchor_terminates() {+ // Jump Object pushes the lines after the anchor below the object; vertical centring then moves+ // every line, the anchor's too, and the object with it.+ let text = [LOREM; 2].join(" ");+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 500.0), ParaAttrs::default());+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Center;+ let plain = compose_story(&d, sid, &ComposeOptions::default());+ let at = all_lines(&plain)[1].range.start + 2;+ anchor_box(&mut d, sid, at, 0.0, -20.0, true, WrapMode::JumpObject);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(cs.line_count() > 0);+ assert_eq!(cs.frames[0].objects.len(), 1);+}+++ #[test]+ fn same_para_style_spacing_replaces_space_between_same_style_paragraphs() {+ let rect = Rect::new(0.0, 0.0, 300.0, 700.0);+ let base = ParaAttrs { space_before: Some(5.0), space_after: Some(10.0), ..Default::default() };+ // `other_last`: the last paragraph gets a different paragraph style.+ let baselines = |para: ParaAttrs, other_last: bool| {+ let (mut d, sid, _) = doc_with("A\n\nB", rect, para);+ if other_last && let Some(st) = d.stories.get_mut(&sid) {+ std::sync::Arc::make_mut(st).paras[2].style = "Other".into();+ }+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ all_lines(&cs).iter().map(|l| l.baseline).collect::<Vec<_>>()+ };+ let tight_attrs = ParaAttrs { same_para_style_spacing: Some(Some(0.0)), ..base.clone() };+ let normal = baselines(base.clone(), false);+ let tight = baselines(tight_attrs.clone(), false);+ let wide = baselines(ParaAttrs { same_para_style_spacing: Some(Some(20.0)), ..base }, false);+ let mixed = baselines(tight_attrs, true);+ assert_eq!(normal.len(), 3);+ // Ordinary spacing: space after (10) + space before (5) between each pair, empty paragraph included.+ assert!((normal[1] - normal[0] - 14.4 - 15.0).abs() < 1e-6, "{normal:?}");+ assert!((tight[1] - tight[0] - 14.4).abs() < 1e-6 && (tight[2] - tight[1] - 14.4).abs() < 1e-6, "{tight:?}");+ assert!((wide[2] - wide[1] - 14.4 - 20.0).abs() < 1e-6, "{wide:?}");+ // A different style keeps the ordinary spacing at its boundary.+ assert!((mixed[1] - mixed[0] - 14.4).abs() < 1e-6 && (mixed[2] - mixed[1] - 14.4 - 15.0).abs() < 1e-6, "{mixed:?}");+ }diff --cc crates/doc/src/attrs.rsindex e5d2b28d7,04c643c80..02cd839c0--- a/crates/doc/src/attrs.rs+++ b/crates/doc/src/attrs.rs@@@ -1122,17 -809,10 +1122,19 @@@ attr_set!last_line_indent: f64 = 0.0,space_before: f64 = 0.0,space_after: f64 = 0.0,+ /// Space between consecutive paragraphs of the same style; replaces space after/before there (None = ignore).+ same_para_style_spacing: Option<f64> = None,+ /// Drop cap: the paragraph's first `drop_cap_chars` characters (code points, never+ /// splitting a base from its combining marks) set `drop_cap_lines` lines tall, in the+ /// character style `drop_cap_style` ("" or `[None]`: the text's own formatting).drop_cap_lines: u32 = 0,drop_cap_chars: u32 = 0,+ drop_cap_style: String = String::new(),+ /// Align Left Edge: the drop cap's ink starts at the indent (its first letter's left side+ /// bearing is taken off), and the lines beside it start where its advance ends.+ drop_cap_align_left: bool = true,+ /// Scale for Descenders (kept and round-tripped; doesn't change the layout).+ drop_cap_scale_descenders: bool = false,/// Nested styles, in order from the paragraph start.nested_styles: Vec<NestedStyle> = Vec::new(),/// GREP styles: a character style for every match of a pattern (applied after nested).diff --cc crates/idml/src/export.rsindex 0ddf21f16,2ff616e8a..ec894abda--- a/crates/idml/src/export.rs+++ b/crates/idml/src/export.rs@@@ -1422,18 -1368,15 +1422,24 @@@ impl<'a> Ex<'a>n!(last_line_indent, "LastLineIndent");n!(space_before, "SpaceBefore");n!(space_after, "SpaceAfter");+ match a.same_para_style_spacing {+ Some(Some(v)) => el.set("SameParaStyleSpacing", num(v)),+ // Explicit Ignore: must be written so it still overrides a based-on style's value.+ Some(None) => el.set("SameParaStyleSpacing", "Nothing"),+ None => {}+ }n!(drop_cap_lines, "DropCapLines");n!(drop_cap_chars, "DropCapCharacters");+ if a.drop_cap_align_left.is_some() || a.drop_cap_scale_descenders.is_some() {+ let d = designcraft_doc::ParaProps::default();+ let bits = u32::from(a.drop_cap_align_left.unwrap_or(d.drop_cap_align_left))+ | u32::from(a.drop_cap_scale_descenders.unwrap_or(d.drop_cap_scale_descenders)) << 1;+ el.set("DropcapDetail", bits);+ }if let Some(g) = a.grid_align {+ // IDML has one attribute for on/off and the reference: a reference set without+ // `grid_align` isn't written.+ let reference = crate::cjk::grid_reference_out(a.grid_reference.unwrap_or_default());match g {designcraft_doc::GridAlign::None => el.set("GridAlignment", "None"),designcraft_doc::GridAlign::AllLines => {diff --cc crates/idml/src/import.rsindex 87fc538db,77f0447f6..df7159967--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@@ -1580,16 -1278,12 +1580,18 @@@ impl<'r> Importer<'r>a.grep_styles = Some(v);}a.space_after = e.num("SpaceAfter");+ // A number, or an enumeration (Ignore) that turns it off even over a based-on style's value.+ a.same_para_style_spacing = e.prop("SameParaStyleSpacing").map(|v| v.trim().parse::<f64>().ok().filter(|v| v.is_finite()));a.drop_cap_lines = u("DropCapLines");a.drop_cap_chars = u("DropCapCharacters");+ // DropcapDetail bits: 1 = Align Left Edge, 2 = Scale for Descenders.+ if let Some(v) = e.num("DropcapDetail").filter(|v| v.is_finite() && *v >= 0.0) {+ let bits = v as u32;+ a.drop_cap_align_left = Some(bits & 1 != 0);+ a.drop_cap_scale_descenders = Some(bits & 2 != 0);+ }if let Some(g) = e.prop("GridAlignment") {- a.grid_align = Some(if g == "None" {+ a.grid_align = Some(if g.trim() == "None" {GridAlign::None} else if e.boolean("GridAlignFirstLineOnly") == Some(true) {GridAlign::FirstLineOnlydiff --cc crates/idml/src/tests.rsindex 6ae6747de,4a622955b..a7aaacd6b--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -2589,639 -1400,23 +2589,660 @@@ fn list_numbering_format_expression_andcheck(&import_idml(&export_idml(&d)).unwrap());}+/// InDesign can write `AppliedFont` with its `$ID/` prefix (`$ID/Source Serif 4`). The text is+/// set in that family instead of counting as a missing font drawn in the fallback.+#[test]+fn applied_font_with_an_id_prefix_names_the_family() {+ let styles = STYLES.replace(">Source Serif 4</AppliedFont>", ">$ID/Source Serif 4</AppliedFont>");+ let story = STORY.replace(+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14">"#,+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14"><Properties><AppliedFont type="string">$ID/Source Serif 4</AppliedFont></Properties>"#,+ );+ 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 d = import_idml_with(&bytes, &|_| None).unwrap();+ let fonts: Vec<&str> = d.styles.paragraph.iter().filter_map(|s| s.chars.font_family.as_deref()).collect();+ assert!(!fonts.is_empty() && fonts.iter().all(|f| *f == "Source Serif 4"), "{fonts:?}");+ let (sid, story) = d.stories.iter().next().unwrap();+ let bold = story.runs().find(|(r, _)| story.text[r.clone()].starts_with("bold")).unwrap().1;+ assert_eq!(bold.over.font_family.as_deref(), Some("Source Serif 4"));+ // The bundled family draws the text (an unknown family would fall back to Source Sans 3).+ let cs = designcraft_compose::compose_story(&d, *sid, &Default::default());+ let first_para = story.text.find('\n').unwrap();+ let families: Vec<&str> = cs+ .frames+ .iter()+ .flat_map(|f| &f.lines)+ .flat_map(|l| &l.glyphs)+ .filter(|g| g.visible && g.len > 0 && g.byte < first_para)+ .map(|g| g.face.get().family.as_str())+ .collect();+ assert!(!families.is_empty() && families.iter().all(|f| *f == "Source Serif 4"), "{families:?}");+}++#[test]+fn list_tab_position_round_trips_as_a_tab_stop() {+ use designcraft_doc::{ListType, ParaAttrs, ParagraphStyle, TabAlign, TabStop};+ let stop = |position, align| TabStop { position, align, leader: String::new(), align_on: String::new() };+ let mut d = Document::new(&NewDocument::default());+ std::sync::Arc::make_mut(&mut d.styles).paragraph.push(ParagraphStyle {+ name: "List".into(),+ based_on: None,+ next_style: None,+ para: ParaAttrs { list_type: Some(ListType::Bullets), list_tab: Some(Some(24.0)), ..Default::default() },+ chars: CharAttrs::default(),+ shortcut: String::new(),+ });+ let local = ParaAttrs {+ list_type: Some(ListType::Bullets),+ list_tab: Some(Some(36.0)),+ tabs: Some(vec![stop(100.0, TabAlign::Right)]),+ ..Default::default()+ };+ let ended = ParaAttrs { list_type: Some(ListType::None), ..Default::default() };+ let lid = d.default_layer();+ for (i, (text, style, para)) in+ [("Local\tx", "", local), ("Styled\ty", "List", ParaAttrs::default()), ("Ended\tz", "List", ended)].into_iter().enumerate()+ {+ let pf = ParaFormat { style: if style.is_empty() { ParaFormat::default().style } else { style.into() }, para, ..Default::default() };+ let y = 40.0 + 100.0 * i as f64;+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, y, 300.0, y + 80.0), lid, text, pf).unwrap();+ }+ let back = import_idml(&export_idml(&d)).unwrap();+ let tabs = |prefix: &str| {+ let s = back.stories.values().find(|s| s.text.starts_with(prefix)).unwrap();+ back.styles.resolve_para(&s.paras[0]).0.tabs+ };+ assert_eq!(tabs("Local"), vec![stop(36.0, TabAlign::Left), stop(100.0, TabAlign::Right)]);+ assert_eq!(tabs("Styled"), vec![stop(24.0, TabAlign::Left)]);+ assert_eq!(tabs("Ended"), vec![], "a paragraph that ends the list has no list tab stop");+}++#[test]+fn round_trips_the_zero_point_and_ruler_origin() {+ let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });+ d.settings.zero_point = [36.0, 18.5];+ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(back.settings.zero_point, [36.0, 18.5]);+ for origin in [designcraft_doc::RulerOrigin::Page, designcraft_doc::RulerOrigin::Spine, designcraft_doc::RulerOrigin::Spread] {+ d.settings.ruler_origin = origin;+ assert_eq!(import_idml(&export_idml(&d)).unwrap().settings.ruler_origin, origin);+ }+ // A hostile ZeroPoint lands on the pasteboard; a malformed one is ignored.+ let fixture = |zp: &str| {+ let designmap = format!(+ r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d" ZeroPoint="{zp}">+ <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"/></Spread>+ </idPkg:Spread>"#;+ import_idml(&zip_files(&[("designmap.xml", &designmap), ("Spreads/Spread_s.xml", spread)])).unwrap()+ };+ let [x, y] = fixture("1e300 -1e300").settings.zero_point;+ assert!(x.is_finite() && y.is_finite() && x < 1e4 && y > -1e4, "{x} {y}");+ assert_eq!(fixture("12").settings.zero_point, [0.0, 0.0]);+ assert_eq!(fixture("NaN 4").settings.zero_point, [0.0, 0.0]);+}++#[test]+fn kenten_shatai_and_grid_settings_import_and_round_trip() {+ use designcraft_doc::cjk::CharacterAlignment;+ use designcraft_doc::cjk_settings::{AdornmentOverprint, KentenAlignment, KentenKind, KentenPosition};+ 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]" AutoTcy="3" AutoTcyIncludeRoman="true" RotateSingleByteCharacters="true" AllowArbitraryHyphenation="true" GridAlignment="AlignEmCenter" GridAlignFirstLineOnly="true" GridGyoudori="2" ParagraphGyoudori="true">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" KentenKind="KentenSmallBlackCircle" KentenFontSize="6" KentenXScale="80" KentenYScale="120" KentenPlacement="1.5" KentenPosition="BelowLeft" KentenAlignment="AlignKentenLeft" KentenCharacterSet="CharacterInput" KentenTint="50" KentenStrokeTint="-1" KentenWeight="0.5" KentenOverprintFill="OverprintOn" KentenOverprintStroke="Auto" ShataiMagnification="20" ShataiDegreeAngle="6000" ShataiAdjustRotation="true" ShataiAdjustTsume="false"><Properties><KentenFont type="string">$ID/</KentenFont><KentenFontStyle type="enumeration">Nothing</KentenFontStyle><KentenFillColor type="string">Text Color</KentenFillColor></Properties><Content>甲乙</Content></CharacterStyleRange>+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" KentenKind="Custom" KentenCustomCharacter="★"><Content>丙</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#;+ let doc = import_idml(&fixture_with_story(story)).unwrap();+ let st = doc.stories.values().find(|s| s.text.contains("甲乙")).unwrap();+ let runs: Vec<CharAttrs> = st.runs().map(|(_, f)| f.over.clone()).collect();+ let a = &runs[0];+ assert_eq!((a.kenten, a.kenten_kind, a.kenten_character.as_deref()), (Some(true), Some(KentenKind::SmallBlackCircle), Some("\u{2022}")));+ assert_eq!((a.kenten_size, a.kenten_x_scale, a.kenten_y_scale, a.kenten_distance), (Some(Some(6.0)), Some(0.8), Some(1.2), Some(1.5)));+ assert_eq!((a.kenten_position, a.kenten_alignment), (Some(KentenPosition::BelowLeft), Some(KentenAlignment::Start)));+ assert_eq!((a.kenten_font.as_deref(), a.kenten_font_style.as_deref(), a.kenten_fill.as_deref()), (Some(""), Some(""), Some("")));+ assert_eq!((a.kenten_fill_tint, a.kenten_stroke_tint, a.kenten_stroke_weight), (Some(Some(0.5)), Some(None), Some(Some(0.5))));+ assert_eq!((a.kenten_overprint_fill, a.kenten_overprint_stroke), (Some(AdornmentOverprint::On), Some(AdornmentOverprint::Auto)));+ assert_eq!(a.kenten_character_set.as_deref(), Some("CharacterInput"));+ assert_eq!(+ (a.shatai_magnification, a.shatai_angle, a.shatai_adjust_rotation, a.shatai_adjust_tsume),+ (Some(20.0), Some(60.0), Some(true), Some(false))+ );+ let custom = runs.iter().find(|r| r.kenten_kind == Some(KentenKind::Custom)).unwrap();+ assert_eq!(custom.kenten_character.as_deref(), Some("★"));+ let p = &st.paras[0].para;+ assert_eq!((p.auto_tcy, p.auto_tcy_include_roman, p.rotate_roman, p.roman_word_break), (Some(3), Some(true), Some(true), Some(true)));+ assert_eq!((p.grid_align, p.grid_reference), (Some(designcraft_doc::GridAlign::FirstLineOnly), Some(CharacterAlignment::EmCenter)));+ assert_eq!((p.grid_gyoudori, p.paragraph_gyoudori), (Some(2), Some(true)));++ let back = import_idml(&export_idml(&doc)).unwrap();+ let st2 = back.stories.values().find(|s| s.text.contains("甲乙")).unwrap();+ let runs2: Vec<CharAttrs> = st2.runs().map(|(_, f)| f.over.clone()).collect();+ for (a, b) in runs.iter().zip(&runs2) {+ assert_eq!((a.kenten, a.kenten_kind, &a.kenten_character), (b.kenten, b.kenten_kind, &b.kenten_character));+ assert_eq!(+ (a.kenten_size, a.kenten_x_scale, a.kenten_y_scale, a.kenten_distance),+ (b.kenten_size, b.kenten_x_scale, b.kenten_y_scale, b.kenten_distance)+ );+ assert_eq!(+ (a.kenten_position, a.kenten_alignment, &a.kenten_character_set),+ (b.kenten_position, b.kenten_alignment, &b.kenten_character_set)+ );+ assert_eq!((&a.kenten_font, &a.kenten_font_style, &a.kenten_fill), (&b.kenten_font, &b.kenten_font_style, &b.kenten_fill));+ assert_eq!(+ (a.kenten_fill_tint, a.kenten_stroke_tint, a.kenten_stroke_weight),+ (b.kenten_fill_tint, b.kenten_stroke_tint, b.kenten_stroke_weight)+ );+ assert_eq!((a.kenten_overprint_fill, a.kenten_overprint_stroke), (b.kenten_overprint_fill, b.kenten_overprint_stroke));+ assert_eq!(+ (a.shatai_magnification, a.shatai_angle, a.shatai_adjust_rotation, a.shatai_adjust_tsume),+ (b.shatai_magnification, b.shatai_angle, b.shatai_adjust_rotation, b.shatai_adjust_tsume)+ );+ }+ let p2 = &st2.paras[0].para;+ assert_eq!(+ (p.auto_tcy, p.auto_tcy_include_roman, p.rotate_roman, p.roman_word_break),+ (p2.auto_tcy, p2.auto_tcy_include_roman, p2.rotate_roman, p2.roman_word_break)+ );+ assert_eq!(+ (p.grid_align, p.grid_reference, p.grid_gyoudori, p.paragraph_gyoudori),+ (p2.grid_align, p2.grid_reference, p2.grid_gyoudori, p2.paragraph_gyoudori)+ );+}++#[test]+fn ruby_settings_import_from_idml_and_round_trip() {+ use designcraft_doc::cjk_settings::AdornmentOverprint;+ use designcraft_doc::ruby::{RubyAlignment, RubyOverhang, RubyParentSpacing, RubyPosition, RubyType};+ // InDesign's names: RubyFlag is a number, colours and fonts are properties.+ 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]">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" RubyFlag="1" RubyString="かん じ" RubyType="PerCharacterRuby" RubyAlignment="RubyCenter" RubyPosition="BelowLeft" RubyYOffset="-1.4173228" RubyFontSize="-1" RubyXScale="90" RubyParentOverhangAmount="RubyOverhangNoLimit" RubyParentSpacing="RubyParentBothSides" RubyAutoAlign="false" RubyAutoScaling="true" RubyParentScalingPercent="40" RubyAutoTcyDigits="2" RubyTint="-1" RubyOverprintFill="Auto"><Properties><RubyFont type="string">$ID/</RubyFont><RubyFontStyle type="enumeration">Nothing</RubyFontStyle><RubyFill type="string">Text Color</RubyFill></Properties><Content>漢字</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#;+ let doc = import_idml(&fixture_with_story(story)).unwrap();+ let a = doc.stories.values().find(|s| s.text.contains("漢字")).unwrap().runs().next().unwrap().1.over.clone();+ assert_eq!(a.ruby.as_deref(), Some("かん じ"));+ assert_eq!(a.ruby_type, Some(RubyType::PerCharacter));+ assert_eq!(a.ruby_alignment, Some(RubyAlignment::Center));+ assert_eq!(a.ruby_position, Some(RubyPosition::BelowLeft));+ assert_eq!(a.ruby_y_offset, Some(-1.4173228));+ assert_eq!(a.ruby_font_size, Some(None));+ assert_eq!(a.ruby_x_scale, Some(0.9));+ assert_eq!(a.ruby_overhang_amount, Some(RubyOverhang::NoLimit));+ assert_eq!(a.ruby_parent_spacing, Some(RubyParentSpacing::BothSides));+ assert_eq!((a.ruby_auto_align, a.ruby_auto_scaling, a.ruby_scaling_min), (Some(false), Some(true), Some(0.4)));+ assert_eq!(a.ruby_auto_tcy_digits, Some(2));+ assert_eq!((a.ruby_font.as_deref(), a.ruby_font_style.as_deref(), a.ruby_fill.as_deref()), (Some(""), Some(""), Some("")));+ assert_eq!((a.ruby_fill_tint, a.ruby_overprint_fill), (Some(None), Some(AdornmentOverprint::Auto)));++ // Every setting survives export and import.+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 300.0, 200.0), lid, "漢字", ParaFormat::default()).unwrap();+ d.story_mut(sid).unwrap().format_chars(0.."漢字".len(), |f| {+ let o = &mut f.over;+ o.ruby = Some("かん じ".into());+ o.ruby_type = Some(RubyType::PerCharacter);+ o.ruby_alignment = Some(RubyAlignment::OneAki);+ o.ruby_position = Some(RubyPosition::BelowLeft);+ o.ruby_x_offset = Some(1.5);+ o.ruby_y_offset = Some(-1.25);+ o.ruby_font = Some("Source Sans 3".into());+ o.ruby_font_style = Some("Bold".into());+ o.ruby_font_size = Some(Some(7.0));+ o.ruby_x_scale = Some(0.9);+ o.ruby_y_scale = Some(1.1);+ o.ruby_open_type_pro = Some(false);+ o.ruby_auto_tcy_digits = Some(3);+ o.ruby_auto_tcy_include_roman = Some(true);+ o.ruby_auto_tcy_auto_scale = Some(false);+ o.ruby_overhang = Some(true);+ o.ruby_overhang_amount = Some(RubyOverhang::HalfChar);+ o.ruby_parent_spacing = Some(RubyParentSpacing::EqualAki);+ o.ruby_auto_align = Some(false);+ o.ruby_auto_scaling = Some(true);+ o.ruby_scaling_min = Some(0.5);+ o.ruby_fill = Some("[Black]".into());+ o.ruby_fill_tint = Some(Some(0.5));+ o.ruby_stroke = Some(String::new());+ o.ruby_stroke_tint = Some(None);+ o.ruby_stroke_weight = Some(Some(0.25));+ o.ruby_overprint_fill = Some(AdornmentOverprint::On);+ o.ruby_overprint_stroke = Some(AdornmentOverprint::Off);+ });+ let a = d.stories[&sid].runs().next().unwrap().1.over.clone();+ let back = import_idml(&export_idml(&d)).unwrap();+ let b = back.stories.values().find(|s| s.text.contains("漢字")).unwrap().runs().next().unwrap().1.over.clone();+ macro_rules! same {+ ($($f:ident),*) => { $( assert_eq!(a.$f, b.$f, stringify!($f)); )* };+ }+ same!(+ ruby,+ ruby_type,+ ruby_alignment,+ ruby_position,+ ruby_x_offset,+ ruby_y_offset,+ ruby_font,+ ruby_font_style,+ ruby_font_size,+ ruby_x_scale,+ ruby_y_scale,+ ruby_open_type_pro,+ ruby_auto_tcy_digits,+ ruby_auto_tcy_include_roman,+ ruby_auto_tcy_auto_scale,+ ruby_overhang,+ ruby_overhang_amount,+ ruby_parent_spacing,+ ruby_auto_align,+ ruby_auto_scaling,+ ruby_scaling_min,+ ruby_fill,+ ruby_fill_tint,+ ruby_stroke,+ ruby_stroke_tint,+ ruby_stroke_weight,+ ruby_overprint_fill,+ ruby_overprint_stroke+ );+}++/// A file's tab list is sanitized as the Tabs commands check theirs: a hostile one imports+/// within the limits instead of failing the import.+#[test]+fn hostile_tab_lists_import_within_the_limits() {+ let item = |position: &str, leader: &str| {+ format!(+ r#"<ListItem type="record"><Alignment type="enumeration">LeftAlign</Alignment><AlignmentCharacter type="string">.</AlignmentCharacter><Leader type="string">{leader}</Leader><Position type="unit">{position}</Position></ListItem>"#+ )+ };+ let mut items: String = (0..500).rev().map(|i| item(&(i * 3).to_string(), "")).collect();+ items.push_str(&item("NaN", ""));+ items.push_str(&item("1e300", "0123456789"));+ let story = format!(+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">+ <Properties><TabList type="list">{items}</TabList></Properties>+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Many tabs</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#+ );+ let report = import_idml_report(&fixture_with_story(&story), &|_| None).unwrap();+ assert!(report.warnings.iter().any(|w| w.starts_with("tab lists repaired to fit the limits") && w.ends_with("): 1")), "{:?}", report.warnings);+ let doc = report.document;+ let tabs = doc.stories.values().find(|s| s.text.contains("Many tabs")).unwrap().paras[0].para.tabs.clone().unwrap();+ assert_eq!(tabs.len(), designcraft_doc::MAX_TAB_STOPS);+ assert!(tabs.iter().all(|t| t.position.is_finite() && t.leader.chars().count() <= designcraft_doc::MAX_TAB_LEADER));+ assert!(tabs.windows(2).all(|w| w[0].position < w[1].position), "sorted");+ assert_eq!((tabs[0].position, tabs[99].position), (0.0, 297.0), "the first stops by position");+ // A list within the limits, unsorted and with a char stop on `.`, imports without a warning.+ let fine = format!(+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">+ <Properties><TabList type="list">{}{}<ListItem type="record"><Alignment type="enumeration">CharacterAlign</Alignment><AlignmentCharacter type="string">.</AlignmentCharacter><Leader type="string"></Leader><Position type="unit">40</Position></ListItem></TabList></Properties>+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Few tabs</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#,+ item("90", "."),+ item("12", "")+ );+ let report = import_idml_report(&fixture_with_story(&fine), &|_| None).unwrap();+ assert!(report.warnings.is_empty(), "{:?}", report.warnings);+}++#[test]+fn cell_edge_gap_colours_and_tints_import_and_round_trip_per_edge() {+ let styles = CASCADE_STYLES.replace(+ r#"TopEdgeStrokeType="StrokeStyle/$ID/Dashed""#,+ r#"TopEdgeStrokeType="StrokeStyle/$ID/Dashed" TopEdgeStrokeGapColor="Color/Paper" TopEdgeStrokeGapTint="60" BottomEdgeStrokeGapColor="Color/Brand""#,+ );+ let story = CASCADE_STORY.replace(+ r#"<Cell Name="1:1">"#,+ r#"<Cell Name="1:1" LeftEdgeStrokeType="StrokeStyle/$ID/Dotted" LeftEdgeStrokeGapColor="Color/Brand" LeftEdgeStrokeGapTint="30" RightEdgeStrokeGapColor="Color/Paper">"#,+ );+ let gaps = |d: &Document| {+ let base = d.styles.cell.iter().find(|s| s.name == "Base").unwrap().strokes.clone();+ let table = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ let cell = table.cell(1, 1).unwrap().strokes.clone();+ (base.map(|e| (e.gap_color, e.gap_tint)), cell.map(|e| (e.gap_color, e.gap_tint)))+ };+ let d = import_idml(&fixture_with_table_styles(&styles, &story)).unwrap();+ d.check().unwrap();+ let (style, cell) = gaps(&d);+ assert_eq!(style[0], (Some("[Paper]".to_string()), Some(0.6)));+ assert_eq!(style[2], (Some("Brand".to_string()), None));+ assert_eq!((style[1].clone(), style[3].clone()), ((None, None), (None, None)));+ assert_eq!(cell[1], ("Brand".to_string(), 0.3), "left");+ assert_eq!(cell[3], ("[Paper]".to_string(), 1.0), "right");+ assert_eq!(cell[0].0, "[Paper]", "the Base style's top gap colour reaches the cell");+ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(gaps(&back), (style, cell));+}++#[test]+fn em_box_first_baseline_offset_round_trips() {+ use designcraft_doc::FirstBaseline;+ let first = |d: &Document| d.spreads[0].items[0].text_frame().unwrap().options.first_baseline;+ let d = inset_fixture(r#"<TextFramePreference FirstBaselineOffset="EmboxHeight"/>"#, "");+ assert_eq!(first(&d), FirstBaseline::EmboxHeight);+ assert_eq!(first(&import_idml(&export_idml(&d)).unwrap()), FirstBaseline::EmboxHeight);+ let unknown = inset_fixture(r#"<TextFramePreference FirstBaselineOffset="SomethingElse"/>"#, "");+ assert_eq!(first(&unknown), FirstBaseline::Ascent);+}++#[test]+fn imports_and_round_trips_text_wrap_side_and_contour_type() {+ let wrap = r#"<TextWrapPreference TextWrapMode="Contour" TextWrapSide="LeftSide"><ContourOption ContourType="BoundingBox" IncludeInsideEdges="false"/></TextWrapPreference><Image Self="im""#;+ let spread = SPREAD.replace(r#"<Image Self="im""#, wrap);+ assert_ne!(spread, SPREAD);+ 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 mut d = import_idml(&bytes).unwrap();+ let id = d.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().id;+ let w = d.item(id).unwrap().wrap.clone();+ assert_eq!(+ (w.mode, w.side, w.contour),+ (designcraft_doc::WrapMode::Contour, designcraft_doc::WrapSide::LeftSide, designcraft_doc::ContourType::BoundingBox)+ );+ // Every side and contour type survives export and import (detected edges included, which+ // composition follows as the frame's path).+ d.item_mut(id).unwrap().wrap.side = designcraft_doc::WrapSide::AwayFromSpine;+ d.item_mut(id).unwrap().wrap.contour = designcraft_doc::ContourType::DetectEdges;+ let back = import_idml(&export_idml(&d)).unwrap();+ let w = back.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().wrap.clone();+ assert_eq!((w.side, w.contour), (designcraft_doc::WrapSide::AwayFromSpine, designcraft_doc::ContourType::DetectEdges));+}++fn feather_fixture(transparency: &str) -> Document {+ let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">+ <idPkg:Spread src="Spreads/Spread_s.xml"/>+ </Document>"#;+ let rect = |id: &str, inner: &str| {+ format!(+ r#"<Rectangle Self="{id}" ItemTransform="1 0 0 1 0 0">+ <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>+ {inner}+ </Rectangle>"#+ )+ };+ let spread = format!(+ r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">+ <Spread Self="s">+ <Page Self="p" GeometricBounds="0 0 200 200" ItemTransform="1 0 0 1 0 0"/>+ {}{}+ </Spread>+ </idPkg:Spread>"#,+ rect("a", transparency),+ rect("b", "")+ );+ import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", &spread)])).unwrap()+}++#[test]+fn imports_gradient_and_directional_feathers() {+ let d = feather_fixture(+ r#"<TransparencySetting>+ <GradientFeatherSetting Applied="true" Type="Linear" Angle="0" Length="50" GradientStart="10 20">+ <OpacityGradientStop Self="s0" Opacity="90" Location="20"/>+ <OpacityGradientStop Self="s2" Opacity="10" Location="80" Midpoint="40"/>+ <OpacityGradientStop Self="s1" Opacity="55" Location="50" Midpoint="50"/>+ </GradientFeatherSetting>+ <DirectionalFeatherSetting Applied="true" LeftWidth="3" RightWidth="4" TopWidth="5" BottomWidth="6" Angle="0" Noise="0" ChokeAmount="0"/>+ </TransparencySetting>"#,+ );+ let items = &d.spreads[0].items;+ let gf = &items[0].effects.gradient_feather;+ assert!(gf.on && !gf.radial);+ assert!((gf.start - 0.9).abs() < 1e-6 && (gf.end - 0.1).abs() < 1e-6, "{gf:?}");+ let v = gf.vector.unwrap();+ for (a, b) in v.iter().zip([20.0, 20.0, 50.0, 20.0]) {+ assert!((a - b).abs() < 1e-9, "{v:?}");+ }+ let df = &items[0].effects.directional_feather;+ assert!(df.on);+ assert_eq!(df.widths, [5.0, 3.0, 6.0, 4.0]);+ assert_eq!(items[1].effects, designcraft_doc::Effects::default());++ // Not applied: the settings stay off.+ let off = feather_fixture(+ r#"<TransparencySetting>+ <GradientFeatherSetting Applied="false" Length="50" GradientStart="10 20"/>+ <DirectionalFeatherSetting Applied="false" LeftWidth="3"/>+ </TransparencySetting>"#,+ );+ assert_eq!(off.spreads[0].items[0].effects, designcraft_doc::Effects::default());+}++#[test]+fn gradient_and_directional_feathers_round_trip() {+ use designcraft_doc::{DirectionalFeather, GradientFeather, Item, ItemId};+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let add = |d: &mut Document, effects: designcraft_doc::Effects| {+ let mut it = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(40.0, 40.0, 140.0, 120.0)));+ it.effects = effects;+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ };+ let linear = designcraft_doc::Effects {+ gradient_feather: GradientFeather { on: true, radial: false, angle: 0.0, start: 0.75, end: 0.25, vector: Some([50.0, 60.0, 110.0, 60.0]) },+ directional_feather: DirectionalFeather { on: true, widths: [1.0, 2.0, 3.0, 4.0] },+ ..Default::default()+ };+ let radial = designcraft_doc::Effects {+ gradient_feather: GradientFeather { on: true, radial: true, angle: 30.0, start: 0.0, end: 1.0, vector: None },+ ..Default::default()+ };+ add(&mut d, linear.clone());+ add(&mut d, radial.clone());+ add(&mut d, designcraft_doc::Effects::default());+ let back = import_idml(&export_idml(&d)).unwrap();+ let effects: Vec<_> = back.spreads[0].items.iter().map(|i| i.effects.clone()).collect();+ assert_eq!(effects, [linear, radial, designcraft_doc::Effects::default()]);+}++/// One single-column text frame at (0, 0)-(300, 200) on page 1, beside a 100 pt wide rectangle+/// with a bounding-box wrap and `wrap_props` inside its `TextWrapPreference/Properties`.+fn custom_wrap_fixture(wrap_props: &str) -> Vec<u8> {+ let rect = |w: f64, h: f64| {+ format!(+ r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray><PathPointType Anchor="0 0"/><PathPointType Anchor="0 {h}"/><PathPointType Anchor="{w} {h}"/><PathPointType Anchor="{w} 0"/></PathPointArray></GeometryPathType></PathGeometry>"#+ )+ };+ let spread = format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <Spread Self="sp1" PageCount="2" ItemTransform="1 0 0 1 0 0">+ <Page Self="p1" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 -500 -350"/>+ <Page Self="p2" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 0 -350"/>+ <TextFrame Self="t1" ParentStory="s1" PreviousTextFrame="n" NextTextFrame="n" ItemLayer="L1" ItemTransform="1 0 0 1 -450 -300">+ <Properties>{frame}</Properties>+ </TextFrame>+ <Rectangle Self="w" ItemLayer="L1" ItemTransform="1 0 0 1 -450 -300">+ <Properties>{obj}</Properties>+ <TextWrapPreference TextWrapMode="BoundingBoxTextWrap" TextWrapSide="BothSides"><Properties>{wrap_props}<TextWrapOffset Top="0" Left="0" Bottom="0" Right="0"/></Properties></TextWrapPreference>+ </Rectangle>+ </Spread>+</idPkg:Spread>"#,+ frame = rect(300.0, 200.0),+ obj = rect(100.0, 200.0),+ );+ let words = "wrap ".repeat(120);+ let story = format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <Story Self="s1"><ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>{words}</Content></CharacterStyleRange></ParagraphStyleRange></Story>+</idPkg:Story>"#+ );+ 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),+ ])+}++/// The custom boundary: 40 pt wide, the full height of the 100 pt wide rectangle.+const NARROW_WRAP_PATH: &str = r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray><PathPointType Anchor="0 0" LeftDirection="0 0" RightDirection="0 0"/><PathPointType Anchor="0 200" LeftDirection="0 200" RightDirection="0 200"/><PathPointType Anchor="40 200" LeftDirection="40 200" RightDirection="40 200"/><PathPointType Anchor="40 0" LeftDirection="40 0" RightDirection="40 0"/></PathPointArray></GeometryPathType></PathGeometry>"#;++fn wrapping_item(d: &Document) -> &designcraft_doc::Item {+ d.spreads[0].items.iter().find(|i| i.wrap.mode != designcraft_doc::WrapMode::None).unwrap()+}++/// Leftmost line start in the frame.+fn first_line_x(d: &Document) -> f64 {+ let sid = *d.stories.keys().next().unwrap();+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());+ assert!(cs.frames[0].lines.len() > 3);+ cs.frames[0].lines.iter().map(|l| l.x0).fold(f64::INFINITY, f64::min)+}++#[test]+fn custom_wrap_boundary_imports_composes_and_round_trips() {+ let plain = import_idml_with(&custom_wrap_fixture(""), &|_| None).unwrap();+ assert_eq!(wrapping_item(&plain).wrap.path, None);+ assert!(first_line_x(&plain) >= 100.0 - 1e-6, "the frame's bounds push text to x = 100");++ let d = import_idml_with(&custom_wrap_fixture(NARROW_WRAP_PATH), &|_| None).unwrap();+ let path = wrapping_item(&d).wrap.path.clone().unwrap();+ assert_eq!(path.bounds(), Some(Rect::new(0.0, 0.0, 40.0, 200.0)));+ let x = first_line_x(&d);+ assert!((40.0 - 1e-6..100.0).contains(&x), "lines start at the custom boundary's edge, not the frame's: {x}");++ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(wrapping_item(&back).wrap.path, Some(path));+}++#[test]+fn hostile_custom_wrap_boundary_is_dropped() {+ let nan = NARROW_WRAP_PATH.replacen(r#"Anchor="40 200""#, r#"Anchor="NaN 200""#, 1);+ let inf = NARROW_WRAP_PATH.replacen(r#"Anchor="40 200""#, r#"Anchor="inf 200""#, 1);+ let huge = format!(+ r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{}</PathPointArray></GeometryPathType></PathGeometry>"#,+ r#"<PathPointType Anchor="1 1"/>"#.repeat(50_000)+ );+ let empty = r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray/></GeometryPathType></PathGeometry>"#;+ for props in [nan.as_str(), inf.as_str(), huge.as_str(), empty] {+ let d = import_idml_with(&custom_wrap_fixture(props), &|_| None).unwrap();+ let it = wrapping_item(&d);+ assert_eq!(it.wrap.mode, designcraft_doc::WrapMode::BoundingBox);+ assert_eq!(it.wrap.path, None);+ assert!(first_line_x(&d) >= 100.0 - 1e-6);+ }+}++/// A family name keeps its spaces ("Minion Pro " is a font of its own) and `FontStyle="Nothing"`+/// leaves the style to the paragraph, also after an export.+#[test]+fn applied_font_keeps_spaces_and_font_style_nothing_inherits() {+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Text%3aBody" FontStyle="Bold">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" FontStyle="Nothing"><Properties><AppliedFont type="string">DC Space </AppliedFont></Properties><Content>Spaced</Content></CharacterStyleRange>+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" FontStyle="$ID/Nothing"><Content> plain</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#;+ let check = |d: &Document| {+ let s = d.stories.values().find(|s| s.text.contains("Spaced")).unwrap();+ let (_, base) = d.styles.resolve_para(&s.paras[0]);+ let runs: Vec<_> = s.runs().map(|(_, f)| f.clone()).collect();+ assert_eq!(runs[0].over.font_family.as_deref(), Some("DC Space "));+ for f in &runs {+ assert_eq!(d.styles.resolve_char(&base, f).font_style, "Bold", "the enclosing range's style");+ }+ };+ let d = import_idml(&fixture_with_story(story)).unwrap();+ check(&d);+ check(&import_idml(&export_idml(&d)).unwrap());+}++fn tracked_story(body: &str) -> String {+ format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <Story Self="s1">{body}</Story>+</idPkg:Story>"#+ )+}++const CSR: &str = r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]">"#;++#[test]+fn tracked_deleted_text_takes_no_room_and_round_trips() {+ let psr = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle">"#;+ let kwn = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle" KeepWithNext="2">"#;+ let tracked = tracked_story(&format!(+ r#"{psr}{CSR}<Content>The first paragraph keeps a </Content><Change Self="c1" ChangeType="DeletedText"><Content>deleted </Content></Change><Content>word.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>+{kwn}{CSR}<Change Self="c2" ChangeType="DeletedText"><Br/></Change></CharacterStyleRange></ParagraphStyleRange>+{psr}{CSR}<Change Self="c3" ChangeType="InsertedText"><Content>New </Content></Change><Content>second paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#+ ));+ let plain = tracked_story(&format!(+ r#"{psr}{CSR}<Content>The first paragraph keeps a word.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>+{psr}{CSR}<Content>New second paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#+ ));+ let lines = |d: &Document| {+ let sid = *d.stories.keys().next().unwrap();+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());+ cs.frames.iter().flat_map(|f| f.lines.iter().map(|l| (l.baseline, l.x0, l.end_x))).collect::<Vec<_>>()+ };+ let d = import_idml_with(&fixture_with_story(&tracked), &|_| None).unwrap();+ let story = d.stories.values().next().unwrap();+ assert_eq!(story.text, "The first paragraph keeps a deleted word.\n\nNew second paragraph.");+ let marks = |s: &designcraft_doc::Story| s.runs().map(|(r, f)| (s.text[r].to_string(), f.over.change)).collect::<Vec<_>>();+ use designcraft_doc::ChangeMark::{Deleted, Inserted};+ let want = vec![+ ("The first paragraph keeps a ".to_string(), None),+ ("deleted ".to_string(), Some(Deleted)),+ ("word.\n".to_string(), None),+ ("\n".to_string(), Some(Deleted)),+ ("New ".to_string(), Some(Inserted)),+ ("second paragraph.".to_string(), None),+ ];+ assert_eq!(marks(story), want);+ let reference = import_idml_with(&fixture_with_story(&plain), &|_| None).unwrap();+ let expected = lines(&reference);+ assert!(expected.len() >= 2);+ assert_eq!(lines(&d), expected);+ // Export writes the changes back as `Change` elements.+ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(marks(back.stories.values().next().unwrap()), want);+}+++ #[test]+ fn same_para_style_spacing_imports_and_round_trips() {+ 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]" SameParaStyleSpacing="0">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Gap</Content><Br/></CharacterStyleRange>+ </ParagraphStyleRange>+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" SameParaStyleSpacing="Nothing">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Ignore</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#;+ let d = import_idml(&fixture_with_story(story)).unwrap();+ let st = d.stories.values().find(|s| s.text.contains("Gap")).unwrap();+ assert_eq!(st.paras[0].para.same_para_style_spacing, Some(Some(0.0)));+ // Ignore is an explicit "off", not an unset value.+ assert_eq!(st.paras[1].para.same_para_style_spacing, Some(None));+ let back = import_idml(&export_idml(&d)).unwrap();+ let b = back.stories.values().find(|s| s.text.contains("Gap")).unwrap();+ assert_eq!(b.paras[0].para.same_para_style_spacing, Some(Some(0.0)));+ // The explicit Ignore survives the round trip too.+ assert_eq!(b.paras[1].para.same_para_style_spacing, Some(None));+ }