Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge #285: Text: a column, frame or page break ends its paragraph; odd and even page breaks

aiongg2a80cfe54cee
diff --cc crates/compose/src/lib.rs
index dbb6eabf1,782d9c653..fae985652
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@@ -553,26 -504,18 +553,27 @@@ fn compose_with_db(doc: &Document, stor
note_snaps.truncate(pi);
note_snaps.push((notes.num, notes.key, notes.placed.len()));
info.truncate(pi);
+ // A balancing trial whose band ran past its frame: re-lay the band with more room.
+ if trial.as_ref().is_some_and(|t| cur.fi > t.key.0)
+ && let Some(j) = trial_failed(&mut trial, &mut limits, balance_runs < balance_budget)
+ {
+ balance_runs += 1;
+ rewind(j, &snaps, &note_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap);
+ pi = j;
+ continue 'paras;
+ }
let pf = &story.paras[pi];
let (pp, base_chars) = doc.styles.resolve_para(pf);
+ // A break character that ends the previous paragraph sends this one on, like a start option.
+ let after_break = pi
+ .checked_sub(1)
+ .and_then(|p| para_ranges.get(p))
+ .and_then(|r| story.text.get(r.clone()))
+ .and_then(|t| t.chars().next_back())
+ .and_then(break_start);
if let Some(t) = story.para_table(pi) {
if cur.last_baseline.is_some() {
- match pp.start_paragraph {
- StartParagraph::NextColumn => cur.next_column(&cols),
- StartParagraph::NextFrame | StartParagraph::NextPage | StartParagraph::NextOddPage | StartParagraph::NextEvenPage => {
- cur.next_frame()
- }
- StartParagraph::Anywhere => {}
- }
+ cur.start(after_break.unwrap_or(pp.start_paragraph), &cols, frames, doc);
}
let at_top = cur.last_baseline.is_none();
let start_at = (cur.fi, cur.col);
@@@ -794,76 -688,24 +795,81 @@@
);
bidi::resolve_mirroring(&mut glyphs, &bidi_info);
apply_desired_spacing(&mut glyphs, &pp);
+ mojikumi::apply(&mut glyphs, &doc.styles, &pp.mojikumi);
let hyph_after = hyphenation_points(&story.text, &glyphs, &pp, &hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), &base_chars));
let base_size = base_chars.size;
- let base_leading = match base_chars.leading {
- designcraft_doc::Leading::Auto => base_size * pp.auto_leading,
+ let spacing = spacing_for(&pp, base_size);
+ // An empty paragraph takes its height from its paragraph mark's character format.
+ let mark_chars = if glyphs.is_empty() {
+ std::borrow::Cow::Owned(doc.styles.resolve_char(&base_chars, story.char_format_of(prange.start)))
+ } else {
+ std::borrow::Cow::Borrowed(&base_chars)
+ };
+ let mark_leading = match mark_chars.leading {
+ designcraft_doc::Leading::Auto => mark_chars.size * pp.auto_leading,
designcraft_doc::Leading::Points(v) => v,
};
- let spacing = spacing_for(&pp, base_size);
+ // A paragraph set across the columns moves on to the next frame where others move on to
+ // the next column.
+ let spanning = matches!(pp.span_columns, SpanColumns::Span(n) if n != 1);
+ span_paras[pi] = spanning;
+ let next_column = |cur: &mut Cursor| if spanning { cur.next_frame() } else { cur.next_column(&cols) };
++ let go = |cur: &mut Cursor, start| match start {
++ StartParagraph::NextColumn => next_column(cur),
++ start => cur.start(start, &cols, frames, doc),
++ };
// Paragraph start options.
+ if let Some(start) = after_break
+ && cur.last_baseline.is_some()
+ {
- cur.start(start, &cols, frames, doc);
++ go(&mut cur, start);
+ }
if force_col[pi] {
- cur.next_column(&cols);
+ next_column(&mut cur);
}
if cur.last_baseline.is_some() {
- match pp.start_paragraph {
- StartParagraph::NextColumn => next_column(&mut cur),
- StartParagraph::NextFrame | StartParagraph::NextPage | StartParagraph::NextOddPage | StartParagraph::NextEvenPage => cur.next_frame(),
- StartParagraph::Anywhere => {}
- }
- cur.start(pp.start_paragraph, &cols, frames, doc);
++ go(&mut cur, pp.start_paragraph);
+ }
+ if spanning && cur.fi < frames.len() {
+ // Close the band: the paragraph goes below the deepest of its columns, which are
+ // balanced first.
+ let key = cur.band_key();
+ let deepest = out.frames[cur.fi]
+ .lines
+ .get(cur.band.line0..)
+ .unwrap_or_default()
+ .iter()
+ .map(|l| (l.baseline, l.descent))
+ .max_by(|a, b| (a.0 + a.1).total_cmp(&(b.0 + b.1)));
+ if let Some((baseline, descent)) = deepest {
+ let bottom = baseline + descent;
+ let multi = cols[cur.fi].len() > 1;
+ let active = trial.as_ref().is_some_and(|t| t.key == key && t.span == pi);
+ if !active && let Some(t) = trial.take() {
+ set_limit(&mut limits, t.key, None);
+ }
+ if multi && (active || limit_of(&limits, key).is_none() && balance_runs < balance_budget) {
+ let top = cur.clip(cols[cur.fi][0]).y0;
+ let mut t = trial.take().unwrap_or(Trial { key, span: pi, lo: top, hi: bottom, tries: 0, done: false });
+ // This layout fits: its bottom is the best so far.
+ t.hi = t.hi.min(bottom);
+ let next = if t.done { t.hi } else { t.next() };
+ set_limit(&mut limits, key, Some(next));
+ if !t.done {
+ trial = Some(t);
+ balance_runs += 1;
+ rewind(key.1, &snaps, &note_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap);
+ pi = key.1;
+ continue 'paras;
+ }
+ }
+ cur.col = 0;
+ cur.last_baseline = Some(baseline);
+ cur.last_descent = descent;
+ } else if cur.col != 0 {
+ cur.col = 0;
+ cur.resume();
+ }
}
if cur.last_baseline.is_some() {
cur.pending += pp.space_before;
@@@ -1042,49 -842,12 +1048,49 @@@
moved = true;
break;
}
- let ind_l = pp.left_indent + if line_no == 0 { pp.first_line_indent } else { 0.0 };
+ // A drop cap sits at the start-side indent; the first-line indent doesn't move it.
+ let beside = drop_cap.as_ref().filter(|dc| line_no < dc.lines && col_first_line == 0).map(DropCap::indent);
+ let (ind_l, ind_r) = match beside {
+ Some(w) if rtl => (pp.left_indent, pp.right_indent + w),
+ Some(w) => (pp.left_indent + w, pp.right_indent),
+ None => (pp.left_indent + if line_no == 0 { pp.first_line_indent } else { 0.0 }, pp.right_indent),
+ };
let lx0 = x0 + ind_l;
- let lx1 = x1 - pp.right_indent;
+ let lx1 = x1 - ind_r;
let last = k + 1 == breaks.len();
+ // The break character that ends this line, if any (it is the line's last glyph).
+ let brk = if b.forced && e > s {
+ e.checked_sub(1).and_then(|i| glyphs.get(i)).map(|g| g.ch).filter(|&c| breaker::is_forced(c))
+ } else {
+ None
+ };
+ // A column, frame or page break ends the line as a paragraph's last line (last-line
+ // alignment); a justified line ended by a forced line break stays justified.
- let ends_para = last || matches!(brk, Some(story::COLUMN_BREAK | story::FRAME_BREAK | story::PAGE_BREAK));
++ let ends_para = last || brk.is_some_and(story::is_break_char);
+ let forced_mid = brk == Some(story::FORCED_LINE_BREAK) && !last;
let (mut placed, end_x, ratio) =
- layout_line(&glyphs, s, e, b.hyphen, lx0, lx1, col.x0, &pp, &spacing, last, b.forced && !last, f.left_page, &bidi_info);
+ layout_line(&glyphs, s, e, b.hyphen, lx0, lx1, col.x0, &pp, &spacing, ends_para, forced_mid, f.left_page, &bidi_info);
+ // The spaces the break trimmed off the end follow the line undrawn, so the caret
+ // and the selection reach them; alignment and justification ignore them.
+ if pp.direction != designcraft_doc::TextDirection::RightToLeft && !placed.iter().any(|g| g.rtl) {
+ let mut x = end_x;
+ for g in glyphs.get(e..(g0 + b.next).min(glyphs.len())).unwrap_or(&[]).iter().filter(|g| g.is_space()) {
+ placed.push(PlacedGlyph { visible: false, ..place(g, x) });
+ x += g.adv;
+ }
+ }
+ let mut drop_box = None;
+ if line_no == 0
+ && let Some(dc) = &drop_cap
+ {
+ let at = if rtl { x1 - pp.right_indent - dc.width } else { x0 + pp.left_indent - dc.lsb };
+ placed.splice(0..0, place_drop_cap(dc, at, rtl));
+ drop_box = Some(DropCapBox {
+ end: dc.end,
+ baseline: baseline + dc.drop,
+ rect: Rect::new(at, baseline - asc, at + dc.width, baseline + dc.drop + desc),
+ });
+ }
ruby::annotate(db, &styles_tab, &mut placed, doc.settings.glyph_fallback);
let range_end = if last { prange.end } else { glyphs.get(g0 + b.next).map(|g| g.byte).unwrap_or(prange.end) };
let range_start = glyphs.get(s).map(|g| g.byte).unwrap_or(prange.start).min(range_end);
@@@ -1151,28 -894,18 +1157,18 @@@
cur.last_descent = desc;
cur.pending = 0.0;
line_no += 1;
- // Column / frame / page break characters.
- if b.forced && e < glyphs.len() + 1 {
- let jumped = match brk {
- Some(story::COLUMN_BREAK) => {
- next_column(&mut cur);
- true
- }
- Some(story::FRAME_BREAK) | Some(story::PAGE_BREAK) => {
- cur.next_frame();
- true
- }
- _ => false,
- };
- if jumped {
- // The rest of the paragraph continues in the new column/frame: re-break it there.
- col_first_line = line_no;
- if k + 1 < breaks.len() {
- g0 += b.next;
- moved = true;
- break;
- }
- }
+ // A column / frame / page break inside the paragraph: the rest of it continues in the
+ // new column/frame/page, re-broken there. (A break that ends the paragraph moves the
+ // next paragraph instead.)
+ if b.forced
+ && k + 1 < breaks.len()
- && let Some(start) = glyphs.get(g0 + b.next.saturating_sub(1)).and_then(|g| break_start(g.ch))
++ && let Some(start) = brk.and_then(break_start)
+ {
- cur.start(start, &cols, frames, doc);
++ go(&mut cur, start);
+ col_first_line = line_no;
+ g0 += b.next;
+ moved = true;
+ break;
}
}
if !moved {
@@@ -1860,76 -1374,49 +1868,100 @@@ impl Cursor
fn next_frame(&mut self) {
self.fi += 1;
self.col = 0;
- self.last_baseline = None;
- self.pending = 0.0;
+ self.band = Band { para: self.pi, ..Band::default() };
+ self.resume();
+ }
+ /// Start the current column at the top of the band.
+ fn resume(&mut self) {
+ match self.band.above {
+ Some(a) => {
+ self.last_baseline = Some(a.baseline);
+ self.last_descent = a.descent;
+ self.last_reference = a.reference;
+ self.pending = a.pending;
+ }
+ None => {
+ self.last_baseline = None;
+ self.pending = 0.0;
+ }
+ }
}
+ /// Move on as a paragraph start option (or a break character) asks.
+ fn start(&mut self, start: StartParagraph, cols: &[Vec<Rect>], frames: &[FrameSpec], doc: &Document) {
+ match start {
+ StartParagraph::Anywhere => {}
+ StartParagraph::NextColumn => self.next_column(cols),
+ StartParagraph::NextFrame => self.next_frame(),
+ StartParagraph::NextPage => self.next_page(frames, doc, None),
+ StartParagraph::NextOddPage => self.next_page(frames, doc, Some(true)),
+ StartParagraph::NextEvenPage => self.next_page(frames, doc, Some(false)),
+ }
+ }
+ /// Move to the next frame on a later page, one with an odd page number (`odd` true) or an
+ /// even one (false) when asked. Frames without a page (parent pages) qualify; with no frame
+ /// left, the rest of the story is overset.
+ fn next_page(&mut self, frames: &[FrameSpec], doc: &Document, odd: Option<bool>) {
+ let from = frames.get(self.fi).and_then(|f| f.page);
+ let skip = |f: &FrameSpec| f.page.is_some_and(|p| Some(p) == from || odd.is_some_and(|o| (doc.page_number(p) % 2 == 1) != o));
+ let mut fi = self.fi.saturating_add(1);
+ while frames.get(fi).is_some_and(skip) {
+ fi += 1;
+ }
+ self.next_frame();
+ self.fi = fi;
+ }
- /// Baseline for the next line with leading `lead` and ascent `asc`.
- fn next_baseline(&self, f: &FrameSpec, col: Rect, lead: f64, asc: f64, _pp: &ParaProps) -> f64 {
+ fn band_key(&self) -> BandKey {
+ (self.fi, self.band.para)
+ }
+ /// Column `col` of the current frame limited to the band: below the spanning paragraph above
+ /// it and, while balancing, above the trial bottom.
+ fn clip(&self, col: Rect) -> Rect {
+ let y0 = self.band.above.map_or(col.y0, |a| a.top.max(col.y0).min(col.y1.max(col.y0)));
+ let y1 = limit_of(&self.limits, self.band_key()).map_or(col.y1, |b| b.min(col.y1).max(y0));
+ Rect::new(col.x0, y0, col.x1, y1)
+ }
+ /// Baseline for the next line with leading `lead`, ascent `asc` and first baseline heights
+ /// `tops`.
+ fn next_baseline(&self, f: &FrameSpec, col: Rect, lead: f64, asc: f64, tops: Tops, _pp: &ParaProps) -> f64 {
match self.last_baseline {
Some(b) => b + lead + self.pending,
- None => {
- let off = match f.opts.first_baseline {
- FirstBaseline::Ascent => asc,
- FirstBaseline::CapHeight => asc * 0.72,
- FirstBaseline::XHeight => asc * 0.5,
- FirstBaseline::Leading => lead,
- FirstBaseline::Fixed => 0.0,
- };
- col.y0 + off.max(f.opts.first_baseline_min)
- }
+ None => col.y0 + first_baseline_offset(f, lead, asc, tops),
}
}
+ /// How the next line clears a Jump Object wrap: by whole leadings below the line above, or, first
+ /// in its column, as at the top of a frame whose top is the wrap bottom.
+ fn jump(&self, f: &FrameSpec, lead: f64, asc: f64, tops: Tops) -> Jump {
+ match self.last_baseline {
+ Some(_) => Jump { top: lead, step: lead },
+ None => Jump { top: first_baseline_offset(f, lead, asc, tops), step: 0.0 },
+ }
+ }
+}
+
+/// The frame's first baseline offset below the top of a column, for a line with leading `lead`,
+/// ascent `asc` and first baseline heights `tops`.
+fn first_baseline_offset(f: &FrameSpec, lead: f64, asc: f64, tops: Tops) -> f64 {
+ let off = match f.opts.first_baseline {
+ // Vertical frames measure from the ascent.
+ FirstBaseline::Ascent if f.vertical => asc,
+ FirstBaseline::CapHeight if f.vertical => asc * 0.72,
+ FirstBaseline::XHeight if f.vertical => asc * 0.5,
+ FirstBaseline::Ascent => tops.typo_ascent,
+ FirstBaseline::CapHeight => tops.cap,
+ FirstBaseline::XHeight => tops.xh,
+ FirstBaseline::Leading => lead,
+ FirstBaseline::Fixed => 0.0,
+ };
+ off.max(f.opts.first_baseline_min)
+}
+
+/// A line's tallest typographic ascender, cap height and x height above its baseline: the
+/// first baseline offsets.
+#[derive(Clone, Copy, Default)]
+struct Tops {
+ typo_ascent: f64,
+ cap: f64,
+ xh: f64,
}
/// Em box relative to the baseline. Font ascender/descender proportions locate it;
diff --cc crates/compose/src/tests.rs
index 2959bdd95,7180dc339..62aafe760
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@@ -812,32 -561,23 +812,49 @@@ fn column_break_moves_following_text()
assert!(lines[1].baseline < 20.0, "second column starts at the top");
}
+ /// InDesign: a break character ends its paragraph; the next paragraph starts on the next page (odd
+ /// or even for those breaks), with no empty line where the break was.
+ #[test]
+ fn break_characters_end_their_paragraph_and_keep_page_parity() {
+ use designcraft_doc::story::{EVEN_PAGE_BREAK, ODD_PAGE_BREAK, PAGE_BREAK};
+ let mut d = Document::new(&NewDocument { pages: 4, facing_pages: false, primary_text_frame: true, ..Default::default() });
+ let sid = d.settings.primary_story.unwrap();
+ let text = format!("one{ODD_PAGE_BREAK}\ntwo{EVEN_PAGE_BREAK}\nthree{PAGE_BREAK}\nfour");
+ d.story_mut(sid).unwrap().insert(0, &text);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ // Frame i is on page i + 1: "one" on 1, "two" on the next odd page (3), "three" on the next
+ // even page (4), and "four" has no page left.
+ let lines: Vec<(usize, usize)> = cs.frames.iter().enumerate().flat_map(|(fi, f)| f.lines.iter().map(move |l| (fi, l.para))).collect();
+ assert_eq!(lines, vec![(0, 0), (2, 1), (3, 2)]);
+ assert_eq!(cs.overset_at, Some(text.find("four").unwrap()));
+ }
+
+#[test]
+fn line_before_a_break_character_is_a_last_line() {
+ // As in InDesign: column, frame and page breaks end the paragraph's last line (set with the
+ // last-line alignment), while a forced line break inside a justified paragraph is justified.
+ use designcraft_doc::story::{COLUMN_BREAK, FORCED_LINE_BREAK, FRAME_BREAK, PAGE_BREAK};
+ for (brk, align, justified) in [
+ (COLUMN_BREAK, Align::LeftJustified, false),
+ (FRAME_BREAK, Align::LeftJustified, false),
+ (PAGE_BREAK, Align::LeftJustified, false),
+ (PAGE_BREAK, Align::FullyJustified, true),
+ (FORCED_LINE_BREAK, Align::LeftJustified, true),
+ ] {
+ // A space after the break is skipped and does not keep the break from moving the text.
+ let text = format!("one two three{brk} four five six");
+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 400.0, 300.0), ParaAttrs { align: Some(align), ..Default::default() });
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let full = (l.end_x - l.x1).abs() < 0.6;
+ assert_eq!(full, justified, "{brk:?} {align:?}: line ends at {} of {}", l.end_x, l.x1);
+ if brk == COLUMN_BREAK {
+ assert_eq!(all_lines(&cs)[1].column, 1, "the text after a column break starts the next column");
+ }
+ }
+}
+
#[test]
fn tabs_without_stops_use_default_half_inch() {
let (d, sid, _) = doc_with("A\tB", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());
diff --cc crates/idml/src/tests.rs
index 9ef95e63e,73321c055..d6befa5ea
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@@ -210,376 -194,49 +210,419 @@@ fn fixture_with_story(story: &str) -> V
])
}
+fn fixture_with_styles(styles: &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),
+ ])
+}
+
+/// Paragraph styles `Body` (based on the root) and `Loose` (no BasedOn), both with `attrs`.
+fn keep_styles(attrs: &str) -> String {
+ format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?>
+<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
+ <RootParagraphStyleGroup Self="rp">
+ <ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" PointSize="12"/>
+ <ParagraphStyle Self="ParagraphStyle/Body" Name="Body" {attrs}>
+ <Properties><BasedOn type="object">ParagraphStyle/$ID/[No paragraph style]</BasedOn></Properties>
+ </ParagraphStyle>
+ <ParagraphStyle Self="ParagraphStyle/Loose" Name="Loose" {attrs}/>
+ </RootParagraphStyleGroup>
+</idPkg:Styles>"#
+ )
+}
+
+/// Keep Lines Together whose mode no style sets is InDesign's default: at start/end of paragraph.
+/// An explicit mode still wins.
+#[test]
+fn keep_lines_mode_defaults_to_start_and_end() {
+ let keep = r#"KeepLinesTogether="true" KeepFirstLines="2" KeepLastLines="2""#;
+ for (attrs, all) in [(keep.to_string(), false), (format!(r#"{keep} KeepAllLinesTogether="true""#), true)] {
+ let d = import_idml_with(&fixture_with_styles(&keep_styles(&attrs)), &|_| None).unwrap();
+ for name in ["Body", "Loose"] {
+ let (pp, _) = d.styles.resolve_para_style(name);
+ assert_eq!((pp.keep_lines_together, pp.keep_all_lines, pp.keep_first, pp.keep_last), (true, all, 2, 2), "{name}: {attrs}");
+ }
+ }
+}
+
+type Resolved = (designcraft_doc::ParaProps, designcraft_doc::CharProps);
+
+/// (IDML attribute, InDesign's default as IDML writes it, another value, the resolved field,
+/// its value for InDesign's default, its value for the other value).
+type AttrRow = (&'static str, &'static str, &'static str, fn(&Resolved) -> String, String, String);
+
+macro_rules! attr_rows {
+ ($($attr:literal: $default:literal => $dv:expr, $other:literal => $ov:expr, |$r:ident| $field:expr;)*) => {
+ vec![$(($attr, $default, $other, (|$r: &Resolved| format!("{:?}", $field)) as fn(&Resolved) -> String, format!("{:?}", $dv), format!("{:?}", $ov)),)*]
+ };
+}
+
+/// InDesign's defaults for a new document's [No Paragraph Style], for every paragraph and
+/// character attribute the importer reads (except the font family: see below).
+fn indesign_text_defaults() -> Vec<AttrRow> {
+ use designcraft_doc::{Align, Capitalization, Composer, Digits, GridAlign, Leading, ListType, Position, StartParagraph, TextDirection};
+ attr_rows! {
+ "Justification": "LeftAlign" => Align::Left, "CenterAlign" => Align::Center, |r| r.0.align;
+ "ParagraphDirection": "LeftToRightDirection" => TextDirection::LeftToRight, "RightToLeftDirection" => TextDirection::RightToLeft, |r| r.0.direction;
+ "LeftIndent": "0" => 0.0, "6" => 6.0, |r| r.0.left_indent;
+ "RightIndent": "0" => 0.0, "6" => 6.0, |r| r.0.right_indent;
+ "FirstLineIndent": "0" => 0.0, "6" => 6.0, |r| r.0.first_line_indent;
+ "LastLineIndent": "0" => 0.0, "6" => 6.0, |r| r.0.last_line_indent;
+ "SpaceBefore": "0" => 0.0, "6" => 6.0, |r| r.0.space_before;
+ "SpaceAfter": "0" => 0.0, "6" => 6.0, |r| r.0.space_after;
+ "DropCapLines": "0" => 0, "3" => 3, |r| r.0.drop_cap_lines;
+ "DropCapCharacters": "0" => 0, "1" => 1, |r| r.0.drop_cap_chars;
+ "DropcapDetail": "1" => (true, false), "2" => (false, true), |r| (r.0.drop_cap_align_left, r.0.drop_cap_scale_descenders);
+ "GridAlignment": "None" => GridAlign::None, "AlignToBaseline" => GridAlign::AllLines, |r| r.0.grid_align;
+ "Composer": "HL Composer" => Composer::Paragraph, "HL Single" => Composer::SingleLine, |r| r.0.composer;
+ "Hyphenation": "true" => true, "false" => false, |r| r.0.hyphenate;
+ "HyphenateWordsLongerThan": "5" => 5, "7" => 7, |r| r.0.hyph_min_word;
+ "HyphenateAfterFirst": "2" => 2, "3" => 3, |r| r.0.hyph_after_first;
+ "HyphenateBeforeLast": "2" => 2, "3" => 3, |r| r.0.hyph_before_last;
+ "HyphenateLadderLimit": "3" => 3, "0" => 0, |r| r.0.hyph_limit;
+ "HyphenationZone": "36" => 36.0, "18" => 18.0, |r| r.0.hyph_zone;
+ "HyphenateCapitalizedWords": "true" => true, "false" => false, |r| r.0.hyph_capitalized;
+ "HyphenateLastWord": "true" => true, "false" => false, |r| r.0.hyph_last_word;
+ "HyphenateAcrossColumns": "true" => true, "false" => false, |r| r.0.hyph_across_column;
+ "HyphenWeight": "5" => 0.5, "9" => 0.9, |r| r.0.hyph_weight;
+ "MinimumWordSpacing": "80" => 0.8, "70" => 0.7, |r| r.0.word_space_min;
+ "DesiredWordSpacing": "100" => 1.0, "90" => 0.9, |r| r.0.word_space_desired;
+ "MaximumWordSpacing": "133" => 1.33, "150" => 1.5, |r| r.0.word_space_max;
+ "MinimumLetterSpacing": "0" => 0.0, "-5" => -0.05, |r| r.0.letter_space_min;
+ "DesiredLetterSpacing": "0" => 0.0, "1" => 0.01, |r| r.0.letter_space_desired;
+ "MaximumLetterSpacing": "0" => 0.0, "5" => 0.05, |r| r.0.letter_space_max;
+ "MinimumGlyphScaling": "100" => 1.0, "97" => 0.97, |r| r.0.glyph_scale_min;
+ "DesiredGlyphScaling": "100" => 1.0, "101" => 1.01, |r| r.0.glyph_scale_desired;
+ "MaximumGlyphScaling": "100" => 1.0, "103" => 1.03, |r| r.0.glyph_scale_max;
+ "AutoLeading": "120" => 1.2, "100" => 1.0, |r| r.0.auto_leading;
+ "SingleWordJustification": "FullyJustified" => Align::FullyJustified, "LeftAlign" => Align::Left, |r| r.0.single_word_justify;
+ "KeepWithNext": "0" => 0, "1" => 1, |r| r.0.keep_with_next;
+ "KeepLinesTogether": "false" => false, "true" => true, |r| r.0.keep_lines_together;
+ "KeepAllLinesTogether": "false" => false, "true" => true, |r| r.0.keep_all_lines;
+ "KeepFirstLines": "2" => 2, "3" => 3, |r| r.0.keep_first;
+ "KeepLastLines": "2" => 2, "3" => 3, |r| r.0.keep_last;
+ "StartParagraph": "Anywhere" => StartParagraph::Anywhere, "NextColumn" => StartParagraph::NextColumn, |r| r.0.start_paragraph;
+ "BulletsAndNumberingListType": "NoList" => ListType::None, "BulletList" => ListType::Bullets, |r| r.0.list_type;
+ "BalanceRaggedLines": "NoBalancing" => false, "FullyBalanced" => true, |r| r.0.balance_ragged;
+ "Kashidas": "DefaultKashidas" => true, "KashidasOff" => false, |r| r.0.kashidas;
+ "RuleAbove": "false" => false, "true" => true, |r| r.0.rule_above.on;
+ "RuleAboveColor": "Text Color" => designcraft_doc::TEXT_COLOR, "Color/Black" => "[Black]", |r| r.0.rule_above.color;
+ "RuleAboveTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.rule_above.tint;
+ "RuleBelow": "false" => false, "true" => true, |r| r.0.rule_below.on;
+ "RuleBelowColor": "Text Color" => designcraft_doc::TEXT_COLOR, "Color/Black" => "[Black]", |r| r.0.rule_below.color;
+ "RuleBelowTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.rule_below.tint;
+ "ParagraphShadingOn": "false" => false, "true" => true, |r| r.0.shading_on;
+ "ParagraphShadingColor": "Color/Black" => "[Black]", "Swatch/None" => "[None]", |r| r.0.shading_color;
+ "ParagraphShadingTint": "20" => 0.2f32, "50" => 0.5f32, |r| r.0.shading_tint;
+ "ParagraphBorderOn": "false" => false, "true" => true, |r| r.0.border_on;
+ "ParagraphBorderColor": "Color/Black" => "[Black]", "Swatch/None" => "[None]", |r| r.0.border_color;
+ "ParagraphBorderTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.border_tint;
+ "FontStyle": "Regular" => "Regular", "Bold" => "Bold", |r| r.1.font_style;
+ "PointSize": "12" => 12.0, "9" => 9.0, |r| r.1.size;
+ "Leading": "Auto" => Leading::Auto, "14" => Leading::Points(14.0), |r| r.1.leading;
+ "KerningMethod": "$ID/Metrics" => designcraft_doc::Kerning::Metrics, "$ID/Optical" => designcraft_doc::Kerning::Optical, |r| r.1.kerning;
+ "Tracking": "0" => 0.0, "20" => 20.0, |r| r.1.tracking;
+ "HorizontalScale": "100" => 1.0, "90" => 0.9, |r| r.1.h_scale;
+ "VerticalScale": "100" => 1.0, "90" => 0.9, |r| r.1.v_scale;
+ "BaselineShift": "0" => 0.0, "2" => 2.0, |r| r.1.baseline_shift;
+ "Skew": "0" => 0.0, "10" => 10.0, |r| r.1.skew;
+ "FillColor": "Color/Black" => "[Black]", "Swatch/None" => "[None]", |r| r.1.fill;
+ "FillTint": "-1" => 1.0, "50" => 0.5, |r| r.1.fill_tint;
+ "StrokeColor": "Swatch/None" => "[None]", "Color/Black" => "[Black]", |r| r.1.stroke;
+ "StrokeTint": "-1" => 1.0, "50" => 0.5, |r| r.1.stroke_tint;
+ "StrokeWeight": "1" => 1.0, "2" => 2.0, |r| r.1.stroke_weight;
+ "Capitalization": "Normal" => Capitalization::Normal, "AllCaps" => Capitalization::AllCaps, |r| r.1.capitalization;
+ "Position": "Normal" => Position::Normal, "Superscript" => Position::Superscript, |r| r.1.position;
+ "Underline": "false" => false, "true" => true, |r| r.1.underline;
+ "StrikeThru": "false" => false, "true" => true, |r| r.1.strikethrough;
+ "UnderlineTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.1.underline_tint;
+ "StrikeThruTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.1.strikethrough_tint;
+ "Ligatures": "true" => true, "false" => false, |r| r.1.ligatures;
+ "NoBreak": "false" => false, "true" => true, |r| r.1.no_break;
+ "OTFContextualAlternate": "true" => true, "false" => false, |r| designcraft_doc::otf::is_on(&r.1.otf_features, "calt");
+ "DigitsType": "DefaultDigits" => Digits::Default, "ArabicDigits" => Digits::Arabic, |r| r.1.digits;
+ "AppliedLanguage": "$ID/English: USA" => "English: USA", "$ID/German: 2006 Reform" => "German: 2006 Reform", |r| r.1.language;
+ }
+}
+
+/// [No paragraph style] with `root` attributes and `Body`, based on it, with `body` attributes.
+fn text_styles(root: &str, body: &str) -> String {
+ format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?>
+<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
+ <RootParagraphStyleGroup Self="rp">
+ <ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" {root}/>
+ <ParagraphStyle Self="ParagraphStyle/Body" Name="Body" {body}>
+ <Properties><BasedOn type="object">ParagraphStyle/$ID/[No paragraph style]</BasedOn></Properties>
+ </ParagraphStyle>
+ </RootParagraphStyleGroup>
+</idPkg:Styles>"#
+ )
+}
+
+fn resolve_body(root: &str, body: &str) -> Resolved {
+ let d = import_idml_with(&fixture_with_styles(&text_styles(root, body)), &|_| None).unwrap();
+ d.styles.resolve_para_style("Body")
+}
+
+/// Text attributes an IDML file leaves unset are InDesign's defaults; written ones win, and a
+/// file that writes every default (as InDesign's own exports do) imports the same.
+#[test]
+fn absent_text_attributes_take_indesign_defaults() {
+ let rows = indesign_text_defaults();
+ let all = |pick: fn(&AttrRow) -> &str| rows.iter().map(|r| format!(r#"{}="{}""#, r.0, pick(r))).collect::<Vec<_>>().join(" ");
+ let (defaults, others) = (all(|r| r.1), all(|r| r.2));
+ let omitted = resolve_body("", "");
+ let written = resolve_body(&defaults, "");
+ for (attr, _, _, field, want, _) in &rows {
+ assert_eq!(field(&omitted), *want, "{attr} omitted");
+ assert_eq!(field(&written), *want, "{attr} written as InDesign's default");
+ }
+ assert_eq!(omitted, written);
+ for (root, body) in [(others.as_str(), ""), ("", others.as_str())] {
+ let r = resolve_body(root, body);
+ for (attr, _, _, field, _, want) in &rows {
+ assert_eq!(field(&r), *want, "{attr} written on the {}", if root.is_empty() { "style" } else { "root" });
+ }
+ }
+ // Product difference: InDesign's default face isn't available, so unset fonts are DesignCraft's.
+ assert_eq!(omitted.1.font_family, designcraft_doc::CharProps::default().font_family);
+}
+
+/// A tint of -1 is the colour's own tint (100 %): written on a style, it replaces its parent's.
+/// Tints are never negative or above 100 %.
+#[test]
+fn minus_one_tint_is_the_colours_own() {
+ let tints = |v: &str| {
+ ["UnderlineTint", "StrikeThruTint", "FillTint", "StrokeTint", "ParagraphShadingTint", "ParagraphBorderTint", "RuleAboveTint", "RuleBelowTint"]
+ .map(|k| format!(r#"{k}="{v}""#))
+ .join(" ")
+ + r#" RuleAbove="true" RuleBelow="true""#
+ };
+ for (body, want) in [("-1", 1.0), ("150", 1.0)] {
+ let r = resolve_body(&tints("50"), &tints(body));
+ let got = [
+ r.1.underline_tint,
+ r.1.strikethrough_tint,
+ r.1.fill_tint,
+ r.1.stroke_tint,
+ r.0.shading_tint,
+ r.0.border_tint,
+ r.0.rule_above.tint,
+ r.0.rule_below.tint,
+ ];
+ assert_eq!(got, [want; 8], "{body}");
+ }
+ // Footnote rules, table fills and strokes, cell fills.
+ let prefs = PREFS.replace("</idPkg:Preferences>", r#"<FootnoteOption RuleTint="-1"/></idPkg:Preferences>"#);
+ let story = 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><CharacterStyleRange><Table Self="tb" StartRowFillCount="1" StartRowFillTint="-1" EndRowFillTint="-1" TopBorderStrokeTint="-1">
+<Row Self="r0" Name="0"/><Column Self="c0" Name="0"/><Cell Self="ce" Name="0:0" FillColor="Color/Black" FillTint="-1" TopEdgeStrokeTint="-1"/></Table></CharacterStyleRange></ParagraphStyleRange></Story>
+</idPkg:Story>"#;
+ let d = import_idml_with(
+ &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),
+ ]),
+ &|_| None,
+ )
+ .unwrap();
+ assert_eq!(d.footnote_options.rule.tint, 1.0);
+ let t = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();
+ let alt = t.options.alt_rows.as_ref().unwrap();
+ assert_eq!((alt.first_tint, alt.next_tint, t.options.border.tint), (1.0, 1.0, 1.0));
+ let c = t.cell(0, 0).unwrap();
+ assert_eq!((c.fill_tint, c.strokes[0].tint), (1.0, 1.0));
+}
+
+/// Rules in Text Color take the colour of the paragraph's text; they round-trip as Text Color.
+#[test]
+fn text_color_rules_round_trip() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let rule = designcraft_doc::Rule { on: true, ..Default::default() };
+ assert_eq!(rule.color, designcraft_doc::TEXT_COLOR);
+ let para = designcraft_doc::ParaAttrs {
+ rule_above: Some(rule.clone()),
+ rule_below: Some(designcraft_doc::Rule { color: "[Black]".into(), ..rule }),
+ kashidas: Some(false),
+ ..Default::default()
+ };
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "Ruled", ParaFormat::default()).unwrap();
+ d.story_mut(sid).unwrap().paras[0].para = para.clone();
+ let bytes = export_idml(&d);
+ let story = zip_text(&bytes, "Stories/");
+ assert!(story.contains(r#"<RuleAboveColor type="string">Text Color</RuleAboveColor>"#), "{story}");
+ assert!(story.contains(r#"Kashidas="KashidasOff""#), "{story}");
+ let back = import_idml(&bytes).unwrap();
+ let p = &back.stories.values().find(|s| s.text == "Ruled").unwrap().paras[0];
+ assert_eq!((p.para.rule_above.as_ref(), p.para.rule_below.as_ref()), (para.rule_above.as_ref(), para.rule_below.as_ref()));
+ assert_eq!(p.para.kashidas, Some(false));
+}
+
+/// `[Basic Paragraph]` is InDesign's `$ID/NormalParagraphStyle`, both ways.
+#[test]
+fn basic_paragraph_is_normal_paragraph_style() {
+ let d = import_idml_with(&fixture(), &|_| None).unwrap();
+ let basic = d.styles.para(st::BASIC_PARAGRAPH).unwrap();
+ assert_eq!(basic.based_on.as_deref(), Some(designcraft_doc::NO_PARA_STYLE));
+ assert_eq!(d.styles.para("Text/Body").unwrap().based_on.as_deref(), Some(st::BASIC_PARAGRAPH));
+ let s = d.stories.values().find(|s| s.text.starts_with("Hello")).unwrap();
+ assert_eq!(s.paras[1].style, st::BASIC_PARAGRAPH);
+ assert!(d.styles.paragraph.iter().all(|p| !p.name.contains("NormalParagraphStyle")));
+ let bytes = export_idml(&d);
+ let styles = zip_text(&bytes, "Resources/Styles.xml");
+ assert!(styles.contains(r#"Self="ParagraphStyle/$ID/NormalParagraphStyle" Name="$ID/NormalParagraphStyle""#), "{styles}");
+ assert!(zip_text(&bytes, "Stories/").contains(r#"AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle""#));
+ let back = import_idml(&bytes).unwrap();
+ assert_eq!(back.styles.paragraph.iter().filter(|p| p.name == st::BASIC_PARAGRAPH).count(), 1);
+}
+
+/// Page items, frames, tables and preferences an IDML file leaves unset are InDesign's defaults
+/// for a new document.
+#[test]
+fn absent_item_and_document_attributes_take_indesign_defaults() {
+ use designcraft_doc::{Cap, FirstBaseline, Join, StrokeAlign, VerticalJustification};
+ use designcraft_geom::corners::CornerShape;
+ let path = |x: f64| {
+ let pts: String = [(x, 0.0), (x, 50.0), (x + 50.0, 50.0), (x + 50.0, 0.0)]
+ .iter()
+ .map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))
+ .collect();
+ format!(
+ r#"<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties>"#
+ )
+ };
+ let designmap = format!(
+ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0" Self="d">
+<NumberingList Self="NumberingList/Steps" Name="Steps"/>
+<RootTableStyleGroup Self="rts"><TableStyle Self="TableStyle/Banded" Name="Banded" StartRowFillCount="1"/></RootTableStyleGroup>
+<Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Table Self="tb" StartRowFillCount="1" StartColumnFillCount="2"><Row Self="r0" Name="0"/><Column Self="c0" Name="0"/><Cell Self="ce" Name="0:0"/></Table></CharacterStyleRange></ParagraphStyleRange></Story>
+<Spread Self="sp1"><Page Self="p1"/>
+<Rectangle Self="plain">{}</Rectangle>
+<Rectangle Self="round" TopLeftCornerOption="RoundedCorner" TopRightCornerOption="RoundedCorner" BottomLeftCornerOption="RoundedCorner" BottomRightCornerOption="RoundedCorner">{}</Rectangle>
+<Rectangle Self="legacy" CornerOption="RoundedCorner">{}</Rectangle>
+<Rectangle Self="sized" TopLeftCornerOption="RoundedCorner" TopLeftCornerRadius="5">{}</Rectangle>
+<TextFrame Self="tf" ParentStory="s1">{}</TextFrame>
+</Spread>
+</Document>"#,
+ path(0.0),
+ path(100.0),
+ path(200.0),
+ path(300.0),
+ path(400.0)
+ );
+ let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap)]), &|_| None).unwrap();
+ // Document Setup, margins and columns, grids, Advanced Type, transparency, black.
+ let s = &d.settings;
+ assert_eq!((s.page_width, s.page_height, s.facing_pages, s.intent), (612.0, 792.0, true, designcraft_doc::Intent::Print));
+ assert_eq!((s.bleed, s.slug), ([0.0; 4], [0.0; 4]));
+ let page = &d.spreads[0].pages[0];
+ assert_eq!((page.margins.top, page.margins.bottom, page.margins.inside, page.margins.outside), (36.0, 36.0, 36.0, 36.0));
+ assert_eq!((page.columns.count, page.columns.gutter), (1, 12.0));
+ assert_eq!((s.baseline_grid.start, s.baseline_grid.increment, s.baseline_grid.view_threshold), (36.0, 12.0, 0.75));
+ assert_eq!((s.grid.horizontal, s.grid.vertical, s.grid.subdivisions, s.grid.in_back), (72.0, 72.0, 8, true));
+ let a = &s.advanced_type;
+ assert_eq!((a.superscript_size, a.superscript_position, a.subscript_size, a.subscript_position), (58.3, 33.3, 58.3, 33.3));
+ assert_eq!((s.blend_space, s.overprint_black, s.keyboard_increment), (designcraft_doc::BlendSpace::Cmyk, true, 1.0));
+ // Fill, stroke, transparency, wrap and corners of a frame with no attributes.
+ let item = |n: usize| d.spreads[0].items[n].clone();
+ let plain = item(0);
+ assert!(plain.fill.is_none() && plain.stroke.is_none());
+ let st = &plain.stroke;
+ assert_eq!((st.weight, st.miter_limit, st.cap, st.join, st.align), (1.0, 4.0, Cap::Butt, Join::Miter, StrokeAlign::Center));
+ assert_eq!((plain.opacity, plain.blend, plain.wrap.mode), (1.0, designcraft_color::BlendMode::Normal, designcraft_doc::WrapMode::None));
+ assert!(plain.corners.is_none());
+ // A corner shape without a size: 12 pt.
+ for n in [1, 2] {
+ assert_eq!(item(n).corners.corners.map(|c| (c.shape, c.size)), [(CornerShape::Rounded, 12.0); 4], "item {n}");
+ }
+ assert_eq!(item(3).corners.corners[0].size, 5.0);
+ // Text Frame Options.
+ let tf = item(4);
+ let o = &tf.text_frame().unwrap().options;
+ assert_eq!((o.columns, o.gutter, o.inset, o.balance_columns, o.ignore_wrap), (1, 12.0, [0.0; 4], false, false));
+ assert_eq!((o.vertical_justification, o.first_baseline, o.first_baseline_min), (VerticalJustification::Top, FirstBaseline::Ascent, 0.0));
+ assert_eq!((o.auto_size, o.auto_size_ref), (designcraft_doc::AutoSize::Off, 4), "auto-size from the centre");
+ // Numbered lists don't continue across stories.
+ assert_eq!(d.settings.lists, vec![designcraft_doc::NumberedList { name: "Steps".into(), continue_across_stories: false }]);
+ // Table and cell options.
+ let t = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();
+ assert_eq!((t.options.space_before, t.options.space_after, t.options.repeat_header), (4.0, -4.0, true));
+ assert_eq!((t.options.border.weight, t.options.border.color.as_str()), (1.0, "[Black]"));
+ assert_eq!((t.rows[0].mode, t.rows[0].height), (designcraft_doc::RowHeightMode::AtLeast, 3.0));
+ // Alternating fills: the first rows or columns Black 20 %, the next None.
+ let fills = |a: &designcraft_doc::AltFills| (a.first_color.clone(), a.first_tint, a.next_color.clone(), a.next_tint, a.next);
+ let want = ("[Black]".to_string(), 0.2f32, "[None]".to_string(), 1.0f32, 1);
+ assert_eq!(fills(t.options.alt_rows.as_ref().unwrap()), want);
+ let cols = t.options.alt_cols.as_ref().unwrap();
+ assert_eq!((fills(cols), cols.first), (want.clone(), 2));
+ let banded = d.styles.table.iter().find(|s| s.name == "Banded").unwrap();
+ assert_eq!(fills(banded.alt_rows.as_ref().unwrap()), want);
+ let c = t.cell(0, 0).unwrap();
+ assert_eq!((c.insets, c.vj, c.fill.as_str()), ([4.0; 4], VerticalJustification::Top, "[None]"));
+ for e in &c.strokes {
+ assert_eq!((e.weight, e.color.as_str(), e.tint, &e.kind), (1.0, "[Black]", 1.0, &designcraft_doc::StrokeType::Solid));
+ }
+}
+
+ /// InDesign: a break character ends its paragraph (`<Br/>` with a ParagraphBreakType closes the
+ /// range); the text after it is a paragraph with its own style, set on the next page of the
+ /// break's parity.
+ const ODD_PAGE_BREAK_STORY: &str = 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/Text%3aBody">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Body</Content></CharacterStyleRange>
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" ParagraphBreakType="NextOddPage"><Br/></CharacterStyleRange>
+ </ParagraphStyleRange>
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle" Justification="CenterAlign">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>1</Content></CharacterStyleRange>
+ </ParagraphStyleRange>
+ </Story>
+ </idPkg:Story>"#;
+
+ #[test]
+ fn odd_page_break_ends_its_paragraph_and_keeps_its_parity() {
+ let mut d = import_idml_with(&fixture_with_story(ODD_PAGE_BREAK_STORY), &|_| None).unwrap();
+ let sid = *d.stories.keys().next().unwrap();
+ let story = &d.stories[&sid];
+ assert_eq!(story.text, format!("Body{}\n1", st::ODD_PAGE_BREAK));
+ assert_eq!(story.paras.len(), 2);
+ assert_eq!(story.paras[0].style, "Text/Body");
+ assert_eq!(story.paras[1].style, st::BASIC_PARAGRAPH);
+ assert_eq!(story.paras[1].para.align, Some(designcraft_doc::Align::Center));
+ // Export writes the break as the paragraph's one `Br`; importing that gives the same story.
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let again = back.stories.values().next().unwrap();
+ assert_eq!(again.text, story.text);
+ assert_eq!(again.paras, story.paras);
+ // The fixture's frames are on pages v and vi: the next odd page after v has no frame.
+ let cs = designcraft_compose::compose_story(&d, sid, &Default::default());
+ assert_eq!(cs.frames[0].lines.len(), 1, "no empty line after the break");
+ assert!(cs.frames[1].lines.is_empty());
+ assert_eq!(cs.overset_at, Some(story.text.len() - 1));
+ // Numbered from 4, the second frame is on page 5: "1" starts there.
+ d.sections[0].start_number = Some(4);
+ let cs = designcraft_compose::compose_story(&d, sid, &Default::default());
+ assert_eq!(cs.overset_at, None);
+ assert_eq!(cs.frames[1].lines.iter().map(|l| l.para).collect::<Vec<_>>(), vec![1]);
+ }
+
#[test]
fn imports_hand_written_fixture() {
let d = import_idml_with(&fixture(), &|_| None).unwrap();
diff --cc crates/textimport/src/docx.rs
index 670f8a0fa,eca3a8ec1..7f1e85819
--- a/crates/textimport/src/docx.rs
+++ b/crates/textimport/src/docx.rs
@@@ -472,22 -472,21 +474,40 @@@ mod tests
assert_eq!(i.char_styles[0].chars.font_style.as_deref(), Some("Italic"));
}
+ #[test]
+ fn tracked_changes_import_as_accepted_including_moves() {
+ // Regression (#256): text in a tracked move destination (`w:moveTo`) vanished on import.
+ let document = format!(
+ r#"<w:document {W}><w:body>
+ <w:p><w:r><w:t xml:space="preserve">Kept text. </w:t></w:r>
+ <w:moveTo w:id="1" w:author="A"><w:r><w:t xml:space="preserve">MOVED HERE.</w:t></w:r>
+ <w:del w:id="5" w:author="A"><w:r><w:delText>MOVED THEN DELETED</w:delText></w:r></w:del></w:moveTo>
+ <w:r><w:t xml:space="preserve"> Plain </w:t></w:r>
+ <w:ins w:id="2" w:author="A"><w:r><w:t>INSERTED</w:t></w:r></w:ins>
+ <w:del w:id="3" w:author="A"><w:r><w:delText>DELETED</w:delText></w:r></w:del></w:p>
+ <w:p><w:moveFrom w:id="4" w:author="A"><w:r><w:t>MOVED HERE.</w:t></w:r></w:moveFrom><w:r><w:t>End.</w:t></w:r></w:p>
+ </w:body></w:document>"#
+ );
+ let i = import(&docx(&document, "", "")).unwrap();
+ i.story.check().unwrap();
+ assert_eq!(i.story.text, "Kept text. MOVED HERE. Plain INSERTED\nEnd.");
+ }
++
+ /// A page break ends its paragraph: the text after it is a paragraph of its own (same style).
+ #[test]
+ fn page_break_ends_its_paragraph() {
+ let styles = format!(r#"<w:styles {W}><w:style w:type="paragraph" w:styleId="H"><w:name w:val="Chapter"/></w:style></w:styles>"#);
+ let document = format!(
+ r#"<w:document {W}><w:body>
+ <w:p><w:r><w:t>End of one</w:t></w:r><w:r><w:br w:type="page"/></w:r></w:p>
+ <w:p><w:pPr><w:pStyle w:val="H"/></w:pPr><w:r><w:br w:type="page"/><w:t>Two</w:t><w:br w:type="column"/></w:r></w:p>
+ </w:body></w:document>"#
+ );
+ let st = import(&docx(&document, &styles, "")).unwrap().story;
+ st.check().unwrap();
+ let (pb, cb) = (designcraft_doc::PAGE_BREAK, designcraft_doc::COLUMN_BREAK);
+ assert_eq!(st.text, format!("End of one{pb}\n{pb}\nTwo{cb}\n"));
+ let styles: Vec<&str> = st.paras.iter().map(|p| p.style.as_str()).collect();
+ assert_eq!(styles, [BASIC_PARAGRAPH, "Chapter", "Chapter", "Chapter"]);
+ }
}