DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Drop caps: the cap style goes through IDML as a Dropcap nested style
aiongg7636af73e430
diff --git a/ROADMAP.md b/ROADMAP.mdindex 201dd6031..b0a3c2f29 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -68,7 +68,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope- Appearance of Black complete: Printing/Exporting rich black for RGB output (PNG), Overprint [Black] Swatch at 100% (document, IDML OverprintBlack).- Hyperlinks and Bookmarks panels (Window ▸ Interactive): new from the selection, edit (`hyperlink.edit`), go to source (`hyperlink.goToSource`), rename bookmarks (`bookmark.rename`), go to page, delete.- Nested line styles (`nestedLineStyles` paragraph attribute, Paragraph Style Options › Drop Caps and Nested Styles, IDML AllNestedLineStyles): the first lines restyle until the line breaks settle.-- Drop caps (`type.para {dropCapLines, dropCapChars, dropCapStyle, dropCapAlignLeft, dropCapScaleDescenders}`, Paragraph panel, Paragraph Style Options › Drop Caps and Nested Styles; IDML DropCapLines/DropCapCharacters/DropcapDetail, DropCapStyle on import): the first characters (code points, as InDesign counts them, never splitting a letter from its combining marks; up to 150) are enlarged from the first line's cap height down to the baseline of line N (up to 25), the lines beside them are indented by their advance (on the right in right-to-left paragraphs), baselines don't move; Align Left Edge (on by default) moves the drop cap left by its first letter's side bearing so its ink starts at the indent; Scale for Descenders is kept but doesn't change the layout yet; a drop cap character style, and nested styles through the drop cap (Dropcap delimiter). Drawn on screen and in PDF (text in order), with caret, hit testing and selection over the enlarged letters. Vertical text sets no drop caps.+- Drop caps (`type.para {dropCapLines, dropCapChars, dropCapStyle, dropCapAlignLeft, dropCapScaleDescenders}`, Paragraph panel, Paragraph Style Options › Drop Caps and Nested Styles; IDML DropCapLines/DropCapCharacters/DropcapDetail, DropCapStyle on import): the first characters (code points, as InDesign counts them, never splitting a letter from its combining marks; up to 150) are enlarged from the first line's cap height down N − 1 leadings of the text after them (up to 25 lines; grid steps on a baseline grid), the lines beside them are indented by their advance (on the right in right-to-left paragraphs), baselines don't move; Align Left Edge (on by default) moves the drop cap left by its first letter's side bearing so its ink starts at the indent; Scale for Descenders is kept but doesn't change the layout yet; a drop cap character style, and nested styles through the drop cap (Dropcap delimiter). Drawn on screen and in PDF (text in order), with caret, hit testing and selection over the enlarged letters. Vertical text sets no drop caps.- User dictionary hyphenation exceptions (`hyphenation.addException/removeException/list`, Edit ▸ Spelling ▸ User Dictionary): `ex~am~ple` breaks only at `~`, a plain word never hyphenates.- Frame Fitting Options (`object.fittingOptions`, Object ▸ Fitting ▸ Frame Fitting Options…): Auto-Fit refits on resize, fitting, Align From reference point, crop amounts; IDML FrameFittingOption.- Paragraph borders (per-side weights, colour, tint, offsets) and shading offsets, drawn per column part of split paragraphs (also when overset); Paragraph panel controls; IDML ParagraphBorder*/ParagraphShading*Offset.diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex 97dbb9e97..d29528529 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -916,9 +916,6 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Clet has_tabs = glyphs.iter().any(|g| g.ch == '\t');let mut first_line_rect: Option<(usize, f64, f64, f64)> = None; // frame, baseline, ascent, x-spanlet rtl = pp.direction == designcraft_doc::TextDirection::RightToLeft;- // The drop cap's line (frame, index) and the baseline it sits on, once that line is set.- let mut drop_line: Option<(usize, usize)> = None;- let mut drop_baseline: Option<f64> = None;loop {if cur.fi >= frames.len() {if let Some(j) = trial_failed(&mut trial, &mut limits, balance_runs < balance_budget) {@@ -1151,15 +1148,6 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Ckeep_violation: false,drop_cap: drop_box,});- if drop_box.is_some() {- drop_line = Some((cur.fi, ft.lines.len() - 1));- }- if let Some(dc) = &drop_cap- && line_no + 1 == dc.lines- && col_first_line == 0- {- drop_baseline = Some(baseline);- }for k in line_notes {notes.place(doc, k, cur.fi, cur.col, col_w, f, opts);}@@ -1197,19 +1185,6 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Cbreak;}}- // The drop cap sits on its last line's baseline as set (it was placed at the leading's).- if let (Some((fi, li)), Some(b), Some(n)) = (drop_line, drop_baseline, drop_cap.as_ref().map(|dc| dc.glyphs.len()))- && let Some(l) = out.frames.get_mut(fi).and_then(|f| f.lines.get_mut(li))- && let Some(dc) = l.drop_cap.as_mut()- {- let d = b - dc.baseline;- dc.baseline = b;- dc.rect.y1 += d;- // Its glyphs start the line.- for g in l.glyphs.iter_mut().take(n) {- g.y += d;- }- }info.push(ParaInfo {start: start_at,at_top,@@ -2884,7 +2859,8 @@ struct DropCap {/// How far its origin sits left of the indent: its first letter's left side bearing with/// Align Left Edge, else 0.lsb: f64,- /// Its baseline below the first line's, at the paragraph's leading.+ /// Its baseline below the first line's: `lines − 1` leadings of the text after it (grid steps+ /// on a baseline grid), wherever line `lines` is set.drop: f64,}diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rsindex 748de241e..06cf04fc0 100644--- a/crates/compose/src/shape.rs+++ b/crates/compose/src/shape.rs@@ -215,11 +215,24 @@ pub(crate) fn shape_para(// Nested line styles lie under nested and GREP styles, and the drop cap's style over them all// (later overlays win).let mut overlays: Vec<(std::ops::Range<usize>, String)> = lines.to_vec();+ // The drop cap's style counts as a leading "through 1 Dropcap" nested style (the form IDML+ // stores it in), so the nested styles after it start after the drop cap.+ let cap_style = Some(drop.1).filter(|s| !s.is_empty() && *s != designcraft_doc::NO_CHAR_STYLE);+ let with_cap: Vec<designcraft_doc::NestedStyle>;+ let nested = match cap_style {+ Some(s) if !nested.is_empty() && !nested.first().is_some_and(designcraft_doc::NestedStyle::is_drop_cap) => {+ with_cap = std::iter::once(designcraft_doc::NestedStyle::drop_cap(s)).chain(nested.iter().cloned()).collect();+ &with_cap[..]+ }+ _ => nested,+ };if !nested.is_empty() || !grep.is_empty() {overlays.extend(crate::overlay::overlays(&story.text, range.clone(), nested, grep, drop.0));}- if drop.0 > range.start && !drop.1.is_empty() && drop.1 != designcraft_doc::NO_CHAR_STYLE {- overlays.push((range.start..drop.0, drop.1.to_string()));+ if let Some(s) = cap_style+ && drop.0 > range.start+ {+ overlays.push((range.start..drop.0, s.to_string()));}// Each run, cut where nested / GREP styles start and end.let mut segments: Vec<(usize, usize, Option<&str>, &designcraft_doc::CharFormat)> = Vec::new();diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rsindex 3d9b7c977..57c5516dd 100644--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@ -2124,8 +2124,9 @@ fn drop_cap_caret_and_hit_testing() {}#[test]-fn drop_cap_sits_on_its_line_as_set() {- // Lines on a 15 pt baseline grid (not the 12 pt leading): the drop cap follows line 3.+fn drop_cap_on_a_baseline_grid_reaches_down_by_grid_steps() {+ // Lines on a 15 pt baseline grid (not the 12 pt leading): the drop cap reaches down two grid+ // steps, to line 3.let (mut d, sid, _) = drop_doc(LOREM, ParaAttrs { grid_align: Some(designcraft_doc::GridAlign::AllLines), ..drop_cap(3, 1) });d.settings.baseline_grid.increment = 15.0;d.settings.baseline_grid.start = 0.0;@@ -2141,6 +2142,28 @@ fn drop_cap_sits_on_its_line_as_set() {assert!((lines[2].baseline - cap_of(dc) - (lines[0].baseline - cap_of(body))).abs() < 0.01);}+/// A line with a larger auto leading doesn't move the drop cap: it reaches down `lines − 1`+/// leadings of the text after it, not to where line N is set.+#[test]+fn drop_cap_reaches_down_by_the_text_leading_past_a_line_with_larger_leading() {+ use designcraft_doc::{CharAttrs, Composer, Leading};+ let text = [LOREM; 2].join(" ");+ let para = ParaAttrs { composer: Some(Composer::SingleLine), ..drop_cap(3, 1) };+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 1000.0), para);+ d.story_mut(sid).unwrap().paras[0].chars = CharAttrs { size: Some(12.0), leading: Some(Leading::Auto), ..Default::default() };+ // A larger word starts line 2, so lines 2 and 3 are set further down than 2 × 14.4 pt.+ let start2 = all_lines(&compose_story(&d, sid, &ComposeOptions::default()))[1].range.start;+ d.story_mut(sid).unwrap().format_chars(start2..start2 + 3, |f| f.over.size = Some(20.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines[1].range.start, start2);+ assert!(lines[2].baseline - lines[0].baseline > 2.0 * 14.4 + 5.0, "{} {}", lines[0].baseline, lines[2].baseline);+ let dc = &lines[0].glyphs[0];+ assert!((dc.y - 2.0 * 14.4).abs() < 1e-6, "drop cap baseline {} below line 1", dc.y);+ let b = lines[0].drop_cap.unwrap();+ assert!((b.baseline - (lines[0].baseline + 2.0 * 14.4)).abs() < 1e-6, "{}", b.baseline);+}+/// A rule in Text Color takes the colour of the paragraph's text: the first character's for the/// rule above, the last character's for the rule below. A swatch colour is used as is.#[test]diff --git a/crates/doc/src/attrs.rs b/crates/doc/src/attrs.rsindex 5f0d518ff..7215c156e 100644--- a/crates/doc/src/attrs.rs+++ b/crates/doc/src/attrs.rs@@ -469,6 +469,18 @@ impl Default for NestedStyle {}}+impl NestedStyle {+ /// The drop cap's character style as a nested style: `style` through 1 drop cap.+ pub fn drop_cap(style: &str) -> Self {+ NestedStyle { style: style.into(), through: true, count: 1, until: NestedUntil::Dropcap }+ }++ /// Is this the form a drop cap's character style takes at the start of a nested style list?+ pub fn is_drop_cap(&self) -> bool {+ self.until == NestedUntil::Dropcap && self.through && self.count == 1+ }+}+/// A character style applied to every match of a regular expression in the paragraph.#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", default)]diff --git a/crates/engine/src/tests_idml.rs b/crates/engine/src/tests_idml.rsindex b3d1ef566..f16d3efc2 100644--- a/crates/engine/src/tests_idml.rs+++ b/crates/engine/src/tests_idml.rs@@ -359,6 +359,7 @@ fn type_para_sets_a_drop_cap_that_survives_idml() {let back = designcraft_idml::import_idml(&designcraft_idml::export_idml(&d)).unwrap();let p = &back.stories.values().find(|st| st.text.starts_with("Once")).unwrap().paras[0].para;assert_eq!((p.drop_cap_lines, p.drop_cap_chars, p.drop_cap_align_left), (Some(3), Some(1), Some(false)));- // IDML has no attribute for the drop cap's character style.- assert_eq!(p.drop_cap_style, None);+ // The drop cap's character style goes through IDML as a leading Dropcap nested style.+ assert_eq!(p.drop_cap_style.as_deref(), Some("Initial"));+ assert_eq!(p.nested_styles, Some(vec![designcraft_doc::NestedStyle::drop_cap("Initial")]));}diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rsindex 0bbf2db93..67ab22f28 100644--- a/crates/idml/src/export.rs+++ b/crates/idml/src/export.rs@@ -1285,10 +1285,19 @@ impl<'a> Ex<'a> {None => el.set("NumberingContinue", "true"),}}- // Nested and GREP styles: property lists of records.- if let Some(list) = &a.nested_styles {+ // Nested and GREP styles: property lists of records. The drop cap's character style is the+ // nested style list's leading "through 1 Dropcap" entry (IDML has no attribute for it).+ let cap_style = a.drop_cap_style.as_deref().filter(|s| !s.is_empty() && *s != st::NO_CHAR_STYLE);+ if a.nested_styles.is_some() || cap_style.is_some() {+ let mut list = a.nested_styles.clone().unwrap_or_default();+ if let Some(s) = cap_style {+ match list.first_mut() {+ Some(ns) if ns.is_drop_cap() => ns.style = s.to_string(),+ _ => list.insert(0, designcraft_doc::NestedStyle::drop_cap(s)),+ }+ }let mut l = El::new("AllNestedStyles").attr("type", "list");- for ns in list {+ for ns in &list {let (ty, delim) = names::nested_until_out(&ns.until);l = l.child(El::new("ListItem")@@ -1370,8 +1379,6 @@ impl<'a> Ex<'a> {n!(space_after, "SpaceAfter");n!(drop_cap_lines, "DropCapLines");n!(drop_cap_chars, "DropCapCharacters");- // The drop cap's character style isn't written: IDML has no attribute for it (InDesign- // applies one through a Dropcap nested style).if a.drop_cap_align_left.is_some() || a.drop_cap_scale_descenders.is_some() {let d = designcraft_doc::ParaProps::default();let bits = u32::from(a.drop_cap_align_left.unwrap_or(d.drop_cap_align_left))diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rsindex 34cdeb836..4dbcbb705 100644--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@ -1255,6 +1255,9 @@ impl<'r> Importer<'r> {}}).collect();+ // IDML has no drop cap style attribute: the drop cap's character style is the list's+ // leading "through 1 Dropcap" nested style.+ a.drop_cap_style = v.first().filter(|ns| ns.is_drop_cap()).map(|ns| ns.style.clone());a.nested_styles = Some(v);}if let Some(l) = e.prop_el("AllNestedLineStyles") {@@ -1283,7 +1286,6 @@ impl<'r> Importer<'r> {a.space_after = e.num("SpaceAfter");a.drop_cap_lines = u("DropCapLines");a.drop_cap_chars = u("DropCapCharacters");- a.drop_cap_style = e.prop("DropCapStyle").map(|r| self.char_style_ref(r.trim()));// DropcapDetail bits: 1 = Align Left Edge, 2 = Scale for Descenders.if let Some(v) = e.num("DropcapDetail").filter(|v| v.is_finite() && *v >= 0.0) {let bits = v as u32;diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rsindex 4afe19ca4..88a7d7bc3 100644--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@ -1784,12 +1784,13 @@ fn absent_item_and_document_attributes_take_indesign_defaults() {}}+/// IDML has no attribute for a drop cap's character style: it is the nested style list's leading+/// "through 1 Dropcap" entry, read into the drop cap style and written back from it.#[test]fn drop_caps_import_and_round_trip() {- // A style with a drop cap, its character style and a nested style through it; a paragraph- // overriding it locally.+ // A style with a drop cap and its character style; a paragraph overriding both locally.let opener = r#"<ParagraphStyle Self="ParagraphStyle/Opener" Name="Opener" DropCapCharacters="1" DropCapLines="3">- <Properties><DropCapStyle type="object">CharacterStyle/Strong</DropCapStyle><AllNestedStyles type="list"><ListItem type="record">+ <Properties><AllNestedStyles type="list"><ListItem type="record"><AppliedCharacterStyle type="object">CharacterStyle/Strong</AppliedCharacterStyle><Delimiter type="enumeration">Dropcap</Delimiter><Repetition type="long">1</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles></Properties></ParagraphStyle>@@ -1798,7 +1799,10 @@ fn drop_caps_import_and_round_trip() {let story = r#"<?xml version="1.0" encoding="UTF-8"?><idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0"><Story Self="s1">- <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener" DropCapCharacters="2" DropCapLines="2" DropCapStyle="CharacterStyle/$ID/[No character style]">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener" DropCapCharacters="2" DropCapLines="2">+ <Properties><AllNestedStyles type="list"><ListItem type="record">+ <AppliedCharacterStyle type="object">CharacterStyle/$ID/[No character style]</AppliedCharacterStyle><Delimiter type="enumeration">Dropcap</Delimiter>+ <Repetition type="long">1</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles></Properties><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Once upon a time</Content></CharacterStyleRange></ParagraphStyleRange></Story>@@ -1816,18 +1820,21 @@ fn drop_caps_import_and_round_trip() {let st = d.styles.para("Opener").unwrap();assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines), (Some(1), Some(3)));assert_eq!(st.para.drop_cap_style.as_deref(), Some("Strong"));- let ns = st.para.nested_styles.clone().unwrap();- assert_eq!((ns[0].style.as_str(), &ns[0].until), ("Strong", &designcraft_doc::NestedUntil::Dropcap));+ assert_eq!(st.para.nested_styles, Some(vec![designcraft_doc::NestedStyle::drop_cap("Strong")]), "one entry, not duplicated");let p = &d.stories.values().find(|s| s.text.starts_with("Once")).unwrap().paras[0];assert_eq!((p.para.drop_cap_chars, p.para.drop_cap_lines), (Some(2), Some(2)));assert_eq!(p.para.drop_cap_style.as_deref(), Some(st::NO_CHAR_STYLE));};let d = import_idml_with(&bytes, &|_| None).unwrap();check(&d);- // The drop cap's character style isn't written to IDML (InDesign sets it through a Dropcap- // nested style); Align Left Edge and Scale for Descenders are, as DropcapDetail.+ let bytes = export_idml(&d);+ assert!(!zip_text(&bytes, "").contains("DropCapStyle"), "not an IDML attribute");+ check(&import_idml(&bytes).unwrap());+ // A drop cap style set without nested styles is written as one; Align Left Edge and Scale for+ // Descenders as DropcapDetail.let mut d = d;if let Some(s) = d.styles_mut().para_mut("Opener") {+ s.para.nested_styles = None;s.para.drop_cap_align_left = Some(false);s.para.drop_cap_scale_descenders = Some(true);}@@ -1836,9 +1843,9 @@ fn drop_caps_import_and_round_trip() {assert!(zip_text(&bytes, "Resources/Styles.xml").contains(r#"DropcapDetail="2""#));let back = import_idml(&bytes).unwrap();let st = back.styles.para("Opener").unwrap();- assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines, st.para.drop_cap_style.as_deref()), (Some(1), Some(3), None));+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines, st.para.drop_cap_style.as_deref()), (Some(1), Some(3), Some("Strong")));assert_eq!((st.para.drop_cap_align_left, st.para.drop_cap_scale_descenders), (Some(false), Some(true)));- assert_eq!(st.para.nested_styles.as_ref().map(|n| n[0].until.clone()), Some(designcraft_doc::NestedUntil::Dropcap));+ assert_eq!(st.para.nested_styles, Some(vec![designcraft_doc::NestedStyle::drop_cap("Strong")]));}/// Frames take the corners and Text Frame Options they don't write from their object style chain,