DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge storytold/main (v0.14.0) into xref-edited-text
Claude11f4364705b1
diff --cc ROADMAP.mdindex d56ca2678,c02176bab..f9999a723--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -348,7 -380,74 +380,75 @@@ list) · [roadmap.md](docs/roadmap.md)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-17** · Cross-references keep text typed over their generated text (IDML import and export), with the page number still live, as InDesign shows them until updated; a cross-reference whose destination is gone shows its saved text and page instead of "??"; and a cross-reference's text breaks at its spaces instead of inside words. 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.diff --cc crates/compose/src/tests.rsindex da00325a5,3083261fb..78e30d16b--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -7291,33 -7751,184 +7751,215 @@@ fn greek_text_gets_greek_hyphenation()assert_eq!(hyphen::hyphen_points_in("ανθρωπος", &hyphen::Limits::default(), el), vec![2, 5]);}+ /// Rule Above's offset runs from the first line's baseline up to the rule's bottom edge, as in+ /// InDesign: a rule set clear of the cap height sits between the rows, not across the row above+ /// (an INDD project list whose rules crossed the previous paragraph's text).+ #[test]+ fn rule_above_offset_is_measured_from_the_baseline() {+ use designcraft_doc::Rule;+ let rule = Rule { on: true, weight: 1.5, offset: 10.0, ..Default::default() };+ let para = ParaAttrs { rule_above: Some(rule), ..Default::default() };+ let (d, sid, fid) = doc_with("Row one\nRow two", Rect::new(0.0, 0.0, 300.0, 200.0), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let (first, second) = (lines[0], lines[1]);+ let mut decos: Vec<Rect> = cs.frame(fid).unwrap().decos.iter().map(|dc| dc.rect).collect();+ decos.sort_by(|a, b| a.y0.total_cmp(&b.y0));+ let rule = decos[1];+ assert!((rule.y1 - (second.baseline - 10.0)).abs() < 1e-6, "{rule:?}, baseline {}", second.baseline);+ assert!((rule.height() - 1.5).abs() < 1e-6);+ assert!(rule.y0 > first.baseline, "the rule stays below the row above: {rule:?}, its baseline {}", first.baseline);+ }++ #[test]+ fn parent_page_frames_know_which_side_of_the_spine_they_are_on() {+ // Folios on a facing-pages parent: towards/away from spine must differ between its left and right page.+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let w = d.parents[0].pages[0].width;+ let para = ParaFormat { para: ParaAttrs { align: Some(Align::TowardsSpine), ..Default::default() }, ..Default::default() };+ let (_, left_story) = d.add_text_frame(SpreadRef::Parent(0), Rect::new(36.0, 700.0, w - 36.0, 730.0), lid, "7", para.clone()).unwrap();+ let (_, right_story) = d.add_text_frame(SpreadRef::Parent(0), Rect::new(w + 36.0, 700.0, 2.0 * w - 36.0, 730.0), lid, "8", para).unwrap();+ assert!(frame_specs(&d, left_story)[0].left_page);+ assert!(!frame_specs(&d, right_story)[0].left_page);+ }++ #[test]+ fn a_grouped_frame_takes_the_side_of_the_page_its_group_moves_it_to() {+ let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });+ let lid = d.default_layer();+ let (l, r) = (d.spreads[1].pages[0].clone(), d.spreads[1].pages[1].clone());+ let rect = Rect::new(l.x + 36.0, 36.0, l.x + l.width - 36.0, 300.0);+ let (fid, sid) = d.add_text_frame(SpreadRef::Doc(1), rect, lid, "Text", ParaFormat::default()).unwrap();+ // The frame's own coordinates are on the left page; its group's transform puts it on the right one.+ let mut g = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Group, designcraft_geom::PathData::default());+ g.xf = designcraft_geom::Affine::translate((r.x - l.x, 0.0));+ let sp = Arc::make_mut(&mut d.spreads[1]);+ let at = sp.items.iter().position(|it| it.id == fid).unwrap();+ g.content = designcraft_doc::Content::Group { items: vec![sp.items.remove(at)] };+ sp.items.push(Arc::new(g));+ let spec = &frame_specs(&d, sid)[0];+ assert!(spec.right_page && !spec.left_page);+ assert_eq!(spec.page, Some(2));+ }++ /// A right-to-left paragraph's first-line indent belongs at its start side, the right. Applied on+ /// the left it moved the first line the wrong way — out of the frame for the hanging indent a+ /// numbered list uses (right indent 10 mm, first line −10 mm), while the wrapped lines sat where+ /// the first line should have been (#1448).+ #[test]+ fn an_rtl_first_line_indent_is_at_the_right_edge() {+ const MM: f64 = 72.0 / 25.4;+ // Latin text in a right-to-left paragraph: the direction is the paragraph's, and it is the+ // placement that is being measured, so no Arabic font has to be present.+ let text = LOREM;+ let rect = Rect::new(0.0, 0.0, 200.0, 300.0);+ let para = |dir, align, first, left, right| ParaAttrs {+ direction: Some(dir),+ align: Some(align),+ first_line_indent: Some(first),+ left_indent: Some(left),+ right_indent: Some(right),+ ..Default::default()+ };+ // The hanging indent of a numbered list, right to left.+ let (d, sid, _) = doc_with(text, rect, para(designcraft_doc::TextDirection::RightToLeft, Align::Right, -10.0 * MM, 0.0, 10.0 * MM));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!(lines.len() >= 2, "the text wraps: {}", lines.len());+ let right_edge = |l: &Line| l.glyphs.iter().filter(|g| g.visible).map(|g| g.x + g.adv).fold(f64::MIN, f64::max);+ let left_edge = |l: &Line| l.glyphs.iter().filter(|g| g.visible).map(|g| g.x).fold(f64::MAX, f64::min);+ // The first line reaches the frame's right edge; the wrapped lines stop 10 mm short of it.+ assert!((right_edge(lines[0]) - rect.x1).abs() < 1.0, "first line at the edge: {}", right_edge(lines[0]));+ assert!((right_edge(lines[1]) - (rect.x1 - 10.0 * MM)).abs() < 1.0, "wrapped line indented: {}", right_edge(lines[1]));+ // And nothing leaves the frame on the left, which is where the first line used to go.+ for (i, l) in lines.iter().enumerate() {+ assert!(left_edge(l) >= rect.x0 - 0.01, "line {i} starts inside the frame: {}", left_edge(l));+ }++ // The same paragraph left to right is unchanged: the first line hangs on the left.+ let (d, sid, _) = doc_with(text, rect, para(designcraft_doc::TextDirection::LeftToRight, Align::Left, -10.0 * MM, 10.0 * MM, 0.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!((left_edge(lines[0]) - rect.x0).abs() < 1.0, "left to right, first line at the edge: {}", left_edge(lines[0]));+ assert!((left_edge(lines[1]) - (rect.x0 + 10.0 * MM)).abs() < 1.0, "left to right, wrapped line indented: {}", left_edge(lines[1]));+ }++ /// A marginal note (an anchored text frame, Only Align First Line to Grid, 9/10) hangs 15 pt+ /// above its anchor's baseline on a right-hand page. It composes against the document grid where+ /// it is placed: its first line moves down onto the grid line, the second follows 10 pt below,+ /// and its page is the host's. Composed where it was stored, it snapped to a grid measured from+ /// its own top edge and sat on no page.+ #[test]+ fn anchored_text_frames_compose_against_the_grid_where_they_are_placed() {+ use designcraft_doc::anchored::AnchorRelative as R;+ let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });+ d.settings.baseline_grid.start = 36.0;+ d.settings.baseline_grid.increment = 10.0;+ let lid = d.default_layer();+ let page = d.spreads[1].pages[1].clone();+ assert_eq!(page.side, designcraft_doc::PageSide::Right);+ // Body lines at 46, 56, 66, … (on the grid) while the frame top is at 36.+ let body = "One.\nTwo.\nThree.\nFour.";+ let rect = Rect::new(page.x + 108.0, 36.0, page.x + page.width - 36.0, 400.0);+ let (bf, sid) = d.add_text_frame(SpreadRef::Doc(1), rect, lid, body, ParaFormat::default()).unwrap();+ d.item_mut(bf).unwrap().text_frame_mut().unwrap().options.first_baseline = FirstBaseline::Leading;+ let nine_ten = |f: &mut designcraft_doc::story::CharFormat| {+ f.over.size = Some(9.0);+ f.over.leading = Some(designcraft_doc::Leading::Points(10.0));+ };+ d.story_mut(sid).unwrap().format_chars(0..body.len(), nine_ten);+ // The note: its own story in a 60 × 40 frame anchored in the third line.+ let (nid, nsid) = (ItemId(d.alloc()), StoryId(d.alloc()));+ let text = "Note one\u{2028}note two";+ let para = ParaFormat { para: ParaAttrs { grid_align: Some(GridAlign::FirstLineOnly), ..Default::default() }, ..Default::default() };+ let mut story = Story::with_text(nsid, text, para);+ story.format_chars(0..text.len(), nine_ten);+ story.frames.push(nid);+ d.stories.insert(nsid, Arc::new(story));+ let mut note =+ designcraft_doc::Item::new(nid, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 40.0)));+ note.content = Content::Text(designcraft_doc::TextFrame { story: nsid, options: Default::default() });+ let position = designcraft_doc::AnchorPosition::Custom {+ x_relative: R::TextFrame,+ y_relative: R::Anchor,+ x_offset: -72.0,+ y_offset: -15.0,+ object_point: 0,+ ref_point: 0,+ keep_within_column: false,+ spine_relative: false,+ };+ let at = body.find("Three").unwrap();+ d.story_mut(sid).unwrap().insert_object(at, designcraft_doc::AnchoredObject::new(note, position));++ let cache = Cache::new();+ let on_grid = |y: f64| on_grid(y, (36.0, 10.0));+ // (anchor line baseline, note baselines), in spread space.+ let baselines = |d: &Document, cs: &ComposedStory| {+ let host = compose_story(d, sid, &ComposeOptions::default());+ let ft = host.frame(bf).unwrap();+ let o = &ft.objects[0];+ let fxf = d.item(bf).unwrap().xf;+ let anchor = (fxf * Point::new(0.0, ft.lines[o.line].baseline)).y;+ let nxf = fxf * Affine::translate(o.origin.to_vec2()) * d.anchored_item(nid).unwrap().xf;+ (anchor, all_lines(cs).iter().map(|l| (nxf * Point::new(0.0, l.baseline)).y).collect::<Vec<_>>())+ };+ let near = |a: f64, b: f64| (a - b).abs() < 1e-6;++ let (anchor, lines) = baselines(&d, &cache.get(&d, nsid, None));+ assert!(near(anchor, 66.0), "anchor baseline {anchor}");+ assert_eq!(lines.len(), 2);+ assert!(near(lines[0], anchor) && near(lines[1], anchor + 10.0), "note baselines {lines:?}, anchor {anchor}");+ assert_eq!(baselines(&d, &compose_story(&d, nsid, &ComposeOptions::default())).1, lines);+ // The note is on the host's right-hand page, with that page's rectangle.+ let placed = placed::placements(&d, nsid, &mut |h| Arc::new(compose_story(&d, h, &ComposeOptions::default())));+ let spec = &frame_specs_placed(&d, nsid, &placed)[0];+ assert_eq!((spec.page, spec.right_page, spec.left_page), (Some(2), true, false));+ assert!(spec.page_rect.is_some());++ // Host moved down 5 pt: the anchor is off the grid, and the note's first line moves down from+ // 10 pt above it onto the grid line 5 pt above it. The cache composes the note again.+ let xf = d.item(bf).unwrap().xf;+ d.item_mut(bf).unwrap().xf = Affine::translate((0.0, 5.0)) * xf;+ let (anchor, lines) = baselines(&d, &cache.get(&d, nsid, None));+ assert!(near(anchor, 71.0), "anchor baseline {anchor}");+ assert!(on_grid(lines[0]) && near(lines[0], anchor - 5.0) && near(lines[1], lines[0] + 10.0), "note baselines {lines:?}, anchor {anchor}");+ assert_eq!(baselines(&d, &compose_story(&d, nsid, &ComposeOptions::default())).1, lines);++ // The host's page turns into a left-hand page: the note is composed again for that side.+ let before = cache.get(&d, nsid, None);+ Arc::make_mut(&mut d.spreads[1]).pages[1].side = designcraft_doc::PageSide::Left;+ assert!(!Arc::ptr_eq(&before, &cache.get(&d, nsid, None)));+ }+++/// A cross-reference's text breaks at its spaces like ordinary text (it is real text in+/// InDesign), not inside words; edited text whose destination is gone shows its saved page.+#[test]+fn cross_reference_text_breaks_at_its_spaces() {+ let (mut d, sid, _) = doc_with("See X.", Rect::new(36.0, 36.0, 110.0, 400.0), ParaAttrs::default());+ let at = d.story(sid).unwrap().text.find('X').unwrap();+ let st = d.story_mut(sid).unwrap();+ st.delete(at..at + 1);+ st.insert_xref(+ at,+ designcraft_doc::CrossRef {+ text: Some("Page <pageNum />: Bove, Vinny. \"Advent Horizon.\" 1996. Volume 6, issue 5.".into()),+ page: Some("7".into()),+ ..Default::default()+ },+ );+ let x = d.story(sid).unwrap().xrefs[0].clone();+ let shown = crate::xref::xref_text(&d, &x, None);+ assert_eq!(shown, "Page 7: Bove, Vinny. \"Advent Horizon.\" 1996. Volume 6, issue 5.");+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines: Vec<String> =+ cs.frames[0].lines.iter().map(|l| l.glyphs.iter().filter(|g| g.visible).map(|g| g.rendered_char).collect::<String>()).collect();+ assert!(lines.len() > 3, "{lines:?}");+ let words: Vec<&str> = format!("See {shown}.").leak().split(' ').collect();+ for l in &lines {+ for w in l.split(' ').filter(|w| !w.is_empty()) {+ assert!(words.contains(&w), "a line breaks inside a word: {w:?} in {lines:?}");+ }+ }+}diff --cc crates/idml/src/export/story.rsindex 000000000,97c2837ec..4a067e402mode 000000,100644..100644--- a/crates/idml/src/export/story.rs+++ b/crates/idml/src/export/story.rs@@@ -1,0 -1,561 +1,586 @@@+ use super::common::{anchor_self, bool_s, change_type, topic_self, uid, with_props, xref_format_self};+ use super::graphics::graphic_layer_attribute_name;+ use super::{+ BTreeMap, CHAR_BUILTINS, CharFormat, El, Ex, ListType, NO_CHAR_ID, Node, PARA_BUILTINS, ParaAttrs, ParaFormat, Story, TOC_STYLE_ID, names, num,+ st,+ };++ impl<'a> Ex<'a> {+ /// `<GraphicLayerOption>` of a placed graphic: its layer attributes and the nested layer tree.+ pub(super) fn layer_option_el(&mut self, options: &designcraft_doc::GraphicLayerOptions) -> El {+ let mut option = El::new("GraphicLayerOption");+ for (key, value) in &options.attributes {+ if graphic_layer_attribute_name(key) {+ option.set(key, value);+ }+ }+ // Only an ancestor whose subtree is still open can parent the next layer.+ // Reopening a closed subtree would reorder native-edited lists on roundtrip.+ let mut open = Vec::new();+ let mut parents = Vec::with_capacity(options.layers.len());+ for i in 0..options.layers.len() {+ let parent = options.parents.get(i).copied().flatten();+ if let Some(at) = parent.and_then(|p| open.iter().position(|id| *id == p)).filter(|at| *at < 239) {+ open.truncate(at + 1);+ parents.push(parent);+ } else {+ open.clear();+ parents.push(None);+ }+ open.push(i);+ }+ let mut children: Vec<Vec<El>> = vec![Vec::new(); options.layers.len()];+ let mut roots = Vec::new();+ for (i, attributes) in options.layers.iter().enumerate().rev() {+ let mut layer = El::new("GraphicLayer").attr("Self", self.fresh());+ for (key, value) in attributes {+ if graphic_layer_attribute_name(key) {+ layer.set(key, value);+ }+ }+ if let Some(nested) = children.get_mut(i) {+ for child in std::mem::take(nested).into_iter().rev() {+ layer.push(child);+ }+ }+ if let Some(nested) = parents.get(i).copied().flatten().and_then(|parent| children.get_mut(parent)) {+ nested.push(layer);+ } else {+ roots.push(layer);+ }+ }+ for layer in roots.into_iter().rev() {+ option.push(layer);+ }+ option+ }++ /// `<Index>`: nested topics with their See / See also cross-references.+ pub(super) fn index_el(&mut self) -> El {+ let mut topics = self.index_topics.clone();+ for (_, _, target) in &self.index_xrefs {+ topics.entry(vec![target.clone()]).or_default();+ }+ fn build(ex: &mut Ex, topics: &BTreeMap<Vec<String>, String>, prefix: &[String]) -> Vec<El> {+ let mut out = Vec::new();+ for (t, sort) in topics.iter().filter(|(t, _)| t.len() == prefix.len() + 1 && t.starts_with(prefix)) {+ let mut el = El::new("Topic").attr("Self", topic_self(t)).attr("SortOrder", sort).attr("Name", t.last().map_or("", String::as_str));+ for (from, kind, target) in ex.index_xrefs.clone() {+ if from == *t {+ el.push(+ El::new("CrossReference")+ .attr("Self", ex.fresh())+ .attr("ReferencedTopic", topic_self(std::slice::from_ref(&target)))+ .attr("CrossReferenceType", kind)+ .attr("CustomTypeString", ""),+ );+ }+ }+ for c in build(ex, topics, t) {+ el.push(c);+ }+ out.push(el);+ }+ out+ }+ let mut el = El::new("Index").attr("Self", "ix");+ for t in build(self, &topics, &[]) {+ el.push(t);+ }+ el+ }++ pub(super) fn footnote_option_el(&self) -> El {+ let o = &self.d.footnote_options;+ let marker = if o.ref_char_style == st::NO_CHAR_STYLE {+ NO_CHAR_ID.to_string()+ } else {+ names::style_self("CharacterStyle", CHAR_BUILTINS, &o.ref_char_style)+ };+ let enumv = |name: &str, v: &str| {+ let mut e = El::new(name).attr("type", "enumeration");+ e.children.push(Node::Text(v.into()));+ e+ };+ let mut color = El::new("RuleColor").attr("type", "object");+ color.children.push(Node::Text(self.sw(&o.rule.color)));+ let mut el = El::new("FootnoteOption")+ .attr("StartAt", o.start_at)+ .attr("Prefix", &o.prefix)+ .attr("Suffix", &o.suffix)+ .attr("FootnoteTextStyle", names::style_self("ParagraphStyle", PARA_BUILTINS, &o.para_style))+ .attr("FootnoteMarkerStyle", marker)+ .attr("SeparatorText", &o.separator)+ .attr("SpaceBetween", num(o.space_between))+ .attr("Spacer", num(o.space_before))+ .attr("FootnoteFirstBaselineOffset", names::first_baseline_out(o.first_baseline))+ .attr("FootnoteMinimumFirstBaselineOffset", num(o.first_baseline_min))+ .attr("EnableStraddling", bool_s(o.span_columns))+ .attr("RuleOn", bool_s(o.rule.on))+ .attr("RuleLineWeight", num(o.rule.weight))+ .attr("RuleTint", num(o.rule.tint as f64 * 100.0))+ .attr("RuleLeftIndent", num(o.rule.left_indent))+ .attr("RuleWidth", num(o.rule.width))+ .attr("RuleOffset", num(o.rule.offset));+ let restart = names::NOTE_RESTART.iter().find(|r| r.0 == o.restart).map_or("DontRestart", |r| r.1);+ let affix = names::NOTE_AFFIX.iter().find(|r| r.0 == o.affix_in).map_or("NoPrefixSuffix", |r| r.1);+ let mut props = El::new("Properties");+ props.push(enumv("FootnoteNumberingStyle", names::number_style_out(o.style)));+ props.push(enumv("RestartNumbering", restart));+ props.push(enumv("ShowPrefixSuffix", affix));+ props.push(enumv("MarkerPositioning", names::note_marker_out(o.ref_position)));+ props.push(color);+ el.push(props);+ el+ }++ /// `<Footnote>`: the footnote's paragraphs, the first starting with the footnote number marker+ /// and the separator (as InDesign stores them).+ fn footnote_el(&mut self, note: &Story) -> El {+ let mut el = El::new("Footnote");+ let mut paras = self.story_paras(note);+ let lead = vec![Node::Pi("ACE".into(), "4".into()), Node::Text(self.d.footnote_options.separator.clone())];+ if let Some(Node::El(csr)) =+ paras.first_mut().and_then(|p| p.children.iter_mut().find(|n| matches!(n, Node::El(e) if e.name == "CharacterStyleRange")))+ {+ match csr.children.iter_mut().find_map(|n| match n {+ Node::El(c) if c.name == "Content" => Some(c),+ _ => None,+ }) {+ Some(c) => {+ c.children.splice(0..0, lead);+ }+ None => {+ let mut c = El::new("Content");+ c.children = lead;+ csr.children.insert(0, Node::El(c));+ }+ }+ }+ for p in paras {+ el.push(p);+ }+ el+ }++ // ---------- stories ----------++ pub(super) fn story_el(&mut self, s: &Story) -> El {+ let toc = self.d.toc.as_ref().is_some_and(|t| t.story == s.id);+ let mut el = El::new("Story")+ .attr("Self", uid(s.id.0))+ .attr("AppliedTOCStyle", if toc { TOC_STYLE_ID } else { "n" })+ .attr("TrackChanges", "false")+ .attr("StoryTitle", "$ID/");+ el.push(+ El::new("StoryPreference")+ .attr("OpticalMarginAlignment", bool_s(s.optical_margin.on))+ .attr(+ "OpticalMarginSize",+ num(designcraft_doc::OpticalMargin::clamp_size(s.optical_margin.size).unwrap_or(designcraft_doc::OpticalMargin::DEFAULT_SIZE)),+ )+ .attr("FrameType", "TextFrameType")+ .attr("StoryOrientation", if s.vertical { "Vertical" } else { "Horizontal" })+ .attr(+ "StoryDirection",+ if s.direction == designcraft_doc::TextDirection::RightToLeft { "RightToLeftDirection" } else { "LeftToRightDirection" },+ ),+ );+ for psr in self.story_paras(s) {+ el.push(psr);+ }+ el+ }++ /// Write an index reference and record any cross-reference it declares.+ fn index_reference(&mut self, s: &Story, k: usize) -> Option<El> {+ if let Some(r) = s.index_refs.get(k).filter(|r| !r.topics.is_empty()) {+ use designcraft_doc::index::IndexRange as R;+ for n in 1..=r.topics.len() {+ // A shared topic has one key: keep the first reference's+ // value (even empty), rather than inventing a merged key.+ self.index_topics.entry(r.topics[..n].to_vec()).or_insert_with(|| r.sort.get(n - 1).cloned().unwrap_or_default());+ }+ let (kind, limit) = match &r.range {+ R::CurrentPage => (Some("CurrentPage"), None),+ R::ToEndOfStory => (Some("ToEndOfStory"), None),+ R::NextParagraphs(n) => (Some("ForNextNParagraphs"), Some(*n)),+ R::SuppressPageRange => (Some("SuppressPageNumbers"), None),+ R::See(t) => {+ self.index_xrefs.push((r.topics.clone(), "See", t.clone()));+ (None, None)+ }+ R::SeeAlso(t) => {+ self.index_xrefs.push((r.topics.clone(), "SeeAlso", t.clone()));+ (Some("CurrentPage"), None)+ }+ };+ if let Some(kind) = kind {+ let mut el = El::new("PageReference")+ .attr("Self", self.fresh())+ .attr("PageReferenceType", kind)+ .attr("ReferencedTopic", topic_self(&r.topics))+ .attr("Id", k + 1);+ if let Some(n) = limit {+ el.set("PageReferenceLimit", n);+ }+ return Some(el);+ }+ }+ None+ }++ fn anchored_object(&mut self, s: &Story, k: usize) -> Option<El> {+ if let Some(o) = s.objects.get(k) {+ let mut e = self.item_el(&o.item, o.item.xf);+ use designcraft_doc::anchored::AnchorAlign as A;+ let setting = match &o.position {+ designcraft_doc::AnchorPosition::Inline { y_offset } => {+ El::new("AnchoredObjectSetting").attr("AnchoredPosition", "InlinePosition").attr("AnchorYoffset", num(*y_offset))+ }+ designcraft_doc::AnchorPosition::AboveLine { align, space_before, space_after } => El::new("AnchoredObjectSetting")+ .attr("AnchoredPosition", "AboveLine")+ .attr(+ "HorizontalAlignment",+ match align {+ A::Left => "LeftAlign",+ A::Center => "CenterAlign",+ A::Right => "RightAlign",+ },+ )+ .attr("AnchorSpaceAbove", num(*space_before))+ .attr("AnchorYoffset", num(*space_after)),+ designcraft_doc::AnchorPosition::Custom {+ x_relative,+ y_relative,+ x_offset,+ y_offset,+ object_point,+ ref_point,+ keep_within_column,+ spine_relative,+ } => El::new("AnchoredObjectSetting")+ .attr("AnchoredPosition", "Anchored")+ .attr("AnchorPoint", names::anchor_out(*object_point))+ .attr("HorizontalReferencePoint", names::anchor_rel_out(*x_relative, false))+ .attr("VerticalReferencePoint", names::anchor_rel_out(*y_relative, true))+ .attr("HorizontalAlignment", ["LeftAlign", "CenterAlign", "RightAlign"][(*ref_point % 3) as usize])+ .attr("VerticalAlignment", ["TopAlign", "CenterAlign", "BottomAlign"][(*ref_point / 3).min(2) as usize])+ // IDML measures a left-aligned object's X offset leftwards.+ .attr("AnchorXoffset", num(if *ref_point % 3 == 0 { 0.0 - *x_offset } else { *x_offset }))+ .attr("AnchorYoffset", num(*y_offset))+ .attr("PinPosition", bool_s(*keep_within_column))+ .attr("SpineRelative", bool_s(*spine_relative)),+ };+ e.push(setting);+ return Some(e);+ }+ None+ }++ fn apply_tracked_changes(&mut self, s: &Story, f: &CharFormat, csrs: &mut [El], para_br: bool, para_end: usize) {+ // Tracked changes wrap the text they mark.+ if let Some(kind) = change_type(f.over.change) {+ for c in csrs.iter_mut().filter(|c| c.name == "CharacterStyleRange" && !c.children.is_empty()) {+ let mut ch = El::new("Change").attr("Self", self.fresh()).attr("ChangeType", kind);+ ch.children = std::mem::take(&mut c.children);+ c.push(ch);+ }+ }+ if para_br && let Some(c) = csrs.last_mut() {+ let nl = s.runs().find(|(rr, _)| rr.contains(¶_end)).and_then(|(_, nf)| change_type(nf.over.change));+ match nl {+ None => c.push(El::new("Br")),+ Some(kind) => match c.children.last_mut() {+ Some(Node::El(ch)) if ch.name == "Change" && ch.get("ChangeType") == Some(kind) => ch.push(El::new("Br")),+ _ => {+ let mut ch = El::new("Change").attr("Self", self.fresh()).attr("ChangeType", kind);+ ch.push(El::new("Br"));+ c.push(ch);+ }+ },+ }+ }+ }++ /// `ParagraphStyleRange`s of a story (or a table cell's story).+ pub(super) fn story_paras(&mut self, s: &Story) -> Vec<El> {+ let ranges = s.para_ranges();+ let n = ranges.len();+ ranges.into_iter().enumerate().map(|(pi, r)| self.story_para(s, pi, r, pi + 1 == n)).collect()+ }++ fn paragraph_runs(s: &Story, r: &std::ops::Range<usize>) -> Vec<(std::ops::Range<usize>, CharFormat)> {+ // Character runs intersecting the paragraph.+ let mut segs: Vec<(std::ops::Range<usize>, CharFormat)> = Vec::new();+ for (rr, f) in s.runs() {+ let a = rr.start.max(r.start);+ let b = rr.end.min(r.end);+ if a < b {+ segs.push((a..b, f.clone()));+ }+ }+ if segs.is_empty() {+ let f = s.char_format_at(r.start).clone();+ segs.push((r.start..r.start, f));+ }+ segs+ }++ fn story_para(&mut self, s: &Story, pi: usize, r: std::ops::Range<usize>, last: bool) -> El {+ let pf = s.paras.get(pi).cloned().unwrap_or_default();+ let mut psr = self.psr_el(&pf);+ let ends_with_break = s.text.get(r.clone()).and_then(|t| t.chars().next_back()).is_some_and(st::is_break_char);+ let segs = Self::paragraph_runs(s, &r);+ let nseg = segs.len();+ for (k, (rr, f)) in segs.into_iter().enumerate() {+ let seg_start = rr.start;+ let text = &s.text[rr];+ // Split at break characters.+ let mut cur = String::new();+ let mut pending: Vec<Node> = Vec::new();+ let mut csrs: Vec<El> = Vec::new();+ let flush_text = |cur: &mut String, pending: &mut Vec<Node>| {+ if !cur.is_empty() {+ pending.push(Node::Text(std::mem::take(cur)));+ }+ };+ let flush_content = |pending: &mut Vec<Node>, out: &mut Vec<Node>| {+ if !pending.is_empty() {+ let mut c = El::new("Content");+ c.children = std::mem::take(pending);+ out.push(Node::El(c));+ }+ };+ let mut out: Vec<Node> = Vec::new();+ for (ci, ch) in text.char_indices() {+ let ace = match ch {+ st::PAGE_NUMBER | st::NEXT_PAGE_NUMBER | st::PREV_PAGE_NUMBER => Some("18"),+ st::SECTION_MARKER => Some("19"),+ st::INDENT_HERE => Some("7"),+ st::RIGHT_INDENT_TAB => Some("8"),+ _ => None,+ };+ let brk = match ch {+ st::COLUMN_BREAK => Some("NextColumn"),+ st::FRAME_BREAK => Some("NextFrame"),+ st::PAGE_BREAK => Some("NextPage"),+ st::ODD_PAGE_BREAK => Some("NextOddPage"),+ st::EVEN_PAGE_BREAK => Some("NextEvenPage"),+ _ => None,+ };+ if let Some(code) = ace {+ flush_text(&mut cur, &mut pending);+ pending.push(Node::Pi("ACE".into(), code.into()));+ } else if ch == st::TABLE_ANCHOR {+ flush_text(&mut cur, &mut pending);+ flush_content(&mut pending, &mut out);+ if let Some(t) = s.para_table(pi) {+ out.push(Node::El(self.table_el(t)));+ }+ } else if ch == designcraft_doc::ANCHOR_MARK {+ flush_text(&mut cur, &mut pending);+ flush_content(&mut pending, &mut out);+ let k = s.text[..seg_start + ci].matches(designcraft_doc::ANCHOR_MARK).count();+ if let Some(a) = s.anchors.get(k) {+ out.push(Node::El(+ El::new("HyperlinkTextDestination")+ .attr("Self", anchor_self(a.id))+ .attr("Name", &a.name)+ .attr("Hidden", "false")+ .attr("DestinationUniqueKey", a.id & 0xFFFF_FFFF),+ ));+ }+ } else if ch == designcraft_doc::OBJECT_MARK {+ // An anchored object: the item inside the range with its anchoring settings.+ flush_text(&mut cur, &mut pending);+ flush_content(&mut pending, &mut out);+ let k = s.text[..seg_start + ci].matches(designcraft_doc::OBJECT_MARK).count();+ if let Some(el) = self.anchored_object(s, k) {+ out.push(Node::El(el));+ }+ } else if ch == designcraft_doc::INDEX_MARK {+ flush_text(&mut cur, &mut pending);+ flush_content(&mut pending, &mut out);+ let k = s.text[..seg_start + ci].matches(designcraft_doc::INDEX_MARK).count();+ if let Some(el) = self.index_reference(s, k) {+ out.push(Node::El(el));+ }+ } else if ch == designcraft_doc::XREF_MARK {+ // A source wrapping its current text (InDesign regenerates it on update).+ flush_text(&mut cur, &mut pending);+ flush_content(&mut pending, &mut out);+ if !out.is_empty() {+ let mut c = self.csr_el(&f);+ c.children.append(&mut out);+ csrs.push(c);+ }+ let k = s.text[..seg_start + ci].matches(designcraft_doc::XREF_MARK).count();+ if let Some(x) = s.xrefs.get(k) {+ let me = self.fresh();+ let fmt = self.d.xref_formats.iter().position(|ff| ff.name == x.format).map_or("n".to_string(), xref_format_self);+ let text = self.d.xref_values(x.target).map_or("??".into(), |mut v| {+ v.page = "?".into();+ designcraft_doc::xref::expand(self.d.xref_format(&x.format).map_or("<fullPara />", |ff| ff.definition.as_str()), &v)+ });+ let mut c = self.csr_el(&f);- let mut content = El::new("Content");- content.children.push(Node::Text(text));- c.push(content);++ match &x.text {++ // Edited text as typed, its page numbers as InDesign's live++ // cross-reference page number.++ Some(t) => {++ let page = x.page.clone().unwrap_or_else(|| "?".into());++ for (n, part) in t.split(designcraft_doc::xref::PAGE_NUM_BLOCK).enumerate() {++ if n > 0 {++ c.push(++ El::new("TextVariableInstance")++ .attr("Self", self.fresh())++ .attr("Name", "<?AID 001b?>TV XRefPageNumber")++ .attr("ResultText", &page)++ .attr("AssociatedTextVariable", "dTextVariablen<?AID 001b?>TV XRefPageNumber"),++ );++ }++ if !part.is_empty() {++ let mut content = El::new("Content");++ content.children.push(Node::Text(part.to_string()));++ c.push(content);++ }++ }++ }++ None => {++ let mut content = El::new("Content");++ content.children.push(Node::Text(text));++ c.push(content);++ }++ }+ let mut src = El::new("CrossReferenceSource")+ .attr("Self", &me)+ .attr("AppliedFormat", fmt)+ .attr("Name", format!("Cross-Reference {}", self.xref_sources.len() + 1))+ .attr("Hidden", "false");+ src.push(c);+ csrs.push(src);+ self.xref_sources.push((me, x.target));+ }+ } else if let Some(vi) = designcraft_doc::vars::var_index(ch) {+ flush_text(&mut cur, &mut pending);+ flush_content(&mut pending, &mut out);+ if let Some(v) = self.d.text_variables.get(vi) {+ let result = self.d.variable_value(vi, None).unwrap_or_else(|| format!("{}{}", v.before, v.after));+ out.push(Node::El(+ El::new("TextVariableInstance")+ .attr("Self", self.fresh())+ .attr("Name", &v.name)+ .attr("ResultText", result)+ .attr("AssociatedTextVariable", format!("dTextVariablen{}", v.name)),+ ));+ }+ } else if ch == designcraft_doc::NOTE_MARK {+ // Editorial notes aren't written to IDML yet.+ } else if ch == designcraft_doc::ENDNOTE_REF {+ // Endnotes aren't written to IDML yet: the endnote frame keeps their text+ // (numbers included) and the references are left out.+ } else if ch == designcraft_doc::FOOTNOTE_REF {+ // The reference: its own range carrying the reference position.+ flush_text(&mut cur, &mut pending);+ flush_content(&mut pending, &mut out);+ if !out.is_empty() {+ let mut c = self.csr_el(&f);+ c.children.append(&mut out);+ csrs.push(c);+ }+ if let Some(n) = s.notes.get(s.notes_before(seg_start + ci)) {+ let mut c = self.csr_el(&f);+ let pos = self.d.footnote_options.ref_position;+ if pos != designcraft_doc::Position::Normal {+ c.set("Position", names::position_out(pos));+ }+ c.push(self.footnote_el(&n.text));+ csrs.push(c);+ }+ } else if let Some(bt) = brk {+ flush_text(&mut cur, &mut pending);+ flush_content(&mut pending, &mut out);+ if !out.is_empty() {+ let mut c = self.csr_el(&f);+ c.children.append(&mut out);+ csrs.push(c);+ }+ let mut c = self.csr_el(&f);+ c.set("ParagraphBreakType", bt);+ c.push(El::new("Br"));+ csrs.push(c);+ } else {+ cur.push(ch);+ }+ }+ flush_text(&mut cur, &mut pending);+ flush_content(&mut pending, &mut out);+ let is_last_seg = k + 1 == nseg;+ // A break character that ends the paragraph was written as its `Br`.+ let para_br = is_last_seg && !last && !ends_with_break;+ if !out.is_empty() || csrs.is_empty() || para_br {+ let mut c = self.csr_el(&f);+ c.children.extend(out);+ csrs.push(c);+ }+ self.apply_tracked_changes(s, &f, &mut csrs, para_br, r.end);+ for c in csrs {+ psr.push(c);+ }+ }+ psr+ }++ pub(super) fn psr_el(&mut self, pf: &ParaFormat) -> El {+ let mut el = El::new("ParagraphStyleRange").attr("AppliedParagraphStyle", names::style_self("ParagraphStyle", PARA_BUILTINS, &pf.style));+ let mut props = Vec::new();+ let styles = &self.d.styles;+ let pa = with_list_tab(pf.para.clone(), || (styles.resolve_para(pf).0, styles.resolve_para_style(&pf.style).0));+ self.para_attrs(&mut el, &mut props, &pa, Some(&pf.style));+ self.char_attrs(&mut el, &mut props, &pf.chars);+ with_props(el, props)+ }++ pub(super) fn csr_el(&mut self, f: &CharFormat) -> El {+ let id = if f.style.is_empty() || f.style == st::NO_CHAR_STYLE {+ NO_CHAR_ID.to_string()+ } else {+ names::style_self("CharacterStyle", CHAR_BUILTINS, &f.style)+ };+ let mut el = El::new("CharacterStyleRange").attr("AppliedCharacterStyle", id);+ let mut props = Vec::new();+ self.char_attrs(&mut el, &mut props, &f.over);+ with_props(el, props)+ }+ }++ /// The left stop the composer adds for a list's Tab Position, if it adds one.+ fn list_tab_stop(pp: &designcraft_doc::ParaProps) -> Option<f64> {+ if !matches!(pp.list_type, ListType::Bullets | ListType::Numbers) {+ return None;+ }+ pp.list_tab.filter(|t| t.is_finite() && *t >= 0.0 && !pp.tabs.iter().any(|s| (s.position - t).abs() < 1e-6))+ }++ /// IDML has no attribute for the bullets-and-numbering Tab Position, so it is written as the left+ /// stop the composer adds for it, in the TabList of each level (style or paragraph) that sets the+ /// list type, the tab position or the tabs. `resolved` gives this level's resolved attributes and+ /// those it inherits; the stop comes back on import as an ordinary tab stop.+ pub(super) fn with_list_tab(mut a: ParaAttrs, resolved: impl FnOnce() -> (designcraft_doc::ParaProps, designcraft_doc::ParaProps)) -> ParaAttrs {+ if a.list_tab.is_none() && a.tabs.is_none() && a.list_type.is_none() {+ return a;+ }+ let (here, parent) = resolved();+ let stop = list_tab_stop(&here);+ // An inherited TabList holds the parent's stop; a level that ends the list writes its tabs without it.+ if stop.is_none() && list_tab_stop(&parent).is_none() {+ return a;+ }+ let mut tabs = here.tabs;+ if let Some(t) = stop {+ tabs.push(designcraft_doc::TabStop { position: t, align: designcraft_doc::TabAlign::Left, leader: String::new(), align_on: String::new() });+ tabs.sort_by(|a, b| a.position.total_cmp(&b.position));+ }+ a.tabs = Some(tabs);+ a+ }diff --cc crates/idml/src/import/story.rsindex 000000000,3d87fc35a..679f2f668mode 000000,100644..100644--- a/crates/idml/src/import/story.rs+++ b/crates/idml/src/import/story.rs@@@ -1,0 -1,444 +1,491 @@@+ use super::text_attrs::{ace_char, clear_story_drop_cap_styles, inherits_drop_cap_style};+ use super::{+ Arc, BTreeMap, CharAttrs, CharFormat, CharRun, El, HashMap, HashSet, Importer, Item, ItemId, ParaFormat, Story, StoryId, Table, names, st,+ };+ use crate::xml::Node;++ impl<'r> Importer<'r> {+ // ---------- stories ----------++ pub(super) fn story(&mut self, id: StoryId, e: &El) -> Story {+ self.story_with_para(id, e, ParaFormat::default())+ }++ pub(super) fn story_with_para(&mut self, id: StoryId, e: &El, default_para: ParaFormat) -> Story {+ let mut b = StoryBuilder {+ text: String::new(),+ paras: vec![default_para.clone()],+ runs: Vec::new(),+ fresh: true,+ last: CharFormat::default(),+ tables: Vec::new(),+ after_table: None,+ notes: Vec::new(),+ anchors: Vec::new(),+ xrefs: Vec::new(),+ index_refs: Vec::new(),+ objects: Vec::new(),+ };+ self.walk_story(e, &mut b, &default_para, &CharAttrs::default(), &CharFormat::default(), None);+ let StoryBuilder { text, mut paras, runs, last, tables: tbls, notes, anchors, xrefs, index_refs, objects, .. } = b;+ let mut chars: Vec<CharRun> = runs.into_iter().filter(|r| r.len > 0).collect();+ if chars.is_empty() {+ chars.push(CharRun { len: 0, format: last });+ }+ let mut tables = BTreeMap::new();+ for (pi, t) in tbls {+ if let Some(p) = paras.get_mut(pi) {+ p.table = Some(t.id);+ tables.insert(t.id, Arc::new(t));+ }+ }+ let notes = notes.into_iter().enumerate().map(|(i, text)| Arc::new(designcraft_doc::Footnote { id: i as u64 + 1, text })).collect();+ let mut anchor_list = Vec::new();+ for (k, (me, name)) in anchors.into_iter().enumerate() {+ let aid = (id.0 << 24) | (k as u64 + 1);+ self.anchor_ids.insert(me, aid);+ anchor_list.push(Arc::new(designcraft_doc::TextAnchor { id: aid, name }));+ }+ let mut xref_list = Vec::new();- for (k, (me, fmt)) in xrefs.into_iter().enumerate() {- self.xref_srcs.insert(me, (id, k));- let format = self.xref_format_names.get(&fmt).cloned().unwrap_or_else(|| "Full Paragraph & Page Number".into());- xref_list.push(Arc::new(designcraft_doc::CrossRef { target: 0, format }));++ for (k, x) in xrefs.into_iter().enumerate() {++ self.xref_srcs.insert(x.me, (id, k));++ let format = self.xref_format_names.get(&x.format).cloned().unwrap_or_else(|| "Full Paragraph & Page Number".into());++ // Text typed over the generated text is kept (InDesign shows it until the++ // cross-reference is updated); text the format still produces is generated again.++ let definition = self.xref_formats.iter().find(|f| f.name == format).map_or("<fullPara />", |f| f.definition.as_str());++ let edited = !x.text.is_empty() && !designcraft_doc::xref::matches_format(&x.text, definition);++ xref_list.push(Arc::new(designcraft_doc::CrossRef {++ target: 0,++ format,++ text: edited.then_some(x.text),++ page: x.page.filter(|_| edited),++ }));+ }+ let pref = e.find("StoryPreference");+ let optical_margin = designcraft_doc::OpticalMargin {+ on: pref.and_then(|p| p.boolean("OpticalMarginAlignment")).unwrap_or(false),+ size: pref+ .and_then(|p| p.num("OpticalMarginSize"))+ .and_then(designcraft_doc::OpticalMargin::clamp_size)+ .unwrap_or(designcraft_doc::OpticalMargin::DEFAULT_SIZE),+ };+ let mut st = Story {+ id,+ text,+ paras,+ chars,+ frames: vec![],+ direction: if e.find("StoryPreference").and_then(|p| p.get("StoryDirection")) == Some("RightToLeftDirection") {+ designcraft_doc::TextDirection::RightToLeft+ } else {+ designcraft_doc::TextDirection::LeftToRight+ },+ vertical: e.find("StoryPreference").and_then(|p| p.get("StoryOrientation")) == Some("Vertical"),+ optical_margin,+ rev: 0,+ tables,+ notes,+ endnotes: Vec::new(),+ anchors: anchor_list,+ xrefs: xref_list,+ index_refs: index_refs.into_iter().map(Arc::new).collect(),+ objects: objects.into_iter().map(Arc::new).collect(),+ editorial: Vec::new(),+ link: None,+ file_link: None,+ };+ st.fix_notes();+ st.fix_marks();+ // Drop anything inconsistent (e.g. a table sharing a paragraph with another).+ if st.check().is_err() {+ st.tables.retain(|_, _| false);+ for p in &mut st.paras {+ p.table = None;+ }+ }+ st+ }++ /// The format of the text in a `CharacterStyleRange`: its style, and its local attributes over+ /// the enclosing paragraph range's, inside a tracked change if `outer` (the enclosing format) is.+ fn range_format(&mut self, c: &El, pchars: &CharAttrs, outer: &CharFormat) -> CharFormat {+ let style = c.get("AppliedCharacterStyle").map(|r| self.char_style_ref(r)).unwrap_or_else(|| st::NO_CHAR_STYLE.into());+ let mut over = pchars.clone();+ over.merge(&self.char_attrs(c));+ over.change = over.change.or(outer.over.change);+ CharFormat { style, over }+ }++ fn walk_story(&mut self, e: &El, b: &mut StoryBuilder, pf: &ParaFormat, pchars: &CharAttrs, cf: &CharFormat, brk: Option<&str>) {+ for n in &e.children {+ match n {+ Node::El(c) => match c.local() {+ "ParagraphStyleRange" => {+ let style = c.get("AppliedParagraphStyle").map(|r| self.para_style_ref(r)).unwrap_or_else(|| pf.style.clone());+ let para = self.para_attrs(c);+ let mut chars = self.char_attrs(c);+ // A paragraph range inside a tracked change is part of that change.+ chars.change = chars.change.or(cf.over.change);+ let npf = ParaFormat { style, para, chars: CharAttrs::default(), table: None };+ if b.fresh+ && let Some(last) = b.paras.last_mut()+ {+ *last = npf.clone();+ }+ // Text and markers outside any character range (a destination or a+ // cross-reference source at paragraph level) take the paragraph's format.+ let pcf = CharFormat { style: st::NO_CHAR_STYLE.into(), over: chars.clone() };+ self.walk_story(c, b, &npf, &chars, &pcf, None);+ }+ "CharacterStyleRange" => {+ let ncf = self.range_format(c, pchars, cf);+ let bt = c.get("ParagraphBreakType").filter(|t| *t != "Anywhere");+ b.last = ncf.clone();+ self.walk_story(c, b, pf, pchars, &ncf, bt);+ }+ "Content" => {+ for t in &c.children {+ match t {+ Node::Text(s) | Node::CData(s) => {+ let s: String = s+ .chars()+ .filter(|c| *c != '\u{FEFF}')+ .map(|c| if c == '\n' || c == '\r' || c == '\u{2029}' { st::FORCED_LINE_BREAK } else { c })+ .collect();+ b.push(&s, cf);+ }+ Node::Pi(t, v) if t == "ACE" => {+ if let Some(ch) = ace_char(v) {+ b.push(&ch.to_string(), cf);+ }+ }+ _ => {}+ }+ }+ }+ "Br" => {+ // A column, frame or page break ends its paragraph like a return does.+ if let Some(t) = brk {+ let ch = match t {+ "NextColumn" => st::COLUMN_BREAK,+ "NextFrame" => st::FRAME_BREAK,+ "NextOddPage" => st::ODD_PAGE_BREAK,+ "NextEvenPage" => st::EVEN_PAGE_BREAK,+ _ => st::PAGE_BREAK,+ };+ b.push(&ch.to_string(), cf);+ }+ b.push("\n", cf);+ b.paras.push(pf.clone());+ b.fresh = true;+ }+ "Table" => {+ let t = self.table(c);+ b.push_table(t, pf, cf);+ }+ "HyperlinkTextDestination" | "ParagraphDestination" => {+ b.anchors.push((c.get("Self").unwrap_or("").to_string(), c.get("Name").unwrap_or("Anchor").to_string()));+ b.push(&designcraft_doc::ANCHOR_MARK.to_string(), cf);+ }+ "PageReference" => {+ use designcraft_doc::index::IndexRange as R;+ let topic = c.get("ReferencedTopic").and_then(|r| self.index_topics.get(r)).cloned().unwrap_or_default();+ let range = match c.get("PageReferenceType") {+ Some("ToEndOfStory") | Some("ToEndOfDocument") | Some("ToEndOfSection") => R::ToEndOfStory,+ Some("ForNextNParagraphs") => R::NextParagraphs(c.num("PageReferenceLimit").unwrap_or(1.0).max(1.0) as u32),+ Some("SuppressPageNumbers") => R::SuppressPageRange,+ _ => R::CurrentPage,+ };+ b.index_refs.push(designcraft_doc::IndexRef { topics: topic.path, sort: topic.sort, range });+ b.push(&designcraft_doc::INDEX_MARK.to_string(), cf);+ }+ "CrossReferenceSource" => {+ // The generated text is regenerated from the format.- b.xrefs.push((c.get("Self").unwrap_or("").to_string(), c.get("AppliedFormat").unwrap_or("").to_string()));++ let (mut text, mut page) = (String::new(), None);++ xref_saved_text(c, &mut text, &mut page, 0);++ b.xrefs.push(XrefSource {++ me: c.get("Self").unwrap_or("").to_string(),++ format: c.get("AppliedFormat").unwrap_or("").to_string(),++ text,++ page,++ });+ // A source at paragraph level wraps a range; inside a range it holds the+ // text directly and takes that range's format.+ let f = c.find("CharacterStyleRange").map_or_else(|| cf.clone(), |r| self.range_format(r, pchars, cf));+ b.push(&designcraft_doc::XREF_MARK.to_string(), &f);+ }+ "Footnote" => {+ // The text starts with the number marker (ACE 4, dropped) and the separator.+ let mut note = self.story(StoryId(0), c);+ let sep = self.footnote_options.separator.clone();+ if !sep.is_empty() && note.text.starts_with(&sep) {+ note.delete(0..sep.len());+ }+ b.notes.push(note);+ // The reference's position comes from the footnote options.+ let mut rcf = cf.clone();+ rcf.over.position = None;+ b.push(&designcraft_doc::FOOTNOTE_REF.to_string(), &rcf);+ }+ // Anchored page items, including groups containing text frames.+ "Rectangle" | "Oval" | "Polygon" | "GraphicLine" | "Group" | "TextFrame" => {+ if let Some(item) = self.item(c, designcraft_geom::Affine::IDENTITY) {+ use designcraft_doc::anchored::AnchorAlign as A;+ // Each setting the item leaves unset comes from its object style chain,+ // then from the IDML defaults.+ let levels: Vec<&El> = std::iter::once(c).chain(self.object_style_chain(c)).collect();+ let s = |k: &str| {+ let set = levels.iter().filter_map(|l| l.find("AnchoredObjectSetting")).find_map(|x| x.get(k));+ set.unwrap_or(match k {+ "AnchoredPosition" => "InlinePosition",+ "AnchorPoint" => "BottomRightAnchor",+ "HorizontalAlignment" => "LeftAlign",+ "HorizontalReferencePoint" => "TextFrame",+ "VerticalAlignment" => "BottomAlign",+ "VerticalReferencePoint" => "LineBaseline",+ "PinPosition" => "true",+ _ => "",+ })+ };+ let get = |k: &str| s(k).trim().parse::<f64>().ok().filter(|v| v.is_finite()).unwrap_or(0.0);+ let position = match s("AnchoredPosition") {+ "AboveLine" => designcraft_doc::AnchorPosition::AboveLine {+ align: match s("HorizontalAlignment") {+ "CenterAlign" => A::Center,+ "RightAlign" => A::Right,+ _ => A::Left,+ },+ space_before: get("AnchorSpaceAbove"),+ space_after: get("AnchorYoffset"),+ },+ "Anchored" => {+ let col = match s("HorizontalAlignment") {+ "CenterAlign" => 1,+ "RightAlign" => 2,+ _ => 0,+ };+ let row = match s("VerticalAlignment") {+ "CenterAlign" => 1,+ "BottomAlign" => 2,+ _ => 0,+ };+ designcraft_doc::AnchorPosition::Custom {+ x_relative: names::anchor_rel_in(s("HorizontalReferencePoint")),+ y_relative: names::anchor_rel_in(s("VerticalReferencePoint")),+ // IDML measures a left-aligned object's X offset leftwards.+ x_offset: if col == 0 { 0.0 - get("AnchorXoffset") } else { get("AnchorXoffset") },+ y_offset: get("AnchorYoffset"),+ object_point: names::anchor_in(s("AnchorPoint")),+ ref_point: row * 3 + col,+ keep_within_column: s("PinPosition") == "true",+ spine_relative: s("SpineRelative") == "true",+ }+ }+ _ => designcraft_doc::AnchorPosition::Inline { y_offset: get("AnchorYoffset") },+ };+ b.objects.push(designcraft_doc::AnchoredObject::new(item, position));+ b.push(&designcraft_doc::OBJECT_MARK.to_string(), cf);+ }+ }+ "TextVariableInstance" => {+ let t = self.text_variable_instance(c);+ b.push(&t, cf);+ }+ "Change" => {+ // Tracked changes: deleted text stays in the story, marked, and takes no+ // room in the layout.+ let mut ncf = cf.clone();+ match c.get("ChangeType") {+ Some("DeletedText") => ncf.over.change = Some(designcraft_doc::ChangeMark::Deleted),+ Some("InsertedText" | "MovedText") => ncf.over.change = Some(designcraft_doc::ChangeMark::Inserted),+ _ => {}+ }+ self.walk_story(c, b, pf, pchars, &ncf, brk);+ }+ "Properties" | "Note" | "StoryPreference" | "InCopyExportOption" => {}+ _ => self.walk_story(c, b, pf, pchars, cf, brk),+ },+ Node::Pi(t, v) if t == "ACE" => {+ if let Some(ch) = ace_char(v) {+ b.push(&ch.to_string(), cf);+ }+ }+ _ => {}+ }+ }+ }++ pub(super) fn link_threads(&mut self) {+ let threads = std::mem::take(&mut self.ctx.threads);+ let by_self: HashMap<String, ItemId> = self.item_ids.clone();+ let mut per_story: BTreeMap<StoryId, Vec<usize>> = BTreeMap::new();+ for (i, (id, story, _, _)) in threads.iter().enumerate() {+ let sid = self.story_ids.get(story).copied().or_else(|| self.frame_story(*id));+ if let Some(sid) = sid {+ per_story.entry(sid).or_default().push(i);+ }+ }+ for (sid, idx) in per_story {+ let members: HashSet<ItemId> = idx.iter().map(|i| threads[*i].0).collect();+ let next_of: HashMap<ItemId, ItemId> =+ idx.iter().filter_map(|i| by_self.get(&threads[*i].3).filter(|n| members.contains(n)).map(|n| (threads[*i].0, *n))).collect();+ let has_prev: HashSet<ItemId> = next_of.values().copied().collect();+ let mut order = Vec::new();+ let mut seen = HashSet::new();+ for i in &idx {+ let head = threads[*i].0;+ if has_prev.contains(&head) || seen.contains(&head) {+ continue;+ }+ let mut cur = Some(head);+ while let Some(c) = cur {+ if !seen.insert(c) {+ break;+ }+ order.push(c);+ cur = next_of.get(&c).copied();+ }+ }+ for i in &idx {+ let f = threads[*i].0;+ if seen.insert(f) {+ order.push(f);+ }+ }+ if let Some(s) = self.stories.get_mut(&sid) {+ s.frames = order;+ }+ }+ }++ fn frame_story(&self, id: ItemId) -> Option<StoryId> {+ fn find(items: &[Arc<Item>], id: ItemId) -> Option<StoryId> {+ for it in items {+ let mut r = None;+ it.walk(&mut |i| {+ if i.id == id {+ r = i.text_frame().map(|t| t.story);+ }+ });+ if r.is_some() {+ return r;+ }+ }+ None+ }+ self.spreads.iter().chain(self.parents.iter()).find_map(|s| find(&s.items, id))+ }++ /// A nested style list replaces the one a style or paragraph inherits, and with it the drop+ /// cap style (the list's leading "through 1 Dropcap" entry, read into the drop cap style). A+ /// list of its own without that entry clears an inherited drop cap style.+ pub(super) fn clear_inherited_drop_cap_styles(&mut self) {+ let clears = |a: &designcraft_doc::ParaAttrs| a.drop_cap_style.is_none() && a.nested_styles.is_some();+ let cleared: Vec<String> = self+ .styles+ .paragraph+ .iter()+ .filter(|s| clears(&s.para) && inherits_drop_cap_style(&self.styles, s.based_on.as_deref()))+ .map(|s| s.name.clone())+ .collect();+ for name in cleared {+ if let Some(s) = self.styles.para_mut(&name) {+ s.para.drop_cap_style = Some(st::NO_CHAR_STYLE.into());+ }+ }+ for story in self.stories.values_mut() {+ clear_story_drop_cap_styles(&self.styles, story, 0);+ }+ }+ }++ struct StoryBuilder {+ text: String,+ paras: Vec<ParaFormat>,+ runs: Vec<CharRun>,+ /// The current paragraph has no content yet (its format can still be set by a range).+ fresh: bool,+ last: CharFormat,+ /// Tables by anchor paragraph index.+ tables: Vec<(usize, Table)>,+ /// Content after a table anchor starts a new paragraph (with this format).+ after_table: Option<ParaFormat>,+ /// Footnote texts in reference order.+ notes: Vec<Story>,+ /// Text destinations (Self, name) and cross-reference sources (Self, format Self) in order.+ anchors: Vec<(String, String)>,+ index_refs: Vec<designcraft_doc::IndexRef>,- xrefs: Vec<(String, String)>,++ xrefs: Vec<XrefSource>,+ objects: Vec<designcraft_doc::AnchoredObject>,+ }+++/// A cross-reference source as saved: its id, its format's id, and its text with each page number++/// as `<pageNum />` (and the page it last showed).++struct XrefSource {++ me: String,++ format: String,++ text: String,++ page: Option<String>,++}++++/// The text a `CrossReferenceSource` holds, with its live page numbers (InDesign's++/// `XRefPageNumber` text variable) as `<pageNum />`. Returns the text and the page shown.++fn xref_saved_text(e: &El, text: &mut String, page: &mut Option<String>, depth: usize) {++ if depth > 16 {++ return;++ }++ for c in e.elements() {++ match c.local() {++ "Content" => text.push_str(&c.text_content()),++ "TextVariableInstance" if c.get("Name").is_some_and(|n| n.contains("XRefPageNumber")) => {++ text.push_str(designcraft_doc::xref::PAGE_NUM_BLOCK);++ if page.is_none() {++ *page = c.get("ResultText").map(str::to_string);++ }++ }++ "TextVariableInstance" => text.push_str(c.get("ResultText").unwrap_or("")),++ "CharacterStyleRange" => xref_saved_text(c, text, page, depth + 1),++ _ => {}++ }++ }++}+++ impl StoryBuilder {+ /// A table gets an anchor paragraph of its own.+ fn push_table(&mut self, t: Table, pf: &ParaFormat, cf: &CharFormat) {+ let para_empty = self.text.rsplit('\n').next().is_none_or(str::is_empty);+ if !para_empty {+ self.after_table = None;+ self.push("\n", cf);+ self.paras.push(pf.clone());+ }+ self.after_table = None;+ self.push(&st::TABLE_ANCHOR.to_string(), cf);+ self.tables.push((self.paras.len() - 1, t));+ self.after_table = Some(pf.clone());+ self.fresh = false;+ }++ fn push(&mut self, s: &str, f: &CharFormat) {+ if s.is_empty() {+ return;+ }+ if let Some(pf) = self.after_table.take()+ && !s.starts_with('\n')+ {+ self.push("\n", f);+ self.paras.push(pf);+ }+ self.text.push_str(s);+ if !s.contains('\n') || s.len() > 1 {+ self.fresh = false;+ }+ match self.runs.last_mut() {+ Some(r) if r.format == *f => r.len += s.len(),+ _ => self.runs.push(CharRun { len: s.len(), format: f.clone() }),+ }+ }+ }++ /// Deepest table-in-cell or note nesting the drop cap pass walks into.+ pub(super) const MAX_STORY_NESTING: usize = 32;diff --cc crates/idml/src/tests.rsindex a62cfa977,0d078c63c..99c0afae9--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -4262,3 -4581,199 +4581,227 @@@ fn cell_first_baseline_comes_from_cell_let s2 = back.styles.cell.iter().find(|c| c.name == "Cap").unwrap();assert_eq!(s2.first_baseline, Some(FirstBaseline::CapHeight));}++ /// A graphic placed in a table cell is written into the cell, not dropped.+ #[test]+ fn exports_graphic_in_table_cell() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "Intro", ParaFormat::default()).unwrap();+ let asset = designcraft_doc::AssetId(d.alloc());+ let id = d.add_asset(designcraft_doc::Asset {+ id: asset,+ name: "tick.png".into(),+ mime: "image/png".into(),+ data: std::sync::Arc::new(vec![1, 2, 3]),+ ..Default::default()+ });+ let mut t = designcraft_doc::Table::new(d.alloc(), 2, 2, 0, 0, 200.0);+ t.cell_mut(1, 0).unwrap().graphic = Some(designcraft_doc::Graphic {+ layer_options: None,+ asset: id,+ size: (24.0, 24.0),+ xf: designcraft_geom::Affine::IDENTITY,+ clip: None,+ auto_fit: Default::default(),+ fit_align: 4,+ crop: [0.0; 4],+ wrap: Default::default(),+ fill: Default::default(),+ });+ d.story_mut(sid).unwrap().insert_table(5, t);+ let story = zip_text(&export_idml(&d), "Stories/");+ let cell = story.split("<Cell ").nth(3).unwrap_or_default();+ let cell = cell.split("</Cell>").next().unwrap_or_default();+ assert!(cell.contains("<Image "), "{story}");+ assert!(cell.contains("ClipContentToCell=\"true\""), "{story}");+ }++ /// Non-finite numbers in colour values, page bounds and item transforms (NaN, infinities and+ /// values like 1e300 that overflow `f32`) never reach the model: JSON would write them as null.+ #[test]+ fn non_finite_number_lists_never_reach_the_model() {+ let graphic = GRAPHIC.replace(r#"ColorValue="255 0 0""#, r#"ColorValue="NaN 1e300 inf""#);+ let spread = SPREAD+ .replace(r#"Self="p2" AppliedMaster="m1" GeometricBounds="0 0 700 500""#, r#"Self="p2" AppliedMaster="m1" GeometricBounds="0 0 NaN 500""#)+ .replace(r#"ItemTransform="1 0 0 1 50 -300""#, r#"ItemTransform="1 0 0 1 inf -300""#);+ let bytes = zip_files(&[+ ("designmap.xml", DESIGNMAP),+ ("Resources/Graphic.xml", &graphic),+ ("Resources/Styles.xml", STYLES),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", &spread),+ ("Stories/Story_s1.xml", STORY),+ ]);+ let doc = import_idml(&bytes).unwrap();+ for s in &doc.swatches {+ if let SwatchValue::Color { color, .. } | SwatchValue::Paper { color } = &s.value {+ let parts: Vec<f32> = match *color {+ Color::Rgb { r, g, b } => vec![r, g, b],+ Color::Cmyk { c, m, y, k } => vec![c, m, y, k],+ Color::Gray { k } => vec![k],+ };+ assert!(parts.iter().all(|v| v.is_finite()), "swatch {} is not finite: {color:?}", s.name);+ }+ }+ for sp in doc.spreads.iter().chain(&doc.parents) {+ for p in &sp.pages {+ assert!(p.width.is_finite() && p.height.is_finite() && p.x.is_finite(), "page {p:?}");+ }+ }+ assert_eq!(doc.non_finite_item(), None);+ }++ /// Cell Options › Text › Rotation: the angle survives the round trip, and the import says it is+ /// not composed — narrow header columns of vertical labels come in horizontal and wrap mid-word,+ /// and nothing said so (#1468).+ #[test]+ fn rotated_cell_text_round_trips_and_the_import_says_it_is_not_composed() {+ let mut d = Document::new(&NewDocument::default());+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 300.0, 300.0), d.default_layer(), "", ParaFormat::default()).unwrap();+ let mut t = designcraft_doc::Table::new(7, 1, 3, 0, 0, 300.0);+ t.cell_mut(0, 0).unwrap().rotation = 90.0;+ t.cell_mut(0, 1).unwrap().rotation = 270.0;+ d.story_mut(sid).unwrap().insert_table(0, t);+ let bytes = export_idml(&d);+ let story = zip_text(&bytes, "Stories/");+ assert!(story.contains(r#"RotationAngle="90""#) && story.contains(r#"RotationAngle="270""#), "{story}");++ let back = import_idml_report(&bytes, &|_| None).unwrap();+ let t = back.document.stories.values().find(|st| !st.tables.is_empty()).unwrap().tables.values().next().unwrap().clone();+ assert_eq!((t.cell(0, 0).unwrap().rotation, t.cell(0, 1).unwrap().rotation, t.cell(0, 2).unwrap().rotation), (90.0, 270.0, 0.0));+ let about: Vec<&String> = back.warnings.iter().filter(|w| w.contains("rotated text")).collect();+ assert_eq!(about.len(), 1, "one line for the file, not one per cell: {:?}", back.warnings);+ assert!(about[0].starts_with("2 table cell(s)"), "{}", about[0]);+ assert!(about[0].contains("composed horizontally"), "{}", about[0]);++ // A file with no rotated cell says nothing.+ let mut plain = Document::new(&NewDocument::default());+ let (_, sid) =+ plain.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 300.0, 300.0), plain.default_layer(), "", ParaFormat::default()).unwrap();+ plain.story_mut(sid).unwrap().insert_table(0, designcraft_doc::Table::new(8, 1, 2, 0, 0, 200.0));+ let quiet = import_idml_report(&export_idml(&plain), &|_| None).unwrap();+ assert!(quiet.warnings.iter().all(|w| !w.contains("rotated text")), "{:?}", quiet.warnings);+ }++ #[test]+ fn style_names_with_a_literal_colon_survive_a_round_trip() {+ use designcraft_doc::styles::{CellStyle, CharacterStyle, ObjectStyle, ParagraphStyle, TableStyle};+ let names = ["Title: Big", "Group/Child: X", "Back\\slash: \\:"];+ let mut d = small_doc();+ for n in names {+ let st = d.styles_mut();+ st.paragraph.push(ParagraphStyle {+ name: n.into(),+ based_on: None,+ next_style: None,+ para: Default::default(),+ chars: Default::default(),+ shortcut: String::new(),+ });+ st.character.push(CharacterStyle { name: n.into(), based_on: None, chars: Default::default(), shortcut: String::new() });+ st.cell.push(CellStyle { name: n.into(), ..Default::default() });+ st.table.push(TableStyle { name: n.into(), ..Default::default() });+ st.object.push(ObjectStyle { name: n.into(), ..Default::default() });+ }+ let back = import_idml(&export_idml(&d)).unwrap();+ for n in names {+ assert!(+ back.styles.paragraph.iter().any(|s| s.name == n),+ "paragraph {n:?}: {:?}",+ back.styles.paragraph.iter().map(|s| &s.name).collect::<Vec<_>>()+ );+ assert!(back.styles.character.iter().any(|s| s.name == n), "character {n:?}");+ assert!(back.styles.cell.iter().any(|s| s.name == n), "cell {n:?}");+ assert!(back.styles.table.iter().any(|s| s.name == n), "table {n:?}");+ assert!(back.styles.object.iter().any(|s| s.name == n), "object {n:?}");+ }+ // A group is still written as an IDML `:` group path.+ assert_eq!(names::style_name_out(names::PARA_BUILTINS, "Group/Child"), "Group:Child");+ for n in names {+ assert_eq!(names::style_name_in(names::PARA_BUILTINS, &names::style_name_out(names::PARA_BUILTINS, n)), n);+ }+ }++ /// Split Document (EPUB only) comes from the style, or from its EPUB export tag map, and is+ /// written back on the style.+ #[test]+ fn split_document_round_trips() {+ let xml = r#"<?xml version="1.0" encoding="UTF-8"?>+ <idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <RootParagraphStyleGroup Self="rp">+ <ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" PointSize="12" SplitDocument="false"/>+ <ParagraphStyle Self="ParagraphStyle/Part" Name="Part" SplitDocument="true"/>+ <ParagraphStyle Self="ParagraphStyle/Chapter" Name="Chapter" SplitDocument="false">+ <StyleExportTagMap Self="uaStyleExportTagMapnEPUB" ExportType="EPUB" ExportTag="h1" ExportClass="" ExportAttributes="" SplitDocument="true" EmitCss="true"/>+ </ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/Body" Name="Body" SplitDocument="false"/>+ </RootParagraphStyleGroup>+ </idPkg:Styles>"#;+ let d = import_idml_with(&fixture_with_styles(xml), &|_| None).unwrap();+ let split = |d: &designcraft_doc::Document, name: &str| d.styles.export_tag(name, false).is_some_and(|t| t.split);+ assert!(split(&d, "Part") && split(&d, "Chapter") && !split(&d, "Body"));+ let back = import_idml(&export_idml(&d)).unwrap();+ assert!(split(&back, "Part") && split(&back, "Chapter") && !split(&back, "Body"));+ }++ /// EPUB Export Options › Split Document: off, one style (built in or not) or the styles' export+ /// tags, read from the file's `EPubExportPreference` and written back.+ #[test]+ fn epub_split_document_round_trips() {+ use designcraft_doc::EpubSplit;+ let styles =+ STYLES.replace("</RootParagraphStyleGroup>", r#"<ParagraphStyle Self="ParagraphStyle/Chapter" Name="Chapter"/></RootParagraphStyleGroup>"#);+ assert!(styles.contains("ParagraphStyle/Chapter"), "the fixture has a paragraph style group");+ for (attrs, want) in [+ (r#"BreakDocument="false" ParagraphStyleName="ParagraphStyle/Chapter""#, EpubSplit::Off),+ (r#"BreakDocument="true" ParagraphStyleName="ParagraphStyle/Chapter""#, EpubSplit::Style("Chapter".into())),+ (r#"BreakDocument="true" ParagraphStyleName="ParagraphStyle/Text%3aBody""#, EpubSplit::Style("Text/Body".into())),+ (r#"BreakDocument="true" ParagraphStyleName="$ID/NormalParagraphStyle""#, EpubSplit::Style(designcraft_doc::BASIC_PARAGRAPH.into())),+ (r#"BreakDocument="true" ParagraphStyleName="""#, EpubSplit::ExportTags),+ (r#"BreakDocument="true" ParagraphStyleName="ParagraphStyle/Missing""#, EpubSplit::Off),+ ] {+ let prefs = PREFS.replace("</idPkg:Preferences>", &format!("<EPubExportPreference {attrs}/></idPkg:Preferences>"));+ let file = zip_files(&[+ ("designmap.xml", DESIGNMAP),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Styles.xml", &styles),+ ("Resources/Preferences.xml", &prefs),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", SPREAD),+ ("Stories/Story_s1.xml", STORY),+ ]);+ let d = import_idml_with(&file, &|_| None).unwrap();+ assert_eq!(d.settings.epub_split, want, "{attrs}");+ assert_eq!(import_idml(&export_idml(&d)).unwrap().settings.epub_split, want, "{attrs}");+ }+ }++++/// Text typed over a cross-reference's generated text is kept, its page number live (InDesign's++/// XRefPageNumber variable); text the format still produces is generated again. The edits++/// survive export and import.++#[test]++fn keeps_edited_cross_reference_text() {++ let story = r#"<?xml version="1.0" encoding="UTF-8"?>++<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">++<Story Self="s1"><ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle">++<CrossReferenceSource Self="x1" AppliedFormat="n"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Page </Content></CharacterStyleRange><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><TextVariableInstance Self="v1" Name="<?AID 001b?>TV XRefPageNumber" ResultText="7" AssociatedTextVariable="dTextVariablen<?AID 001b?>TV XRefPageNumber"/></CharacterStyleRange><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>: Bove, Vinny. "Advent Horizon." 1996.</Content></CharacterStyleRange></CrossReferenceSource>++<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content> and </Content></CharacterStyleRange>++<CrossReferenceSource Self="x2" AppliedFormat="n"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>"Intro" on page </Content><TextVariableInstance Self="v2" Name="<?AID 001b?>TV XRefPageNumber" ResultText="3" AssociatedTextVariable="dTextVariablen<?AID 001b?>TV XRefPageNumber"/></CharacterStyleRange></CrossReferenceSource>++</ParagraphStyleRange></Story></idPkg:Story>"#;++ let d = import_idml(&fixture_with_story(story)).unwrap();++ d.check().unwrap();++ let s = d.stories.values().find(|s| !s.xrefs.is_empty()).expect("story with cross-references");++ assert_eq!(s.xrefs.len(), 2);++ assert_eq!(s.xrefs[0].text.as_deref(), Some("Page <pageNum />: Bove, Vinny. \"Advent Horizon.\" 1996."));++ assert_eq!(s.xrefs[0].page.as_deref(), Some("7"));++ assert_eq!(s.xrefs[1].text, None, "unedited text follows its format");++ // Its destination is gone: the page it last showed.++ assert_eq!(designcraft_compose::xref::xref_text(&d, &s.xrefs[0], None), "Page 7: Bove, Vinny. \"Advent Horizon.\" 1996.");++ let back = import_idml(&export_idml(&d)).unwrap();++ back.check().unwrap();++ let b = back.stories.values().find(|s| !s.xrefs.is_empty()).unwrap();++ assert_eq!(b.xrefs[0].text, s.xrefs[0].text);++ assert_eq!(b.xrefs[0].page, s.xrefs[0].page);++}