Skip to content

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

Merge #609: Balance Columns evens out the last frame's columns

aiongge2dd71378ef7
diff --cc ROADMAP.md
index f04e93fc9,e9c469780..dcf012b24
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -128,33 -129,8 +128,34 @@@ list) · [roadmap.md](docs/roadmap.md)
Newest first.
+- **2026-10-12** · With the Type tool, dragging a table's column or row border resizes it (the double-arrow cursor shows over a border): later columns and rows move along, Shift keeps the table size, and Shift on the right or bottom edge scales every column or row. A dragged row becomes At Least; one undo step per drag, Esc cancels; works in rotated frames and turned spreads. Scripts use `table.resizeBorder`. No readiness percentage change.
+- **2026-10-12** · The Tools panel's Fill/Stroke keys work: D (default fill and stroke), X (fill or stroke in front), Shift+X (swap per object, tints included) and / (Apply None), as `color.*` commands; swap and default are one undo step (`object.swapFillStroke`, `object.defaultFillStroke`); the Color panel follows the proxy's fill/stroke choice. No readiness percentage change.
+- **2026-10-12** · With a placed graphic selected (Direct Selection), the Transform values act on the graphic inside its frame, as in InDesign: a tilted frame's image can be straightened to 0°. No readiness percentage change.
+- **2026-10-11** · Font menu laid out like InDesign's: filters (classification, favourites,
+ recently added), families opening to their styles, the selected text as the sample in three
+ sizes, Recently Used fonts, Show Similar Fonts and each font's format.
+- **2026-10-12** · The Effects panel shows the level its settings apply to ("Group: Color Dodge 100%") and, as in InDesign, Isolate Blending and Knockout Group for a selected group. No readiness percentage change.
+- **2026-10-12** · Edit › Step and Repeat has its InDesign dialog: Repeat (Count, or Rows and Columns with Create as a grid), Offset (Vertical, Horizontal, in ruler units) and Preview, which shows the copies while the dialog is open; Cancel takes them away and OK makes them as one undo step. No readiness percentage change.
+- **2026-10-12** · Load Styles: the Paragraph Styles and Character Styles panels load styles from another DesignCraft document or an IDML file, with the styles, swatches and lists they name; a dialog picks the styles and what happens to one the document defines differently (`style.load`). No readiness percentage change.
+- **2026-10-12** · On screen, blend modes blend with the objects below and not with the paper, as in InDesign and in PDF export: a Color Dodge or Screen object over blank paper shows as it is. No readiness percentage change.
+- **2026-10-12** · Text threads by hand: click a selected text frame's in or out port to load
+ the text cursor, then click a frame to thread it, click empty space for a column-wide frame or
+ drag one (it snaps like frame drawing); Shift-click autoflows, Alt-click stays loaded on the
+ frame just added; click the linked frame or double-click a port to break the thread.
+ `text.thread`, `text.unthread`, `text.removeFromThread` with undo; locked frames and layers
+ refuse threads. The alpha gate now waits only on the Primary Text Frame page fixes (#165). No
+ readiness percentage change.
+- **2026-10-12** · Properties › Transform shows rotation, shear and X/Y scale, and Rotate 90° and Flip Horizontal/Vertical buttons, as InDesign's does. No readiness percentage change.
+- **2026-10-12** · Underlines and strikethroughs are drawn as one bar per stretch of text on screen, as in PDF export: a bar per letter left faint seams between the letters. No readiness percentage change.
+- **2026-10-12** · The section marker character shows its section's marker text on document pages (nothing when the section has none) instead of the word "Section", which stays on parent pages; editing the marker recomposes (#556). No readiness percentage change.
+- **2026-10-12** · IDML import keeps a font family name exactly as written, trailing spaces included, and font lookup falls back to the name without surrounding spaces; `FontStyle="Nothing"` leaves the style to the paragraph (#558). No readiness percentage change.
+- **2026-10-12** · Clipping paths saved with images in IDML (Detect Edges, Alpha Channel, Photoshop Path, User-Modified Path, inverted or not) clip the image on screen and in PDF and survive IDML export; `object.clippingPathOptions` reports, inverts or removes one (#450). No readiness percentage change.
+- **2026-10-12** · Anchored objects with text wrap push text aside: other stories' text under them and the lines of their own story after the anchor's line (#557). No readiness percentage change.
+- **2026-10-12** · Hyphenation Zone applies to the Single-line Composer only, as in InDesign. With the default Paragraph Composer, ragged text hyphenates where InDesign does (aper-natem), giving the same line breaks. No readiness percentage change.
+- **2026-10-12** · Text frame auto-size: Height Only, Width Only, Height and Width (also keeping proportions) frames grow and shrink to fit their text after edits and IDML import, around their reference point, with minimum sizes and No Line Breaks, in the same undo step (#180). No readiness percentage change.
+ - **2026-10-12** · Text Frame Options › Balance Columns (`object.textFrameOptions {balanceColumns}`, IDML `VerticalBalanceColumns`) evens out the columns of the frame a story ends in, from its last column break on; frames the text runs on from fill normally (#609). No readiness percentage change.
- **2026-10-12** · Orderly native exit writes the latest recovery state after finalizing current quit approvals; incomplete or stale plans keep their documents, and Undo to the saved state clears stale recovery. Unavailable or failed recovery is reported. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.
+- **2026-10-12** · Windows: dragging the window across monitors with different display scales keeps its size instead of growing until it crashes (winit pinned to its 0.30.x backport of the fix). The GPU surface may be as large as the adapter's largest texture (16384 px on DirectX 12, Vulkan and Metal hardware) instead of 8192, and a wgpu error is logged instead of closing the app. No readiness percentage change.
- **2026-10-12** · Recovered documents keep a checkpoint until saved, closed or reverted, including a second crash before autosave. Restarted document IDs and explicit recovery folders preserve other snapshots; failed republishing retains the original. No readiness percentage change.
- **2026-10-12** · Book numbering and style updates prepare every chapter before saving. Only closed native chapters are changed; imported IDML remains a read-only style/PDF source. If a later disk write fails, the error names the completed chapters; the batch is not a whole-book transaction. No readiness percentage change.
- **2026-10-12** · Desktop write callbacks and CLI raster exports use the atomic writer too; open readers retain the original bytes, while private Unix modes and symlink targets survive replacement. Permanent tests cover both actual callers. No readiness percentage change.
diff --cc crates/compose/src/lib.rs
index 49a9a05f3,14df05cb7..fa401aa65
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@@ -866,40 -567,28 +868,53 @@@ fn compose_with_db(doc: &Document, stor
pi = j;
continue 'paras;
}
+ if pi >= np {
+ // The story ends here: Balance Columns evens out the columns of its last frame.
+ if balance_frames > 0
+ && let Some(j) = balance_end(&mut trial, &mut limits, &cur, &cols, frames, &out, np, 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;
+ }
+ break 'paras;
+ }
+ if deleted.get(pi).copied().unwrap_or(false) {
+ // A deleted paragraph takes no room; for keeps it stands in for the one before it.
+ let filler = info.last().map_or(
+ ParaInfo {
+ start: (cur.fi, cur.col),
+ at_top: cur.last_baseline.is_none(),
+ end: (cur.fi, cur.col),
+ lines: 0,
+ lines_in_end_col: 0,
+ keep_with_next: 0,
+ keep_together: false,
+ keep_all: false,
+ keep_first: 1,
+ keep_last: 1,
+ },
+ |p| ParaInfo { lines_in_end_col: 0, ..p.clone() },
+ );
+ info.push(filler);
+ pi += 1;
+ continue;
+ }
+ let prange = para_ranges[pi].clone();
let pf = &story.paras[pi];
- let (pp, base_chars) = doc.styles.resolve_para(pf);
+ let (mut 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);
+ // Deleted paragraphs in between don't count, nor does a deleted or hidden break.
+ let after_break = (0..pi).rev().find(|p| !deleted.get(*p).copied().unwrap_or(false)).and_then(|p| {
+ let r = para_ranges.get(p)?;
+ let (i, c) = story.text.get(r.clone())?.char_indices().next_back()?;
+ let start = break_start(c)?;
+ let (_, chars) = doc.styles.resolve_para(story.paras.get(p)?);
+ let props = doc.styles.resolve_char(&chars, story.char_format_at(r.start + i + c.len_utf8()));
+ let gone = props.change == designcraft_doc::ChangeMark::Deleted || doc.conditions_hide(&props.conditions);
+ (!gone).then_some(start)
+ });
if let Some(t) = story.para_table(pi) {
if cur.last_baseline.is_some() {
cur.start(after_break.unwrap_or(pp.start_paragraph), &cols, frames, doc);
@@@ -1212,9 -806,15 +1227,15 @@@
};
// A paragraph start or a break character; Next Column while a paragraph spans columns is
// the next frame, as above.
- let go = |cur: &mut Cursor, start| match start {
- StartParagraph::NextColumn => next_column(cur),
- start => cur.start(start, &cols, frames, doc),
- let begin_at = |cur: &mut Cursor, start: StartParagraph| match start {
++ let go = |cur: &mut Cursor, start: StartParagraph| match start {
+ StartParagraph::NextColumn => {
+ let (fi, col) = (cur.fi, cur.col);
+ next_column(cur);
+ if cur.fi == fi && cur.col != col {
+ cur.band.tail = Some((cur.pi, cur.col));
+ }
+ }
+ other => cur.start(other, &cols, frames, doc),
};
// Paragraph start options.
if let Some(start) = after_break
@@@ -1758,10 -1151,9 +1779,10 @@@
baseline: l.baseline,
descent: l.descent,
reference: cur.last_reference,
- pending: pp.space_after,
+ aki_below: cur.aki_below,
+ pending: if spans_in(cur.fi) { pp.space_after.max(pp.span_space_after) } else { pp.space_after },
};
- cur.band = Band { para: pi + 1, line0: ft.lines.len(), above: Some(above) };
+ cur.band = Band { para: pi + 1, line0: ft.lines.len(), above: Some(above), tail: None };
}
// Rules and shading for the paragraph.
if let Some((fi, bl, asc, _)) = first_line_rect {
@@@ -2636,66 -2068,22 +2708,69 @@@ impl Cursor
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.
++ /// The current column of the frame (`col`) limited to the band: below the spanning paragraph
++ /// above it and, while balancing, above the trial bottom (Balance Columns limits only the
++ /// columns after the band's last column break).
+ 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));
++ let tail = self.band.tail.filter(|&(_, c)| self.col >= c).map(|(p, _)| (self.fi, p));
++ let limit = limit_of(&self.limits, self.band_key()).or_else(|| tail.and_then(|k| limit_of(&self.limits, k)));
++ let y1 = limit.filter(|b| !b.is_nan()).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 | FirstBaseline::EmboxHeight 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::EmboxHeight => tops.em,
+ FirstBaseline::Leading => lead,
+ FirstBaseline::Fixed => 0.0,
+ };
+ off.max(f.opts.first_baseline_min)
+}
+
+/// A line's tallest typographic ascender, cap height, x height and em box top above its baseline:
+/// the first baseline offsets.
+#[derive(Clone, Copy, Default)]
+struct Tops {
+ typo_ascent: f64,
+ cap: f64,
+ xh: f64,
+ em: f64,
+}
+
+/// The em box top above the baseline at `size` ([`designcraft_fonts::FontFace::em_box`]).
+fn em_box_top(face: &designcraft_fonts::FontFace, size: f64) -> f64 {
+ let em = Some(face.em_box().0 / face.upem).filter(|e| e.is_finite()).unwrap_or(0.88);
+ em * size
}
/// Em box relative to the baseline. Font ascender/descender proportions locate it;
diff --cc crates/compose/src/tests.rs
index d32c9a767,f1e13db19..5ff1747ae
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@@ -5785,793 -2789,113 +5785,904 @@@ 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(&centred[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 (top to baseline) 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 > 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:?}");
+}
++
+ // ---------- balance columns ----------
+
+ /// A story of `paras` body paragraphs in one frame of `columns` columns, Balance Columns `on`.
+ fn balance_doc(paras: usize, columns: u32, rect: Rect, on: bool) -> (Document, StoryId, ItemId) {
+ let (mut d, sid, fid) = doc_with(&vec![LOREM; paras].join("\n"), rect, ParaAttrs::default());
+ let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options;
+ o.columns = columns;
+ o.balance_columns = on;
+ (d, sid, fid)
+ }
+
+ fn column_line_counts(ft: &FrameText) -> Vec<usize> {
+ (0..ft.columns.len() as u32).map(|c| ft.lines.iter().filter(|l| l.column == c).count()).collect()
+ }
+
+ /// The baseline of each column's last line.
+ fn column_ends(ft: &FrameText) -> Vec<f64> {
+ (0..ft.columns.len() as u32).map(|c| ft.lines.iter().filter(|l| l.column == c).map(|l| l.baseline).fold(f64::NEG_INFINITY, f64::max)).collect()
+ }
+
+ #[test]
+ fn balance_columns_evens_out_the_columns_the_story_ends_in() {
+ let rect = Rect::new(0.0, 0.0, 400.0, 300.0);
+ let (d, sid, _) = balance_doc(3, 2, rect, false);
+ let off = compose_story(&d, sid, &ComposeOptions::default());
+ let counts = column_line_counts(&off.frames[0]);
+ assert!(counts[1] > 0 && counts[0] > counts[1] + 2, "fills the first column: {counts:?}");
+
+ let (d, sid, _) = balance_doc(3, 2, rect, true);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset());
+ let ft = &cs.frames[0];
+ assert_no_overlap(ft);
+ let on = column_line_counts(ft);
+ assert_eq!(on.iter().sum::<usize>(), counts.iter().sum::<usize>(), "the same lines");
+ assert!(on[0] >= on[1] && on[0] - on[1] <= 1, "{on:?}");
+ let ends = column_ends(ft);
+ assert!((ends[0] - ends[1]).abs() <= 14.4 + 1e-6, "{ends:?}");
+ assert_eq!(all_lines(&cs).last().unwrap().range.end, d.story(sid).unwrap().text.len());
+
+ // A paragraph kept together stays in one column while the columns still balance.
+ let (mut d, sid, _) = balance_doc(3, 2, rect, true);
+ let p = &mut d.story_mut(sid).unwrap().paras[1].para;
+ p.keep_lines_together = Some(true);
+ p.keep_all_lines = Some(true);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset());
+ let kept: Vec<u32> = cs.frames[0].lines.iter().filter(|l| l.para == 1).map(|l| l.column).collect();
+ assert!(kept.iter().all(|&c| c == kept[0]), "{kept:?}");
+ let c = column_line_counts(&cs.frames[0]);
+ assert!(c[1] > 0 && c[0].max(c[1]) < counts[0], "{c:?} vs {counts:?}");
+
+ // Three columns: the first two are equal, the last at most two lines shorter.
+ let (d, sid, _) = balance_doc(3, 3, Rect::new(0.0, 0.0, 540.0, 500.0), true);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset());
+ let c = column_line_counts(&cs.frames[0]);
+ let total: usize = c.iter().sum();
+ assert_eq!(c[0], total.div_ceil(3), "{c:?}");
+ assert!(c[1] <= c[0] && c[2] <= c[1] && c[0] - c[2] <= 2 && c[2] > 0, "{c:?}");
+ assert_no_overlap(&cs.frames[0]);
+
+ // Vertical stories balance their columns too (bands across the turned frame).
+ let (mut d, sid, _) = balance_doc(2, 2, Rect::new(0.0, 0.0, 400.0, 400.0), true);
+ d.story_mut(sid).unwrap().vertical = true;
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset());
+ let c = column_line_counts(&cs.frames[0]);
+ assert!(c[1] > 0 && c[0].abs_diff(c[1]) <= 1, "{c:?}");
+ }
+
+ #[test]
+ fn balance_columns_leaves_a_frame_the_text_runs_on_from() {
+ let rect = Rect::new(0.0, 0.0, 400.0, 150.0);
+ let layout = |on: bool| {
+ let (mut d, sid, f1) = balance_doc(4, 2, rect, on);
+ let lid = d.default_layer();
+ let (f2, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 300.0, 400.0, 700.0), lid, "", ParaFormat::default()).unwrap();
+ let o = &mut d.item_mut(f2).unwrap().text_frame_mut().unwrap().options;
+ o.columns = 2;
+ o.balance_columns = on;
+ d.thread(f1, f2).unwrap();
+ compose_story(&d, sid, &ComposeOptions::default())
+ };
+ let (off, on) = (layout(false), layout(true));
+ assert!(!on.is_overset());
+ let first = |cs: &ComposedStory| cs.frames[0].lines.iter().map(|l| (l.column, l.baseline, l.range.clone())).collect::<Vec<_>>();
+ assert_eq!(first(&on), first(&off), "the first frame fills normally");
+ let c = column_line_counts(&on.frames[1]);
+ assert!(c[1] > 0 && c[0] - c[1] <= 1, "the frame the story ends in is balanced: {c:?}");
+ }
+
+ #[test]
+ fn balance_columns_starts_after_a_column_break() {
+ // The first paragraph ends with a column break: the first column holds it alone and the
+ // other two share the rest.
+ let text = format!("{LOREM}{}\n{}", designcraft_doc::story::COLUMN_BREAK, [LOREM; 3].join("\n"));
+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 540.0, 500.0), ParaAttrs::default());
+ let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options;
+ o.columns = 3;
+ o.balance_columns = true;
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset());
+ let ft = &cs.frames[0];
+ assert_no_overlap(ft);
+ assert!(ft.lines.iter().filter(|l| l.column == 0).all(|l| l.para == 0));
+ assert!(ft.lines.iter().filter(|l| l.para == 0).all(|l| l.column == 0));
+ let c = column_line_counts(ft);
+ assert!(c[2] > 0 && c[1] >= c[2] && c[1] - c[2] <= 1, "{c:?}");
+ }
diff --cc crates/idml/src/tests.rs
index 404def0f5,555a4ae8d..592ce6764
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@@ -2589,787 -1455,42 +2589,827 @@@ fn list_numbering_format_expression_and
check(&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));
+}
+
+/// SameParaStyleSpacing set as a `Properties` element on the based-on style (`Normal`) reaches
+/// the headings: consecutive headings sit one leading apart. SetIgnore keeps the usual spacing.
+#[test]
+fn same_para_style_spacing_from_a_based_on_style_element_closes_the_gap() {
+ let styles = r#"<?xml version="1.0" encoding="UTF-8"?>
+<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
+ <RootCharacterStyleGroup Self="rc">
+ <CharacterStyle Self="CharacterStyle/$ID/[No character style]" Name="$ID/[No character style]"/>
+ </RootCharacterStyleGroup>
+ <RootParagraphStyleGroup Self="rp">
+ <ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" PointSize="12">
+ <Properties><AppliedFont type="string">Source Serif 4</AppliedFont><Leading type="unit">13</Leading></Properties>
+ </ParagraphStyle>
+ <ParagraphStyle Self="ParagraphStyle/$ID/NormalParagraphStyle" Name="$ID/NormalParagraphStyle">
+ <Properties><BasedOn type="string">$ID/[No paragraph style]</BasedOn><SameParaStyleSpacing type="unit">0</SameParaStyleSpacing></Properties>
+ </ParagraphStyle>
+ <ParagraphStyle Self="ParagraphStyle/Heading" Name="Heading" SpaceBefore="18" SpaceAfter="4.5">
+ <Properties><BasedOn type="object">ParagraphStyle/$ID/NormalParagraphStyle</BasedOn></Properties>
+ </ParagraphStyle>
+ <ParagraphStyle Self="ParagraphStyle/Loose" Name="Loose" SpaceBefore="18" SpaceAfter="4.5">
+ <Properties><BasedOn type="object">ParagraphStyle/$ID/NormalParagraphStyle</BasedOn><SameParaStyleSpacing type="enumeration">SetIgnore</SameParaStyleSpacing></Properties>
+ </ParagraphStyle>
+ </RootParagraphStyleGroup>
+</idPkg:Styles>"#;
+ let para = |style: &str, text: &str| {
+ format!(
+ r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/{style}"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>{text}</Content><Br/></CharacterStyleRange></ParagraphStyleRange>"#
+ )
+ };
+ let story = format!(
+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">{}{}{}{}</Story></idPkg:Story>"#,
+ para("Heading", "One"),
+ para("Heading", "Two"),
+ para("Loose", "Three"),
+ para("Loose", "Four")
+ );
+ let d = import_idml(&fixture_with_table_styles(styles, &story)).unwrap();
+ let sid = d.stories.iter().find(|(_, s)| s.text.contains("One")).map(|(id, _)| *id).unwrap();
+ let cs = designcraft_compose::compose_story(&d, sid, &Default::default());
+ let baseline = |para: usize| cs.frames[0].lines.iter().find(|l| l.para == para).unwrap().baseline;
+ assert!((baseline(1) - baseline(0) - 13.0).abs() < 1e-6, "{} {}", baseline(0), baseline(1));
+ assert!((baseline(3) - baseline(2) - 13.0 - 4.5 - 18.0).abs() < 1e-6, "{} {}", baseline(2), baseline(3));
+}
+
+/// Composed lines (baseline, left, right) of the only story.
+fn story_lines(d: &Document) -> Vec<(f64, f64, f64)> {
+ 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()
+}
+
+const PSR: &str = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle">"#;
+
+/// Lays out like the same story without the deleted paragraph.
+fn assert_deleted_para_takes_no_room(deleted: &str, deleted_text: &str) {
+ let tracked = tracked_story(&format!(
+ r#"{PSR}{CSR}<Content>First live paragraph.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>
+{deleted}
+{PSR}{CSR}<Content>Second live paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#
+ ));
+ let plain = tracked_story(&format!(
+ r#"{PSR}{CSR}<Content>First live paragraph.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>
+{PSR}{CSR}<Content>Second live paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#
+ ));
+ let d = import_idml_with(&fixture_with_story(&tracked), &|_| None).unwrap();
+ let story = d.stories.values().next().unwrap();
+ let marks: Vec<_> = story.runs().map(|(r, f)| (story.text[r].to_string(), f.over.change)).collect();
+ let want = vec![
+ ("First live paragraph.\n".to_string(), None),
+ (deleted_text.to_string(), Some(designcraft_doc::ChangeMark::Deleted)),
+ ("Second live paragraph.".to_string(), None),
+ ];
+ assert_eq!(marks, want);
+ let expected = story_lines(&import_idml_with(&fixture_with_story(&plain), &|_| None).unwrap());
+ assert_eq!(expected.len(), 2);
+ assert_eq!(story_lines(&d), expected);
+}
+
+#[test]
+fn tracked_deleted_paragraph_range_stays_deleted() {
+ assert_deleted_para_takes_no_room(
+ &format!(
+ r#"<Change Self="c1" ChangeType="DeletedText">{PSR}{CSR}<Content>Deleted text</Content><Br/></CharacterStyleRange></ParagraphStyleRange></Change>"#
+ ),
+ "Deleted text\n",
+ );
+}
+
+#[test]
+fn tracked_deleted_frame_break_does_not_break() {
+ let fb = "\u{E003}";
+ let nf = r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" ParagraphBreakType="NextFrame">"#;
+ // The change around the paragraph range.
+ assert_deleted_para_takes_no_room(
+ &format!(
+ r#"<Change Self="c1" ChangeType="DeletedText">{PSR}{CSR}<Content>Gone</Content></CharacterStyleRange>{nf}<Br/></CharacterStyleRange></ParagraphStyleRange></Change>"#
+ ),
+ &format!("Gone{fb}\n"),
+ );
+ // The change inside the character range.
+ assert_deleted_para_takes_no_room(
+ &format!(
+ r#"{PSR}{nf}<Change Self="c1" ChangeType="DeletedText"><Content>Gone</Content><Br/></Change></CharacterStyleRange></ParagraphStyleRange>"#
+ ),
+ &format!("Gone{fb}\n"),
+ );
+}
+
+#[test]
+fn live_frame_break_before_deleted_paragraph_still_breaks() {
+ let nf = r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" ParagraphBreakType="NextFrame">"#;
+ let first =
+ format!(r#"{PSR}{CSR}<Content>First live paragraph.</Content></CharacterStyleRange>{nf}<Br/></CharacterStyleRange></ParagraphStyleRange>"#);
+ let second = format!(r#"{PSR}{CSR}<Content>Second live paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#);
+ let deleted = format!(
+ r#"<Change Self="c1" ChangeType="DeletedText">{PSR}{CSR}<Content>Gone</Content><Br/></CharacterStyleRange></ParagraphStyleRange></Change>"#
+ );
+ let import = |body: String| import_idml_with(&fixture_with_story(&tracked_story(&body)), &|_| None).unwrap();
+ let reference = import(format!("{first}\n{second}"));
+ let sid = *reference.stories.keys().next().unwrap();
+ let per_frame: Vec<usize> =
+ designcraft_compose::compose_story(&reference, sid, &Default::default()).frames.iter().map(|f| f.lines.len()).collect();
+ assert!(per_frame.first() == Some(&1) && per_frame.get(1).is_some_and(|n| *n > 0), "the break sends the second paragraph on");
+ let expected = story_lines(&reference);
+ assert_eq!(story_lines(&import(format!("{first}\n{deleted}\n{second}"))), expected);
+}
++
+ #[test]
+ fn vertical_balance_columns_balances_the_imported_frame() {
+ let text = "Balanced columns end at about the same depth when the story ends in the frame. ".repeat(4);
+ let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">
+ <idPkg:Spread src="Spreads/Spread_s.xml"/>
+ <idPkg:Story src="Stories/Story_s1.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 400 400" ItemTransform="1 0 0 1 0 0"/>
+ <TextFrame Self="f" ParentStory="s1">
+ <Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>
+ <PathPointType Anchor="0 0"/><PathPointType Anchor="0 150"/>
+ <PathPointType Anchor="300 150"/><PathPointType Anchor="300 0"/>
+ </PathPointArray></GeometryPathType></PathGeometry></Properties>
+ <TextFramePreference TextColumnCount="2" TextColumnGutter="12" VerticalBalanceColumns="true"/>
+ </TextFrame>
+ </Spread>
+ </idPkg:Spread>"#;
+ let story = format!(
+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange><CharacterStyleRange><Content>{text}</Content></CharacterStyleRange></ParagraphStyleRange>
+ </Story></idPkg:Story>"#
+ );
+ let mut d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", spread), ("Stories/Story_s1.xml", &story)])).unwrap();
+ let sid = *d.stories.keys().next().unwrap();
+ let per_column = |d: &Document| {
+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());
+ assert!(!cs.is_overset());
+ let ft = &cs.frames[0];
+ [0, 1].map(|c| ft.lines.iter().filter(|l| l.column == c).count())
+ };
+ let on = per_column(&d);
+ assert!(on[1] > 0 && on[0] - on[1] <= 1, "balanced: {on:?}");
+ let fid = d.stories[&sid].frames[0];
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.balance_columns = false;
+ let off = per_column(&d);
+ assert!(off[0] > off[1] + 1, "unbalanced: {off:?}");
+ }
diff --cc crates/ui-egui/src/dialogs.rs
index e9e0710f4,ada71b19d..d83fe567b
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@@ -4590,1656 -3562,191 +4594,1659 @@@ fn open_type_features(lang: &str, ui: &
}
}
-/// New Cross-Reference: link to a paragraph (paragraph styles on the left, their paragraphs on
-/// the right) or a text anchor, with a cross-reference format.
-fn insert_xref(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
- let Some(st) = app.session.active() else { return };
- let doc = &st.doc;
- let all = "[All Paragraphs]";
- ui.horizontal(|ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Link To:"));
- combo(ui, d, "linkTo", &[("paragraph", "Paragraph"), ("anchor", "Text Anchor")]);
- });
- ui.add_space(6.0);
- let dim = crate::theme::Tokens::get(ui.ctx()).text_dim;
- if d.s("linkTo") == "anchor" {
- egui::ScrollArea::vertical().id_salt("xr_anchors").max_height(220.0).max_width(460.0).show(ui, |ui| {
- let mut any = false;
- for st in doc.stories.values() {
- for a in &st.anchors {
- any = true;
- let key = format!("a:{}", a.id);
- if ui.selectable_label(d.s("target") == key, &a.name).clicked() {
- d.fields.insert("target".into(), json!(key));
+/// Underline Options / Strikethrough Options (`key` is `underline` or `strikethrough`).
+fn line_options(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, doc: &designcraft_doc::Document, key: &str) {
+ char_check(ui, d, cf, key, crate::i18n::tr(lang, if key == "underline" { "Underline On" } else { "Strikethrough On" }));
+ ui.add_space(4.0);
+ egui::Grid::new(("csline", key)).num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Weight:"));
+ char_number(ui, d, cf, &format!("{key}Weight"), " pt", 1.0, (0.0, 800.0));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Offset:"));
+ char_number(ui, d, cf, &format!("{key}Offset"), " pt", 1.0, (-800.0, 800.0));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Color:"));
+ char_swatch(lang, ui, d, cf, doc, &format!("{key}Color"), Some("(Text Color)"));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Tint:"));
+ char_number(ui, d, cf, &format!("{key}Tint"), "%", 100.0, (0.0, 100.0));
+ ui.end_row();
+ });
+}
+
+fn delete_character_style(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
+ let name = d.s("name");
+ ui.set_min_width(380.0);
+ crate::rtl::label(
+ ui,
+ egui::RichText::new(
+ crate::i18n::tr(&app.ui.language, "Delete the character style \"{name}\"?")
+ .replace("{name}", crate::i18n::style_name(&app.ui.language, &name)),
+ )
+ .size(12.5),
+ );
+ ui.add_space(8.0);
+ let Some(st) = app.session.active() else { return };
+ let in_use = st.doc.stories.values().any(|s| s.chars.iter().any(|r| r.format.style == name));
+ let names: Vec<String> = st.doc.styles.character.iter().map(|c| c.name.clone()).filter(|n| *n != name).collect();
+ if in_use {
+ crate::rtl::label(
+ ui,
+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "This style is in use. Text using it will be reassigned to:"))
+ .size(11.0)
+ .color(crate::theme::Tokens::get(ui.ctx()).text_dim),
+ );
+ } else {
+ crate::rtl::label(
+ ui,
+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "Replace with:")).size(11.0).color(crate::theme::Tokens::get(ui.ctx()).text_dim),
+ );
+ }
+ ui.add_space(4.0);
+ if !d.fields.contains_key("replaceWith") {
+ d.fields.insert("replaceWith".into(), json!(designcraft_doc::NO_CHAR_STYLE));
+ }
+ let replace = d.s("replaceWith");
+ egui::ComboBox::from_id_salt("del_char_replace")
+ .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, &replace)))
+ .width(260.0)
+ .show_ui(ui, |ui| {
+ for n in [designcraft_doc::NO_CHAR_STYLE].into_iter().chain(names.iter().map(String::as_str)) {
+ if ui.selectable_label(n == replace, crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, n))).clicked() {
+ d.fields.insert("replaceWith".into(), json!(n));
+ }
+ }
+ });
+}
+
+fn combo(ui: &mut egui::Ui, d: &mut Dialog, key: &str, opts: &[(&str, &str)]) {
+ let cur = d.s(key);
+ let shown = opts.iter().find(|o| o.0 == cur).map_or(cur.as_str(), |o| o.1).to_string();
+ egui::ComboBox::from_id_salt(key).selected_text(crate::rtl::widget(ui, &shown)).width(170.0).show_ui(ui, |ui| {
+ for (v, label) in opts {
+ if ui.selectable_label(cur == *v, crate::rtl::widget(ui, *label)).clicked() {
+ d.fields.insert(key.into(), json!(v));
+ }
+ }
+ });
+}
+
+/// Translate enum captions without changing serialized values or user-defined names.
+fn translated_combo(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, key: &str, opts: &[(&str, &str)]) {
+ let opts: Vec<_> = opts.iter().map(|(value, label)| (*value, crate::i18n::tr(lang, label))).collect();
+ combo(ui, d, key, &opts);
+}
+
+/// Style name picker (paragraph or character styles of the active document).
+fn style_combo(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, key: &str, character: bool) {
+ let names: Vec<String> = app
+ .session
+ .active()
+ .map(|st| {
+ if character {
+ st.doc.styles.character.iter().map(|s| s.name.clone()).collect()
+ } else {
+ st.doc.styles.paragraph.iter().map(|s| s.name.clone()).collect()
+ }
+ })
+ .unwrap_or_default();
+ let mut opts: Vec<(&str, &str)> = names.iter().map(|n| (n.as_str(), crate::i18n::style_name(&app.ui.language, n))).collect();
+ if character && !names.iter().any(|n| n == designcraft_doc::NO_CHAR_STYLE) {
+ opts.insert(0, (designcraft_doc::NO_CHAR_STYLE, crate::i18n::style_name(&app.ui.language, designcraft_doc::NO_CHAR_STYLE)));
+ }
+ combo(ui, d, key, &opts);
+}
+
+const RULES: [(&str, &str); 2] = [("ruleAbove", "Rule Above"), ("ruleBelow", "Rule Below")];
+
+/// A rule as the dialog shows it: `current[which]` (the resolved rule, inherited values included)
+/// with the fields edited in the dialog (`{prefix}{which}.{field}`) on top.
+fn shown_rule(d: &Dialog, prefix: &str, which: &str, current: &Value) -> Value {
+ let mut r = match current.get(which) {
+ Some(Value::Object(m)) => m.clone(),
+ _ => Map::new(),
+ };
+ let edited = format!("{prefix}{which}.");
+ for (k, v) in &d.fields {
+ if let Some(field) = k.strip_prefix(&edited) {
+ r.insert(field.into(), v.clone());
+ }
+ }
+ Value::Object(r)
+}
+
+/// The paragraph attributes of the Justification controls.
+pub const JUSTIFY_ATTRS: [&str; 12] = [
+ "wordSpaceMin",
+ "wordSpaceDesired",
+ "wordSpaceMax",
+ "letterSpaceMin",
+ "letterSpaceDesired",
+ "letterSpaceMax",
+ "glyphScaleMin",
+ "glyphScaleDesired",
+ "glyphScaleMax",
+ "composer",
+ "kashidas",
+ "koreanCharBreaks",
+];
+
+/// The spacing rows of the Justification controls: (label, attribute stem, allowed percent range).
+const JUSTIFY_ROWS: [(&str, &str, (f64, f64)); 3] = [
+ ("Word Spacing", "wordSpace", (0.0, 1000.0)),
+ ("Letter Spacing", "letterSpace", (-100.0, 500.0)),
+ ("Glyph Scaling", "glyphScale", (50.0, 200.0)),
+];
+
+/// Checks the edited spacing values: each within its range, and minimum ≤ desired ≤ maximum
+/// (values left mixed are not compared).
+fn check_justification(d: &Dialog, prefix: &str, current: &Value) -> Result<(), String> {
+ for (label, stem, (lo, hi)) in JUSTIFY_ROWS {
+ let mut edited = false;
+ let mut known = Vec::new();
+ for suffix in ["Min", "Desired", "Max"] {
+ let key = format!("{stem}{suffix}");
+ let v = match d.fields.get(&format!("{prefix}{key}")) {
+ Some(v) => {
+ edited = true;
+ let pct =
+ v.as_f64().map(|x| x * 100.0).filter(|x| x.is_finite()).ok_or_else(|| format!("Justification: {label} is not a number"))?;
+ // The fields show whole percents; compare what was shown.
+ if pct.round() < lo || pct.round() > hi {
+ return Err(format!("Justification: {label} must be between {lo}% and {hi}%"));
}
+ Some(pct)
+ }
+ None => current[key.as_str()].as_f64().map(|x| x * 100.0),
+ };
+ known.extend(v);
+ }
+ if edited && known.windows(2).any(|w| w[0] > w[1] + 1e-9) {
+ return Err(format!("Justification: {label} needs Minimum ≤ Desired ≤ Maximum"));
+ }
+ }
+ Ok(())
+}
+
+/// The Justification controls (the Justification dialog, and the Paragraph Style Options section).
+/// `current` holds the resolved paragraph attributes, `null` where the selected paragraphs differ
+/// (the field shows empty); each edit is stored as `{prefix}{attr}`, so OK changes only the fields
+/// edited.
+fn justification(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, current: &Value) {
+ let cur = |d: &Dialog, k: &str| d.fields.get(&format!("{prefix}{k}")).cloned().unwrap_or_else(|| current[k].clone());
+ egui::Grid::new("psj").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
+ ui.label("");
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Minimum"));
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Desired"));
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Maximum"));
+ ui.end_row();
+ for (label, base, _) in JUSTIFY_ROWS {
+ crate::rtl::label(ui, crate::i18n::tr(lang, &format!("{label}:")));
+ for suffix in ["Min", "Desired", "Max"] {
+ let key = format!("{base}{suffix}");
+ let v = cur(d, &key).as_f64().map(|x| x * 100.0);
+ if let Some(n) = ui.scope(|ui| crate::widgets::number(ui, &format!("ps{key}"), v, "%", 60.0, 0)).inner {
+ d.fields.insert(format!("{prefix}{key}"), json!(n / 100.0));
}
}
- if !any {
- ui.label(crate::rtl::widget(
- ui,
- egui::RichText::new(crate::i18n::tr(&app.ui.language, "No text anchors in this document.")).color(dim),
- ));
+ ui.end_row();
+ }
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Composer:"));
+ let composer = cur(d, "composer");
+ // Mixed (null) selects neither; a Japanese composer keeps its kind.
+ let (single, [paragraph, single_line]) = crate::panels::properties::composer_choice(composer.as_str());
+ let known = !composer.is_null();
+ if ui.selectable_label(known && !single, crate::rtl::widget(ui, crate::i18n::tr(lang, "Paragraph Composer"))).clicked() {
+ d.fields.insert(format!("{prefix}composer"), json!(paragraph));
+ }
+ if ui.selectable_label(known && single, crate::rtl::widget(ui, crate::i18n::tr(lang, "Single-line Composer"))).clicked() {
+ d.fields.insert(format!("{prefix}composer"), json!(single_line));
+ }
+ ui.end_row();
+ for (label, key, text, default) in [
+ ("Insert Kashidas:", "kashidas", "In justified Arabic text", true),
+ ("Korean Line Breaks:", "koreanCharBreaks", "Between syllables (not only at spaces)", false),
+ ] {
+ crate::rtl::label(ui, crate::i18n::tr(lang, label));
+ let v = cur(d, key);
+ let mut on = v.as_bool().unwrap_or(default);
+ if ui.add(egui::Checkbox::new(&mut on, crate::rtl::widget(ui, crate::i18n::tr(lang, text))).indeterminate(v.is_null())).changed() {
+ d.fields.insert(format!("{prefix}{key}"), json!(on));
}
- });
- } else {
- let mut styles: Vec<String> = vec![all.to_string()];
- styles.extend(doc.styles.paragraph.iter().map(|s| s.name.clone()));
- let cur_style = if d.s("style").is_empty() { all.to_string() } else { d.s("style") };
- ui.horizontal_top(|ui| {
- let col = |w: f32| (egui::vec2(w, 240.0), egui::Layout::top_down(egui::Align::Min));
- let (sz, lay) = col(180.0);
- ui.allocate_ui_with_layout(sz, lay, |ui| {
- egui::ScrollArea::vertical().id_salt("xr_styles").auto_shrink([false, false]).show(ui, |ui| {
- for name in &styles {
- if ui.selectable_label(*name == cur_style, name).clicked() {
- d.fields.insert("style".into(), json!(name));
- }
+ ui.end_row();
+ }
+ });
+ if let Some(e) = d.fields.get("justifyError").and_then(Value::as_str) {
+ ui.add_space(6.0);
+ crate::rtl::label(ui, egui::RichText::new(e).color(ui.visuals().error_fg_color));
+ }
+}
+
+/// The rule fields edited in the dialog, as `type.para` attrs: `{ruleAbove?: {…}, ruleBelow?: {…}}`.
+fn rule_edits(d: &Dialog, prefix: &str) -> Map<String, Value> {
+ let mut out = Map::new();
+ for (which, _) in RULES {
+ let edited = format!("{prefix}{which}.");
+ let fields: Map<String, Value> = d.fields.iter().filter_map(|(k, v)| k.strip_prefix(&edited).map(|f| (f.to_string(), v.clone()))).collect();
+ if !fields.is_empty() {
+ out.insert(which.into(), Value::Object(fields));
+ }
+ }
+ out
+}
+
+/// Paragraph Rules (the dialog, and the Paragraph Style Options section): Rule Above or Rule Below,
+/// chosen at the top. `current` holds the resolved `ruleAbove` / `ruleBelow`; each edit is stored as
+/// `{prefix}{rule}.{field}`, so OK changes only the fields edited.
+fn paragraph_rules(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, current: &Value) {
+ let lang = app.ui.language.as_str();
+ let (h_units, v_units) =
+ app.session.active().map(|st| (st.doc.settings.horizontal_units, st.doc.settings.vertical_units)).unwrap_or((Unit::Points, Unit::Points));
+ let which = if d.s("rule") == "ruleBelow" { "ruleBelow" } else { "ruleAbove" };
+ let rule = shown_rule(d, prefix, which, current);
+ let key = |field: &str| format!("{prefix}{which}.{field}");
+ // A number field takes the rest of the row; keep its grid column to the field's width.
+ let sized = |ui: &mut egui::Ui, add: &mut dyn FnMut(&mut egui::Ui) -> Option<f64>| {
+ ui.allocate_ui_with_layout(egui::vec2(80.0, 22.0), egui::Layout::left_to_right(egui::Align::Center), |ui| add(ui)).inner
+ };
+ ui.horizontal(|ui| {
+ let shown = RULES.iter().find(|r| r.0 == which).map_or(which, |r| r.1);
+ egui::ComboBox::from_id_salt("rule_which").selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, shown))).width(130.0).show_ui(
+ ui,
+ |ui| {
+ for (v, label) in RULES {
+ if ui.selectable_label(v == which, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {
+ d.fields.insert("rule".into(), json!(v));
}
- })
- });
- ui.add_space(8.0);
- let (sz, lay) = col(330.0);
- ui.allocate_ui_with_layout(sz, lay, |ui| {
- egui::ScrollArea::vertical().id_salt("xr_paras").auto_shrink([false, false]).show(ui, |ui| {
- for st in doc.stories.values().filter(|s| !s.frames.is_empty()) {
- for (pi, r) in st.para_ranges().into_iter().enumerate() {
- if cur_style != all && st.paras[pi].style != cur_style {
- continue;
- }
- let text = designcraft_doc::xref::clean(&st.text[r]);
- if text.is_empty() {
- continue;
- }
- let short: String = text.chars().take(52).collect();
- let key = format!("{}:{pi}", st.id.0);
- if ui.selectable_label(d.s("target") == key, short).clicked() {
- d.fields.insert("target".into(), json!(key));
- }
+ }
+ },
+ );
+ ui.add_space(12.0);
+ let mut on = rule["on"].as_bool().unwrap_or(false);
+ if ui.checkbox(&mut on, crate::rtl::widget(ui, crate::i18n::tr(lang, "Rule On"))).changed() {
+ d.fields.insert(key("on"), json!(on));
+ }
+ });
+ ui.add_space(6.0);
+ let on = rule["on"].as_bool().unwrap_or(false);
+ ui.add_enabled_ui(on, |ui| {
+ egui::Grid::new(("rules", which)).num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Weight:"));
+ if let Some(v) = sized(ui, &mut |ui| crate::widgets::number(ui, &key("weight"), rule["weight"].as_f64(), " pt", 80.0, 2)) {
+ d.fields.insert(key("weight"), json!(v.clamp(0.0, 1000.0)));
+ }
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Color:"));
+ let color = rule["color"].as_str().unwrap_or("").to_string();
+ if let Some(w) = app.session.active().and_then(|st| swatch_menu(ui, &st.doc, ("rule_color", which), &color, 130.0)) {
+ d.fields.insert(key("color"), json!(w));
+ }
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Tint:"));
+ if let Some(v) = sized(ui, &mut |ui| crate::widgets::number(ui, &key("tint"), rule["tint"].as_f64().map(|t| t * 100.0), "%", 80.0, 0)) {
+ d.fields.insert(key("tint"), json!((v / 100.0).clamp(0.0, 1.0)));
+ }
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Width:"));
+ let column = rule["columnWidth"].as_bool().unwrap_or(true);
+ egui::ComboBox::from_id_salt(("rule_width", which))
+ .selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, if column { "Column" } else { "Text" })))
+ .width(130.0)
+ .show_ui(ui, |ui| {
+ for (v, label) in [(true, "Column"), (false, "Text")] {
+ if ui.selectable_label(v == column, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {
+ d.fields.insert(key("columnWidth"), json!(v));
}
}
- })
- });
+ });
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Offset:"));
+ if let Some(v) = sized(ui, &mut |ui| crate::widgets::measure(ui, &key("offset"), rule["offset"].as_f64(), v_units, 80.0)) {
+ d.fields.insert(key("offset"), json!(v));
+ }
+ ui.end_row();
+ for (label, field) in [("Left Indent:", "leftIndent"), ("Right Indent:", "rightIndent")] {
+ crate::rtl::label(ui, crate::i18n::tr(lang, label));
+ if let Some(v) = sized(ui, &mut |ui| crate::widgets::measure(ui, &key(field), rule[field].as_f64(), h_units, 80.0)) {
+ d.fields.insert(key(field), json!(v));
+ }
+ }
+ ui.end_row();
});
+ });
+}
+
+/// Document Footnote Options: Numbering and Formatting / Layout tabs.
+fn footnote_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
+ ui.horizontal(|ui| {
+ for (tab, label) in [("numbering", "Numbering and Formatting"), ("layout", "Layout")] {
+ if ui.selectable_label(d.s("tab") == tab, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() {
+ d.fields.insert("tab".into(), json!(tab));
+ }
+ }
+ });
+ ui.separator();
+ let head = |ui: &mut egui::Ui, t: &str| {
+ ui.add_space(4.0);
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, t)).font(semibold(12.0)));
+ };
+ if d.s("tab") == "layout" {
+ head(ui, "Spacing Options");
+ egui::Grid::new("fn_sp").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Minimum Space Before First Footnote:"));
+ text_field(ui, d, "spaceBefore", 70.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Space Between Footnotes:"));
+ text_field(ui, d, "spaceBetween", 70.0);
+ ui.end_row();
+ });
+ head(ui, "First Baseline");
+ egui::Grid::new("fn_fb").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Offset:"));
+ translated_combo(
+ &app.ui.language,
+ ui,
+ d,
+ "firstBaseline",
+ &[
+ ("ascent", "Ascent"),
+ ("capHeight", "Cap Height"),
+ ("leading", "Leading"),
+ ("xHeight", "x Height"),
+ ("emboxHeight", "Em Box Height"),
+ ("fixed", "Fixed"),
+ ],
+ );
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Min:"));
+ text_field(ui, d, "firstBaselineMin", 70.0);
+ ui.end_row();
+ });
+ check(ui, d, "spanColumns", crate::i18n::tr(&app.ui.language, "Span Footnotes Across Columns"));
+ head(ui, "Rule Above");
+ check(ui, d, "rule.on", crate::i18n::tr(&app.ui.language, "Rule On"));
+ egui::Grid::new("fn_rule").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Weight:"));
+ text_field(ui, d, "rule.weight", 60.0);
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Color:"));
+ let swatches: Vec<String> = app.session.active().map(|st| st.doc.swatches.iter().map(|s| s.name.clone()).collect()).unwrap_or_default();
+ let opts: Vec<(&str, &str)> = swatches.iter().map(|n| (n.as_str(), n.as_str())).collect();
+ combo(ui, d, "rule.color", &opts);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Width:"));
+ text_field(ui, d, "rule.width", 60.0);
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Offset:"));
+ text_field(ui, d, "rule.offset", 60.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Left Indent:"));
+ text_field(ui, d, "rule.leftIndent", 60.0);
+ ui.end_row();
+ });
+ return;
+ }
+ head(ui, "Numbering");
+ egui::Grid::new("fn_num").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Style:"));
+ translated_combo(
+ &app.ui.language,
+ ui,
+ d,
+ "style",
+ &[
+ ("arabic", "1, 2, 3, 4..."),
+ ("upperRoman", "I, II, III, IV..."),
+ ("lowerRoman", "i, ii, iii, iv..."),
+ ("upperLetters", "A, B, C, D..."),
+ ("lowerLetters", "a, b, c, d..."),
+ ("arabicLeadingZero", "01, 02, 03..."),
+ ("symbols", "*, †, ‡, §..."),
+ ("kanji", "一, 二, 三, 四..."),
+ ],
+ );
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Start at:"));
+ text_field(ui, d, "startAt", 60.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Restart Numbering Every:"));
+ translated_combo(
+ &app.ui.language,
+ ui,
+ d,
+ "restart",
+ &[("never", "Never (continuous)"), ("page", "Page"), ("spread", "Spread"), ("section", "Section")],
+ );
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Show Prefix/Suffix in:"));
+ translated_combo(
+ &app.ui.language,
+ ui,
+ d,
+ "affixIn",
+ &[("none", "None"), ("reference", "Footnote Reference"), ("text", "Footnote Text"), ("both", "Both")],
+ );
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Prefix:"));
+ text_field(ui, d, "prefix", 60.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Suffix:"));
+ text_field(ui, d, "suffix", 60.0);
+ ui.end_row();
+ });
+ head(ui, "Footnote Reference Number in Text");
+ egui::Grid::new("fn_ref").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Position:"));
+ translated_combo(
+ &app.ui.language,
+ ui,
+ d,
+ "refPosition",
+ &[
+ ("superscript", "Apply Superscript"),
+ ("subscript", "Apply Subscript"),
+ ("normal", "Apply Normal"),
+ ("otSuperscript", "OpenType Superscript"),
+ ],
+ );
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Character Style:"));
+ style_combo(app, ui, d, "refCharStyle", true);
+ ui.end_row();
+ });
+ head(ui, "Footnote Formatting");
+ egui::Grid::new("fn_fmt").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Paragraph Style:"));
+ style_combo(app, ui, d, "paraStyle", false);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Separator:"));
+ text_field(ui, d, "separator", 60.0);
+ ui.end_row();
+ });
+}
+
+/// One parameter of a command, parsed from its params documentation
+/// (`{name, type?: a|b|c, count?, flag?: bool, …}`).
+#[derive(Clone, Debug, PartialEq)]
+pub struct CommandField {
+ pub key: String,
+ pub optional: bool,
+ /// Enumerated values (`a|b|c`).
+ pub choices: Vec<String>,
+ pub boolean: bool,
+ /// The documented value spec (shown as a hint).
+ pub hint: String,
+}
+
+/// Parameters of a command from its documentation string: the top-level keys of the first `{…}`.
+pub fn command_fields(doc: &str) -> Vec<CommandField> {
+ let Some(start) = doc.find('{') else { return vec![] };
+ let mut depth = 0i32;
+ let mut end = doc.len();
+ for (i, c) in doc[start..].char_indices() {
+ match c {
+ '{' | '[' | '(' => depth += 1,
+ '}' | ']' | ')' => {
+ depth -= 1;
+ if depth == 0 {
+ end = start + i;
+ break;
+ }
+ }
+ _ => {}
+ }
+ }
+ let body = &doc[start + 1..end];
+ let mut parts = Vec::new();
+ let (mut depth, mut from) = (0i32, 0usize);
+ for (i, c) in body.char_indices() {
+ match c {
+ '{' | '[' | '(' => depth += 1,
+ '}' | ']' | ')' => depth -= 1,
+ ',' if depth == 0 => {
+ parts.push(&body[from..i]);
+ from = i + 1;
+ }
+ _ => {}
+ }
+ }
+ parts.push(&body[from..]);
+ let ident = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') && !s.starts_with(|c: char| c.is_ascii_digit());
+ let mut out = Vec::new();
+ for part in parts {
+ // `key`, `key?`, `key: spec` or `key (spec)`: the key is the leading word.
+ let part = part.trim();
+ let k_end = part.find(|c: char| c.is_whitespace() || c == ':' || c == '(').unwrap_or(part.len());
+ let (k, rest) = part.split_at(k_end);
+ let rest = rest.trim_start();
+ let spec = match rest.strip_prefix(':') {
+ Some(v) => v.trim(),
+ None => rest.strip_prefix('(').and_then(|r| r.strip_suffix(')')).unwrap_or(rest).trim(),
+ };
+ let optional = k.ends_with('?');
+ let key = k.trim_end_matches('?');
+ if !ident(key) || out.iter().any(|f: &CommandField| f.key == key) {
+ continue;
+ }
+ let word = spec.split_whitespace().next().unwrap_or("");
+ let choices: Vec<String> =
+ if word.contains('|') && word.split('|').all(ident) { word.split('|').map(str::to_string).collect() } else { vec![] };
+ let boolean = spec.starts_with("bool") || spec.starts_with("true|false") || spec.starts_with("true") && spec.len() <= 5;
+ out.push(CommandField { key: key.into(), optional, choices: if boolean { vec![] } else { choices }, boolean, hint: spec.into() });
+ }
+ out
+}
+
+fn humanize(key: &str) -> String {
+ let mut s = String::new();
+ for (i, c) in key.chars().enumerate() {
+ if i == 0 {
+ s.extend(c.to_uppercase());
+ } else if c.is_uppercase() {
+ s.push(' ');
+ s.extend(c.to_lowercase());
+ } else {
+ s.push(c);
+ }
+ }
+ s
+}
+
+/// A form for any command, from its parameter documentation.
+fn command_form(app: &crate::DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
+ let doc = designcraft_engine::find_command(&d.id[4..]).map_or("", |c| c.params);
+ let fields = command_fields(doc);
+ let dim = crate::theme::Tokens::get(ui.ctx()).text_dim;
+ egui::Grid::new("cmdform").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ for f in &fields {
+ ui.label(crate::rtl::widget(
+ ui,
+ format!("{}{}", crate::i18n::tr(&app.ui.language, &humanize(&f.key)), if f.optional { "" } else { " *" }),
+ ));
+ if f.boolean {
+ check(ui, d, &f.key, "");
+ } else if !f.choices.is_empty() {
+ let mut opts: Vec<(&str, &str)> = vec![("", "—")];
+ let labels: Vec<_> = f.choices.iter().map(|c| humanize(c)).collect();
+ opts.extend(f.choices.iter().zip(&labels).map(|(value, label)| (value.as_str(), crate::i18n::tr(&app.ui.language, label))));
+ combo(ui, d, &f.key, &opts);
+ } else {
+ let mut s = d.s(&f.key);
+ let hint = if f.hint.is_empty() { String::new() } else { f.hint.clone() };
+ if ui.add(egui::TextEdit::singleline(&mut s).hint_text(egui::RichText::new(hint).color(dim)).desired_width(240.0)).changed() {
+ d.fields.insert(f.key.clone(), Value::String(s));
+ }
+ }
+ ui.end_row();
+ }
+ });
+ if let Some(st) = d.fields.get("status").and_then(Value::as_str) {
+ ui.label(egui::RichText::new(st).color(crate::theme::Tokens::get(ui.ctx()).text_dim));
+ }
+}
+
+const STEP_AND_REPEAT: &str = "cmd:edit.stepAndRepeat";
+/// The params a previewing dialog shows on the page (its interaction is open while it is set).
+const PREVIEWED: &str = "_previewed";
+
+/// Edit › Step and Repeat, as in InDesign: Repeat (Count, or Rows and Columns with Create as a
+/// grid), Offset (Vertical, Horizontal, in the document's ruler units) and Preview, which shows
+/// the copies on the page while the dialog is open.
+fn step_and_repeat_dialog(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
+ let (hu, vu) = app.session.active().map_or((Unit::Picas, Unit::Picas), |s| (s.doc.settings.horizontal_units, s.doc.settings.vertical_units));
+ for (k, v) in [
+ ("count", json!("1")),
+ ("rows", json!("1")),
+ ("columns", json!("1")),
+ ("vertical", json!(format_measure(12.0, vu))),
+ ("horizontal", json!(format_measure(12.0, hu))),
+ ] {
+ d.fields.entry(k).or_insert(v);
+ }
+ let lang = app.ui.language.clone();
+ let tr = |s: &str| crate::i18n::tr(&lang, s).to_string();
+ ui.horizontal_top(|ui| {
+ ui.vertical(|ui| {
+ crate::rtl::label(ui, egui::RichText::new(tr("Repeat")).font(semibold(12.0)));
+ egui::Grid::new("sr_repeat").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ let grid = d.b("grid");
+ let fields: &[(&str, &str)] = if grid { &[("rows", "Rows:"), ("columns", "Columns:")] } else { &[("count", "Count:")] };
+ for (k, l) in fields {
+ // A grid's columns, not a text frame's.
+ crate::rtl::label(ui, crate::i18n::tr_context(&lang, l, "grid"));
+ text_field(ui, d, k, 70.0);
+ ui.end_row();
+ }
+ crate::rtl::label(ui, "");
+ check(ui, d, "grid", &tr("Create as a grid"));
+ ui.end_row();
+ });
+ ui.add_space(10.0);
+ crate::rtl::label(ui, egui::RichText::new(tr("Offset")).font(semibold(12.0)));
+ ui.horizontal(|ui| {
+ for (k, l) in [("vertical", "Vertical:"), ("horizontal", "Horizontal:")] {
+ crate::rtl::label(ui, tr(l));
+ text_field(ui, d, k, 80.0);
+ ui.add_space(12.0);
+ }
+ });
+ });
+ ui.add_space(32.0);
+ check(ui, d, "preview", &tr("Preview"));
+ });
+ step_and_repeat_preview(app, d);
+ if let Some(st) = d.fields.get("status").and_then(Value::as_str) {
+ ui.add_space(6.0);
+ crate::rtl::label(ui, egui::RichText::new(st).color(crate::theme::Tokens::get(ui.ctx()).text_dim));
+ }
+}
+
+/// `edit.stepAndRepeat`'s params from the dialog: whole counts, offsets in the ruler units
+/// (or any unit typed: "-0.75 in", "3p"). Empty fields are 1 copy and 1p0.
+fn step_and_repeat_params(app: &DesignApp, d: &Dialog) -> Result<Value, String> {
+ let (hu, vu) = app.session.active().map_or((Unit::Picas, Unit::Picas), |s| (s.doc.settings.horizontal_units, s.doc.settings.vertical_units));
+ let invalid = |s: &str| format!("{}: {}", crate::i18n::tr(&app.ui.language, "Invalid value"), s.trim());
+ // Fields not shown yet (a dialog confirmed over the control channel) take the defaults.
+ let whole = |k: &str| {
+ let s = d.s(k);
+ if s.trim().is_empty() { Ok(1) } else { s.trim().parse::<u64>().map_err(|_| invalid(&s)) }
+ };
+ let measure = |k: &str, u: Unit| {
+ let s = d.s(k);
+ if s.trim().is_empty() {
+ return Ok(12.0);
+ }
+ parse_measure(&s, u).ok().filter(|v| v.is_finite()).ok_or_else(|| invalid(&s))
+ };
+ let (dx, dy) = (measure("horizontal", hu)?, measure("vertical", vu)?);
+ Ok(if d.b("grid") {
+ json!({"rows": whole("rows")?, "columns": whole("columns")?, "dx": dx, "dy": dy})
+ } else {
+ json!({"count": whole("count")?, "dx": dx, "dy": dy})
+ })
+}
+
+/// Preview on: the copies show on the page (redone when a field changes); off: they go.
+fn step_and_repeat_preview(app: &mut DesignApp, d: &mut Dialog) {
+ let shown = d.fields.get(PREVIEWED).cloned();
+ if !d.b("preview") {
+ if shown.is_some() {
+ app.session.cancel_interaction();
+ d.fields.remove(PREVIEWED);
+ d.fields.remove("status");
+ }
+ return;
+ }
+ let params = match step_and_repeat_params(app, d) {
+ Ok(p) => p,
+ Err(e) => {
+ d.fields.insert("status".into(), json!(e));
+ return;
+ }
+ };
+ if shown.as_ref() == Some(&params) {
+ return;
+ }
+ if shown.is_none()
+ && let Err(e) = app.session.begin_interaction("Step and Repeat")
+ {
+ d.fields.insert("status".into(), json!(e.to_string()));
+ return;
+ }
+ match app.session.preview("edit.stepAndRepeat", params.clone()) {
+ Ok(()) => d.fields.remove("status"),
+ Err(e) => d.fields.insert("status".into(), json!(e.to_string())),
+ };
+ d.fields.insert(PREVIEWED.into(), params);
+}
+
+/// New Cross-Reference: link to a paragraph (paragraph styles on the left, their paragraphs on
+/// the right) or a text anchor, with a cross-reference format.
+fn insert_xref(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
+ let Some(st) = app.session.active() else { return };
+ let doc = &st.doc;
+ let all = "[All Paragraphs]";
+ ui.horizontal(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Link To:"));
+ translated_combo(&app.ui.language, ui, d, "linkTo", &[("paragraph", "Paragraph"), ("anchor", "Text Anchor")]);
+ });
+ ui.add_space(6.0);
+ let dim = crate::theme::Tokens::get(ui.ctx()).text_dim;
+ if d.s("linkTo") == "anchor" {
+ egui::ScrollArea::vertical().id_salt("xr_anchors").max_height(220.0).max_width(460.0).show(ui, |ui| {
+ let mut any = false;
+ for st in doc.stories.values() {
+ for a in &st.anchors {
+ any = true;
+ let key = format!("a:{}", a.id);
+ if ui.selectable_label(d.s("target") == key, &a.name).clicked() {
+ d.fields.insert("target".into(), json!(key));
+ }
+ }
+ }
+ if !any {
+ ui.label(crate::rtl::widget(
+ ui,
+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "No text anchors in this document.")).color(dim),
+ ));
+ }
+ });
+ } else {
+ let mut styles: Vec<String> = vec![all.to_string()];
+ styles.extend(doc.styles.paragraph.iter().map(|s| s.name.clone()));
+ let cur_style = if d.s("style").is_empty() { all.to_string() } else { d.s("style") };
+ ui.horizontal_top(|ui| {
+ let col = |w: f32| (egui::vec2(w, 240.0), egui::Layout::top_down(egui::Align::Min));
+ let (sz, lay) = col(180.0);
+ ui.allocate_ui_with_layout(sz, lay, |ui| {
+ egui::ScrollArea::vertical().id_salt("xr_styles").auto_shrink([false, false]).show(ui, |ui| {
+ for name in &styles {
+ if ui.selectable_label(*name == cur_style, name).clicked() {
+ d.fields.insert("style".into(), json!(name));
+ }
+ }
+ })
+ });
+ ui.add_space(8.0);
+ let (sz, lay) = col(330.0);
+ ui.allocate_ui_with_layout(sz, lay, |ui| {
+ egui::ScrollArea::vertical().id_salt("xr_paras").auto_shrink([false, false]).show(ui, |ui| {
+ for st in doc.stories.values().filter(|s| !s.frames.is_empty()) {
+ for (pi, r) in st.para_ranges().into_iter().enumerate() {
+ if cur_style != all && st.paras[pi].style != cur_style {
+ continue;
+ }
+ let text = designcraft_doc::xref::clean(&st.text[r]);
+ if text.is_empty() {
+ continue;
+ }
+ let short: String = text.chars().take(52).collect();
+ let key = format!("{}:{pi}", st.id.0);
+ if ui.selectable_label(d.s("target") == key, short).clicked() {
+ d.fields.insert("target".into(), json!(key));
+ }
+ }
+ }
+ })
+ });
+ });
+ }
+ ui.add_space(8.0);
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Cross-Reference Format")).font(semibold(12.0)));
+ let names: Vec<String> = doc.xref_formats.iter().map(|f| f.name.clone()).collect();
+ if d.s("format").is_empty() {
+ d.fields.insert("format".into(), json!(names.first().cloned().unwrap_or_default()));
+ }
+ let opts: Vec<(&str, &str)> = names.iter().map(|n| (n.as_str(), n.as_str())).collect();
+ ui.horizontal(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Format:"));
+ combo(ui, d, "format", &opts);
+ });
+ if let Some(m) = d.fields.get("status").and_then(Value::as_str) {
+ ui.label(egui::RichText::new(m).color(dim));
+ }
+}
+
+/// Color Picker: saturation/brightness field and hue slider, with RGB, CMYK and hex fields.
+fn color_picker(ui: &mut egui::Ui, d: &mut Dialog) {
+ let hex = d.s("hex");
+ let mut c = designcraft_color::Color::from_hex(&hex).map(|c| c.to_rgb()).map_or(egui::Color32::BLACK, |[r, g, b]| {
+ egui::Color32::from_rgb((r * 255.0).round() as u8, (g * 255.0).round() as u8, (b * 255.0).round() as u8)
+ });
+ let before = c;
+ ui.horizontal_top(|ui| {
+ egui::color_picker::color_picker_color32(ui, &mut c, egui::color_picker::Alpha::Opaque);
+ ui.vertical(|ui| {
+ let mut rgb = [c.r() as f32, c.g() as f32, c.b() as f32];
+ egui::Grid::new("cp_rgb").num_columns(2).spacing([6.0, 4.0]).show(ui, |ui| {
+ for (k, l) in ["R", "G", "B"].iter().enumerate() {
+ ui.label(*l);
+ ui.add(egui::DragValue::new(&mut rgb[k]).range(0.0..=255.0));
+ ui.end_row();
+ }
+ });
+ c = egui::Color32::from_rgb(rgb[0] as u8, rgb[1] as u8, rgb[2] as u8);
+ let col = designcraft_color::Color::rgb8(c.r(), c.g(), c.b());
+ let [cc, m, y, k] = col.to_cmyk();
+ ui.add_space(6.0);
+ ui.label(format!("C {:.0}% M {:.0}% Y {:.0}% K {:.0}%", cc * 100.0, m * 100.0, y * 100.0, k * 100.0));
+ ui.add_space(6.0);
+ ui.horizontal(|ui| {
+ ui.label("#");
+ let mut h = format!("{:02x}{:02x}{:02x}", c.r(), c.g(), c.b());
+ if ui.add(egui::TextEdit::singleline(&mut h).desired_width(70.0)).changed()
+ && let Some(n) = designcraft_color::Color::from_hex(&h)
+ {
+ let [r, g, b] = n.to_rgb();
+ c = egui::Color32::from_rgb((r * 255.0).round() as u8, (g * 255.0).round() as u8, (b * 255.0).round() as u8);
+ }
+ });
+ });
+ });
+ if c != before {
+ d.fields.insert("hex".into(), json!(format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b())));
+ }
+}
+
+/// Find/Replace Font: the document's fonts (missing ones first, flagged) and a replacement.
+/// Load Styles: a checkbox for each style of the picked file, and what happens to a style this
+/// document defines differently under the same name.
+fn load_styles(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
+ let lang = app.ui.language.as_str();
+ let dim = crate::theme::Tokens::get(ui.ctx()).text_dim;
+ ui.label(egui::RichText::new(d.s("path")).size(10.5));
+ ui.horizontal(|ui| {
+ for (label, on) in [("Select All", true), ("Deselect All", false)] {
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {
+ for key in ["paragraph", "character"] {
+ for row in d.fields.get_mut(key).and_then(Value::as_array_mut).into_iter().flatten().filter_map(Value::as_object_mut) {
+ row.insert("on".into(), json!(on));
+ }
+ }
+ }
+ }
+ });
+ let mut conflicts = 0;
+ egui::ScrollArea::vertical().id_salt("load_styles").max_height(240.0).show(ui, |ui| {
+ for (key, title) in [("paragraph", "Paragraph Styles"), ("character", "Character Styles")] {
+ let Some(rows) = d.fields.get_mut(key).and_then(Value::as_array_mut).filter(|rows| !rows.is_empty()) else { continue };
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, title)).font(semibold(12.0)));
+ for row in rows.iter_mut().filter_map(Value::as_object_mut) {
+ let Some(name) = row.get("name").and_then(Value::as_str).map(str::to_string) else { continue };
+ let (mut on, conflict) = (row.get("on") != Some(&json!(false)), row.get("conflict") == Some(&json!(true)));
+ ui.horizontal(|ui| {
+ if ui.checkbox(&mut on, crate::rtl::widget(ui, crate::i18n::style_name(lang, &name))).changed() {
+ row.insert("on".into(), json!(on));
+ }
+ if conflict {
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, "Differs from this document")).size(10.5).color(dim));
+ }
+ });
+ conflicts += usize::from(on && conflict);
+ }
+ }
+ });
+ ui.add_space(4.0);
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, "Style Name Conflicts")).font(semibold(12.0)));
+ if conflicts == 0 {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "No conflicts"));
+ return;
+ }
+ let cur = d.s("conflicts");
+ ui.horizontal(|ui| {
+ for (v, l) in [("redefine", "Redefine Document Style"), ("useExisting", "Use Document Style Definition"), ("autoRename", "Auto Rename")] {
+ if ui.radio(cur == v, crate::rtl::widget(ui, crate::i18n::tr(lang, l))).clicked() {
+ d.fields.insert("conflicts".into(), json!(v));
+ }
+ }
+ });
+}
+
+fn find_font(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
+ // Listed once when the dialog opens (it scans every story).
+ if !d.fields.contains_key("_fonts") {
+ let list = app.session.execute("font.list", &json!({})).unwrap_or_default();
+ d.fields.insert("_fonts".into(), list);
+ }
+ let fonts = d.fields.get("_fonts").and_then(Value::as_array).cloned().unwrap_or_default();
+ if !fonts.iter().any(|font| font["family"] == d.s("family") && font["style"] == d.s("style"))
+ && let Some(font) = fonts.first()
+ {
+ d.fields.insert("family".into(), font["family"].clone());
+ d.fields.insert("style".into(), font["style"].clone());
+ }
+ if d.b("onOpen") && fonts.iter().any(|f| f["missing"] == true || f["styleMissing"] == true) {
+ crate::rtl::label(
+ ui,
+ crate::i18n::tr(
+ &app.ui.language,
+ "This document uses unavailable fonts. Choose replacements, or select Done to continue with fallback fonts.",
+ ),
+ );
+ }
+ if !d.s("error").is_empty() {
+ crate::rtl::label(ui, d.s("error"));
+ }
+ let missing = fonts.iter().filter(|f| f["missing"] == true || f["styleMissing"] == true).count();
+ crate::rtl::label(
+ ui,
+ crate::i18n::tr(&app.ui.language, "Fonts in Document: {count} Missing: {missing}")
+ .replace("{count}", &fonts.len().to_string())
+ .replace("{missing}", &missing.to_string()),
+ );
+ egui::ScrollArea::vertical().id_salt("ff_list").max_height(180.0).show(ui, |ui| {
+ for f in &fonts {
+ let (fam, st) = (f["family"].as_str().unwrap_or(""), f["style"].as_str().unwrap_or(""));
+ let warn = f["missing"] == true || f["styleMissing"] == true;
+ let label = format!("{}{fam} {st}", if warn { "\u{26A0} " } else { "" });
+ let on = d.s("family") == fam && d.s("style") == st;
+ let mut text = egui::RichText::new(label);
+ if warn && !on {
+ text = text.color(crate::theme::Tokens::get(ui.ctx()).text_strong);
+ }
+ if ui.selectable_label(on, text).clicked() {
+ d.fields.insert("family".into(), json!(fam));
+ d.fields.insert("style".into(), json!(st));
+ }
+ }
+ });
+ let key = format!("{}\n{}", d.s("family"), d.s("style"));
+ if let Some(font) = fonts.iter().find(|f| f["family"] == d.s("family") && f["style"] == d.s("style")) {
+ if d.s("_fontKey") != key {
+ d.fields.insert("_fontKey".into(), json!(key));
+ d.fields.insert("toFamily".into(), font["replacementFamily"].clone());
+ d.fields.insert("toStyle".into(), font["replacementStyle"].clone());
+ }
+ crate::rtl::label(
+ ui,
+ format!(
+ "{}: {} {}",
+ crate::i18n::tr(&app.ui.language, "Currently Rendered With"),
+ font["resolvedFamily"].as_str().unwrap_or(""),
+ font["resolvedStyle"].as_str().unwrap_or("")
+ ),
+ );
+ }
+ ui.add_space(8.0);
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Replace With")).font(semibold(12.0)));
+ let db = crate::panels::fonts(app);
+ if d.s("toFamily").is_empty() {
+ d.fields.insert("toFamily".into(), json!(designcraft_fonts::FALLBACK_FAMILY));
+ }
+ egui::Grid::new("ff_to").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Font Family:"));
+ if let Some(f) = crate::panels::font_combo(app, ui, "toFamily", &d.s("toFamily"), 170.0) {
+ let style = crate::panels::pick_style(app, &f);
+ d.fields.insert("toFamily".into(), json!(f.family));
+ d.fields.insert("toStyle".into(), json!(style));
+ }
+ ui.end_row();
+ let styles = db.styles(&d.s("toFamily"));
+ if !styles.iter().any(|style| style == &d.s("toStyle")) {
+ let preferred = d.s("style");
+ let style = styles
+ .iter()
+ .find(|s| s.eq_ignore_ascii_case(&preferred))
+ .or_else(|| styles.iter().find(|s| s.eq_ignore_ascii_case("Regular")))
+ .or_else(|| styles.first());
+ if let Some(style) = style {
+ d.fields.insert("toStyle".into(), json!(style));
+ }
+ }
+ let st_opts: Vec<(&str, &str)> = styles.iter().map(|s| (s.as_str(), s.as_str())).collect();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Font Style:"));
+ combo(ui, d, "toStyle", &st_opts);
+ ui.end_row();
+ });
+ ui.label(crate::rtl::widget(
+ ui,
+ egui::RichText::new(crate::i18n::tr(
+ &app.ui.language,
+ "Replace All updates this font throughout text and styles. Done keeps remaining fallback fonts.",
+ ))
+ .color(crate::theme::Tokens::get(ui.ctx()).text_dim)
+ .size(11.0),
+ ));
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn step_and_repeat_dialog_previews_and_makes_the_copies_as_one_undo_step() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let id = app.run("frame.create", json!({"rect": [72, 600, 540, 640]})).unwrap()["id"].as_u64().unwrap();
+ app.run("selection.set", json!({"ids": [id]})).unwrap();
+ let open = |app: &mut DesignApp| {
+ crate::menus::activate(app, "edit.stepAndRepeat", &Value::Null);
+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some(STEP_AND_REPEAT));
+ };
+ let set = |app: &mut DesignApp, k: &str, v: Value| {
+ app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v);
+ };
+ let items = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].items.len();
+ let undo = |app: &DesignApp| app.session.doc().unwrap().history.undo.len();
+ let (n0, u0) = (items(&app), undo(&app));
+ let ctx = dialog_context("en");
+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));
+ open(&mut app);
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);
+ for expected in ["Step and Repeat", "Repeat", "Count:", "Create as a grid", "Offset", "Vertical:", "Horizontal:", "Preview", "OK", "Cancel"] {
+ visible_label(&labels, screen, expected);
+ }
+ // Preview: the copies show, and change with the fields, without an undo step.
+ set(&mut app, "count", json!("5"));
+ set(&mut app, "vertical", json!("-0.75 in"));
+ set(&mut app, "horizontal", json!("0"));
+ set(&mut app, "preview", json!(true));
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ assert_eq!((items(&app), undo(&app)), (n0 + 5, u0));
+ set(&mut app, "count", json!("3"));
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ assert_eq!(items(&app), n0 + 3);
+ set(&mut app, "preview", json!(false));
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ assert_eq!(items(&app), n0, "Preview off takes them away");
+ set(&mut app, "preview", json!(true));
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ assert_eq!(items(&app), n0 + 3);
+ // Cancel puts the document back.
+ cancel(&mut app);
+ assert!(app.ui.dialog.is_none());
+ assert_eq!((items(&app), undo(&app)), (n0, u0));
+ // OK after a preview makes the copies once, as one undo step, 0.75 in apart.
+ app.run("selection.set", json!({"ids": [id]})).unwrap();
+ open(&mut app);
+ set(&mut app, "count", json!("2"));
+ set(&mut app, "vertical", json!("-0.75 in"));
+ set(&mut app, "horizontal", json!("0"));
+ set(&mut app, "preview", json!(true));
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ let r = confirm(&mut app).unwrap();
+ assert_eq!((items(&app), undo(&app)), (n0 + 2, u0 + 1));
+ let last = r["ids"][1].as_u64().unwrap();
+ let top = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(last)).unwrap().bounds().min_y();
+ assert!((top - (600.0 - 108.0)).abs() < 1e-6, "{top}");
+ // Create as a grid: Rows × Columns cells, the original being one.
+ app.run("selection.set", json!({"ids": [id]})).unwrap();
+ open(&mut app);
+ set(&mut app, "grid", json!(true));
+ set(&mut app, "rows", json!("2"));
+ set(&mut app, "columns", json!("3"));
+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);
+ visible_label(&labels, screen, "Rows:");
+ visible_label(&labels, screen, "Columns:");
+ assert_eq!(confirm(&mut app).unwrap()["created"], 5);
+ // A value that isn't a measure keeps the dialog open and says so.
+ open(&mut app);
+ set(&mut app, "vertical", json!("up"));
+ assert!(confirm(&mut app).is_err());
+ let d = app.ui.dialog.as_ref().unwrap();
+ assert_eq!(d.s("status"), "Invalid value: up");
+ }
+
+ /// A three-page document in `units` with Document Setup open.
+ fn document_setup_app(units: &str) -> DesignApp {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"pages": 3})).unwrap();
+ app.run("document.preferences", json!({"horizontalUnits": units, "verticalUnits": units})).unwrap();
+ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);
+ app
+ }
+
+ fn setup_fields(app: &mut DesignApp, fields: Value) {
+ let d = app.ui.dialog.as_mut().unwrap();
+ for (k, v) in fields.as_object().unwrap() {
+ d.fields.insert(k.clone(), v.clone());
+ }
+ }
+
+ #[test]
+ fn document_setup_ok_applies_margins_bleed_and_size_in_one_step() {
+ let mut app = document_setup_app("millimeters");
+ let d = app.ui.dialog.as_ref().unwrap();
+ assert_eq!(d.id, "documentSetup");
+ assert_eq!((d.s("marginTop"), d.b("marginLinked")), ("12.7 mm".to_string(), true), "the document's margins, in its units");
+ setup_fields(
+ &mut app,
+ json!({"marginTop": "20 mm", "marginBottom": "20 mm", "marginInside": "20 mm", "marginOutside": "20 mm", "bleedTop": "3 mm",
+ "bleedBottom": "3 mm", "bleedInside": "3 mm", "bleedOutside": "3 mm", "width": "210 mm", "height": "297 mm"}),
+ );
+ confirm(&mut app).unwrap();
+ assert!(app.ui.dialog.is_none());
+ let mm = designcraft_geom::units::PT_PER_MM;
+ let doc = &app.session.active().unwrap().doc;
+ assert!((doc.settings.page_width - 210.0 * mm).abs() < 1e-6 && (doc.settings.bleed[2] - 3.0 * mm).abs() < 1e-6);
+ assert!(doc.spreads.iter().flat_map(|s| &s.pages).all(|p| (p.margins.top - 20.0 * mm).abs() < 1e-6), "every page");
+ app.run("edit.undo", json!({})).unwrap();
+ let doc = &app.session.active().unwrap().doc;
+ assert!((doc.settings.page_width - 612.0).abs() < 1e-6 && doc.settings.bleed[0] == 0.0, "one undo step");
+ }
+
+ #[test]
+ fn document_setup_keeps_each_pages_margins_unless_they_are_edited() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"pages": 3, "margins": 36})).unwrap();
+ app.run("layout.marginsAndColumns", json!({"pages": [1], "margins": 90})).unwrap();
+ let margins =
+ |app: &DesignApp| app.session.active().unwrap().doc.spreads.iter().flat_map(|s| &s.pages).map(|p| p.margins.top).collect::<Vec<_>>();
+ // Only the page count changes: every page keeps its own margins.
+ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);
+ setup_fields(&mut app, json!({"pages": "4"}));
+ confirm(&mut app).unwrap();
+ assert_eq!(margins(&app), [36.0, 90.0, 36.0, 36.0]);
+ // Edited margins go to every page.
+ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);
+ setup_fields(&mut app, json!({"marginTop": "1p0"}));
+ confirm(&mut app).unwrap();
+ assert_eq!(margins(&app), [12.0; 4]);
+ }
+
+ #[test]
+ fn document_setup_keeps_a_value_it_cannot_read_and_changes_nothing() {
+ for (key, value) in [("width", "wide"), ("marginTop", "-"), ("pages", "0"), ("bleedTop", "x")] {
+ let mut app = document_setup_app("points");
+ setup_fields(&mut app, json!({key: value, "bleedInside": "9"}));
+ assert!(confirm(&mut app).is_err(), "{key}");
+ assert!(app.ui.dialog.is_some(), "{key}: the dialog stays open");
+ assert_eq!(app.session.active().unwrap().doc.settings.bleed, [0.0; 4], "{key}: nothing changed");
+ }
+ }
+
+ #[test]
+ fn document_setup_links_edges_and_adjust_layout_applies() {
+ let mut app = document_setup_app("points");
+ let f = app.run("frame.create", json!({"rect": [36, 36, 576, 756], "content": "text"})).unwrap();
+ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);
+ let ctx = dialog_context("en");
+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 900.0));
+ for _ in 0..3 {
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ }
+ // Typing in a linked margin sets all four.
+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);
+ let top = labels.iter().filter(|(t, _, _)| t == "36 pt").map(|(_, r, _)| *r).next().expect("the top margin");
+ click_dialog(&mut app, &ctx, screen, top.center());
+ let select_all =
+ egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND };
+ dialog_frame(&mut app, &ctx, screen, vec![select_all, egui::Event::Text("72 pt".into())]);
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ let d = app.ui.dialog.as_ref().unwrap();
+ assert!(["Top", "Bottom", "Inside", "Outside"].iter().all(|e| d.s(&format!("margin{e}")) == "72 pt"), "linked: {:?}", d.fields);
+ // Adjust Layout applies at once, and the frame follows the margins.
+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);
+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Adjust Layout").center());
+ assert!(app.ui.dialog.is_none(), "applied");
+ let doc = &app.session.active().unwrap().doc;
+ let b = doc.item(designcraft_doc::ItemId(f["id"].as_u64().unwrap())).unwrap().bounds();
+ assert!((b.y0 - 72.0).abs() < 1e-6 && doc.page(0).unwrap().margins.outside == 72.0, "{b:?}");
+ }
+
+ #[test]
+ fn cell_options_dialog_draws_and_applies_only_changed_values_to_the_chosen_edges() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
+ let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
+ app.run("table.select", json!({"what": "table"})).unwrap();
+ app.run("app.cellOptionsDialog", json!({})).unwrap();
+ let ctx = dialog_context("");
+ dialog_frame(&mut app, &ctx, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0)), vec![]);
+ let d = app.ui.dialog.as_mut().unwrap();
+ assert_eq!(d.id, "cellOptions");
+ assert_eq!(d.fields["weight"], json!(1.0));
+ d.fields.insert("edges".into(), json!(["top", "bottom", "left", "right"]));
+ d.fields.insert("gapColor".into(), json!("[Paper]"));
+ d.fields.insert("fill".into(), json!("[Black]"));
+ d.fields.insert("fillTint".into(), json!(0.2));
+ confirm(&mut app).unwrap();
+ let st = app.session.active().unwrap();
+ let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
+ let gap = |r: usize, c: usize, side: usize| t.cell(r, c).unwrap().strokes[side].gap_color.clone();
+ assert_eq!([gap(0, 0, 0), gap(0, 0, 1), gap(1, 1, 2), gap(1, 1, 3)], ["[Paper]"; 4].map(String::from), "outer edges");
+ assert_eq!([gap(0, 0, 2), gap(0, 0, 3)], ["[None]"; 2].map(String::from), "inner edges keep theirs");
+ assert!(t.cells.iter().all(|c| c.fill == "[Black]" && (c.fill_tint - 0.2).abs() < 1e-6));
+ assert!(t.cells.iter().all(|c| c.strokes.iter().all(|e| e.weight == 1.0)), "unchanged values are not applied");
+ }
+
+ #[test]
+ fn cell_options_edge_changes_reseed_every_stroke_field_and_survive_a_bad_seed() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
+ let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
+ app.run("table.select", json!({"what": "table"})).unwrap();
+ app.run("table.setCell", json!({"stroke": {"weight": 3, "edges": "innerHorizontal"}})).unwrap();
+ app.run("app.cellOptionsDialog", json!({})).unwrap();
+ let mut d = app.ui.dialog.take().unwrap();
+ d.fields.insert("seed".into(), json!(5));
+ let outer = [true, true, true, true, false, false];
+ cell_options_edges_changed(&mut app, &mut d, &outer);
+ assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(1.0), &json!(1.0)));
+ // A weight typed for the outer edges, then the inner horizontal edges (3 pt) chosen
+ // and 1 pt typed: 1 pt differs from what those edges show, so OK applies it.
+ d.fields.insert("weight".into(), json!(5.0));
+ cell_options_edges_changed(&mut app, &mut d, &[false, false, false, false, true, false]);
+ assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(5.0), &json!(3.0)));
+ d.fields.insert("weight".into(), json!(1.0));
+ app.ui.dialog = Some(d);
+ confirm(&mut app).unwrap();
+ let st = app.session.active().unwrap();
+ let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
+ assert_eq!([t.cell(0, 0).unwrap().strokes[2].weight, t.cell(1, 1).unwrap().strokes[0].weight], [1.0; 2]);
+ }
+
+ #[test]
+ fn enter_and_escape_close_the_style_menu_not_numbering_and_section_options() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"pages": 2})).unwrap();
+ crate::menus::activate(&mut app, "layout.section", &Value::Null);
+ let ctx = dialog_context("en");
+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));
+ for _ in 0..3 {
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ }
+ let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
+ for pressed in [egui::Key::Enter, egui::Key::Escape] {
+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);
+ // The section's Style menu (the first of the two).
+ let style = labels.iter().filter(|(t, r, c)| t.trim() == "1, 2, 3, 4…" && c.contains_rect(*r)).map(|(_, r, _)| *r).next().unwrap();
+ click_dialog(&mut app, &ctx, screen, style.center());
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ assert!(egui::Popup::is_any_open(&ctx), "the Style menu opened");
+ dialog_frame(&mut app, &ctx, screen, vec![key(pressed)]);
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ assert!(app.ui.dialog.is_some(), "{pressed:?} with the menu open leaves the dialog open");
+ assert!(app.session.active().unwrap().doc.sections.iter().all(|s| s.start_number != Some(0)));
+ if egui::Popup::is_any_open(&ctx) {
+ egui::Popup::close_all(&ctx);
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ }
+ }
+ // With no menu open, Escape closes the dialog.
+ dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Escape)]);
+ assert!(app.ui.dialog.is_none());
+ }
+
+ #[test]
+ fn numbering_and_section_options_keep_their_actions_in_view() {
+ for language in ["en", "ar"] {
+ for size in [egui::vec2(1178.0, 814.0), egui::vec2(392.0, 271.0)] {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.ui.language = language.into();
+ app.run("file.new", json!({"pages": 2})).unwrap();
+ crate::menus::activate(&mut app, "layout.section", &Value::Null);
+ let ctx = dialog_context(language);
+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size);
+ for _ in 0..3 {
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ }
+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);
+ let tr = |s| crate::i18n::tr(language, s);
+ for expected in [tr("Numbering & Section Options…").trim_end_matches('…'), tr("OK"), tr("Cancel"), tr("Start Section")] {
+ visible_label(&labels, screen, expected);
+ }
+ if size.x > 1000.0 {
+ // Every option fits without scrolling, and choosing one then OK applies it.
+ visible_label(&labels, screen, &format!("{} {}", tr("Book Name:"), tr("N/A")));
+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, tr("Automatic Page Numbering")).center());
+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);
+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, tr("OK")).center());
+ assert!(app.ui.dialog.is_none(), "{language}: OK closes the dialog");
+ let doc = &app.session.active().unwrap().doc;
+ assert!(doc.sections.iter().all(|s| s.start != 0 || s.start_number.is_none()), "{language}: page 1 numbers automatically");
+ }
+ }
+ }
+ }
+
+ fn draw(app: &mut DesignApp, ctx: &egui::Context) {
+ let input =
+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };
+ let mut out = ctx.run_ui(input, |ui| {
+ app.logic(&ui.ctx().clone());
+ app.ui(ui);
+ });
+ out.textures_delta.clear();
+ }
+
+ /// A paragraph styled "Ruled Child", whose Rule Below comes from its parent "Ruled".
+ fn ruled_paragraph() -> (DesignApp, Value) {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let rule = json!({"on": true, "weight": 3.0, "color": "[Black]", "tint": 0.5, "columnWidth": false, "offset": 4.0, "leftIndent": 6.0, "rightIndent": 2.0});
+ app.run("style.paragraph.create", json!({"name": "Ruled", "para": {"ruleBelow": rule}})).unwrap();
+ app.run("style.paragraph.create", json!({"name": "Ruled Child", "basedOn": "Ruled"})).unwrap();
+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 400], "content": "text", "text": "One"})).unwrap();
+ app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();
+ app.run("style.paragraph.apply", json!({"name": "Ruled Child"})).unwrap();
+ (app, rule)
+ }
+
+ fn undo_steps(app: &DesignApp) -> usize {
+ app.session.doc().map_or(0, |st| st.history.undo.len())
+ }
+
+ #[test]
+ fn paragraph_rules_dialog_shows_the_rule_and_applies_one_field() {
+ let (mut app, rule) = ruled_paragraph();
+ let ctx = egui::Context::default();
+ app.run("app.paragraphRulesDialog", json!({"rule": "ruleBelow"})).unwrap();
+ draw(&mut app, &ctx);
+ let d = app.ui.dialog.clone().unwrap();
+ assert_eq!(d.id, "paragraphRules");
+ let current = d.fields["current"].clone();
+ assert_eq!(shown_rule(&d, "", "ruleBelow", &current), rule, "the inherited rule");
+ assert_eq!(shown_rule(&d, "", "ruleAbove", &current)["on"], false);
+ // Pick a colour, as the Color menu does.
+ app.ui.dialog.as_mut().unwrap().fields.insert("ruleBelow.color".into(), json!("[Registration]"));
+ draw(&mut app, &ctx);
+ let before = undo_steps(&app);
+ confirm(&mut app).unwrap();
+ assert_eq!(undo_steps(&app), before + 1, "one undo step");
+ let mut want = rule.clone();
+ want["color"] = json!("[Registration]");
+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want);
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], rule);
+ }
+
+ #[test]
+ fn paragraph_style_options_edit_one_rule_field() {
+ let (mut app, rule) = ruled_paragraph();
+ let ctx = egui::Context::default();
+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"})));
+ draw(&mut app, &ctx);
+ let resolved = |app: &DesignApp| serde_json::to_value(app.session.doc().unwrap().doc.styles.resolve_para_style("Ruled Child").0).unwrap();
+ let d = app.ui.dialog.clone().unwrap();
+ assert_eq!(shown_rule(&d, "p.", "ruleBelow", &resolved(&app)), rule, "inherited from the parent style");
+ app.ui.dialog.as_mut().unwrap().fields.insert("p.ruleBelow.weight".into(), json!(1.5));
+ draw(&mut app, &ctx);
+ let before = undo_steps(&app);
+ confirm(&mut app).unwrap();
+ assert_eq!(undo_steps(&app), before + 1, "one undo step");
+ let mut want = rule.clone();
+ want["weight"] = json!(1.5);
+ assert_eq!(resolved(&app)["ruleBelow"], want);
+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want, "the paragraph follows its style");
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(resolved(&app)["ruleBelow"], rule);
+ }
+
+ /// Opens Paragraph Style Options on "Ruled Child" at each of `sections`, sets `fields` and
+ /// clicks OK; returns the resolved attributes of the paragraph styled with it.
+ fn style_section_edit(sections: &[&str], fields: Value) -> Value {
+ let (mut app, _) = ruled_paragraph();
+ let ctx = egui::Context::default();
+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child"})));
+ for section in sections {
+ app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!(section));
+ draw(&mut app, &ctx);
+ }
+ for (k, v) in fields.as_object().unwrap() {
+ app.ui.dialog.as_mut().unwrap().fields.insert(k.clone(), v.clone());
+ }
+ draw(&mut app, &ctx);
+ let before = undo_steps(&app);
+ confirm(&mut app).unwrap();
+ assert_eq!(undo_steps(&app), before + 1, "one undo step");
+ let style = app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap();
+ let own = serde_json::to_value(&style.para).unwrap();
+ for (k, v) in fields.as_object().unwrap() {
+ assert_eq!(own[k.trim_start_matches("p.")], *v, "the style sets {k}");
+ }
+ app.run("type.selectionAttrs", json!({})).unwrap()["para"].clone()
+ }
+
+ #[test]
+ fn paragraph_style_options_keep_and_border_sections_reach_the_styled_paragraph() {
+ let para = style_section_edit(
+ &["keep", "border"],
+ json!({"p.keepWithNext": 2, "p.keepLinesTogether": true, "p.keepAllLines": false, "p.keepFirst": 3,
+ "p.startParagraph": "nextPage", "p.borderOn": true, "p.borderWeights": [2.0, 0.0, 2.0, 0.0]}),
+ );
+ assert_eq!(para["keepWithNext"], 2);
+ assert_eq!(para["keepLinesTogether"], true);
+ assert_eq!(para["keepAllLines"], false);
+ assert_eq!(para["keepFirst"], 3);
+ assert_eq!(para["startParagraph"], "nextPage");
+ assert_eq!(para["borderOn"], true);
+ assert_eq!(para["borderWeights"], json!([2.0, 0.0, 2.0, 0.0]));
+ // Fields not edited keep the resolved value.
+ assert_eq!(para["keepLast"], 2);
+ assert_eq!(para["ruleBelow"]["weight"], 3.0);
+ }
+
+ #[test]
+ fn paragraph_style_options_bullets_and_span_sections_reach_the_styled_paragraph() {
+ let para = style_section_edit(
+ &["bullets", "span"],
+ json!({"p.listType": "numbers", "p.numberStyle": "upperRoman", "p.numberExpression": "^#)^t", "p.startAt": 3,
+ "p.spanColumns": {"kind": "split", "columns": 3}}),
+ );
+ assert_eq!(para["listType"], "numbers");
+ assert_eq!(para["numberStyle"], "upperRoman");
+ assert_eq!(para["numberExpression"], "^#)^t");
+ assert_eq!(para["startAt"], 3);
+ assert_eq!(para["spanColumns"], json!({"kind": "split", "columns": 3}));
+ let props: designcraft_doc::ParaProps = serde_json::from_value(para).unwrap();
+ assert_eq!(props.number_label(3), "III)\t");
}
- ui.add_space(8.0);
- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Cross-Reference Format")).font(semibold(12.0)));
- let names: Vec<String> = doc.xref_formats.iter().map(|f| f.name.clone()).collect();
- if d.s("format").is_empty() {
- d.fields.insert("format".into(), json!(names.first().cloned().unwrap_or_default()));
+
+ #[test]
+ fn paragraph_style_options_keep_a_bad_grep_pattern_open_with_the_error() {
+ let (mut app, _) = ruled_paragraph();
+ let ctx = egui::Context::default();
+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled", "section": "general"})));
+ draw(&mut app, &ctx);
+ app.ui.dialog.as_mut().unwrap().fields.insert("p.grepStyles".into(), json!([{"style": "[None]", "pattern": "(?<=x"}]));
+ let e = confirm(&mut app).unwrap_err();
+ assert!(e.contains("bad GREP"), "{e}");
+ let d = app.ui.dialog.clone().expect("the dialog stays open");
+ assert_eq!((d.s("section").as_str(), d.s("status").contains("bad GREP")), ("grep", true));
+ assert!(app.session.doc().unwrap().doc.styles.para("Ruled").unwrap().para.grep_styles.is_none(), "nothing saved");
+ draw(&mut app, &ctx);
}
- let opts: Vec<(&str, &str)> = names.iter().map(|n| (n.as_str(), n.as_str())).collect();
- ui.horizontal(|ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Format:"));
- combo(ui, d, "format", &opts);
- });
- if let Some(m) = d.fields.get("status").and_then(Value::as_str) {
- ui.label(egui::RichText::new(m).color(dim));
+
+ /// A frame with two paragraphs of [Basic Paragraph]; the first has a local Word Spacing minimum.
+ fn two_paragraphs() -> (DesignApp, Value) {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 400], "content": "text", "text": "One\nTwo"})).unwrap();
+ app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();
+ app.run("type.para", json!({"attrs": {"wordSpaceMin": 0.7}})).unwrap();
+ (app, r["story"].clone())
}
-}
-/// Color Picker: saturation/brightness field and hue slider, with RGB, CMYK and hex fields.
-fn color_picker(ui: &mut egui::Ui, d: &mut Dialog) {
- let hex = d.s("hex");
- let mut c = designcraft_color::Color::from_hex(&hex).map(|c| c.to_rgb()).map_or(egui::Color32::BLACK, |[r, g, b]| {
- egui::Color32::from_rgb((r * 255.0).round() as u8, (g * 255.0).round() as u8, (b * 255.0).round() as u8)
- });
- let before = c;
- ui.horizontal_top(|ui| {
- egui::color_picker::color_picker_color32(ui, &mut c, egui::color_picker::Alpha::Opaque);
- ui.vertical(|ui| {
- let mut rgb = [c.r() as f32, c.g() as f32, c.b() as f32];
- egui::Grid::new("cp_rgb").num_columns(2).spacing([6.0, 4.0]).show(ui, |ui| {
- for (k, l) in ["R", "G", "B"].iter().enumerate() {
- ui.label(*l);
- ui.add(egui::DragValue::new(&mut rgb[k]).range(0.0..=255.0));
- ui.end_row();
- }
- });
- c = egui::Color32::from_rgb(rgb[0] as u8, rgb[1] as u8, rgb[2] as u8);
- let col = designcraft_color::Color::rgb8(c.r(), c.g(), c.b());
- let [cc, m, y, k] = col.to_cmyk();
- ui.add_space(6.0);
- ui.label(format!("C {:.0}% M {:.0}% Y {:.0}% K {:.0}%", cc * 100.0, m * 100.0, y * 100.0, k * 100.0));
- ui.add_space(6.0);
- ui.horizontal(|ui| {
- ui.label("#");
- let mut h = format!("{:02x}{:02x}{:02x}", c.r(), c.g(), c.b());
- if ui.add(egui::TextEdit::singleline(&mut h).desired_width(70.0)).changed()
- && let Some(n) = designcraft_color::Color::from_hex(&h)
- {
- let [r, g, b] = n.to_rgb();
- c = egui::Color32::from_rgb((r * 255.0).round() as u8, (g * 255.0).round() as u8, (b * 255.0).round() as u8);
- }
- });
+ /// The resolved paragraph attribute `key` of the paragraph at byte `at`.
+ fn para_attr(app: &mut DesignApp, story: &Value, at: usize, key: &str) -> Value {
+ app.run("text.select", json!({"story": story, "anchor": at, "focus": at})).unwrap();
+ app.run("type.selectionAttrs", json!({})).unwrap()["para"][key].clone()
+ }
+
+ #[test]
+ fn justification_dialog_applies_to_a_local_paragraph_and_cancel_changes_nothing() {
+ let (mut app, story) = two_paragraphs();
+ let ctx = egui::Context::default();
+ assert!(crate::menus::menu_enabled(&app, "app.justificationDialog"));
+ app.run("app.justificationDialog", json!({})).unwrap();
+ draw(&mut app, &ctx);
+ let d = app.ui.dialog.clone().unwrap();
+ assert_eq!(d.id, "justification");
+ assert_eq!(d.fields["current"]["wordSpaceMin"], 0.7);
+ assert_eq!(d.fields["current"]["wordSpaceDesired"], 1.0);
+ app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceDesired".into(), json!(1.1));
+ draw(&mut app, &ctx);
+ let before = undo_steps(&app);
+ confirm(&mut app).unwrap();
+ assert_eq!(undo_steps(&app), before + 1, "one undo step");
+ assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceDesired"), 1.1);
+ assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceMin"), 0.7, "unedited fields stay");
+ assert_eq!(para_attr(&mut app, &story, 4, "wordSpaceDesired"), 1.0, "only the selected paragraph");
+ let style = app.session.doc().unwrap().doc.styles.resolve_para_style(designcraft_doc::story::BASIC_PARAGRAPH).0.word_space_desired;
+ assert_eq!(style, 1.0, "the paragraph style keeps its value");
+
+ // Cancel (Escape) leaves the paragraph alone.
+ app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap();
+ app.run("app.justificationDialog", json!({})).unwrap();
+ app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceDesired".into(), json!(1.2));
+ let before = undo_steps(&app);
+ let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
+ let input = egui::RawInput {
+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),
+ events: vec![escape],
+ ..Default::default()
+ };
+ let mut out = ctx.run_ui(input, |ui| {
+ app.logic(&ui.ctx().clone());
+ app.ui(ui);
});
- });
- if c != before {
- d.fields.insert("hex".into(), json!(format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b())));
+ out.textures_delta.clear();
+ assert!(app.ui.dialog.is_none(), "cancelled");
+ assert_eq!(undo_steps(&app), before);
+ assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceDesired"), 1.1);
+
+ app.run("edit.deselectAll", json!({})).unwrap();
+ assert!(!crate::menus::menu_enabled(&app, "app.justificationDialog"), "nothing to justify");
+ assert!(app.run("app.justificationDialog", json!({})).is_err());
}
-}
-/// Find/Replace Font: the document's fonts (missing ones first, flagged) and a replacement.
-fn find_font(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
- // Listed once when the dialog opens (it scans every story).
- if !d.fields.contains_key("_fonts") {
- let list = app.session.execute("font.list", &json!({})).unwrap_or_default();
- d.fields.insert("_fonts".into(), list);
+ #[test]
+ fn justification_dialog_leaves_mixed_fields_alone_and_refuses_bad_values() {
+ let (mut app, story) = two_paragraphs();
+ let ctx = egui::Context::default();
+ app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap();
+ app.run("app.justificationDialog", json!({})).unwrap();
+ draw(&mut app, &ctx);
+ let d = app.ui.dialog.clone().unwrap();
+ assert_eq!(d.fields["current"]["wordSpaceMin"], Value::Null, "mixed shows empty");
+ assert_eq!(d.fields["current"]["wordSpaceMax"], 1.33);
+
+ // Out of range, and minimum above desired: an error, the dialog stays open, nothing changes.
+ let before = undo_steps(&app);
+ for (key, v) in [("wordSpaceMax", 20.0), ("glyphScaleMin", 0.2), ("letterSpaceDesired", f64::NAN)] {
+ app.ui.dialog = Some(d.clone());
+ app.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!(v));
+ assert!(confirm(&mut app).is_err(), "{key} = {v}");
+ assert!(app.ui.dialog.as_ref().is_some_and(|d| d.fields.contains_key("justifyError")), "{key}: the dialog shows why");
+ }
+ app.ui.dialog = Some(d.clone());
+ app.ui.dialog.as_mut().unwrap().fields.insert("letterSpaceMin".into(), json!(0.1));
+ assert!(confirm(&mut app).is_err(), "letter spacing minimum above desired");
+ draw(&mut app, &ctx);
+ assert_eq!(undo_steps(&app), before);
+
+ app.ui.dialog = Some(d);
+ app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceMax".into(), json!(1.5));
+ confirm(&mut app).unwrap();
+ assert_eq!(undo_steps(&app), before + 1);
+ for (at, min) in [(0, 0.7), (4, 0.8)] {
+ assert_eq!(para_attr(&mut app, &story, at, "wordSpaceMax"), 1.5);
+ assert_eq!(para_attr(&mut app, &story, at, "wordSpaceMin"), min, "each paragraph keeps its own minimum");
+ }
}
- let fonts = d.fields.get("_fonts").and_then(Value::as_array).cloned().unwrap_or_default();
- let missing = fonts.iter().filter(|f| f["missing"] == true || f["styleMissing"] == true).count();
- crate::rtl::label(
- ui,
- crate::i18n::tr(&app.ui.language, "Fonts in Document: {count} Missing: {missing}")
- .replace("{count}", &fonts.len().to_string())
- .replace("{missing}", &missing.to_string()),
- );
- egui::ScrollArea::vertical().id_salt("ff_list").max_height(180.0).show(ui, |ui| {
- for f in &fonts {
- let (fam, st) = (f["family"].as_str().unwrap_or(""), f["style"].as_str().unwrap_or(""));
- let warn = f["missing"] == true || f["styleMissing"] == true;
- let label = format!("{}{fam} {st}", if warn { "\u{26A0} " } else { "" });
- let on = d.s("family") == fam && d.s("style") == st;
- let mut text = egui::RichText::new(label);
- if warn {
- text = text.color(egui::Color32::from_rgb(0xe5, 0x4b, 0x4b));
- }
- if ui.selectable_label(on, text).clicked() {
- d.fields.insert("family".into(), json!(fam));
- d.fields.insert("style".into(), json!(st));
+
+ fn command_app(id: &str, fields: Value) -> DesignApp {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.ui.dialog = Some(Dialog::new(&format!("cmd:{id}"), fields));
+ app
+ }
+
+ #[test]
+ fn generic_new_document_preserves_typed_values_and_text_entry() {
+ for pages in [json!(2), json!(" 2 ")] {
+ let mut app = command_app(
+ "file.new",
+ json!({
+ "preset": "A4", "pages": pages, "facingPages": false, "gutter": 0,
+ "margins": {"top": 10, "bottom": 20, "inside": 30, "outside": 40},
+ "title": " ", "status": "internal", "primaryTextFrame": true
+ }),
+ );
+ confirm(&mut app).unwrap();
+ let doc = &app.session.active().unwrap().doc;
+ assert_eq!(doc.page_count(), 2);
+ assert!(!doc.settings.facing_pages);
+ assert!(doc.title.starts_with("Untitled-"));
+ for page in doc.spreads.iter().flat_map(|s| &s.pages) {
+ assert!((page.width - 595.2755905511812).abs() < 0.01);
+ assert!((page.height - 841.8897637795277).abs() < 0.01);
+ assert_eq!(page.columns.gutter, 0.0);
+ assert_eq!(page.margins.top, 10.0);
+ assert_eq!(page.margins.outside, 40.0);
}
+ assert!(doc.spreads.iter().all(|s| s.items.is_empty()), "undocumented fields stay excluded");
+ assert!(app.ui.dialog.is_none());
}
- });
- ui.add_space(8.0);
- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Replace With")).font(semibold(12.0)));
- let db = crate::panels::fonts(app);
- egui::Grid::new("ff_to").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Font Family:"));
- if let Some(f) = crate::panels::font_combo(app, ui, "toFamily", &d.s("toFamily"), 170.0) {
- d.fields.insert("toFamily".into(), json!(f));
+ }
+
+ #[test]
+ fn numbering_commands_document_their_fields() {
+ let names = |id: &str| command_fields(designcraft_engine::find_command(id).unwrap().params).into_iter().map(|f| f.key).collect::<Vec<_>>();
+ assert_eq!(names("layout.section"), ["page", "startNumber", "style", "prefix", "includePrefix", "marker", "remove"]);
+ assert_eq!(names("layout.chapterNumbering"), ["style", "start", "source"]);
+ }
+
+ #[test]
+ fn generic_command_preserves_array_geometry() {
+ let mut app = command_app("file.new", json!({}));
+ confirm(&mut app).unwrap();
+ app.ui.dialog = Some(Dialog::new("cmd:frame.create", json!({"rect": [10, 20, 110, 220]})));
+ confirm(&mut app).unwrap();
+ let doc = &app.session.active().unwrap().doc;
+ let item = doc.spreads.iter().flat_map(|s| &s.items).next().unwrap();
+ assert_eq!(item.bounds(), designcraft_geom::Rect::new(10.0, 20.0, 110.0, 220.0));
+ }
+
+ #[test]
+ fn generic_explicit_null_uses_the_commands_existing_semantics() {
+ // file.new accepts null width by using the selected preset's width.
+ for width in [Value::Null, json!("null")] {
+ let mut app = command_app("file.new", json!({"preset": "A4", "width": width, "title": " Sample layout "}));
+ confirm(&mut app).unwrap();
+ let doc = &app.session.active().unwrap().doc;
+ assert_eq!(doc.title, "Sample layout");
+ assert!((doc.settings.page_width - 595.2755905511812).abs() < 0.01);
}
- ui.end_row();
- let styles = db.styles(&d.s("toFamily"));
- let st_opts: Vec<(&str, &str)> = styles.iter().map(|s| (s.as_str(), s.as_str())).collect();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Font Style:"));
- combo(ui, d, "toStyle", &st_opts);
- ui.end_row();
- });
- ui.label(crate::rtl::widget(
- ui,
- egui::RichText::new(crate::i18n::tr(&app.ui.language, "OK changes all: text and paragraph/character styles."))
- .color(crate::theme::Tokens::get(ui.ctx()).text_dim)
- .size(11.0),
- ));
-}
+ }
-#[cfg(test)]
-mod tests {
- use super::*;
+ #[test]
+ fn generic_invalid_number_retains_dialog_without_creating_document() {
+ let mut app = command_app("file.new", json!({"width": 0}));
+ assert!(confirm(&mut app).is_err());
+ assert!(app.session.active().is_none());
+ let dialog = app.ui.dialog.as_ref().unwrap();
+ assert_eq!(dialog.fields["width"], 0);
+ assert!(dialog.fields["status"].as_str().unwrap().contains("page size out of range"));
+ }
+
+ #[test]
+ fn text_frame_options_change_only_what_was_edited() {
+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap();
+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());
+ app.run("object.textFrameOptions", json!({"ids": [id.0], "columns": 2, "inset": [1, 2, 3, 4]})).unwrap();
+ let opts = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone();
+ let before = opts(&app);
+ let open = |app: &mut DesignApp, fields: &[(&str, Value)]| {
+ app.ui.dialog = Some(Dialog::new("textFrameOptions", json!({})));
+ let mut d = app.ui.dialog.take().unwrap();
+ seed_text_frame_options(app, &mut d);
+ for (k, v) in fields {
+ d.fields.insert((*k).into(), v.clone());
+ }
+ app.ui.dialog = Some(d);
+ confirm(app)
+ };
+ // OK without edits changes nothing (no undo step either).
+ assert_eq!(open(&mut app, &[]).unwrap(), Value::Null);
+ assert_eq!(opts(&app), before);
+ // The rule's weight is in points; unequal insets the user didn't touch stay.
+ open(&mut app, &[("columnRule", json!(true)), ("columnRuleWeight", json!("6"))]).unwrap();
+ let o = opts(&app);
+ assert!(o.column_rule && o.column_rule_weight == 6.0, "{o:?}");
+ assert_eq!((o.inset, o.columns, o.gutter), (before.inset, before.columns, before.gutter));
+ // One of the rule's insets edited: the other rule settings stay.
+ open(&mut app, &[("columnRuleBottomInset", json!("0p9")), ("columnRuleTint", json!("40"))]).unwrap();
+ let o = opts(&app);
+ assert_eq!((o.column_rule_bottom_inset, o.column_rule_top_inset, o.column_rule_offset, o.column_rule_weight), (9.0, 0.0, 0.0, 6.0));
+ assert!((o.column_rule_tint - 0.4).abs() < 1e-6 && o.column_rule);
+ // One inset side edited: the others keep their values.
+ open(&mut app, &[("insetLeft", json!("1p0"))]).unwrap();
+ assert_eq!(opts(&app).inset, [1.0, 12.0, 3.0, 4.0]);
++ open(&mut app, &[("balanceColumns", json!(true))]).unwrap();
++ let o = opts(&app);
++ assert!(o.balance_columns && o.column_rule && o.columns == 2, "{o:?}");
+ // An unknown swatch is an error and the dialog stays open.
+ let e = open(&mut app, &[("columnRuleColor", json!("Mauve"))]).unwrap_err();
+ assert!(e.contains("Mauve") && app.ui.dialog.is_some(), "{e}");
+ assert_eq!(opts(&app).column_rule_color, designcraft_color::swatch::BLACK);
+ // Each OK is one undo step.
- for _ in 0..3 {
++ for _ in 0..4 {
+ app.run("edit.undo", json!({})).unwrap();
+ }
+ assert_eq!(opts(&app), before);
+ }
fn dialog_context(language: &str) -> egui::Context {
let ctx = egui::Context::default();
diff --cc docs/target-app-parity.md
index d7491eac6,4e930bcee..ae6899c0f
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@@ -340,10 -337,10 +340,11 @@@ It is evidence of breadth: each item ex
- Stroke styles: striped (thick-thin… and custom bands), wavy and straight-hash strokes now draw on screen and in PDF; named custom stripe/dash/dot styles (`strokeStyle.new/delete/list`, Stroke panel Type list; IDML Striped/Dashed/DottedStrokeStyle).
- Object ▸ Primary Text Frame (`object.primaryTextFrame`): any text frame's story can become (or stop being) the primary story Smart Text Reflow follows.
- Column rules (Text Frame Options › Column Rules, `object.textFrameOptions {columnRule, columnRuleWeight, columnRuleColor, columnRuleTint, columnRuleOffset, columnRuleTopInset, columnRuleBottomInset}`, reported by `document.inspect`): a bar centred in each gutter of a multi-column frame, inside the insets and between the columns of right-to-left and vertical frames too, broken around paragraphs that span columns, with weight, colour, tint, horizontal offset and top/bottom insets; on screen, in PDF (tagged as an artifact) and in IDML (`ColumnRule…` attributes of `TextFramePreference`, also in object styles). The dialog shows the frame's options and changes only the fields edited. Rule stroke types and overprint aren't there yet.
+- Auto-size (Text Frame Options › Auto-Size, `object.textFrameOptions {autoSize: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference, useMinimumHeight, minimumHeight, useMinimumWidth, minimumWidth, noLineBreaks}`): the frame fits its text exactly after every edit (typing, pasting, style changes, option changes) in the same undo step, and after IDML import; it grows and shrinks around the reference point, which stays put in spread space for rotated frames too, never below the minimum height/width and never past 10,000 pt. Width Only and No Line Breaks set each paragraph on one line; Height and Width without No Line Breaks keeps the width; Keep Proportions scales both sides until the text fits. IDML keeps all the options (`AutoSizing…`, `…ForAutoSizing` attributes). Not covered: frames of a thread other than the last, vertical frames, type on a path, and multi-column balancing in Keep Proportions.
+ - Balance Columns (Text Frame Options › Balance Columns, `object.textFrameOptions {balanceColumns}`, IDML `VerticalBalanceColumns`): in the frame the story ends in, the columns after the last explicit column break fill to about the same depth (the last may be shorter by a line per column); keep options hold, spanning and split paragraphs keep their own balancing, vertical justification then applies to each column as usual, and vertical frames balance their bands. A frame the text runs on from, or that is overset, fills normally.
- Place a page of an IDML or DesignCraft document (`file.place {layoutPage}`): its objects, stories, styles and swatches as one group (INDD files are not readable).
- Articles panel (`article.new/add/remove/options/delete/list`): reading order and content of EPUB and HTML exports.
-- Object ▸ Clipping Path (`object.clippingPath {type: alpha|edges, threshold, tolerance}`): traces the placed image and makes the outline the frame.
+- Object ▸ Clipping Path (`object.clippingPath {type: alpha|edges, threshold, tolerance}`): traces the placed image and makes the outline the frame. Clipping paths saved in IDML (Detect Edges, Alpha Channel, Photoshop Path, User-Modified Path; Invert) hide the image outside the path on screen and in PDF and survive IDML export; `object.clippingPathOptions` reports, inverts or removes one (Object ▸ Clipping Path ▸ None).
- Gridify: arrow keys while dragging a frame or shape tool add columns/rows (`frame.grid`), one undo step.
- Gap tool (U, `gap.move`): drag the space between objects (or an object and the page edge) and both sides resize.
- XML basics (`xml.newTag/deleteTag/tag/mapStyle/structure`, `file.exportXml`, `file.importXml`; Tags panel with structure; View ▸ Show Tagged Frames): tagged frames export in reading order, mapped paragraph styles become elements, imported elements flow into frames with matching tags. Inline text tagging (`xml.tagText`, an `xmlTag` character attribute, exported as nested elements) and tag markers (View ▸ Structure ▸ Show Tag Markers) too. DTDs (`xml.loadDtd`, `xml.validate`, `xml.deleteDtd`; Tags panel): loading one adds its elements as tags and names the root; validation checks content models (sequences, choices, `?*+`, mixed content, EMPTY/ANY, parameter entities) and required attributes, and lists each problem with its element path.