DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Story Optical Margin Alignment with a size, and Ignore Optical Margin (Story panel, engine and IDML) (#1705)
aiongg5def4a8c01a1
diff --git a/ROADMAP.md b/ROADMAP.mdindex 3eff9dc1c..9299837ae 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -358,6 +358,8 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.mNewest first.+- **2026-10-24** · Story panel (Window › Type & Tables › Story): Optical Margin Alignment and its size for the stories of the text selection or the selected text frames, disabled without either; `type.selectionAttrs` reports them as `storyOptions`, null where the stories differ. The Paragraph panel menu has Ignore Optical Margin in place of the per-paragraph Optical Margin Alignment switch, which stays in `type.para`, and Paragraph Style Options › Indents and Spacing has Ignore Optical Margin (#947). No readiness percentage change.+- **2026-10-24** · Optical Margin Alignment per story with a size (`story.options {opticalMargin, opticalMarginSize}`, off by default): when it is on, the story's paragraphs hang punctuation and letter edges by amounts set for that type size, except paragraphs with Ignore Optical Margin (`ignoreOpticalMargin` in `type.para` and paragraph styles). Table cells and footnotes don't take the story setting yet. When it is off, the per-paragraph switch still hangs at the text's own size. IDML imports and exports both (`StoryPreference/@OpticalMarginAlignment`, `@OpticalMarginSize`, `IgnoreEdgeAlignment`) (#947). No readiness percentage change.- **2026-10-24** · Text frames: a custom baseline grid's Relative To (Text Frame Options › Baseline Options, `object.textFrameOptions {baselineGrid: {relativeTo}}`, IDML `BaselineFrameGridRelativeOption`) measures the grid's start from the top of the page, the top margin, the top of the frame or its top inset. Text Frame Options had no custom baseline grid controls, imports dropped the setting and every frame grid started from the page top, so grid-aligned text in a frame measured from its own top sat on the wrong lines. No readiness percentage change.- **2026-10-24** · Paragraph Style Options › Indents and Spacing has an Align to Grid menu: None, All Lines or First Line Only. It shows the style's current setting. A First Line Only style could be set only in the CJK Grid Settings section, which shows only with CJK features on, or through commands. No readiness percentage change.- **2026-10-24** · Anchored text frames, such as marginal notes, compose where their host story places them: they align to the baseline grid at that position, and page-number markers and spine-relative alignment inside them read the host's page. They composed against a grid measured from their stored position and on no page, so a note set to Only Align First Line to Grid could sit a fraction of a line off the body text's grid line. No readiness percentage change.diff --git a/crates/compose/src/breaker.rs b/crates/compose/src/breaker.rsindex 85b3a0dc2..08027f379 100644--- a/crates/compose/src/breaker.rs+++ b/crates/compose/src/breaker.rs@@ -48,6 +48,9 @@ pub struct Spacing {pub hyph_zone: f64,/// Optical margin alignment: punctuation hangs outside the measure (counted as extra width).pub optical: bool,+ /// The type size the hang amounts are set for (Story ▸ Optical Margin Alignment's size);+ /// `None`: each glyph's own size, so the hang is [`hang`]'s proportion of its advance.+ pub optical_size: Option<f64>,/// Korean text breaks between syllables instead of at spaces.pub korean_char_breaks: bool,/// 0: minimum adjustment; 1: push in; 2: push out first; 3: push out only.@@ -72,6 +75,7 @@ impl Default for Spacing {ragged_stretch: 24.0,hyph_zone: 0.0,optical: false,+ optical_size: None,korean_char_breaks: false,kinsoku_priority: 0,}@@ -318,16 +322,32 @@ pub fn hang(c: char) -> (f64, f64) {}}-fn hang_left(g: &Glyph) -> f64 {- hang(g.ch).0 * g.adv+/// How much more than [`hang`]'s proportions `g` hangs: the hang is set for+/// [`Spacing::optical_size`] and grows with it, relative to the glyph's own size.+pub(crate) fn optical_scale(g: &Glyph, sp: &Spacing) -> f64 {+ match sp.optical_size {+ Some(s) if s.is_finite() && g.size.is_finite() && g.size > 0.0 => s / g.size,+ _ => 1.0,+ }+}++/// Optical hang of `g` at the start of a line (0 without optical margin alignment).+pub(crate) fn hang_left(g: &Glyph, sp: &Spacing) -> f64 {+ if sp.optical { hang(g.ch).0 * g.adv * optical_scale(g, sp) } else { 0.0 }+}++/// Optical hang of `g` at the end of a line (0 without optical margin alignment).+pub(crate) fn hang_right(g: &Glyph, sp: &Spacing) -> f64 {+ if sp.optical { hang(g.ch).1 * g.adv * optical_scale(g, sp) } else { 0.0 }}fn right_hang(g: &Glyph, sp: &Spacing) -> f64 {- g.cjk_hang.max(if sp.optical { hang_right(g) } else { 0.0 }) - g.moji.end+ g.cjk_hang.max(hang_right(g, sp)) - g.moji.end}-fn hang_right(g: &Glyph) -> f64 {- hang(g.ch).1 * g.adv+/// The part of a hyphen after `g` (of width `hw`) that hangs past the line's end.+fn hyphen_hang(g: &Glyph, hw: f64, sp: &Spacing) -> f64 {+ if sp.optical { hw * hang('-').1 * optical_scale(g, sp) } else { 0.0 }}/// Advance of the hyphen glyph that would follow `g` (cached per face).@@ -428,15 +448,13 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &Slet mut p = Item::penalty(hw, sp.hyphen_penalty, true);p.auto = true;p.zone_from = last_space;- if sp.optical {- p.hang = hw * hang('-').1;- }+ p.hang = hyphen_hang(g, hw, sp);push_inword(&mut it, &mut ig, p, i + 1, sp);continue;}let (st, sh) = sp.box_elastic(g);let mut bx = Item::boxed(g.adv, st, sh);- bx.hang = (if sp.optical { hang_left(g) } else { 0.0 }) - g.moji.start;+ bx.hang = hang_left(g, sp) - g.moji.start;bx.start_elastic = crate::mojikumi::start_elastic(g, sp.justify, sp.kinsoku_priority != 3);it.push(bx);ig.push(i);@@ -457,9 +475,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &Slet mut p = Item::penalty(hw, sp.hyphen_penalty, true);p.auto = true;p.zone_from = last_space;- if sp.optical {- p.hang = hw * hang('-').1;- }+ p.hang = hyphen_hang(g, hw, sp);push_inword(&mut it, &mut ig, p, i + 1, sp);} else if emergency_after.get(i) == Some(&true) {let mut p = Item::penalty(0.0, EMERGENCY_PENALTY, false);@@ -876,7 +892,7 @@ pub fn greedy(let may_hyphenate = |hyphens: u32| sp.hyphen_limit == 0 || hyphens < sp.hyphen_limit;while start < n {let w = width(line).max(1.0);- let mut x = (if sp.optical { -hang_left(&glyphs[start]) } else { 0.0 }) + glyphs[start].moji.start;+ let mut x = -hang_left(&glyphs[start], sp) + glyphs[start].moji.start;let mut shrink = crate::mojikumi::start_elastic(&glyphs[start], sp.justify, sp.kinsoku_priority != 3)[1];let mut last_natural: Option<(usize, bool)> = None;let mut last_ok: Option<(usize, bool)> = None; // (break position = end glyph, hyphen)@@ -939,7 +955,8 @@ pub fn greedy(last_natural = last_ok;}} else if hyph_after[i] && may_hyphenate(hyphens) {- let hy = hyphen_width(g, &mut hy_cache) * if sp.optical { 1.0 - hang('-').1 } else { 1.0 };+ let hw = hyphen_width(g, &mut hy_cache);+ let hy = (hw - hyphen_hang(g, hw, sp)).max(0.0);if x + hy <= w + shrink + FIT_EPS {last_ok = Some((i + 1, true));}diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex 687f4c7ea..22a545003 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -1136,7 +1136,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Clet cols_here = &cols[cur.fi];let col = span_rect(cols_here, cols_here[cur.col.min(cols_here.len() - 1)], pp.span_columns);let col = SplitCfg::of(&pp).map_or(col, |c| c.sub_rect(col, 0));- let spacing = spacing_for(&pp, base_chars.size);+ let spacing = spacing_for(&pp, base_chars.size, story);let mut lines: Vec<(std::ops::Range<usize>, String)> = Vec::new();for _ in 0..3 {// The same drop cap, spacing, hyphenation and breaker as the layout below.@@ -1292,7 +1292,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Chyphenation_points(&story.text, &glyphs, &pp, &hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), &base_chars));suppress_hyphens(&mut hyph_after, &glyphs, no_hyph.get(pi).map_or(&[], Vec::as_slice));let base_size = base_chars.size;- let spacing = spacing_for(&pp, base_size);+ let spacing = spacing_for(&pp, base_size, story);// An empty paragraph takes its height from its paragraph mark's character format.let mark_chars = if glyphs.is_empty() {std::borrow::Cow::Owned(doc.styles.resolve_char(&base_chars, story.char_format_of(prange.start)))@@ -2303,8 +2303,22 @@ pub fn column_rule_rects(columns: &[Rect], lines: &[Line], opts: &TextFrameOptioout}+/// Optical margin alignment for a paragraph of `story`: (on, the size the hang is set for).+/// Ignore Optical Margin turns it off; the story's setting, when on, applies to every other+/// paragraph; otherwise the paragraph's own switch hangs at each glyph's own size.+fn optical_for(pp: &ParaProps, story: &Story) -> (bool, Option<f64>) {+ if pp.ignore_optical_margin {+ return (false, None);+ }+ match story.optical_margin.hang_size() {+ Some(size) => (true, Some(size)),+ None => (pp.optical_margin, None),+ }+}+/// Breaker parameters from the paragraph's settings.-fn spacing_for(pp: &ParaProps, base_size: f64) -> Spacing {+fn spacing_for(pp: &ParaProps, base_size: f64, story: &Story) -> Spacing {+ let (optical, optical_size) = optical_for(pp, story);Spacing {justify: pp.align.is_justified(),word_min: pp.word_space_min,@@ -2322,7 +2336,8 @@ fn spacing_for(pp: &ParaProps, base_size: f64) -> Spacing {// The zone is the Single-line Composer's (unjustified text only), as in InDesign: the// Paragraph Composer weighs every break of the paragraph instead.hyph_zone: if pp.align.is_justified() || !pp.composer.single_line() { 0.0 } else { pp.hyph_zone },- optical: pp.optical_margin,+ optical,+ optical_size,korean_char_breaks: pp.korean_char_breaks,kinsoku_priority: match pp.kinsoku_type.as_str() {"KinsokuPushInFirst" => 1,@@ -3448,8 +3463,8 @@ fn layout_line(if (sp.optical || pp.kinsoku_hang != designcraft_doc::cjk::KinsokuHang::None) && !has_tab {let first = line.iter().find(|g| g.adv > 0.0 && !g.is_space());let lastg = line.iter().rev().find(|g| g.adv > 0.0 && !g.is_space());- let hl = if sp.optical { first.map_or(0.0, |g| breaker::hang(g.ch).0 * g.adv) } else { 0.0 };- let optical_right = if sp.optical { lastg.map_or(0.0, |g| breaker::hang(g.ch).1 * g.adv) } else { 0.0 };+ let hl = first.map_or(0.0, |g| breaker::hang_left(g, sp));+ let optical_right = lastg.map_or(0.0, |g| breaker::hang_right(g, sp));let cjk_right = lastg.map_or(0.0, |g| g.cjk_hang);let cjk_right = if pp.kinsoku_hang == designcraft_doc::cjk::KinsokuHang::Regular {cjk_right.min((line.iter().map(|g| g.adv).sum::<f64>() - measure).max(0.0))diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rsindex cd4783520..90b4ac3c4 100644--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@ -1358,6 +1358,56 @@ fn optical_margin_hangs_punctuation() {assert!(lines.iter().all(|l| l.end_x <= l.x1 + 12.0));}+/// How far the opening quote of a one-line paragraph at `text_size` hangs into the left margin,+/// with the story's Optical Margin Alignment `story` (on, size) and the paragraph's attributes.+fn quote_hang(text_size: f64, story: Option<f64>, para: ParaAttrs) -> f64 {+ let text = "“Quoted” words.";+ let first_x = |story: Option<f64>, para: ParaAttrs| {+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 400.0, 200.0), para);+ let st = d.story_mut(sid).unwrap();+ st.format_chars(0..text.len(), |f| f.over.size = Some(text_size));+ if let Some(size) = story {+ st.optical_margin = designcraft_doc::OpticalMargin { on: true, size };+ }+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 1);+ lines[0].glyphs[0].x+ };+ first_x(None, ParaAttrs::default()) - first_x(story, para)+}++#[test]+fn story_optical_margin_hang_scales_with_its_size() {+ let at12 = quote_hang(12.0, Some(12.0), ParaAttrs::default());+ let at24 = quote_hang(12.0, Some(24.0), ParaAttrs::default());+ assert!(at12 > 1.0, "{at12}");+ assert!((at24 - 2.0 * at12).abs() < 0.01, "{at12} {at24}");+ // The size is the type size the hang is set for: 24 pt text at 24 hangs like 12 at 12, twice as far.+ let big = quote_hang(24.0, Some(24.0), ParaAttrs::default());+ assert!((big - 2.0 * at12).abs() < 0.01, "{at12} {big}");+}++#[test]+fn ignore_optical_margin_paragraph_does_not_hang() {+ let ignored = ParaAttrs { ignore_optical_margin: Some(true), optical_margin: Some(true), ..Default::default() };+ assert_eq!(quote_hang(12.0, Some(12.0), ignored.clone()), 0.0);+ assert_eq!(quote_hang(12.0, None, ignored), 0.0);+}++#[test]+fn paragraph_optical_margin_hangs_at_the_text_size() {+ // Documents saved before the story setting existed: the paragraph's switch hangs each+ // character by its own size, not the story's default 12 pt.+ let own = ParaAttrs { optical_margin: Some(true), ..Default::default() };+ let at24 = quote_hang(24.0, None, own.clone());+ assert!((at24 - quote_hang(24.0, Some(24.0), ParaAttrs::default())).abs() < 0.01);+ assert!((at24 - 2.0 * quote_hang(12.0, None, own)).abs() < 0.01);+ // The story setting, when on, sets the size.+ let story = quote_hang(24.0, Some(12.0), ParaAttrs { optical_margin: Some(true), ..Default::default() });+ assert!((story - at24 / 2.0).abs() < 0.01, "{story} {at24}");+}+// ---------- golden paragraph corpus ----------/// Original prose (written for this corpus) with a realistic mix of short and long words.diff --git a/crates/doc/src/attrs.rs b/crates/doc/src/attrs.rsindex fa7cffc68..587a00280 100644--- a/crates/doc/src/attrs.rs+++ b/crates/doc/src/attrs.rs@@ -1274,7 +1274,13 @@ attr_set! {/// again with the list (an indent the paragraph had before stays).list_hang: bool = false,balance_ragged: bool = false,+ /// Hang punctuation outside the measure in this paragraph, at each character's own size+ /// (DesignCraft's own per-paragraph switch; a story with Optical Margin Alignment on+ /// overrides it with the story's size).optical_margin: bool = false,+ /// Ignore Optical Margin: no hang in this paragraph, whatever the story or+ /// `optical_margin` say.+ ignore_optical_margin: bool = false,/// None uses the legacy built-in rules; an empty set explicitly disables kinsoku.kinsoku: Option<crate::cjk::Kinsoku> = None => "deserialize_explicit_value",/// Preserved spacing-table reference; compatibility audit reports unsupported composition.diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rsindex 43b65144a..53308e1b8 100644--- a/crates/doc/src/edit.rs+++ b/crates/doc/src/edit.rs@@ -318,15 +318,16 @@ impl Document {let pos_to = other.frames.iter().position(|f| *f == to).unwrap_or(0);let after = other.frames.split_off(pos_to);let before = std::mem::take(&mut other.frames);- let (vertical, direction) = (other.vertical, other.direction);+ let (vertical, direction, optical_margin) = (other.vertical, other.direction, other.optical_margin);let offset;{let st = self.story_mut(fs).ok_or(DocError::NoStory(fs))?;offset = if st.text.is_empty() { 0 } else { st.text.len().saturating_add(1) };- // The story keeps its own direction, even when it was empty and takes the other's text.- let own = (st.vertical, st.direction);+ // The story keeps its own direction and options, even when it was empty and takes the+ // other's text.+ let own = (st.vertical, st.direction, st.optical_margin);st.append_story(other);- (st.vertical, st.direction) = own;+ (st.vertical, st.direction, st.optical_margin) = own;let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);for (k, f) in after.iter().enumerate() {st.frames.insert(at + k, *f);@@ -345,6 +346,7 @@ impl Document {ns.frames = before.clone();ns.vertical = vertical;ns.direction = direction;+ ns.optical_margin = optical_margin;for f in &before {if let Some(t) = self.item_mut(*f).and_then(Item::text_frame_mut) {t.story = nid;@@ -526,12 +528,12 @@ impl Document {/// stays with the first part and may become overset).pub fn unthread_after(&mut self, frame: ItemId) -> Result<()> {let sid = self.item(frame).and_then(|i| i.text_frame()).map(|t| t.story).ok_or(DocError::NoItem(frame))?;- let (tail, vertical, direction) = {+ let (tail, vertical, direction, optical_margin) = {let st = self.story_mut(sid).ok_or(DocError::NoStory(sid))?;let p = st.frames.iter().position(|f| *f == frame).ok_or(DocError::NoItem(frame))?;let tail = st.frames.split_off(p + 1);st.rev = st.rev.wrapping_add(1);- (tail, st.vertical, st.direction)+ (tail, st.vertical, st.direction, st.optical_margin)};if tail.is_empty() {return Ok(());@@ -541,6 +543,7 @@ impl Document {ns.frames = tail.clone();ns.vertical = vertical;ns.direction = direction;+ ns.optical_margin = optical_margin;self.stories.insert(nid, Arc::new(ns));for f in tail {if let Some(t) = self.item_mut(f).and_then(Item::text_frame_mut) {@@ -554,20 +557,21 @@ impl Document {/// `frame` stays on the page with a new empty story.pub fn remove_from_thread(&mut self, frame: ItemId) -> Result<()> {let sid = self.item(frame).and_then(|i| i.text_frame()).map(|t| t.story).ok_or(DocError::NoItem(frame))?;- let (vertical, direction) = {+ let (vertical, direction, optical_margin) = {let st = self.story_mut(sid).ok_or(DocError::NoStory(sid))?;if st.frames.len() < 2 {return Err(DocError::Invalid(format!("frame {frame} is not threaded to another frame")));}st.frames.retain(|f| *f != frame);st.rev = st.rev.wrapping_add(1);- (st.vertical, st.direction)+ (st.vertical, st.direction, st.optical_margin)};let nid = StoryId(self.alloc());let mut ns = Story::new(nid);ns.frames = vec![frame];ns.vertical = vertical;ns.direction = direction;+ ns.optical_margin = optical_margin;self.stories.insert(nid, Arc::new(ns));let t = self.item_mut(frame).and_then(Item::text_frame_mut).ok_or(DocError::NoItem(frame))?;t.story = nid;diff --git a/crates/doc/src/story.rs b/crates/doc/src/story.rsindex e3a0e39ee..05adcb35f 100644--- a/crates/doc/src/story.rs+++ b/crates/doc/src/story.rs@@ -125,6 +125,9 @@ pub struct Story {/// right to left, in every frame of the thread.#[serde(default, skip_serializing_if = "std::ops::Not::not")]pub vertical: bool,+ /// Story ▸ Optical Margin Alignment.+ #[serde(default, skip_serializing_if = "OpticalMargin::is_default")]+ pub optical_margin: OpticalMargin,/// Bumped on every edit (composition cache key).#[serde(default)]pub rev: u64,@@ -160,6 +163,45 @@ pub struct Story {pub file_link: Option<TextFileLink>,}+/// Story ▸ Optical Margin Alignment: punctuation and the edges of some letters hang outside the+/// frame's edges, in every paragraph of the story except those with Ignore Optical Margin.+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct OpticalMargin {+ pub on: bool,+ /// The type size (points) the hang amounts are set for: text of this size hangs by the+ /// built-in proportions of each character's advance, and the hang grows with this size.+ pub size: f64,+}++impl Default for OpticalMargin {+ fn default() -> Self {+ OpticalMargin { on: false, size: Self::DEFAULT_SIZE }+ }+}++impl OpticalMargin {+ pub const DEFAULT_SIZE: f64 = 12.0;+ /// InDesign's range for the size.+ pub const MIN_SIZE: f64 = 0.1;+ pub const MAX_SIZE: f64 = 1296.0;++ /// `v` clamped to the size range, or `None` when it isn't a finite number.+ pub fn clamp_size(v: f64) -> Option<f64> {+ v.is_finite().then(|| v.clamp(Self::MIN_SIZE, Self::MAX_SIZE))+ }++ /// The size the story's text hangs for, when the setting is on (a stored size outside the+ /// range is clamped, a non-finite one reads as the default).+ pub fn hang_size(&self) -> Option<f64> {+ self.on.then(|| Self::clamp_size(self.size).unwrap_or(Self::DEFAULT_SIZE))+ }++ pub fn is_default(&self) -> bool {+ *self == Self::default()+ }+}+/// A linked text file: where a placed story came from, what the file held, and the Word Import/// Options that brought it in, so Update Link can import it again the same way.#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]@@ -201,6 +243,7 @@ impl Story {frames: vec![],direction: crate::TextDirection::LeftToRight,vertical: false,+ optical_margin: OpticalMargin::default(),rev: 0,tables: BTreeMap::new(),notes: Vec::new(),@@ -596,6 +639,22 @@ mod tests {Story::with_text(StoryId(1), t, ParaFormat::default())}+ #[test]+ fn optical_margin_is_optional_in_saved_stories() {+ let plain = serde_json::to_value(st("Text")).unwrap();+ assert!(plain.get("opticalMargin").is_none());+ let old: Story = serde_json::from_value(plain).unwrap();+ assert_eq!(old.optical_margin, OpticalMargin { on: false, size: 12.0 });+ let mut s = st("Text");+ s.optical_margin = OpticalMargin { on: true, size: 18.0 };+ let back: Story = serde_json::from_value(serde_json::to_value(&s).unwrap()).unwrap();+ assert_eq!(back.optical_margin, s.optical_margin);+ // A hostile stored size is clamped where it is used.+ assert_eq!(OpticalMargin { on: true, size: 1e9 }.hang_size(), Some(OpticalMargin::MAX_SIZE));+ assert_eq!(OpticalMargin { on: true, size: -3.0 }.hang_size(), Some(OpticalMargin::MIN_SIZE));+ assert_eq!(OpticalMargin { on: false, size: 18.0 }.hang_size(), None);+ }+#[test]fn paragraphs_track_newlines() {let mut s = st("one\ntwo");diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rsindex d1bd06ad0..ab24a05d8 100644--- a/crates/engine/src/cmd/style.rs+++ b/crates/engine/src/cmd/style.rs@@ -302,7 +302,7 @@ pub fn specs() -> Vec<CommandSpec> {"New Paragraph Style…",[],None,- "{name, basedOn?, nextStyle?, para?: {paragraph attributes, as type.para names them: align, leftIndent, firstLineIndent, spaceBefore, spaceAfter, …; startAt?: null = continue numbering; grepStyles?: [{style, pattern}]: a pattern that can't compile is an error}, chars?: {character attributes, as type.char names them: fontFamily, fontStyle, size, leading, tracking, fill, …}, fromSelection?: bool}",+ "{name, basedOn?, nextStyle?, para?: {paragraph attributes, as type.para names them: align, leftIndent, firstLineIndent, spaceBefore, spaceAfter, ignoreOpticalMargin, …; startAt?: null = continue numbering; grepStyles?: [{style, pattern}]: a pattern that can't compile is an error}, chars?: {character attributes, as type.char names them: fontFamily, fontStyle, size, leading, tracking, fill, …}, fromSelection?: bool}",has_doc,create_para),@@ -311,7 +311,7 @@ pub fn specs() -> Vec<CommandSpec> {"Paragraph Style Options…",[],None,- "{name, rename?, basedOn?, nextStyle?, para?: {paragraph attributes, as type.para names them: align, leftIndent, spaceBefore, …; ruleAbove?/ruleBelow?: only the named rule fields change; startAt?: null = continue numbering; kinsoku?: set | null (default rules); a grepStyles pattern that can't compile is an error}, chars?: {character attributes, as type.char names them: fontFamily, fontStyle, size, leading, tracking, fill, …}}",+ "{name, rename?, basedOn?, nextStyle?, para?: {paragraph attributes, as type.para names them: align, leftIndent, spaceBefore, ignoreOpticalMargin, …; ruleAbove?/ruleBelow?: only the named rule fields change; startAt?: null = continue numbering; kinsoku?: set | null (default rules); a grepStyles pattern that can't compile is an error}, chars?: {character attributes, as type.char names them: fontFamily, fontStyle, size, leading, tracking, fill, …}}",has_doc,edit_para),diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rsindex 3a40844be..43038f76a 100644--- a/crates/engine/src/cmd/text.rs+++ b/crates/engine/src/cmd/text.rs@@ -104,6 +104,15 @@ pub fn specs() -> Vec<CommandSpec> {})}),+ cmd!(+ "story.options",+ "Story Options",+ [],+ None,+ "{story?, frame?: a text frame of the story (default: the stories of the text selection or the selected frames), opticalMargin?: bool — Optical Margin Alignment: punctuation and letter edges hang outside the frame in every paragraph of the story except those with ignoreOpticalMargin, opticalMarginSize?: pt (0.1–1296, default 12) — the type size the hang amounts are set for} → {stories}",+ has_doc,+ story_options+ ),cmd!("story.setText", "Set Story Text", [], None, "{story, text} — replace a story's whole text", has_doc, |s, p| {let sid = StoryId(p.get("story").and_then(Value::as_u64).ok_or_else(|| bad("story.setText", "missing story"))?);let text = super::text_param(p, "text");@@ -182,7 +191,7 @@ pub fn specs() -> Vec<CommandSpec> {"Paragraph Formatting",[],None,- "{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?: bool (default true), composer?, tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}",+ "{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?: bool (default true), composer?, opticalMargin?: bool (hang at each character's own size; a story with story.options opticalMargin overrides it), ignoreOpticalMargin?: bool (no hang in the paragraph), tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}",has_text_or_frames,|s, p| format_paras(s, p.get("attrs").unwrap_or(p))),@@ -374,7 +383,7 @@ pub fn specs() -> Vec<CommandSpec> {"Selection Attributes",[],None,- "{mixed?: bool} → resolved character/paragraph attributes at the text selection; with mixed, paraMixed lists the paragraph attributes that differ across the selected paragraphs; the selection's start as `selectedText` (one line, up to 60 characters)",+ "{mixed?: bool} → resolved character/paragraph attributes at the text selection; with mixed, paraMixed lists the paragraph attributes that differ across the selected paragraphs; the selection's start as `selectedText` (one line, up to 60 characters); `storyOptions` {opticalMargin, opticalMarginSize} of the stories story.options would change (null where they differ)",has_doc,selection_attrs),@@ -991,11 +1000,11 @@ fn sentence_bounds(s: &str, i: usize) -> (usize, usize) {(pa + start, pb)}-/// Type ▸ Story Direction.-fn story_direction(s: &mut Session, p: &Value) -> Result<Value> {- let vertical = p.get("vertical").and_then(Value::as_bool).ok_or_else(|| bad("type.storyDirection", "missing vertical"))?;+/// The stories of the text selection, the selected cells and the selected text frames.+fn selected_stories(s: &Session) -> Result<Vec<StoryId>> {let st = s.doc()?;let mut stories: Vec<StoryId> = st.selection.text.map(|t| t.story).into_iter().chain(st.selection.cells.map(|c| c.story)).collect();+ stories.dedup();for id in &st.selection.items {if let Some(tf) = st.doc.item(*id).and_then(|i| i.text_frame())&& !stories.contains(&tf.story)@@ -1003,6 +1012,54 @@ fn story_direction(s: &mut Session, p: &Value) -> Result<Value> {stories.push(tf.story);}}+ Ok(stories)+}++/// Type ▸ Story: the story-wide options (Optical Margin Alignment and its size).+fn story_options(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "story.options";+ let on = match p.get("opticalMargin") {+ None => None,+ Some(v) => Some(v.as_bool().ok_or_else(|| bad(CMD, "`opticalMargin` must be a bool"))?),+ };+ let size = match p.get("opticalMarginSize") {+ None => None,+ Some(v) => Some(+ v.as_f64()+ .and_then(designcraft_doc::OpticalMargin::clamp_size)+ .ok_or_else(|| bad(CMD, "`opticalMarginSize` must be a finite number of points"))?,+ ),+ };+ if on.is_none() && size.is_none() {+ return Err(bad(CMD, "nothing to set: give opticalMargin or opticalMarginSize"));+ }+ let stories = if p.get("story").is_some() || p.get("frame").is_some() {+ vec![story_of(s, p).ok_or_else(|| bad(CMD, "no such story"))?]+ } else {+ selected_stories(s)?+ };+ if stories.is_empty() {+ return Err(bad(CMD, "no story: select text or a text frame, or give story or frame"));+ }+ s.edit(|d, _| {+ for sid in &stories {+ let st = d.story_mut(*sid).ok_or(designcraft_doc::DocError::NoStory(*sid))?;+ let mut om = st.optical_margin;+ om.on = on.unwrap_or(om.on);+ om.size = size.unwrap_or(om.size);+ if om != st.optical_margin {+ st.optical_margin = om;+ st.rev = st.rev.wrapping_add(1);+ }+ }+ Ok(json!({"stories": stories.len()}))+ })+}++/// Type ▸ Story Direction.+fn story_direction(s: &mut Session, p: &Value) -> Result<Value> {+ let vertical = p.get("vertical").and_then(Value::as_bool).ok_or_else(|| bad("type.storyDirection", "missing vertical"))?;+ let stories = selected_stories(s)?;s.edit(|d, _| {set_story_direction(d, &stories, vertical);Ok(json!({"stories": stories.len()}))@@ -1836,12 +1893,30 @@ fn selection_attrs(s: &mut Session, p: &Value) -> Result<Value> {"paraOverrides": style_para.delta(&pp).count() + style_chars.delta(&base).count(),"charOverrides": char_delta.count(), "characterStyleOverrides": character_style_overrides,"selectedText": selected.trim()});+ let mut stories = selected_stories(s)?;+ if stories.is_empty() {+ stories.push(sid);+ }+ out["storyOptions"] = story_options_of(&st.doc, &stories);if bool_or(p, "mixed", false) {out["paraMixed"] = json!(mixed_para_attrs(&st.doc, &targets));}Ok(out)}+/// The story options of `stories`, as story.options names them; a value that differs between+/// the stories is null.+fn story_options_of(doc: &designcraft_doc::Document, stories: &[StoryId]) -> Value {+ let mut values = stories.iter().filter_map(|sid| doc.story(*sid)).map(|st| st.optical_margin);+ let Some(first) = values.next() else { return json!({"opticalMargin": null, "opticalMarginSize": null}) };+ let (mut on, mut size) = (Some(first.on), Some(first.size));+ for om in values {+ on = on.filter(|v| *v == om.on);+ size = size.filter(|v| *v == om.size);+ }+ json!({"opticalMargin": on, "opticalMarginSize": size})+}+/// The paragraph attributes whose resolved values differ across the paragraphs of `targets`.fn mixed_para_attrs(doc: &designcraft_doc::Document, targets: &[Target]) -> Vec<String> {let mut first: Option<serde_json::Map<String, Value>> = None;@@ -3280,6 +3355,90 @@ mod bidi_caret_tests {}}+#[cfg(test)]+mod story_options_tests {+ use super::*;++ fn first_x(s: &Session, sid: StoryId) -> f64 {+ let cs = s.cache.get(&s.doc().unwrap().doc, sid, None);+ cs.frames[0].lines[0].glyphs[0].x+ }++ fn story(s: &Session, sid: StoryId) -> designcraft_doc::OpticalMargin {+ s.doc().unwrap().doc.story(sid).unwrap().optical_margin+ }++ #[test]+ fn story_options_set_optical_margin_with_one_undo_step_each() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let r = s.execute("frame.create", &json!({"rect": [0, 0, 300, 200], "content": "text", "text": "“Hung” words."})).unwrap();+ let sid = StoryId(r["story"].as_u64().unwrap());+ let flush = first_x(&s, sid);+ // The selected frame's story.+ s.execute("story.options", &json!({"opticalMargin": true})).unwrap();+ assert_eq!(story(&s, sid), designcraft_doc::OpticalMargin { on: true, size: 12.0 });+ let hung = first_x(&s, sid);+ assert!(hung < flush - 1.0, "{hung} {flush}");+ s.execute("story.options", &json!({"story": sid.0, "opticalMarginSize": 24})).unwrap();+ assert_eq!(story(&s, sid).size, 24.0);+ assert!(first_x(&s, sid) < hung - 1.0);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(story(&s, sid), designcraft_doc::OpticalMargin { on: true, size: 12.0 });+ s.execute("edit.undo", &json!({})).unwrap();+ assert!(!story(&s, sid).on);+ assert_eq!(first_x(&s, sid), flush);+ // Hostile sizes.+ s.execute("story.options", &json!({"story": sid.0, "opticalMarginSize": 1e9})).unwrap();+ assert_eq!(story(&s, sid).size, designcraft_doc::OpticalMargin::MAX_SIZE);+ for bad in [json!({"opticalMarginSize": "big"}), json!({"opticalMargin": 1}), json!({}), json!({"story": 999_999, "opticalMargin": true})] {+ assert!(s.execute("story.options", &bad).is_err(), "{bad}");+ }+ }++ #[test]+ fn ignore_optical_margin_through_type_para_and_paragraph_styles() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let r = s.execute("frame.create", &json!({"rect": [0, 0, 300, 200], "content": "text", "text": "“Hung” words."})).unwrap();+ let sid = StoryId(r["story"].as_u64().unwrap());+ let flush = first_x(&s, sid);+ s.execute("story.options", &json!({"opticalMargin": true})).unwrap();+ assert!(first_x(&s, sid) < flush - 1.0);+ let ignored = |s: &Session| s.doc().unwrap().doc.story(sid).unwrap().paras[0].para.ignore_optical_margin;+ s.execute("type.para", &json!({"attrs": {"ignoreOpticalMargin": true}})).unwrap();+ assert_eq!(ignored(&s), Some(true));+ assert_eq!(first_x(&s, sid), flush);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(ignored(&s), None);+ s.execute("style.paragraph.create", &json!({"name": "Flush", "para": {"ignoreOpticalMargin": true}})).unwrap();+ let resolved = |s: &Session| s.doc().unwrap().doc.styles.resolve_para_style("Flush").0.ignore_optical_margin;+ assert!(resolved(&s));+ s.execute("style.paragraph.edit", &json!({"name": "Flush", "para": {"ignoreOpticalMargin": false}})).unwrap();+ assert!(!resolved(&s));+ s.execute("edit.undo", &json!({})).unwrap();+ assert!(resolved(&s));+ s.execute("style.paragraph.apply", &json!({"name": "Flush"})).unwrap();+ assert_eq!(first_x(&s, sid), flush);+ }++ #[test]+ fn selection_attrs_report_the_story_options_with_differences_as_null() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let a = s.execute("frame.create", &json!({"rect": [0, 0, 300, 200], "content": "text", "text": "One"})).unwrap();+ let b = s.execute("frame.create", &json!({"rect": [0, 300, 300, 500], "content": "text", "text": "Two"})).unwrap();+ let options = |s: &mut Session| s.execute("type.selectionAttrs", &json!({})).unwrap()["storyOptions"].clone();+ assert_eq!(options(&mut s), json!({"opticalMargin": false, "opticalMarginSize": 12.0}));+ s.execute("story.options", &json!({"story": b["story"], "opticalMargin": true, "opticalMarginSize": 18})).unwrap();+ assert_eq!(options(&mut s), json!({"opticalMargin": true, "opticalMarginSize": 18.0}), "the selected frame's story");+ s.execute("selection.set", &json!({"ids": [a["id"], b["id"]]})).unwrap();+ assert_eq!(options(&mut s), json!({"opticalMargin": null, "opticalMarginSize": null}));+ s.execute("story.options", &json!({"opticalMarginSize": 18})).unwrap();+ assert_eq!(options(&mut s), json!({"opticalMargin": null, "opticalMarginSize": 18.0}));+ }+}+#[cfg(test)]mod arabic_tests {use super::*;diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rsindex 0106364e2..3a9dc778d 100644--- a/crates/idml/src/export.rs+++ b/crates/idml/src/export.rs@@ -1528,6 +1528,7 @@ impl<'a> Ex<'a> {}n!(keep_with_next, "KeepWithNext");b!(keep_lines_together, "KeepLinesTogether");+ b!(ignore_optical_margin, "IgnoreEdgeAlignment");b!(keep_all_lines, "KeepAllLinesTogether");n!(keep_first, "KeepFirstLines");n!(keep_last, "KeepLastLines");@@ -2226,8 +2227,11 @@ impl<'a> Ex<'a> {.attr("StoryTitle", "$ID/");el.push(El::new("StoryPreference")- .attr("OpticalMarginAlignment", "false")- .attr("OpticalMarginSize", "12")+ .attr("OpticalMarginAlignment", bool_s(s.optical_margin.on))+ .attr(+ "OpticalMarginSize",+ num(designcraft_doc::OpticalMargin::clamp_size(s.optical_margin.size).unwrap_or(designcraft_doc::OpticalMargin::DEFAULT_SIZE)),+ ).attr("FrameType", "TextFrameType").attr("StoryOrientation", if s.vertical { "Vertical" } else { "Horizontal" }).attr(diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rsindex 77d730fa0..1000638d3 100644--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@ -1820,6 +1820,7 @@ impl<'r> Importer<'r> {a.single_word_justify = e.prop("SingleWordJustification").and_then(|v| names::align_in(v.trim()));a.keep_with_next = u("KeepWithNext");a.keep_lines_together = e.boolean("KeepLinesTogether");+ a.ignore_optical_margin = e.boolean("IgnoreEdgeAlignment");a.keep_all_lines = e.boolean("KeepAllLinesTogether");a.keep_first = u("KeepFirstLines");a.keep_last = u("KeepLastLines");@@ -2095,6 +2096,14 @@ impl<'r> Importer<'r> {let format = self.xref_format_names.get(&fmt).cloned().unwrap_or_else(|| "Full Paragraph & Page Number".into());xref_list.push(Arc::new(designcraft_doc::CrossRef { target: 0, format }));}+ let pref = e.find("StoryPreference");+ let optical_margin = designcraft_doc::OpticalMargin {+ on: pref.and_then(|p| p.boolean("OpticalMarginAlignment")).unwrap_or(false),+ size: pref+ .and_then(|p| p.num("OpticalMarginSize"))+ .and_then(designcraft_doc::OpticalMargin::clamp_size)+ .unwrap_or(designcraft_doc::OpticalMargin::DEFAULT_SIZE),+ };let mut st = Story {id,text,@@ -2107,6 +2116,7 @@ impl<'r> Importer<'r> {designcraft_doc::TextDirection::LeftToRight},vertical: e.find("StoryPreference").and_then(|p| p.get("StoryOrientation")) == Some("Vertical"),+ optical_margin,rev: 0,tables,notes,diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rsindex 970567e7c..fcee91706 100644--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@ -300,6 +300,7 @@ fn indesign_text_defaults() -> Vec<AttrRow> {"HyphenateLadderLimit": "3" => 3, "0" => 0, |r| r.0.hyph_limit;"HyphenationZone": "36" => 36.0, "18" => 18.0, |r| r.0.hyph_zone;"HyphenateCapitalizedWords": "true" => true, "false" => false, |r| r.0.hyph_capitalized;+ "IgnoreEdgeAlignment": "false" => false, "true" => true, |r| r.0.ignore_optical_margin;"HyphenateLastWord": "true" => true, "false" => false, |r| r.0.hyph_last_word;"HyphenateAcrossColumns": "true" => true, "false" => false, |r| r.0.hyph_across_column;"HyphenWeight": "5" => 0.5, "9" => 0.9, |r| r.0.hyph_weight;@@ -484,6 +485,57 @@ fn text_color_rules_round_trip() {assert_eq!(p.para.kashidas, Some(false));}+fn optical_story(pref: &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">+ <StoryPreference {pref} StoryOrientation="Horizontal" StoryDirection="LeftToRightDirection"/>+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Body">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>“Hung” here.</Content><Br/></CharacterStyleRange>+ </ParagraphStyleRange>+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Body" IgnoreEdgeAlignment="true">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>“Flush” here.</Content></CharacterStyleRange>+ </ParagraphStyleRange>+ </Story>+</idPkg:Story>"#+ )+}++/// Story ▸ Optical Margin Alignment and its size, and Ignore Optical Margin on paragraphs and+/// paragraph styles, survive import and export.+#[test]+fn story_optical_margin_round_trips() {+ let story = |d: &Document| d.stories.values().find(|s| s.text.starts_with("“Hung”")).cloned().unwrap();+ let d = import_idml_with(&fixture_with_story(&optical_story(r#"OpticalMarginAlignment="true" OpticalMarginSize="18""#)), &|_| None).unwrap();+ let s = story(&d);+ assert_eq!(s.optical_margin, designcraft_doc::OpticalMargin { on: true, size: 18.0 });+ assert_eq!((s.paras[0].para.ignore_optical_margin, s.paras[1].para.ignore_optical_margin), (None, Some(true)));+ let bytes = export_idml(&d);+ let text = zip_text(&bytes, "Stories/");+ assert!(text.contains(r#"OpticalMarginAlignment="true" OpticalMarginSize="18""#), "{text}");+ assert!(text.contains(r#"IgnoreEdgeAlignment="true""#), "{text}");+ let back = story(&import_idml(&bytes).unwrap());+ assert_eq!(back.optical_margin, s.optical_margin);+ assert_eq!(back.paras[1].para.ignore_optical_margin, Some(true));+ // Sizes outside InDesign's range are clamped; malformed ones and an absent preference are the default.+ for (pref, want) in [+ (r#"OpticalMarginAlignment="true" OpticalMarginSize="1e9""#, (true, 1296.0)),+ (r#"OpticalMarginAlignment="true" OpticalMarginSize="0""#, (true, 0.1)),+ (r#"OpticalMarginAlignment="true" OpticalMarginSize="NaN""#, (true, 12.0)),+ (r#"OpticalMarginAlignment="false""#, (false, 12.0)),+ ] {+ let d = import_idml_with(&fixture_with_story(&optical_story(pref)), &|_| None).unwrap();+ let om = story(&d).optical_margin;+ assert_eq!((om.on, om.size), want, "{pref}");+ }+ // On a paragraph style.+ let d = import_idml_with(&fixture_with_styles(&keep_styles(r#"IgnoreEdgeAlignment="true""#)), &|_| None).unwrap();+ assert!(d.styles.resolve_para_style("Body").0.ignore_optical_margin);+ let styles = zip_text(&export_idml(&d), "Resources/Styles.xml");+ assert!(styles.contains(r#"IgnoreEdgeAlignment="true""#), "{styles}");+}+/// `[Basic Paragraph]` is InDesign's `$ID/NormalParagraphStyle`, both ways.#[test]fn basic_paragraph_is_normal_paragraph_style() {diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rsindex 303c08703..5183222eb 100644--- a/crates/ui-egui/src/chrome.rs+++ b/crates/ui-egui/src/chrome.rs@@ -579,7 +579,7 @@ const TRACKING: &[f64] = &[-100.0, -75.0, -50.0, -25.0, -10.0, -5.0, 0.0, 5.0, 1const PARA_MODE: &str = "ctl_text_para_mode";/// An icon and a field after it, as the Control panel lays its fields out.-fn icon_field(ui: &mut egui::Ui, icon: &str, tip: &str, field: NumField) -> Option<f64> {+pub(crate) fn icon_field(ui: &mut egui::Ui, icon: &str, tip: &str, field: NumField) -> Option<f64> {let t = Tokens::get(ui.ctx());let (r, resp) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover());icons::paint(ui.painter(), r, icon, t.icon);diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 5245e00be..04d2391f3 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -4059,6 +4059,11 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo});ui.end_row();});+ ui.add_space(6.0);+ let mut ignore = cur(d, "p.ignoreOpticalMargin", &pv["ignoreOpticalMargin"]).as_bool().unwrap_or(false);+ if ui.checkbox(&mut ignore, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Ignore Optical Margin"))).changed() {+ d.fields.insert("p.ignoreOpticalMargin".into(), json!(ignore));+ }}"tabs" => style_tabs(&app.ui.language, ui, d, &pv, &doc),"rules" => paragraph_rules(app, ui, d, "p.", &pv),@@ -7867,6 +7872,35 @@ mod tests {assert_eq!(props.number_label(3), "III)\t");}+ #[test]+ fn paragraph_style_options_ignore_optical_margin_is_set_on_ok() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("style.paragraph.create", json!({"name": "Flush"})).unwrap();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Flush", "section": "indents"})));+ let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::new("ignore_optical_margin_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(3);+ h.get_by_label("Ignore Optical Margin").click();+ h.run_steps(3);+ h.get_by_label(" OK ").click();+ h.run_steps(3);+ let app = h.state();+ assert!(app.ui.dialog.is_none());+ assert_eq!(app.session.doc().unwrap().doc.styles.para("Flush").unwrap().para.ignore_optical_margin, Some(true));+ }+#[test]fn paragraph_style_options_keep_a_bad_grep_pattern_open_with_the_error() {let (mut app, _) = ruled_paragraph();diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rsindex d4551e813..65e4420ad 100644--- a/crates/ui-egui/src/dock.rs+++ b/crates/ui-egui/src/dock.rs@@ -23,6 +23,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[("typography", "Typography", "panel-typography"),("glyphs", "Glyphs", "panel-character"),("paragraph", "Paragraph", "panel-paragraph"),+ ("story", "Story", "panel-text-frame"),("textWrap", "Text Wrap", "panel-wrap"),("table", "Table", "panel-table"),("align", "Align", "panel-align"),@@ -285,6 +286,7 @@ pub fn panel_body(app: &mut DesignApp, ui: &mut egui::Ui, id: &str) {"typography" => panels::typography::show(app, ui),"glyphs" => panels::glyphs::show(app, ui),"paragraph" => panels::properties::paragraph_panel(app, ui),+ "story" => panels::story::show(app, ui),"textWrap" => panels::properties::wrap_panel(app, ui),"align" => panels::properties::align_panel(app, ui),"pathfinder" => panels::properties::pathfinder_panel(app, ui),diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 75053ef1b..b7382c906 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -913,6 +913,7 @@ pub const MENUS: &[(&str, &[&str])] = &["ui:window.panel|Conditional Text|{\"panel\": \"conditions\"}","ui:window.panel|Glyphs|{\"panel\": \"glyphs\"}","ui:window.panel|Paragraph|{\"panel\": \"paragraph\"}",+ "ui:window.panel|Story|{\"panel\": \"story\"}","ui:window.panel|Table|{\"panel\": \"table\"}","ui:app.tabsPanel","ui:window.panel|Typography|{\"panel\": \"typography\"}",@@ -966,7 +967,8 @@ pub const CLASSIC_GROUPS: &[&[&str]] = &[];/// The Typography preset's available panels in the order observed in InDesign's workspace.-/// CC Libraries and the separate Story panel have no corresponding DesignCraft panel.+/// CC Libraries has no corresponding DesignCraft panel, and where the Story panel sits in it is+/// not recorded, so these groups leave it out.pub const TYPOGRAPHY_GROUPS: &[&[&str]] = &[&["pages", "layers", "swatches"],&["glyphs", "textWrap"],diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rsindex 85058d7a8..0624d0c66 100644--- a/crates/ui-egui/src/panels/mod.rs+++ b/crates/ui-egui/src/panels/mod.rs@@ -12,6 +12,7 @@ pub mod library;pub mod notes;pub mod pages;pub mod properties;+pub mod story;pub mod styles;pub mod swatches;pub mod table;diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rsindex 6deace3fc..fda46efad 100644--- a/crates/ui-egui/src/panels/properties.rs+++ b/crates/ui-egui/src/panels/properties.rs@@ -2089,9 +2089,10 @@ fn paragraph_panel_menu(app: &mut DesignApp, ui: &mut Ui, p: &Value) {if item(ui, "Balance Ragged Lines", Some(balance), true) {attrs = Some(json!({"balanceRagged": !balance}));}- let optical = p["opticalMargin"].as_bool().unwrap_or(false);- if item(ui, "Optical Margin Alignment", Some(optical), true) {- attrs = Some(json!({"opticalMargin": !optical}));+ // Story-wide Optical Margin Alignment is in the Story panel.+ let ignore = p["ignoreOpticalMargin"].as_bool().unwrap_or(false);+ if item(ui, "Ignore Optical Margin", Some(ignore), true) {+ attrs = Some(json!({"ignoreOpticalMargin": !ignore}));}ui.separator();for (label, id) in [@@ -3451,6 +3452,22 @@ mod tests {let _ = h.get_by_label("✓ Only Align First Line to Grid");}+ #[test]+ fn paragraph_panel_menu_toggles_ignore_optical_margin() {+ let mut h = panel_harness(text_app(), paragraph_panel);+ h.run_steps(3);+ h.get_by_label("☰").click();+ h.run_steps(3);+ h.get_by_label(" Ignore Optical Margin").click();+ h.run_steps(3);+ assert_eq!(text_attrs(h.state_mut()).unwrap()["para"]["ignoreOpticalMargin"], true);+ h.get_by_label("☰").click();+ h.run_steps(3);+ h.get_by_label("✓ Ignore Optical Margin").click();+ h.run_steps(3);+ assert_eq!(text_attrs(h.state_mut()).unwrap()["para"]["ignoreOpticalMargin"], false);+ }+#[test]fn paragraph_panel_menu_define_lists_opens_its_dialog() {let mut h = panel_harness(text_app(), paragraph_panel);diff --git a/crates/ui-egui/src/panels/story.rs b/crates/ui-egui/src/panels/story.rsnew file mode 100644index 000000000..adb2ed1d5--- /dev/null+++ b/crates/ui-egui/src/panels/story.rs@@ -0,0 +1,106 @@+//! Window › Type & Tables › Story: the story-wide options.++use serde_json::{Value, json};++use crate::DesignApp;+use crate::widgets::{self, NumField};++/// The Story panel: Optical Margin Alignment for the stories of the text selection or the+/// selected text frames, and the type size its hang amounts are set for. Without text or a text+/// frame selected, the controls are disabled.+pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {+ let options = super::text_attrs(app).map(|a| a["storyOptions"].clone());+ let enabled = options.is_some();+ let options = options.unwrap_or(Value::Null);+ let lang = app.ui.language.clone();+ let tr = |s: &str| crate::i18n::tr(&lang, s).to_string();+ ui.add_enabled_ui(enabled, |ui| {+ ui.horizontal_wrapped(|ui| {+ // Stories that differ show unchecked; a click turns it on for all of them.+ let mut on = options["opticalMargin"].as_bool().unwrap_or(false);+ if widgets::checkbox(ui, &mut on, &tr("Optical Margin Alignment")).changed() {+ let _ = app.run("story.options", json!({"opticalMargin": on}));+ }+ let field = NumField::number("storyOpticalMarginSize", options["opticalMarginSize"].as_f64(), " pt", 2)+ .width(72.0)+ .range(designcraft_doc::OpticalMargin::MIN_SIZE, designcraft_doc::OpticalMargin::MAX_SIZE);+ if let Some(size) = crate::chrome::icon_field(ui, "font-size", &tr("Optical Margin Size"), field) {+ let _ = app.run("story.options", json!({"opticalMarginSize": size}));+ }+ });+ });+}++#[cfg(test)]+mod tests {+ use egui_kittest::{+ Harness,+ kittest::{NodeT, Queryable},+ };++ use super::*;++ fn harness(app: DesignApp) -> Harness<'static, DesignApp> {+ let mut h = Harness::builder().with_size(egui::vec2(260.0, 200.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let id = egui::Id::new("test_fonts");+ if ui.data(|d| d.get_temp::<bool>(id)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(id, true));+ return;+ }+ show(app, ui);+ },+ app,+ );+ h.run_steps(3);+ h+ }++ fn optical_margin(h: &Harness<'static, DesignApp>, story: u64) -> designcraft_doc::OpticalMargin {+ h.state().session.active().unwrap().doc.story(designcraft_doc::StoryId(story)).unwrap().optical_margin+ }++ fn size_field_text(h: &Harness<'static, DesignApp>) -> Option<String> {+ h.get_all_by_role(egui::accesskit::Role::TextInput).next().unwrap().value()+ }++ #[test]+ fn story_panel_sets_and_shows_the_storys_optical_margin() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let story =+ app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "“Hung”", "caret": true})).unwrap()["story"]+ .as_u64()+ .unwrap();+ app.run("edit.selectAll", json!({})).unwrap();+ let mut h = harness(app);+ assert_eq!(size_field_text(&h).as_deref(), Some("12 pt"));+ h.get_by_label("Optical Margin Alignment").click();+ h.run_steps(3);+ assert!(optical_margin(&h, story).on);+ assert_eq!(h.get_by_label("Optical Margin Alignment").accesskit_node().toggled(), Some(egui::accesskit::Toggled::True));+ h.get_all_by_role(egui::accesskit::Role::TextInput).next().unwrap().click();+ h.run_steps(2);+ h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });+ h.event(egui::Event::Text("18".into()));+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ assert_eq!(optical_margin(&h, story), designcraft_doc::OpticalMargin { on: true, size: 18.0 });+ // A value set elsewhere shows in the panel.+ h.state_mut().run("story.options", json!({"opticalMarginSize": 30})).unwrap();+ h.run_steps(3);+ assert_eq!(size_field_text(&h).as_deref(), Some("30 pt"));+ }++ #[test]+ fn story_panel_is_disabled_without_text() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let mut h = harness(app);+ assert!(h.get_by_label("Optical Margin Alignment").accesskit_node().is_disabled());+ h.get_by_label("Optical Margin Alignment").click();+ h.run_steps(3);+ assert_eq!(h.get_by_label("Optical Margin Alignment").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False));+ }+}diff --git a/docs/typography-parity.md b/docs/typography-parity.mdindex 9d3f7d4d0..8c92e8dfa 100644--- a/docs/typography-parity.md+++ b/docs/typography-parity.md@@ -1,6 +1,6 @@# Typography and composition parity-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (Type › Reload Fonts reads fonts installed, edited or removed since start-up (#328, #547); Optical kerning from outlines (#181); macOS lists fonts that font services and managers activate; Justification dialog for the selected paragraphs; anchored objects wrap text; Tabs panel listed as present (#343); character stroke behind fill) · **Target:** Adobe InDesign 2026 (21.6)+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (Optical Margin Alignment per story with a size in the Story panel, and Ignore Optical Margin in the Paragraph panel menu and paragraph styles, kept through IDML (#947); Type › Reload Fonts reads fonts installed, edited or removed since start-up (#328, #547); Optical kerning from outlines (#181); macOS lists fonts that font services and managers activate; Justification dialog for the selected paragraphs; anchored objects wrap text; Tabs panel listed as present (#343); character stroke behind fill) · **Target:** Adobe InDesign 2026 (21.6)Typesetting is what InDesign is bought for. A feature can exist and still set text differentlyfrom InDesign: different line breaks, different page count, overset where InDesign fits. This@@ -58,7 +58,7 @@ Fidelity: **unmeasured** unless stated.| Tabs | left/center/right/decimal/align-on, leaders, right-indent tab | ✓ | ~ | Tabs panel with a ruler over the text column, and a Tabs section in Paragraph Style Options (#343); wrapping of lines with tabs fixed (#282) || Paragraph rules, borders, shading | ✓ | ✓ | ✓ | || Balance ragged lines | ✓ | ✓ | ✓ | |-| Optical margin alignment | ✓ | ✓ (hang table of our own) | ~ | hang amounts are ours, InDesign's unknown |+| Optical margin alignment | per story with a size, Ignore Optical Margin per paragraph and style | ✓ (hang table of our own, scaled by the story's size; Story panel; IDML `StoryPreference`, `IgnoreEdgeAlignment`) | ~ | hang amounts are ours, InDesign's unknown (#947) || Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options, on page items and anchored objects | ✓ | ~ | Detect Edges, Alpha Channel and Photoshop Path contours follow the frame's path (composition doesn't read the image) || Anchored objects | inline, above line, custom | ✓ | ~ | anchored objects in table cells not drawn (#163) || Footnotes, endnotes | ✓ | ✓ | ~ | footnotes don't split across columns yet |diff --git a/docs/ui-parity.md b/docs/ui-parity.mdindex 2430b489b..4366847f3 100644--- a/docs/ui-parity.md+++ b/docs/ui-parity.md@@ -1,6 +1,6 @@# UI and interaction parity-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-21 · **Change:** minor (text Control panel Character/Paragraph modes; Properties ••• expands Character and Paragraph; live corners work; document views row: scrollbars, Alt pans while editing text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; paragraph style override feedback and clearing) · **Target:** Adobe InDesign 2026 (21.6, Medium Dark, macOS)+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (Story panel; text Control panel Character/Paragraph modes; Properties ••• expands Character and Paragraph; live corners work; document views row: scrollbars, Alt pans while editing text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; paragraph style override feedback and clearing) · **Target:** Adobe InDesign 2026 (21.6, Medium Dark, macOS)Tools, handles, snapping, nudging, modifiers, shortcuts, panels, menus, context menus and feel,against InDesign 2026. The look was measured from the running app@@ -47,7 +47,7 @@ basics of editing fail for too many users on Windows and Linux.| Quick Apply | ✓ | ✓ | ✓ | || Numeric fields: units, arithmetic, scrubbing | ✓ | 21 pt spinner fields with arithmetic | ✓ | || Colour fields: hex, picker from any swatch field | ✓ | ✓ | ~ | hex entry and picker issues (#323, #190) |-| Panels: Pages, Layers, Swatches, Color, Stroke, Character, Paragraph, Styles, Links, Effects, Text Wrap, Align, Pathfinder, Table, Index, TOC, Hyperlinks, Bookmarks, Articles, Tags, Notes, Track Changes, Object States, Buttons and Forms, Preflight, Data Merge, Library, Scripts, Glyphs, Info, Tabs | ✓ | all present | ~ | Navigator, Trap Presets, Animation, Timing missing; pull-down panels can't scroll on Linux (#267) |+| Panels: Pages, Layers, Swatches, Color, Stroke, Character, Paragraph, Styles, Links, Effects, Text Wrap, Align, Pathfinder, Table, Index, TOC, Hyperlinks, Bookmarks, Articles, Tags, Notes, Track Changes, Object States, Buttons and Forms, Preflight, Data Merge, Library, Scripts, Glyphs, Info, Tabs, Story | ✓ | all present | ~ | Navigator, Trap Presets, Animation, Timing missing; pull-down panels can't scroll on Linux (#267) || Dialogs: New Document, Document Setup, Preferences (all pages), Paragraph/Character/Object/Table/Cell Style Options, Export PDF, Print, Package, Find/Change | ✓ | present | ~ | generated command dialogs fill the long tail; depth varies || Workspaces | Essentials, Essentials Classic, Advanced, Book, Digital Publishing, Interactive for PDF, Printing and Proofing, Review, Typography, Touch | ✓ named workspaces (Essentials Classic: Control panel and iconic panel groups) + custom; Window › Workspace; no Review or Touch | ~ | tab bar overlaps menus in Book/Advanced (#182) || Story Editor | ✓ | ✓ | ~ | style-name column, depth ruler missing |@@ -122,6 +122,7 @@ covers checking the sampled and redefined settings in the styles tutorial (2:45| Date | Change | Summary ||---|---|---|+| 2026-10-24 | minor | Panels row: Story panel (Optical Margin Alignment and its size) || 2026-10-21 | minor | Chrome row: the text Control panel's A/¶ modes; Properties row: ••• expands Character and Paragraph in place || 2026-10-11 | minor | Live corners row to ✓: widget, diamonds, drag, Shift-drag, Alt-click shape cycling (#186) || 2026-10-11 | minor | Added held Cmd+Space / Cmd+Alt+Space Zoom navigation and canvas input regression tests |