diff --git a/ROADMAP.md b/ROADMAP.md index fbc6e01cf..1847d0499 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -359,11 +359,22 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. - **2026-10-23** · Effects dialog: with Use Global Light on, the Angle field (and the Bevel and Emboss one) stays editable and shows the document's global light angle; a change there sets the global light for every effect that uses it, applied with the effects in one undo step (`object.effects` takes `globalLight`). Before, the field was greyed out and the angle couldn't be changed in the dialog. No readiness percentage change. +- **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. +- **2026-10-24** · New documents start with Hyphenate Capitalized Words, Hyphenate Last Word and Hyphenate Across Column off in [Basic Paragraph], as in InDesign. Opened and imported files keep the values they carry. No readiness percentage change. +- **2026-10-24** · The baseline grid's Relative To setting applies: with Top Margin, the grid starts at each page's own top margin in text composition, on the canvas and for snapping. It started at the page top, so grid-aligned text sat on the wrong lines and a page could fit one line fewer. No readiness percentage change. - **2026-10-24** · Custom-positioned anchored objects honour Relative to Spine (`anchored.options {spineRelative}`, IDML `SpineRelative`): the settings describe a left-hand page and mirror on a right-hand page, so marginal notes stay in the outside margin on both pages of a spread. On right-hand pages they took the left-hand placement and landed in the inside margin, across the spine or over the body text. No readiness percentage change. +- **2026-10-24** · Text frames: a custom baseline grid (Text Frame Options › Baseline Options) from an IDML file sets lines from its start by its increment. The composer read the two values in the other order, so lines landed on the wrong grid. No readiness percentage change. - **2026-10-23** · Save and export dialogs (Save As, Save a Copy, Export PDF and the other exports, Package, libraries and books) start in the active document's folder once it has been saved, and for a document never saved in the folder of the last file saved or exported, remembered across sessions (#1653). A folder deleted since falls back to the system's choice. No readiness percentage change. - **2026-10-22** · Autoflow (Shift-click with the loaded text cursor, autoflow on Place, `text.thread {autoflow}`) fills the pages that follow before it adds any, as InDesign does: one frame per column on each following page, whatever else the page holds, then new pages at the end of the document. It inserted pages right after the story's last frame, in front of the document's own pages. Frames it set past the end of the text go again; a page the document had stays, and a page autoflow added only for such a frame goes with it. Smart Text Reflow of the primary text frame is unchanged. No readiness percentage change. - **2026-10-16** · Edit › Keyboard Shortcuts imports a set saved by InDesign's Show Set (.txt, Windows or Mac key names, UTF-8 or UTF-16): matched commands take its Default shortcuts or lose theirs, other commands give up keys it takes, and a report lists what it changed and the items it could not match (`window.importShortcuts`, #1180). Tool keys stay fixed. No readiness percentage change. - **2026-10-23** · Translations: a missing string shows in English and fails no test; `cargo xtask i18n-report`, run by `cargo xtask ci`, prints the missing strings per language. Tests keep duplicate-key and placeholder checks and the language mechanics (lookup, context captions, plural captions, right-to-left). No readiness percentage change. +- **2026-10-22** · Hyphenation Settings, as in InDesign: the Paragraph panel menu's Hyphenation… (`app.hyphenationDialog`) sets the selected paragraphs' Hyphenate, Words with at Least, After First, Before Last, Hyphen Limit, Hyphenation Zone, the Better Spacing ↔ Fewer Hyphens slider (InDesign's 0–10 steps), Hyphenate Capitalized Words, Last Word and Across Column, with Preview, as one undo step; Paragraph Style Options › Hyphenation has the same form. The panel menu lists its items in InDesign's order. Replicated from a hyphenation tutorial: the same text in Minion Pro breaks into the same lines as InDesign's with hyphenation on, off, and at Fewer Hyphens. No readiness percentage change. +- **2026-10-22** · Hyphenate Across Column (Hyphenation Settings; IDML HyphenateAcrossColumns) is applied: with it off, a paragraph whose line ending in an automatic hyphen would end a column or frame is re-composed without that hyphenation point, so the word moves on whole, as in InDesign. Opened and imported files keep their own setting, so their layouts don't change. No readiness percentage change. +- **2026-10-22** · The Paragraph panel is laid out as InDesign's: the nine alignment buttons in groups; indent, spacing and drop cap fields by their icons in two columns, with Space Between Paragraphs Using Same Style (Ignore or a space); Shading and Border with the Paragraph Borders and Shading button and colour; Hyphenate with Do Not Align / Align to Baseline Grid. Its panel menu follows InDesign's order: Paragraph and Single-line Composer, Only Align First Line to Grid, Balance Ragged Lines, Optical Margin Alignment, Justification…, Keep Options…, Span Columns…, Hyphenation…, Drop Caps and Nested Styles…, GREP Styles… (these three now open for the selected paragraphs), Paragraph Rules…, Paragraph Borders and Shading…, Bullets and Numbering…, Restart/Continue Numbering, Define Lists… and the paragraph direction. Convert Bullets and Numbering to Text is listed but not available yet. No readiness percentage change. - **2026-10-22** · A ruler guide dragged with the Selection tools, out of a ruler, on its own or with other selected guides, snaps along its axis as objects do (#1221): to other ruler guides, margins, columns, bleed, page and object edges and centers (with the smart-guide mark) and the document grid, within the snap zone and following Snap to Guides and Smart Guides. Shift snaps to the ruler's ticks and Cmd suspends snapping. The preview line, the position readout and the drop use the same snapped position. No readiness percentage change. - **2026-10-22** · macOS: the app menu has a Language submenu after Settings… with each interface language in its own name and the current one checked, as in the suite's other apps; Preferences › General › Interface Language stays. No readiness percentage change. - **2026-10-22** · macOS menu bar: the menus keep working after the interface language or Show CJK Features changes (a rebuilt menu bar lost every click, Quit included), and its key equivalents are the shortcuts in effect, so a shortcut moved in the Keyboard Shortcuts editor leaves its old menu item. No readiness percentage change. @@ -381,6 +392,11 @@ Newest first. - **2026-10-16** · Lock Guides and Lock Column Guides are commands in View ▸ Grids & Guides (`view.lockGuides`, ⌥⌘;, and `view.lockColumnGuides`), so the control channel and MCP reach them. Lock Column Guides is an undo step, is saved with the document, on in new ones, and read from and written to IDML's `ColumnGuideLocked`, which export always wrote as locked (#1096). No readiness percentage change. - **2026-10-16** · IDML: a page keeps column guides that were dragged off centre (InDesign's Custom columns). They were divided evenly on import, so the gutter sprang back to the middle; the imported positions now place the columns, with the canvas guides, snapping and text placement following them, and they are written back on export. Layout › Margins and Columns re-divides them evenly when the count or gutter changes, as InDesign's does. No readiness percentage change. - **2026-10-16** · IDML: custom column positions are checked before they are used (#1096). A set must give two edges per column, ascending from the left margin to the right one; any other (a wrong count, unsorted or non-numeric values, a list longer than 216 columns allow, or positions left behind by a margin or page-size change) is the even split, in the canvas, on import and on export, instead of columns drawn outside the margins. No readiness percentage change. +- **2026-10-21** · Properties › Character and Paragraph: ••• (More Options) expands the section in place, as InDesign's: Character adds vertical and horizontal scale, baseline shift, skew, language and OpenType, and All Caps, Small Caps, Superscript, Subscript, Underline and Strikethrough; Paragraph adds the left, right, first line and last line indents, space before and after, the drop cap's lines and characters, Align to Baseline Grid and Hyphenate. It used to open the Character or Paragraph panel; the language field moved under ••• as in InDesign. Found in the Learn Skills Daily course, chapter 16. No readiness percentage change. +- **2026-10-21** · The text Control panel has InDesign's two modes: A (Character Formatting Controls: font and style, size and leading, All Caps/Superscript/Underline and Small Caps/Subscript/Strikethrough, kerning and tracking, vertical and horizontal scale, baseline shift and skew, character style and language) and ¶ (Paragraph Formatting Controls: the nine alignments, left/first line and right/last line indents, space before and after, the drop cap's lines and characters, paragraph style, Hyphenate and Align to Baseline Grid). It used to show a fixed mix of both. Found in the Learn Skills Daily course, chapter 16. No readiness percentage change. +- **2026-10-20** · With the Type tool, the Control panel's font size, leading and tracking fields have a spinner and a list of common values, as in InDesign (auto leading in parentheses). No readiness percentage change. +- **2026-10-21** · The ¶ (Paragraph Formatting Controls) mode of the text Control panel has InDesign's Bulleted List and Numbered List buttons (with the default hanging indent) and Shading and Border: a checkbox, a button opening Paragraph Borders and Shading on that tab, and the colour. Found in the Learn Skills Daily course, chapter 21. No readiness percentage change. +- **2026-10-21** · The Bulleted and Numbered List buttons (Properties, and Type › Bulleted & Numbered Lists › Apply Bullets / Apply Numbers) work as InDesign's: a paragraph with no indents gets the default hanging indent (0.25 in, −0.25 in), so the text lines up after the bullet instead of at the next default tab stop, and pressing the button again removes the list and that indent (`list.bullets`, `list.numbers`). Found in the Learn Skills Daily course, chapter 21. No readiness percentage change. - **2026-10-16** · Type › Reload Fonts (`font.reload`): fonts installed, edited or removed while DesignCraft runs are read again without a restart, and the open documents recompose with them (#328, #547). An edited font file is noticed by its length and modification time; bundled, added and document fonts stay as they are. InDesign does this by itself, so noticing changes automatically is still open (gap 6). No readiness percentage change. - **2026-10-16** · Parents can be deleted from their Pages-panel context menu or `layout.parents.delete {id}`. Applied-page and based-on references are cleared, local override copies survive, and Undo restores the parent. Addresses the deletion portion of #956; no readiness percentage change. - **2026-10-17** · File › Package writes the document's and the IDML's links relative to the package (`Links/logo.png`, `file:Links/logo.png`), so a package holds no path from the machine that made it; opening a document resolves them to the files beside it. Links › Copy Link(s) To still links by full path. (#340). No readiness percentage change. @@ -388,14 +404,8 @@ Newest first. - **2026-10-17** · Object strokes reject malformed types and unknown type fields before changing the document; command help lists every stroke kind and its required fields. No readiness percentage change. - **2026-10-17** · Docs: documented a persistent source CLI install with Cargo, MCP-client PATH setup and bare-name server registration in `docs/mcp.md`. No readiness percentage change. -- **2026-10-16** · Selection: drag a column guide to move its gutter, as in InDesign (#1096). Both guides of the gutter move together and keep its width, stop at the neighbouring guides and the margins, and snap to the document grid, guides and objects, or with Shift to the ruler's tick marks; Escape cancels and the drag is one undo step. Locked column guides (the default) are not picked. A document page takes the result as its own columns; on a parent page it passes to the pages that follow it. `layout.moveColumnGuide` does the same over the control channel and MCP. No readiness percentage change. -- **2026-10-16** · Layout: Margins and Columns keeps dragged column guides unless the column count or gutter changes (#1096). The dialog sends every field on OK, so a margin-only change re-divided the columns evenly. Margin changes keep the positions; the columns follow them only while they fit the margin box. No readiness percentage change. - **2026-10-16** · Layout: autoflow, inserted pages and new parents follow dragged column guides (#1096). Autoflow sets one frame per dragged column and counts the pages it adds from them; Insert Pages and New Parent keep the custom positions with the column count and gutter; `document.inspect` reports each page's gutter, column rects and whether its columns are custom. No readiness percentage change. -- **2026-10-16** · Layout: autoflow, inserted pages and new parents follow dragged column guides (#1096). Autoflow sets one frame per dragged column and counts the pages it adds from them; Insert Pages and New Parent keep the custom positions with the column count and gutter; a page that moves to the other side of the spine (inserted, deleted or moved pages, Duplicate Spread, a new parent's other page) has them mirrored across its margin box, as InDesign does; `document.inspect` reports each page's gutter, column rects and whether its columns are custom. No readiness percentage change. -- **2026-10-16** · IDML: custom column positions are checked before they are used (#1096). A set must give two edges per column, ascending from the left margin to the right one; any other (a wrong count, unsorted or non-numeric values, a list longer than 216 columns allow, or positions left behind by a margin or page-size change) is the even split, in the canvas, on import and on export, instead of columns drawn outside the margins. No readiness percentage change. -- **2026-10-16** · IDML: a page keeps column guides that were dragged off centre (InDesign's Custom columns). They were divided evenly on import, so the gutter sprang back to the middle; the imported positions now place the columns, with the canvas guides, snapping and text placement following them, and they are written back on export. Layout › Margins and Columns re-divides them evenly when the count or gutter changes, as InDesign's does. No readiness percentage change. - **2026-10-16** · Lock Guides and Lock Column Guides are commands in View ▸ Grids & Guides (`view.lockGuides`, ⌥⌘;, and `view.lockColumnGuides`), so the control channel and MCP reach them. Lock Column Guides is saved with the document, on in new ones, and read from and written to IDML's `ColumnGuideLocked`, which export always wrote as locked (#1096). No readiness percentage change. -- **2026-10-16** · Lock Guides and Lock Column Guides are commands in View ▸ Grids & Guides (`view.lockGuides`, ⌥⌘;, and `view.lockColumnGuides`), so the control channel and MCP reach them. Lock Column Guides is an undo step, is saved with the document, on in new ones, and read from and written to IDML's `ColumnGuideLocked`, which export always wrote as locked (#1096). No readiness percentage change. - **2026-10-16** · Threading: the loaded text cursor threads into a text frame inside a group (it hit the group and showed it could not thread); a plain click still selects the group (#1075). Gap 27 closed. No readiness percentage change. - **2026-10-16** · Greek text hyphenates. The patterns were never compiled in, so Greek set unhyphenated however narrow the column; `"Greek"`, `"Greek: Greece"`, `el` and `el-GR` all resolve now and ανθρωπος breaks αν-θρω-πος. They are the monotonic patterns (hyph-el-monoton, Dimitrios Filippou, under MIT), which is what polytonic text hyphenates by too. Five of InDesign's ~40 hyphenation languages. No readiness percentage change. - **2026-10-16** · A swatch applied to a placed greyscale or bitmap image colours it, as in InDesign: IDML's `` is read and written, greyscale pixels become a tint of the swatch on opaque white and a bitmap's white lets the frame show through, on screen and in PDF (spot swatches print on their plate). Colour images keep their colours. Applying the swatch from the Swatches panel comes next. No readiness percentage change. diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs index 3d18dcaee..faa4f4af0 100644 --- a/apps/designcraft-cli/src/main.rs +++ b/apps/designcraft-cli/src/main.rs @@ -263,7 +263,7 @@ impl Export { /// A name with another extension is an error: it used to get a PNG of the page. One with no /// extension still does (`--export /dev/stdout`). fn of(out: &str) -> Result { - let ext = std::path::Path::new(out).extension().and_then(|e| e.to_str()).map(str::to_lowercase); + let ext = std::path::Path::new(out).extension().and_then(std::ffi::OsStr::to_str).map(str::to_lowercase); Ok(match ext.as_deref() { None | Some("png" | "jpg" | "jpeg") => Export::Image, Some("pdf") => Export::Pdf, diff --git a/apps/designcraft-cli/src/perf.rs b/apps/designcraft-cli/src/perf.rs index bed57cfcc..0c665f7e7 100644 --- a/apps/designcraft-cli/src/perf.rs +++ b/apps/designcraft-cli/src/perf.rs @@ -335,7 +335,7 @@ fn row(rows: &mut Vec, name: impl Into, ms: f64, budget: Option Result, String> { let mut rows = vec![]; - let cores = std::thread::available_parallelism().map_or(1, |c| c.get()); + let cores = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get); let chars: usize = doc.stories.values().map(|s| s.text.len()).sum(); // Budget: 250 ms per 300k characters (MT), scaled to this document. let compose_budget = 250.0 * (chars as f64 / 300_000.0).max(1.0); @@ -532,7 +532,7 @@ fn print(title: &str, rows: &[Row], noisy: bool) -> Result<(), String> { } fn header() -> (usize, bool) { - let cores = std::thread::available_parallelism().map_or(1, |c| c.get()); + let cores = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get); let load = load_average(); let noisy = load.is_some_and(|l| l > cores as f64 * 0.75); outln!( diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index e694fe84f..195a2dc6e 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -256,7 +256,7 @@ const ALL_FILES: &str = if cfg!(target_os = "macos") { "public.data" } else { "* /// The extension of the file name a save dialog suggests (`Brochure.designcraft`), if it has one. /// The dialog filters on it, so the macOS and Windows dialogs add it to a name typed without it. fn suggested_extension(name: &str) -> Option<&str> { - std::path::Path::new(name).extension().and_then(|e| e.to_str()).filter(|e| !e.is_empty() && !e.contains(char::is_whitespace)) + std::path::Path::new(name).extension().and_then(std::ffi::OsStr::to_str).filter(|e| !e.is_empty() && !e.contains(char::is_whitespace)) } /// The file a save dialog's answer writes: `picked` with the suggested extension added when it has diff --git a/crates/compose/src/breaker.rs b/crates/compose/src/breaker.rs index 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, /// 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: &S let 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: &S let 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/cache.rs b/crates/compose/src/cache.rs index 6ca7c7366..66122ccf4 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -3,7 +3,8 @@ //! An entry is valid while the inputs it was composed from are the *same allocations*: the story //! `Arc` (and its revision), the styles `Arc`, the frame items' `Arc`s and the `Arc`s of every //! wrapping item on the frames' spreads, and the same for every story whose anchored objects wrap -//! its text ([`crate::wrap::neighbours`]). Entries hold clones of those `Arc`s, so the pointers +//! its text ([`crate::wrap::neighbours`]). An anchored frame's entry also records where its host +//! story's composition places it. Entries hold clones of those `Arc`s, so the pointers //! can't be reused by other allocations while the entry lives. use std::collections::HashMap; @@ -99,11 +100,12 @@ impl Cache { /// [`Cache::get`] for any [`ShownOn`]. pub fn get_on(&self, doc: &Document, sid: StoryId, on: ShownOn) -> Arc { - self.get_with(doc, sid, on, true) + self.get_with(doc, sid, on, true, 0) } - /// [`Cache::get_on`], wrapped by other stories' anchored objects only when `cross` is set. - fn get_with(&self, doc: &Document, sid: StoryId, on: ShownOn, cross: bool) -> Arc { + /// [`Cache::get_on`], wrapped by other stories' anchored objects only when `cross` is set, for + /// a story `depth` hosts down from the story asked for. + fn get_with(&self, doc: &Document, sid: StoryId, on: ShownOn, cross: bool, depth: usize) -> Arc { let Some(story) = doc.stories.get(&sid) else { return Arc::new(ComposedStory { story: sid, ..Default::default() }) }; let (mut sig, mut keep_items) = signature(doc, story); let neighbours = if cross { crate::wrap::neighbours(doc, sid) } else { Vec::new() }; @@ -117,6 +119,24 @@ impl Cache { keep_stories.push(ns.clone()); } } + // Anchored frames compose where their host story places them, so the host is composed + // first and the placements are part of the signature. + let placed = if depth < crate::placed::MAX_DEPTH { + crate::placed::placements(doc, sid, &mut |host| self.get_with(doc, host, ShownOn::Own, true, depth + 1)) + } else { + Vec::new() + }; + for (id, p) in &placed { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + (id, p.spread, p.xf.as_coeffs().map(f64::to_bits)).hash(&mut h); + // The placed spread's pages give the frame its page, side and page rect. + for pg in doc.spread(p.spread).map_or(&[][..], |sp| &sp.pages[..]) { + let m = &pg.margins; + (pg.side as u8, [pg.x, pg.width, pg.height, m.top, m.bottom, m.inside, m.outside].map(f64::to_bits)).hash(&mut h); + } + sig.push(h.finish() as usize); + } let key = (sid, on, !neighbours.is_empty()); // The key holds the page's index, which a renumbering doesn't change: its name (section // start number, style, prefix) is part of the signature. @@ -186,7 +206,7 @@ impl Cache { } // Advanced Type sizes super/subscripts. let a = doc.settings.advanced_type; - sig.extend([a.superscript_size, a.superscript_position, a.subscript_size, a.subscript_position].map(|v| v.to_bits() as usize)); + sig.extend([a.superscript_size, a.superscript_position, a.subscript_size, a.subscript_position].into_iter().flat_map(bits)); // Missing glyphs: fallback fonts or the font's box. sig.push(usize::from(doc.settings.glyph_fallback)); // Named lists continue from earlier stories. @@ -209,11 +229,11 @@ impl Cache { // Parent-page items are composed per page: markers show its name, variables need its index. let page = page.filter(|_| with_vars); let running = running.then(|| self.running_index(doc)); - let others: Vec> = neighbours.iter().map(|n| self.neighbour(doc, *n)).collect(); + let others: Vec> = neighbours.iter().map(|n| self.neighbour(doc, *n, depth)).collect(); let out = Arc::new(crate::wrap::compose_among( doc, sid, - &ComposeOptions { page_name, section_marker, page, running, label: None, xrefs: with_xrefs.then(|| self.xref_index(doc)) }, + &ComposeOptions { page_name, section_marker, page, running, label: None, xrefs: with_xrefs.then(|| self.xref_index(doc)), placed }, &others.iter().map(|o| &**o).collect::>(), )); let mut g = self.map.lock().unwrap_or_else(PoisonError::into_inner); @@ -295,13 +315,13 @@ impl Cache { /// Story `sid` composed for the wrap of its anchored objects in other stories: without other /// stories' anchored objects (no cycles), and outside the cache when it needs the document-wide /// indexes (they compose every story). - fn neighbour(&self, doc: &Document, sid: StoryId) -> Arc { + fn neighbour(&self, doc: &Document, sid: StoryId, depth: usize) -> Arc { let indexed = doc.stories.get(&sid).is_some_and(|st| crate::xref::has_xrefs(st) || (crate::vars::has_vars(st) && crate::vars::has_running(doc, st))); if indexed { Arc::new(crate::wrap::compose_among(doc, sid, &ComposeOptions::default(), &[])) } else { - self.get_with(doc, sid, ShownOn::Own, false) + self.get_with(doc, sid, ShownOn::Own, false, depth) } } @@ -338,6 +358,13 @@ impl Cache { } } +/// Both halves of `v`'s bits: a 32-bit `usize` (wasm) would drop the high half, where whole +/// numbers keep their differences. +fn bits(v: f64) -> [usize; 2] { + let b = v.to_bits(); + [(b & 0xffff_ffff) as usize, (b >> 32) as usize] +} + fn signature(doc: &Document, story: &Arc) -> (Vec, Vec>) { // The document's font scope: another document's fonts of the same name set it differently. // Sections name the pages under the frames (page-number and section markers). @@ -348,9 +375,9 @@ fn signature(doc: &Document, story: &Arc) -> (Vec, Vec>) Arc::as_ptr(&doc.styles) as usize, sections_hash(doc) as usize, doc.font_scope as usize, - g.start.to_bits() as usize, - g.increment.to_bits() as usize, + usize::from(g.relative_to == designcraft_doc::GridRelative::TopMargin), ]; + sig.extend([g.start, g.increment].into_iter().flat_map(bits)); let mut keep = Vec::new(); let mut spreads = Vec::new(); for f in &story.frames { @@ -373,6 +400,12 @@ fn signature(doc: &Document, story: &Arc) -> (Vec, Vec>) sig.push(loc.top()); if !spreads.contains(&loc.spread) { spreads.push(loc.spread); + // The page under a frame (found by x) gives its grid origin, page rect and side. + for p in &sp.pages { + let m = &p.margins; + sig.extend([p.x, p.width, p.height, m.top, m.bottom, m.inside, m.outside].into_iter().flat_map(bits)); + sig.push(p.side as usize); + } for it in &sp.items { let mut wraps = false; it.walk(&mut |i| wraps |= i.has_wrap()); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index a3fac1eab..6b6a61618 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -23,6 +23,7 @@ pub mod optical; mod outline; mod overlay; mod parabox; +mod placed; mod ruby; pub mod shape; pub mod shatai; @@ -50,6 +51,7 @@ use crate::notes::Notes; pub use crate::notes::{find_note, hit_note, hit_note_with, note_caret}; pub use crate::outline::FrameOutline; use crate::parabox::ParaBox; +pub use crate::placed::Placement; use crate::shape::{Glyph, StyleTable, SubstCtx}; pub use crate::table::{BorderHit, PlacedCell, StrokeSeg, TableFrag, cell_caret, find_cell, hit_border, hit_cell, hit_cell_with}; @@ -627,6 +629,9 @@ pub struct ComposeOptions { pub label: Option, /// Anchor pages for cross-references (needed when the story contains cross-references). pub xrefs: Option>, + /// Where the story's anchored frames sit on their spreads; an anchored frame not listed is + /// composed where it is stored, on no page. + pub placed: Vec<(ItemId, Placement)>, } /// Nesting depth past which wrap obstacles inside groups are not collected. @@ -659,21 +664,34 @@ fn wrap_obstacles(it: &Item, parent: Affine, inv: Affine, skip: ItemId, left_pag /// Build the frame specs of a story from the document (geometry, wrap, page names, grid). pub fn frame_specs(doc: &Document, sid: StoryId) -> Vec { + frame_specs_placed(doc, sid, &[]) +} + +/// [`frame_specs`] with anchored frames where their host story placed them (`placed`). +pub(crate) fn frame_specs_placed(doc: &Document, sid: StoryId, placed: &[(ItemId, Placement)]) -> Vec { let Some(st) = doc.story(sid) else { return vec![] }; let mut out = Vec::with_capacity(st.frames.len()); for &fid in &st.frames { let loc = doc.find(fid); let Some(item) = loc.as_ref().and_then(|l| doc.item_at(l)).or_else(|| doc.anchored_item(fid)) else { continue }; let Some(tf) = item.text_frame() else { continue }; - let parent = loc.as_ref().map(|l| doc.parent_xf(l)).unwrap_or(designcraft_geom::Affine::IDENTITY); + // An anchored frame takes its page, page side, page rect and grid from where it is placed. + let placement = if loc.is_none() { placed.iter().find(|(id, _)| *id == fid).map(|(_, p)| *p) } else { None }; + let parent = match (&loc, placement) { + (Some(l), _) => doc.parent_xf(l), + (None, Some(p)) => p.xf, + (None, None) => Affine::IDENTITY, + }; let xf = parent * item.xf; // Where the frame is on the spread (a group's transform included), to find its page. let center_x = parent.transform_rect_bbox(item.bounds()).center().x; let inv = xf.inverse(); let mut exclusions = Vec::new(); - let spread_ref = loc.as_ref().map(|l| l.spread); + let spread_ref = loc.as_ref().map(|l| l.spread).or(placement.map(|p| p.spread)); let spread = spread_ref.and_then(|r| doc.spread(r)); + // Page items wrap the text of frames on the spread, not of anchored frames. if !tf.options.ignore_wrap + && loc.is_some() && let Some(sp) = spread { let left = |x: f64| sp.page_at_x(x).and_then(|pi| sp.pages.get(pi)).is_some_and(|p| p.side == designcraft_doc::PageSide::Left); @@ -709,19 +727,28 @@ pub fn frame_specs(doc: &Document, sid: StoryId) -> Vec { let left_page = side == Some(designcraft_doc::PageSide::Left); let right_page = side == Some(designcraft_doc::PageSide::Right); let section_marker = page.map(|abs| section_marker(doc, abs)); - // The page under the frame and its margins, in inner space (bounding boxes). - let page_rect = match (spread_ref, spread) { - (_, Some(sp)) => sp - .page_at_x(center_x) - .and_then(|pi| sp.pages.get(pi)) - .map(|pg| (inv.transform_rect_bbox(pg.bounds()), inv.transform_rect_bbox(pg.margin_rect()))), - _ => None, - }; + // The page under the frame, and its bounds and margins in inner space (bounding boxes). + let under = spread.and_then(|sp| sp.page_at_x(center_x).and_then(|pi| sp.pages.get(pi))); + let page_rect = under.map(|pg| (inv.transform_rect_bbox(pg.bounds()), inv.transform_rect_bbox(pg.margin_rect()))); let g = &doc.settings.baseline_grid; - let (inc, start) = tf.options.baseline_grid.unwrap_or((g.increment, g.start)); // Grid lines are at spread y = start + n·inc (page tops are y = 0); map into inner space (translation only). let ty = xf.translation().y; - let grid = (inc > 0.0).then_some((start - ty, inc)); + let (start, inc) = match tf.options.baseline_grid { + None => (under.map_or(g.start, |pg| g.origin(pg)), g.increment), + Some(f) => { + use designcraft_doc::FrameGridRelative as R; + // The frame's own edges are in inner space; `ty` takes them to spread y as it takes + // the grid back, so a frame-relative grid keeps its place in a turned frame. + let from = match f.relative_to { + R::TopOfPage => 0.0, + R::TopMargin => under.map_or(0.0, |pg| pg.margins.top), + R::TopOfFrame => ty + item.inner_bounds().y0, + R::TopInset => ty + item.text_area().y0, + }; + (from + f.start, f.increment) + } + }; + let grid = (inc > 0.0 && inc.is_finite() && start.is_finite()).then_some((start - ty, inc)); // Type on a path: one line as long as the path (from the start offset). let (area, opts) = match &tf.options.path { Some(pt) => { @@ -788,10 +815,23 @@ pub fn frame_specs(doc: &Document, sid: StoryId) -> Vec { /// Compose a story of `doc` through its frames, with the text wrap of page items and of anchored /// objects ([`wrap`]). +/// Anchored frames are composed where their host story places them (unless `opts` places them). pub fn compose_story(doc: &Document, sid: StoryId, opts: &ComposeOptions) -> ComposedStory { + compose_story_at(doc, sid, opts, 0) +} + +/// [`compose_story`] for a story `depth` hosts down from the story asked for. +fn compose_story_at(doc: &Document, sid: StoryId, opts: &ComposeOptions, depth: usize) -> ComposedStory { let others: Vec = wrap::neighbours(doc, sid).into_iter().map(|o| wrap::compose_among(doc, o, &ComposeOptions::default(), &[])).collect(); - wrap::compose_among(doc, sid, opts, &others.iter().collect::>()) + let others: Vec<&ComposedStory> = others.iter().collect(); + if opts.placed.is_empty() && depth < placed::MAX_DEPTH { + let placed = placed::placements(doc, sid, &mut |host| Arc::new(compose_story_at(doc, host, &ComposeOptions::default(), depth + 1))); + if !placed.is_empty() { + return wrap::compose_among(doc, sid, &ComposeOptions { placed, ..opts.clone() }, &others); + } + } + wrap::compose_among(doc, sid, opts, &others) } const DEFAULT_TAB: f64 = 36.0; @@ -868,6 +908,12 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C let mut info: Vec = Vec::with_capacity(np); let mut force_col = vec![false; np]; let mut line_cap: Vec> = vec![None; np]; + // Hyphenate Across Column off: the hyphenation points (story bytes) a paragraph is re-laid + // without, because a line ending at one of them ended a column or frame. Each re-lay leaves + // out one more point of the paragraph, so they are bounded by its points; the cap only guards + // against keep options clearing them over and over. + let mut no_hyph: Vec> = vec![Vec::new(); np]; + let mut hyph_relays = 0usize; let mut restores = 0usize; let mut pi = 0; let var_story = vars::has_vars(story); @@ -907,7 +953,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C && let Some(j) = trial_failed(&mut trial, &mut limits, balance_runs < balance_budget) { balance_runs += 1; - rewind(j, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap); + rewind(j, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap, &mut no_hyph); pi = j; continue 'paras; } @@ -917,7 +963,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C && let Some(j) = balance_end(&mut trial, &mut limits, &cur, &cols, frames, &out, np, balance_runs < balance_budget) { balance_runs += 1; - rewind(j, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap); + rewind(j, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap, &mut no_hyph); pi = j; continue 'paras; } @@ -971,7 +1017,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C if !table::place_table(doc, t, anchor, pi, &pp, frames, &cols, &mut cur, &mut out, opts) { if let Some(j) = trial_failed(&mut trial, &mut limits, balance_runs < balance_budget) { balance_runs += 1; - rewind(j, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap); + rewind(j, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap, &mut no_hyph); pi = j; continue 'paras; } @@ -1017,9 +1063,9 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C }; if !story.endnotes.is_empty() { // Endnote reference numbers continue through the document. - let first = doc.endnote_start(story.id) + story.text[..prange.start].matches(designcraft_doc::ENDNOTE_REF).count() as u32; + let first = doc.endnote_start(story.id).saturating_add(story.text[..prange.start].matches(designcraft_doc::ENDNOTE_REF).count() as u32); for (k, (i, _)) in story.text[prange.clone()].match_indices(designcraft_doc::ENDNOTE_REF).enumerate() { - sub.notes.insert(prange.start + i, doc.endnote_options.label(first + k as u32)); + sub.notes.insert(prange.start + i, doc.endnote_options.label(first.saturating_add(k as u32))); } } if !story.objects.is_empty() { @@ -1090,7 +1136,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C let 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, String)> = Vec::new(); for _ in 0..3 { // The same drop cap, spacing, hyphenation and breaker as the layout below. @@ -1106,7 +1152,8 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C }; apply_desired_spacing(&mut gl, &pp); mojikumi::apply(&mut gl, &doc.styles, &pp.mojikumi); - let hy = hyphenation_points(&story.text, &gl, &pp, &hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), &base_chars)); + let mut hy = hyphenation_points(&story.text, &gl, &pp, &hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), &base_chars)); + suppress_hyphens(&mut hy, &gl, no_hyph.get(pi).map_or(&[], Vec::as_slice)); let breaks = if pp.composer.single_line() || gl.iter().any(|g| g.ch == '\t') || gl.len() > 4000 { let tab = |j: usize, x: f64, i: usize| { let ind = pp.left_indent + if j == 0 { pp.first_line_indent } else { 0.0 }; @@ -1241,9 +1288,11 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C bidi::resolve_mirroring(&mut glyphs, &bidi_info); apply_desired_spacing(&mut glyphs, &pp); mojikumi::apply(&mut glyphs, &doc.styles, &pp.mojikumi); - let hyph_after = hyphenation_points(&story.text, &glyphs, &pp, &hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), &base_chars)); + let mut hyph_after = + hyphenation_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))) @@ -1348,7 +1397,18 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C if !t.done { trial = Some(t); balance_runs += 1; - rewind(key.1, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap); + rewind( + key.1, + &snaps, + ¬e_snaps, + &mut notes, + &mut out, + &mut cur, + &mut list_counter, + &mut force_col, + &mut line_cap, + &mut no_hyph, + ); pi = key.1; continue 'paras; } @@ -1384,6 +1444,8 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C let mut line_no = 0usize; // Paragraph line number of the first line in the current column. let mut col_first_line = 0usize; + // The story byte at which the last line set ended at an automatic hyphenation point. + let mut hyphen_at: Option = None; let has_tabs = glyphs.iter().any(|g| g.ch == '\t'); let mut first_line_rect: Option<(usize, f64, f64, f64)> = None; // frame, baseline, ascent, x-span let rtl = pp.direction == designcraft_doc::TextDirection::RightToLeft; @@ -1401,7 +1463,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C if cur.fi >= frames.len() { if let Some(j) = trial_failed(&mut trial, &mut limits, balance_runs < balance_budget) { balance_runs += 1; - rewind(j, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap); + rewind(j, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap, &mut no_hyph); pi = j; continue 'paras; } @@ -1628,6 +1690,17 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C 0.0 }; let fits = baseline + fit_descent <= col.y1 - reserve + 0.01 && !capped; + if !fits + && !pp.hyph_across_column + && line_no > col_first_line + && let Some(at) = hyphen_at + && hyph_relays < story.text.len().saturating_add(64).saturating_mul(restores.saturating_add(1)) + { + hyph_relays += 1; + no_hyph[pi].push(at); + rewind(pi, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap, &mut no_hyph); + continue 'paras; + } if !fits { if cur.can_next_sub() { g0 = s; @@ -1649,7 +1722,18 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C }; if let Some(j) = j { split_runs += 1; - rewind(j, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap); + rewind( + j, + &snaps, + ¬e_snaps, + &mut notes, + &mut out, + &mut cur, + &mut list_counter, + &mut force_col, + &mut line_cap, + &mut no_hyph, + ); pi = j; continue 'paras; } @@ -1682,7 +1766,18 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C j } }; - rewind(j, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap); + rewind( + j, + &snaps, + ¬e_snaps, + &mut notes, + &mut out, + &mut cur, + &mut list_counter, + &mut force_col, + &mut line_cap, + &mut no_hyph, + ); pi = j; continue 'paras; } @@ -1794,7 +1889,18 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C if notes.earlier_columns_collide(&out.frames[cur.fi].lines, cur.fi, cur.col, &cols[cur.fi], r) && let Some(j) = out.frames[cur.fi].lines.first().map(|l| l.para) { - rewind(j, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap); + rewind( + j, + &snaps, + ¬e_snaps, + &mut notes, + &mut out, + &mut cur, + &mut list_counter, + &mut force_col, + &mut line_cap, + &mut no_hyph, + ); pi = j; continue 'paras; } @@ -1826,6 +1932,8 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C cur.last_descent = desc; cur.pending = 0.0; cur.grid_next = grid_end.map(|end| (baseline, end)); + hyphen_at = + e.checked_sub(1).filter(|&i| b.hyphen && hyph_after.get(i) == Some(&true)).and_then(|i| glyphs.get(i)).map(|g| g.byte + g.len); line_no += 1; // A column / frame / page break inside the paragraph: the rest of it continues in the // new column/frame/page, re-broken there. (A break that ends the paragraph moves the @@ -1953,7 +2061,18 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C if !t.done { split_trial = Some(t); split_runs += 1; - rewind(key.2, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap); + rewind( + key.2, + &snaps, + ¬e_snaps, + &mut notes, + &mut out, + &mut cur, + &mut list_counter, + &mut force_col, + &mut line_cap, + &mut no_hyph, + ); pi = key.2; continue 'paras; } @@ -2184,8 +2303,22 @@ pub fn column_rule_rects(columns: &[Rect], lines: &[Line], opts: &TextFrameOptio out } +/// 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) { + 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, @@ -2203,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, @@ -2318,9 +2452,11 @@ fn rewind( list_counter: &mut ListCounter, force_col: &mut [bool], line_cap: &mut [Option], + no_hyph: &mut [Vec], ) { force_col.iter_mut().skip(j + 1).for_each(|f| *f = false); line_cap.iter_mut().skip(j + 1).for_each(|c| *c = None); + no_hyph.iter_mut().skip(j + 1).for_each(Vec::clear); if let Some(s) = snaps.get(j) { s.restore(out, cur, list_counter); } @@ -3327,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::() - measure).max(0.0)) @@ -4020,6 +4156,18 @@ fn foreign_ranges( .collect() } +/// Leave out the hyphenation points after the glyphs that end at story bytes `at`. +fn suppress_hyphens(hy: &mut [bool], glyphs: &[Glyph], at: &[usize]) { + if at.is_empty() { + return; + } + for (h, g) in hy.iter_mut().zip(glyphs) { + if *h && at.contains(&(g.byte + g.len)) { + *h = false; + } + } +} + fn hyphenation_points( text: &str, glyphs: &[Glyph], @@ -4040,7 +4188,7 @@ fn hyphenation_points( // Words repeat a lot: remember their points per set of limits. static CACHE: Mutex), Box<[usize]>>)>> = Mutex::new(Vec::new()); let key = (lim.min_word, lim.after_first, lim.before_last, lim.capitalized); - let mut guard = CACHE.lock().unwrap_or_else(|e| e.into_inner()); + let mut guard = CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let idx = match guard.iter().position(|e| e.0 == key) { Some(i) => i, None => { @@ -4541,7 +4689,7 @@ pub fn adjacent_row(l: &Line, x: f64, caret_y: f64, up: bool) -> Option { // count as still inside the note. let over = |r: &(f64, f64, f64)| x >= r.1 - 0.01 && x < r.2 - 0.01; let candidates = rows.iter().filter(|r| over(r)).filter(|r| if up { r.0 < caret_y - ROW_Y } else { r.0 > caret_y + ROW_Y }); - if up { candidates.map(|r| r.0).max_by(|a, b| a.total_cmp(b)) } else { candidates.map(|r| r.0).min_by(|a, b| a.total_cmp(b)) } + if up { candidates.map(|r| r.0).max_by(f64::total_cmp) } else { candidates.map(|r| r.0).min_by(f64::total_cmp) } } #[cfg(test)] diff --git a/crates/compose/src/notes.rs b/crates/compose/src/notes.rs index 2a465fbfa..75d143928 100644 --- a/crates/compose/src/notes.rs +++ b/crates/compose/src/notes.rs @@ -130,7 +130,7 @@ impl Notes { self.num = o.start_at; } self.numbers[k] = self.num; - self.num += 1; + self.num = self.num.saturating_add(1); sub.notes.insert(self.refs[k], o.label(self.numbers[k], false)); } sub.note_position = o.ref_position; @@ -180,6 +180,7 @@ impl Notes { running: opts.running.clone(), label: Some(label), xrefs: opts.xrefs.clone(), + placed: Vec::new(), }; let cs = crate::compose(doc, &self.notes[k].text, std::slice::from_ref(&spec), &nopts); let lines = cs.frames.first().map(|ft| ft.lines.as_slice()).unwrap_or_default(); diff --git a/crates/compose/src/parabox.rs b/crates/compose/src/parabox.rs index b8b58cb44..f6b90e127 100644 --- a/crates/compose/src/parabox.rs +++ b/crates/compose/src/parabox.rs @@ -122,6 +122,45 @@ pub(crate) fn draw(out: &mut ComposedStory, boxes: &[Option], frames: & } } +/// The shading box for one part of a paragraph run, if it has any area. +fn shading_deco(s: &Shading, part: &Part<'_>, frames: &[FrameSpec], first_part: bool, last_part: bool) -> Option { + let r = inner_rect(&part.lines, s.width, s.top, s.bottom)?; + let [t, l, bo, rr] = s.offsets; + let mut rect = Rect::new(r.x0 - l, r.y0 - t, r.x1 + rr, r.y1 + bo); + if s.clip + && let Some(f) = frames.get(part.fi) + { + rect = rect.intersect(frame_rect(f)); + } + if rect.width() > 0.0 && rect.height() > 0.0 { + // Corners stay square where the box is cut by a split. + let corners = cut_corners(s.corners, !first_part, !last_part); + let path = (!corners.iter().all(Corner::is_none)).then(|| box_outline(rect, &corners, [true; 4])); + return Some(Deco { rect, color: s.color.clone(), tint: s.tint, path, nonprinting: s.nonprinting }); + } + None +} + +/// The border strokes (and plain edges) for one part of a paragraph run, pushed onto `decos`. +fn border_decos(bd: &Border, part: &Part<'_>, first_part: bool, last_part: bool, decos: &mut Vec<(usize, bool, Deco)>) { + let Some(r) = inner_rect(&part.lines, bd.width, bd.top, bd.bottom) else { return }; + let [t, l, bo, rr] = bd.offsets; + let o = Rect::new(r.x0 - l, r.y0 - t, r.x1 + rr, r.y1 + bo); + let open_top = !first_part && !bd.display_if_splits; + let open_bottom = !last_part && !bd.display_if_splits; + for (path, gap) in border_paths(bd, o, open_top, open_bottom) { + let (color, tint) = if gap { (bd.gap_color.clone(), bd.gap_tint) } else { (bd.color.clone(), bd.tint) }; + decos.push((part.fi, false, Deco { rect: path.bounding_box(), color, tint, path: Some(path), nonprinting: false })); + } + if is_plain(bd, open_top, open_bottom) { + decos.extend( + plain_edges(bd, o, open_top, open_bottom) + .into_iter() + .map(|rect| (part.fi, false, Deco { rect, color: bd.color.clone(), tint: bd.tint, path: None, nonprinting: false })), + ); + } +} + /// The decorations of paragraphs `paras` sharing box `b`: (frame, drawn under the rest, deco). fn group_decos(out: &ComposedStory, paras: std::ops::RangeInclusive, b: &ParaBox, frames: &[FrameSpec]) -> Vec<(usize, bool, Deco)> { let mut parts: Vec> = Vec::new(); @@ -136,40 +175,12 @@ fn group_decos(out: &ComposedStory, paras: std::ops::RangeInclusive, b: & for (k, part) in parts.iter().enumerate() { let (first_part, last_part) = (k == 0, k + 1 == n); if let Some(s) = &b.shading - && let Some(r) = inner_rect(&part.lines, s.width, s.top, s.bottom) + && let Some(deco) = shading_deco(s, part, frames, first_part, last_part) { - let [t, l, bo, rr] = s.offsets; - let mut rect = Rect::new(r.x0 - l, r.y0 - t, r.x1 + rr, r.y1 + bo); - if s.clip - && let Some(f) = frames.get(part.fi) - { - rect = rect.intersect(frame_rect(f)); - } - if rect.width() > 0.0 && rect.height() > 0.0 { - // Corners stay square where the box is cut by a split. - let corners = cut_corners(s.corners, !first_part, !last_part); - let path = (!corners.iter().all(Corner::is_none)).then(|| box_outline(rect, &corners, [true; 4])); - decos.push((part.fi, true, Deco { rect, color: s.color.clone(), tint: s.tint, path, nonprinting: s.nonprinting })); - } + decos.push((part.fi, true, deco)); } - if let Some(bd) = &b.border - && let Some(r) = inner_rect(&part.lines, bd.width, bd.top, bd.bottom) - { - let [t, l, bo, rr] = bd.offsets; - let o = Rect::new(r.x0 - l, r.y0 - t, r.x1 + rr, r.y1 + bo); - let open_top = !first_part && !bd.display_if_splits; - let open_bottom = !last_part && !bd.display_if_splits; - for (path, gap) in border_paths(bd, o, open_top, open_bottom) { - let (color, tint) = if gap { (bd.gap_color.clone(), bd.gap_tint) } else { (bd.color.clone(), bd.tint) }; - decos.push((part.fi, false, Deco { rect: path.bounding_box(), color, tint, path: Some(path), nonprinting: false })); - } - if is_plain(bd, open_top, open_bottom) { - decos.extend( - plain_edges(bd, o, open_top, open_bottom) - .into_iter() - .map(|rect| (part.fi, false, Deco { rect, color: bd.color.clone(), tint: bd.tint, path: None, nonprinting: false })), - ); - } + if let Some(bd) = &b.border { + border_decos(bd, part, first_part, last_part, &mut decos); } } decos diff --git a/crates/compose/src/placed.rs b/crates/compose/src/placed.rs new file mode 100644 index 000000000..200ff6e3c --- /dev/null +++ b/crates/compose/src/placed.rs @@ -0,0 +1,84 @@ +//! Where anchored text frames sit on their spread. +//! +//! An anchored frame is not a spread item: its host story's composition places it on a line. Its +//! own story is composed against that placement (page, page side, page rect, baseline grid), so +//! the host story is composed first. + +use std::sync::Arc; + +use designcraft_doc::{Document, Item, ItemId, SpreadRef, StoryId}; +use designcraft_geom::Affine; + +use crate::{ComposedStory, FrameText}; + +/// Hosts nested deeper than this (a note anchored in a note anchored in …, or stories anchored in +/// each other in a cycle) are composed where they are stored. +pub(crate) const MAX_DEPTH: usize = 8; + +/// An anchored item's parent space on its spread, where its host story's composition placed it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Placement { + pub spread: SpreadRef, + /// The item's parent space → spread space. + pub xf: Affine, +} + +/// The placements of `sid`'s anchored frames, from their host stories composed by `host`. +pub(crate) fn placements(doc: &Document, sid: StoryId, host: &mut dyn FnMut(StoryId) -> Arc) -> Vec<(ItemId, Placement)> { + let Some(st) = doc.story(sid) else { return Vec::new() }; + let mut anchored = None; + let mut out = Vec::new(); + for &fid in &st.frames { + if doc.find(fid).is_some() { + continue; + } + let items = anchored.get_or_insert_with(|| doc.anchored_items()); + // A frame anchored in its own story would need its own composition to place it. + let Some(owner) = items.iter().find_map(|(owner, it)| (it.id == fid).then_some(*owner)).filter(|o| *o != sid) else { continue }; + if let Some(p) = locate(doc, &host(owner), fid) { + out.push((fid, p)); + } + } + out +} + +/// Where `cs` (a host story's composition) places item `fid`: in its frames' anchored objects, +/// footnotes and table cells. +fn locate(doc: &Document, cs: &ComposedStory, fid: ItemId) -> Option { + cs.frames.iter().find_map(|ft| { + let loc = doc.find(ft.frame)?; + let frame = doc.item_at(&loc)?; + let xf = in_frame(ft, doc.parent_xf(&loc) * doc.text_xf(frame), fid, 0)?; + Some(Placement { spread: loc.spread, xf }) + }) +} + +/// The parent space of `fid` among the objects of `ft`, whose text space maps to the spread by +/// `xf`. +fn in_frame(ft: &FrameText, xf: Affine, fid: ItemId, depth: usize) -> Option { + if depth > MAX_DEPTH { + return None; + } + let objects = ft.objects.iter().find_map(|o| in_item(&o.object.item, xf * Affine::translate(o.origin.to_vec2()), fid, 0)); + objects + .or_else(|| ft.notes.iter().find_map(|n| in_frame(n.text.frames.first()?, xf * Affine::translate(n.origin.to_vec2()), fid, depth + 1))) + .or_else(|| { + ft.tables + .iter() + .flat_map(|t| &t.cells) + .find_map(|c| in_frame(c.text.frames.first()?, xf * Affine::translate(c.origin.to_vec2()), fid, depth + 1)) + }) +} + +/// The parent space of `fid` in `it` (it or a group member), `it`'s parent space mapping to the +/// spread by `parent`. +fn in_item(it: &Item, parent: Affine, fid: ItemId, depth: usize) -> Option { + if it.id == fid { + return Some(parent); + } + if depth > crate::MAX_WRAP_DEPTH { + return None; + } + let xf = parent * it.xf; + it.children().iter().find_map(|c| in_item(c, xf, fid, depth + 1)) +} diff --git a/crates/compose/src/ruby.rs b/crates/compose/src/ruby.rs index 1afea6b0d..47c48a728 100644 --- a/crates/compose/src/ruby.rs +++ b/crates/compose/src/ruby.rs @@ -71,6 +71,36 @@ fn tcy_char(c: char, roman: bool) -> bool { c.is_ascii_digit() || (roman && c.is_ascii_alphabetic()) } +/// Tate-chu-yoko in vertical ruby: each short run of digits (and Latin letters) is set in one +/// ruby em across the line, scaled down to fit when the spec asks for it. +fn apply_tcy(glyphs: &mut [RubyGlyph], spec: &RubySpec, size: f64) { + let roman = spec.auto_tcy_include_roman; + let mut i = 0; + while i < glyphs.len() { + let j = i + glyphs.get(i..).unwrap_or_default().iter().take_while(|g| tcy_char(g.ch, roman)).count(); + if j == i { + i += 1; + continue; + } + if u32::try_from(j - i).is_ok_and(|n| n <= spec.auto_tcy_digits) + && let Some(run) = glyphs.get_mut(i..j) + { + let total: f64 = run.iter().map(|g| g.adv).sum(); + let f = if spec.auto_tcy_auto_scale && total > size && total > 0.0 { size / total } else { 1.0 }; + let mut across = -total * f / 2.0; + for (n, g) in run.iter_mut().enumerate() { + g.tcy = Some([size / 2.0, across + g.x * f, size]); + across += g.adv * f; + g.sx *= f; + g.x = 0.0; + g.adv = if n == 0 { size } else { 0.0 }; + g.joined = n > 0; + } + } + i = j; + } +} + /// Shape `text` as the ruby of parent text `parent_size` points big. fn shape_ruby(db: &ScopedFonts<'_>, parent: FaceRef, text: &str, spec: &RubySpec, parent_size: f64, fallback: bool, vertical: bool) -> Shaped { let size = spec.size_for(parent_size); @@ -96,31 +126,7 @@ fn shape_ruby(db: &ScopedFonts<'_>, parent: FaceRef, text: &str, spec: &RubySpec .collect(); // Tate-chu-yoko: short runs of digits (and Latin letters) take one ruby em along the line. if vertical && spec.auto_tcy_digits > 0 { - let roman = spec.auto_tcy_include_roman; - let mut i = 0; - while i < glyphs.len() { - let j = i + glyphs.get(i..).unwrap_or_default().iter().take_while(|g| tcy_char(g.ch, roman)).count(); - if j == i { - i += 1; - continue; - } - if u32::try_from(j - i).is_ok_and(|n| n <= spec.auto_tcy_digits) - && let Some(run) = glyphs.get_mut(i..j) - { - let total: f64 = run.iter().map(|g| g.adv).sum(); - let f = if spec.auto_tcy_auto_scale && total > size && total > 0.0 { size / total } else { 1.0 }; - let mut across = -total * f / 2.0; - for (n, g) in run.iter_mut().enumerate() { - g.tcy = Some([size / 2.0, across + g.x * f, size]); - across += g.adv * f; - g.sx *= f; - g.x = 0.0; - g.adv = if n == 0 { size } else { 0.0 }; - g.joined = n > 0; - } - } - i = j; - } + apply_tcy(&mut glyphs, spec, size); } // Pen positions: a joined glyph sits at its group's start. let mut pen = 0.0; diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs index ffbc4857d..0f739e16e 100644 --- a/crates/compose/src/shape.rs +++ b/crates/compose/src/shape.rs @@ -950,10 +950,10 @@ static WORD_CACHE: RwLock>)>> = RwLock::new(Ve const WORD_CACHE_MAX: usize = 50_000; fn word_map(key: WordKey) -> Arc> { - if let Some((_, m)) = WORD_CACHE.read().unwrap_or_else(|e| e.into_inner()).iter().find(|e| e.0 == key) { + if let Some((_, m)) = WORD_CACHE.read().unwrap_or_else(std::sync::PoisonError::into_inner).iter().find(|e| e.0 == key) { return m.clone(); } - let mut w = WORD_CACHE.write().unwrap_or_else(|e| e.into_inner()); + let mut w = WORD_CACHE.write().unwrap_or_else(std::sync::PoisonError::into_inner); if let Some((_, m)) = w.iter().find(|e| e.0 == key) { return m.clone(); } diff --git a/crates/compose/src/table.rs b/crates/compose/src/table.rs index 39219e43b..9a41a546e 100644 --- a/crates/compose/src/table.rs +++ b/crates/compose/src/table.rs @@ -343,6 +343,26 @@ pub(crate) fn place_table( true } +/// A cell's text cut to the lines that fit `clip_height`, with where the overset text begins. +/// Uses the same baseline/bounds test as auto-growth, and retains a prefix: overset text cannot +/// reappear after a line that did not fit. +fn clip_overset(lay: &CellLayout, clip_height: f64) -> Arc { + let Some(f) = lay.text.frames.first() else { return lay.text.clone() }; + let keep = lay.line_heights.iter().take_while(|h| **h <= clip_height + 0.01).count(); + let overset_at = f.lines.get(keep).map(|l| l.range.start); + let mut t = (*lay.text).clone(); + if let Some(frame) = t.frames.first_mut() { + frame.lines.truncate(keep); + frame.objects.retain(|o| o.line < keep); + frame.tables.retain(|table| table.line < keep); + frame.range.end = frame.lines.last().map_or(frame.range.start, |l| l.range.end); + } + if let Some(at) = overset_at { + t.overset_at = Some(at); + } + Arc::new(t) +} + /// Build one fragment from its rows and push it (with its glyph-less line) to the current frame. #[allow(clippy::too_many_arguments)] fn emit( @@ -407,24 +427,7 @@ fn emit( _ => 0.0, }; let overset = space < -0.01 || lay.text.is_overset(); - let mut text = lay.text.clone(); - if overset && let Some(f) = text.frames.first() { - // Use the same baseline/bounds test as auto-growth, and retain a prefix: - // overset text cannot reappear after a line that did not fit. - let keep = lay.line_heights.iter().take_while(|h| **h <= clip.height() + 0.01).count(); - let overset_at = f.lines.get(keep).map(|l| l.range.start); - let mut t = (*text).clone(); - if let Some(frame) = t.frames.first_mut() { - frame.lines.truncate(keep); - frame.objects.retain(|o| o.line < keep); - frame.tables.retain(|table| table.line < keep); - frame.range.end = frame.lines.last().map_or(frame.range.start, |l| l.range.end); - } - if let Some(at) = overset_at { - t.overset_at = Some(at); - } - text = Arc::new(t); - } + let text = if overset { clip_overset(lay, clip.height()) } else { lay.text.clone() }; cells.push(PlacedCell { row: r, col: c, diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index f9e8ba0fd..90b4ac3c4 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -1013,6 +1013,92 @@ fn hyphenation_zone_limits_ragged_hyphens() { assert!(free > 0 && zoned == free && huge == free, "{c:?}: {free} {zoned} {huge}"); } +#[test] +fn hyphenate_across_column_off_ends_no_column_with_a_hyphen() { + let text = CORPUS.join(" "); + // Column-end lines that are hyphenated, over frame heights that end the first column at each + // line in turn. + let ends = |across: bool, composer: designcraft_doc::Composer| { + let mut ends = 0; + let mut lines = 0; + for h in (30..400).step_by(3) { + let para = ParaAttrs { + align: Some(Align::Left), + hyph_weight: Some(0.0), + hyph_across_column: Some(across), + composer: Some(composer), + ..Default::default() + }; + let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 240.0, h as f64), para); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let col0: Vec<&Line> = all_lines(&cs).into_iter().filter(|l| l.column == 0).collect(); + ends += usize::from(col0.last().is_some_and(|l| l.hyphenated)); + lines += col0.len(); + // The frame's last line too, when the text goes on (overset). + let last = all_lines(&cs).into_iter().last(); + ends += usize::from(cs.is_overset() && last.is_some_and(|l| l.hyphenated && !l.last_in_para)); + } + (ends, lines) + }; + for c in [designcraft_doc::Composer::Paragraph, designcraft_doc::Composer::SingleLine] { + let (on, lines_on) = ends(true, c); + let (off, lines_off) = ends(false, c); + // With it on, columns do end in hyphens here; with it off, none does, and the columns + // still fill. + assert!(on > 3, "{c:?}: {on}"); + assert_eq!(off, 0, "{c:?}"); + assert!(lines_off * 10 >= lines_on * 9, "{c:?}: {lines_off} {lines_on}"); + } +} + +#[test] +fn hyphenate_across_column_off_keeps_nested_line_styles_on_their_lines() { + // The first line in a character style of another colour (the same widths): when its hyphen is + // left out at a column end, the style still covers exactly the first line as set. + let text = CORPUS.join(" "); + let compose = |w: f64, h: f64, across: bool| { + let para = ParaAttrs { + align: Some(Align::Left), + hyph_weight: Some(0.0), + hyph_across_column: Some(across), + nested_line_styles: Some(vec![designcraft_doc::NestedLineStyle { style: "Lead".into(), lines: 1 }]), + ..Default::default() + }; + let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, w, h), para); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2; + let chars = designcraft_doc::CharAttrs { fill: Some("[Registration]".into()), ..Default::default() }; + std::sync::Arc::make_mut(&mut d.styles).character.push(designcraft_doc::CharacterStyle { + name: "Lead".into(), + based_on: None, + chars, + shortcut: String::new(), + }); + compose_story(&d, sid, &ComposeOptions::default()) + }; + let mut checked = 0; + for w in (160..320).step_by(10) { + for h in (12..40).step_by(2) { + // Where, with the setting on, a hyphenated first line ends column 1. + let on = compose(w as f64, h as f64, true); + let lines = all_lines(&on); + if !(lines.iter().filter(|l| l.column == 0).count() == 1 && lines[0].hyphenated) { + continue; + } + let cs = compose(w as f64, h as f64, false); + let lines = all_lines(&cs); + assert!(!lines[0].hyphenated, "{w}×{h}"); + let lead = |l: &Line| { + l.glyphs.iter().filter(|g| g.len > 0 && g.visible).map(|g| cs.styles[g.style as usize].fill == "[Registration]").collect::>() + }; + assert!(lead(lines[0]).iter().all(|&r| r), "{w}×{h}: first line"); + assert!(lead(lines[1]).iter().all(|&r| !r), "{w}×{h}: second line"); + checked += 1; + } + } + assert!(checked > 3, "{checked}"); +} + #[test] fn discretionary_hyphen_replaces_automatic_points() { let text = "aaaa bbbb cccc extraordi\u{AD}narily dddd eeee"; @@ -1150,7 +1236,7 @@ fn nonbreaking_space_alone_fills_a_justified_line() { /// Story of `n` one-line filler paragraphs followed by `extra` paragraphs, in a 2-column frame. fn keep_doc(fillers: usize, extra: &[&str], height: f64) -> (Document, StoryId, Vec) { let mut parts: Vec = (0..fillers).map(|k| format!("Filler {k}")).collect(); - parts.extend(extra.iter().map(|s| s.to_string())); + parts.extend(extra.iter().map(ToString::to_string)); let text = parts.join("\n"); let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 400.0, height), ParaAttrs::default()); d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2; @@ -1272,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, para: ParaAttrs) -> f64 { + let text = "“Quoted” words."; + let first_x = |story: Option, 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. @@ -6611,7 +6747,7 @@ fn roman_word_break_breaks_inside_words_without_hyphens() { fn grid_doc(text: &str, para: ParaAttrs, edit: impl FnOnce(&mut Document, StoryId)) -> (Vec, (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)); + tf.options.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(0.0, 12.0)); } edit(&mut d, sid); // Vertical frames have no baseline grid. @@ -7266,6 +7402,158 @@ fn cache_recomposes_when_the_baseline_grid_changes() { assert!((la.baseline - lb.baseline).abs() > 1.0, "{} {}", la.baseline, lb.baseline); } +/// Two single pages 618 pt tall, top margins 36 and 48, each with an overset 11/13 story aligned +/// to a baseline grid (start 0, increment 13) and a frame filling its margin box (bottom 582). +fn grid_margin_doc(relative_to: designcraft_doc::GridRelative) -> (Document, [StoryId; 2]) { + let mut d = Document::new(&NewDocument { + height: 618.0, + pages: 2, + facing_pages: false, + margins: designcraft_doc::Margins::uniform(36.0), + ..Default::default() + }); + Arc::make_mut(&mut d.spreads[1]).pages[0].margins.top = 48.0; + Arc::make_mut(&mut d.spreads[1]).pages[0].local_margins = true; + d.settings.baseline_grid.start = 0.0; + d.settings.baseline_grid.increment = 13.0; + d.settings.baseline_grid.relative_to = relative_to; + let lid = d.default_layer(); + let para = ParaFormat { para: ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, ..Default::default() }; + let text = [LOREM; 12].join(" "); + let mut sids = Vec::new(); + for (si, top) in [(0, 36.0), (1, 48.0)] { + let (_, sid) = d.add_text_frame(SpreadRef::Doc(si), Rect::new(36.0, top, 336.0, 582.0), lid, &text, para.clone()).unwrap(); + let st = d.story_mut(sid).unwrap(); + st.paras[0].chars = + designcraft_doc::CharAttrs { size: Some(11.0), leading: Some(designcraft_doc::Leading::Points(13.0)), ..Default::default() }; + sids.push(sid); + } + (d, [sids[0], sids[1]]) +} + +/// Page y of a frame's baselines (the frame's inner space is its page's: it has no transform). +fn page_baselines(d: &Document, sid: StoryId) -> Vec { + let cs = compose_story(d, sid, &ComposeOptions::default()); + assert!(cs.is_overset()); + cs.frames[0].lines.iter().map(|l| l.baseline).collect() +} + +#[test] +fn baseline_grid_relative_to_the_top_margin_starts_at_each_pages_margin() { + use designcraft_doc::GridRelative; + let (d, [p1, p2]) = grid_margin_doc(GridRelative::TopMargin); + // Grid lines at 36 + 13n on page 1: 42 lines from 49 to 582. + let lines = page_baselines(&d, p1); + assert!((lines[0] - 49.0).abs() < 1e-6, "{lines:?}"); + assert!(lines.iter().enumerate().all(|(n, y)| (y - (49.0 + 13.0 * n as f64)).abs() < 1e-6), "{lines:?}"); + assert_eq!(lines.len(), 42); + // Page 2's own margin: lines at 48 + 13n. + let lines = page_baselines(&d, p2); + assert!((lines[0] - 61.0).abs() < 1e-6, "{lines:?}"); + // From the top of the page the lines are at 13n: the first at 52, and one line fewer. + let (d, [p1, _]) = grid_margin_doc(GridRelative::TopOfPage); + let lines = page_baselines(&d, p1); + assert!((lines[0] - 52.0).abs() < 1e-6, "{lines:?}"); + assert_eq!(lines.len(), 41); +} + +/// A frame's custom grid (start 10, increment 13) measured from the page top, the top margin +/// (36), the frame top (100) or the top inset (6 below it). +#[test] +fn frame_baseline_grid_relative_to_page_margin_frame_or_inset() { + use designcraft_doc::{FrameBaselineGrid, FrameGridRelative as R}; + let first_baseline = |relative_to: Option| { + let mut d = Document::new(&NewDocument { margins: designcraft_doc::Margins::uniform(36.0), ..Default::default() }); + let lid = d.default_layer(); + let para = ParaFormat { para: ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, ..Default::default() }; + let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 100.0, 336.0, 400.0), lid, "Grid", para).unwrap(); + let st = d.story_mut(sid).unwrap(); + st.paras[0].chars = + designcraft_doc::CharAttrs { size: Some(11.0), leading: Some(designcraft_doc::Leading::Points(13.0)), ..Default::default() }; + let tf = d.item_mut(fid).unwrap().text_frame_mut().unwrap(); + tf.options.inset = [6.0, 0.0, 0.0, 0.0]; + tf.options.baseline_grid = relative_to.map(|r| FrameBaselineGrid { relative_to: r, ..FrameBaselineGrid::new(10.0, 13.0) }); + // A document grid that matches none of the frame grids. + d.settings.baseline_grid.start = 0.0; + d.settings.baseline_grid.increment = 0.0; + compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].baseline + }; + // Without a grid the first baseline sits an ascent below the top inset. + let natural = first_baseline(None); + assert!(natural > 106.0 && natural < 120.0, "{natural}"); + for (r, origin) in [(R::TopOfPage, 10.0), (R::TopMargin, 46.0), (R::TopOfFrame, 110.0), (R::TopInset, 116.0)] { + let want = (0..).map(|n| origin + 13.0 * f64::from(n)).find(|y| *y >= natural - 1e-9).unwrap(); + let got = first_baseline(Some(r)); + assert!((got - want).abs() < 1e-6, "{r:?}: first baseline {got}, want {want} (natural {natural})"); + } +} + +/// A group's transform moves a frame from the left page of a spread to the right one: the grid +/// starts at the right page's top margin. +#[test] +fn baseline_grid_follows_a_grouped_frame_to_its_page() { + use designcraft_doc::{Content, GridRelative, Item, ItemId, Shape}; + let mut d = Document::new(&NewDocument { pages: 3, facing_pages: true, margins: designcraft_doc::Margins::uniform(36.0), ..Default::default() }); + Arc::make_mut(&mut d.spreads[1]).pages[1].margins.top = 48.0; + d.settings.baseline_grid.start = 0.0; + d.settings.baseline_grid.increment = 13.0; + d.settings.baseline_grid.relative_to = GridRelative::TopMargin; + let lid = d.default_layer(); + let para = ParaFormat { para: ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, ..Default::default() }; + let (fid, sid) = d.add_text_frame(SpreadRef::Doc(1), Rect::new(36.0, 36.0, 336.0, 582.0), lid, LOREM, para).unwrap(); + let sp = Arc::make_mut(&mut d.spreads[1]); + let at = sp.items.iter().position(|it| it.id == fid).unwrap(); + let frame = sp.items.remove(at); + let right = sp.pages[1].x; + let mut g = Item::new(ItemId(d.alloc()), lid, Shape::Group, designcraft_geom::PathData::default()); + g.content = Content::Group { items: vec![frame] }; + g.xf = designcraft_geom::Affine::translate((right, 0.0)); + Arc::make_mut(&mut d.spreads[1]).items.push(Arc::new(g)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let first = cs.frames[0].lines[0].baseline; + assert!((first - 61.0).abs() < 1e-6, "{first}"); +} + +#[test] +fn cache_recomposes_when_the_grid_reference_or_a_top_margin_changes() { + use designcraft_doc::GridRelative; + let (mut d, [p1, _]) = grid_margin_doc(GridRelative::TopOfPage); + let cache = Cache::new(); + let a = cache.get(&d, p1, None); + d.settings.baseline_grid.relative_to = GridRelative::TopMargin; + let b = cache.get(&d, p1, None); + assert!(!Arc::ptr_eq(&a, &b)); + assert!((a.frames[0].lines[0].baseline - b.frames[0].lines[0].baseline).abs() > 1.0); + Arc::make_mut(&mut d.spreads[0]).pages[0].margins.top = 40.0; + let c = cache.get(&d, p1, None); + assert!(!Arc::ptr_eq(&b, &c)); + assert!((b.frames[0].lines[0].baseline - c.frames[0].lines[0].baseline).abs() > 1.0); +} + +/// Pages trading places under a frame: the frame is on the other page, with its top margin. +#[test] +fn cache_recomposes_when_the_page_under_a_frame_changes() { + use designcraft_doc::GridRelative; + let mut d = Document::new(&NewDocument { pages: 3, facing_pages: true, margins: designcraft_doc::Margins::uniform(36.0), ..Default::default() }); + Arc::make_mut(&mut d.spreads[1]).pages[1].margins.top = 48.0; + d.settings.baseline_grid.start = 0.0; + d.settings.baseline_grid.increment = 13.0; + d.settings.baseline_grid.relative_to = GridRelative::TopMargin; + let lid = d.default_layer(); + let para = ParaFormat { para: ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, ..Default::default() }; + let x = d.spreads[1].pages[0].x; + let (_, sid) = d.add_text_frame(SpreadRef::Doc(1), Rect::new(x + 36.0, 36.0, x + 336.0, 582.0), lid, LOREM, para).unwrap(); + let cache = Cache::new(); + let a = cache.get(&d, sid, None); + let sp = Arc::make_mut(&mut d.spreads[1]); + let (x0, x1) = (sp.pages[0].x, sp.pages[1].x); + (sp.pages[0].x, sp.pages[1].x) = (x1, x0); + let b = cache.get(&d, sid, None); + assert!(!Arc::ptr_eq(&a, &b)); + assert_eq!(b.frames[0].lines[0].baseline, compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].baseline); + assert!((a.frames[0].lines[0].baseline - b.frames[0].lines[0].baseline).abs() > 1.0); +} + #[test] fn cache_recomposes_when_a_wrap_layer_is_hidden() { let (mut d, sid, _) = doc_with(&[LOREM; 2].join(" "), Rect::new(0.0, 0.0, 300.0, 800.0), ParaAttrs::default()); @@ -7451,3 +7739,91 @@ fn an_rtl_first_line_indent_is_at_the_right_edge() { assert!((left_edge(lines[0]) - rect.x0).abs() < 1.0, "left to right, first line at the edge: {}", left_edge(lines[0])); assert!((left_edge(lines[1]) - (rect.x0 + 10.0 * MM)).abs() < 1.0, "left to right, wrapped line indented: {}", left_edge(lines[1])); } + +/// A marginal note (an anchored text frame, Only Align First Line to Grid, 9/10) hangs 15 pt +/// above its anchor's baseline on a right-hand page. It composes against the document grid where +/// it is placed: its first line moves down onto the grid line, the second follows 10 pt below, +/// and its page is the host's. Composed where it was stored, it snapped to a grid measured from +/// its own top edge and sat on no page. +#[test] +fn anchored_text_frames_compose_against_the_grid_where_they_are_placed() { + use designcraft_doc::anchored::AnchorRelative as R; + let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() }); + d.settings.baseline_grid.start = 36.0; + d.settings.baseline_grid.increment = 10.0; + let lid = d.default_layer(); + let page = d.spreads[1].pages[1].clone(); + assert_eq!(page.side, designcraft_doc::PageSide::Right); + // Body lines at 46, 56, 66, … (on the grid) while the frame top is at 36. + let body = "One.\nTwo.\nThree.\nFour."; + let rect = Rect::new(page.x + 108.0, 36.0, page.x + page.width - 36.0, 400.0); + let (bf, sid) = d.add_text_frame(SpreadRef::Doc(1), rect, lid, body, ParaFormat::default()).unwrap(); + d.item_mut(bf).unwrap().text_frame_mut().unwrap().options.first_baseline = FirstBaseline::Leading; + let nine_ten = |f: &mut designcraft_doc::story::CharFormat| { + f.over.size = Some(9.0); + f.over.leading = Some(designcraft_doc::Leading::Points(10.0)); + }; + d.story_mut(sid).unwrap().format_chars(0..body.len(), nine_ten); + // The note: its own story in a 60 × 40 frame anchored in the third line. + let (nid, nsid) = (ItemId(d.alloc()), StoryId(d.alloc())); + let text = "Note one\u{2028}note two"; + let para = ParaFormat { para: ParaAttrs { grid_align: Some(GridAlign::FirstLineOnly), ..Default::default() }, ..Default::default() }; + let mut story = Story::with_text(nsid, text, para); + story.format_chars(0..text.len(), nine_ten); + story.frames.push(nid); + d.stories.insert(nsid, Arc::new(story)); + let mut note = + designcraft_doc::Item::new(nid, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 40.0))); + note.content = Content::Text(designcraft_doc::TextFrame { story: nsid, options: Default::default() }); + let position = designcraft_doc::AnchorPosition::Custom { + x_relative: R::TextFrame, + y_relative: R::Anchor, + x_offset: -72.0, + y_offset: -15.0, + object_point: 0, + ref_point: 0, + keep_within_column: false, + spine_relative: false, + }; + let at = body.find("Three").unwrap(); + d.story_mut(sid).unwrap().insert_object(at, designcraft_doc::AnchoredObject::new(note, position)); + + let cache = Cache::new(); + let on_grid = |y: f64| on_grid(y, (36.0, 10.0)); + // (anchor line baseline, note baselines), in spread space. + let baselines = |d: &Document, cs: &ComposedStory| { + let host = compose_story(d, sid, &ComposeOptions::default()); + let ft = host.frame(bf).unwrap(); + let o = &ft.objects[0]; + let fxf = d.item(bf).unwrap().xf; + let anchor = (fxf * Point::new(0.0, ft.lines[o.line].baseline)).y; + let nxf = fxf * Affine::translate(o.origin.to_vec2()) * d.anchored_item(nid).unwrap().xf; + (anchor, all_lines(cs).iter().map(|l| (nxf * Point::new(0.0, l.baseline)).y).collect::>()) + }; + let near = |a: f64, b: f64| (a - b).abs() < 1e-6; + + let (anchor, lines) = baselines(&d, &cache.get(&d, nsid, None)); + assert!(near(anchor, 66.0), "anchor baseline {anchor}"); + assert_eq!(lines.len(), 2); + assert!(near(lines[0], anchor) && near(lines[1], anchor + 10.0), "note baselines {lines:?}, anchor {anchor}"); + assert_eq!(baselines(&d, &compose_story(&d, nsid, &ComposeOptions::default())).1, lines); + // The note is on the host's right-hand page, with that page's rectangle. + let placed = placed::placements(&d, nsid, &mut |h| Arc::new(compose_story(&d, h, &ComposeOptions::default()))); + let spec = &frame_specs_placed(&d, nsid, &placed)[0]; + assert_eq!((spec.page, spec.right_page, spec.left_page), (Some(2), true, false)); + assert!(spec.page_rect.is_some()); + + // Host moved down 5 pt: the anchor is off the grid, and the note's first line moves down from + // 10 pt above it onto the grid line 5 pt above it. The cache composes the note again. + let xf = d.item(bf).unwrap().xf; + d.item_mut(bf).unwrap().xf = Affine::translate((0.0, 5.0)) * xf; + let (anchor, lines) = baselines(&d, &cache.get(&d, nsid, None)); + assert!(near(anchor, 71.0), "anchor baseline {anchor}"); + assert!(on_grid(lines[0]) && near(lines[0], anchor - 5.0) && near(lines[1], lines[0] + 10.0), "note baselines {lines:?}, anchor {anchor}"); + assert_eq!(baselines(&d, &compose_story(&d, nsid, &ComposeOptions::default())).1, lines); + + // The host's page turns into a left-hand page: the note is composed again for that side. + let before = cache.get(&d, nsid, None); + Arc::make_mut(&mut d.spreads[1]).pages[1].side = designcraft_doc::PageSide::Left; + assert!(!Arc::ptr_eq(&before, &cache.get(&d, nsid, None))); +} diff --git a/crates/compose/src/warichu.rs b/crates/compose/src/warichu.rs index 14b732e5e..8418faac4 100644 --- a/crates/compose/src/warichu.rs +++ b/crates/compose/src/warichu.rs @@ -93,6 +93,21 @@ fn line_count(len: usize, want: usize, before: usize, after: usize) -> usize { 1 } +/// The per-line counts recovered from the split table, or `None` when they don't cover all `m`. +fn trace_counts(take: &[Vec], n: usize, m: usize) -> Option> { + let mut counts = Vec::with_capacity(n); + let mut s = 0_usize; + for lines in (1..=n).rev() { + let t = take[lines][s]; + if t == 0 || s + t > m { + return None; + } + counts.push(t); + s += t; + } + (s == m).then_some(counts) +} + /// Glyph counts for `n` lines. Minimises the widest line, and the first and last lines keep their /// break minimums. One line when no split satisfies them. fn split_even(advs: &[f64], n: usize, before: usize, after: usize) -> Vec { @@ -142,17 +157,7 @@ fn split_even(advs: &[f64], n: usize, before: usize, after: usize) -> Vec if !best[n][0].is_finite() { return vec![m]; } - let mut counts = Vec::with_capacity(n); - let mut s = 0_usize; - for lines in (1..=n).rev() { - let t = take[lines][s]; - if t == 0 || s + t > m { - return vec![m]; - } - counts.push(t); - s += t; - } - if s != m { vec![m] } else { counts } + trace_counts(&take, n, m).unwrap_or_else(|| vec![m]) } fn restore(line: &mut [PlacedGlyph], members: &[usize], saved: &[(f64, f64, f64, f64)]) { diff --git a/crates/compose/src/wrap.rs b/crates/compose/src/wrap.rs index 57657213f..e1cdc5fa7 100644 --- a/crates/compose/src/wrap.rs +++ b/crates/compose/src/wrap.rs @@ -182,7 +182,7 @@ fn settled(a: &[Vec], b: &[Vec]) -> bool { /// [`neighbours`]) and of its own. pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, others: &[&ComposedStory]) -> ComposedStory { let Some(st) = doc.story(sid) else { return ComposedStory { story: sid, ..Default::default() } }; - let mut specs = crate::frame_specs(doc, sid); + let mut specs = crate::frame_specs_placed(doc, sid, &opts.placed); if !others.is_empty() { let mut obs = Vec::new(); for cs in others { diff --git a/crates/doc/src/attrs.rs b/crates/doc/src/attrs.rs index 077637672..587a00280 100644 --- a/crates/doc/src/attrs.rs +++ b/crates/doc/src/attrs.rs @@ -371,7 +371,7 @@ fn locale_code(words: &[&str]) -> Option { /// from documents, so at most [`MAX_TAGS`] are kept; past that a new tag is unknown (`None`). fn intern_tag(tag: String) -> Option<&'static str> { const MAX_TAGS: usize = 512; - static TAGS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + static TAGS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); let mut tags = TAGS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); if let Some(t) = tags.iter().find(|t| **t == tag) { return Some(t); @@ -1270,8 +1270,17 @@ attr_set! { number_expression: String = "^#.^t".into(), /// Text after the bullet (metacharacters expand as in [`expand_list_text`]). list_separator: String = "\t".into(), + /// The hanging indent was set by the Bulleted or Numbered List button, which takes it away + /// 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 = 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.rs index 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/endnotes.rs b/crates/doc/src/endnotes.rs index da213d08c..b15bb745c 100644 --- a/crates/doc/src/endnotes.rs +++ b/crates/doc/src/endnotes.rs @@ -147,7 +147,7 @@ impl crate::Document { if st.id == sid { break; } - n += st.endnotes.len() as u32; + n = n.saturating_add(st.endnotes.len() as u32); } n } @@ -173,7 +173,7 @@ impl crate::Document { let at = out.len(); out.insert_with(at, ¬e.text.text[r].replace('\n', " "), f.clone()); } - n += 1; + n = n.saturating_add(1); } } out diff --git a/crates/doc/src/index.rs b/crates/doc/src/index.rs index 9f56c42ea..826464329 100644 --- a/crates/doc/src/index.rs +++ b/crates/doc/src/index.rs @@ -100,6 +100,25 @@ fn sort_key(s: &str) -> String { if k.is_empty() { s.to_lowercase() } else { k } } +/// Record one reference's see-target or page on its topic node. +fn record_ref(n: &mut Node, res: &Resolved) { + match &res.r.range { + IndexRange::See(t) => n.see.push(t.clone()), + IndexRange::SeeAlso(t) => { + n.see_also.push(t.clone()); + if let Some(p) = res.pages { + n.pages.push(p); + } + } + IndexRange::SuppressPageRange => {} + _ => { + if let Some(p) = res.pages { + n.pages.push(p); + } + } + } +} + /// The index as paragraphs `(style, text)`; `page_name` formats an absolute page. pub fn build(spec: &IndexSpec, refs: &[Resolved], page_name: &dyn Fn(usize) -> String) -> Vec<(String, String)> { let mut root: BTreeMap = BTreeMap::new(); @@ -114,21 +133,7 @@ pub fn build(spec: &IndexSpec, refs: &[Resolved], page_name: &dyn Fn(usize) -> S .map(|(i, t)| (format!("{}\u{0}{}", sort_key(res.r.sort.get(i).filter(|s| !s.is_empty()).unwrap_or(t)), t.trim()), t.trim().to_string())) .collect(); let n = descend(&mut root, &keys); - match &res.r.range { - IndexRange::See(t) => n.see.push(t.clone()), - IndexRange::SeeAlso(t) => { - n.see_also.push(t.clone()); - if let Some(p) = res.pages { - n.pages.push(p); - } - } - IndexRange::SuppressPageRange => {} - _ => { - if let Some(p) = res.pages { - n.pages.push(p); - } - } - } + record_ref(n, res); } let mut out = Vec::new(); if !spec.title.is_empty() { diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index cfb13dc53..31d3a08d2 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -452,12 +452,96 @@ pub struct TextFrameOptions { pub column_rule_bottom_inset: f64, /// Use a custom baseline grid for this frame. #[serde(skip_serializing_if = "Option::is_none")] - pub baseline_grid: Option<(f64, f64)>, + pub baseline_grid: Option, /// Type on a Path: the text runs along the item's path instead of filling it. #[serde(skip_serializing_if = "Option::is_none")] pub path: Option, } +/// A text frame's custom baseline grid. Saved as `[start, increment]` when it starts from the +/// top of the page, otherwise as `[start, increment, relativeTo]`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FrameBaselineGrid { + /// The first grid line, down from the line `relative_to` names. + pub start: f64, + /// The distance between grid lines; 0 or less turns the grid off. + pub increment: f64, + pub relative_to: FrameGridRelative, +} + +impl FrameBaselineGrid { + /// A grid measured from the top of the page. + pub fn new(start: f64, increment: f64) -> Self { + FrameBaselineGrid { start, increment, relative_to: FrameGridRelative::TopOfPage } + } +} + +/// What a frame's custom baseline grid's start is measured from. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum FrameGridRelative { + #[default] + #[serde(rename = "page")] + TopOfPage, + #[serde(rename = "margin")] + TopMargin, + #[serde(rename = "frame")] + TopOfFrame, + #[serde(rename = "inset")] + TopInset, +} + +impl FrameGridRelative { + pub const ALL: [FrameGridRelative; 4] = + [FrameGridRelative::TopOfPage, FrameGridRelative::TopMargin, FrameGridRelative::TopOfFrame, FrameGridRelative::TopInset]; + + /// The name commands and native files use: page, margin, frame or inset. + pub fn name(self) -> &'static str { + match self { + FrameGridRelative::TopOfPage => "page", + FrameGridRelative::TopMargin => "margin", + FrameGridRelative::TopOfFrame => "frame", + FrameGridRelative::TopInset => "inset", + } + } + + pub fn from_name(name: &str) -> Option { + Self::ALL.into_iter().find(|r| r.name() == name) + } +} + +impl Serialize for FrameBaselineGrid { + fn serialize(&self, s: S) -> Result { + // Files saved before Relative To existed hold two elements; a page-relative grid keeps that form. + match self.relative_to { + FrameGridRelative::TopOfPage => (self.start, self.increment).serialize(s), + r => (self.start, self.increment, r).serialize(s), + } + } +} + +impl<'de> Deserialize<'de> for FrameBaselineGrid { + fn deserialize>(d: D) -> Result { + struct Grid; + impl<'de> serde::de::Visitor<'de> for Grid { + type Value = FrameBaselineGrid; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("[start, increment] or [start, increment, relativeTo]") + } + fn visit_seq>(self, mut a: A) -> Result { + use serde::de::Error; + let start = a.next_element()?.ok_or_else(|| A::Error::invalid_length(0, &self))?; + let increment = a.next_element()?.ok_or_else(|| A::Error::invalid_length(1, &self))?; + let relative_to = a.next_element()?.unwrap_or_default(); + if a.next_element::()?.is_some() { + return Err(A::Error::invalid_length(4, &self)); + } + Ok(FrameBaselineGrid { start, increment, relative_to }) + } + } + d.deserialize_seq(Grid) + } +} + /// Type on a Path Options. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default)] @@ -1662,6 +1746,28 @@ mod tests { assert_eq!(*c, ClippingPath::new(ClippingKind::AlphaChannel, PathData::default())); } + #[test] + fn frame_baseline_grid_saves_as_start_then_increment() { + // A file saved before Relative To existed: the grid starts from the top of the page and + // saves back unchanged. + let v = serde_json::json!({"baselineGrid": [6.0, 14.0]}); + let o = serde_json::from_value::(v).unwrap(); + assert_eq!(o.baseline_grid, Some(FrameBaselineGrid { start: 6.0, increment: 14.0, relative_to: FrameGridRelative::TopOfPage })); + assert_eq!(serde_json::to_value(&o).unwrap()["baselineGrid"], serde_json::json!([6.0, 14.0])); + for r in [FrameGridRelative::TopMargin, FrameGridRelative::TopOfFrame, FrameGridRelative::TopInset] { + let o = TextFrameOptions { + baseline_grid: Some(FrameBaselineGrid { relative_to: r, ..FrameBaselineGrid::new(6.0, 14.0) }), + ..Default::default() + }; + let v = serde_json::to_value(&o).unwrap(); + assert_eq!(v["baselineGrid"], serde_json::json!([6.0, 14.0, r.name()])); + assert_eq!(serde_json::from_value::(v).unwrap().baseline_grid, o.baseline_grid); + } + for bad in [serde_json::json!([6.0]), serde_json::json!([6.0, 14.0, "frame", 1]), serde_json::json!([6.0, 14.0, "spine"])] { + assert!(serde_json::from_value::(serde_json::json!({"baselineGrid": bad})).is_err()); + } + } + #[test] fn bounds_and_text_area() { let mut it = Item::new(ItemId(1), LayerId(1), Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0))); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index b2d3b4f4c..a509fdd8b 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -147,6 +147,17 @@ impl Default for BaselineGrid { } } +impl BaselineGrid { + /// The first grid line on `page`, measured down from the page top: `start` from the top of + /// the page or from its top margin. The other lines follow every `increment` below it. + pub fn origin(&self, page: &page::Page) -> f64 { + match self.relative_to { + GridRelative::TopOfPage => self.start, + GridRelative::TopMargin => self.start + page.margins.top, + } + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default)] pub struct DocumentGrid { diff --git a/crates/doc/src/notes.rs b/crates/doc/src/notes.rs index c4d83969a..0811c549c 100644 --- a/crates/doc/src/notes.rs +++ b/crates/doc/src/notes.rs @@ -262,7 +262,7 @@ impl crate::Document { let Some(me) = self.story(sid) else { return o.start_at }; let mine = key(me); let before: usize = self.stories.values().filter(|st| st.id != sid && !st.notes.is_empty() && key(st) < mine).map(|st| st.notes.len()).sum(); - o.start_at + before as u32 + o.start_at.saturating_add(before as u32) } /// Absolute page an item sits on (its center), None on parent pages / pasteboard-only spreads. diff --git a/crates/doc/src/otf.rs b/crates/doc/src/otf.rs index 5e246b8bf..64c976bad 100644 --- a/crates/doc/src/otf.rs +++ b/crates/doc/src/otf.rs @@ -53,7 +53,7 @@ pub fn figures(list: &[String]) -> &'static str { pub fn set_figures(list: &mut Vec, id: &str) -> bool { let Some((_, _, tags, _)) = FIGURES.iter().find(|f| f.0 == id) else { return false }; list.retain(|t| !matches!(t.as_str(), "tnum" | "pnum" | "lnum" | "onum")); - list.extend(tags.iter().map(|t| t.to_string())); + list.extend(tags.iter().map(ToString::to_string)); true } diff --git a/crates/doc/src/story.rs b/crates/doc/src/story.rs index 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, } +/// 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 { + 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 { + 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/doc/src/table.rs b/crates/doc/src/table.rs index e96aac4b7..d80b1d475 100644 --- a/crates/doc/src/table.rs +++ b/crates/doc/src/table.rs @@ -1040,6 +1040,15 @@ impl Table { if self.rows[h..self.nrows() - f].iter().any(|r| r.kind != RowKind::Body) { return Err(format!("table {}: header/footer rows out of order", self.id)); } + self.check_spans()?; + for cell in &self.cells { + cell.text.check()?; + } + Ok(()) + } + + /// Every merged cell stays inside the grid and no two merged cells overlap. + fn check_spans(&self) -> Result<(), String> { let mut seen = vec![false; self.cells.len()]; for r in 0..self.nrows() { for c in 0..self.ncols() { @@ -1064,9 +1073,6 @@ impl Table { } } } - for cell in &self.cells { - cell.text.check()?; - } Ok(()) } } diff --git a/crates/engine/src/cmd/book.rs b/crates/engine/src/cmd/book.rs index 4a65137cf..18f554d57 100644 --- a/crates/engine/src/cmd/book.rs +++ b/crates/engine/src/cmd/book.rs @@ -130,7 +130,7 @@ impl ChapterBatch { fn writable_chapter(s: &Session, path: &str, command: &'static str) -> Result<()> { use std::path::Path; - if Path::new(path).extension().and_then(|ext| ext.to_str()).is_some_and(|ext| ext.eq_ignore_ascii_case("idml")) { + if Path::new(path).extension().and_then(std::ffi::OsStr::to_str).is_some_and(|ext| ext.eq_ignore_ascii_case("idml")) { return Err(bad(command, format!("cannot change imported IDML chapter {path}; convert it to a native DesignCraft document first"))); } let target = crate::io::canonicalize(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index b0165d9d3..d4b2235e9 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -254,7 +254,7 @@ fn find_markers(text: &str) -> Vec<(usize, usize, String)> { continue; } } - i += text[i..].chars().next().map(|c| c.len_utf8()).unwrap_or(1); + i += text[i..].chars().next().map(char::len_utf8).unwrap_or(1); } out } diff --git a/crates/engine/src/cmd/datamerge/mod.rs b/crates/engine/src/cmd/datamerge/mod.rs index 38b543ff7..c07e2fff4 100644 --- a/crates/engine/src/cmd/datamerge/mod.rs +++ b/crates/engine/src/cmd/datamerge/mod.rs @@ -617,7 +617,7 @@ fn marker_ranges(text: &str, marker: &str) -> Vec<(usize, usize)> { i = end; continue; } - i = i.saturating_add(text[i..].chars().next().map(|c| c.len_utf8()).unwrap_or(1)); + i = i.saturating_add(text[i..].chars().next().map(char::len_utf8).unwrap_or(1)); } out } diff --git a/crates/engine/src/cmd/datamerge/parse.rs b/crates/engine/src/cmd/datamerge/parse.rs index 61ad6224e..c76c37f1e 100644 --- a/crates/engine/src/cmd/datamerge/parse.rs +++ b/crates/engine/src/cmd/datamerge/parse.rs @@ -379,7 +379,7 @@ fn sniff(name: &str, text: &str) -> Delimiter { } pub fn extension(name: &str) -> String { - Path::new(name).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase() + Path::new(name).extension().and_then(std::ffi::OsStr::to_str).unwrap_or("").to_ascii_lowercase() } struct HeaderDelimiterCandidate { diff --git a/crates/engine/src/cmd/endnotes.rs b/crates/engine/src/cmd/endnotes.rs index 7bcae744b..fb3bf64ce 100644 --- a/crates/engine/src/cmd/endnotes.rs +++ b/crates/engine/src/cmd/endnotes.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { for st in d.stories.values().filter(|st| !st.endnotes.is_empty()) { let first = d.endnote_start(st.id); for (k, n) in st.endnotes.iter().enumerate() { - out.push(json!({"story": st.id.0, "id": n.id, "number": first + k as u32, "text": n.text.text})); + out.push(json!({"story": st.id.0, "id": n.id, "number": first.saturating_add(k as u32), "text": n.text.text})); } } out.sort_by_key(|v| v["number"].as_u64()); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index c644284d1..33cea7ed0 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -166,7 +166,7 @@ fn save_bytes(d: &Document, preview: Option<&[u8]>) -> Result> { /// the file opens from the file manager. A path without a file name is left for the write to fail. pub fn with_document_extension(path: &str) -> String { let p = std::path::Path::new(path); - let ext = p.extension().and_then(|e| e.to_str()); + let ext = p.extension().and_then(std::ffi::OsStr::to_str); if p.file_name().is_none() || ext.is_some_and(|e| e.eq_ignore_ascii_case(designcraft_format::EXTENSION)) { return path.to_string(); } @@ -231,11 +231,24 @@ fn new_document_settings(s: &Session, p: &Value) -> Result { Ok(nd) } +/// A document as `file.new` makes it. Its Basic Paragraph doesn't hyphenate capitalized words, a +/// paragraph's last word or across a column. Opened and imported files keep their own values, +/// which is why `ParaProps` keeps the IDML defaults (on). +fn new_document(nd: &NewDocument) -> Document { + let mut d = Document::new(nd); + if let Some(st) = Arc::make_mut(&mut d.styles).para_mut(designcraft_doc::BASIC_PARAGRAPH) { + st.para.hyph_capitalized = Some(false); + st.para.hyph_last_word = Some(false); + st.para.hyph_across_column = Some(false); + } + d +} + fn file_new(s: &mut Session, p: &Value) -> Result { let mut nd = new_document_settings(s, p)?; s.untitled += 1; nd.title = str_param(p, "title").map(str::to_string).unwrap_or_else(|| format!("Untitled-{}", s.untitled)); - let d = Document::new(&nd); + let d = new_document(&nd); let i = s.add_document(DocState::new(d, None)); Ok(json!({"index": i})) } @@ -259,7 +272,7 @@ impl Session { self.untitled += 1; } nd.title = str_param(p, "title").map(str::to_string).unwrap_or_else(|| self.next_untitled_title()); - let st = DocState::new(Document::new(&nd), None); + let st = DocState::new(new_document(&nd), None); let uid = st.uid; match replace.and_then(|i| self.docs.get_mut(i).map(|d| (i, d))) { Some((i, d)) => { @@ -469,7 +482,7 @@ fn open_path(s: &mut Session, p: &Value) -> Result { let bytes = crate::io::read_file(path).map_err(EngineError::Other)?; // The content decides first: a file's extension may be missing or wrong. The extension // then routes files whose content isn't recognised to the reader that explains why. - let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase(); + let ext = std::path::Path::new(path).extension().and_then(std::ffi::OsStr::to_str).unwrap_or_default().to_ascii_lowercase(); let native = designcraft_format::is_designcraft(&bytes) || bytes.trim_ascii_start().starts_with(b"{"); if designcraft_idml::is_idml(&bytes) || (!native && (super::interchange::is_indd(path, &bytes) || ext == "idml")) { return super::interchange::open_idml(s, p); @@ -2124,3 +2137,35 @@ mod recent_tests { assert!(old.recent_files.is_empty(), "older prefs.json without the list still load"); } } + +#[cfg(test)] +mod hyphenation_default_tests { + use std::sync::Arc; + + use designcraft_doc::BASIC_PARAGRAPH; + use designcraft_doc::build::NewDocument; + use serde_json::json; + + use crate::Session; + + fn hyph_flags(d: &designcraft_doc::Document) -> (bool, bool, bool) { + let (pp, _) = d.styles.resolve_para(&designcraft_doc::ParaFormat::default()); + (pp.hyph_capitalized, pp.hyph_last_word, pp.hyph_across_column) + } + + #[test] + fn new_documents_hyphenate_no_capitalized_last_or_column_end_words_and_imports_keep_theirs() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + assert_eq!(hyph_flags(&s.doc().unwrap().doc), (false, false, false)); + + let mut d = designcraft_doc::Document::new(&NewDocument::default()); + let st = Arc::make_mut(&mut d.styles).para_mut(BASIC_PARAGRAPH).unwrap(); + st.para.hyph_capitalized = Some(true); + st.para.hyph_last_word = Some(true); + st.para.hyph_across_column = Some(true); + let b64 = super::base64_encode(&designcraft_idml::export_idml(&d)); + s.execute("file.openIdml", &json!({"base64": b64, "name": "in.idml"})).unwrap(); + assert_eq!(hyph_flags(&s.doc().unwrap().doc), (true, true, true)); + } +} diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index b2cb88fd2..c39e05668 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -480,7 +480,7 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result { continue; } let old = std::path::PathBuf::from(a.link.clone().unwrap_or_else(|| a.name.clone())); - let mut name = old.file_name().map(|n| n.to_os_string()).unwrap_or_else(|| a.name.clone().into()); + let mut name = old.file_name().map(std::ffi::OsStr::to_os_string).unwrap_or_else(|| a.name.clone().into()); if let Some(e) = &ext { name = std::path::Path::new(&name).with_extension(e).into_os_string(); } diff --git a/crates/engine/src/cmd/lists.rs b/crates/engine/src/cmd/lists.rs index 9f8824870..74570f3fd 100644 --- a/crates/engine/src/cmd/lists.rs +++ b/crates/engine/src/cmd/lists.rs @@ -1,13 +1,37 @@ //! Type › Bulleted & Numbered Lists › Define Lists: named lists whose numbers can continue from //! story to story. Paragraphs join one with `listName` (and restart with `startAt`). -use designcraft_doc::NumberedList; +use designcraft_doc::{ListType, NumberedList}; use serde_json::{Value, json}; -use super::{CommandSpec, bad, cmd, has_doc, str_param}; +use super::{CommandSpec, bad, cmd, has_doc, has_text_or_frames, str_param}; +use crate::{Result, Session}; + +/// The hanging indent a list gets from the Bulleted and Numbered List buttons, as InDesign's +/// default (Left Indent 0.25 in, First Line Indent −0.25 in): the bullet or number at the margin, +/// the text after its tab at the left indent. +pub const LIST_HANG: f64 = 18.0; pub fn specs() -> Vec { vec![ + cmd!( + "list.bullets", + "Apply Bullets", + ["Type", "Bulleted & Numbered Lists"], + None, + "{on?: bool (default: off when every selected paragraph has bullets, else on)} — the Bulleted List button: paragraphs with no indents get the default hanging indent (left 18 pt, first line −18 pt); taking bullets off removes that indent if it is still as applied", + has_text_or_frames, + |s, p| apply_list(s, p, ListType::Bullets) + ), + cmd!( + "list.numbers", + "Apply Numbers", + ["Type", "Bulleted & Numbered Lists"], + None, + "{on?: bool (default: off when every selected paragraph is numbered, else on)} — the Numbered List button, as list.bullets", + has_text_or_frames, + |s, p| apply_list(s, p, ListType::Numbers) + ), cmd!( "list.define", "Define Lists…", @@ -48,12 +72,181 @@ pub fn specs() -> Vec { ] } +/// Bullets or numbers on (or off) for the selected paragraphs, as InDesign's Bulleted and +/// Numbered List buttons: one undo step. Values equal to the paragraph style's are left to the +/// style rather than set locally, so a paragraph back to its style shows no override. +fn apply_list(s: &mut Session, p: &Value, kind: ListType) -> Result { + let name = if kind == ListType::Bullets { "list.bullets" } else { "list.numbers" }; + let on = match p.get("on") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_bool().ok_or_else(|| bad(name, "`on` must be true or false"))?), + }; + let targets = super::text::format_targets_pub(s); + if targets.is_empty() { + return Err(bad(name, "select text or a text frame")); + } + // Off when every selected paragraph already has this list, as the button shows it pressed. + let on = on.unwrap_or_else(|| !s.doc().is_ok_and(|st| all_have(&st.doc, &targets, kind))); + s.edit(|d, _| { + let styles = d.styles.clone(); + for t in &targets { + let Some(st) = d.text_story_mut(t.story, t.cell) else { continue }; + let span = para_span(&st.text, &t.range); + st.format_paras(span, |pf| { + let (now, _) = styles.resolve_para(pf); + // Off takes away this list only: a paragraph with the other list keeps it. + if !on && now.list_type != kind { + return; + } + let (style, _) = styles.resolve_para_style(&pf.style); + // The hanging indent this button set (and nothing has changed since). + let own_hang = pf.para.list_hang == Some(true) && now.left_indent == LIST_HANG && now.first_line_indent == -LIST_HANG; + // A value: left to the style when it gives the same, else set here. + let mut set = |key: &str, v: Value, same: bool| { + let _ = pf.para.set_json(key, if same { &Value::Null } else { &v }); + }; + let list = if on { kind } else { ListType::None }; + set("listType", serde_json::to_value(list).unwrap_or(Value::Null), style.list_type == list); + if on && now.left_indent == 0.0 && now.first_line_indent == 0.0 { + set("leftIndent", json!(LIST_HANG), style.left_indent == LIST_HANG); + set("firstLineIndent", json!(-LIST_HANG), style.first_line_indent == -LIST_HANG); + set("listHang", json!(true), false); + } else if !on && now.list_type == kind { + // Only the hanging indent set here: one the paragraph had before, or its style + // gives, stays. + if own_hang { + set("leftIndent", json!(0.0), style.left_indent == 0.0); + set("firstLineIndent", json!(0.0), style.first_line_indent == 0.0); + } + set("listHang", Value::Null, true); + } + }); + } + Ok(json!({"on": on})) + }) +} + +/// The range whose paragraphs a list applies to: a selection ending where a paragraph starts (after +/// a return) doesn't reach into that paragraph. The story's last paragraph, empty after a final +/// return, stays in when the range runs to the end (a whole frame). +fn para_span(text: &str, range: &std::ops::Range) -> std::ops::Range { + let end = range.end.max(range.start); + if end > range.start && end < text.len() && text.as_bytes().get(end - 1) == Some(&b'\n') { range.start..end - 1 } else { range.start..end } +} + +/// Whether every paragraph of `targets` has list `kind`. +fn all_have(d: &designcraft_doc::Document, targets: &[super::text::Target], kind: ListType) -> bool { + targets.iter().all(|t| { + d.text_story(t.story, t.cell).is_some_and(|st| { + let span = para_span(&st.text, &t.range); + let (a, b) = (st.para_at(span.start), st.para_at(span.end)); + st.paras.get(a..=b).is_some_and(|ps| ps.iter().all(|pf| d.styles.resolve_para(pf).0.list_type == kind)) + }) + }) +} + +impl Session { + /// Whether the Bulleted or Numbered List button (and Type › Apply Bullets or Numbers) shows + /// pressed: every paragraph the list commands apply to has list `kind`, through the selected + /// text, table cells or text frames. + pub fn selection_has_list(&self, kind: ListType) -> bool { + let targets = super::text::format_targets_pub(self); + !targets.is_empty() && self.doc().is_ok_and(|st| all_have(&st.doc, &targets, kind)) + } +} + #[cfg(test)] mod tests { use serde_json::json; use crate::Session; + /// The Bulleted List button, as InDesign's: bullets with the default hanging indent (the + /// bullet at the margin, the text 18 pt in); again, bullets and that indent go, back to the + /// style. Numbers swap in keeping the indent; paragraphs with their own indents keep them. + #[test] + fn list_buttons_apply_the_default_hanging_indent() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Eggs\nMilk\nFlour"})).unwrap(); + let sid = f["story"].as_u64().unwrap(); + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 9})).unwrap(); + let para = |s: &Session, i: usize| { + let d = &s.doc().unwrap().doc; + let st = d.story(designcraft_doc::StoryId(sid)).unwrap(); + (d.styles.resolve_para(&st.paras[i]).0, st.paras[i].para.clone()) + }; + let undo = s.doc().unwrap().history.undo.len(); + assert_eq!(s.execute("list.bullets", &json!({})).unwrap()["on"], true); + for i in 0..2 { + let (p, _) = para(&s, i); + assert_eq!((p.list_type, p.left_indent, p.first_line_indent), (designcraft_doc::ListType::Bullets, 18.0, -18.0)); + } + assert_eq!(para(&s, 2).0.list_type, designcraft_doc::ListType::None, "the paragraph outside the selection"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + // The number of a bullet's tab: the text starts at the left indent. + let d = &s.doc().unwrap().doc; + let cs = designcraft_compose::compose_story(d, designcraft_doc::StoryId(sid), &Default::default()); + let line = &cs.frames[0].lines[0]; + let text_x = line.glyphs.iter().filter(|g| g.len > 0).map(|g| g.x).next().unwrap(); + assert!((text_x - line.x0 - 18.0).abs() < 0.5, "the text at the hanging indent: {} from {}", text_x, line.x0); + // Numbers instead: the indent stays. + s.execute("list.numbers", &json!({})).unwrap(); + let (p, _) = para(&s, 0); + assert_eq!((p.list_type, p.left_indent), (designcraft_doc::ListType::Numbers, 18.0)); + // Numbers off: list and hanging indent go, and nothing is left set on the paragraph. + assert_eq!(s.execute("list.numbers", &json!({})).unwrap()["on"], false); + let (p, own) = para(&s, 0); + assert_eq!((p.list_type, p.left_indent, p.first_line_indent), (designcraft_doc::ListType::None, 0.0, 0.0)); + assert_eq!(own, designcraft_doc::ParaAttrs::default(), "back to the style"); + // A paragraph with its own indents keeps them. + s.execute("type.para", &json!({"attrs": {"leftIndent": 36}})).unwrap(); + s.execute("list.bullets", &json!({"on": true})).unwrap(); + let (p, _) = para(&s, 0); + assert_eq!((p.left_indent, p.first_line_indent), (36.0, 0.0)); + s.execute("list.bullets", &json!({"on": false})).unwrap(); + assert_eq!(para(&s, 0).0.left_indent, 36.0); + assert!(s.execute("list.bullets", &json!({"on": "yes"})).is_err()); + } + + /// Pressed means every targeted paragraph has the list: a selection reaching an unbulleted + /// paragraph, or a frame with one, isn't. Explicitly off, a list button takes away its own + /// list only: a bulleted paragraph keeps bullets and indent when Numbers go off. + #[test] + fn a_list_is_pressed_and_turned_off_for_its_own_paragraphs() { + use designcraft_doc::ListType; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Eggs\nMilk\nFlour"})).unwrap(); + let sid = f["story"].as_u64().unwrap(); + let select = |s: &mut Session, a: usize, b: usize| { + s.execute("text.select", &json!({"story": sid, "anchor": a, "focus": b})).unwrap(); + }; + select(&mut s, 0, 3); + s.execute("list.bullets", &json!({})).unwrap(); + assert!(s.selection_has_list(ListType::Bullets)); + assert!(!s.selection_has_list(ListType::Numbers)); + // From the bulleted Eggs into the plain Milk: not pressed, and a press bullets both. + select(&mut s, 0, 7); + assert!(!s.selection_has_list(ListType::Bullets)); + // The frame selected: its whole story, Flour unbulleted. + s.execute("selection.set", &json!({"ids": [f["id"]]})).unwrap(); + assert!(!s.selection_has_list(ListType::Bullets)); + // Eggs bulleted, Milk numbered; Numbers off over both leaves Eggs' bullets and indent. + select(&mut s, 5, 7); + s.execute("list.numbers", &json!({"on": true})).unwrap(); + select(&mut s, 0, 7); + s.execute("list.numbers", &json!({"on": false})).unwrap(); + let d = &s.doc().unwrap().doc; + let st = d.story(designcraft_doc::StoryId(sid)).unwrap(); + let p = |i: usize| d.styles.resolve_para(&st.paras[i]).0; + assert_eq!((p(0).list_type, p(0).left_indent, p(0).first_line_indent), (ListType::Bullets, 18.0, -18.0)); + assert_eq!((p(1).list_type, p(1).left_indent), (ListType::None, 0.0)); + // With no text or frame selected, nothing is pressed. + s.execute("selection.set", &json!({"ids": []})).unwrap(); + assert!(!s.selection_has_list(ListType::Bullets)); + } + /// The digit the story's first line starts with (its list number). fn digit(g: &designcraft_compose::PlacedGlyph) -> char { let face = g.face.get(); @@ -99,4 +292,74 @@ mod tests { s.execute("type.para", &json!({"attrs": {"startAt": null}})).unwrap(); assert_eq!(first_char(&s, stories[1]), '4'); } + + /// A selection ending right after a return (the whole first paragraph, as a triple click selects + /// it) applies the list to that paragraph only, and the button shows it pressed. + #[test] + fn a_selection_ending_at_a_paragraph_start_leaves_that_paragraph_out() { + use designcraft_doc::ListType; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let f = s + .execute( + "frame.create", + &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Eggs +Milk +Flour +"}), + ) + .unwrap(); + let sid = f["story"].as_u64().unwrap(); + let kinds = |s: &Session| { + let d = &s.doc().unwrap().doc; + d.story(designcraft_doc::StoryId(sid)).unwrap().paras.iter().map(|p| d.styles.resolve_para(p).0.list_type).collect::>() + }; + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 5})).unwrap(); + assert!(!s.selection_has_list(ListType::Bullets)); + assert_eq!(s.execute("list.bullets", &json!({})).unwrap()["on"], true); + assert_eq!(kinds(&s), [ListType::Bullets, ListType::None, ListType::None, ListType::None]); + assert!(s.selection_has_list(ListType::Bullets), "pressed for the paragraph selected"); + // The whole frame still takes in its last, empty paragraph. + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 16})).unwrap(); + s.execute("list.numbers", &json!({"on": true})).unwrap(); + assert_eq!(kinds(&s), [ListType::Numbers; 4]); + } + + /// A paragraph's own hanging indent, the same as the button's, stays when the list goes off: + /// the button takes away only the indent it set. + #[test] + fn a_paragraphs_own_hanging_indent_stays_when_the_list_goes_off() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Eggs"})).unwrap(); + let sid = f["story"].as_u64().unwrap(); + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 4})).unwrap(); + s.execute("type.para", &json!({"attrs": {"leftIndent": 18, "firstLineIndent": -18}})).unwrap(); + s.execute("list.bullets", &json!({"on": true})).unwrap(); + s.execute("list.bullets", &json!({"on": false})).unwrap(); + let d = &s.doc().unwrap().doc; + let pf = &d.story(designcraft_doc::StoryId(sid)).unwrap().paras[0]; + let p = d.styles.resolve_para(pf).0; + assert_eq!((p.list_type, p.left_indent, p.first_line_indent), (designcraft_doc::ListType::None, 18.0, -18.0)); + assert_eq!(pf.para.list_hang, None, "nothing of the list left"); + } + + /// A hanging indent the paragraph style gives stays when the list goes off. + #[test] + fn a_style_hanging_indent_stays_when_the_list_goes_off() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Eggs"})).unwrap(); + let sid = f["story"].as_u64().unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Hang", "para": {"leftIndent": 18, "firstLineIndent": -18}})).unwrap(); + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 4})).unwrap(); + s.execute("style.paragraph.apply", &json!({"name": "Hang"})).unwrap(); + s.execute("list.bullets", &json!({"on": true})).unwrap(); + s.execute("list.bullets", &json!({"on": false})).unwrap(); + let d = &s.doc().unwrap().doc; + let pf = &d.story(designcraft_doc::StoryId(sid)).unwrap().paras[0]; + let p = d.styles.resolve_para(pf).0; + assert_eq!((p.list_type, p.left_indent, p.first_line_indent), (designcraft_doc::ListType::None, 18.0, -18.0)); + assert_eq!(pf.para, designcraft_doc::ParaAttrs::default(), "nothing left set on the paragraph"); + } } diff --git a/crates/engine/src/cmd/load_styles.rs b/crates/engine/src/cmd/load_styles.rs index 19a5a6794..b89b42fa5 100644 --- a/crates/engine/src/cmd/load_styles.rs +++ b/crates/engine/src/cmd/load_styles.rs @@ -201,9 +201,9 @@ fn plan(doc: &Document, src: &Document, paragraph: Option<&[String]>, character: Ok((para, chars)) } -fn load(s: &mut Session, p: &Value) -> Result { - let src = source(p, ID)?; - let conflict = match p.get("conflicts") { +/// The `conflicts` parameter: how a style that differs under the same name is handled. +fn conflict_param(p: &Value) -> Result { + Ok(match p.get("conflicts") { None | Some(Value::Null) => Conflict::Redefine, Some(v) => match v.as_str() { Some("redefine") => Conflict::Redefine, @@ -211,7 +211,37 @@ fn load(s: &mut Session, p: &Value) -> Result { Some("autoRename") => Conflict::AutoRename, _ => return Err(bad(ID, "`conflicts` must be redefine, useExisting or autoRename")), }, + }) +} + +/// Give the loaded style `ours` the export tag the source had for `theirs` (`kind` is `p` or `c`). +fn carry_export_tag(src: &Styles, dst: &mut Styles, kind: char, theirs: &str, ours: &str) { + let tag = format!("{kind}:{ours}"); + match src.export_tags.get(&format!("{kind}:{theirs}")) { + Some(t) => dst.export_tags.insert(tag, t.clone()), + None => dst.export_tags.remove(&tag), }; +} + +/// A loaded style and one the document keeps can name each other as their base. +fn check_based_on_cycles(styles: &Styles, loaded: &[(bool, String)]) -> Result<()> { + for (is_para, name) in loaded { + let looped = if *is_para { + styles.para(name).and_then(|s| s.based_on.as_deref()).is_some_and(|b| styles.para_based_on_cycles(name, b)) + } else { + styles.char_style(name).and_then(|s| s.based_on.as_deref()).is_some_and(|b| styles.char_based_on_cycles(name, b)) + }; + if looped { + let kind = if *is_para { "paragraph" } else { "character" }; + return Err(bad(ID, format!("{kind} style `{name}` would be based on itself; load the style it is based on as well"))); + } + } + Ok(()) +} + +fn load(s: &mut Session, p: &Value) -> Result { + let src = source(p, ID)?; + let conflict = conflict_param(p)?; let (paragraph, character) = (names(p, "paragraph")?, names(p, "character")?); let doc = s.doc()?.doc.clone(); let (mut para, mut chars) = plan(&doc, &src, paragraph.as_deref(), character.as_deref(), conflict)?; @@ -231,11 +261,7 @@ fn load(s: &mut Session, p: &Value) -> Result { p.nested_line_styles.iter_mut().flatten().for_each(|l| chars.follow(&mut l.style)); swatches.extend(char_swatches(&style.chars).chain(para_swatches(&style.para)).cloned()); lists.extend(style.para.list_name.iter().cloned()); - let tag = format!("p:{}", style.name); - match src.styles.export_tags.get(&format!("p:{}", theirs.name)) { - Some(t) => styles.export_tags.insert(tag, t.clone()), - None => styles.export_tags.remove(&tag), - }; + carry_export_tag(&src.styles, &mut styles, 'p', &theirs.name, &style.name); loaded.push((true, style.name.clone())); match styles.para_mut(&style.name) { Some(m) if action == Action::Replace => { @@ -256,11 +282,7 @@ fn load(s: &mut Session, p: &Value) -> Result { chars.follow(&mut style.name); style.based_on.iter_mut().for_each(|n| chars.follow(n)); swatches.extend(char_swatches(&style.chars).cloned()); - let tag = format!("c:{}", style.name); - match src.styles.export_tags.get(&format!("c:{}", theirs.name)) { - Some(t) => styles.export_tags.insert(tag, t.clone()), - None => styles.export_tags.remove(&tag), - }; + carry_export_tag(&src.styles, &mut styles, 'c', &theirs.name, &style.name); loaded.push((false, style.name.clone())); match styles.char_style_mut(&style.name) { Some(m) if action == Action::Replace => { @@ -275,18 +297,7 @@ fn load(s: &mut Session, p: &Value) -> Result { } } } - // A loaded style and one the document keeps can name each other as their base. - for (is_para, name) in &loaded { - let looped = if *is_para { - styles.para(name).and_then(|s| s.based_on.as_deref()).is_some_and(|b| styles.para_based_on_cycles(name, b)) - } else { - styles.char_style(name).and_then(|s| s.based_on.as_deref()).is_some_and(|b| styles.char_based_on_cycles(name, b)) - }; - if looped { - let kind = if *is_para { "paragraph" } else { "character" }; - return Err(bad(ID, format!("{kind} style `{name}` would be based on itself; load the style it is based on as well"))); - } - } + check_based_on_cycles(&styles, &loaded)?; let swatches = missing_swatches(&doc, &src, swatches); let lists: Vec = { diff --git a/crates/engine/src/cmd/notes.rs b/crates/engine/src/cmd/notes.rs index 9318458de..03dde5c40 100644 --- a/crates/engine/src/cmd/notes.rs +++ b/crates/engine/src/cmd/notes.rs @@ -221,4 +221,15 @@ mod tests { // Caret is now in footnote text: no nested footnotes. assert!(s.execute("footnote.insert", &json!({})).is_err()); } + + #[test] + fn huge_start_at_does_not_overflow() { + let (mut s, sid) = session_with_text(); + s.execute("text.select", &json!({"story": sid.0, "anchor": 16, "focus": 16})).unwrap(); + s.execute("footnote.insert", &json!({"text": "x"})).unwrap(); + s.execute("footnote.options", &json!({"startAt": 4294967295u32})).unwrap(); + let d = s.doc().unwrap().doc.clone(); + let cs = s.cache.get(&d, sid, None); + assert_eq!(cs.frames[0].notes.len(), 1); + } } diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 24c44b83a..5c0e7e814 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -598,7 +598,7 @@ pub fn specs() -> Vec { "Text Frame Options…", ["Object"], Some("Cmd+B"), - "{columns?, gutter?, inset?: number|[t,l,b,r] (null keeps that side), verticalJustification?: top|center|bottom|justify, columnsKind?: fixedNumber|fixedWidth, columnWidth? (pt, Fixed Width), firstBaseline?: ascent|capHeight|leading|xHeight|emboxHeight|fixed, firstBaselineMin? (pt), autoSize?: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference?: topLeft|topCenter|topRight|leftCenter|center|rightCenter|bottomLeft|bottomCenter|bottomRight (the point that stays put), useMinimumHeight?: bool, minimumHeight? (pt), useMinimumWidth?: bool, minimumWidth? (pt), noLineBreaks?: bool, ignoreWrap?, balanceColumns?, columnRule?: bool, columnRuleWeight? (pt), columnRuleColor? (swatch name), columnRuleTint? (0..1), columnRuleOffset? (pt, horizontal), columnRuleTopInset? (pt), columnRuleBottomInset? (pt), vertical?: bool (sets the story direction of the frames' stories, as Type ▸ Story Direction), ids?}", + "{columns?, gutter?, inset?: number|[t,l,b,r] (null keeps that side), verticalJustification?: top|center|bottom|justify, columnsKind?: fixedNumber|fixedWidth, columnWidth? (pt, Fixed Width), firstBaseline?: ascent|capHeight|leading|xHeight|emboxHeight|fixed, firstBaselineMin? (pt), autoSize?: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference?: topLeft|topCenter|topRight|leftCenter|center|rightCenter|bottomLeft|bottomCenter|bottomRight (the point that stays put), useMinimumHeight?: bool, minimumHeight? (pt), useMinimumWidth?: bool, minimumWidth? (pt), noLineBreaks?: bool, ignoreWrap?, balanceColumns?, columnRule?: bool, columnRuleWeight? (pt), columnRuleColor? (swatch name), columnRuleTint? (0..1), columnRuleOffset? (pt, horizontal), columnRuleTopInset? (pt), columnRuleBottomInset? (pt), baselineGrid?: {start? (pt), increment? (pt), relativeTo?: page|margin|frame|inset} (the frame's custom baseline grid; fields not given keep the frame's, or come from the document grid; null turns it off), vertical?: bool (sets the story direction of the frames' stories, as Type ▸ Story Direction), ids?}", has_selection, text_frame_options ), @@ -2514,6 +2514,41 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { as u8, ), }; + // `Some(None)` turns the frame's custom baseline grid off. + let custom_grid = match p.get("baselineGrid") { + None => None, + Some(Value::Null) => Some(None), + Some(Value::Object(g)) => { + let num = |key: &str, lo: f64, hi: f64| match g.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_f64() { + Some(x) if x.is_finite() && (lo..=hi).contains(&x) => Ok(Some(x)), + _ => Err(bad(ID, format!("baselineGrid.{key} must be a number of points from {lo} to {hi}, not {v}"))), + }, + }; + let start = num("start", -15552.0, 15552.0)?; + let increment = num("increment", 0.0, 15552.0)?; + let relative_to = match g.get("relativeTo") { + None | Some(Value::Null) => None, + Some(v) => Some( + v.as_str() + .and_then(designcraft_doc::FrameGridRelative::from_name) + .ok_or_else(|| bad(ID, format!("baselineGrid.relativeTo must be page|margin|frame|inset, not {v}")))?, + ), + }; + Some(Some((start, increment, relative_to))) + } + Some(v) => return Err(bad(ID, format!("baselineGrid must be an object or null, not {v}"))), + }; + // A frame without a custom grid starts from the document's. + let doc_grid = { + let g = &st.doc.settings.baseline_grid; + let relative_to = match g.relative_to { + designcraft_doc::GridRelative::TopOfPage => designcraft_doc::FrameGridRelative::TopOfPage, + designcraft_doc::GridRelative::TopMargin => designcraft_doc::FrameGridRelative::TopMargin, + }; + designcraft_doc::FrameBaselineGrid { start: g.start, increment: g.increment, relative_to } + }; let rule_color = match p.get("columnRuleColor") { None | Some(Value::Null) => None, Some(Value::String(c)) if st.doc.swatch(c).is_some() => Some(c.clone()), @@ -2604,6 +2639,17 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { if let Some(v) = rule_bottom { o.column_rule_bottom_inset = v; } + match custom_grid { + Some(Some((start, increment, relative_to))) => { + let mut g = o.baseline_grid.unwrap_or(doc_grid); + g.start = start.unwrap_or(g.start); + g.increment = increment.unwrap_or(g.increment); + g.relative_to = relative_to.unwrap_or(g.relative_to); + o.baseline_grid = Some(g); + } + Some(None) => o.baseline_grid = None, + None => {} + } // Fixed Width columns set the frame's width: n columns, the gutters between them and // the left and right insets. let fixed_width = o.columns_kind == designcraft_doc::ColumnsKind::FixedWidth && o.column_width > 0.0; @@ -5637,3 +5683,33 @@ mod fill_tint_tests { assert!(stroke_of(&s, b).is_none()); } } + +#[cfg(test)] +mod frame_baseline_grid_tests { + use super::*; + use designcraft_doc::{FrameBaselineGrid, FrameGridRelative}; + + #[test] + fn text_frame_options_set_a_custom_baseline_grid_relative_to() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Hello"})).unwrap(); + let id = ItemId(r["id"].as_u64().unwrap()); + let grid = |s: &Session| s.doc().unwrap().doc.item(id).and_then(|i| i.text_frame()).and_then(|t| t.options.baseline_grid); + // Turning it on with only Relative To takes the document grid's start and increment. + let doc = s.doc().unwrap().doc.settings.baseline_grid.clone(); + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "baselineGrid": {"relativeTo": "frame"}})).unwrap(); + assert_eq!(grid(&s), Some(FrameBaselineGrid { start: doc.start, increment: doc.increment, relative_to: FrameGridRelative::TopOfFrame })); + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "baselineGrid": {"start": 10, "increment": 13, "relativeTo": "inset"}})).unwrap(); + assert_eq!(grid(&s), Some(FrameBaselineGrid { start: 10.0, increment: 13.0, relative_to: FrameGridRelative::TopInset })); + // Fields not given keep the frame's. + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "baselineGrid": {"relativeTo": "margin"}})).unwrap(); + assert_eq!(grid(&s), Some(FrameBaselineGrid { start: 10.0, increment: 13.0, relative_to: FrameGridRelative::TopMargin })); + for bad in [json!({"relativeTo": "spine"}), json!({"start": f64::MAX}), json!({"increment": -1}), json!(3)] { + assert!(s.execute("object.textFrameOptions", &json!({"ids": [id.0], "baselineGrid": bad})).is_err(), "{bad}"); + } + assert_eq!(grid(&s).map(|g| g.relative_to), Some(FrameGridRelative::TopMargin)); + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "baselineGrid": null})).unwrap(); + assert_eq!(grid(&s), None); + } +} diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index d0ed58b03..ffc69b39e 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -907,13 +907,12 @@ mod tests { let outside = base.join("separate"); std::fs::create_dir_all(&outside).unwrap(); let redirected = base.join("Package"); - match symlink_dir(&outside, &redirected) { - Ok(()) => {} - Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => { - let _ = std::fs::remove_dir_all(&base); - return; - } - Err(e) => panic!("could not create directory redirect: {e}"), + // A symbolic link needs Developer Mode or elevation (os error 1314 without them); a + // directory junction needs neither, and `is_redirect` treats both as redirects. + if symlink_dir(&outside, &redirected).is_err() && !make_junction(&outside, &redirected) { + eprintln!("skipped: directory redirects can't be made here"); + let _ = std::fs::remove_dir_all(&base); + return; } let mut s = Session::new(); s.execute("file.new", &json!({"title": "Annual"})).unwrap(); @@ -922,4 +921,17 @@ mod tests { std::fs::remove_dir(&redirected).unwrap(); let _ = std::fs::remove_dir_all(&base); } + + /// Makes `link` a directory junction to `target` with `mklink /J`, and reports whether it was made. + #[cfg(windows)] + fn make_junction(target: &Path, link: &Path) -> bool { + use std::os::windows::process::CommandExt; + + // Windows paths can't hold `"`, so quoting each one keeps `&` and spaces in it literal for cmd. + std::process::Command::new("cmd") + .args(["/D", "/C"]) + .raw_arg(format!("mklink /J \"{}\" \"{}\"", link.display(), target.display())) + .output() + .is_ok_and(|output| output.status.success()) + } } diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs index 19d64c1fc..2d9698ba1 100644 --- a/crates/engine/src/cmd/preflight.rs +++ b/crates/engine/src/cmd/preflight.rs @@ -354,11 +354,15 @@ mod placed_vector_tests { s.execute("file.place", &json!({"base64": base64_encode(&png), "name": "photo.jpg", "x": 72, "y": 72, "width": 20})).unwrap(); let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); let asset = doc.assets.values_mut().next().unwrap(); - std::sync::Arc::make_mut(asset).link = Some("/definitely/missing dir/photo.jpg".into()); + // The temporary folder is an absolute path with the default settings on Windows, macOS and Linux. On Windows, + // `/x` names no drive, so `document_path` refuses it when the document has no path. + let link = std::env::temp_dir().join(format!("dc-preflight-missing-{} dir", std::process::id())).join("photo.jpg"); + let link = link.to_string_lossy().into_owned(); + std::sync::Arc::make_mut(asset).link = Some(link.clone()); let r = s.execute("preflight.run", &json!({})).unwrap(); let missing: Vec<&str> = r["issues"].as_array().unwrap().iter().filter(|i| i["kind"] == "missingLink").map(|i| i["message"].as_str().unwrap()).collect(); - assert_eq!(missing, ["Missing link: /definitely/missing dir/photo.jpg"]); + assert_eq!(missing, [format!("Missing link: {link}")]); } } diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 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 { "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 { "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/table.rs b/crates/engine/src/cmd/table.rs index 063be89ac..e62fd1344 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -1273,6 +1273,35 @@ fn resize_track(sizes: &[f64], index: usize, delta: f64, keep: bool) -> Option Result<()> { + const ID: &str = "table.resizeBorder"; + if let Some(fid) = super::id_param(p, "frame") { + let it = st.doc.item(fid).ok_or_else(|| bad(ID, format!("no frame {}", fid.0)))?; + if it.text_frame().map(|f| f.story) != Some(story) { + return Err(bad(ID, "the table is not in that frame's story")); + } + if it.locked || st.doc.layer(it.layer).is_some_and(|l| l.locked) { + return Err(bad(ID, "the frame or its layer is locked")); + } + } + Ok(()) +} + +/// The change in track size: `delta`, or `size` measured from the current size `cur`. +fn border_delta(p: &Value, cur: f64) -> Result { + const ID: &str = "table.resizeBorder"; + let delta = match (p.get("delta").and_then(Value::as_f64), p.get("size").and_then(Value::as_f64)) { + (Some(d), _) => d, + (None, Some(sz)) => sz - cur, + (None, None) => return Err(bad(ID, "`delta` or `size` required")), + }; + if !delta.is_finite() { + return Err(bad(ID, "`delta`/`size` must be a finite number")); + } + Ok(delta) +} + fn resize_border(s: &mut Session, p: &Value) -> Result { const ID: &str = "table.resizeBorder"; let column = match str_param(p, "axis") { @@ -1284,15 +1313,7 @@ fn resize_border(s: &mut Session, p: &Value) -> Result { let keep = p.get("keepTableSize").and_then(Value::as_bool).unwrap_or(false); let g = target(s, p, ID)?; let st = s.doc()?; - if let Some(fid) = super::id_param(p, "frame") { - let it = st.doc.item(fid).ok_or_else(|| bad(ID, format!("no frame {}", fid.0)))?; - if it.text_frame().map(|f| f.story) != Some(g.story) { - return Err(bad(ID, "the table is not in that frame's story")); - } - if it.locked || st.doc.layer(it.layer).is_some_and(|l| l.locked) { - return Err(bad(ID, "the frame or its layer is locked")); - } - } + check_border_frame(st, p, g.story)?; let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or_else(|| bad(ID, "no table"))?; let sizes: Vec = if column { t.columns.iter().map(|c| c.width).collect() @@ -1301,14 +1322,7 @@ fn resize_border(s: &mut Session, p: &Value) -> Result { (0..t.nrows()).map(|r| composed_row_height(&cs, t, r).unwrap_or(MIN_TRACK)).collect() }; let cur = *sizes.get(index).ok_or_else(|| bad(ID, format!("index {index} out of range")))?; - let delta = match (p.get("delta").and_then(Value::as_f64), p.get("size").and_then(Value::as_f64)) { - (Some(d), _) => d, - (None, Some(sz)) => sz - cur, - (None, None) => return Err(bad(ID, "`delta` or `size` required")), - }; - if !delta.is_finite() { - return Err(bad(ID, "`delta`/`size` must be a finite number")); - } + let delta = border_delta(p, cur)?; let new = resize_track(&sizes, index, delta, keep).ok_or_else(|| bad(ID, "invalid table geometry"))?; let size = new.get(index).copied().unwrap_or(cur); let scaled = keep && index + 1 == sizes.len(); @@ -1751,7 +1765,7 @@ fn table_style_fields(ts: &mut designcraft_doc::TableStyle, p: &Value, border: O ts.borders = Default::default(); } if let Some(a) = p.get("altRows").and_then(Value::as_object) { - let n = |k: &str, d: u32| a.get(k).and_then(Value::as_u64).map_or(d, |v| v as u32); + let n = |k: &str, d: u32| a.get(k).and_then(Value::as_u64).map_or(d, |v| u32::try_from(v).unwrap_or(u32::MAX)); let c = |k: &str| a.get(k).and_then(Value::as_str).unwrap_or(designcraft_color::swatch::NONE).to_string(); let t = |k: &str| a.get(k).and_then(Value::as_f64).map_or(1.0, |v| v.clamp(0.0, 1.0) as f32); ts.alt_rows = Some(designcraft_doc::AltFills { @@ -2466,3 +2480,22 @@ mod resize_border_tests { assert!(s.execute("table.resizeBorder", &json!({"frame": f, "table": t, "axis": "column", "index": 0, "delta": 5})).is_err()); } } + +#[cfg(test)] +mod style_alt_rows_tests { + use serde_json::json; + + use super::table_style_fields; + + #[test] + fn style_alt_rows_counts_saturate() { + let mut ts = designcraft_doc::TableStyle::default(); + let p = json!({"altRows": {"first": 4294967297u64, "next": 4294967296u64, "skipFirst": 4294967295u64, "skipLast": 3}}); + table_style_fields(&mut ts, &p, None); + let a = ts.alt_rows.unwrap(); + assert_eq!(a.first, u32::MAX, "first"); + assert_eq!(a.next, u32::MAX, "next"); + assert_eq!(a.skip_first, u32::MAX, "skip_first"); + assert_eq!(a.skip_last, 3, "skip_last"); + } +} diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 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 { }) } ), + 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 { "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 { "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 { - 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> { let st = s.doc()?; let mut stories: Vec = 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 { 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 { + 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 { + 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 { "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 { let mut first: Option> = 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/engine/src/guard.rs b/crates/engine/src/guard.rs index 2ac6bb63c..6395c3594 100644 --- a/crates/engine/src/guard.rs +++ b/crates/engine/src/guard.rs @@ -13,7 +13,7 @@ use crate::{EngineError, Result, Session}; pub fn panic_message(payload: &(dyn std::any::Any + Send)) -> String { payload .downcast_ref::<&str>() - .map(|s| s.to_string()) + .map(ToString::to_string) .or_else(|| payload.downcast_ref::().cloned()) .unwrap_or_else(|| "unknown panic".into()) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index d16dc9dd1..545c3fac3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -542,17 +542,7 @@ impl Session { // passes that its command's description doesn't name fails the test. #[cfg(test)] check_params(id, params)?; - if let Err(e) = (spec.enabled)(self) { - // A command that takes `ids` acts on the objects the call names, so the selection - // doesn't matter: with a text caret, nothing selected, or a selection the command - // can't act on, `{"ids": [5]}` still runs. - let named = if cmd::selection_reason(&e) { cmd::named_targets(spec, params) } else { None }; - let Some(ids) = named else { return Err(EngineError::Disabled(id.into(), e)) }; - let st = self.doc()?; - if let Some(gone) = ids.iter().find(|i| st.doc.item(**i).is_none()) { - return Err(EngineError::Disabled(id.into(), format!("no object with id {}", gone.0))); - } - } + self.check_enabled(spec, id, params)?; // Preview is temporary. Save, merge, and every other edit restore the template first. // Queries stay read-only so the panel can poll fields during a preview. `data.preview` // itself is the one command that fills the live document. @@ -598,11 +588,38 @@ impl Session { st.doc = Arc::new(d); } } - // Auto-size frames fit the text the command changed, in the same undo step. + self.autosize_changed(spec, before.as_ref()); + self.keep_guide_selection_valid(before.as_ref(), id); + self.record_undo_step(spec, before, nested); + if spec.journal { + self.journal.push((id.to_string(), params.clone())); + } + self.discard_stale_find_scope(); + Ok(r) + } + + /// Fails with `Disabled` unless the command is enabled or names objects it can act on. + fn check_enabled(&self, spec: &CommandSpec, id: &str, params: &Value) -> Result<()> { + if let Err(e) = (spec.enabled)(self) { + // A command that takes `ids` acts on the objects the call names, so the selection + // doesn't matter: with a text caret, nothing selected, or a selection the command + // can't act on, `{"ids": [5]}` still runs. + let named = if cmd::selection_reason(&e) { cmd::named_targets(spec, params) } else { None }; + let Some(ids) = named else { return Err(EngineError::Disabled(id.into(), e)) }; + let st = self.doc()?; + if let Some(gone) = ids.iter().find(|i| st.doc.item(**i).is_none()) { + return Err(EngineError::Disabled(id.into(), format!("no object with id {}", gone.0))); + } + } + Ok(()) + } + + /// Auto-size frames fit the text the command changed, in the same undo step. + fn autosize_changed(&mut self, spec: &CommandSpec, before: Option<&(u64, Arc, Selection)>) { if spec.undoable && let Some(st) = self.active_mut() { - let prev = before.as_ref().filter(|(uid, _, _)| *uid == st.uid).map(|(_, d, _)| d.as_ref()); + let prev = before.filter(|(uid, _, _)| *uid == st.uid).map(|(_, d, _)| d.as_ref()); if prev.is_none_or(|p| !std::ptr::eq(p, st.doc.as_ref())) { let todo = autosize::candidates(&st.doc, prev); if !todo.is_empty() { @@ -614,13 +631,6 @@ impl Session { } } } - self.keep_guide_selection_valid(before.as_ref(), id); - self.record_undo_step(spec, before, nested); - if spec.journal { - self.journal.push((id.to_string(), params.clone())); - } - self.discard_stale_find_scope(); - Ok(r) } /// Drops selected guides the command `id` made stale, against the document as it will be diff --git a/crates/epub/src/lib.rs b/crates/epub/src/lib.rs index 1df759608..62de05cb7 100644 --- a/crates/epub/src/lib.rs +++ b/crates/epub/src/lib.rs @@ -450,11 +450,12 @@ fn char_css(doc: &Document, c: &CharProps, base_size: f64, generics: &BTreeMap {} } - if c.underline { - out.push_str("text-decoration: underline; "); - } - if c.strikethrough { - out.push_str("text-decoration: line-through; "); + // One declaration: a later `text-decoration` would replace the earlier one. + match (c.underline, c.strikethrough) { + (true, true) => out.push_str("text-decoration: underline line-through; "), + (true, false) => out.push_str("text-decoration: underline; "), + (false, true) => out.push_str("text-decoration: line-through; "), + (false, false) => {} } if let Some(h) = hex(doc, &c.fill, c.fill_tint) { let _ = write!(out, "color: {h}; "); @@ -785,6 +786,39 @@ impl<'a, 'f> StoryWriter<'a, 'f> { close_blocks(&mut list, &mut pre, out); } + /// The markup for one run's text `raw` (starting at byte `a` of the story): anchored objects + /// and notes where their marks are. + fn run_markup(&mut self, st: &Story, raw: &str, a: usize, depth: usize, after: &mut String) -> String { + let doc = self.doc; + let mut t = String::new(); + let mut seg_start = 0; + // Index of the next anchored object: marks count from the story start, as + // `Story::object_at` counts them (counted once, at the run's first mark). + let mut mark: Option = None; + for (i, c) in raw.char_indices() { + if c != FOOTNOTE_REF && c != ENDNOTE_REF && c != OBJECT_MARK { + continue; + } + t.push_str(&run_text(doc, raw.get(seg_start..i).unwrap_or_default())); + seg_start = i + c.len_utf8(); + if c == OBJECT_MARK { + let k = mark.unwrap_or_else(|| st.text.get(..a).map_or(0, |t| t.matches(OBJECT_MARK).count())); + mark = Some(k.saturating_add(1)); + if let Some(o) = st.objects.get(k) { + t.push_str(&self.object(o)); + } + } else if depth < MAX_DEPTH { + if c == FOOTNOTE_REF { + self.footnote(st, a + i, depth, &mut t, after); + } else { + self.endnote(st, a + i, depth, &mut t); + } + } + } + t.push_str(&run_text(doc, raw.get(seg_start..).unwrap_or_default())); + t + } + /// The runs of paragraph `para` of `st`; footnotes go to `after`. fn runs(&mut self, st: &Story, para: std::ops::Range, depth: usize, out: &mut String, after: &mut String) { let doc = self.doc; @@ -799,32 +833,7 @@ impl<'a, 'f> StoryWriter<'a, 'f> { continue; } let Some(raw) = st.text.get(a..b) else { continue }; - let mut t = String::new(); - let mut seg_start = 0; - // Index of the next anchored object: marks count from the story start, as - // `Story::object_at` counts them (counted once, at the run's first mark). - let mut mark: Option = None; - for (i, c) in raw.char_indices() { - if c != FOOTNOTE_REF && c != ENDNOTE_REF && c != OBJECT_MARK { - continue; - } - t.push_str(&run_text(doc, raw.get(seg_start..i).unwrap_or_default())); - seg_start = i + c.len_utf8(); - if c == OBJECT_MARK { - let k = mark.unwrap_or_else(|| st.text.get(..a).map_or(0, |t| t.matches(OBJECT_MARK).count())); - mark = Some(k.saturating_add(1)); - if let Some(o) = st.objects.get(k) { - t.push_str(&self.object(o)); - } - } else if depth < MAX_DEPTH { - if c == FOOTNOTE_REF { - self.footnote(st, a + i, depth, &mut t, after); - } else { - self.endnote(st, a + i, depth, &mut t); - } - } - } - t.push_str(&run_text(doc, raw.get(seg_start..).unwrap_or_default())); + let t = self.run_markup(st, raw, a, depth, after); let (ctag, cls) = if f.style != story::NO_CHAR_STYLE { let (tag, class) = export_mapping(&doc.styles, &f.style, true, &self.cc); (tag, format!(" class=\"{}\"", xml_attr(&class))) @@ -2223,4 +2232,21 @@ mod tests { let last = "
  • 1 End note
  • "; assert_eq!(link_across_chapters(last, "content2.xhtml", &files), "
  • 1 End note
  • "); } + + #[test] + fn char_css_joins_underline_and_strikethrough_in_one_declaration() { + let d = Document::new(&NewDocument::default()); + let css = |u: bool, s: bool| { + let c = CharProps { underline: u, strikethrough: s, ..CharProps::default() }; + let mut out = String::new(); + char_css(&d, &c, 12.0, &BTreeMap::new(), &mut out); + out + }; + let both = css(true, true); + assert_eq!(both.matches("text-decoration:").count(), 1, "{both}"); + assert!(both.contains("text-decoration: underline line-through;"), "{both}"); + assert!(css(true, false).contains("text-decoration: underline;")); + assert!(css(false, true).contains("text-decoration: line-through;")); + assert!(!css(false, false).contains("text-decoration")); + } } diff --git a/crates/fonts/src/fontdb.rs b/crates/fonts/src/fontdb.rs index ef5314b32..1c1e55bd1 100644 --- a/crates/fonts/src/fontdb.rs +++ b/crates/fonts/src/fontdb.rs @@ -148,7 +148,7 @@ pub struct FaceRef(&'static FontFace); impl FaceRef { /// The handle for a loaded face (memoised per face). pub fn of(face: &Arc) -> FaceRef { - static LEAKED: RwLock>> = RwLock::new(Vec::new()); + static LEAKED: RwLock>> = RwLock::new(Vec::new()); let id = face.id as usize; if let Some(Some(f)) = LEAKED.read().unwrap_or_else(PoisonError::into_inner).get(id) { return FaceRef(f); @@ -579,7 +579,7 @@ fn script_chain(c: char) -> Option<&'static [&'static str]> { /// The Japanese fallback chain: the craft-fonts Japanese faces' families in document order /// (Mincho first; none without craft-fonts), then [`JAPANESE_FALLBACKS`]. fn japanese_chain() -> &'static [&'static str] { - static CHAIN: std::sync::OnceLock> = std::sync::OnceLock::new(); + static CHAIN: std::sync::OnceLock> = std::sync::OnceLock::new(); CHAIN.get_or_init(|| { let mut chain: Vec<&'static str> = Vec::new(); for f in crate::japanese_document_fonts() { @@ -1314,7 +1314,7 @@ impl FontDb { stack.push(p); continue; } - let ext = p.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase()); + let ext = p.extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase); if !matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) { continue; } @@ -1399,7 +1399,7 @@ impl FontDb { let Ok(entries) = std::fs::read_dir(folder) else { return out }; let mut files: Vec = Vec::new(); for path in entries.flatten().map(|e| e.path()) { - let ext = path.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase()); + let ext = path.extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase); if !matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) { continue; } diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index b50234a8f..adfc4a2e4 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -281,9 +281,12 @@ impl PathData { for el in bp.elements() { match *el { PathEl::MoveTo(p) => { - if let Some(sp) = cur.take() + if let Some(mut sp) = cur.take() && !sp.anchors.is_empty() { + for a in &mut sp.anchors { + *a = Anchor::with_handles(a.p, a.h_in, a.h_out); + } subpaths.push(sp); } cur = Some(SubPath { anchors: vec![Anchor::corner(p)], closed: false }); @@ -418,6 +421,20 @@ mod tests { PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)], true)) } + #[test] + fn from_bezpath_detects_smooth_on_every_open_subpath() { + let mut bp = BezPath::new(); + for _ in 0..2 { + bp.move_to((0.0, 0.0)); + bp.curve_to((0.0, 10.0), (10.0, 10.0), (10.0, 0.0)); + bp.curve_to((10.0, -10.0), (20.0, -10.0), (20.0, 0.0)); + } + let pd = PathData::from_bezpath(&bp); + assert_eq!(pd.subpaths.len(), 2); + assert_eq!(pd.subpaths[1].anchors[1].kind, AnchorKind::Smooth); + assert_eq!(pd.subpaths[0].anchors[1].kind, pd.subpaths[1].anchors[1].kind); + } + #[test] fn anchors_serialize_compactly_and_read_v1_maps() { let corner = Anchor::corner(Point::new(1.0, 2.0)); diff --git a/crates/geom/src/trace.rs b/crates/geom/src/trace.rs index b2d850ea9..292f82e87 100644 --- a/crates/geom/src/trace.rs +++ b/crates/geom/src/trace.rs @@ -5,12 +5,9 @@ use std::collections::HashMap; use crate::Point; -/// Closed outlines around the `true` cells of a `w`×`h` mask (row-major), simplified to within -/// `tol` pixels; outlines enclosing less than `min_area` pixels are dropped. Holes come out -/// with the opposite winding. -pub fn trace(mask: &[bool], w: usize, h: usize, tol: f64, min_area: f64) -> Vec> { +/// Pixel-border edges of the mask with the inside on the right (clockwise, y down), by start point. +fn border_edges(mask: &[bool], w: usize, h: usize) -> HashMap<(isize, isize), Vec<(isize, isize)>> { let inside = |x: isize, y: isize| x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h && mask[y as usize * w + x as usize]; - // Pixel-border edges with the inside on the right (clockwise, y down). let mut next: HashMap<(isize, isize), Vec<(isize, isize)>> = HashMap::new(); let mut add = |a: (isize, isize), b: (isize, isize)| next.entry(a).or_default().push(b); for y in 0..h as isize { @@ -32,16 +29,24 @@ pub fn trace(mask: &[bool], w: usize, h: usize, tol: f64, min_area: f64) -> Vec< } } } + next +} + +/// Closed outlines around the `true` cells of a `w`×`h` mask (row-major), simplified to within +/// `tol` pixels; outlines enclosing less than `min_area` pixels are dropped. Holes come out +/// with the opposite winding. +pub fn trace(mask: &[bool], w: usize, h: usize, tol: f64, min_area: f64) -> Vec> { + let mut next = border_edges(mask, w, h); let mut out = Vec::new(); let mut starts: Vec<(isize, isize)> = next.keys().copied().collect(); starts.sort(); for s in starts { - while let Some(first) = next.get_mut(&s).and_then(|v| v.pop()) { + while let Some(first) = next.get_mut(&s).and_then(Vec::pop) { let mut ring = vec![s]; let mut cur = first; while cur != s { ring.push(cur); - match next.get_mut(&cur).and_then(|v| v.pop()) { + match next.get_mut(&cur).and_then(Vec::pop) { Some(n) => cur = n, None => break, } diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs index d3587c943..3a9dc778d 100644 --- a/crates/idml/src/export.rs +++ b/crates/idml/src/export.rs @@ -177,7 +177,7 @@ impl<'a> Ex<'a> { } fn assign_swatch_ids(&mut self) { - let mut used: HashSet = ["Swatch/None", "Color/Paper", "Color/Black", "Color/Registration"].iter().map(|s| s.to_string()).collect(); + let mut used: HashSet = ["Swatch/None", "Color/Paper", "Color/Black", "Color/Registration"].iter().map(ToString::to_string).collect(); self.swatch_ids.insert(swatch::NONE.into(), "Swatch/None".into()); self.swatch_ids.insert(swatch::PAPER.into(), "Color/Paper".into()); self.swatch_ids.insert(swatch::BLACK.into(), "Color/Black".into()); @@ -309,28 +309,7 @@ impl<'a> Ex<'a> { ); } for t in &d.styles.mojikumi_tables { - let mut e = El::new("MojikumiTable").attr("Self", format!("MojikumiTable/{}", escape_id(&t.name))).attr("Name", &t.name); - if !t.based_on.is_empty() { - e.set("BasedOnMojikumiSet", &t.based_on); - } - if !t.overrides.is_empty() { - let mut list = El::new("OverrideMojikumiAkiList"); - for r in &t.overrides { - list.push( - El::new("OverrideMojikumiAkiType") - .attr("TargetMojikumiClass", r.target_class) - .attr("SideMojikumiClass", r.side_class) - .attr("SideIsAfterTarget", bool_s(r.after)) - .attr("Minimum", num(r.minimum)) - .attr("Desired", num(r.desired)) - .attr("Maximum", num(r.maximum)) - .attr("CompressionPriority", r.priority) - .attr("AkiDoesNotFloat", bool_s(r.does_not_float)), - ); - } - e.push(El::new("Properties").child(list)); - } - root.push(e); + root.push(mojikumi_table_el(t)); } root.push(El::new("idPkg:Graphic").attr("src", "Resources/Graphic.xml")); root.push(El::new("idPkg:Fonts").attr("src", "Resources/Fonts.xml")); @@ -364,28 +343,7 @@ impl<'a> Ex<'a> { } // IDML lists layers back to front. for l in d.layers.iter().rev() { - let color = match names::layer_color_out(l.color) { - Some(n) => p("LayerColor", "enumeration", n), - None => { - let mut e = El::new("LayerColor").attr("type", "list"); - for c in l.color { - e.push(p("ListItem", "double", num(c as f64))); - } - e - } - }; - let el = El::new("Layer") - .attr("Self", uid(l.id.0)) - .attr("Name", &l.name) - .attr("Visible", bool_s(l.visible)) - .attr("Locked", bool_s(l.locked)) - .attr("IgnoreWrap", bool_s(l.suppress_wrap_when_hidden)) - .attr("ShowGuides", bool_s(l.show_guides)) - .attr("LockGuides", "false") - .attr("UI", "true") - .attr("Expendable", "true") - .attr("Printable", bool_s(l.printable)); - root.push(with_props(el, vec![color])); + root.push(layer_el(l)); } for (name, _) in masters { root.push(El::new("idPkg:MasterSpread").attr("src", name)); @@ -1570,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"); @@ -1828,33 +1787,7 @@ impl<'a> Ex<'a> { .attr("ItemTransform", format!("1 0 0 1 {} {}", num(pg.x - ox), num(-oy))) .child(margin_el(pg)); let mut pe = pe; - // Ruler guides, measured from the ruler origin written in the preferences: the - // spread's top left, the page's, or the spine (the import reads them the same way). - let left = sp.pages.iter().map(|p| p.x).fold(f64::INFINITY, f64::min); - let left = if left.is_finite() { left } else { 0.0 }; - let spine = sp.pages.iter().map(|p| p.x - left).filter(|x| *x > 1e-6).fold(f64::INFINITY, f64::min); - let spine = if spine.is_finite() && facing { spine } else { 0.0 }; - let origin_x = match d.settings.ruler_origin { - designcraft_doc::RulerOrigin::Spread => left, - designcraft_doc::RulerOrigin::Page => pg.x, - designcraft_doc::RulerOrigin::Spine => left + spine, - }; - for g in &pg.guides { - let vertical = g.orientation == designcraft_doc::Orientation::Vertical; - let mut ge = El::new("Guide") - .attr("Self", format!("{}g{}", uid(pg.id.0), pe.elements().count())) - .attr("Orientation", if vertical { "Vertical" } else { "Horizontal" }) - .attr("Location", num(if vertical { g.position - origin_x } else { g.position })) - .attr("FitToPage", bool_s(!g.spread)) - .attr("ViewThreshold", "5") - .attr("Locked", bool_s(g.locked)) - .attr("PageIndex", (first_page + i).to_string()) - .attr("GuideType", if g.liquid { "Liquid" } else { "Ruler" }); - if let Some(l) = g.layer { - ge.set("ItemLayer", uid(l.0)); - } - pe.push(ge); - } + push_page_guides(d, sp, pg, &mut pe, first_page + i); el.push(pe); } let origin = Affine::translate((-ox, -oy)); @@ -2012,12 +1945,21 @@ impl<'a> Ex<'a> { } if let Content::Text(t) = &it.content { el.push(text_frame_pref(&t.options, &self.sw(&t.options.column_rule_color))); - if let Some((start, inc)) = t.options.baseline_grid { + if let Some(g) = t.options.baseline_grid { el.push( El::new("BaselineFrameGridOption") .attr("UseCustomBaselineFrameGrid", "true") - .attr("StartingOffsetForBaselineFrameGrid", num(start)) - .attr("BaselineFrameGridIncrement", num(inc)), + .attr("StartingOffsetForBaselineFrameGrid", num(g.start)) + .attr( + "BaselineFrameGridRelativeOption", + match g.relative_to { + designcraft_doc::FrameGridRelative::TopOfPage => "TopOfPageOfBaselineFrameGridRelativeOption", + designcraft_doc::FrameGridRelative::TopMargin => "TopOfMarginOfBaselineFrameGridRelativeOption", + designcraft_doc::FrameGridRelative::TopOfFrame => "TopOfFrameOfBaselineFrameGridRelativeOption", + designcraft_doc::FrameGridRelative::TopInset => "TopOfInsetOfBaselineFrameGridRelativeOption", + }, + ) + .attr("BaselineFrameGridIncrement", num(g.increment)), ); } } @@ -2285,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( @@ -3197,6 +3142,90 @@ fn metadata_xmp(d: &Document) -> String { ) } +/// The page's ruler guides, measured from the ruler origin written in the preferences. +fn push_page_guides(d: &Document, sp: &Spread, pg: &designcraft_doc::Page, pe: &mut El, page_index: usize) { + let facing = d.settings.facing_pages; + // Ruler guides, measured from the ruler origin written in the preferences: the + // spread's top left, the page's, or the spine (the import reads them the same way). + let left = sp.pages.iter().map(|p| p.x).fold(f64::INFINITY, f64::min); + let left = if left.is_finite() { left } else { 0.0 }; + let spine = sp.pages.iter().map(|p| p.x - left).filter(|x| *x > 1e-6).fold(f64::INFINITY, f64::min); + let spine = if spine.is_finite() && facing { spine } else { 0.0 }; + let origin_x = match d.settings.ruler_origin { + designcraft_doc::RulerOrigin::Spread => left, + designcraft_doc::RulerOrigin::Page => pg.x, + designcraft_doc::RulerOrigin::Spine => left + spine, + }; + for g in &pg.guides { + let vertical = g.orientation == designcraft_doc::Orientation::Vertical; + let mut ge = El::new("Guide") + .attr("Self", format!("{}g{}", uid(pg.id.0), pe.elements().count())) + .attr("Orientation", if vertical { "Vertical" } else { "Horizontal" }) + .attr("Location", num(if vertical { g.position - origin_x } else { g.position })) + .attr("FitToPage", bool_s(!g.spread)) + .attr("ViewThreshold", "5") + .attr("Locked", bool_s(g.locked)) + .attr("PageIndex", page_index.to_string()) + .attr("GuideType", if g.liquid { "Liquid" } else { "Ruler" }); + if let Some(l) = g.layer { + ge.set("ItemLayer", uid(l.0)); + } + pe.push(ge); + } +} + +/// A `MojikumiTable` element with its spacing overrides. +fn mojikumi_table_el(t: &designcraft_doc::cjk::MojikumiTable) -> El { + let mut e = El::new("MojikumiTable").attr("Self", format!("MojikumiTable/{}", escape_id(&t.name))).attr("Name", &t.name); + if !t.based_on.is_empty() { + e.set("BasedOnMojikumiSet", &t.based_on); + } + if !t.overrides.is_empty() { + let mut list = El::new("OverrideMojikumiAkiList"); + for r in &t.overrides { + list.push( + El::new("OverrideMojikumiAkiType") + .attr("TargetMojikumiClass", r.target_class) + .attr("SideMojikumiClass", r.side_class) + .attr("SideIsAfterTarget", bool_s(r.after)) + .attr("Minimum", num(r.minimum)) + .attr("Desired", num(r.desired)) + .attr("Maximum", num(r.maximum)) + .attr("CompressionPriority", r.priority) + .attr("AkiDoesNotFloat", bool_s(r.does_not_float)), + ); + } + e.push(El::new("Properties").child(list)); + } + e +} + +/// A `Layer` element with its colour property. +fn layer_el(l: &designcraft_doc::Layer) -> El { + let color = match names::layer_color_out(l.color) { + Some(n) => p("LayerColor", "enumeration", n), + None => { + let mut e = El::new("LayerColor").attr("type", "list"); + for c in l.color { + e.push(p("ListItem", "double", num(c as f64))); + } + e + } + }; + let el = El::new("Layer") + .attr("Self", uid(l.id.0)) + .attr("Name", &l.name) + .attr("Visible", bool_s(l.visible)) + .attr("Locked", bool_s(l.locked)) + .attr("IgnoreWrap", bool_s(l.suppress_wrap_when_hidden)) + .attr("ShowGuides", bool_s(l.show_guides)) + .attr("LockGuides", "false") + .attr("UI", "true") + .attr("Expendable", "true") + .attr("Printable", bool_s(l.printable)); + with_props(el, vec![color]) +} + /// A text variable definition with its type's settings element. fn text_variable_el(v: &designcraft_doc::vars::TextVariable) -> El { use designcraft_doc::vars::{Use, VarKind}; @@ -3338,6 +3367,10 @@ impl Ex<'_> { if let Some(v) = a.kenten_overprint_stroke { el.set("KentenOverprintStroke", crate::cjk::overprint_out(v)); } + self.shatai_chars(el, a); + } + + fn shatai_chars(&self, el: &mut El, a: &CharAttrs) { if let Some(v) = a.shatai_magnification { el.set("ShataiMagnification", num(v)); } diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index 039d1e562..1000638d3 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -1641,28 +1641,7 @@ impl<'r> Importer<'r> { a.strikethrough_tint = tint; } } - // OpenType features (only when the element sets any). - let mut otf_list: Vec = Vec::new(); - let mut any = false; - for (tag, _, attr) in designcraft_doc::otf::TOGGLES { - if let Some(on) = e.boolean(attr) { - designcraft_doc::otf::set(&mut otf_list, tag, on); - any = true; - } - } - if let Some(fig) = e.prop("OTFFigureStyle") - && let Some((id, ..)) = designcraft_doc::otf::FIGURES.iter().find(|f| f.3 == fig.trim()) - { - designcraft_doc::otf::set_figures(&mut otf_list, id); - any = true; - } - if let Some(m) = e.num("OTFStylisticSets") { - designcraft_doc::otf::set_stylistic_sets(&mut otf_list, m.max(0.0) as u32); - any = true; - } - if any { - a.otf_features = Some(otf_list); - } + read_otf_features(e, &mut a); a.glyph_form = e.prop("GlyphForm"); a.no_break = e.boolean("NoBreak"); a.tate_chu_yoko = e.boolean("Tatechuyoko"); @@ -1841,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"); @@ -2116,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, @@ -2128,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, @@ -2995,8 +2984,11 @@ impl<'r> Importer<'r> { if let Some(g) = self.with_style(e, "BaselineFrameGridOption") && g.get("UseCustomBaselineFrameGrid") == Some("true") { - options.baseline_grid = - Some((g.num("StartingOffsetForBaselineFrameGrid").unwrap_or(0.0), g.num("BaselineFrameGridIncrement").unwrap_or(12.0))); + options.baseline_grid = Some(designcraft_doc::FrameBaselineGrid { + start: g.num("StartingOffsetForBaselineFrameGrid").unwrap_or(0.0), + increment: g.num("BaselineFrameGridIncrement").unwrap_or(12.0), + relative_to: g.get("BaselineFrameGridRelativeOption").map(frame_grid_relative).unwrap_or_default(), + }); } it.content = Content::Text(TextFrame { story, options }); self.ctx.threads.push(( @@ -3537,6 +3529,19 @@ fn fit_columns(mut columns: Columns, margins: &Margins, page_width: f64) -> Colu columns } +/// A `BaselineFrameGridRelativeOption` value (`TopOfInsetOfBaselineFrameGridRelativeOption`, or a +/// short form such as `TopOfInset`); unknown values measure from the top of the page. +fn frame_grid_relative(v: &str) -> designcraft_doc::FrameGridRelative { + use designcraft_doc::FrameGridRelative as R; + let v = v.strip_suffix("OfBaselineFrameGridRelativeOption").unwrap_or(v); + match v { + "TopOfMargin" | "TopMargin" => R::TopMargin, + "TopOfFrame" => R::TopOfFrame, + "TopOfInset" | "TopInset" => R::TopInset, + _ => R::TopOfPage, + } +} + /// Text Frame Options from `TextFramePreference` elements: each attribute from the first that sets it. fn text_frame_options(prefs: &[&El]) -> TextFrameOptions { let e = Prefs(prefs); @@ -3889,6 +3894,31 @@ impl Importer<'_> { } } +/// OpenType features (only when the element sets any). +fn read_otf_features(e: &El, a: &mut CharAttrs) { + let mut otf_list: Vec = Vec::new(); + let mut any = false; + for (tag, _, attr) in designcraft_doc::otf::TOGGLES { + if let Some(on) = e.boolean(attr) { + designcraft_doc::otf::set(&mut otf_list, tag, on); + any = true; + } + } + if let Some(fig) = e.prop("OTFFigureStyle") + && let Some((id, ..)) = designcraft_doc::otf::FIGURES.iter().find(|f| f.3 == fig.trim()) + { + designcraft_doc::otf::set_figures(&mut otf_list, id); + any = true; + } + if let Some(m) = e.num("OTFStylisticSets") { + designcraft_doc::otf::set_stylistic_sets(&mut otf_list, m.max(0.0) as u32); + any = true; + } + if any { + a.otf_features = Some(otf_list); + } +} + #[cfg(test)] mod numeric_property_tests { use super::*; diff --git a/crates/idml/src/ruby.rs b/crates/idml/src/ruby.rs index 601792f6c..352da63a1 100644 --- a/crates/idml/src/ruby.rs +++ b/crates/idml/src/ruby.rs @@ -98,11 +98,45 @@ pub(crate) fn read(e: &El, a: &mut CharAttrs, mut swatch: impl FnMut(&str) -> St a.ruby_overprint_stroke = overprint("RubyOverprintStroke"); } +/// Ruby parent-text options (OpenType Pro, auto tate-chu-yoko, overhang, spacing, scaling). +fn write_parent_options(el: &mut El, a: &CharAttrs) { + let b = |v: bool| if v { "true" } else { "false" }; + if let Some(v) = a.ruby_open_type_pro { + el.set("RubyOpenTypePro", b(v)); + } + if let Some(v) = a.ruby_auto_tcy_digits { + el.set("RubyAutoTcyDigits", v); + } + if let Some(v) = a.ruby_auto_tcy_include_roman { + el.set("RubyAutoTcyIncludeRoman", b(v)); + } + if let Some(v) = a.ruby_auto_tcy_auto_scale { + el.set("RubyAutoTcyAutoScale", b(v)); + } + if let Some(v) = a.ruby_overhang { + el.set("RubyOverhang", b(v)); + } + if let Some(v) = a.ruby_overhang_amount.and_then(|v| name(OVERHANGS, v)) { + el.set("RubyParentOverhangAmount", v); + } + if let Some(v) = a.ruby_parent_spacing.and_then(|v| name(SPACINGS, v)) { + el.set("RubyParentSpacing", v); + } + if let Some(v) = a.ruby_auto_align { + el.set("RubyAutoAlign", b(v)); + } + if let Some(v) = a.ruby_auto_scaling { + el.set("RubyAutoScaling", b(v)); + } + if let Some(v) = a.ruby_scaling_min { + el.set("RubyParentScalingPercent", num(v * 100.0)); + } +} + /// Write the ruby settings set in `a`: attributes on `el`, fonts and colours as `props`. `sw` /// maps a swatch name to its IDML reference. Returns the ruby font (family, style) to list in /// the fonts part. pub(crate) fn write(el: &mut El, props: &mut Vec, a: &CharAttrs, sw: impl Fn(&str) -> String) -> Option<(String, String)> { - let b = |v: bool| if v { "true" } else { "false" }; let prop = |k: &str, ty: &str, v: String| El::new(k).attr("type", ty).text(v); if let Some(v) = a.ruby_type.and_then(|v| name(TYPES, v)) { el.set("RubyType", v); @@ -134,36 +168,7 @@ pub(crate) fn write(el: &mut El, props: &mut Vec, a: &CharAttrs, sw: impl Fn if let Some(v) = a.ruby_y_scale { el.set("RubyYScale", num(v * 100.0)); } - if let Some(v) = a.ruby_open_type_pro { - el.set("RubyOpenTypePro", b(v)); - } - if let Some(v) = a.ruby_auto_tcy_digits { - el.set("RubyAutoTcyDigits", v); - } - if let Some(v) = a.ruby_auto_tcy_include_roman { - el.set("RubyAutoTcyIncludeRoman", b(v)); - } - if let Some(v) = a.ruby_auto_tcy_auto_scale { - el.set("RubyAutoTcyAutoScale", b(v)); - } - if let Some(v) = a.ruby_overhang { - el.set("RubyOverhang", b(v)); - } - if let Some(v) = a.ruby_overhang_amount.and_then(|v| name(OVERHANGS, v)) { - el.set("RubyParentOverhangAmount", v); - } - if let Some(v) = a.ruby_parent_spacing.and_then(|v| name(SPACINGS, v)) { - el.set("RubyParentSpacing", v); - } - if let Some(v) = a.ruby_auto_align { - el.set("RubyAutoAlign", b(v)); - } - if let Some(v) = a.ruby_auto_scaling { - el.set("RubyAutoScaling", b(v)); - } - if let Some(v) = a.ruby_scaling_min { - el.set("RubyParentScalingPercent", num(v * 100.0)); - } + write_parent_options(el, a); for (k, c) in [("RubyFill", &a.ruby_fill), ("RubyStroke", &a.ruby_stroke)] { if let Some(c) = c { props.push(if c.is_empty() { prop(k, "string", TEXT_COLOR.into()) } else { prop(k, "object", sw(c.as_str())) }); diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index b72ba1c86..fcee91706 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -10,6 +10,8 @@ use super::*; mod assets; mod clipping; mod decorations; +mod facing_ltr; +mod frame_grid; mod index_sort; mod liquid_guides; mod object_styles; @@ -298,6 +300,7 @@ fn indesign_text_defaults() -> Vec { "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; @@ -482,6 +485,57 @@ fn text_color_rules_round_trip() { assert_eq!(p.para.kashidas, Some(false)); } +fn optical_story(pref: &str) -> String { + format!( + r#" + + + + + “Hung” here.
    +
    + + “Flush” here. + +
    +
    "# + ) +} + +/// 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/idml/src/tests/facing_ltr.rs b/crates/idml/src/tests/facing_ltr.rs new file mode 100644 index 000000000..b1c322ecc --- /dev/null +++ b/crates/idml/src/tests/facing_ltr.rs @@ -0,0 +1,111 @@ +use designcraft_doc::PageSide::{self, Left, Right}; + +use super::*; + +const NS: &str = r#"xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0""#; + +/// A running head: a text frame across `x0..x1` (IDML spread x), 20 pt below the page top. +fn head(id: &str, story: &str, x0: f64, x1: f64) -> String { + let pts: String = [(x0, -280.0), (x0, -260.0), (x1, -260.0), (x1, -280.0)] + .iter() + .map(|(x, y)| format!(r#""#)) + .collect(); + format!( + r#"{pts}"# + ) +} + +fn story(id: &str, text: &str) -> String { + format!( + r#"{text}"# + ) +} + +/// Bound left to right with facing pages: the first page of a spread lies left of the spine +/// (except page 1, alone on the right). Every page has margins `Left=36 Right=120` (inside 36, +/// outside 120), the parent's left page a ruler guide at 108 and a "Left head" running head, its +/// right page a guide at 300 and a "Right head". Three pages: 1 alone, then 2–3. Rulers measure +/// from each page. +fn left_to_right_fixture() -> Vec { + let margins = r#""#; + let page = |id: &str, x: f64, applied: bool, guide: Option| { + let applied = if applied { r#" AppliedMaster="m1""# } else { "" }; + let guide = guide.map_or(String::new(), |at| format!(r#""#)); + format!(r#"{margins}{guide}"#) + }; + let master = format!( + r#"{}{}{}{}"#, + page("mp1", -400.0, false, Some(108.0)), + page("mp2", 0.0, false, Some(300.0)), + head("hl", "sl", -280.0, -36.0), + head("hr", "sr", 36.0, 280.0), + ); + let spread = |id: &str, pages: &[(&str, f64)]| { + let ps: String = pages.iter().map(|(p, x)| page(p, *x, true, None)).collect(); + format!(r#"{ps}"#, pages.len()) + }; + let map = format!( + r#""# + ); + let prefs = format!( + r#""# + ); + zip_files(&[ + ("designmap.xml", &map), + ("Resources/Preferences.xml", &prefs), + ("MasterSpreads/m1.xml", &master), + ("Spreads/sp0.xml", &spread("sp0", &[("p1", 0.0)])), + ("Spreads/sp1.xml", &spread("sp1", &[("p2", -400.0), ("p3", 0.0)])), + ("Stories/sl.xml", &story("sl", "Left head")), + ("Stories/sr.xml", &story("sr", "Right head")), + ]) +} + +/// The text of the running heads a document page shows from its parent page. +fn shown_heads(d: &Document, abs: usize) -> Vec { + let (ppi, ppage) = d.parent_page_for(abs).unwrap(); + let parent = &d.parents[ppi]; + parent + .items + .iter() + .filter(|it| parent.page_at_x(it.bounds().center().x) == Some(ppage)) + .filter_map(|it| d.story(it.text_frame()?.story).map(|s| s.text.clone())) + .collect() +} + +/// Ruler guides of the parent page a document page shows, as x from that parent page's left edge. +fn parent_guides(d: &Document, abs: usize) -> Vec { + let (ppi, ppage) = d.parent_page_for(abs).unwrap(); + let pp = &d.parents[ppi].pages[ppage]; + pp.guides.iter().map(|g| g.position - pp.x).collect() +} + +fn assert_right_pages_mirror_left_pages(d: &Document) { + assert!(d.settings.facing_pages && !d.settings.right_to_left_binding); + let sides: Vec = d.parents[0].pages.iter().map(|p| p.side).collect(); + assert_eq!(sides, vec![Left, Right]); + // Right pages: inside (36) on the left; left pages: outside (120) on the left. + for (abs, side, live, guide, text) in [ + (0, Right, (36.0, 280.0), 300.0, "Right head"), + (1, Left, (120.0, 364.0), 108.0, "Left head"), + (2, Right, (36.0, 280.0), 300.0, "Right head"), + ] { + let n = abs + 1; + let page = d.page(abs).unwrap(); + assert_eq!(page.side, side, "page {n}"); + let m = page.margin_rect(); + assert!((m.x0 - page.x - live.0).abs() < 1e-6 && (m.x1 - page.x - live.1).abs() < 1e-6, "page {n}: margins {m:?}"); + assert_eq!(d.parents[0].pages[d.parent_page_for(abs).unwrap().1].side, side, "page {n} shows the parent's {side:?} page"); + let guides = parent_guides(d, abs); + assert!(guides.len() == 1 && (guides[0] - guide).abs() < 1e-6, "page {n}: guides {guides:?}"); + assert_eq!(shown_heads(d, abs), vec![text.to_string()], "page {n}"); + } +} + +#[test] +fn left_to_right_right_pages_take_mirrored_margins_and_the_right_parent_page() { + let d = import_idml(&left_to_right_fixture()).unwrap(); + assert_right_pages_mirror_left_pages(&d); + let again = import_idml(&export_idml(&d)).unwrap(); + assert_right_pages_mirror_left_pages(&again); +} diff --git a/crates/idml/src/tests/frame_grid.rs b/crates/idml/src/tests/frame_grid.rs new file mode 100644 index 000000000..99f57b4ea --- /dev/null +++ b/crates/idml/src/tests/frame_grid.rs @@ -0,0 +1,98 @@ +use super::*; + +const NS: &str = r#"xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="14.0""#; + +/// A page with one text frame at its top edge whose custom baseline grid starts at 6 pt with a +/// 14 pt increment; its four paragraphs align to the grid. The frame's top is the page's top, so +/// the grid lines are 6 + n·14 pt down from the frame top whatever the grid is measured from. +fn frame_grid_doc() -> Document { + frame_grid_doc_relative(None) +} + +/// [`frame_grid_doc`] with `BaselineFrameGridRelativeOption` set to `relative` when given. +fn frame_grid_doc_relative(relative: Option<&str>) -> Document { + let relative = relative.map(|r| format!(r#" BaselineFrameGridRelativeOption="{r}""#)).unwrap_or_default(); + let designmap = format!( + r#" +"# + ); + let prefs = format!(r#""#); + let pts: String = [(50.0, 0.0), (50.0, 300.0), (250.0, 300.0), (250.0, 0.0)] + .iter() + .map(|(x, y)| format!(r#""#)) + .collect(); + let spread = format!( + r#" +{pts} +"# + ); + let story = format!( + r#"One
    Two
    Three
    Four
    "# + ); + let bytes = zip_files(&[ + ("designmap.xml", &designmap), + ("Resources/Graphic.xml", GRAPHIC), + ("Resources/Styles.xml", STYLES), + ("Resources/Preferences.xml", &prefs), + ("Spreads/Spread_sp1.xml", &spread), + ("Stories/Story_s1.xml", &story), + ]); + import_idml_with(&bytes, &|_| None).unwrap() +} + +/// Each composed line's baseline below the frame top. +fn baselines(d: &Document) -> Vec { + let sid = *d.stories.keys().next().unwrap(); + let top = d.spreads[0].items[0].text_area().y0; + let cs = designcraft_compose::compose_story(d, sid, &Default::default()); + cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| l.baseline - top).collect() +} + +#[test] +fn custom_frame_grid_sets_lines_from_its_start_by_its_increment() { + let d = frame_grid_doc(); + let grid = d.spreads[0].items[0].text_frame().unwrap().options.baseline_grid; + assert_eq!(grid, Some(designcraft_doc::FrameBaselineGrid::new(6.0, 14.0))); + let b = baselines(&d); + assert_eq!(b.len(), 4, "{b:?}"); + for y in &b { + let n = (y - 6.0) / 14.0; + assert!((n - n.round()).abs() < 1e-6 && n >= 0.0, "baseline {y} is on the 6 + n·14 grid: {b:?}"); + } + // The first line's ascent is past the 6 pt line, so it sits on the next one. + assert!((b[0] - 20.0).abs() < 1e-6, "{b:?}"); +} + +#[test] +fn custom_frame_grid_round_trips() { + let d = frame_grid_doc(); + let bytes = export_idml(&d); + let spread = zip_text(&bytes, "Spreads/"); + assert!(spread.contains(r#"StartingOffsetForBaselineFrameGrid="6""#), "{spread}"); + assert!(spread.contains(r#"BaselineFrameGridIncrement="14""#), "{spread}"); + let back = import_idml(&bytes).unwrap(); + let grid = |d: &Document| d.spreads[0].items[0].text_frame().unwrap().options.baseline_grid; + assert_eq!(grid(&back), grid(&d)); + assert_eq!(baselines(&back), baselines(&d)); +} + +#[test] +fn custom_frame_grid_relative_to_round_trips() { + use designcraft_doc::FrameGridRelative as R; + let relative = |d: &Document| d.spreads[0].items[0].text_frame().unwrap().options.baseline_grid.map(|g| g.relative_to); + for (attr, want) in [ + ("TopOfPageOfBaselineFrameGridRelativeOption", R::TopOfPage), + ("TopOfMarginOfBaselineFrameGridRelativeOption", R::TopMargin), + ("TopOfFrameOfBaselineFrameGridRelativeOption", R::TopOfFrame), + ("TopOfInsetOfBaselineFrameGridRelativeOption", R::TopInset), + ("TopOfInset", R::TopInset), + ("SomethingNew", R::TopOfPage), + ] { + let d = frame_grid_doc_relative(Some(attr)); + assert_eq!(relative(&d), Some(want), "{attr}"); + let back = import_idml(&export_idml(&d)).unwrap(); + assert_eq!(relative(&back), Some(want), "{attr} after export"); + } + // A frame without the attribute measures from the top of the page. + assert_eq!(relative(&frame_grid_doc()), Some(R::TopOfPage)); +} diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 1723145ea..3a8facf08 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -738,8 +738,8 @@ mod tests { impl tiff::encoder::colortype::ColorType for Palette { type Inner = u8; const TIFF_VALUE: tiff::tags::PhotometricInterpretation = tiff::tags::PhotometricInterpretation::RGBPalette; - const BITS_PER_SAMPLE: &'static [u16] = &[BITS]; - const SAMPLE_FORMAT: &'static [tiff::tags::SampleFormat] = &[tiff::tags::SampleFormat::Uint]; + const BITS_PER_SAMPLE: &[u16] = &[BITS]; + const SAMPLE_FORMAT: &[tiff::tags::SampleFormat] = &[tiff::tags::SampleFormat::Uint]; fn horizontal_predict(row: &[u8], result: &mut Vec) { result.extend_from_slice(row); } diff --git a/crates/images/src/psd.rs b/crates/images/src/psd.rs index db11eef5a..4006e0e30 100644 --- a/crates/images/src/psd.rs +++ b/crates/images/src/psd.rs @@ -81,6 +81,16 @@ impl Mode { /// The merged composite as straight RGBA8, `None` when the file is damaged or unsupported (32-bit, /// Multichannel, ZIP-compressed composite). +/// Whether the header's depth, channel count and size are all within what the decoder supports. +fn header_in_range(mode: Mode, depth: u16, channels: usize, (w, h): (u32, u32), max_side: u32) -> bool { + let depth_ok = match mode { + Mode::Bitmap => depth == 1, + Mode::Indexed => depth == 8, + _ => depth == 8 || depth == 16, + }; + (1..=56).contains(&channels) && channels >= mode.colour_channels() && (1..=max_side).contains(&w) && (1..=max_side).contains(&h) && depth_ok +} + pub(crate) fn decode(bytes: &[u8]) -> Option { let mut r = Reader { b: bytes }; if r.take(4)? != b"8BPS" { @@ -97,13 +107,8 @@ pub(crate) fn decode(bytes: &[u8]) -> Option { let depth = r.u16()?; let mode = Mode::parse(r.u16()?)?; let max_side = if psb { 300_000 } else { 30_000 }; - let depth_ok = match mode { - Mode::Bitmap => depth == 1, - Mode::Indexed => depth == 8, - _ => depth == 8 || depth == 16, - }; let colours = mode.colour_channels(); - if !(1..=56).contains(&channels) || channels < colours || !(1..=max_side).contains(&w) || !(1..=max_side).contains(&h) || !depth_ok { + if !header_in_range(mode, depth, channels, (w, h), max_side) { return None; } let (wu, hu) = (usize::try_from(w).ok()?, usize::try_from(h).ok()?); @@ -298,7 +303,7 @@ impl<'a> ImageData<'a> { } let mut counts = self.counts.chunks_exact(self.count_size).map(|c| c.iter().fold(0usize, |n, &b| n << 8 | usize::from(b))); // This channel starts after every earlier channel's rows. - let mut at = counts.by_ref().take(ch.checked_mul(self.height)?).try_fold(0usize, |at, n| at.checked_add(n))?; + let mut at = counts.by_ref().take(ch.checked_mul(self.height)?).try_fold(0usize, usize::checked_add)?; for _ in 0..self.height { let n = counts.next()?; let end = at.checked_add(n)?; diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 34934b911..5d3ad0644 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -134,6 +134,25 @@ pub fn export_pdf_with_report(doc: &Document, cache: &Cache, opts: &PdfOptions) write::guard(|| export_pdf_with_report_inner(doc, cache, opts)) } +/// Form fields (Buttons and Forms) and, for interactive PDF, video and sound; not in PDF/X +/// or PDF/A: this update comes after krilla's validator ran, and its NeedAppearances fields and +/// Screen annotations aren't allowed in PDF/A. +fn add_form_fields(bytes: &mut Vec, warnings: &mut Vec, doc: &Document, sheets: &[Sheet], opts: &PdfOptions) { + let fields = crate::forms::collect(doc, sheets); + let media = if opts.media { crate::forms::collect_media(doc, sheets) } else { Vec::new() }; + if fields.is_empty() && media.is_empty() { + return; + } + match opts.standard { + Standard::PdfX4 => warnings.push("PDF/X-4: form fields and media were left out".into()), + Standard::PdfA2b => warnings.push("PDF/A-2b: form fields and media were left out".into()), + _ => match crate::forms::add_fields(&*bytes, &fields, &media) { + Some(b) => *bytes = b, + None => warnings.push("form fields and media couldn't be added to this PDF".into()), + }, + } +} + fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions) -> Result { let sheets = sheets(doc, opts)?; let warnings = Vec::new(); @@ -235,23 +254,7 @@ fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions // group that got past it, with its page. crate::pdfx::cmyk_group_spaces(&mut bytes); } - // Form fields (Buttons and Forms) and, for interactive PDF, video and sound; not in PDF/X - // or PDF/A: this update comes after krilla's validator ran, and its NeedAppearances fields and - // Screen annotations aren't allowed in PDF/A. - let fields = crate::forms::collect(doc, &sheets); - let media = if opts.media { crate::forms::collect_media(doc, &sheets) } else { Vec::new() }; - if !fields.is_empty() || !media.is_empty() { - if opts.standard == Standard::PdfX4 { - warnings.push("PDF/X-4: form fields and media were left out".into()); - } else if opts.standard == Standard::PdfA2b { - warnings.push("PDF/A-2b: form fields and media were left out".into()); - } else { - match crate::forms::add_fields(&bytes, &fields, &media) { - Some(b) => bytes = b, - None => warnings.push("form fields and media couldn't be added to this PDF".into()), - } - } - } + add_form_fields(&mut bytes, &mut warnings, doc, &sheets, opts); if opts.standard == Standard::PdfX4 { // Output intent and PDF/X identification, then check the result. match crate::pdfx::make_pdfx4(&bytes, &title, created) { @@ -654,6 +657,27 @@ impl Exporter<'_> { self.doc.resolve_color(name, tint).map(|c| device(&c, self.rgb_only)) } + /// The parent pages' items on `layer` shown on page `pi` of spread `si`: the parent's bases + /// first, then the parent. + fn parent_items(&mut self, s: &mut Surface, si: usize, pi: usize, page: &designcraft_doc::Page, layer: &designcraft_doc::Layer, first: usize) { + let doc = self.doc; + for (ppi, ppage) in doc.shown_parent_pages(SpreadRef::Doc(si), pi) { + let Some(parent) = doc.parents.get(ppi) else { continue }; + let Some(ppg) = parent.pages.get(ppage) else { continue }; + let dx = page.x - ppg.x; + for it in &parent.items { + if it.layer != layer.id || page.overridden.contains(&it.id) { + continue; + } + // Parent items belong to the parent page they sit on. + if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 { + continue; + } + self.top_item(s, it, Affine::translate((dx, 0.0)), Some(first + pi), true); + } + } + } + fn spread(&mut self, s: &mut Surface, si: usize) { let doc = self.doc; let Some(sp) = doc.spreads.get(si) else { return }; @@ -663,24 +687,8 @@ impl Exporter<'_> { continue; } for (pi, page) in sp.pages.iter().enumerate() { - if !page.show_parent_items { - continue; - } - // The parent's bases first, then the parent. - for (ppi, ppage) in doc.shown_parent_pages(SpreadRef::Doc(si), pi) { - let Some(parent) = doc.parents.get(ppi) else { continue }; - let Some(ppg) = parent.pages.get(ppage) else { continue }; - let dx = page.x - ppg.x; - for it in &parent.items { - if it.layer != layer.id || page.overridden.contains(&it.id) { - continue; - } - // Parent items belong to the parent page they sit on. - if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 { - continue; - } - self.top_item(s, it, Affine::translate((dx, 0.0)), Some(first + pi), true); - } + if page.show_parent_items { + self.parent_items(s, si, pi, page, layer, first); } } for it in &sp.items { diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index ad1123897..66512ac50 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -56,7 +56,7 @@ pub enum Standard { impl Standard { /// `none`, `x4` / `pdfx4` / `PDF/X-4`, `a2b` / `pdfa2b` / `PDF/A-2b`. pub fn parse(s: &str) -> Option { - let k: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect::().to_ascii_lowercase(); + let k: String = s.chars().filter(char::is_ascii_alphanumeric).collect::().to_ascii_lowercase(); match k.as_str() { "" | "none" => Some(Self::None), "x4" | "pdfx4" | "pdfx42008" | "pdfx42010" => Some(Self::PdfX4), diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rs index 2be38f97a..11d30602b 100644 --- a/crates/pdf/src/pdfx.rs +++ b/crates/pdf/src/pdfx.rs @@ -285,7 +285,7 @@ fn device_rgb(pdf: &[u8]) -> Vec { found .into_iter() .map(|(what, pages)| { - let list: Vec = pages.iter().take(10).map(|p| p.to_string()).collect(); + let list: Vec = pages.iter().take(10).map(ToString::to_string).collect(); let more = if pages.len() > 10 { ", …" } else { "" }; let s = if pages.len() == 1 { "" } else { "s" }; format!("{what} on page{s} {}{more}: under a CMYK output intent RGB needs an ICC profile", list.join(", ")) @@ -392,18 +392,7 @@ impl RgbScan { } b"BI" | b"EI" if !managed => { if let Some(Object::Stream(img)) = last { - let cs = img.dict().get::>(b"CS").or_else(|| img.dict().get::>(b"ColorSpace")); - let cs = match cs { - Some(Object::Name(n)) - if !matches!(n.as_ref(), b"DeviceRGB" | b"RGB" | b"G" | b"DeviceGray" | b"CMYK" | b"DeviceCMYK") => - { - res.get_color_space(&n) - } - cs => cs, - }; - if cs.is_some_and(|cs| is_device_rgb(&cs)) { - self.add("an RGB inline image".into()); - } + self.inline_image(&img, res); } } _ => {} @@ -411,6 +400,20 @@ impl RgbScan { } } + /// An inline image (`BI … EI`) in an RGB space, named directly or through the resources. + fn inline_image(&mut self, img: &Stream<'_>, res: &Resources<'_>) { + let cs = img.dict().get::>(b"CS").or_else(|| img.dict().get::>(b"ColorSpace")); + let cs = match cs { + Some(Object::Name(n)) if !matches!(n.as_ref(), b"DeviceRGB" | b"RGB" | b"G" | b"DeviceGray" | b"CMYK" | b"DeviceCMYK") => { + res.get_color_space(&n) + } + cs => cs, + }; + if cs.is_some_and(|cs| is_device_rgb(&cs)) { + self.add("an RGB inline image".into()); + } + } + fn image(&mut self, img: &Stream<'_>, managed: bool) { let id = img.obj_id(); if managed || !self.seen.insert(id) || img.dict().get::(b"ImageMask") == Some(true) { diff --git a/crates/pdf/src/pdfx/fonts.rs b/crates/pdf/src/pdfx/fonts.rs index 5dc149b7f..83178682a 100644 --- a/crates/pdf/src/pdfx/fonts.rs +++ b/crates/pdf/src/pdfx/fonts.rs @@ -33,7 +33,7 @@ pub(super) fn unembedded_fonts(pdf: &[u8]) -> Vec { let mut warnings: Vec = found .into_iter() .map(|(name, pages)| { - let list: Vec = pages.iter().take(10).map(|p| p.to_string()).collect(); + let list: Vec = pages.iter().take(10).map(ToString::to_string).collect(); let more = if pages.len() > 10 { ", …" } else { "" }; let s = if pages.len() == 1 { "" } else { "s" }; format!("the font {name} isn't embedded (page{s} {}{more}): PDF/X-4 needs every font used for visible text embedded", list.join(", ")) diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs index 1aaf435d9..7687bd2f8 100644 --- a/crates/pdf/src/text.rs +++ b/crates/pdf/src/text.rs @@ -303,6 +303,25 @@ impl Exporter<'_> { }); } + /// One table cell's graphic, or its text composed in the cell's own area. + fn table_cell(&mut self, s: &mut Surface, c: &designcraft_compose::PlacedCell) { + if let Some(g) = &c.graphic { + if let Some(clip) = to_path(&c.clip.to_path(0.1)) { + s.push_clip_path(&clip, &krilla::paint::FillRule::NonZero); + s.push_transform(&tf(Affine::translate((c.clip.x0, c.clip.y0)))); + self.graphic(s, g); + s.pop(); + s.pop(); + } + } else if let Some(cft) = c.text.frames.first() { + s.push_transform(&tf(Affine::translate(c.origin.to_vec2()))); + let area = std::mem::replace(&mut self.text_area, lines_area(cft)); + self.frame_text(s, &c.text, cft, &c.source); + self.text_area = area; + s.pop(); + } + } + /// Table fragments: cell fills, cell text (real text), edges and the border. fn tables(&mut self, s: &mut Surface, ft: &FrameText) { for t in &ft.tables { @@ -314,21 +333,7 @@ impl Exporter<'_> { } } for c in &t.cells { - if let Some(g) = &c.graphic { - if let Some(clip) = to_path(&c.clip.to_path(0.1)) { - s.push_clip_path(&clip, &krilla::paint::FillRule::NonZero); - s.push_transform(&tf(Affine::translate((c.clip.x0, c.clip.y0)))); - self.graphic(s, g); - s.pop(); - s.pop(); - } - } else if let Some(cft) = c.text.frames.first() { - s.push_transform(&tf(Affine::translate(c.origin.to_vec2()))); - let area = std::mem::replace(&mut self.text_area, lines_area(cft)); - self.frame_text(s, &c.text, cft, &c.source); - self.text_area = area; - s.pop(); - } + self.table_cell(s, c); } for seg in &t.strokes { let st = &seg.stroke; diff --git a/crates/render/src/blendspace.rs b/crates/render/src/blendspace.rs index 79c476343..f6c2fa328 100644 --- a/crates/render/src/blendspace.rs +++ b/crates/render/src/blendspace.rs @@ -240,7 +240,7 @@ fn srgb_table() -> std::sync::Arc> { type Lut = (designcraft_color::cms::ColorSettings, std::sync::Arc>); static LUT: std::sync::Mutex> = std::sync::Mutex::new(None); let settings = designcraft_color::cms::active_settings(); - let mut g = LUT.lock().unwrap_or_else(|e| e.into_inner()); + let mut g = LUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner); match g.as_ref() { Some((s, t)) if *s == settings => t.clone(), _ => { diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 4a6052781..37606097d 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -56,7 +56,7 @@ fn size_of(pm: &Pixmap) -> usize { } fn with(f: impl FnOnce(&mut Cache) -> R) -> R { - let mut g = CACHE.lock().unwrap_or_else(|e| e.into_inner()); + let mut g = CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let c = g.get_or_insert_with(Cache::default); // Decoding converts CMYK through the working space: new colour settings, new pixels. let colour = designcraft_color::cms::generation(); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index b239df164..522e245cb 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -277,6 +277,26 @@ pub fn default_threads() -> u16 { } } +/// An item's fill under its content; an overprinting fill multiplies into what is beneath. +fn draw_body_fill(ctx: &mut RenderContext, f: &Frame, it: &Item, bp: &BezPath, xf: Affine) { + if it.fill.is_none() { + return; + } + let doc = f.doc; + ctx.set_transform(f.view * xf); + let op = overprints(f, &it.fill.swatch, it.fill.tint, it.fill.overprint); + if op { + ctx.push_layer(None, Some(BlendMode::new(Mix::Multiply, Compose::SrcOver)), None, None, None); + } + if set_fill_paint(ctx, doc, &it.fill, bp.bounding_box()) { + ctx.fill_path(bp); + } + ctx.reset_paint_transform(); + if op { + ctx.pop_layer(); + } +} + impl Renderer { pub fn new() -> Self { Self { @@ -627,22 +647,7 @@ impl Renderer { /// Fill, content and stroke of a leaf item (no opacity, blend or effects). pub(crate) fn draw_body(&mut self, ctx: &mut RenderContext, f: &Frame, it: &Item, bp: &BezPath, xf: Affine, page: ShownOn) { - let doc = f.doc; - // Fill. - if !it.fill.is_none() { - ctx.set_transform(f.view * xf); - let op = overprints(f, &it.fill.swatch, it.fill.tint, it.fill.overprint); - if op { - ctx.push_layer(None, Some(BlendMode::new(Mix::Multiply, Compose::SrcOver)), None, None, None); - } - if set_fill_paint(ctx, doc, &it.fill, bp.bounding_box()) { - ctx.fill_path(bp); - } - ctx.reset_paint_transform(); - if op { - ctx.pop_layer(); - } - } + draw_body_fill(ctx, f, it, bp, xf); // Content. match &it.content { Content::Graphic(g) => { diff --git a/crates/render/src/pdf_layers.rs b/crates/render/src/pdf_layers.rs index 2573598d9..3b323a505 100644 --- a/crates/render/src/pdf_layers.rs +++ b/crates/render/src/pdf_layers.rs @@ -236,7 +236,7 @@ pub(crate) fn layered(data: &Arc>, hidden: &[String]) -> Option); static CACHE: Mutex>, Option>>)>>> = Mutex::new(None); let key = (Arc::as_ptr(data) as usize, hidden.to_vec()); - let mut c = CACHE.lock().unwrap_or_else(|e| e.into_inner()); + let mut c = CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let map = c.get_or_insert_with(HashMap::new); if let Some(v) = map.get(&key) { return v.1.clone(); diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index a4fa80ad0..a9cdc5ce3 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -156,6 +156,22 @@ fn union(r: Option, b: Rect) -> Option { Some(r.map_or(b, |r| r.union(b))) } +/// Add a rule bar, joined onto the previous one when it continues the same stretch. +fn push_bar(bars: &mut Vec<(String, f32, Rect)>, color: &str, tint: f32, r: Rect) { + match bars.last_mut() { + Some((c, t, last)) + if c.as_str() == color + && *t == tint + && (last.y0 - r.y0).abs() < 1e-6 + && (last.y1 - r.y1).abs() < 1e-6 + && (r.x0 - last.x1).abs() < 0.5 => + { + last.x1 = last.x1.max(r.x1); + } + _ => bars.push((color.to_owned(), tint, r)), + } +} + fn build_line(db: &FontDb, cs: &ComposedStory, l: &Line, vertical: bool) -> LineGlyphs { let mut runs: Vec<(u32, BezPath)> = Vec::new(); let mut underlines: Vec<(String, f32, Rect)> = Vec::new(); @@ -171,18 +187,7 @@ fn build_line(db: &FontDb, cs: &ComposedStory, l: &Line, vertical: bool) -> Line let r = rule.rect(g.x, g.x + g.adv, designcraft_compose::rule_baseline(style, l, g)); // One bar per stretch, as the PDF export draws them: a bar per glyph left // anti-aliased seams between the letters. - match bars.last_mut() { - Some((color, tint, last)) - if *color == rule.color - && *tint == rule.tint - && (last.y0 - r.y0).abs() < 1e-6 - && (last.y1 - r.y1).abs() < 1e-6 - && (r.x0 - last.x1).abs() < 0.5 => - { - last.x1 = last.x1.max(r.x1); - } - _ => bars.push((rule.color.clone(), rule.tint, r)), - } + push_bar(bars, &rule.color, rule.tint, r); } } // A tab carries the rule across its width but draws nothing itself. diff --git a/crates/textimport/src/xlsx.rs b/crates/textimport/src/xlsx.rs index 3f20f3dee..83bea3c87 100644 --- a/crates/textimport/src/xlsx.rs +++ b/crates/textimport/src/xlsx.rs @@ -11,7 +11,7 @@ use crate::{ImportError, Imported}; /// "B12" → (row 11, column 1). fn cell_ref(r: &str) -> Option<(usize, usize)> { - let letters: String = r.chars().take_while(|c| c.is_ascii_alphabetic()).collect(); + let letters: String = r.chars().take_while(char::is_ascii_alphabetic).collect(); let row: usize = r[letters.len()..].parse().ok()?; let col = letters.chars().try_fold(0usize, |acc, c| { let digit = (c.to_ascii_uppercase() as u8).checked_sub(b'A')? as usize + 1; diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index c437484c2..cba5fc317 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -570,8 +570,7 @@ fn finish_snapped_resize( proposed: Rect, mods: Mods, driver_x: bool, - x_edges: [bool; 3], - y_edges: [bool; 3], + (x_edges, y_edges): ([bool; 3], [bool; 3]), hit: &crate::Snap, ) -> Rect { if !mods.alt { @@ -1021,7 +1020,7 @@ impl Tool for SelectionTool { pointer, }, ); - to = finish_snapped_resize(from, handle, proposed, ev.mods, driver_x, x_edges, y_edges, &hit); + to = finish_snapped_resize(from, handle, proposed, ev.mods, driver_x, (x_edges, y_edges), &hit); crate::snap::lay_dimension_guides(&mut hit.guides, cx.layout.xf(spread), proposed, to, x_edges, y_edges, hit.length_delta); self.guides = hit.guides; } diff --git a/crates/tools/src/snap.rs b/crates/tools/src/snap.rs index 11da46178..974081dd5 100644 --- a/crates/tools/src/snap.rs +++ b/crates/tools/src/snap.rs @@ -204,7 +204,7 @@ fn match_rotation(cx: &ToolContext, req: &SnapRequest<'_>, zone_length: f64) -> let mut seen = HashSet::new(); if let Some(spread) = cx.doc.spread(req.spread) { for item in &spread.items { - push_rotation(&mut best, cx.selection, req, item, Affine::IDENTITY, false, 0, &mut seen, proposed, tol); + push_rotation(&mut best, cx.selection, req, item, Walk::ROOT, &mut seen, (proposed, tol)); } } if shows_parent_items(cx, req) { @@ -223,7 +223,24 @@ fn push_parent_rotations( tol: f64, ) { for (item, _) in shown_parent_items(cx.doc, req.spread) { - push_rotation(best, cx.selection, req, item, Affine::IDENTITY, false, 0, seen_items, proposed, tol); + push_rotation(best, cx.selection, req, item, Walk::ROOT, seen_items, (proposed, tol)); + } +} + +/// Where a recursive walk over an item tree stands: the parent's absolute transform, whether an +/// ancestor was skipped, and how deep it is. +#[derive(Clone, Copy)] +struct Walk { + ancestor: Affine, + skipped: bool, + depth: usize, +} + +impl Walk { + const ROOT: Walk = Walk { ancestor: Affine::IDENTITY, skipped: false, depth: 0 }; + + fn child(self, ancestor: Affine, skipped: bool) -> Walk { + Walk { ancestor, skipped, depth: self.depth + 1 } } } @@ -232,13 +249,11 @@ fn push_rotation( selection: &Selection, req: &SnapRequest<'_>, item: &Item, - ancestor: Affine, - skipped: bool, - depth: usize, + walk: Walk, seen: &mut HashSet, - proposed: f64, - tol: f64, + (proposed, tol): (f64, f64), ) { + let Walk { ancestor, skipped, depth } = walk; if depth >= ALIGN_GROUP_DEPTH || !seen.insert(item.id) || item.hidden { return; } @@ -254,7 +269,7 @@ fn push_rotation( return; } for child in item.children() { - push_rotation(best, selection, req, child, abs, skip, depth + 1, seen, proposed, tol); + push_rotation(best, selection, req, child, walk.child(abs, skip), seen, (proposed, tol)); } } @@ -393,10 +408,11 @@ fn grid_origin(cx: &ToolContext, req: &SnapRequest<'_>, axis: Axis) -> Option= 0 while the line is inside the page -/// (the bottom edge is not a line, matching the canvas). An increment of 0 or less skips the -/// pass. `relative_to` and `view_threshold` are not read, and hiding the baseline grid does not -/// turn this off. Only a page the rect crosses on x contributes. A dragged ruler guide +/// Lines are `page.y0 + origin + n * increment` for n >= 0 while the line is inside the page +/// (the bottom edge is not a line, matching the canvas), `origin` from +/// [`BaselineGrid::origin`](designcraft_doc::BaselineGrid::origin). An increment of 0 or less +/// skips the pass. `view_threshold` is not read, and hiding the baseline grid does not turn this +/// off. Only a page the rect crosses on x contributes. A dragged ruler guide /// ([`Gesture::Guide`]) doesn't snap to it. fn pass_baseline(cx: &ToolContext, req: &SnapRequest<'_>, axis: Axis, tol: f64) -> Option { if !matches!(axis, Axis::Y) || !cx.snap.snap_to_guides || matches!(req.gesture, Gesture::Guide) { @@ -417,7 +433,10 @@ fn pass_baseline(cx: &ToolContext, req: &SnapRequest<'_>, axis: Axis, tol: f64) if !ranges_overlap(moving_lo, moving_hi, lo, hi) { continue; } - let origin = bounds.y0 + baseline.start; + let origin = bounds.y0 + baseline.origin(page); + if !origin.is_finite() { + continue; + } offer_enabled(&mut best, req.rect, flags, axis, tol, |v| nearest_baseline(v, origin, increment, bounds.y0, bounds.y1)); } best.map(|b| b.hit) @@ -907,7 +926,7 @@ fn dimension_lengths(cx: &ToolContext, req: &SnapRequest<'_>) -> Vec { let mut seen = HashSet::new(); if let Some(sp) = cx.doc.spread(req.spread) { for item in &sp.items { - push_own_lengths(&mut out, cx.selection, req, item, Affine::IDENTITY, false, 0, &mut seen); + push_own_lengths(&mut out, cx.selection, req, item, Walk::ROOT, &mut seen); } } if shows_parent_items(cx, req) { @@ -916,16 +935,8 @@ fn dimension_lengths(cx: &ToolContext, req: &SnapRequest<'_>) -> Vec { out } -fn push_own_lengths( - out: &mut Vec, - selection: &Selection, - req: &SnapRequest<'_>, - item: &Item, - ancestor: Affine, - skipped: bool, - depth: usize, - seen: &mut HashSet, -) { +fn push_own_lengths(out: &mut Vec, selection: &Selection, req: &SnapRequest<'_>, item: &Item, walk: Walk, seen: &mut HashSet) { + let Walk { ancestor, skipped, depth } = walk; if depth >= ALIGN_GROUP_DEPTH || !seen.insert(item.id) || item.hidden { return; } @@ -936,7 +947,7 @@ fn push_own_lengths( let skip = skipped || align_skips_item(selection, req, item.id); if item.is_group() && !item.children().is_empty() { for child in item.children() { - push_own_lengths(out, selection, req, child, abs, skip, depth + 1, seen); + push_own_lengths(out, selection, req, child, walk.child(abs, skip), seen); } return; } @@ -994,7 +1005,7 @@ fn stroke_outset(item: &Item) -> f64 { fn push_parent_lengths(out: &mut Vec, cx: &ToolContext, req: &SnapRequest<'_>, seen_items: &mut HashSet) { for (item, _) in shown_parent_items(cx.doc, req.spread) { - push_own_lengths(out, cx.selection, req, item, Affine::IDENTITY, false, 0, seen_items); + push_own_lengths(out, cx.selection, req, item, Walk::ROOT, seen_items); } } @@ -1084,11 +1095,11 @@ fn pass_align(cx: &ToolContext, req: &SnapRequest<'_>, axis: Axis, tol: f64) -> let mut best: Option = None; if let Some(sp) = cx.doc.spread(req.spread) { for page in &sp.pages { - offer_box(&mut best, req.rect, flags, axis, page.bounds(), tol, cx.snap.align_edges, cx.snap.align_centers); + offer_box(&mut best, req.rect, flags, axis, page.bounds(), tol, (cx.snap.align_edges, cx.snap.align_centers)); } for item in &sp.items { let Some(rect) = item_target_rect(cx.selection, req, item) else { continue }; - offer_box(&mut best, req.rect, flags, axis, rect, tol, cx.snap.align_edges, cx.snap.align_centers); + offer_box(&mut best, req.rect, flags, axis, rect, tol, (cx.snap.align_edges, cx.snap.align_centers)); } } if shows_parent_items(cx, req) { @@ -1186,7 +1197,7 @@ fn group_box(item: &Item, seen: &mut HashSet, depth: usize, filter: Opti fn offer_parent_items(best: &mut Option, cx: &ToolContext, req: &SnapRequest<'_>, flags: [bool; 3], axis: Axis, tol: f64) { for (item, dx) in shown_parent_items(cx.doc, req.spread) { let Some(rect) = item_target_rect(cx.selection, req, item) else { continue }; - offer_box(best, req.rect, flags, axis, shift_x(rect, dx), tol, cx.snap.align_edges, cx.snap.align_centers); + offer_box(best, req.rect, flags, axis, shift_x(rect, dx), tol, (cx.snap.align_edges, cx.snap.align_centers)); } } @@ -1280,7 +1291,7 @@ fn offer_line(best: &mut Option, moving: Rect, flags: [bool; 3], axis: Axi } } -fn offer_box(best: &mut Option, moving: Rect, flags: [bool; 3], axis: Axis, target: Rect, tol: f64, edges: bool, centers: bool) { +fn offer_box(best: &mut Option, moving: Rect, flags: [bool; 3], axis: Axis, target: Rect, tol: f64, (edges, centers): (bool, bool)) { let (m0, m_mid, m1) = axis_triple(moving, axis); let (t0, t_mid, t1) = axis_triple(target, axis); let [use_left, use_mid, use_right] = flags; @@ -1790,6 +1801,22 @@ mod tests { assert_eq!(hit.delta.y, 0.0); } + #[test] + fn baseline_relative_to_the_top_margin_snaps_from_the_margin() { + let mut doc = Document::new(&NewDocument::default()); + std::sync::Arc::make_mut(&mut doc.spreads[0]).pages[0].margins.top = 37.0; + doc.settings.baseline_grid.start = 0.0; + doc.settings.baseline_grid.increment = 10.0; + doc.settings.baseline_grid.relative_to = designcraft_doc::GridRelative::TopMargin; + let cache = Cache::new(); + let layout = CanvasLayout::new(&doc, false); + let sel = Selection::default(); + let cx = ctx_on(&doc, &sel, &cache, &layout); + // Lines at 37 + 10n: a top at 58 goes up to 57, not down to the page-relative 60. + let hit = snap(&cx, y_req(Rect::new(100.0, 58.0, 140.0, 80.0))); + assert!((hit.delta.y - -1.0).abs() < 1e-6, "{}", hit.delta.y); + } + #[test] fn nearer_of_margin_and_baseline_wins() { // Bottom margin at 792 - 54 = 738, between baseline lines 732 and 744. diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index 56658f41e..f0503e912 100644 --- a/crates/tools/src/text.rs +++ b/crates/tools/src/text.rs @@ -212,6 +212,123 @@ fn underlines(cx: &ToolContext, ts: TextSel, r: Range) -> Vec<(Point, Poi out } +impl TypeTool { + fn pointer_down(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + self.start = Some(ev.pos); + self.drawing = false; + self.selecting = None; + self.cell_drag = None; + self.unit = None; + self.border = None; + if ev.kind == PointerKind::Down + && let Some(b) = border_at(cx, ev.pos) + { + self.border = Some(b); + return vec![]; + } + // Text frames take the caret (locked ones too, as in InDesign); an empty frame + // becomes one, unless it's locked: then the press draws a new text frame over it. + if let Some((_, id)) = cx.hit(ev.pos) + && let Some(it) = cx.doc.item(id) + && !matches!(it.content, designcraft_doc::Content::Graphic(_) | designcraft_doc::Content::Group { .. }) + && (it.is_text_frame() || !it.locked) + { + let sp = cx.layout.spread_at(ev.pos).map(|(_, p)| p).unwrap_or(ev.pos); + let clicks = ev.click_count(); + // Whole rows/columns selected: wait to see whether this is a drag. + if clicks == 1 && !ev.mods.shift && whole_rows_or_cols(cx) { + self.cell_drag = Some((id.0, sp)); + return vec![]; + } + self.selecting = Some(id.0); + // Two presses select a word (or a run of spaces), three a line, four a + // paragraph, five the story. + if clicks >= 2 { + let unit = match clicks { + 2 => "word", + 3 => "line", + 4 => "paragraph", + _ => "story", + }; + self.unit = Some(unit); + return vec![Action::Exec("text.selectAt".into(), json!({"frame": id.0, "point": [sp.x, sp.y], "unit": unit}))]; + } + let cmd = if ev.mods.shift { "text.extendTo" } else { "text.placeCaret" }; + return vec![Action::Exec(cmd.into(), json!({"frame": id.0, "point": [sp.x, sp.y]}))]; + } + vec![] + } + + fn pointer_drag(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + let Some(a) = self.start else { return vec![] }; + if let Some(b) = self.border.as_mut() { + // A click with a little wobble must not resize. + if !b.begun && (ev.pos - a).hypot() < cx.tol(3.0) { + return vec![]; + } + return b.drag(ev.pos, ev.mods.shift); + } + if self.cell_drag.is_some() { + return vec![]; + } + if let Some(fid) = self.selecting { + let sp = cx.layout.spread_at(ev.pos).map(|(_, p)| p).unwrap_or(ev.pos); + let mut p = json!({"frame": fid, "point": [sp.x, sp.y]}); + // After several clicks the drag grows the selection by whole units. + if let Some(unit) = self.unit { + p["unit"] = json!(unit); + } + return vec![Action::Exec("text.extendTo".into(), p)]; + } + if (ev.pos - a).hypot() < cx.tol(3.0) && !self.drawing { + return vec![]; + } + let Some((sr, sa)) = cx.layout.spread_at(a) else { return vec![] }; + // Drawn like the frame tools: the press point and the moving edges snap. + let sa = if cx.snap.any() { crate::snap::snap_point(cx, sr, sa).0 } else { sa }; + let (r, guides) = snapped_drag_rect(cx, sr, sa, cx.layout.to_spread(sr, ev.pos), ev.mods); + self.guides = guides; + let mut out = vec![]; + if !self.drawing { + self.drawing = true; + out.push(Action::Begin("Create Text Frame".into())); + } + out.push(Action::Preview( + "frame.create".into(), + json!({"spread": spread_json(sr), "shape": "rectangle", "content": "text", "rect": rect_json(r), "caret": true, "vertical": self.vertical}), + )); + out + } + + fn pointer_up(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + self.guides.clear(); + let start = self.start.take(); + if let Some(b) = self.border.take() { + return if b.begun { vec![Action::Commit] } else { vec![] }; + } + if let Some((fid, from)) = self.cell_drag.take() { + let sp = cx.layout.spread_at(ev.pos).map(|(_, p)| p).unwrap_or(ev.pos); + let moved = start.is_some_and(|a| (ev.pos - a).hypot() >= cx.tol(3.0)); + return if moved { + vec![Action::Exec("table.dropCells".into(), json!({"frame": fid, "from": [from.x, from.y], "to": [sp.x, sp.y]}))] + } else { + vec![Action::Exec("text.placeCaret".into(), json!({"frame": fid, "point": [from.x, from.y]}))] + }; + } + if std::mem::take(&mut self.drawing) { + self.selecting = None; + return vec![Action::Commit]; + } + // Ends a press in text: drops dragged text, or is ignored by the engine. + if let Some(fid) = self.selecting.take() { + let sp = cx.layout.spread_at(ev.pos).map(|(_, p)| p).unwrap_or(ev.pos); + let moved = start.is_some_and(|a| (ev.pos - a).hypot() >= cx.tol(3.0)); + return vec![Action::Exec("text.release".into(), json!({"frame": fid, "point": [sp.x, sp.y], "moved": moved, "copy": ev.mods.alt}))]; + } + vec![] + } +} + impl Tool for TypeTool { fn id(&self) -> &'static str { if self.vertical { "verticalType" } else { "type" } @@ -219,121 +336,9 @@ impl Tool for TypeTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { match ev.kind { - PointerKind::Down | PointerKind::DoubleClick => { - self.start = Some(ev.pos); - self.drawing = false; - self.selecting = None; - self.cell_drag = None; - self.unit = None; - self.border = None; - if ev.kind == PointerKind::Down - && let Some(b) = border_at(cx, ev.pos) - { - self.border = Some(b); - return vec![]; - } - // Text frames take the caret (locked ones too, as in InDesign); an empty frame - // becomes one, unless it's locked: then the press draws a new text frame over it. - if let Some((_, id)) = cx.hit(ev.pos) - && let Some(it) = cx.doc.item(id) - && !matches!(it.content, designcraft_doc::Content::Graphic(_) | designcraft_doc::Content::Group { .. }) - && (it.is_text_frame() || !it.locked) - { - let sp = cx.layout.spread_at(ev.pos).map(|(_, p)| p).unwrap_or(ev.pos); - let clicks = ev.click_count(); - // Whole rows/columns selected: wait to see whether this is a drag. - if clicks == 1 && !ev.mods.shift && whole_rows_or_cols(cx) { - self.cell_drag = Some((id.0, sp)); - return vec![]; - } - self.selecting = Some(id.0); - // Two presses select a word (or a run of spaces), three a line, four a - // paragraph, five the story. - if clicks >= 2 { - let unit = match clicks { - 2 => "word", - 3 => "line", - 4 => "paragraph", - _ => "story", - }; - self.unit = Some(unit); - return vec![Action::Exec("text.selectAt".into(), json!({"frame": id.0, "point": [sp.x, sp.y], "unit": unit}))]; - } - let cmd = if ev.mods.shift { "text.extendTo" } else { "text.placeCaret" }; - return vec![Action::Exec(cmd.into(), json!({"frame": id.0, "point": [sp.x, sp.y]}))]; - } - vec![] - } - PointerKind::Drag => { - let Some(a) = self.start else { return vec![] }; - if let Some(b) = self.border.as_mut() { - // A click with a little wobble must not resize. - if !b.begun && (ev.pos - a).hypot() < cx.tol(3.0) { - return vec![]; - } - return b.drag(ev.pos, ev.mods.shift); - } - if self.cell_drag.is_some() { - return vec![]; - } - if let Some(fid) = self.selecting { - let sp = cx.layout.spread_at(ev.pos).map(|(_, p)| p).unwrap_or(ev.pos); - let mut p = json!({"frame": fid, "point": [sp.x, sp.y]}); - // After several clicks the drag grows the selection by whole units. - if let Some(unit) = self.unit { - p["unit"] = json!(unit); - } - return vec![Action::Exec("text.extendTo".into(), p)]; - } - if (ev.pos - a).hypot() < cx.tol(3.0) && !self.drawing { - return vec![]; - } - let Some((sr, sa)) = cx.layout.spread_at(a) else { return vec![] }; - // Drawn like the frame tools: the press point and the moving edges snap. - let sa = if cx.snap.any() { crate::snap::snap_point(cx, sr, sa).0 } else { sa }; - let (r, guides) = snapped_drag_rect(cx, sr, sa, cx.layout.to_spread(sr, ev.pos), ev.mods); - self.guides = guides; - let mut out = vec![]; - if !self.drawing { - self.drawing = true; - out.push(Action::Begin("Create Text Frame".into())); - } - out.push(Action::Preview( - "frame.create".into(), - json!({"spread": spread_json(sr), "shape": "rectangle", "content": "text", "rect": rect_json(r), "caret": true, "vertical": self.vertical}), - )); - out - } - PointerKind::Up => { - self.guides.clear(); - let start = self.start.take(); - if let Some(b) = self.border.take() { - return if b.begun { vec![Action::Commit] } else { vec![] }; - } - if let Some((fid, from)) = self.cell_drag.take() { - let sp = cx.layout.spread_at(ev.pos).map(|(_, p)| p).unwrap_or(ev.pos); - let moved = start.is_some_and(|a| (ev.pos - a).hypot() >= cx.tol(3.0)); - return if moved { - vec![Action::Exec("table.dropCells".into(), json!({"frame": fid, "from": [from.x, from.y], "to": [sp.x, sp.y]}))] - } else { - vec![Action::Exec("text.placeCaret".into(), json!({"frame": fid, "point": [from.x, from.y]}))] - }; - } - if std::mem::take(&mut self.drawing) { - self.selecting = None; - return vec![Action::Commit]; - } - // Ends a press in text: drops dragged text, or is ignored by the engine. - if let Some(fid) = self.selecting.take() { - let sp = cx.layout.spread_at(ev.pos).map(|(_, p)| p).unwrap_or(ev.pos); - let moved = start.is_some_and(|a| (ev.pos - a).hypot() >= cx.tol(3.0)); - return vec![Action::Exec( - "text.release".into(), - json!({"frame": fid, "point": [sp.x, sp.y], "moved": moved, "copy": ev.mods.alt}), - )]; - } - vec![] - } + PointerKind::Down | PointerKind::DoubleClick => self.pointer_down(cx, ev), + PointerKind::Drag => self.pointer_drag(cx, ev), + PointerKind::Up => self.pointer_up(cx, ev), PointerKind::Move => vec![], } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 2118c4929..b1c71c056 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -962,7 +962,8 @@ fn dashed(painter: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke, dash: f32, const MAX_BASELINES: usize = 216 * 72; /// Baseline grid lines inside a page, measured from its top: `start + n * increment` for n >= 0 (the bottom -/// edge is not a line). Lines above the page are skipped without walking them, however far up the start is. +/// edge is not a line), `start` from [`BaselineGrid::origin`](designcraft_doc::BaselineGrid::origin). Lines +/// above the page are skipped without walking them, however far up the start is. fn baseline_grid_lines(start: f64, increment: f64, height: f64) -> impl Iterator { let step = increment.max(1.0); let first = if start < 0.0 { start.rem_euclid(step) } else { start }; @@ -1022,7 +1023,7 @@ fn draw_guides(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document // Baseline grid. if app.ui.baseline_grid && xf.zoom >= s.baseline_grid.view_threshold { let g = &s.baseline_grid; - for y in baseline_grid_lines(g.start, g.increment, p.height) { + for y in baseline_grid_lines(g.origin(p), g.increment, p.height) { painter.line_segment( [pt(Point::new(pr.x0, pr.y0 + y)), pt(Point::new(pr.x1, pr.y0 + y))], Stroke::new(hair(painter), c32(g.color).gamma_multiply(0.8)), diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index b0fed5799..5183222eb 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -7,7 +7,7 @@ use serde_json::json; use crate::panels; use crate::theme::{Tokens, semibold}; -use crate::widgets::{caption, measure, number}; +use crate::widgets::{NumField, caption, measure}; use crate::{DesignApp, icons}; /// Height of the application bar (InDesign 2026), then a 7 pt lower band and a 1 pt border. The @@ -477,6 +477,32 @@ pub fn control_bar(app: &mut DesignApp, ui: &mut egui::Ui) { }); } +/// Page-size preset menu and the portrait / landscape toggles of the Control panel. +fn page_preset_and_orientation(app: &mut DesignApp, ui: &mut egui::Ui, lang: &str, size: (f64, f64), n: usize, anchor: u8) { + let landscape = size.0 > size.1; + ui.vertical(|ui| { + let cur = panels::properties::preset_name(size.0, size.1); + egui::ComboBox::from_id_salt("ctl_page_preset").selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, cur))).width(130.0).show_ui( + ui, + |ui| { + for (name, w, h) in panels::properties::PAGE_PRESETS { + if ui.selectable_label(cur == *name, crate::rtl::widget(ui, crate::i18n::tr(lang, name))).clicked() { + let (w, h) = if landscape { (h, w) } else { (w, h) }; + let _ = app.run("layout.pageSize", json!({"pages": [n], "width": w, "height": h, "anchor": anchor})); + } + } + }, + ); + ui.horizontal(|ui| { + for (icon, tip, want) in [("orient-portrait", "Portrait", false), ("orient-landscape", "Landscape", true)] { + if crate::widgets::icon_toggle(ui, icon, landscape == want, crate::i18n::tr(lang, tip)).clicked() && landscape != want { + let _ = app.run("layout.pageSize", json!({"pages": [n], "width": size.1, "height": size.0, "anchor": anchor})); + } + } + }); + }); +} + /// The Control panel with the Page tool, as InDesign's: reference point, X/Y, W/H, page-size /// preset, orientation, Liquid Page Rule and Show Parent Page Overlay, for /// the page the Page tool selected (else the page in view). W/H keep the reference point in place. @@ -518,28 +544,7 @@ fn control_page(app: &mut DesignApp, ui: &mut egui::Ui) { }); vsep(ui); // Page-size preset and orientation. - let landscape = pg.width > pg.height; - ui.vertical(|ui| { - let cur = panels::properties::preset_name(pg.width, pg.height); - egui::ComboBox::from_id_salt("ctl_page_preset").selected_text(crate::rtl::widget(ui, crate::i18n::tr(&lang, cur))).width(130.0).show_ui( - ui, - |ui| { - for (name, w, h) in panels::properties::PAGE_PRESETS { - if ui.selectable_label(cur == *name, crate::rtl::widget(ui, crate::i18n::tr(&lang, name))).clicked() { - let (w, h) = if landscape { (h, w) } else { (w, h) }; - let _ = app.run("layout.pageSize", json!({"pages": [n], "width": w, "height": h, "anchor": anchor})); - } - } - }, - ); - ui.horizontal(|ui| { - for (icon, tip, want) in [("orient-portrait", "Portrait", false), ("orient-landscape", "Landscape", true)] { - if crate::widgets::icon_toggle(ui, icon, landscape == want, crate::i18n::tr(&lang, tip)).clicked() && landscape != want { - let _ = app.run("layout.pageSize", json!({"pages": [n], "width": pg.height, "height": pg.width, "anchor": anchor})); - } - } - }); - }); + page_preset_and_orientation(app, ui, &lang, (pg.width, pg.height), n, anchor); vsep(ui); ui.vertical(|ui| { caption(ui, crate::i18n::tr(&lang, "Liquid Page Rule:")); @@ -564,20 +569,101 @@ fn control_page(app: &mut DesignApp, ui: &mut egui::Ui) { }); } +/// The Control panel's font sizes (and leadings), as InDesign lists them. +const SIZES: &[f64] = &[6.0, 8.0, 9.0, 10.0, 11.0, 12.0, 14.0, 18.0, 24.0, 30.0, 36.0, 48.0, 60.0, 72.0]; +/// The Control panel's tracking values (1/1000 em). +const TRACKING: &[f64] = &[-100.0, -75.0, -50.0, -25.0, -10.0, -5.0, 0.0, 5.0, 10.0, 25.0, 50.0, 75.0, 100.0, 200.0]; + +/// Whether the text Control panel shows Paragraph Formatting Controls (¶) rather than Character +/// Formatting Controls (A). +const PARA_MODE: &str = "ctl_text_para_mode"; + +/// An icon and a field after it, as the Control panel lays its fields out. +pub(crate) fn icon_field(ui: &mut egui::Ui, icon: &str, tip: &str, field: NumField) -> Option { + 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); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, tip)); + let label = resp.id; + resp.on_hover_text(tip); + field.spinner().labelled_by(label).show(ui) +} + +/// A column of two rows (the Control panel's two-row groups). +fn rows(ui: &mut egui::Ui, mut row: impl FnMut(&mut egui::Ui, usize)) { + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 3.0; + ui.horizontal(|ui| row(ui, 0)); + ui.horizontal(|ui| row(ui, 1)); + }); +} + +/// A small toggle button showing `text` (the case and position buttons). +fn text_toggle(ui: &mut egui::Ui, text: &str, strike: bool, on: bool, tip: &str) -> bool { + let t = Tokens::get(ui.ctx()); + let (r, resp) = ui.allocate_exact_size(vec2(24.0, 20.0), Sense::click()); + if on { + ui.painter().rect_filled(r, 2.0, t.tool_active); + } else if resp.hovered() { + ui.painter().rect_filled(r, 2.0, t.hover); + } + let col = if on { t.text_strong } else { t.icon }; + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, text, egui::FontId::proportional(13.0), col); + if strike { + ui.painter().line_segment([r.center() + vec2(-6.0, 0.5), r.center() + vec2(6.0, 0.5)], Stroke::new(1.2, col)); + } + resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, on, tip)); + resp.on_hover_text(tip).clicked() +} + +/// The text Control panel, as InDesign's: A shows the Character Formatting Controls (font, size +/// and leading, the case and position buttons, kerning and tracking, the scales, baseline shift +/// and skew, the character style and language); ¶ the Paragraph Formatting Controls (alignment, +/// the indents, space before and after, the drop cap, the paragraph style, Hyphenate and Align to +/// Baseline Grid). fn control_text(app: &mut DesignApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); + let lang = app.ui.language.clone(); + let tr = |s: &str| crate::i18n::tr(&lang, s).to_string(); let attrs = panels::text_attrs(app); let chars = attrs.as_ref().map(|a| a["chars"].clone()).unwrap_or_default(); let para = attrs.as_ref().map(|a| a["para"].clone()).unwrap_or_default(); + let mode_id = egui::Id::new(PARA_MODE); + let para_mode = ui.data(|d| d.get_temp::(mode_id)).unwrap_or(false); ui.vertical(|ui| { - ui.horizontal(|ui| { - ui.label(egui::RichText::new("A").font(semibold(15.0)).color(t.text_strong)); - }); - ui.horizontal(|ui| { - ui.label(egui::RichText::new("¶").font(semibold(15.0)).color(t.text_dim)); - }); + ui.spacing_mut().item_spacing.y = 3.0; + for (para, text, tip) in [(false, "A", "Character Formatting Controls"), (true, "¶", "Paragraph Formatting Controls")] { + let on = para_mode == para; + let (r, resp) = ui.allocate_exact_size(vec2(24.0, 22.0), Sense::click()); + if on { + ui.painter().rect_filled(r, 2.0, t.tool_active); + } else if resp.hovered() { + ui.painter().rect_filled(r, 2.0, t.hover); + } + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, text, semibold(15.0), if on { t.text_strong } else { t.text_dim }); + let tip = tr(tip); + resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, on, &tip)); + if resp.on_hover_text(&tip).clicked() { + ui.data_mut(|d| d.insert_temp(mode_id, para)); + } + } }); vsep(ui); + if para_mode { + control_paragraph(app, ui, &attrs, ¶, &tr); + } else { + control_character(app, ui, &attrs, &chars, ¶, &tr); + } +} + +fn control_character( + app: &mut DesignApp, + ui: &mut egui::Ui, + attrs: &Option, + chars: &serde_json::Value, + para: &serde_json::Value, + tr: &dyn Fn(&str) -> String, +) { ui.vertical(|ui| { let fam = chars["fontFamily"].as_str().unwrap_or("").to_string(); let sty = chars["fontStyle"].as_str().unwrap_or("").to_string(); @@ -585,84 +671,358 @@ fn control_text(app: &mut DesignApp, ui: &mut egui::Ui) { panels::font_style_picker(app, ui, &fam, &sty, 170.0); }); vsep(ui); - egui::Grid::new("ctl_char").num_columns(4).spacing(vec2(4.0, 3.0)).show(ui, |ui| { - caption(ui, "𝐓"); - if let Some(v) = number(ui, "csize", chars["size"].as_f64(), " pt", 54.0, 2) { - let _ = app.run("type.char", json!({"attrs": {"size": v}})); + // Size and leading: a spinner on the left and a list of common values on the right; + // automatic leading in parentheses. + rows(ui, |ui, row| { + if row == 0 { + if let Some(v) = icon_field( + ui, + "font-size", + &tr("Font Size"), + NumField::number("csize", chars["size"].as_f64(), " pt", 2).width(84.0).presets(SIZES).range(0.1, 1296.0), + ) { + let _ = app.run("type.char", json!({"attrs": {"size": v}})); + } + } else { + let auto = chars["leading"]["kind"].as_str() != Some("points"); + let lead = if auto { + chars["size"].as_f64().map(|s| s * para["autoLeading"].as_f64().unwrap_or(1.2)) + } else { + chars["leading"]["value"].as_f64() + }; + let lead = lead.map(|v| (v * 100.0).round() / 100.0); + let key = if auto { "cleadauto" } else { "clead" }; + if let Some(v) = icon_field( + ui, + "leading", + &tr("Leading"), + NumField::number(key, lead, " pt", 2).width(84.0).presets(SIZES).range(0.0, 5000.0).parens(auto), + ) { + let _ = app.run("type.char", json!({"attrs": {"leading": {"kind": "points", "value": v}}})); + } } - caption(ui, crate::i18n::tr(&app.ui.language, "VA")); - if let Some(v) = number(ui, "ctrack", chars["tracking"].as_f64(), "", 48.0, 0) { - let _ = app.run("type.char", json!({"attrs": {"tracking": v}})); + }); + vsep(ui); + // All Caps, Superscript, Underline / Small Caps, Subscript, Strikethrough. + let caps = chars["capitalization"].as_str().unwrap_or("normal").to_string(); + let pos = chars["position"].as_str().unwrap_or("normal").to_string(); + let (ul, st) = (chars["underline"].as_bool().unwrap_or(false), chars["strikethrough"].as_bool().unwrap_or(false)); + let mut set = None; + rows(ui, |ui, row| { + if row == 0 { + if text_toggle(ui, "TT", false, caps == "allCaps", &tr("All Caps")) { + set = Some(json!({"capitalization": if caps == "allCaps" { "normal" } else { "allCaps" }})); + } + if text_toggle(ui, "T¹", false, pos == "superscript", &tr("Superscript")) { + set = Some(json!({"position": if pos == "superscript" { "normal" } else { "superscript" }})); + } + if text_toggle(ui, "T̲", false, ul, &tr("Underline")) { + set = Some(json!({"underline": !ul})); + } + } else { + if text_toggle(ui, "Tᴛ", false, caps == "smallCaps", &tr("Small Caps")) { + set = Some(json!({"capitalization": if caps == "smallCaps" { "normal" } else { "smallCaps" }})); + } + if text_toggle(ui, "T₁", false, pos == "subscript", &tr("Subscript")) { + set = Some(json!({"position": if pos == "subscript" { "normal" } else { "subscript" }})); + } + if text_toggle(ui, "T", true, st, &tr("Strikethrough")) { + set = Some(json!({"strikethrough": !st})); + } } - ui.end_row(); - caption(ui, "Ā"); - let lead = match chars["leading"]["kind"].as_str() { - Some("points") => chars["leading"]["value"].as_f64(), - _ => chars["size"].as_f64().map(|s| s * para["autoLeading"].as_f64().unwrap_or(1.2)), - }; - if let Some(v) = number(ui, "clead", lead, " pt", 54.0, 2) { - let _ = app.run("type.char", json!({"attrs": {"leading": {"kind": "points", "value": v}}})); + }); + if let Some(a) = set { + let _ = app.run("type.char", json!({"attrs": a})); + } + vsep(ui); + rows(ui, |ui, row| { + if row == 0 { + 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, "kerning", t.icon); + resp.on_hover_text(tr("Kerning")); + crate::panels::properties::kerning_control(app, ui, "ckern", &chars["kerning"], 92.0); + } else { + if let Some(v) = icon_field( + ui, + "tracking", + &tr("Tracking"), + NumField::number("ctrack", chars["tracking"].as_f64(), "", 0).width(92.0).presets(TRACKING).step(5.0).range(-1000.0, 10000.0), + ) { + let _ = app.run("type.char", json!({"attrs": {"tracking": v}})); + } } - caption(ui, crate::i18n::tr(&app.ui.language, "IT")); - if let Some(v) = number(ui, "chs", chars["hScale"].as_f64().map(|v| v * 100.0), "%", 48.0, 0) { - let _ = app.run("type.char", json!({"attrs": {"hScale": v / 100.0}})); + }); + vsep(ui); + const SCALES: &[f64] = &[25.0, 50.0, 75.0, 80.0, 90.0, 100.0, 110.0, 120.0, 125.0, 150.0, 200.0]; + let pct = |v: &serde_json::Value| v.as_f64().map(|s| (s * 1000.0).round() / 10.0); + rows(ui, |ui, row| { + if row == 0 { + if let Some(v) = icon_field( + ui, + "vscale", + &tr("Vertical Scale"), + NumField::number("cvs", pct(&chars["vScale"]), "%", 1).width(84.0).presets(SCALES).range(1.0, 1000.0), + ) { + let _ = app.run("type.char", json!({"attrs": {"vScale": v / 100.0}})); + } + } else { + if let Some(v) = icon_field( + ui, + "hscale", + &tr("Horizontal Scale"), + NumField::number("chs", pct(&chars["hScale"]), "%", 1).width(84.0).presets(SCALES).range(1.0, 1000.0), + ) { + let _ = app.run("type.char", json!({"attrs": {"hScale": v / 100.0}})); + } + } + }); + vsep(ui); + rows(ui, |ui, row| { + if row == 0 { + if let Some(v) = icon_field( + ui, + "baseline-shift", + &tr("Baseline Shift"), + NumField::number("cbs", chars["baselineShift"].as_f64(), " pt", 2).width(76.0).range(-5000.0, 5000.0), + ) { + let _ = app.run("type.char", json!({"attrs": {"baselineShift": v}})); + } + } else { + if let Some(v) = icon_field( + ui, + "skew", + &tr("Skew (False Italic)"), + NumField::number("csk", chars["skew"].as_f64(), "°", 1).width(76.0).range(-85.0, 85.0), + ) { + let _ = app.run("type.char", json!({"attrs": {"skew": v}})); + } } - ui.end_row(); }); vsep(ui); ui.vertical(|ui| { - let cur: Align = serde_json::from_value(para["align"].clone()).unwrap_or_default(); - ui.horizontal(|ui| { - for (a, icon) in [(Align::Left, "align-left"), (Align::Center, "align-center"), (Align::Right, "align-right")] { - if icons::button(ui, icon, 20.0, cur == a, a.label()).clicked() { - let _ = app.run("type.para", json!({"attrs": {"align": a}})); + ui.spacing_mut().item_spacing.y = 3.0; + // The character style, then the language. + let cs = attrs.as_ref().and_then(|a| a["characterStyle"].as_str()).unwrap_or(designcraft_doc::NO_CHAR_STYLE).to_string(); + let names: Vec = app.session.active().map(|d| d.doc.styles.character.iter().map(|c| c.name.clone()).collect()).unwrap_or_default(); + let mut pick = None; + egui::ComboBox::from_id_salt("ctl_char_style") + .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, &cs))) + .width(150.0) + .show_ui(ui, |ui| { + for n in &names { + if ui.selectable_label(*n == cs, crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, n))).clicked() { + pick = Some(n.clone()); + } } - } - }); - ui.horizontal(|ui| { - for (a, icon) in [(Align::LeftJustified, "align-justify"), (Align::FullyJustified, "align-justify-all")] { - if icons::button(ui, icon, 20.0, cur == a, a.label()).clicked() { - let _ = app.run("type.para", json!({"attrs": {"align": a}})); - } - } + }); + if let Some(n) = pick { + let _ = app.run("style.character.apply", json!({"name": n})); + } + let lang = chars["language"].as_str().unwrap_or("English: USA").to_string(); + egui::ComboBox::from_id_salt("ctl_language").selected_text(crate::rtl::widget(ui, tr(&lang))).width(150.0).show_ui(ui, |ui| { + egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| crate::panels::properties::language_menu(app, ui, &lang)); }); }); +} + +fn control_paragraph( + app: &mut DesignApp, + ui: &mut egui::Ui, + attrs: &Option, + para: &serde_json::Value, + tr: &dyn Fn(&str) -> String, +) { + let cur: Align = serde_json::from_value(para["align"].clone()).unwrap_or_default(); + let mut align = None; + rows(ui, |ui, row| { + if row == 0 { + for (a, icon) in [ + (Align::Left, "palign-left"), + (Align::Center, "palign-center"), + (Align::Right, "palign-right"), + (Align::TowardsSpine, "palign-spine-towards"), + ] { + if icons::button(ui, icon, 20.0, cur == a, &tr(a.label())).clicked() { + align = Some(a); + } + } + } else { + for (a, icon) in [ + (Align::LeftJustified, "palign-justify-left"), + (Align::CenterJustified, "palign-justify-center"), + (Align::RightJustified, "palign-justify-right"), + (Align::FullyJustified, "palign-justify-all"), + (Align::AwayFromSpine, "palign-spine-away"), + ] { + if icons::button(ui, icon, 20.0, cur == a, &tr(a.label())).clicked() { + align = Some(a); + } + } + } + }); + if let Some(a) = align { + let _ = app.run("type.para", json!({"attrs": {"align": a}})); + } vsep(ui); let units = app.session.active().map(|d| d.doc.settings.horizontal_units).unwrap_or(Unit::Picas); - egui::Grid::new("ctl_para").num_columns(4).spacing(vec2(4.0, 3.0)).show(ui, |ui| { - caption(ui, "→|"); - if let Some(v) = measure(ui, "cli", para["leftIndent"].as_f64(), units, 54.0) { - let _ = app.run("type.para", json!({"attrs": {"leftIndent": v}})); + let mut set = None; + for ((ia, ta, ka), (ib, tb, kb)) in [ + (("indent-left", "Left Indent", "leftIndent"), ("indent-first", "First Line Left Indent", "firstLineIndent")), + (("indent-right", "Right Indent", "rightIndent"), ("indent-last", "Last Line Right Indent", "lastLineIndent")), + (("space-before", "Space Before", "spaceBefore"), ("space-after", "Space After", "spaceAfter")), + ] { + rows(ui, |ui, row| { + if row == 0 { + if let Some(v) = icon_field(ui, ia, &tr(ta), NumField::measure(ka, para[ka].as_f64(), units).width(84.0).range(0.0, 10_000.0)) { + set = Some((ka, v)); + } + } else { + let min = crate::panels::properties::para_field_min(kb); + if let Some(v) = icon_field(ui, ib, &tr(tb), NumField::measure(kb, para[kb].as_f64(), units).width(84.0).range(min, 10_000.0)) { + set = Some((kb, v)); + } + } + }); + vsep(ui); + } + if let Some((k, v)) = set { + let _ = app.run("type.para", json!({"attrs": {k: v}})); + } + let mut drop = None; + rows(ui, |ui, row| { + if row == 0 { + let max = designcraft_compose::MAX_DROP_CAP_LINES as f64; + if let Some(v) = icon_field( + ui, + "drop-lines", + &tr("Drop Cap Number of Lines"), + NumField::number("cdl", para["dropCapLines"].as_f64(), "", 0).width(64.0).range(0.0, max), + ) { + drop = Some(("dropCapLines", v)); + } + } else { + let max = designcraft_compose::MAX_DROP_CAP_CHARS as f64; + if let Some(v) = icon_field( + ui, + "drop-chars", + &tr("Drop Cap One or More Characters"), + NumField::number("cdc", para["dropCapChars"].as_f64(), "", 0).width(64.0).range(0.0, max), + ) { + drop = Some(("dropCapChars", v)); + } } - caption(ui, "↑¶"); - if let Some(v) = measure(ui, "csb", para["spaceBefore"].as_f64(), units, 54.0) { - let _ = app.run("type.para", json!({"attrs": {"spaceBefore": v}})); - } - ui.end_row(); - caption(ui, "→¶"); - if let Some(v) = measure(ui, "cfi", para["firstLineIndent"].as_f64(), units, 54.0) { - let _ = app.run("type.para", json!({"attrs": {"firstLineIndent": v}})); - } - caption(ui, "↓¶"); - if let Some(v) = measure(ui, "csa", para["spaceAfter"].as_f64(), units, 54.0) { - let _ = app.run("type.para", json!({"attrs": {"spaceAfter": v}})); - } - ui.end_row(); }); + if let Some((k, v)) = drop { + let _ = app.run("type.para", json!({"attrs": {k: v.max(0.0) as u64}})); + } + vsep(ui); + // Bulleted List over Numbered List, as InDesign's (a list with the default hanging indent, or, + // pressed, none). Pressed when every selected paragraph has it, as Type › Apply Bullets shows. + use designcraft_doc::ListType; + let pressed = [ListType::Bullets, ListType::Numbers].map(|k| app.session.selection_has_list(k)); + let mut list = None; + rows(ui, |ui, row| { + let (icon, cmd, tip) = if row == 0 { ("bullets", "list.bullets", "Bulleted List") } else { ("numbering", "list.numbers", "Numbered List") }; + let on = pressed.get(row).copied().unwrap_or(false); + if crate::widgets::icon_toggle(ui, icon, on, &tr(tip)).clicked() { + list = Some((cmd, !on)); + } + }); + if let Some((cmd, on)) = list { + let _ = app.run(cmd, json!({"on": on})); + } + vsep(ui); + // Shading over Border: on or off, the Paragraph Borders and Shading dialog on its tab, and the + // colour, as InDesign's. + let doc = app.session.active().map(|d| d.doc.clone()); + let mut shade = None; + let mut dialog = None; + // Both checkboxes as wide as the wider label, so the icons and colours line up in columns. + let check_w = ["Shading", "Border"] + .iter() + .map(|l| ui.fonts_mut(|f| f.layout_no_wrap(tr(l), egui::FontId::proportional(11.5), Color32::WHITE).size().x)) + .fold(0.0, f32::max) + + 28.0; + rows(ui, |ui, row| { + let (on_key, color_key, label, icon, tab) = if row == 0 { + ("shadingOn", "shadingColor", "Shading", "para-shading", "shading") + } else { + ("borderOn", "borderColor", "Border", "para-border", "border") + }; + let mut on = para[on_key].as_bool().unwrap_or(false); + ui.allocate_ui_with_layout(vec2(check_w, crate::widgets::FIELD_H), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(check_w); + if crate::widgets::checkbox(ui, &mut on, &tr(label)).changed() { + shade = Some(json!({ on_key: on })); + } + }); + if crate::widgets::icon_toggle(ui, icon, false, &tr("Paragraph Borders and Shading…")).clicked() { + dialog = Some(tab); + } + if let Some(doc) = &doc { + let cur = para[color_key].as_str().unwrap_or("[Black]").to_string(); + if let Some(w) = swatch_field(ui, doc, &cur, 96.0, &tr(if row == 0 { "Paragraph Shading" } else { "Paragraph Border" })) { + shade = Some(json!({ color_key: w })); + } + } + }); + if let Some(attrs) = shade { + let _ = app.run("type.para", json!({ "attrs": attrs })); + } + if let Some(tab) = dialog { + let _ = app.run("app.paragraphBordersDialog", json!({ "tab": tab })); + } vsep(ui); ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 3.0; let ps = attrs.as_ref().and_then(|a| a["paragraphStyle"].as_str()).unwrap_or("").to_string(); let ov = attrs.as_ref().and_then(|a| a["paraOverrides"].as_u64()).unwrap_or(0) + attrs.as_ref().and_then(|a| a["charOverrides"].as_u64()).unwrap_or(0); panels::para_style_picker(app, ui, &ps, ov > 0, 170.0); - let hy = para["hyphenate"].as_bool().unwrap_or(true); - let mut h = hy; - if ui.checkbox(&mut h, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Hyphenate"))).changed() { - let _ = app.run("type.para", json!({"attrs": {"hyphenate": h}})); - } + ui.horizontal(|ui| { + let mut h = para["hyphenate"].as_bool().unwrap_or(true); + if crate::widgets::checkbox(ui, &mut h, &tr("Hyphenate")).changed() { + let _ = app.run("type.para", json!({"attrs": {"hyphenate": h}})); + } + // First Line Only is aligned too: the button shows it pressed, and a click turns alignment off. + let grid = matches!(para["gridAlign"].as_str(), Some("allLines" | "firstLineOnly")); + if crate::widgets::icon_toggle(ui, "grid-baseline", grid, &tr("Align to Baseline Grid")).clicked() { + let _ = app.run("type.para", json!({"attrs": {"gridAlign": if grid { "none" } else { "allLines" }}})); + } + }); }); } +/// A swatch field of the Control panel (Shading and Border colours): the swatch's chip and name, +/// and the document's swatches in its menu. Returns the swatch picked. +pub(crate) fn swatch_field(ui: &mut egui::Ui, doc: &designcraft_doc::Document, cur: &str, width: f32, label: &str) -> Option { + let t = Tokens::get(ui.ctx()); + let (r, resp) = ui.allocate_exact_size(vec2(width, crate::widgets::FIELD_H), Sense::click()); + let resp = resp.on_hover_text(label); + resp.widget_info(|| { + let mut info = egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, true, label); + info.current_text_value = Some(cur.to_string()); + info + }); + let p = ui.painter(); + p.rect_filled(r, 0.0, if resp.hovered() { t.hover } else { t.input }); + p.rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); + let seg = egui::Rect::from_min_max(egui::pos2(r.max.x - crate::widgets::SEG_W, r.min.y), r.max); + p.line_segment([seg.left_top(), seg.left_bottom()], Stroke::new(1.0, t.field_border)); + icons::paint(p, egui::Rect::from_center_size(seg.center(), vec2(12.0, 12.0)), "chevron-down", t.icon); + let (c, g) = crate::widgets::swatch_colors(doc, cur, 1.0); + let chip = egui::Rect::from_min_size(egui::pos2(r.min.x + 4.0, r.center().y - 6.0), vec2(12.0, 12.0)); + crate::widgets::paint_chip(p, chip, c, g); + let clip = egui::Rect::from_min_max(r.min, egui::pos2(seg.min.x - 2.0, r.max.y)); + p.with_clip_rect(clip).text(egui::pos2(chip.max.x + 5.0, r.center().y), egui::Align2::LEFT_CENTER, cur, egui::FontId::proportional(11.5), t.text); + let mut picked = None; + egui::Popup::menu(&resp).show(|ui| { + picked = crate::panels::swatch_list(ui, doc, cur); + }); + picked +} + /// The widest a document tab grows: a longer name is shortened so its close button and the /// tabs after it stay in view. const DOC_TAB_MAX_W: f32 = 260.0; @@ -1114,6 +1474,28 @@ fn community_card(app: &mut DesignApp, ui: &mut egui::Ui) { #[cfg(test)] mod tests { + + /// A Control panel field is labelled by its icon, so assistive technology reads "Tracking" + /// (or "Font Size", …) with the value. + #[test] + fn icon_fields_are_labelled_by_their_icon() { + use egui::accesskit::Role; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx, "en"); + ctx.enable_accesskit(); + let mut update = None; + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + icon_field(ui, "tracking", "Tracking", NumField::number("tracking_test", Some(0.0), "", 0)); + }); + out.textures_delta.clear(); + update = out.platform_output.accesskit_update; + } + let update = update.expect("an AccessKit tree"); + let named = |n: &egui::accesskit::Node| n.label() == Some("Tracking") || n.value() == Some("Tracking"); + let icon = update.nodes.iter().find(|(_, n)| named(n)).map(|(id, _)| *id).expect("the icon's node"); + assert!(update.nodes.iter().any(|(_, n)| n.role() == Role::TextInput && n.labelled_by().contains(&icon)), "the editor names its icon"); + } use egui::{pos2, vec2}; use egui_kittest::kittest::{NodeT, Queryable}; @@ -1318,6 +1700,233 @@ mod tests { assert!(short.min.x - first.min.x <= 2.0 * super::DOC_TAB_MAX_W, "the last tab {short:?} starts too far right"); } + /// Zero2Graphic's page layout video (0:48): with the Type tool, the Control panel's font size + /// has a list of sizes; the instructor picks 72 pt from it. Leading has the same list. + #[test] + fn the_type_control_panel_lists_font_sizes_and_leadings() { + let mut app = app(); + app.run("file.new", serde_json::json!({})).unwrap(); + let f = app.run("frame.create", serde_json::json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Headline"})).unwrap(); + app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 8})).unwrap(); + app.session.set_tool("type"); + let mut h = test_window::open(app, vec2(1800.0, 700.0)); + let bar = test_window::panel_rect(&h, "control_bar"); + let in_bar = |r: &egui::Rect| bar.y_range().contains(r.center().y); + let field = |h: &egui_kittest::Harness<'static, test_window::Window>, value: &str| { + h.query_all_by_value(value).map(|n| n.rect()).find(in_bar).unwrap_or_else(|| panic!("no {value:?} field in the Control panel")) + }; + let press = |h: &mut egui_kittest::Harness<'static, test_window::Window>, p: egui::Pos2| { + h.hover_at(p); + h.drag_at(p); + h.drop_at(p); + }; + let size_of = |h: &egui_kittest::Harness<'static, test_window::Window>| { + let st = h.state().app.session.doc().unwrap(); + let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap()); + st.doc.story(sid).unwrap().format_after(0).over.size + }; + // The ⌄ segment right of the size field opens the list; choosing 72 pt sets the size. + let size = field(&h, "12 pt"); + let chevron = pos2(size.max.x + 1.0 + crate::widgets::SEG_W / 2.0, size.center().y); + press(&mut h, chevron); + h.run_steps(3); + h.get_by_label("72 pt").click(); + h.run_steps(3); + assert_eq!(size_of(&h), Some(72.0)); + // Auto leading shows in parentheses, with the same list beside it. + let lead = field(&h, "(86.4 pt)"); + press(&mut h, pos2(lead.max.x + 1.0 + crate::widgets::SEG_W / 2.0, lead.center().y)); + h.run_steps(3); + h.get_by_label("60 pt").click(); + h.run_steps(3); + let st = h.state().app.session.doc().unwrap(); + let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap()); + assert_eq!(st.doc.story(sid).unwrap().format_after(0).over.leading, Some(designcraft_doc::Leading::Points(60.0))); + // The spinner left of the size steps it by a point. + let size = field(&h, "72 pt"); + press(&mut h, pos2(size.min.x - 5.0 - crate::widgets::SEG_W / 2.0, size.min.y + 3.0)); + h.run_steps(3); + assert_eq!(size_of(&h), Some(73.0)); + // Typing the automatic value itself over "(87.6 pt)" fixes the leading at it. + h.state_mut().app.run("type.char", serde_json::json!({"attrs": {"leading": {"kind": "auto"}}})).unwrap(); + h.run_steps(3); + let lead = field(&h, "(87.6 pt)"); + press(&mut h, lead.center()); + 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("87.6".into())); + h.key_press(egui::Key::Enter); + h.run_steps(3); + let st = h.state().app.session.doc().unwrap(); + let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap()); + assert_eq!(st.doc.story(sid).unwrap().format_after(0).over.leading, Some(designcraft_doc::Leading::Points(87.6))); + // Escape cancels: the same typing, then Escape, leaves the leading automatic. + h.state_mut().app.run("type.char", serde_json::json!({"attrs": {"leading": {"kind": "auto"}}})).unwrap(); + h.run_steps(3); + let auto = h.state().app.session.doc().unwrap().doc.story(sid).unwrap().format_after(0).over.leading; + let lead = field(&h, "(87.6 pt)"); + press(&mut h, lead.center()); + 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("87.6".into())); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert_eq!(h.state().app.session.doc().unwrap().doc.story(sid).unwrap().format_after(0).over.leading, auto, "Escape leaves it automatic"); + // Escape also reverts a different number, in the leading field and in a plain one. (It + // leaves the text too, so each try selects it again.) + for (shown, typed) in [("(87.6 pt)", "20"), ("73 pt", "50")] { + h.state_mut().app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 8})).unwrap(); + h.state_mut().app.session.set_tool("type"); + h.run_steps(3); + let r = field(&h, shown); + press(&mut h, r.center()); + 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(typed.into())); + h.key_press(egui::Key::Escape); + h.run_steps(3); + } + assert_eq!(h.state().app.session.doc().unwrap().doc.story(sid).unwrap().format_after(0).over.leading, auto, "still automatic"); + assert_eq!(size_of(&h), Some(73.0), "the size is unchanged"); + } + + /// The Control panel's ¶ mode on a First Line Only paragraph: Align to Baseline Grid shows + /// pressed, and a click turns alignment off instead of making it All Lines. + #[test] + fn the_control_panel_grid_button_keeps_first_line_only() { + use egui_kittest::kittest::{NodeT, Queryable}; + let mut app = app(); + app.run("file.new", serde_json::json!({})).unwrap(); + let f = app.run("frame.create", serde_json::json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Bulbs"})).unwrap(); + app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 5})).unwrap(); + app.run("type.para", serde_json::json!({"attrs": {"gridAlign": "firstLineOnly"}})).unwrap(); + app.session.set_tool("type"); + let mut h = test_window::open(app, vec2(2400.0, 700.0)); + let bar = test_window::panel_rect(&h, "control_bar"); + let in_bar = move |r: egui::Rect| bar.y_range().contains(r.center().y); + let click = |h: &mut egui_kittest::Harness<'static, test_window::Window>, label: &str| { + let r = h.query_all_by_label(label).map(|n| n.rect()).find(|r| in_bar(*r)).unwrap_or_else(|| panic!("no {label:?} in the Control panel")); + h.hover_at(r.center()); + h.drag_at(r.center()); + h.drop_at(r.center()); + h.run_steps(3); + }; + click(&mut h, "Paragraph Formatting Controls"); + let pressed = h.query_all_by_label("Align to Baseline Grid").find(|n| in_bar(n.rect())).map(|n| n.accesskit_node().toggled()); + assert_eq!(pressed, Some(Some(egui::accesskit::Toggled::True))); + assert_eq!(crate::panels::text_attrs(&mut h.state_mut().app).unwrap()["para"]["gridAlign"], "firstLineOnly"); + click(&mut h, "Align to Baseline Grid"); + assert_eq!(crate::panels::text_attrs(&mut h.state_mut().app).unwrap()["para"]["gridAlign"], "none"); + } + + /// The course's chapter 16: the text Control panel has InDesign's two modes. A shows the + /// Character Formatting Controls (the case buttons, kerning and tracking, the scales…), ¶ the + /// Paragraph Formatting Controls (alignment, indents, spacing, the drop cap…). + #[test] + fn the_type_control_panel_has_character_and_paragraph_modes() { + let mut app = app(); + app.run("file.new", serde_json::json!({})).unwrap(); + let f = app.run("frame.create", serde_json::json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Bulbs"})).unwrap(); + app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 5})).unwrap(); + app.session.set_tool("type"); + let mut h = test_window::open(app, vec2(2400.0, 700.0)); + let bar = test_window::panel_rect(&h, "control_bar"); + let in_bar = move |r: egui::Rect| bar.y_range().contains(r.center().y); + let click = |h: &mut egui_kittest::Harness<'static, test_window::Window>, label: &str| { + let r = h.query_all_by_label(label).map(|n| n.rect()).find(|r| in_bar(*r)).unwrap_or_else(|| panic!("no {label:?} in the Control panel")); + h.hover_at(r.center()); + h.drag_at(r.center()); + h.drop_at(r.center()); + h.run_steps(3); + }; + let has = |h: &egui_kittest::Harness<'static, test_window::Window>, label: &str| h.query_all_by_label(label).any(|n| in_bar(n.rect())); + assert!(has(&h, "Small Caps") && has(&h, "Vertical Scale") && !has(&h, "Drop Cap Number of Lines")); + click(&mut h, "Small Caps"); + click(&mut h, "Paragraph Formatting Controls"); + assert!(has(&h, "Drop Cap Number of Lines") && has(&h, "Space Before") && !has(&h, "Small Caps")); + click(&mut h, "Align to Baseline Grid"); + click(&mut h, "Align center"); + let a = crate::panels::text_attrs(&mut h.state_mut().app).unwrap(); + assert_eq!(a["chars"]["capitalization"], "smallCaps"); + assert_eq!(a["para"]["gridAlign"], "allLines"); + assert_eq!(a["para"]["align"], "center"); + click(&mut h, "Character Formatting Controls"); + assert!(has(&h, "Small Caps")); + } + + /// The course's chapter 21: the ¶ Control panel has InDesign's Bulleted and Numbered List + /// buttons (with the default hanging indent), and Shading and Border with their colours and + /// the Paragraph Borders and Shading dialog. + #[test] + fn the_paragraph_control_panel_has_lists_shading_and_border() { + let mut app = app(); + app.run("file.new", serde_json::json!({})).unwrap(); + let f = app + .run( + "frame.create", + serde_json::json!({"rect": [72, 72, 400, 300], "content": "text", "text": "4 eggs +1 cup milk"}), + ) + .unwrap(); + app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 15})).unwrap(); + app.session.set_tool("type"); + let mut h = test_window::open(app, vec2(2400.0, 700.0)); + let bar = test_window::panel_rect(&h, "control_bar"); + let in_bar = move |r: egui::Rect| bar.y_range().contains(r.center().y); + let click = |h: &mut egui_kittest::Harness<'static, test_window::Window>, label: &str, nth: usize| { + let r = h + .query_all_by_label(label) + .map(|n| n.rect()) + .filter(|r| in_bar(*r)) + .nth(nth) + .unwrap_or_else(|| panic!("no {label:?} in the Control panel")); + h.hover_at(r.center()); + h.drag_at(r.center()); + h.drop_at(r.center()); + h.run_steps(3); + }; + click(&mut h, "Paragraph Formatting Controls", 0); + click(&mut h, "Bulleted List", 0); + let a = crate::panels::text_attrs(&mut h.state_mut().app).unwrap(); + assert_eq!( + (a["para"]["listType"].as_str(), a["para"]["leftIndent"].as_f64(), a["para"]["firstLineIndent"].as_f64()), + (Some("bullets"), Some(18.0), Some(-18.0)) + ); + click(&mut h, "Numbered List", 0); + assert_eq!(crate::panels::text_attrs(&mut h.state_mut().app).unwrap()["para"]["listType"], "numbers"); + click(&mut h, "Shading", 0); + click(&mut h, "Border", 0); + let a = crate::panels::text_attrs(&mut h.state_mut().app).unwrap(); + assert_eq!((a["para"]["shadingOn"].as_bool(), a["para"]["borderOn"].as_bool()), (Some(true), Some(true))); + assert!(h.query_all_by_label("Paragraph Shading").any(|n| in_bar(n.rect())), "the shading colour"); + // The icon beside Border opens the dialog on its Border tab. + click(&mut h, "Paragraph Borders and Shading…", 1); + let d = h.state().app.ui.dialog.clone().expect("the dialog"); + assert_eq!((d.id.as_str(), d.s("section").as_str()), ("paragraphLocal", "border")); + // The Last Line Right Indent takes a negative value, as the First Line Left Indent does. + h.state_mut().app.ui.dialog = None; + h.state_mut().app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 15})).unwrap(); + h.state_mut().app.session.set_tool("type"); + h.run_steps(3); + // The field is labelled by its icon. + let at = h + .query_all_by_label("Last Line Right Indent") + .filter(|n| n.accesskit_node().role() == egui::accesskit::Role::TextInput) + .map(|n| n.rect()) + .find(|r| in_bar(*r)) + .expect("the last line indent") + .center(); + h.hover_at(at); + h.drag_at(at); + h.drop_at(at); + 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("-0p6".into())); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(crate::panels::text_attrs(&mut h.state_mut().app).unwrap()["para"]["lastLineIndent"].as_f64(), Some(-6.0)); + } + #[test] fn the_page_tool_has_its_own_control_panel() { // Chris Cicchino's Page Tool and Liquid Layout video (1:02): with the Page tool, the diff --git a/crates/ui-egui/src/credits.rs b/crates/ui-egui/src/credits.rs index b9efa035a..d4828b1f4 100644 --- a/crates/ui-egui/src/credits.rs +++ b/crates/ui-egui/src/credits.rs @@ -212,10 +212,8 @@ impl Default for View { } } -/// About ▸ Contributors: a name toggle, a sort, and the list as a grab bag or a table. -pub fn contributors_ui(ui: &mut egui::Ui, lang: &str) { - let id = egui::Id::new("credits_view"); - let mut v = ui.data_mut(|d| d.get_temp::(id)).unwrap_or_default(); +/// The name toggle, sort and layout controls above the list. +fn controls(ui: &mut egui::Ui, v: &mut View, lang: &str) { ui.horizontal_wrapped(|ui| { ui.label(tr(lang, "Show")); for m in NameMode::ALL { @@ -244,6 +242,13 @@ pub fn contributors_ui(ui: &mut egui::Ui, lang: &str) { v.table = true; } }); +} + +/// About ▸ Contributors: a name toggle, a sort, and the list as a grab bag or a table. +pub fn contributors_ui(ui: &mut egui::Ui, lang: &str) { + let id = egui::Id::new("credits_view"); + let mut v = ui.data_mut(|d| d.get_temp::(id)).unwrap_or_default(); + controls(ui, &mut v, lang); let list = sorted(CONTRIBUTORS, v.names, v.key, v.ascending); let totals = tr(lang, "{contributors} contributors · {commits} commits") .replace("{contributors}", &list.len().to_string()) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index b412a06f0..04d2391f3 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -527,6 +527,15 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { _ => ((inner - o.gutter * (n - 1.0)) / n).max(0.0), }; let kind = |v: Value| v.as_str().unwrap_or_default().to_string(); + // A frame without a custom baseline grid shows the document grid's start and increment. + let grid = o.baseline_grid.unwrap_or_else(|| { + let g = app.session.active().map(|s| s.doc.settings.baseline_grid.clone()).unwrap_or_default(); + let relative_to = match g.relative_to { + designcraft_doc::GridRelative::TopOfPage => designcraft_doc::FrameGridRelative::TopOfPage, + designcraft_doc::GridRelative::TopMargin => designcraft_doc::FrameGridRelative::TopMargin, + }; + designcraft_doc::FrameBaselineGrid { start: g.start, increment: g.increment, relative_to } + }); let shown = json!({ "columns": o.columns, "gutter": fm(o.gutter), "columnsKind": kind(serde_json::to_value(o.columns_kind).unwrap_or_default()), "columnWidth": fm(width), @@ -542,6 +551,8 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { "useMinimumHeight": o.auto_size_use_min_height, "minimumHeight": fm(o.auto_size_min_height), "useMinimumWidth": o.auto_size_use_min_width, "minimumWidth": fm(o.auto_size_min_width), "noLineBreaks": o.auto_size_no_line_breaks, + "customGrid": o.baseline_grid.is_some(), "gridStart": fm(grid.start), "gridIncrement": fm(grid.increment), + "gridRelativeTo": grid.relative_to.name(), }); if let Value::Object(m) = &shown { for (k, v) in m { @@ -593,6 +604,28 @@ fn text_frame_options_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) text_field(ui, d, "firstBaselineMin", 70.0); ui.end_row(); }); + ui.add_space(8.0); + crate::rtl::label(ui, egui::RichText::new(tr("Baseline Grid")).font(semibold(12.0))); + check(ui, d, "customGrid", tr("Use Custom Baseline Grid")); + ui.add_enabled_ui(d.b("customGrid"), |ui| { + egui::Grid::new("tfo_grid").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { + crate::rtl::label(ui, tr("Start:")); + text_field(ui, d, "gridStart", 70.0); + ui.end_row(); + crate::rtl::label(ui, tr("Relative To:")); + translated_combo( + &lang, + ui, + d, + "gridRelativeTo", + &[("page", "Top of Page"), ("margin", "Top Margin"), ("frame", "Top of Frame"), ("inset", "Top Inset")], + ); + ui.end_row(); + crate::rtl::label(ui, tr("Increment Every:")); + text_field(ui, d, "gridIncrement", 70.0); + ui.end_row(); + }); + }); } "autosize" => auto_size(&lang, ui, d), "rules" => column_rules(app, ui, d), @@ -857,6 +890,30 @@ fn confirm_text_frame_options(app: &mut DesignApp, d: &mut Dialog) -> Result= 0.0).ok_or_else(|| bad(what))?)); } } + // The custom baseline grid: off, or the fields the user changed (all of them when it is + // turned on, since it shows the document grid's). + let grid_keys = ["customGrid", "gridStart", "gridIncrement", "gridRelativeTo"]; + if grid_keys.iter().any(|k| edited(d, k)) { + if d.b("customGrid") { + let all = edited(d, "customGrid"); + let mut g = Map::new(); + if all || edited(d, "gridStart") { + g.insert("start".into(), json!(d.m("gridStart").ok_or_else(|| bad("the baseline grid start is not a measure"))?)); + } + if all || edited(d, "gridIncrement") { + g.insert( + "increment".into(), + json!(d.m("gridIncrement").filter(|v| *v > 0.0).ok_or_else(|| bad("the baseline grid increment is not a measure"))?), + ); + } + if all || edited(d, "gridRelativeTo") { + g.insert("relativeTo".into(), json!(d.s("gridRelativeTo"))); + } + p.insert("baselineGrid".into(), Value::Object(g)); + } else { + p.insert("baselineGrid".into(), Value::Null); + } + } if p.is_empty() { return Ok(Value::Null); } @@ -2064,10 +2121,14 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { match d.s("section").as_str() { "span" => "Span Columns", "bullets" => "Bullets and Numbering", + "keep" => "Keep Options", + "nested" => "Drop Caps and Nested Styles", + "grep" => "GREP Styles", _ => "Paragraph Borders and Shading", }, ), "justification" => crate::i18n::tr(&app.ui.language, "Justification"), + "hyphenation" => crate::i18n::tr(&app.ui.language, "Hyphenation Settings"), "insertXref" => crate::i18n::tr(&app.ui.language, "New Cross-Reference"), "findFont" => crate::i18n::tr(&app.ui.language, "Find/Replace Font"), "polygonSettings" => crate::i18n::tr(&app.ui.language, "Polygon Settings"), @@ -2109,6 +2170,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { "alert" => 440.0, "closeDocument" | "updateLink" | "deletePages" | "newWorkspace" | "pagesPanelOptions" => 380.0, "newDocument" => 960.0, + "hyphenation" => 560.0, "numberingSection" => 560.0, crate::effects_dialog::ID => 720.0, _ => 640.0, @@ -2361,6 +2423,21 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { let current = d.fields.get("current").cloned().unwrap_or_default(); justification(&app.ui.language, ui, &mut d, "", ¤t); } + "hyphenation" => { + let current = d.fields.get("current").cloned().unwrap_or_default(); + let units = app.session.active().map_or(Unit::Picas, |st| st.doc.settings.horizontal_units); + let preview = crate::i18n::tr(&app.ui.language, "Preview").to_string(); + ui.horizontal_top(|ui| { + ui.vertical(|ui| hyphenation(&app.ui.language, ui, &mut d, "", ¤t, units)); + ui.add_space(24.0); + check(ui, &mut d, "preview", &preview); + }); + hyphenation_preview(app, &mut 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(ui.visuals().error_fg_color)); + } + } "insertXref" => insert_xref(app, ui, &mut d), "findFont" => find_font(app, ui, &mut d), "colorPicker" => color_picker(ui, &mut d), @@ -3173,6 +3250,24 @@ pub fn confirm(app: &mut DesignApp) -> Result { } app.run("type.para", json!({"attrs": attrs})) } + "hyphenation" => { + // The preview goes; the edits are made once, as one undo step. + if d.fields.contains_key(PREVIEWED) { + app.session.cancel_interaction(); + } + let attrs = hyphenation_edits(&d); + if attrs.is_empty() { + return Ok(Value::Null); + } + app.run("type.para", json!({"attrs": attrs})).inspect_err(|e| { + // The dialog stays open, with the reason, to be corrected. + app.status(e.clone()); + let mut d = d; + d.fields.remove(PREVIEWED); + d.fields.insert("status".into(), json!(e)); + app.ui.dialog = Some(d); + }) + } "justification" => { let current = d.fields.get("current").cloned().unwrap_or_default(); if let Err(e) = check_justification(&d, "", ¤t) { @@ -3679,18 +3774,13 @@ fn check_paragraph_style_justification(app: &DesignApp, d: &Dialog) -> Result<() check_justification(d, "p.", &base) } -fn confirm_paragraph_style_options(app: &mut DesignApp, d: &mut Dialog) -> Result { - let name = d.s("name"); - if let Err(e) = check_paragraph_style_justification(app, d) { - // The caller shows the reason in the dialog's status line. - d.fields.insert("section".into(), json!("justify")); - return Err(e); - } +/// The `p.*` and `c.*` dialog fields as the paragraph and character attribute maps a style +/// command takes. `p.ruleAbove.weight` is one field of a rule (the command keeps the others). +fn style_option_maps(d: &Dialog) -> (serde_json::Map, serde_json::Map) { let mut para = serde_json::Map::new(); let mut chars = serde_json::Map::new(); for (k, v) in &d.fields { if let Some(a) = k.strip_prefix("p.") { - // `p.ruleAbove.weight`: one field of a rule (the command keeps the others). match a.split_once('.') { Some((attr, field)) => { if let Value::Object(m) = para.entry(attr).or_insert_with(|| json!({})) { @@ -3705,6 +3795,17 @@ fn confirm_paragraph_style_options(app: &mut DesignApp, d: &mut Dialog) -> Resul chars.insert(a.into(), v.clone()); } } + (para, chars) +} + +fn confirm_paragraph_style_options(app: &mut DesignApp, d: &mut Dialog) -> Result { + let name = d.s("name"); + if let Err(e) = check_paragraph_style_justification(app, d) { + // The caller shows the reason in the dialog's status line. + d.fields.insert("section".into(), json!("justify")); + return Err(e); + } + let (para, chars) = style_option_maps(d); let based = d.s("basedOn"); let rename = d.s("rename"); let (r, style) = if d.b("new") { @@ -3739,6 +3840,26 @@ fn confirm_paragraph_style_options(app: &mut DesignApp, d: &mut Dialog) -> Resul Ok(r) } +/// Copies the dialog's `c.*` (and, for a paragraph style, `p.*`) fields into the preview params. +fn fill_style_preview_fields(params: &mut Value, d: &Dialog, paragraph: bool) { + for (key, value) in &d.fields { + if let Some(attr) = key.strip_prefix("c.") { + params["chars"][attr] = value.clone(); + } else if paragraph && let Some(attr) = key.strip_prefix("p.") { + if let Some((attr, field)) = attr.split_once('.') { + if params["para"][attr].is_null() { + params["para"][attr] = json!({}); + } + if let Some(fields) = params["para"][attr].as_object_mut() { + fields.insert(field.into(), value.clone()); + } + } else { + params["para"][attr] = value.clone(); + } + } + } +} + /// Preview the changed style attributes through the same engine commands as OK. Renaming and /// export tagging have no visual effect and wait for OK, so the dialog can keep looking up the /// original style while the preview is visible. The interaction restores its starting document @@ -3768,22 +3889,7 @@ fn style_options_preview(app: &mut DesignApp, d: &mut Dialog) { if paragraph { params["para"] = json!({}); } - for (key, value) in &d.fields { - if let Some(attr) = key.strip_prefix("c.") { - params["chars"][attr] = value.clone(); - } else if paragraph && let Some(attr) = key.strip_prefix("p.") { - if let Some((attr, field)) = attr.split_once('.') { - if params["para"][attr].is_null() { - params["para"][attr] = json!({}); - } - if let Some(fields) = params["para"][attr].as_object_mut() { - fields.insert(field.into(), value.clone()); - } - } else { - params["para"][attr] = value.clone(); - } - } - } + fill_style_preview_fields(&mut params, d, paragraph); if let Some(based) = d.fields.get("basedOn") { params["basedOn"] = match based.as_str() { Some(designcraft_doc::NO_PARA_STYLE | designcraft_doc::NO_CHAR_STYLE) => Value::Null, @@ -3900,270 +4006,8 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo text_field(ui, d, "x.class", 160.0); }); } - "nested" => { - crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Drop Caps")).font(semibold(12.0))); - egui::Grid::new("psdc").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { - for (label, key, max) in [ - ("Lines:", "dropCapLines", designcraft_compose::MAX_DROP_CAP_LINES), - ("Characters:", "dropCapChars", designcraft_compose::MAX_DROP_CAP_CHARS), - ] { - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, label)); - let v = cur(d, &format!("p.{key}"), &pv[key]).as_f64(); - if let Some(n) = crate::widgets::number(ui, &format!("ps{key}"), v, "", 60.0, 0) { - d.fields.insert(format!("p.{key}"), json!((n.max(0.0) as u64).min(max as u64))); - } - ui.end_row(); - } - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Character Style:")); - let style = cur(d, "p.dropCapStyle", &pv["dropCapStyle"]).as_str().unwrap_or("").to_string(); - let style = if style.is_empty() { designcraft_doc::NO_CHAR_STYLE.to_string() } else { style }; - egui::ComboBox::from_id_salt("ps_dropcap_style") - .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, &style))) - .width(160.0) - .show_ui(ui, |ui| { - for c in &cnames { - if ui.selectable_label(*c == style, crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, c))).clicked() { - d.fields.insert("p.dropCapStyle".into(), json!(c)); - } - } - }); - ui.end_row(); - }); - for (label, key) in [("Align Left Edge", "dropCapAlignLeft"), ("Scale for Descenders", "dropCapScaleDescenders")] { - let mut on = cur(d, &format!("p.{key}"), &pv[key]).as_bool().unwrap_or(false); - if ui.checkbox(&mut on, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).changed() { - d.fields.insert(format!("p.{key}"), json!(on)); - } - } - ui.add_space(8.0); - crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Nested Styles")).font(semibold(12.0))); - let mut list: Vec = cur(d, "p.nestedStyles", &pv["nestedStyles"]).as_array().cloned().unwrap_or_default(); - let mut changed = false; - let mut remove = None; - for (i, ns) in list.iter_mut().enumerate() { - ui.horizontal(|ui| { - let style = ns["style"].as_str().unwrap_or("[None]").to_string(); - egui::ComboBox::from_id_salt(("ns_style", i)) - .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, &style))) - .width(110.0) - .show_ui(ui, |ui| { - for c in &cnames { - if ui - .selectable_label(*c == style, crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, c))) - .clicked() - { - ns["style"] = json!(c); - changed = true; - } - } - }); - let through = ns["through"].as_bool().unwrap_or(true); - egui::ComboBox::from_id_salt(("ns_thr", i)) - .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, if through { "through" } else { "up to" }))) - .width(70.0) - .show_ui(ui, |ui| { - for (v, l) in [(true, "through"), (false, "up to")] { - if ui.selectable_label(v == through, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, l))).clicked() { - ns["through"] = json!(v); - changed = true; - } - } - }); - let mut n = ns["count"].as_u64().unwrap_or(1) as u32; - let mut count_value = |ui: &mut egui::Ui, ns: &mut Value, changed: &mut bool| { - if ui.add(egui::DragValue::new(&mut n).range(1..=999)).changed() { - ns["count"] = json!(n); - *changed = true; - } - }; - if !crate::i18n::category_first(&app.ui.language) { - count_value(ui, ns, &mut changed); - } - let kind = ns["until"]["kind"].as_str().unwrap_or("words").to_string(); - egui::ComboBox::from_id_salt(("ns_until", i)) - .selected_text(crate::rtl::widget( - ui, - if crate::i18n::category_first(&app.ui.language) { - format!("{}:", crate::i18n::tr(&app.ui.language, &kind)) - } else { - crate::i18n::tr(&app.ui.language, &kind).to_owned() - }, - )) - .width(100.0) - .show_ui(ui, |ui| { - for k in [ - "sentences", - "words", - "characters", - "letters", - "digits", - "tab", - "forcedLineBreak", - "emSpace", - "enSpace", - "dropcap", - "chars", - ] { - if ui.selectable_label(k == kind, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, k))).clicked() { - ns["until"] = if k == "chars" { json!({"kind": "chars", "chars": ":"}) } else { json!({"kind": k}) }; - changed = true; - } - } - }); - if crate::i18n::category_first(&app.ui.language) { - count_value(ui, ns, &mut changed); - } - if kind == "chars" { - let mut c = ns["until"]["chars"].as_str().unwrap_or("").to_string(); - if ui.add(egui::TextEdit::singleline(&mut c).desired_width(40.0)).changed() { - ns["until"]["chars"] = json!(c); - changed = true; - } - } - if ui - .small_button("×") - .on_hover_ui(|ui| { - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Delete")); - }) - .clicked() - { - remove = Some(i); - } - }); - } - if let Some(i) = remove { - list.remove(i); - changed = true; - } - if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "New Nested Style"))).clicked() { - list.push(json!({"style": cnames.get(1).cloned().unwrap_or_default(), "through": true, "count": 1, "until": {"kind": "words"}})); - changed = true; - } - if changed { - d.fields.insert("p.nestedStyles".into(), Value::Array(list)); - } - ui.add_space(8.0); - crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Nested Line Styles")).font(semibold(12.0))); - let mut lines: Vec = cur(d, "p.nestedLineStyles", &pv["nestedLineStyles"]).as_array().cloned().unwrap_or_default(); - let mut changed = false; - let mut remove = None; - for (i, l) in lines.iter_mut().enumerate() { - ui.horizontal(|ui| { - let style = l["style"].as_str().unwrap_or("").to_string(); - egui::ComboBox::from_id_salt(("nls_style", i)) - .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, &style))) - .width(130.0) - .show_ui(ui, |ui| { - for c in &cnames { - if ui - .selectable_label(*c == style, crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, c))) - .clicked() - { - l["style"] = json!(c); - changed = true; - } - } - }); - crate::rtl::label( - ui, - if crate::i18n::category_first(&app.ui.language) { - format!("{}:", crate::i18n::tr(&app.ui.language, "lines")) - } else { - crate::i18n::tr(&app.ui.language, "for").to_owned() - }, - ); - let mut n = l["lines"].as_u64().unwrap_or(1) as u32; - if ui.add(egui::DragValue::new(&mut n).range(1..=999)).changed() { - l["lines"] = json!(n); - changed = true; - } - if !crate::i18n::category_first(&app.ui.language) { - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, if n == 1 { "line" } else { "lines" })); - } - if ui - .small_button("×") - .on_hover_ui(|ui| { - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Delete")); - }) - .clicked() - { - remove = Some(i); - } - }); - } - if let Some(i) = remove { - lines.remove(i); - changed = true; - } - if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "New Line Style"))).clicked() { - lines.push(json!({"style": cnames.get(1).cloned().unwrap_or_default(), "lines": 1})); - changed = true; - } - if changed { - d.fields.insert("p.nestedLineStyles".into(), Value::Array(lines)); - } - } - "grep" => { - crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "GREP Styles")).font(semibold(12.0))); - let mut list: Vec = cur(d, "p.grepStyles", &pv["grepStyles"]).as_array().cloned().unwrap_or_default(); - let mut changed = false; - let mut remove = None; - for (i, g) in list.iter_mut().enumerate() { - ui.horizontal(|ui| { - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Apply Style:")); - let style = g["style"].as_str().unwrap_or("").to_string(); - egui::ComboBox::from_id_salt(("gs_style", i)) - .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, &style))) - .width(110.0) - .show_ui(ui, |ui| { - for c in &cnames { - if ui - .selectable_label(*c == style, crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, c))) - .clicked() - { - g["style"] = json!(c); - changed = true; - } - } - }); - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "To Text:")); - let mut pat = g["pattern"].as_str().unwrap_or("").to_string(); - let bad = grep_error(&pat).is_some(); - let r = ui.add( - egui::TextEdit::singleline(&mut pat) - .desired_width(150.0) - .text_color_opt(bad.then_some(egui::Color32::from_rgb(240, 90, 90))), - ); - if r.changed() { - g["pattern"] = json!(pat); - changed = true; - } - if ui - .small_button("×") - .on_hover_ui(|ui| { - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Delete")); - }) - .clicked() - { - remove = Some(i); - } - }); - if let Some(e) = grep_error(g["pattern"].as_str().unwrap_or("")) { - crate::rtl::label(ui, egui::RichText::new(e).size(11.0).color(egui::Color32::from_rgb(240, 90, 90))); - } - } - if let Some(i) = remove { - list.remove(i); - changed = true; - } - if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "New GREP Style"))).clicked() { - list.push(json!({"style": cnames.get(1).cloned().unwrap_or_default(), "pattern": "\\d+"})); - changed = true; - } - if changed { - d.fields.insert("p.grepStyles".into(), Value::Array(list)); - } - } + "nested" => drop_caps_and_nested_styles(&app.ui.language, ui, d, &pv, &cnames), + "grep" => grep_styles(&app.ui.language, ui, d, &pv, &cnames), "chars" => basic_character_formats(app, ui, d, &CharFields { base: &cv, sparse: false }), "indents" => { egui::Grid::new("psi").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { @@ -4194,31 +4038,36 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo } ui.end_row(); } + // The CJK Grid Settings section edits the same `p.gridAlign` field. + use designcraft_doc::GridAlign; + const GRID_ALIGN: [(GridAlign, &str); 3] = + [(GridAlign::None, "None"), (GridAlign::AllLines, "All Lines"), (GridAlign::FirstLineOnly, "First Line Only")]; + crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Align to Grid:")); + let g: GridAlign = serde_json::from_value(cur(d, "p.gridAlign", &pv["gridAlign"])).unwrap_or_default(); + let shown = GRID_ALIGN.iter().find(|o| o.0 == g).map_or("", |o| o.1); + egui::ComboBox::from_id_salt("psgridalign") + .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, shown))) + .width(240.0) + .show_ui(ui, |ui| { + for (v, label) in GRID_ALIGN { + if ui.selectable_label(v == g, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() + && let Ok(v) = serde_json::to_value(v) + { + d.fields.insert("p.gridAlign".into(), v); + } + } + }); + 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), - "hyph" => { - let mut h = cur(d, "p.hyphenate", &pv["hyphenate"]).as_bool().unwrap_or(true); - if ui.checkbox(&mut h, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Hyphenate"))).changed() { - d.fields.insert("p.hyphenate".into(), json!(h)); - } - egui::Grid::new("psh").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { - for (label, key) in [ - ("Words with at Least:", "hyphMinWord"), - ("After First:", "hyphAfterFirst"), - ("Before Last:", "hyphBeforeLast"), - ("Hyphen Limit:", "hyphLimit"), - ] { - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, label)); - let v = cur(d, &format!("p.{key}"), &pv[key]).as_f64(); - if let Some(n) = crate::widgets::number(ui, &format!("ps{key}"), v, "", 60.0, 0) { - d.fields.insert(format!("p.{key}"), json!(n.max(0.0) as u64)); - } - ui.end_row(); - } - }); - } + "hyph" => hyphenation(&app.ui.language, ui, d, "p.", &pv, units), "justify" => justification(&app.ui.language, ui, d, "p.", &pv), "color" => character_color(&app.ui.language, ui, d, &CharFields { base: &cv, sparse: false }, &doc), "advanced" => advanced_character_formats(&app.ui.language, ui, d, &CharFields { base: &cv, sparse: false }), @@ -4714,6 +4563,254 @@ fn border_shading(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc }); } +/// Drop Caps and Nested Styles: the drop cap, nested styles and nested line styles (`p.` fields). +fn drop_caps_and_nested_styles(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, cnames: &[String]) { + let cur = |d: &Dialog, k: &str, base: &Value| d.fields.get(k).cloned().unwrap_or_else(|| base.clone()); + crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, "Drop Caps")).font(semibold(12.0))); + egui::Grid::new("psdc").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { + for (label, key, max) in [ + ("Lines:", "dropCapLines", designcraft_compose::MAX_DROP_CAP_LINES), + ("Characters:", "dropCapChars", designcraft_compose::MAX_DROP_CAP_CHARS), + ] { + crate::rtl::label(ui, crate::i18n::tr(lang, label)); + let v = cur(d, &format!("p.{key}"), &pv[key]).as_f64(); + if let Some(n) = crate::widgets::number(ui, &format!("ps{key}"), v, "", 60.0, 0) { + d.fields.insert(format!("p.{key}"), json!((n.max(0.0) as u64).min(max as u64))); + } + ui.end_row(); + } + crate::rtl::label(ui, crate::i18n::tr(lang, "Character Style:")); + let style = cur(d, "p.dropCapStyle", &pv["dropCapStyle"]).as_str().unwrap_or("").to_string(); + let style = if style.is_empty() { designcraft_doc::NO_CHAR_STYLE.to_string() } else { style }; + egui::ComboBox::from_id_salt("ps_dropcap_style") + .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(lang, &style))) + .width(160.0) + .show_ui(ui, |ui| { + for c in cnames { + if ui.selectable_label(*c == style, crate::rtl::widget(ui, crate::i18n::style_name(lang, c))).clicked() { + d.fields.insert("p.dropCapStyle".into(), json!(c)); + } + } + }); + ui.end_row(); + }); + for (label, key) in [("Align Left Edge", "dropCapAlignLeft"), ("Scale for Descenders", "dropCapScaleDescenders")] { + let mut on = cur(d, &format!("p.{key}"), &pv[key]).as_bool().unwrap_or(false); + if ui.checkbox(&mut on, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).changed() { + d.fields.insert(format!("p.{key}"), json!(on)); + } + } + ui.add_space(8.0); + crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, "Nested Styles")).font(semibold(12.0))); + let mut list: Vec = cur(d, "p.nestedStyles", &pv["nestedStyles"]).as_array().cloned().unwrap_or_default(); + let mut changed = false; + let mut remove = None; + for (i, ns) in list.iter_mut().enumerate() { + ui.horizontal(|ui| { + let style = ns["style"].as_str().unwrap_or("[None]").to_string(); + egui::ComboBox::from_id_salt(("ns_style", i)) + .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(lang, &style))) + .width(110.0) + .show_ui(ui, |ui| { + for c in cnames { + if ui.selectable_label(*c == style, crate::rtl::widget(ui, crate::i18n::style_name(lang, c))).clicked() { + ns["style"] = json!(c); + changed = true; + } + } + }); + let through = ns["through"].as_bool().unwrap_or(true); + egui::ComboBox::from_id_salt(("ns_thr", i)) + .selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, if through { "through" } else { "up to" }))) + .width(70.0) + .show_ui(ui, |ui| { + for (v, l) in [(true, "through"), (false, "up to")] { + if ui.selectable_label(v == through, crate::rtl::widget(ui, crate::i18n::tr(lang, l))).clicked() { + ns["through"] = json!(v); + changed = true; + } + } + }); + let mut n = ns["count"].as_u64().unwrap_or(1) as u32; + let mut count_value = |ui: &mut egui::Ui, ns: &mut Value, changed: &mut bool| { + if ui.add(egui::DragValue::new(&mut n).range(1..=999)).changed() { + ns["count"] = json!(n); + *changed = true; + } + }; + if !crate::i18n::category_first(lang) { + count_value(ui, ns, &mut changed); + } + let kind = ns["until"]["kind"].as_str().unwrap_or("words").to_string(); + egui::ComboBox::from_id_salt(("ns_until", i)) + .selected_text(crate::rtl::widget( + ui, + if crate::i18n::category_first(lang) { + format!("{}:", crate::i18n::tr(lang, &kind)) + } else { + crate::i18n::tr(lang, &kind).to_owned() + }, + )) + .width(100.0) + .show_ui(ui, |ui| { + for k in + ["sentences", "words", "characters", "letters", "digits", "tab", "forcedLineBreak", "emSpace", "enSpace", "dropcap", "chars"] + { + if ui.selectable_label(k == kind, crate::rtl::widget(ui, crate::i18n::tr(lang, k))).clicked() { + ns["until"] = if k == "chars" { json!({"kind": "chars", "chars": ":"}) } else { json!({"kind": k}) }; + changed = true; + } + } + }); + if crate::i18n::category_first(lang) { + count_value(ui, ns, &mut changed); + } + if kind == "chars" { + let mut c = ns["until"]["chars"].as_str().unwrap_or("").to_string(); + if ui.add(egui::TextEdit::singleline(&mut c).desired_width(40.0)).changed() { + ns["until"]["chars"] = json!(c); + changed = true; + } + } + if ui + .small_button("×") + .on_hover_ui(|ui| { + crate::rtl::label(ui, crate::i18n::tr(lang, "Delete")); + }) + .clicked() + { + remove = Some(i); + } + }); + } + if let Some(i) = remove { + list.remove(i); + changed = true; + } + if ui.button(crate::rtl::widget(ui, crate::i18n::tr(lang, "New Nested Style"))).clicked() { + list.push(json!({"style": cnames.get(1).cloned().unwrap_or_default(), "through": true, "count": 1, "until": {"kind": "words"}})); + changed = true; + } + if changed { + d.fields.insert("p.nestedStyles".into(), Value::Array(list)); + } + ui.add_space(8.0); + crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, "Nested Line Styles")).font(semibold(12.0))); + let mut lines: Vec = cur(d, "p.nestedLineStyles", &pv["nestedLineStyles"]).as_array().cloned().unwrap_or_default(); + let mut changed = false; + let mut remove = None; + for (i, l) in lines.iter_mut().enumerate() { + ui.horizontal(|ui| { + let style = l["style"].as_str().unwrap_or("").to_string(); + egui::ComboBox::from_id_salt(("nls_style", i)) + .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(lang, &style))) + .width(130.0) + .show_ui(ui, |ui| { + for c in cnames { + if ui.selectable_label(*c == style, crate::rtl::widget(ui, crate::i18n::style_name(lang, c))).clicked() { + l["style"] = json!(c); + changed = true; + } + } + }); + crate::rtl::label( + ui, + if crate::i18n::category_first(lang) { + format!("{}:", crate::i18n::tr(lang, "lines")) + } else { + crate::i18n::tr(lang, "for").to_owned() + }, + ); + let mut n = l["lines"].as_u64().unwrap_or(1) as u32; + if ui.add(egui::DragValue::new(&mut n).range(1..=999)).changed() { + l["lines"] = json!(n); + changed = true; + } + if !crate::i18n::category_first(lang) { + crate::rtl::label(ui, crate::i18n::tr(lang, if n == 1 { "line" } else { "lines" })); + } + if ui + .small_button("×") + .on_hover_ui(|ui| { + crate::rtl::label(ui, crate::i18n::tr(lang, "Delete")); + }) + .clicked() + { + remove = Some(i); + } + }); + } + if let Some(i) = remove { + lines.remove(i); + changed = true; + } + if ui.button(crate::rtl::widget(ui, crate::i18n::tr(lang, "New Line Style"))).clicked() { + lines.push(json!({"style": cnames.get(1).cloned().unwrap_or_default(), "lines": 1})); + changed = true; + } + if changed { + d.fields.insert("p.nestedLineStyles".into(), Value::Array(lines)); + } +} + +/// GREP Styles: a character style applied to text matching each pattern (`p.` fields). +fn grep_styles(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, cnames: &[String]) { + let cur = |d: &Dialog, k: &str, base: &Value| d.fields.get(k).cloned().unwrap_or_else(|| base.clone()); + crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, "GREP Styles")).font(semibold(12.0))); + let mut list: Vec = cur(d, "p.grepStyles", &pv["grepStyles"]).as_array().cloned().unwrap_or_default(); + let mut changed = false; + let mut remove = None; + for (i, g) in list.iter_mut().enumerate() { + ui.horizontal(|ui| { + crate::rtl::label(ui, crate::i18n::tr(lang, "Apply Style:")); + let style = g["style"].as_str().unwrap_or("").to_string(); + egui::ComboBox::from_id_salt(("gs_style", i)) + .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(lang, &style))) + .width(110.0) + .show_ui(ui, |ui| { + for c in cnames { + if ui.selectable_label(*c == style, crate::rtl::widget(ui, crate::i18n::style_name(lang, c))).clicked() { + g["style"] = json!(c); + changed = true; + } + } + }); + crate::rtl::label(ui, crate::i18n::tr(lang, "To Text:")); + let mut pat = g["pattern"].as_str().unwrap_or("").to_string(); + let bad = grep_error(&pat).is_some(); + let r = + ui.add(egui::TextEdit::singleline(&mut pat).desired_width(150.0).text_color_opt(bad.then_some(egui::Color32::from_rgb(240, 90, 90)))); + if r.changed() { + g["pattern"] = json!(pat); + changed = true; + } + if ui + .small_button("×") + .on_hover_ui(|ui| { + crate::rtl::label(ui, crate::i18n::tr(lang, "Delete")); + }) + .clicked() + { + remove = Some(i); + } + }); + if let Some(e) = grep_error(g["pattern"].as_str().unwrap_or("")) { + crate::rtl::label(ui, egui::RichText::new(e).size(11.0).color(egui::Color32::from_rgb(240, 90, 90))); + } + } + if let Some(i) = remove { + list.remove(i); + changed = true; + } + if ui.button(crate::rtl::widget(ui, crate::i18n::tr(lang, "New GREP Style"))).clicked() { + list.push(json!({"style": cnames.get(1).cloned().unwrap_or_default(), "pattern": "\\d+"})); + changed = true; + } + if changed { + d.fields.insert("p.grepStyles".into(), Value::Array(list)); + } +} + /// Paragraph Style Options › Keep Options: lines kept with the next paragraph, the paragraph's /// lines kept together (all of them, or its first and last lines), and where it starts. fn keep_options(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value) { @@ -5123,6 +5220,15 @@ fn paragraph_local(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.set_min_width(480.0); match d.s("section").as_str() { "span" => span_columns(&lang, ui, d, &pv, &doc), + "keep" => keep_options(&lang, ui, d, &pv), + "nested" | "grep" => { + let cnames: Vec = doc.styles.character.iter().map(|c| c.name.clone()).collect(); + if d.s("section") == "nested" { + drop_caps_and_nested_styles(&lang, ui, d, &pv, &cnames); + } else { + grep_styles(&lang, ui, d, &pv, &cnames); + } + } "bullets" => { let (char_styles, families, fonts, scope) = ListUi::new_parts(app); let (family, style) = (d.s("family"), d.s("style")); @@ -5186,6 +5292,57 @@ pub fn open_new_style(app: &mut DesignApp, para: bool) { app.ui.dialog = Some(Dialog::new(id, json!({"new": true, "rename": name}))); } +/// The General section of the Character Style Options dialog: name, Based On, and a summary of +/// the style's settings. +fn character_style_general( + lang: &str, + ui: &mut egui::Ui, + d: &mut Dialog, + styles: &designcraft_doc::Styles, + style: &designcraft_doc::CharacterStyle, + based: &str, +) { + let (name, new) = (d.s("name"), d.b("new")); + egui::Grid::new("csg").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { + crate::rtl::label(ui, crate::i18n::tr(lang, "Style Name:")); + text_field(ui, d, "rename", 220.0); + ui.end_row(); + crate::rtl::label(ui, crate::i18n::tr(lang, "Based On:")); + egui::ComboBox::from_id_salt("csbased").selected_text(crate::rtl::widget(ui, crate::i18n::style_name(lang, based))).width(220.0).show_ui( + ui, + |ui| { + // Not itself, nor a style based on it. + for s in styles.character.iter().filter(|s| new || !styles.char_based_on_cycles(&name, &s.name)) { + if ui.selectable_label(s.name == based, crate::rtl::widget(ui, crate::i18n::style_name(lang, &s.name))).clicked() { + d.fields.insert("basedOn".into(), json!(s.name)); + } + } + }, + ); + ui.end_row(); + }); + let status = d.s("status"); + if !status.is_empty() { + crate::rtl::label(ui, egui::RichText::new(status).color(crate::theme::Tokens::get(ui.ctx()).text_strong)); + } + ui.add_space(8.0); + crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, "Style Settings:")).font(semibold(12.0))); + // What OK would leave the style setting, after its Based On. + let mut own = serde_json::to_value(&style.chars).unwrap_or_default(); + if let Some(o) = own.as_object_mut() { + for (k, v) in d.fields.iter().filter_map(|(k, v)| Some((k.strip_prefix("c.")?, v))) { + if v.is_null() { + o.remove(k); + } else { + o.insert(k.to_string(), v.clone()); + } + } + } + let mut parts = vec![crate::i18n::style_name(lang, based).to_string()]; + parts.extend(own.as_object().into_iter().flatten().map(|(k, v)| format!("{}: {}", setting_label(lang, k), setting_text(v)))); + ui.add(egui::Label::new(egui::RichText::new(parts.join(" + ")).color(crate::theme::Tokens::get(ui.ctx()).text_dim)).wrap()); +} + /// Character Style Options: General, then the character sections it shares with Paragraph Style /// Options. A character style sets only some attributes: the fields show those it and its Based /// On set and leave the rest blank. Edits are `c.` fields (`null` = no longer set), applied @@ -5248,46 +5405,7 @@ fn character_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo "underline" => line_options(&lang, ui, d, &cf, &doc, "underline"), "strikethrough" => line_options(&lang, ui, d, &cf, &doc, "strikethrough"), s if style_cjk::is_section(s) => style_cjk::section_ui(app, ui, d, s, &cf, None, &doc), - _ => { - egui::Grid::new("csg").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { - crate::rtl::label(ui, crate::i18n::tr(&lang, "Style Name:")); - text_field(ui, d, "rename", 220.0); - ui.end_row(); - crate::rtl::label(ui, crate::i18n::tr(&lang, "Based On:")); - egui::ComboBox::from_id_salt("csbased") - .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&lang, &based))) - .width(220.0) - .show_ui(ui, |ui| { - // Not itself, nor a style based on it. - for s in styles.character.iter().filter(|s| new || !styles.char_based_on_cycles(&name, &s.name)) { - if ui.selectable_label(s.name == based, crate::rtl::widget(ui, crate::i18n::style_name(&lang, &s.name))).clicked() { - d.fields.insert("basedOn".into(), json!(s.name)); - } - } - }); - ui.end_row(); - }); - let status = d.s("status"); - if !status.is_empty() { - crate::rtl::label(ui, egui::RichText::new(status).color(crate::theme::Tokens::get(ui.ctx()).text_strong)); - } - ui.add_space(8.0); - crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Style Settings:")).font(semibold(12.0))); - // What OK would leave the style setting, after its Based On. - let mut own = serde_json::to_value(&style.chars).unwrap_or_default(); - if let Some(o) = own.as_object_mut() { - for (k, v) in d.fields.iter().filter_map(|(k, v)| Some((k.strip_prefix("c.")?, v))) { - if v.is_null() { - o.remove(k); - } else { - o.insert(k.to_string(), v.clone()); - } - } - } - let mut parts = vec![crate::i18n::style_name(&lang, &based).to_string()]; - parts.extend(own.as_object().into_iter().flatten().map(|(k, v)| format!("{}: {}", setting_label(&lang, k), setting_text(v)))); - ui.add(egui::Label::new(egui::RichText::new(parts.join(" + ")).color(crate::theme::Tokens::get(ui.ctx()).text_dim)).wrap()); - } + _ => character_style_general(&lang, ui, d, styles, &style, &based), }); }); } @@ -5808,6 +5926,158 @@ fn check_justification(d: &Dialog, prefix: &str, current: &Value) -> Result<(), Ok(()) } +/// Paragraph attributes the Hyphenation Settings dialog sets. +pub const HYPH_ATTRS: [&str; 10] = [ + "hyphenate", + "hyphMinWord", + "hyphAfterFirst", + "hyphBeforeLast", + "hyphLimit", + "hyphZone", + "hyphWeight", + "hyphCapitalized", + "hyphLastWord", + "hyphAcrossColumn", +]; + +/// InDesign's Hyphenation Settings: Hyphenate; Words with at Least, After First and Before Last +/// (letters), Hyphen Limit (hyphens) and Hyphenation Zone; the Better Spacing ↔ Fewer Hyphens +/// slider (0–10, as InDesign's HyphenWeight); Hyphenate Capitalized Words, Last Word and Across +/// Column. Edited fields are stored as `{prefix}{key}`; the others show `current` (a mixed value +/// is null and shows blank). The Hyphenation dialog for the selected paragraphs and Paragraph +/// Style Options › Hyphenation both use it. +fn hyphenation(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, current: &Value, units: Unit) { + let tr = |s: &str| crate::i18n::tr(lang, s).to_string(); + let cur = |d: &Dialog, k: &str| d.fields.get(&format!("{prefix}{k}")).cloned().unwrap_or_else(|| current[k].clone()); + // Labels right-aligned against their fields, as InDesign's. + let label_right = |ui: &mut egui::Ui, text: &str| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add(egui::Label::new(crate::rtl::widget(ui, text)).wrap_mode(egui::TextWrapMode::Extend)) + }); + }; + let checkbox = |ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str| { + let v = cur(d, key); + // Mixed shows indeterminate and starts off, so the first click turns it on for all. + let mut on = v.as_bool().unwrap_or(false); + if ui.add(egui::Checkbox::new(&mut on, crate::rtl::widget(ui, tr(label))).indeterminate(v.is_null())).changed() { + d.fields.insert(format!("{prefix}{key}"), json!(on)); + } + }; + checkbox(ui, d, "hyphenate", "Hyphenate"); + ui.add_space(4.0); + egui::Grid::new(("hyph", prefix)).num_columns(3).spacing([8.0, 6.0]).show(ui, |ui| { + // InDesign's ranges. + for (label, key, unit, max) in [ + ("Words with at Least:", "hyphMinWord", "letters", 25.0), + ("After First:", "hyphAfterFirst", "letters", 15.0), + ("Before Last:", "hyphBeforeLast", "letters", 15.0), + ("Hyphen Limit:", "hyphLimit", "hyphens", 25.0), + ] { + label_right(ui, &tr(label)); + let min = if key == "hyphLimit" { 0.0 } else { 1.0 }; + if let Some(n) = crate::widgets::spin_number(ui, &format!("hy{prefix}{key}"), cur(d, key).as_f64(), "", 60.0, 0) { + d.fields.insert(format!("{prefix}{key}"), json!(n.round().clamp(min, max) as u64)); + } + crate::rtl::label(ui, tr(unit)); + ui.end_row(); + } + label_right(ui, &tr("Hyphenation Zone:")); + if let Some(n) = crate::widgets::spin_measure(ui, &format!("hy{prefix}zone"), cur(d, "hyphZone").as_f64(), units, 60.0) { + d.fields.insert(format!("{prefix}hyphZone"), json!(if n.is_finite() { n.clamp(0.0, 8640.0) } else { 36.0 })); + } + ui.end_row(); + }); + ui.add_space(6.0); + // Better Spacing ↔ Fewer Hyphens, in InDesign's eleven steps. + ui.horizontal(|ui| { + crate::rtl::label(ui, tr("Better Spacing")); + let w = cur(d, "hyphWeight").as_f64(); + let mut step = w.map_or(5.0, |w| (w * 10.0).round()).clamp(0.0, 10.0); + // Mixed across the selection: the slider shows dimmed, and a click or drag on it, even + // one that leaves the knob in place, sets every paragraph to that step. + let mixed = w.is_none(); + // The ticks go under the knob: their place in the paint order is taken first. + let ticks = ui.painter().add(egui::Shape::Noop); + let r = ui + .scope(|ui| { + ui.spacing_mut().slider_width = 180.0; + if mixed { + ui.multiply_opacity(0.4); + } + ui.add(egui::Slider::new(&mut step, 0.0..=10.0).step_by(1.0).show_value(false).handle_shape(egui::style::HandleShape::Circle)) + }) + .inner; + // The tick marks under the track. + let t = crate::theme::Tokens::get(ui.ctx()); + let inner = r.rect.shrink2(egui::vec2(r.rect.height() / 2.0, 0.0)); + let y = r.rect.center().y; + let marks: Vec = (0..=10) + .map(|i| { + let x = inner.left() + inner.width() * i as f32 / 10.0; + egui::Shape::line_segment([egui::pos2(x, y - 8.0), egui::pos2(x, y + 8.0)], egui::Stroke::new(1.0, t.text_dim)) + }) + .collect(); + ui.painter().set(ticks, egui::Shape::Vec(marks)); + if r.changed() || (mixed && (r.clicked() || r.drag_stopped())) { + d.fields.insert(format!("{prefix}hyphWeight"), json!(step / 10.0)); + } + crate::rtl::label(ui, tr("Fewer Hyphens")); + }); + ui.add_space(6.0); + egui::Grid::new(("hyphc", prefix)).num_columns(2).spacing([16.0, 6.0]).show(ui, |ui| { + checkbox(ui, d, "hyphCapitalized", "Hyphenate Capitalized Words"); + checkbox(ui, d, "hyphLastWord", "Hyphenate Last Word"); + ui.end_row(); + checkbox(ui, d, "hyphAcrossColumn", "Hyphenate Across Column"); + ui.end_row(); + }); +} + +/// The Hyphenation dialog's edits, as `type.para` attrs. +fn hyphenation_edits(d: &Dialog) -> Map { + HYPH_ATTRS.iter().filter_map(|k| d.fields.get(*k).map(|v| (k.to_string(), v.clone()))).collect() +} + +/// Preview on: the edits show on the page (redone when a field changes) without an undo step; +/// off, the paragraphs go back. +fn hyphenation_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); + } + return; + } + let params = json!({"attrs": hyphenation_edits(d)}); + if shown.as_ref() == Some(¶ms) || d.fields.get(PREVIEW_FAILED) == Some(¶ms) { + return; + } + if shown.is_none() + && let Err(e) = app.session.begin_interaction("Hyphenation") + { + d.fields.insert("status".into(), json!(e.to_string())); + return; + } + match app.session.preview("type.para", params.clone()) { + Ok(_) => { + d.fields.remove("status"); + d.fields.remove(PREVIEW_FAILED); + d.fields.insert(PREVIEWED.into(), params); + } + // Rejected settings: the paragraphs go back, and the reason shows until they change. + Err(e) => { + app.session.cancel_interaction(); + d.fields.remove(PREVIEWED); + d.fields.insert("status".into(), json!(e.to_string())); + d.fields.insert(PREVIEW_FAILED.into(), params); + } + } +} + +/// The hyphenation settings a preview was refused for (not tried again until they change). +const PREVIEW_FAILED: &str = "previewFailed"; + /// 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 @@ -7602,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::(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(); @@ -7633,6 +7932,146 @@ mod tests { app.run("type.selectionAttrs", json!({})).unwrap()["para"][key].clone() } + /// The hyphenation video (Graphd Tutorials, 0:39–1:13): the Paragraph panel menu's + /// Hyphenation… opens InDesign's Hyphenation Settings for the selected paragraphs. Preview + /// shows the slider moved to Fewer Hyphens on the page without an undo step, OK makes it one + /// step on the selected paragraph only, and Cancel puts it back. + #[test] + fn hyphenation_settings_preview_apply_and_cancel_on_the_selected_paragraph() { + let (mut app, story) = two_paragraphs(); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)); + let sid = designcraft_doc::StoryId(story.as_u64().unwrap()); + let weight = |app: &DesignApp, para: usize| { + let d = &app.session.doc().unwrap().doc; + d.styles.resolve_para(&d.story(sid).unwrap().paras[para]).0.hyph_weight + }; + assert!(crate::menus::menu_enabled(&app, "app.hyphenationDialog")); + app.run("app.hyphenationDialog", json!({})).unwrap(); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!( + (d.id.as_str(), d.fields["current"]["hyphWeight"].as_f64(), d.fields["current"]["hyphenate"].as_bool()), + ("hyphenation", Some(0.5), Some(true)) + ); + for label in [ + "Hyphenation Settings", + "Hyphenate", + "Words with at Least:", + "letters", + "Hyphen Limit:", + "hyphens", + "Hyphenation Zone:", + "Better Spacing", + "Fewer Hyphens", + "Hyphenate Capitalized Words", + "Hyphenate Last Word", + "Hyphenate Across Column", + "Preview", + ] { + assert!(labels.iter().any(|(t, _, _)| t == label), "{label}: {labels:?}"); + } + // Fewer Hyphens (9 of 10) with Preview: on the page, no undo step. + let before = undo_steps(&app); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("hyphWeight".into(), json!(0.9)); + d.fields.insert("preview".into(), json!(true)); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert_eq!(weight(&app, 0), 0.9, "previewed"); + assert_eq!(undo_steps(&app), before, "a preview is no step"); + // Cancel: back as it was. + cancel(&mut app); + assert_eq!(weight(&app, 0), 0.5); + // Again, and OK: one step, the selected paragraph only. + app.run("app.hyphenationDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("hyphWeight".into(), json!(0.9)); + d.fields.insert("preview".into(), json!(true)); + dialog_frame(&mut app, &ctx, screen, vec![]); + confirm(&mut app).unwrap(); + assert_eq!((weight(&app, 0), weight(&app, 1)), (0.9, 0.5)); + assert_eq!(undo_steps(&app), before + 1, "one undo step"); + // Paragraph Style Options › Hyphenation has the same form. + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": designcraft_doc::story::BASIC_PARAGRAPH, "section": "hyph"}))); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + for label in ["Hyphenation Zone:", "Better Spacing", "Fewer Hyphens", "Hyphenate Last Word", "Hyphenate Across Column"] { + assert!(labels.iter().any(|(t, _, _)| t == label), "style options: {label}"); + } + app.ui.dialog = None; + app.run("edit.deselectAll", json!({})).unwrap(); + assert!(!crate::menus::menu_enabled(&app, "app.hyphenationDialog"), "no paragraph"); + } + + /// Hyphenate differs across the selection: it shows mixed, and the first click turns it on for + /// all. Settings the command refuses show why: a preview goes back and isn't retried until they + /// change, and OK keeps the dialog open. + /// A mixed Better Spacing ↔ Fewer Hyphens slider: a click on its middle step sets every + /// selected paragraph to it, though the knob already sat there. + #[test] + fn hyphenation_settings_mixed_slider_click_sets_the_step() { + let (mut app, story) = two_paragraphs(); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)); + app.run("type.para", json!({"attrs": {"hyphWeight": 0.2}})).unwrap(); + app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap(); + app.run("app.hyphenationDialog", json!({})).unwrap(); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let rect = |l: &str| labels.iter().find(|(t, _, _)| t == l).map(|(_, r, _)| *r).unwrap(); + let (better, fewer) = (rect("Better Spacing"), rect("Fewer Hyphens")); + click_dialog(&mut app, &ctx, screen, egui::pos2((better.right() + fewer.left()) / 2.0, better.center().y)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("hyphWeight"), Some(&json!(0.5))); + } + + #[test] + fn hyphenation_settings_mixed_checkbox_and_refused_settings() { + let (mut app, story) = two_paragraphs(); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)); + app.run("type.para", json!({"attrs": {"hyphenate": false}})).unwrap(); + app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap(); + app.run("app.hyphenationDialog", json!({})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().fields["current"]["hyphenate"].is_null(), "mixed"); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let at = labels.iter().find(|(t, _, _)| t == "Hyphenate").map(|(_, r, _)| r.left_center() - egui::vec2(10.0, 0.0)).unwrap(); + click_dialog(&mut app, &ctx, screen, at); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("hyphenate"), Some(&json!(true)), "the first click turns it on"); + // A refused setting (as a control-channel caller could send it): no preview, the reason. + let before = undo_steps(&app); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("hyphWeight".into(), json!("heavy")); + d.fields.insert("preview".into(), json!(true)); + dialog_frame(&mut app, &ctx, screen, vec![]); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!d.fields.contains_key(PREVIEWED) && d.fields.contains_key("status"), "{:?}", d.fields); + assert!(app.session.doc().unwrap().interaction.is_none(), "the preview went back"); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert!(app.session.doc().unwrap().interaction.is_none(), "not tried again"); + // OK with it: an error, and the dialog stays open with the reason. + assert!(confirm(&mut app).is_err()); + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert!(d.fields.contains_key("status")); + assert_eq!(undo_steps(&app), before); + // Corrected, it previews and applies. + app.ui.dialog.as_mut().unwrap().fields.insert("hyphWeight".into(), json!(0.9)); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("status")); + confirm(&mut app).unwrap(); + assert_eq!(para_attr(&mut app, &story, 0, "hyphenate"), true); + assert_eq!(para_attr(&mut app, &story, 4, "hyphWeight"), 0.9); + } + #[test] fn justification_dialog_applies_to_a_local_paragraph_and_cancel_changes_nothing() { let (mut app, story) = two_paragraphs(); @@ -7975,6 +8414,35 @@ mod tests { assert_eq!((opts(&app).columns_kind, opts(&app).column_width), (designcraft_doc::ColumnsKind::FixedNumber, 120.0)); } + #[test] + fn text_frame_options_set_a_custom_baseline_grid_relative_to() { + use designcraft_doc::{FrameBaselineGrid, FrameGridRelative}; + 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()); + let grid = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.baseline_grid; + let open = |app: &mut DesignApp, fields: &[(&str, Value)]| { + let mut d = Dialog::new("textFrameOptions", json!({})); + 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) + }; + app.run("selection.set", json!({"ids": [id.0]})).unwrap(); + // Turned on, the grid takes the shown start and increment (the document grid's: 3p0 and 1p0). + open(&mut app, &[("customGrid", json!(true)), ("gridRelativeTo", json!("frame"))]).unwrap(); + assert_eq!(grid(&app), Some(FrameBaselineGrid { start: 36.0, increment: 12.0, relative_to: FrameGridRelative::TopOfFrame })); + // The dialog shows the frame's grid; changing Relative To keeps its start and increment. + open(&mut app, &[("gridStart", json!("0p10"))]).unwrap(); + open(&mut app, &[("gridRelativeTo", json!("inset"))]).unwrap(); + assert_eq!(grid(&app), Some(FrameBaselineGrid { start: 10.0, increment: 12.0, relative_to: FrameGridRelative::TopInset })); + open(&mut app, &[("customGrid", json!(false))]).unwrap(); + assert_eq!(grid(&app), None); + } + #[test] fn text_frame_options_change_only_what_was_edited() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); @@ -9330,6 +9798,31 @@ mod tests { assert_eq!(st.doc.styles.para(&name).unwrap().para.align, Some(designcraft_doc::Align::Center)); } + #[test] + fn paragraph_style_options_align_to_grid_shows_and_sets_the_style_grid_alignment() { + use designcraft_doc::GridAlign; + use egui_kittest::kittest::Queryable; + let mut app = test_app(); + app.session.execute("style.paragraph.create", &json!({"name": "Grid Body", "para": {"gridAlign": "firstLineOnly"}})).unwrap(); + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Grid Body", "section": "indents"}))); + let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); + let grid = |h: &egui_kittest::Harness<'static, crate::test_window::Window>| { + h.state().app.session.active().unwrap().doc.styles.para("Grid Body").unwrap().para.grid_align + }; + h.run_steps(4); + h.get_by_value("First Line Only"); + confirm(&mut h.state_mut().app).unwrap(); + assert_eq!(grid(&h), Some(GridAlign::FirstLineOnly), "OK without edits keeps the style's alignment"); + h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Grid Body", "section": "indents"}))); + h.run_steps(4); + h.get_by_value("First Line Only").click(); + h.run_steps(3); + h.get_by_label("All Lines").click(); + h.run_steps(3); + confirm(&mut h.state_mut().app).unwrap(); + assert_eq!(grid(&h), Some(GridAlign::AllLines)); + } + #[test] fn delete_paragraph_style_dialog_removes_the_style_and_reassigns_text() { let mut app = test_app(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 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/i18n.rs b/crates/ui-egui/src/i18n.rs index be5f43c97..e74cc0f73 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -46,6 +46,71 @@ pub fn picker_languages() -> Vec<(&'static str, &'static str)> { /// English → [German, French, Spanish, Japanese, Simplified Chinese]. const TABLE: &[(&str, [&str; 5])] = &[ + ( + "Character Formatting Controls", + [ + "Steuerelemente für Zeichenformatierung", + "Commandes de mise en forme des caractères", + "Controles de formato de carácter", + "文字形式コントロール", + "字符格式控制", + ], + ), + ( + "Paragraph Formatting Controls", + [ + "Steuerelemente für Absatzformatierung", + "Commandes de mise en forme des paragraphes", + "Controles de formato de párrafo", + "段落形式コントロール", + "段落格式控制", + ], + ), + ("Font Size", ["Schriftgrad", "Corps", "Tamaño de fuente", "フォントサイズ", "字体大小"]), + ("Vertical Scale", ["Vertikal skalieren", "Échelle verticale", "Escala vertical", "垂直比率", "垂直缩放"]), + ("Horizontal Scale", ["Horizontal skalieren", "Échelle horizontale", "Escala horizontal", "水平比率", "水平缩放"]), + ("Baseline Shift", ["Grundlinienversatz", "Décalage vertical", "Desplazamiento vertical", "ベースラインシフト", "基线偏移"]), + ( + "Skew (False Italic)", + ["Verzerren (falscher Kursivstil)", "Inclinaison (faux italique)", "Sesgar (cursiva falsa)", "歪み(斜体)", "倾斜(伪斜体)"], + ), + ("Left Indent", ["Einzug links", "Retrait gauche", "Sangría izquierda", "左インデント", "左缩进"]), + ("Right Indent", ["Einzug rechts", "Retrait droit", "Sangría derecha", "右インデント", "右缩进"]), + ( + "First Line Left Indent", + ["Einzug links in erster Zeile", "Retrait gauche de première ligne", "Sangría izquierda en primera línea", "1行目左インデント", "首行左缩进"], + ), + ( + "Last Line Right Indent", + ["Einzug rechts in letzter Zeile", "Retrait droit de dernière ligne", "Sangría derecha en última línea", "最終行右インデント", "末行右缩进"], + ), + ( + "Drop Cap Number of Lines", + ["Initiale: Anzahl der Zeilen", "Lettrine (nombre de lignes)", "Capitular: número de líneas", "ドロップキャップの行数", "首字下沉行数"], + ), + ( + "Drop Cap One or More Characters", + [ + "Initiale: ein oder mehrere Zeichen", + "Lettrine (un ou plusieurs caractères)", + "Capitular: uno o más caracteres", + "ドロップキャップの文字数", + "首字下沉一个或多个字符", + ], + ), + ( + "Align to Baseline Grid", + [ + "An Grundlinienraster ausrichten", + "Aligner sur la grille de ligne de base", + "Alinear con cuadrícula base", + "ベースライングリッドに揃える", + "对齐基线网格", + ], + ), + // Properties › Paragraph (•••). + ("Space Before", ["Abstand davor", "Espace avant", "Espacio anterior", "段落前の間隔", "段前间距"]), + ("Space After", ["Abstand danach", "Espace après", "Espacio posterior", "段落後の間隔", "段后间距"]), // Menus. ("File", ["Datei", "Fichier", "Archivo", "ファイル", "文件"]), ("Edit", ["Bearbeiten", "Édition", "Edición", "編集", "编辑"]), @@ -1010,6 +1075,102 @@ const TABLE: &[(&str, [&str; 5])] = &[ ], ), ("Load Styles", ["Formate laden", "Charger les styles", "Cargar estilos", "スタイルを読み込み", "加载样式"]), + ("Restart Numbering", ["Nummerierung neu beginnen", "Recommencer la numérotation", "Reiniciar numeración", "番号の振り直し", "重新开始编号"]), + ("Continue Numbering", ["Nummerierung fortführen", "Poursuivre la numérotation", "Continuar numeración", "番号の継続", "继续编号"]), + ("Keep Options…", ["Umbruchoptionen …", "Options d'enchaînement…", "Opciones de separación…", "段落分離禁止オプション…", "保持选项…"]), + ( + "Space Between Paragraphs Using Same Style", + [ + "Abstand zwischen Absätzen mit gleichem Format", + "Espace entre les paragraphes de même style", + "Espacio entre párrafos con el mismo estilo", + "同じスタイルの段落間のスペース", + "使用相同样式的段落间距", + ], + ), + ("Ignore", ["Ignorieren", "Ignorer", "Ignorar", "無視", "忽略"]), + ( + "Do Not Align to Baseline Grid", + [ + "Nicht am Grundlinienraster ausrichten", + "Ne pas aligner sur la grille de ligne de base", + "No alinear con cuadrícula base", + "ベースライングリッドに揃えない", + "不对齐基线网格", + ], + ), + ( + "Only Align First Line to Grid", + [ + "Nur erste Zeile am Raster ausrichten", + "Aligner uniquement la première ligne sur la grille", + "Alinear solo primera línea con cuadrícula", + "最初の行のみグリッドに揃える", + "仅首行对齐网格", + ], + ), + ( + "Balance Ragged Lines", + ["Unausgeglichene Zeilen ausgleichen", "Équilibrer les lignes irrégulières", "Equilibrar líneas desiguales", "行末を調整", "平衡未对齐的行"], + ), + ( + "Drop Caps and Nested Styles…", + [ + "Initialen und verschachtelte Formate …", + "Lettrines et styles imbriqués…", + "Capitulares y estilos anidados…", + "ドロップキャップと先頭文字スタイル…", + "首字下沉和嵌套样式…", + ], + ), + ("GREP Styles…", ["GREP-Stile …", "Styles GREP…", "Estilos GREP…", "正規表現スタイル…", "GREP 样式…"]), + ( + "Restart/Continue Numbering", + [ + "Nummerierung neu beginnen/fortführen", + "Recommencer/Poursuivre la numérotation", + "Reiniciar/Continuar numeración", + "番号の振り直し/継続", + "重新开始/继续编号", + ], + ), + ( + "Convert Bullets and Numbering to Text", + [ + "Aufzählungszeichen und Nummerierung in Text konvertieren", + "Convertir les puces et la numérotation en texte", + "Convertir viñetas y numeración en texto", + "箇条書きと段落番号をテキストに変換", + "将项目符号和编号转换为文本", + ], + ), + ("Hyphenation…", ["Silbentrennung …", "Césure…", "Separación por sílabas…", "ハイフネーション…", "连字…"]), + ( + "Hyphenation Settings", + ["Silbentrennungseinstellungen", "Paramètres de césure", "Configuración de separación por sílabas", "ハイフネーション設定", "连字设置"], + ), + ("hyphens", ["Trennstriche", "tirets", "guiones", "ハイフン", "连字符"]), + ("Hyphenation Zone:", ["Silbentrennungsbereich:", "Zone de césure :", "Zona de separación:", "ハイフネーション領域 :", "连字区:"]), + ("Better Spacing", ["Bessere Abstände", "Meilleur espacement", "Mejor espaciado", "スペースを優先", "更好的间距"]), + ("Fewer Hyphens", ["Weniger Trennstriche", "Moins de tirets", "Menos guiones", "ハイフンを減らす", "更少的连字符"]), + ( + "Hyphenate Capitalized Words", + [ + "Großgeschriebene Wörter trennen", + "Césure des mots en capitales", + "Separar palabras en mayúscula", + "大文字で始まる単語をハイフネーション", + "连字大写的单词", + ], + ), + ( + "Hyphenate Last Word", + ["Letztes Wort trennen", "Césure du dernier mot", "Separar última palabra", "最後の単語をハイフネーション", "连字最后一个单词"], + ), + ( + "Hyphenate Across Column", + ["Über Spalten trennen", "Césure entre colonnes", "Separar entre columnas", "段をまたいでハイフネーション", "跨栏连字"], + ), ( "Differs from this document", ["Weicht von diesem Dokument ab", "Diffère de ce document", "Difiere de este documento", "このドキュメントと異なります", "与此文档不同"], @@ -1648,6 +1809,8 @@ const TABLE: &[(&str, [&str; 5])] = &[ ], ), ("Define Lists…", ["Define Lists…", "Définir des listes…", "Define Lists…", "Define Lists…", "定义列表…"]), + ("Apply Bullets", ["Aufzählungszeichen anwenden", "Appliquer des puces", "Aplicar viñetas", "箇条書きを適用", "应用项目符号"]), + ("Apply Numbers", ["Nummerierung anwenden", "Appliquer la numérotation", "Aplicar números", "段落番号を適用", "应用编号"]), ( "Define Text Variable…", ["Define Text Variable…", "Définir une variable de texte…", "Define Text Variable…", "Define Text Variable…", "定义文本变量…"], @@ -4465,18 +4628,18 @@ pub fn tr<'a>(lang: &str, s: &'a str) -> &'a str { } fn lookup<'a>(lang: &str, s: &'a str) -> &'a str { - static GERMAN: OnceLock> = OnceLock::new(); - static JAPANESE: OnceLock> = OnceLock::new(); - static TRANSLATIONS: OnceLock> = OnceLock::new(); - static ARABIC: OnceLock> = OnceLock::new(); - static UKRAINIAN: OnceLock> = OnceLock::new(); - static PORTUGUESE_BR: OnceLock> = OnceLock::new(); - static ITALIAN: OnceLock> = OnceLock::new(); - static POLISH: OnceLock> = OnceLock::new(); - static RUSSIAN: OnceLock> = OnceLock::new(); - static CZECH: OnceLock> = OnceLock::new(); - static FRENCH: OnceLock> = OnceLock::new(); - static GEORGIAN: OnceLock> = OnceLock::new(); + static GERMAN: OnceLock> = OnceLock::new(); + static JAPANESE: OnceLock> = OnceLock::new(); + static TRANSLATIONS: OnceLock> = OnceLock::new(); + static ARABIC: OnceLock> = OnceLock::new(); + static UKRAINIAN: OnceLock> = OnceLock::new(); + static PORTUGUESE_BR: OnceLock> = OnceLock::new(); + static ITALIAN: OnceLock> = OnceLock::new(); + static POLISH: OnceLock> = OnceLock::new(); + static RUSSIAN: OnceLock> = OnceLock::new(); + static CZECH: OnceLock> = OnceLock::new(); + static FRENCH: OnceLock> = OnceLock::new(); + static GEORGIAN: OnceLock> = OnceLock::new(); if lang == "ar" { return ARABIC.get_or_init(|| ar::TABLE.iter().copied().collect()).get(s).copied().unwrap_or(s); } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 31f7fb70d..49fd3046e 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -30,6 +30,43 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "قص"), ("Copy", "نسخ"), ("Paste", "لصق"), + ("Restart Numbering", "إعادة الترقيم"), + ("Continue Numbering", "متابعة الترقيم"), + ("Keep Options…", "خيارات الإبقاء…"), + ("Space Between Paragraphs Using Same Style", "المسافة بين الفقرات ذات النمط نفسه"), + ("Ignore", "تجاهل"), + ("Do Not Align to Baseline Grid", "عدم المحاذاة إلى شبكة خط الأساس"), + ("Only Align First Line to Grid", "محاذاة السطر الأول فقط إلى الشبكة"), + ("Balance Ragged Lines", "موازنة الأسطر غير المتساوية"), + ("Drop Caps and Nested Styles…", "الأحرف الاستهلالية والأنماط المتداخلة…"), + ("GREP Styles…", "أنماط GREP…"), + ("Restart/Continue Numbering", "إعادة/متابعة الترقيم"), + ("Convert Bullets and Numbering to Text", "تحويل التعداد النقطي والترقيم إلى نص"), + ("Hyphenation…", "الواصلة…"), + ("Hyphenation Settings", "إعدادات الواصلة"), + ("hyphens", "واصلات"), + ("Hyphenation Zone:", "منطقة الواصلة:"), + ("Better Spacing", "تباعد أفضل"), + ("Fewer Hyphens", "واصلات أقل"), + ("Hyphenate Capitalized Words", "وصل الكلمات ذات الأحرف الكبيرة"), + ("Hyphenate Last Word", "وصل الكلمة الأخيرة"), + ("Hyphenate Across Column", "الوصل عبر الأعمدة"), + ("Character Formatting Controls", "عناصر تحكم تنسيق الأحرف"), + ("Paragraph Formatting Controls", "عناصر تحكم تنسيق الفقرات"), + ("Font Size", "حجم الخط"), + ("Vertical Scale", "المقياس الرأسي"), + ("Horizontal Scale", "المقياس الأفقي"), + ("Baseline Shift", "إزاحة خط الأساس"), + ("Skew (False Italic)", "إمالة (مائل زائف)"), + ("Left Indent", "مسافة بادئة يسرى"), + ("Right Indent", "مسافة بادئة يمنى"), + ("First Line Left Indent", "مسافة بادئة يسرى للسطر الأول"), + ("Last Line Right Indent", "مسافة بادئة يمنى للسطر الأخير"), + ("Drop Cap Number of Lines", "عدد أسطر الحرف الاستهلالي"), + ("Drop Cap One or More Characters", "حرف استهلالي واحد أو أكثر"), + ("Align to Baseline Grid", "محاذاة إلى شبكة خط الأساس"), + ("Apply Bullets", "تطبيق التعداد النقطي"), + ("Apply Numbers", "تطبيق الترقيم"), ("Paste Vector Art", "لصق رسم متجه"), ("Baseline Options", "خيارات خط الأساس"), ("Fixed Number", "عدد ثابت"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 4d41c30dc..6f47fdaff 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -31,6 +31,43 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Vyjmout"), ("Copy", "Kopírovat"), ("Paste", "Vložit"), + ("Restart Numbering", "Začít číslování znovu"), + ("Continue Numbering", "Pokračovat v číslování"), + ("Keep Options…", "Volby zachování…"), + ("Space Between Paragraphs Using Same Style", "Mezera mezi odstavci se stejným stylem"), + ("Ignore", "Ignorovat"), + ("Do Not Align to Baseline Grid", "Nezarovnávat na mřížku účaří"), + ("Only Align First Line to Grid", "Zarovnat na mřížku jen první řádek"), + ("Balance Ragged Lines", "Vyrovnat nezarovnané řádky"), + ("Drop Caps and Nested Styles…", "Iniciály a vnořené styly…"), + ("GREP Styles…", "Styly GREP…"), + ("Restart/Continue Numbering", "Začít znovu/pokračovat v číslování"), + ("Convert Bullets and Numbering to Text", "Převést odrážky a číslování na text"), + ("Hyphenation…", "Dělení slov…"), + ("Hyphenation Settings", "Nastavení dělení slov"), + ("hyphens", "spojovníky"), + ("Hyphenation Zone:", "Zóna dělení:"), + ("Better Spacing", "Lepší mezery"), + ("Fewer Hyphens", "Méně spojovníků"), + ("Hyphenate Capitalized Words", "Dělit slova s velkým počátečním písmenem"), + ("Hyphenate Last Word", "Dělit poslední slovo"), + ("Hyphenate Across Column", "Dělit přes sloupce"), + ("Character Formatting Controls", "Ovládací prvky formátování znaků"), + ("Paragraph Formatting Controls", "Ovládací prvky formátování odstavců"), + ("Font Size", "Velikost písma"), + ("Vertical Scale", "Svislá změna velikosti"), + ("Horizontal Scale", "Vodorovná změna velikosti"), + ("Baseline Shift", "Posun účaří"), + ("Skew (False Italic)", "Zkosení (nepravá kurzíva)"), + ("Left Indent", "Odsazení zleva"), + ("Right Indent", "Odsazení zprava"), + ("First Line Left Indent", "Odsazení prvního řádku zleva"), + ("Last Line Right Indent", "Odsazení posledního řádku zprava"), + ("Drop Cap Number of Lines", "Počet řádků iniciály"), + ("Drop Cap One or More Characters", "Iniciála: jeden nebo více znaků"), + ("Align to Baseline Grid", "Zarovnat na mřížku účaří"), + ("Apply Bullets", "Použít odrážky"), + ("Apply Numbers", "Použít číslování"), ("Reverse Path", "Obrátit cestu"), ("Set Anchor", "Nastavit kotvu"), ("Clear", "Vymazat"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 367ca52f8..97b48316b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -31,6 +31,29 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Ausschneiden"), ("Copy", "Kopieren"), ("Paste", "Einfügen"), + ("Restart Numbering", "Nummerierung neu beginnen"), + ("Continue Numbering", "Nummerierung fortführen"), + ("Keep Options…", "Umbruchoptionen …"), + ("Space Between Paragraphs Using Same Style", "Abstand zwischen Absätzen mit gleichem Format"), + ("Ignore", "Ignorieren"), + ("Do Not Align to Baseline Grid", "Nicht am Grundlinienraster ausrichten"), + ("Only Align First Line to Grid", "Nur erste Zeile am Raster ausrichten"), + ("Balance Ragged Lines", "Unausgeglichene Zeilen ausgleichen"), + ("Drop Caps and Nested Styles…", "Initialen und verschachtelte Formate …"), + ("GREP Styles…", "GREP-Stile …"), + ("Restart/Continue Numbering", "Nummerierung neu beginnen/fortführen"), + ("Convert Bullets and Numbering to Text", "Aufzählungszeichen und Nummerierung in Text konvertieren"), + ("Hyphenation…", "Silbentrennung …"), + ("Hyphenation Settings", "Silbentrennungseinstellungen"), + ("hyphens", "Trennstriche"), + ("Hyphenation Zone:", "Silbentrennungsbereich:"), + ("Better Spacing", "Bessere Abstände"), + ("Fewer Hyphens", "Weniger Trennstriche"), + ("Hyphenate Capitalized Words", "Großgeschriebene Wörter trennen"), + ("Hyphenate Last Word", "Letztes Wort trennen"), + ("Hyphenate Across Column", "Über Spalten trennen"), + ("Apply Bullets", "Aufzählungszeichen anwenden"), + ("Apply Numbers", "Nummerierung anwenden"), ("Inches Decimal", "Zoll dezimal"), ("Back", "Zurück"), ("Warning", "Warnung"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 681230d84..d19a5b56e 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -337,8 +337,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Sixth Space", "Sixième d'espace"), ("Smart Guide Options", "Options des repères commentés"), ("Smooth Tool", "Outil Lissage"), - ("Space After", "Espace après"), - ("Space Before", "Espace avant"), ("Start Page #", "N° de la première page"), ("Step and Repeat", "Exécuter et répéter"), ("Stop Preview", "Arrêter l'aperçu"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 755272fe5..4a3656699 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -28,6 +28,43 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Taglia"), ("Copy", "Copia"), ("Paste", "Incolla"), + ("Restart Numbering", "Riavvia numerazione"), + ("Continue Numbering", "Continua numerazione"), + ("Keep Options…", "Opzioni di separazione…"), + ("Space Between Paragraphs Using Same Style", "Spazio tra paragrafi con lo stesso stile"), + ("Ignore", "Ignora"), + ("Do Not Align to Baseline Grid", "Non allineare alla griglia linee di base"), + ("Only Align First Line to Grid", "Allinea solo la prima riga alla griglia"), + ("Balance Ragged Lines", "Bilancia righe irregolari"), + ("Drop Caps and Nested Styles…", "Capilettera e stili nidificati…"), + ("GREP Styles…", "Stili GREP…"), + ("Restart/Continue Numbering", "Riavvia/continua numerazione"), + ("Convert Bullets and Numbering to Text", "Converti elenchi puntati e numerati in testo"), + ("Hyphenation…", "Sillabazione…"), + ("Hyphenation Settings", "Impostazioni sillabazione"), + ("hyphens", "trattini"), + ("Hyphenation Zone:", "Area di sillabazione:"), + ("Better Spacing", "Spaziatura migliore"), + ("Fewer Hyphens", "Meno trattini"), + ("Hyphenate Capitalized Words", "Sillaba parole con iniziale maiuscola"), + ("Hyphenate Last Word", "Sillaba ultima parola"), + ("Hyphenate Across Column", "Sillaba tra colonne"), + ("Character Formatting Controls", "Controlli di formattazione carattere"), + ("Paragraph Formatting Controls", "Controlli di formattazione paragrafo"), + ("Font Size", "Dimensione font"), + ("Vertical Scale", "Scala verticale"), + ("Horizontal Scale", "Scala orizzontale"), + ("Baseline Shift", "Spostamento linea di base"), + ("Skew (False Italic)", "Inclinazione (falso corsivo)"), + ("Left Indent", "Rientro sinistro"), + ("Right Indent", "Rientro destro"), + ("First Line Left Indent", "Rientro sinistro prima riga"), + ("Last Line Right Indent", "Rientro destro ultima riga"), + ("Drop Cap Number of Lines", "Capolettera: numero di righe"), + ("Drop Cap One or More Characters", "Capolettera: uno o più caratteri"), + ("Align to Baseline Grid", "Allinea alla griglia di base"), + ("Apply Bullets", "Applica punti elenco"), + ("Apply Numbers", "Applica numeri"), ("Paste Vector Art", "Incolla grafica vettoriale"), ("Baseline Options", "Opzioni linea di base"), ("Fixed Number", "Numero fisso"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 37b14ac5c..6180858af 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -30,6 +30,29 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "カット"), ("Copy", "コピー"), ("Paste", "ペースト"), + ("Restart Numbering", "番号の振り直し"), + ("Continue Numbering", "番号の継続"), + ("Keep Options…", "段落分離禁止オプション…"), + ("Space Between Paragraphs Using Same Style", "同じスタイルの段落間のスペース"), + ("Ignore", "無視"), + ("Do Not Align to Baseline Grid", "ベースライングリッドに揃えない"), + ("Only Align First Line to Grid", "最初の行のみグリッドに揃える"), + ("Balance Ragged Lines", "行末を調整"), + ("Drop Caps and Nested Styles…", "ドロップキャップと先頭文字スタイル…"), + ("GREP Styles…", "正規表現スタイル…"), + ("Restart/Continue Numbering", "番号の振り直し/継続"), + ("Convert Bullets and Numbering to Text", "箇条書きと段落番号をテキストに変換"), + ("Hyphenation…", "ハイフネーション…"), + ("Hyphenation Settings", "ハイフネーション設定"), + ("hyphens", "ハイフン"), + ("Hyphenation Zone:", "ハイフネーション領域 :"), + ("Better Spacing", "スペースを優先"), + ("Fewer Hyphens", "ハイフンを減らす"), + ("Hyphenate Capitalized Words", "大文字で始まる単語をハイフネーション"), + ("Hyphenate Last Word", "最後の単語をハイフネーション"), + ("Hyphenate Across Column", "段をまたいでハイフネーション"), + ("Apply Bullets", "箇条書きを適用"), + ("Apply Numbers", "段落番号を適用"), ("Paste Vector Art", "ベクトルアートをペースト"), ("Baseline Options", "ベースラインオプション"), ("Column Rules", "段落境界線"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index 0300b62d7..4767b6c30 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -31,6 +31,43 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "ამოჭრა"), ("Copy", "კოპირება"), ("Paste", "ჩასმა"), + ("Restart Numbering", "ნუმერაციის თავიდან დაწყება"), + ("Continue Numbering", "ნუმერაციის გაგრძელება"), + ("Keep Options…", "შენარჩუნების პარამეტრები…"), + ("Space Between Paragraphs Using Same Style", "დაშორება ერთი სტილის აბზაცებს შორის"), + ("Ignore", "უგულებელყოფა"), + ("Do Not Align to Baseline Grid", "საბაზისო ბადეზე არ გასწორდეს"), + ("Only Align First Line to Grid", "ბადეზე მხოლოდ პირველი ხაზის გასწორება"), + ("Balance Ragged Lines", "უსწორმასწორო ხაზების დაბალანსება"), + ("Drop Caps and Nested Styles…", "საწყისი ასოები და ჩადგმული სტილები…"), + ("GREP Styles…", "GREP სტილები…"), + ("Restart/Continue Numbering", "ნუმერაციის თავიდან დაწყება/გაგრძელება"), + ("Convert Bullets and Numbering to Text", "მარკერებისა და ნუმერაციის ტექსტად გარდაქმნა"), + ("Hyphenation…", "დამარცვლა…"), + ("Hyphenation Settings", "დამარცვლის პარამეტრები"), + ("hyphens", "დეფისი"), + ("Hyphenation Zone:", "დამარცვლის ზონა:"), + ("Better Spacing", "უკეთესი დაშორება"), + ("Fewer Hyphens", "ნაკლები დეფისი"), + ("Hyphenate Capitalized Words", "მთავრული სიტყვების დამარცვლა"), + ("Hyphenate Last Word", "ბოლო სიტყვის დამარცვლა"), + ("Hyphenate Across Column", "სვეტებს შორის დამარცვლა"), + ("Character Formatting Controls", "სიმბოლოების ფორმატირების მართვა"), + ("Paragraph Formatting Controls", "აბზაცების ფორმატირების მართვა"), + ("Font Size", "შრიფტის ზომა"), + ("Vertical Scale", "ვერტიკალური მასშტაბი"), + ("Horizontal Scale", "ჰორიზონტალური მასშტაბი"), + ("Baseline Shift", "საბაზო ხაზის წანაცვლება"), + ("Skew (False Italic)", "დახრა (ცრუ კურსივი)"), + ("Left Indent", "მარცხენა შეწევა"), + ("Right Indent", "მარჯვენა შეწევა"), + ("First Line Left Indent", "პირველი სტრიქონის მარცხენა შეწევა"), + ("Last Line Right Indent", "ბოლო სტრიქონის მარჯვენა შეწევა"), + ("Drop Cap Number of Lines", "ინიციალის სტრიქონების რაოდენობა"), + ("Drop Cap One or More Characters", "ინიციალი: ერთი ან მეტი სიმბოლო"), + ("Align to Baseline Grid", "საბაზო ბადეზე სწორება"), + ("Apply Bullets", "მარკერების გამოყენება"), + ("Apply Numbers", "ნუმერაციის გამოყენება"), ("Inches Decimal", "ინჩები (ათობითი)"), ("Back", "უკან"), ("Warning", "გაფრთხილება"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 7d1d12c67..bf0c7600b 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -29,6 +29,43 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Wytnij"), ("Copy", "Kopiuj"), ("Paste", "Wklej"), + ("Restart Numbering", "Zacznij numerowanie od nowa"), + ("Continue Numbering", "Kontynuuj numerowanie"), + ("Keep Options…", "Opcje utrzymywania…"), + ("Space Between Paragraphs Using Same Style", "Odstęp między akapitami o tym samym stylu"), + ("Ignore", "Ignoruj"), + ("Do Not Align to Baseline Grid", "Nie wyrównuj do siatki linii bazowych"), + ("Only Align First Line to Grid", "Wyrównaj do siatki tylko pierwszy wiersz"), + ("Balance Ragged Lines", "Wyrównaj nierówne wiersze"), + ("Drop Caps and Nested Styles…", "Inicjały i style zagnieżdżone…"), + ("GREP Styles…", "Style GREP…"), + ("Restart/Continue Numbering", "Zacznij od nowa/kontynuuj numerowanie"), + ("Convert Bullets and Numbering to Text", "Konwertuj wypunktowanie i numerowanie na tekst"), + ("Hyphenation…", "Dzielenie wyrazów…"), + ("Hyphenation Settings", "Ustawienia dzielenia wyrazów"), + ("hyphens", "dywizy"), + ("Hyphenation Zone:", "Strefa dzielenia:"), + ("Better Spacing", "Lepsze odstępy"), + ("Fewer Hyphens", "Mniej dywizów"), + ("Hyphenate Capitalized Words", "Dziel wyrazy pisane wielką literą"), + ("Hyphenate Last Word", "Dziel ostatni wyraz"), + ("Hyphenate Across Column", "Dziel między łamami"), + ("Character Formatting Controls", "Elementy formatowania znaków"), + ("Paragraph Formatting Controls", "Elementy formatowania akapitów"), + ("Font Size", "Rozmiar czcionki"), + ("Vertical Scale", "Skala pionowa"), + ("Horizontal Scale", "Skala pozioma"), + ("Baseline Shift", "Przesunięcie linii bazowej"), + ("Skew (False Italic)", "Pochylenie (fałszywa kursywa)"), + ("Left Indent", "Wcięcie z lewej"), + ("Right Indent", "Wcięcie z prawej"), + ("First Line Left Indent", "Wcięcie pierwszego wiersza z lewej"), + ("Last Line Right Indent", "Wcięcie ostatniego wiersza z prawej"), + ("Drop Cap Number of Lines", "Inicjał: liczba wierszy"), + ("Drop Cap One or More Characters", "Inicjał: jeden lub więcej znaków"), + ("Align to Baseline Grid", "Wyrównaj do siatki linii bazowych"), + ("Apply Bullets", "Zastosuj wypunktowanie"), + ("Apply Numbers", "Zastosuj numerowanie"), ("Clear", "Wyczyść"), ("Duplicate", "Powiel"), ("Select All", "Zaznacz wszystko"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index f552e9a63..59c4f2e23 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -31,6 +31,43 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Recortar"), ("Copy", "Copiar"), ("Paste", "Colar"), + ("Restart Numbering", "Reiniciar numeração"), + ("Continue Numbering", "Continuar numeração"), + ("Keep Options…", "Opções de manutenção…"), + ("Space Between Paragraphs Using Same Style", "Espaço entre parágrafos com o mesmo estilo"), + ("Ignore", "Ignorar"), + ("Do Not Align to Baseline Grid", "Não alinhar à grade de linha de base"), + ("Only Align First Line to Grid", "Alinhar somente a primeira linha à grade"), + ("Balance Ragged Lines", "Equilibrar linhas irregulares"), + ("Drop Caps and Nested Styles…", "Capitulares e estilos aninhados…"), + ("GREP Styles…", "Estilos GREP…"), + ("Restart/Continue Numbering", "Reiniciar/continuar numeração"), + ("Convert Bullets and Numbering to Text", "Converter marcadores e numeração em texto"), + ("Hyphenation…", "Hifenização…"), + ("Hyphenation Settings", "Configurações de hifenização"), + ("hyphens", "hifens"), + ("Hyphenation Zone:", "Zona de hifenização:"), + ("Better Spacing", "Melhor espaçamento"), + ("Fewer Hyphens", "Menos hifens"), + ("Hyphenate Capitalized Words", "Hifenizar palavras iniciadas por maiúscula"), + ("Hyphenate Last Word", "Hifenizar última palavra"), + ("Hyphenate Across Column", "Hifenizar entre colunas"), + ("Character Formatting Controls", "Controles de formatação de caracteres"), + ("Paragraph Formatting Controls", "Controles de formatação de parágrafos"), + ("Font Size", "Tamanho da fonte"), + ("Vertical Scale", "Escala vertical"), + ("Horizontal Scale", "Escala horizontal"), + ("Baseline Shift", "Deslocamento da linha de base"), + ("Skew (False Italic)", "Inclinação (falso itálico)"), + ("Left Indent", "Recuo à esquerda"), + ("Right Indent", "Recuo à direita"), + ("First Line Left Indent", "Recuo à esquerda da primeira linha"), + ("Last Line Right Indent", "Recuo à direita da última linha"), + ("Drop Cap Number of Lines", "Capitular: número de linhas"), + ("Drop Cap One or More Characters", "Capitular: um ou mais caracteres"), + ("Align to Baseline Grid", "Alinhar à grade de linha de base"), + ("Apply Bullets", "Aplicar marcadores"), + ("Apply Numbers", "Aplicar números"), ("Paste Vector Art", "Colar arte vetorial"), ("Baseline Options", "Opções de linha de base"), ("Fixed Number", "Número fixo"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 3f6ef1be0..412faea7e 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -33,6 +33,43 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Вырезать"), ("Copy", "Копировать"), ("Paste", "Вставить"), + ("Restart Numbering", "Начать нумерацию заново"), + ("Continue Numbering", "Продолжить нумерацию"), + ("Keep Options…", "Параметры удержания…"), + ("Space Between Paragraphs Using Same Style", "Интервал между абзацами одного стиля"), + ("Ignore", "Игнорировать"), + ("Do Not Align to Baseline Grid", "Не выравнивать по базовой сетке"), + ("Only Align First Line to Grid", "Выравнивать по сетке только первую строку"), + ("Balance Ragged Lines", "Сбалансировать рваные строки"), + ("Drop Caps and Nested Styles…", "Буквицы и вложенные стили…"), + ("GREP Styles…", "Стили GREP…"), + ("Restart/Continue Numbering", "Начать заново/продолжить нумерацию"), + ("Convert Bullets and Numbering to Text", "Преобразовать маркеры и нумерацию в текст"), + ("Hyphenation…", "Расстановка переносов…"), + ("Hyphenation Settings", "Параметры расстановки переносов"), + ("hyphens", "дефисов"), + ("Hyphenation Zone:", "Зона переносов:"), + ("Better Spacing", "Лучшие интервалы"), + ("Fewer Hyphens", "Меньше переносов"), + ("Hyphenate Capitalized Words", "Переносить слова с прописной буквы"), + ("Hyphenate Last Word", "Переносить последнее слово"), + ("Hyphenate Across Column", "Переносить между колонками"), + ("Character Formatting Controls", "Элементы управления форматированием символов"), + ("Paragraph Formatting Controls", "Элементы управления форматированием абзацев"), + ("Font Size", "Кегль"), + ("Vertical Scale", "Масштаб по вертикали"), + ("Horizontal Scale", "Масштаб по горизонтали"), + ("Baseline Shift", "Смещение базовой линии"), + ("Skew (False Italic)", "Наклон (ложный курсив)"), + ("Left Indent", "Отступ слева"), + ("Right Indent", "Отступ справа"), + ("First Line Left Indent", "Отступ первой строки слева"), + ("Last Line Right Indent", "Отступ последней строки справа"), + ("Drop Cap Number of Lines", "Буквица: число строк"), + ("Drop Cap One or More Characters", "Буквица: один или несколько символов"), + ("Align to Baseline Grid", "Выровнять по сетке базовых линий"), + ("Apply Bullets", "Применить маркеры"), + ("Apply Numbers", "Применить нумерацию"), ("Clear", "Очистить"), ("Duplicate", "Дублировать"), ("Select All", "Выделить все"), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 9c7cc855a..62c594fd1 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -29,6 +29,43 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Вирізати"), ("Copy", "Копіювати"), ("Paste", "Вставити"), + ("Restart Numbering", "Почати нумерацію знову"), + ("Continue Numbering", "Продовжити нумерацію"), + ("Keep Options…", "Параметри утримання…"), + ("Space Between Paragraphs Using Same Style", "Інтервал між абзацами одного стилю"), + ("Ignore", "Ігнорувати"), + ("Do Not Align to Baseline Grid", "Не вирівнювати за базовою сіткою"), + ("Only Align First Line to Grid", "Вирівнювати за сіткою лише перший рядок"), + ("Balance Ragged Lines", "Збалансувати нерівні рядки"), + ("Drop Caps and Nested Styles…", "Буквиці та вкладені стилі…"), + ("GREP Styles…", "Стилі GREP…"), + ("Restart/Continue Numbering", "Почати знову/продовжити нумерацію"), + ("Convert Bullets and Numbering to Text", "Перетворити маркери й нумерацію на текст"), + ("Hyphenation…", "Перенесення…"), + ("Hyphenation Settings", "Параметри перенесення"), + ("hyphens", "дефісів"), + ("Hyphenation Zone:", "Зона перенесення:"), + ("Better Spacing", "Кращі інтервали"), + ("Fewer Hyphens", "Менше перенесень"), + ("Hyphenate Capitalized Words", "Переносити слова з великої літери"), + ("Hyphenate Last Word", "Переносити останнє слово"), + ("Hyphenate Across Column", "Переносити між колонками"), + ("Character Formatting Controls", "Елементи керування форматуванням символів"), + ("Paragraph Formatting Controls", "Елементи керування форматуванням абзаців"), + ("Font Size", "Кегль"), + ("Vertical Scale", "Масштаб по вертикалі"), + ("Horizontal Scale", "Масштаб по горизонталі"), + ("Baseline Shift", "Зсув базової лінії"), + ("Skew (False Italic)", "Нахил (несправжній курсив)"), + ("Left Indent", "Відступ ліворуч"), + ("Right Indent", "Відступ праворуч"), + ("First Line Left Indent", "Відступ першого рядка ліворуч"), + ("Last Line Right Indent", "Відступ останнього рядка праворуч"), + ("Drop Cap Number of Lines", "Буквиця: кількість рядків"), + ("Drop Cap One or More Characters", "Буквиця: один або кілька символів"), + ("Align to Baseline Grid", "Вирівняти за сіткою базових ліній"), + ("Apply Bullets", "Застосувати маркери"), + ("Apply Numbers", "Застосувати нумерацію"), ("Paste Vector Art", "Вставити векторну графіку"), ("Baseline Options", "Параметри базової лінії"), ("Fixed Number", "Фіксована кількість"), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index a90fe989e..72c37fc83 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -798,6 +798,12 @@ pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) { pen.line(&[(3.0, v), (5.0, v)]); } } + // Do Not Align to Baseline Grid: ragged lines of text, free of any grid. + "grid-none" => { + for (y, x1) in [(5.0, 17.0), (8.5, 12.0), (12.0, 17.0), (15.5, 14.0)] { + pen.line(&[(3.0, y), (x1, y)]); + } + } "grid-baseline" => { pen.rect(3.0, 3.0, 17.0, 17.0); for y in [6.5, 10.0, 13.5] { @@ -938,6 +944,86 @@ pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) { pen.line(&[(15.0, 13.5), (17.0, 15.5), (15.0, 17.5)]); } } + "vscale" => { + pen.text(13.0, 10.5, "T", 15.0); + pen.line(&[(4.0, 3.0), (4.0, 17.0)]); + pen.line(&[(2.5, 5.0), (4.0, 3.0), (5.5, 5.0)]); + pen.line(&[(2.5, 15.0), (4.0, 17.0), (5.5, 15.0)]); + } + "hscale" => { + pen.text(10.0, 8.0, "T", 13.0); + pen.line(&[(3.0, 16.5), (17.0, 16.5)]); + pen.line(&[(5.0, 14.5), (3.0, 16.5), (5.0, 18.5)]); + pen.line(&[(15.0, 14.5), (17.0, 16.5), (15.0, 18.5)]); + } + "baseline-shift" => { + pen.text(7.0, 11.0, "A", 13.0); + pen.text(15.5, 5.5, "a", 8.0); + pen.line(&[(15.5, 17.5), (15.5, 10.0)]); + pen.line(&[(13.5, 12.0), (15.5, 10.0), (17.5, 12.0)]); + } + "skew" => { + pen.w = 1.8; + pen.line(&[(7.0, 4.0), (17.0, 4.0)]); + pen.line(&[(12.0, 4.0), (8.0, 17.0)]); + } + "indent-left" | "indent-right" | "indent-first" | "indent-last" => { + // Text lines, and an arrow at the side (or line) indented. + let (x0, x1) = match name { + "indent-left" => (9.0, 18.0), + "indent-right" => (2.0, 11.0), + _ => (2.0, 18.0), + }; + for (k, y) in [4.0, 8.0, 12.0, 16.0].into_iter().enumerate() { + let (a, z) = match (name, k) { + ("indent-first", 0) => (9.0, x1), + ("indent-last", 3) => (x0, 11.0), + _ => (x0, x1), + }; + pen.line(&[(a, y), (z, y)]); + } + let (y, from, to) = match name { + "indent-left" => (10.0, 2.0, 7.0), + "indent-right" => (10.0, 18.0, 13.0), + "indent-first" => (4.0, 2.0, 7.0), + _ => (16.0, 18.0, 13.0), + }; + pen.line(&[(from, y), (to, y)]); + let d = if to > from { -2.0 } else { 2.0 }; + pen.line(&[(to + d, y - 2.0), (to, y), (to + d, y + 2.0)]); + } + "space-before" | "space-after" => { + let before = name == "space-before"; + let (bar, lines) = if before { (3.0, [11.0, 14.5, 18.0]) } else { (17.0, [2.0, 5.5, 9.0]) }; + pen.line(&[(2.0, bar), (18.0, bar)]); + for y in lines { + pen.line(&[(8.0, y), (18.0, y)]); + } + let (a, z) = if before { (5.0, 10.0) } else { (10.0, 15.0) }; + pen.line(&[(4.0, a), (4.0, z)]); + pen.line(&[(2.5, a + 1.5), (4.0, a), (5.5, a + 1.5)]); + pen.line(&[(2.5, z - 1.5), (4.0, z), (5.5, z - 1.5)]); + } + // Space Between Paragraphs Using Same Style: two paragraphs and the space between them. + "space-same" => { + for y in [2.0, 5.0, 15.0, 18.0] { + pen.line(&[(8.0, y), (18.0, y)]); + } + pen.line(&[(4.0, 6.5), (4.0, 13.5)]); + pen.line(&[(2.5, 8.0), (4.0, 6.5), (5.5, 8.0)]); + pen.line(&[(2.5, 12.0), (4.0, 13.5), (5.5, 12.0)]); + } + "drop-lines" | "drop-chars" => { + pen.text(5.5, 8.0, "A", 14.0); + if name == "drop-chars" { + pen.text(13.5, 4.5, "a", 8.0); + } + for (y, x) in [(if name == "drop-chars" { 8.5 } else { 3.5 }, 11.0), (8.5, 11.0), (13.5, 11.0), (17.5, 2.0)] { + if name == "drop-lines" || y > 5.0 { + pen.line(&[(x, y), (18.0, y)]); + } + } + } "corner" => { pen.w = 1.0; for (x, y) in [(3.0, 3.0), (14.0, 3.0), (3.0, 14.0), (14.0, 14.0)] { @@ -975,6 +1061,20 @@ pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) { pen.line(&[(7.5, *y), (if k == 1 { 14.0 } else { 17.0 }, *y)]); } } + // Paragraph shading: a square with a checked fill (the Control panel's Shading). + "para-shading" => { + pen.w = 1.0; + pen.rect(4.0, 4.0, 16.0, 16.0); + pen.frect(4.0, 4.0, 10.0, 10.0); + pen.frect(10.0, 10.0, 16.0, 16.0); + } + // Paragraph border: a box with its corner drawn heavy (the Control panel's Border). + "para-border" => { + pen.w = 1.0; + pen.rect(4.0, 4.0, 16.0, 16.0); + pen.w = 2.5; + pen.line(&[(5.0, 12.0), (5.0, 5.0), (12.0, 5.0)]); + } "pilcrow-menu" => { pen.text(9.0, 10.0, "¶", 14.0); pen.fill(&[(14.0, 15.0), (17.0, 15.0), (15.5, 17.0)]); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b149cea64..6a60da26e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1071,7 +1071,7 @@ impl DesignApp { } } let Some(inbox) = self.services.inbox.clone() else { return }; - let files = std::mem::take(&mut *inbox.lock().unwrap_or_else(|e| e.into_inner())); + let files = std::mem::take(&mut *inbox.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); for file in files { if file.request.purpose == "shortcuts" { shortcut_import::import_delivered(self, &file.bytes); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index d97dcdeba..b7382c906 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -114,7 +114,21 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ "{tab?: border|shading} — border and shading of the selected paragraphs (type.para)", ), ("app.spanColumnsDialog", "Span Columns…", None, "{} — span or split columns of the selected paragraphs (type.para)"), + ("app.keepOptionsDialog", "Keep Options…", None, "{} — Keep with Next and Keep Lines Together of the selected paragraphs (type.para)"), + ( + "app.nestedStylesDialog", + "Drop Caps and Nested Styles…", + None, + "{} — drop cap, nested styles and nested line styles of the selected paragraphs (type.para)", + ), + ("app.grepStylesDialog", "GREP Styles…", None, "{} — GREP styles of the selected paragraphs (type.para)"), ("app.bulletsNumberingDialog", "Bullets and Numbering…", None, "{} — bullets or numbers of the selected paragraphs (type.para)"), + ( + "app.hyphenationDialog", + "Hyphenation…", + None, + "{} — Hyphenation Settings of the selected paragraphs (type.para): limits, zone, Better Spacing ↔ Fewer Hyphens, Preview", + ), ( "app.justificationDialog", "Justification…", @@ -510,6 +524,9 @@ pub const MENUS: &[(&str, &[&str])] = &[ "<", "-", ">Bulleted & Numbered Lists", + "cmd:list.bullets", + "cmd:list.numbers", + "-", "cmd:list.define", "<", "-", @@ -896,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\"}", @@ -949,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"], @@ -1280,11 +1299,19 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option { + "app.paragraphBordersDialog" + | "app.spanColumnsDialog" + | "app.bulletsNumberingDialog" + | "app.keepOptionsDialog" + | "app.nestedStylesDialog" + | "app.grepStylesDialog" => { let Some(a) = crate::panels::text_attrs(app) else { return Some(Err("select text or a text frame".into())) }; let section = match id { "app.spanColumnsDialog" => "span", "app.bulletsNumberingDialog" => "bullets", + "app.keepOptionsDialog" => "keep", + "app.nestedStylesDialog" => "nested", + "app.grepStylesDialog" => "grep", _ if p.get("tab").and_then(Value::as_str) == Some("shading") => "shading", _ => "border", }; @@ -1297,6 +1324,18 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option { + let Some(a) = app.session.execute("type.selectionAttrs", &json!({"mixed": true})).ok().filter(|a| !a.is_null()) else { + return Some(Err("select text or a text frame".into())); + }; + let mixed: Vec<&str> = a["paraMixed"].as_array().map(|m| m.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + let current: serde_json::Map = crate::dialogs::HYPH_ATTRS + .iter() + .map(|k| (k.to_string(), if mixed.contains(k) { Value::Null } else { a["para"][*k].clone() })) + .collect(); + app.ui.dialog = Some(crate::dialogs::Dialog::new("hyphenation", json!({"current": current}))); + Ok(Value::Null) + } "app.justificationDialog" => { let Some(a) = app.session.execute("type.selectionAttrs", &json!({"mixed": true})).ok().filter(|a| !a.is_null()) else { return Some(Err("select text or a text frame".into())); @@ -1933,7 +1972,7 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option Some(TYPOGRAPHY_GROUPS), _ => None, }; - app.ui.icon_groups = groups.map(|groups| groups.iter().map(|g| g.iter().map(|p| p.to_string()).collect()).collect()); + app.ui.icon_groups = groups.map(|groups| groups.iter().map(|g| g.iter().map(ToString::to_string).collect()).collect()); app.ui.dock_expanded = groups.is_none(); let dock_tab = match name { "Interactive for PDF" | "Digital Publishing" => Some("pages"), @@ -2399,6 +2438,11 @@ pub fn checked(app: &DesignApp, id: &str, params: &Value) -> Option { "view.hiddenCharacters" => app.ui.hidden_characters, "view.taggedFrames" => app.ui.tagged_frames, "changes.track" => app.session.active().is_some_and(|d| d.doc.settings.track_changes), + // Pressed, as the Bulleted and Numbered List buttons: every paragraph the command applies + // to (selected text, cells or text frames) has it. + "list.bullets" | "list.numbers" => { + app.session.selection_has_list(if id == "list.bullets" { designcraft_doc::ListType::Bullets } else { designcraft_doc::ListType::Numbers }) + } "window.controlBar" => app.ui.control_bar, "window.split" => app.split, "window.newWindow" => app.second_window, @@ -2455,7 +2499,7 @@ pub fn menu_enabled(app: &DesignApp, id: &str) -> bool { if is_window_control(id) { return window_control_available(app, id); } - if id == "app.justificationDialog" { + if matches!(id, "app.justificationDialog" | "app.hyphenationDialog") { return enabled(app, "type.para"); } if id.starts_with("fit.") { diff --git a/crates/ui-egui/src/panels/conditions.rs b/crates/ui-egui/src/panels/conditions.rs index 45eddec20..a855b4820 100644 --- a/crates/ui-egui/src/panels/conditions.rs +++ b/crates/ui-egui/src/panels/conditions.rs @@ -7,6 +7,18 @@ use serde_json::json; use crate::DesignApp; use crate::theme::Tokens; +/// Click on a condition name: toggle it on the selected text, or tell the user to select some. +fn apply_condition(app: &mut DesignApp, name: &str, has_text: bool, applied: &[String]) { + if has_text { + let on = !applied.iter().any(|a| a == name); + if let Err(e) = app.run("condition.apply", json!({"name": name, "on": on})) { + app.status_error("Conditional Text", e); + } + } else { + app.status(crate::i18n::tr(&app.ui.language, "Select text to apply a condition")); + } +} + pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let Some(st) = app.session.active() else { return }; @@ -55,14 +67,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { let chip = egui::Rect::from_min_size(egui::pos2(row.max.x - 20.0, row.min.y + 5.0), vec2(14.0, 12.0)); ui.painter().rect_filled(chip, 2.0, egui::Color32::from_rgb(c.color[0], c.color[1], c.color[2])); if nr.clicked() { - if has_text { - let on = !applied.contains(&c.name); - if let Err(e) = app.run("condition.apply", json!({"name": c.name, "on": on})) { - app.status_error("Conditional Text", e); - } - } else { - app.status(crate::i18n::tr(&app.ui.language, "Select text to apply a condition")); - } + apply_condition(app, &c.name, has_text, &applied); } nr.context_menu(|ui| { if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Delete Condition"))).clicked() { diff --git a/crates/ui-egui/src/panels/library.rs b/crates/ui-egui/src/panels/library.rs index 65fb16862..2199e571e 100644 --- a/crates/ui-egui/src/panels/library.rs +++ b/crates/ui-egui/src/panels/library.rs @@ -84,10 +84,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { } } -/// Book panel: the open book's documents with their page ranges; numbering, synchronising and -/// exporting the whole book. -pub fn book(app: &mut DesignApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); +fn book_open_buttons(app: &mut DesignApp, ui: &mut egui::Ui) { ui.horizontal(|ui| { if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "New Book…"))).clicked() && let Some(path) = app.pick_save("Book.dcbook") @@ -102,6 +99,36 @@ pub fn book(app: &mut DesignApp, ui: &mut egui::Ui) { app.status_error("Book", e); } }); +} + +fn book_action_buttons(app: &mut DesignApp, ui: &mut egui::Ui) { + ui.horizontal_wrapped(|ui| { + if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Add Document…"))).clicked() + && let Some(path) = app.services.pick_open.as_mut().and_then(|f| f("open")) + && let Err(e) = app.run("book.add", json!({"path": path})) + { + app.status_error("Book", e); + } + if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Update Numbering"))).clicked() { + let _ = app.run("book.paginate", json!({})); + } + if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Synchronize"))).clicked() { + let _ = app.run("book.syncStyles", json!({})); + } + if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Export PDF…"))).clicked() + && let Some(path) = app.pick_save("Book.pdf") + && let Err(e) = app.run("book.exportPdf", json!({"path": path})) + { + app.status_error("Book", e); + } + }); +} + +/// Book panel: the open book's documents with their page ranges; numbering, synchronising and +/// exporting the whole book. +pub fn book(app: &mut DesignApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + book_open_buttons(app, ui); let Ok(info) = app.session.execute("book.list", &json!({})) else { crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "No book open.")).size(11.0).color(t.text_dim)); return; @@ -140,26 +167,7 @@ pub fn book(app: &mut DesignApp, ui: &mut egui::Ui) { }); } ui.separator(); - ui.horizontal_wrapped(|ui| { - if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Add Document…"))).clicked() - && let Some(path) = app.services.pick_open.as_mut().and_then(|f| f("open")) - && let Err(e) = app.run("book.add", json!({"path": path})) - { - app.status_error("Book", e); - } - if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Update Numbering"))).clicked() { - let _ = app.run("book.paginate", json!({})); - } - if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Synchronize"))).clicked() { - let _ = app.run("book.syncStyles", json!({})); - } - if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Export PDF…"))).clicked() - && let Some(path) = app.pick_save("Book.pdf") - && let Err(e) = app.run("book.exportPdf", json!({"path": path})) - { - app.status_error("Book", e); - } - }); + book_action_buttons(app, ui); } /// Scripts panel: saved command scripts — run (one undo step), edit, add, delete, load. diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index f2229b604..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; @@ -264,7 +265,7 @@ pub fn preflight_errors(app: &DesignApp) -> usize { static MEMO: std::sync::Mutex> = std::sync::Mutex::new(None); let Some(st) = app.session.active() else { return 0 }; let key = std::sync::Arc::as_ptr(&st.doc) as usize; - let mut g = MEMO.lock().unwrap_or_else(|e| e.into_inner()); + let mut g = MEMO.lock().unwrap_or_else(std::sync::PoisonError::into_inner); if let Some((k, n)) = *g && k == key { diff --git a/crates/ui-egui/src/panels/pages.rs b/crates/ui-egui/src/panels/pages.rs index 4b2360f8f..534eb4aa1 100644 --- a/crates/ui-egui/src/panels/pages.rs +++ b/crates/ui-egui/src/panels/pages.rs @@ -28,7 +28,7 @@ const MAX_THUMB_W: f64 = 1024.0; fn thumb(app: &mut DesignApp, ctx: &egui::Context, of: ThumbOf, h: f32) -> Option { let st = app.session.active()?; let key = (st.uid, st.revision, of, h.round() as u32); - let mut g = THUMBS.lock().unwrap_or_else(|e| e.into_inner()); + let mut g = THUMBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let map = g.get_or_insert_with(HashMap::new); if let Some(t) = map.get(&key) { return Some(t.clone()); diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 0422936e3..fda46efad 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -1348,21 +1348,141 @@ fn character_section(app: &mut DesignApp, ui: &mut Ui) { }) { let _ = app.run("type.char", json!({"attrs": {"tracking": v}})); } - // Language: hyphenation, spelling and typographer's quotes follow it. - ui.add_space(1.0); + // ••• shows the rest in place, as InDesign's Properties panel does. + let more = temp_bool(ui, "props_char_more", false); + if more { + character_more(app, ui, &c, fw); + } + if more_options(ui, &app.ui.language).clicked() { + set_temp_bool(ui, "props_char_more", !more); + } +} + +/// A percentage or other number field in one half of a two-field row, with its icon. +#[allow(clippy::too_many_arguments)] +fn half_field(ui: &mut Ui, b: Rect, right: bool, y: f32, half: f32, icon: &str, tip: &str, field: NumField) -> Option { + half_field_or_clear(ui, b, right, y, half, icon, tip, field).flatten() +} + +/// [`half_field`] for a value that may be unset: emptying the field commits `Some(None)`. +#[allow(clippy::too_many_arguments)] +fn half_field_or_clear(ui: &mut Ui, b: Rect, right: bool, y: f32, half: f32, icon: &str, tip: &str, field: NumField) -> Option> { + let t = Tokens::get(ui.ctx()); + let x = if right { half + 10.0 } else { 0.0 }; + let ir = sub(b, x, y + 1.0, 19.0, 19.0); + icons::paint(ui.painter(), ir, icon, t.icon); + let resp = ui.interact(ir, ui.id().with(("half_icon", icon)), Sense::hover()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, tip)); + let label = resp.id; + resp.on_hover_text(tip); + place(ui, sub(b, x + 24.0, y, half - 24.0, FIELD_H), |ui| field.width(half - 24.0).labelled_by(label).show_or_clear(ui)) +} + +/// Properties › Character after •••: vertical and horizontal scale, baseline shift and skew, +/// language and OpenType, then All Caps, Small Caps, Superscript, Subscript, Underline and +/// Strikethrough, as InDesign lays them out. +fn character_more(app: &mut DesignApp, ui: &mut Ui, c: &Value, fw: f32) { + let lang_ui = app.ui.language.clone(); + let tr = |s: &str| crate::i18n::tr(&lang_ui, s).to_string(); + let half = (fw - 10.0) / 2.0; + let b = block(ui, 2.0 * FIELD_H + 5.0); + const SCALES: &[f64] = &[25.0, 50.0, 75.0, 80.0, 90.0, 100.0, 110.0, 120.0, 125.0, 150.0, 200.0]; + let pct = |v: &Value| v.as_f64().map(|s| (s * 1000.0).round() / 10.0); + let field = |id, v, suffix, decimals| NumField::number(id, v, suffix, decimals).spinner(); + if let Some(v) = half_field( + ui, + b, + false, + 0.0, + half, + "vscale", + &tr("Vertical Scale"), + field("cvscale", pct(&c["vScale"]), "%", 1).presets(SCALES).range(1.0, 1000.0), + ) { + let _ = app.run("type.char", json!({"attrs": {"vScale": v / 100.0}})); + } + if let Some(v) = half_field( + ui, + b, + true, + 0.0, + half, + "hscale", + &tr("Horizontal Scale"), + field("chscale", pct(&c["hScale"]), "%", 1).presets(SCALES).range(1.0, 1000.0), + ) { + let _ = app.run("type.char", json!({"attrs": {"hScale": v / 100.0}})); + } + if let Some(v) = half_field( + ui, + b, + false, + 26.0, + half, + "baseline-shift", + &tr("Baseline Shift"), + field("cbshift", c["baselineShift"].as_f64(), " pt", 2).range(-5000.0, 5000.0), + ) { + let _ = app.run("type.char", json!({"attrs": {"baselineShift": v}})); + } + if let Some(v) = + half_field(ui, b, true, 26.0, half, "skew", &tr("Skew (False Italic)"), field("cskew", c["skew"].as_f64(), "°", 1).range(-85.0, 85.0)) + { + let _ = app.run("type.char", json!({"attrs": {"skew": v}})); + } + // Language (hyphenation, spelling and typographer's quotes follow it) and OpenType. + ui.add_space(4.0); let lang = c["language"].as_str().unwrap_or("English: USA").to_string(); - let label = crate::i18n::tr(&app.ui.language, "Language"); - let resp = widgets::dropdown(ui, crate::i18n::tr(&app.ui.language, &lang), fw).on_hover_ui(|ui| { - crate::rtl::label(ui, label); + let label = tr("Language"); + let row = block(ui, FIELD_H); + let resp = place(ui, sub(row, 0.0, 0.0, half, FIELD_H), |ui| widgets::dropdown(ui, crate::i18n::tr(&lang_ui, &lang), half)).on_hover_ui(|ui| { + crate::rtl::label(ui, label.clone()); }); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, true, label)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, true, &label)); egui::Popup::menu(&resp).show(|ui| { - ui.set_min_width(fw); + ui.set_min_width(half); egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| language_menu(app, ui, &lang)); }); - if more_options(ui, &app.ui.language).clicked() { - show_panel(app, "character"); + if place(ui, sub(row, half + 10.0, 0.0, half, FIELD_H), |ui| widgets::outline_button(ui, &tr("OpenType"), half)).clicked() { + show_typography_panel(app); } + // The case and position buttons. + ui.add_space(8.0); + let caps = c["capitalization"].as_str().unwrap_or("normal").to_string(); + let pos = c["position"].as_str().unwrap_or("normal").to_string(); + let (ul, st) = (c["underline"].as_bool().unwrap_or(false), c["strikethrough"].as_bool().unwrap_or(false)); + let buttons: [(&str, &str, bool, Value); 6] = [ + ("TT", "All Caps", caps == "allCaps", json!({"capitalization": if caps == "allCaps" { "normal" } else { "allCaps" }})), + ("Tᴛ", "Small Caps", caps == "smallCaps", json!({"capitalization": if caps == "smallCaps" { "normal" } else { "smallCaps" }})), + ("T¹", "Superscript", pos == "superscript", json!({"position": if pos == "superscript" { "normal" } else { "superscript" }})), + ("T₁", "Subscript", pos == "subscript", json!({"position": if pos == "subscript" { "normal" } else { "subscript" }})), + ("T̲", "Underline", ul, json!({"underline": !ul})), + ("T", "Strikethrough", st, json!({"strikethrough": !st})), + ]; + let pitch = fw / 6.0; + let row = block(ui, 22.0); + for (i, (text, tip, on, attrs)) in buttons.into_iter().enumerate() { + let r = Rect::from_center_size(row.min + vec2(pitch * (i as f32 + 0.5), 11.0), vec2(26.0, 22.0)); + let resp = ui.interact(r, ui.id().with(("case", i)), Sense::click()); + let t = Tokens::get(ui.ctx()); + if on { + ui.painter().rect_filled(r, 2.0, t.tool_active); + } else if resp.hovered() { + ui.painter().rect_filled(r, 2.0, t.hover); + } + let col = if on { t.text_strong } else { t.icon }; + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, text, egui::FontId::proportional(13.0), col); + // Strikethrough: the T struck through (a combining stroke doesn't draw in every font). + if i == 5 { + ui.painter().line_segment([r.center() + vec2(-6.0, 0.5), r.center() + vec2(6.0, 0.5)], Stroke::new(1.2, col)); + } + let tip = tr(tip); + resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, on, &tip)); + if resp.on_hover_text(&tip).clicked() { + let _ = app.run("type.char", json!({"attrs": attrs})); + } + } + ui.add_space(4.0); } /// Paragraph section: the 9 alignment buttons and •••. @@ -1392,20 +1512,81 @@ fn paragraph_section(app: &mut DesignApp, ui: &mut Ui) { } } }); + let more = temp_bool(ui, "props_para_more", false); + if more { + paragraph_more(app, ui, &a["para"], fw); + } if more_options(ui, &app.ui.language).clicked() { - show_panel(app, "paragraph"); + set_temp_bool(ui, "props_para_more", !more); } } +/// Properties › Paragraph after •••: left and right indent, first line and last line indent, +/// space before and after, drop cap lines and characters, then Hyphenate and Align to Baseline +/// Grid, as InDesign lays them out. +fn paragraph_more(app: &mut DesignApp, ui: &mut Ui, p: &Value, fw: f32) { + let lang_ui = app.ui.language.clone(); + let tr = |s: &str| crate::i18n::tr(&lang_ui, s).to_string(); + let u = units(app); + let half = (fw - 10.0) / 2.0; + ui.add_space(4.0); + let b = block(ui, 4.0 * FIELD_H + 15.0); + let rows = [ + (("indent-left", "Left Indent", "leftIndent"), ("indent-right", "Right Indent", "rightIndent")), + (("indent-first", "First Line Left Indent", "firstLineIndent"), ("indent-last", "Last Line Right Indent", "lastLineIndent")), + (("space-before", "Space Before", "spaceBefore"), ("space-after", "Space After", "spaceAfter")), + ]; + for (i, (l, r)) in rows.into_iter().enumerate() { + let y = i as f32 * (FIELD_H + 5.0); + for (right, (icon, tip, key)) in [(false, l), (true, r)] { + let min = para_field_min(key); + let field = NumField::measure(key, p[key].as_f64(), u).spinner().range(min, 10_000.0); + if let Some(v) = half_field(ui, b, right, y, half, icon, &tr(tip), field) { + let _ = app.run("type.para", json!({"attrs": {key: v}})); + } + } + } + let y = 3.0 * (FIELD_H + 5.0); + for (right, icon, tip, key, max) in [ + (false, "drop-lines", "Drop Cap Number of Lines", "dropCapLines", designcraft_compose::MAX_DROP_CAP_LINES), + (true, "drop-chars", "Drop Cap One or More Characters", "dropCapChars", designcraft_compose::MAX_DROP_CAP_CHARS), + ] { + let field = NumField::number(key, p[key].as_f64(), "", 0).spinner().range(0.0, max as f64); + if let Some(v) = half_field(ui, b, right, y, half, icon, &tr(tip), field) { + let _ = app.run("type.para", json!({"attrs": {key: (v.max(0.0) as u64).min(max as u64)}})); + } + } + ui.add_space(4.0); + ui.horizontal(|ui| { + // First Line Only is aligned too: the button shows it pressed, and a click turns alignment off. + let grid = matches!(p["gridAlign"].as_str(), Some("allLines" | "firstLineOnly")); + if widgets::icon_toggle(ui, "grid-baseline", grid, &tr("Align to Baseline Grid")).clicked() { + let _ = app.run("type.para", json!({"attrs": {"gridAlign": if grid { "none" } else { "allLines" }}})); + } + ui.add_space(12.0); + let mut h = p["hyphenate"].as_bool().unwrap_or(true); + if widgets::checkbox(ui, &mut h, &tr("Hyphenate")).changed() { + let _ = app.run("type.para", json!({"attrs": {"hyphenate": h}})); + } + }); + ui.add_space(4.0); +} + fn bullets_section(app: &mut DesignApp, ui: &mut Ui) { - let Some(a) = text_attrs(app) else { return }; - let lt = a["para"]["listType"].as_str().unwrap_or("none").to_string(); + if text_attrs(app).is_none() { + return; + } ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 10.0; - for (icon, kind, tip) in [("bullets", "bullets", "Bulleted List"), ("numbering", "numbers", "Numbered List")] { - let on = lt == kind; + // As InDesign's: a list with the default hanging indent, or (pressed: every selected + // paragraph has it, as Type › Apply Bullets shows) no list. + use designcraft_doc::ListType; + for (icon, kind, cmd, tip) in + [("bullets", ListType::Bullets, "list.bullets", "Bulleted List"), ("numbering", ListType::Numbers, "list.numbers", "Numbered List")] + { + let on = app.session.selection_has_list(kind); if icon_toggle(ui, icon, on, crate::i18n::tr(&app.ui.language, tip)).clicked() { - let _ = app.run("type.para", json!({"attrs": {"listType": if on { "none" } else { kind }}})); + let _ = app.run(cmd, json!({"on": !on})); } } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -1505,7 +1686,7 @@ pub(crate) const LANGUAGES: &[&str] = &[ /// The Language list (Character panel, Properties ▸ Character): picking one sets the language of /// the selected text. -fn language_menu(app: &mut DesignApp, ui: &mut Ui, cur: &str) { +pub(crate) fn language_menu(app: &mut DesignApp, ui: &mut Ui, cur: &str) { for l in LANGUAGES { if ui.selectable_label(*l == cur, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, l))).clicked() { let _ = app.run("type.char", json!({"attrs": {"language": l}})); @@ -1517,7 +1698,7 @@ fn language_menu(app: &mut DesignApp, ui: &mut Ui, cur: &str) { /// Kerning for the text selection, or at a caret for the pair at the caret: the label shows /// Metrics, Optical, 0 or the manual value; its menu sets one of the first three or a manual value /// in 1/1000 em (typed or stepped). -fn kerning_control(app: &mut DesignApp, ui: &mut egui::Ui, id: &str, k: &Value, width: f32) { +pub(crate) fn kerning_control(app: &mut DesignApp, ui: &mut egui::Ui, id: &str, k: &Value, width: f32) { let kind = k["kind"].as_str().unwrap_or("metrics"); let manual = k["value"].as_f64().filter(|v| kind == "manual" && v.is_finite()); let label = match (kind, manual) { @@ -1737,161 +1918,236 @@ pub fn show_typography_panel(app: &mut DesignApp) { let _ = app.run("window.panel", json!({"panel": "typography"})); } +/// The paragraph alignments in InDesign's order, with their icons. +const PARA_ALIGNS: [(Align, &str); 9] = [ + (Align::Left, "palign-left"), + (Align::Center, "palign-center"), + (Align::Right, "palign-right"), + (Align::LeftJustified, "palign-justify-left"), + (Align::CenterJustified, "palign-justify-center"), + (Align::RightJustified, "palign-justify-right"), + (Align::FullyJustified, "palign-justify-all"), + (Align::TowardsSpine, "palign-spine-towards"), + (Align::AwayFromSpine, "palign-spine-away"), +]; + +/// Space Between Paragraphs Using Same Style's presets (pt), after Ignore. +const SAME_STYLE_SPACING: &[f64] = &[0.0, 3.0, 6.0, 9.0, 12.0, 18.0, 24.0]; + +/// The Paragraph panel, laid out as InDesign's: the alignment buttons in groups of 3, 4 and 2; +/// indents, spacing and drop cap fields by their icons in two columns; Shading and Border with +/// their colours; Hyphenate and the baseline grid buttons. The rest (composer, grid and ragged +/// lines options, the paragraph dialogs) is in the panel menu. pub fn paragraph_panel(app: &mut DesignApp, ui: &mut egui::Ui) { let Some(a) = text_attrs(app) else { crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Select text or a text frame.")); return; }; + let lang_ui = app.ui.language.clone(); + let tr = |s: &str| crate::i18n::tr(&lang_ui, s).to_string(); let u = units(app); let p = a["para"].clone(); - ui.horizontal(|ui| { - crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Paragraph")).strong()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - crate::menus::menu_button(ui, "☰", |ui| { - for (label, id) in [ - ("Paragraph Rules…", "app.paragraphRulesDialog"), - ("Justification…", "app.justificationDialog"), - ("Paragraph Borders and Shading…", "app.paragraphBordersDialog"), - ("Span Columns…", "app.spanColumnsDialog"), - ("Bullets and Numbering…", "app.bulletsNumberingDialog"), - ] { - if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() { - let _ = app.run(id, json!({})); - ui.close(); - } - } - }); - }); - }); + let fw = full_width(ui); + let half = (fw - 10.0) / 2.0; + // Alignment, and the panel menu at the right. let cur: Align = serde_json::from_value(p["align"].clone()).unwrap_or_default(); - ui.horizontal(|ui| { - for (al, icon) in [ - (Align::Left, "align-left"), - (Align::Center, "align-center"), - (Align::Right, "align-right"), - (Align::LeftJustified, "align-justify"), - (Align::FullyJustified, "align-justify-all"), - ] { - if icons::button(ui, icon, 24.0, cur == al, al.label()).clicked() { - let _ = app.run("type.para", json!({"attrs": {"align": al}})); - } + const GAP: f32 = 8.0; + let pitch = ((fw - 24.0 - 2.0 * GAP) / 9.0).clamp(16.0, 24.0); + let b = block(ui, 21.0); + let mut x = 0.0; + for (i, (al, icon)) in PARA_ALIGNS.into_iter().enumerate() { + if i == 3 || i == 7 { + x += GAP; } - }); - // Paragraph Direction (World-Ready): switching also mirrors left/right alignment. - let rtl = p["direction"] == "rightToLeft"; - ui.horizontal(|ui| { - caption(ui, crate::i18n::tr(&app.ui.language, "Direction")); - for (on, label, dir) in [(!rtl, "Left to Right", "leftToRight"), (rtl, "Right to Left", "rightToLeft")] { - if ui.selectable_label(on, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() && !on { - let align = match cur { - Align::Left => Align::Right, - Align::Right => Align::Left, - a => a, - }; - let _ = app.run("type.para", json!({"attrs": {"direction": dir, "align": align}})); - } - } - }); - egui::Grid::new("paragrid").num_columns(4).spacing(vec2(6.0, 4.0)).show(ui, |ui| { - for (row, ((la, ka), (lb, kb))) in [ - (("Left", "leftIndent"), ("Right", "rightIndent")), - (("First", "firstLineIndent"), ("Last", "lastLineIndent")), - (("Before", "spaceBefore"), ("After", "spaceAfter")), - ] - .into_iter() - .enumerate() + if place(ui, sub(b, x, 0.0, pitch, 21.0), |ui| widgets::icon_toggle_sized(ui, icon, cur == al, &tr(al.label()), vec2(pitch, 21.0))).clicked() { - caption(ui, crate::i18n::tr(&app.ui.language, la)); - if let Some(v) = measure(ui, &format!("pp{row}a"), p[ka].as_f64(), u, 64.0) { - let _ = app.run("type.para", json!({"attrs": {ka: v}})); - } - caption(ui, crate::i18n::tr(&app.ui.language, lb)); - if let Some(v) = measure(ui, &format!("pp{row}b"), p[kb].as_f64(), u, 64.0) { - let _ = app.run("type.para", json!({"attrs": {kb: v}})); - } - ui.end_row(); + let _ = app.run("type.para", json!({"attrs": {"align": al}})); } - // Drop cap: number of lines and characters. - for (label, key, max, id) in [ - ("Drop Lines", "dropCapLines", designcraft_compose::MAX_DROP_CAP_LINES, "ppdl"), - ("Drop Chars", "dropCapChars", designcraft_compose::MAX_DROP_CAP_CHARS, "ppdc"), - ] { - caption(ui, crate::i18n::tr(&app.ui.language, label)); - if let Some(v) = number(ui, id, p[key].as_f64(), "", 64.0, 0) { - let _ = app.run("type.para", json!({"attrs": {key: (v.max(0.0) as u64).min(max as u64)}})); - } - } - ui.end_row(); - }); - ui.horizontal(|ui| { - let mut h = p["hyphenate"].as_bool().unwrap_or(true); - if ui.checkbox(&mut h, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Hyphenate"))).changed() { - let _ = app.run("type.para", json!({"attrs": {"hyphenate": h}})); - } - let mut grid = p["gridAlign"].as_str() == Some("allLines"); - if ui.checkbox(&mut grid, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Align to baseline grid"))).changed() { - let _ = app.run("type.para", json!({"attrs": {"gridAlign": if grid { "allLines" } else { "none" }}})); - } - }); - let mut optical = p["opticalMargin"].as_bool().unwrap_or(false); - if ui.checkbox(&mut optical, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Optical Margin Alignment"))).changed() { - let _ = app.run("type.para", json!({"attrs": {"opticalMargin": optical}})); + x += pitch; } - ui.horizontal(|ui| { - caption(ui, crate::i18n::tr(&app.ui.language, "Composer")); - let (single, [paragraph, single_line]) = composer_choice(p["composer"].as_str()); - if ui.selectable_label(!single, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Paragraph"))).clicked() { - let _ = app.run("type.para", json!({"attrs": {"composer": paragraph}})); + place(ui, sub(b, fw - 20.0, 0.0, 20.0, 21.0), |ui| crate::menus::menu_button(ui, "☰", |ui| paragraph_panel_menu(app, ui, &p))); + ui.add_space(6.0); + // Indents, spacing and drop cap, two to a row as in InDesign. + let row = FIELD_H + 5.0; + let b = block(ui, 5.0 * row - 5.0); + let rows = [ + (("indent-left", "Left Indent", "leftIndent"), ("indent-right", "Right Indent", "rightIndent")), + (("indent-first", "First Line Left Indent", "firstLineIndent"), ("indent-last", "Last Line Right Indent", "lastLineIndent")), + (("space-before", "Space Before", "spaceBefore"), ("space-after", "Space After", "spaceAfter")), + ]; + for (i, (l, r)) in rows.into_iter().enumerate() { + for (right, (icon, tip, key)) in [(false, l), (true, r)] { + // The first and last line indents may be negative (a hanging line), as InDesign's. + let min = if matches!(key, "firstLineIndent" | "lastLineIndent") { -10_000.0 } else { 0.0 }; + let field = NumField::measure(key, p[key].as_f64(), u).spinner().range(min, 10_000.0); + if let Some(v) = half_field(ui, b, right, i as f32 * row, half, icon, &tr(tip), field) { + let _ = app.run("type.para", json!({"attrs": {key: v}})); + } } - if ui.selectable_label(single, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Single-line"))).clicked() { - let _ = app.run("type.para", json!({"attrs": {"composer": single_line}})); + } + // Space Between Paragraphs Using Same Style: Ignore (unset) or a space that replaces the + // space after and before between paragraphs of the same style. + let ignore = tr("Ignore"); + let field = NumField::measure("sameParaStyleSpacing", p["sameParaStyleSpacing"].as_f64(), u) + .spinner() + .presets(SAME_STYLE_SPACING) + .empty_text(&ignore) + .range(0.0, 10_000.0); + if let Some(v) = half_field_or_clear(ui, b, false, 3.0 * row, half, "space-same", &tr("Space Between Paragraphs Using Same Style"), field) { + let _ = app.run("type.para", json!({"attrs": {"sameParaStyleSpacing": v}})); + } + for (right, icon, tip, key, max) in [ + (false, "drop-lines", "Drop Cap Number of Lines", "dropCapLines", designcraft_compose::MAX_DROP_CAP_LINES), + (true, "drop-chars", "Drop Cap One or More Characters", "dropCapChars", designcraft_compose::MAX_DROP_CAP_CHARS), + ] { + let field = NumField::number(key, p[key].as_f64(), "", 0).spinner().range(0.0, max as f64); + if let Some(v) = half_field(ui, b, right, 4.0 * row, half, icon, &tr(tip), field) { + let _ = app.run("type.para", json!({"attrs": {key: (v.max(0.0) as u64).min(max as u64)}})); } - }); - // Paragraph Border and Shading. - let swatches: Vec = - app.session.active().map(|d| d.doc.swatches.iter().filter(|w| !w.hidden).map(|w| w.name.clone()).collect()).unwrap_or_default(); - for (on_key, color_key, label) in [("shadingOn", "shadingColor", "Shading"), ("borderOn", "borderColor", "Border")] { - ui.horizontal(|ui| { - let mut on = p[on_key].as_bool().unwrap_or(false); - if ui.checkbox(&mut on, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).changed() { - let _ = app.run("type.para", json!({ on_key: on })); - } - if on { - let cur = p[color_key].as_str().unwrap_or("[Black]").to_string(); - egui::ComboBox::from_id_salt(("pbs", label)).selected_text(&cur).width(110.0).show_ui(ui, |ui| { - for w in &swatches { - if ui.selectable_label(*w == cur, w).clicked() { - let _ = app.run("type.para", json!({ color_key: w })); - } - } - }); - if label == "Shading" { - if let Some(v) = number(ui, "pshtint", p["shadingTint"].as_f64().map(|t| t * 100.0), "%", 46.0, 0) { - let _ = app.run("type.para", json!({"shadingTint": (v / 100.0).clamp(0.0, 1.0)})); - } - } else if let Some(v) = number(ui, "pbw", p["borderWeights"][0].as_f64(), " pt", 50.0, 2) { - let w = [v.max(0.0); 4]; - let _ = app.run("type.para", json!({ "borderWeights": w })); - } - } - }); } - if p["shadingOn"].as_bool().unwrap_or(false) || p["borderOn"].as_bool().unwrap_or(false) { - ui.horizontal(|ui| { - caption(ui, crate::i18n::tr(&app.ui.language, "Offsets")); - let o = p["borderOffsets"][0].as_f64().or(p["shadingOffsets"][0].as_f64()); - if let Some(v) = number(ui, "pbo", o, " pt", 50.0, 2) { - let o = [v; 4]; - let _ = app.run("type.para", json!({ "borderOffsets": o, "shadingOffsets": o })); + // Shading and Border: on or off at the left; at the right the Paragraph Borders and Shading + // dialog on its tab and the colour. + ui.add_space(10.0); + let doc = app.session.active().map(|d| d.doc.clone()); + let b = block(ui, 2.0 * row - 5.0); + for (i, (on_key, color_key, label, icon, tab, name)) in [ + ("shadingOn", "shadingColor", "Shading", "para-shading", "shading", "Paragraph Shading"), + ("borderOn", "borderColor", "Border", "para-border", "border", "Paragraph Border"), + ] + .into_iter() + .enumerate() + { + let y = i as f32 * row; + let mut on = p[on_key].as_bool().unwrap_or(false); + if place(ui, sub(b, 0.0, y, half, FIELD_H), |ui| widgets::checkbox(ui, &mut on, &tr(label))).changed() { + let _ = app.run("type.para", json!({"attrs": {on_key: on}})); + } + if place(ui, sub(b, half + 10.0, y, 23.0, FIELD_H), |ui| widgets::icon_toggle(ui, icon, false, &tr("Paragraph Borders and Shading…"))) + .clicked() + { + let _ = app.run("app.paragraphBordersDialog", json!({"tab": tab})); + } + if let Some(doc) = &doc { + let color = p[color_key].as_str().unwrap_or("[Black]").to_string(); + let w = half - 24.0; + if let Some(sw) = place(ui, sub(b, half + 34.0, y, w, FIELD_H), |ui| crate::chrome::swatch_field(ui, doc, &color, w, &tr(name))) { + let _ = app.run("type.para", json!({"attrs": {color_key: sw}})); } - }); + } + } + // Hyphenate, and Do Not Align / Align to Baseline Grid. + ui.add_space(10.0); + let b = block(ui, FIELD_H); + let mut h = p["hyphenate"].as_bool().unwrap_or(true); + if place(ui, sub(b, 0.0, 0.0, half, FIELD_H), |ui| widgets::checkbox(ui, &mut h, &tr("Hyphenate"))).changed() { + let _ = app.run("type.para", json!({"attrs": {"hyphenate": h}})); + } + let grid = matches!(p["gridAlign"].as_str(), Some("allLines" | "firstLineOnly")); + for (i, (icon, tip, on, v)) in + [("grid-none", "Do Not Align to Baseline Grid", !grid, "none"), ("grid-baseline", "Align to Baseline Grid", grid, "allLines")] + .into_iter() + .enumerate() + { + if place(ui, sub(b, fw - 48.0 + i as f32 * 25.0, 0.0, 23.0, FIELD_H), |ui| widgets::icon_toggle(ui, icon, on, &tr(tip))).clicked() && !on { + let _ = app.run("type.para", json!({"attrs": {"gridAlign": v}})); + } + } + ui.add_space(4.0); +} + +/// The Paragraph panel menu, in the order of InDesign's. +fn paragraph_panel_menu(app: &mut DesignApp, ui: &mut Ui, p: &Value) { + let lang = app.ui.language.clone(); + let item = |ui: &mut Ui, label: &str, check: Option, enabled: bool| -> bool { + let label = crate::i18n::tr(&lang, label); + let text = match check { + Some(true) => format!("✓ {label}"), + Some(false) => format!(" {label}"), + None => label.to_string(), + }; + let clicked = ui.add_enabled(enabled, egui::Button::new(crate::rtl::widget(ui, text))).clicked(); + if clicked { + ui.close(); + } + clicked + }; + let mut attrs = None; + let mut command = None; + let (single, [paragraph, single_line]) = composer_choice(p["composer"].as_str()); + if item(ui, "Paragraph Composer", Some(!single), true) { + attrs = Some(json!({"composer": paragraph})); + } + if item(ui, "Single-line Composer", Some(single), true) { + attrs = Some(json!({"composer": single_line})); + } + ui.separator(); + let grid = p["gridAlign"].as_str().unwrap_or("none"); + if item(ui, "Only Align First Line to Grid", Some(grid == "firstLineOnly"), grid != "none") { + attrs = Some(json!({"gridAlign": if grid == "firstLineOnly" { "allLines" } else { "firstLineOnly" }})); + } + let balance = p["balanceRagged"].as_bool().unwrap_or(false); + if item(ui, "Balance Ragged Lines", Some(balance), true) { + attrs = Some(json!({"balanceRagged": !balance})); + } + // 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 [ + ("Justification…", "app.justificationDialog"), + ("Keep Options…", "app.keepOptionsDialog"), + ("Span Columns…", "app.spanColumnsDialog"), + ("Hyphenation…", "app.hyphenationDialog"), + ("Drop Caps and Nested Styles…", "app.nestedStylesDialog"), + ("GREP Styles…", "app.grepStylesDialog"), + ("Paragraph Rules…", "app.paragraphRulesDialog"), + ("Paragraph Borders and Shading…", "app.paragraphBordersDialog"), + ] { + if item(ui, label, None, true) { + command = Some(id); + } + } + ui.separator(); + if item(ui, "Bullets and Numbering…", None, true) { + command = Some("app.bulletsNumberingDialog"); + } + // Restart Numbering at 1, or Continue Numbering from the paragraph before, for a numbered list. + let numbered = p["listType"].as_str() == Some("numbers"); + let restarts = p["startAt"].is_u64(); + let label = match (numbered, restarts) { + (false, _) => "Restart/Continue Numbering", + (true, false) => "Restart Numbering", + (true, true) => "Continue Numbering", + }; + if item(ui, label, None, numbered) { + attrs = Some(json!({"startAt": if restarts { Value::Null } else { json!(1) }})); + } + item(ui, "Convert Bullets and Numbering to Text", None, false); + if item(ui, "Define Lists…", None, true) { + command = Some("list.define"); + } + // Paragraph Direction (World-Ready): switching also mirrors left and right alignment. + ui.separator(); + let rtl = p["direction"] == "rightToLeft"; + for (on, label, dir) in [(!rtl, "Left to Right", "leftToRight"), (rtl, "Right to Left", "rightToLeft")] { + if item(ui, label, Some(on), true) && !on { + let align = match serde_json::from_value(p["align"].clone()).unwrap_or_default() { + Align::Left => Align::Right, + Align::Right => Align::Left, + a => a, + }; + attrs = Some(json!({"direction": dir, "align": align})); + } + } + if let Some(attrs) = attrs { + let _ = app.run("type.para", json!({"attrs": attrs})); + } + // As a menu choice: Define Lists… and the other commands open their dialogs. + if let Some(id) = command { + crate::menus::activate(app, id, &Value::Null); } - let ps = a["paragraphStyle"].as_str().unwrap_or("").to_string(); - let ov = a["paraOverrides"].as_u64().unwrap_or(0) + a["charOverrides"].as_u64().unwrap_or(0); - ui.horizontal(|ui| { - caption(ui, crate::i18n::tr(&app.ui.language, "Style")); - super::para_style_picker(app, ui, &ps, ov > 0, 190.0); - }); } /// Stroke panel: weight, cap, miter limit, join, alignment, type, arrowheads, gap colour. @@ -2905,9 +3161,18 @@ pub fn digit_label(lang: &str, o: (&str, &str, &str)) -> String { if o.2.is_empty() { name.to_string() } else { format!("{name} {}", o.2) } } +/// The least value a paragraph field takes: the first and last line indents may be negative (a +/// hanging line, a last line past the right indent), as in InDesign; the others not. +pub(crate) fn para_field_min(key: &str) -> f64 { + if matches!(key, "firstLineIndent" | "lastLineIndent") { -10_000.0 } else { 0.0 } +} + #[cfg(test)] mod tests { - use egui_kittest::{Harness, kittest::Queryable}; + use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, + }; use super::*; @@ -2979,6 +3244,18 @@ mod tests { } /// With the caret in text, the Stroke panel offers the text's stroke options, not an empty panel. + /// The first and last line indents take negative values, as InDesign's (and the Paragraph + /// panel's) do; the left and right indents and the spacing don't. + #[test] + fn last_line_indent_may_be_negative() { + for key in ["firstLineIndent", "lastLineIndent"] { + assert!(super::para_field_min(key) < 0.0, "{key}"); + } + for key in ["leftIndent", "rightIndent", "spaceBefore", "spaceAfter"] { + assert_eq!(super::para_field_min(key), 0.0, "{key}"); + } + } + #[test] fn stroke_panel_shows_the_text_stroke_options_while_text_is_selected() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); @@ -3094,6 +3371,9 @@ mod tests { app, ); h.run_steps(3); + assert!(h.query_by_label("Language").is_none(), "under •••, as in InDesign"); + h.get_all_by_label("More Options").next().unwrap().click(); + h.run_steps(3); h.get_by_label("Language").click(); h.run_steps(2); h.get_by_label("French").click(); @@ -3101,6 +3381,182 @@ mod tests { assert_eq!(language(h.state_mut()), "French"); } + /// Properties › Character and Paragraph •••, as in InDesign: the sections expand in place, + /// with the scales, baseline shift, skew, language, OpenType and the case buttons, and the + /// indents, spacing and drop caps. + /// Properties › Paragraph ••• on a First Line Only paragraph: Align to Baseline Grid shows + /// pressed, and a click turns alignment off instead of making it All Lines. + #[test] + fn more_options_grid_button_keeps_first_line_only() { + 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, 300, 200], "content": "text", "text": "If fine plants", "caret": true})).unwrap(); + app.run("edit.selectAll", json!({})).unwrap(); + app.run("type.para", json!({"attrs": {"gridAlign": "firstLineOnly"}})).unwrap(); + let mut h = panel_harness(app, show); + h.run_steps(3); + h.get_all_by_label("More Options").nth(1).unwrap().click(); + h.run_steps(3); + assert_eq!(h.get_by_label("Align to Baseline Grid").accesskit_node().toggled(), Some(egui::accesskit::Toggled::True)); + assert_eq!(text_attrs(h.state_mut()).unwrap()["para"]["gridAlign"], "firstLineOnly"); + h.get_by_label("Align to Baseline Grid").click(); + h.run_steps(3); + assert_eq!(text_attrs(h.state_mut()).unwrap()["para"]["gridAlign"], "none"); + } + + #[test] + fn more_options_expand_character_and_paragraph_in_place() { + 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, 300, 200], "content": "text", "text": "If fine plants", "caret": true})).unwrap(); + app.run("edit.selectAll", json!({})).unwrap(); + let mut h = panel_harness(app, show); + h.run_steps(3); + for l in ["Vertical Scale", "Small Caps", "Drop Cap Number of Lines", "Space Before"] { + assert!(h.query_by_label(l).is_none(), "{l} hidden until •••"); + } + h.get_all_by_label("More Options").next().unwrap().click(); + h.run_steps(3); + h.get_by_label("Small Caps").click(); + h.run_steps(3); + let _ = h.get_by_label("OpenType"); + let _ = h.get_by_label("Language"); + h.get_all_by_label("More Options").nth(1).unwrap().click(); + h.run_steps(3); + let _ = h.get_by_label("Hyphenate"); + h.get_by_label("Align to Baseline Grid").click(); + h.run_steps(3); + let a = text_attrs(h.state_mut()).unwrap(); + assert_eq!(a["chars"]["capitalization"], "smallCaps"); + assert_eq!(a["para"]["gridAlign"], "allLines"); + // ••• again folds the section. + h.get_all_by_label("More Options").next().unwrap().click(); + h.run_steps(3); + assert!(h.query_by_label("Small Caps").is_none()); + } + + /// The Paragraph panel on a First Line Only paragraph: Align to Baseline Grid shows pressed + /// and keeps First Line Only, and the panel menu checks Only Align First Line to Grid. + #[test] + fn paragraph_panel_keeps_first_line_only() { + let mut app = text_app(); + app.run("type.para", json!({"attrs": {"gridAlign": "firstLineOnly"}})).unwrap(); + let mut h = panel_harness(app, paragraph_panel); + h.run_steps(3); + assert_eq!(h.get_by_label("Align to Baseline Grid").accesskit_node().toggled(), Some(egui::accesskit::Toggled::True)); + h.get_by_label("Align to Baseline Grid").click(); + h.run_steps(3); + assert_eq!(text_attrs(h.state_mut()).unwrap()["para"]["gridAlign"], "firstLineOnly"); + h.get_by_label("☰").click(); + h.run_steps(3); + 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); + h.run_steps(3); + h.get_by_label("☰").click(); + h.run_steps(3); + h.get_by_label("Define Lists…").click(); + h.run_steps(3); + assert!(h.state_mut().ui.dialog.is_some(), "Define Lists"); + } + + #[test] + fn paragraph_panel_is_laid_out_as_indesigns_with_its_panel_menu() { + let mut h = panel_harness(text_app(), paragraph_panel); + h.run_steps(3); + for l in [ + "Left Indent", + "Right Indent", + "First Line Left Indent", + "Last Line Right Indent", + "Space Before", + "Space After", + "Space Between Paragraphs Using Same Style", + "Drop Cap Number of Lines", + "Drop Cap One or More Characters", + "Paragraph Shading", + "Paragraph Border", + "Hyphenate", + "Do Not Align to Baseline Grid", + ] { + let _ = h.get_by_label(l); + } + let para = |h: &mut Harness<'static, DesignApp>| text_attrs(h.state_mut()).unwrap()["para"].clone(); + // Space Between Paragraphs Using Same Style starts at Ignore; a value is set, and emptying + // the field ignores it again. + assert!(para(&mut h)["sameParaStyleSpacing"].is_null()); + let field = h.get_all_by_role(egui::accesskit::Role::TextInput).nth(6).unwrap(); + field.focus(); + field.type_text("6 pt"); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(para(&mut h)["sameParaStyleSpacing"], 6.0); + h.get_all_by_role(egui::accesskit::Role::TextInput).nth(6).unwrap().focus(); + h.run_steps(1); + for _ in 0..8 { + h.key_press(egui::Key::Backspace); + } + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(para(&mut h)["sameParaStyleSpacing"].is_null(), "Ignore"); + // Shading on, then the grid buttons and Only Align First Line to Grid from the menu. + h.get_by_label("Shading").click(); + h.run_steps(3); + assert_eq!(para(&mut h)["shadingOn"], true); + h.get_by_label("Align to Baseline Grid").click(); + h.run_steps(3); + assert_eq!(para(&mut h)["gridAlign"], "allLines"); + h.get_by_label("☰").click(); + h.run_steps(3); + for l in [ + " Balance Ragged Lines", + "Keep Options…", + "Drop Caps and Nested Styles…", + "GREP Styles…", + "Define Lists…", + "Restart/Continue Numbering", + ] { + let _ = h.get_by_label(l); + } + h.get_by_label(" Only Align First Line to Grid").click(); + h.run_steps(3); + assert_eq!(para(&mut h)["gridAlign"], "firstLineOnly"); + h.get_by_label("Do Not Align to Baseline Grid").click(); + h.run_steps(3); + assert_eq!(para(&mut h)["gridAlign"], "none"); + // Keep Options… opens the selected paragraphs' Keep Options, and OK applies them. + h.get_by_label("☰").click(); + h.run_steps(3); + h.get_by_label("Keep Options…").click(); + h.run_steps(3); + let app = h.state_mut(); + let d = app.ui.dialog.as_mut().expect("Keep Options"); + assert_eq!((d.id.as_str(), d.s("section").as_str()), ("paragraphLocal", "keep")); + d.fields.insert("p.keepWithNext".into(), json!(2)); + crate::dialogs::confirm(app).unwrap(); + assert_eq!(para(&mut h)["keepWithNext"], 2); + } + fn kerning(app: &mut DesignApp) -> Value { text_attrs(app).unwrap()["chars"]["kerning"].clone() } @@ -3364,6 +3820,35 @@ mod tests { h } + /// The course's chapter 21: Properties' Bulleted List button gives the selected paragraphs + /// bullets with InDesign's hanging indent; pressed again, both go. + #[test] + fn the_bulleted_list_button_applies_a_hanging_indent() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app + .run( + "frame.create", + json!({"rect": [72, 72, 300, 200], "content": "text", "text": "4 eggs +1 cup milk"}), + ) + .unwrap(); + app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 15})).unwrap(); + let mut h = panel(app); + h.get_by_label("Bulleted List").click(); + h.run_steps(3); + let a = h.state_mut().run("type.selectionAttrs", json!({})).unwrap(); + assert_eq!( + (a["para"]["listType"].as_str(), a["para"]["leftIndent"].as_f64(), a["para"]["firstLineIndent"].as_f64()), + (Some("bullets"), Some(18.0), Some(-18.0)) + ); + assert_eq!(crate::menus::checked(h.state(), "list.bullets", &json!({})), Some(true), "Type › Apply Bullets shows it"); + h.get_by_label("Bulleted List").click(); + h.run_steps(3); + let a = h.state_mut().run("type.selectionAttrs", json!({})).unwrap(); + assert_eq!((a["para"]["listType"].as_str(), a["para"]["leftIndent"].as_f64()), (Some("none"), Some(0.0))); + } + #[test] fn several_shapes_show_pathfinder_and_intersect_combines_them() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/panels/story.rs b/crates/ui-egui/src/panels/story.rs new file mode 100644 index 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::(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 { + 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/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index fb9876aa2..e820e21a8 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -80,6 +80,10 @@ pub struct NumField<'a> { range: (f64, f64), enabled: bool, parens: bool, + /// The widget naming the field (an icon or caption beside it), for accessibility. + label: Option, + /// What an unset value shows (InDesign's "Ignore"), and the first of the presets. + empty: Option<&'a str>, } impl<'a> NumField<'a> { @@ -90,7 +94,20 @@ impl<'a> NumField<'a> { Self::new(id, value, NumKind::Number { suffix, decimals }) } fn new(id: &'a str, value: Option, kind: NumKind<'a>) -> Self { - NumField { id, value, kind, width: 72.0, spinner: false, presets: &[], step: None, range: (f64::MIN, f64::MAX), enabled: true, parens: false } + NumField { + id, + value, + kind, + width: 72.0, + spinner: false, + presets: &[], + step: None, + range: (f64::MIN, f64::MAX), + enabled: true, + parens: false, + label: None, + empty: None, + } } /// Total width (spinner and preset segments included). pub fn width(mut self, w: f32) -> Self { @@ -130,6 +147,19 @@ impl<'a> NumField<'a> { self.enabled = on; self } + /// The editor is labelled by widget `id` (an icon or caption that names the field), so + /// assistive technology reads the field's name with its value. + pub fn labelled_by(mut self, id: egui::Id) -> Self { + self.label = Some(id); + self + } + + /// An unset value shows `text` (dimmed), and the preset menu offers it first: picking it, or + /// emptying the field, commits `Some(None)` from [`NumField::show_or_clear`]. + pub fn empty_text(mut self, text: &'a str) -> Self { + self.empty = Some(text); + self + } /// Draw the field; returns the new value when the user commits an edit (Enter, focus loss, /// a spinner click, ↑/↓ while focused (Shift = ×10) or a preset). @@ -194,13 +224,16 @@ impl<'a> NumField<'a> { // Value. ui.painter().rect_filled(text_rect, 0.0, bg); let mut buf: String = ui.data(|d| d.get_temp::(key)).unwrap_or_else(|| self.value.map(|v| self.fmt(v)).unwrap_or_default()); - let te = egui::TextEdit::singleline(&mut buf) + let mut te = egui::TextEdit::singleline(&mut buf) .id(focused_id) .frame(egui::Frame::NONE) .font(label_font()) .text_color(fg) .margin(egui::Margin::ZERO) .vertical_align(egui::Align::Center); + if let Some(empty) = self.empty { + te = te.hint_text(egui::RichText::new(empty).font(label_font()).color(t.text_dim)); + } // The field already allocated its slot. A scoped allocation here would consume another // grid cell and enlarge toolbar rows; the value editor must stay inside that same slot. let value_rect = Rect::from_min_max(text_rect.min + vec2(5.0, 1.0), text_rect.max - vec2(1.0, 1.0)); @@ -210,6 +243,10 @@ impl<'a> NumField<'a> { editor_ui.disable(); } let r = editor_ui.put(value_rect, te); + let r = match self.label { + Some(id) => r.labelled_by(id), + None => r, + }; if r.has_focus() { // ↑/↓ step the value while typing. let (up, down, shift) = ui.input_mut(|i| { @@ -227,8 +264,14 @@ impl<'a> NumField<'a> { ui.data_mut(|d| d.insert_temp(key, buf.clone())); } if r.lost_focus() { - if let Some(v) = self.parse(&buf).map(clamp) - && self.value.is_none_or(|old| (old - v).abs() > 1e-9) + // An automatic value (in parentheses) typed over commits even when it's the same + // number: typing "14.4 pt" over "(14.4 pt)" makes it a fixed value. Escape reverts + // whatever was typed, as in InDesign. + let escaped = ui.input(|i| i.key_pressed(egui::Key::Escape)); + let typed_over_auto = self.parens && !buf.trim_start().starts_with('('); + if escaped { + } else if let Some(v) = self.parse(&buf).map(clamp) + && (typed_over_auto || self.value.is_none_or(|old| (old - v).abs() > 1e-9)) { out = Some(v); } else if buf.trim().is_empty() && self.value.is_some() { @@ -253,6 +296,12 @@ impl<'a> NumField<'a> { if let Some(resp) = preset_resp { egui::Popup::menu(&resp).show(|ui| { ui.set_min_width(self.width); + if let Some(empty) = self.empty + && ui.selectable_label(self.value.is_none(), empty).clicked() + { + cleared = self.value.is_some(); + ui.close(); + } for v in self.presets { if ui.selectable_label(self.value.is_some_and(|c| (c - v).abs() < 1e-9), self.kind.format(*v)).clicked() { out = Some(*v); @@ -382,6 +431,8 @@ pub fn more_options(ui: &mut Ui, language: &str) -> Response { let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), 14.0), Sense::hover()); let r = Rect::from_min_max(pos2(row.max.x - 26.0, row.min.y), pos2(row.max.x - 4.0, row.max.y)); let resp = ui.interact(r, ui.id().with(("more", row.min.y as i32)), Sense::click()); + let label = crate::i18n::tr(language, "More Options"); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label)); for i in 0..3 { ui.painter().circle_filled(pos2(r.min.x + 4.0 + i as f32 * 7.0, r.center().y), 1.9, if resp.hovered() { t.text_strong } else { t.icon }); } @@ -567,6 +618,8 @@ pub fn checkbox(ui: &mut Ui, on: &mut bool, label: &str) -> Response { *on = !*on; resp.mark_changed(); } + let checked = *on; + resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, true, checked, label)); resp } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8ae902a21..6e676c470 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # DesignCraft parity with Adobe InDesign -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (custom anchored objects honour Relative to Spine; PDF/X-4 visible unembedded font detection, #909; autoflow fills the following pages first; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; image clipping paths from IDML; anchored objects wrap text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; recovery checkpoint retention; cancelable macOS Dock Quit; Based on Parent; object styles carry effects; colour management on craft-cms, Coated FOGRA39 default CMYK; swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (list buttons with the default hanging indent; custom anchored objects honour Relative to Spine; PDF/X-4 visible unembedded font detection, #909; autoflow fills the following pages first; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; image clipping paths from IDML; anchored objects wrap text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; recovery checkpoint retention; cancelable macOS Dock Quit; Based on Parent; object styles carry effects; colour management on craft-cms, Coated FOGRA39 default CMYK; swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS) The authoritative assessment of how close DesignCraft is to Adobe InDesign. [ROADMAP.md](../ROADMAP.md) summarizes it; [gaps.md](gaps.md) lists every known shortfall one at a time; the feature-by-feature @@ -382,7 +382,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Split Window / New Window (`window.split`, `window.newWindow`, Window ▸ Arrange): two side-by-side views of the document with their own zoom, scroll and render cache. New Window puts the second view in its own OS window (an egui viewport; a floating window on the web). - Transparency flattener (`file.exportPdf {flatten: high|medium|low|ppi}`, Edit ▸ Transparency Flattener Presets): each object involving transparency becomes an opaque image of its area over what's beneath it, so everything else stays vector (spreads with transparent parent items are rasterised whole). - Video and sound (place .mp4/.mov/.webm/.mp3/.wav…, `media.options/get`, Media panel): media frames show a poster or placeholder on screen, in print and in PDF, and export as HTML5 `