Skip to content

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

Merge remote-tracking branch 'origin/main' into codex/toc-pdf-bookmarks

moppeeerc0b4746c8df5
diff --cc ROADMAP.md
index 255c941d7,c02176bab..a7f31eecb
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -346,10 -378,85 +378,87 @@@ list) · [roadmap.md](docs/roadmap.md)
## Progress log
+- **2026-10-18** · Table of Contents gains Create PDF Bookmarks: included headings become nested page destinations, regenerated in their existing outline position on update without replacing or moving surrounding manual bookmarks. The setting survives native and IDML files. No readiness percentage change.
+
Newest first.
+ - **2026-10-27** · An iconic panel's flyout stays open while you work in the canvas or a text field: Auto-Collapse Iconic Panels is off by default, and preferences saved with it on start with it off. Preferences › Interface › Panels holds the setting next to the column bar's menu item. No readiness percentage change.
+ - **2026-10-24** · Column rules run from the top line's ascent to the bottom line's descent, as InDesign draws them, instead of from the top to the bottom of the columns, on screen, in PDF and in PowerPoint export. The top and bottom insets shorten the rule from those lines. Existing documents draw their column rules at the new length. No readiness percentage change.
+ - **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change.
+ - **2026-10-19** · Import InDesign Set… runs on craft-keymap's importer: a set's Window menu panel items (Layers F7, Pages F12, Swatches F5) and Tools items set the panel and tool shortcuts, all of an item's Default keys apply, and the report adds numeric keypad keys read as main keys and likely commands for unmatched items (`window.importShortcuts`). On InDesign's Windows defaults it matches 366 of 1,629 items (was 233) and changes 23 commands. No readiness percentage change.
+ - **2026-10-19** · Keyboard shortcuts run on the shared craft-keymap crate. Panels take shortcuts, with InDesign's defaults where the key is free (Swatches F5, Color F6, Layers F7, Info F8, Stroke F10, Paragraph Styles F11, Character Styles Shift+F11, Pages F12, Align Shift+F7); tool keys are editable in Edit › Keyboard Shortcuts and `window.setShortcut`, and tools sharing a key take turns (B). Saved shortcuts load 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-20** · PDF/X-1a:2003 export (craft-libs#194): `file.exportPdf {standard: "x1a"}`, the Export PDF dialog's PDF/X-1a:2003 preset and standard. The PDF/X-4 print file is flattened in its inks by craft-prepress (no transparency; spot, process, overprint and live text kept; complex regions as DeviceN images at the Transparency Flattener preset's resolution), then written as PDF 1.4 with the X-1a identification and checked; `validate-pdf --standard x1a`. Soft drop shadows reach the flattener in their swatch's inks; other soft effects are still RGB images. No readiness percentage change.
+ - **2026-10-20** · Print color (craft-libs#190): CMYK print PDFs blend in DeviceCMYK through craft-pdf's print settings instead of byte rewrites, with the CMYK working space as the output intent in PDF/X-4 only; overprint (Overprint Fill, Stroke and Gap, overprinting text, 100% [Black]) is written as `/op` `/OP` `/OPM 1`; Knockout Group writes `/K true` instead of becoming an image; File › Print prints the PDF Export PDF writes. No readiness percentage change.
+ - **2026-10-20** · Separations Preview shows the plates the exported PDF prints, spot plates included: each visible spread is exported in memory with the Export PDF settings and separated by craft-prepress off the UI thread, then shown as all inks, one plate or an ink limit. The Ink Manager builds craft-prepress's `InkSet` from the document for export and preview. On the sample magazine the first preview of a spread takes about 0.6–1.1 s, most of it the PDF export. No readiness percentage change.
+ - **2026-10-20** · Spot gradients print on their plates. A gradient stop keeps the swatch it was given (Gradient panel drop, `swatch.create {gradient}`, `object.gradient`, IDML `StopColor`), following its renames and edits. PDF export shades one spot with its tints or [Paper] as a Separation, and a spot with process inks or a second spot as DeviceN; a process gradient to [Paper] prints in DeviceCMYK. Documents with plain-color stops export as before. No readiness percentage change.
+ - **2026-10-24** · Panels dock through the suite's shared docking (craft-libs), and on desktop a floating panel opens in its own window that can leave the main window: keys pressed there run the main window's shortcuts, clipboard and tool keys, and the canvas paints no tool cursor while another of the app's windows has the pointer. The web build keeps floating panels in the page. No readiness percentage change.
+ - **2026-10-24** · Story Options rejects malformed or nonexistent explicit story/frame IDs without changing the selected story, including an invalid frame alongside a valid story. Null targets remain absent; omitted targets still use the selection. No readiness percentage change.
+ - **2026-10-24** · Text Frame Options explains that a custom baseline-grid increment must be a measure greater than zero when zero, a negative value or a non-measure is entered. Validation is unchanged. No readiness percentage change.
+ - **2026-10-24** · Renaming a paragraph or character style, or moving it into a style group, keeps its Export Tagging under the new name, and undo puts it back under the old one. Deleting a tagged style drops its tagging and leaves the replacement style's own tagging as it was. No readiness percentage change.
+ - **2026-10-24** · Quick Apply and the application bar's search leave out the interface commands that failed or reset a setting when chosen there: those that need a workspace, a command and shortcut, a menu item, a panel, a window edge, an app page, a recent file or a swatch they can't give them, a Contextual Task Bar place, and Interface Color Theme, UI Scaling, Reset Shortcuts, the flattener preset, Screen Mode and Zoom To, which without a value switched to the dark theme, set 100%, cleared every custom shortcut or the preset, or went to Normal mode or 100% zoom. Each stays in the menu, panel or dialog that gives it the value. No readiness percentage change.
+ - **2026-10-24** · EPUB Export Options › Split Document, a dialog before File › Export EPUB… saves (`document.epubSplit`, stored with the document): off, a single paragraph style, or based on paragraph style export tags, with Paragraph Style Options › Export Tagging's Split Document flag marking those styles. A reflowable EPUB is one content file unless Split Document is on; the split before each top-level h1 from #791 is gone. A split before a list item or preformatted line no longer leaves an unclosed list or block in a content file. IDML import and export keep the setting and the flag, and Load Styles the flag. No readiness percentage change.
+ - **2026-10-18** · Repeated placed-PDF layer variants are prepared once per asset and hidden-name set, with recovery warnings retained. All-visible named layers keep their original source bytes, including PDFs whose cross-reference tables the reader repairs, in plain, PDF/X-4, booklet and book-merge output. Layer changes that require writing still reject an unusable cross-reference table with a file-named damage error; the first placement error is retained (#906). No readiness percentage change.
+ - **2026-10-18** · Placed PDF optional-content defaults and per-frame overrides survive plain and PDF/X-4 vector export, including repeated placements, booklet output and book merging (#906). Source usage-application arrays are accepted; groups without a catalog configuration stay visible. Missing or unreadable default configurations and unsupported base states use all-ON defaults with a file-named export warning, retaining explicit frame overrides. Readable groups omitted from the catalog list are added with a distinct file-named warning, preserving their default ON/OFF states. Concurrent recovery warnings are combined. Malformed ON data is recoverable when a known ON base and empty OFF list prove it cannot hide artwork; missing display names are generated without changing known visibility when no override needs name matching. Contradictory states, unresolved references and ambiguous name overrides still fail export. Print-usage adjustments and IDML layer overrides remain follow-ups. No readiness percentage change.
+
+ - **2026-10-24** · Optical Margin Alignment and hanging punctuation apply to lines with a tab or a right indent tab, as both composers already measured them: the edge glyphs hang, and tab stops stay where they are. Such a line was set without the hang: a justified line that fit only because its period or closing quote hangs had its word spaces squeezed to make up for it, and text after a right indent tab stopped at the measure instead of hanging. No readiness percentage change.
+ - **2026-10-23** · `designcraft-cli mcp` takes `--automation-read-root` and `--automation-write-root` more than once, as the suite's other apps do (#1552): a path inside any root of its kind passes, and the roots' common parent, `..` or a link out of them and the other kind's roots stay refused. No readiness percentage change.
+ - **2026-10-23** · Layout › Go Back and Go Forward (Cmd+Page Up / Cmd+Page Down, Ctrl on Windows and Linux) retrace the jumps between pages (Go to Page, the page and spread commands, the Pages panel) as InDesign's do, returning to where the view was on each page at the current zoom; a new jump after going back drops the pages ahead, scrolling adds no entry, and pages deleted since are skipped. No readiness percentage change.
+ - **2026-10-24** · The Story Editor has InDesign's vertical depth ruler between the style column and the text, and View › Story Editor › Show/Hide Depth Ruler (`view.storyEditorDepthRuler`) shows or hides it in the Story Editor, remembered with the preferences. The ruler is marked in the document's vertical ruler units with how deep the story's text fills its frames, counted through its columns and threaded frames (lines set side by side, in the sub-columns of a split paragraph or on both sides of a wrap object, count once), and is shaded down to the overset point, where a red line now crosses the editor. No readiness percentage change.
+ - **2026-10-24** · Split Note (`note.split {story, id, at}`, the Notes panel's Split Note button): as in InDesign, a note splits in two at the insertion point in its text. DesignCraft moves the text after it into a new note by the same author, anchored right after the first. No readiness percentage change.
+ - **2026-10-24** · Type › Notes › Previous Note and Next Note (`note.previous`, `note.next`): as in InDesign, they move the insertion point from note to note in the story, putting the caret after the note's anchor. Each item is unavailable when no note lies in its direction in the story, or when the insertion point is in a table cell or a footnote. No readiness percentage change.
+ - **2026-10-24** · Type › Notes › Convert to Note (`note.convertFromText {author?}`): as in InDesign, the selected text leaves the story and becomes the text of a new note, whose anchor takes its place; Convert Note to Text puts it back. DesignCraft refuses a selection in a table cell, or one that holds a note, footnote, endnote, anchored object, index marker, text anchor, cross-reference or table. No readiness percentage change.
+ - **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** · Tables: a gradient swatch in a cell fill draws as a gradient on the canvas and in PDF, in one gradient space for the whole table, so it runs across cells without restarting. Cells showed the gradient's first stop as a solid colour. 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** · File › File Info… edits the document's Document Title, Author, Description, Keywords, Copyright Notice and Copyright Info URL (`file.info`), and the document saves them. PDF export (PDF/X-4 and Print Booklet included) writes the title, author, description and keywords into the PDF's document information and XMP. EPUB export takes the title and author from File Info, and HTML export takes the title. A title or author given to the export replaces File Info's, and an empty Document Title leaves the document's name as the title. 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-23** · Type › Text Variables › Convert Variable to Text (`variables.convertToText`): the variable instances in the selected text, in a story, a table cell or a footnote, become plain text of the value each shows on its own page (a running header on page 3 becomes page 3's heading). `variables.convertAllToText {name}` does the same for every instance of one variable in the document, as the Text Variables dialog's Convert to Text button. The variable stays defined; one undo step. 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.
+ - **2026-10-22** · Paragraph rules: Rule Above's offset is measured from the first line's baseline to the rule's bottom edge, as in InDesign. Rules sat one ascent too high and crossed the previous paragraph's text (reported from an imported INDD document). No readiness percentage change.
+ - **2026-10-21** · Ruler guides are selected like objects (#1282): a click with the Selection tools selects a guide (also where it crosses an object), Shift-click adds or removes one, a new guide from the rulers is selected, a marquee that touches no object selects the guides it crosses, and Edit › Select All Guides (⌥⌘G, `guide.selectAll`) selects every unlocked guide on the spread. Selected guides draw thicker in their layer's color, drag together (all of them shown moving), nudge with the arrow keys and go with Delete, each as one undo step (`guide.select`, `guide.deselect`, `guide.moveBy`, `guide.delete {}`). With one guide selected the Control bar's X (vertical guide) or Y (horizontal guide) field and Properties › Transform show where it is, as the rulers measure, and typing a value moves it there. No readiness percentage change.
+ - **2026-10-17** · PDF/X-4 export warns about fonts drawing visible text without an embedded
+ font program, including placed PDF forms; `validate-pdf` reports the font and page (#909).
+ Invisible OCR text is exempt. Detection only: fonts are not embedded or outlined automatically.
+ Repeated forms reuse context-aware font findings; a document-wide operation limit and a form-nesting depth limit
+ report incomplete checks instead of allowing excessive nested-form traversal.
+ 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: 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** · 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** · 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.
+ - **2026-10-18** · View › Screen Mode: Bleed and Slug do what they say. Both were selectable from the toolbar, the View menu and `view.screenMode` but drew the canvas exactly as Normal did, guides and all; they are preview modes now, and what each page shows reaches the bleed box or the slug box instead of stopping at the trim. The slug guide is drawn as well, in the Slug colour from Preferences › Guides & Pasteboard, which nothing had read. No readiness percentage change.
+ - **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** · 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** · 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** · 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 `<Image FillColor>` 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 --cc crates/engine/src/cmd/style/paragraph.rs
index 000000000,81711ff10..9c3a70eed
mode 000000,100644..100644
--- a/crates/engine/src/cmd/style/paragraph.rs
+++ b/crates/engine/src/cmd/style/paragraph.rs
@@@ -1,0 -1,1236 +1,1238 @@@
+ use super::{CharAttrs, CharacterStyle, ParaAttrs, ParagraphStyle, Result, Session, Styles, Value, bad, json, ok, str_param};
+
+ #[cfg(test)]
+ mod redefine_tests {
+ use super::*;
+
+ fn sample() -> (Session, Value, Value) {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let a = s.execute("frame.create", &json!({"rect":[36,36,300,200],"content":"text","text":"First header"})).unwrap();
+ let b = s.execute("frame.create", &json!({"rect":[36,240,300,400],"content":"text","text":"Second header"})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name":"Header","chars":{"size":18,"fill":"[Paper]"}})).unwrap();
+ for story in [&a["story"], &b["story"]] {
+ s.execute("text.select", &json!({"story":story,"anchor":0,"focus":5})).unwrap();
+ s.execute("style.paragraph.apply", &json!({"name":"Header"})).unwrap();
+ }
+ s.execute("text.select", &json!({"story":a["story"],"anchor":0,"focus":5})).unwrap();
+ (s, a["story"].clone(), b["story"].clone())
+ }
+
+ #[test]
+ fn redefine_paragraph_updates_other_stories_and_clears_the_source_overrides() {
+ let (mut s, a, b) = sample();
+ s.execute("style.character.create", &json!({"name":"Emphasis","chars":{"underline":true}})).unwrap();
+ s.execute("style.character.apply", &json!({"name":"Emphasis"})).unwrap();
+ s.execute("type.char", &json!({"size":20,"fill":"[Black]"})).unwrap();
+ s.execute("type.para", &json!({"spaceAfter":9})).unwrap();
+ let before = s.doc().unwrap().doc.clone();
+ let undo = s.doc().unwrap().history.undo.len();
+ s.execute("style.paragraph.redefine", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
+ assert!(s.doc().unwrap().doc.styles.para("Header").unwrap().chars.underline.is_none());
+ for story in [&a, &b] {
+ s.execute("text.select", &json!({"story":story,"anchor":0,"focus":5})).unwrap();
+ let attrs = s.execute("type.selectionAttrs", &json!({})).unwrap();
+ assert_eq!(attrs["chars"]["size"], 20.0);
+ assert_eq!(attrs["chars"]["fill"], "[Black]");
+ assert_eq!(attrs["para"]["spaceAfter"], 9.0);
+ assert_eq!(attrs["chars"]["underline"], story == &a);
+ }
+ s.execute("style.paragraph.edit", &json!({"name":"Header","chars":{"size":22}})).unwrap();
+ s.execute("text.select", &json!({"story":a,"anchor":0,"focus":5})).unwrap();
+ assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["size"], 22.0);
+ s.execute("edit.undo", &json!({})).unwrap();
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().doc, before);
+ }
+
+ #[test]
+ fn redefine_character_does_not_capture_paragraph_font_size() {
+ let (mut s, a, b) = sample();
+ s.execute("style.character.create", &json!({"name":"Underline","chars":{"underline":true}})).unwrap();
+ for story in [&a, &b] {
+ s.execute("text.select", &json!({"story":story,"anchor":0,"focus":5})).unwrap();
+ s.execute("style.character.apply", &json!({"name":"Underline"})).unwrap();
+ }
+ s.execute("type.char", &json!({"fill":"[Black]"})).unwrap();
+ s.execute("style.character.redefine", &json!({"name":"Underline"})).unwrap();
+ let style = s.doc().unwrap().doc.styles.char_style("Underline").unwrap();
+ assert!(style.chars.size.is_none());
+ assert_eq!(style.chars.underline, Some(true));
+ for story in [&a, &b] {
+ s.execute("text.select", &json!({"story":story,"anchor":0,"focus":5})).unwrap();
+ assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["fill"], "[Black]");
+ }
+ }
+
+ #[test]
+ fn redefine_rejects_the_wrong_style_and_the_none_entry_atomically() {
+ let (mut s, _, _) = sample();
+ let before = s.doc().unwrap().doc.clone();
+ let undo = s.doc().unwrap().history.undo.len();
+ assert!(s.execute("style.paragraph.redefine", &json!({"name":"Other"})).is_err());
+ assert!(s.execute("style.character.redefine", &json!({})).is_err());
+ assert_eq!(s.doc().unwrap().doc, before);
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);
+ }
+
+ #[test]
+ fn redefine_character_at_a_caret_cleans_the_source_run_but_keeps_other_overrides() {
+ let (mut s, story, _) = sample();
+ s.execute("style.character.create", &json!({"name":"Emphasis","chars":{"underline":true}})).unwrap();
+ for (start, end, size) in [(0, 5, 24), (6, 12, 32)] {
+ s.execute("text.select", &json!({"story":story,"anchor":start,"focus":end})).unwrap();
+ s.execute("style.character.apply", &json!({"name":"Emphasis"})).unwrap();
+ s.execute("type.char", &json!({"size":size})).unwrap();
+ }
+ let before = s.doc().unwrap().doc.clone();
+ s.execute("text.select", &json!({"story":story,"anchor":2,"focus":2})).unwrap();
+ s.execute("style.character.redefine", &json!({"name":"Emphasis"})).unwrap();
+ s.execute("style.character.edit", &json!({"name":"Emphasis","chars":{"size":30}})).unwrap();
+ for (start, end, size) in [(0, 5, 30.0), (6, 12, 32.0)] {
+ s.execute("text.select", &json!({"story":story,"anchor":start,"focus":end})).unwrap();
+ assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["size"], size);
+ }
+ s.execute("edit.undo", &json!({})).unwrap();
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().doc, before);
+ }
+ }
+
+ #[cfg(test)]
+ mod application_inheritance_tests {
+ use super::*;
+
+ fn setup(text: &str) -> (Session, Value) {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let f = s.execute("frame.create", &json!({"rect": [36,36,300,300], "content": "text", "text": text})).unwrap();
+ (s, f["story"].clone())
+ }
+ fn select(s: &mut Session, story: &Value, start: usize, end: usize) {
+ s.execute("text.select", &json!({"story": story, "anchor": start, "focus": end})).unwrap();
+ }
+ fn attrs(s: &mut Session) -> Value {
+ s.execute("type.selectionAttrs", &json!({})).unwrap()
+ }
+
+ #[test]
+ fn paragraph_capture_source_follows_later_style_edits_and_undo() {
+ let (mut s, story) = setup("First\nSecond");
+ select(&mut s, &story, 0, 5);
+ s.execute("type.char", &json!({"size": 18, "fill": "[Paper]"})).unwrap();
+ s.execute("type.para", &json!({"spaceAfter": 6})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Header", "fromSelection": true})).unwrap();
+ let before = s.doc().unwrap().doc.clone();
+ let undo = s.doc().unwrap().history.undo.len();
+ s.execute("style.paragraph.apply", &json!({"name": "Header"})).unwrap();
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().doc, before);
+ s.execute("edit.redo", &json!({})).unwrap();
+ select(&mut s, &story, 6, 6);
+ s.execute("style.paragraph.apply", &json!({"name": "Header"})).unwrap();
+ s.execute("style.paragraph.edit", &json!({"name": "Header", "chars": {"size": 20, "fill": "[Black]"}, "para": {"spaceAfter": 12}})).unwrap();
+ for pos in [0, 6] {
+ select(&mut s, &story, pos, pos + 1);
+ let a = attrs(&mut s);
+ assert_eq!(a["chars"]["size"], 20.0);
+ assert_eq!(a["chars"]["fill"], "[Black]");
+ assert_eq!(a["para"]["spaceAfter"], 12.0);
+ }
+ }
+
+ #[test]
+ fn applying_styles_keeps_different_overrides_and_named_character_styles() {
+ let (mut s, story) = setup("First\nSecond");
+ select(&mut s, &story, 0, 5);
+ s.execute("type.char", &json!({"size": 14})).unwrap();
+ s.execute("type.para", &json!({"spaceAfter": 9})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Emphasis", "chars": {"underline": true}})).unwrap();
+ s.execute("style.character.apply", &json!({"name": "Emphasis"})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Body", "chars": {"size": 10}, "para": {"spaceAfter": 6}})).unwrap();
+ s.execute("style.paragraph.apply", &json!({"name": "Body"})).unwrap();
+ let a = attrs(&mut s);
+ assert_eq!(a["chars"]["size"], 14.0);
+ assert_eq!(a["para"]["spaceAfter"], 9.0);
+ assert_eq!(a["characterStyle"], "Emphasis");
+ assert_eq!(a["chars"]["underline"], true);
+ }
+
+ #[test]
+ fn character_capture_source_remains_sparse_and_follows_style_edits() {
+ let (mut s, story) = setup("First\nSecond");
+ select(&mut s, &story, 0, 5);
+ s.execute("type.char", &json!({"underline": true})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Emphasis", "fromSelection": true})).unwrap();
+ s.execute("style.character.apply", &json!({"name": "Emphasis"})).unwrap();
+ s.execute("style.character.edit", &json!({"name": "Emphasis", "chars": {"underline": false}})).unwrap();
+ assert_eq!(attrs(&mut s)["chars"]["underline"], false);
+ assert!(s.doc().unwrap().doc.styles.char_style("Emphasis").unwrap().chars.size.is_none());
+ s.execute("style.paragraph.edit", &json!({"name": designcraft_doc::BASIC_PARAGRAPH, "chars": {"size": 20}})).unwrap();
+ assert_eq!(attrs(&mut s)["chars"]["size"], 20.0);
+ }
+
+ #[test]
+ fn paragraph_selection_excludes_the_next_paragraph_at_its_start() {
+ let (mut s, story) = setup("é\nNext");
+ select(&mut s, &story, 0, 3);
+ s.execute("style.paragraph.create", &json!({"name": "Header"})).unwrap();
+ s.execute("style.paragraph.apply", &json!({"name": "Header", "clearOverrides": true})).unwrap();
+ select(&mut s, &story, 3, 4);
+ assert_eq!(attrs(&mut s)["paragraphStyle"], designcraft_doc::BASIC_PARAGRAPH);
+ select(&mut s, &story, 0, 2);
+ assert_eq!(attrs(&mut s)["paragraphStyle"], "Header");
+ }
+
+ #[test]
+ fn clearing_a_partial_selection_preserves_character_overrides_outside_it() {
+ let (mut s, story) = setup("First Second");
+ select(&mut s, &story, 0, 12);
+ s.execute("type.char", &json!({"size": 18})).unwrap();
+ select(&mut s, &story, 0, 5);
+ s.execute("style.paragraph.apply", &json!({"name": designcraft_doc::BASIC_PARAGRAPH, "clearOverrides": true})).unwrap();
+ assert_ne!(attrs(&mut s)["chars"]["size"], 18.0);
+ select(&mut s, &story, 6, 12);
+ assert_eq!(attrs(&mut s)["chars"]["size"], 18.0);
+ }
+ }
+
+ /// The `group` (`chars`, `para`) object of command `cmd`'s params as attributes; a bad attribute
+ /// is that command's parameter error, naming the group.
+ fn attrs<T: Default>(cmd: &str, group: &str, p: &Value, set: impl Fn(&mut T, &str, &Value) -> std::result::Result<(), String>) -> Result<T> {
+ let mut a = T::default();
+ match p.get(group) {
+ None | Some(Value::Null) => {}
+ Some(Value::Object(o)) => {
+ for (k, v) in o {
+ set(&mut a, k, v).map_err(|e| bad(cmd, format!("{group}: {e}")))?;
+ }
+ }
+ Some(_) => return Err(bad(cmd, format!("{group} must be an object of attributes"))),
+ }
+ Ok(a)
+ }
+
+ pub(super) fn redefine(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {
+ let command = if paragraph { "style.paragraph.redefine" } else { "style.character.redefine" };
+ let targets = crate::cmd::text::format_targets_pub(s);
+ let target = targets.first().ok_or_else(|| bad(command, "select text using the style to redefine"))?;
+ let state = s.doc()?;
+ let story = state.doc.text_story(target.story, target.cell).ok_or(designcraft_doc::DocError::NoStory(target.story))?;
+ let pf = story.paras.get(story.para_at(target.range.start)).ok_or_else(|| bad(command, "no paragraph at the selection"))?;
+ let cf = crate::cmd::text::effective_char_format(s, target)?;
+ let selected = if paragraph { &pf.style } else { &cf.style };
+ let name = str_param(p, "name").unwrap_or(selected).to_string();
+ if name != *selected || name == if paragraph { designcraft_doc::NO_PARA_STYLE } else { designcraft_doc::NO_CHAR_STYLE } {
+ return Err(bad(command, "select text using the named style; the no-style entry cannot be redefined"));
+ }
+ let (base_para, base_chars) = state.doc.styles.resolve_para_style(&pf.style);
+ let (resolved_para, paragraph_chars) = state.doc.styles.resolve_para(pf);
+ let para_changes = base_para.delta(&resolved_para);
+ let mut current = if paragraph {
+ paragraph_chars.clone()
+ } else {
+ state.doc.styles.resolve_char(&paragraph_chars, &designcraft_doc::CharFormat { style: name.clone(), over: CharAttrs::default() })
+ };
+ let inherited = if paragraph { base_chars } else { current.clone() };
+ // A named character style is an intentional layer, not a paragraph override to absorb.
+ current.apply(&cf.over);
+ let char_changes = inherited.delta(&current);
+ let result = s.edit(|d, _| {
+ if paragraph {
+ let style = d.styles_mut().para_mut(&name).ok_or_else(|| bad(command, "paragraph style no longer exists"))?;
+ style.para.merge(&para_changes);
+ style.chars.merge(&char_changes);
+ } else {
+ let style =
+ d.styles_mut().character.iter_mut().find(|st| st.name == name).ok_or_else(|| bad(command, "character style no longer exists"))?;
+ style.chars.merge(&char_changes);
+ }
+ let styles = d.styles.clone();
+ for target in &targets {
+ let Some(story) = d.text_story_mut(target.story, target.cell) else { continue };
+ // At a character-style caret, the sampled format belongs to the containing run
+ // (the preceding run at a boundary). Normalize that source run too, otherwise its
+ // old local values would mask the next edit of the redefined style.
+ let mut selected_range = target.range.clone();
+ if !paragraph && selected_range.is_empty() {
+ let caret = selected_range.start;
+ let mut start = 0usize;
+ for run in &story.chars {
+ let end = start.saturating_add(run.len).min(story.len());
+ if caret < end || (caret == end && caret > start) {
+ selected_range = start..end;
+ break;
+ }
+ start = end;
+ }
+ }
+ let end = if selected_range.is_empty() { selected_range.start } else { selected_range.end.saturating_sub(1) };
+ let (first, last) = (story.para_at(selected_range.start), story.para_at(end));
+ for (index, range) in story.para_ranges().into_iter().enumerate().take(last.saturating_add(1)).skip(first) {
+ let Some(pf) = story.paras.get_mut(index) else { continue };
+ if paragraph && pf.style != name {
+ continue;
+ }
+ if paragraph {
+ let (pp, cp) = styles.resolve_para(pf);
+ let (base_p, base_c) = styles.resolve_para_style(&name);
+ pf.para = base_p.delta(&pp);
+ pf.chars = base_c.delta(&cp);
+ }
+ let (_, base) = styles.resolve_para(pf);
+ let end = range.end.saturating_add(1).min(story.len());
+ let range = if paragraph { range.start..end } else { range.start.max(selected_range.start)..end.min(selected_range.end) };
+ story.format_chars(range, |format| {
+ if !paragraph && format.style != name {
+ return;
+ }
+ let mut inherited = base.clone();
+ inherited.apply(&styles.char_style_attrs(&format.style));
+ let resolved = styles.resolve_char(&base, format);
+ format.over = inherited.delta(&resolved);
+ });
+ }
+ }
+ Ok(json!({"name":name}))
+ });
+ if result.is_ok() {
+ s.typing_format = None;
+ }
+ result
+ }
+
+ /// Apply paragraph style `name` over `r` in one story; `clear` drops overrides instead of keeping
+ /// only those that differ from the style (`resolved` is the style's paragraph and character attributes).
+ fn apply_para_in_story(
+ st: &mut designcraft_doc::Story,
+ r: &std::ops::Range<usize>,
+ name: &str,
+ clear: bool,
+ resolved: (&designcraft_doc::ParaProps, &designcraft_doc::CharProps),
+ styles: &designcraft_doc::Styles,
+ ) {
+ let (style_para, style_chars) = resolved;
+ // Text selections are half-open: a selection ending at the next paragraph's
+ // start must not apply a style to that paragraph too.
+ let end = if r.is_empty() { r.start } else { r.end.saturating_sub(1) };
+ let (first, last) = (st.para_at(r.start), st.para_at(end));
+ st.format_paras(r.start..end, |f| {
+ f.style = name.to_string();
+ if clear {
+ f.para = ParaAttrs::default();
+ f.chars = CharAttrs::default();
+ } else {
+ f.para.retain_differences(style_para);
+ f.chars.retain_differences(style_chars);
+ }
+ });
+ for (pi, range) in st.para_ranges().into_iter().enumerate().take(last.saturating_add(1)).skip(first) {
+ let Some(pf) = st.paras.get(pi) else { continue };
+ let (_, base) = styles.resolve_para(pf);
+ let end = range.end.saturating_add(1).min(st.len());
+ let range = if clear && !r.is_empty() { range.start.max(r.start)..end.min(r.end) } else { range.start..end };
+ st.format_chars(range, |f| {
+ if clear {
+ f.over = CharAttrs::default();
+ } else {
+ let mut inherited = base.clone();
+ inherited.apply(&styles.char_style_attrs(&f.style));
+ f.over.retain_differences(&inherited);
+ }
+ });
+ }
+ }
+
+ pub(super) fn apply_para(s: &mut Session, p: &Value) -> Result<Value> {
+ let name = str_param(p, "name").ok_or_else(|| bad("style.paragraph.apply", "missing name"))?.to_string();
+ let clear = p.get("clearOverrides").and_then(Value::as_bool).unwrap_or(false);
+ if s.doc()?.doc.styles.para(&name).is_none() {
+ return Err(bad("style.paragraph.apply", format!("no paragraph style `{name}`")));
+ }
+ let targets = crate::cmd::text::format_targets_pub(s);
+ s.edit(|d, _| {
+ let styles = d.styles.clone();
+ let (style_para, style_chars) = styles.resolve_para_style(&name);
+ for t in &targets {
+ if let Some(st) = d.text_story_mut(t.story, t.cell) {
+ apply_para_in_story(st, &t.range, &name, clear, (&style_para, &style_chars), &styles);
+ }
+ }
+ ok()
+ })
+ }
+
+ pub(super) fn apply_char(s: &mut Session, p: &Value) -> Result<Value> {
+ let name = str_param(p, "name").ok_or_else(|| bad("style.character.apply", "missing name"))?.to_string();
+ if s.doc()?.doc.styles.char_style(&name).is_none() {
+ return Err(bad("style.character.apply", format!("no character style `{name}`")));
+ }
+ let targets = crate::cmd::text::format_targets_pub(s);
+ s.edit(|d, _| {
+ let styles = d.styles.clone();
+ for t in &targets {
+ if let Some(st) = d.text_story_mut(t.story, t.cell) {
+ for (pi, range) in st.para_ranges().into_iter().enumerate() {
+ let range = range.start.max(t.range.start)..range.end.saturating_add(1).min(st.len()).min(t.range.end);
+ if range.is_empty() {
+ continue;
+ }
+ let Some(pf) = st.paras.get(pi) else { continue };
+ let (_, mut inherited) = styles.resolve_para(pf);
+ inherited.apply(&styles.char_style_attrs(&name));
+ st.format_chars(range, |f| {
+ f.style = name.clone();
+ f.over.retain_differences(&inherited);
+ });
+ }
+ }
+ }
+ ok()
+ })
+ }
+
+ /// In a style, `startAt: null` is Continue from Previous Number: it is stored as an explicit
+ /// "continue" so it also overrides a Start At the style would inherit.
+ fn continue_numbering(p: Option<&Value>, para: &mut ParaAttrs) {
+ let explicit =
+ p.and_then(Value::as_object).is_some_and(|o| o.iter().any(|(k, v)| v.is_null() && k.replace('_', "").eq_ignore_ascii_case("startAt")));
+ if explicit {
+ para.start_at = Some(None);
+ }
+ }
+
+ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result<Value> {
+ let base = str_param(p, "name").unwrap_or("Paragraph Style 1").to_string();
+ let mut para: ParaAttrs =
+ attrs("style.paragraph.create", "para", p, |a: &mut ParaAttrs, k, v| a.set_json_over(k, v, &designcraft_doc::ParaProps::default()))?;
+ continue_numbering(p.get("para"), &mut para);
+ explicit_default_kinsoku(&mut para, p.get("para"));
+ check_grep_styles("style.paragraph.create", &para)?;
+ let mut chars: CharAttrs = attrs("style.paragraph.create", "chars", p, |a: &mut CharAttrs, k, v| a.set_json(k, v))?;
+ // Validate caller-supplied fills, not selection fills retained after a swatch is deleted.
+ crate::cmd::text::validate_char_fill(&s.doc()?.doc, &chars, "style.paragraph.create")?;
+ if p.get("fromSelection").and_then(Value::as_bool).unwrap_or(false)
+ && let Ok(cur) = s.execute("type.selectionAttrs", &json!({}))
+ && !cur.is_null()
+ {
+ if let Ok(pp) = serde_json::from_value::<designcraft_doc::ParaProps>(cur["para"].clone()) {
+ let mut full = ParaProps_to_attrs(&pp);
+ full.merge(&para);
+ para = full;
+ }
+ if let Ok(cp) = serde_json::from_value::<designcraft_doc::CharProps>(cur["chars"].clone()) {
+ let mut full = CharProps_to_attrs(&cp);
+ full.merge(&chars);
+ chars = full;
+ }
+ }
+ let based_on = str_param(p, "basedOn").map(str::to_string);
+ let next = str_param(p, "nextStyle").map(str::to_string);
+ s.edit(|d, _| {
+ let name = Styles::unique_name(|n| d.styles.para(n).is_some(), &base);
+ if let Some(b) = &based_on
+ && d.styles.para(b).is_none()
+ {
+ return Err(bad("style.paragraph.create", format!("no style `{b}`")));
+ }
+ d.styles_mut().paragraph.push(ParagraphStyle { name: name.clone(), based_on, next_style: next, para, chars, shortcut: String::new() });
+ Ok(json!({"name": name}))
+ })
+ }
+
+ /// `kinsoku: null` sets the composer's default kinsoku rules, also over a Based On style's set.
+ /// For the other attributes `null` leaves the style's value as it is.
+ fn explicit_default_kinsoku(para: &mut ParaAttrs, given: Option<&Value>) {
+ if given.and_then(|o| o.get("kinsoku")).is_some_and(Value::is_null) {
+ para.kinsoku = Some(None);
+ }
+ }
+
+ /// The compile error of the first GREP style in `a` whose pattern can't compile.
+ pub(crate) fn grep_style_error(a: &ParaAttrs) -> Option<String> {
+ a.grep_styles
+ .iter()
+ .flatten()
+ .filter(|g| !g.pattern.is_empty())
+ .find_map(|g| designcraft_compose::grep::Grep::new(&g.pattern, Default::default()).err().map(|e| format!("{e} (pattern {:?})", g.pattern)))
+ }
+
+ /// Rejects GREP styles a command would set with a pattern that can't compile.
+ pub(crate) fn check_grep_styles(cmd: &str, a: &ParaAttrs) -> Result<()> {
+ grep_style_error(a).map_or(Ok(()), |e| Err(bad(cmd, e)))
+ }
+
+ /// One warning for each paragraph style or paragraph whose GREP style pattern can't compile.
+ /// Such a GREP style stays in the document and composition skips it.
+ pub(crate) fn grep_style_warnings(d: &designcraft_doc::Document) -> Vec<String> {
+ let mut out: Vec<String> = d
+ .styles
+ .paragraph
+ .iter()
+ .filter_map(|st| grep_style_error(&st.para).map(|e| format!("paragraph style {:?}: GREP style not applied: {e}", st.name)))
+ .collect();
+ for st in d.stories.values() {
+ for (i, pf) in st.paras.iter().enumerate() {
+ if let Some(e) = grep_style_error(&pf.para) {
+ out.push(format!("story {} paragraph {}: GREP style not applied: {e}", st.id.0, i + 1));
+ }
+ }
+ }
+ out
+ }
+
+ #[allow(non_snake_case)]
+ fn ParaProps_to_attrs(p: &designcraft_doc::ParaProps) -> ParaAttrs {
+ designcraft_doc::ParaProps::common([p])
+ }
+
+ #[allow(non_snake_case)]
+ fn CharProps_to_attrs(p: &designcraft_doc::CharProps) -> CharAttrs {
+ designcraft_doc::CharProps::common([p])
+ }
+
+ pub(super) fn edit_para(s: &mut Session, p: &Value) -> Result<Value> {
+ let name = str_param(p, "name").ok_or_else(|| bad("style.paragraph.edit", "missing name"))?.to_string();
+ let chars: CharAttrs = attrs("style.paragraph.edit", "chars", p, |a: &mut CharAttrs, k, v| a.set_json(k, v))?;
+ crate::cmd::text::validate_char_fill(&s.doc()?.doc, &chars, "style.paragraph.edit")?;
+ let rename = str_param(p, "rename").map(str::trim).filter(|n| *n != name).map(str::to_string);
+ let based = p.get("basedOn").cloned();
+ s.edit(|d, _| {
+ if let Some(Value::String(b)) = &based
+ && d.styles.para_based_on_cycles(&name, b)
+ {
+ return Err(bad("style.paragraph.edit", "based-on would create a cycle"));
+ }
+ if let Some(n) = &rename {
+ if n.is_empty() || n.starts_with('[') {
+ return Err(bad("style.paragraph.edit", format!("can't rename to `{n}`")));
+ }
+ if d.styles.para(n).is_some() {
+ return Err(bad("style.paragraph.edit", format!("a paragraph style named `{n}` already exists")));
+ }
+ }
+ // A rule object changes only the rule fields it names, over the style's resolved rule.
+ let (current, _) = d.styles.resolve_para_style(&name);
+ let mut para: ParaAttrs = attrs("style.paragraph.edit", "para", p, |a: &mut ParaAttrs, k, v| a.set_json_over(k, v, &current))?;
+ continue_numbering(p.get("para"), &mut para);
+ explicit_default_kinsoku(&mut para, p.get("para"));
+ check_grep_styles("style.paragraph.edit", &para)?;
+ let st = d.styles_mut().para_mut(&name).ok_or_else(|| bad("style.paragraph.edit", format!("no style `{name}`")))?;
+ st.para.merge(&para);
+ st.chars.merge(&chars);
+ match based {
+ Some(Value::String(b)) => st.based_on = Some(b),
+ Some(Value::Null) => st.based_on = None,
+ _ => {}
+ }
+ if let Some(n) = rename.clone() {
+ // Every use: other styles, stories, table cells, footnotes, object styles.
+ rename_style(d, true, &name, &n);
+ }
+ ok()
+ })
+ }
+
+ /// Rename a paragraph or character style everywhere it's used; its Export Tagging follows.
+ fn rename_style(d: &mut designcraft_doc::Document, para: bool, from: &str, to: &str) {
+ let st = d.styles_mut();
+ if para {
+ for s in &mut st.paragraph {
+ if s.name == from {
+ s.name = to.to_string();
+ }
+ }
+ } else {
+ for s in &mut st.character {
+ if s.name == from {
+ s.name = to.to_string();
+ }
+ }
+ }
+ // An entry already under `to` belongs to no style (names are unique), so it never survives.
+ st.export_tags.remove(&export_tag_key(para, to));
+ if let Some(tag) = st.export_tags.remove(&export_tag_key(para, from)) {
+ st.export_tags.insert(export_tag_key(para, to), tag);
+ }
+ redirect_style_refs(d, para, from, to);
+ }
+
+ /// The `Styles::export_tags` key of a paragraph (`para`) or character style.
+ pub(super) fn export_tag_key(para: bool, name: &str) -> String {
+ format!("{}:{name}", if para { "p" } else { "c" })
+ }
+
+ /// Point every reference to style `from` at `to`, except the style's own registry entry (its
+ /// `name` field) — shared by renaming (which also updates the entry's name) and deletion (which
+ /// instead removes the entry, after its former uses point at the replacement).
+ fn redirect_style_refs(d: &mut designcraft_doc::Document, para: bool, from: &str, to: &str) {
+ let rename = |r: &mut String| {
+ if r == from {
+ *r = to.to_string();
+ }
+ };
+ let st = d.styles_mut();
+ // A style is never based on itself: when `to` was based on `from`, it takes `from`'s parent.
+ let parent_of = |based_on: Option<&String>| based_on.filter(|b| b.as_str() != to).cloned();
+ if para {
+ let from_parent = parent_of(st.paragraph.iter().find(|x| x.name == from).and_then(|x| x.based_on.as_ref()));
+ for s in &mut st.paragraph {
+ if s.based_on.as_deref() == Some(from) {
+ s.based_on = if s.name == to { from_parent.clone() } else { Some(to.to_string()) };
+ }
+ if s.next_style.as_deref() == Some(from) {
+ s.next_style = Some(to.to_string());
+ }
+ }
+ let objects = st.object.iter_mut().map(|o| &mut o.paragraph_style);
+ for r in objects.chain(st.cell.iter_mut().map(|c| &mut c.paragraph_style)) {
+ if r.as_deref() == Some(from) {
+ *r = Some(to.to_string());
+ }
+ }
+ rename(&mut st.default_paragraph);
+ let (fo, eo) = (&mut d.footnote_options, &mut d.endnote_options);
+ [&mut fo.para_style, &mut eo.para_style, &mut eo.heading_style].into_iter().for_each(rename);
+ d.toc.iter_mut().flat_map(|t| t.entries.iter_mut().map(|e| &mut e.style)).for_each(rename);
+ for t in d.toc.iter_mut() {
+ let formats = t.entries.iter_mut().map(|e| &mut e.entry_style).chain([&mut t.title_style]);
+ for r in formats.filter(|r| r.as_deref() == Some(from)) {
+ *r = Some(to.to_string());
+ }
+ }
+ if let designcraft_doc::EpubSplit::Style(n) = &mut d.settings.epub_split {
+ rename(n);
+ }
+ } else {
+ let from_parent = parent_of(st.character.iter().find(|x| x.name == from).and_then(|x| x.based_on.as_ref()));
+ for s in &mut st.character {
+ if s.based_on.as_deref() == Some(from) {
+ s.based_on = if s.name == to { from_parent.clone() } else { Some(to.to_string()) };
+ }
+ }
+ for s in &mut st.paragraph {
+ rename_char_refs(&mut s.para, from, to);
+ }
+ rename(&mut st.default_character);
+ rename(&mut d.footnote_options.ref_char_style);
+ }
+ // The table of contents' character styles ([None] is stored as no style).
+ if !para && let Some(toc) = d.toc.as_mut() {
+ for e in &mut toc.entries {
+ for n in [&mut e.page_number_style, &mut e.separator_style] {
+ if n.as_deref() == Some(from) {
+ *n = Some(to.to_string()).filter(|t| t != designcraft_doc::NO_CHAR_STYLE);
+ }
+ }
+ }
+ }
+ for sid in d.stories.keys().copied().collect::<Vec<_>>() {
+ let Some(story) = d.story_mut(sid) else { continue };
+ story.for_each_text_mut(&mut |st| {
+ if para {
+ for f in st.paras.iter_mut().filter(|f| f.style == from) {
+ f.style = to.to_string();
+ }
+ } else {
+ for r in st.chars.iter_mut().filter(|r| r.format.style == from) {
+ r.format.style = to.to_string();
+ }
+ for f in &mut st.paras {
+ rename_char_refs(&mut f.para, from, to);
+ }
+ }
+ st.rev = st.rev.wrapping_add(1);
+ });
+ }
+ }
+
+ /// Point the nested, nested line and GREP styles, and the drop cap style, of paragraph
+ /// attributes at a renamed (or deleted, pointed at its replacement) character style.
+ fn rename_char_refs(p: &mut ParaAttrs, from: &str, to: &str) {
+ let names = p.nested_styles.iter_mut().flatten().map(|n| &mut n.style);
+ let names = names.chain(p.nested_line_styles.iter_mut().flatten().map(|n| &mut n.style));
+ let names = names.chain(p.drop_cap_style.iter_mut());
+ for n in names.chain(p.grep_styles.iter_mut().flatten().map(|g| &mut g.style)) {
+ if n == from {
+ *n = to.to_string();
+ }
+ }
+ }
+
+ pub(super) fn group_styles(s: &mut Session, p: &Value) -> Result<Value> {
+ let para = match str_param(p, "kind").unwrap_or("paragraph") {
+ "paragraph" => true,
+ "character" => false,
+ k => return Err(bad("style.group", format!("unknown kind `{k}`"))),
+ };
+ let names: Vec<String> =
+ p.get("names").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();
+ let group = str_param(p, "group").unwrap_or("").trim_matches('/').to_string();
+ s.edit(|d, _| {
+ let mut renamed = serde_json::Map::new();
+ for n in &names {
+ if n.starts_with('[') {
+ return Err(bad("style.group", format!("`{n}` is built in")));
+ }
+ let exists = if para { d.styles.para(n).is_some() } else { d.styles.character.iter().any(|c| c.name == *n) };
+ if !exists {
+ return Err(bad("style.group", format!("no style `{n}`")));
+ }
+ let base = n.rsplit('/').next().unwrap_or(n);
+ let mut to = if group.is_empty() { base.to_string() } else { format!("{group}/{base}") };
+ let taken = |d: &designcraft_doc::Document, x: &str| {
+ if para { d.styles.para(x).is_some() } else { d.styles.character.iter().any(|c| c.name == x) }
+ };
+ if to != *n {
+ to = Styles::unique_name(|x| taken(d, x), &to);
+ rename_style(d, para, n, &to);
+ renamed.insert(n.clone(), json!(to));
+ }
+ }
+ Ok(json!({"renamed": renamed}))
+ })
+ }
+
+ pub(super) fn delete_para(s: &mut Session, p: &Value) -> Result<Value> {
+ delete_style(s, p, true)
+ }
+
+ pub(super) fn delete_char(s: &mut Session, p: &Value) -> Result<Value> {
+ delete_style(s, p, false)
+ }
+
+ /// Delete a paragraph (`para`) or character style; everything that used it uses `replaceWith`
+ /// (default [Basic Paragraph] or [None]) instead, in one undo step.
+ fn delete_style(s: &mut Session, p: &Value, para: bool) -> Result<Value> {
+ let (id, default) =
+ if para { ("style.paragraph.delete", designcraft_doc::BASIC_PARAGRAPH) } else { ("style.character.delete", designcraft_doc::NO_CHAR_STYLE) };
+ let name = str_param(p, "name").filter(|n| !n.is_empty()).ok_or_else(|| bad(id, "missing name"))?.to_string();
+ let repl = str_param(p, "replaceWith").unwrap_or(default).to_string();
+ if name.starts_with('[') {
+ return Err(bad(id, "built-in styles can't be deleted"));
+ }
+ if repl == name {
+ return Err(bad(id, "`replaceWith` can't be the deleted style"));
+ }
+ s.edit(|d, _| {
+ let st = &d.styles;
+ let exists = |n: &str| if para { st.para(n).is_some() } else { n == designcraft_doc::NO_CHAR_STYLE || st.char_style(n).is_some() };
+ if !exists(&name) {
+ return Err(bad(id, format!("no style `{name}`")));
+ }
+ if !exists(&repl) {
+ return Err(bad(id, format!("no style `{repl}` to replace it with")));
+ }
+ // The deleted style's children are based on the replacement, or on the deleted style's
+ // own parent when the replacement descends from it (so no based-on chain loops).
+ let (own_parent, descends) = if para {
+ (st.para(&name).and_then(|x| x.based_on.clone()), st.para_based_on_cycles(&name, &repl))
+ } else {
+ (st.char_style(&name).and_then(|x| x.based_on.clone()), st.char_based_on_cycles(&name, &repl))
+ };
+ let parent = if descends {
+ own_parent.filter(|b| *b != name)
+ } else if repl == designcraft_doc::NO_CHAR_STYLE || repl == designcraft_doc::NO_PARA_STYLE {
+ None
+ } else {
+ Some(repl.clone())
+ };
+ let st = d.styles_mut();
+ let based = if para {
+ st.paragraph.retain(|x| x.name != name);
+ st.paragraph.iter_mut().map(|x| &mut x.based_on).collect::<Vec<_>>()
+ } else {
+ st.character.retain(|x| x.name != name);
+ st.character.iter_mut().map(|x| &mut x.based_on).collect()
+ };
+ for b in based.into_iter().filter(|b| b.as_deref() == Some(name.as_str())) {
+ *b = parent.clone();
+ }
+ // The replacement keeps its own Export Tagging.
+ st.export_tags.remove(&export_tag_key(para, &name));
+ // Every other use: styles, stories, table cells, nested and GREP styles, notes, defaults.
+ redirect_style_refs(d, para, &name, &repl);
+ ok()
+ })
+ }
+
+ pub(super) fn create_char(s: &mut Session, p: &Value) -> Result<Value> {
+ let base = str_param(p, "name").unwrap_or("Character Style 1").to_string();
+ let mut chars: CharAttrs = attrs("style.character.create", "chars", p, |a: &mut CharAttrs, k, v| a.set_json(k, v))?;
+ // Validate caller-supplied fills; captured formatting may retain a deleted swatch name.
+ crate::cmd::text::validate_char_fill(&s.doc()?.doc, &chars, "style.character.create")?;
+ if p.get("fromSelection").and_then(Value::as_bool).unwrap_or(false)
+ && let Some(target) = crate::cmd::text::format_targets_pub(s).first()
+ {
+ let st = s.doc()?;
+ // Match paragraph fromSelection's first-character/caret policy, but keep paragraph
+ // attributes inherited instead of freezing the fully resolved character properties.
+ let format = crate::cmd::text::effective_char_format(s, target)?;
+ let mut captured = st.doc.styles.char_style_attrs(&format.style);
+ captured.merge(&format.over);
+ // Replay the explicit fields so null clears a captured value rather than looking absent.
+ if let Some(overrides) = p.get("chars").and_then(Value::as_object) {
+ for (key, value) in overrides {
+ captured.set_json(key, value).map_err(|e| bad("style.character.create", format!("chars: {e}")))?;
+ }
+ }
+ chars = captured;
+ }
+ // Based on [None] is based on nothing.
+ let based_on = str_param(p, "basedOn").filter(|b| *b != designcraft_doc::NO_CHAR_STYLE).map(str::to_string);
+ s.edit(|d, _| {
+ if let Some(b) = &based_on
+ && d.styles.char_style(b).is_none()
+ {
+ return Err(bad("style.character.create", format!("no character style `{b}`")));
+ }
+ let name = Styles::unique_name(|n| d.styles.char_style(n).is_some(), &base);
+ d.styles_mut().character.push(CharacterStyle { name: name.clone(), based_on, chars, shortcut: String::new() });
+ Ok(json!({"name": name}))
+ })
+ }
+
+ pub(super) fn edit_char(s: &mut Session, p: &Value) -> Result<Value> {
+ let name = str_param(p, "name").ok_or_else(|| bad("style.character.edit", "missing name"))?.to_string();
+ if name == designcraft_doc::NO_CHAR_STYLE {
+ return Err(bad("style.character.edit", "[None] can't be edited"));
+ }
+ let chars: CharAttrs = attrs("style.character.edit", "chars", p, |a: &mut CharAttrs, k, v| a.set_json(k, v))?;
+ crate::cmd::text::validate_char_fill(&s.doc()?.doc, &chars, "style.character.edit")?;
+ // `null` unsets an attribute (the style no longer sets it).
+ let unset: Vec<String> = p
+ .get("chars")
+ .and_then(Value::as_object)
+ .map(|o| o.iter().filter(|(_, v)| v.is_null()).map(|(k, _)| k.clone()).collect())
+ .unwrap_or_default();
+ let rename = str_param(p, "rename").map(str::trim).filter(|n| *n != name).map(str::to_string);
+ let based: Option<Option<String>> = match p.get("basedOn") {
+ None => None,
+ Some(Value::Null) => Some(None),
+ Some(Value::String(b)) if b == designcraft_doc::NO_CHAR_STYLE => Some(None),
+ Some(Value::String(b)) => Some(Some(b.clone())),
+ Some(_) => return Err(bad("style.character.edit", "`basedOn` is a style name or null")),
+ };
+ s.edit(|d, _| {
+ if let Some(Some(b)) = &based {
+ if d.styles.char_style(b).is_none() {
+ return Err(bad("style.character.edit", format!("no character style `{b}`")));
+ }
+ if d.styles.char_based_on_cycles(&name, b) {
+ return Err(bad("style.character.edit", "based-on would create a cycle"));
+ }
+ }
+ if let Some(n) = &rename {
+ if n.is_empty() || n.starts_with('[') {
+ return Err(bad("style.character.edit", format!("can't rename to `{n}`")));
+ }
+ if d.styles.char_style(n).is_some() {
+ return Err(bad("style.character.edit", format!("a character style named `{n}` already exists")));
+ }
+ }
+ let st = d.styles_mut().char_style_mut(&name).ok_or_else(|| bad("style.character.edit", format!("no character style `{name}`")))?;
+ st.chars.merge(&chars);
+ for k in &unset {
+ st.chars.set_json(k, &Value::Null).map_err(|e| bad("style.character.edit", e))?;
+ }
+ if let Some(b) = based.clone() {
+ st.based_on = b;
+ }
+ if let Some(n) = &rename {
+ // Every use: other styles, stories, table cells, nested and GREP styles, footnotes.
+ rename_style(d, false, &name, n);
+ }
+ ok()
+ })
+ }
+
+ /// #777: the params descriptions name the attributes, and a wrong one is the command's error.
+ #[cfg(test)]
+ mod attribute_error_tests {
+ use super::*;
+ use crate::cmd::find_command;
+
+ #[test]
+ fn a_wrong_attribute_names_the_command_and_the_right_attribute() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let err = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_err().to_string();
+ assert_eq!(
+ err(&mut s, "style.paragraph.create", json!({"name": "H", "chars": {"font": "Source Sans 3"}})),
+ "invalid parameters for `style.paragraph.create`: chars: unknown attribute `font`; did you mean `fontFamily`?"
+ );
+ assert_eq!(
+ err(&mut s, "style.paragraph.create", json!({"name": "H", "para": {"spaceBefor": 6}})),
+ "invalid parameters for `style.paragraph.create`: para: unknown attribute `spaceBefor`; did you mean `spaceBefore`?"
+ );
+ assert!(
+ err(&mut s, "style.character.create", json!({"name": "C", "chars": {"font": "X"}}))
+ .starts_with("invalid parameters for `style.character.create`: chars:")
+ );
+ assert!(err(&mut s, "style.paragraph.create", json!({"name": "H", "chars": "bold"})).contains("chars must be an object of attributes"));
+ s.execute("style.paragraph.create", &json!({"name": "H", "chars": {"fontFamily": "Source Sans 3", "size": 14}})).unwrap();
+ assert!(
+ err(&mut s, "style.paragraph.edit", json!({"name": "H", "chars": {"font": "X"}}))
+ .starts_with("invalid parameters for `style.paragraph.edit`: chars:")
+ );
+ s.execute("style.character.create", &json!({"name": "C", "chars": {"fontStyle": "Bold"}})).unwrap();
+ assert!(
+ err(&mut s, "style.character.edit", json!({"name": "C", "chars": {"font": "X"}}))
+ .starts_with("invalid parameters for `style.character.edit`: chars:")
+ );
+ for id in ["style.paragraph.create", "style.paragraph.edit", "style.character.create", "style.character.edit"] {
+ let doc = find_command(id).unwrap().params;
+ assert!(doc.contains("as type.char names them: fontFamily"), "{id}: {doc}");
+ }
+ assert!(find_command("style.paragraph.create").unwrap().params.contains("as type.para names them: align"));
+ }
+ }
+
+ #[cfg(test)]
+ mod export_tag_tests {
+ use serde_json::json;
+
+ use crate::Session;
+
+ #[test]
+ fn export_tagging_shapes_epub_markup() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Chapter Title", "chars": {"size": 24}})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Key Term", "chars": {"fontStyle": "Bold"}})).unwrap();
+ s.execute("style.exportTag", &json!({"style": "Chapter Title", "tag": "h1", "class": "chapter"})).unwrap();
+ s.execute("style.exportTag", &json!({"style": "Key Term", "character": true, "tag": "strong"})).unwrap();
+ assert!(s.execute("style.exportTag", &json!({"style": "Nope"})).is_err());
+ // Split Document is for paragraph styles; it alone keeps the tagging.
+ assert!(s.execute("style.exportTag", &json!({"style": "Key Term", "character": true, "split": true})).is_err());
+ s.execute("style.paragraph.create", &json!({"name": "Part"})).unwrap();
+ assert_eq!(s.execute("style.exportTag", &json!({"style": "Part", "split": true})).unwrap()["split"], true);
+ assert!(s.doc().unwrap().doc.styles.export_tag("Part", false).is_some_and(|t| t.split));
+ s.execute("style.exportTag", &json!({"style": "Part", "split": false})).unwrap();
+ assert!(s.doc().unwrap().doc.styles.export_tag("Part", false).is_none(), "an untouched tagging goes");
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Origins\nA word"})).unwrap();
+ let sid = r["story"].as_u64().unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap();
+ s.execute("style.paragraph.apply", &json!({"name": "Chapter Title"})).unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 10, "focus": 14})).unwrap();
+ s.execute("style.character.apply", &json!({"name": "Key Term"})).unwrap();
+ let html = s.execute("file.exportHtml", &json!({})).unwrap()["text"].as_str().unwrap().to_string();
+ assert!(html.contains("<h1 class=\"chapter\">Origins</h1>"), "{html}");
+ assert!(html.contains("<strong class=\"key-term\">word</strong>"), "{html}");
+ // Tagged PDF: a heading element and a paragraph element.
+ let r = s.execute("file.exportPdf", &json!({"tagged": true, "compressImages": false})).unwrap();
+ let pdf = crate::cmd::file::base64_decode(r["base64"].as_str().unwrap());
+ let text = String::from_utf8_lossy(&pdf);
+ assert!(text.contains("/S/H1") && text.contains("/S/P"), "structure elements");
+ assert!(designcraft_render::pdf_page_count(&pdf) == Some(1));
+ }
+
+ #[test]
+ fn export_tagging_follows_a_renamed_style_and_goes_with_a_deleted_one() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Head"})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Body"})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Term"})).unwrap();
+ s.execute("style.exportTag", &json!({"style": "Head", "tag": "h2", "class": "head"})).unwrap();
+ s.execute("style.exportTag", &json!({"style": "Body", "tag": "p", "class": "body"})).unwrap();
+ s.execute("style.exportTag", &json!({"style": "Term", "character": true, "tag": "em", "class": "term"})).unwrap();
+ let tag = |s: &Session, name: &str, character: bool| {
+ s.doc().unwrap().doc.styles.export_tag(name, character).map(|t| (t.tag.clone(), t.class.clone()))
+ };
+ let pair = |t: &str, c: &str| Some((t.to_string(), c.to_string()));
+ // A rename onto another style's name is refused, so neither tagging is lost.
+ assert!(s.execute("style.paragraph.edit", &json!({"name": "Head", "rename": "Body"})).is_err());
+ assert_eq!((tag(&s, "Head", false), tag(&s, "Body", false)), (pair("h2", "head"), pair("p", "body")));
+
+ s.execute("style.paragraph.edit", &json!({"name": "Head", "rename": "Title"})).unwrap();
+ s.execute("style.character.edit", &json!({"name": "Term", "rename": "Word"})).unwrap();
+ assert_eq!(tag(&s, "Title", false), pair("h2", "head"));
+ assert_eq!(tag(&s, "Head", false), None);
+ assert_eq!(tag(&s, "Word", true), pair("em", "term"));
+ assert_eq!(tag(&s, "Term", true), None);
+ // Moving a style into a group renames it to Group/Name.
+ s.execute("style.group", &json!({"kind": "paragraph", "names": ["Title"], "group": "Heads"})).unwrap();
+ assert_eq!(tag(&s, "Heads/Title", false), pair("h2", "head"));
+ assert_eq!(tag(&s, "Title", false), None);
+
+ for _ in 0..3 {
+ s.execute("edit.undo", &json!({})).unwrap();
+ }
+ assert_eq!(tag(&s, "Head", false), pair("h2", "head"));
+ assert_eq!(tag(&s, "Title", false), None);
+ assert_eq!(tag(&s, "Term", true), pair("em", "term"));
+ assert_eq!(tag(&s, "Word", true), None);
+
+ // Deleting drops the deleted style's tagging; the replacement keeps its own.
+ s.execute("style.paragraph.delete", &json!({"name": "Head", "replaceWith": "Body"})).unwrap();
+ assert_eq!(tag(&s, "Head", false), None);
+ assert_eq!(tag(&s, "Body", false), pair("p", "body"));
+ s.execute("style.character.delete", &json!({"name": "Term"})).unwrap();
+ assert_eq!(tag(&s, "Term", true), None);
+ assert!(s.doc().unwrap().doc.styles.export_tags.keys().all(|k| k == "p:Body"));
+ }
+
+ #[test]
+ fn a_rename_onto_a_taken_name_says_so_and_a_trimmed_rename_drops_a_stale_tag() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ for (kind, a, b) in [("paragraph", "Head", "Body"), ("character", "Term", "Word")] {
+ s.execute(&format!("style.{kind}.create"), &json!({"name": a})).unwrap();
+ s.execute(&format!("style.{kind}.create"), &json!({"name": b})).unwrap();
+ let e = s.execute(&format!("style.{kind}.edit"), &json!({"name": a, "rename": b})).unwrap_err().to_string();
+ assert!(e.contains(&format!("a {kind} style named `{b}` already exists")), "{e}");
+ let e = s.execute(&format!("style.{kind}.edit"), &json!({"name": a, "rename": "[None]"})).unwrap_err().to_string();
+ assert!(e.contains("can't rename to `[None]`"), "{e}");
+ }
+ // An entry left under a name no style has doesn't attach to a style renamed onto it.
+ s.edit(|d, _| {
+ d.styles_mut()
+ .export_tags
+ .insert("p:Title".into(), designcraft_doc::ExportTag { tag: "h6".into(), class: "stale".into(), ..Default::default() });
+ Ok(())
+ })
+ .unwrap();
+ s.execute("style.paragraph.edit", &json!({"name": "Head", "rename": " Title "})).unwrap();
+ let st = &s.doc().unwrap().doc.styles;
+ assert!(st.para("Title").is_some(), "the new name is trimmed");
+ assert_eq!(st.export_tag("Title", false), None);
+ }
+ }
+
+ #[cfg(test)]
+ mod cjk_tests {
+ use super::*;
+ #[test]
+ fn cjk_composite_font_command_invalidates_layout_and_undo_restores_it() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let r = s.execute("frame.create", &json!({"rect": [0, 0, 300, 150], "content": "text", "text": "AB"})).unwrap();
+ let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap());
+ let definition = |scale| json!({"name": "Mixed", "entries": [{"family": "Source Serif 4", "relativeSize": scale}]});
+ s.execute("style.compositeFont.set", &definition(1.0)).unwrap();
+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 2})).unwrap();
+ s.execute("type.char", &json!({"fontFamily": "Mixed", "leadingAki": 0.25, "jidori": 4})).unwrap();
+ let old = s.cache.get(&s.doc().unwrap().doc, sid, None);
+ s.execute("style.compositeFont.set", &definition(2.0)).unwrap();
+ let new = s.cache.get(&s.doc().unwrap().doc, sid, None);
+ assert!(!std::sync::Arc::ptr_eq(&old, &new));
+ assert!(new.frames[0].lines[0].end_x > old.frames[0].lines[0].end_x);
+ s.execute("edit.undo", &json!({})).unwrap();
+ let restored = s.cache.get(&s.doc().unwrap().doc, sid, None);
+ assert_eq!(old.frames[0].lines[0].end_x, restored.frames[0].lines[0].end_x);
+ assert!(s.execute("style.compositeFont.set", &definition(-1.0)).is_err());
+ }
+ }
+
+ #[cfg(test)]
+ mod delete_tests {
+ use designcraft_doc::{CellStyle, ObjectStyle, StoryId, Toc, TocEntry};
+ use serde_json::json;
+
+ use crate::Session;
+
+ /// Is `name` still named anywhere in the document?
+ fn named(s: &Session, name: &str) -> bool {
+ serde_json::to_string(&*s.doc().unwrap().doc).unwrap().contains(&format!("\"{name}\""))
+ }
+
+ fn char_doc() -> (Session, u64) {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Base", "chars": {"fontStyle": "Bold"}})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Emphasis", "basedOn": "Base", "chars": {"tracking": 20}})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Child", "basedOn": "Emphasis"})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Strong", "chars": {"size": 14}})).unwrap();
+ let refs = json!({
+ "nestedStyles": [{"style": "Emphasis", "through": true, "count": 1, "until": {"kind": "words"}}],
+ "grepStyles": [{"style": "Emphasis", "pattern": "\\d+"}],
+ "nestedLineStyles": [{"style": "Emphasis", "lines": 1}],
+ "dropCapLines": 2, "dropCapChars": 1, "dropCapStyle": "Emphasis"});
+ s.execute("style.paragraph.create", &json!({"name": "Lead", "para": refs})).unwrap();
+ s.execute("footnote.options", &json!({"refCharStyle": "Emphasis"})).unwrap();
+ let sid = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hi there"})).unwrap()["story"]
+ .as_u64()
+ .unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 2})).unwrap();
+ s.execute("style.character.apply", &json!({"name": "Emphasis"})).unwrap();
+ // Local paragraph overrides name it too.
+ s.execute("type.para", &json!({"attrs": refs})).unwrap();
+ s.edit(|d, _| {
+ d.styles_mut().default_character = "Emphasis".into();
+ Ok(())
+ })
+ .unwrap();
+ assert!(named(&s, "Emphasis"));
+ (s, sid)
+ }
+
+ #[test]
+ fn deleting_a_character_style_points_every_use_at_the_replacement() {
+ let (mut s, sid) = char_doc();
+ let undo = s.doc().unwrap().history.undo.len();
+ s.execute("style.character.delete", &json!({"name": "Emphasis", "replaceWith": "Strong"})).unwrap();
+ assert!(!named(&s, "Emphasis"), "no dangling reference");
+ let d = s.doc().unwrap().doc.clone();
+ assert_eq!(d.styles.char_style("Child").unwrap().based_on.as_deref(), Some("Strong"));
+ assert_eq!(d.story(StoryId(sid)).unwrap().chars[0].format.style, "Strong");
+ let lead = &d.styles.para("Lead").unwrap().para;
+ assert_eq!(lead.nested_styles.as_ref().unwrap()[0].style, "Strong");
+ assert_eq!(lead.grep_styles.as_ref().unwrap()[0].style, "Strong");
+ assert_eq!(lead.nested_line_styles.as_ref().unwrap()[0].style, "Strong");
+ assert_eq!(lead.drop_cap_style.as_deref(), Some("Strong"));
+ assert_eq!(d.footnote_options.ref_char_style, "Strong");
+ assert_eq!(d.styles.default_character, "Strong");
+ // One undo step brings the style and every use back.
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert!(s.doc().unwrap().doc.styles.char_style("Emphasis").is_some());
+ assert_eq!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().chars[0].format.style, "Emphasis");
+ }
+
+ #[test]
+ fn deleting_a_character_style_for_none_unsets_based_on() {
+ let (mut s, _) = char_doc();
+ s.execute("style.character.delete", &json!({"name": "Emphasis"})).unwrap();
+ assert!(!named(&s, "Emphasis"), "no dangling reference");
+ let d = s.doc().unwrap().doc.clone();
+ assert_eq!(d.styles.char_style("Child").unwrap().based_on, None);
+ assert_eq!(d.footnote_options.ref_char_style, designcraft_doc::NO_CHAR_STYLE);
+ }
+
+ /// Replacing a style with its own descendant rebases the deleted style's children on its
+ /// parent, so no based-on chain becomes a cycle.
+ #[test]
+ fn replacing_a_style_with_its_child_makes_no_cycle() {
+ let (mut s, _) = char_doc();
+ s.execute("style.character.create", &json!({"name": "Grandchild", "basedOn": "Child"})).unwrap();
+ s.execute("style.character.delete", &json!({"name": "Emphasis", "replaceWith": "Grandchild"})).unwrap();
+ let d = s.doc().unwrap().doc.clone();
+ assert_eq!(d.styles.char_style("Child").unwrap().based_on.as_deref(), Some("Base"));
+ assert_eq!(d.styles.char_style("Grandchild").unwrap().based_on.as_deref(), Some("Child"));
+ assert!(!named(&s, "Emphasis"));
+ }
+
+ #[test]
+ fn bad_style_deletes_are_errors_and_change_nothing() {
+ let (mut s, _) = char_doc();
+ s.execute("style.paragraph.create", &json!({"name": "Head"})).unwrap();
+ let before = s.doc().unwrap().doc.clone();
+ let undo = s.doc().unwrap().history.undo.len();
+ for (id, p) in [
+ ("style.character.delete", json!({})),
+ ("style.character.delete", json!({"name": ""})),
+ ("style.character.delete", json!({"name": "Nope"})),
+ ("style.character.delete", json!({"name": "[None]"})),
+ ("style.character.delete", json!({"name": "Emphasis", "replaceWith": "Nope"})),
+ ("style.character.delete", json!({"name": "Emphasis", "replaceWith": "Emphasis"})),
+ ("style.paragraph.delete", json!({})),
+ ("style.paragraph.delete", json!({"name": ""})),
+ ("style.paragraph.delete", json!({"name": "Nope"})),
+ ("style.paragraph.delete", json!({"name": "[Basic Paragraph]"})),
+ ("style.paragraph.delete", json!({"name": "Head", "replaceWith": "Nope"})),
+ ("style.paragraph.delete", json!({"name": "Head", "replaceWith": "Head"})),
+ ] {
+ assert!(s.execute(id, &p).is_err(), "{id} {p}");
+ }
+ assert_eq!(*s.doc().unwrap().doc, *before);
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);
+ }
+
++ /// Deleting a paragraph style also redirects TOC style references to its replacement.
+ #[test]
+ fn deleting_a_paragraph_style_points_every_use_at_the_replacement() {
+ let mut s = Session::new();
+ s.execute("file.newSample", &json!({})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Sub", "basedOn": "Table Body", "nextStyle": "Table Body"})).unwrap();
+ s.edit(|d, _| {
+ let story = *d.stories.keys().next().ok_or(crate::EngineError::NoDocument)?;
+ let st = d.styles_mut();
+ st.default_paragraph = "Table Body".into();
+ st.object.push(ObjectStyle { name: "Boxed".into(), paragraph_style: Some("Table Body".into()), ..Default::default() });
+ st.cell.push(CellStyle { name: "Body Cell".into(), paragraph_style: Some("Table Body".into()), ..Default::default() });
+ d.footnote_options.para_style = "Table Body".into();
+ d.endnote_options.para_style = "Table Body".into();
+ d.endnote_options.heading_style = "Table Body".into();
+ d.settings.epub_split = designcraft_doc::EpubSplit::Style("Table Body".into());
+ d.toc = Some(Toc {
+ story,
+ title: "Contents".into(),
+ entries: vec![TocEntry { entry_style: Some("Table Body".into()), ..TocEntry::new("Table Body", 1) }],
+ page_numbers: false,
+ title_style: Some("Table Body".into()),
++ create_bookmarks: false,
+ });
+ Ok(())
+ })
+ .unwrap();
+ assert!(named(&s, "Table Body"));
+ s.execute("style.paragraph.delete", &json!({"name": "Table Body", "replaceWith": "Body"})).unwrap();
+ assert!(!named(&s, "Table Body"), "no dangling reference");
+ let d = s.doc().unwrap().doc.clone();
+ let sub = d.styles.para("Sub").unwrap();
+ assert_eq!((sub.based_on.as_deref(), sub.next_style.as_deref()), (Some("Body"), Some("Body")));
+ assert_eq!(d.styles.default_paragraph, "Body");
+ assert_eq!(d.endnote_options.heading_style, "Body");
+ assert_eq!(d.settings.epub_split, designcraft_doc::EpubSplit::Style("Body".into()), "EPUB Split Document follows the replacement");
+ let after = s.execute("preflight.run", &json!({})).unwrap();
+ assert!(!after.to_string().contains("Table Body"), "{after}");
+ }
+ }
+
+ #[cfg(test)]
+ mod grep_style_tests {
+ use serde_json::json;
+
+ use crate::Session;
+
+ #[test]
+ fn grep_style_pattern_that_cannot_compile_is_rejected() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Keep"})).unwrap();
+ let bad = json!([{"style": "Keep", "pattern": "(\\d+"}]);
+ let e = s.execute("style.paragraph.create", &json!({"name": "Broken", "para": {"grepStyles": bad}})).unwrap_err().to_string();
+ assert!(e.contains("bad GREP") && e.contains("(\\\\d+"), "{e}");
+ assert!(s.doc().unwrap().doc.styles.para("Broken").is_none());
+
+ // The lookbehind dialect compiles.
+ let good = json!([{"style": "Keep", "pattern": "(?<=\\s)[aiouwzAIOUWZ]\\s"}]);
+ s.execute("style.paragraph.create", &json!({"name": "Polish", "para": {"grepStyles": good}})).unwrap();
+ let e = s.execute("style.paragraph.edit", &json!({"name": "Polish", "para": {"grepStyles": bad, "spaceAfter": 6}})).unwrap_err().to_string();
+ assert!(e.contains("bad GREP"), "{e}");
+ let st = s.doc().unwrap().doc.styles.para("Polish").unwrap().clone();
+ assert_eq!(st.para.grep_styles.unwrap()[0].pattern, "(?<=\\s)[aiouwzAIOUWZ]\\s");
+ assert_eq!(st.para.space_after, None, "nothing changes");
+
+ // A paragraph override too.
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Ala i kot"})).unwrap();
+ s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();
+ let e = s.execute("type.para", &json!({"grepStyles": bad})).unwrap_err().to_string();
+ assert!(e.contains("bad GREP"), "{e}");
+ }
+
+ #[test]
+ fn idml_import_keeps_a_broken_grep_style_and_warns() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Keep"})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Broken"})).unwrap();
+ // Written past the command, as another application could.
+ s.edit(|d, _| {
+ if let Some(st) = d.styles_mut().para_mut("Broken") {
+ st.para.grep_styles = Some(vec![designcraft_doc::GrepStyle { style: "Keep".into(), pattern: "[a-".into() }]);
+ }
+ Ok(())
+ })
+ .unwrap();
+ let b64 = s.execute("file.exportIdml", &json!({})).unwrap()["base64"].as_str().unwrap().to_string();
+ let r = s.execute("file.openIdml", &json!({"base64": b64})).unwrap();
+ let warnings = r["warnings"].to_string();
+ assert!(warnings.contains("Broken") && warnings.contains("[a-") && warnings.contains("bad GREP"), "{warnings}");
+ let st = s.doc().unwrap().doc.styles.para("Broken").unwrap().clone();
+ assert_eq!(st.para.grep_styles.unwrap()[0].pattern, "[a-", "the style opens with its pattern");
+ }
+ }
diff --cc crates/idml/src/export/styles.rs
index 000000000,9435b533c..571af1eb1
mode 000000,100644..100644
--- a/crates/idml/src/export/styles.rs
+++ b/crates/idml/src/export/styles.rs
@@@ -1,0 -1,361 +1,361 @@@
+ use super::common::{bool_s, p, pct, pkg_root, with_props};
+ use super::item::{Group, text_frame_pref};
+ use super::story::with_list_tab;
+ use super::{
+ CHAR_BUILTINS, El, Ex, NO_PARA_ID, OBJECT_BUILTINS, PARA_BUILTINS, Rule, TOC_STYLE_ID, TOC_STYLE_NAME, document, escape_id, names, num, st,
+ };
+
+ impl<'a> Ex<'a> {
+ // ---------- Styles.xml ----------
+
+ pub(super) fn styles_part(&mut self) -> Vec<u8> {
+ let d = self.d;
+ let styles = d.styles.clone();
+ let mut root = pkg_root("Styles");
+
+ // Character styles.
+ let mut cg = Group::default();
+ for cs in &styles.character {
+ let id = names::style_self("CharacterStyle", CHAR_BUILTINS, &cs.name);
+ let mut el =
+ El::new("CharacterStyle").attr("Self", &id).attr("Imported", "false").attr("Name", names::style_name_out(CHAR_BUILTINS, &cs.name));
+ let mut props = Vec::new();
+ if cs.name != st::NO_CHAR_STYLE {
+ let based = cs.based_on.as_deref().filter(|b| *b != st::NO_CHAR_STYLE);
+ match based {
+ Some(b) => props.push(p("BasedOn", "object", names::style_self("CharacterStyle", CHAR_BUILTINS, b))),
+ None => props.push(p("BasedOn", "string", "$ID/[No character style]")),
+ }
+ self.char_attrs(&mut el, &mut props, &cs.chars);
+ }
+ cg.insert(&cs.name, with_props(el, props));
+ }
+ let mut rc = El::new("RootCharacterStyleGroup").attr("Self", self.fresh());
+ cg.emit(&mut rc, "CharacterStyleGroup", "");
+ root.push(rc);
+
+ // Paragraph styles.
+ let mut pg = Group::default();
+ for ps in &styles.paragraph {
+ let id = names::style_self("ParagraphStyle", PARA_BUILTINS, &ps.name);
+ let mut el =
+ El::new("ParagraphStyle").attr("Self", &id).attr("Name", names::style_name_out(PARA_BUILTINS, &ps.name)).attr("Imported", "false");
+ let mut props = Vec::new();
+ let (pa, ca) = if ps.name == designcraft_doc::NO_PARA_STYLE {
+ // The root style carries the complete attribute set.
+ let mut pa = designcraft_doc::ParaProps::common([&designcraft_doc::ParaProps::default()]);
+ pa.merge(&ps.para);
+ let mut ca = designcraft_doc::CharProps::common([&designcraft_doc::CharProps::default()]);
+ ca.merge(&ps.chars);
+ (pa, ca)
+ } else {
+ let next = ps.next_style.as_deref().unwrap_or(&ps.name);
+ el.set("NextStyle", names::style_self("ParagraphStyle", PARA_BUILTINS, next));
+ match ps.based_on.as_deref().filter(|b| *b != designcraft_doc::NO_PARA_STYLE) {
+ Some(b) => props.push(p("BasedOn", "object", names::style_self("ParagraphStyle", PARA_BUILTINS, b))),
+ None => props.push(p("BasedOn", "string", "$ID/[No paragraph style]")),
+ }
+ (ps.para.clone(), ps.chars.clone())
+ };
+ let parent = (ps.name != designcraft_doc::NO_PARA_STYLE).then(|| ps.based_on.as_deref().unwrap_or(designcraft_doc::NO_PARA_STYLE));
+ let parent_props = match ps.based_on.as_deref() {
+ Some(b) if ps.name != designcraft_doc::NO_PARA_STYLE => styles.resolve_para_style(b).0,
+ _ => designcraft_doc::ParaProps::default(),
+ };
+ let pa = with_list_tab(pa, || (styles.resolve_para_style(&ps.name).0, parent_props));
+ self.para_attrs(&mut el, &mut props, &pa, parent);
+ self.char_attrs(&mut el, &mut props, &ca);
+ if styles.export_tag(&ps.name, false).is_some_and(|t| t.split) {
+ el.set("SplitDocument", "true");
+ }
+ pg.insert(&ps.name, with_props(el, props));
+ }
+ let mut rp = El::new("RootParagraphStyleGroup").attr("Self", self.fresh());
+ pg.emit(&mut rp, "ParagraphStyleGroup", "");
+ root.push(rp);
+
+ self.append_cell_styles(&mut root, &styles);
+ self.append_table_styles(&mut root, &styles);
+ // Named numbered lists.
+ for l in &self.d.settings.lists {
+ root.push(
+ El::new("NumberingList")
+ .attr("Self", format!("NumberingList/{}", escape_id(&l.name)))
+ .attr("Name", &l.name)
+ .attr("ContinueNumbersAcrossStories", bool_s(l.continue_across_stories))
+ .attr("ContinueNumbersAcrossDocuments", "false"),
+ );
+ }
+
+ // Object styles.
+ let mut og = Group::default();
+ let mut have: Vec<&str> = styles.object.iter().map(|o| o.name.as_str()).collect();
+ let defaults = designcraft_doc::Styles::default();
+ let mut all: Vec<designcraft_doc::ObjectStyle> = styles.object.clone();
+ for b in &defaults.object {
+ if !have.contains(&b.name.as_str()) {
+ all.push(b.clone());
+ have.push(&b.name);
+ }
+ }
+ for os in &all {
+ let id = names::style_self("ObjectStyle", OBJECT_BUILTINS, &os.name);
+ let mut el = El::new("ObjectStyle").attr("Self", &id).attr("Name", names::style_name_out(OBJECT_BUILTINS, &os.name));
+ let mut props = Vec::new();
+ if os.name != designcraft_doc::NO_OBJECT_STYLE {
+ match os.based_on.as_deref().filter(|b| *b != designcraft_doc::NO_OBJECT_STYLE) {
+ Some(b) => props.push(p("BasedOn", "object", names::style_self("ObjectStyle", OBJECT_BUILTINS, b))),
+ None => props.push(p("BasedOn", "string", "$ID/[None]")),
+ }
+ }
+ el.set("EnableFill", bool_s(os.fill.is_some()));
+ el.set("EnableStroke", bool_s(os.stroke.is_some()));
+ el.set("EnableParagraphStyle", bool_s(os.paragraph_style.is_some()));
+ el.set("EnableTextFrameGeneralOptions", bool_s(os.text_frame.is_some()));
+ if let Some(f) = &os.fill {
+ el.set("FillColor", self.sw(&f.swatch));
+ el.set("FillTint", pct(f.tint as f64));
+ }
+ if let Some(s) = &os.stroke {
+ self.stroke_attrs(&mut el, s);
+ }
+ if let Some(ps) = &os.paragraph_style {
+ el.set("AppliedParagraphStyle", names::style_self("ParagraphStyle", PARA_BUILTINS, ps));
+ }
+ let mut el = with_props(el, props);
+ if let Some(e) = &os.effects {
+ let mut t = El::new("TransparencySetting");
+ for c in self.effect_els(e, true) {
+ t.push(c);
+ }
+ el.push(t);
+ }
+ if let Some(tf) = &os.text_frame {
+ el.push(text_frame_pref(tf, &self.sw(&tf.column_rule_color)));
+ }
+ // Effects: a style with effects sets the drop shadow and feather, never blending.
+ let on = bool_s(os.effects.is_some());
+ el.push(
+ El::new("ObjectStyleObjectEffectsCategorySettings")
+ .attr("EnableTransparency", "false")
+ .attr("EnableDropShadow", on)
+ .attr("EnableFeather", on)
+ .attr("EnableInnerShadow", "false")
+ .attr("EnableOuterGlow", "false")
+ .attr("EnableInnerGlow", "false")
+ .attr("EnableBevelEmboss", "false")
+ .attr("EnableSatin", "false")
+ .attr("EnableDirectionalFeather", "false")
+ .attr("EnableGradientFeather", "false"),
+ );
+ og.insert(&os.name, el);
+ }
+ let mut ro = El::new("RootObjectStyleGroup").attr("Self", self.fresh());
+ og.emit(&mut ro, "ObjectStyleGroup", "");
+ root.push(ro);
+ if let Some(toc) = d.toc.as_ref().filter(|t| d.story(t.story).is_some()) {
+ root.push(self.toc_style_el(toc));
+ }
+ document(&root)
+ }
+
+ fn append_cell_styles(&mut self, root: &mut El, styles: &designcraft_doc::Styles) {
+ let mut cells = El::new("RootCellStyleGroup")
+ .attr("Self", self.fresh())
+ .child(El::new("CellStyle").attr("Self", "CellStyle/$ID/[None]").attr("AppliedParagraphStyle", NO_PARA_ID).attr("Name", "$ID/[None]"));
+ for cs in styles.cell.iter().filter(|c| c.name != designcraft_doc::NO_CELL_STYLE) {
+ let mut el = El::new("CellStyle")
+ .attr("Self", names::style_self("CellStyle", names::CELL_BUILTINS, &cs.name))
+ .attr("Name", names::style_name_out(names::CELL_BUILTINS, &cs.name));
+ if let Some(f) = &cs.fill {
+ el.set("FillColor", self.sw(f));
+ }
+ if let Some(t) = cs.fill_tint {
+ el.set("FillTint", pct(t as f64));
+ }
+ if let Some(i) = cs.insets {
+ for (k, v) in ["TopInset", "LeftInset", "BottomInset", "RightInset"].iter().zip(i) {
+ el.set(k, num(v));
+ }
+ }
+ for (key, value) in ["TopInset", "LeftInset", "BottomInset", "RightInset"].iter().zip(cs.inset_overrides) {
+ if let Some(value) = value {
+ el.set(key, num(value));
+ }
+ }
+ if let Some(vj) = cs.vj {
+ el.set("VerticalJustification", names::vj_out(vj));
+ }
+ if let Some(fb) = cs.first_baseline {
+ el.set("FirstBaselineOffset", names::first_baseline_out(fb));
+ }
+ if let Some(min) = cs.first_baseline_min {
+ el.set("MinimumFirstBaselineOffset", num(min));
+ }
+ if let Some(st) = &cs.stroke {
+ for side in ["TopEdge", "LeftEdge", "BottomEdge", "RightEdge"] {
+ self.cell_stroke_attrs(&mut el, side, st);
+ }
+ }
+ for (side, attrs) in ["TopEdge", "LeftEdge", "BottomEdge", "RightEdge"].iter().zip(&cs.strokes) {
+ self.partial_cell_stroke_attrs(&mut el, side, attrs);
+ }
+ if let Some(ps) = &cs.paragraph_style {
+ el.set("AppliedParagraphStyle", names::style_self("ParagraphStyle", PARA_BUILTINS, ps));
+ }
+ let base = cs.based_on.as_deref().unwrap_or(designcraft_doc::NO_CELL_STYLE);
+ let based_on = if base == designcraft_doc::NO_CELL_STYLE {
+ p("BasedOn", "string", "$ID/[None]")
+ } else {
+ p("BasedOn", "object", names::style_self("CellStyle", names::CELL_BUILTINS, base))
+ };
+ cells = cells.child(with_props(el, vec![based_on]));
+ }
+ root.push(cells);
+ }
+
+ fn append_table_styles(&mut self, root: &mut El, styles: &designcraft_doc::Styles) {
+ let mut tables = El::new("RootTableStyleGroup").attr("Self", self.fresh());
+ if !styles.table.iter().any(|s| s.name == designcraft_doc::NO_TABLE_STYLE) {
+ tables.push(El::new("TableStyle").attr("Self", "TableStyle/$ID/[No table style]").attr("Name", "$ID/[No table style]"));
+ }
+ if !styles.table.iter().any(|s| s.name == designcraft_doc::BASIC_TABLE) {
+ tables.push(with_props(
+ El::new("TableStyle").attr("Self", "TableStyle/$ID/[Basic Table]").attr("Name", "$ID/[Basic Table]"),
+ vec![p("BasedOn", "string", "$ID/[No table style]")],
+ ));
+ }
+ for ts in &styles.table {
+ let mut el = El::new("TableStyle")
+ .attr("Self", names::style_self("TableStyle", names::TABLE_BUILTINS, &ts.name))
+ .attr("Name", names::style_name_out(names::TABLE_BUILTINS, &ts.name));
+ for (k, v) in [
+ ("HeaderRegionCellStyle", &ts.header),
+ ("BodyRegionCellStyle", &ts.body),
+ ("FooterRegionCellStyle", &ts.footer),
+ ("LeftColumnRegionCellStyle", &ts.left_column),
+ ("RightColumnRegionCellStyle", &ts.right_column),
+ ] {
+ if let Some(n) = v {
+ el.set(k, names::style_self("CellStyle", names::CELL_BUILTINS, n));
+ }
+ }
+ for (key, value) in [
+ ("HeaderRegionSameAsBodyRegion", ts.header_same_as_body),
+ ("FooterRegionSameAsBodyRegion", ts.footer_same_as_body),
+ ("LeftColumnRegionSameAsBodyRegion", ts.left_column_same_as_body),
+ ("RightColumnRegionSameAsBodyRegion", ts.right_column_same_as_body),
+ ] {
+ if let Some(value) = value {
+ el.set(key, value);
+ }
+ }
+ if let Some(b) = &ts.border {
+ for side in ["Top", "Left", "Bottom", "Right"] {
+ self.cell_stroke_attrs(&mut el, &format!("{side}Border"), b);
+ }
+ }
+ for (side, attrs) in ["TopBorder", "LeftBorder", "BottomBorder", "RightBorder"].iter().zip(&ts.borders) {
+ self.partial_cell_stroke_attrs(&mut el, side, attrs);
+ }
+ if let Some(a) = &ts.alt_rows {
+ el.set("StartRowFillColor", self.sw(&a.first_color));
+ el.set("StartRowFillCount", a.first);
+ el.set("StartRowFillTint", pct(a.first_tint as f64));
+ el.set("EndRowFillColor", self.sw(&a.next_color));
+ el.set("EndRowFillCount", a.next);
+ el.set("EndRowFillTint", pct(a.next_tint as f64));
+ }
+ self.partial_alt_fill_attrs(&mut el, "Row", &ts.row_fills);
+ self.partial_alt_fill_attrs(&mut el, "Column", &ts.column_fills);
+ self.partial_alt_stroke_attrs(&mut el, "Row", &ts.row_strokes);
+ self.partial_alt_stroke_attrs(&mut el, "Column", &ts.column_strokes);
+ if let Some(v) = ts.space_before {
+ el.set("SpaceBefore", num(v));
+ }
+ if let Some(v) = ts.space_after {
+ el.set("SpaceAfter", num(v));
+ }
+ let mut props = Vec::new();
+ if ts.name != designcraft_doc::NO_TABLE_STYLE {
+ let base = ts.based_on.as_deref().unwrap_or(designcraft_doc::NO_TABLE_STYLE);
+ props.push(if base == designcraft_doc::NO_TABLE_STYLE {
+ p("BasedOn", "string", "$ID/[No table style]")
+ } else {
+ p("BasedOn", "object", names::style_self("TableStyle", names::TABLE_BUILTINS, base))
+ });
+ }
+ tables = tables.child(with_props(el, props));
+ }
+ root.push(tables);
+ }
+
+ /// The document's table of contents as a TOC style; its story names it in `AppliedTOCStyle`.
+ fn toc_style_el(&mut self, toc: &designcraft_doc::Toc) -> El {
+ let para = |n: &str| names::style_self("ParagraphStyle", PARA_BUILTINS, n);
+ let chars = |n: Option<&str>| names::style_self("CharacterStyle", CHAR_BUILTINS, n.unwrap_or(designcraft_doc::NO_CHAR_STYLE));
+ let mut el = El::new("TOCStyle")
+ .attr("Self", TOC_STYLE_ID)
+ .attr("Name", TOC_STYLE_NAME)
+ .attr("Title", &toc.title)
+ .attr("TitleStyle", para(toc.title_style.as_deref().unwrap_or("TOC Title")))
+ .attr("RunIn", "false")
+ .attr("IncludeHidden", "false")
+ .attr("IncludeBookDocuments", "false")
- .attr("CreatePdfBookmarks", "false");
++ .attr("CreateBookmarks", if toc.create_bookmarks { "true" } else { "false" });
+ for e in &toc.entries {
+ let format = e.entry_style.clone().unwrap_or_else(|| format!("TOC Level {}", e.level));
+ let position = match e.page_number {
+ _ if !toc.page_numbers => "NoPageNumber",
+ designcraft_doc::TocPageNumber::After => "AfterEntry",
+ designcraft_doc::TocPageNumber::Before => "BeforeEntry",
+ designcraft_doc::TocPageNumber::None => "NoPageNumber",
+ };
+ el.push(
+ El::new("TOCStyleEntry")
+ .attr("Self", self.fresh())
+ .attr("Name", names::style_name_out(PARA_BUILTINS, &e.style))
+ .attr("FormatStyle", para(&format))
+ .attr("Level", e.level)
+ .attr("PageNumberPosition", position)
+ .attr("Separator", names::toc_separator_out(e.separator.as_deref().unwrap_or("\t")))
+ .attr("PageNumberStyle", chars(e.page_number_style.as_deref()))
+ .attr("SeparatorStyle", chars(e.separator_style.as_deref()))
+ .attr("Sort", if e.sort { "true" } else { "false" }),
+ );
+ }
+ el
+ }
+
+ pub(super) fn rule(&mut self, el: &mut El, props: &mut Vec<El>, k: &str, r: &Rule) {
+ el.set(k, bool_s(r.on));
+ el.set(&format!("{k}LineWeight"), num(r.weight));
+ el.set(&format!("{k}Tint"), pct(r.tint as f64));
+ el.set(&format!("{k}Width"), if r.column_width { "ColumnWidth" } else { "TextWidth" });
+ el.set(&format!("{k}Offset"), num(r.offset));
+ el.set(&format!("{k}LeftIndent"), num(r.left_indent));
+ el.set(&format!("{k}RightIndent"), num(r.right_indent));
+ props.push(if r.color == designcraft_doc::TEXT_COLOR {
+ p(&format!("{k}Color"), "string", designcraft_doc::TEXT_COLOR)
+ } else {
+ p(&format!("{k}Color"), "object", self.sw(&r.color))
+ });
+ }
+
+ pub(super) fn stroke_attrs(&self, el: &mut El, s: &designcraft_doc::Stroke) {
+ el.set("StrokeColor", self.sw(&s.swatch));
+ el.set("StrokeWeight", num(if s.is_none() { 0.0 } else { s.weight }));
+ el.set("StrokeTint", pct(s.tint as f64));
+ el.set("StrokeType", names::stroke_type_out(&s.kind));
+ el.set("StrokeAlignment", names::stroke_align_out(s.align));
+ el.set("EndCap", names::cap_out(s.cap));
+ el.set("EndJoin", names::join_out(s.join));
+ el.set("MiterLimit", num(s.miter_limit));
+ el.set("LeftLineEnd", names::arrow_out(s.start));
+ el.set("RightLineEnd", names::arrow_out(s.end));
+ el.set("GapColor", self.sw(&s.gap_swatch));
+ el.set("GapTint", pct(s.gap_tint as f64));
+ el.set("OverprintStroke", bool_s(s.overprint));
+ el.set("OverprintGap", bool_s(s.gap_overprint));
+ }
+ }
diff --cc crates/idml/src/import/document.rs
index 000000000,dce466381..a31eb0bad
mode 000000,100644..100644
--- a/crates/idml/src/import/document.rs
+++ b/crates/idml/src/import/document.rs
@@@ -1,0 -1,351 +1,352 @@@
+ use super::values::tint;
+ use super::{BaselineGrid, El, GridRelative, Importer, PARA_BUILTINS, names};
+
+ /// IDML stores a sort key on each topic, rather than on its page references.
+ #[derive(Clone, Default)]
+ pub(super) struct IndexTopic {
+ pub(super) path: Vec<String>,
+ pub(super) sort: Vec<String>,
+ }
+
+ impl IndexTopic {
+ fn child(&self, topic: &El) -> Self {
+ let mut path = self.path.clone();
+ path.push(topic.get("Name").unwrap_or("").to_string());
+ let mut sort = self.sort.clone();
+ if let Some(key) = topic.get("SortOrder").filter(|key| !key.is_empty()) {
+ // Keep empty positions before a child's key, but omit trailing defaults.
+ sort.resize(self.path.len(), String::new());
+ sort.push(key.to_string());
+ }
+ Self { path, sort }
+ }
+ }
+
+ impl<'r> Importer<'r> {
+ pub(super) fn doc_prefs(&mut self, e: &El) {
+ let s = &mut self.settings;
+ if let Some(v) = e.get("OverprintBlack") {
+ s.overprint_black = v != "false";
+ }
+ if let Some(v) = e.num("PageWidth") {
+ s.page_width = v;
+ }
+ if let Some(v) = e.num("PageHeight") {
+ s.page_height = v;
+ }
+ if let Some(v) = e.boolean("FacingPages") {
+ s.facing_pages = v;
+ }
+ if let Some(v) = e.get("PageBinding") {
+ s.right_to_left_binding = v == "RightToLeft";
+ }
+ for (i, k) in ["DocumentBleedTopOffset", "DocumentBleedBottomOffset", "DocumentBleedInsideOrLeftOffset", "DocumentBleedOutsideOrRightOffset"]
+ .iter()
+ .enumerate()
+ {
+ if let Some(v) = e.num(k) {
+ s.bleed[i] = v;
+ }
+ }
+ for (i, k) in ["SlugTopOffset", "SlugBottomOffset", "SlugInsideOrLeftOffset", "SlugRightOrOutsideOffset"].iter().enumerate() {
+ if let Some(v) = e.num(k) {
+ s.slug[i] = v;
+ }
+ }
+ if let Some(i) = e.get("Intent") {
+ s.intent = match i {
+ "WebIntent" => designcraft_doc::Intent::Web,
+ "MobileIntent" => designcraft_doc::Intent::Mobile,
+ _ => designcraft_doc::Intent::Print,
+ };
+ }
+ if let Some(v) = e.boolean("CreatePrimaryTextFrame") {
+ s.primary_text_frame = v;
+ }
+ if let Some(v) = e.boolean("ColumnGuideLocked") {
+ s.column_guides_locked = v;
+ }
+ }
+
+ pub(super) fn grid_prefs(&mut self, e: &El) {
+ let s = &mut self.settings;
+ let bg: &mut BaselineGrid = &mut s.baseline_grid;
+ if let Some(v) = e.num("BaselineStart") {
+ bg.start = v;
+ }
+ if let Some(v) = e.num("BaselineDivision") {
+ bg.increment = v;
+ }
+ if let Some(v) = e.num("BaselineViewThreshold") {
+ bg.view_threshold = v / 100.0;
+ }
+ if let Some(v) = e.get("BaselineGridRelativeOption") {
+ bg.relative_to = if v.contains("Margin") { GridRelative::TopMargin } else { GridRelative::TopOfPage };
+ }
+ if let Some(v) = e.num("HorizontalGridlineDivision") {
+ s.grid.horizontal = v;
+ }
+ if let Some(v) = e.num("VerticalGridlineDivision") {
+ s.grid.vertical = v;
+ }
+ if let Some(v) = e.num("HorizontalGridSubdivision") {
+ s.grid.subdivisions = v.max(1.0) as u32;
+ }
+ if let Some(v) = e.boolean("GridsInBack") {
+ s.grid.in_back = v;
+ }
+ }
+
+ /// Index topics (recursively); at the root, their See / See also cross-references too.
+ pub(super) fn index_topics_of(&mut self, e: &El, prefix: &IndexTopic) {
+ for t in e.find_all("Topic") {
+ let topic = prefix.child(t);
+ if let Some(me) = t.get("Self") {
+ self.index_topics.insert(me.to_string(), topic.clone());
+ }
+ self.index_topics_of(t, &topic);
+ }
+ if !prefix.path.is_empty() {
+ return;
+ }
+ let mut stack = vec![(e, IndexTopic::default())];
+ while let Some((el, prefix)) = stack.pop() {
+ for t in el.find_all("Topic") {
+ let topic = prefix.child(t);
+ for x in t.find_all("CrossReference") {
+ let target = x.get("ReferencedTopic").and_then(|r| self.index_topics.get(r)).map(|t| t.path.join(": ")).unwrap_or_default();
+ use designcraft_doc::index::IndexRange as R;
+ let range = match x.get("CrossReferenceType") {
+ Some("SeeAlso") | Some("SeeAlsoHerein") => R::SeeAlso(target),
+ _ => R::See(target),
+ };
+ self.index_xrefs.push(designcraft_doc::IndexRef { topics: topic.path.clone(), sort: topic.sort.clone(), range });
+ }
+ stack.push((t, topic));
+ }
+ }
+ }
+
+ /// `CrossReferenceFormat`: building blocks back to a format definition.
+ /// A `TextVariable` definition. Types that aren't computed here keep their settings and show
+ /// the result of their first instance.
+ pub(super) fn text_variable(&mut self, e: &El) {
+ use designcraft_doc::vars::{TextVariable, Use, VAR_MAX, VarKind};
+ let ty = e.get("VariableType").unwrap_or("");
+ // Cross-reference internals; export writes its own.
+ if ty.is_empty() || ty.starts_with("Xref") {
+ return;
+ }
+ let vars = self.text_vars.get_or_insert_with(Vec::new);
+ if vars.len() >= VAR_MAX {
+ return;
+ }
+ let pref = e.elements().find(|c| c.local().ends_with("Preference"));
+ let attr = |k: &str| pref.and_then(|p| p.get(k)).unwrap_or("");
+ let date = || Some(attr("Format")).filter(|f| !f.is_empty()).unwrap_or("MM/dd/yy").to_string();
+ let kind = match ty {
+ "CustomTextType" => Some(VarKind::Custom { text: attr("Contents").into() }),
+ "LastPageNumberType" => Some(VarKind::LastPageNumber { section: attr("Scope") == "SectionScope" }),
+ "ChapterNumberType" => Some(VarKind::ChapterNumber),
+ "FileNameType" if attr("IncludePath") != "true" => Some(VarKind::FileName { extension: attr("IncludeExtension") == "true" }),
+ "CreationDateType" => Some(VarKind::CreationDate { format: date() }),
+ "ModificationDateType" => Some(VarKind::ModificationDate { format: date() }),
+ "OutputDateType" => Some(VarKind::OutputDate { format: date() }),
+ "MatchParagraphStyleType" | "MatchCharacterStyleType" => {
+ let character = ty == "MatchCharacterStyleType";
+ let r = attr(if character { "AppliedCharacterStyle" } else { "AppliedParagraphStyle" });
+ let use_ = if attr("SearchStrategy") == "LastOnPage" { Use::LastOnPage } else { Use::FirstOnPage };
+ // Change Case and Delete End Punctuation aren't modelled: the header shows the text as set.
+ (!r.is_empty()).then(|| VarKind::RunningHeader {
+ style: if character { self.char_style_ref(r) } else { self.para_style_ref(r) },
+ use_,
+ character,
+ })
+ }
+ _ => None,
+ };
+ let name = e.get("Name").unwrap_or("").to_string();
+ let v = match kind {
+ Some(kind) => {
+ let mut v = TextVariable::new(&name, kind);
+ v.before = attr("TextBefore").into();
+ v.after = attr("TextAfter").into();
+ v
+ }
+ None => TextVariable::new(
+ &name,
+ VarKind::Imported {
+ variable_type: ty.into(),
+ result: String::new(),
+ settings_element: pref.map(|p| p.name.clone()).unwrap_or_default(),
+ settings: pref.map(|p| p.attrs.clone()).unwrap_or_default(),
+ },
+ ),
+ };
+ let vars = self.text_vars.get_or_insert_with(Vec::new);
+ if let Some(s) = e.get("Self") {
+ self.text_var_ids.insert(s.to_string(), vars.len());
+ }
+ vars.push(v);
+ }
+
+ /// A `TextVariableInstance`: the variable's character, or its recorded text when the file
+ /// doesn't define the variable.
+ pub(super) fn text_variable_instance(&mut self, e: &El) -> String {
+ use designcraft_doc::vars::{VarKind, var_char};
+ let result = e.get("ResultText").unwrap_or("");
+ let found = e.get("AssociatedTextVariable").and_then(|r| self.text_var_ids.get(r)).copied();
+ let var = found.and_then(|i| Some((i, self.text_vars.as_mut()?.get_mut(i)?)));
+ match var.and_then(|(i, v)| Some((var_char(i)?, v))) {
+ Some((c, v)) => {
+ if let VarKind::Imported { result: r, .. } = &mut v.kind
+ && r.is_empty()
+ {
+ *r = result.to_string();
+ }
+ c.to_string()
+ }
+ None => result.to_string(),
+ }
+ }
+
+ pub(super) fn xref_format(&mut self, e: &El) {
+ let name = e.get("Name").unwrap_or("Format").to_string();
+ let mut def = String::new();
+ for b in e.find_all("BuildingBlock") {
+ let text = |k: &str| b.get(k).filter(|v| *v != "$ID/").unwrap_or("").to_string();
+ match b.get("BlockType").unwrap_or("") {
+ "CustomStringBuildingBlock" => def.push_str(&text("CustomText")),
+ "FullParagraphBuildingBlock" => def.push_str("<fullPara />"),
+ "ParagraphTextBuildingBlock" => def.push_str("<paraText />"),
+ "ParagraphNumberBuildingBlock" => def.push_str("<paraNum />"),
+ "PageNumberBuildingBlock" => def.push_str("<pageNum />"),
+ "BookmarkNameBuildingBlock" => def.push_str("<txtAnchrName />"),
+ "ChapterNumberBuildingBlock" => def.push_str("<chapNum />"),
+ "FileNameBuildingBlock" => def.push_str("<fileName />"),
+ "PartialParagraphBuildingBlock" => def.push_str(&format!(
+ "<partialPara delim=\"{}\" includeDelim=\"{}\" />",
+ text("AppliedDelimiter"),
+ b.get("IncludeDelimiter") == Some("true")
+ )),
+ _ => {}
+ }
+ }
+ if let Some(me) = e.get("Self") {
+ self.xref_format_names.insert(me.to_string(), name.clone());
+ }
+ match self.xref_formats.iter_mut().find(|f| f.name == name) {
+ Some(f) => f.definition = def,
+ None => self.xref_formats.push(designcraft_doc::XrefFormat { name, definition: def }),
+ }
+ }
+
+ /// Preferences › `EPubExportPreference`: Split Document (after styles: it can name one). An
+ /// empty style name splits on the styles' export tags; a style the file lacks splits nothing.
+ pub(super) fn epub_split(&mut self, e: &El) {
+ if e.boolean("BreakDocument") != Some(true) {
+ return;
+ }
+ let name = e.get("ParagraphStyleName").unwrap_or("$ID/NormalParagraphStyle");
+ self.settings.epub_split = if name.trim().is_empty() {
+ designcraft_doc::EpubSplit::ExportTags
+ } else {
+ let style = self.para_style_ref(name);
+ if self.styles.para(&style).is_some() { designcraft_doc::EpubSplit::Style(style) } else { designcraft_doc::EpubSplit::Off }
+ };
+ }
+
+ /// Preferences › `FootnoteOption` (after styles: it names the footnote text and marker styles).
+ pub(super) fn footnote_option(&mut self, e: &El) {
+ let mut o = designcraft_doc::FootnoteOptions::default();
+ if let Some(v) = e.num("StartAt") {
+ o.start_at = v.max(0.0) as u32;
+ }
+ o.prefix = e.get("Prefix").unwrap_or("").into();
+ o.suffix = e.get("Suffix").unwrap_or("").into();
+ if let Some(r) = e.get("FootnoteTextStyle") {
+ o.para_style = self.para_style_ref(r);
+ }
+ if let Some(r) = e.get("FootnoteMarkerStyle") {
+ o.ref_char_style = self.char_style_ref(r);
+ }
+ if let Some(v) = e.get("SeparatorText") {
+ o.separator = v.into();
+ }
+ o.space_between = e.num("SpaceBetween").unwrap_or(0.0);
+ o.space_before = e.num("Spacer").unwrap_or(0.0);
+ if let Some(v) = e.prop("FootnoteFirstBaselineOffset") {
+ o.first_baseline = names::first_baseline_in(v.trim());
+ }
+ o.first_baseline_min = e.num("FootnoteMinimumFirstBaselineOffset").unwrap_or(0.0);
+ o.span_columns = e.boolean("EnableStraddling").unwrap_or(false);
+ o.rule.on = e.boolean("RuleOn").unwrap_or(true);
+ o.rule.weight = e.num("RuleLineWeight").unwrap_or(1.0);
+ o.rule.tint = tint(e.num("RuleTint")).unwrap_or(1.0);
+ o.rule.left_indent = e.num("RuleLeftIndent").unwrap_or(0.0);
+ o.rule.width = e.num("RuleWidth").unwrap_or(72.0);
+ o.rule.offset = e.num("RuleOffset").unwrap_or(0.0);
+ if let Some(c) = e.prop("RuleColor") {
+ o.rule.color = self.swatch_ref(c.trim());
+ }
+ if let Some(v) = e.prop("FootnoteNumberingStyle") {
+ o.style = names::note_style_in(v.trim());
+ }
+ if let Some(v) = e.prop("RestartNumbering") {
+ o.restart = names::NOTE_RESTART.iter().find(|r| r.1 == v.trim()).map_or(Default::default(), |r| r.0);
+ }
+ if let Some(v) = e.prop("ShowPrefixSuffix") {
+ o.affix_in = names::NOTE_AFFIX.iter().find(|r| r.1 == v.trim()).map_or(Default::default(), |r| r.0);
+ }
+ if let Some(v) = e.prop("MarkerPositioning") {
+ o.ref_position = names::note_marker_in(v.trim());
+ }
+ self.footnote_options = o;
+ }
+
+ /// The table of contents: the TOC style a story is generated from (`AppliedTOCStyle`), with
+ /// its entries. Styles the document doesn't have fall back to the generated TOC styles.
+ pub(super) fn toc_of(&self, top: &[El]) -> Option<designcraft_doc::Toc> {
+ use designcraft_doc::{TocEntry, TocPageNumber};
+ let (ts, story) = top.iter().filter(|e| e.local() == "TOCStyle").find_map(|ts| {
+ let id = ts.get("Self")?;
+ let story = top.iter().find(|e| e.local() == "Story" && e.get("AppliedTOCStyle") == Some(id))?;
+ Some((ts, *self.story_ids.get(story.get("Self")?)?))
+ })?;
+ let known = |r: Option<&str>| r.map(|r| self.para_style_ref(r)).filter(|n| self.styles.para(n).is_some());
+ // Character styles the document has; [None] is stored as no style.
+ let known_chars = |r: Option<&str>| {
+ r.map(|r| self.char_style_ref(r)).filter(|n| n != designcraft_doc::NO_CHAR_STYLE && self.styles.char_style(n).is_some())
+ };
+ let entries: Vec<TocEntry> = ts
+ .elements()
+ .filter(|e| e.local() == "TOCStyleEntry")
+ .filter_map(|e| {
+ let style = names::style_name_in(PARA_BUILTINS, e.get("Name")?);
+ if style.is_empty() || style.chars().count() > 256 {
+ return None;
+ }
+ let level = e.get("Level").and_then(|l| l.trim().parse::<u8>().ok()).unwrap_or(1).clamp(1, 9);
+ let page_number = match e.get("PageNumberPosition") {
+ Some("BeforeEntry") => TocPageNumber::Before,
+ Some("NoPageNumber") => TocPageNumber::None,
+ _ => TocPageNumber::After,
+ };
+ let separator = e.get("Separator").map(crate::names::toc_separator_in).filter(|s| s != "\t" && s.chars().count() <= 64);
+ let entry_style = known(e.get("FormatStyle")).filter(|n| *n != format!("TOC Level {level}"));
+ let page_number_style = known_chars(e.get("PageNumberStyle"));
+ let separator_style = known_chars(e.get("SeparatorStyle"));
+ let sort = e.get("Sort").is_some_and(|v| v.trim() == "true");
+ Some(TocEntry { style, level, entry_style, page_number, separator, page_number_style, separator_style, sort })
+ })
+ .take(64)
+ .collect();
+ if entries.is_empty() {
+ return None;
+ }
+ let title: String = ts.get("Title").unwrap_or("").chars().filter(|c| !matches!(c, '\n' | '\r' | '\u{2029}')).take(1024).collect();
+ let title_style = known(ts.get("TitleStyle")).filter(|n| n != "TOC Title");
- Some(designcraft_doc::Toc { story, title, entries, page_numbers: true, title_style })
++ let create_bookmarks = ts.get("CreateBookmarks").or_else(|| ts.get("CreatePdfBookmarks")) == Some("true");
++ Some(designcraft_doc::Toc { story, title, entries, page_numbers: true, title_style, create_bookmarks })
+ }
+ }
diff --cc crates/ui-egui/src/dialogs.rs
index c4f8823c7,bb3077103..cba803f4d
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@@ -174,6 -186,6 +186,36 @@@ fn color_theme(app: &DesignApp, ui: &mu
mod color_theme_tests {
use super::*;
++ /// The bookmarks checkbox persists through generation and reopening the dialog.
++ #[test]
++ fn toc_bookmarks_checkbox_sets_and_reopens_the_persisted_option() {
++ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
++ app.run("file.newSample", json!({})).unwrap();
++ open_toc(&mut app);
++ assert!(app.ui.dialog.as_ref().unwrap().b("createBookmarks"));
++ app.ui.dialog.as_mut().unwrap().fields.insert("included".into(), json!([{"style": "Headline", "level": 1}]));
++ let ctx = dialog_context("en");
++ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));
++ for _ in 0..3 {
++ dialog_frame(&mut app, &ctx, screen, vec![]);
++ }
++ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);
++ visible_label(&labels, screen, "Create PDF Bookmarks");
++ confirm(&mut app).unwrap();
++ assert!(app.session.doc().unwrap().doc.toc.as_ref().unwrap().create_bookmarks);
++ assert!(!app.session.doc().unwrap().doc.bookmarks.is_empty());
++ open_toc(&mut app);
++ for _ in 0..3 {
++ dialog_frame(&mut app, &ctx, screen, vec![]);
++ }
++ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);
++ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Create PDF Bookmarks").center());
++ confirm(&mut app).unwrap();
++ assert!(app.session.doc().unwrap().doc.bookmarks.is_empty());
++ open_toc(&mut app);
++ assert!(!app.ui.dialog.as_ref().unwrap().b("createBookmarks"));
++ }
++
#[test]
fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() {
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());