DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
#1620: Port parent resizing to current layout modules
makesomethingshit5c364f98972d
diff --cc ROADMAP.mdindex 349f68fe2,796ff7306..dbf91dc8e--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -1,9 -1,10 +1,10 @@@# DesignCraft roadmap**Stage: pre-alpha** · next: alpha, ~5–7 h away; beta ~28 points and ~420–750 h beyond that (the core-workflow gate, not the percentage: ready for real work is already ~47%)+ - 2026-10-23: placed-artwork layer options survive IDML and native round trips per placement, independently of shared assets. Unsupported visibility overrides are explicit import/preflight/PDF warnings; format 4 prevents older native readers from silently discarding them. Rendering parity is still open; see [graphic-layer-options.md](docs/graphic-layer-options.md).- FID1: PDF export normalizes mixed emitted gradient color spaces to RGB with an explicit warning; homogeneous device-space gradients retain their components. Linear/radial, midpoint, archival and print policies have synthetic regression coverage.- > **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-23 · **Change:** minor (independent parent page resizing, #1620; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text) · **Target:** Adobe InDesign 2026-> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-23 · **Change:** minor (placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text) · **Target:** Adobe InDesign 2026++> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-01 · **Change:** minor (placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text) · **Target:** Adobe InDesign 2026- AR1.1: Kashida justification tests verify space fallback without Tatweel fonts using an isolated font database, while retaining elongation assertions when fonts support it.- AR1: Arabic IDML controls now retain character direction, kashida switches, diacritic offsets/forms, paragraph policy values and independent story/table directions. Shaping preserves joining context and script/language selection; paragraph-level bidi, contextual digit conversion, mark-safe elongation, RTL columns/tables and physical column insertion have regression coverage. Vendor-specific justification and diacritic presets remain explicit preflight warnings; see docs/arabic-typography.md.@@@ -346,13 -382,81 +382,83 @@@ list) · [roadmap.md](docs/roadmap.md)## Progress log- Newest first.+ - **2026-10-30** · The Color Picker takes an eyedropper: dragged from the picker onto the page, it takes the colour the canvas shows (proofed under Proof Colors). No readiness percentage change.+ - **2026-10-30** · The Color Picker is laid out as the reference app's: a field and slider for the component chosen, HSB, Lab, RGB and CMYK values, the old colour, and Add CMYK Swatch; Enter and Esc close it once. No readiness percentage change.+ - **2026-10-18** · Table of Contents gains Create PDF Bookmarks: included headings become nested page destinations, regenerated in their existing outline position on update without replacing or moving surrounding manual bookmarks. The setting survives native and IDML files. No readiness percentage change.- - **2026-10-23** · Parent page size edits target the selected parent page from Properties, the Page Tool Control panel and page handles (#1620), preserving independent document page sizes, Undo/Redo and the existing preview/Alt-drag behavior. No readiness percentage change.+ Newest first.++- **2026-11-01** · Parent page resizing (#1620): Properties, the Page Tool Control panel and on-page handles resize the selected parent page independently of document pages. Stable parent IDs, repeated resizing, anchors and liquid rules are preserved on the current command modules. No readiness percentage change.+++ - **2026-10-30** · Import warnings about a story have a Show button: it closes the warnings (the status line keeps them) and selects the story's first frame, fitted in the window. `file.open` returns `warningItems`, the frame each IDML or InDesign warning is about (or null), matching the converter's INDD story numbers (`story 30892`, written to IDML as `u78ac`) and IDML `Self` names to the imported stories. No readiness percentage change.+ - **2026-10-30** · Parent pages: a running-header variable shows its name in angle brackets on the parent itself (it was blank), as InDesign shows it; on the document pages, and in text with no page, it shows its text as before. No readiness percentage change.+ - **2026-10-30** · Without facing pages, a page of a multi-page spread shows the parent page in its place, as in InDesign: the second page of a two-page spread shows the parent's second page. Every single-sided page showed the parent's first page, so an InDesign book set up without facing pages but laid out in two-page spreads repeated the left parent page's items (a black heading bar) on its right pages and lost the right parent page's. No readiness percentage change.+ - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515).+ - **2026-10-30** · IDML import reads TOC separators and entry styles written with the `$ID/` prefix or as `Properties` children, and the TOC separator notation (`^t`, `^y`, `^m`, `^>`) is shared by the dialog and IDML, with a special-character menu on the separator field (#1249, #1255).+ - **2026-10-29** · Inserting text with many returns no longer takes time that grows with their square (part of #1588): each return copied its paragraph's format with its own insert, moving every format after it. Splitting 20,000 returns into paragraphs took 15.8 s; placing a text file of them now takes 0.2 s, and one of a million returns 5.5 s. No readiness percentage change.+ - **2026-10-28** · A placed image whose pixels would decode past 1 GiB of RGBA (256 Mpx) is refused from its header, before decoding (#1586). A 288 KB 23,000 px gray PNG used to hang the first draw for 9 s and take the app to 4.5 GB; it now draws as an empty frame, and PDF export skips it with a warning. A 300 ppi A0 scan still fits. No readiness percentage change.+ - **2026-10-28** · Discretionary hyphens (U+00AD) break in the single-line composer with automatic hyphenation on or off, matching the paragraph composer. Unbroken soft hyphens remain invisible and zero-width, and words containing them keep only their discretionary break points (#1955). No readiness percentage change.+ - **2026-10-28** · Autoflow no longer sizes the rest of a story by a frame that a Start Paragraph option (next column, frame, page, or odd or even page) ends early (#1209). With a title before a chapter that starts on the next odd page, it estimated a page per few characters, added up to 2000 pages (the autoflow limit) and removed them again: placing 2000 words took 36 s in the app, now 0.4 s, with the same pages. It looks past tracked-deleted paragraphs for the option, as composing does, and asks for every frame that start options and breaks force in one round: 200 one-line chapters on their own pages take 9 ms (58 ms before). A break and the start option it meets count once, and breaks that tracked changes delete or a hidden condition hides don't count. No readiness percentage change.+ - **2026-10-28** · IDML export writes the document's default `StoryPreference` in `Resources/Preferences.xml`, as InDesign does. Only each story carried one, and IDML readers that take the spread reading order from the document's (Okapi's IDML filter) failed on DesignCraft's files. No readiness percentage change.+ - **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-26** · Inner Shadow, Inner Glow (from the edges) and Bevel and Emboss on a frame holding an image follow what the image paints: a transparent part is outside the object, so the effect lines the image's opaque edge, not the frame (#1622). Satin and a centred Inner Glow still follow the frame. 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** · A guide pulled out of a ruler keeps the resize cursor across it until it is dropped; the tool's cursor took over as soon as the pointer left the ruler, so the drag looked as if it had stopped. 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-22** · Paragraph Style Options › Paragraph Shading and Paragraph Border are laid out as InDesign's: headed with the page's name; Tint is a spinner with InDesign's presets and has Overprint beside it (shading, border and gap; a new attribute each, kept through IDML; PDF export warns it doesn't overprint yet); Corner Size and Shape is InDesign's two-by-two grid of corner icons, sizes and shape menus showing each shape's glyph, with the link in the middle; offsets and weights have spinners. Found in the Learn Skills Daily course, chapter 41. 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-18** · German text hyphenates using the MIT-licensed 2006 reform patterns (`hyph-de-1996.tex`) through `hypher`. Explicit 2006 names and plain/2006 locale codes reach both composers; traditional and unknown spelling variants stay unhyphenated. Tests cover this distinction, umlauts, ß, compounds, reformed ck/st breaks and paragraph limits. Six of InDesign's ~40 hyphenation languages. 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-23** · Show Hidden Characters marks table cells as InDesign does: every cell shows its own spaces, tabs and paragraph returns and an end-of-story # after its text (an empty cell shows just the #), and the table paragraph's ¶ sits after the table's bottom right corner. Cells showed no marks. No readiness percentage change.+ - **2026-10-23** · Tables: with the Type tool in a cell, Shift+Tab goes back a cell (it went on to the next one) and Esc toggles between the text and the cell, as in InDesign: the insertion point selects its cell, and selected cells select the text of the first one (`table.toggleSelection`). Esc left the table for the frame. No readiness percentage change.+ - **2026-10-23** · Direct Selection shows a path's direction handles as InDesign: both handles of each selected anchor and, on its neighbours, the handle shaping the segment to it; no handles with no anchor selected, and handles that don't show can't be grabbed. The tool draws the path and its points without the bounding box. Found in the Learn Skills Daily course, chapter 43. No readiness percentage change.+ - **2026-10-23** · Tables: Convert Text to Table… and Convert Table to Text… open InDesign's dialogs (they converted at once, with tabs and paragraphs only). Column and Row Separator take Tab, Comma, Paragraph or any characters typed; Number of Columns, available when both separators are the same, fills rows of that many cells (a list of paragraphs into two columns); Convert Text to Table also applies a Table Style. `table.convertFromText` takes `rowSeparator`, `columns` and `tableStyle`, and `table.convertToText` its separators. Convert Text to Table is available only with text selected outside a table. No readiness percentage change.+ - **2026-10-23** · Tables: the Table menu follows InDesign's order (Cell Options before Insert, Delete and Select; Merge, Unmerge and Split before Convert Cell Type and Convert Rows; Distribute Rows Evenly before Distribute Columns Evenly), and its first item is Insert Table… with InDesign's Cmd+Alt+Shift+T, which opens the dialog (the shortcut ran `table.insert` with its defaults, behind the dialog). The Table panel stays in Window › Type & Tables (Shift+F9). The Insert Table dialog is laid out as InDesign's: Body Rows and Columns, then Header and Footer Rows, as numbers with spinners and right-aligned labels, and a Table Style applied to the new table. 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** · Preferences › Units & Increments with no document open, as in InDesign: the ruler units (horizontal and vertical), the ruler origin and the cursor-key and kerning increments set there are what new documents start with, and New Document opens in those units. They are kept with the application preferences (`prefs.set {defaultUnits}`); a document keeps its own once made. Reported by a reader who works in inches and had to change every file. No readiness percentage change.+ - **2026-10-22** · French and Italian text is hyphenated, with hyph-utf8's patterns through hypher (hyph-fr 2.13 and hyph-it 4.9, MIT): for the Language set in the Character panel (French, French: Canadian, French: Swiss, Italian, or fr / it locale codes). A word with an elision hyphenates after its apostrophe (l'im-pri-me-rie, dell'im-pa-gi-na-zio-ne), in French and Italian only; other languages leave apostrophe words unbroken. Gap 13 shrinks. 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.diff --cc crates/engine/src/cmd/layout/pages.rsindex 000000000,0417f1ff6..4a7092eb2mode 000000,100644..100644--- a/crates/engine/src/cmd/layout/pages.rs+++ b/crates/engine/src/cmd/layout/pages.rs@@@ -1,0 -1,535 +1,589 @@@+ use super::margins::set_page_width;+ use super::{Result, Value, bad, json, str_param};++ #[allow(dead_code)]+ fn _r(_: Result<()>) {}++ /// Layout › Page Size (the Page tool): resize pages one by one. Left pages grow to the left+ /// (the spine stays put); objects move with their page.+ pub(super) fn page_size(s: &mut crate::Session, p: &Value) -> Result<Value> {+ let pages: Vec<usize> =+ p.get("pages").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(|n| n as usize).collect()).unwrap_or_default();+ let n = s.doc()?.doc.page_count();+ if pages.is_empty() || pages.iter().any(|x| *x == 0 || *x > n) {+ return Err(bad("layout.pageSize", "give `pages` (1-based)"));+ }+ let (mut w, mut h) = (p.get("width").and_then(Value::as_f64), p.get("height").and_then(Value::as_f64));+ if let Some(name) = str_param(p, "preset") {+ let pr = designcraft_doc::build::PRESETS+ .iter()+ .find(|x| x.name.eq_ignore_ascii_case(name))+ .ok_or_else(|| bad("layout.pageSize", format!("no preset `{name}`")))?;+ w = Some(pr.width);+ h = Some(pr.height);+ }+ let anchor = match p.get("anchor") {+ None | Some(Value::Null) => 0,+ Some(v) => v.as_u64().filter(|a| *a <= 8).ok_or_else(|| bad("layout.pageSize", "`anchor`: 0–8"))? as usize,+ };+ s.edit(|d, _| {+ resize_pages_from(d, &pages, w, h, anchor);+ Ok(json!({"pages": pages.len()}))+ })+ }++ pub(super) fn page_options(s: &mut crate::Session, p: &Value) -> Result<Value> {+ let pages: Vec<usize> =+ p.get("pages").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(|n| n as usize).collect()).unwrap_or_default();+ let n = s.doc()?.doc.page_count();+ if pages.is_empty() || pages.iter().any(|x| *x == 0 || *x > n) {+ return Err(bad("layout.pageOptions", "give `pages` (1-based)"));+ }+ let overlay = p.get("showParentOverlay").and_then(Value::as_bool);+ s.edit(|d, _| {+ for page in &pages {+ let Some((si, pi)) = d.page_loc(page - 1) else { continue };+ let pg = &mut std::sync::Arc::make_mut(&mut d.spreads[si]).pages[pi];+ if let Some(v) = overlay {+ pg.show_parent_overlay = v;+ }+ }+ Ok(json!({"pages": pages.len()}))+ })+ }++ /// Give `pages` (1-based) their own size. Objects stay on their page; pages with a liquid rule+ /// re-flow their objects by it.+ pub(crate) fn resize_pages(d: &mut designcraft_doc::Document, pages: &[usize], w: Option<f64>, h: Option<f64>) {+ resize_pages_from(d, pages, w, h, 0);+ }++ /// [`resize_pages`] keeping reference point `anchor` (0–8, row-major from the top-left) in place:+ /// the page grows away from it, so objects keep their place relative to it.+ pub(crate) fn resize_pages_from(d: &mut designcraft_doc::Document, pages: &[usize], w: Option<f64>, h: Option<f64>, anchor: usize) {++ for page in pages {++ let Some((si, pi)) = page.checked_sub(1).and_then(|i| d.page_loc(i)) else { continue };++ resize_spread_page(d, designcraft_doc::SpreadRef::Doc(si), pi, w.map(|v| v.max(1.0)), h.map(|v| v.max(1.0)), anchor);++ }++}++++pub(super) fn resize_spread_page(++ d: &mut designcraft_doc::Document,++ sr: designcraft_doc::SpreadRef,++ pi: usize,++ w: Option<f64>,++ h: Option<f64>,++ anchor: usize,++) {+ let (fx, fy) = ((anchor % 3) as f64 / 2.0, (anchor / 3).min(2) as f64 / 2.0);- {- for page in pages {- let Some((si, pi)) = d.page_loc(page - 1) else { continue };- let sp = std::sync::Arc::make_mut(&mut d.spreads[si]);- let old: Vec<f64> = sp.pages.iter().map(|x| x.x).collect();- let old_bounds = sp.pages[pi].bounds();- // The page's own objects (outer pages take the pasteboard beside them).- let last = sp.pages.len() - 1;- let (lo, hi) = (if pi == 0 { f64::NEG_INFINITY } else { old_bounds.x0 }, if pi == last { f64::INFINITY } else { old_bounds.x1 });- let own: Vec<usize> = sp- .items- .iter()- .enumerate()- .filter(|(_, it)| {- let c = it.bounds().center().x;- c >= lo && c < hi- })- .map(|(i, _)| i)- .collect();- let pg = &mut sp.pages[pi];- let dw = w.map_or(0.0, |w| w.max(1.0) - pg.width);- let dh = h.map_or(0.0, |h| h.max(1.0) - pg.height);- if let Some(w) = w {- set_page_width(pg, w.max(1.0));- }- if let Some(h) = h {- pg.height = h.max(1.0);- }- let left = pg.side == designcraft_doc::PageSide::Left;- sp.relayout();- // Keep the spine: shift the whole spread back when a left page grows.- if left && dw != 0.0 {- for q in &mut sp.pages {- q.x -= dw;- }- }- let new: Vec<f64> = sp.pages.iter().map(|x| x.x).collect();- // Objects follow their page.- let shifts: Vec<(f64, f64, f64)> =- sp.pages.iter().enumerate().map(|(k, q)| (old[k], old[k] + q.width - if k == pi { dw } else { 0.0 }, new[k] - old[k])).collect();- for it in &mut sp.items {- let cx = it.bounds().center().x;- if let Some((_, _, dx)) = shifts.iter().find(|(a, b, _)| cx >= *a && cx < *b)- && *dx != 0.0- {- let it = std::sync::Arc::make_mut(it);- it.xf = designcraft_geom::Affine::translate((*dx, 0.0)) * it.xf;- }- }- // Page guides move with their page.- for (k, q) in sp.pages.iter_mut().enumerate() {- let dx = new[k] - old[k];- if dx != 0.0 {- for g in q.guides.iter_mut().filter(|g| g.orientation == designcraft_doc::Orientation::Vertical) {- g.position += dx;- }- }++ let Some(sp) = d.spread_mut(sr) else { return };++ let origin = sp.bounds().x0;++ let old: Vec<f64> = sp.pages.iter().map(|x| x.x).collect();++ let old_bounds = sp.pages[pi].bounds();++ // The page's own objects (outer pages take the pasteboard beside them).++ let Some((leftmost, rightmost)) = sp.outer_page_indices() else { return };++ let (lo, hi) = (if pi == leftmost { f64::NEG_INFINITY } else { old_bounds.x0 }, if pi == rightmost { f64::INFINITY } else { old_bounds.x1 });++ let own: Vec<usize> = sp++ .items++ .iter()++ .enumerate()++ .filter(|(_, it)| {++ let c = it.bounds().center().x;++ c >= lo && c < hi++ })++ .map(|(i, _)| i)++ .collect();++ let pg = &mut sp.pages[pi];++ let dw = w.map_or(0.0, |w| w - pg.width);++ let dh = h.map_or(0.0, |h| h - pg.height);++ if let Some(w) = w {++ set_page_width(pg, w);++ }++ if let Some(h) = h {++ pg.height = h;++ }++ let left = pg.side == designcraft_doc::PageSide::Left;++ sp.relayout();++ // Relayout resets the origin; retain prior edits and grow left pages away from the spine.++ let offset = origin - if left { dw } else { 0.0 };++ for q in &mut sp.pages {++ q.x += offset;++ }++ let new: Vec<f64> = sp.pages.iter().map(|x| x.x).collect();++ // Objects follow their page.++ let shifts: Vec<(f64, f64, f64)> =++ sp.pages.iter().enumerate().map(|(k, q)| (old[k], old[k] + q.width - if k == pi { dw } else { 0.0 }, new[k] - old[k])).collect();++ for it in &mut sp.items {++ let cx = it.bounds().center().x;++ if let Some((_, _, dx)) = shifts.iter().find(|(a, b, _)| cx >= *a && cx < *b)++ && *dx != 0.0++ {++ let it = std::sync::Arc::make_mut(it);++ it.xf = designcraft_geom::Affine::translate((*dx, 0.0)) * it.xf;++ }++ }++ // Page guides move with their page.++ for (k, q) in sp.pages.iter_mut().enumerate() {++ let dx = new[k] - old[k];++ if dx != 0.0 {++ for g in q.guides.iter_mut().filter(|g| g.orientation == designcraft_doc::Orientation::Vertical) {++ g.position += dx;+ }- // Growing away from the anchor: the page's objects and guides keep their place- // relative to it.- let shift = designcraft_geom::Vec2::new(fx * dw, fy * dh);- if shift != designcraft_geom::Vec2::ZERO {- for i in &own {- if let Some(it) = sp.items.get_mut(*i) {- let it = std::sync::Arc::make_mut(it);- it.xf = designcraft_geom::Affine::translate(shift) * it.xf;- }- }- for g in &mut sp.pages[pi].guides {- g.position += if g.orientation == designcraft_doc::Orientation::Vertical { shift.x } else { shift.y };- }++ }++ }++ // Growing away from the anchor: the page's objects and guides keep their place++ // relative to it.++ let shift = designcraft_geom::Vec2::new(fx * dw, fy * dh);++ if shift != designcraft_geom::Vec2::ZERO {++ for i in &own {++ if let Some(it) = sp.items.get_mut(*i) {++ let it = std::sync::Arc::make_mut(it);++ it.xf = designcraft_geom::Affine::translate(shift) * it.xf;+ }- // Liquid rules: objects were carried along with the page's left edge (and the anchor).- let moved = old_bounds + designcraft_geom::Vec2::new(new[pi] - old[pi], 0.0) + shift;- crate::cmd::liquid::apply(d, designcraft_doc::SpreadRef::Doc(si), pi, moved);++ }++ for g in &mut sp.pages[pi].guides {++ g.position += if g.orientation == designcraft_doc::Orientation::Vertical { shift.x } else { shift.y };+ }+ }++ // Liquid rules: objects were carried along with the page's left edge (and the anchor).++ let moved = old_bounds + designcraft_geom::Vec2::new(new[pi] - old[pi], 0.0) + shift;++ crate::cmd::liquid::apply(d, sr, pi, moved);+ }++ /// File › Document Setup values.+ pub(super) fn document_setup(d: &designcraft_doc::Document) -> Value {+ let st = &d.settings;+ let start = d.sections.iter().find(|x| x.start == 0).and_then(|x| x.start_number).unwrap_or(1);+ json!({"width": st.page_width, "height": st.page_height, "pages": d.page_count(), "startPage": start, "facingPages": st.facing_pages,+ "binding": if st.right_to_left_binding { "rightToLeft" } else { "leftToRight" }, "intent": st.intent, "bleed": st.bleed, "slug": st.slug,+ "margins": d.page(0).map(|p| p.margins), "primaryTextFrame": st.primary_text_frame})+ }++ #[cfg(test)]+ mod setup_tests {+ use serde_json::json;++ #[test]+ fn chapter_numbering_sets_style_and_start() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let r = s.execute("layout.chapterNumbering", &json!({})).unwrap();+ assert_eq!(r, json!({"chapterNumber": 1, "label": "1", "style": "arabic", "source": "automatic", "book": null}));+ let r = s.execute("layout.chapterNumbering", &json!({"start": 4, "style": "upperRoman"})).unwrap();+ assert_eq!((&r["label"], &r["source"]), (&json!("IV"), &json!("userDefined")), "a start number means Start Chapter Numbering at");+ s.execute("variables.define", &json!({"name": "Chapter", "type": "chapterNumber"})).unwrap();+ let d = &s.doc().unwrap().doc;+ let chapter = d.variable("Chapter").unwrap();+ assert_eq!(d.variable_value(chapter, Some(0)).as_deref(), Some("IV"), "the Chapter Number variable uses the style");+ for bad in [json!({"style": "symbols"}), json!({"start": 0}), json!({"start": 100_000}), json!({"source": "nextBook"})] {+ assert!(s.execute("layout.chapterNumbering", &bad).is_err(), "{bad}");+ }+ s.execute("layout.chapterNumbering", &json!({"source": "sameAsPrevious"})).unwrap();+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.execute("layout.chapterNumbering", &json!({})).unwrap()["source"], "userDefined", "undoable");+ }++ #[test]+ fn document_setup_sets_every_pages_margins_in_one_step() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 3, "margins": 36})).unwrap();+ let f = s.execute("frame.create", &json!({"rect": [36, 36, 576, 756], "content": "text"})).unwrap();+ let r = s.execute("layout.documentSetup", &json!({})).unwrap();+ assert_eq!(r["margins"], json!({"top": 36.0, "bottom": 36.0, "inside": 36.0, "outside": 36.0}));+ let m = json!({"top": 72, "bottom": 54, "inside": 72, "outside": 72});+ let r = s.execute("layout.documentSetup", &json!({"margins": m, "bleed": 9, "adjustLayout": true})).unwrap();+ assert_eq!(r["margins"]["bottom"], 54.0);+ let d = &s.doc().unwrap().doc;+ assert!(+ d.spreads.iter().chain(&d.parents).flat_map(|sp| &sp.pages).all(|pg| pg.margins.top == 72.0 && pg.margins.bottom == 54.0),+ "every page and parent page"+ );+ let b = d.item(designcraft_doc::ItemId(f["id"].as_u64().unwrap())).unwrap().bounds();+ assert!((b.y0 - 72.0).abs() < 1e-6, "Adjust Layout: the frame follows the margins ({b:?})");+ // One step: undo brings back the margins and the bleed.+ s.execute("edit.undo", &json!({})).unwrap();+ let r = s.execute("layout.documentSetup", &json!({})).unwrap();+ assert_eq!((r["margins"]["top"].clone(), r["bleed"][0].clone()), (json!(36.0), json!(0.0)));+ for bad in [+ json!({"width": 0}),+ json!({"height": -5}),+ json!({"width": 1e9}),+ json!({"width": "wide"}),+ json!({"margins": -1}),+ json!({"margins": {"top": 1}}),+ ] {+ assert!(s.execute("layout.documentSetup", &bad).is_err(), "{bad}");+ }+ assert_eq!(s.execute("layout.documentSetup", &json!({})).unwrap()["width"], 612.0, "refused values change nothing");+ }++ #[test]+ fn document_setup_pages_start_bleed_slug() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ let r = s.execute("layout.documentSetup", &json!({})).unwrap();+ assert_eq!(r["pages"], 2);+ assert_eq!(r["startPage"], 1);+ let r = s.execute("layout.documentSetup", &json!({"pages": 5, "startPage": 2, "bleed": 9, "slug": [0, 18, 0, 0], "intent": "web"})).unwrap();+ assert_eq!(r["pages"], 5);+ assert_eq!(r["startPage"], 2);+ assert_eq!(r["bleed"], json!([9.0, 9.0, 9.0, 9.0]));+ assert_eq!(r["slug"], json!([0.0, 18.0, 0.0, 0.0]));+ assert_eq!(r["intent"], "web");+ let d = &s.doc().unwrap().doc;+ assert_eq!(d.page_name(0), "2");+ assert_eq!(d.page(0).unwrap().side, designcraft_doc::PageSide::Left);+ assert_eq!(d.spreads[0].pages.len(), 2, "pages 2–3 form the first spread");+ let r = s.execute("layout.documentSetup", &json!({"pages": 3})).unwrap();+ assert_eq!(r["pages"], 3);+ s.doc().unwrap().doc.check().unwrap();+ }++ #[test]+ fn right_to_left_binding_reverses_spreads() {+ use designcraft_doc::PageSide::{Left, Right};+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 4})).unwrap();+ // A frame on page 2 stays on page 2.+ let w = s.doc().unwrap().doc.settings.page_width;+ let f = s.execute("frame.create", &json!({"rect": [w + 72.0, 72, w + 200.0, 200], "content": "text", "text": "two"})).unwrap();+ let r = s.execute("layout.documentSetup", &json!({"binding": "rightToLeft"})).unwrap();+ assert_eq!(r["binding"], "rightToLeft");+ let d = &s.doc().unwrap().doc;+ let shape: Vec<Vec<(designcraft_doc::PageSide, f64)>> = d.spreads.iter().map(|sp| sp.pages.iter().map(|p| (p.side, p.x)).collect()).collect();+ // Page 1 alone on the left; pages 2–3 with 2 on the right; page 4 alone on the right.+ assert_eq!(shape, vec![vec![(Left, 0.0)], vec![(Right, w), (Left, 0.0)], vec![(Right, 0.0)]]);+ let (si, _) = d.page_loc(1).unwrap();+ assert_eq!(si, 1);+ let it = d.item(designcraft_doc::ItemId(f["id"].as_u64().unwrap())).unwrap();+ assert_eq!(d.spreads[si].page_at_x(it.bounds().center().x), Some(0), "the frame is still on page 2");+ assert!(it.bounds().x0 >= w, "page 2 is the right page now");+ d.check().unwrap();+ // And back.+ s.execute("layout.documentSetup", &json!({"binding": "leftToRight"})).unwrap();+ let d = &s.doc().unwrap().doc;+ assert_eq!(d.spreads[1].pages.iter().map(|p| (p.side, p.x)).collect::<Vec<_>>(), vec![(Left, 0.0), (Right, w)]);+ }++ /// Bound right to left, a parent spread lists its right page first; each document page still+ /// shows the parent page on its own side, at its own position, also after an IDML round trip.+ #[test]+ fn right_to_left_binding_shows_the_parent_page_of_the_same_side() {+ use designcraft_doc::PageSide::{Left, Right};+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 4})).unwrap();+ s.execute("layout.documentSetup", &json!({"binding": "rightToLeft"})).unwrap();+ let w = s.doc().unwrap().doc.settings.page_width;+ let parent = json!({"kind": "parent", "index": 0});+ for (rect, text) in [(json!([72, 36, 200, 60]), "left head"), (json!([w + 72.0, 36, w + 200.0, 60]), "right head")] {+ s.execute("frame.create", &json!({"spread": parent, "rect": rect, "content": "text", "text": text})).unwrap();+ }+ let d = s.doc().unwrap().doc.clone();+ assert_eq!(d.parents[0].pages.iter().map(|p| (p.side, p.x)).collect::<Vec<_>>(), vec![(Right, w), (Left, 0.0)]);+ let docs = [(*d).clone(), designcraft_idml::import_idml(&designcraft_idml::export_idml(&d)).unwrap()];+ for d in docs {+ let mut s = crate::Session::new();+ s.add_document(crate::DocState::new(d, None));+ for (page, side, text) in [(0, Left, "left head"), (1, Right, "right head"), (2, Left, "left head"), (3, Right, "right head")] {+ let r = s.execute("layout.overrideParentItems", &json!({"page": page})).unwrap();+ let d = &s.doc().unwrap().doc;+ let ids = r["ids"].as_array().unwrap();+ assert_eq!(ids.len(), 1, "page {}", page + 1);+ let it = d.item(designcraft_doc::ItemId(ids[0].as_u64().unwrap())).unwrap();+ let story = d.story(it.text_frame().unwrap().story).unwrap();+ assert_eq!((d.page(page).unwrap().side, story.text.trim_end()), (side, text), "page {}", page + 1);+ assert_eq!(d.page_of_item(it.id), Some(page), "page {}", page + 1);+ }+ }+ }++ /// Multi-column frames filled the left column first in a right-to-left document (#100):+ /// stories made in a right-to-left-bound document start their columns on the right.+ #[test]+ fn new_stories_follow_the_binding_direction() {+ use designcraft_doc::TextDirection::{LeftToRight, RightToLeft};+ let text = (1..=12).map(|i| format!("الفقرة {i}")).collect::<Vec<_>>().join("\n");+ for (binding, expected) in [("rightToLeft", RightToLeft), ("leftToRight", LeftToRight)] {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"preset": "A4", "pages": 1})).unwrap();+ s.execute("layout.documentSetup", &json!({"binding": binding})).unwrap();+ let f = s.execute("frame.create", &json!({"rect": [40, 170, 555, 260], "content": "text", "text": text})).unwrap();+ s.execute("object.textFrameOptions", &json!({"ids": [f["id"]], "columns": 2, "gutter": 20})).unwrap();+ let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap());+ let st = s.doc().unwrap();+ assert_eq!(st.doc.story(sid).unwrap().direction, expected, "{binding}");+ let cs = s.cache.get(&st.doc, sid, None);+ let fr = &cs.frames[0];+ let (first, last) = (fr.lines.first().unwrap(), fr.lines.last().unwrap());+ assert!(fr.columns.len() == 2 && first.x0 != last.x0, "the text fills both columns: {:?}", fr.columns);+ assert_eq!(first.x0 > last.x0, expected == RightToLeft, "{binding}: the first line is in the first column");+ // An empty frame given text content starts a story too.+ let g = s.execute("frame.create", &json!({"rect": [40, 400, 555, 500]})).unwrap();+ s.execute("object.content", &json!({"ids": [g["id"]], "type": "text"})).unwrap();+ let d = &s.doc().unwrap().doc;+ let tf = d.item(designcraft_doc::ItemId(g["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;+ assert_eq!(d.story(tf).unwrap().direction, expected, "{binding}: object.content");+ }+ }+ }++ #[cfg(test)]+ mod page_size_tests {+ use serde_json::json;+++ #[test]++ fn document_page_resize_preserves_shifted_spread_objects_and_guides() {++ for binding in ["leftToRight", "rightToLeft"] {++ let mut s = crate::Session::new();++ s.execute("file.new", &json!({"pages": 3, "facingPages": true, "width": 400, "height": 400})).unwrap();++ s.execute("layout.documentSetup", &json!({"binding": binding})).unwrap();++ let before = s.doc().unwrap().doc.clone();++ let (si, _) = before.page_loc(1).unwrap();++ let (left, right) = before.spreads[si].outer_page_indices().unwrap();++ let mut items = Vec::new();++ for pi in [left, right] {++ let x = before.spreads[si].pages[pi].x;++ let id = s.execute("frame.create", &json!({"spread": si, "rect": [x + 80.0, 80, x + 180.0, 180]})).unwrap()["id"].as_u64().unwrap();++ items.push(designcraft_doc::ItemId(id));++ s.execute("guide.add", &json!({"spread": si, "page": pi, "orientation": "vertical", "position": x + 120.0})).unwrap();++ }++ let first = before.first_page_of_spread(si) + 1;++ s.execute("layout.pageSize", &json!({"pages": [first + left], "width": 300})).unwrap();++ let shifted = s.doc().unwrap().doc.clone();++ let sp = &shifted.spreads[si];++ assert_eq!(sp.bounds().x0, 100.0);++ assert_eq!(sp.pages[right].x, 400.0);++ assert_eq!(sp.pages[left].guides[0].position, 220.0);++ assert_eq!(sp.pages[right].guides[0].position, 520.0);++ assert_eq!(shifted.item(items[0]).unwrap().bounds().x0, 180.0);++ assert_eq!(shifted.item(items[1]).unwrap().bounds().x0, 480.0);++ for width in [500, 450, 520] {++ s.execute("layout.pageSize", &json!({"pages": [first + right], "width": width})).unwrap();++ let d = &s.doc().unwrap().doc;++ let sp = &d.spreads[si];++ assert_eq!(sp.bounds().x0, 100.0, "{binding}, width {width}");++ assert_eq!(sp.pages[right].x, 400.0);++ for pi in [left, right] {++ assert_eq!(sp.pages[pi].guides, shifted.spreads[si].pages[pi].guides);++ }++ for id in &items {++ assert_eq!(d.item(*id).unwrap().bounds(), shifted.item(*id).unwrap().bounds());++ }++ assert_eq!(d.parents, before.parents);++ assert_eq!(d.settings, before.settings);++ d.check().unwrap();++ }++ }++ }+++ #[test]+ fn page_size_per_page_keeps_objects_on_their_page() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 3})).unwrap();+ // Page 3 is the right page of spread 2 (pages 2–3); an object on it.+ let d = s.doc().unwrap().doc.clone();+ let (si, pi) = d.page_loc(2).unwrap();+ let x0 = d.spreads[si].pages[pi].x;+ let id = s.execute("frame.create", &json!({"spread": si, "rect": [x0 + 100.0, 100, x0 + 200.0, 200]})).unwrap()["id"].as_u64().unwrap();+ s.execute("layout.pageSize", &json!({"pages": [2], "width": 300, "height": 500})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ let left = &d.spreads[si].pages[0];+ assert_eq!((left.width, left.height), (300.0, 500.0));+ assert_eq!(d.spreads[si].pages[1].x, x0, "the spine stays");+ let it = d.item(designcraft_doc::ItemId(id)).unwrap();+ assert_eq!(it.bounds().x0, x0 + 100.0);+ assert_eq!(d.page_of_item(it.id), Some(2));+ s.execute("layout.pageSize", &json!({"pages": [3], "preset": "A4"})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ assert!((d.spreads[si].pages[1].width - 595.276).abs() < 0.01);+ assert!(s.execute("layout.pageSize", &json!({"pages": [9], "width": 100})).is_err());+ }+ }++ #[cfg(test)]+ mod spread_tests {+ use serde_json::json;++ #[test]+ fn three_page_spread_survives_page_inserts() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 5})).unwrap();+ // [1] [2 3] [4 5]: page 4 joins spread 1 → [1] [2 3 4] [5].+ let d = s.doc().unwrap().doc.clone();+ let (si, pi) = d.page_loc(3).unwrap();+ let x = d.spreads[si].pages[pi].x;+ let id = s.execute("frame.create", &json!({"spread": si, "rect": [x + 50.0, 50, x + 150.0, 150]})).unwrap()["id"].as_u64().unwrap();+ s.execute("layout.pages.toSpread", &json!({"page": 4, "spread": 1})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ assert_eq!(d.spreads[1].pages.len(), 3);+ assert!(!d.spreads[1].allow_shuffle);+ assert_eq!(d.page_of_item(designcraft_doc::ItemId(id)), Some(3), "the object went with its page");+ // Adding a page at the start reshuffles the others but keeps the 3-page spread.+ s.execute("layout.pages.insert", &json!({"after": 0, "count": 1})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ assert!(d.spreads.iter().any(|sp| sp.pages.len() == 3 && !sp.allow_shuffle));+ assert_eq!(d.page_count(), 6);+ d.check().unwrap();+ }+ }++ #[cfg(test)]+ mod page_numbering_view_tests {+ use serde_json::json;++ use crate::Session;++ #[test]+ fn section_and_absolute_page_numbering_view() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 4})).unwrap();+ s.execute("layout.section", &json!({"page": 1, "startNumber": 1, "style": "lowerRoman"})).unwrap();+ s.execute("layout.section", &json!({"page": 3, "startNumber": 1})).unwrap();+ assert_eq!((0..4).map(|i| s.page_label(i)).collect::<Vec<_>>(), ["i", "ii", "1", "2"]);+ assert_eq!(s.resolve_page("ii"), Some(1));+ assert_eq!(s.resolve_page("1"), Some(2), "section name first");+ assert_eq!(s.resolve_page("+1"), Some(0), "+n is a position");+ s.execute("prefs.set", &json!({"absolutePageNumbers": true})).unwrap();+ assert_eq!((0..4).map(|i| s.page_label(i)).collect::<Vec<_>>(), ["1", "2", "3", "4"]);+ assert_eq!(s.resolve_page("1"), Some(0));+ assert_eq!(s.resolve_page("9"), None);+ }++ #[test]+ fn section_start_numbers_are_bounded() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ for n in [json!(0), json!(100_000), json!(u32::MAX), json!(u64::from(u32::MAX) + 2), json!(-1), json!(2.5), json!("7")] {+ let e = s.execute("layout.section", &json!({"page": 1, "startNumber": n})).unwrap_err().to_string();+ assert!(e.contains("startNumber"), "{n}: {e}");+ assert!(s.execute("layout.documentSetup", &json!({"startPage": n})).is_err(), "{n}");+ }+ assert_eq!((0..2).map(|i| s.page_label(i)).collect::<Vec<_>>(), ["1", "2"]);+ let r = s.execute("layout.section", &json!({"page": 1, "startNumber": 99_999})).unwrap();+ assert_eq!(r["names"], json!(["99999", "100000"]));+ }++ #[test]+ fn numbering_options_apply_in_one_undo_step_or_not_at_all() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 4})).unwrap();+ let names = |s: &crate::Session| (0..4).map(|i| s.doc().unwrap().doc.page_name(i)).collect::<Vec<_>>();+ let r = s+ .execute(+ "layout.numberingOptions",+ &json!({"page": 3, "startNumber": 5, "style": "lowerRoman", "prefix": "A-", "includePrefix": true, "chapter": {"start": 4, "style": "upperRoman"}}),+ )+ .unwrap();+ assert_eq!((r["names"].clone(), r["chapter"].clone()), (json!(["1", "2", "A-v", "A-vi"]), json!("IV")));+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(names(&s), ["1", "2", "3", "4"], "one undo reverts the section…");+ assert_eq!(s.doc().unwrap().doc.chapter_label(), "1", "…and the chapter numbering");+ // A refused part leaves the other undone too.+ for bad in [+ json!({"page": 3, "startNumber": 5, "chapter": {"start": 100_000}}),+ json!({"page": 3, "startNumber": 4_294_967_295u64, "chapter": {"start": 2}}),+ json!({"page": 3, "prefix": "A+B", "chapter": {"start": 2}}),+ json!({"page": 9, "chapter": {"start": 2}}),+ ] {+ assert!(s.execute("layout.numberingOptions", &bad).is_err(), "{bad}");+ assert_eq!(names(&s), ["1", "2", "3", "4"], "{bad}");+ assert_eq!(s.doc().unwrap().doc.settings.chapter_source, designcraft_doc::ChapterSource::Automatic, "{bad}");+ }+ // Removing a section keeps the chapter part.+ s.execute("layout.section", &json!({"page": 3, "startNumber": 1})).unwrap();+ s.execute("layout.numberingOptions", &json!({"page": 3, "remove": true, "chapter": {"source": "userDefined", "start": 2}})).unwrap();+ assert_eq!(names(&s), ["1", "2", "3", "4"]);+ assert_eq!(s.doc().unwrap().doc.chapter_label(), "2");+ }++ #[test]+ fn section_prefixes_are_short_and_avoid_plus_and_comma() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ for prefix in ["A-", "Appendix", "§ 1"] {+ s.execute("layout.section", &json!({"page": 2, "prefix": prefix})).unwrap();+ }+ for prefix in ["Appendix1", "A+", "1,2"] {+ assert!(s.execute("layout.section", &json!({"page": 2, "prefix": prefix})).is_err(), "{prefix}");+ }+ assert!(s.execute("layout.section", &json!({"page": 2, "style": "symbols"})).is_err());+ assert_eq!(s.doc().unwrap().doc.sections.iter().find(|x| x.start == 1).unwrap().prefix, "§ 1", "a refused prefix changes nothing");+ }++ /// `layout.section` edits one named setting; the others stay as the section was (#717).+ #[test]+ fn updating_a_section_keeps_settings_the_command_does_not_name() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 4})).unwrap();+ s.execute(+ "layout.section",+ &json!({"page": 2, "startNumber": 1, "style": "lowerRoman", "prefix": "A-", "includePrefix": true, "marker": "First"}),+ )+ .unwrap();+ assert_eq!(s.page_label(1), "A-i");+ s.execute("layout.section", &json!({"page": 2, "marker": "Second"})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ let sec = d.sections.iter().find(|x| x.start == 1).expect("the page-2 section is still the only one there");+ assert_eq!(sec.marker, "Second");+ assert_eq!(sec.start_number, Some(1), "startNumber is kept");+ assert_eq!(sec.style, designcraft_doc::NumberStyle::LowerRoman, "style is kept");+ assert_eq!(sec.prefix, "A-", "prefix is kept");+ assert!(sec.include_prefix, "includePrefix is kept");+ assert_eq!(s.page_label(1), "A-i");+ }+ }++ #[cfg(test)]+ mod spread_rotation_input_tests {+ use serde_json::json;++ #[test]+ fn quarter_turns_work_and_other_angles_are_rejected_without_mutation() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let rotation = |s: &crate::Session| s.doc().unwrap().doc.spreads[0].pages[0].view_rotation;+ for bad in [json!(45), json!(-45), json!(91), json!("90"), json!(0.5)] {+ assert!(s.execute("layout.rotateSpreadView", &json!({"angle": bad})).is_err(), "{bad}");+ assert_eq!(rotation(&s), 0, "invalid input must not change the view");+ }+ s.execute("layout.rotateSpreadView", &json!({"angle": 90})).unwrap();+ assert_eq!(rotation(&s), 1);+ s.execute("layout.rotateSpreadView", &json!({"angle": -90})).unwrap();+ assert_eq!(rotation(&s), 0);+ s.execute("layout.rotateSpreadView", &json!({"angle": 180})).unwrap();+ assert_eq!(rotation(&s), 2);+ s.execute("layout.rotateSpreadView", &json!({"angle": 0})).unwrap();+ assert_eq!(rotation(&s), 0, "zero resets the spread view");+ }+ }++ #[cfg(test)]+ mod insert_count_tests {+ use serde_json::json;++ use crate::Session;++ /// A count that is given but is not a number of pages used to insert one page anyway:+ /// `{"count": 0}` added a page, `-1` and `1.5` added one each, and `10000` was quietly capped+ /// to 9999. A position past the last page appends, which is deliberate.+ #[test]+ fn a_page_count_insert_pages_cannot_mean_is_refused() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap();+ let total = |s: &mut Session| s.execute("layout.pages.insert", &json!({"count": 1})).unwrap()["total"].as_u64().unwrap();+ assert_eq!(total(&mut s), 3, "one page added");++ for params in [json!({"count": 0}), json!({"count": -1}), json!({"count": 1.5}), json!({"count": 10000}), json!({"count": "two"})] {+ let e = s.execute("layout.pages.insert", ¶ms).expect_err("refused").to_string();+ assert!(e.contains("1 to 9999 pages"), "{params}: {e}");+ }+ // Nothing was inserted by any of those.+ assert_eq!(s.doc().unwrap().doc.page_count(), 3);+ // A position past the last page still appends, which `insert_pages_bounds.rs` pins.+ let r = s.execute("layout.pages.insert", &json!({"after": 99})).unwrap();+ assert_eq!((r["pages"].as_u64(), r["total"].as_u64()), (Some(1), Some(4)));+ // The positions it does have still work: after the first page of three.+ let r = s.execute("layout.pages.insert", &json!({"count": 2, "after": 0})).unwrap();+ assert_eq!((r["pages"].as_u64(), r["total"].as_u64()), (Some(2), Some(6)));+ }+ }diff --cc crates/engine/src/cmd/layout/parents.rsindex 000000000,293fe27e9..d43bc14famode 000000,100644..100644--- a/crates/engine/src/cmd/layout/parents.rs+++ b/crates/engine/src/cmd/layout/parents.rs@@@ -1,0 -1,504 +1,541 @@@+ use super::{Result, SpreadId, Value, bad, json};++ /// A parent spread named by prefix, label (`A-Parent`) or index.+ pub(super) fn parent_spread_index(d: &designcraft_doc::Document, v: &Value) -> Option<usize> {+ match v {+ Value::Number(n) => n.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < d.parents.len()),+ Value::String(s) => d.parents.iter().position(|p| p.parent.as_ref().is_some_and(|i| i.prefix == *s || i.label() == *s)),+ _ => None,+ }+ }++ /// A parent named by a command parameter: its id (a number), its full label (`"A-Parent"`), or+ /// its prefix (`"A"`) when only one parent has it. `null` or `"[None]"` → `Some(None)` (no parent);+ /// missing → `None` (the command's default). Unknown or ambiguous names are errors, so a typo never+ /// clears a page's parent.+ pub(super) fn parent_ref(cmd: &str, d: &designcraft_doc::Document, v: Option<&Value>) -> Result<Option<Option<SpreadId>>> {+ let Some(v) = v else { return Ok(None) };+ match v {+ Value::Null => Ok(Some(None)),+ Value::String(s) if s == "[None]" => Ok(Some(None)),+ Value::Number(n) => {+ let id = n.as_u64().ok_or_else(|| bad(cmd, format!("no parent with id {n}")))?;+ d.parents.iter().find(|p| p.id.0 == id).map(|p| Some(Some(p.id))).ok_or_else(|| bad(cmd, format!("no parent with id {id}")))+ }+ Value::String(s) => {+ let by = |f: &dyn Fn(&designcraft_doc::ParentInfo) -> bool| -> Vec<SpreadId> {+ d.parents.iter().filter(|p| p.parent.as_ref().is_some_and(f)).map(|p| p.id).collect()+ };+ let mut hits = by(&|i| i.label() == *s);+ if hits.is_empty() {+ hits = by(&|i| i.prefix == *s);+ }+ match hits.as_slice() {+ [id] => Ok(Some(Some(*id))),+ [] => Err(bad(cmd, format!("no parent named `{s}`"))),+ _ => Err(bad(cmd, format!("more than one parent is named `{s}`: give its id"))),+ }+ }+ _ => Err(bad(cmd, "`parent` is a parent id, a parent name or null")),+ }+ }++ /// Layout › Pages › Parent Options: Based on Parent. A base that would make a cycle is refused.+ pub(super) fn parent_options(s: &mut crate::Session, p: &Value) -> Result<Value> {+ const CMD: &str = "layout.parents.options";+ let d = &s.doc()?.doc;+ let Some(Some(id)) = parent_ref(CMD, d, p.get("parent"))? else { return Err(bad(CMD, "`parent` names the parent to change")) };+ let pi = d.parent_index(id).ok_or_else(|| bad(CMD, format!("no parent with id {}", id.0)))?;+ let base = parent_ref(CMD, d, p.get("basedOn"))?.ok_or_else(|| bad(CMD, "missing `basedOn` (a parent, or null for [None])"))?;+ let label = |d: &designcraft_doc::Document, i: usize| d.parents.get(i).and_then(|x| x.parent.as_ref()).map(|i| i.label());+ if let Some(b) = base+ && d.parent_base_cycles(pi, b)+ {+ let (name, b) = (label(d, pi).unwrap_or_default(), d.parent_index(b).and_then(|i| label(d, i)).unwrap_or_default());+ return Err(bad(CMD, format!("{name} cannot be based on {b}: that would make a cycle")));+ }+ let out = json!({"parent": label(d, pi), "basedOn": base.and_then(|b| d.parent_index(b)).and_then(|i| label(d, i))});+ if d.parents.get(pi).and_then(|x| x.parent.as_ref()).and_then(|i| i.based_on) == base {+ return Ok(out);+ }+ s.edit(|d, _| {+ let info = d.parents.get_mut(pi).map(std::sync::Arc::make_mut).and_then(|x| x.parent.as_mut()).ok_or_else(|| bad(CMD, "no such parent"))?;+ info.based_on = base;+ Ok(out)+ })+ }+++pub(super) fn parent_page_target(d: &designcraft_doc::Document, p: &Value, cmd: &str) -> Result<(usize, usize)> {++ let parent = p.get("parent").and_then(Value::as_u64).map(SpreadId).ok_or_else(|| bad(cmd, "give a parent spread id"))?;++ let si = d.parent_index(parent).ok_or_else(|| bad(cmd, "no such parent"))?;++ let pi = p++ .get("page")++ .and_then(Value::as_u64)++ .and_then(|n| usize::try_from(n).ok())++ .filter(|i| *i < d.parents[si].pages.len())++ .ok_or_else(|| bad(cmd, "no such parent page"))?;++ Ok((si, pi))++}++++pub(super) fn parent_page_size(s: &mut crate::Session, p: &Value) -> Result<Value> {++ const ID: &str = "layout.parentPageSize";++ let (si, pi) = parent_page_target(&s.doc()?.doc, p, ID)?;++ let size = |key| {++ p.get(key)++ .map(|v| {++ v.as_f64().filter(|v| v.is_finite() && *v > 0.0 && *v <= 15552.0).ok_or_else(|| bad(ID, "page size out of range (0 < size ≤ 216 in)"))++ })++ .transpose()++ };++ let (w, h) = (size("width")?, size("height")?);++ if w.is_none() && h.is_none() {++ return Err(bad(ID, "give width or height"));++ }++ let anchor = match p.get("anchor") {++ None => 0,++ Some(v) => v.as_u64().filter(|n| *n <= 8).ok_or_else(|| bad(ID, "anchor: 0–8"))? as usize,++ };++ s.edit(|d, _| {++ super::pages::resize_spread_page(d, designcraft_doc::SpreadRef::Parent(si), pi, w, h, anchor);++ d.sync_parent_margins();++ Ok(json!({"parent": d.parents[si].id.0, "page": pi}))++ })++}+++ #[cfg(test)]+ mod parent_margin_tests {+ use designcraft_doc::{Document, Margins};+ use serde_json::json;++ use crate::Session;++ fn margins(d: &Document) -> Vec<(Margins, u32, bool)> {+ (0..d.page_count()).filter_map(|i| d.page(i)).map(|p| (p.margins, p.columns.count, p.local_margins)).collect()+ }++ #[test]+ fn document_setup_margins_let_pages_follow_their_parent_page_again() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 3})).unwrap();+ s.execute("layout.marginsAndColumns", &json!({"pages": [1], "margins": 100})).unwrap();+ s.execute("layout.marginsAndColumns", &json!({"pages": [2], "margins": 100, "columns": 3})).unwrap();+ s.execute("layout.documentSetup", &json!({"margins": 20})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ let twenty = Margins::uniform(20.0);+ assert_eq!(m, vec![(twenty, 1, false), (twenty, 1, false), (twenty, 3, true)], "own columns stay local");+ s.execute("layout.marginsAndColumns", &json!({"parent": "A", "margins": 50})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m[1], (Margins::uniform(50.0), 1, false), "page 2 follows the parent page again");+ assert_eq!(m[2], (twenty, 3, true));+ }++ #[test]+ fn pages_follow_their_parent_pages_margins_unless_set_locally() {+ let mut s = Session::new();+ // Facing: [1] [2 3]; page 3 gets its own margins.+ s.execute("file.new", &json!({"pages": 3})).unwrap();+ s.execute("layout.marginsAndColumns", &json!({"pages": [2], "margins": 100})).unwrap();+ // A's left page: only the left document page follows.+ let left = json!({"top": 10, "bottom": 20, "inside": 30, "outside": 40});+ s.execute("layout.marginsAndColumns", &json!({"parent": "A", "pages": [0], "margins": left, "columns": 2})).unwrap();+ let l = Margins { top: 10.0, bottom: 20.0, inside: 30.0, outside: 40.0 };+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m, vec![(Margins::uniform(36.0), 1, false), (l, 2, false), (Margins::uniform(100.0), 1, true)]);+ // A's right page: page 1 follows, page 3 keeps its own.+ s.execute("layout.marginsAndColumns", &json!({"parent": "A-Parent", "pages": [1], "margins": 50})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m, vec![(Margins::uniform(50.0), 1, false), (l, 2, false), (Margins::uniform(100.0), 1, true)]);+ // A page inserted after page 1 pushes page 2 to the right: it takes the right parent page's.+ s.execute("layout.pages.insert", &json!({"after": 0, "count": 1, "parent": "A"})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m[1], (l, 2, false), "the new left page");+ assert_eq!(m[2], (Margins::uniform(50.0), 1, false), "old page 2, now a right page");+ assert_eq!(m[3], (Margins::uniform(100.0), 1, true));+ assert!(s.execute("layout.marginsAndColumns", &json!({"parent": "Z", "margins": 10})).is_err());+ }++ /// Insert Pages before a page, or at the start of the document (`before: 0`), as InDesign's+ /// dialog offers; `after` and `before` together are refused without an undo step.+ #[test]+ fn pages_go_in_before_a_page_or_at_the_start() {+ let mut s = Session::new();+ // Facing: [1] [2 3].+ s.execute("file.new", &json!({"pages": 3})).unwrap();+ let b = s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap()["id"].as_u64().unwrap();+ let ids = |s: &Session| -> Vec<u64> {+ let d = &s.doc().unwrap().doc;+ (0..d.page_count()).map(|i| d.page(i).unwrap().id.0).collect()+ };+ let parent = |s: &Session, i: usize| s.doc().unwrap().doc.page(i).unwrap().parent.map(|p| p.0);+ let old = ids(&s);+ s.execute("layout.pages.insert", &json!({"before": 0, "parent": "B"})).unwrap();+ let now = ids(&s);+ assert_eq!(now.len(), 4);+ assert_eq!(now[1..], old[..], "the old pages follow the new first page");+ assert_eq!(parent(&s, 0), Some(b));+ // Before page 4 (index 3, the old page 3): two pages without a parent.+ s.execute("layout.pages.insert", &json!({"before": 3, "count": 2, "parent": null})).unwrap();+ let then = ids(&s);+ assert_eq!(then.len(), 6);+ assert_eq!(then[..3], now[..3]);+ assert_eq!(then[5], old[2]);+ assert_eq!((parent(&s, 3), parent(&s, 4)), (None, None));+ // Refused without a change or an undo step: both placements, even one of them null, and a+ // placement that isn't a page index.+ let undo = s.doc().unwrap().history.undo.len();+ for bad in [+ json!({"after": 0, "before": 1}),+ json!({"after": 0, "before": null}),+ json!({"after": null, "before": 1}),+ json!({"before": -1}),+ json!({"before": "0"}),+ json!({"before": null}),+ json!({"after": 1.5}),+ json!({"before": 6}),+ json!({"before": 99}),+ ] {+ assert!(s.execute("layout.pages.insert", &bad).is_err(), "{bad}");+ assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{bad}");+ assert_eq!(ids(&s), then, "{bad}");+ }+ }++ #[test]+ fn applying_a_parent_gives_its_margins_and_local_margins_stay_local() {+ let mut s = Session::new();+ // Facing: [1] [2 3].+ s.execute("file.new", &json!({"pages": 3})).unwrap();+ s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap();+ s.execute("layout.marginsAndColumns", &json!({"parent": "B", "margins": 70, "columns": 3})).unwrap();+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "B"})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m[1], (Margins::uniform(70.0), 3, false), "the page takes B's margins");+ // Page 3 is given margins equal to A's: they are its own all the same.+ s.execute("layout.marginsAndColumns", &json!({"pages": [2], "margins": 36})).unwrap();+ s.execute("layout.marginsAndColumns", &json!({"parent": "A", "margins": 20})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m[0], (Margins::uniform(20.0), 1, false));+ assert_eq!(m[1], (Margins::uniform(70.0), 3, false), "B's page is not A's");+ assert_eq!(m[2], (Margins::uniform(36.0), 1, true));+ // Back to A: page 2 follows A again.+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "A"})).unwrap();+ assert_eq!(margins(&s.doc().unwrap().doc)[1], (Margins::uniform(20.0), 1, false));+ }++ #[test]+ fn parent_guides_show_on_pages_but_stay_on_the_parent() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ // A vertical guide 100 pt into A's right page (x = 612 in the parent spread).+ s.execute("guide.add", &json!({"spread": {"kind": "parent", "index": 0}, "page": 1, "orientation": "vertical", "position": 712})).unwrap();+ let d = &s.doc().unwrap().doc;+ let right = d.page(0).unwrap();+ let shown: Vec<f64> = d.parent_guides(right).map(|g| g.position).collect();+ assert_eq!(shown, vec![100.0], "moved to the document page's place");+ assert_eq!(d.parent_guides(d.page(1).unwrap()).count(), 0, "the left page shows A's left page's guides");+ // Not the document page's own: not listed, moved or deleted from there.+ assert_eq!(s.execute("guide.list", &json!({"spread": 0})).unwrap(), json!([]));+ assert!(s.execute("guide.move", &json!({"spread": 0, "page": 0, "index": 0, "position": 50})).is_err());+ assert!(s.execute("guide.delete", &json!({"spread": 0, "page": 0, "index": 0})).is_err());+ }+ }++ #[cfg(test)]+ mod parent_tests {+ use serde_json::json;++ fn parent_of(s: &crate::Session, page: usize) -> Option<u64> {+ s.doc().unwrap().doc.page(page).unwrap().parent.map(|p| p.0)+ }++ #[test]+ fn parents_with_one_prefix_stay_distinct() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ let a = s.execute("layout.parents.new", &json!({"prefix": "IMG", "name": "Parent"})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("layout.parents.new", &json!({"prefix": "IMG", "name": "Half"})).unwrap()["id"].as_u64().unwrap();+ s.execute("layout.pages.applyParent", &json!({"pages": [0], "parent": b})).unwrap();+ assert_eq!(parent_of(&s, 0), Some(b));+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "IMG-Half"})).unwrap();+ assert_eq!(parent_of(&s, 1), Some(b));+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "IMG-Parent"})).unwrap();+ assert_eq!(parent_of(&s, 1), Some(a));+ // A prefix two parents share, or a name no parent has, is an error and changes nothing.+ assert!(s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "IMG"})).is_err());+ assert!(s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "Nope"})).is_err());+ assert!(s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": 999_999})).is_err());+ assert_eq!(parent_of(&s, 1), Some(a));+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "[None]"})).unwrap();+ assert_eq!(parent_of(&s, 1), None);+ }++ #[test]+ fn edit_parents_shows_the_named_parent() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let ids: Vec<u64> =+ ["B", "C", "D"].iter().map(|p| s.execute("layout.parents.new", &json!({"prefix": p})).unwrap()["id"].as_u64().unwrap()).collect();+ s.ui_requests.clear();+ let r = s.execute("layout.parents.edit", &json!({"parent": ids[2]})).unwrap();+ assert_eq!(r, json!({"on": true, "parent": ids[2]}));+ assert!(s.doc().unwrap().editing_parents);+ let n = s.doc().unwrap().doc.parent_index(designcraft_doc::SpreadId(ids[2])).unwrap();+ let shown: Vec<_> = s+ .ui_requests+ .iter()+ .filter_map(|r| match r {+ crate::UiRequest::View { params } => params.get("showSpread").cloned(),+ _ => None,+ })+ .collect();+ assert_eq!(shown, vec![json!({"kind": "parent", "index": n})]);+ let r = s.execute("layout.parents.edit", &json!({"on": true, "parent": "C-Parent"})).unwrap();+ assert_eq!(r["parent"], ids[1]);+ assert!(s.execute("layout.parents.edit", &json!({"parent": "Z-Parent"})).is_err());+ let r = s.execute("layout.parents.edit", &json!({"on": false})).unwrap();+ assert_eq!(r, json!({"on": false, "parent": null}));+ assert!(!s.doc().unwrap().editing_parents);+ }++ /// A new parent takes the first page's columns, dragged column guides included: the right+ /// parent page as the first (right) page has them, the left one mirrored across the spine.+ /// `document.inspect` reports where those columns are.+ #[test]+ fn a_new_parent_keeps_dragged_columns() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 1})).unwrap();+ let dragged = designcraft_doc::Columns { count: 2, gutter: 12.0, positions: Some(vec![0.0, 100.0, 130.0, 540.0]) };+ // There is no command for dragging a column guide yet, so set what an import would leave.+ s.edit(|d, _| {+ let pg = &mut std::sync::Arc::make_mut(&mut d.spreads[0]).pages[0];+ (pg.columns, pg.local_margins) = (dragged.clone(), true);+ Ok(())+ })+ .unwrap();+ let id = s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap()["id"].as_u64().unwrap();+ let d = &s.doc().unwrap().doc;+ let parent = d.parents.iter().find(|p| p.id.0 == id).unwrap();+ assert_eq!(parent.pages.len(), 2);+ let side = |s: designcraft_doc::PageSide| parent.pages.iter().find(|p| p.side == s).unwrap();+ let (left, right) = (side(designcraft_doc::PageSide::Left), side(designcraft_doc::PageSide::Right));+ assert_eq!(right.columns, dragged);+ assert_eq!(right.column_rects().iter().map(|r| r.width()).collect::<Vec<_>>(), vec![100.0, 410.0]);+ assert_eq!(left.columns.positions, Some(vec![0.0, 410.0, 440.0, 540.0]));+ assert_eq!(left.column_rects().iter().map(|r| r.width()).collect::<Vec<_>>(), vec![410.0, 100.0]);++ let inspect = s.execute("document.inspect", &json!({})).unwrap();+ let page = &inspect["spreads"][0]["pages"][0];+ assert_eq!((page["columns"].clone(), page["customColumns"].clone()), (json!(2), json!(true)), "{page}");+ assert_eq!(page["columnRects"][0], json!([36.0, 36.0, 136.0, 756.0]), "{page}");+ }++ fn columns_of(s: &crate::Session, abs: usize) -> (Option<Vec<f64>>, bool) {+ let pg = s.doc().unwrap().doc.page(abs).unwrap().clone();+ (pg.columns.positions, pg.local_margins)+ }++ /// Three columns across a 540 pt margin box (36 pt margins), column guides unlocked.+ fn three_columns(pages: u64) -> crate::Session {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": pages})).unwrap();+ s.execute("layout.marginsAndColumns", &json!({"parent": "A", "columns": 3, "gutter": 12})).unwrap();+ s.execute("view.lockColumnGuides", &json!({"on": false})).unwrap();+ s+ }++ /// Dragging a column guide moves its gutter's two guides together, stops at the neighbouring+ /// gutter and the margin, makes a following page's columns its own, and undoes in one step.+ #[test]+ fn move_column_guide_moves_the_gutter_pair_within_its_neighbours() {+ let mut s = three_columns(1);+ assert_eq!(columns_of(&s, 0), (None, false), "the page follows A");+ let mv =+ |s: &mut crate::Session, gutter: u64, x: f64| s.execute("layout.moveColumnGuide", &json!({"page": 0, "gutter": gutter, "position": x}));+ let r = mv(&mut s, 0, 236.0).unwrap();+ assert_eq!(r, json!({"positions": [0.0, 200.0, 212.0, 356.0, 368.0, 540.0], "left": 236.0}));+ assert_eq!(columns_of(&s, 0), (Some(vec![0.0, 200.0, 212.0, 356.0, 368.0, 540.0]), true));+ let inspect = s.execute("document.inspect", &json!({})).unwrap();+ assert_eq!(inspect["spreads"][0]["pages"][0]["columnRects"][0], json!([36.0, 36.0, 236.0, 756.0]));+ // Past the next gutter: it stops there, and the middle column has no width.+ assert_eq!(mv(&mut s, 0, 1000.0).unwrap()["left"], json!(36.0 + 344.0));+ // Past the right margin: the last gutter stops 12 pt (its width) inside it.+ assert_eq!(mv(&mut s, 1, 1e12).unwrap()["positions"], json!([0.0, 344.0, 356.0, 528.0, 540.0, 540.0]));+ // Past the left margin.+ assert_eq!(mv(&mut s, 0, -1e12).unwrap()["positions"], json!([0.0, 0.0, 12.0, 528.0, 540.0, 540.0]));+ for _ in 0..3 {+ s.execute("edit.undo", &json!({})).unwrap();+ }+ assert_eq!(columns_of(&s, 0), (Some(vec![0.0, 200.0, 212.0, 356.0, 368.0, 540.0]), true));+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(columns_of(&s, 0), (None, false), "one undo step per drag");+ }++ /// On a parent page the drag changes the parent, and the document pages that follow it get+ /// the new columns; a page with columns of its own keeps them.+ #[test]+ fn move_column_guide_on_a_parent_reaches_the_pages_that_follow_it() {+ let mut s = three_columns(3);+ // Page 1, the left page of spread 1, gets columns of its own.+ let x = s.doc().unwrap().doc.spreads[1].pages[0].margin_rect().x0 + 300.0;+ s.execute("layout.moveColumnGuide", &json!({"spread": 1, "page": 0, "gutter": 1, "position": x})).unwrap();+ let own = columns_of(&s, 1);+ assert!(own.1 && own.0.is_some());+ let d = &s.doc().unwrap().doc;+ // A's right page: the one page 0 (a right page) and page 2 follow.+ let x0 = d.parents[0].pages[1].margin_rect().x0;+ s.execute("layout.moveColumnGuide", &json!({"parent": "A", "page": 1, "gutter": 0, "position": x0 + 100.0})).unwrap();+ let moved = vec![0.0, 100.0, 112.0, 356.0, 368.0, 540.0];+ assert_eq!(s.doc().unwrap().doc.parents[0].pages[1].columns.positions, Some(moved.clone()));+ assert_eq!(columns_of(&s, 0), (Some(moved.clone()), false));+ assert_eq!(columns_of(&s, 2), (Some(moved), false));+ assert_eq!(columns_of(&s, 1), own, "page 1's columns are its own");+ // The same parent page by spread reference.+ let spread = json!({"kind": "parent", "index": 0});+ s.execute("layout.moveColumnGuide", &json!({"spread": spread, "page": 1, "gutter": 0, "position": x0 + 50.0})).unwrap();+ assert_eq!(columns_of(&s, 0).0.unwrap()[1], 50.0);+ }++ /// A drag's preview in one document is put back there when another document became active.+ #[test]+ fn a_column_guide_preview_is_cancelled_in_its_own_document() {+ let mut s = three_columns(1);+ let uid = s.doc().unwrap().uid;+ s.begin_interaction("Move Column Guide").unwrap();+ s.preview("layout.moveColumnGuide", json!({"page": 0, "gutter": 0, "position": 236})).unwrap();+ s.execute("file.new", &json!({})).unwrap();+ s.cancel_interaction_of(uid);+ s.set_active(0);+ assert!(s.doc().unwrap().interaction.is_none());+ assert_eq!(columns_of(&s, 0), (None, false));+ }++ #[test]+ fn move_column_guide_refuses_while_locked_and_hostile_params() {+ let mut s = three_columns(1);+ s.execute("view.lockColumnGuides", &json!({"on": true})).unwrap();+ assert!(s.execute("layout.moveColumnGuide", &json!({"page": 0, "gutter": 0, "position": 200})).is_err());+ assert_eq!(columns_of(&s, 0), (None, false));+ s.execute("view.lockColumnGuides", &json!({"on": false})).unwrap();+ for p in [+ json!({"page": 0, "gutter": 0}),+ json!({"page": 0, "gutter": 0, "position": f64::NAN}),+ json!({"page": 0, "gutter": 0, "position": "200"}),+ json!({"page": 0, "gutter": 2, "position": 200}),+ json!({"page": 0, "gutter": u64::MAX, "position": 200}),+ json!({"page": 0, "gutter": -1, "position": 200}),+ json!({"page": 0, "gutter": 0.5, "position": 200}),+ json!({"page": 9, "gutter": 0, "position": 200}),+ json!({"page": u64::MAX, "gutter": 0, "position": 200}),+ json!({"gutter": 0, "position": 200}),+ json!({"spread": 99, "page": 0, "gutter": 0, "position": 200}),+ json!({"parent": "Z", "page": 0, "gutter": 0, "position": 200}),+ json!({"page": 0, "gutter": 0, "position": f64::MAX}),+ ] {+ let r = s.execute("layout.moveColumnGuide", &p);+ // A huge but finite position is clamped to the margin; everything else is refused.+ assert!(r.is_err() || p["position"] == json!(f64::MAX), "{p}: {r:?}");+ }+ }+ }++ #[cfg(test)]+ mod parent_base_tests {+ use serde_json::{Value, json};++ fn rect(s: &mut crate::Session, spread: Value, r: [f64; 4], swatch: &str) -> u64 {+ let id = s.execute("frame.create", &json!({"spread": spread, "rect": r, "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ s.execute("object.fill", &json!({"ids": [id], "swatch": swatch})).unwrap();+ id+ }++ fn page(s: &crate::Session, abs: usize) -> designcraft_render::Rendered {+ let mut rr = designcraft_render::Renderer::new();+ rr.threads = 0;+ rr.render_page(&s.doc().unwrap().doc, &s.cache, abs, 1.0, false, &Default::default()).unwrap()+ }++ /// Parent A (black), parent B based on A (cyan, half over A's square), and a page item (paper)+ /// over B's: the page draws A, then B, then its own items.+ #[test]+ fn based_on_parent_draws_base_items_under_parent_items() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"width": 400, "height": 400, "pages": 2, "facingPages": false, "margins": 0})).unwrap();+ s.execute("layout.parents.new", &json!({"prefix": "B", "name": "Opening"})).unwrap();+ rect(&mut s, json!({"kind": "parent", "index": 0}), [0.0, 0.0, 200.0, 200.0], "[Black]");+ rect(&mut s, json!({"kind": "parent", "index": 1}), [100.0, 0.0, 300.0, 200.0], "C=100 M=0 Y=0 K=0");+ rect(&mut s, json!(1), [150.0, 0.0, 190.0, 40.0], "[Paper]");+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "B"})).unwrap();+ let black = |p: [u8; 4]| p[0] < 80 && p[1] < 80 && p[2] < 80;+ let cyan = |p: [u8; 4]| p[0] < 80 && p[1] > 120 && p[2] > 180;+ let paper = |p: [u8; 4]| p[0] > 240 && p[1] > 240 && p[2] > 240;+ assert!(paper(page(&s, 1).pixel(50, 100)), "B alone does not show A's items");++ let r = s.execute("layout.parents.options", &json!({"parent": "B", "basedOn": "A"})).unwrap();+ assert_eq!(r, json!({"parent": "B-Opening", "basedOn": "A-Parent"}));+ let img = page(&s, 1);+ assert!(black(img.pixel(50, 100)), "A's item: {:?}", img.pixel(50, 100));+ assert!(cyan(img.pixel(150, 150)), "B's item over A's: {:?}", img.pixel(150, 150));+ assert!(paper(img.pixel(170, 20)), "the page's item over B's: {:?}", img.pixel(170, 20));+ assert!(black(page(&s, 0).pixel(50, 100)) && !cyan(page(&s, 0).pixel(250, 100)), "page 1 uses A only");+ // Parent B itself shows A's items under its own.+ let mut rr = designcraft_render::Renderer::new();+ rr.threads = 0;+ let placed = [designcraft_render::Placed { spread: designcraft_doc::SpreadRef::Parent(1), xf: designcraft_geom::Affine::IDENTITY }];+ let opts = designcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };+ let img = rr.render(&s.doc().unwrap().doc, &s.cache, &placed, (400, 400), designcraft_geom::Affine::IDENTITY, &opts);+ assert!(black(img.pixel(50, 100)) && cyan(img.pixel(150, 150)), "{:?} {:?}", img.pixel(50, 100), img.pixel(150, 150));+ let inspect = s.execute("document.inspect", &json!({})).unwrap();+ assert_eq!(inspect["parents"][1]["basedOn"], "A-Parent");+ assert_eq!(inspect["parents"][0]["basedOn"], Value::Null);++ // Cycles are refused.+ assert!(s.execute("layout.parents.options", &json!({"parent": "A", "basedOn": "B"})).is_err());+ assert!(s.execute("layout.parents.options", &json!({"parent": "B", "basedOn": "B-Opening"})).is_err());+ assert!(s.execute("layout.parents.options", &json!({"parent": "B", "basedOn": "Z"})).is_err());++ s.execute("edit.undo", &json!({})).unwrap();+ assert!(paper(page(&s, 1).pixel(50, 100)), "undo clears Based on Parent");+ s.execute("edit.redo", &json!({})).unwrap();+ s.execute("layout.parents.options", &json!({"parent": "B", "basedOn": null})).unwrap();+ assert_eq!(s.execute("document.inspect", &json!({})).unwrap()["parents"][1]["basedOn"], Value::Null);+ }++ /// A's page-number marker shown on parent XYZ (based on A) reads XYZ, as markers on XYZ's own items do.+ #[test]+ fn base_parent_markers_read_the_showing_parent() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 1, "facingPages": false})).unwrap();+ s.execute("layout.parents.new", &json!({"prefix": "XYZ"})).unwrap();+ s.execute("layout.parents.options", &json!({"parent": "XYZ", "basedOn": "A"})).unwrap();+ let marker = designcraft_doc::story::PAGE_NUMBER.to_string();+ let r = s+ .execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 30, 500, 60], "content": "text", "text": marker}))+ .unwrap();+ let d = s.doc().unwrap().doc.clone();+ let sid = d.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;+ let glyphs = |on| -> usize {+ let cs = s.cache.get_on(&d, sid, on);+ cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum()+ };+ assert_eq!(glyphs(designcraft_compose::ShownOn::Own), 1, "A");+ assert_eq!(glyphs(designcraft_compose::ShownOn::Parent(1)), 3, "XYZ");+ }++ /// A file whose parents are based on each other opens, with the cycle broken and reported.+ #[test]+ fn opening_a_parent_cycle_breaks_it_with_a_warning() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 1})).unwrap();+ s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap();+ let mut d = s.doc().unwrap().doc.as_ref().clone();+ let (a, b) = (d.parents[0].id, d.parents[1].id);+ std::sync::Arc::make_mut(&mut d.parents[0]).parent.as_mut().unwrap().based_on = Some(b);+ std::sync::Arc::make_mut(&mut d.parents[1]).parent.as_mut().unwrap().based_on = Some(a);+ let b64 = crate::cmd::base64_encode(&crate::cmd::to_bytes(&d).unwrap());+ let r = s.execute("file.openBytes", &json!({"name": "cycle", "base64": b64})).unwrap();+ assert!(r["warnings"].to_string().contains("cycle"), "{r}");+ let d = &s.doc().unwrap().doc;+ assert_eq!(d.parents[0].parent.as_ref().unwrap().based_on, None);+ assert_eq!(d.parents[1].parent.as_ref().unwrap().based_on, Some(a));+ }+ }diff --cc crates/engine/src/cmd/layout/registry.rsindex 000000000,c3cb69b71..85db79680mode 000000,100644..100644--- a/crates/engine/src/cmd/layout/registry.rs+++ b/crates/engine/src/cmd/layout/registry.rs@@@ -1,0 -1,760 +1,785 @@@+ use super::layers::set_layer;+ use super::margins::{adjust_layout, column_guides_unlocked, margin_boxes, move_column_guide, set_margins_columns, set_page_width};+ use super::pages::{document_setup, page_options, page_size};-use super::parents::{parent_options, parent_ref, parent_spread_index};++use super::parents::{parent_options, parent_page_size, parent_page_target, parent_ref, parent_spread_index};+ use super::sections::{ChapterEdit, SectionEdit, chapter_numbering, start_number};+ use super::{CommandSpec, LAYER_COLORS, Layer, LayerId, Margins, SpreadId, Value, bad, cmd, has_doc, json, ok, str_param};++ pub fn specs() -> Vec<CommandSpec> {+ vec![+ cmd!(+ "layout.pages.insert",+ "Insert Pages…",+ ["Layout", "Pages"],+ Some("Cmd+Shift+P"),+ "{count?: 1 (1 to 9999), after?: 0-based page index (default: the last page; past it: at the end), before?: 0-based page index (instead of `after`; 0: at the start), parent?: id|\"A-Parent\"|\"A\"|null}",+ has_doc,+ |s, p| {+ const ID: &str = "layout.pages.insert";+ // A count that is given but is not a number of pages used to insert one page:+ // `0`, `-1` and `1.5` all came out as 1, and 10000 was quietly capped.+ let count = match p.get("count").filter(|v| !v.is_null()) {+ None => 1,+ Some(v) => match v.as_u64().filter(|n| (1..=9999).contains(n)).map(|n| n as usize) {+ Some(n) => n,+ None => return Err(bad(ID, format!("count {v}: 1 to 9999 pages"))),+ },+ };+ let st = s.doc()?;+ let n = st.doc.page_count();+ // A placement given (null included) must be a page index; only when neither is+ // given do the pages go after the last.+ if p.get("after").is_some() && p.get("before").is_some() {+ return Err(bad("layout.pages.insert", "give `after` or `before`, not both"));+ }+ // `before` names a page of the document; an `after` past the last page appends+ // (`insert_pages_bounds.rs` pins that).+ let index = |k: &str| match p.get(k) {+ None => Ok(None),+ Some(v) => v+ .as_u64()+ .map(|v| usize::try_from(v).unwrap_or(usize::MAX))+ .filter(|&i| k == "after" || i < n)+ .map(|i| Some(i.min(n.saturating_sub(1))))+ .ok_or_else(|| bad(ID, format!("`{k}` must be the index of one of the {n} pages, not {v}"))),+ };+ // The page the new ones follow; none: they go first.+ let after = match (index("after")?, index("before")?) {+ (_, Some(b)) => b.checked_sub(1),+ (a, None) => Some(a.unwrap_or(n.saturating_sub(1))),+ };+ let parent = parent_ref(ID, &st.doc, p.get("parent"))?.unwrap_or_else(|| st.doc.parents.first().map(|x| x.id));+ s.edit(|d, _| {+ let ids = d.insert_pages(after, count, parent)?;+ Ok(json!({"pages": ids.len(), "total": d.page_count()}))+ })+ }+ ),+ cmd!(+ "layout.rotateSpreadView",+ "Rotate Spread",+ [],+ None,+ "{spread?: index (0), angle: 90 (clockwise) | -90 | 180 | 0 (clear)} — turn one spread on screen (output is unaffected)",+ has_doc,+ |s, p| {+ let si = p.get("spread").and_then(Value::as_u64).unwrap_or(0) as usize;+ let angle = match p.get("angle") {+ None => 90,+ Some(v) => v.as_i64().ok_or_else(|| bad("layout.rotateSpreadView", "angle must be an integer multiple of 90 degrees"))?,+ };+ if angle % 90 != 0 {+ return Err(bad("layout.rotateSpreadView", "angle must be an integer multiple of 90 degrees"));+ }+ s.edit(|d, _| {+ let sp = d.spreads.get_mut(si).ok_or_else(|| bad("layout.rotateSpreadView", "no such spread"))?;+ let pg = std::sync::Arc::make_mut(sp).pages.first_mut().ok_or_else(|| bad("layout.rotateSpreadView", "empty spread"))?;+ pg.view_rotation = if angle == 0 { 0 } else { ((pg.view_rotation as i64 + angle.div_euclid(90)).rem_euclid(4)) as u8 };+ Ok(json!({"rotation": pg.view_rotation as u32 * 90}))+ })+ }+ ),+ cmd!("layout.pages.delete", "Delete Pages", ["Layout", "Pages"], None, "{pages: [index]}", has_doc, |s, p| {+ let pages: Vec<usize> = p+ .get("pages")+ .and_then(Value::as_array)+ .map(|a| a.iter().filter_map(Value::as_u64).map(|v| v as usize).collect())+ .unwrap_or_default();+ s.edit(|d, sel| {+ d.delete_pages(&pages)?;+ sel.items.retain(|i| d.item(*i).is_some());+ sel.text = sel.text.filter(|t| d.story(t.story).is_some());+ ok()+ })+ }),+ cmd!("layout.pages.move", "Move Pages…", ["Layout", "Pages"], None, "{from, to}", has_doc, |s, p| {+ let from = p.get("from").and_then(Value::as_u64).ok_or_else(|| bad("layout.pages.move", "missing from"))? as usize;+ let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad("layout.pages.move", "missing to"))? as usize;+ s.edit(|d, _| {+ d.move_page(from, to)?;+ ok()+ })+ }),+ cmd!(+ "layout.pages.duplicateSpread",+ "Duplicate Spread",+ ["Layout", "Pages"],+ None,+ "{spread, atEnd?: bool (Duplicate Spread at End of Document; the Pages panel's New Page button takes a dropped page there), to?: page index the copied pages move to in the same undo step (the Pages panel's Alt-drag)} → {page: the copy's first page (0-based)} — the spread's pages (size, margins, columns, guides, liquid rule) and items",+ has_doc,+ |s, p| {+ let si = p.get("spread").and_then(Value::as_u64).unwrap_or(0) as usize;+ let at_end = p.get("atEnd").and_then(Value::as_bool).unwrap_or(false);+ let to = p.get("to").and_then(Value::as_u64).map(|t| t as usize);+ s.edit(|d, _| {+ let sp = d.spreads.get(si).cloned().ok_or_else(|| bad("layout.pages.duplicateSpread", "no such spread"))?;+ // The copies land at `to`..`to + n` of the document with them in it.+ if to.is_some_and(|t| t > d.page_count()) {+ return Err(bad("layout.pages.duplicateSpread", "no such page"));+ }+ let after = if at_end { d.page_count() - 1 } else { d.first_page_of_spread(si) + sp.pages.len() - 1 };+ let parent = sp.pages.first().and_then(|p| p.parent);+ d.insert_pages(Some(after), sp.pages.len(), parent)?;+ // The copies are the pages they copy: size, margins, columns, guides, liquid rule.+ for (k, src) in sp.pages.iter().enumerate() {+ let Some((nsi, npi)) = d.page_loc(after + 1 + k) else { continue };+ let nsp = std::sync::Arc::make_mut(&mut d.spreads[nsi]);+ let pg = &mut nsp.pages[npi];+ let dx = pg.x - src.x;+ // A copy on the other side of the spine has its dragged columns mirrored.+ let columns = pg.columns_from(src);+ (pg.width, pg.height, pg.margins, pg.columns, pg.liquid) = (src.width, src.height, src.margins, columns, src.liquid);+ pg.guides = src.guides.clone();+ for g in pg.guides.iter_mut().filter(|g| g.orientation == designcraft_doc::Orientation::Vertical) {+ g.position += dx;+ }+ nsp.relayout();+ }+ // Copy items onto the new spread(s) at the same positions.+ let src = d.clone();+ let ids: Vec<_> = sp.items.iter().map(|i| i.id).collect();+ let (nsi, _) = d.page_loc(after + 1).ok_or_else(|| bad("layout.pages.duplicateSpread", "insert failed"))?;+ crate::cmd::object::duplicate_from(d, &src, &ids, designcraft_doc::SpreadRef::Doc(nsi), designcraft_geom::Vec2::ZERO)?;+ let first = after + 1;+ let Some(to) = to else { return Ok(json!({"page": first})) };+ // Moving a page shifts the ones between; order the moves so each copy keeps+ // its place among the others.+ let n = sp.pages.len();+ if first < to {+ for k in (0..n).rev() {+ d.move_page(first + k, to + k)?;+ }+ } else {+ for k in 0..n {+ d.move_page(first + k, to + k)?;+ }+ }+ Ok(json!({"page": to}))+ })+ }+ ),+ cmd!(+ "layout.pages.applyParent",+ "Apply Parent to Pages…",+ ["Layout", "Pages"],+ None,+ "{pages: [index], parent: id|\"A-Parent\"|\"A\"|null (null or \"[None]\" clears)}",+ has_doc,+ |s, p| {+ let pages: Vec<usize> = p+ .get("pages")+ .and_then(Value::as_array)+ .map(|a| a.iter().filter_map(Value::as_u64).map(|v| v as usize).collect())+ .unwrap_or_default();+ let parent = parent_ref("layout.pages.applyParent", &s.doc()?.doc, p.get("parent"))?.unwrap_or(None);+ s.edit(|d, _| {+ d.apply_parent(&pages, parent)?;+ ok()+ })+ }+ ),+ cmd!("layout.parents.new", "New Parent…", ["Layout", "Pages"], None, "{prefix?, name?: \"Parent\"}", has_doc, |s, p| {+ let name = str_param(p, "name").unwrap_or("Parent").to_string();+ s.edit(|d, _| {+ let prefix = str_param(p, "prefix").map(str::to_string).unwrap_or_else(|| d.next_parent_prefix());+ let src = d.page(0).cloned();+ let (columns, margins) =+ src.as_ref().map_or_else(|| (designcraft_doc::Columns::default(), Margins::uniform(36.0)), |p| (p.columns.clone(), p.margins));+ let id = d.add_parent(&prefix, &name, columns.count, columns.gutter, margins);+ // Dragged column guides carry over to the parent pages they still fit, mirrored+ // on the parent page across the spine from the first page.+ if let (Some(src), Some(sp)) = (&src, d.parents.iter_mut().find(|x| x.id == id)) {+ for pg in &mut std::sync::Arc::make_mut(sp).pages {+ let columns = pg.columns_from(src);+ if columns.valid_positions(pg.margin_rect().width()).is_some() {+ pg.columns.positions = columns.positions;+ }+ }+ }+ Ok(json!({"id": id.0, "prefix": prefix}))+ })+ }),+ cmd!(+ "layout.parents.delete",+ "Delete Parent",+ [],+ None,+ "{id: parent spread id} — unapply the parent and keep local overrides as ordinary items",+ has_doc,+ |s, p| {+ let id = p.get("id").and_then(Value::as_u64).map(SpreadId).ok_or_else(|| bad("layout.parents.delete", "missing parent id"))?;+ s.edit(|d, sel| {+ d.delete_parent(id)?;+ *sel = Default::default();+ ok()+ })?;+ let st = s.doc_mut()?;+ if st.doc.parents.is_empty() {+ st.editing_parents = false;+ }+ ok()+ }+ ),+ cmd!(+ noundo "layout.parents.edit",+ "Edit Parents",+ [],+ None,+ "{on?: bool, parent?: id|\"A-Parent\"|\"A\"} — show parent spreads on the canvas; `parent` shows that parent (and implies on). Turning on without `parent` shows the first parent",+ has_doc,+ |s, p| {+ const ID: &str = "layout.parents.edit";+ let doc = s.doc()?.doc.clone();+ let parent = match p.get("parent") {+ None | Some(Value::Null) => None,+ v => match parent_ref(ID, &doc, v)? {+ Some(Some(id)) => Some(id),+ _ => return Err(bad(ID, "`parent` names a parent to show")),+ },+ };+ let st = s.doc_mut()?;+ let was = st.editing_parents;+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(parent.is_some() || !was);+ st.editing_parents = on;+ st.selection = Default::default();+ st.bump_revision();+ // The parent to show: the one asked for, or the first when editing starts.+ let index = match parent {+ Some(id) => doc.parent_index(id),+ None if !was && !doc.parents.is_empty() => Some(0),+ None => None,+ };+ let shown = index.filter(|_| on);+ if let Some(i) = shown {+ s.ui_requests.push(crate::UiRequest::View { params: json!({"showSpread": designcraft_doc::SpreadRef::Parent(i)}) });+ }+ Ok(json!({"on": on, "parent": shown.and_then(|i| doc.parents.get(i)).map(|x| x.id.0)}))+ }+ ),+ cmd!(+ "layout.parents.options",+ "Parent Options…",+ [],+ None,+ "{parent: id|\"B-Parent\"|\"B\", basedOn: id|\"A-Parent\"|\"A\"|null (= [None])} — the parent shows its base's items under its own, and so do the pages that use it → {parent, basedOn}",+ has_doc,+ parent_options+ ),+ cmd!(+ "layout.marginsAndColumns",+ "Margins and Columns…",+ ["Layout"],+ None,+ "{pages?: [index] (default all), margins?: number|{top,bottom,inside,outside}, columns?, gutter?, adjustLayout?: bool (objects follow the margins), parent? (a parent's prefix, label or index)} — document pages take these as their own margins; with `parent` the parent's pages change instead (`pages` then indexes them), and so do the document pages without their own",+ has_doc,+ |s, p| {+ let pages: Option<Vec<usize>> =+ p.get("pages").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(|v| v as usize).collect());+ let parent = match p.get("parent") {+ None | Some(Value::Null) => None,+ Some(v) => Some(parent_spread_index(&s.doc()?.doc, v).ok_or_else(|| bad("layout.marginsAndColumns", "no such parent"))?),+ };+ let p = p.clone();+ let adjust = p.get("adjustLayout").and_then(Value::as_bool).unwrap_or(false);+ s.edit(|d, _| {+ let before = adjust.then(|| margin_boxes(d));+ if let Some(pi) = parent {+ let n = d.parents.get(pi).map_or(0, |sp| sp.pages.len());+ let sp = d.parents.get_mut(pi).map(std::sync::Arc::make_mut);+ if let Some(sp) = sp {+ for qi in pages.clone().unwrap_or_else(|| (0..n).collect()) {+ if let Some(pg) = sp.pages.get_mut(qi) {+ set_margins_columns(pg, &p);+ }+ }+ }+ d.sync_parent_margins();+ } else {+ let all: Vec<usize> = pages.clone().unwrap_or_else(|| (0..d.page_count()).collect());+ for abs in all {+ let Some((si, pi)) = d.page_loc(abs) else { continue };+ let Some(pg) = d.spreads.get_mut(si).map(std::sync::Arc::make_mut).and_then(|sp| sp.pages.get_mut(pi)) else { continue };+ set_margins_columns(pg, &p);+ pg.local_margins = true;+ }+ }+ if let Some(b) = before {+ adjust_layout(d, &b);+ }+ ok()+ })+ }+ ),+ cmd!(+ "layout.moveColumnGuide",+ "Move Column Guide",+ [],+ None,+ "{spread?, parent? (a parent's prefix, label or index: its spread instead of `spread`), page (index in the spread), gutter (0 = between the first two columns), position (the gutter's new left edge, spread x)} → {positions (each column's left and right edge from the margin box's left edge), left (where the gutter's left edge went, spread x)} — both guides of the gutter move, keeping its width, and stop at the neighbouring guides and the margins; a document page takes the result as its own columns, a parent page passes it to the pages that follow it; refused while column guides are locked",+ column_guides_unlocked,+ move_column_guide+ ),+ cmd!(+ "layout.documentSetup",+ "Document Setup…",+ ["File"],+ Some("Cmd+Alt+P"),+ "{width?, height?, pages?: count, startPage?: n, facingPages?, binding?: leftToRight|rightToLeft, intent?: print|web|mobile, margins?: n | {top, bottom, inside, outside} (every page and parent page), bleed?, slug?: n | [top, bottom, inside, outside], adjustLayout?: bool (objects follow the new page size and margins)} → the document setup (margins: the first page's)",+ has_doc,+ |s, p| {+ let p = p.clone();+ if p.as_object().is_none_or(|o| o.is_empty()) {+ return Ok(document_setup(&s.doc()?.doc));+ }+ let edges = |k: &str| -> Option<[f64; 4]> {+ match p.get(k)? {+ Value::Array(a) if a.len() == 4 => {+ let v: Vec<f64> = a.iter().filter_map(Value::as_f64).map(|v| v.max(0.0)).collect();+ (v.len() == 4).then(|| [v[0], v[1], v[2], v[3]])+ }+ v => v.as_f64().map(|b| [b.max(0.0); 4]),+ }+ };+ let (bleed, slug) = (edges("bleed"), edges("slug"));+ for k in ["width", "height"] {+ if let Some(v) = p.get(k)+ && !v.as_f64().is_some_and(|x| x > 0.0 && x <= 15552.0)+ {+ return Err(bad("layout.documentSetup", format!("{k}: page size out of range (0 < size ≤ 216 in)")));+ }+ }+ let margins: Option<Margins> = match p.get("margins") {+ None => None,+ Some(Value::Number(n)) => n.as_f64().map(Margins::uniform),+ Some(v) => serde_json::from_value(v.clone()).ok(),+ };+ if margins.is_some_and(|m| ![m.top, m.bottom, m.inside, m.outside].iter().all(|v| v.is_finite() && (0.0..=15552.0).contains(v))) {+ return Err(bad("layout.documentSetup", "margins: 0 to 216 in"));+ }+ if p.get("margins").is_some() && margins.is_none() {+ return Err(bad("layout.documentSetup", "margins: a number or {top, bottom, inside, outside}"));+ }+ let intent: Option<designcraft_doc::Intent> = p.get("intent").and_then(|v| serde_json::from_value(v.clone()).ok());+ let pages = p.get("pages").and_then(Value::as_u64).map(|n| n.clamp(1, 9999) as usize);+ let adjust = p.get("adjustLayout").and_then(Value::as_bool).unwrap_or(false);+ s.edit(|d, _| {+ let before = adjust.then(|| margin_boxes(d));+ if let Some(f) = p.get("facingPages").and_then(Value::as_bool) {+ d.settings.facing_pages = f;+ }+ if let Some(b) = p.get("binding").and_then(Value::as_str) {+ d.settings.right_to_left_binding = b == "rightToLeft";+ d.order_parent_pages();+ }+ if let Some(b) = bleed {+ d.settings.bleed = b;+ }+ if let Some(b) = slug {+ d.settings.slug = b;+ }+ if let Some(i) = intent {+ d.settings.intent = i;+ }+ if let Some(n) = p.get("startPage").map(|v| start_number("layout.documentSetup", "startPage", v)).transpose()? {+ if !d.sections.iter().any(|x| x.start == 0) {+ d.sections.insert(+ 0,+ designcraft_doc::Section {+ start: 0,+ start_number: None,+ style: Default::default(),+ prefix: String::new(),+ marker: String::new(),+ include_prefix: false,+ },+ );+ }+ if let Some(first) = d.sections.iter_mut().find(|x| x.start == 0) {+ first.start_number = Some(n);+ }+ }+ // Number of Pages: add at the end (with the last page's parent) or remove from the end.+ if let Some(n) = pages {+ let have = d.page_count();+ if n > have {+ let parent = d.page_loc(have - 1).and_then(|(si, pi)| d.spreads[si].pages[pi].parent);+ d.insert_pages(Some(have - 1), n - have, parent)?;+ } else if n < have {+ d.delete_pages(&(n..have).collect::<Vec<_>>())?;+ }+ }+ let w = p.get("width").and_then(Value::as_f64);+ let h = p.get("height").and_then(Value::as_f64);+ // Pages with a liquid rule re-flow their objects (Adjust Layout aside).+ let liquid_before: Vec<(usize, usize, designcraft_geom::Rect)> = if adjust {+ vec![]+ } else {+ d.spreads+ .iter()+ .enumerate()+ .flat_map(|(si, sp)| {+ sp.pages.iter().enumerate().filter(|(_, pg)| !pg.liquid.is_off()).map(move |(pi, pg)| (si, pi, pg.bounds()))+ })+ .collect()+ };+ if w.is_some() || h.is_some() {+ d.settings.page_width = w.unwrap_or(d.settings.page_width);+ d.settings.page_height = h.unwrap_or(d.settings.page_height);+ for sp in d.spreads.iter_mut().chain(d.parents.iter_mut()) {+ let sp = std::sync::Arc::make_mut(sp);+ for pg in &mut sp.pages {+ set_page_width(pg, d.settings.page_width);+ pg.height = d.settings.page_height;+ }+ sp.relayout();+ }+ }+ if let Some(m) = margins {+ for sp in d.spreads.iter_mut().chain(d.parents.iter_mut()) {+ for pg in &mut std::sync::Arc::make_mut(sp).pages {+ pg.margins = m;+ }+ }+ // Pages that now match their parent page follow its later changes; local+ // columns stay local.+ d.unmark_matching_local_margins();+ d.sync_parent_margins();+ }+ d.repaginate();+ if let Some(b) = before {+ adjust_layout(d, &b);+ }+ for (si, pi, old) in liquid_before {+ crate::cmd::liquid::apply(d, designcraft_doc::SpreadRef::Doc(si), pi, old);+ }+ Ok(document_setup(d))+ })+ }+ ),+ cmd!(+ "layout.pages.toSpread",+ "Add Page to Spread",+ ["Layout", "Pages"],+ None,+ "{page (1-based), spread (0-based)} — the page joins that spread (up to 10 pages; the spread stops shuffling)",+ has_doc,+ |s, p| {+ let page =+ p.get("page").and_then(Value::as_u64).filter(|n| *n >= 1).ok_or_else(|| bad("layout.pages.toSpread", "missing page"))? as usize;+ let spread = p.get("spread").and_then(Value::as_u64).ok_or_else(|| bad("layout.pages.toSpread", "missing spread"))? as usize;+ s.edit(|d, _| {+ d.page_to_spread(page - 1, spread)?;+ Ok(json!({"spreads": d.spreads.len()}))+ })+ }+ ),+ cmd!(+ "layout.spreadShuffle",+ "Allow Selected Spread to Shuffle",+ ["Layout", "Pages"],+ None,+ "{spread (0-based), allow: bool} — off keeps the spread's pages together when pages are added or removed",+ has_doc,+ |s, p| {+ let si = p.get("spread").and_then(Value::as_u64).unwrap_or(0) as usize;+ let allow = p.get("allow").and_then(Value::as_bool).unwrap_or(true);+ s.edit(|d, _| {+ let sp = d.spreads.get_mut(si).ok_or_else(|| bad("layout.spreadShuffle", "no such spread"))?;+ std::sync::Arc::make_mut(sp).allow_shuffle = allow;+ if allow {+ d.repaginate();+ }+ ok()+ })+ }+ ),+ cmd!(+ "layout.pageSize",+ "Page Size",+ [],+ None,+ "{pages: [1-based page numbers], width?, height?, preset?: \"A4\"|\"Letter\"|…, anchor?: 0–8 (reference point that stays put, row-major from the top-left; default 0)} — pages of their own size (Page tool); objects keep their place relative to the anchor, or follow the page's liquid rule",+ has_doc,+ page_size+ ),++ cmd!(++ "layout.parentPageSize",++ "Parent Page Size",++ [],++ None,++ "{parent: spread id, page: 0-based parent page index, width?, height?, anchor?: 0–8} — resize only this parent page, keeping document page sizes independent",++ has_doc,++ parent_page_size++ ),++ cmd!(++ noundo "layout.selectParentPage", "Select Parent Page", [], None,++ "{parent: spread id|null, page?: 0-based parent page index} — select a parent page with the Page tool; null clears the selection",++ has_doc, |s, p| {++ let target = match p.get("parent") {++ Some(Value::Null) => None,++ _ => Some(parent_page_target(&s.doc()?.doc, p, "layout.selectParentPage")?),++ };++ let st = s.doc_mut()?;++ st.selection = Default::default();++ st.selection.parent_page = target.map(|(si, pi)| (st.doc.parents[si].id, pi));++ st.bump_revision();++ ok()++ }++ ),+ cmd!(+ "layout.pageOptions",+ "Page Options",+ [],+ None,+ "{pages: [1-based], showParentOverlay?: bool} — Page tool options (Show Parent Page Overlay: the parent page's size drawn over the page)",+ has_doc,+ page_options+ ),+ cmd!(+ noundo "layout.selectPage",+ "Select Page",+ [],+ None,+ "{page: 1-based | null, ids?: [item ids] (objects selected with it: the Page tool on an object-based page)} — the page the Page tool selects (its handles, the Control panel)",+ has_doc,+ |s, p| {+ let n = s.doc()?.doc.page_count();+ let page = match p.get("page") {+ None | Some(Value::Null) => None,+ Some(v) => Some(v.as_u64().filter(|v| *v >= 1 && *v as usize <= n).ok_or_else(|| bad("layout.selectPage", format!("`page`: 1–{n}")))? as usize - 1),+ };+ let ids: Vec<designcraft_doc::ItemId> = {+ let d = &s.doc()?.doc;+ p.get("ids")+ .and_then(Value::as_array)+ .map(|a| a.iter().filter_map(Value::as_u64).map(designcraft_doc::ItemId).filter(|id| d.item(*id).is_some()).collect())+ .unwrap_or_default()+ };+ let st = s.doc_mut()?;+ if page.is_some() {+ st.selection = designcraft_doc::Selection::items(ids);+ }+ st.selection.page = page;++ st.selection.parent_page = None;+ st.bump_revision();+ Ok(json!({"page": page.map(|p| p + 1)}))+ }+ ),+ cmd!(+ "layout.section",+ "Numbering & Section Options…",+ ["Layout"],+ None,+ "{page (1-based; starts a section there), startNumber?: n (1–99999)|null (continue), style?: arabic|upperRoman|lowerRoman|upperLetters|lowerLetters|arabicLeadingZero|arabicThreeDigits|arabicFourDigits|kanji, prefix? (up to 8 characters; no + or comma), includePrefix?, marker?, remove?: bool}",+ has_doc,+ |s, p| {+ let edit = SectionEdit::parse("layout.section", s, p)?;+ s.edit(|d, _| {+ edit.apply(d);+ Ok(json!({"names": (0..d.page_count()).map(|i| d.page_name(i)).collect::<Vec<_>>()}))+ })+ }+ ),+ cmd!(+ "layout.chapterNumbering",+ "Document Chapter Numbering",+ [],+ None,+ "{style?: arabic|upperRoman|lowerRoman|upperLetters|lowerLetters|arabicLeadingZero|arabicThreeDigits|arabicFourDigits, start?: n (Start Chapter Numbering at), source?: automatic|userDefined|sameAsPrevious} → {chapterNumber, label, style, source, book: the open book holding the document, or null}; no parameters reports the setting",+ has_doc,+ |s, p| {+ if p.as_object().is_none_or(|o| o.is_empty()) {+ return chapter_numbering(s);+ }+ let edit = ChapterEdit::parse("layout.chapterNumbering", p)?;+ s.edit(|d, _| {+ edit.apply(d);+ ok()+ })?;+ chapter_numbering(s)+ }+ ),+ cmd!(+ "layout.numberingOptions",+ "Apply Numbering & Section Options",+ [],+ None,+ "{page, …the settings as layout.section, chapter?: {…the settings as layout.chapterNumbering}} — the section and the document's chapter numbering in one undo step; if either is refused nothing changes",+ has_doc,+ |s, p| {+ let section = SectionEdit::parse("layout.numberingOptions", s, p)?;+ let chapter = match p.get("chapter") {+ Some(c) => Some(ChapterEdit::parse("layout.numberingOptions", c)?),+ None => None,+ };+ s.edit(|d, _| {+ section.apply(d);+ if let Some(chapter) = &chapter {+ chapter.apply(d);+ }+ Ok(json!({"names": (0..d.page_count()).map(|i| d.page_name(i)).collect::<Vec<_>>(), "chapter": d.chapter_label()}))+ })+ }+ ),+ cmd!("layer.move", "Move Layer", [], None, "{id, to: index (0 = top/frontmost)}", has_doc, |s, p| {+ let id = LayerId(p.get("id").and_then(Value::as_u64).ok_or_else(|| bad("layer.move", "missing id"))?);+ let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad("layer.move", "missing to"))?;+ s.edit(|d, _| {+ let i = d.layers.iter().position(|l| l.id == id).ok_or_else(|| bad("layer.move", "no such layer"))?;+ let to = usize::try_from(to).ok().filter(|t| *t < d.layers.len()).ok_or_else(|| bad("layer.move", "to out of range"))?;+ let l = d.layers.remove(i);+ d.layers.insert(to, l);+ ok()+ })+ }),+ cmd!(noundo "layer.selectItems", "Select All on Layer", [], None, "{id}", has_doc, |s, p| {+ let id = LayerId(p.get("id").and_then(Value::as_u64).unwrap_or(0));+ let st = s.doc_mut()?;+ let ids: Vec<_> = st.doc.spreads.iter().flat_map(|sp| sp.items.iter().filter(|i| i.layer == id && !i.locked).map(|i| i.id)).collect();+ st.selection = designcraft_doc::Selection::items(ids);+ st.bump_revision();+ ok()+ }),+ cmd!("layer.new", "New Layer…", [], None, "{name?}", has_doc, |s, p| {+ let name = str_param(p, "name").map(str::to_string);+ let r = s.edit(|d, _| {+ let id = LayerId(d.alloc());+ let n = d.layers.len();+ let name = name.clone().unwrap_or_else(|| format!("Layer {}", n + 1));+ d.layers.insert(+ 0,+ Layer {+ id,+ name,+ color: LAYER_COLORS[n % LAYER_COLORS.len()].1,+ visible: true,+ locked: false,+ printable: true,+ show_guides: true,+ suppress_wrap_when_hidden: false,+ },+ );+ Ok(id)+ })?;+ s.doc_mut()?.active_layer = r;+ Ok(json!({"id": r.0}))+ }),+ cmd!(+ "layer.set",+ "Layer Options…",+ [],+ None,+ "{id, name?, color?: [r,g,b] | layer colour name (\"Light Blue\", \"Red\", …), visible?, locked?, printable?, showGuides?, suppressWrapWhenHidden?} — names are unique and not empty",+ has_doc,+ set_layer+ ),+ cmd!("layer.delete", "Delete Layer", [], None, "{id}", has_doc, |s, p| {+ let id = LayerId(p.get("id").and_then(Value::as_u64).unwrap_or(0));+ s.edit(|d, sel| {+ if d.layers.len() < 2 {+ return Err(bad("layer.delete", "a document needs at least one layer"));+ }+ let doomed: Vec<_> =+ d.spreads.iter().chain(d.parents.iter()).flat_map(|sp| sp.items.iter().filter(|i| i.layer == id).map(|i| i.id)).collect();+ for i in doomed {+ let _ = d.remove_item(i);+ }+ d.layers.retain(|l| l.id != id);+ *sel = Default::default();+ ok()+ })+ }),+ cmd!(+ "layer.merge",+ "Merge Layers",+ [],+ None,+ "{ids: [layer ids], into?: layer id (default: the first)} — their objects move to `into`, the other layers are deleted",+ has_doc,+ |s, p| {+ let ids: Vec<LayerId> =+ p.get("ids").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(LayerId).collect()).unwrap_or_default();+ let into = p+ .get("into")+ .and_then(Value::as_u64)+ .map(LayerId)+ .or_else(|| ids.first().copied())+ .ok_or_else(|| bad("layer.merge", "no layers"))?;+ s.edit(|d, _| {+ if d.layer(into).is_none() || ids.iter().any(|l| d.layer(*l).is_none()) {+ return Err(bad("layer.merge", "no such layer"));+ }+ let gone: Vec<LayerId> = ids.iter().copied().filter(|l| *l != into).collect();+ for sp in d.spreads.iter_mut().chain(d.parents.iter_mut()) {+ if !sp.items.iter().any(|i| gone.contains(&i.layer)) {+ continue;+ }+ for it in &mut std::sync::Arc::make_mut(sp).items {+ if gone.contains(&it.layer) {+ std::sync::Arc::make_mut(it).layer = into;+ }+ }+ }+ d.layers.retain(|l| !gone.contains(&l.id));+ Ok(json!({"merged": gone.len()}))+ })+ }+ ),+ cmd!("layer.deleteUnused", "Delete Unused Layers", [], None, "{} — layers without objects (one layer always stays)", has_doc, |s, _| {+ s.edit(|d, _| {+ let used: std::collections::HashSet<LayerId> =+ d.spreads.iter().chain(d.parents.iter()).flat_map(|sp| sp.items.iter().map(|i| i.layer)).collect();+ let before = d.layers.len();+ if used.is_empty() {+ // Nothing anywhere: keep the first layer.+ d.layers.truncate(1);+ } else {+ d.layers.retain(|l| used.contains(&l.id));+ }+ Ok(json!({"deleted": before - d.layers.len()}))+ })+ }),+ cmd!(+ "layer.others",+ "Hide/Lock Others",+ [],+ None,+ "{id, hide?: bool, lock?: bool, show?: true (Show All Layers), unlock?: true (Unlock All Layers)} — Hide Others / Lock Others act on every layer but `id`",+ has_doc,+ |s, p| {+ let id = LayerId(p.get("id").and_then(Value::as_u64).unwrap_or(0));+ let f = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(false);+ let (hide, lock, show, unlock) = (f("hide"), f("lock"), f("show"), f("unlock"));+ s.edit(|d, _| {+ for l in &mut d.layers {+ if show {+ l.visible = true;+ }+ if unlock {+ l.locked = false;+ }+ if l.id != id {+ if hide {+ l.visible = false;+ }+ if lock {+ l.locked = true;+ }+ }+ }+ ok()+ })+ }+ ),+ cmd!(noundo "layer.activate", "Set Active Layer", [], None, "{id}", has_doc, |s, p| {+ let id = LayerId(p.get("id").and_then(Value::as_u64).unwrap_or(0));+ let st = s.doc_mut()?;+ if st.doc.layer(id).is_none() {+ return Err(bad("layer.activate", "no such layer"));+ }+ st.active_layer = id;+ st.bump_revision();+ ok()+ }),+ ]+ }diff --cc crates/engine/src/tests.rsindex 3e1773853,3590b2814..c06586c21--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@@ -1650,60 -1719,342 +1719,398 @@@ fn a_line_fits_when_its_baseline_does(// descent (about 25 pt more) doesn't.assert!(!overset(&mut s, 78.5), "the line is set; its descenders hang below the frame");assert!(overset(&mut s, 50.0), "a baseline below the frame still oversets the line");+}++#[test]+fn parent_resize_tool_previews_cancels_commits_and_undoes_on_the_selected_spread() {+ use designcraft_tools::{Mods, Overlay, PointerEvent, PointerKind};+ let mut s = Session::new();+ s.execute("file.new", &json!({"width":400,"height":600,"pages":3,"facingPages":true})).unwrap();+ s.execute("layout.parents.new", &json!({"prefix":"B"})).unwrap();+ s.execute("layout.parents.edit", &json!({"on":true})).unwrap();+ s.set_tool("page");+ let v = ViewInfo::at_zoom(1.0);+ let before = s.doc().unwrap().doc.clone();+ for si in 0..2 {+ for pi in 0..2 {+ let sr = designcraft_doc::SpreadRef::Parent(si);+ let rect = |s: &Session| s.layout().spread_page_rect(&s.doc().unwrap().doc, sr, pi).unwrap();+ let c = rect(&s).center();+ s.pointer(&PointerEvent::new(PointerKind::Down, c.x, c.y), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, c.x, c.y), v).unwrap();+ assert_eq!(s.doc().unwrap().selection.parent_page, Some((before.parents[si].id, pi)));+ assert_eq!(s.doc().unwrap().selection.page, None);+ assert!(s.overlays(v).iter().any(|o| matches!(o,Overlay::PageHandles(r) if *r==rect(&s))));+ for alt in [false, true] {+ let original = s.doc().unwrap().doc.clone();+ let undo = s.doc().unwrap().history.undo.len();+ let r = rect(&s);+ let p = designcraft_geom::Point::new(r.x1, r.center().y);+ let ev = |kind, x| PointerEvent::new(kind, x, p.y).with_mods(Mods { alt, ..Default::default() });+ s.pointer(&ev(PointerKind::Down, p.x), v).unwrap();+ s.pointer(&ev(PointerKind::Drag, p.x + 80.0), v).unwrap();+ assert_eq!(s.doc().unwrap().doc.parents[si].pages[pi].width, 480.0);+ assert_eq!(s.doc().unwrap().doc.spreads, before.spreads);+ assert_eq!(s.doc().unwrap().doc.parents[1 - si], before.parents[1 - si]);+ s.pointer(&ev(PointerKind::Up, p.x + 80.0), v).unwrap();+ if alt {+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);+ assert_eq!(s.doc().unwrap().doc.parents[si].pages[pi].width, 480.0);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.parents, original.parents);+ s.execute("edit.redo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.parents[si].pages[pi].width, 480.0);+ s.execute("edit.undo", &json!({})).unwrap();+ } else {+ assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &original));+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);+ }+ }+ let c = rect(&s).center();+ s.pointer(&PointerEvent::new(PointerKind::DoubleClick, c.x, c.y), v).unwrap();+ let req = std::mem::take(&mut s.ui_requests);+ assert!(+ matches!(req.last(),Some(crate::UiRequest::Dialog{id,params}) if id=="cmd:layout.parentPageSize" && params["parent"]==before.parents[si].id.0 && params["page"]==pi)+ );+ s.doc().unwrap().doc.check().unwrap();+ }+ }}++ /// Reset To Base with a new Based On: a partial rule edit resolves over the new parent, not the+ /// old one.+ #[test]+ fn reset_to_base_with_a_new_parent_resolves_rule_edits_over_it() {+ let mut s = session();+ let rule = |weight: f64, offset: f64| json!({"on": true, "weight": weight, "color": "[Black]", "offset": offset});+ s.execute("style.paragraph.create", &json!({"name": "Old", "para": {"ruleBelow": rule(3.0, 1.0)}})).unwrap();+ s.execute("style.paragraph.create", &json!({"name": "New", "para": {"ruleBelow": rule(1.0, 9.0)}})).unwrap();+ s.execute("style.paragraph.create", &json!({"name": "Child", "basedOn": "Old"})).unwrap();+ s.execute("style.paragraph.edit", &json!({"name": "Child", "resetToBase": true, "basedOn": "New", "para": {"ruleBelow": {"weight": 2}}}))+ .unwrap();+ let r = s.doc().unwrap().doc.styles.resolve_para_style("Child").0.rule_below;+ assert_eq!((r.weight, r.offset), (2.0, 9.0), "the offset is the new parent's");+ }++ /// Paragraph style references are checked: a Based On or Next Style that names no style, or+ /// that isn't a name or null, is refused and changes nothing.+ #[test]+ fn paragraph_style_references_must_name_styles() {+ let mut s = session();+ s.execute("style.paragraph.create", &json!({"name": "Body"})).unwrap();+ assert!(s.execute("style.paragraph.create", &json!({"name": "Lost", "nextStyle": "Nowhere"})).is_err());+ assert!(s.doc().unwrap().doc.styles.para("Lost").is_none());+ // On creation too, a reference that isn't a name or null is refused, not dropped.+ for p in [json!({"name": "Lost", "nextStyle": true}), json!({"name": "Lost", "basedOn": 3})] {+ assert!(s.execute("style.paragraph.create", &p).is_err(), "{p}");+ assert!(s.doc().unwrap().doc.styles.para("Lost").is_none(), "{p}");+ }+ assert!(s.execute("style.character.create", &json!({"name": "Lost", "basedOn": ["Body"]})).is_err());+ assert!(s.doc().unwrap().doc.styles.char_style("Lost").is_none());+ s.execute("style.paragraph.create", &json!({"name": "Self", "nextStyle": "Self"})).unwrap();+ let before = s.doc().unwrap().doc.clone();+ for p in [json!({"name": "Body", "basedOn": "Nowhere"}), json!({"name": "Body", "basedOn": 3}), json!({"name": "Body", "nextStyle": true})] {+ assert!(s.execute("style.paragraph.edit", &p).is_err(), "{p}");+ }+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "nothing changed");+ s.execute("style.paragraph.edit", &json!({"name": "Body", "basedOn": null, "nextStyle": "Self"})).unwrap();+ }++ /// The course's chapter 43: with Direct Selection, a circle's selected anchor shows its handles+ /// and they drag, reshaping the curve; the handles of the anchors away from it neither show nor+ /// catch a press, as in InDesign.+ #[test]+ fn direct_selection_drags_only_the_handles_around_the_selected_anchor() {+ use designcraft_tools::{PointerEvent, PointerKind};+ let mut s = session();+ let v = ViewInfo::at_zoom(1.0);+ let id = s.execute("frame.create", &json!({"rect": [100, 300, 300, 500], "shape": "ellipse"})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [id]})).unwrap();+ s.set_tool("directSelection");+ // Each anchor and its two handles, in the spread.+ let anchors = |s: &Session| {+ let st = s.doc().unwrap();+ let it = st.doc.item(designcraft_doc::ItemId(id)).unwrap();+ it.path.subpaths[0].anchors.iter().map(|a| (it.xf * a.p, it.xf * a.h_in, it.xf * a.h_out)).collect::<Vec<_>>()+ };+ let before = anchors(&s);+ let lowest = |f: &dyn Fn(f64) -> f64| (0..before.len()).min_by(|a, b| f(before[*a].0.y).total_cmp(&f(before[*b].0.y))).unwrap();+ let (bottom, top) = (lowest(&|y| -y), lowest(&|y| y));+ let press = |s: &mut Session, from: designcraft_geom::Point, to: designcraft_geom::Point| {+ s.pointer(&PointerEvent::new(PointerKind::Down, from.x, from.y), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Drag, (from.x + to.x) / 2.0, (from.y + to.y) / 2.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Drag, to.x, to.y), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, to.x, to.y), v).unwrap();+ };+ // Select the bottom anchor.+ let b = before[bottom].0;+ press(&mut s, b, b);+ assert_eq!(s.doc().unwrap().selection.anchors, [(designcraft_doc::ItemId(id), 0, bottom)]);+ // Its handle drags: the handle moves.+ let h = before[bottom].2;+ press(&mut s, h, h + designcraft_geom::Vec2::new(30.0, 0.0));+ let after = anchors(&s);+ assert!((after[bottom].2 - before[bottom].2).hypot() > 20.0, "the bottom handle moved: {:?} → {:?}", before[bottom], after[bottom]);+ // The top anchor's handle isn't shown, so a press on it doesn't take it.+ let t = before[top].2;+ press(&mut s, t, t + designcraft_geom::Vec2::new(0.0, -30.0));+ let after2 = anchors(&s);+ assert!((after2[top].2 - before[top].2).hypot() < 1e-6, "the top handle stays: {:?} → {:?}", before[top], after2[top]);+ }++ /// Direct Selection: a marquee over the top edges of two frames selects their top points, and a+ /// drag on one of them slants both frames in one undo step (InDesign's way to make a row of+ /// parallelograms).+ #[test]+ fn direct_selection_moves_the_points_of_several_frames_at_once() {+ use designcraft_tools::{Mods, PointerEvent, PointerKind};+ let mut s = session();+ let v = ViewInfo::at_zoom(1.0);+ let a = s.execute("frame.create", &json!({"rect": [100, 300, 200, 400]})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("frame.create", &json!({"rect": [200, 300, 300, 400]})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": []})).unwrap();+ s.set_tool("directSelection");+ s.pointer(&PointerEvent::new(PointerKind::Down, 80.0, 280.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Drag, 320.0, 320.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 320.0), v).unwrap();+ let sel = s.doc().unwrap().selection.clone();+ assert_eq!(sel.anchors.len(), 4, "{:?}", sel.anchors);+ assert!(sel.items.contains(&designcraft_doc::ItemId(a)) && sel.items.contains(&designcraft_doc::ItemId(b)));+ let shift = Mods { shift: true, ..Default::default() };+ s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 300.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Drag, 136.0, 302.0).with_mods(shift), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, 136.0, 302.0).with_mods(shift), v).unwrap();+ let corners = |s: &Session, id: u64| -> Vec<(f64, f64)> {+ let st = s.doc().unwrap();+ let it = st.doc.item(designcraft_doc::ItemId(id)).unwrap();+ it.path.subpaths[0].anchors.iter().map(|an| ((it.xf * an.p).x.round(), (it.xf * an.p).y.round())).collect()+ };+ // Both frames: top points 36 pt to the right, bottom points where they were.+ assert_eq!(corners(&s, a), vec![(136.0, 300.0), (236.0, 300.0), (200.0, 400.0), (100.0, 400.0)]);+ assert_eq!(corners(&s, b), vec![(236.0, 300.0), (336.0, 300.0), (300.0, 400.0), (200.0, 400.0)]);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(corners(&s, a), vec![(100.0, 300.0), (200.0, 300.0), (200.0, 400.0), (100.0, 400.0)]);+ assert_eq!(corners(&s, b), vec![(200.0, 300.0), (300.0, 300.0), (300.0, 400.0), (200.0, 400.0)]);+ }++ #[test]+ fn selected_points_follow_their_path() {+ let mut s = session();+ let a = s.execute("frame.create", &json!({"rect": [100, 300, 200, 400]})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("frame.create", &json!({"rect": [200, 300, 300, 400]})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"anchors": [[a, 0, 1], [b, 0, 2]]})).unwrap();+ // Shift-clicking a frame off the selection drops its points too.+ s.execute("selection.toggle", &json!({"id": a})).unwrap();+ let id = |n| designcraft_doc::ItemId(n);+ assert_eq!(s.doc().unwrap().selection.anchors, vec![(id(b), 0, 2)]);+ // A point added before the first one: the selected point keeps pointing at the same anchor.+ let l = s.execute("path.create", &json!({"anchors": [{"p": [100, 100]}, {"p": [200, 100]}, {"p": [300, 150]}]})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"anchors": [[l, 0, 1]]})).unwrap();+ s.execute("path.appendAnchor", &json!({"id": l, "anchor": {"p": [50, 120]}, "at": "start"})).unwrap();+ let st = s.doc().unwrap();+ let (_, si, ai) = st.selection.anchors[0];+ let it = st.doc.item(id(l)).unwrap();+ assert_eq!((it.xf * it.path.subpaths[si].anchors[ai].p).round(), designcraft_geom::Point::new(200.0, 100.0));+ // `points` that isn't a list is refused, even with an `id` beside it.+ for bad in [json!("x"), json!({"0": 1}), json!(5)] {+ assert!(s.execute("path.moveAnchors", &json!({"points": bad, "id": l, "anchors": [[0, 0]], "dx": 5})).is_err(), "points {bad}");+ }+ for bad in [json!(3), json!(-1), json!("0")] {+ assert!(s.execute("path.appendAnchor", &json!({"id": l, "anchor": {"p": [0, 0]}, "subpath": bad})).is_err(), "subpath {bad}");+ }+ assert_eq!(s.doc().unwrap().doc.item(id(l)).unwrap().path.subpaths[0].anchors.len(), 4, "nothing appended");+ }++ #[test]+ fn direct_selection_pulls_one_corner_of_an_unselected_frame() {+ // Chris Nielsen's "The Adobe InDesign Toolbox" (10:10): with the White Arrow, click outside,+ // then press on a frame's corner and pull it: only that corner moves (a triangle, nearly).+ use designcraft_tools::{PointerEvent, PointerKind, SnapView};+ let mut s = Session::new();+ s.execute("file.new", &json!({"width": 612, "height": 792, "facingPages": false})).unwrap();+ let id = s.execute("frame.create", &json!({"rect": [156, 219, 455, 569], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();+ s.execute("edit.deselectAll", &json!({})).unwrap();+ let corners = |s: &Session| {+ let d = &s.doc().unwrap().doc;+ let it = d.item(designcraft_doc::ItemId(id)).unwrap();+ it.path.subpaths[0].anchors.iter().map(|a| it.xf * a.p).collect::<Vec<_>>()+ };+ let before = corners(&s);+ s.set_tool("directSelection");+ let v = ViewInfo { snap: SnapView::OFF, ..ViewInfo::at_zoom(1.0) };+ let layout = s.layout();+ let at = |x: f64, y: f64| layout.to_canvas(designcraft_doc::SpreadRef::Doc(0), designcraft_geom::Point::new(x, y));+ let (a, b) = (at(455.0, 219.0), at(455.0, 150.0));+ s.pointer(&PointerEvent::new(PointerKind::Down, a.x, a.y), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Drag, a.x, a.y - 30.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Drag, b.x, b.y), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, b.x, b.y), v).unwrap();+ let after = corners(&s);+ let moved: Vec<_> = before.iter().zip(&after).filter(|(p, q)| (**p - **q).hypot() > 1e-6).collect();+ assert_eq!(moved.len(), 1, "one corner moved: {before:?} → {after:?}");+ assert!((*moved[0].1 - designcraft_geom::Point::new(455.0, 150.0)).hypot() < 1e-6, "{after:?}");+ assert_eq!(s.doc().unwrap().selection.items, [designcraft_doc::ItemId(id)], "the frame is selected");+ // One undo step puts the corner back.+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(corners(&s), before);+ // Away from its corners, the White Arrow still drags the whole unselected frame.+ s.execute("edit.deselectAll", &json!({})).unwrap();+ let (c, d) = (at(300.0, 219.0), at(300.0, 269.0));+ s.pointer(&PointerEvent::new(PointerKind::Down, c.x, c.y), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Drag, c.x, c.y + 20.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Drag, d.x, d.y), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, d.x, d.y), v).unwrap();+ assert!(corners(&s).iter().zip(&before).all(|(p, q)| (p.y - q.y - 50.0).abs() < 1e-6), "{:?}", corners(&s));+ }++ #[test]+ fn direct_selection_on_a_selected_frame_deletes_only_its_image() {+ use designcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};+ let dir = tempfile::tempdir().unwrap();+ let png = dir.path().join("photo.png");+ std::fs::write(&png, designcraft_render::Rendered { width: 100, height: 100, pixels: vec![40u8; 100 * 100 * 4] }.to_png()).unwrap();+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let frame = s.execute("frame.create", &json!({"rect": [100, 100, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ s.execute("file.place", &json!({"path": png.to_string_lossy(), "frame": frame})).unwrap();+ s.execute("selection.set", &json!({"ids": [frame], "content": false})).unwrap();+ let v = ViewInfo::at_zoom(1.0);+ let click = |s: &mut Session| {+ s.pointer(&PointerEvent::new(PointerKind::Down, 110.0, 150.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, 110.0, 150.0), v).unwrap();+ };+ // The frame is selected with the Selection tool, then the image is clicked with Direct Selection.+ s.set_tool("selection");+ click(&mut s);+ assert!(!s.doc().unwrap().selection.content);+ s.set_tool("directSelection");+ click(&mut s);+ assert!(s.doc().unwrap().selection.content, "Direct Selection selects the image inside the selected frame");+ assert!(s.tool_key(ToolKey::Delete, Mods::default(), v).unwrap());+ let st = s.doc().unwrap();+ let it = st.doc.item(designcraft_doc::ItemId(frame)).expect("the frame stays");+ assert!(matches!(it.content, designcraft_doc::Content::Unassigned), "{:?}", it.content);+ assert_eq!(st.selection.items, vec![designcraft_doc::ItemId(frame)]);+ // A frame holding pasted-in items: the click selects them too, so arrow keys move them.+ let inner = s.execute("frame.create", &json!({"rect": [320, 120, 360, 160]})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [inner]})).unwrap();+ s.execute("edit.cut", &json!({})).unwrap();+ let holder = s.execute("frame.create", &json!({"rect": [300, 100, 400, 200]})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [holder]})).unwrap();+ s.execute("edit.pasteInto", &json!({})).unwrap();+ s.set_tool("selection");+ s.pointer(&PointerEvent::new(PointerKind::Down, 340.0, 140.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, 340.0, 140.0), v).unwrap();+ assert_eq!(s.doc().unwrap().selection.items, vec![designcraft_doc::ItemId(holder)]);+ assert!(!s.doc().unwrap().selection.content);+ s.set_tool("directSelection");+ s.pointer(&PointerEvent::new(PointerKind::Down, 340.0, 140.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, 340.0, 140.0), v).unwrap();+ let st = s.doc().unwrap();+ assert!(st.selection.content && st.selection.items == [designcraft_doc::ItemId(holder)], "the pasted-in items are selected: {:?}", st.selection);+ }++ /// Issue #1637: with several objects selected, a click on one of them (no drag) makes it the key+ /// object, and Align to Key Object leaves it in place. A second click on it drops the key.+ #[test]+ fn a_click_in_the_selection_makes_the_key_object() {+ use designcraft_tools::{PointerEvent, PointerKind};+ let mut s = session();+ let a = s.execute("frame.create", &json!({"rect": [50.0, 100.0, 100.0, 150.0], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("frame.create", &json!({"rect": [200.0, 120.0, 300.0, 170.0], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [a, b]})).unwrap();+ s.set_tool("selection");+ let v = ViewInfo::at_zoom(1.0);+ // On the part of the key object that the aligned object never covers, away from the handles.+ let click = |s: &mut Session| {+ s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 160.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 160.0), v).unwrap();+ };+ click(&mut s);+ assert_eq!(s.doc().unwrap().selection.items.len(), 2, "the click keeps both selected");+ // The key is the right-hand object, so aligning left edges to the selection would move it.+ s.execute("object.align", &json!({"edge": "left", "to": "keyObject"})).unwrap();+ let x0 = |s: &Session, id: u64| s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().bounds().x0;+ assert!((x0(&s, b) - 200.0).abs() < 1e-6, "the key object moved to {}", x0(&s, b));+ assert!((x0(&s, a) - 200.0).abs() < 1e-6, "the other object is at {}", x0(&s, a));+ // The Align panel and the Control panel send no target: the key object is the default one.+ s.execute("object.align", &json!({"edge": "top"})).unwrap();+ let y0 = |s: &Session, id: u64| s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().bounds().y0;+ assert!((y0(&s, b) - 120.0).abs() < 1e-6, "the key object moved to {}", y0(&s, b));+ assert!((y0(&s, a) - 120.0).abs() < 1e-6, "the other object is at {}", y0(&s, a));+ click(&mut s);+ assert_eq!(s.doc().unwrap().selection.key, None, "a click on the key object drops the key");+ }++ /// Dragging one of several selected objects moves them all and makes no key object.+ #[test]+ fn dragging_the_selection_makes_no_key_object() {+ use designcraft_tools::{PointerEvent, PointerKind};+ let mut s = session();+ let a = s.execute("frame.create", &json!({"rect": [50.0, 100.0, 100.0, 150.0], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("frame.create", &json!({"rect": [200.0, 100.0, 260.0, 150.0], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [a, b]})).unwrap();+ s.set_tool("selection");+ let v = ViewInfo::at_zoom(1.0);+ s.pointer(&PointerEvent::new(PointerKind::Down, 230.0, 125.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 135.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 135.0), v).unwrap();+ assert_eq!(s.doc().unwrap().selection.key, None);+ }++ /// Shift-clicking the key object out of the selection drops the key.+ #[test]+ fn deselecting_the_key_object_drops_the_key() {+ let mut s = session();+ let a = s.execute("frame.create", &json!({"rect": [50.0, 100.0, 100.0, 150.0]})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("frame.create", &json!({"rect": [200.0, 100.0, 260.0, 150.0]})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [a, b]})).unwrap();+ s.execute("selection.key", &json!({"id": b})).unwrap();+ assert_eq!(s.doc().unwrap().selection.key, Some(designcraft_doc::ItemId(b)));+ s.execute("selection.toggle", &json!({"id": b})).unwrap();+ assert_eq!(s.doc().unwrap().selection.key, None);+ }++ /// A key object needs another object to align to: with one object selected there is nothing to key+ /// against, and the stored key would turn that object into the target as soon as a second one joins.+ #[test]+ fn a_single_selected_object_cannot_be_the_key_object() {+ let mut s = session();+ let a = s.execute("frame.create", &json!({"rect": [50.0, 100.0, 100.0, 150.0]})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("frame.create", &json!({"rect": [200.0, 120.0, 300.0, 170.0]})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [a]})).unwrap();+ assert!(s.execute("selection.key", &json!({"id": a})).is_err());+ assert_eq!(s.doc().unwrap().selection.key, None);+ s.execute("selection.toggle", &json!({"id": b})).unwrap();+ assert_eq!(s.doc().unwrap().selection.key, None, "the second object joining must not find a key already set");+ }++ /// With the selection down to the key object alone, Align no longer has a key object: a single+ /// object aligns to the page, as before.+ #[test]+ fn a_lone_key_object_aligns_to_the_page() {+ let mut s = session();+ let a = s.execute("frame.create", &json!({"rect": [50.0, 100.0, 100.0, 150.0]})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("frame.create", &json!({"rect": [200.0, 120.0, 300.0, 170.0]})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [a, b]})).unwrap();+ s.execute("selection.key", &json!({"id": b})).unwrap();+ s.execute("selection.toggle", &json!({"id": a})).unwrap();+ assert_eq!(s.doc().unwrap().selection.key, None);+ s.execute("object.align", &json!({"edge": "left"})).unwrap();+ let x0 = s.doc().unwrap().doc.item(designcraft_doc::ItemId(b)).unwrap().bounds().x0;+ assert!(x0.abs() < 1e-6, "the object is at {x0}, not at the page's left edge");+ }++ /// Aligning one object alone (`ids`) while it is the key object of a larger selection also takes+ /// the page.+ #[test]+ fn aligning_the_key_object_alone_takes_the_page() {+ let mut s = session();+ let a = s.execute("frame.create", &json!({"rect": [50.0, 100.0, 100.0, 150.0]})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("frame.create", &json!({"rect": [200.0, 120.0, 300.0, 170.0]})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [a, b]})).unwrap();+ s.execute("selection.key", &json!({"id": b})).unwrap();+ s.execute("object.align", &json!({"edge": "left", "ids": [b]})).unwrap();+ let x0 = s.doc().unwrap().doc.item(designcraft_doc::ItemId(b)).unwrap().bounds().x0;+ assert!(x0.abs() < 1e-6, "the object is at {x0}, not at the page's left edge");+ }diff --cc crates/tools/src/tests.rsindex 555ea9e1e,9e2421db5..1ecc238b1--- a/crates/tools/src/tests.rs+++ b/crates/tools/src/tests.rs@@@ -1937,37 -2077,141 +2077,176 @@@ fn loaded_text_cursor_threads_into_a_frassert_eq!(t2.cursor(&cx2, q, Mods::default()), Cursor::NotAllowed);}+#[test]+fn parent_resize_page_tool_targets_the_visible_parent() {+ let d = Document::new(&NewDocument { width: 400.0, height: 600.0, pages: 3, facing_pages: true, ..Default::default() });+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, true));+ let cx = ctx(&d, &s, &c, &l);+ let p = l.to_canvas(SpreadRef::Parent(0), d.parents[0].pages[0].bounds().center());+ let mut t = create("page");+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, p.x, p.y));+ assert_eq!(+ a,+ vec![Action::Dialog(+ "cmd:layout.parentPageSize".into(),+ serde_json::json!({"parent": d.parents[0].id.0, "page": 0, "width": 400.0, "height": 600.0})+ )],+ "double click must target the visible parent instead of document page zero"+ );+}++#[test]+fn parent_resize_selection_tracks_ids_and_never_crosses_canvas_modes() {+ let mut d = Document::new(&NewDocument::default());+ let second = d.add_parent("B", "Parent", 1, 12.0, designcraft_doc::Margins::uniform(36.0));+ let selection = Selection { page: Some(0), parent_page: Some((second, 1)), ..Default::default() };+ let l = CanvasLayout::new(&d, true);+ assert_eq!(l.selected_page(&d, &selection), Some((SpreadRef::Parent(1), 1)));+ d.parents.swap(0, 1);+ let l = CanvasLayout::new(&d, true);+ assert_eq!(l.selected_page(&d, &selection), Some((SpreadRef::Parent(0), 1)));+ assert_eq!(CanvasLayout::new(&d, false).selected_page(&d, &selection), Some((SpreadRef::Doc(0), 0)));+ d.parents.remove(0);+ assert_eq!(CanvasLayout::new(&d, true).selected_page(&d, &selection), None);+ let selection = Selection { page: Some(0), ..Default::default() };+ assert_eq!(CanvasLayout::new(&d, true).selected_page(&d, &selection), None);+}+++ #[test]+ fn direct_selection_click_on_one_of_several_selected_frames_selects_only_it() {+ let mut d = Document::new(&NewDocument::default());+ let a = add_rect(&mut d, Rect::new(100.0, 100.0, 200.0, 200.0));+ let b = add_rect(&mut d, Rect::new(300.0, 100.0, 400.0, 200.0));+ let (s, c, l) = (Selection::items(vec![a, b]), Cache::new(), CanvasLayout::new(&d, false));+ let cx = ctx(&d, &s, &c, &l);+ let p = spread_pt(&l, 150.0, 150.0);+ let mut t = create("directSelection");+ let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p.x, p.y));+ assert_eq!(acts, vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [a.0], "content": true}))]);+ }++ #[test]+ fn pulling_a_corner_of_an_unselected_frame_selects_the_frame_not_its_content() {+ let mut d = Document::new(&NewDocument::default());+ let a = add_rect(&mut d, Rect::new(100.0, 100.0, 200.0, 200.0));+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));+ let cx = ctx(&d, &s, &c, &l);+ let p = spread_pt(&l, 200.0, 100.0);+ let mut t = create("directSelection");+ let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p.x, p.y));+ assert_eq!(+ acts,+ vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [a.0], "content": false})), Action::Begin("Move Anchor".into())]+ );+ }++ #[test]+ fn anchor_drag_on_a_rotated_spread_sends_a_spread_space_delta() {+ let mut d = Document::new(&NewDocument::default());+ let a = add_rect(&mut d, Rect::new(100.0, 100.0, 200.0, 200.0));+ Arc::make_mut(&mut d.spreads[0]).pages[0].view_rotation = 1;+ let (s, c, l) = (Selection::items(vec![a]), Cache::new(), CanvasLayout::new(&d, false));+ let cx = ctx(&d, &s, &c, &l);+ let p = l.to_canvas(SpreadRef::Doc(0), Point::new(200.0, 100.0));+ let mut t = create("directSelection");+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p.x, p.y));+ let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, p.x + 50.0, p.y));+ let [Action::Preview(cmd, params)] = acts.as_slice() else { panic!("{acts:?}") };+ assert_eq!(cmd, "path.moveAnchors");+ let want = l.delta_to_spread(SpreadRef::Doc(0), Vec2::new(50.0, 0.0));+ assert!(want.y.abs() > 1.0, "the view rotation turns a canvas x move into a spread y move: {want:?}");+ let (dx, dy) = (params["dx"].as_f64().unwrap(), params["dy"].as_f64().unwrap());+ assert!((dx - want.x).abs() < 1e-6 && (dy - want.y).abs() < 1e-6, "{params} want {want:?}");+ }++ /// Direct Selection selects anchor points with a marquee across several frames, and dragging one of+ /// them moves them all, as InDesign does when the top points of a row of frames are dragged to slant+ /// them (Zero2Graphic's page layout tutorial, 1:15).+ #[test]+ fn direct_selection_marquee_selects_points_of_several_frames_and_drags_them_together() {+ let mut d = Document::new(&NewDocument::default());+ let a = add_rect(&mut d, Rect::new(100.0, 100.0, 200.0, 200.0));+ let b = add_rect(&mut d, Rect::new(200.0, 100.0, 300.0, 200.0));+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));+ let none = Selection::default();+ let mut t = create("directSelection");+ // A marquee around the top edges: the four top points, not the frames' bottom ones.+ let (p0, p1) = (spread_pt(&l, 80.0, 90.0), spread_pt(&l, 320.0, 110.0));+ t.pointer(&ctx(&d, &none, &c, &l), &PointerEvent::new(PointerKind::Down, p0.x, p0.y));+ t.pointer(&ctx(&d, &none, &c, &l), &PointerEvent::new(PointerKind::Drag, p1.x, p1.y));+ let up = t.pointer(&ctx(&d, &none, &c, &l), &PointerEvent::new(PointerKind::Up, p1.x, p1.y));+ let Some(Action::Exec(cmd, p)) = up.last() else { panic!("{up:?}") };+ assert_eq!(cmd, "selection.set");+ assert_eq!(p["ids"], serde_json::json!([a.0, b.0]));+ let mut got: Vec<(u64, u64, u64)> =+ p["anchors"].as_array().unwrap().iter().map(|v| (v[0].as_u64().unwrap(), v[1].as_u64().unwrap(), v[2].as_u64().unwrap())).collect();+ got.sort();+ assert_eq!(got, vec![(a.0, 0, 0), (a.0, 0, 1), (b.0, 0, 0), (b.0, 0, 1)]);+ // With another frame selected before, a marquee without Shift selects only the paths whose+ // points it takes; with Shift the other frame stays selected.+ let other = add_rect(&mut d, Rect::new(400.0, 400.0, 450.0, 450.0));+ let l = CanvasLayout::new(&d, false);+ let was = Selection { items: vec![other], ..Default::default() };+ let shift = Mods { shift: true, ..Default::default() };+ for (mods, want) in [(Mods::default(), serde_json::json!([a.0, b.0])), (shift, serde_json::json!([other.0, a.0, b.0]))] {+ t.pointer(&ctx(&d, &was, &c, &l), &PointerEvent::new(PointerKind::Down, p0.x, p0.y).with_mods(mods));+ t.pointer(&ctx(&d, &was, &c, &l), &PointerEvent::new(PointerKind::Drag, p1.x, p1.y).with_mods(mods));+ let up = t.pointer(&ctx(&d, &was, &c, &l), &PointerEvent::new(PointerKind::Up, p1.x, p1.y).with_mods(mods));+ let Some(Action::Exec(_, p)) = up.last() else { panic!("{up:?}") };+ assert_eq!(p["ids"], want, "{mods:?}");+ }+ // Those points selected: dragging one moves all four, in one preview.+ let sel = Selection { items: vec![a, b], anchors: vec![(a, 0, 0), (a, 0, 1), (b, 0, 0), (b, 0, 1)], ..Default::default() };+ let cx = ctx(&d, &sel, &c, &l);+ let at = spread_pt(&l, 200.0, 100.0);+ let down = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y));+ assert_eq!(down, vec![Action::Begin("Move Anchors".into())]);+ let drag = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, at.x + 36.0, at.y + 3.0).with_mods(shift));+ let Some(Action::Preview(cmd, p)) = drag.last() else { panic!("{drag:?}") };+ assert_eq!(cmd, "path.moveAnchors");+ assert_eq!(p["points"].as_array().map(Vec::len), Some(4), "{p}");+ // Shift keeps the move horizontal.+ // Each point carries its own movement (in its spread): here all the same.+ let moves = |p: &serde_json::Value| -> Vec<(f64, f64)> {+ p["points"].as_array().unwrap().iter().map(|v| (v[3].as_f64().unwrap(), v[4].as_f64().unwrap())).collect()+ };+ assert!(moves(p).iter().all(|&(x, y)| (x - 36.0).abs() < 1e-9 && y.abs() < 1e-9), "{p}");+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x + 36.0, at.y)), vec![Action::Commit]);+ // A Shift-drag that starts on a selected point keeps it: all four move, constrained.+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(shift));+ let drag = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, at.x + 3.0, at.y + 30.0).with_mods(shift));+ let Some(Action::Preview(_, p)) = drag.last() else { panic!("{drag:?}") };+ assert_eq!(p["points"].as_array().map(Vec::len), Some(4), "{p}");+ assert!(moves(p).iter().all(|&(x, y)| x.abs() < 1e-9 && (y - 30.0).abs() < 1e-9), "vertical: {p}");+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x, at.y + 30.0).with_mods(shift)), vec![Action::Commit]);+ // Shift+click on a selected point takes it out of the selection, on release; the arrow keys+ // move the points.+ let out = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(shift));+ assert!(!out.iter().any(|a| matches!(a, Action::Exec(..))), "kept while it may become a drag: {out:?}");+ // A jiggle inside the drag tolerance moves nothing: it is still a click.+ let jiggle = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, at.x + 1.0, at.y + 1.0).with_mods(shift));+ assert!(jiggle.is_empty(), "{jiggle:?}");+ let out = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x + 1.0, at.y + 1.0).with_mods(shift));+ let Some(Action::Exec(cmd, p)) = out.last() else { panic!("{out:?}") };+ assert_eq!(cmd, "selection.set");+ assert_eq!(p["anchors"].as_array().map(Vec::len), Some(3), "{p}");+ let keys = t.key(&cx, ToolKey::Right, Mods::default());+ assert!(+ matches!(keys.as_slice(), [Action::Exec(cmd, p)] if cmd == "path.moveAnchors" && p["points"].as_array().map(Vec::len) == Some(4)),+ "{keys:?}"+ );+ // Delete deletes the selected points, not their paths.+ assert_eq!(t.key(&cx, ToolKey::Delete, Mods::default()), vec![Action::Exec("path.deletePoints".into(), serde_json::json!({}))]);+ // On a spread turned a quarter on screen, → moves the points right on screen: up or down in+ // the spread, not across it.+ let mut turned = d.clone();+ std::sync::Arc::make_mut(&mut turned.spreads[0]).pages[0].view_rotation = 1;+ let lt = CanvasLayout::new(&turned, false);+ let cxt = ctx(&turned, &sel, &c, <);+ let keys = t.key(&cxt, ToolKey::Right, Mods::default());+ let [Action::Exec(_, p)] = keys.as_slice() else { panic!("{keys:?}") };+ let inc = turned.settings.keyboard_increment;+ let want = lt.delta_to_spread(SpreadRef::Doc(0), designcraft_geom::Vec2::new(inc, 0.0));+ assert!(want.x.abs() < 1e-9 && (want.y.abs() - inc).abs() < 1e-9, "a quarter turn: {want:?}");+ assert!(moves(p).iter().all(|&(x, y)| (x - want.x).abs() < 1e-9 && (y - want.y).abs() < 1e-9), "{p}");+ }diff --cc crates/ui-egui/src/canvas.rsindex 496d17bdd,ed207c34b..9eece3fb1--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@ -11,6 -14,57 +14,57 @@@ use serde_json::{Value, json}use crate::{DesignApp, ScreenMode, View, theme::Tokens};+ mod column_guides;+ mod frames;+ mod guides;+ mod ime;+ mod input;+ mod page_decor;+ mod render;+ mod rulers;+ mod scroll;+ mod text_overlay;+ mod tool_overlays;+ mod view;++ use column_guides::{COLUMN_DRAG, ColumnDrag, column_guide_at, spread_x_across};+ use frames::{draw_frames, draw_selection};+ #[cfg(test)]+ use frames::{item_canvas_xf, overset_frames, overset_marks, ported_frames, text_frames_in};+ use guides::{GUIDE_DRAG, GUIDE_PRESS, GuideDrag, GuidePress, guide_readout, guide_spot, moving_guides, readout_at};+ #[cfg(test)]+ use guides::{guide_at, guide_drag_delta, guide_measure};+ use ime::ime_canvas_pass;+ pub(crate) use ime::{CanvasIme, ime_observe};+ pub(crate) use input::forwarded_keys;+ pub use input::{begin_frame, context_menu_open};+ use input::{context_menu, draw_cursor_badge, handle_input, pointer_elsewhere};+ #[cfg(test)]+ use input::{press_count, release_clicks};+ #[cfg(test)]+ use page_decor::{MAX_BASELINES, baseline_grid_lines};+ use page_decor::{dashed, draw_flattener_preview, draw_guides, shown_area};+ use render::render_texture;+ pub use render::{DisplayKey, color_at};+ #[cfg(test)]+ use render::{c32, invalidate_on_display_change, screen_options};+ pub(crate) use rulers::fmt_tick;+ #[cfg(test)]+ use rulers::ruler_pieces;+ use rulers::{draw_rulers, ruler_units_menus};+ use scroll::{mods, navigation_space, scrollbars, spring_zoom_mode};+ pub use text_overlay::selected_text;+ use text_overlay::{draw_dynamic_spelling, draw_hidden_characters};+ #[cfg(test)]+ use text_overlay::{draw_text_selection, frame_hidden_marks, hidden_marks};+ use tool_overlays::draw_tool_overlays;+ pub(crate) use view::page_in_view;+ use view::present_fit;+ pub use view::{+ PageBox, apply_view_request, can_go_through_history, current_page, current_parent_page, current_slot, current_spread, current_spread_page,- drop_point, fit, go_through_history, go_to_page, page_box, page_box_go, set_zoom, show_spread, step_spread, view_centre, zoom_at,++ drop_point, fit, go_through_history, go_to_page, page_box, page_box_go, page_target, set_zoom, show_spread, step_spread, view_centre, zoom_at,+ };+pub const RULER: f32 = 15.0;/// Width of the view's scrollbars.pub const SCROLLBAR: f32 = 10.0;diff --cc crates/ui-egui/src/canvas/view.rsindex 000000000,2ba0876a1..f00a005f5mode 000000,100644..100644--- a/crates/ui-egui/src/canvas/view.rs+++ b/crates/ui-egui/src/canvas/view.rs@@@ -1,0 -1,392 +1,390 @@@+ use super::{CanvasLayout, DRect, DVec2, DesignApp, Document, Point, Pos2, Rect, SpreadRef, Value, View, Xf};++ /// Fit the current spread (or page) in the canvas.+ pub fn fit(app: &mut DesignApp, rect: Rect, what: &str) {+ let Some(st) = app.session.active() else { return };+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ let cur = current_slot(app, &layout).unwrap_or(0);+ let Some(slot) = layout.slots.get(cur) else { return };+ let mut b = slot.bounds;+ if what == "page"+ && let Some(sp) = st.doc.spread(slot.spread)+ {+ let center = app.view().map(|v| v.origin.x + rect.width() as f64 / 2.0 / v.zoom).unwrap_or(0.0);+ let c = slot.to_spread(Point::new(center, slot.bounds.center().y));+ let pi = sp.page_at_x(c.x).unwrap_or(0);+ b = slot.xf.transform_rect_bbox(sp.pages[pi].bounds());+ }+ if what == "all" {+ b = layout.slots.iter().map(|s| s.bounds).reduce(|a, b| a.union(b)).unwrap_or(b);+ }+ if what == "selection" {+ // Fit Selection in Window: the selected objects (on their spread's slot).+ let sel: Vec<designcraft_geom::Rect> = st+ .selection+ .items+ .iter()+ .filter_map(|id| {+ let loc = st.doc.find(*id)?;+ let slot = layout.slots.iter().find(|s| s.spread == loc.spread)?;+ Some(slot.xf.transform_rect_bbox(st.doc.item(*id)?.bounds()))+ })+ .collect();+ let Some(u) = sel.into_iter().reduce(|a, b| a.union(b)) else { return };+ b = u.inflate(u.width().max(u.height()) * 0.05 + 1.0, u.width().max(u.height()) * 0.05 + 1.0);+ }+ fit_bounds(app, rect, b);+ }++ /// Zoom and scroll so canvas rectangle `b` fills the canvas `rect`.+ fn fit_bounds(app: &mut DesignApp, rect: Rect, b: DRect) {+ let pad = 40.0;+ let zoom =+ ((rect.width() as f64 - 2.0 * pad) / b.width().max(1e-6)).min((rect.height() as f64 - 2.0 * pad) / b.height().max(1e-6)).clamp(0.05, 40.0);+ let origin = Point::new(b.center().x - rect.width() as f64 / 2.0 / zoom, b.center().y - rect.height() as f64 / 2.0 / zoom);+ if let Some(v) = app.view_mut() {+ *v = View { zoom, origin, fitted: true, rotation: v.rotation };+ }+ }++ /// Fit spread `r` (a document or parent spread on the canvas as it is laid out now) in the canvas.+ /// Before the canvas has a size, the next frame fits whatever spread is current.+ pub fn show_spread(app: &mut DesignApp, r: SpreadRef) {+ let Some(st) = app.session.active() else { return };+ let Some(b) = CanvasLayout::new(&st.doc, st.editing_parents).slot(r).map(|s| s.bounds) else { return };+ match app.canvas_rect {+ Some(rect) => fit_bounds(app, rect, b),+ None => {+ if let Some(v) = app.view_mut() {+ v.fitted = false;+ }+ }+ }+ }++ /// Index of the slot nearest the view centre.+ pub fn current_slot(app: &DesignApp, layout: &CanvasLayout) -> Option<usize> {+ let v = app.view()?;+ let r = app.canvas_rect?;+ let c = Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, v.origin.y + r.height() as f64 / 2.0 / v.zoom);+ layout+ .slots+ .iter()+ .enumerate()+ .min_by(|a, b| {+ let da = (a.1.bounds.center().y - c.y).abs();+ let db = (b.1.bounds.center().y - c.y).abs();+ da.total_cmp(&db)+ })+ .map(|(i, _)| i)+ }++ /// The spread under the view centre (a parent spread while parents are edited).+ pub fn current_spread(app: &DesignApp) -> Option<SpreadRef> {+ let st = app.session.active()?;+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ Some(layout.slots.get(current_slot(app, &layout)?)?.spread)+ }++ /// The spread nearest the view centre and the centre in that spread's coordinates.+ pub fn view_centre(app: &DesignApp) -> Option<(SpreadRef, Point)> {+ let st = app.session.active()?;+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ let slot = layout.slots.get(current_slot(app, &layout)?)?;+ let v = app.view()?;+ let r = app.canvas_rect?;+ let c = Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, v.origin.y + r.height() as f64 / 2.0 / v.zoom);+ Some((slot.spread, slot.to_spread(c)))+ }++ /// Where a file dropped on the window lands: the spread under the pointer, or under the view+ /// centre when the pointer isn't over the canvas, and that point in spread coordinates.+ pub fn drop_point(app: &DesignApp, screen: Option<Pos2>) -> Option<(SpreadRef, Point)> {+ let rect = app.canvas_rect?;+ let Some(pos) = screen.filter(|p| rect.contains(*p)) else { return view_centre(app) };+ let st = app.session.active()?;+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ layout.spread_at(Xf::new(rect, app.view()?).to_canvas(pos))+ }++ /// Absolute page index under the view centre.+ pub fn current_page(app: &DesignApp) -> Option<usize> {+ let st = app.session.active()?;+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ let i = current_slot(app, &layout)?;+ let slot = layout.slots.get(i)?;- let SpreadRef::Doc(si) = slot.spread else { return Some(0) };++ let SpreadRef::Doc(si) = slot.spread else { return None };+ let v = app.view()?;+ let r = app.canvas_rect?;+ let c = slot.to_spread(Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, slot.bounds.center().y));+ let pi = st.doc.spreads[si].page_at_x(c.x).unwrap_or(0);+ Some(st.doc.first_page_of_spread(si) + pi)+ }+++/// The Page tool selection, or the page in view, without crossing canvas modes.++pub fn page_target(app: &DesignApp) -> Option<(SpreadRef, usize)> {++ let st = app.session.active()?;++ let selected = CanvasLayout::new(&st.doc, st.editing_parents).selected_page(&st.doc, &st.selection);++ if st.editing_parents && st.selection.parent_page.is_some() {++ return selected;++ }++ selected.or_else(|| current_spread_page(app))++}+++ /// The spread (document or parent) under the view centre and the page index within it: where+ /// commands that act "on the page I am working on" should go.+ pub fn current_spread_page(app: &DesignApp) -> Option<(SpreadRef, usize)> {+ let st = app.session.active()?;+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ let i = current_slot(app, &layout)?;+ let slot = layout.slots.get(i)?;+ let v = app.view()?;+ let r = app.canvas_rect?;+ let c = slot.to_spread(Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, slot.bounds.center().y));+ let pg = st.doc.spread(slot.spread)?.page_at_x(c.x).unwrap_or(0);+ Some((slot.spread, pg))+ }+-/// While parent spreads are being edited: (parent spread index, page index within it) under the-/// view centre. `None` when document pages are shown.++/// The selected parent page, or the parent page under the view centre.+ pub fn current_parent_page(app: &DesignApp) -> Option<(usize, usize)> {- let st = app.session.active()?;- if !st.editing_parents {- return None;- }- let layout = CanvasLayout::new(&st.doc, true);- let i = current_slot(app, &layout)?;- let slot = layout.slots.get(i)?;- let SpreadRef::Parent(pi) = slot.spread else { return None };- let v = app.view()?;- let r = app.canvas_rect?;- let c = slot.to_spread(Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, slot.bounds.center().y));- let qi = st.doc.parents.get(pi)?.page_at_x(c.x).unwrap_or(0);- Some((pi, qi))++ let (SpreadRef::Parent(si), pi) = page_target(app)? else { return None };++ Some((si, pi))+ }++ /// The page box's entries (the status bar's, and Properties › Page), as InDesign's: the+ /// document's pages by name, then the parents by label ("A-Parent").+ pub struct PageBox {+ pub names: Vec<String>,+ /// The entry in view: the parent shown while parents are edited, else the page.+ pub current: usize,+ /// How many of `names` are pages; the parents follow.+ pub pages: usize,+ parents: Vec<designcraft_doc::SpreadId>,+ }++ impl PageBox {+ /// The name of the entry in view ("3", "A-Parent").+ pub fn current_name(&self) -> &str {+ self.names.get(self.current).map_or("", String::as_str)+ }+ }++ pub fn page_box(app: &DesignApp) -> Option<PageBox> {+ let st = app.session.active()?;+ let pages = st.doc.page_count();+ let mut names: Vec<String> = (0..pages).map(|i| app.session.page_label(i)).collect();+ names.extend(st.doc.parents.iter().map(|p| p.parent.as_ref().map(|i| i.label()).unwrap_or_default()));+ let current = match current_parent_page(app) {+ Some((pi, _)) => pages + pi,+ None => current_page(app).unwrap_or(0).min(pages.saturating_sub(1)),+ };+ Some(PageBox { names, current, pages, parents: st.doc.parents.iter().map(|p| p.id).collect() })+ }++ /// Shows entry `i` of `b`: a page (leaving the parents, if they are shown) or a parent.+ pub fn page_box_go(app: &mut DesignApp, b: &PageBox, i: usize) {+ if i < b.pages {+ if app.session.active().is_some_and(|st| st.editing_parents) {+ let _ = app.run("layout.parents.edit", serde_json::json!({"on": false}));+ // Fit the page's spread first, then centre the page: a later refit would centre the+ // spread, and the page box would then show its other page.+ let spread = app.session.active().and_then(|st| st.doc.page_loc(i)).map(|(si, _)| SpreadRef::Doc(si));+ if let Some(r) = spread {+ show_spread(app, r);+ }+ }+ go_to_page(app, i);+ } else if let Some(id) = b.parents.get(i - b.pages) {+ let _ = app.run("layout.parents.edit", serde_json::json!({"parent": id.0}));+ }+ }++ /// Scroll so absolute page `abs` is centred (keeps zoom). A jump Go Back can return from.+ pub fn go_to_page(app: &mut DesignApp, abs: usize) {+ note_jump(app, false);+ centre_page(app, abs);+ note_jump(app, true);+ }++ fn centre_page(app: &mut DesignApp, abs: usize) {+ let Some(st) = app.session.active() else { return };+ let layout = CanvasLayout::new(&st.doc, false);+ let Some(pr) = layout.page_rect(&st.doc, abs) else { return };+ let Some(rect) = app.canvas_rect else { return };+ if let Some(v) = app.view_mut() {+ v.origin = Point::new(pr.center().x - rect.width() as f64 / 2.0 / v.zoom, pr.center().y - rect.height() as f64 / 2.0 / v.zoom);+ }+ }++ /// The document's pages by id, in page order.+ fn page_ids(doc: &Document) -> Vec<designcraft_doc::ids::PageId> {+ doc.spreads.iter().flat_map(|s| s.pages.iter().map(|p| p.id)).collect()+ }++ /// The page in view and the view centre's offset from that page's centre. Parent pages have none,+ /// nor has a view still waiting to be fitted (leaving parent pages for a document page).+ pub(crate) fn page_in_view(app: &DesignApp) -> Option<(designcraft_doc::ids::PageId, DVec2)> {+ let st = app.session.active().filter(|st| !st.editing_parents)?;+ let (v, r) = (app.view().filter(|v| v.fitted)?, app.canvas_rect?);+ let abs = current_page(app)?;+ let id = st.doc.page(abs)?.id;+ let pr = CanvasLayout::new(&st.doc, false).page_rect(&st.doc, abs)?;+ let c = Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, v.origin.y + r.height() as f64 / 2.0 / v.zoom);+ Some((id, c - pr.center()))+ }++ /// Layout ▸ Go Back / Go Forward record jumps (Go to Page, the page and spread commands, the Pages+ /// panel), not scrolling: where the view is when a jump starts, and where the jump took it.+ fn note_jump(app: &mut DesignApp, to: bool) {+ let Some((id, offset)) = page_in_view(app) else { return };+ if let Some(h) = app.page_history_mut() {+ if to { h.visit(id, offset) } else { h.leave(id, offset) }+ }+ }++ /// Whether Layout ▸ Go Back (`step` < 0) or Go Forward has a page to go to from the view as it is.+ pub fn can_go_through_history(app: &DesignApp, step: isize) -> bool {+ let Some(st) = app.session.active().filter(|st| !st.editing_parents) else { return false };+ // A view still waiting to be fitted is refitted next frame, which would replace the destination.+ if !app.view().is_some_and(|v| v.fitted) {+ return false;+ }+ let ids = page_ids(&st.doc);+ let Some(mut h) = app.page_history().cloned() else { return false };+ if let Some((id, offset)) = page_in_view(app) {+ h.leave(id, offset);+ }+ h.can_go(step, |id| ids.contains(&id))+ }++ /// Layout ▸ Go Back (`step` < 0) or Go Forward: show the page viewed before or after this one, where+ /// the view was on it (zoom kept).+ pub fn go_through_history(app: &mut DesignApp, step: isize) {+ if !app.view().is_some_and(|v| v.fitted) {+ return;+ }+ note_jump(app, false);+ let Some(ids) = app.session.active().filter(|st| !st.editing_parents).map(|st| page_ids(&st.doc)) else { return };+ let Some((id, offset)) = app.page_history_mut().and_then(|h| h.go(step, |id| ids.contains(&id))) else { return };+ let Some(st) = app.session.active() else { return };+ let Some(pr) = ids.iter().position(|p| *p == id).and_then(|abs| CanvasLayout::new(&st.doc, false).page_rect(&st.doc, abs)) else { return };+ let Some(rect) = app.canvas_rect else { return };+ let c = pr.center() + offset;+ if let Some(v) = app.view_mut() {+ v.origin = Point::new(c.x - rect.width() as f64 / 2.0 / v.zoom, c.y - rect.height() as f64 / 2.0 / v.zoom);+ }+ }++ /// Presentation: the spread in view, centred and as large as `rect` allows.+ pub(super) fn present_fit(app: &mut DesignApp, rect: Rect) {+ let Some(st) = app.session.active() else { return };+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ let Some(b) = current_slot(app, &layout).and_then(|i| layout.slots.get(i)).map(|s| s.bounds) else { return };+ if b.width() <= 0.0 || b.height() <= 0.0 {+ return;+ }+ let zoom = (rect.width() as f64 / b.width()).min(rect.height() as f64 / b.height()).clamp(0.05, 40.0);+ let origin = Point::new(b.center().x - rect.width() as f64 / 2.0 / zoom, b.center().y - rect.height() as f64 / 2.0 / zoom);+ if let Some(v) = app.view_mut() {+ v.zoom = zoom;+ v.origin = origin;+ }+ }++ /// Centre the spread `delta` spreads after (or before) the one in view (keeps zoom); stops at the+ /// first and last spread. Parent spreads while they are being edited.+ pub fn step_spread(app: &mut DesignApp, delta: isize) {+ // At the first or last spread only the view moves, within the spread: no jump for Go Back.+ let jump = spread_step(app, delta).is_some_and(|(cur, to)| cur != to);+ if jump {+ note_jump(app, false);+ }+ centre_spread(app, delta);+ if jump {+ note_jump(app, true);+ }+ }++ /// The slot in view and the one `delta` spreads after (or before) it, stopping at the ends.+ fn spread_step(app: &DesignApp, delta: isize) -> Option<(usize, usize)> {+ let st = app.session.active()?;+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ let cur = current_slot(app, &layout)?;+ Some((cur, cur.saturating_add_signed(delta).min(layout.slots.len().saturating_sub(1))))+ }++ fn centre_spread(app: &mut DesignApp, delta: isize) {+ let Some((_, to)) = spread_step(app, delta) else { return };+ let Some(st) = app.session.active() else { return };+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ let Some(b) = layout.slots.get(to).map(|s| s.bounds) else { return };+ let Some(rect) = app.canvas_rect else { return };+ if let Some(v) = app.view_mut() {+ v.origin = Point::new(b.center().x - rect.width() as f64 / 2.0 / v.zoom, b.center().y - rect.height() as f64 / 2.0 / v.zoom);+ }+ }++ pub fn zoom_at(app: &mut DesignApp, screen: Pos2, factor: f64) {+ let Some(rect) = app.canvas_rect else { return };+ let Some(v) = app.view_mut() else { return };+ let xf = Xf::new(rect, v);+ let c = xf.to_canvas(screen);+ let screen = xf.unrotate(screen);+ let nz = (v.zoom * factor).clamp(0.05, 40.0);+ v.zoom = nz;+ v.origin = Point::new(c.x - (screen.x - rect.min.x) as f64 / nz, c.y - (screen.y - rect.min.y) as f64 / nz);+ }++ pub fn set_zoom(app: &mut DesignApp, z: f64) {+ let Some(rect) = app.canvas_rect else { return };+ let cur = app.view().map(|v| v.zoom).unwrap_or(1.0);+ zoom_at(app, rect.center(), z / cur);+ }++ pub fn apply_view_request(app: &mut DesignApp, p: &Value) {+ if let Some(r) = p.get("showSpread").and_then(|v| serde_json::from_value::<SpreadRef>(v.clone()).ok()) {+ show_spread(app, r);+ }+ // Power Zoom (Hand tool, Alt-press): zoom out to the spread, aim a view-sized rectangle, zoom+ // back in where it was released.+ if let Some(phase) = p.get("powerZoom").and_then(Value::as_str) {+ let at = p.get("at").and_then(Value::as_array).map(|a| Point::new(a[0].as_f64().unwrap_or(0.0), a[1].as_f64().unwrap_or(0.0)));+ match phase {+ "start" => {+ if let (Some(v), Some(rect)) = (app.view().copied(), app.canvas_rect) {+ let centre = Xf::new(rect, &v).to_canvas(rect.center());+ app.power_zoom = Some((v.zoom, at.unwrap_or(centre)));+ fit(app, rect, "spread");+ }+ }+ "move" => {+ if let (Some(pz), Some(a)) = (&mut app.power_zoom, at) {+ pz.1 = a;+ }+ }+ _ => {+ if let (Some((z, c)), Some(rect)) = (app.power_zoom.take(), app.canvas_rect)+ && let Some(v) = app.view_mut()+ {+ let c = at.unwrap_or(c);+ v.zoom = z;+ v.origin = Point::new(c.x - rect.width() as f64 / 2.0 / z, c.y - rect.height() as f64 / 2.0 / z);+ }+ }+ }+ }+ if let Some(d) = p.get("pan").and_then(Value::as_array) {+ let (dx, dy) = (d.first().and_then(Value::as_f64).unwrap_or(0.0), d.get(1).and_then(Value::as_f64).unwrap_or(0.0));+ if let Some(v) = app.view_mut() {+ v.origin = Point::new(v.origin.x - dx / v.zoom, v.origin.y - dy / v.zoom);+ }+ }+ if let (Some(a), Some(rect)) = (p.get("zoomAt").and_then(Value::as_array), app.canvas_rect)+ && let Some(v) = app.view()+ {+ let c = Point::new(a[0].as_f64().unwrap_or(0.0), a[1].as_f64().unwrap_or(0.0));+ let xf = Xf::new(rect, v);+ let s = xf.to_screen(c);+ zoom_at(app, s, p.get("factor").and_then(Value::as_f64).unwrap_or(2.0));+ }+ }diff --cc crates/ui-egui/src/chrome/control_bar.rsindex 000000000,36a7521fe..d4dab9cc6mode 000000,100644..100644--- a/crates/ui-egui/src/chrome/control_bar.rs+++ b/crates/ui-egui/src/chrome/control_bar.rs@@@ -1,0 -1,614 +1,638 @@@+ use super::{Align, Color32, DesignApp, NumField, Sense, Stroke, Tokens, Unit, caption, icons, json, measure, panels, semibold, vec2};++ fn vsep(ui: &mut egui::Ui) {+ let t = Tokens::get(ui.ctx());+ let (r, _) = ui.allocate_exact_size(vec2(9.0, 46.0), Sense::hover());+ ui.painter().line_segment([r.center_top() + vec2(0.0, 4.0), r.center_bottom() - vec2(0.0, 4.0)], Stroke::new(1.0, t.divider));+ }++ /// Two-row context-sensitive Control panel.+ pub fn control_bar(app: &mut DesignApp, ui: &mut egui::Ui) {+ let t = Tokens::get(ui.ctx());+ egui::Panel::top("control_bar")+ .exact_size(59.0)+ .frame(+ egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin { left: 8, right: 8, top: 5, bottom: 3 }).stroke(Stroke::new(1.0, t.divider)),+ )+ .show(ui, |ui| {+ // Wider than the window: the bar scrolls sideways.+ crate::widgets::overflow_scrolling(ui);+ egui::ScrollArea::horizontal().id_salt("control_bar_scroll").auto_shrink([false, true]).show(ui, |ui| {+ ui.horizontal_top(|ui| {+ let text_mode =+ matches!(app.session.tool_id(), "type" | "verticalType") || app.session.active().is_some_and(|d| d.selection.text.is_some());+ if app.session.tool_id() == "page" {+ control_page(app, ui);+ } else if text_mode {+ control_text(app, ui);+ } else {+ crate::object_control::show(app, ui);+ }+ });+ });+ });+ }++ /// Page-size preset menu and the portrait / landscape toggles of the Control panel.-fn page_preset_and_orientation(app: &mut DesignApp, ui: &mut egui::Ui, lang: &str, size: (f64, f64), n: usize, anchor: u8) {++fn page_preset_and_orientation(++ app: &mut DesignApp,++ ui: &mut egui::Ui,++ lang: &str,++ size: (f64, f64),++ anchor: u8,++ resize: impl Fn(&mut DesignApp, serde_json::Value),++) {+ let landscape = size.0 > size.1;+ ui.vertical(|ui| {+ let cur = panels::properties::preset_name(size.0, size.1);- craft_ui::ComboBox::from_id_salt("ctl_page_preset").selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, cur))).width(130.0).show_ui(- ui,- |ui| {++ craft_ui::ComboBox::from_id_salt("ctl_page_preset")++ .selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, cur)))++ .width(130.0)++ .show_ui(ui, |ui| {+ for (name, w, h) in panels::properties::PAGE_PRESETS {+ if ui.selectable_label(cur == *name, crate::rtl::widget(ui, crate::i18n::tr(lang, name))).clicked() {+ let (w, h) = if landscape { (h, w) } else { (w, h) };- let _ = app.run("layout.pageSize", json!({"pages": [n], "width": w, "height": h, "anchor": anchor}));++ resize(app, json!({"width": w, "height": h, "anchor": anchor}));+ }+ }- },- );++ })++ .response++ .accessible_name(crate::i18n::tr(lang, "Page Size"));+ ui.horizontal(|ui| {+ for (icon, tip, want) in [("orient-portrait", "Portrait", false), ("orient-landscape", "Landscape", true)] {+ if crate::widgets::icon_toggle(ui, icon, landscape == want, crate::i18n::tr(lang, tip)).clicked() && landscape != want {- let _ = app.run("layout.pageSize", json!({"pages": [n], "width": size.1, "height": size.0, "anchor": anchor}));++ resize(app, json!({"width": size.1, "height": size.0, "anchor": anchor}));+ }+ }+ });+ });+ }++ /// The Control panel with the Page tool, as InDesign's: reference point, X/Y, W/H, page-size+ /// preset, orientation, Liquid Page Rule and Show Parent Page Overlay, for+ /// the page the Page tool selected (else the page in view). W/H keep the reference point in place.-fn control_page(app: &mut DesignApp, ui: &mut egui::Ui) {++pub(super) fn control_page(app: &mut DesignApp, ui: &mut egui::Ui) {+ let lang = app.ui.language.clone();+ let Some(st) = app.session.active() else { return };+ let units = st.doc.settings.horizontal_units;- let Some(page) = st.selection.page.or_else(|| crate::canvas::current_page(app)) else { return };++ let Some((spread, page)) = crate::canvas::page_target(app) else { return };+ let Some(st) = app.session.active() else { return };+ let d = st.doc.clone();- let Some((si, pi)) = d.page_loc(page) else { return };- let pg = d.spreads[si].pages[pi].clone();- let n = page + 1;++ let Some(sp) = d.spread(spread) else { return };++ let Some(pg) = sp.pages.get(page).cloned() else { return };++ let n = match spread {++ designcraft_doc::SpreadRef::Doc(si) => Some(d.first_page_of_spread(si) + page + 1),++ _ => None,++ };++ let resize = |app: &mut DesignApp, params| {++ if let Some((cmd, params)) = designcraft_tools::layout::page_size_command(&d, spread, page, params) {++ let _ = app.run(cmd, params);++ }++ };+ // Reference point: W/H edits keep it in place.+ let (r, _) = ui.allocate_exact_size(vec2(30.0, 44.0), Sense::hover());+ if let Some(p) = panels::properties::ref_point_proxy(ui, egui::Rect::from_center_size(r.center(), vec2(27.0, 27.0)), app.ui.ref_point) {+ app.ui.ref_point = p;+ }+ let anchor = app.ui.ref_point.min(8);+ let (fx, fy) = ((anchor % 3) as f64 / 2.0, (anchor / 3) as f64 / 2.0);+ // The reference point's position: from the spine across, from the top down.- let (x, y) = (pg.x - d.spreads[si].spine_x() + fx * pg.width, fy * pg.height);++ let (x, y) = (pg.x - sp.spine_x() + fx * pg.width, fy * pg.height);+ egui::Grid::new("ctl_page_xywh").num_columns(4).spacing(vec2(4.0, 4.0)).show(ui, |ui| {+ caption(ui, crate::i18n::tr(&lang, "X:"));+ // Pages don't move within their spread yet.+ ui.add_enabled_ui(false, |ui| measure(ui, "cpx", Some(x), units, 64.0));+ caption(ui, crate::i18n::tr(&lang, "W:"));+ if let Some(v) = measure(ui, "cpw", Some(pg.width), units, 64.0) {- let _ = app.run("layout.pageSize", json!({"pages": [n], "width": v, "anchor": anchor}));++ resize(app, json!({"width": v, "anchor": anchor}));+ }+ ui.end_row();+ caption(ui, crate::i18n::tr(&lang, "Y:"));+ ui.add_enabled_ui(false, |ui| measure(ui, "cpy", Some(y), units, 64.0));+ caption(ui, crate::i18n::tr(&lang, "H:"));+ if let Some(v) = measure(ui, "cph", Some(pg.height), units, 64.0) {- let _ = app.run("layout.pageSize", json!({"pages": [n], "height": v, "anchor": anchor}));++ resize(app, json!({"height": v, "anchor": anchor}));+ }+ ui.end_row();+ });+ vsep(ui);+ // Page-size preset and orientation.- page_preset_and_orientation(app, ui, &lang, (pg.width, pg.height), n, anchor);++ page_preset_and_orientation(app, ui, &lang, (pg.width, pg.height), anchor, resize);+ vsep(ui);- ui.vertical(|ui| {++ ui.add_enabled_ui(n.is_some(), |ui| {+ caption(ui, crate::i18n::tr(&lang, "Liquid Page Rule:"));+ let label = panels::interactive::liquid_rule_label(pg.liquid);- craft_ui::ComboBox::from_id_salt("ctl_page_rule").selected_text(crate::rtl::widget(ui, crate::i18n::tr(&lang, label))).width(150.0).show_ui(- ui,- |ui| {++ craft_ui::ComboBox::from_id_salt("ctl_page_rule")++ .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&lang, label)))++ .width(150.0)++ .show_ui(ui, |ui| {+ for (r, l) in panels::interactive::LIQUID_RULES {- if ui.selectable_label(pg.liquid == r, crate::rtl::widget(ui, crate::i18n::tr(&lang, l))).clicked() && pg.liquid != r {++ if ui.selectable_label(pg.liquid == r, crate::rtl::widget(ui, crate::i18n::tr(&lang, l))).clicked()++ && pg.liquid != r++ && let Some(n) = n++ {+ let _ = app.run("liquid.pageRule", json!({"rule": r, "pages": [n]}));+ }+ }- },- );++ })++ .response++ .accessible_name(crate::i18n::tr(&lang, "Liquid Page Rule:"));+ });+ vsep(ui);- ui.vertical(|ui| {++ ui.add_enabled_ui(n.is_some(), |ui| {+ let mut overlay = pg.show_parent_overlay;- if ui.checkbox(&mut overlay, crate::rtl::widget(ui, crate::i18n::tr(&lang, "Show Parent Page Overlay"))).changed() {++ if ui.checkbox(&mut overlay, crate::rtl::widget(ui, crate::i18n::tr(&lang, "Show Parent Page Overlay"))).changed()++ && let Some(n) = n++ {+ let _ = app.run("layout.pageOptions", json!({"pages": [n], "showParentOverlay": overlay}));+ }+ });+ }++ /// The Control panel's font sizes (and leadings), as InDesign lists them.+ const SIZES: &[f64] = &[6.0, 8.0, 9.0, 10.0, 11.0, 12.0, 14.0, 18.0, 24.0, 30.0, 36.0, 48.0, 60.0, 72.0];++ /// The Control panel's tracking values (1/1000 em).+ const TRACKING: &[f64] = &[-100.0, -75.0, -50.0, -25.0, -10.0, -5.0, 0.0, 5.0, 10.0, 25.0, 50.0, 75.0, 100.0, 200.0];++ /// Whether the text Control panel shows Paragraph Formatting Controls (¶) rather than Character+ /// Formatting Controls (A).+ const PARA_MODE: &str = "ctl_text_para_mode";++ /// An icon and a field after it, as the Control panel lays its fields out.+ pub(crate) fn icon_field(ui: &mut egui::Ui, icon: &str, tip: &str, field: NumField) -> Option<f64> {+ let t = Tokens::get(ui.ctx());+ let (r, resp) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover());+ icons::paint(ui.painter(), r, icon, t.icon);+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, tip));+ let label = resp.id;+ resp.on_hover_text(tip);+ field.spinner().labelled_by(label).show(ui)+ }++ /// A column of two rows (the Control panel's two-row groups).+ fn rows(ui: &mut egui::Ui, mut row: impl FnMut(&mut egui::Ui, usize)) {+ ui.vertical(|ui| {+ ui.spacing_mut().item_spacing.y = 3.0;+ ui.horizontal(|ui| row(ui, 0));+ ui.horizontal(|ui| row(ui, 1));+ });+ }++ /// A small toggle button showing `text` (the case and position buttons).+ fn text_toggle(ui: &mut egui::Ui, text: &str, strike: bool, on: bool, tip: &str) -> bool {+ let t = Tokens::get(ui.ctx());+ let (r, resp) = ui.allocate_exact_size(vec2(24.0, 20.0), Sense::click());+ if on {+ ui.painter().rect_filled(r, 2.0, t.tool_active);+ } else if resp.hovered() {+ ui.painter().rect_filled(r, 2.0, t.hover);+ }+ let col = if on { t.text_strong } else { t.icon };+ if text == "small-caps" {+ crate::icons::paint(ui.painter(), r, "small-caps", col);+ } else {+ ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, text, egui::FontId::proportional(13.0), col);+ }+ if strike {+ ui.painter().line_segment([r.center() + vec2(-6.0, 0.5), r.center() + vec2(6.0, 0.5)], Stroke::new(1.2, col));+ }+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, tip));+ resp.on_hover_text(tip).clicked()+ }++ /// The text Control panel, as InDesign's: A shows the Character Formatting Controls (font, size+ /// and leading, the case and position buttons, kerning and tracking, the scales, baseline shift+ /// and skew, the character style and language); ¶ the Paragraph Formatting Controls (alignment,+ /// the indents, space before and after, the drop cap, the paragraph style, Hyphenate and Align to+ /// Baseline Grid).+ fn control_text(app: &mut DesignApp, ui: &mut egui::Ui) {+ let t = Tokens::get(ui.ctx());+ let lang = app.ui.language.clone();+ let tr = |s: &str| crate::i18n::tr(&lang, s).to_string();+ let attrs = panels::text_attrs(app);+ let chars = attrs.as_ref().map(|a| a["chars"].clone()).unwrap_or_default();+ let para = attrs.as_ref().map(|a| a["para"].clone()).unwrap_or_default();+ let mode_id = egui::Id::unique(PARA_MODE);+ let para_mode = ui.data(|d| d.get_temp::<bool>(mode_id)).unwrap_or(false);+ ui.vertical(|ui| {+ ui.spacing_mut().item_spacing.y = 3.0;+ for (para, text, tip) in [(false, "A", "Character Formatting Controls"), (true, "¶", "Paragraph Formatting Controls")] {+ let on = para_mode == para;+ let (r, resp) = ui.allocate_exact_size(vec2(24.0, 22.0), Sense::click());+ if on {+ ui.painter().rect_filled(r, 2.0, t.tool_active);+ } else if resp.hovered() {+ ui.painter().rect_filled(r, 2.0, t.hover);+ }+ ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, text, semibold(15.0), if on { t.text_strong } else { t.text_dim });+ let tip = tr(tip);+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, &tip));+ if resp.on_hover_text(&tip).clicked() {+ ui.data_mut(|d| d.insert_temp(mode_id, para));+ }+ }+ });+ vsep(ui);+ if para_mode {+ control_paragraph(app, ui, &attrs, ¶, &tr);+ } else {+ control_character(app, ui, &attrs, &chars, ¶, &tr);+ }+ }++ /// Draw the character-mode controls and issue their corresponding text commands.+ fn control_character(+ app: &mut DesignApp,+ ui: &mut egui::Ui,+ attrs: &Option<serde_json::Value>,+ chars: &serde_json::Value,+ para: &serde_json::Value,+ tr: &dyn Fn(&str) -> String,+ ) {+ ui.vertical(|ui| {+ let fam = chars["fontFamily"].as_str().unwrap_or("").to_string();+ let sty = chars["fontStyle"].as_str().unwrap_or("").to_string();+ panels::font_family_picker(app, ui, &fam, 170.0);+ panels::font_style_picker(app, ui, &fam, &sty, 170.0);+ });+ vsep(ui);+ // Size and leading: a spinner on the left and a list of common values on the right;+ // automatic leading in parentheses.+ rows(ui, |ui, row| {+ if row == 0 {+ if let Some(v) = icon_field(+ ui,+ "font-size",+ &tr("Font Size"),+ NumField::number("csize", chars["size"].as_f64(), " pt", 2).width(84.0).presets(SIZES).range(0.1, 1296.0),+ ) {+ let _ = app.run("type.char", json!({"attrs": {"size": v}}));+ }+ } else {+ let auto = chars["leading"]["kind"].as_str() != Some("points");+ let lead = if auto {+ chars["size"].as_f64().map(|s| s * para["autoLeading"].as_f64().unwrap_or(1.2))+ } else {+ chars["leading"]["value"].as_f64()+ };+ let lead = lead.map(|v| (v * 100.0).round() / 100.0);+ let key = if auto { "cleadauto" } else { "clead" };+ if let Some(v) = icon_field(+ ui,+ "leading",+ &tr("Leading"),+ NumField::number(key, lead, " pt", 2).width(84.0).presets(SIZES).range(0.0, 5000.0).parens(auto),+ ) {+ let _ = app.run("type.char", json!({"attrs": {"leading": {"kind": "points", "value": v}}}));+ }+ }+ });+ vsep(ui);+ // All Caps, Superscript, Underline / Small Caps, Subscript, Strikethrough.+ let caps = chars["capitalization"].as_str().unwrap_or("normal").to_string();+ let pos = chars["position"].as_str().unwrap_or("normal").to_string();+ let (ul, st) = (chars["underline"].as_bool().unwrap_or(false), chars["strikethrough"].as_bool().unwrap_or(false));+ let mut set = None;+ rows(ui, |ui, row| {+ if row == 0 {+ if text_toggle(ui, "TT", false, caps == "allCaps", &tr("All Caps")) {+ set = Some(json!({"capitalization": if caps == "allCaps" { "normal" } else { "allCaps" }}));+ }+ if text_toggle(ui, "T¹", false, pos == "superscript", &tr("Superscript")) {+ set = Some(json!({"position": if pos == "superscript" { "normal" } else { "superscript" }}));+ }+ if text_toggle(ui, "T̲", false, ul, &tr("Underline")) {+ set = Some(json!({"underline": !ul}));+ }+ } else {+ if text_toggle(ui, "small-caps", false, caps == "smallCaps", &tr("Small Caps")) {+ set = Some(json!({"capitalization": if caps == "smallCaps" { "normal" } else { "smallCaps" }}));+ }+ if text_toggle(ui, "T₁", false, pos == "subscript", &tr("Subscript")) {+ set = Some(json!({"position": if pos == "subscript" { "normal" } else { "subscript" }}));+ }+ if text_toggle(ui, "T", true, st, &tr("Strikethrough")) {+ set = Some(json!({"strikethrough": !st}));+ }+ }+ });+ if let Some(a) = set {+ let _ = app.run("type.char", json!({"attrs": a}));+ }+ vsep(ui);+ rows(ui, |ui, row| {+ if row == 0 {+ let t = Tokens::get(ui.ctx());+ let (r, resp) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover());+ icons::paint(ui.painter(), r, "kerning", t.icon);+ resp.on_hover_text(tr("Kerning"));+ crate::panels::properties::kerning_control(app, ui, "ckern", &chars["kerning"], 92.0);+ } else {+ if let Some(v) = icon_field(+ ui,+ "tracking",+ &tr("Tracking"),+ NumField::number("ctrack", chars["tracking"].as_f64(), "", 0).width(92.0).presets(TRACKING).step(5.0).range(-1000.0, 10000.0),+ ) {+ let _ = app.run("type.char", json!({"attrs": {"tracking": v}}));+ }+ }+ });+ vsep(ui);+ const SCALES: &[f64] = &[25.0, 50.0, 75.0, 80.0, 90.0, 100.0, 110.0, 120.0, 125.0, 150.0, 200.0];+ let pct = |v: &serde_json::Value| v.as_f64().map(|s| (s * 1000.0).round() / 10.0);+ rows(ui, |ui, row| {+ if row == 0 {+ if let Some(v) = icon_field(+ ui,+ "vscale",+ &tr("Vertical Scale"),+ NumField::number("cvs", pct(&chars["vScale"]), "%", 1).width(84.0).presets(SCALES).range(1.0, 1000.0),+ ) {+ let _ = app.run("type.char", json!({"attrs": {"vScale": v / 100.0}}));+ }+ } else {+ if let Some(v) = icon_field(+ ui,+ "hscale",+ &tr("Horizontal Scale"),+ NumField::number("chs", pct(&chars["hScale"]), "%", 1).width(84.0).presets(SCALES).range(1.0, 1000.0),+ ) {+ let _ = app.run("type.char", json!({"attrs": {"hScale": v / 100.0}}));+ }+ }+ });+ vsep(ui);+ rows(ui, |ui, row| {+ if row == 0 {+ if let Some(v) = icon_field(+ ui,+ "baseline-shift",+ &tr("Baseline Shift"),+ NumField::number("cbs", chars["baselineShift"].as_f64(), " pt", 2).width(76.0).range(-5000.0, 5000.0),+ ) {+ let _ = app.run("type.char", json!({"attrs": {"baselineShift": v}}));+ }+ } else {+ if let Some(v) = icon_field(+ ui,+ "skew",+ &tr("Skew (False Italic)"),+ NumField::number("csk", chars["skew"].as_f64(), "°", 1).width(76.0).range(-85.0, 85.0),+ ) {+ let _ = app.run("type.char", json!({"attrs": {"skew": v}}));+ }+ }+ });+ vsep(ui);+ ui.vertical(|ui| {+ ui.spacing_mut().item_spacing.y = 3.0;+ // The character style, then the language.+ let cs = attrs.as_ref().and_then(|a| a["characterStyle"].as_str()).unwrap_or(designcraft_doc::NO_CHAR_STYLE).to_string();+ let names: Vec<String> = app.session.active().map(|d| d.doc.styles.character.iter().map(|c| c.name.clone()).collect()).unwrap_or_default();+ let mut pick = None;+ craft_ui::ComboBox::from_id_salt("ctl_char_style")+ .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, &cs)))+ .width(150.0)+ .show_ui(ui, |ui| {+ for n in &names {+ if ui.selectable_label(*n == cs, crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, n))).clicked() {+ pick = Some(n.clone());+ }+ }+ });+ if let Some(n) = pick {+ let _ = app.run("style.character.apply", json!({"name": n}));+ }+ let lang = chars["language"].as_str().unwrap_or("English: USA").to_string();+ craft_ui::ComboBox::from_id_salt("ctl_language").selected_text(crate::rtl::widget(ui, tr(&lang))).width(150.0).show_ui(ui, |ui| {+ egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| crate::panels::properties::language_menu(app, ui, &lang));+ });+ });+ }++ fn control_paragraph(+ app: &mut DesignApp,+ ui: &mut egui::Ui,+ attrs: &Option<serde_json::Value>,+ para: &serde_json::Value,+ tr: &dyn Fn(&str) -> String,+ ) {+ let cur: Align = serde_json::from_value(para["align"].clone()).unwrap_or_default();+ if let Some(a) = align_buttons(ui, cur, tr) {+ let _ = app.run("type.para", json!({"attrs": {"align": a}}));+ }+ vsep(ui);+ let units = app.session.active().map(|d| d.doc.settings.horizontal_units).unwrap_or(Unit::Picas);+ if let Some((k, v)) = indent_space_fields(ui, para, units, tr) {+ let _ = app.run("type.para", json!({"attrs": {k: v}}));+ }+ if let Some((k, v)) = drop_cap_fields(ui, para, tr) {+ let _ = app.run("type.para", json!({"attrs": {k: v.max(0.0) as u64}}));+ }+ vsep(ui);+ // Bulleted List over Numbered List, as InDesign's (a list with the default hanging indent, or,+ // pressed, none). Pressed when every selected paragraph has it, as Type › Apply Bullets shows.+ use designcraft_doc::ListType;+ let pressed = [ListType::Bullets, ListType::Numbers].map(|k| app.session.selection_has_list(k));+ let mut list = None;+ rows(ui, |ui, row| {+ let (icon, cmd, tip) = if row == 0 { ("bullets", "list.bullets", "Bulleted List") } else { ("numbering", "list.numbers", "Numbered List") };+ let on = pressed.get(row).copied().unwrap_or(false);+ if crate::widgets::icon_toggle(ui, icon, on, &tr(tip)).clicked() {+ list = Some((cmd, !on));+ }+ });+ if let Some((cmd, on)) = list {+ let _ = app.run(cmd, json!({"on": on}));+ }+ vsep(ui);+ let (shade, dialog) = shading_buttons(app, ui, para, tr);+ if let Some(attrs) = shade {+ let _ = app.run("type.para", json!({ "attrs": attrs }));+ }+ if let Some(tab) = dialog {+ let _ = app.run("app.paragraphBordersDialog", json!({ "tab": tab }));+ }+ vsep(ui);+ ui.vertical(|ui| {+ ui.spacing_mut().item_spacing.y = 3.0;+ let ps = attrs.as_ref().and_then(|a| a["paragraphStyle"].as_str()).unwrap_or("").to_string();+ let ov = attrs.as_ref().and_then(|a| a["paraOverrides"].as_u64()).unwrap_or(0)+ + attrs.as_ref().and_then(|a| a["charOverrides"].as_u64()).unwrap_or(0);+ panels::para_style_picker(app, ui, &ps, ov > 0, 170.0);+ ui.horizontal(|ui| {+ let mut h = para["hyphenate"].as_bool().unwrap_or(true);+ if crate::widgets::checkbox(ui, &mut h, &tr("Hyphenate")).changed() {+ let _ = app.run("type.para", json!({"attrs": {"hyphenate": h}}));+ }+ // First Line Only is aligned too: the button shows it pressed, and a click turns alignment off.+ let grid = matches!(para["gridAlign"].as_str(), Some("allLines" | "firstLineOnly"));+ if crate::widgets::icon_toggle(ui, "grid-baseline", grid, &tr("Align to Baseline Grid")).clicked() {+ let _ = app.run("type.para", json!({"attrs": {"gridAlign": if grid { "none" } else { "allLines" }}}));+ }+ });+ });+ }++ /// The paragraph alignment buttons, in two rows: the alignment picked this frame, if any.+ fn align_buttons(ui: &mut egui::Ui, cur: Align, tr: &dyn Fn(&str) -> String) -> Option<Align> {+ let mut align = None;+ rows(ui, |ui, row| {+ if row == 0 {+ for (a, icon) in [+ (Align::Left, "palign-left"),+ (Align::Center, "palign-center"),+ (Align::Right, "palign-right"),+ (Align::TowardsSpine, "palign-spine-towards"),+ ] {+ if icons::button(ui, icon, 20.0, cur == a, &tr(a.label())).clicked() {+ align = Some(a);+ }+ }+ } else {+ for (a, icon) in [+ (Align::LeftJustified, "palign-justify-left"),+ (Align::CenterJustified, "palign-justify-center"),+ (Align::RightJustified, "palign-justify-right"),+ (Align::FullyJustified, "palign-justify-all"),+ (Align::AwayFromSpine, "palign-spine-away"),+ ] {+ if icons::button(ui, icon, 20.0, cur == a, &tr(a.label())).clicked() {+ align = Some(a);+ }+ }+ }+ });+ align+ }++ /// The indents and space before and after, two per column. Returns the one field changed this+ /// frame, with its paragraph attribute and value.+ fn indent_space_fields(ui: &mut egui::Ui, para: &serde_json::Value, units: Unit, tr: &dyn Fn(&str) -> String) -> Option<(&'static str, f64)> {+ let mut set = None;+ for ((ia, ta, ka), (ib, tb, kb)) in [+ (("indent-left", "Left Indent", "leftIndent"), ("indent-first", "First Line Left Indent", "firstLineIndent")),+ (("indent-right", "Right Indent", "rightIndent"), ("indent-last", "Last Line Right Indent", "lastLineIndent")),+ (("space-before", "Space Before", "spaceBefore"), ("space-after", "Space After", "spaceAfter")),+ ] {+ rows(ui, |ui, row| {+ if row == 0 {+ if let Some(v) = icon_field(ui, ia, &tr(ta), NumField::measure(ka, para[ka].as_f64(), units).width(84.0).range(0.0, 10_000.0)) {+ set = Some((ka, v));+ }+ } else {+ let min = crate::panels::properties::para_field_min(kb);+ if let Some(v) = icon_field(ui, ib, &tr(tb), NumField::measure(kb, para[kb].as_f64(), units).width(84.0).range(min, 10_000.0)) {+ set = Some((kb, v));+ }+ }+ });+ vsep(ui);+ }+ set+ }++ /// The drop cap's line and character counts. Returns the one changed this frame, with its+ /// paragraph attribute and value.+ fn drop_cap_fields(ui: &mut egui::Ui, para: &serde_json::Value, tr: &dyn Fn(&str) -> String) -> Option<(&'static str, f64)> {+ let mut drop = None;+ rows(ui, |ui, row| {+ if row == 0 {+ let max = designcraft_compose::MAX_DROP_CAP_LINES as f64;+ if let Some(v) = icon_field(+ ui,+ "drop-lines",+ &tr("Drop Cap Number of Lines"),+ NumField::number("cdl", para["dropCapLines"].as_f64(), "", 0).width(64.0).range(0.0, max),+ ) {+ drop = Some(("dropCapLines", v));+ }+ } else {+ let max = designcraft_compose::MAX_DROP_CAP_CHARS as f64;+ if let Some(v) = icon_field(+ ui,+ "drop-chars",+ &tr("Drop Cap One or More Characters"),+ NumField::number("cdc", para["dropCapChars"].as_f64(), "", 0).width(64.0).range(0.0, max),+ ) {+ drop = Some(("dropCapChars", v));+ }+ }+ });+ drop+ }++ /// Shading over Border: the on/off checkboxes, the colour swatches and the Paragraph Borders and+ /// Shading buttons. Returns the attributes to set and the dialog tab to open, if any.+ fn shading_buttons(+ app: &DesignApp,+ ui: &mut egui::Ui,+ para: &serde_json::Value,+ tr: &dyn Fn(&str) -> String,+ ) -> (Option<serde_json::Value>, Option<&'static str>) {+ // On or off, the Paragraph Borders and Shading dialog on its tab, and the colour, as InDesign's.+ let doc = app.session.active().map(|d| d.doc.clone());+ let mut shade = None;+ let mut dialog = None;+ // Both checkboxes as wide as the wider label, so the icons and colours line up in columns.+ let check_w = ["Shading", "Border"]+ .iter()+ .map(|l| ui.fonts_mut(|f| f.layout_no_wrap(tr(l), egui::FontId::proportional(11.5), Color32::WHITE).size().x))+ .fold(0.0, f32::max)+ + 28.0;+ rows(ui, |ui, row| {+ let (on_key, color_key, label, icon, tab) = if row == 0 {+ ("shadingOn", "shadingColor", "Shading", "para-shading", "shading")+ } else {+ ("borderOn", "borderColor", "Border", "para-border", "border")+ };+ let mut on = para[on_key].as_bool().unwrap_or(false);+ ui.allocate_ui_with_layout(vec2(check_w, crate::widgets::FIELD_H), egui::Layout::left_to_right(egui::Align::Center), |ui| {+ ui.set_min_width(check_w);+ if crate::widgets::checkbox(ui, &mut on, &tr(label)).changed() {+ shade = Some(json!({ on_key: on }));+ }+ });+ if crate::widgets::icon_toggle(ui, icon, false, &tr("Paragraph Borders and Shading…")).clicked() {+ dialog = Some(tab);+ }+ if let Some(doc) = &doc {+ let cur = para[color_key].as_str().unwrap_or("[Black]").to_string();+ if let Some(w) = swatch_field(ui, doc, &cur, 96.0, &tr(if row == 0 { "Paragraph Shading" } else { "Paragraph Border" })) {+ shade = Some(json!({ color_key: w }));+ }+ }+ });+ (shade, dialog)+ }++ /// A swatch field of the Control panel (Shading and Border colours): the swatch's chip and name,+ /// and the document's swatches in its menu. Returns the swatch picked.+ pub(crate) fn swatch_field(ui: &mut egui::Ui, doc: &designcraft_doc::Document, cur: &str, width: f32, label: &str) -> Option<String> {+ let t = Tokens::get(ui.ctx());+ let (r, resp) = ui.allocate_exact_size(vec2(width, crate::widgets::FIELD_H), Sense::click());+ let resp = resp.on_hover_text(label);+ resp.widget_info(|| {+ let mut info = egui::WidgetInfo::labeled(egui::Role::ComboBox, true, label);+ info.current_text_value = Some(cur.to_string());+ info+ });+ let p = ui.painter();+ p.rect_filled(r, 0.0, if resp.hovered() { t.hover } else { t.input });+ p.rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);+ let seg = egui::Rect::from_min_max(egui::pos2(r.max.x - crate::widgets::SEG_W, r.min.y), r.max);+ p.line_segment([seg.left_top(), seg.left_bottom()], Stroke::new(1.0, t.field_border));+ icons::paint(p, egui::Rect::from_center_size(seg.center(), vec2(12.0, 12.0)), "chevron-down", t.icon);+ let (c, g) = crate::widgets::swatch_colors(doc, cur, 1.0);+ let chip = egui::Rect::from_min_size(egui::pos2(r.min.x + 4.0, r.center().y - 6.0), vec2(12.0, 12.0));+ crate::widgets::paint_chip(p, chip, c, g);+ let clip = egui::Rect::from_min_max(r.min, egui::pos2(seg.min.x - 2.0, r.max.y));+ p.with_clip_rect(clip).text(egui::pos2(chip.max.x + 5.0, r.center().y), egui::Align2::LEFT_CENTER, cur, egui::FontId::proportional(11.5), t.text);+ let mut picked = None;+ egui::Popup::menu(&resp).show(|ui| {+ picked = crate::panels::swatch_list(ui, doc, cur);+ });+ picked+ }diff --cc crates/ui-egui/src/chrome/tests.rsindex 000000000,742aba403..73a943330mode 000000,100644..100644--- a/crates/ui-egui/src/chrome/tests.rs+++ b/crates/ui-egui/src/chrome/tests.rs@@@ -1,0 -1,913 +1,1011 @@@+ /// A Control panel field is labelled by its icon, so assistive technology reads "Tracking"+ /// (or "Font Size", …) with the value.+ #[test]+ fn icon_fields_are_labelled_by_their_icon() {+ use egui::accesskit::Role;+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx, "en");+ ctx.enable_accesskit();+ let mut update = None;+ for _ in 0..2 {+ let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {+ icon_field(ui, "tracking", "Tracking", NumField::number("tracking_test", Some(0.0), "", 0));+ });+ out.textures_delta.clear();+ update = out.platform_output.accesskit_update;+ }+ let update = update.expect("an AccessKit tree");+ let named = |n: &egui::accesskit::Node| n.label() == Some("Tracking") || n.value() == Some("Tracking");+ let icon = update.nodes.iter().find(|(_, n)| named(n)).map(|(id, _)| *id).expect("the icon's node");+ assert!(update.nodes.iter().any(|(_, n)| n.role() == Role::TextInput && n.labelled_by().contains(&icon)), "the editor names its icon");+ }+ use egui::{pos2, vec2};+ use egui_kittest::kittest::{NodeT, Queryable};++ use super::*;+ use crate::test_window::{self, wheel};++ /// The Control panel's last control with no text frame selected.+ const LAST_CONTROL: &str = "Align bottom edges";+ const FIRST_CONTROL: &str = "Rotate 90° Counterclockwise";++ /// The start screen and Open Recent menu look a recent file up on disk at most every few+ /// seconds, not every frame.+ #[test]+ fn recent_files_are_looked_up_on_disk_every_few_seconds() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("a.designcraft");+ std::fs::write(&path, b"x").unwrap();+ let path = path.to_string_lossy().to_string();+ let ctx = egui::Context::default();+ let first = super::recent_file_stat_at(&ctx, &path, 10_000.0);+ assert!(first.exists && first.modified.is_some());+ std::fs::remove_file(&path).unwrap();+ assert_eq!(super::recent_file_stat_at(&ctx, &path, 10_000.0 + super::RECENT_STAT_MS - 1.0), first, "cached");+ assert!(!super::recent_file_stat_at(&ctx, &path, 10_000.0 + super::RECENT_STAT_MS).exists, "looked up again");+ }++ fn app() -> crate::DesignApp {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.control_bar = true;+ app+ }++ /// A document with a rectangle selected, so the object controls are enabled.+ fn app_with_selection() -> crate::DesignApp {+ let mut app = app();+ app.run("file.new", serde_json::json!({})).unwrap();+ app.run("frame.create", serde_json::json!({"rect": [72, 72, 300, 200]})).unwrap();+ app.run("edit.selectAll", serde_json::json!({})).unwrap();+ app+ }++ /// The rect of an object Control panel group.+ fn group(h: &egui_kittest::Harness<'static, test_window::Window>, id: &str) -> egui::Rect {+ h.ctx.read_response(egui::Id::unique(("object_control", id))).unwrap().rect+ }++ /// The rect of the node with this label, preferring the one in the Control bar's row: the+ /// Properties panel has buttons with the same names.+ fn rect(h: &egui_kittest::Harness<'static, test_window::Window>, label: &str) -> egui::Rect {+ let bar = test_window::panel_rect(h, "control_bar");+ h.query_all_by_label(label).map(|n| n.rect()).find(|r| bar.y_range().contains(r.center().y)).unwrap_or_else(|| h.get_by_label(label).rect())+ }++ /// The application bar's search field (German interface).+ fn search_node<'h>(h: &'h egui_kittest::Harness<'static, test_window::Window>) -> egui_kittest::Node<'h> {+ h.get_by(|n| n.role() == egui::accesskit::Role::TextInput && n.placeholder() == Some(crate::i18n::tr("de", "Search")))+ }++ /// A document with two frames, the Selection tool, German menus, and the search field clicked.+ fn searching() -> egui_kittest::Harness<'static, test_window::Window> {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.language = "de".into();+ let mut h = test_window::open(app, vec2(1440.0, 900.0));+ let app = &mut h.state_mut().app;+ app.run("frame.create", serde_json::json!({"rect": [36, 36, 200, 200]})).unwrap();+ app.run("frame.create", serde_json::json!({"rect": [236, 36, 400, 200]})).unwrap();+ app.run("edit.deselectAll", serde_json::json!({})).unwrap();+ h.run_steps(4);+ let field = search_node(&h).rect();+ test_window::click_at(&mut h, field.center());+ assert!(h.ctx.memory(|m| m.has_focus(super::search_id())), "a click gives the field the keyboard");+ h+ }++ /// A match in the search's list, whose accessible label ends in its shortcut.+ fn row<'h>(h: &'h egui_kittest::Harness<'static, test_window::Window>, label: &'static str) -> Option<egui_kittest::Node<'h>> {+ h.query_by(move |n| n.label().is_some_and(|l| l == label || l.starts_with(&format!("{label} "))))+ }++ fn items(h: &egui_kittest::Harness<'static, test_window::Window>) -> (usize, usize) {+ let d = h.state().app.session.active().unwrap();+ (d.doc.spreads.iter().flat_map(|sp| &sp.items).count(), d.selection.items.len())+ }++ #[test]+ fn the_search_field_finds_and_runs_menu_commands() {+ let mut h = searching();+ let group = crate::i18n::tr("de", "Group");+ h.event(egui::Event::Text(group.to_lowercase()));+ h.run_steps(4);+ assert!(row(&h, group).is_some(), "the German label is listed");+ // Nothing is selected, so Group is off and Return doesn't run it.+ assert!(row(&h, group).is_some_and(|n| n.accesskit_node().is_disabled()));+ h.key_press(egui::Key::Enter);+ h.run_steps(4);+ assert_eq!(items(&h), (2, 0), "a disabled command doesn't run");+ // Select both frames, then ↓ ↑ Return runs the first match, as Object › Group would.+ h.state_mut().app.run("edit.selectAll", serde_json::json!({})).unwrap();+ h.key_press(egui::Key::ArrowDown);+ h.run_steps(2);+ h.key_press(egui::Key::ArrowUp);+ h.run_steps(2);+ h.key_press(egui::Key::Enter);+ h.run_steps(4);+ assert_eq!(items(&h).0, 1, "the two frames are grouped");+ assert!(row(&h, group).is_none(), "the matches closed");+ assert!(!h.ctx.memory(|m| m.has_focus(super::search_id())), "the field gave the keyboard back");+ }++ #[test]+ fn keys_typed_in_the_search_field_stay_out_of_the_document() {+ let mut h = searching();+ h.state_mut().app.run("edit.selectAll", serde_json::json!({})).unwrap();+ // Escape would switch this tool back to the Selection tool.+ h.state_mut().app.run("tool.select", serde_json::json!({"tool": "rectangleFrame"})).unwrap();+ h.run_steps(2);+ // Tool keys, Delete and Backspace edit the query; the tool and the frames stay.+ for key in [egui::Key::P, egui::Key::T, egui::Key::M, egui::Key::Delete, egui::Key::Backspace] {+ h.key_press(key);+ h.run_steps(2);+ }+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);+ h.run_steps(2);+ assert_eq!(h.state().app.session.tool_id(), "rectangleFrame");+ assert_eq!(items(&h), (2, 2), "nothing was deleted or deselected");+ h.event(egui::Event::Text("zz-no-such-command".into()));+ h.run_steps(4);+ assert!(h.query_by_label(crate::i18n::tr("de", "No matching commands")).is_some());+ // Escape closes the matches and clears the field without touching the document.+ h.key_press(egui::Key::Escape);+ h.run_steps(4);+ assert!(h.query_by_label(crate::i18n::tr("de", "No matching commands")).is_none());+ assert!(!h.ctx.text_edit_focused());+ assert_eq!(h.state().app.session.tool_id(), "rectangleFrame");+ assert_eq!(items(&h), (2, 2));+ let field = search_node(&h);+ assert_eq!(field.value().unwrap_or_default(), "", "the query is cleared");+ }++ /// The status bar's preflight count is a menu; its Preflight Panel entry shows the panel.+ #[test]+ fn status_bar_error_count_opens_the_preflight_panel() {+ let mut app = app();+ app.run("file.new", serde_json::json!({})).unwrap();+ app.ui.dock_tab = "properties".into();+ let mut h = test_window::open(app, vec2(1200.0, 700.0));+ h.get_by_label("No errors ▾").click();+ h.run_steps(3);+ h.get_by_label("Preflight Panel…").click();+ h.run_steps(3);+ // Preflight is in the iconic column: `window.panel` shows it.+ assert!(crate::panel_docking::showing(&h.state().app, "preflight"));+ assert!(h.query_all_by_label("Preflight").count() >= 2, "its icon and its tab in the flyout");+ // With the panel already showing, the entry keeps it open.+ h.get_by_label("No errors ▾").click();+ h.run_steps(3);+ h.get_by_label("Preflight Panel…").click();+ h.run_steps(3);+ assert!(crate::panel_docking::showing(&h.state().app, "preflight"));+ }++ /// The course's chapter 25: while a parent is shown, the status bar's page box names it+ /// ("A-Parent"), as InDesign's. Its menu lists the pages, then the parents: a parent shows+ /// that parent, a page leaves the parents for that page.+ #[test]+ fn the_page_box_names_the_parent_in_view_and_lists_the_parents() {+ use egui::accesskit::Role;+ let mut app = app();+ app.run("file.new", serde_json::json!({"pages": 4, "facingPages": true})).unwrap();+ app.run("layout.parents.new", serde_json::json!({"prefix": "B", "name": "Cover"})).unwrap();+ app.ui.dock_tab = "properties".into();+ let mut h = test_window::open(app, vec2(1200.0, 700.0));+ let shown = |h: &egui_kittest::Harness<'static, test_window::Window>| {+ let b = h.get_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Page"));+ b.value().unwrap_or_default()+ };+ assert_eq!(shown(&h), "1");+ h.state_mut().app.run("layout.parents.edit", serde_json::json!({"on": true})).unwrap();+ h.run_steps(6);+ assert_eq!(shown(&h), "A-Parent");+ // The menu: a parent.+ h.get_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Page")).click();+ h.run_steps(3);+ for name in ["1", "2", "3", "4", "A-Parent"] {+ // The canvas or a panel may show the name too: the menu lists it.+ assert!(h.query_all_by_label(name).next().is_some(), "{name} is listed");+ }+ // The menu, drawn last, holds the last match.+ h.get_all_by_label("B-Cover").last().unwrap().click();+ h.run_steps(6);+ assert_eq!(shown(&h), "B-Cover");+ assert_eq!(crate::canvas::current_parent_page(&h.state().app).map(|(i, _)| i), Some(1));+ // A page: the parents are left.+ h.get_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Page")).click();+ h.run_steps(3);+ h.get_all_by_label("3").last().unwrap().click();+ h.run_steps(6);+ assert!(!h.state().app.session.active().unwrap().editing_parents);+ assert_eq!(crate::canvas::current_page(&h.state().app), Some(2));+ assert_eq!(shown(&h), "3");+ // Its accessible name is in the interface's language.+ h.state_mut().app.ui.language = "de".into();+ h.run_steps(3);+ assert!(h.query_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Seite")).is_some(), "the page box is Seite");+ }++ /// As in InDesign, double-clicking the preflight count (or its light) shows the panel.+ #[test]+ fn double_clicking_the_status_bar_error_count_opens_the_preflight_panel() {+ let mut app = app();+ app.run("file.new", serde_json::json!({})).unwrap();+ app.ui.dock_tab = "properties".into();+ let mut h = test_window::open_stepped(app, vec2(1200.0, 700.0), 1.0, 1.0 / 60.0);+ let count = h.get_by_label("No errors ▾");+ count.click();+ count.click();+ h.run_steps(3);+ assert!(crate::panel_docking::showing(&h.state().app, "preflight"));+ assert!(h.query_all_by_label("Preflight").count() >= 2, "its icon and its tab in the flyout");+ assert!(h.query_by_label("Preflight Panel…").is_none(), "the menu isn't left open");+ // A double-click with the panel already showing keeps it open (the first click closes+ // its flyout, the double-click opens it again). Past the double-click time, so the+ // clicks are not counted with the ones before.+ h.run_steps(30);+ let count = h.get_by_label("No errors ▾");+ count.click();+ count.click();+ h.run_steps(3);+ assert!(crate::panel_docking::showing(&h.state().app, "preflight"));+ }++ /// A very long document name made its tab grow past the window, hiding the close button+ /// and the tabs after it (#603).+ #[test]+ fn long_document_names_keep_tabs_short_and_close_buttons_visible() {+ let latin = "Quarterly report with a very long file name ".repeat(6);+ let hebrew = "דוח רבעוני עם שם קובץ ארוך מאוד ".repeat(6);+ // Use the bundled or pinned test face; optional-input builds without either skip+ // the Hebrew tab explicitly instead of rendering tofu under the strict glyph policy.+ let hebrew_ok = test_window::install_test_hebrew_face();+ if !hebrew_ok {+ eprintln!("skipped the Hebrew tab: set DESIGNCRAFT_TEST_HEBREW_FONT to the pinned NotoSansHebrew.ttf");+ }+ let mut app = app();+ app.run("file.new", serde_json::json!({ "title": latin })).unwrap();+ if hebrew_ok {+ app.run("file.new", serde_json::json!({ "title": hebrew })).unwrap();+ }+ app.run("file.new", serde_json::json!({ "title": "Short" })).unwrap();+ let h = test_window::open(app, vec2(1200.0, 600.0));+ let titles = if hebrew_ok { vec![latin.as_str(), hebrew.as_str()] } else { vec![latin.as_str()] };+ for title in titles {+ let tab = rect(&h, title);+ assert!(tab.width() <= super::DOC_TAB_MAX_W, "{title:?} tab is {} wide", tab.width());+ let close = rect(&h, &format!("Close {title}"));+ assert!(tab.contains_rect(close), "close button {close:?} outside its tab {tab:?}");+ }+ let (first, short) = (rect(&h, &latin), rect(&h, "Short"));+ assert!(short.min.x - first.min.x <= 2.0 * super::DOC_TAB_MAX_W, "the last tab {short:?} starts too far right");+ }++ /// Zero2Graphic's page layout video (0:48): with the Type tool, the Control panel's font size+ /// has a list of sizes; the instructor picks 72 pt from it. Leading has the same list.+ #[test]+ fn the_type_control_panel_lists_font_sizes_and_leadings() {+ let mut app = app();+ app.run("file.new", serde_json::json!({})).unwrap();+ let f = app.run("frame.create", serde_json::json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Headline"})).unwrap();+ app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 8})).unwrap();+ app.session.set_tool("type");+ let mut h = test_window::open(app, vec2(1800.0, 700.0));+ let bar = test_window::panel_rect(&h, "control_bar");+ let in_bar = |r: &egui::Rect| bar.y_range().contains(r.center().y);+ let field = |h: &egui_kittest::Harness<'static, test_window::Window>, value: &str| {+ h.query_all_by_value(value).map(|n| n.rect()).find(in_bar).unwrap_or_else(|| panic!("no {value:?} field in the Control panel"))+ };+ let press = |h: &mut egui_kittest::Harness<'static, test_window::Window>, p: egui::Pos2| {+ h.hover_at(p);+ h.drag_at(p);+ h.drop_at(p);+ };+ let size_of = |h: &egui_kittest::Harness<'static, test_window::Window>| {+ let st = h.state().app.session.doc().unwrap();+ let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap());+ st.doc.story(sid).unwrap().format_after(0).over.size+ };+ // The ⌄ segment right of the size field opens the list; choosing 72 pt sets the size.+ let size = field(&h, "12 pt");+ let chevron = pos2(size.max.x + 1.0 + crate::widgets::SEG_W / 2.0, size.center().y);+ press(&mut h, chevron);+ h.run_steps(3);+ h.get_by_label("72 pt").click();+ h.run_steps(3);+ assert_eq!(size_of(&h), Some(72.0));+ // Auto leading shows in parentheses, with the same list beside it.+ let lead = field(&h, "(86.4 pt)");+ press(&mut h, pos2(lead.max.x + 1.0 + crate::widgets::SEG_W / 2.0, lead.center().y));+ h.run_steps(3);+ h.get_by_label("60 pt").click();+ h.run_steps(3);+ let st = h.state().app.session.doc().unwrap();+ let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap());+ assert_eq!(st.doc.story(sid).unwrap().format_after(0).over.leading, Some(designcraft_doc::Leading::Points(60.0)));+ // The spinner left of the size steps it by a point.+ let size = field(&h, "72 pt");+ press(&mut h, pos2(size.min.x - 5.0 - crate::widgets::SEG_W / 2.0, size.min.y + 3.0));+ h.run_steps(3);+ assert_eq!(size_of(&h), Some(73.0));+ // Typing the automatic value itself over "(87.6 pt)" fixes the leading at it.+ h.state_mut().app.run("type.char", serde_json::json!({"attrs": {"leading": {"kind": "auto"}}})).unwrap();+ h.run_steps(3);+ let lead = field(&h, "(87.6 pt)");+ press(&mut h, lead.center());+ h.run_steps(2);+ h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });+ h.event(egui::Event::Text("87.6".into()));+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ let st = h.state().app.session.doc().unwrap();+ let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap());+ assert_eq!(st.doc.story(sid).unwrap().format_after(0).over.leading, Some(designcraft_doc::Leading::Points(87.6)));+ // Escape cancels: the same typing, then Escape, leaves the leading automatic.+ h.state_mut().app.run("type.char", serde_json::json!({"attrs": {"leading": {"kind": "auto"}}})).unwrap();+ h.run_steps(3);+ let auto = h.state().app.session.doc().unwrap().doc.story(sid).unwrap().format_after(0).over.leading;+ let lead = field(&h, "(87.6 pt)");+ press(&mut h, lead.center());+ h.run_steps(2);+ h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });+ h.event(egui::Event::Text("87.6".into()));+ h.key_press(egui::Key::Escape);+ h.run_steps(3);+ assert_eq!(h.state().app.session.doc().unwrap().doc.story(sid).unwrap().format_after(0).over.leading, auto, "Escape leaves it automatic");+ // Escape also reverts a different number, in the leading field and in a plain one. (It+ // leaves the text too, so each try selects it again.)+ for (shown, typed) in [("(87.6 pt)", "20"), ("73 pt", "50")] {+ h.state_mut().app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 8})).unwrap();+ h.state_mut().app.session.set_tool("type");+ h.run_steps(3);+ let r = field(&h, shown);+ press(&mut h, r.center());+ h.run_steps(2);+ h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });+ h.event(egui::Event::Text(typed.into()));+ h.key_press(egui::Key::Escape);+ h.run_steps(3);+ }+ assert_eq!(h.state().app.session.doc().unwrap().doc.story(sid).unwrap().format_after(0).over.leading, auto, "still automatic");+ assert_eq!(size_of(&h), Some(73.0), "the size is unchanged");+ }++ /// The Control panel's ¶ mode on a First Line Only paragraph: Align to Baseline Grid shows+ /// pressed, and a click turns alignment off instead of making it All Lines.+ #[test]+ fn the_control_panel_grid_button_keeps_first_line_only() {+ use egui_kittest::kittest::{NodeT, Queryable};+ let mut app = app();+ app.run("file.new", serde_json::json!({})).unwrap();+ let f = app.run("frame.create", serde_json::json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Bulbs"})).unwrap();+ app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 5})).unwrap();+ app.run("type.para", serde_json::json!({"attrs": {"gridAlign": "firstLineOnly"}})).unwrap();+ app.session.set_tool("type");+ let mut h = test_window::open(app, vec2(2400.0, 700.0));+ let bar = test_window::panel_rect(&h, "control_bar");+ let in_bar = move |r: egui::Rect| bar.y_range().contains(r.center().y);+ let click = |h: &mut egui_kittest::Harness<'static, test_window::Window>, label: &str| {+ let r = h.query_all_by_label(label).map(|n| n.rect()).find(|r| in_bar(*r)).unwrap_or_else(|| panic!("no {label:?} in the Control panel"));+ h.hover_at(r.center());+ h.drag_at(r.center());+ h.drop_at(r.center());+ h.run_steps(3);+ };+ click(&mut h, "Paragraph Formatting Controls");+ let pressed = h.query_all_by_label("Align to Baseline Grid").find(|n| in_bar(n.rect())).map(|n| n.accesskit_node().toggled());+ assert_eq!(pressed, Some(Some(egui::accesskit::Toggled::True)));+ assert_eq!(crate::panels::text_attrs(&mut h.state_mut().app).unwrap()["para"]["gridAlign"], "firstLineOnly");+ click(&mut h, "Align to Baseline Grid");+ assert_eq!(crate::panels::text_attrs(&mut h.state_mut().app).unwrap()["para"]["gridAlign"], "none");+ }++ /// The course's chapter 16: the text Control panel has InDesign's two modes. A shows the+ /// Character Formatting Controls (the case buttons, kerning and tracking, the scales…), ¶ the+ /// Paragraph Formatting Controls (alignment, indents, spacing, the drop cap…).+ #[test]+ fn the_type_control_panel_has_character_and_paragraph_modes() {+ let mut app = app();+ app.run("file.new", serde_json::json!({})).unwrap();+ let f = app.run("frame.create", serde_json::json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Bulbs"})).unwrap();+ app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 5})).unwrap();+ app.session.set_tool("type");+ let mut h = test_window::open(app, vec2(2400.0, 700.0));+ let bar = test_window::panel_rect(&h, "control_bar");+ let in_bar = move |r: egui::Rect| bar.y_range().contains(r.center().y);+ let click = |h: &mut egui_kittest::Harness<'static, test_window::Window>, label: &str| {+ let r = h.query_all_by_label(label).map(|n| n.rect()).find(|r| in_bar(*r)).unwrap_or_else(|| panic!("no {label:?} in the Control panel"));+ h.hover_at(r.center());+ h.drag_at(r.center());+ h.drop_at(r.center());+ h.run_steps(3);+ };+ let has = |h: &egui_kittest::Harness<'static, test_window::Window>, label: &str| h.query_all_by_label(label).any(|n| in_bar(n.rect()));+ assert!(has(&h, "Small Caps") && has(&h, "Vertical Scale") && !has(&h, "Drop Cap Number of Lines"));+ click(&mut h, "Small Caps");+ click(&mut h, "Paragraph Formatting Controls");+ assert!(has(&h, "Drop Cap Number of Lines") && has(&h, "Space Before") && !has(&h, "Small Caps"));+ click(&mut h, "Align to Baseline Grid");+ click(&mut h, "Align center");+ let a = crate::panels::text_attrs(&mut h.state_mut().app).unwrap();+ assert_eq!(a["chars"]["capitalization"], "smallCaps");+ assert_eq!(a["para"]["gridAlign"], "allLines");+ assert_eq!(a["para"]["align"], "center");+ click(&mut h, "Character Formatting Controls");+ assert!(has(&h, "Small Caps"));+ }++ /// The course's chapter 21: the ¶ Control panel has InDesign's Bulleted and Numbered List+ /// buttons (with the default hanging indent), and Shading and Border with their colours and+ /// the Paragraph Borders and Shading dialog.+ #[test]+ fn the_paragraph_control_panel_has_lists_shading_and_border() {+ let mut app = app();+ app.run("file.new", serde_json::json!({})).unwrap();+ let f = app+ .run(+ "frame.create",+ serde_json::json!({"rect": [72, 72, 400, 300], "content": "text", "text": "4 eggs+ 1 cup milk"}),+ )+ .unwrap();+ app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 15})).unwrap();+ app.session.set_tool("type");+ let mut h = test_window::open(app, vec2(2400.0, 700.0));+ let bar = test_window::panel_rect(&h, "control_bar");+ let in_bar = move |r: egui::Rect| bar.y_range().contains(r.center().y);+ let click = |h: &mut egui_kittest::Harness<'static, test_window::Window>, label: &str, nth: usize| {+ let r = h+ .query_all_by_label(label)+ .map(|n| n.rect())+ .filter(|r| in_bar(*r))+ .nth(nth)+ .unwrap_or_else(|| panic!("no {label:?} in the Control panel"));+ h.hover_at(r.center());+ h.drag_at(r.center());+ h.drop_at(r.center());+ h.run_steps(3);+ };+ click(&mut h, "Paragraph Formatting Controls", 0);+ click(&mut h, "Bulleted List", 0);+ let a = crate::panels::text_attrs(&mut h.state_mut().app).unwrap();+ assert_eq!(+ (a["para"]["listType"].as_str(), a["para"]["leftIndent"].as_f64(), a["para"]["firstLineIndent"].as_f64()),+ (Some("bullets"), Some(18.0), Some(-18.0))+ );+ click(&mut h, "Numbered List", 0);+ assert_eq!(crate::panels::text_attrs(&mut h.state_mut().app).unwrap()["para"]["listType"], "numbers");+ click(&mut h, "Shading", 0);+ click(&mut h, "Border", 0);+ let a = crate::panels::text_attrs(&mut h.state_mut().app).unwrap();+ assert_eq!((a["para"]["shadingOn"].as_bool(), a["para"]["borderOn"].as_bool()), (Some(true), Some(true)));+ assert!(h.query_all_by_label("Paragraph Shading").any(|n| in_bar(n.rect())), "the shading colour");+ // The icon beside Border opens the dialog on its Border tab.+ click(&mut h, "Paragraph Borders and Shading…", 1);+ let d = h.state().app.ui.dialog.clone().expect("the dialog");+ assert_eq!((d.id.as_str(), d.s("section").as_str()), ("paragraphLocal", "border"));+ // The Last Line Right Indent takes a negative value, as the First Line Left Indent does.+ h.state_mut().app.ui.dialog = None;+ h.state_mut().app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 15})).unwrap();+ h.state_mut().app.session.set_tool("type");+ h.run_steps(3);+ // The field is labelled by its icon.+ let at = h+ .query_all_by_label("Last Line Right Indent")+ .filter(|n| n.accesskit_node().role() == egui::accesskit::Role::TextInput)+ .map(|n| n.rect())+ .find(|r| in_bar(*r))+ .expect("the last line indent")+ .center();+ h.hover_at(at);+ h.drag_at(at);+ h.drop_at(at);+ h.run_steps(2);+ h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });+ h.event(egui::Event::Text("-0p6".into()));+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ assert_eq!(crate::panels::text_attrs(&mut h.state_mut().app).unwrap()["para"]["lastLineIndent"].as_f64(), Some(-6.0));+ }++ #[test]+ fn the_page_tool_has_its_own_control_panel() {+ // Chris Cicchino's Page Tool and Liquid Layout video (1:02): with the Page tool, the+ // Control panel shows the page's size, preset, orientation and liquid page rule.+ let mut app = app();+ app.run("file.new", serde_json::json!({"width": 252, "height": 144, "facingPages": false})).unwrap();+ app.session.set_tool("page");+ let mut h = test_window::open(app, vec2(1800.0, 600.0));- let _ = h.get_by_label("Liquid Page Rule:");++ let _ = h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Liquid Page Rule:");+ // Pages don't move within their spread, so there is no "Objects Move with Page" option, and+ // no "Controlled by Parent" rule until parent pages have rules of their own.+ assert!(h.query_by_label("Objects Move with Page").is_none());+ assert!(!crate::panels::interactive::LIQUID_RULES.iter().any(|(r, _)| *r == designcraft_doc::LiquidRule::ControlledByParent));+ assert_eq!(crate::panels::properties::preset_name(252.0, 144.0), "US Business Card");+ h.get_by_label("Show Parent Page Overlay").click();+ h.run_steps(4);+ assert!(h.state().app.session.doc().unwrap().doc.spreads[0].pages[0].show_parent_overlay);+ }++ #[test]+ fn a_narrow_window_scrolls_the_control_bar() {+ let w = 700.0;+ let mut h = test_window::open(app_with_selection(), vec2(w, 600.0));+ let bar = test_window::panel_rect(&h, "control_bar");+ assert!(rect(&h, LAST_CONTROL).max.x > w, "the controls are wider than the window");+ // A plain mouse wheel scrolls the bar sideways.+ let first = rect(&h, FIRST_CONTROL).center();+ wheel(&mut h, first, vec2(0.0, -3000.0));+ let last = rect(&h, LAST_CONTROL);+ let window = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(w, 600.0));+ assert!(window.contains_rect(last) && bar.contains_rect(last), "{last:?} outside the bar {bar:?}");+ assert_eq!(test_window::panel_rect(&h, "control_bar").height(), bar.height(), "the bar keeps its height");+ // A popup opened from a scrolled control opens at that control.+ let appearance = group(&h, "appearance");+ let fill = egui::Rect::from_min_size(appearance.min, vec2(30.0, crate::widgets::FIELD_H));+ let chip = pos2(fill.min.x + 9.0, fill.center().y);+ h.hover_at(chip);+ h.drag_at(chip);+ h.drop_at(chip);+ h.run_steps(4);+ let item = rect(&h, "[Black]");+ assert!(item.min.y > fill.max.y && (item.min.x - chip.x).abs() < 120.0, "popup item at {item:?}, control at {chip:?}");+ }++ #[test]+ fn the_mac_app_bar_centres_and_clears_the_traffic_lights() {+ use super::{MAC_APP_BAR, MAC_CONTENT_LEFT, MAC_LIGHT, MAC_LIGHT_PITCH, MAC_LIGHTS_LEFT};+ // Content keeps the same gap after the lights as the lights keep from the top.+ let margin = (MAC_APP_BAR - MAC_LIGHT) / 2.0;+ assert_eq!(MAC_CONTENT_LEFT - (MAC_LIGHTS_LEFT + 2.0 * MAC_LIGHT_PITCH + MAC_LIGHT), margin);+ // `egui::Margin` is in `i8`.+ assert!(MAC_CONTENT_LEFT <= f32::from(i8::MAX));+ let mut app = app();+ app.integrated_titlebar = true;+ let h = test_window::open(app, vec2(1400.0, 900.0));+ // The bar's controls share the lights' centre line and start after them (relative to the+ // bar, which the test window insets).+ let bar = test_window::panel_rect(&h, "app_bar").min.to_vec2();+ let home = rect(&h, "Home").translate(-bar);+ assert_eq!(home.center().y, MAC_APP_BAR / 2.0, "{home:?}");+ assert!(home.min.y >= 2.0 && home.min.x >= MAC_CONTENT_LEFT, "{home:?}");+ for label in ["File", "Help", "Share"] {+ let r = rect(&h, label).translate(-bar);+ assert!((r.center().y - MAC_APP_BAR / 2.0).abs() <= 0.5 && r.max.y <= MAC_APP_BAR, "{label} at {r:?}");+ }+ }++ fn press(h: &egui_kittest::Harness<'static, test_window::Window>, pos: egui::Pos2, pressed: bool) {+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });+ }++ /// The window commands the app sends over the next `steps` frames.+ fn window_commands(h: &mut egui_kittest::Harness<'static, test_window::Window>, steps: usize) -> Vec<egui::ViewportCommand> {+ let mut out = Vec::new();+ for _ in 0..steps {+ h.step();+ if let Some(v) = h.output().viewport_output.get(&egui::ViewportId::ROOT) {+ out.extend(v.commands.iter().cloned());+ }+ }+ out+ }++ fn double_click(h: &mut egui_kittest::Harness<'static, test_window::Window>, pos: egui::Pos2) -> Vec<egui::ViewportCommand> {+ h.hover_at(pos);+ h.step();+ // One frame: the harness gives each queued event a frame of its own, longer apart than a+ // double-click allows.+ for pressed in [true, false, true, false] {+ h.input_mut().events.push(egui::Event::PointerButton {+ pos,+ button: egui::PointerButton::Primary,+ pressed,+ modifiers: egui::Modifiers::NONE,+ });+ }+ window_commands(h, 3)+ }++ fn drag(h: &mut egui_kittest::Harness<'static, test_window::Window>, from: egui::Pos2) -> Vec<egui::ViewportCommand> {+ h.hover_at(from);+ h.step();+ press(h, from, true);+ let mut out = window_commands(h, 1);+ for i in 1..=6 {+ h.hover_at(from + vec2(8.0 * i as f32, 3.0));+ out.extend(window_commands(h, 1));+ }+ press(h, from + vec2(48.0, 3.0), false);+ out.extend(window_commands(h, 2));+ out+ }++ #[test]+ fn the_empty_mac_title_bar_zooms_and_moves_the_window() {+ use super::{MAC_APP_BAR, MAC_CONTENT_LEFT};+ use egui::ViewportCommand::{Maximized, Minimized, StartDrag};+ let mut app = app();+ app.integrated_titlebar = true;+ let mut h = test_window::open(app, vec2(1400.0, 900.0));+ let bar = test_window::panel_rect(&h, "app_bar");+ // Under the centred title, and between the traffic lights and the Home button.+ let empty = [pos2(bar.center().x, bar.min.y + MAC_APP_BAR / 2.0), pos2(bar.min.x + MAC_CONTENT_LEFT - 4.0, bar.min.y + 4.0)];+ for at in empty {+ // Tests read the setting as its default, zoom.+ let cmds = double_click(&mut h, at);+ assert_eq!(cmds, vec![Maximized(true)], "double-click at {at:?}");+ let cmds = drag(&mut h, at);+ assert_eq!(cmds, vec![StartDrag], "drag from {at:?}");+ }+ // The bar's controls keep their clicks and drags.+ for label in ["Home", "Share", "File"] {+ let at = rect(&h, label).center();+ let cmds = double_click(&mut h, at);+ assert!(!cmds.iter().any(|c| matches!(c, Maximized(_) | Minimized(_))), "double-click on {label}: {cmds:?}");+ if label == "Home" {+ assert_eq!(h.state().app.ui.status, "Home", "Home took its clicks");+ }+ h.key_press(egui::Key::Escape);+ h.run_steps(2);+ let cmds = drag(&mut h, at);+ assert!(!cmds.contains(&StartDrag), "drag from {label}: {cmds:?}");+ h.key_press(egui::Key::Escape);+ h.run_steps(2);+ }+ }++ #[test]+ fn the_mac_window_is_not_movable_on_the_title_bar_controls() {+ use super::{MAC_APP_BAR, MAC_CONTENT_LEFT};+ let mut app = app();+ app.integrated_titlebar = true;+ let mut h = test_window::open(app, vec2(1400.0, 900.0));+ let bar = test_window::panel_rect(&h, "app_bar");+ let mid = bar.min.y + MAC_APP_BAR / 2.0;+ // The search field is the bar's last control: 125 wide, 4 from the 10-wide right margin.+ let search = pos2(bar.max.x - 10.0 - 4.0 - 60.0, mid);+ let controls = [rect(&h, "Home").center(), rect(&h, "Share").center(), rect(&h, "File").center(), search];+ let mut movable_at = |at: egui::Pos2| {+ h.hover_at(at);+ h.run_steps(2);+ craft_window::title_bar::window_movable(&h.ctx)+ };+ for at in [pos2(bar.center().x, mid), pos2(bar.min.x + MAC_CONTENT_LEFT - 4.0, bar.min.y + 4.0), pos2(bar.center().x, 500.0)] {+ assert!(movable_at(at), "empty title bar or the page at {at:?}");+ }+ for at in controls {+ assert!(!movable_at(at), "control at {at:?}");+ }+ }++ #[test]+ fn a_narrow_window_scrolls_the_app_bar() {+ let w = 640.0;+ let mut h = test_window::open(app(), vec2(w, 600.0));+ let (help, share) = (rect(&h, "Help"), rect(&h, "Share"));+ assert!(help.max.x <= share.min.x, "the menus ({help:?}) and the workspace controls ({share:?}) overlap");+ wheel(&mut h, help.center(), vec2(0.0, -3000.0));+ let share = rect(&h, "Share");+ let window = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(w, 600.0));+ assert!(window.contains_rect(share), "{share:?} outside the window");+ }++ #[test]+ fn a_wide_window_does_not_scroll_the_bars() {+ let mut h = test_window::open(app(), vec2(1400.0, 900.0));+ let before = [rect(&h, FIRST_CONTROL), rect(&h, LAST_CONTROL), rect(&h, "Help"), rect(&h, "Share")];+ assert!(before.iter().all(|r| r.max.x <= 1400.0), "{before:?}");+ wheel(&mut h, before[0].center(), vec2(0.0, -3000.0));+ wheel(&mut h, before[2].center(), vec2(0.0, -3000.0));+ let after = [rect(&h, FIRST_CONTROL), rect(&h, LAST_CONTROL), rect(&h, "Help"), rect(&h, "Share")];+ assert_eq!(after, before);+ }++ /// At 115% the app bar fits a wide window exactly: it must not scroll sideways by a rounding error.+ #[test]+ fn the_app_bar_does_not_scroll_at_115_percent() {+ let w = 1400.0;+ let mut h = test_window::open_scaled(app(), vec2(w, 900.0), 1.15);+ assert_eq!(h.ctx.pixels_per_point(), 1.15);+ let before = [rect(&h, "Help"), rect(&h, "Share")];+ assert!(before.iter().all(|r| r.max.x <= w), "{before:?}");+ wheel(&mut h, before[0].center(), vec2(0.0, -3000.0));+ wheel(&mut h, before[0].center(), vec2(-3000.0, 0.0));+ let after = [rect(&h, "Help"), rect(&h, "Share")];+ assert_eq!(after, before, "the app bar scrolled sideways although everything fits");+ }++ #[test]+ fn a_scrolled_bar_keeps_its_captions_on_one_line() {+ let mut app = app();+ app.run("file.new", serde_json::json!({})).unwrap();+ let f = app.run("frame.create", serde_json::json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hello"})).unwrap();+ app.run("selection.set", serde_json::json!({"ids": [f["id"]]})).unwrap();+ let mut h = test_window::open(app, vec2(700.0, 600.0));+ let bar = test_window::panel_rect(&h, "control_bar").center();+ wheel(&mut h, bar, vec2(0.0, -3000.0));+ // The text frame's last group keeps its full size, not only what is left of the row.+ let columns = group(&h, "columns");+ assert!(columns.width() >= 48.0 && columns.max.x <= 700.0, "Columns group squeezed or off screen: {columns:?}");+ }++ struct WindowHarness {+ ctx: egui::Context,+ app: DesignApp,+ time: f64,+ maximized: bool,+ size: egui::Vec2,+ }++ impl WindowHarness {+ fn new() -> Self {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.custom_titlebar = true;+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx, "");+ let mut harness = Self { ctx, app, time: 0.0, maximized: false, size: vec2(1440.0, 900.0) };+ harness.frame(vec![]);+ harness.frame(vec![]);+ harness+ }++ fn frame(&mut self, events: Vec<egui::Event>) -> Vec<egui::ViewportCommand> {+ self.time += 0.1;+ let mut input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, self.size)),+ time: Some(self.time),+ events,+ ..Default::default()+ };+ input.viewports.entry(egui::ViewportId::ROOT).or_default().maximized = Some(self.maximized);+ let mut output = self.ctx.run_ui(input, |ui| {+ app_bar(&mut self.app, ui);+ resize_borders(&mut self.app, ui);+ });+ output.textures_delta.clear();+ output.viewport_output.get(&egui::ViewportId::ROOT).map(|v| v.commands.clone()).unwrap_or_default()+ }++ fn press(&mut self, pos: egui::Pos2) -> Vec<egui::ViewportCommand> {+ self.frame(vec![+ egui::Event::PointerMoved(pos),+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() },+ ])+ }++ fn click(&mut self, pos: egui::Pos2) -> Vec<egui::ViewportCommand> {+ let mut commands = self.press(pos);+ commands.extend(self.frame(vec![egui::Event::PointerButton {+ pos,+ button: egui::PointerButton::Primary,+ pressed: false,+ modifiers: Default::default(),+ }]));+ commands+ }++ fn caption_center(&self, id: &str) -> egui::Pos2 {+ self.ctx.read_response(egui::Id::unique(id)).unwrap().rect.center()+ }+ }++ #[test]+ fn caption_buttons_minimize_maximize_restore_and_close() {+ let mut h = WindowHarness::new();+ for (id, command) in [("window.minimize", egui::ViewportCommand::Minimized(true)), ("window.maximize", egui::ViewportCommand::Maximized(true))] {+ let p = h.caption_center(id);+ assert!(h.click(p).contains(&command), "{id}");+ }+ h.maximized = true;+ h.frame(vec![]);+ let p = h.caption_center("window.maximize");+ assert!(h.click(p).contains(&egui::ViewportCommand::Maximized(false)));+ let p = h.caption_center("window.close");+ assert!(h.click(p).contains(&egui::ViewportCommand::Close));+ }++ #[test]+ fn title_area_drags_and_double_clicks_but_menus_do_not_drag() {+ let mut h = WindowHarness::new();+ let title = h.ctx.read_response(egui::Id::unique("window_title_drag")).unwrap().rect;+ assert!(title.width() > 0.0, "there is a drag region between menus and tools");+ let p = title.center();+ let mut commands = h.press(p);+ commands.extend(h.frame(vec![egui::Event::PointerMoved(p + vec2(20.0, 0.0))]));+ assert!(commands.contains(&egui::ViewportCommand::StartDrag));++ let mut h = WindowHarness::new();+ h.click(p);+ assert!(h.click(p).contains(&egui::ViewportCommand::Maximized(true)));++ let mut h = WindowHarness::new();+ let p = egui::pos2(70.0, 18.0); // File menu, outside the title's drag region.+ let mut commands = h.press(p);+ commands.extend(h.frame(vec![egui::Event::PointerMoved(title.center())]));+ assert!(!commands.contains(&egui::ViewportCommand::StartDrag));+ }++ #[test]+ fn edges_resize_only_when_the_window_is_restored() {+ let mut h = WindowHarness::new();+ let p = egui::pos2(1438.0, 400.0);+ let mut commands = h.press(p);+ commands.extend(h.frame(vec![egui::Event::PointerMoved(p + vec2(-20.0, 0.0))]));+ assert!(commands.contains(&egui::ViewportCommand::BeginResize(egui::ResizeDirection::East)));+ let mut h = WindowHarness::new();+ h.maximized = true;+ h.frame(vec![]);+ let mut commands = h.press(p);+ commands.extend(h.frame(vec![egui::Event::PointerMoved(p + vec2(-20.0, 0.0))]));+ assert!(!commands.iter().any(|c| matches!(c, egui::ViewportCommand::BeginResize(_))));+ }++ #[test]+ fn native_window_actions_are_unavailable_without_custom_chrome() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ assert!(!crate::menus::enabled(&app, "window.close"));+ assert!(app.run("window.close", json!({})).is_err());+ assert!(app.pending_window_commands.is_empty());+ app.custom_titlebar = true;+ assert!(app.run("window.resize", json!({"edge": "invalid"})).is_err());+ assert!(app.pending_window_commands.is_empty());+ }++ #[test]+ fn caption_buttons_stay_put_while_a_narrow_app_bar_scrolls() {+ let mut h = WindowHarness::new();+ h.size = vec2(640.0, 560.0);+ h.frame(vec![]);+ h.frame(vec![]);+ let rect = |h: &WindowHarness, id: &str| h.ctx.read_response(egui::Id::unique(id)).unwrap().rect;+ let menus_end = |h: &WindowHarness| h.ctx.data(|d| d.get_temp::<f32>(egui::Id::unique("app_bar_menus_end"))).unwrap();+ let (close, menus0) = (rect(&h, "window.close"), menus_end(&h));+ assert!(close.left() >= 0.0 && close.right() <= h.size.x, "{close:?}");+ let p = egui::pos2(200.0, 18.0);+ h.frame(vec![+ egui::Event::PointerMoved(p),+ egui::Event::MouseWheel {+ unit: egui::MouseWheelUnit::Point,+ delta: vec2(0.0, -3000.0),+ phase: egui::TouchPhase::Move,+ modifiers: egui::Modifiers::NONE,+ source: egui::MouseWheelSource::Unknown,+ },+ ]);+ for _ in 0..10 {+ h.frame(vec![]);+ }+ assert!(menus_end(&h) < menus0, "the menus scrolled");+ assert_eq!(rect(&h, "window.close"), close, "the caption buttons did not");+ assert!(h.click(close.center()).contains(&egui::ViewportCommand::Close));+ }++ #[test]+ fn the_window_drags_from_its_lower_band_at_the_minimum_width() {+ // At 900 px the menus and tools fill the bar's row; its lower band still moves the window,+ // and it isn't drawn over the caption buttons.+ let mut h = WindowHarness::new();+ h.size = vec2(900.0, 560.0);+ h.frame(vec![]);+ h.frame(vec![]);+ let drag = h.ctx.read_response(egui::Id::unique("window_title_drag")).unwrap().rect;+ let close = h.ctx.read_response(egui::Id::unique("window.close")).unwrap().rect;+ assert!(drag.right() <= close.left() + 0.5, "{drag:?} {close:?}");+ let p = egui::pos2(450.0, APP_BAR + APP_BAR_BAND / 2.0);+ assert!(drag.contains(p), "{drag:?}");+ let mut commands = h.press(p);+ commands.extend(h.frame(vec![egui::Event::PointerMoved(p + vec2(20.0, 0.0))]));+ assert!(commands.contains(&egui::ViewportCommand::StartDrag));+ }++ #[test]+ fn caption_buttons_fit_the_minimum_window_width() {+ let mut h = WindowHarness::new();+ h.size = vec2(900.0, 560.0);+ h.frame(vec![]);+ h.frame(vec![]);+ for id in ["window.minimize", "window.maximize", "window.close"] {+ let rect = h.ctx.read_response(egui::Id::unique(id)).unwrap().rect;+ assert!(rect.left() >= 0.0 && rect.right() <= h.size.x, "{id}: {rect:?}");+ let p = rect.center();+ assert!(!h.click(p).is_empty(), "{id} remains clickable");+ }+ }++++#[test]++fn parent_resize_properties_changes_the_parent_not_document_page_zero() {++ parent_resize_panel(true);++}++++#[test]++fn parent_resize_control_changes_the_parent_not_document_page_zero() {++ parent_resize_panel(false);++}++++fn parent_resize_panel(properties: bool) {++ use egui_kittest::Harness;++ {++ let mut app = app();++ app.run("file.new", serde_json::json!({"width": 400, "height": 600, "pages": 3, "facingPages": true})).unwrap();++ app.run("layout.parents.new", serde_json::json!({"prefix": "B"})).unwrap();++ app.run("layout.pages.applyParent", serde_json::json!({"pages": [0], "parent": "A"})).unwrap();++ app.run("layout.parents.edit", serde_json::json!({"on": true, "parent": "A"})).unwrap();++ app.session.set_tool("page");++ app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, 600.0)));++ *app.view_mut().unwrap() = crate::View { zoom: 1.0, origin: designcraft_geom::Point::new(-600.0, 0.0), fitted: true, rotation: 0 };++ let before = app.session.doc().unwrap().doc.clone();++ let mut h = Harness::builder().with_size(vec2(1600.0, 900.0)).build_ui_state(++ move |ui, app: &mut DesignApp| {++ let id = egui::Id::unique("parent_resize_fonts");++ if ui.data(|d| d.get_temp::<bool>(id)).is_none() {++ crate::theme::install_fonts(ui.ctx(), "");++ ui.data_mut(|d| d.insert_temp(id, true));++ return;++ }++ if properties {++ panels::properties::show(app, ui);++ } else {++ super::control_bar::control_page(app, ui);++ }++ },++ app,++ );++ h.run_steps(3);++ edit_parent_resize_field(&mut h, "33p4", "500 pt");++ let d = &h.state().session.doc().unwrap().doc;++ assert_eq!(d.parents[0].pages[0].width, 500.0, "the parent page in view must change");++ assert_eq!(d.spreads, before.spreads);++ assert_eq!(d.parents[1], before.parents[1]);++ let b = before.parents[1].id.0;++ h.state_mut().run("layout.selectParentPage", json!({"parent": b, "page": 1})).unwrap();++ h.run_steps(3);++ assert_eq!(crate::canvas::current_parent_page(h.state()), Some((1, 1)));++ if properties {++ h.state_mut().session.set_tool("selection");++ }++ h.run_steps(3);++ edit_parent_resize_field(&mut h, "50p0", "700 pt");++ edit_parent_resize_field(&mut h, "33p4", "560 pt");++ let d = &h.state().session.doc().unwrap().doc;++ assert_eq!((d.parents[1].pages[1].width, d.parents[1].pages[1].height), (560.0, 700.0));++ assert_eq!(d.parents[1].pages[0].width, 400.0);++ assert_eq!(d.parents[0].pages[0].width, 500.0);++ assert_eq!(d.spreads, before.spreads);++ let parents = d.parents.clone();++ if properties {++ let saved = d.clone();++ h.get_by_label("Back").click();++ h.run_steps(3);++ assert!(!h.state().session.doc().unwrap().editing_parents, "Back returns to document properties");++ assert_eq!(h.state().session.tool_id(), "selection");++ assert!(h.query_by_label("Back").is_none(), "the next frame must leave the page properties screen");++ assert!(std::sync::Arc::ptr_eq(&saved, &h.state().session.doc().unwrap().doc));++ }++ h.state_mut().run("layout.parents.edit", json!({"on": false})).unwrap();++ h.state_mut().session.set_tool("page");++ h.state_mut().run("layout.selectPage", json!({"page": 1})).unwrap();++ h.run_steps(3);++ edit_parent_resize_field(&mut h, "33p4", "530 pt");++ let d = &h.state().session.doc().unwrap().doc;++ assert_eq!(d.spreads[0].pages[0].width, 530.0);++ assert_eq!(d.parents, parents);++ if properties {++ let saved = d.clone();++ h.get_by_label("Back").click();++ h.run_steps(3);++ assert_eq!(h.state().session.tool_id(), "selection");++ assert!(h.query_by_label("Back").is_none());++ assert_eq!(h.state().session.doc().unwrap().selection.page, None);++ assert!(std::sync::Arc::ptr_eq(&saved, &h.state().session.doc().unwrap().doc));++ }++ }++}++++fn edit_parent_resize_field(h: &mut egui_kittest::Harness<'_, DesignApp>, value: &str, input: &str) {++ h.query_all_by(|n| n.role() == egui::accesskit::Role::TextInput && n.value().as_deref() == Some(value)).next().expect("page size field").click();++ h.run_steps(2);++ h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });++ h.event(egui::Event::Text(input.into()));++ h.key_press(egui::Key::Enter);++ h.run_steps(3);++}diff --cc crates/ui-egui/src/dialogs/tests.rsindex 000000000,1cdce534f..6f2c4e868mode 000000,100644..100644--- a/crates/ui-egui/src/dialogs/tests.rs+++ b/crates/ui-egui/src/dialogs/tests.rs@@@ -1,0 -1,4933 +1,4963 @@@+ use super::*;++ #[test]+ fn paragraph_style_settings_show_captured_color_and_pending_spacing_without_changing_the_document() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let f = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":"Heading"})).unwrap();+ app.run("text.select", json!({"story":f["story"],"anchor":0,"focus":7})).unwrap();+ app.run("type.char", json!({"fontFamily":"Source Sans 3","fontStyle":"Bold","size":16,"fill":"[Paper]"})).unwrap();+ app.run("style.paragraph.create", json!({"name":"Header","fromSelection":true})).unwrap();+ let doc = app.session.doc().unwrap().doc.clone();+ let style = doc.styles.para("Header").unwrap();+ let mut d = Dialog::new("paragraphStyleOptions", json!({"name":"Header"}));+ let summary = paragraph_style_summary("", &d, style, &doc.styles);+ for value in ["Source Sans 3", "Bold", "16 pt", "[Paper]"] {+ assert!(summary.contains(value), "{summary}");+ }+ assert!(summary.len() < 250, "default attributes do not swamp the captured settings: {summary}");+ d.fields.insert("c.fill".into(), json!("[Registration]"));+ d.fields.insert("p.spaceAfter".into(), json!(4.5));+ let summary = paragraph_style_summary("", &d, style, &doc.styles);+ assert!(summary.contains("[Registration]") && !summary.contains("[Paper]"), "{summary}");+ assert!(summary.contains("4.5 pt"), "{summary}");+ assert_eq!(app.session.doc().unwrap().doc, doc);+ }++ /// A dialog opened without the menu's fields has no `useDefaults` field at all. Confirming it+ /// with no layer unticked must keep the file's defaults, not choose every layer explicitly:+ /// an implicit all-on choice is rejected for a PDF without layers, so the command's error+ /// tells the two apart.+ #[test]+ fn layer_options_confirm_without_the_menu_fields_keeps_file_defaults() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 100, "height": 100, "pages": 1})).unwrap();+ let pdf = app.run("file.exportPdf", json!({})).unwrap()["base64"].clone();+ let placed = app.run("file.place", json!({"base64": pdf, "name": "plain.pdf", "x": 0, "y": 0, "width": 100})).unwrap();+ let id = designcraft_doc::ItemId(placed["id"].as_u64().unwrap());+ app.run("selection.set", json!({"ids": [placed["id"]]})).unwrap();+ app.ui.dialog = Some(Dialog::new("layerOptions", json!({})));+ confirm(&mut app).unwrap();+ assert!(!app.session.doc().unwrap().doc.item(id).unwrap().has_pdf_layer_override(), "an untouched dialog keeps the file defaults");+ // The menu's own dialog still asks for an explicit all-on choice when that is the state+ // it was opened in; a layerless PDF refuses it rather than accepting an empty override.+ app.ui.dialog = Some(Dialog::new("layerOptions", json!({"useDefaults": false, "layers": []})));+ let err = confirm(&mut app).unwrap_err();+ assert!(err.contains("could not be changed"), "{err}");+ assert!(!app.session.doc().unwrap().doc.item(id).unwrap().has_pdf_layer_override(), "a layerless PDF never takes an explicit choice");+ }++ #[test]+ fn paragraph_style_settings_compare_with_the_chosen_parent() {+ let mut styles = designcraft_doc::Styles::default();+ styles.paragraph.push(designcraft_doc::ParagraphStyle {+ name: "Parent".into(),+ chars: designcraft_doc::CharAttrs { size: Some(20.0), ..Default::default() },+ based_on: None,+ next_style: None,+ para: Default::default(),+ shortcut: String::new(),+ });+ let style = designcraft_doc::ParagraphStyle {+ name: "Child".into(),+ based_on: Some("Parent".into()),+ next_style: None,+ para: Default::default(),+ chars: Default::default(),+ shortcut: String::new(),+ };+ let d = Dialog::new("paragraphStyleOptions", json!({"name":"Child"}));+ assert_eq!(paragraph_style_summary("", &d, &style, &styles), "Parent");+ }++ #[test]+ fn step_and_repeat_dialog_previews_and_makes_the_copies_as_one_undo_step() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = app.run("frame.create", json!({"rect": [72, 600, 540, 640]})).unwrap()["id"].as_u64().unwrap();+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ let open = |app: &mut DesignApp| {+ crate::menus::activate(app, "edit.stepAndRepeat", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some(STEP_AND_REPEAT));+ };+ let set = |app: &mut DesignApp, k: &str, v: Value| {+ app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v);+ };+ let items = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].items.len();+ let undo = |app: &DesignApp| app.session.doc().unwrap().history.undo.len();+ let (n0, u0) = (items(&app), undo(&app));+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));+ open(&mut app);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in ["Step and Repeat", "Repeat", "Count:", "Create as a grid", "Offset", "Vertical:", "Horizontal:", "Preview", "OK", "Cancel"] {+ visible_label(&labels, screen, expected);+ }+ // Preview: the copies show, and change with the fields, without an undo step.+ set(&mut app, "count", json!("5"));+ set(&mut app, "vertical", json!("-0.75 in"));+ set(&mut app, "horizontal", json!("0"));+ set(&mut app, "preview", json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!((items(&app), undo(&app)), (n0 + 5, u0));+ set(&mut app, "count", json!("3"));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!(items(&app), n0 + 3);+ set(&mut app, "preview", json!(false));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!(items(&app), n0, "Preview off takes them away");+ set(&mut app, "preview", json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!(items(&app), n0 + 3);+ // Cancel puts the document back.+ cancel(&mut app);+ assert!(app.ui.dialog.is_none());+ assert_eq!((items(&app), undo(&app)), (n0, u0));+ // OK after a preview makes the copies once, as one undo step, 0.75 in apart.+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ open(&mut app);+ set(&mut app, "count", json!("2"));+ set(&mut app, "vertical", json!("-0.75 in"));+ set(&mut app, "horizontal", json!("0"));+ set(&mut app, "preview", json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let r = confirm(&mut app).unwrap();+ assert_eq!((items(&app), undo(&app)), (n0 + 2, u0 + 1));+ let last = r["ids"][1].as_u64().unwrap();+ let top = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(last)).unwrap().bounds().min_y();+ assert!((top - (600.0 - 108.0)).abs() < 1e-6, "{top}");+ // Create as a grid: Rows × Columns cells, the original being one.+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ open(&mut app);+ set(&mut app, "grid", json!(true));+ set(&mut app, "rows", json!("2"));+ set(&mut app, "columns", json!("3"));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, "Rows:");+ visible_label(&labels, screen, "Columns:");+ assert_eq!(confirm(&mut app).unwrap()["created"], 5);+ // A value that isn't a measure keeps the dialog open and says so.+ open(&mut app);+ set(&mut app, "vertical", json!("up"));+ assert!(confirm(&mut app).is_err());+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!(d.s("status"), "Invalid value: up");+ }++ /// A three-page document in `units` with Document Setup open.+ fn document_setup_app(units: &str) -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 3})).unwrap();+ app.run("document.preferences", json!({"horizontalUnits": units, "verticalUnits": units})).unwrap();+ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);+ app+ }++ fn setup_fields(app: &mut DesignApp, fields: Value) {+ let d = app.ui.dialog.as_mut().unwrap();+ for (k, v) in fields.as_object().unwrap() {+ d.fields.insert(k.clone(), v.clone());+ }+ }++ /// File › File Info opens filled from the document and OK stores what was typed; Export PDF+ /// then names the file after the document and takes the PDF's title from File Info.+ #[test]+ fn file_info_dialog_stores_the_fields_and_titles_the_pdf() {+ use std::sync::{Arc, Mutex};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"title": "flyer-v3"})).unwrap();+ app.run("file.info", json!({"author": "Ana Ruiz", "keywords": ["spring", "shoes"]})).unwrap();+ crate::menus::activate(&mut app, "file.info", &Value::Null);+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!(d.id, "fileInfo");+ assert_eq!((d.s("documentTitle"), d.s("author"), d.s("keywords")), (String::new(), "Ana Ruiz".into(), "spring; shoes".into()));+ setup_fields(&mut app, json!({"documentTitle": "Spring Catalog", "author": "", "keywords": "spring, catalog", "description": "Shoes"}));+ confirm(&mut app).unwrap();+ assert!(app.ui.dialog.is_none());+ let info = app.session.active().unwrap().doc.file_info.clone();+ assert_eq!((info.document_title.as_str(), info.author.as_str(), info.description.as_str()), ("Spring Catalog", "", "Shoes"));+ assert_eq!(info.keywords, ["spring", "catalog"]);+ // Keywords left as shown stay as they are, even one with a comma in it.+ app.run("file.info", json!({"keywords": ["Washington, DC", "map"]})).unwrap();+ crate::menus::activate(&mut app, "file.info", &Value::Null);+ setup_fields(&mut app, json!({"author": "Studio"}));+ confirm(&mut app).unwrap();+ let info = app.session.active().unwrap().doc.file_info.clone();+ assert_eq!((info.author.as_str(), info.keywords.clone()), ("Studio", vec!["Washington, DC".to_string(), "map".to_string()]));+ // Another keyword edited: the one with a comma in it still stays one keyword.+ crate::menus::activate(&mut app, "file.info", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("keywords"), "Washington, DC; map");+ setup_fields(&mut app, json!({"keywords": "Washington, DC; atlas"}));+ confirm(&mut app).unwrap();+ assert_eq!(app.session.active().unwrap().doc.file_info.keywords, ["Washington, DC", "atlas"]);++ let writes: Arc<Mutex<Vec<Vec<u8>>>> = Arc::new(Mutex::new(Vec::new()));+ let sink = writes.clone();+ app.services.write = Some(Box::new(move |_: &str, bytes: &[u8]| {+ sink.lock().unwrap().push(bytes.to_vec());+ Ok(())+ }));+ let names: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));+ let asked = names.clone();+ app.answer_dialogs(move |request| match request {+ craft_dialogs::Request::File(dialog) => {+ asked.lock().unwrap().push(dialog.file_name.clone().unwrap_or_default());+ craft_dialogs::Answer::Paths(vec!["/tmp/designcraft-file-info.pdf".into()])+ }+ craft_dialogs::Request::Message(_) => craft_dialogs::Answer::Message(craft_dialogs::MessageResult::Yes),+ });+ open_pdf_export(&mut app);+ confirm(&mut app).unwrap();+ app.settle_dialogs();+ assert_eq!(names.lock().unwrap().as_slice(), ["flyer-v3.pdf"]);+ let pdf = String::from_utf8_lossy(&writes.lock().unwrap()[0]).into_owned();+ assert!(pdf.contains("/Title(Spring Catalog)") && !pdf.contains("/Title(flyer-v3)"), "the PDF's title is File Info's");+ // A title given to the export is the PDF's title, even when it is the document's name.+ open_pdf_export(&mut app);+ setup_fields(&mut app, json!({"title": "flyer-v3"}));+ confirm(&mut app).unwrap();+ app.settle_dialogs();+ let asked = names.lock().unwrap().last().cloned().unwrap_or_default();+ assert_eq!(std::path::Path::new(&asked).file_name().and_then(|n| n.to_str()), Some("flyer-v3.pdf"), "{asked}");+ let pdf = String::from_utf8_lossy(&writes.lock().unwrap()[1]).into_owned();+ assert!(pdf.contains("/Title(flyer-v3)") && !pdf.contains("/Title(Spring Catalog)"), "the given title wins");+ }++ /// File Info's OK stores the fields in the document the dialog was opened for, even when+ /// another document became active meanwhile; once that document has closed, OK stores nothing.+ #[test]+ fn file_info_dialog_stores_into_the_document_it_was_opened_for() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"title": "first"})).unwrap();+ crate::menus::activate(&mut app, "file.info", &Value::Null);+ app.run("file.new", json!({"title": "second"})).unwrap();+ setup_fields(&mut app, json!({"author": "Ana Ruiz"}));+ confirm(&mut app).unwrap();+ let docs = app.session.documents();+ let author = |title: &str| docs.iter().find(|d| d.doc.title == title).map(|d| d.doc.file_info.author.clone());+ assert_eq!((author("first").as_deref(), author("second").as_deref()), (Some("Ana Ruiz"), Some("")));+ assert_eq!(app.session.active().map(|d| d.doc.title.as_str()), Some("second"), "the active document stays active");++ crate::menus::activate(&mut app, "file.info", &Value::Null);+ app.run("file.close", json!({})).unwrap();+ setup_fields(&mut app, json!({"author": "Studio"}));+ confirm(&mut app).unwrap();+ assert!(app.session.documents().iter().all(|d| d.doc.file_info.author != "Studio"), "the dialog's document closed");+ }++ /// File Info opened through `ui.dialog.open` with only some fields stores only those fields;+ /// the others keep what the document holds.+ #[test]+ fn file_info_opened_with_some_fields_keeps_the_others() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("file.info", json!({"documentTitle": "Spring Catalog", "keywords": ["spring", "shoes"]})).unwrap();+ assert_eq!(ctl(&mut app, "ui.dialog.open", json!({"id": "fileInfo", "fields": {"author": "Ana Ruiz", "description": ""}}))["ok"], true);+ confirm(&mut app).unwrap();+ let info = app.session.active().unwrap().doc.file_info.clone();+ assert_eq!((info.document_title.as_str(), info.author.as_str(), info.description.as_str()), ("Spring Catalog", "Ana Ruiz", ""));+ assert_eq!(info.keywords, ["spring", "shoes"]);+ }++ /// Fields given to `ui.dialog.open` as JSON other than text reach `file.info` as they are: a+ /// keyword list stays a list, and `null` clears a field.+ #[test]+ fn file_info_opened_with_a_keyword_list_stores_the_list() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("file.info", json!({"author": "Ana Ruiz"})).unwrap();+ let fields = json!({"keywords": ["Washington, DC", "map"], "author": null});+ assert_eq!(ctl(&mut app, "ui.dialog.open", json!({"id": "fileInfo", "fields": fields}))["ok"], true);+ confirm(&mut app).unwrap();+ let info = app.session.active().unwrap().doc.file_info.clone();+ assert_eq!(info.keywords, ["Washington, DC", "map"]);+ assert_eq!(info.author, "");+ }++ /// File Info's OK for a document that is not the active one leaves the active document's+ /// Data Merge preview showing the record it showed.+ #[test]+ fn file_info_for_another_document_keeps_the_active_preview() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"title": "first"})).unwrap();+ crate::menus::activate(&mut app, "file.info", &Value::Null);+ app.run("file.new", json!({"title": "second"})).unwrap();+ let csv = designcraft_engine::cmd::base64_encode(b"Name\nAda\nGrace\n");+ app.run("data.source.select", json!({"bytes": csv, "name": "people.csv"})).unwrap();+ app.run("data.preview", json!({"record": 2})).unwrap();+ setup_fields(&mut app, json!({"author": "Ana Ruiz"}));+ confirm(&mut app).unwrap();+ let active = app.session.active().unwrap();+ assert_eq!((active.doc.title.as_str(), active.preview_record), ("second", Some(2)), "the preview still shows record 2");+ let first = app.session.documents().iter().find(|d| d.doc.title == "first").map(|d| d.doc.file_info.author.clone());+ assert_eq!(first.as_deref(), Some("Ana Ruiz"));+ }++ #[test]+ fn document_setup_ok_applies_margins_bleed_and_size_in_one_step() {+ let mut app = document_setup_app("millimeters");+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!(d.id, "documentSetup");+ assert_eq!((d.s("marginTop"), d.b("marginLinked")), ("12.7 mm".to_string(), true), "the document's margins, in its units");+ setup_fields(+ &mut app,+ json!({"marginTop": "20 mm", "marginBottom": "20 mm", "marginInside": "20 mm", "marginOutside": "20 mm", "bleedTop": "3 mm",+ "bleedBottom": "3 mm", "bleedInside": "3 mm", "bleedOutside": "3 mm", "width": "210 mm", "height": "297 mm"}),+ );+ confirm(&mut app).unwrap();+ assert!(app.ui.dialog.is_none());+ let mm = designcraft_geom::units::PT_PER_MM;+ let doc = &app.session.active().unwrap().doc;+ assert!((doc.settings.page_width - 210.0 * mm).abs() < 1e-6 && (doc.settings.bleed[2] - 3.0 * mm).abs() < 1e-6);+ assert!(doc.spreads.iter().flat_map(|s| &s.pages).all(|p| (p.margins.top - 20.0 * mm).abs() < 1e-6), "every page");+ app.run("edit.undo", json!({})).unwrap();+ let doc = &app.session.active().unwrap().doc;+ assert!((doc.settings.page_width - 612.0).abs() < 1e-6 && doc.settings.bleed[0] == 0.0, "one undo step");+ }++ #[test]+ fn document_setup_reads_a_bare_number_in_the_documents_units() {+ let mut app = document_setup_app("millimeters");+ setup_fields(&mut app, json!({"bleedTop": "5", "bleedBottom": "5", "bleedInside": "5", "bleedOutside": "5", "width": "210"}));+ confirm(&mut app).unwrap();+ let mm = designcraft_geom::units::PT_PER_MM;+ let settings = &app.session.active().unwrap().doc.settings;+ assert!(settings.bleed.iter().all(|b| (b - 5.0 * mm).abs() < 1e-6), "5 mm, not 5 picas: {:?}", settings.bleed);+ assert!((settings.page_width - 210.0 * mm).abs() < 1e-6, "{}", settings.page_width);+ }++ #[test]+ fn document_setup_keeps_each_pages_margins_unless_they_are_edited() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 3, "margins": 36})).unwrap();+ app.run("layout.marginsAndColumns", json!({"pages": [1], "margins": 90})).unwrap();+ let margins =+ |app: &DesignApp| app.session.active().unwrap().doc.spreads.iter().flat_map(|s| &s.pages).map(|p| p.margins.top).collect::<Vec<_>>();+ // Only the page count changes: every page keeps its own margins.+ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);+ setup_fields(&mut app, json!({"pages": "4"}));+ confirm(&mut app).unwrap();+ assert_eq!(margins(&app), [36.0, 90.0, 36.0, 36.0]);+ // Edited margins go to every page.+ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);+ setup_fields(&mut app, json!({"marginTop": "1p0"}));+ confirm(&mut app).unwrap();+ assert_eq!(margins(&app), [12.0; 4]);+ }++ #[test]+ fn document_setup_keeps_a_value_it_cannot_read_and_changes_nothing() {+ for (key, value) in [("width", "wide"), ("marginTop", "-"), ("pages", "0"), ("bleedTop", "x")] {+ let mut app = document_setup_app("points");+ setup_fields(&mut app, json!({key: value, "bleedInside": "9"}));+ assert!(confirm(&mut app).is_err(), "{key}");+ assert!(app.ui.dialog.is_some(), "{key}: the dialog stays open");+ assert_eq!(app.session.active().unwrap().doc.settings.bleed, [0.0; 4], "{key}: nothing changed");+ }+ }++ #[test]+ fn document_setup_links_edges_and_adjust_layout_applies() {+ let mut app = document_setup_app("points");+ let f = app.run("frame.create", json!({"rect": [36, 36, 576, 756], "content": "text"})).unwrap();+ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 900.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ // Typing in a linked margin sets all four.+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let top = labels.iter().filter(|(t, _, _)| t == "36 pt").map(|(_, r, _)| *r).next().expect("the top margin");+ click_dialog(&mut app, &ctx, screen, top.center());+ let select_all = egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND };+ dialog_frame(&mut app, &ctx, screen, vec![select_all, egui::Event::Text("72 pt".into())]);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let d = app.ui.dialog.as_ref().unwrap();+ assert!(["Top", "Bottom", "Inside", "Outside"].iter().all(|e| d.s(&format!("margin{e}")) == "72 pt"), "linked: {:?}", d.fields);+ // Adjust Layout applies at once, and the frame follows the margins.+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Adjust Layout").center());+ assert!(app.ui.dialog.is_none(), "applied");+ let doc = &app.session.active().unwrap().doc;+ let b = doc.item(designcraft_doc::ItemId(f["id"].as_u64().unwrap())).unwrap().bounds();+ assert!((b.y0 - 72.0).abs() < 1e-6 && doc.page(0).unwrap().margins.outside == 72.0, "{b:?}");+ }++ #[test]+ fn cell_options_dialog_draws_and_applies_only_changed_values_to_the_chosen_edges() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();+ let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ app.run("table.select", json!({"what": "table"})).unwrap();+ app.run("app.cellOptionsDialog", json!({})).unwrap();+ let ctx = dialog_context("");+ dialog_frame(&mut app, &ctx, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0)), vec![]);+ let d = app.ui.dialog.as_mut().unwrap();+ assert_eq!(d.id, "cellOptions");+ assert_eq!(d.fields["weight"], json!(1.0));+ d.fields.insert("edges".into(), json!(["top", "bottom", "left", "right"]));+ d.fields.insert("gapColor".into(), json!("[Paper]"));+ d.fields.insert("fill".into(), json!("[Black]"));+ d.fields.insert("fillTint".into(), json!(0.2));+ confirm(&mut app).unwrap();+ let st = app.session.active().unwrap();+ let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();+ let gap = |r: usize, c: usize, side: usize| t.cell(r, c).unwrap().strokes[side].gap_color.clone();+ assert_eq!([gap(0, 0, 0), gap(0, 0, 1), gap(1, 1, 2), gap(1, 1, 3)], ["[Paper]"; 4].map(String::from), "outer edges");+ assert_eq!([gap(0, 0, 2), gap(0, 0, 3)], ["[None]"; 2].map(String::from), "inner edges keep theirs");+ assert!(t.cells.iter().all(|c| c.fill == "[Black]" && (c.fill_tint - 0.2).abs() < 1e-6));+ assert!(t.cells.iter().all(|c| c.strokes.iter().all(|e| e.weight == 1.0)), "unchanged values are not applied");+ }++ #[test]+ fn cell_options_edge_changes_reseed_every_stroke_field_and_survive_a_bad_seed() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();+ let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ app.run("table.select", json!({"what": "table"})).unwrap();+ app.run("table.setCell", json!({"stroke": {"weight": 3, "edges": "innerHorizontal"}})).unwrap();+ app.run("app.cellOptionsDialog", json!({})).unwrap();+ let mut d = app.ui.dialog.take().unwrap();+ d.fields.insert("seed".into(), json!(5));+ let outer = [true, true, true, true, false, false];+ cell_options_edges_changed(&mut app, &mut d, &outer);+ assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(1.0), &json!(1.0)));+ // A weight typed for the outer edges, then the inner horizontal edges (3 pt) chosen+ // and 1 pt typed: 1 pt differs from what those edges show, so OK applies it.+ d.fields.insert("weight".into(), json!(5.0));+ cell_options_edges_changed(&mut app, &mut d, &[false, false, false, false, true, false]);+ assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(5.0), &json!(3.0)));+ d.fields.insert("weight".into(), json!(1.0));+ app.ui.dialog = Some(d);+ confirm(&mut app).unwrap();+ let st = app.session.active().unwrap();+ let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();+ assert_eq!([t.cell(0, 0).unwrap().strokes[2].weight, t.cell(1, 1).unwrap().strokes[0].weight], [1.0; 2]);+ }++ #[test]+ fn preferences_ok_saves_a_story_editor_size_that_loads_back() {+ // `ui.dialog.set` takes any value; a size that isn't finite is saved as `null`.+ let sizes = [(json!("nan"), 20.0), (json!("inf"), 20.0), (json!(null), 20.0), (json!(1e39), 36.0), (json!(3), 8.0), (json!(11), 11.0)];+ for (size, want) in sizes {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.ui.story_editor_size = 20.0;+ app.run("app.preferences", json!({})).unwrap();+ app.ui.dialog.as_mut().unwrap().fields.insert("storyEditorSize".into(), size);+ confirm(&mut app).unwrap();+ let saved = serde_json::to_vec(&app.ui).unwrap();+ assert_eq!(crate::UiState::from_preferences_json(&saved).unwrap().story_editor_size, want);+ }+ }++ #[test]+ fn preferences_ok_sets_only_the_ruler_units_it_is_given() {+ // `ui.dialog.open` takes any fields, so the vertical units can be missing.+ for (vertical, want) in [(None, "inches"), (Some("points"), "points")] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("document.preferences", json!({"verticalUnits": "inches"})).unwrap();+ let mut fields = json!({"horizontalUnits": "millimeters", "bg.relativeTo": "topOfPage"});+ if let Some(vertical) = vertical {+ fields["verticalUnits"] = json!(vertical);+ }+ app.ui.dialog = Some(Dialog::new("preferences", fields));+ confirm(&mut app).unwrap();+ let units = app.run("document.preferences", json!({})).unwrap();+ assert_eq!((units["horizontalUnits"].as_str(), units["verticalUnits"].as_str()), (Some("millimeters"), Some(want)));+ }+ }++ #[test]+ fn enter_and_escape_close_the_style_menu_not_numbering_and_section_options() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 2})).unwrap();+ crate::menus::activate(&mut app, "layout.section", &Value::Null);+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };+ for pressed in [egui::Key::Enter, egui::Key::Escape] {+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ // The section's Style menu (the first of the two).+ let style = labels.iter().filter(|(t, r, c)| t.trim() == "1, 2, 3, 4…" && c.contains_rect(*r)).map(|(_, r, _)| *r).next().unwrap();+ click_dialog(&mut app, &ctx, screen, style.center());+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(egui::Popup::is_any_open(&ctx), "the Style menu opened");+ dialog_frame(&mut app, &ctx, screen, vec![key(pressed)]);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(app.ui.dialog.is_some(), "{pressed:?} with the menu open leaves the dialog open");+ assert!(app.session.active().unwrap().doc.sections.iter().all(|s| s.start_number != Some(0)));+ if egui::Popup::is_any_open(&ctx) {+ egui::Popup::close_all(&ctx);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ }+ // With no menu open, Escape closes the dialog.+ dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Escape)]);+ assert!(app.ui.dialog.is_none());+ }++ #[test]+ fn numbering_and_section_options_keep_their_actions_in_view() {+ for language in ["en", "ar"] {+ for size in [egui::vec2(1178.0, 814.0), egui::vec2(392.0, 271.0)] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.language = language.into();+ app.run("file.new", json!({"pages": 2})).unwrap();+ crate::menus::activate(&mut app, "layout.section", &Value::Null);+ let ctx = dialog_context(language);+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size);+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let tr = |s| crate::i18n::tr(language, s);+ for expected in [tr("Numbering & Section Options…").trim_end_matches('…'), tr("OK"), tr("Cancel"), tr("Start Section")] {+ visible_label(&labels, screen, expected);+ }+ if size.x > 1000.0 {+ // Every option fits without scrolling, and choosing one then OK applies it.+ visible_label(&labels, screen, &format!("{} {}", tr("Book Name:"), tr("N/A")));+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, tr("Automatic Page Numbering")).center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, tr("OK")).center());+ assert!(app.ui.dialog.is_none(), "{language}: OK closes the dialog");+ let doc = &app.session.active().unwrap().doc;+ assert!(doc.sections.iter().all(|s| s.start != 0 || s.start_number.is_none()), "{language}: page 1 numbers automatically");+ }+ }+ }+ }++ fn select_all_key() -> egui::Event {+ egui::Event::Key {+ key: egui::Key::A,+ physical_key: None,+ pressed: true,+ repeat: false,+ modifiers: egui::Modifiers { ctrl: true, command: true, ..Default::default() },+ }+ }++ /// The Color Picker over a new document's selected frame, a few frames in.+ fn picker(fields: Value) -> (DesignApp, egui::Context, egui::Rect, u64) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ app.ui.dialog = Some(Dialog::new("colorPicker", fields));+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(700.0, 500.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ (app, ctx, screen, id)+ }++ /// Types `text` one character per frame, with an idle frame after each.+ fn type_slowly(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, text: &str) {+ for ch in text.chars() {+ dialog_frame(app, ctx, screen, vec![egui::Event::Text(ch.into())]);+ dialog_frame(app, ctx, screen, vec![]);+ }+ }++ fn fill(app: &DesignApp, id: u64) -> designcraft_color::Color {+ let d = &app.session.active().unwrap().doc;+ d.resolve_color(&d.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch, 1.0).unwrap()+ }++ fn key_press(key: egui::Key) -> egui::Event {+ egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }+ }++ #[test]+ fn the_color_picker_enter_confirms_and_escape_cancels_even_in_a_field() {+ for (key, applied) in [(egui::Key::Enter, true), (egui::Key::Escape, false)] {+ let (mut app, ctx, screen, id) = picker(json!({"target": "fill", "hex": "#ffffff"}));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "ffffff").center());+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "#f59019");+ dialog_frame(&mut app, &ctx, screen, vec![key_press(key)]);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(app.ui.dialog.is_none(), "{key:?} closes the picker");+ let d = &app.session.active().unwrap().doc;+ let swatch = d.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch.clone();+ let hex = d.resolve_color(&swatch, 1.0).map(|c| c.to_hex());+ assert_eq!(hex.as_deref() == Some("#f59019"), applied, "{key:?}: {hex:?}");+ }+ }++ #[test]+ fn the_hex_field_keeps_typed_text_and_commits_a_valid_code() {+ let (mut app, ctx, screen, _) = picker(json!({"target": "fill", "hex": "#ffffff"}));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "ffffff").center());+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "#f5");+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!((d.s("hexEdit").as_str(), d.s("hex").as_str()), ("#f5", "#ffffff"), "half-typed text stays; the colour waits");+ type_slowly(&mut app, &ctx, screen, "9019");+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!((d.s("hexEdit").as_str(), d.s("hex").as_str()), ("#f59019", "#f59019"), "a 7-character #rrggbb commits");+ // Invalid text is replaced by the colour when focus leaves.+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "zz");+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "#:").center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, "f59019");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("hex"), "#f59019");+ }++ #[test]+ fn typed_channel_values_are_kept_while_typing() {+ let (mut app, ctx, screen, id) = picker(json!({"target": "fill", "hex": "#010203", "model": "rgb", "rgb": [1, 2, 3]}));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let r = visible_label(&labels, screen, "R:");+ click_dialog(&mut app, &ctx, screen, egui::pos2(r.min.x + 46.0, r.center().y));+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "12.5");+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, "12.5");+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields["rgb"][1], json!(2.0));+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("hex"), "#0d0203");+ confirm(&mut app).unwrap();+ let designcraft_color::Color::Rgb { r, .. } = fill(&app, id) else { panic!("not RGB") };+ assert!((r - 12.5 / 255.0).abs() < 1e-6, "{r}");+ }++ #[test]+ fn a_cmyk_colour_stays_cmyk_unless_rgb_values_are_typed() {+ let cmyk = json!({"target": "fill", "hex": "#ff8000", "model": "cmyk", "cmyk": [0, 50, 100, 0]});+ // Picked by hex: converted to CMYK.+ let (mut app, ctx, screen, id) = picker(cmyk.clone());+ let hex = app.ui.dialog.as_ref().unwrap().s("hex");+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, hex.trim_start_matches('#')).center());+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "3366cc");+ confirm(&mut app).unwrap();+ assert!(matches!(fill(&app, id), designcraft_color::Color::Cmyk { .. }), "{:?}", fill(&app, id));+ // A typed C/M/Y/K percent is a percent: M 1 is 1 %.+ let (mut app, ctx, screen, id) = picker(cmyk.clone());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let r = visible_label(&labels, screen, "M:");+ click_dialog(&mut app, &ctx, screen, egui::pos2(r.max.x + 29.0, r.center().y));+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "1");+ confirm(&mut app).unwrap();+ let designcraft_color::Color::Cmyk { c, m, y, k } = fill(&app, id) else { panic!("not CMYK") };+ assert!(c == 0.0 && (m - 0.01).abs() < 1e-6 && (y - 1.0).abs() < 1e-6 && k == 0.0, "{c} {m} {y} {k}");+ // Typed R/G/B values: RGB.+ let (mut app, ctx, screen, id) = picker(cmyk);+ let r = app.ui.dialog.as_ref().unwrap().fields["rgb"][0].as_f64().unwrap();+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let _ = r;+ let r = visible_label(&labels, screen, "R:");+ click_dialog(&mut app, &ctx, screen, egui::pos2(r.min.x + 46.0, r.center().y));+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "10");+ confirm(&mut app).unwrap();+ assert!(matches!(fill(&app, id), designcraft_color::Color::Rgb { .. }), "{:?}", fill(&app, id));+ }++ #[test]+ fn ok_without_edits_leaves_the_fill_alone() {+ let (mut app, _, _, id) = picker(json!({"target": "fill", "hex": "#ff8000", "model": "cmyk", "cmyk": [0, 50, 100, 0]}));+ let before = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().fill.clone();+ confirm(&mut app).unwrap();+ assert_eq!(app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().fill, before);+ }++ #[test]+ fn dialogs_do_not_dim_the_page() {+ let (mut app, ctx, screen, _) = picker(json!({"target": "fill", "hex": "#ff8000"}));+ let time = ctx.input(|i| i.time) + 1.0 / 60.0;+ let output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }, |ui| show(&mut app, ui.ctx()));+ fn covers(shape: &egui::Shape, screen: egui::Rect) -> bool {+ match shape {+ egui::Shape::Rect(r) => r.rect.contains_rect(screen) && r.fill.a() > 0,+ egui::Shape::Vec(v) => v.iter().any(|s| covers(s, screen)),+ _ => false,+ }+ }+ assert!(app.ui.dialog.is_some());+ assert!(!output.shapes.iter().any(|s| covers(&s.shape, screen)), "nothing paints over the whole window");+ }++ fn draw(app: &mut DesignApp, ctx: &egui::Context) {+ let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ }++ /// A paragraph styled "Ruled Child", whose Rule Below comes from its parent "Ruled".+ fn ruled_paragraph() -> (DesignApp, Value) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let rule = json!({"on": true, "weight": 3.0, "color": "[Black]", "tint": 0.5, "columnWidth": false, "offset": 4.0, "leftIndent": 6.0, "rightIndent": 2.0});+ app.run("style.paragraph.create", json!({"name": "Ruled", "para": {"ruleBelow": rule}})).unwrap();+ app.run("style.paragraph.create", json!({"name": "Ruled Child", "basedOn": "Ruled"})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 400], "content": "text", "text": "One"})).unwrap();+ app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();+ app.run("style.paragraph.apply", json!({"name": "Ruled Child"})).unwrap();+ (app, rule)+ }++ fn undo_steps(app: &DesignApp) -> usize {+ app.session.doc().map_or(0, |st| st.history.undo.len())+ }++ #[test]+ fn paragraph_rules_dialog_shows_the_rule_and_applies_one_field() {+ let (mut app, rule) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.run("app.paragraphRulesDialog", json!({"rule": "ruleBelow"})).unwrap();+ draw(&mut app, &ctx);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(d.id, "paragraphRules");+ let current = d.fields["current"].clone();+ assert_eq!(shown_rule(&d, "", "ruleBelow", ¤t), rule, "the inherited rule");+ assert_eq!(shown_rule(&d, "", "ruleAbove", ¤t)["on"], false);+ // Pick a colour, as the Color menu does.+ app.ui.dialog.as_mut().unwrap().fields.insert("ruleBelow.color".into(), json!("[Registration]"));+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ let mut want = rule.clone();+ want["color"] = json!("[Registration]");+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want);+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], rule);+ }++ #[test]+ fn paragraph_style_options_edit_one_rule_field() {+ let (mut app, rule) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"})));+ draw(&mut app, &ctx);+ let resolved = |app: &DesignApp| serde_json::to_value(app.session.doc().unwrap().doc.styles.resolve_para_style("Ruled Child").0).unwrap();+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(shown_rule(&d, "p.", "ruleBelow", &resolved(&app)), rule, "inherited from the parent style");+ app.ui.dialog.as_mut().unwrap().fields.insert("p.ruleBelow.weight".into(), json!(1.5));+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ let mut want = rule.clone();+ want["weight"] = json!(1.5);+ assert_eq!(resolved(&app)["ruleBelow"], want);+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want, "the paragraph follows its style");+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(resolved(&app)["ruleBelow"], rule);+ }++ /// Opens Paragraph Style Options on "Ruled Child" at each of `sections`, sets `fields` and+ /// clicks OK; returns the resolved attributes of the paragraph styled with it.+ fn style_section_edit(sections: &[&str], fields: Value) -> Value {+ let (mut app, _) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child"})));+ for section in sections {+ app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!(section));+ draw(&mut app, &ctx);+ }+ for (k, v) in fields.as_object().unwrap() {+ app.ui.dialog.as_mut().unwrap().fields.insert(k.clone(), v.clone());+ }+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ let style = app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap();+ let own = serde_json::to_value(&style.para).unwrap();+ for (k, v) in fields.as_object().unwrap() {+ assert_eq!(own[k.trim_start_matches("p.")], *v, "the style sets {k}");+ }+ app.run("type.selectionAttrs", json!({})).unwrap()["para"].clone()+ }++ #[test]+ fn paragraph_style_options_keep_and_border_sections_reach_the_styled_paragraph() {+ let para = style_section_edit(+ &["keep", "border"],+ json!({"p.keepWithNext": 2, "p.keepLinesTogether": true, "p.keepAllLines": false, "p.keepFirst": 3,+ "p.startParagraph": "nextPage", "p.borderOn": true, "p.borderWeights": [2.0, 0.0, 2.0, 0.0]}),+ );+ assert_eq!(para["keepWithNext"], 2);+ assert_eq!(para["keepLinesTogether"], true);+ assert_eq!(para["keepAllLines"], false);+ assert_eq!(para["keepFirst"], 3);+ assert_eq!(para["startParagraph"], "nextPage");+ assert_eq!(para["borderOn"], true);+ assert_eq!(para["borderWeights"], json!([2.0, 0.0, 2.0, 0.0]));+ // Fields not edited keep the resolved value.+ assert_eq!(para["keepLast"], 2);+ assert_eq!(para["ruleBelow"]["weight"], 3.0);+ }++ #[test]+ fn paragraph_style_options_bullets_and_span_sections_reach_the_styled_paragraph() {+ let para = style_section_edit(+ &["bullets", "span"],+ json!({"p.listType": "numbers", "p.numberStyle": "upperRoman", "p.numberExpression": "^#)^t", "p.startAt": 3,+ "p.spanColumns": {"kind": "split", "columns": 3}}),+ );+ assert_eq!(para["listType"], "numbers");+ assert_eq!(para["numberStyle"], "upperRoman");+ assert_eq!(para["numberExpression"], "^#)^t");+ assert_eq!(para["startAt"], 3);+ assert_eq!(para["spanColumns"], json!({"kind": "split", "columns": 3}));+ let props: designcraft_doc::ParaProps = serde_json::from_value(para).unwrap();+ assert_eq!(props.number_label(3), "III)\t");+ }++ #[test]+ fn paragraph_style_options_ignore_optical_margin_is_set_on_ok() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("style.paragraph.create", json!({"name": "Flush"})).unwrap();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Flush", "section": "indents"})));+ let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::unique("ignore_optical_margin_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(3);+ h.get_by_label("Ignore Optical Margin").click();+ h.run_steps(3);+ h.get_by_label(" OK ").click();+ h.run_steps(3);+ let app = h.state();+ assert!(app.ui.dialog.is_none());+ assert_eq!(app.session.doc().unwrap().doc.styles.para("Flush").unwrap().para.ignore_optical_margin, Some(true));+ }++ #[test]+ fn paragraph_style_options_keep_a_bad_grep_pattern_open_with_the_error() {+ let (mut app, _) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled", "section": "general"})));+ draw(&mut app, &ctx);+ app.ui.dialog.as_mut().unwrap().fields.insert("p.grepStyles".into(), json!([{"style": "[None]", "pattern": "(?<=x"}]));+ let e = confirm(&mut app).unwrap_err();+ assert!(e.contains("bad GREP"), "{e}");+ let d = app.ui.dialog.clone().expect("the dialog stays open");+ assert_eq!((d.s("section").as_str(), d.s("status").contains("bad GREP")), ("grep", true));+ assert!(app.session.doc().unwrap().doc.styles.para("Ruled").unwrap().para.grep_styles.is_none(), "nothing saved");+ draw(&mut app, &ctx);+ }++ #[test]+ fn paragraph_style_options_show_a_refused_rename_on_general_and_trim_a_new_name() {+ let (mut app, _) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled", "section": "rules"})));+ draw(&mut app, &ctx);+ app.ui.dialog.as_mut().unwrap().fields.insert("rename".into(), json!("Ruled Child"));+ let e = confirm(&mut app).unwrap_err();+ let d = app.ui.dialog.clone().expect("the dialog stays open");+ assert_eq!(d.s("section"), "general", "the name field is on General");+ assert!(d.s("status").contains("already exists"), "{e}");++ app.ui.dialog.as_mut().unwrap().fields.insert("rename".into(), json!(" Fresh "));+ app.ui.dialog.as_mut().unwrap().fields.insert("x.tag".into(), json!("h3"));+ confirm(&mut app).unwrap();+ let st = &app.session.doc().unwrap().doc.styles;+ assert!(st.para("Fresh").is_some());+ assert_eq!(st.export_tag("Fresh", false).map(|t| t.tag.as_str()), Some("h3"));+ }++ /// A frame with two paragraphs of [Basic Paragraph]; the first has a local Word Spacing minimum.+ fn two_paragraphs() -> (DesignApp, Value) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 400], "content": "text", "text": "One\nTwo"})).unwrap();+ app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();+ app.run("type.para", json!({"attrs": {"wordSpaceMin": 0.7}})).unwrap();+ (app, r["story"].clone())+ }++ /// The resolved paragraph attribute `key` of the paragraph at byte `at`.+ fn para_attr(app: &mut DesignApp, story: &Value, at: usize, key: &str) -> Value {+ app.run("text.select", json!({"story": story, "anchor": at, "focus": at})).unwrap();+ app.run("type.selectionAttrs", json!({})).unwrap()["para"][key].clone()+ }++ /// The hyphenation video (Graphd Tutorials, 0:39–1:13): the Paragraph panel menu's+ /// Hyphenation… opens InDesign's Hyphenation Settings for the selected paragraphs. Preview+ /// shows the slider moved to Fewer Hyphens on the page without an undo step, OK makes it one+ /// step on the selected paragraph only, and Cancel puts it back.+ #[test]+ fn hyphenation_settings_preview_apply_and_cancel_on_the_selected_paragraph() {+ let (mut app, story) = two_paragraphs();+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));+ let sid = designcraft_doc::StoryId(story.as_u64().unwrap());+ let weight = |app: &DesignApp, para: usize| {+ let d = &app.session.doc().unwrap().doc;+ d.styles.resolve_para(&d.story(sid).unwrap().paras[para]).0.hyph_weight+ };+ assert!(crate::menus::menu_enabled(&app, "app.hyphenationDialog"));+ app.run("app.hyphenationDialog", json!({})).unwrap();+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(+ (d.id.as_str(), d.fields["current"]["hyphWeight"].as_f64(), d.fields["current"]["hyphenate"].as_bool()),+ ("hyphenation", Some(0.5), Some(true))+ );+ for label in [+ "Hyphenation Settings",+ "Hyphenate",+ "Words with at Least:",+ "letters",+ "Hyphen Limit:",+ "hyphens",+ "Hyphenation Zone:",+ "Better Spacing",+ "Fewer Hyphens",+ "Hyphenate Capitalized Words",+ "Hyphenate Last Word",+ "Hyphenate Across Column",+ "Preview",+ ] {+ assert!(labels.iter().any(|(t, _, _)| t == label), "{label}: {labels:?}");+ }+ // Fewer Hyphens (9 of 10) with Preview: on the page, no undo step.+ let before = undo_steps(&app);+ let d = app.ui.dialog.as_mut().unwrap();+ d.fields.insert("hyphWeight".into(), json!(0.9));+ d.fields.insert("preview".into(), json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!(weight(&app, 0), 0.9, "previewed");+ assert_eq!(undo_steps(&app), before, "a preview is no step");+ // Cancel: back as it was.+ cancel(&mut app);+ assert_eq!(weight(&app, 0), 0.5);+ // Again, and OK: one step, the selected paragraph only.+ app.run("app.hyphenationDialog", json!({})).unwrap();+ let d = app.ui.dialog.as_mut().unwrap();+ d.fields.insert("hyphWeight".into(), json!(0.9));+ d.fields.insert("preview".into(), json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ confirm(&mut app).unwrap();+ assert_eq!((weight(&app, 0), weight(&app, 1)), (0.9, 0.5));+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ // Paragraph Style Options › Hyphenation has the same form.+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": designcraft_doc::story::BASIC_PARAGRAPH, "section": "hyph"})));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for label in ["Hyphenation Zone:", "Better Spacing", "Fewer Hyphens", "Hyphenate Last Word", "Hyphenate Across Column"] {+ assert!(labels.iter().any(|(t, _, _)| t == label), "style options: {label}");+ }+ app.ui.dialog = None;+ app.run("edit.deselectAll", json!({})).unwrap();+ assert!(!crate::menus::menu_enabled(&app, "app.hyphenationDialog"), "no paragraph");+ }++ /// Hyphenate differs across the selection: it shows mixed, and the first click turns it on for+ /// all. Settings the command refuses show why: a preview goes back and isn't retried until they+ /// change, and OK keeps the dialog open.+ /// A mixed Better Spacing ↔ Fewer Hyphens slider: a click on its middle step sets every+ /// selected paragraph to it, though the knob already sat there.+ #[test]+ fn hyphenation_settings_mixed_slider_click_sets_the_step() {+ let (mut app, story) = two_paragraphs();+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));+ app.run("type.para", json!({"attrs": {"hyphWeight": 0.2}})).unwrap();+ app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap();+ app.run("app.hyphenationDialog", json!({})).unwrap();+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let rect = |l: &str| labels.iter().find(|(t, _, _)| t == l).map(|(_, r, _)| *r).unwrap();+ let (better, fewer) = (rect("Better Spacing"), rect("Fewer Hyphens"));+ click_dialog(&mut app, &ctx, screen, egui::pos2((better.right() + fewer.left()) / 2.0, better.center().y));+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("hyphWeight"), Some(&json!(0.5)));+ }++ #[test]+ fn hyphenation_settings_mixed_checkbox_and_refused_settings() {+ let (mut app, story) = two_paragraphs();+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));+ app.run("type.para", json!({"attrs": {"hyphenate": false}})).unwrap();+ app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap();+ app.run("app.hyphenationDialog", json!({})).unwrap();+ assert!(app.ui.dialog.as_ref().unwrap().fields["current"]["hyphenate"].is_null(), "mixed");+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let at = labels.iter().find(|(t, _, _)| t == "Hyphenate").map(|(_, r, _)| r.left_center() - egui::vec2(10.0, 0.0)).unwrap();+ click_dialog(&mut app, &ctx, screen, at);+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("hyphenate"), Some(&json!(true)), "the first click turns it on");+ // A refused setting (as a control-channel caller could send it): no preview, the reason.+ let before = undo_steps(&app);+ let d = app.ui.dialog.as_mut().unwrap();+ d.fields.insert("hyphWeight".into(), json!("heavy"));+ d.fields.insert("preview".into(), json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let d = app.ui.dialog.as_ref().unwrap();+ assert!(!d.fields.contains_key(PREVIEWED) && d.fields.contains_key("status"), "{:?}", d.fields);+ assert!(app.session.doc().unwrap().interaction.is_none(), "the preview went back");+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(app.session.doc().unwrap().interaction.is_none(), "not tried again");+ // OK with it: an error, and the dialog stays open with the reason.+ assert!(confirm(&mut app).is_err());+ let d = app.ui.dialog.as_ref().expect("the dialog stays open");+ assert!(d.fields.contains_key("status"));+ assert_eq!(undo_steps(&app), before);+ // Corrected, it previews and applies.+ app.ui.dialog.as_mut().unwrap().fields.insert("hyphWeight".into(), json!(0.9));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("status"));+ confirm(&mut app).unwrap();+ assert_eq!(para_attr(&mut app, &story, 0, "hyphenate"), true);+ assert_eq!(para_attr(&mut app, &story, 4, "hyphWeight"), 0.9);+ }++ #[test]+ fn justification_dialog_applies_to_a_local_paragraph_and_cancel_changes_nothing() {+ let (mut app, story) = two_paragraphs();+ let ctx = egui::Context::default();+ assert!(crate::menus::menu_enabled(&app, "app.justificationDialog"));+ app.run("app.justificationDialog", json!({})).unwrap();+ draw(&mut app, &ctx);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(d.id, "justification");+ assert_eq!(d.fields["current"]["wordSpaceMin"], 0.7);+ assert_eq!(d.fields["current"]["wordSpaceDesired"], 1.0);+ app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceDesired".into(), json!(1.1));+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceDesired"), 1.1);+ assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceMin"), 0.7, "unedited fields stay");+ assert_eq!(para_attr(&mut app, &story, 4, "wordSpaceDesired"), 1.0, "only the selected paragraph");+ let style = app.session.doc().unwrap().doc.styles.resolve_para_style(designcraft_doc::story::BASIC_PARAGRAPH).0.word_space_desired;+ assert_eq!(style, 1.0, "the paragraph style keeps its value");++ // Cancel (Escape) leaves the paragraph alone.+ app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap();+ app.run("app.justificationDialog", json!({})).unwrap();+ app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceDesired".into(), json!(1.2));+ let before = undo_steps(&app);+ let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events: vec![escape],+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ assert!(app.ui.dialog.is_none(), "cancelled");+ assert_eq!(undo_steps(&app), before);+ assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceDesired"), 1.1);++ app.run("edit.deselectAll", json!({})).unwrap();+ assert!(!crate::menus::menu_enabled(&app, "app.justificationDialog"), "nothing to justify");+ assert!(app.run("app.justificationDialog", json!({})).is_err());+ }++ #[test]+ fn justification_dialog_leaves_mixed_fields_alone_and_refuses_bad_values() {+ let (mut app, story) = two_paragraphs();+ let ctx = egui::Context::default();+ app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap();+ app.run("app.justificationDialog", json!({})).unwrap();+ draw(&mut app, &ctx);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(d.fields["current"]["wordSpaceMin"], Value::Null, "mixed shows empty");+ assert_eq!(d.fields["current"]["wordSpaceMax"], 1.33);++ // Out of range, and minimum above desired: an error, the dialog stays open, nothing changes.+ let before = undo_steps(&app);+ for (key, v) in [("wordSpaceMax", 20.0), ("glyphScaleMin", 0.2), ("letterSpaceDesired", f64::NAN)] {+ app.ui.dialog = Some(d.clone());+ app.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!(v));+ assert!(confirm(&mut app).is_err(), "{key} = {v}");+ assert!(app.ui.dialog.as_ref().is_some_and(|d| d.fields.contains_key("justifyError")), "{key}: the dialog shows why");+ }+ app.ui.dialog = Some(d.clone());+ app.ui.dialog.as_mut().unwrap().fields.insert("letterSpaceMin".into(), json!(0.1));+ assert!(confirm(&mut app).is_err(), "letter spacing minimum above desired");+ draw(&mut app, &ctx);+ assert_eq!(undo_steps(&app), before);++ app.ui.dialog = Some(d);+ app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceMax".into(), json!(1.5));+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1);+ for (at, min) in [(0, 0.7), (4, 0.8)] {+ assert_eq!(para_attr(&mut app, &story, at, "wordSpaceMax"), 1.5);+ assert_eq!(para_attr(&mut app, &story, at, "wordSpaceMin"), min, "each paragraph keeps its own minimum");+ }+ }++ fn command_app(id: &str, fields: Value) -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.dialog = Some(Dialog::new(&format!("cmd:{id}"), fields));+ app+ }++ #[test]+ fn generic_new_document_preserves_typed_values_and_text_entry() {+ for pages in [json!(2), json!(" 2 ")] {+ let mut app = command_app(+ "file.new",+ json!({+ "preset": "A4", "pages": pages, "facingPages": false, "gutter": 0,+ "margins": {"top": 10, "bottom": 20, "inside": 30, "outside": 40},+ "title": " ", "status": "internal", "primaryTextFrame": true+ }),+ );+ confirm(&mut app).unwrap();+ let doc = &app.session.active().unwrap().doc;+ assert_eq!(doc.page_count(), 2);+ assert!(!doc.settings.facing_pages);+ assert!(doc.title.starts_with("Untitled-"));+ for page in doc.spreads.iter().flat_map(|s| &s.pages) {+ assert!((page.width - 595.2755905511812).abs() < 0.01);+ assert!((page.height - 841.8897637795277).abs() < 0.01);+ assert_eq!(page.columns.gutter, 0.0);+ assert_eq!(page.margins.top, 10.0);+ assert_eq!(page.margins.outside, 40.0);+ }+ // `primaryTextFrame` is documented since #776, so the dialog passes it on (`status` isn't).+ assert!(doc.spreads.iter().any(|s| !s.items.is_empty()), "documented fields reach the command");+ assert!(app.ui.dialog.is_none());+ }+ }++ #[test]+ fn numbering_commands_document_their_fields() {+ let names = |id: &str| command_fields(designcraft_engine::find_command(id).unwrap().params).into_iter().map(|f| f.key).collect::<Vec<_>>();+ assert_eq!(names("layout.section"), ["page", "startNumber", "style", "prefix", "includePrefix", "marker", "remove"]);+ assert_eq!(names("layout.chapterNumbering"), ["style", "start", "source"]);+ }++ #[test]+ fn generic_command_preserves_array_geometry() {+ let mut app = command_app("file.new", json!({}));+ confirm(&mut app).unwrap();+ app.ui.dialog = Some(Dialog::new("cmd:frame.create", json!({"rect": [10, 20, 110, 220]})));+ confirm(&mut app).unwrap();+ let doc = &app.session.active().unwrap().doc;+ let item = doc.spreads.iter().flat_map(|s| &s.items).next().unwrap();+ assert_eq!(item.bounds(), designcraft_geom::Rect::new(10.0, 20.0, 110.0, 220.0));+ }++ #[test]+ fn generic_explicit_null_uses_the_commands_existing_semantics() {+ // file.new accepts null width by using the selected preset's width.+ for width in [Value::Null, json!("null")] {+ let mut app = command_app("file.new", json!({"preset": "A4", "width": width, "title": " Sample layout "}));+ confirm(&mut app).unwrap();+ let doc = &app.session.active().unwrap().doc;+ assert_eq!(doc.title, "Sample layout");+ assert!((doc.settings.page_width - 595.2755905511812).abs() < 0.01);+ }+ }++ #[test]+ fn generic_invalid_number_retains_dialog_without_creating_document() {+ let mut app = command_app("file.new", json!({"width": 0}));+ assert!(confirm(&mut app).is_err());+ assert!(app.session.active().is_none());+ let dialog = app.ui.dialog.as_ref().unwrap();+ assert_eq!(dialog.fields["width"], 0);+ assert!(dialog.fields["status"].as_str().unwrap().contains("page size out of range"));+ }++ #[test]+ fn style_options_preview_choice_is_remembered_on_reopen() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("style.paragraph.create", json!({"name":"Tutorial","chars":{"size":10}})).unwrap();+ open_style_options(&mut app, true, "Tutorial");+ let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::unique("style_preview_remember_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(3);+ h.get_by_label("Preview").click();+ h.run_steps(3);+ cancel(h.state_mut());+ open_style_options(h.state_mut(), true, "Tutorial");+ assert!(h.state().ui.dialog.as_ref().unwrap().b("preview"), "Preview stays checked on reopen");+ }++ #[test]+ fn style_options_preview_updates_all_uses_cancels_and_commits_once() {+ use egui_kittest::{Harness, kittest::Queryable};+ for paragraph in [true, false] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let f = app.run("frame.create", json!({"rect":[36,36,300,300],"content":"text","text":"First\nSecond"})).unwrap();+ app.run("text.select", json!({"story":f["story"],"anchor":0,"focus":12})).unwrap();+ let kind = if paragraph { "paragraph" } else { "character" };+ app.run(&format!("style.{kind}.create"), json!({"name":"Tutorial","chars":{"size":10}})).unwrap();+ app.run(&format!("style.{kind}.apply"), json!({"name":"Tutorial"})).unwrap();+ let before = app.session.doc().unwrap().doc.clone();+ let undo = app.session.doc().unwrap().history.undo.len();+ let journal = app.session.journal.len();+ open_style_options(&mut app, paragraph, "Tutorial");+ let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::unique("style_preview_test_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(3);+ h.get_by_label("Preview").click();+ h.run_steps(3);+ h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("c.size".into(), json!(18));+ h.run_steps(3);+ let app = h.state_mut();+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 18.0);+ assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);+ assert_eq!(app.session.journal.len(), journal);+ // Repeated previews replace each other, never accumulate undo entries.+ app.ui.dialog.as_mut().unwrap().fields.insert("c.size".into(), json!(20));+ h.run_steps(3);+ assert_eq!(h.state_mut().run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 20.0);+ h.get_by_label("Preview").click();+ h.run_steps(3);+ assert_eq!(h.state().session.doc().unwrap().doc, before);+ h.get_by_label("Preview").click();+ h.run_steps(3);+ cancel(h.state_mut());+ assert_eq!(h.state().session.doc().unwrap().doc, before);+ assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo);+ open_style_options(h.state_mut(), paragraph, "Tutorial");+ let d = h.state_mut().ui.dialog.as_mut().unwrap();+ d.fields.insert("preview".into(), json!(true));+ d.fields.insert("c.size".into(), json!(24));+ h.run_steps(3);+ confirm(h.state_mut()).unwrap();+ assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo + 1);+ // Both paragraphs/character runs still use the globally edited definition.+ for pos in [0, 6] {+ h.state_mut().run("text.select", json!({"story":f["story"],"anchor":pos,"focus":pos+1})).unwrap();+ assert_eq!(h.state_mut().run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 24.0);+ }+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(h.state().session.doc().unwrap().doc, before);+ }+ }++ #[test]+ fn style_preview_refuses_justification_spacing_ok_would_refuse() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let before = app.session.doc().unwrap().doc.clone();+ let mut d = Dialog::new("paragraphStyleOptions", json!({"name": designcraft_doc::BASIC_PARAGRAPH, "preview": true, "p.wordSpaceDesired": 1.1}));+ style_options_preview(&mut app, &mut d);+ assert_ne!(app.session.doc().unwrap().doc, before, "a valid value previews");+ // Minimum above Desired: the page goes back and the dialog says why.+ d.fields.insert("p.wordSpaceMin".into(), json!(1.5));+ style_options_preview(&mut app, &mut d);+ assert_eq!(app.session.doc().unwrap().doc, before);+ assert!(d.s("status").contains("Word Spacing"), "{:?}", d.fields.get("status"));+ assert!(app.session.doc().unwrap().interaction.is_none());+ }++ #[test]+ fn invalid_style_preview_leaves_the_starting_document_and_can_be_cancelled() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("style.character.create", json!({"name":"Emphasis"})).unwrap();+ let before = app.session.doc().unwrap().doc.clone();+ let mut d = Dialog::new("characterStyleOptions", json!({"name":"Emphasis","preview":true,"basedOn":"Emphasis"}));+ style_options_preview(&mut app, &mut d);+ assert!(d.fields.contains_key("status"));+ assert_eq!(app.session.doc().unwrap().doc, before);+ app.ui.dialog = Some(d);+ cancel(&mut app);+ assert_eq!(app.session.doc().unwrap().doc, before);+ assert!(app.session.doc().unwrap().interaction.is_none());+ }++ #[test]+ fn style_preview_rejects_conflicting_scalar_and_nested_rule_fields_without_panicking() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let before = app.session.doc().unwrap().doc.clone();+ let mut dialog = Dialog::new(+ "paragraphStyleOptions",+ json!({+ "name": designcraft_doc::BASIC_PARAGRAPH, "preview": true,+ "p.ruleAbove": false, "p.ruleAbove.weight": 2+ }),+ );+ style_options_preview(&mut app, &mut dialog);+ assert!(dialog.fields.contains_key("status"));+ assert_eq!(app.session.doc().unwrap().doc, before);+ app.ui.dialog = Some(dialog);+ cancel(&mut app);+ assert!(app.session.doc().unwrap().interaction.is_none());+ }++ #[test]+ fn text_frame_options_set_columns_baseline_and_wrap_as_indesign_does() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ // A 300 pt frame, 2 columns, 12 pt gutter (picas in the dialog).+ let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap();+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());+ app.run("object.textFrameOptions", json!({"ids": [id.0], "columns": 2, "gutter": 12})).unwrap();+ let opts = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone();+ let mut d = Dialog::new("textFrameOptions", json!({}));+ seed_text_frame_options(&app, &mut d);+ // Fixed Number shows each column's width: (300 - 12) / 2 = 144 pt.+ assert_eq!((d.s("columnsKind"), d.s("columnWidth"), d.s("firstBaseline")), ("fixedNumber".into(), "12p0".into(), "ascent".into()));+ for (k, v) in [+ ("columnsKind", json!("fixedWidth")),+ ("columnWidth", json!("10p0")),+ ("firstBaseline", json!("capHeight")),+ ("firstBaselineMin", json!("0p6")),+ ("balanceColumns", json!(true)),+ ("ignoreWrap", json!(true)),+ ] {+ d.fields.insert(k.into(), v);+ }+ app.ui.dialog = Some(d);+ confirm(&mut app).unwrap();+ let o = opts(&app);+ assert_eq!(o.columns_kind, designcraft_doc::ColumnsKind::FixedWidth);+ assert_eq!((o.column_width, o.first_baseline_min, o.columns), (120.0, 6.0, 2));+ assert_eq!(o.first_baseline, designcraft_doc::FirstBaseline::CapHeight);+ assert!(o.balance_columns && o.ignore_wrap);+ // Fixed Number again: the width isn't sent.+ let mut d = Dialog::new("textFrameOptions", json!({}));+ seed_text_frame_options(&app, &mut d);+ assert_eq!(d.s("columnWidth"), "10p0", "Fixed Width shows its own width");+ d.fields.insert("columnsKind".into(), json!("fixedNumber"));+ app.ui.dialog = Some(d);+ confirm(&mut app).unwrap();+ assert_eq!((opts(&app).columns_kind, opts(&app).column_width), (designcraft_doc::ColumnsKind::FixedNumber, 120.0));+ }++ #[test]+ fn baseline_grid_increment_error_explains_the_positive_measure_rule() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap();+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());+ for increment in ["0", "-1 pt", "not a measure"] {+ let mut d = Dialog::new("textFrameOptions", json!({}));+ seed_text_frame_options(&app, &mut d);+ d.fields.insert("customGrid".into(), json!(true));+ d.fields.insert("gridIncrement".into(), json!(increment));+ app.ui.dialog = Some(d);+ let error = confirm(&mut app).unwrap_err().to_string();+ assert!(error.contains("the baseline grid increment must be a measure greater than zero"), "{increment}: {error}");+ assert!(app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.baseline_grid.is_none());+ }+ }++ #[test]+ fn text_frame_options_set_a_custom_baseline_grid_relative_to() {+ use designcraft_doc::{FrameBaselineGrid, FrameGridRelative};+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap();+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());+ let grid = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.baseline_grid;+ let open = |app: &mut DesignApp, fields: &[(&str, Value)]| {+ let mut d = Dialog::new("textFrameOptions", json!({}));+ seed_text_frame_options(app, &mut d);+ for (k, v) in fields {+ d.fields.insert((*k).into(), v.clone());+ }+ app.ui.dialog = Some(d);+ confirm(app)+ };+ app.run("selection.set", json!({"ids": [id.0]})).unwrap();+ // Turned on, the grid takes the shown start and increment (the document grid's: 3p0 and 1p0).+ open(&mut app, &[("customGrid", json!(true)), ("gridRelativeTo", json!("frame"))]).unwrap();+ assert_eq!(grid(&app), Some(FrameBaselineGrid { start: 36.0, increment: 12.0, relative_to: FrameGridRelative::TopOfFrame }));+ // The dialog shows the frame's grid; changing Relative To keeps its start and increment.+ open(&mut app, &[("gridStart", json!("0p10"))]).unwrap();+ open(&mut app, &[("gridRelativeTo", json!("inset"))]).unwrap();+ assert_eq!(grid(&app), Some(FrameBaselineGrid { start: 10.0, increment: 12.0, relative_to: FrameGridRelative::TopInset }));+ open(&mut app, &[("customGrid", json!(false))]).unwrap();+ assert_eq!(grid(&app), None);+ }++ #[test]+ fn text_frame_options_change_only_what_was_edited() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap();+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());+ app.run("object.textFrameOptions", json!({"ids": [id.0], "columns": 2, "inset": [1, 2, 3, 4]})).unwrap();+ let opts = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone();+ let before = opts(&app);+ let open = |app: &mut DesignApp, fields: &[(&str, Value)]| {+ app.ui.dialog = Some(Dialog::new("textFrameOptions", json!({})));+ let mut d = app.ui.dialog.take().unwrap();+ seed_text_frame_options(app, &mut d);+ for (k, v) in fields {+ d.fields.insert((*k).into(), v.clone());+ }+ app.ui.dialog = Some(d);+ confirm(app)+ };+ // OK without edits changes nothing (no undo step either).+ assert_eq!(open(&mut app, &[]).unwrap(), Value::Null);+ assert_eq!(opts(&app), before);+ // The rule's weight is in points; unequal insets the user didn't touch stay.+ open(&mut app, &[("columnRule", json!(true)), ("columnRuleWeight", json!("6"))]).unwrap();+ let o = opts(&app);+ assert!(o.column_rule && o.column_rule_weight == 6.0, "{o:?}");+ assert_eq!((o.inset, o.columns, o.gutter), (before.inset, before.columns, before.gutter));+ // One of the rule's insets edited: the other rule settings stay.+ open(&mut app, &[("columnRuleBottomInset", json!("0p9")), ("columnRuleTint", json!("40"))]).unwrap();+ let o = opts(&app);+ assert_eq!((o.column_rule_bottom_inset, o.column_rule_top_inset, o.column_rule_offset, o.column_rule_weight), (9.0, 0.0, 0.0, 6.0));+ assert!((o.column_rule_tint - 0.4).abs() < 1e-6 && o.column_rule);+ // One inset side edited: the others keep their values.+ open(&mut app, &[("insetLeft", json!("1p0"))]).unwrap();+ assert_eq!(opts(&app).inset, [1.0, 12.0, 3.0, 4.0]);+ open(&mut app, &[("balanceColumns", json!(true))]).unwrap();+ let o = opts(&app);+ assert!(o.balance_columns && o.column_rule && o.columns == 2, "{o:?}");+ // An unknown swatch is an error and the dialog stays open.+ let e = open(&mut app, &[("columnRuleColor", json!("Mauve"))]).unwrap_err();+ assert!(e.contains("Mauve") && app.ui.dialog.is_some(), "{e}");+ assert_eq!(opts(&app).column_rule_color, designcraft_color::swatch::BLACK);+ // Each OK is one undo step.+ for _ in 0..4 {+ app.run("edit.undo", json!({})).unwrap();+ }+ assert_eq!(opts(&app), before);+ }++ #[test]+ fn toc_dialog_adds_a_style_and_ok_makes_the_table_of_contents() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.newSample", json!({})).unwrap();+ crate::menus::activate(&mut app, "toc.generate", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some(TOC));+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in+ ["Table of Contents", "Title:", "Include Paragraph Styles:", "Other Styles:", "« Add", "Remove »", "Replace Existing Table of Contents"]+ {+ visible_label(&labels, screen, expected);+ }+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Headline").center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "« Add").center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in ["Entry Style:", "TOC Level 1", "After Entry", "Between Entry and Number:", "Level:"] {+ visible_label(&labels, screen, expected);+ }+ let undo = app.session.doc().unwrap().history.undo.len();+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "OK").center());+ assert!(app.ui.dialog.is_none());+ let d = &app.session.doc().unwrap().doc;+ let toc = d.toc.clone().unwrap();+ assert_eq!(toc.entries, vec![designcraft_doc::TocEntry::new("Headline", 1)]);+ let text = &d.story(toc.story).unwrap().text;+ assert!(text.starts_with("Contents\n") && text.contains("\nNotes on the Grid\t"), "{text}");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);+ // Reopened, the dialog shows the table of contents and replaces it.+ crate::menus::activate(&mut app, "toc.generate", &Value::Null);+ let d = app.ui.dialog.as_ref().unwrap();+ assert!(d.b("replace"));+ assert_eq!(toc_rows(d).iter().map(|r| r.style.as_str()).collect::<Vec<_>>(), ["Headline"]);+ }++ #[test]+ fn margins_and_columns_link_arithmetic_preview_and_one_undo_step() {+ // Adobe's "Set up a modern magazine layout" (1:41–3:04): linked margins to 0.4375 in, then+ // 5 columns with a 0.1875 in gutter, unlinked, and "*2" typed after the outside margin.+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"preset": "A4", "pages": 3, "facingPages": true, "margins": 36})).unwrap();+ app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0)));+ open_margins_and_columns(&mut app);+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));+ let mut labels = vec![];+ for _ in 0..3 {+ labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ for expected in+ ["Margins and Columns", "Margins", "Top:", "Bottom:", "Inside:", "Outside:", "Columns", "Number:", "Gutter:", "Adjust Layout", "Preview"]+ {+ visible_label(&labels, screen, expected);+ }+ let d = app.ui.dialog.as_ref().unwrap();+ assert!(d.b("link"), "four equal margins open linked");+ // Linked: one margin typed is all four.+ app.ui.dialog.as_mut().unwrap().fields.insert("marginTop".into(), json!("0.4375 in"));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let d = app.ui.dialog.as_ref().unwrap();+ assert!(MARGIN_FIELDS.iter().all(|(k, _, _)| d.s(k) == "0.4375 in"), "{:?}", d.fields);+ // Preview: the page changes, with no undo step.+ let undo = app.session.doc().unwrap().history.undo.len();+ app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let top = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].pages[0].margins.top;+ assert!((top(&app) - 31.5).abs() < 1e-6, "previewed: {}", top(&app));+ assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);+ // Unlinked (the link button), the outside margin alone: "*2" typed after it is worked out+ // when the field is left.+ app.ui.dialog.as_mut().unwrap().fields.insert("link".into(), json!(false));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };+ let field = labels+ .iter()+ .filter(|(t, _, _)| t.trim() == "0.4375 in")+ .map(|(_, r, _)| *r)+ .max_by(|a, b| (a.max.x + a.max.y).total_cmp(&(b.max.x + b.max.y)))+ .unwrap();+ click_dialog(&mut app, &ctx, screen, field.center());+ dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::End), egui::Event::Text("*2".into())]);+ dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Tab)]);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let d = app.ui.dialog.as_ref().unwrap();+ assert!(+ !d.s("marginOutside").contains('*') && (d.m("marginOutside").unwrap() - 63.0).abs() < 1e-6,+ "worked out on leaving the field: {}",+ d.s("marginOutside")+ );+ let d = app.ui.dialog.as_mut().unwrap();+ d.fields.insert("link".into(), json!(false));+ for (k, v) in [("marginOutside", "0.4375 in*2"), ("columns", "5"), ("gutter", "0.1875 in"), ("target", "all")] {+ d.fields.insert(k.into(), json!(v));+ }+ dialog_frame(&mut app, &ctx, screen, vec![]);+ confirm(&mut app).unwrap();+ let pg = app.session.doc().unwrap().doc.spreads[1].pages[0].clone();+ assert_eq!((pg.margins.top, pg.margins.outside, pg.columns.count), (31.5, 63.0, 5));+ assert!((pg.columns.gutter - 13.5).abs() < 1e-6);+ assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step");+ // Cancel after a preview puts the page back.+ open_margins_and_columns(&mut app);+ let d = app.ui.dialog.as_mut().unwrap();+ d.fields.insert("preview".into(), json!(true));+ d.fields.insert("columns".into(), json!("2"));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ cancel(&mut app);+ assert_eq!(app.session.doc().unwrap().doc.spreads[1].pages[0].columns.count, 5);+ }++ #[test]+ fn create_guides_reads_like_indesigns_and_previews() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 1, "facingPages": false})).unwrap();+ app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0)));+ open_create_guides(&mut app);+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));+ let mut labels = vec![];+ for _ in 0..3 {+ labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ for expected in ["Create Guides", "Rows", "Columns", "Options", "Fit Guides to:", "Margins", "Page", "Remove Existing Ruler Guides", "Preview"] {+ visible_label(&labels, screen, expected);+ }+ // Rows and Columns side by side.+ let (r, c) = (visible_label(&labels, screen, "Rows"), visible_label(&labels, screen, "Columns"));+ assert!((r.center().y - c.center().y).abs() < 2.0 && r.center().x < c.center().x);+ // Thirds, single guides, fitted to the page: clicking the Page radio.+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Page").center());+ let d = app.ui.dialog.as_mut().unwrap();+ assert_eq!(d.s("fitTo"), "page");+ d.fields.insert("rows".into(), json!("3"));+ d.fields.insert("rowGutter".into(), json!("0"));+ d.fields.insert("preview".into(), json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let guides = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].pages[0].guides.len();+ assert_eq!(guides(&app), 2, "previewed");+ confirm(&mut app).unwrap();+ assert_eq!(guides(&app), 2, "made once");+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(guides(&app), 0, "one undo step");+ }++ fn dialog_context(language: &str) -> egui::Context {+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx, language);+ crate::theme::apply(&ctx, &crate::theme::Tokens::for_brightness(crate::theme::Brightness::default()));+ ctx+ }++ fn dialog_frame(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, events: Vec<egui::Event>) -> Vec<(String, egui::Rect, egui::Rect)> {+ let time = ctx.input(|i| i.time) + 1.0 / 60.0;+ let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), events, ..Default::default() }, |ui| {+ show(app, ui.ctx());+ });+ output.textures_delta.clear();+ fn collect(shape: &egui::Shape, clip: egui::Rect, labels: &mut Vec<(String, egui::Rect, egui::Rect)>) {+ match shape {+ egui::Shape::Text(t) => labels.push((t.galley.job.text.clone(), t.visual_bounding_rect(), clip)),+ egui::Shape::Vec(shapes) => {+ for s in shapes {+ collect(s, clip, labels);+ }+ }+ _ => {}+ }+ }+ let mut labels = Vec::new();+ for shape in output.shapes {+ collect(&shape.shape, shape.clip_rect, &mut labels);+ }+ labels+ }++ /// What Find/Change's Search list shows for a scope.+ fn scope_label(scope: &str) -> &'static str {+ match scope {+ "story" => "Story",+ "selection" => "Selection",+ _ => "Document",+ }+ }++ fn visible_label(labels: &[(String, egui::Rect, egui::Rect)], screen: egui::Rect, expected: &str) -> egui::Rect {+ let (_, rect, clip) = labels.iter().find(|(text, _, _)| text.trim() == expected).unwrap_or_else(|| panic!("{expected} is painted"));+ assert!(screen.contains_rect(*rect), "{expected} must stay on screen: {rect:?}");+ assert!(clip.expand(0.5).contains_rect(*rect), "{expected} must not be clipped: {rect:?}, {clip:?}");+ *rect+ }++ fn click_dialog(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, pos: egui::Pos2) {+ for pressed in [true, false] {+ dialog_frame(+ app,+ ctx,+ screen,+ vec![+ egui::Event::PointerMoved(pos),+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },+ ],+ );+ }+ }++ fn scroll_dialog(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, pos: egui::Pos2, delta: egui::Vec2) {+ dialog_frame(+ app,+ ctx,+ screen,+ vec![+ egui::Event::PointerMoved(pos),+ egui::Event::MouseWheel {+ unit: egui::MouseWheelUnit::Point,+ delta,+ phase: egui::TouchPhase::Move,+ modifiers: egui::Modifiers::NONE,+ source: egui::MouseWheelSource::Unknown,+ },+ ],+ );+ // Let smooth wheel scrolling and scrollbar visibility settle before clicking.+ for _ in 0..30 {+ dialog_frame(app, ctx, screen, vec![]);+ }+ }++ fn scope_control(app: &mut DesignApp, ctx: &egui::Context, method: &str, params: Value) -> Value {+ let (request, _reply) = crate::control::ControlRequest::new(method, params);+ let crate::control::Outcome::Done(value) = crate::control::handle(app, ctx, &request) else { panic!("ordinary control response") };+ assert_eq!(value["ok"], true, "{value}");+ value["result"].clone()+ }++ fn scope_click(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, label: &str) {+ let labels = dialog_frame(app, ctx, screen, vec![]);+ let pos = visible_label(&labels, screen, label).center();+ click_dialog(app, ctx, screen, pos);+ }++ fn scope_dialog() -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) {+ scope_dialog_with_selection("red red | red", 7)+ }++ fn scope_dialog_with_selection(text: &str, end: usize) -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) {+ scope_dialog_with_tool(text, end, None)+ }++ fn scope_dialog_with_tool(text: &str, end: usize, tool: Option<&str>) -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.language = "en".into();+ app.run("file.new", json!({})).unwrap();+ let frame = app.run("frame.create", json!({"rect": [36, 36, 100, 100], "content": "text", "text": text})).unwrap();+ let sid = designcraft_engine::doc::StoryId(frame["story"].as_u64().unwrap());+ let ctx = dialog_context("en");+ if let Some(tool) = tool {+ scope_control(&mut app, &ctx, "ui.tool.select", json!({"tool": tool}));+ }+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": end})).unwrap();+ app.run("app.findChange", json!({})).unwrap();+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));+ for (field, value) in [("find", "red"), ("change", "unused")] {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));+ }+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ scope_click(&mut app, &ctx, screen, "Document");+ scope_click(&mut app, &ctx, screen, "Selection");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("scope"), "selection");+ (app, ctx, screen, sid)+ }++ fn scope_selected(app: &DesignApp, sid: designcraft_engine::doc::StoryId, a: usize, b: usize) {+ let t = app.session.doc().unwrap().selection.text.unwrap();+ assert_eq!((t.story, t.range(), t.cell), (sid, a..b, None));+ }++ fn scope_state_unchanged(app: &DesignApp, before: &designcraft_engine::DocState) {+ let after = app.session.doc().unwrap();+ assert!(std::sync::Arc::ptr_eq(&before.doc, &after.doc));+ assert_eq!(after.uid, before.uid);+ assert_eq!(after.revision, before.revision);+ assert_eq!(after.selection, before.selection);+ assert_eq!(after.history.limit, before.history.limit);+ for (actual, expected) in [(&after.history.undo, &before.history.undo), (&after.history.redo, &before.history.redo)] {+ assert_eq!(actual.len(), expected.len());+ for (a, b) in actual.iter().zip(expected) {+ assert_eq!(a.label, b.label);+ assert_eq!(a.selection, b.selection);+ assert!(std::sync::Arc::ptr_eq(&a.doc, &b.doc));+ }+ }+ }++ #[test]+ fn find_scope_dialog_control_effective_noops_retain_bounds() {+ for (field, value) in [("objectMode", json!(false)), ("story", Value::Null)] {+ let (mut app, ctx, screen, sid) = scope_dialog();+ assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key(field));+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ let before = app.session.doc().unwrap().clone();+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields[field], value);+ scope_state_unchanged(&app, &before);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 4, 7);+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);+ }+ }++ #[test]+ fn find_scope_dialog_explicit_story_ignored_scope_preserves_grep_cursor() {+ for physical in [false, true] {+ for (text, pattern, hits, changed) in [+ ("é", "é|(?:)", vec![(0, 2)], "X"),+ ("é🙂", "é|(?:)", vec![(0, 2), (6, 6)], "X🙂X"),+ ("é🙂", "(?:)", vec![(0, 0), (2, 2), (6, 6)], "XéX🙂X"),+ ] {+ let (mut app, ctx, screen, sid) = scope_dialog_with_selection(text, 0);+ for (field, value) in [("find", json!(pattern)), ("change", json!("X")), ("story", json!(sid.0))] {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));+ }+ scope_click(&mut app, &ctx, screen, "GREP");+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} match(es)", hits.len()));+ for &(a, b) in &hits {+ scope_click(&mut app, &ctx, screen, "Find Next");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "Found");+ scope_selected(&app, sid, a, b);+ let before = app.session.doc().unwrap().clone();+ let cur = app.ui.dialog.as_ref().unwrap().s("scope");+ let next = if cur == "selection" { "document" } else { "selection" };+ if physical {+ scope_click(&mut app, &ctx, screen, scope_label(&cur));+ scope_click(&mut app, &ctx, screen, scope_label(next));+ } else {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": next}));+ }+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("scope"), next);+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields["story"], json!(sid.0));+ scope_state_unchanged(&app, &before);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} match(es)", hits.len()));+ }+ scope_click(&mut app, &ctx, screen, "Find Next");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches");+ // An ignored scope change must not revive an exhausted endpoint either.+ let before = app.session.doc().unwrap().clone();+ let cur = app.ui.dialog.as_ref().unwrap().s("scope");+ let next = if cur == "selection" { "document" } else { "selection" };+ if physical {+ scope_click(&mut app, &ctx, screen, scope_label(&cur));+ scope_click(&mut app, &ctx, screen, scope_label(next));+ } else {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": next}));+ }+ scope_click(&mut app, &ctx, screen, "Find Next");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches");+ scope_state_unchanged(&app, &before);+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} replacement(s) made", hits.len()));+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, changed);+ }+ }+ }++ #[test]+ fn find_scope_dialog_explicit_story_transitions_reset_cursor() {+ for remove_override in [false, true] {+ let (mut app, ctx, screen, sid) = scope_dialog_with_selection("é🙂", 0);+ let other = app.run("frame.create", json!({"rect": [180, 36, 100, 100], "content": "text", "text": "other"})).unwrap();+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();+ for (field, value) in [("find", json!("(?:)")), ("story", json!(sid.0))] {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));+ }+ scope_click(&mut app, &ctx, screen, "GREP");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 0);+ let before = app.session.doc().unwrap().clone();+ let value = if remove_override { Value::Null } else { other["story"].clone() };+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": value}));+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": sid.0}));+ scope_state_unchanged(&app, &before);+ // Away and back still releases continuation even if no Find command intervenes.+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 0);+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 2, 2);+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "é🙂");+ let other_sid = designcraft_engine::doc::StoryId(other["story"].as_u64().unwrap());+ assert_eq!(app.session.doc().unwrap().doc.story(other_sid).unwrap().text, "other");+ }+ }++ #[test]+ fn find_scope_dialog_control_mode_changes_release_bounds() {+ for object_mode in [false, true] {+ let (mut app, ctx, _, sid) = scope_dialog();+ if object_mode {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "objectMode", "value": true}));+ }+ // Direct Session consumers share the retained domain even while Object is shown.+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));+ assert_eq!(count.as_array().unwrap().len(), 2);+ scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.next", "params": p}));+ scope_selected(&app, sid, 0, 3);+ let before = app.session.doc().unwrap().clone();+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "objectMode", "value": !object_mode}));+ assert_eq!(app.ui.dialog.as_ref().unwrap().b("objectMode"), !object_mode);+ scope_state_unchanged(&app, &before);+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));+ assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));+ let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p}));+ assert_eq!(changed, json!({"count": 1}));+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");+ }+ }++ #[test]+ fn find_scope_dialog_tool_replacement_releases_bounds() {+ for (tool, replacement) in [("page", "cmd:layout.pageSize"), ("rectangleFrame", "frameSize")] {+ let (mut app, ctx, screen, sid) = scope_dialog_with_tool("red red | red", 7, Some(tool));+ assert_eq!(app.session.tool_id(), tool);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ let before = app.session.doc().unwrap().clone();+ let active = (app.session.active_index(), app.session.documents().len());+ let off = app.session.layout().xf(designcraft_engine::doc::SpreadRef::Doc(0)).translation();+ let x = off.x + before.doc.spreads[0].pages[0].x + 200.0;+ let y = off.y + 200.0;+ // The Page tool opens Page Size on a double-click (a click selects the page).+ let events = if tool == "page" {+ json!([{"kind": "doubleclick", "x": x, "y": y}])+ } else {+ json!([{"kind": "down", "x": x, "y": y}, {"kind": "up", "x": x, "y": y}])+ };+ // Real tool -> Action::Dialog -> after_engine; no injected UI request.+ scope_control(&mut app, &ctx, "ui.pointer", json!({"events": events}));+ assert_eq!(app.ui.dialog.as_ref().unwrap().id, replacement);+ assert!(app.session.ui_requests.is_empty());+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);+ scope_state_unchanged(&app, &before);+ scope_click(&mut app, &ctx, screen, "Cancel");+ assert!(app.ui.dialog.is_none());+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);+ scope_state_unchanged(&app, &before);+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));+ assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));+ scope_state_unchanged(&app, &before);+ let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p}));+ assert_eq!(changed, json!({"count": 1}));+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);+ }+ }++ #[test]+ fn find_scope_dialog_tool_without_replacement_retains_bounds() {+ for tool in ["page", "rectangleFrame"] {+ let (mut app, ctx, screen, sid) = scope_dialog_with_tool("red red | red", 7, Some(tool));+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ let before = app.session.doc().unwrap().clone();+ let fields = app.ui.dialog.as_ref().unwrap().fields.clone();+ scope_control(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "move", "x": 200, "y": 200}]}));+ assert_eq!(app.ui.dialog.as_ref().unwrap().id, "findChange");+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields, fields);+ scope_state_unchanged(&app, &before);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 4, 7);+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");+ }+ }++ #[cfg(not(target_arch = "wasm32"))]+ #[test]+ fn find_scope_dialog_native_pdf_replacement_releases_bounds() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("three.pdf");+ std::fs::write(&path, crate::browser_import_tests::pdf()).unwrap();+ for dismissal in ["Cancel", "Escape", "control"] {+ let (mut app, ctx, screen, sid) = scope_dialog();+ let picked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let read = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let seen_pick = picked.clone();+ let seen_read = read.clone();+ let pick_path = path.to_string_lossy().to_string();+ let read_path = pick_path.clone();+ app.answer_dialogs(move |request| {+ assert_eq!(place_filter(request), Some("Graphics and text"));+ seen_pick.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ craft_dialogs::Answer::Paths(vec![pick_path.clone().into()])+ });+ app.services.read = Some(Box::new(move |path| {+ assert_eq!(path, read_path);+ seen_read.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ std::fs::read(path).map_err(|e| e.to_string())+ }));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ let before = app.session.doc().unwrap().clone();+ let active = (app.session.active_index(), app.session.documents().len());+ // Exercise engine.execute -> UiRequest::Pick -> native host PDF replacement.+ scope_control(&mut app, &ctx, "engine.execute", json!({"command": "file.place", "params": {}}));+ app.settle_dialogs();+ assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1);+ assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 1);+ let dialog = app.ui.dialog.as_ref().unwrap();+ assert_eq!(dialog.id, "pdfImport");+ assert_eq!(dialog.s("path"), path.to_string_lossy());+ assert_eq!(dialog.fields["pages"], 3);+ assert_eq!(dialog.s("page"), "1");+ assert!(!dialog.b("async"));+ assert_eq!(dialog.fields["target"], json!(before.uid));+ assert!(app.session.ui_requests.is_empty());+ assert!(app.pending_pdf.is_none());+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);+ scope_state_unchanged(&app, &before);+ match dismissal {+ "Cancel" => scope_click(&mut app, &ctx, screen, "Cancel"),+ "Escape" => {+ dialog_frame(+ &mut app,+ &ctx,+ screen,+ vec![egui::Event::Key {+ key: egui::Key::Escape,+ physical_key: None,+ pressed: true,+ repeat: false,+ modifiers: egui::Modifiers::NONE,+ }],+ );+ }+ "control" => {+ scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({}));+ }+ _ => panic!("known dismissal"),+ }+ assert!(app.ui.dialog.is_none());+ assert!(app.pending_pdf.is_none());+ assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1);+ assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 1);+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);+ scope_state_unchanged(&app, &before);+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));+ assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));+ scope_state_unchanged(&app, &before);+ let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p}));+ assert_eq!(changed, json!({"count": 1}));+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);+ }+ }++ /// The first file type an open dialog offers: Place's is "Graphics and text".+ fn place_filter(request: &craft_dialogs::Request) -> Option<&str> {+ let craft_dialogs::Request::File(dialog) = request else { return None };+ dialog.filters.first().map(|filter| filter.name.as_str())+ }++ #[cfg(not(target_arch = "wasm32"))]+ #[test]+ fn find_scope_dialog_native_picker_cancel_retains_bounds() {+ let (mut app, ctx, screen, sid) = scope_dialog();+ let picked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let seen = picked.clone();+ app.answer_dialogs(move |request| {+ assert_eq!(place_filter(request), Some("Graphics and text"));+ seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ craft_dialogs::Answer::Cancelled+ });+ let read = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let seen_read = read.clone();+ app.services.read = Some(Box::new(move |_| {+ seen_read.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ Err("canceled picker must not read".into())+ }));+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ let before = app.session.doc().unwrap().clone();+ let active = (app.session.active_index(), app.session.documents().len());+ let fields = app.ui.dialog.as_ref().unwrap().fields.clone();+ scope_control(&mut app, &ctx, "engine.execute", json!({"command": "file.place", "params": {}}));+ app.settle_dialogs();+ assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1);+ assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 0);+ assert_eq!(app.ui.dialog.as_ref().unwrap().id, "findChange");+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields, fields);+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);+ scope_state_unchanged(&app, &before);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 4, 7);+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);+ }++ #[test]+ fn find_scope_dialog_exact_baseline_buttons() {+ let (mut app, ctx, screen, sid) = scope_dialog_with_selection("red red", 3);+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 replacement(s) made");+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red");+ }++ #[test]+ fn find_scope_dialog_grep_tab_alone_restarts_original_selection() {+ let (mut app, ctx, screen, sid) = scope_dialog();+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_click(&mut app, &ctx, screen, "GREP");+ assert!(app.ui.dialog.as_ref().unwrap().b("grep"));+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("find"), "red");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 4, 7);+ scope_click(&mut app, &ctx, screen, "Text");+ assert!(!app.ui.dialog.as_ref().unwrap().b("grep"));+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ }++ #[test]+ fn find_scope_dialog_buttons_retain_nonempty_hits_and_change_all() {+ let (mut app, ctx, screen, sid) = scope_dialog();+ let history = app.session.doc().unwrap().history.undo.len();+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 4, 7);+ scope_click(&mut app, &ctx, screen, "Find Next");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches");+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history);+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1);+ scope_click(&mut app, &ctx, screen, "Cancel");+ assert!(app.ui.dialog.is_none());+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");+ app.run("edit.redo", json!({})).unwrap();+ let native = app.run("file.serialize", json!({})).unwrap();+ app.run("file.openBytes", json!({"name": "scope.designcraft", "base64": native["base64"]})).unwrap();+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");+ }++ fn scope_confirm_case(action: &str) {+ let (mut app, ctx, screen, sid) = scope_dialog();+ scope_click(&mut app, &ctx, screen, "Count");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ match action {+ "OK" => scope_click(&mut app, &ctx, screen, "OK"),+ "Enter" => {+ dialog_frame(+ &mut app,+ &ctx,+ screen,+ vec![egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }],+ );+ }+ "control" => {+ assert_eq!(scope_control(&mut app, &ctx, "ui.dialog.confirm", json!({}))["count"], 2);+ }+ _ => panic!("known confirmation route"),+ }+ assert!(app.ui.dialog.is_none());+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");+ // The closed dialog cannot leave its old seven-byte range for a later direct query.+ let matches = app.run("find.find", json!({"find": "blue", "scope": "selection"})).unwrap();+ assert_eq!(matches.as_array().unwrap().len(), 0);+ }++ #[test]+ fn find_scope_dialog_ok_consumes_retained_bounds() {+ scope_confirm_case("OK");+ }++ #[test]+ fn find_scope_dialog_enter_consumes_retained_bounds() {+ scope_confirm_case("Enter");+ }++ #[test]+ fn find_scope_dialog_control_confirm_consumes_retained_bounds() {+ scope_confirm_case("control");+ }++ #[test]+ fn find_scope_dialog_query_reselection_cancel_and_reopen() {+ let (mut app, ctx, screen, sid) = scope_dialog();+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "grep", "value": true}));+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "find", "value": "r.d"}));+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({}));+ assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1);+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 7})).unwrap();+ app.run("find.next", json!({"find": "red", "scope": "selection"})).unwrap();+ scope_control(&mut app, &ctx, "ui.dialog.open", json!({"id": "findChange", "fields": {"find": "red", "scope": "selection"}}));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");+ app.run("text.select", json!({"story": sid.0, "anchor": 4, "focus": 7})).unwrap();+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 4, 7);+ app.run("app.findChange", json!({})).unwrap();+ for (field, value) in [("find", "red"), ("scope", "selection")] {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));+ }+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");+ }++ #[test]+ fn find_scope_dialog_word_reselection_limits_count_and_change_buttons() {+ let (mut app, ctx, screen, sid) = scope_dialog();+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ let selected = app.session.doc().unwrap().selection.clone();+ let frame = selected.text.unwrap().frame.unwrap();+ let point = {+ let st = app.session.doc().unwrap();+ let cs = app.session.cache.get(&st.doc, sid, None);+ let (fi, x, baseline, ascent, _) = designcraft_compose::caret(&cs, 1).unwrap();+ let inner = designcraft_geom::Point::new(x, baseline - ascent * 0.5);+ assert_eq!(cs.frames[fi].frame, frame);+ assert_eq!(designcraft_compose::hit(&cs, fi, inner), Some(1));+ let loc = st.doc.find(frame).unwrap();+ st.doc.parent_xf(&loc) * st.doc.text_xf(st.doc.item(frame).unwrap()) * inner+ };+ let before = app.session.doc().unwrap().doc.clone();+ let revision = app.session.doc().unwrap().revision;+ app.run("text.selectWord", json!({"frame": frame.0, "point": [point.x, point.y]})).unwrap();+ assert_eq!(app.session.doc().unwrap().selection, selected);+ assert!(app.session.doc().unwrap().revision > revision, "a new revision");+ assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 replacement(s) made");+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");+ }++ #[cfg(not(target_arch = "wasm32"))]+ #[test]+ fn find_scope_dialog_failed_native_drop_alert_releases_bounds() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("broken.designcraft");+ std::fs::write(&path, b"not a native document").unwrap();+ for dismissal in ["OK", "Escape", "control"] {+ let (mut app, ctx, screen, sid) = scope_dialog();+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ let before = app.session.doc().unwrap().doc.clone();+ let selected = app.session.doc().unwrap().selection.clone();+ let revision = app.session.doc().unwrap().revision;+ let history = app.session.doc().unwrap().history.undo.len();+ let uid = app.session.doc().unwrap().uid;+ let error = app.open_dropped(&path.to_string_lossy()).unwrap_err();+ let alert = app.ui.dialog.as_ref().unwrap();+ assert_eq!(alert.id, "alert");+ assert_eq!(alert.s("title"), "Can't Open the File");+ assert_eq!(alert.s("message"), error);+ assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc));+ assert_eq!(app.session.doc().unwrap().selection, selected);+ assert_eq!(app.session.doc().unwrap().revision, revision);+ assert_eq!(app.session.doc().unwrap().uid, uid);+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history);+ match dismissal {+ "OK" => scope_click(&mut app, &ctx, screen, "OK"),+ "Escape" => {+ dialog_frame(+ &mut app,+ &ctx,+ screen,+ vec![egui::Event::Key {+ key: egui::Key::Escape,+ physical_key: None,+ pressed: true,+ repeat: false,+ modifiers: egui::Modifiers::NONE,+ }],+ );+ }+ "control" => {+ scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({}));+ }+ _ => panic!("known dismissal"),+ }+ assert!(app.ui.dialog.is_none());+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});+ assert_eq!(app.run("find.find", p.clone()).unwrap(), json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));+ assert_eq!(app.run("find.change", p).unwrap(), json!({"count": 1}));+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1);+ }+ }++ #[test]+ fn find_scope_dialog_child_errors_and_explicit_parent() {+ let (mut app, ctx, screen, sid) = scope_dialog();+ app.run("text.select", json!({"story": sid.0, "anchor": 13, "focus": 13})).unwrap();+ app.run("table.insert", json!({"rows": 1, "cols": 1})).unwrap();+ app.run("text.insert", json!({"text": "red child", "raw": true})).unwrap();+ let child = app.session.doc().unwrap().selection.text.unwrap();+ let before = app.session.doc().unwrap().doc.clone();+ let selection = app.session.doc().unwrap().selection.clone();+ let history = app.session.doc().unwrap().history.undo.len();+ for label in ["Count", "Find Next", "Change All"] {+ scope_click(&mut app, &ctx, screen, label);+ assert!(app.ui.dialog.as_ref().unwrap().s("status").contains("not supported"));+ assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc));+ assert_eq!(app.session.doc().unwrap().selection, selection);+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history);+ }+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": sid.0}));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "3 match(es)");+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "3 replacement(s) made");+ assert_eq!(app.session.doc().unwrap().doc.text_story(sid, child.cell).unwrap().text, "red child");+ assert!(app.session.doc().unwrap().doc.story(sid).unwrap().text.starts_with("blue blue | blue"));+ }++ #[test]+ fn find_scope_dialog_error_confirmation_and_escape_release_context() {+ for escape in [false, true] {+ let (mut app, ctx, screen, sid) = scope_dialog();+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ if escape {+ dialog_frame(+ &mut app,+ &ctx,+ screen,+ vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }],+ );+ } else {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "find", "value": "["}));+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "grep", "value": true}));+ scope_click(&mut app, &ctx, screen, "OK");+ }+ assert!(app.ui.dialog.is_none());+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");+ assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1);+ }+ }++ #[test]+ fn find_scope_dialog_domain_and_object_changes_release_original_range() {+ for route in ["scope", "object", "menu", "command"] {+ let (mut app, ctx, screen, _) = scope_dialog();+ scope_click(&mut app, &ctx, screen, "Find Next");+ match route {+ "scope" => {+ for scope in ["story", "selection"] {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": scope}));+ }+ }+ "object" => {+ scope_click(&mut app, &ctx, screen, "Object");+ scope_click(&mut app, &ctx, screen, "Text");+ }+ "menu" => crate::menus::activate(&mut app, "app.newDocumentDialog", &Value::Null),+ "command" => {+ app.run("app.newDocumentDialog", json!({})).unwrap();+ }+ _ => panic!("known reset route"),+ }+ assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1);+ }+ }++ #[test]+ fn dialog_title_and_actions_fit_scaled_viewports() {+ for language in ["en", "ar"] {+ for size in [egui::vec2(1178.0, 814.0), egui::vec2(589.0, 407.0), egui::vec2(392.0, 271.0), egui::vec2(360.0, 280.0)] {+ for (command, title, ok, cancel) in+ [("app.preferences", "Preferences", "OK", "Cancel"), ("app.newDocumentDialog", "New Document", "Create", "Close")]+ {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.language = language.into();+ app.run("file.new", json!({})).unwrap();+ app.run(command, json!({})).unwrap();+ let ctx = dialog_context(language);+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size);+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in [title, ok, cancel] {+ visible_label(&labels, screen, crate::i18n::tr(language, expected));+ }+ }+ }+ }+ }++ #[test]+ fn preferences_first_setting_switches_interface_language() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("app.preferences", json!({})).unwrap();+ let ctx = dialog_context("");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let heading = visible_label(&labels, screen, "Interface Language");+ let combo = visible_label(&labels, screen, "English");+ let scaling = visible_label(&labels, screen, "When Scaling");+ assert!(heading.bottom() <= combo.top() && combo.bottom() <= scaling.top(), "the language comes first: {heading:?} {combo:?} {scaling:?}");+ let pane = labels.iter().filter(|(_, rect, _)| rect.left() >= heading.left() - 1.0 && rect.top() < heading.top());+ assert!(pane.clone().all(|(text, _, _)| text == "Preferences"), "nothing above it: {:?}", pane.collect::<Vec<_>>());++ // Choosing a language applies it at once; the dialog stays open.+ click_dialog(&mut app, &ctx, screen, combo.center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for (_, name) in crate::i18n::LANGUAGES {+ assert!(labels.iter().any(|(text, _, _)| text == name), "{name} is listed by its own name");+ }+ let deutsch = visible_label(&labels, screen, "Deutsch").center();+ click_dialog(&mut app, &ctx, screen, deutsch);+ assert_eq!(app.ui.language, "de");+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("preferences"));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let heading = visible_label(&labels, screen, crate::i18n::tr("de", "Interface Language"));+ let combo = visible_label(&labels, screen, "Deutsch");++ // The names stay endonyms in the German interface.+ click_dialog(&mut app, &ctx, screen, combo.center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for name in ["English", "Français", "日本語", "Українська"] {+ assert!(labels.iter().any(|(text, _, _)| text == name), "{name}");+ }+ click_dialog(&mut app, &ctx, screen, heading.center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(!labels.iter().any(|(text, _, _)| text == "Français"), "the list closes");++ // The control channel's command and the combo show the same setting.+ app.run("app.language", json!({"lang": "ja"})).unwrap();+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(labels.iter().any(|(text, _, _)| text == "日本語"));+ assert!(labels.iter().any(|(text, _, _)| text == crate::i18n::tr("ja", "Interface Language")));++ // Cancel puts back the language the dialog opened with; OK keeps the choice.+ let cancel_button = visible_label(&labels, screen, crate::i18n::tr("ja", "Cancel")).center();+ click_dialog(&mut app, &ctx, screen, cancel_button);+ assert!(app.ui.dialog.is_none());+ assert_eq!(app.ui.language, "");+ app.run("app.preferences", json!({})).unwrap();+ app.run("app.language", json!({"lang": "it"})).unwrap();+ confirm(&mut app).unwrap();+ assert_eq!(app.ui.language, "it");+ app.run("app.preferences", json!({})).unwrap();+ app.run("app.language", json!({"lang": "uk"})).unwrap();+ cancel(&mut app);+ assert_eq!(app.ui.language, "it");+ }++ /// Preferences › Interface › Panels holds Auto-Collapse Iconic Panels, the same setting as the+ /// iconic column's menu.+ #[test]+ fn preferences_set_auto_collapse_iconic_panels() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("app.preferences", json!({})).unwrap();+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields["autoCollapseIconicPanels"], json!(false));+ app.ui.dialog.as_mut().unwrap().fields.insert("autoCollapseIconicPanels".into(), json!(true));+ confirm(&mut app).unwrap();+ assert!(app.ui.dock_auto_collapse);+ app.run("app.preferences", json!({})).unwrap();+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields["autoCollapseIconicPanels"], json!(true));+ }++ #[test]+ fn preferences_sidebar_scroll_keeps_selected_options_visible() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("app.preferences", json!({})).unwrap();+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(589.0, 407.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let sidebar = visible_label(&labels, screen, "General").center();+ assert!(!labels.iter().any(|(text, rect, clip)| text == "File Handling" && clip.contains_rect(*rect)), "last section starts below the sidebar");+ scroll_dialog(&mut app, &ctx, screen, sidebar, egui::vec2(0.0, -600.0));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let files = visible_label(&labels, screen, "File Handling").center();+ click_dialog(&mut app, &ctx, screen, files);+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("section"), "files");+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in ["Document Recovery Data", "Save recovery data every:", "OK", "Cancel"] {+ visible_label(&labels, screen, expected);+ }+ }++ #[test]+ fn preferences_horizontal_scroll_reaches_clipped_options() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("app.preferences", json!({})).unwrap();+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(360.0, 280.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let body = visible_label(&labels, screen, "When Scaling").center();+ // The last General option sits below this short viewport.+ scroll_dialog(&mut app, &ctx, screen, body, egui::vec2(0.0, -600.0));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let option = "Absolute Numbering (instead of Section Numbering)";+ let (_, rect, clip) = labels.iter().find(|(text, _, _)| text == option).unwrap();+ assert!(rect.right() > clip.right(), "rightmost option starts horizontally clipped: {rect:?}, {clip:?}");+ scroll_dialog(&mut app, &ctx, screen, body, egui::vec2(-600.0, 0.0));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in [option, "Preferences", "OK", "Cancel"] {+ visible_label(&labels, screen, expected);+ }+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, option).center());+ assert!(app.ui.dialog.as_ref().unwrap().b("absolutePageNumbers"));+ }++ /// Scroll the dialog body down at `at` until `text` is painted unclipped on screen.+ fn scroll_to_label(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, at: egui::Pos2, text: &str) -> egui::Rect {+ for _ in 0..40 {+ let labels = dialog_frame(app, ctx, screen, vec![]);+ if let Some((_, rect, _)) = labels.iter().find(|(t, r, clip)| t.trim() == text && screen.contains_rect(*r) && clip.contains_rect(*r)) {+ return *rect;+ }+ scroll_dialog(app, ctx, screen, at, egui::vec2(0.0, -60.0));+ }+ panic!("{text} never scrolled into view");+ }++ #[test]+ fn new_document_vertical_scroll_reaches_every_field_and_preset() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("app.newDocumentDialog", json!({})).unwrap();+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(392.0, 271.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let body = visible_label(&labels, screen, "Width").center();+ let shown = |labels: &[(String, egui::Rect, egui::Rect)]| labels.iter().any(|(t, r, clip)| t == "Primary Text Frame" && clip.contains_rect(*r));+ assert!(!shown(&labels), "the details start vertically clipped");+ let ptf = scroll_to_label(&mut app, &ctx, screen, body, "Primary Text Frame");+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in ["New Document", "Create", "Close"] {+ visible_label(&labels, screen, expected);+ }+ click_dialog(&mut app, &ctx, screen, ptf.center());+ assert!(app.ui.dialog.as_ref().unwrap().b("primaryTextFrame"), "the caption toggles its checkbox");+ // Below the details: the preset tabs and cards.+ scroll_to_label(&mut app, &ctx, screen, body, "[Default]");+ }++ #[test]+ fn arabic_new_document_fields_remain_reachable_and_editable() {+ for size in [egui::vec2(392.0, 271.0), egui::vec2(360.0, 280.0), egui::vec2(1178.0, 814.0)] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.language = "ar".into();+ app.run("app.newDocumentDialog", json!({})).unwrap();+ let fields = [("height", "66p1"), ("gutter", "1p2"), ("marginBottom", "3p3"), ("marginOutside", "3p4")];+ for (field, value) in fields {+ app.ui.dialog.as_mut().unwrap().fields.insert(field.into(), json!(value));+ }+ let ctx = dialog_context("ar");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size);+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ // With craft-fonts' Noto Sans Arabic the rows above are taller, so at the smallest size the+ // Height field starts partly below the body's clip: scroll to it like the other fields.+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let (_, _, body) = labels.iter().find(|(text, _, _)| text.trim() == "66p1").expect("66p1 is painted");+ let height = scroll_to_label(&mut app, &ctx, screen, body.center(), "66p1");+ click_dialog(&mut app, &ctx, screen, height.center());+ dialog_frame(+ &mut app,+ &ctx,+ screen,+ vec![+ egui::Event::Key {+ key: egui::Key::A,+ physical_key: None,+ pressed: true,+ repeat: false,+ modifiers: egui::Modifiers { ctrl: true, command: true, ..Default::default() },+ },+ egui::Event::Text("88p8".into()),+ ],+ );+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("height"), "88p8", "numeric fields accept edits");+ let caption = scroll_to_label(&mut app, &ctx, screen, height.center(), crate::i18n::tr("ar", "Primary Text Frame"));+ click_dialog(&mut app, &ctx, screen, caption.center());+ assert!(app.ui.dialog.as_ref().unwrap().b("primaryTextFrame"), "checkboxes remain clickable");+ for (_, value) in &fields[1..] {+ scroll_to_label(&mut app, &ctx, screen, height.center(), value);+ }+ }+ }++ #[test]+ fn resized_dialogs_cancel_and_reopen_without_applying_edits() {+ for (command, title, field, ok, cancel) in+ [("app.preferences", "Preferences", "recoveryMinutes", "OK", "Cancel"), ("app.newDocumentDialog", "New Document", "pages", "Create", "Close")]+ {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run(command, json!({})).unwrap();+ let original = app.ui.dialog.as_ref().unwrap().fields[field].clone();+ app.ui.dialog.as_mut().unwrap().fields.insert(field.into(), json!(42));+ let ctx = dialog_context("en");+ for size in [egui::vec2(1178.0, 814.0), egui::vec2(392.0, 271.0), egui::vec2(589.0, 407.0)] {+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size);+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in [title, ok, cancel] {+ visible_label(&labels, screen, expected);+ }+ }+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(589.0, 407.0));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, cancel).center());+ assert!(app.ui.dialog.is_none());+ assert!(app.session.active().is_none(), "cancelling must not create a document");+ app.run(command, json!({})).unwrap();+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields[field], original, "cancelled edits must not survive reopening");+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, title);+ dialog_frame(+ &mut app,+ &ctx,+ screen,+ vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }],+ );+ assert!(app.ui.dialog.is_none(), "Escape must also close the reopened dialog");+ }+ }++ #[test]+ fn paragraph_style_options_tabs_section_adds_a_stop_on_its_ruler() {+ use egui_kittest::kittest::Queryable;+ let (app, _) = ruled_paragraph();+ let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0));+ h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "tabs"})));+ h.run_steps(4);+ h.get_by_label("Clear All");+ // The ruler sits below the row of alignment buttons; its strip takes the click.+ let b = h.get_by_label("Right-aligned tab").rect();+ h.get_by_label("Right-aligned tab").click();+ h.run_steps(2);+ let left = h.get_by_label("Left-aligned tab").rect();+ let at = egui::pos2(left.min.x + crate::panels::tabs::PAD + 100.0, b.max.y + 14.0);+ crate::test_window::click_at(&mut h, at);+ let d = h.state().app.ui.dialog.clone().unwrap();+ let tabs = d.fields.get("p.tabs").cloned().unwrap_or_default();+ assert_eq!(tabs.as_array().map(Vec::len), Some(1), "{tabs}");+ assert_eq!(tabs[0]["align"], "right");+ confirm(&mut h.state_mut().app).unwrap();+ let app = &mut h.state_mut().app;+ let style = app.session.execute("type.tabs.get", &json!({"style": "Ruled Child"})).unwrap();+ assert_eq!(style["tabs"], tabs);+ assert_eq!(app.session.execute("type.tabs.get", &json!({})).unwrap()["tabs"], tabs, "the paragraph follows its style");+ }++ #[test]+ fn parses_command_params() {+ let f = command_fields("{name, type: custom|lastPageNumber|chapterNumber, text?, rule?: {on, weight}, flag?: bool} — creates");+ let keys: Vec<&str> = f.iter().map(|f| f.key.as_str()).collect();+ assert_eq!(keys, ["name", "type", "text", "rule", "flag"]);+ assert_eq!(f[1].choices, ["custom", "lastPageNumber", "chapterNumber"]);+ assert!(!f[0].optional && f[2].optional);+ assert!(f[4].boolean);+ assert!(command_fields("{}").is_empty());+ assert!(command_fields("no params").is_empty());+ // A parenthetical after the key describes the value.+ let f = command_fields("{angle (degrees, CCW), ids?}");+ let keys: Vec<&str> = f.iter().map(|f| f.key.as_str()).collect();+ assert_eq!(keys, ["angle", "ids"]);+ assert!(!f[0].optional && f[1].optional);+ assert_eq!(f[0].hint, "degrees, CCW");+ let f = command_fields("{scaleX? (%), ref?: 0..8, ids?: parent items (default: all)}");+ let keys: Vec<&str> = f.iter().map(|f| f.key.as_str()).collect();+ assert_eq!(keys, ["scaleX", "ref", "ids"]);+ assert!(f.iter().all(|f| f.optional));+ assert_eq!(f[0].hint, "%");+ assert_eq!(f[2].hint, "parent items (default: all)");+ // Every command with a "…" label parses without panicking.+ for c in designcraft_engine::command_specs() {+ let _ = command_fields(c.params);+ }+ }++ fn test_app() -> crate::DesignApp {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({"pages": 1})).unwrap();+ app+ }++ #[test]+ fn toc_dialog_keeps_the_character_styles_and_sorting_of_its_entries() {+ let mut app = test_app();+ app.session.execute("style.paragraph.create", &json!({"name": "Head"})).unwrap();+ app.session.execute("style.character.create", &json!({"name": "Number"})).unwrap();+ app.session.execute("style.character.create", &json!({"name": "Dots"})).unwrap();+ let sid = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Pears\nApples"})).unwrap()["story"]+ .clone();+ app.session.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 8})).unwrap();+ app.session.execute("style.paragraph.apply", &json!({"name": "Head"})).unwrap();+ app.session.execute("layout.pages.insert", &json!({"count": 1})).unwrap();+ let entries = json!([{"style": "Head", "pageNumberStyle": "Number", "separatorStyle": "Dots", "sort": true}]);+ app.session.execute("toc.generate", &json!({"page": 2, "entries": entries})).unwrap();+ let before = app.session.active().unwrap().doc.toc.clone().unwrap();+ // The dialog shows the options, and OK (Replace Existing) writes them back unchanged.+ open_toc(&mut app);+ let d = app.ui.dialog.as_ref().unwrap();+ let row = &toc_rows(d)[0];+ assert_eq!((row.page_number_style.as_str(), row.separator_style.as_str(), row.sort), ("Number", "Dots", true));+ let chars: Vec<String> = serde_json::from_value(d.fields["charStyles"].clone()).unwrap();+ assert_eq!(chars, ["Number", "Dots"], "[None] is the menu's first choice, not a style");+ let p = toc_params(&app, d);+ assert_eq!(+ (&p["entries"][0]["pageNumberStyle"], &p["entries"][0]["separatorStyle"], &p["entries"][0]["sort"]),+ (&json!("Number"), &json!("Dots"), &json!(true))+ );+ confirm(&mut app).expect("OK regenerates the table of contents");+ let st = app.session.active().unwrap();+ assert_eq!(st.doc.toc.as_ref().unwrap().entries, before.entries);+ // [None] and unsorted are left out of the params.+ let mut d = Dialog::new(TOC, json!({"included": [{"style": "Head", "level": 1, "separator": "^t"}]}));+ d.fields.insert("replace".into(), json!(true));+ let p = toc_params(&app, &d);+ assert!(p["entries"][0].get("pageNumberStyle").is_none() && p["entries"][0].get("sort").is_none(), "{p}");+ }++ #[test]+ fn paragraph_style_options_dialog_saves_edits() {+ let mut app = test_app();+ let name = app.session.execute("style.paragraph.create", &json!({"name": "Body Copy"})).unwrap()["name"].as_str().unwrap().to_string();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": name, "p.align": "center"})));+ confirm(&mut app).expect("OK saves the style edit");+ let st = app.session.active().unwrap();+ assert_eq!(st.doc.styles.para(&name).unwrap().para.align, Some(designcraft_doc::Align::Center));+ }++ #[test]+ fn paragraph_style_options_align_to_grid_shows_and_sets_the_style_grid_alignment() {+ use designcraft_doc::GridAlign;+ use egui_kittest::kittest::Queryable;+ let mut app = test_app();+ app.session.execute("style.paragraph.create", &json!({"name": "Grid Body", "para": {"gridAlign": "firstLineOnly"}})).unwrap();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Grid Body", "section": "indents"})));+ let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0));+ let grid = |h: &egui_kittest::Harness<'static, crate::test_window::Window>| {+ h.state().app.session.active().unwrap().doc.styles.para("Grid Body").unwrap().para.grid_align+ };+ h.run_steps(4);+ h.get_by_value("First Line Only");+ confirm(&mut h.state_mut().app).unwrap();+ assert_eq!(grid(&h), Some(GridAlign::FirstLineOnly), "OK without edits keeps the style's alignment");+ h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Grid Body", "section": "indents"})));+ h.run_steps(4);+ h.get_by_value("First Line Only").click();+ h.run_steps(3);+ h.get_by_label("All Lines").click();+ h.run_steps(3);+ confirm(&mut h.state_mut().app).unwrap();+ assert_eq!(grid(&h), Some(GridAlign::AllLines));+ }++ #[test]+ fn delete_paragraph_style_dialog_removes_the_style_and_reassigns_text() {+ let mut app = test_app();+ let name = app.session.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap()["name"].as_str().unwrap().to_string();+ let sid = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap()["story"].as_u64().unwrap();+ app.session.execute("text.insert", &json!({"text": "Hello"})).unwrap();+ app.session.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap();+ app.session.execute("style.paragraph.apply", &json!({"name": name})).unwrap();+ app.ui.dialog = Some(Dialog::new("deleteParagraphStyle", json!({"name": name, "replaceWith": designcraft_doc::BASIC_PARAGRAPH})));+ confirm(&mut app).expect("OK deletes the style");+ let st = app.session.active().unwrap();+ assert!(st.doc.styles.para(&name).is_none(), "style removed");+ let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).unwrap();+ assert_eq!(story.paras[0].style, designcraft_doc::BASIC_PARAGRAPH, "text reassigned to the replacement style");+ }++ #[test]+ fn delete_paragraph_style_dialog_defaults_replacement_to_basic_paragraph() {+ let mut app = test_app();+ let name = app.session.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap()["name"].as_str().unwrap().to_string();+ // No `replaceWith` set — the dialog's default field.+ app.ui.dialog = Some(Dialog::new("deleteParagraphStyle", json!({"name": name})));+ confirm(&mut app).expect("OK deletes the style with the default replacement");+ let st = app.session.active().unwrap();+ assert!(st.doc.styles.para(&name).is_none());+ }++ #[test]+ fn character_style_options_dialog_saves_edits() {+ let mut app = test_app();+ let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();+ app.ui.dialog = Some(Dialog::new("characterStyleOptions", json!({"name": name, "c.tracking": 20.0})));+ confirm(&mut app).expect("OK saves the style edit");+ let st = app.session.active().unwrap();+ assert_eq!(st.doc.styles.char_style(&name).unwrap().chars.tracking, Some(20.0));+ }++ #[test]+ fn delete_character_style_dialog_removes_the_style_and_reassigns_text() {+ let mut app = test_app();+ let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();+ let sid = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap()["story"].as_u64().unwrap();+ app.session.execute("text.insert", &json!({"text": "Hello"})).unwrap();+ app.session.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 5})).unwrap();+ app.session.execute("style.character.apply", &json!({"name": name})).unwrap();+ app.ui.dialog = Some(Dialog::new("deleteCharacterStyle", json!({"name": name, "replaceWith": designcraft_doc::NO_CHAR_STYLE})));+ confirm(&mut app).expect("OK deletes the style");+ let st = app.session.active().unwrap();+ assert!(st.doc.styles.char_style(&name).is_none(), "style removed");+ let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).unwrap();+ assert_eq!(story.chars[0].format.style, designcraft_doc::NO_CHAR_STYLE, "text reassigned to the replacement style");+ }++ #[test]+ fn delete_character_style_dialog_defaults_replacement_to_none() {+ let mut app = test_app();+ let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();+ // No `replaceWith` set — the dialog's default field.+ app.ui.dialog = Some(Dialog::new("deleteCharacterStyle", json!({"name": name})));+ confirm(&mut app).expect("OK deletes the style with the default replacement");+ let st = app.session.active().unwrap();+ assert!(st.doc.styles.char_style(&name).is_none());+ }++ /// File › Export EPUB… opens EPUB Export Options from the document's setting; OK stores a+ /// changed Split Document as one undo step, and an unchanged one adds none.+ #[test]+ fn epub_export_passes_its_options_to_the_engine() {+ use std::io::Read;+ use std::sync::{Arc, Mutex};+ let mut app = test_app();+ app.session.execute("style.paragraph.create", &json!({"name": "Chapter"})).unwrap();+ let r = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "One\nTwo"})).unwrap();+ let sid = r["story"].as_u64().unwrap();+ for anchor in [0, 4] {+ app.session.execute("text.select", &json!({"story": sid, "anchor": anchor, "focus": anchor})).unwrap();+ app.session.execute("style.paragraph.apply", &json!({"name": "Chapter"})).unwrap();+ }+ let written: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));+ let sink = written.clone();+ app.services.write = Some(Box::new(move |_: &str, bytes: &[u8]| {+ *sink.lock().unwrap() = bytes.to_vec();+ Ok(())+ }));+ crate::menus::export_epub(&mut app, &json!({"path": "book.epub", "split": {"style": "Chapter"}})).unwrap();+ let bytes = written.lock().unwrap().clone();+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();+ let mut opf = String::new();+ z.by_name("OEBPS/content.opf").unwrap().read_to_string(&mut opf).unwrap();+ assert!(opf.contains("properties=\"cover-image\""), "the first page is the cover: {opf}");+ assert!(z.by_name("OEBPS/content2.xhtml").is_ok(), "the split override reaches the export");+ assert_eq!(app.session.active().unwrap().doc.settings.epub_split, designcraft_doc::EpubSplit::Off, "an override is not stored");+ crate::menus::export_epub(&mut app, &json!({"path": "book.epub", "cover": false})).unwrap();+ let bytes = written.lock().unwrap().clone();+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();+ let mut opf = String::new();+ z.by_name("OEBPS/content.opf").unwrap().read_to_string(&mut opf).unwrap();+ assert!(!opf.contains("cover-image"), "a caller's cover: false stays: {opf}");+ }++ #[test]+ fn epub_export_options_store_split_document() {+ use designcraft_doc::EpubSplit;+ let mut app = test_app();+ app.session.execute("style.paragraph.create", &json!({"name": "Chapter"})).unwrap();+ let undo_steps = |app: &crate::DesignApp| app.session.active().map(|st| st.history.undo.len());+ app.run("app.exportEpub", json!({})).unwrap();+ let d = app.ui.dialog.as_mut().unwrap();+ assert_eq!((d.id.as_str(), d.b("split"), d.s("style").as_str()), ("epubExport", false, designcraft_doc::BASIC_PARAGRAPH));+ d.fields.insert("split".into(), json!(true));+ d.fields.insert("style".into(), json!("Chapter"));+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(app.session.active().unwrap().doc.settings.epub_split, EpubSplit::Style("Chapter".into()));+ assert_eq!(undo_steps(&app), before.map(|n| n + 1));+ open_epub_export(&mut app);+ assert_eq!(app.ui.dialog.as_ref().map(|d| (d.b("split"), d.s("mode"), d.s("style"))), Some((true, "style".into(), "Chapter".into())));+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before.map(|n| n + 1), "unchanged: no undo step");+ open_epub_export(&mut app);+ app.ui.dialog.as_mut().unwrap().fields.insert("mode".into(), json!("exportTags"));+ confirm(&mut app).unwrap();+ assert_eq!(app.session.active().unwrap().doc.settings.epub_split, EpubSplit::ExportTags);+ open_epub_export(&mut app);+ cancel(&mut app);+ assert_eq!(app.session.active().unwrap().doc.settings.epub_split, EpubSplit::ExportTags, "Cancel stores nothing");+ }++ #[test]+ fn pdf_export_defaults() {+ let d = Dialog::new("pdfExport", json!({}));+ let keys: Vec<&str> = d.fields.iter().map(|(k, _)| k.as_str()).collect();+ // serde_json::Map keeps keys sorted.+ let expected = [+ "bleed",+ "compressImages",+ "flatten",+ "marksBleed",+ "marksCrop",+ "marksOffset",+ "marksPageInfo",+ "marksWeight",+ "preset",+ "spreads",+ "standard",+ "tagged",+ ];+ assert_eq!(keys, expected);+ assert_eq!(d.fields["preset"].as_str(), Some("Desktop Printing"));+ assert_eq!(d.fields["standard"].as_str(), Some("none"));+ assert_eq!(d.fields["compressImages"].as_bool(), Some(false));+ assert_eq!(d.fields["flatten"].as_str(), Some(""));+ assert_eq!(d.fields["spreads"].as_bool(), Some(false));+ assert_eq!(d.fields["bleed"].as_bool(), Some(true));+ assert_eq!(d.fields["marksCrop"].as_bool(), Some(false));+ assert_eq!(d.fields["marksBleed"].as_bool(), Some(false));+ assert_eq!(d.fields["marksPageInfo"].as_bool(), Some(false));+ assert_eq!(d.fields["marksWeight"].as_str(), Some("0.25"));+ assert_eq!(d.fields["marksOffset"].as_str(), Some("6"));+ assert_eq!(d.fields["tagged"].as_bool(), Some(true));+ }++ #[test]+ fn pdf_export_override_keeps_override() {+ let d = Dialog::new("pdfExport", json!({"bleed": false}));+ assert_eq!(d.fields["bleed"].as_bool(), Some(false));+ assert_eq!(d.fields["preset"].as_str(), Some("Desktop Printing"));+ assert_eq!(d.fields["tagged"].as_bool(), Some(true));+ }++ #[test]+ fn pdf_export_preset_high_quality_print_keeps_flatten() {+ let mut d = Dialog::new("pdfExport", json!({}));+ d.fields.insert("flatten".into(), json!("medium"));+ apply_pdf_preset(&mut d, "Desktop Printing");+ assert_eq!(d.s("standard"), "none");+ assert!(!d.b("compressImages"));+ assert!(!d.b("marksCrop"));+ assert!(!d.b("marksBleed"));+ assert!(!d.b("marksPageInfo"));+ assert_eq!(d.s("flatten"), "medium", "a leave-unchanged preset must not touch flatten");+ }++ #[test]+ fn pdf_export_preset_press_quality_keeps_flatten() {+ let mut d = Dialog::new("pdfExport", json!({}));+ d.fields.insert("flatten".into(), json!("high"));+ apply_pdf_preset(&mut d, "Commercial Printing");+ assert_eq!(d.s("standard"), "none");+ assert!(d.b("compressImages"));+ assert!(d.b("marksCrop"));+ assert!(d.b("marksBleed"));+ assert!(!d.b("marksPageInfo"));+ assert_eq!(d.s("flatten"), "high");+ }++ #[test]+ fn pdf_export_preset_smallest_file_size_sets_flatten_low() {+ let mut d = Dialog::new("pdfExport", json!({}));+ apply_pdf_preset(&mut d, "Screen and Email");+ assert_eq!(d.s("standard"), "none");+ assert!(d.b("compressImages"));+ assert!(!d.b("marksCrop"));+ assert!(!d.b("marksBleed"));+ assert!(!d.b("marksPageInfo"));+ assert_eq!(d.s("flatten"), "low");+ }++ /// The PDF/X-1a preset exports X-1a with the High Resolution flattener and printer's marks.+ #[test]+ fn pdf_export_preset_pdf_x1a_flattens_at_high_resolution() {+ let mut d = Dialog::new("pdfExport", json!({}));+ apply_pdf_preset(&mut d, "PDF/X-1a:2003");+ assert_eq!(d.s("standard"), "x1a");+ assert_eq!(d.s("flatten"), "high");+ assert!(d.b("marksCrop") && d.b("marksBleed"));+ assert!(PDF_EXPORT_PRESETS.contains(&"PDF/X-1a:2003"));+ }++ #[test]+ fn pdf_export_preset_pdf_x4_keeps_flatten() {+ let mut d = Dialog::new("pdfExport", json!({}));+ d.fields.insert("flatten".into(), json!("medium"));+ apply_pdf_preset(&mut d, "PDF/X-4");+ assert_eq!(d.s("standard"), "x4");+ assert!(!d.b("compressImages"));+ assert!(d.b("marksCrop"));+ assert!(d.b("marksBleed"));+ assert!(!d.b("marksPageInfo"));+ assert_eq!(d.s("flatten"), "medium");+ }++ #[test]+ fn pdf_export_preset_pdf_a2b_keeps_flatten() {+ let mut d = Dialog::new("pdfExport", json!({}));+ d.fields.insert("flatten".into(), json!("low"));+ apply_pdf_preset(&mut d, "PDF/A-2b");+ assert_eq!(d.s("standard"), "a2b");+ assert!(!d.b("compressImages"));+ assert!(!d.b("marksCrop"));+ assert!(!d.b("marksBleed"));+ assert!(!d.b("marksPageInfo"));+ assert_eq!(d.s("flatten"), "low");+ }++ #[test]+ fn open_pdf_export_seeds_fields_from_settings() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.pdf_export.standard = "x4".into();+ app.ui.pdf_export.tagged = false;+ app.ui.pdf_export.marks_crop = true;+ app.ui.pdf_export.flatten = String::new();+ app.ui.flattener = "medium".into();+ open_pdf_export(&mut app);+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!(d.id, "pdfExport");+ assert_eq!(d.s("standard"), "x4");+ assert!(!d.b("tagged"));+ assert!(d.b("marksCrop"));+ assert_eq!(d.s("pages"), "all");+ assert_eq!(d.s("flatten"), "medium", "empty flatten falls back to the global flattener");+ assert_eq!(d.s("title"), "", "no document → empty title");++ // A non-empty persisted flatten is used verbatim, not the global fallback.+ app.ui.pdf_export.flatten = "low".into();+ app.ui.flattener = "medium".into();+ open_pdf_export(&mut app);+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!(d.s("flatten"), "low");+ }++ #[test]+ fn pdf_export_preset_custom_changes_nothing() {+ let mut d = Dialog::new("pdfExport", json!({}));+ d.fields.insert("standard".into(), json!("x4"));+ d.fields.insert("compressImages".into(), json!(true));+ d.fields.insert("marksCrop".into(), json!(true));+ d.fields.insert("marksBleed".into(), json!(true));+ d.fields.insert("marksPageInfo".into(), json!(true));+ d.fields.insert("flatten".into(), json!("high"));+ let before = d.fields.clone();+ apply_pdf_preset(&mut d, "Custom");+ assert_eq!(d.fields, before);+ }++ #[test]+ fn confirm_pdf_export_writes_file_and_persists_settings() {+ use std::sync::{Arc, Mutex};+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let writes: Arc<Mutex<Vec<(String, Vec<u8>)>>> = Arc::new(Mutex::new(Vec::new()));+ let sink = writes.clone();+ app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| {+ sink.lock().unwrap().push((path.to_string(), bytes.to_vec()));+ Ok(())+ }));+ app.answer_dialogs(crate::app::file_dialogs::testing::answer_with(Some("/tmp/designcraft-test.pdf".into())));++ app.ui.dialog = Some(Dialog::new("pdfExport", json!({})));+ {+ let d = app.ui.dialog.as_mut().unwrap();+ d.fields.insert("standard".into(), json!("x4"));+ d.fields.insert("bleed".into(), json!(false));+ d.fields.insert("marksCrop".into(), json!(true));+ d.fields.insert("tagged".into(), json!(false));+ d.fields.insert("title".into(), json!("Report"));+ }+ confirm(&mut app).unwrap();+ app.settle_dialogs();++ let got = writes.lock().unwrap();+ assert_eq!(got.len(), 1, "confirming the dialog writes exactly one file");+ assert_eq!(got[0].0, "/tmp/designcraft-test.pdf");+ assert!(got[0].1.starts_with(b"%PDF"), "the written bytes are a PDF");+ drop(got);++ assert_eq!(app.ui.pdf_export.standard, "x4");+ assert!(!app.ui.pdf_export.bleed);+ assert!(app.ui.pdf_export.marks_crop);+ assert!(!app.ui.pdf_export.tagged);+ }++ #[test]+ fn update_link_asks_before_replacing_edits_made_in_the_layout() {+ let dir = std::env::temp_dir().join(format!("dc-update-link-dialog-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("note.txt");+ std::fs::write(&path, "One").unwrap();+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let r = app.session.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true, "rect": [72, 72, 300, 200]})).unwrap();+ let sid = r["story"].as_u64().unwrap();+ let text = |app: &crate::DesignApp| app.session.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text.clone();++ // Not edited in the layout: updates without asking.+ std::fs::write(&path, "Two").unwrap();+ crate::panels::properties::update_links(&mut app, json!({"story": sid}));+ assert!(app.ui.dialog.is_none());+ assert_eq!(text(&app), "Two");++ // Edited in the layout: asks first; Cancel changes nothing.+ app.session.execute("story.setText", &json!({"story": sid, "text": "Mine"})).unwrap();+ std::fs::write(&path, "Three").unwrap();+ crate::panels::properties::update_links(&mut app, json!({"story": sid}));+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!((d.id.as_str(), d.s("files").as_str()), ("updateLink", "note.txt"));+ app.ui.dialog = None;+ assert_eq!(text(&app), "Mine");++ // Window › Links › Update Link (all links) asks too; confirming updates.+ crate::menus::activate(&mut app, "links.update", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("updateLink"));+ confirm(&mut app).unwrap();+ assert!(app.ui.dialog.is_none());+ assert_eq!(text(&app), "Three");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn confirm_pdf_export_cancelled_save_writes_nothing() {+ use std::sync::{Arc, Mutex};+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let writes: Arc<Mutex<Vec<(String, Vec<u8>)>>> = Arc::new(Mutex::new(Vec::new()));+ let sink = writes.clone();+ app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| {+ sink.lock().unwrap().push((path.to_string(), bytes.to_vec()));+ Ok(())+ }));+ app.answer_dialogs(crate::app::file_dialogs::testing::answer_with(None));++ app.ui.dialog = Some(Dialog::new("pdfExport", json!({})));+ let r = confirm(&mut app).unwrap();+ assert_eq!(r, Value::Null);+ app.settle_dialogs();+ assert!(writes.lock().unwrap().is_empty(), "cancelling the save picker must not write");+ }++ use designcraft_doc::{CharAttrs, CharacterStyle};++ /// A document with character styles Base (bold) and Emphasis (italic) on the first two letters.+ fn styled_app() -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("style.character.create", json!({"name": "Base", "chars": {"fontStyle": "Bold"}})).unwrap();+ app.run("style.character.create", json!({"name": "Emphasis", "chars": {"fontStyle": "Italic"}})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hi there"})).unwrap();+ app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 2})).unwrap();+ app.run("style.character.apply", json!({"name": "Emphasis"})).unwrap();+ app+ }++ /// One control-channel request, as the control port or MCP would send it.+ fn ctl(app: &mut DesignApp, method: &str, params: Value) -> Value {+ let (req, _reply) = crate::control::ControlRequest::new(method, params);+ match crate::control::handle(app, &egui::Context::default(), &req) {+ crate::control::Outcome::Done(v) => v,+ crate::control::Outcome::Screenshot { .. } => Value::Null,+ }+ }++ fn char_style(app: &DesignApp, name: &str) -> Option<CharacterStyle> {+ app.session.active().and_then(|st| st.doc.styles.char_style(name).cloned())+ }++ #[test]+ fn character_style_options_set_exactly_the_edited_attributes() {+ let mut app = styled_app();+ assert_eq!(ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}}))["ok"], true);+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 14}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.fill", "value": "[Paper]"}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "basedOn", "value": "Base"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ assert!(app.ui.dialog.is_none());+ let st = char_style(&app, "Emphasis").unwrap();+ assert_eq!(st.based_on.as_deref(), Some("Base"));+ assert_eq!(st.chars, CharAttrs { font_style: Some("Italic".into()), size: Some(14.0), fill: Some("[Paper]".into()), ..Default::default() });+ }++ #[test]+ fn character_style_options_unset_cleared_fields_and_rename_every_use() {+ let mut app = styled_app();+ ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.fontStyle", "value": null}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "rename", "value": "Strong"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ assert!(char_style(&app, "Emphasis").is_none());+ assert!(char_style(&app, "Strong").unwrap().chars.is_empty());+ let st = app.session.active().unwrap();+ let story = st.doc.stories.values().next().unwrap();+ assert!(story.chars.iter().any(|r| r.format.style == "Strong"));+ // A taken name keeps the dialog open with the reason.+ ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Strong"}}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "rename", "value": "Base"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false);+ assert!(app.ui.dialog.as_ref().is_some_and(|d| !d.s("status").is_empty()));+ assert!(char_style(&app, "Strong").is_some());+ }++ #[test]+ fn new_character_style_opens_its_options_and_creates_the_style() {+ let mut app = styled_app();+ crate::menus::activate(&mut app, "style.character.create", &Value::Null);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!((d.id.as_str(), d.b("new"), d.s("rename").as_str()), ("characterStyleOptions", true, "Character Style 1"));+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 9}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ let st = char_style(&app, "Character Style 1").unwrap();+ // The selected text's own Italic (its Emphasis style) comes along, as InDesign's New+ // Character Style takes it.+ assert_eq!((st.based_on, st.chars), (None, CharAttrs { size: Some(9.0), font_style: Some("Italic".into()), ..Default::default() }));+ crate::menus::activate(&mut app, "style.character.create", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("rename"), "Character Style 2");+ }++ #[test]+ fn new_paragraph_style_opens_its_options_and_creates_the_style() {+ let mut app = styled_app();+ crate::menus::activate(&mut app, "style.paragraph.create", &Value::Null);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!((d.id.as_str(), d.b("new"), d.s("rename").as_str()), ("paragraphStyleOptions", true, "Paragraph Style 1"));+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 20}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "basedOn", "value": designcraft_doc::BASIC_PARAGRAPH}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ let st = app.session.active().unwrap().doc.styles.para("Paragraph Style 1").cloned().unwrap();+ assert_eq!(st.based_on.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH));+ // The selected text's own Italic comes along, as InDesign's New Paragraph Style takes it.+ assert_eq!(st.chars, CharAttrs { size: Some(20.0), font_style: Some("Italic".into()), ..Default::default() });+ }++ #[test]+ fn style_rows_open_their_options_except_none() {+ let mut app = styled_app();+ open_style_options(&mut app, false, "Emphasis");+ let d = app.ui.dialog.take().unwrap();+ assert_eq!((d.id.as_str(), d.s("name").as_str()), ("characterStyleOptions", "Emphasis"));+ open_style_options(&mut app, false, designcraft_doc::NO_CHAR_STYLE);+ assert!(app.ui.dialog.is_none());+ open_style_options(&mut app, true, designcraft_doc::BASIC_PARAGRAPH);+ assert_eq!(app.ui.dialog.take().unwrap().id, "paragraphStyleOptions");+ }++ #[test]+ fn style_options_sections_draw() {+ let mut app = styled_app();+ let ctx = egui::Context::default();+ let frame = |app: &mut DesignApp| {+ for _ in 0..2 {+ let raw = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0))),+ max_texture_side: Some(8192),+ ..Default::default()+ };+ let mut out = ctx.run_ui(raw, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ }+ };+ for lang in ["", "ar"] {+ app.run("app.language", json!({"lang": lang})).unwrap();+ for fields in [json!({"name": "Emphasis"}), json!({"new": true}), json!({"name": "Emphasis", "c.size": null, "c.underline": false})] {+ for section in ["general", "chars", "advanced", "color", "openType", "underline", "strikethrough"] {+ let mut f = fields.clone();+ f["section"] = json!(section);+ app.ui.dialog = Some(Dialog::new("characterStyleOptions", f));+ frame(&mut app);+ assert!(app.ui.dialog.is_some(), "{section} stays open");+ }+ }+ for section in+ ["general", "chars", "advanced", "border", "shading", "keep", "span", "bullets", "color", "openType", "underline", "strikethrough"]+ {+ for fields in [+ json!({"new": true}),+ json!({"new": true, "p.listType": "bullets", "p.spanColumns": {"kind": "span", "columns": 0}, "p.borderOn": true}),+ json!({"new": true, "p.listType": "numbers", "p.startAt": 1, "p.spanColumns": {"kind": "split", "columns": 2}, "p.keepLinesTogether": true}),+ ] {+ let mut f = fields;+ f["section"] = json!(section);+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", f));+ frame(&mut app);+ assert!(app.ui.dialog.is_some(), "{section} stays open");+ }+ }+ }+ }++ #[test]+ fn dragging_the_title_moves_the_dialog_and_dragging_the_body_does_not() {+ use egui::{Event, Modifiers, PointerButton, Pos2, vec2};+ use egui_kittest::{Harness, kittest::Queryable};+ fn drag(h: &mut Harness<'static, DesignApp>, from: Pos2, to: Pos2) {+ h.event(Event::PointerMoved(from));+ h.run_steps(1);+ h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });+ h.run_steps(1);+ for step in 1..=8 {+ h.event(Event::PointerMoved(from + (to - from) * (step as f32 / 8.0)));+ h.run_steps(1);+ }+ h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });+ h.run_steps(3);+ }+ let rect = |h: &Harness<'static, DesignApp>| h.ctx.memory(|m| m.area_rect(egui::Id::unique("dialog"))).unwrap();+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.ui.dialog = Some(Dialog::new("insertTable", Value::Null));+ let mut ready = false;+ let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state(+ move |ui, app: &mut DesignApp| {+ if !ready {+ crate::theme::install_fonts(ui.ctx(), &app.ui.language);+ crate::theme::apply(ui.ctx(), &crate::theme::Tokens::for_brightness(crate::theme::Brightness::default()));+ ready = true;+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(4);+ let centred = rect(&h);+ assert!((centred.center() - egui::pos2(600.0, 400.0)).length() < 1.0, "{centred:?}");+ assert!(centred.width() < 1000.0 && centred.height() < 700.0, "the area is the dialog, not the backdrop: {centred:?}");++ let title = h.get_by_label("Insert Table").rect().center();+ drag(&mut h, title, title + vec2(100.0, 60.0));+ let moved = rect(&h);+ assert!((moved.min - centred.min - vec2(100.0, 60.0)).length() < 2.0, "{centred:?} -> {moved:?}");++ let body = egui::pos2(moved.right() - 40.0, moved.center().y);+ drag(&mut h, body, body + vec2(-150.0, 80.0));+ assert_eq!(rect(&h), moved, "a drag in the body leaves the dialog in place");++ // The title row stays inside the top edge.+ let title = h.get_by_label("Insert Table").rect().center();+ drag(&mut h, title, title - vec2(0.0, 1000.0));+ assert!(rect(&h).top().abs() < 1.0, "{:?}", rect(&h));++ // Opened again, the dialog starts centred.+ h.state_mut().ui.dialog = None;+ h.run_steps(2);+ h.state_mut().ui.dialog = Some(Dialog::new("insertTable", Value::Null));+ h.run_steps(4);+ assert!((rect(&h).center() - centred.center()).length() < 1.0, "{:?}", rect(&h));++ // Past the left edge, about 100 px of the title row stays inside.+ let title = h.get_by_label("Insert Table").rect().center();+ drag(&mut h, title, title - vec2(900.0, 0.0));+ assert!((rect(&h).right() - 100.0).abs() < 2.0, "{:?}", rect(&h));+ }++ #[test]+ fn the_new_document_window_drags_mostly_aside_and_keeps_its_preview() {+ use egui::{Event, Modifiers, PointerButton, vec2};+ use egui_kittest::{Harness, kittest::Queryable};+ let rect = |h: &Harness<'static, DesignApp>| h.ctx.memory(|m| m.area_rect(egui::Id::unique("dialog"))).unwrap();+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"title": "A"})).unwrap();+ app.ui.new_document_preview = true;+ app.run("app.newDocumentDialog", json!({})).unwrap();+ let mut ready = false;+ let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(+ move |ui, app: &mut DesignApp| {+ if !ready {+ crate::theme::install_fonts(ui.ctx(), &app.ui.language);+ crate::theme::apply(ui.ctx(), &crate::theme::Tokens::for_brightness(crate::theme::Brightness::default()));+ ready = true;+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(6);+ let preview = h.state().session.new_document_preview();+ assert!(preview.is_some(), "Preview is on");+ let centred = rect(&h);+ assert!(centred.width() > 900.0, "{centred:?}");+ let from = h.get_all_by_label("New Document").map(|n| n.rect().center()).min_by(|a, b| a.y.total_cmp(&b.y)).unwrap();+ let to = from + vec2(1300.0, 0.0);+ h.event(Event::PointerMoved(from));+ h.run_steps(1);+ h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });+ h.run_steps(1);+ for step in 1..=8 {+ h.event(Event::PointerMoved(from + (to - from) * (step as f32 / 8.0)));+ h.run_steps(1);+ }+ h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });+ h.run_steps(3);+ // All but 100 px of the window's width is past the right edge, over the preview.+ assert!((rect(&h).left() - 1300.0).abs() < 2.0, "{:?}", rect(&h));+ let app = h.state();+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("newDocument"));+ assert_eq!(app.session.new_document_preview(), preview, "moving the window keeps the preview");+ assert_eq!(app.session.documents().len(), 2);+ }++ #[test]+ fn margins_dialog_reads_bare_numbers_in_the_ruler_unit() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("document.preferences", json!({"horizontalUnits": "millimeters"})).unwrap();+ crate::menus::activate(&mut app, "layout.marginsAndColumns", &Value::Null);+ for k in ["marginTop", "marginBottom", "marginInside", "marginOutside"] {+ ctl(&mut app, "ui.dialog.set", json!({"field": k, "value": "15"}));+ }+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ let top = app.session.active().unwrap().doc.page(0).unwrap().margins.top;+ assert!((top - 15.0 * 72.0 / 25.4).abs() < 0.01, "top margin was {top} pt");+ }+ fn facing_app(pages: u64) -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": pages, "facingPages": true})).unwrap();+ app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)));+ app+ }++ fn guide_counts(app: &DesignApp) -> Vec<usize> {+ let doc = &app.session.active().unwrap().doc;+ (0..doc.page_count()).map(|abs| doc.page(abs).unwrap().guides.len()).collect()+ }++ /// The eyedropper takes the colour the canvas shows: with Proof Colors the proofed colour, and+ /// with the ink-limit preview the warning colour over the limit.+ #[test]+ fn the_eyedropper_samples_what_proof_colors_and_the_ink_limit_show() {+ use egui_kittest::Harness;+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("swatch.create", json!({"name": "Vivid Green", "color": [0, 255, 0]})).unwrap();+ let id = app.run("frame.create", json!({"rect": [36, 36, 560, 700], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ app.run("object.fill", json!({"ids": [id], "swatch": "Vivid Green"})).unwrap();+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let ctx = ui.ctx().clone();+ app.logic(&ctx);+ app.ui(ui);+ },+ app,+ );+ h.run_steps(6);+ let target = {+ let app = h.state();+ let doc = &app.session.doc().unwrap().doc;+ let layout = designcraft_tools::CanvasLayout::new(doc, false);+ let v = *app.view().unwrap();+ crate::canvas::Xf::new(app.canvas_rect.unwrap(), &v).to_screen(layout.slots[0].xf * designcraft_geom::Point::new(300.0, 600.0))+ };+ let ctx = h.ctx.clone();+ let sample = |h: &mut Harness<'_, DesignApp>| crate::canvas::color_at(h.state_mut(), &ctx, target).expect("on the page");+ // What a view makes of the plain colour, as the canvas texture gets it.+ let shown = |c: [u8; 3], view: &dyn Fn(&mut designcraft_render::Rendered)| {+ let mut img = designcraft_render::Rendered { width: 1, height: 1, pixels: vec![c[0], c[1], c[2], 255] };+ view(&mut img);+ [img.pixels[0], img.pixels[1], img.pixels[2]]+ };+ let plain = sample(&mut h);+ h.state_mut().ui.proof_colors = true;+ let setup = h.state().ui.proof_setup.clone();+ let proofed = sample(&mut h);+ assert_eq!(proofed, shown(plain, &|img| designcraft_render::proof_view(img, &setup)));+ assert_ne!(proofed, plain, "the proof changes this green");+ }++ /// The course's chapter 23: the Color Picker's eyedropper, dragged from the picker onto the+ /// page and let go there, takes the colour the page shows.+ #[test]+ fn the_color_pickers_eyedropper_takes_a_colour_off_the_page() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = app.run("frame.create", json!({"rect": [36, 36, 560, 700], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ app.run("swatch.create", json!({"name": "Eyedrop Red", "color": {"c": 0, "m": 100, "y": 100, "k": 0}})).unwrap();+ app.run("object.fill", json!({"ids": [id], "swatch": "Eyedrop Red"})).unwrap();+ app.ui.dialog = Some(Dialog::new("colorPicker", json!({"target": "fill", "hex": "#000000"})));+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let ctx = ui.ctx().clone();+ app.logic(&ctx);+ app.ui(ui);+ },+ app,+ );+ h.run_steps(6);+ // Where the frame shows on screen.+ let target = {+ let app = h.state();+ let doc = &app.session.doc().unwrap().doc;+ let layout = designcraft_tools::CanvasLayout::new(doc, false);+ let v = *app.view().unwrap();+ crate::canvas::Xf::new(app.canvas_rect.unwrap(), &v).to_screen(layout.slots[0].xf * designcraft_geom::Point::new(300.0, 600.0))+ };+ let from = h.get_by_label("Eyedropper: drag it onto the page").rect().center();+ h.hover_at(from);+ h.drag_at(from);+ h.run_steps(1);+ for k in 1..=4 {+ h.hover_at(from + (target - from) * (k as f32 / 4.0));+ h.run_steps(1);+ }+ h.drop_at(target);+ h.run_steps(3);+ let d = h.state().ui.dialog.as_ref().expect("the picker stays open");+ let [r, g, b, _] = h.state().session.doc().unwrap().doc.resolve_color("Eyedrop Red", 1.0).unwrap().to_rgba8(1.0);+ let got: Vec<f64> = d.fields["rgb"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();+ for (a, e) in got.iter().zip([r, g, b]) {+ assert!((a - f64::from(e)).abs() <= 3.0, "{got:?} vs {:?}", [r, g, b]);+ }+ assert!(d.b("edited"));+ // Let go off the page (here, on the dialog's own field area): no colour, nothing changes.+ let hex = d.s("hex");+ h.hover_at(from);+ h.drag_at(from);+ h.run_steps(1);+ h.hover_at(from + egui::vec2(-40.0, 0.0));+ h.run_steps(1);+ h.drop_at(egui::pos2(2.0, 2.0));+ h.run_steps(3);+ assert_eq!(h.state().ui.dialog.as_ref().unwrap().s("hex"), hex);+ // Let go over the picker's own colour field, with the page under it: nothing either.+ let field = h.get_by_label("Color field").rect().center();+ let ctx = h.ctx.clone();+ assert!(crate::canvas::color_at(h.state_mut(), &ctx, field).is_some(), "the page lies under the field");+ h.hover_at(from);+ h.drag_at(from);+ h.run_steps(1);+ h.hover_at(field);+ h.run_steps(1);+ h.drop_at(field);+ h.run_steps(3);+ assert_eq!(h.state().ui.dialog.as_ref().unwrap().s("hex"), hex, "the picker isn't sampled");+ }++ /// The Color Picker laid out as InDesign's: a field and a slider for the component whose radio+ /// is on, the new colour over the old one, and the values in every space.+ #[test]++ fn the_color_picker_keeps_a_typed_cmyk_value_the_colour_shown_does_not_change_with() {+ use egui_kittest::kittest::Queryable;+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.ui.dialog = Some(Dialog::new("colorPicker", json!({"target": "fill", "cmyk": [0.0, 0.0, 0.0, 100.0], "text": false})));+ let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0));+ h.run_steps(3);+ // A C typed at 100% K is kept, whether or not the colour shown changes with it.+ let rgb = h.state().app.ui.dialog.as_ref().unwrap().fields.get("rgb").cloned();+ h.get_by_label("C").focus();+ h.run_steps(1);+ h.event(egui::Event::Text("50".into()));+ h.run_steps(2);+ let d = h.state().app.ui.dialog.as_ref().unwrap();+ assert_eq!(d.fields["cmyk"], json!([50.0, 0.0, 0.0, 100.0]), "rgb {:?} (was {rgb:?})", d.fields.get("rgb"));+ assert!(d.b("edited"));+ }++ #[test]+ fn the_color_picker_picks_on_its_field_and_slider_and_adds_a_cmyk_swatch() {+ use egui_kittest::kittest::Queryable;+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [72, 72, 200, 200], "shape": "rectangle"})).unwrap();+ app.run("object.color", json!({"color":designcraft_color::Color::from_hex("#7c1315").unwrap(),"target":"fill"})).unwrap();+ app.ui.dialog = Some(Dialog::new("colorPicker", json!({"target": "fill", "hex": "#7c1315", "text": false})));+ let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0));+ h.run_steps(3);+ // R at first: R up the slider, B across and G up the field.+ let _ = h.get_by_label("RGB Color Space View");+ let field = h.get_by_label("Color field").rect();+ crate::test_window::click_at(&mut h, egui::pos2(field.right() - 1.0, field.top() + 1.0));+ h.run_steps(2);+ let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap());+ assert!((p.rgb[0] - 124.0 / 255.0).abs() < 0.01 && p.rgb[1] > 0.97 && p.rgb[2] > 0.97, "{p:?}: R kept, G and B full");+ // The slider sets R alone.+ let slider = h.get_by_label("Color slider").rect();+ crate::test_window::click_at(&mut h, egui::pos2(slider.center().x, slider.bottom() - 1.0));+ h.run_steps(2);+ let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap());+ assert!(p.rgb[0] < 0.02 && p.rgb[1] > 0.97, "{p:?}");+ // Hue on the slider: the field is saturation across, brightness up.+ store_picked(h.state_mut().app.ui.dialog.as_mut().unwrap(), &Picked::from_rgb([124.0 / 255.0, 19.0 / 255.0, 21.0 / 255.0], 0.0));+ h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("component".into(), json!("h"));+ h.run_steps(2);+ crate::test_window::click_at(&mut h, egui::pos2(field.left() + 1.0, field.top() + 1.0));+ h.run_steps(2);+ let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap());+ assert!(p.hsb[1] < 0.02 && p.hsb[2] > 0.98 && (p.hsb[0] - 359.0).abs() < 2.0, "{p:?}: no saturation, full brightness, the hue kept");+ // Lab shows its own view.+ h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("component".into(), json!("l"));+ h.run_steps(2);+ let _ = h.get_by_label("Lab Color Space View");+ // Add CMYK Swatch adds the colour as a CMYK swatch; OK applies it.+ store_picked(h.state_mut().app.ui.dialog.as_mut().unwrap(), &Picked::from_rgb([124.0 / 255.0, 19.0 / 255.0, 21.0 / 255.0], 0.0));+ h.run_steps(2);+ let before = h.state().app.session.active().unwrap().doc.swatches.len();+ h.get_by_label("Add CMYK Swatch").click();+ h.run_steps(3);+ let doc = &h.state().app.session.active().unwrap().doc;+ assert_eq!(doc.swatches.len(), before + 1);+ assert!(matches!(+ doc.swatches.last().unwrap().value,+ designcraft_color::swatch::SwatchValue::Color { color: designcraft_color::Color::Cmyk { .. }, .. }+ ));+ // The percentages the C/M/Y/K fields show, exactly (not the colour converted back).+ h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("cmyk".into(), json!([0.0, 50.0, 100.0, 0.0]));+ h.run_steps(2);+ h.get_by_label("Add CMYK Swatch").click();+ h.run_steps(3);+ let doc = &h.state().app.session.active().unwrap().doc;+ let designcraft_color::swatch::SwatchValue::Color { color: designcraft_color::Color::Cmyk { c, m, y, k }, .. } =+ doc.swatches.last().unwrap().value+ else {+ panic!("a CMYK swatch")+ };+ assert_eq!([c, m, y, k].map(|v| (v * 100.0).round()), [0.0, 50.0, 100.0, 0.0]);+ // Its own OK, at the top right, applies it.+ h.get_by_label("OK").click();+ h.run_steps(3);+ assert!(h.state().app.ui.dialog.is_none(), "OK closes it");+ let st = h.state().app.session.active().unwrap();+ let id = st.selection.items[0];+ let fill = st.doc.item(id).unwrap().fill.swatch.clone();+ assert_eq!(st.doc.resolve_color(&fill, 1.0).unwrap().to_hex(), "#7c1315");+ }++ #[test]+ fn create_guides_dialog_covers_the_spread_in_view() {+ let mut app = facing_app(6);+ // As in InDesign, both pages of the facing spread in view get the guides.+ crate::canvas::go_to_page(&mut app, 1);+ crate::menus::activate(&mut app, "layout.createGuides", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("target"), "spread");+ ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "2"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ assert_eq!(guide_counts(&app), vec![0, 2, 2, 0, 0, 0]);+ // "This page" narrows them to the page in view.+ crate::canvas::go_to_page(&mut app, 4);+ crate::menus::activate(&mut app, "layout.createGuides", &Value::Null);+ ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "3"}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "target", "value": "page"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ assert_eq!(guide_counts(&app), vec![0, 2, 2, 0, 4, 0]);+ }++ #[test]+ fn parent_dialogs_cover_both_pages_of_the_parent_spread_by_default() {+ let mut app = facing_app(4);+ app.run("layout.parents.edit", json!({"on": true})).unwrap();+ crate::menus::activate(&mut app, "layout.marginsAndColumns", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("target"), "spread");+ for k in ["marginTop", "marginBottom", "marginInside", "marginOutside"] {+ ctl(&mut app, "ui.dialog.set", json!({"field": k, "value": "20 pt"}));+ }+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ crate::menus::activate(&mut app, "layout.createGuides", &Value::Null);+ ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "2"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ let doc = &app.session.active().unwrap().doc;+ for pg in &doc.parents[0].pages {+ assert_eq!((pg.margins.top, pg.margins.outside, pg.guides.len()), (20.0, 20.0, 2));+ }+ // Every document page shows the parent's guides.+ assert!((0..doc.page_count()).all(|abs| doc.inherited_guides(abs).len() == 2));+ }++ #[test]+ fn other_dialogs_keep_reading_bare_numbers_as_picas() {+ let mut app = facing_app(2);+ app.run("document.preferences", json!({"horizontalUnits": "millimeters"})).unwrap();+ app.ui.dialog = Some(Dialog::new("newDocument", json!({"width": "15"})));+ assert_eq!(app.ui.dialog.as_ref().unwrap().m("width"), Some(180.0));+ }+ #[test]+ fn character_style_options_set_the_digits() {+ let mut app = styled_app();+ ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.digits", "value": "farsi"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi));+ }++ #[test]+ fn import_warning_show_selects_the_frame_it_is_about() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let f = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap();+ app.run("selection.set", json!({"ids": []})).unwrap();+ let lines = json!([+ {"text": "a table of 2 rows was read as 1", "item": null},+ {"text": "story 30892: text orientation of its frames is not known or differs; written as horizontal", "item": f["id"]},+ ]);+ app.ui.dialog = Some(Dialog::new("alert", json!({"title": "Import Warnings", "file": "book.indd", "message": "", "lines": lines})));+ let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::unique("import_warning_show_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(3);+ // Only the warning that names a frame offers Show.+ assert_eq!(h.query_all_by_label("Show").count(), 1);+ h.get_by_label("Show").click();+ h.run_steps(3);+ let app = h.state();+ assert!(app.ui.dialog.is_none(), "Show closes the warnings");+ assert_eq!(app.session.doc().unwrap().selection.items, vec![designcraft_doc::ItemId(f["id"].as_u64().unwrap())]);+ }++ /// Replace the text of the field beside the `nth` label `label` (on its row, to its right) with+ /// `new`, and leave the field.+ fn retype_beside(h: &mut egui_kittest::Harness<'static, crate::test_window::Window>, label: &str, nth: usize, new: &str) {+ use egui_kittest::kittest::Queryable;+ let l = h.get_all_by_label(label).nth(nth).unwrap_or_else(|| panic!("no label {label} #{nth}")).rect();+ let field = h+ .get_all_by(|n| n.role() == egui::accesskit::Role::TextInput)+ .map(|n| n.rect())+ .filter(|r| r.center().x > l.max.x && (r.center().y - l.center().y).abs() < l.height().max(8.0))+ .min_by(|a, b| a.min.x.total_cmp(&b.min.x))+ .unwrap_or_else(|| panic!("no field beside {label} #{nth}"))+ .center();+ crate::test_window::click_at(h, field);+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);+ h.event(egui::Event::Text(new.into()));+ h.run_steps(1);+ // Tab leaves the field (Enter would be the dialog's OK).+ h.key_press(egui::Key::Tab);+ h.run_steps(3);+ }++ /// The course's chapter 40: Paragraph Border's four weights are linked as InDesign's, so a+ /// side typed in sets all four; with the link off ("Make all settings the same") a side is set+ /// alone, as the lesson gives the border only a thick left side. The corners link the same way.+ #[test]+ fn paragraph_border_sides_and_corners_link_as_indesigns() {+ use egui_kittest::kittest::Queryable;+ let (app, _) = ruled_paragraph();+ let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0));+ h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "border", "p.borderOn": true})));+ h.run_steps(4);+ let field = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, key: &str| {+ h.state().app.ui.dialog.as_ref().and_then(|d| d.fields.get(&format!("p.{key}")).cloned()).unwrap_or_default()+ };+ // The four weights start the same, so linked: Top sets them all.+ retype_beside(&mut h, "Top:", 0, "3");+ assert_eq!(field(&h, "borderWeights"), json!([3.0, 3.0, 3.0, 3.0]));+ // Unlinked, Left alone takes 10 pt.+ // The link of the weights (0), corners (1) or offsets (2), where it is now: the dialog+ // scrolls as fields take focus.+ let link = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, n: usize| {+ let links: Vec<egui::Rect> = h.get_all_by_label("Make all settings the same").map(|n| n.rect()).collect();+ assert_eq!(links.len(), 3, "weights, corners and offsets each have a link");+ links[n].center()+ };+ let at = link(&h, 0);+ crate::test_window::click_at(&mut h, at);+ retype_beside(&mut h, "Left:", 0, "10");+ assert_eq!(field(&h, "borderWeights"), json!([3.0, 10.0, 3.0, 3.0]));+ // Linked again, the four take Top's weight; unlinked once more for the thick left side.+ let at = link(&h, 0);+ crate::test_window::click_at(&mut h, at);+ assert_eq!(field(&h, "borderWeights"), json!([3.0, 3.0, 3.0, 3.0]));+ let at = link(&h, 0);+ crate::test_window::click_at(&mut h, at);+ retype_beside(&mut h, "Left:", 0, "10");+ assert_eq!(field(&h, "borderWeights"), json!([3.0, 10.0, 3.0, 3.0]));+ // The corners start the same too: Top Left's size goes to all four.+ retype_beside(&mut h, "Top Left Corner", 0, "0p4");+ let corners = field(&h, "borderCorners");+ assert!((0..4).all(|i| corners[i]["size"] == json!(4.0)), "{corners}");+ // Unlinked, Top Right alone takes 0p8; linked again, all four take Top Left's 4 pt.+ let at = link(&h, 1);+ crate::test_window::click_at(&mut h, at);+ retype_beside(&mut h, "Top Right Corner", 0, "0p8");+ assert_eq!(field(&h, "borderCorners")[1]["size"], json!(8.0));+ assert_eq!(field(&h, "borderCorners")[0]["size"], json!(4.0));+ let at = link(&h, 1);+ crate::test_window::click_at(&mut h, at);+ let corners = field(&h, "borderCorners");+ assert!((0..4).all(|i| corners[i] == corners[0] && corners[i]["size"] == json!(4.0)), "{corners}");+ confirm(&mut h.state_mut().app).unwrap();+ let style = h.state().app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap();+ assert_eq!(style.para.border_weights, Some([3.0, 10.0, 3.0, 3.0]));+ }++ /// The course's chapter 41: Paragraph Shading as InDesign's. The page is headed with its name;+ /// the tint has Overprint beside it; the corners are a two-by-two grid whose shape menus show+ /// the shapes. The lesson rounds the top two corners at 10 pt, unlinked, and moves the+ /// offsets.+ #[test]+ fn paragraph_shading_page_is_laid_out_as_indesigns() {+ use designcraft_geom::corners::CornerShape;+ use egui_kittest::kittest::Queryable;+ let (app, _) = ruled_paragraph();+ let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0));+ h.state_mut().app.ui.dialog =+ Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "shading", "p.shadingOn": true})));+ h.run_steps(4);+ let field = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, key: &str| {+ h.state().app.ui.dialog.as_ref().and_then(|d| d.fields.get(&format!("p.{key}")).cloned()).unwrap_or_default()+ };+ assert!(h.get_all_by_label("Paragraph Shading").count() >= 2, "the section list and the page's heading");+ h.get_by_label("Overprint").click();+ h.run_steps(2);+ assert_eq!(field(&h, "shadingOverprint"), json!(true));+ // The corners' link (0) and the offsets' (1).+ let link = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, n: usize| {+ let links: Vec<egui::Rect> = h.get_all_by_label("Make all settings the same").map(|n| n.rect()).collect();+ assert_eq!(links.len(), 2, "corners and offsets each have a link");+ links[n].center()+ };+ let at = link(&h, 0);+ crate::test_window::click_at(&mut h, at);+ for (corner, nth) in [("Top Left Corner", 0), ("Top Right Corner", 1)] {+ retype_beside(&mut h, corner, 0, "10 pt");+ h.get_all_by_label("Corner Shape").nth(nth).unwrap().click();+ h.run_steps(2);+ h.get_by_label("Rounded").click();+ h.run_steps(2);+ }+ let corners: [designcraft_geom::corners::Corner; 4] = serde_json::from_value(field(&h, "shadingCorners")).unwrap();+ assert_eq!(+ corners.map(|c| (c.shape, c.size)),+ [(CornerShape::Rounded, 10.0), (CornerShape::Rounded, 10.0), (CornerShape::None, 0.0), (CornerShape::None, 0.0)]+ );+ // The offsets, unlinked: Top alone.+ let at = link(&h, 1);+ crate::test_window::click_at(&mut h, at);+ retype_beside(&mut h, "Top:", 0, "3 pt");+ assert_eq!(field(&h, "shadingOffsets"), json!([3.0, 0.0, 0.0, 0.0]));+ confirm(&mut h.state_mut().app).unwrap();+ let style = h.state().app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap();+ assert_eq!((style.para.shading_on, style.para.shading_overprint), (Some(true), Some(true)));+ assert_eq!(style.para.shading_corners.map(|c| c[1].shape), Some(CornerShape::Rounded));+ }++ /// Paragraph Rules › Color offers Text Color above the swatches, so a rule set to a swatch can+ /// go back to it; Gap Color lists only swatches.+ #[test]+ fn the_rule_colour_menu_offers_text_color() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let doc = app.session.doc().unwrap().doc.clone();+ let menu = |ctx: &egui::Context, text: Option<&str>, click: Option<egui::Pos2>| {+ let mut picked = None;+ let mut labels = Vec::new();+ let mut events = Vec::new();+ if let Some(pos) = click {+ events.push(egui::Event::PointerMoved(pos));+ events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });+ events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });+ }+ let input =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 600.0))), events, ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ picked = swatch_menu_with(ui, &doc, "m", "[Black]", 130.0, text);+ });+ out.textures_delta.clear();+ for s in out.shapes {+ if let egui::Shape::Text(t) = s.shape {+ labels.push((t.galley.job.text.clone(), t.visual_bounding_rect().center()));+ }+ }+ (picked, labels)+ };+ for text in [Some("Text Color"), None] {+ let ctx = egui::Context::default();+ let (_, labels) = menu(&ctx, text, None);+ let combo = labels.iter().find(|(t, _)| t == "[Black]").unwrap().1;+ menu(&ctx, text, Some(combo));+ let (_, labels) = menu(&ctx, text, None);+ let item = labels.iter().find(|(t, _)| t == "Text Color").map(|l| l.1);+ assert_eq!(item.is_some(), text.is_some(), "{labels:?}");+ if let Some(pos) = item {+ let (picked, _) = menu(&ctx, text, Some(pos));+ assert_eq!(picked.as_deref(), Some(designcraft_doc::TEXT_COLOR));+ }+ }+ }++ /// The course's chapter 20: a paragraph style's rule below becomes wavy, 3 pt, with a gap+ /// colour, from Paragraph Rules › Type and Gap Color.+ #[test]+ fn paragraph_style_rules_take_a_type_and_a_gap_colour() {+ let (mut app, _) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"})));+ draw(&mut app, &ctx);+ if let Some(d) = app.ui.dialog.as_mut() {+ d.fields.insert("p.ruleBelow.type".into(), json!({"kind": "wavy"}));+ d.fields.insert("p.ruleBelow.weight".into(), json!(3.0));+ d.fields.insert("p.ruleBelow.gapColor".into(), json!("[Paper]"));+ }+ draw(&mut app, &ctx);+ confirm(&mut app).unwrap();+ let r = app.session.doc().unwrap().doc.styles.resolve_para_style("Ruled Child").0.rule_below;+ assert_eq!((r.kind, r.weight, r.gap_color.as_str()), (designcraft_doc::StrokeType::Wavy, 3.0, "[Paper]"));+ }++ /// A rule's Gap Tint shows 100% at its default (the rule's JSON leaves a full gap tint out).+ #[test]+ fn a_rules_default_gap_tint_shows_100() {+ use egui_kittest::kittest::Queryable;+ let (mut app, _) = ruled_paragraph();+ app.run(+ "style.paragraph.edit",+ json!({"name": "Ruled Child", "para": {"ruleBelow": {"type": {"kind": "dashed", "pattern": [4.0, 2.0]}, "gapColor": "[Paper]"}}}),+ )+ .unwrap();+ let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0));+ h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"})));+ h.run_steps(4);+ let label = h.get_by_label("Gap Tint:").rect();+ let field = h+ .get_all_by(|n| n.role() == egui::accesskit::Role::TextInput)+ .filter(|n| n.rect().center().x > label.max.x && (n.rect().center().y - label.center().y).abs() < 8.0)+ .min_by(|a, b| a.rect().min.x.total_cmp(&b.rect().min.x))+ .and_then(|n| n.value());+ assert_eq!(field.as_deref(), Some("100%"));+ }++ /// The course's chapter 20: the "Recipe Categories" title formatted on the page (size, All+ /// Caps, tracking, space after), then New Paragraph Style from it: the dialog starts from the+ /// text, and with Apply Style to Selection the paragraph takes the new style. Next Style and+ /// Reset To Base are set from General.+ #[test]+ fn a_new_paragraph_style_starts_from_the_selected_text() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Egg Recipes\rBoil them."})).unwrap();+ app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 11})).unwrap();+ app.run("type.char", json!({"attrs": {"size": 20, "capitalization": "allCaps", "tracking": 50}})).unwrap();+ app.run("type.para", json!({"attrs": {"spaceAfter": 6}})).unwrap();+ open_new_style(&mut app, true);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(+ (d.fields["c.size"].clone(), d.fields["c.capitalization"].clone(), d.fields["p.spaceAfter"].clone()),+ (json!(20.0), json!("allCaps"), json!(6.0))+ );+ assert!(d.b("apply") && !d.fields.contains_key("c.fontFamily"), "only what differs from [No Paragraph Style]");+ if let Some(d) = app.ui.dialog.as_mut() {+ d.fields.insert("rename".into(), json!("Recipe Categories"));+ d.fields.insert("nextStyle".into(), json!(designcraft_doc::BASIC_PARAGRAPH));+ }+ confirm(&mut app).unwrap();+ let a = app.run("type.selectionAttrs", json!({})).unwrap();+ assert_eq!(a["paragraphStyle"], "Recipe Categories", "applied to the selection");+ assert_eq!(a["paraOverrides"].as_u64().unwrap_or(0) + a["charOverrides"].as_u64().unwrap_or(0), 0);+ let style = |app: &DesignApp| app.session.doc().unwrap().doc.styles.para("Recipe Categories").cloned().unwrap();+ assert_eq!(style(&app).next_style.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH));+ assert_eq!(style(&app).chars.size, Some(20.0));+ // Reset To Base: the style keeps nothing of its own, apart from the edits made then.+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Recipe Categories", "basedOn": designcraft_doc::BASIC_PARAGRAPH})));+ if let Some(d) = app.ui.dialog.as_mut() {+ d.fields.insert("resetToBase".into(), json!(true));+ d.fields.insert("c.tracking".into(), json!(10.0));+ }+ confirm(&mut app).unwrap();+ let s = style(&app);+ assert_eq!((s.chars.size, s.chars.tracking, s.para.space_after), (None, Some(10.0), None), "{s:?}");+ assert_eq!(s.based_on.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH));+ }++ /// The course's chapter 22: "eggs" made bold and red on the page, then New Character Style+ /// from it. The dialog is titled as InDesign's, starts from what the text has of its own+ /// over its paragraph style ("[None] + Bold + color"), and Apply Style to Selection gives the+ /// text the style, with no override left.+ #[test]+ fn a_new_character_style_starts_from_the_selected_text() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Drop eggs into boiling water."})).unwrap();+ app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 29})).unwrap();+ app.run("style.paragraph.create", json!({"name": "Recipe", "chars": {"size": 14}})).unwrap();+ app.run("style.paragraph.apply", json!({"name": "Recipe"})).unwrap();+ app.run("text.select", json!({"story": f["story"], "anchor": 5, "focus": 9})).unwrap();+ app.run("type.char", json!({"attrs": {"fontStyle": "Bold", "fill": "C=15 M=100 Y=100 K=0"}})).unwrap();+ open_new_style(&mut app, false);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!((d.fields["c.fontStyle"].clone(), d.fields["c.fill"].clone()), (json!("Bold"), json!("C=15 M=100 Y=100 K=0")));+ assert!(d.b("apply"));+ let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::unique("new_character_style_test_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(4);+ for l in ["New Character Style", "Apply Style to Selection"] {+ assert!(h.query_by_label(l).is_some(), "{l}");+ }+ let app = h.state_mut();+ if let Some(d) = app.ui.dialog.as_mut() {+ d.fields.insert("rename".into(), json!("eggs"));+ }+ confirm(app).unwrap();+ let style = app.session.doc().unwrap().doc.styles.char_style("eggs").cloned().unwrap();+ assert_eq!((style.chars.font_style.as_deref(), style.chars.fill.as_deref()), (Some("Bold"), Some("C=15 M=100 Y=100 K=0")));+ assert_eq!(style.chars.size, None, "the size is the paragraph style's, not the text's own");+ let a = app.run("type.selectionAttrs", json!({})).unwrap();+ assert_eq!((a["characterStyle"].clone(), a["charOverrides"].clone()), (json!("eggs"), json!(0)), "applied to the selection");+ }++ /// A Based On changed in the dialog (without Reset To Base) is what the fields are checked+ /// against: the style's own settings over the new parent.+ #[test]+ fn a_changed_based_on_is_what_the_fields_are_checked_against() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("style.paragraph.create", json!({"name": "Loose", "para": {"wordSpaceMin": 1.2, "wordSpaceDesired": 1.3}})).unwrap();+ app.run("style.paragraph.create", json!({"name": "Child", "basedOn": "Loose"})).unwrap();+ let mut d = Dialog::new("paragraphStyleOptions", json!({"name": "Child"}));+ d.fields.insert("p.wordSpaceDesired".into(), json!(1.0));+ assert!(check_paragraph_style_justification(&app, &d).is_err(), "below Loose's minimum");+ d.fields.insert("basedOn".into(), json!(designcraft_doc::BASIC_PARAGRAPH));+ assert_eq!(check_paragraph_style_justification(&app, &d), Ok(()), "[Basic Paragraph]'s minimum is lower");+ }++ /// With Reset To Base, the justification fields are checked against the base style (the+ /// style's own minimum no longer applies), and Preview shows the reset on the page.+ #[test]+ fn reset_to_base_checks_and_previews_against_the_base() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Loose words"})).unwrap();+ app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 5})).unwrap();+ app.run("style.paragraph.create", json!({"name": "Loose", "basedOn": designcraft_doc::BASIC_PARAGRAPH, "para": {"wordSpaceMin": 1.2, "wordSpaceDesired": 1.3}, "chars": {"size": 30}}))+ .unwrap();+ app.run("style.paragraph.apply", json!({"name": "Loose"})).unwrap();+ let mut d = Dialog::new("paragraphStyleOptions", json!({"name": "Loose"}));+ d.fields.insert("p.wordSpaceDesired".into(), json!(1.1));+ assert!(check_paragraph_style_justification(&app, &d).is_err(), "below the style's own minimum");+ d.fields.insert("resetToBase".into(), json!(true));+ assert_eq!(check_paragraph_style_justification(&app, &d), Ok(()), "the base's minimum is 100%");+ d.fields.insert("preview".into(), json!(true));+ style_options_preview(&mut app, &mut d);+ assert_eq!(d.fields[PREVIEWED]["resetToBase"], true);+ let size = app.run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"].clone();+ assert_eq!(size, json!(12.0), "the page shows the style reset to its base");+ app.session.cancel_interaction();+ }++ /// The course's chapter 22: Find/Change › Change Format. "eggs", case sensitive, nothing in+ /// Change to; Change Format Settings › Style Options sets Character Style "eggs", and the box+ /// shows it (with Change to's ⓘ). Escape leaves the settings, not Find/Change. Change All+ /// gives every lowercase "eggs" the style and keeps the words; the trash clears the format.+ #[test]+ fn find_change_gives_the_found_text_a_change_format() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let text = "Poached Eggs\nBreak eggs; cook until eggs are set.";+ let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": text})).unwrap();+ let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap());+ app.run("style.character.create", json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap();+ app.run("app.findChange", json!({})).unwrap();+ if let Some(d) = app.ui.dialog.as_mut() {+ d.fields.insert("find".into(), json!("eggs"));+ d.fields.insert("caseSensitive".into(), json!(true));+ }+ let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::unique("change_format_test_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(4);+ const TIP: &str = "With a Change Format and nothing in Change to, the found text stays and is only formatted";+ assert!(h.query_by_label("Change Format:").is_some());+ assert!(h.query_by_label(TIP).is_none(), "no ⓘ without a Change Format");+ h.get_by_label("Specify attributes to change").click();+ h.run_steps(3);+ // Style Options is the section's name in the list and its heading.+ for l in ["Change Format Settings", "Style Options", "Basic Character Formats", "Character Color"] {+ assert!(h.query_all_by_label(l).next().is_some(), "{l}");+ }+ // Style Options › Character Style: eggs.+ h.get_all_by_value("[Any Style]").next().unwrap().click();+ h.run_steps(3);+ h.get_by_label("eggs").click();+ h.run_steps(3);+ h.get_all_by_label(" OK ").last().unwrap().click();+ h.run_steps(3);+ let field = |h: &Harness<'_, DesignApp>, k: &str| h.state().ui.dialog.as_ref().unwrap().fields.get(k).cloned();+ assert_eq!((field(&h, CHANGE_FORMAT), field(&h, FORMAT_EDIT)), (Some(json!({"charStyle": "eggs"})), None));+ assert!(h.query_by_label("Character Style: eggs").is_some(), "the box shows it");+ assert!(h.query_by_label(TIP).is_some(), "Change to's ⓘ");+ // Escape closes Change Format Settings only, and keeps the Change Format.+ h.get_by_label("Specify attributes to change").click();+ h.run_steps(3);+ h.key_press(egui::Key::Escape);+ h.run_steps(3);+ assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.id.as_str()), Some("findChange"));+ assert_eq!((field(&h, CHANGE_FORMAT), field(&h, FORMAT_EDIT)), (Some(json!({"charStyle": "eggs"})), None));+ // Change All: the words stay, every lowercase "eggs" has the style.+ h.get_by_label("Change All").click();+ h.run_steps(3);+ assert_eq!(field(&h, "status"), Some(json!("2 replacement(s) made")));+ let story = h.state().session.doc().unwrap().doc.story(sid).cloned().unwrap();+ assert_eq!(story.text, text);+ assert_eq!(+ [8, 19, 36].map(|at| story.format_after(at).style.clone()),+ [designcraft_doc::NO_CHAR_STYLE.to_string(), "eggs".into(), "eggs".into()]+ );+ // The trash clears it (the second: the first is the Find Format's).+ h.get_all_by_label("Clear specified attributes").nth(1).unwrap().click();+ h.run_steps(3);+ assert_eq!(field(&h, CHANGE_FORMAT), None);+ assert!(h.query_by_label(TIP).is_none());+ }++ /// What Change Format Settings sets goes to find.change: a paragraph style and character+ /// attributes as well as a character style; the box sums them up.+ #[test]+ fn a_change_format_goes_with_change_all() {+ let mut d = Dialog::new("findChange", json!({"find": "cook"}));+ d.fields.insert(CHANGE_FORMAT.into(), json!({"charStyle": "eggs", "paraStyle": "Method", "chars": {"underline": true}}));+ let p = find_change_params(&d);+ assert_eq!((p["charStyle"].clone(), p["paraStyle"].clone(), p["attrs"].clone()), (json!("eggs"), json!("Method"), json!({"underline": true})));+ assert_eq!(format_summary("en", d.fields.get(CHANGE_FORMAT)), "Character Style: eggs + Paragraph Style: Method + Underline: on");+ assert!(find_change_params(&Dialog::new("findChange", json!({"find": "cook"}))).get("attrs").is_none());+ // A Find Format goes with every search.+ d.fields.insert(FIND_FORMAT.into(), json!({"paraStyle": "Method"}));+ assert_eq!(find_change_params(&d)["findFormat"], json!({"paraStyle": "Method"}));+ }++ /// Find/Change › Find Format, as InDesign's: Find Format Settings sets the character style the+ /// found text must have, the box shows it with Find what's ⓘ, and Count counts only "eggs" in+ /// it; with nothing in Find what, Find Next finds the text in the style; the first trash clears+ /// it.+ #[test]+ fn find_format_finds_only_text_with_it() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Break eggs; cook eggs."})).unwrap();+ app.run("style.character.create", json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap();+ app.run("text.select", json!({"story": f["story"], "anchor": 6, "focus": 10})).unwrap();+ app.run("style.character.apply", json!({"name": "eggs"})).unwrap();+ app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 0})).unwrap();+ app.run("app.findChange", json!({})).unwrap();+ if let Some(d) = app.ui.dialog.as_mut() {+ d.fields.insert("find".into(), json!("eggs"));+ }+ let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::unique("find_format_test_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(4);+ const TIP: &str = "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it";+ assert!(h.query_by_label("Find Format:").is_some() && h.query_by_label(TIP).is_none());+ h.get_by_label("Specify attributes to find").click();+ h.run_steps(3);+ assert!(h.query_by_label("Find Format Settings").is_some());+ h.get_all_by_value("[Any Style]").next().unwrap().click();+ h.run_steps(3);+ h.get_by_label("eggs").click();+ h.run_steps(3);+ h.get_all_by_label(" OK ").last().unwrap().click();+ h.run_steps(3);+ let field = |h: &Harness<'_, DesignApp>, k: &str| h.state().ui.dialog.as_ref().unwrap().fields.get(k).cloned();+ assert_eq!((field(&h, FIND_FORMAT), field(&h, CHANGE_FORMAT)), (Some(json!({"charStyle": "eggs"})), None));+ assert!(h.query_by_label("Character Style: eggs").is_some() && h.query_by_label(TIP).is_some());+ h.get_by_label("Count").click();+ h.run_steps(3);+ assert_eq!(field(&h, "status"), Some(json!("1 match(es)")), "only the \"eggs\" in the style");+ // Nothing in Find what: the text in the style.+ h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("find".into(), json!(""));+ h.run_steps(2);+ h.get_by_label("Find Next").click();+ h.run_steps(3);+ let sel = h.state().session.doc().unwrap().selection.text.unwrap();+ assert_eq!(sel.range(), 6..10);+ // The first trash is the Find Format's.+ h.get_all_by_label("Clear specified attributes").next().unwrap().click();+ h.run_steps(3);+ assert_eq!(field(&h, FIND_FORMAT), None);+ }++ /// The course's chapter 26: Preferences › Interface as InDesign's. A Color Theme swatch shows+ /// its theme at once and Cancel goes back; OK keeps the theme and the Tools panel's columns.+ /// UI Size is in a UI Scaling section of its own.+ #[test]+ fn preferences_interface_sets_the_color_theme_and_tools_panel() {+ use crate::theme::Brightness;+ use egui::accesskit::Role;+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let opened = app.ui.brightness;+ let open = |app: &mut DesignApp| {+ app.run("app.preferences", json!({})).unwrap();+ app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!("interface"));+ };+ open(&mut app);+ let mut h = Harness::builder().with_size(egui::vec2(1100.0, 760.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::unique("prefs_interface_test_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(3);+ let swatch = |h: &Harness<'_, DesignApp>, name: &str| h.get_by(|n| n.role() == Role::RadioButton && n.label().as_deref() == Some(name)).click();+ for l in ["Appearance", "Color Theme:", "Panels", "Tools Panel:"] {+ assert!(h.query_by_label(l).is_some(), "{l}");+ }+ // A click shows the theme at once; Cancel goes back.+ swatch(&h, "Light");+ h.run_steps(3);+ assert_eq!(h.state().ui.brightness, Brightness::Light);+ h.get_by_label("Cancel").click();+ h.run_steps(3);+ assert!(h.state().ui.dialog.is_none());+ assert_eq!(h.state().ui.brightness, opened, "Cancel goes back to the theme Preferences opened with");+ // OK keeps the theme and the Tools panel's columns.+ open(h.state_mut());+ h.run_steps(3);+ swatch(&h, "Dark");+ h.run_steps(2);+ h.get_by(|n| n.role() == Role::ComboBox && n.value().as_deref() == Some("Single Column")).click();+ h.run_steps(2);+ h.get_by_label("Double Column").click();+ h.run_steps(2);+ h.get_by_label(" OK ").click();+ h.run_steps(3);+ assert!(h.state().ui.dialog.is_none());+ assert_eq!(h.state().ui.brightness, Brightness::Dark);+ assert!(h.state().ui.tools_double_column);+ // The same command the Window menu toggles, with an explicit state for Preferences.+ assert_eq!(h.state_mut().run("window.toolsDoubleColumn", json!({"on": false})).unwrap(), json!(false));+ assert_eq!(h.state_mut().run("window.toolsDoubleColumn", json!({"on": false})).unwrap(), json!(false), "set, not toggled");+ assert_eq!(h.state_mut().run("window.toolsDoubleColumn", json!({})).unwrap(), json!(true), "toggled without `on`");+ // UI Size has a section of its own.+ open(h.state_mut());+ h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!("uiScaling"));+ h.run_steps(3);+ assert!(h.query_by_label("UI Size:").is_some());+ }++ /// With no document open, Preferences has Units & Increments, as InDesign's: OK keeps them+ /// for new documents, and New Document opens in them (Lollo's inches, set once).+ #[test]+ fn preferences_with_no_document_set_the_units_of_new_documents() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ crate::menus::activate(&mut app, "app.preferences", &Value::Null);+ let mut d = app.ui.dialog.take().expect("Preferences");+ assert!(d.b("defaults"), "for new documents");+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));+ app.ui.dialog = Some(d.clone());+ let mut labels = vec![];+ for _ in 0..3 {+ labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ assert!(labels.iter().any(|(t, _, _)| t == "Units & Increments"), "listed with no document: {labels:?}");+ d.fields.insert("horizontalUnits".into(), json!("inches"));+ d.fields.insert("verticalUnits".into(), json!("inches"));+ d.fields.insert("keyboardIncrement".into(), json!("0.5 pt"));+ app.ui.dialog = Some(d);+ confirm(&mut app).unwrap();+ let du = app.session.prefs.default_units;+ assert_eq!((du.horizontal_units, du.vertical_units, du.keyboard_increment), (Unit::Inches, Unit::Inches, 0.5));+ assert!(app.session.active().is_none(), "no document made");+ // A Cursor Key of 0 or text that isn't a measure is refused, keeping the dialog open and+ // the saved values, the other preferences' too; a Kerning/Tracking of 0.5 is kept as it is.+ let scale = app.session.prefs.scale_strokes;+ for bad in [json!({"keyboardIncrement": "0 pt"}), json!({"keyboardIncrement": "wide"}), json!({"kerningIncrement": "lots"})] {+ let mut d = Dialog::new("preferences", json!({"defaults": true, "horizontalUnits": "inches", "scaleStrokes": !scale}));+ for (k, v) in bad.as_object().unwrap() {+ d.fields.insert(k.clone(), v.clone());+ }+ app.ui.dialog = Some(d);+ assert!(confirm(&mut app).is_err(), "{bad}");+ assert!(app.ui.dialog.as_ref().is_some_and(|d| d.id == "preferences"), "still open: {bad}");+ assert_eq!(app.session.prefs.default_units.keyboard_increment, 0.5, "{bad}");+ assert_eq!(app.session.prefs.scale_strokes, scale, "no other preference saved: {bad}");+ }+ app.ui.dialog = Some(Dialog::new("preferences", json!({"defaults": true, "horizontalUnits": "inches", "kerningIncrement": "0.5"})));+ confirm(&mut app).unwrap();+ assert_eq!(app.session.prefs.default_units.kerning_increment, 0.5, "not rounded up to 1");+ // New Document opens in inches, and the document it makes has inch rulers.+ crate::menus::activate(&mut app, "app.newDocumentDialog", &Value::Null);+ let nd = app.ui.dialog.clone().expect("New Document");+ assert_eq!(nd.fields["units"], json!("inches"));+ assert_eq!(nd.s("width"), designcraft_geom::format_measure(612.0, Unit::Inches));+ confirm(&mut app).unwrap();+ let st = &app.session.doc().unwrap().doc.settings;+ assert_eq!((st.horizontal_units, st.vertical_units, st.keyboard_increment), (Unit::Inches, Unit::Inches, 0.5));+ // With the document open, Preferences edits that document's units, not the defaults.+ crate::menus::activate(&mut app, "app.preferences", &Value::Null);+ assert!(!app.ui.dialog.as_ref().unwrap().b("defaults"));+ }++ /// Preferences › File Handling shows the number of recent items as a whole number, as+ /// InDesign's does ("20"; it read "20.0").+ #[test]+ fn file_handling_shows_the_recent_items_count_as_a_whole_number() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("app.preferences", json!({})).unwrap();+ app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!("files"));+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 700.0));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, "Number of Recent Items to Display:");+ let count = app.ui.dialog.as_ref().unwrap().n("recentFilesMax").unwrap();+ assert_eq!(count, 20.0, "InDesign's default");+ visible_label(&labels, screen, &format!("{count}"));+ assert!(!labels.iter().any(|(t, _, _)| t.trim() == format!("{count:.1}")), "no decimal shown");+ }++ /// Collapsing advanced TOC controls changes visibility without discarding their values.+ #[test]+ fn toc_more_options_preserves_hidden_settings() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.newSample", json!({})).unwrap();+ open_toc(&mut app);+ app.ui.dialog.as_mut().unwrap().fields.insert(+ "included".into(),+ json!([{+ "style": "Headline", "level": 3, "separator": " ^t", "pageNumber": "before",+ "pageNumberStyle": "Accent", "separatorStyle": "Emphasis", "sort": true+ }]),+ );+ let before = toc_params(&app, app.ui.dialog.as_ref().unwrap());+ let revision = app.session.doc().unwrap().revision;+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, "Between Entry and Number:");+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Fewer Options").center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(!labels.iter().any(|(text, _, _)| text == "Between Entry and Number:"));+ visible_label(&labels, screen, "Entry Style:");+ assert_eq!(toc_params(&app, app.ui.dialog.as_ref().unwrap()), before);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "More Options").center());+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, "Between Entry and Number:");+ assert_eq!(toc_params(&app, app.ui.dialog.as_ref().unwrap()), before);+ assert_eq!(app.session.doc().unwrap().revision, revision);+ }++ /// Enter on the focused Fewer Options / More Options button toggles the options; it doesn't+ /// also make the table of contents.+ #[test]+ fn enter_on_the_toc_options_toggle_only_toggles() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.newSample", json!({})).unwrap();+ open_toc(&mut app);+ let revision = app.session.doc().unwrap().revision;+ let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::unique("toc_toggle_test_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(3);+ h.get_by_label("Fewer Options").focus();+ h.run_steps(2);+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ let d = h.state().ui.dialog.as_ref().expect("the dialog stays open");+ assert_eq!((d.id.as_str(), d.b("moreOptions")), (TOC, false), "the options are fewer");+ assert_eq!(h.state().session.doc().unwrap().revision, revision, "no table of contents made");+ assert!(h.query_by_label("More Options").is_some());+ }++ /// The title stays readable beside the style selector after the grid settles.+ #[test]+ fn toc_title_field_shows_the_whole_default_title() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.newSample", json!({})).unwrap();+ open_toc(&mut app);+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let title_row = |labels: &[(String, egui::Rect, egui::Rect)]| {+ let y = visible_label(labels, screen, "Title:").center().y;+ labels.iter().filter(|(_, rect, _)| (rect.center().y - y).abs() < 2.0).cloned().collect::<Vec<_>>()+ };+ visible_label(&title_row(&labels), screen, "Contents");+ app.ui.dialog.as_mut().unwrap().fields.insert("title".into(), json!("Table of Contents"));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&title_row(&labels), screen, "Table of Contents");+ // A small window: the title narrows and the style selector beside it stays in view.+ let small = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(450.0, 280.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, small, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, small, vec![]);+ let y = visible_label(&labels, small, "Title:").center().y;+ let row: Vec<_> = labels.iter().filter(|(_, rect, _)| (rect.center().y - y).abs() < 2.0).cloned().collect();+ let style = visible_label(&row, small, "TOC Title");+ // The selector is 200 pt wide from just before its text: all of it is in the dialog body.+ let (_, _, body) = row.iter().find(|(text, _, _)| text == "Style:").unwrap();+ assert!(style.min.x - 4.0 + 200.0 <= body.max.x, "the style selector fits the dialog: {style:?} in {body:?}");+ }++ /// The bookmarks checkbox persists through generation and reopening the dialog.+ #[test]+ fn toc_bookmarks_checkbox_sets_and_reopens_the_persisted_option() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.newSample", json!({})).unwrap();+ open_toc(&mut app);+ assert!(app.ui.dialog.as_ref().unwrap().b("createBookmarks"));+ app.ui.dialog.as_mut().unwrap().fields.insert("included".into(), json!([{"style": "Headline", "level": 1}]));+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, "Create PDF Bookmarks");+ confirm(&mut app).unwrap();+ assert!(app.session.doc().unwrap().doc.toc.as_ref().unwrap().create_bookmarks);+ assert!(!app.session.doc().unwrap().doc.bookmarks.is_empty());+ open_toc(&mut app);+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Create PDF Bookmarks").center());+ confirm(&mut app).unwrap();+ assert!(app.session.doc().unwrap().doc.bookmarks.is_empty());+ open_toc(&mut app);+ assert!(!app.ui.dialog.as_ref().unwrap().b("createBookmarks"));+ }++ #[test]+ fn corner_options_dialog_sets_each_corner_with_preview_and_one_undo_step() {+ use designcraft_geom::corners::CornerShape;+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = app.run("frame.create", json!({"rect": [72, 72, 360, 360]})).unwrap()["id"].as_u64().unwrap();+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ let corners = |app: &DesignApp| app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().corners.corners;+ let undo = |app: &DesignApp| app.session.doc().unwrap().history.undo.len();+ let set = |app: &mut DesignApp, k: &str, v: Value| {+ app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v);+ };+ let u0 = undo(&app);+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));+ // Object › Corner Options… opens InDesign's dialog, not a form of the command's params.+ crate::menus::activate(&mut app, "object.cornerOptions", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some(CORNER_OPTIONS));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in ["Corner Options", "Corner Size and Shape:", "Preview", "OK", "Cancel"] {+ visible_label(&labels, screen, expected);+ }+ assert!(!labels.iter().any(|(t, _, _)| t.trim() == "Ids"), "no raw command fields");+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!((d.s("size1"), d.s("shape1"), d.b("link")), ("0p0".into(), "none".into(), true), "seeded from the frame, linked");+ // Linked: a corner changed is all four.+ set(&mut app, "size0", json!("1p0"));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("size2"), "1p0");+ // Unlinked, only the top-right corner rounds, as in the tutorial.+ set(&mut app, "link", json!(false));+ for k in 0..4 {+ set(&mut app, &format!("size{k}"), json!("0"));+ }+ set(&mut app, "size1", json!("3 cm"));+ set(&mut app, "shape1", json!("rounded"));+ set(&mut app, "preview", json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!(corners(&app)[1].shape, CornerShape::Rounded, "Preview shows it");+ assert_eq!(undo(&app), u0, "without an undo step");+ set(&mut app, "preview", json!(false));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!(corners(&app)[1].shape, CornerShape::None, "Preview off puts it back");+ set(&mut app, "preview", json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ confirm(&mut app).unwrap();+ let c = corners(&app);+ assert_eq!(c.map(|c| c.shape), [CornerShape::None, CornerShape::Rounded, CornerShape::None, CornerShape::None]);+ assert!((c[1].size - 3.0 / 2.54 * 72.0).abs() < 1e-6, "{}", c[1].size);+ assert_eq!(undo(&app), u0 + 1, "one undo step");+ // Reopened, it shows the frame's corners, no longer linked.+ crate::menus::activate(&mut app, "object.cornerOptions", &Value::Null);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!((d.s("shape1"), d.s("shape0"), d.b("link")), ("rounded".into(), "none".into(), false));+ // A size that does not parse keeps the dialog open with the error; so does a shape the+ // dialog doesn't offer (rather than another shape taking its place).+ set(&mut app, "size0", json!("abc"));+ assert!(confirm(&mut app).is_err());+ assert!(app.ui.dialog.is_some());+ set(&mut app, "size0", json!("0"));+ set(&mut app, "shape0", json!("spiky"));+ assert!(confirm(&mut app).is_err());+ assert!(app.ui.dialog.is_some());+ cancel(&mut app);+ assert_eq!(corners(&app), c);+ }++ /// Several objects: the dialog shows the first one's corners, and OK sets only the corners+ /// edited; the others keep each object's own. A linked edit sets all four.+ #[test]+ fn corner_options_keep_each_objects_untouched_corners() {+ use designcraft_geom::corners::CornerShape;+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let a = app.run("frame.create", json!({"rect": [72, 72, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ let b = app.run("frame.create", json!({"rect": [272, 72, 400, 200]})).unwrap()["id"].as_u64().unwrap();+ app.run("object.cornerOptions", json!({"ids": [b], "shape": "bevel", "size": 12})).unwrap();+ app.run("selection.set", json!({"ids": [a, b]})).unwrap();+ let corners = |app: &DesignApp, id: u64| app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().corners.corners;+ let set = |app: &mut DesignApp, k: &str, v: Value| {+ app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v);+ };+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));+ let b0 = corners(&app, b);+ // Unlinked: only the top-right corner rounds, on both.+ crate::menus::activate(&mut app, "object.cornerOptions", &Value::Null);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ set(&mut app, "link", json!(false));+ set(&mut app, "size1", json!("1p0"));+ set(&mut app, "shape1", json!("rounded"));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ confirm(&mut app).unwrap();+ let (ca, cb) = (corners(&app, a), corners(&app, b));+ assert_eq!(ca.map(|c| c.shape), [CornerShape::None, CornerShape::Rounded, CornerShape::None, CornerShape::None]);+ assert_eq!(cb.map(|c| c.shape), [CornerShape::Bevel, CornerShape::Rounded, CornerShape::Bevel, CornerShape::Bevel], "b keeps its others");+ assert_eq!((cb[0], cb[2], cb[3]), (b0[0], b0[2], b0[3]));+ assert_eq!(ca[1], cb[1]);+ // Linked: a corner set to the first object's own value still sets all four, on both.+ crate::menus::activate(&mut app, "object.cornerOptions", &Value::Null);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ set(&mut app, "link", json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ set(&mut app, "size0", json!("0p6"));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ confirm(&mut app).unwrap();+ let (ca, cb) = (corners(&app, a), corners(&app, b));+ assert_eq!(ca, cb, "all four, on both");+ assert!(ca.iter().all(|c| c.shape == CornerShape::None && (c.size - 6.0).abs() < 1e-6), "{ca:?}");+ }++ #[test]+ fn on_a_page_without_a_section_the_window_is_new_section() {+ // Chris Nielsen's "Numbering Page Sections" (4:43): page 3 selected, the Pages panel menu's+ // Numbering & Section Options opens New Section with Start Section on and 1 offered.+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 6, "facingPages": true})).unwrap();+ app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0)));+ crate::canvas::go_to_page(&mut app, 2);+ crate::menus::activate(&mut app, "layout.section", &Value::Null);+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!(+ (d.n("page"), d.b("newSection"), d.b("startSection"), d.b("automatic"), d.s("startNumber")),+ (Some(3.0), true, true, true, "1".into())+ );+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, "New Section");+ // Typing a number in the field chooses Start Page Numbering at; OK: page 3 is page 5 (odd,+ // so a facing page stays on the right).+ let field = visible_label(&labels, screen, "1");+ click_dialog(&mut app, &ctx, screen, field.center());+ dialog_frame(+ &mut app,+ &ctx,+ screen,+ vec![+ egui::Event::Key { key: egui::Key::End, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE },+ egui::Event::Key { key: egui::Key::Backspace, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE },+ egui::Event::Text("5".into()),+ ],+ );+ assert!(!app.ui.dialog.as_ref().unwrap().b("automatic"), "typing chose Start Page Numbering at");+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "OK").center());+ assert!(app.ui.dialog.is_none());+ assert_eq!(app.session.active().unwrap().doc.page_name(2), "5");+ // Opened again on that page, it is Numbering & Section Options, showing the section.+ crate::menus::activate(&mut app, "layout.section", &Value::Null);+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!((d.b("newSection"), d.b("startSection"), d.b("automatic"), d.s("startNumber")), (false, true, false, "5".into()));+ let labels = (0..4).map(|_| dialog_frame(&mut app, &ctx, screen, vec![])).last().unwrap();+ visible_label(&labels, screen, "Numbering & Section Options");+ assert!(!labels.iter().any(|(t, _, _)| t == "New Section"));+ }++ /// Find/Change's Change and Change/Find, as InDesign's: Find Next selects a match, Change/Find+ /// changes it and selects the next, Change changes that one and keeps it selected. With no+ /// text selected they're off.+ #[test]+ fn change_and_change_find_change_the_found_text() {+ use egui_kittest::Harness;+ use egui_kittest::kittest::{NodeT, Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "red red | red"})).unwrap();+ let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap());+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();+ app.run("app.findChange", json!({})).unwrap();+ if let Some(d) = app.ui.dialog.as_mut() {+ d.fields.insert("find".into(), json!("red"));+ d.fields.insert("change".into(), json!("blue"));+ }+ let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::unique("change_find_test_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(4);+ assert!(h.query_by_value("Document").is_some(), "the Search choices are InDesign's");+ assert!(h.get_by_label("Change").accesskit_node().is_disabled(), "nothing found yet");+ let text = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.story(sid).unwrap().text.clone();+ let selected = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().selection.text.unwrap().range();+ h.get_by_label("Find Next").click();+ h.run_steps(3);+ assert_eq!(selected(&h), 0..3);+ h.get_by_label("Change/Find").click();+ h.run_steps(3);+ assert_eq!((text(&h), selected(&h)), ("blue red | red".to_string(), 5..8));+ h.get_by_label("Change").click();+ h.run_steps(3);+ assert_eq!((text(&h), selected(&h)), ("blue blue | red".to_string(), 5..9));+ assert_eq!(h.state().ui.dialog.as_ref().unwrap().fields["status"], json!("1 replacement(s) made"));+ }++ /// Insert Table: the dimensions as typed, and the Table Style chosen is applied to the new+ /// table; [Basic Table] (the default) leaves it unstyled.+ #[test]+ fn insert_table_applies_its_dimensions_and_table_style() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("style.table.create", json!({"name": "Grid"})).unwrap();+ for (style, expected) in [("Grid", "Grid"), (designcraft_doc::BASIC_TABLE, "")] {+ app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap();+ assert_eq!(app.run("app.insertTableDialog", json!({})).unwrap(), Value::Null);+ for (field, value) in [("bodyRows", json!(5)), ("columns", json!(3)), ("headerRows", json!(1)), ("tableStyle", json!(style))] {+ ctl(&mut app, "ui.dialog.set", json!({"field": field, "value": value}));+ }+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ let t = app.run("table.get", json!({})).unwrap();+ let len = |k: &str| t[k].as_array().map_or(0, Vec::len);+ assert_eq!((len("rows"), len("columns"), t["headerRows"].as_u64()), (6, 3, Some(1)), "{t}");+ assert_eq!(t["style"].as_str().unwrap_or(""), expected, "{t}");+ // One Insert Table, one undo.+ app.run("edit.undo", json!({})).unwrap();+ assert!(app.run("table.get", json!({})).is_err(), "the table is gone");+ }+ // A null style is no style: the table is made, unstyled.+ app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap();+ app.run("app.insertTableDialog", json!({})).unwrap();+ ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": null}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ assert_eq!(app.run("table.get", json!({})).unwrap()["style"].as_str().unwrap_or(""), "");+ app.run("edit.undo", json!({})).unwrap();+ // A style that no longer exists changes nothing.+ let tables = |app: &DesignApp| app.session.active().unwrap().doc.stories.values().map(|s| s.tables.len()).sum::<usize>();+ app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap();+ app.run("app.insertTableDialog", json!({})).unwrap();+ ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": "Gone"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false);+ assert_eq!(tables(&app), 0);+ let d = app.ui.dialog.as_ref().expect("the dialog stays open to be corrected");+ assert_eq!((d.id.as_str(), d.s("tableStyle")), ("insertTable", "Gone".to_string()));+ // So does a style that isn't a name: the command refuses it, rather than making the table+ // unstyled.+ ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": 42}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false);+ assert_eq!(tables(&app), 0);+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("insertTable"), "the dialog stays open");+ }++ /// Convert Text to Table: available with text selected (not with a caret alone); its+ /// separators and Number of Columns shape the table. Convert Table to Text takes it back with+ /// the separators chosen there.+ #[test]+ fn convert_dialogs_use_their_separators() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let text = "Name:\nAddress:\nCity:\nState:";+ let sid = app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text", "text": text})).unwrap()["story"].clone();+ app.run("text.select", json!({"story": sid, "anchor": 0, "focus": 0})).unwrap();+ assert!(!crate::menus::menu_enabled(&app, "app.convertTextToTableDialog"), "a caret alone");+ assert!(!crate::menus::menu_enabled(&app, "app.convertTableToTextDialog"), "no table");+ app.run("text.select", json!({"story": sid, "anchor": 0, "focus": text.len()})).unwrap();+ assert!(crate::menus::menu_enabled(&app, "app.convertTextToTableDialog"));+ app.run("app.convertTextToTableDialog", json!({})).unwrap();+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("convertTextToTable"));+ // "comma" and a typed "," are the same separator, so Number of Columns applies; a count of+ // 0 is refused, not taken as 1, and the dialog stays open.+ ctl(&mut app, "ui.dialog.set", json!({"field": "columnSeparator", "value": "comma"}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "rowSeparator", "value": ","}));+ assert!(same_separators(app.ui.dialog.as_ref().unwrap()));+ ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": 0}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false);+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("convertTextToTable"));+ // An emptied separator: the command refuses it and the dialog stays open, as typed.+ ctl(&mut app, "ui.dialog.set", json!({"field": "rowSeparator", "value": ""}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false);+ assert_eq!(app.ui.dialog.as_ref().map(|d| (d.id.as_str(), d.s("rowSeparator"))), Some(("convertTextToTable", String::new())));+ for (field, value) in [("columnSeparator", json!("paragraph")), ("rowSeparator", json!("paragraph")), ("columns", json!(2))] {+ ctl(&mut app, "ui.dialog.set", json!({"field": field, "value": value}));+ }+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ let t = app.run("table.get", json!({})).unwrap();+ let len = |k: &str| t[k].as_array().map_or(0, Vec::len);+ assert_eq!((len("rows"), len("columns")), (2, 2), "{t}");+ assert!(crate::menus::menu_enabled(&app, "app.convertTableToTextDialog"));+ app.run("app.convertTableToTextDialog", json!({})).unwrap();+ ctl(&mut app, "ui.dialog.set", json!({"field": "columnSeparator", "value": ", "}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ let story = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(sid.as_u64().unwrap())).unwrap().text.clone();+ // (The empty paragraph after a table that ends its story stays after the text.)+ assert_eq!(story.trim_end(), "Name:, Address:\nCity:, State:");+ }++ /// The Rectangle dialog a frame-tool click opens shows the width in the horizontal ruler unit and+ /// the height in the vertical one, not always picas, and reads bare numbers the same way (#1964).+ #[test]+ fn frame_size_dialog_follows_the_ruler_units() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("document.preferences", json!({"horizontalUnits": "inches", "verticalUnits": "millimeters"})).unwrap();+ // As the frame tool asks: a click at (36, 36), 72 pt by 72 pt.+ app.session.ui_requests.push(designcraft_engine::UiRequest::Dialog {+ id: "frameSize".into(),+ params: json!({"spread": 0, "shape": "rectangle", "content": "graphic", "x": 36.0, "y": 36.0, "width": 72.0, "height": 72.0}),+ });+ app.after_engine();+ let d = app.ui.dialog.as_ref().expect("the Rectangle dialog");+ assert_eq!((d.id.as_str(), d.unit), ("frameSize", Unit::Inches));+ assert_eq!(d.s("width"), format_measure(72.0, Unit::Inches));+ assert_eq!(d.s("height"), format_measure(72.0, Unit::Millimeters));+ assert!(!d.s("width").contains('p') && !d.s("height").contains('p'), "no picas: {} x {}", d.s("width"), d.s("height"));+ // Bare numbers typed in each field are in that field's unit: 2 in by 50 mm.+ let d = app.ui.dialog.as_mut().unwrap();+ d.fields.insert("width".into(), json!("2"));+ d.fields.insert("height".into(), json!("50"));+ let before = app.session.doc().unwrap().doc.clone();+ confirm(&mut app).unwrap();+ let after = &app.session.doc().unwrap().doc;+ let added: Vec<_> = after.spreads[0].items.iter().filter(|i| !before.spreads[0].items.iter().any(|b| b.id == i.id)).collect();+ assert_eq!(added.len(), 1, "one frame");+ let b = added[0].bounds();+ assert!((b.width() - 144.0).abs() < 0.01 && (b.height() - 50.0 / 25.4 * 72.0).abs() < 0.01, "{b:?}");+ // The properties panel's link opens it in the same units.+ let d = frame_size_dialog(&app, json!({"width": 36.0, "height": 36.0}));+ assert_eq!((d.s("width"), d.s("height")), (format_measure(36.0, Unit::Inches), format_measure(36.0, Unit::Millimeters)));+ // Every ruler unit: the shown size reads back as the size, so OK leaves a 72 pt frame 72 pt.+ let units = serde_json::to_value(Unit::ALL).unwrap();+ for (unit, name) in Unit::ALL.iter().zip(units.as_array().unwrap()) {+ app.run("document.preferences", json!({"horizontalUnits": name, "verticalUnits": name})).unwrap();+ let d = frame_size_dialog(&app, json!({"width": 72.0, "height": 145.0}));+ assert_eq!(d.unit, *unit);+ for (k, pt) in [("width", 72.0), ("height", 145.0)] {+ let back = d.m_in(k, *unit).unwrap_or(f64::NAN);+ assert!((back - pt).abs() < 0.05, "{name}: {k} shows {:?}, reads back {back}", d.s(k));+ }+ }+ }++ /// #2055 review: the Rectangle dialog reads the height in the vertical unit it showed when it+ /// opened. Rulers switched while it is open (the control channel) leave a typed 50 at 50 mm.+ #[test]+ fn frame_size_dialog_keeps_its_units_while_open() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("document.preferences", json!({"horizontalUnits": "millimeters", "verticalUnits": "millimeters"})).unwrap();+ app.session.ui_requests.push(designcraft_engine::UiRequest::Dialog {+ id: "frameSize".into(),+ params: json!({"spread": 0, "shape": "rectangle", "content": "graphic", "x": 36.0, "y": 36.0, "width": 72.0, "height": 72.0}),+ });+ app.after_engine();+ let d = app.ui.dialog.as_mut().expect("the Rectangle dialog");+ d.fields.insert("width".into(), json!("50"));+ d.fields.insert("height".into(), json!("50"));+ app.run("document.preferences", json!({"horizontalUnits": "inches", "verticalUnits": "inches"})).unwrap();+ let before = app.session.doc().unwrap().doc.clone();+ confirm(&mut app).unwrap();+ let after = &app.session.doc().unwrap().doc;+ let added: Vec<_> = after.spreads[0].items.iter().filter(|i| !before.spreads[0].items.iter().any(|b| b.id == i.id)).collect();+ assert_eq!(added.len(), 1, "one frame");+ let b = added[0].bounds();+ let mm50 = 50.0 / 25.4 * 72.0;+ assert!((b.width() - mm50).abs() < 0.01 && (b.height() - mm50).abs() < 0.01, "50 mm by 50 mm (about 141.73 pt): {b:?}");+ // A dialog made without the vertical unit (`Dialog::new`) reads the height in its own unit.+ let mut d = Dialog::new("frameSize", json!({"width": "2", "height": "3"}));+ d.unit = Unit::Inches;+ assert_eq!(d.vertical_unit, None);+ app.ui.dialog = Some(d);+ let before = app.session.doc().unwrap().doc.clone();+ confirm(&mut app).unwrap();+ let after = &app.session.doc().unwrap().doc;+ let added: Vec<_> = after.spreads[0].items.iter().filter(|i| !before.spreads[0].items.iter().any(|b| b.id == i.id)).collect();+ assert_eq!(added.len(), 1, "one frame");+ let b = added[0].bounds();+ assert!((b.width() - 144.0).abs() < 0.01 && (b.height() - 216.0).abs() < 0.01, "{b:?}");+ }++++#[test]++fn parent_resize_exact_dialog_keeps_its_target_and_rejects_invalid_input() {++ use designcraft_tools::{PointerEvent, PointerKind};++ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());++ app.run("file.new", json!({"width":400,"height":600,"pages":3,"facingPages":true})).unwrap();++ app.run("layout.parents.new", json!({"prefix":"B"})).unwrap();++ app.run("layout.parents.edit", json!({"on":true})).unwrap();++ app.session.set_tool("page");++ let before = app.session.doc().unwrap().doc.clone();++ let sr = designcraft_doc::SpreadRef::Parent(1);++ let p = app.session.layout().spread_page_rect(&before, sr, 1).unwrap().center();++ app.session.pointer(&PointerEvent::new(PointerKind::DoubleClick, p.x, p.y), designcraft_engine::ViewInfo::at_zoom(1.0)).unwrap();++ let request = app.session.ui_requests.pop().unwrap();++ let designcraft_engine::UiRequest::Dialog { id, params } = request else { panic!("expected exact-size dialog") };++ app.ui.dialog = Some(Dialog::new(&id, params));++ let d = app.ui.dialog.as_mut().unwrap();++ d.fields.insert("width".into(), json!("530"));++ d.fields.insert("height".into(), json!("710"));++ confirm(&mut app).unwrap();++ let doc = &app.session.doc().unwrap().doc;++ assert_eq!((doc.parents[1].pages[1].width, doc.parents[1].pages[1].height), (530.0, 710.0));++ assert_eq!(doc.parents[0], before.parents[0]);++ assert_eq!(doc.spreads, before.spreads);++ let saved = doc.clone();++ app.ui.dialog = Some(Dialog::new("cmd:layout.parentPageSize", json!({"parent":saved.parents[1].id.0,"page":1,"width":"NaN"})));++ assert!(confirm(&mut app).is_err());++ assert!(app.ui.dialog.is_some());++ assert!(std::sync::Arc::ptr_eq(&saved, &app.session.doc().unwrap().doc));++}diff --cc crates/ui-egui/src/menus/run.rsindex 000000000,ee7fdbb5e..d2a87be3cmode 000000,100644..100644--- a/crates/ui-egui/src/menus/run.rs+++ b/crates/ui-egui/src/menus/run.rs@@@ -1,0 -1,1157 +1,1157 @@@+ use super::export::{download_document, export_bytes, export_epub, export_idml, export_pdf, export_png, separations_view};+ use super::invoke::guide_spread;+ use super::state::{is_window_control, menu_enabled, window_control_available};+ use super::tables::{CLASSIC_GROUPS, TYPOGRAPHY_GROUPS, workspace_open_panel};+ use super::tree::recent_label;+ use super::{DesignApp, ScreenMode, Value, json};+ use crate::app::file_dialogs::{Bound, with_path};++ /// Type › Tabs: float the Tabs panel (placed above the selected text frame) or close it.+ fn toggle_tabs_panel(app: &mut DesignApp) {+ if app.ui.floating.iter().any(|(p, _)| p == "tabs") {+ app.ui.floating.retain(|(p, _)| p != "tabs");+ } else {+ let at = app.canvas_rect.map_or(egui::pos2(300.0, 140.0), |r| r.min + egui::vec2(80.0, 60.0));+ app.ui.floating.push(("tabs".into(), [at.x, at.y]));+ app.ui.tabs_panel.snap_request = 2;+ }+ }++ /// Asks for a file to open for `purpose`, then runs the UI command `id` again with `p` and the+ /// chosen file under `key`.+ #[track_caller]+ fn rerun_with_path(app: &mut DesignApp, purpose: &str, id: &str, p: &Value, key: &'static str) -> Result<Value, String> {+ let (id, p) = (id.to_string(), p.clone());+ app.ask_open(purpose, Bound::Document, move |app, path| run_ui(app, &id, &with_path(&p, key, path)).unwrap_or(Ok(Value::Null)))+ }++ /// File › Save As: asks where, saves there, then runs `after`.+ #[track_caller]+ fn save_as_dialog(app: &mut DesignApp, after: impl FnOnce(&mut DesignApp) -> Result<Value, String> + 'static) -> Result<Value, String> {+ let name = app.session.active().map(|d| format!("{}.designcraft", d.doc.title)).unwrap_or_default();+ app.ask_save(&name, Bound::Document, move |app, path| {+ app.run("file.saveAs", json!({"path": path}))?;+ after(app)+ })+ }++ /// Save the active document (a download in a browser; Save As for one never saved), then run+ /// `after` once it is written. A save dialog answers on a later frame; Cancel runs nothing.+ #[track_caller]+ pub(crate) fn save_then(app: &mut DesignApp, after: impl FnOnce(&mut DesignApp) -> Result<Value, String> + 'static) -> Result<Value, String> {+ if app.services.download.is_some() {+ download_document(app)?;+ return after(app);+ }+ if app.session.active().is_some_and(|d| d.path.is_some()) {+ app.run("file.save", json!({}))?;+ return after(app);+ }+ save_as_dialog(app, after)+ }++ /// Run a UI command; `None` if `id` isn't one.+ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {+ let was_find = app.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange");+ let result = run_ui_inner(app, id, p);+ if was_find && app.ui.dialog.as_ref().is_none_or(|d| d.id != "findChange") {+ app.session.reset_find_scope();+ }+ result+ }++ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {+ if is_window_control(id) && !window_control_available(app, id) {+ return Some(Err("custom window controls are not available in this host".into()));+ }+ if let Some(result) = crate::panel_docking::command(app, id, p) {+ return Some(result);+ }+ run_ui_part1(app, id, p)+ .or_else(|| run_ui_part2(app, id, p))+ .or_else(|| run_ui_part3(app, id, p))+ .or_else(|| run_ui_part4(app, id, p))+ .or_else(|| run_ui_part5(app, id, p))+ }++ /// Toggle `b`, answering its new value.+ fn flag(b: &mut bool) -> Result<Value, String> {+ *b = !*b;+ Ok(json!(*b))+ }++ /// One slice of the UI commands: `None` if `id` isn't one of them.+ fn run_ui_part1(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {+ Some(match id {+ "window.minimize" => {+ app.pending_window_commands.push(egui::ViewportCommand::Minimized(true));+ Ok(Value::Null)+ }+ "window.maximize" => {+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(!app.window_maximized);+ app.pending_window_commands.push(egui::ViewportCommand::Maximized(on));+ Ok(json!(on))+ }+ "window.close" => {+ app.pending_window_commands.push(egui::ViewportCommand::Close);+ Ok(Value::Null)+ }+ "window.drag" => {+ app.pending_window_commands.push(egui::ViewportCommand::StartDrag);+ Ok(Value::Null)+ }+ "window.resize" => {+ let edge = match p.get("edge").and_then(Value::as_str) {+ Some("north") => egui::ResizeDirection::North,+ Some("south") => egui::ResizeDirection::South,+ Some("east") => egui::ResizeDirection::East,+ Some("west") => egui::ResizeDirection::West,+ Some("northEast") => egui::ResizeDirection::NorthEast,+ Some("southEast") => egui::ResizeDirection::SouthEast,+ Some("northWest") => egui::ResizeDirection::NorthWest,+ Some("southWest") => egui::ResizeDirection::SouthWest,+ _ => return Some(Err("invalid window resize edge".into())),+ };+ app.pending_window_commands.push(egui::ViewportCommand::BeginResize(edge));+ Ok(Value::Null)+ }+ "app.newDocumentDialog" => {+ // In the default units (Preferences with no document open).+ let fields = crate::new_document::defaults_for(&app.session.default_new_document());+ app.ui.dialog = Some(crate::dialogs::Dialog::new("newDocument", fields));+ Ok(Value::Null)+ }+ "app.openDialog" => match p.get("path").and_then(Value::as_str) {+ Some(path) => app.open_picked("open", path.to_string()),+ None => app.pick_and_open("open"),+ },+ "app.openRecent" => {+ let index = p.get("index").cloned().unwrap_or(Value::Null);+ let name = index+ .as_u64()+ .and_then(|i| usize::try_from(i).ok())+ .and_then(|i| app.session.prefs.recent_files.get(i))+ .map(|path| recent_label(path))+ .unwrap_or_default();+ app.open_named_file("file.openRecent", json!({"index": index}), name)+ }+ "app.placeDialog" => match p.get("path").and_then(Value::as_str) {+ Some(path) => app.open_picked("place", path.to_string()),+ None => app.pick_and_open("place"),+ },+ "app.placeWithOptions" => {+ // Word/RTF Import Options: style mapping and conflicts before the text lands.+ let Some(path) = p.get("path").and_then(Value::as_str) else { return Some(rerun_with_path(app, "place", id, p, "path")) };+ let l = path.to_lowercase();+ if !(l.ends_with(".docx") || l.ends_with(".rtf")) {+ return Some(app.place_file(json!({"path": path})));+ }+ let info = match app.run("place.styles", json!({"path": path})) {+ Ok(v) => v,+ Err(e) => return Some(Err(e)),+ };+ app.ui.dialog = Some(crate::dialogs::Dialog::new(+ "importOptions",+ json!({"path": path, "styles": info["paragraph"], "charStyles": info["character"], "conflicts": info["conflicts"], "styleConflicts": "useExisting", "removeStyles": false, "map": {}}),+ ));+ Ok(Value::Null)+ }+ "app.save" | "app.saveDialog" if app.services.download.is_some() => download_document(app),+ "app.save" => {+ if app.session.active().is_some_and(|d| d.path.is_some()) {+ return Some(app.run("file.save", json!({})));+ }+ return run_ui(app, "app.saveDialog", p);+ }+ "app.saveDialog" => match p.get("path").and_then(Value::as_str) {+ Some(path) => app.run("file.saveAs", json!({"path": path})),+ None => save_as_dialog(app, |_| Ok(Value::Null)),+ },+ "app.quit" => {+ app.request_quit();+ Ok(Value::Null)+ }+ "app.saveCopyDialog" => match p.get("path").and_then(Value::as_str) {+ Some(path) => app.run("file.saveACopy", json!({"path": path})),+ None => {+ let name = app.session.active().map(|d| format!("{} copy.designcraft", d.doc.title)).unwrap_or_default();+ app.ask_save(&name, Bound::Document, |app, path| app.run("file.saveACopy", json!({"path": path})))+ }+ },+ "app.exportPng" => export_png(app, p),+ "app.exportIdml" => export_idml(app, p),+ // From the menu, EPUB Export Options first; with a path, straight to the file.+ "app.exportEpub" if p.get("path").is_some() => export_epub(app, p),+ "app.exportEpub" => {+ crate::dialogs::open_epub_export(app);+ Ok(Value::Null)+ }+ "app.exportInteractivePdf" => {+ let mut q = if p.is_object() { p.clone() } else { json!({}) };+ for (k, v) in [("pageLayout", json!("single")), ("view", json!("fitPage")), ("bookmarksPanel", json!(true)), ("media", json!(true))] {+ q.as_object_mut().map(|o| o.entry(k).or_insert(v));+ }+ export_pdf(app, &q)+ }+ "app.exportFixedEpub" => export_bytes(app, p, "epub", "file.exportFixedEpub"),+ "app.exportHtml" => export_bytes(app, p, "html", "file.exportHtml"),+ "app.exportPptx" => export_bytes(app, p, "pptx", "file.exportPptx"),+ "app.exportXml" => export_bytes(app, p, "xml", "file.exportXml"),+ "app.printBooklet" => export_bytes(app, p, "pdf", "file.printBooklet"),+ "app.menus" => {+ app.ui.dialog = Some(crate::dialogs::Dialog::new("menus", json!({"query": ""})));+ Ok(Value::Null)+ }+ "app.cellOptionsDialog" => crate::dialogs::open_cell_options(app),+ "window.hideMenuItem" => {+ let Some(item) = p.get("item").and_then(Value::as_str) else { return Some(Err("missing item".into())) };+ let hide = p.get("hidden").and_then(Value::as_bool).unwrap_or(true);+ app.ui.hidden_menu_items.retain(|x| x != item);+ if hide {+ app.ui.hidden_menu_items.push(item.to_string());+ }+ app.ui.show_full_menus = false;+ Ok(Value::Null)+ }+ "app.placeAndLink" => {+ let target = app.session.active().and_then(|d| {+ let id = *d.selection.items.first()?;+ let it = d.doc.item(id)?;+ let loc = d.doc.find(id)?;+ Some((it.text_frame()?.story, it.bounds(), loc.spread))+ });+ let Some((sid, b, sr)) = target else { return Some(Err("select a text frame".into())) };+ Ok(app+ .run("story.placeAndLink", json!({"story": sid.0, "rect": [b.x0 + 24.0, b.y0 + 24.0, b.x1 + 24.0, b.y1 + 24.0], "spread": sr}))+ .unwrap_or(Value::Null))+ }+ "app.fittingOptions" => {+ let g = app.session.active().and_then(|d| d.selection.items.first().and_then(|id| d.doc.item(*id)).and_then(|it| it.graphic().cloned()));+ let Some(g) = g else { return Some(Err("select a frame with a placed graphic".into())) };+ let fitting = serde_json::to_value(g.auto_fit).unwrap_or(json!("none"));+ let c = |v: f64| json!(designcraft_geom::format_measure(v, designcraft_geom::Unit::Points));+ app.ui.dialog = Some(crate::dialogs::Dialog::new(+ "fittingOptions",+ json!({"autoFit": g.auto_fit != designcraft_doc::Fitting::None, "fitting": fitting, "align": g.fit_align,+ "cropTop": c(g.crop[0]), "cropLeft": c(g.crop[1]), "cropBottom": c(g.crop[2]), "cropRight": c(g.crop[3])}),+ ));+ Ok(Value::Null)+ }+ "app.userDictionary" => {+ app.ui.dialog = Some(crate::dialogs::Dialog::new("userDictionary", json!({"word": ""})));+ Ok(Value::Null)+ }+ "app.qrCode" => {+ app.ui.dialog = Some(crate::dialogs::Dialog::new("qrCode", json!({})));+ Ok(Value::Null)+ }+ "app.exportText" => export_bytes(app, p, "rtf", "file.exportText"),+ "app.packageDialog" => {+ // Without a folder, the Package dialog: what the package carries, then the folder.+ let Some(dir) = p.get("dir").and_then(Value::as_str) else {+ return Some(crate::package_dialog::open(app).map(|()| Value::Null));+ };+ let r = app.run("file.package", json!({"dir": dir}));+ if let Ok(v) = &r {+ app.status(+ crate::i18n::tr(&app.ui.language, "Packaged {count} files into {dir}")+ .replace("{count}", &v["files"].as_array().map_or(0, |f| f.len()).to_string())+ .replace("{dir}", v["dir"].as_str().unwrap_or("")),+ );+ }+ r+ }+ "app.language" => {+ let Some(v) = p.get("lang").and_then(Value::as_str) else { return Some(app.run("app.preferences", json!({}))) };+ if !crate::i18n::LANGUAGES.iter().any(|(c, _)| *c == v) {+ return Some(Err(format!("unknown language `{v}`")));+ }+ app.ui.language = v.to_string();+ Ok(json!(v))+ }+ "app.flattener" => {+ let v = p.get("preset").and_then(Value::as_str).unwrap_or("");+ if !["", "high", "medium", "low"].contains(&v) {+ return Some(Err(format!("unknown preset `{v}`")));+ }+ app.ui.flattener = v.to_string();+ Ok(json!(v))+ }+ "app.graphicCell" => match p.get("path").and_then(Value::as_str) {+ Some(path) => app.run("table.placeGraphic", json!({"path": path})),+ None => rerun_with_path(app, "place", id, p, "path"),+ },+ "effects.dialog" => {+ crate::effects_dialog::open(app, p.get("page").and_then(Value::as_str).unwrap_or("transparency"));+ Ok(Value::Null)+ }+ "app.loadSwatches" => {+ if let Some(path) = p.get("path").and_then(Value::as_str) {+ return Some(app.run("swatch.load", json!({"path": path})));+ }+ let request = app.import_request("swatches");+ if let Some(open) = app.services.open_async.as_mut() {+ open(request);+ return Some(Ok(Value::Null));+ }+ app.ask_open("swatches", Bound::Document, |app, path| app.run("swatch.load", json!({"path": path})))+ }+ _ => return None,+ })+ }++ /// One slice of the UI commands: `None` if `id` isn't one of them.+ fn run_ui_part2(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {+ Some(match id {+ "app.loadParagraphStyles" => app.pick_styles("paragraph"),+ "app.loadCharacterStyles" => app.pick_styles("character"),+ "app.loadTextStyles" => app.pick_styles(""),+ "app.saveSwatches" => {+ let Some(path) = p.get("path").and_then(Value::as_str).map(str::to_string) else {+ let p = p.clone();+ return Some(app.ask_save("Swatches.ase", Bound::Document, move |app, path| {+ run_ui(app, "app.saveSwatches", &with_path(&p, "path", path)).unwrap_or(Ok(Value::Null))+ }));+ };+ let r = match app.run("swatch.save", json!({})) {+ Ok(r) => r,+ Err(e) => return Some(Err(e)),+ };+ let bytes = designcraft_engine::cmd::base64_decode(r["base64"].as_str().unwrap_or_default());+ match app.services.write.as_mut() {+ Some(w) => w(&path, &bytes).map(|_| json!({"path": path, "bytes": bytes.len()})),+ None => Err("no writer".into()),+ }+ }+ "app.storyEditor" => {+ let target = app.session.active().and_then(|st| {+ let story = p.get("story").and_then(Value::as_u64).map(designcraft_doc::StoryId).or_else(|| {+ st.selection+ .text+ .map(|t| t.story)+ .or_else(|| st.selection.items.iter().find_map(|i| st.doc.item(*i)?.text_frame().map(|t| t.story)))+ })?;+ Some(crate::story_editor::Target { doc: st.uid, story })+ });+ match target {+ Some(t) => {+ app.story_editor = if app.story_editor == Some(t) { None } else { Some(t) };+ Ok(Value::Null)+ }+ None => Err("select a text frame or place the cursor in text".into()),+ }+ }+ "app.findChange" => {+ app.session.reset_find_scope();+ app.ui.dialog = Some(crate::dialogs::Dialog::new("findChange", json!({})));+ Ok(Value::Null)+ }+ "app.convertTextToTableDialog" => {+ if !menu_enabled(app, id) {+ return Some(Err("select the text to convert to a table".into()));+ }+ app.ui.dialog = Some(crate::dialogs::Dialog::new("convertTextToTable", p.clone()));+ Ok(Value::Null)+ }+ "app.convertTableToTextDialog" => {+ if !menu_enabled(app, id) {+ return Some(Err("place the insertion point in a table to convert it to text".into()));+ }+ app.ui.dialog = Some(crate::dialogs::Dialog::new("convertTableToText", p.clone()));+ Ok(Value::Null)+ }+ "app.insertTableDialog" => {+ if app.session.active().is_none_or(|d| d.selection.text.is_none()) {+ return Some(Err("place the insertion point in a text frame to create a table".into()));+ }+ app.ui.dialog = Some(crate::dialogs::Dialog::new("insertTable", p.clone()));+ Ok(Value::Null)+ }+ "app.rubyDialog" => {+ let Some(st) = app.session.active() else { return Some(Err("no document open".into())) };+ let cur = st.selection.text.and_then(|t| {+ let story = st.doc.text_story(t.story, t.cell)?;+ let at = if t.range().is_empty() { t.range().start } else { t.range().start + 1 };+ story.char_format_at(at).over.ruby.clone()+ });+ let cur = cur.unwrap_or_default();+ // The ruby settings the panes show: the selection's resolved character attributes.+ let base = crate::panels::text_attrs(app).and_then(|a| a.get("chars").cloned()).unwrap_or(Value::Null);+ app.ui.dialog = Some(crate::dialogs::Dialog::new("ruby", json!({"text": cur, "base": base})));+ Ok(Value::Null)+ }+ "app.paragraphRulesDialog" => {+ let Some(a) = crate::panels::text_attrs(app) else { return Some(Err("select text or a text frame".into())) };+ let rule = if p.get("rule").and_then(Value::as_str) == Some("ruleBelow") { "ruleBelow" } else { "ruleAbove" };+ let current = json!({"ruleAbove": a["para"]["ruleAbove"], "ruleBelow": a["para"]["ruleBelow"]});+ app.ui.dialog = Some(crate::dialogs::Dialog::new("paragraphRules", json!({"rule": rule, "current": current})));+ Ok(Value::Null)+ }+ "app.paragraphBordersDialog"+ | "app.spanColumnsDialog"+ | "app.bulletsNumberingDialog"+ | "app.keepOptionsDialog"+ | "app.nestedStylesDialog"+ | "app.grepStylesDialog" => {+ let Some(a) = crate::panels::text_attrs(app) else { return Some(Err("select text or a text frame".into())) };+ let section = match id {+ "app.spanColumnsDialog" => "span",+ "app.bulletsNumberingDialog" => "bullets",+ "app.keepOptionsDialog" => "keep",+ "app.nestedStylesDialog" => "nested",+ "app.grepStylesDialog" => "grep",+ _ if p.get("tab").and_then(Value::as_str) == Some("shading") => "shading",+ _ => "border",+ };+ let fields = json!({+ "section": section,+ "current": a["para"],+ "family": a["chars"]["fontFamily"],+ "style": a["chars"]["fontStyle"],+ });+ app.ui.dialog = Some(crate::dialogs::Dialog::new("paragraphLocal", fields));+ Ok(Value::Null)+ }+ "app.hyphenationDialog" => {+ let Some(a) = app.session.execute("type.selectionAttrs", &json!({"mixed": true})).ok().filter(|a| !a.is_null()) else {+ return Some(Err("select text or a text frame".into()));+ };+ let mixed: Vec<&str> = a["paraMixed"].as_array().map(|m| m.iter().filter_map(Value::as_str).collect()).unwrap_or_default();+ let current: serde_json::Map<String, Value> = crate::dialogs::HYPH_ATTRS+ .iter()+ .map(|k| (k.to_string(), if mixed.contains(k) { Value::Null } else { a["para"][*k].clone() }))+ .collect();+ app.ui.dialog = Some(crate::dialogs::Dialog::new("hyphenation", json!({"current": current})));+ Ok(Value::Null)+ }+ "app.justificationDialog" => {+ let Some(a) = app.session.execute("type.selectionAttrs", &json!({"mixed": true})).ok().filter(|a| !a.is_null()) else {+ return Some(Err("select text or a text frame".into()));+ };+ let mixed: Vec<&str> = a["paraMixed"].as_array().map(|m| m.iter().filter_map(Value::as_str).collect()).unwrap_or_default();+ let current: serde_json::Map<String, Value> = crate::dialogs::JUSTIFY_ATTRS+ .iter()+ .map(|k| (k.to_string(), if mixed.contains(k) { Value::Null } else { a["para"][*k].clone() }))+ .collect();+ app.ui.dialog = Some(crate::dialogs::Dialog::new("justification", json!({"current": current})));+ Ok(Value::Null)+ }+ "app.footnoteOptionsDialog" => {+ let Some(st) = app.session.active() else { return Some(Err("no document open".into())) };+ let o = serde_json::to_value(&st.doc.footnote_options).unwrap_or_default();+ app.ui.dialog = Some(crate::dialogs::Dialog::new("footnoteOptions", o));+ Ok(Value::Null)+ }+ "app.findFontDialog" => {+ if app.session.active().is_none() {+ return Some(Err("no document open".into()));+ }+ app.ui.dialog = Some(crate::dialogs::Dialog::new("findFont", json!({})));+ Ok(Value::Null)+ }+ "app.insertXrefDialog" => {+ if app.session.active().is_none_or(|d| d.selection.text.is_none()) {+ return Some(Err("place the insertion point in text to insert a cross-reference".into()));+ }+ app.ui.dialog = Some(crate::dialogs::Dialog::new("insertXref", json!({})));+ Ok(Value::Null)+ }+ "app.deleteAllGuides" => {+ let Some(spread) = guide_spread(app) else { return Some(Err("no document open".into())) };+ return Some(app.run("guide.deleteAll", json!({"spread": spread})));+ }+ "app.deletePage" | "app.duplicateSpread" => {+ let Some(st) = app.session.active() else { return Some(Err("no document open".into())) };- let page = crate::canvas::current_page(app).unwrap_or(0);++ let Some(page) = crate::canvas::current_page(app) else { return Some(Err("select a document page".into())) };+ let r = if id == "app.deletePage" {+ crate::dialogs::delete_pages(app, vec![page])+ } else {+ let spread = st.doc.page_loc(page).map_or(0, |l| l.0);+ app.run("layout.pages.duplicateSpread", json!({"spread": spread}))+ };+ return Some(r);+ }+ "app.tabsPanel" => {+ toggle_tabs_panel(app);+ Ok(Value::Null)+ }+ "app.exportPdf" => {+ if p.is_null() || p.as_object().is_none_or(|m| m.is_empty()) {+ crate::dialogs::open_pdf_export(app);+ Ok(Value::Null)+ } else {+ export_pdf(app, p)+ }+ }+ "app.palette" => {+ app.ui.palette = Some(String::new());+ Ok(Value::Null)+ }+ "app.preferences" => {+ let mut f = app.session.execute("prefs.set", &json!({})).unwrap_or_default();+ if app.session.active().is_some() {+ let doc = app.session.execute("document.preferences", &json!({})).unwrap_or_default();+ f["horizontalUnits"] = doc["horizontalUnits"].clone();+ f["rulerOrigin"] = doc["rulerOrigin"].clone();+ f["overprintBlack"] = doc["overprintBlack"].clone();+ f["glyphFallback"] = doc["glyphFallback"].clone();+ for k in ["superscriptSize", "superscriptPosition", "subscriptSize", "subscriptPosition"] {+ f[format!("adv.{k}")] = json!(format!("{}", doc["advancedType"][k].as_f64().unwrap_or(0.0)));+ }+ f["verticalUnits"] = doc["verticalUnits"].clone();+ let words = app.session.execute("spelling.words", &json!({})).unwrap_or_default();+ f["userWords"] =+ json!(words.as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("\n")).unwrap_or_default());+ let inc = doc["keyboardIncrement"].as_f64().unwrap_or(1.0);+ f["keyboardIncrement"] = json!(designcraft_geom::format_measure(inc, designcraft_geom::Unit::Points));+ f["kerningIncrement"] = json!(format!("{}", doc["kerningIncrement"].as_f64().unwrap_or(20.0)));+ let units = app.session.active().map(|d| d.doc.settings.horizontal_units).unwrap_or_default();+ let m = |v: &Value| json!(designcraft_geom::format_measure(v.as_f64().unwrap_or(0.0), units));+ let (bg, g) = (&doc["baselineGrid"], &doc["grid"]);+ f["bg.start"] = m(&bg["start"]);+ f["bg.increment"] = m(&bg["increment"]);+ f["bg.relativeTo"] = bg["relativeTo"].clone();+ f["bg.viewThreshold"] = json!((bg["viewThreshold"].as_f64().unwrap_or(0.75) * 100.0).round());+ f["bg.color"] = bg["color"].clone();+ f["grid.horizontal"] = m(&g["horizontal"]);+ f["grid.vertical"] = m(&g["vertical"]);+ f["grid.subdivisions"] = g["subdivisions"].clone();+ f["grid.inBack"] = g["inBack"].clone();+ f["grid.color"] = g["color"].clone();+ for k in ["marginColor", "columnColor", "bleedColor", "slugColor"] {+ f[k] = doc[k].clone();+ }+ f["pasteboard.h"] = m(&doc["pasteboard"][0]);+ f["pasteboard.v"] = m(&doc["pasteboard"][1]);+ } else {+ // No document: Units & Increments are what new documents start with, as InDesign's.+ let du = app.session.prefs.default_units;+ f["defaults"] = json!(true);+ f["horizontalUnits"] = json!(du.horizontal_units);+ f["verticalUnits"] = json!(du.vertical_units);+ f["rulerOrigin"] = json!(du.ruler_origin);+ f["keyboardIncrement"] = json!(designcraft_geom::format_measure(du.keyboard_increment, designcraft_geom::Unit::Points));+ f["kerningIncrement"] = json!(format!("{}", du.kerning_increment));+ }+ f["snap.alignEdges"] = json!(app.ui.align_edges);+ f["snap.alignCenters"] = json!(app.ui.align_centers);+ f["snap.dimensions"] = json!(app.ui.smart_dimensions);+ f["snap.spacing"] = json!(app.ui.smart_spacing);+ f["snap.zone"] = json!(app.ui.snap_zone);+ f["displayQuality"] = json!(match app.ui.display_quality {+ designcraft_render::DisplayQuality::Fast => "fast",+ designcraft_render::DisplayQuality::Typical => "typical",+ designcraft_render::DisplayQuality::High => "high",+ });+ f["uiScale"] = json!((app.ui.ui_scale * 100.0).round());+ f["autoCollapseIconicPanels"] = json!(app.ui.dock_auto_collapse);+ // Interface: Cancel goes back to the theme Preferences opened with.+ f["brightness"] = json!(app.ui.brightness.id());+ f["openedBrightness"] = json!(app.ui.brightness.id());+ f["toolsColumns"] = json!(if app.ui.tools_double_column { "double" } else { "single" });+ f["richBlack"] = json!(app.ui.rich_black);+ f["dynamicSpelling"] = json!(app.ui.dynamic_spelling);+ f["storyEditorSize"] = json!(app.ui.story_editor_size);+ let list = app.session.prefs.autocorrect_list.iter().map(|(a, b)| format!("{a} → {b}")).collect::<Vec<_>>().join("\n");+ f["autocorrectText"] = json!(list);+ // The effective setting; it becomes an explicit preference only when the user changes it,+ // so an untouched one keeps following the interface language.+ let cjk = crate::cjk_features(app);+ f["cjkFeatures"] = json!(cjk);+ f["cjkFeatures.initial"] = json!(cjk);+ f["section"] = json!("general");+ // The language previews as it changes; Cancel goes back to this one.+ f["openedLanguage"] = json!(app.ui.language);+ app.ui.dialog = Some(crate::dialogs::Dialog::new("preferences", f));+ Ok(Value::Null)+ }+ _ => return None,+ })+ }++ /// One slice of the UI commands: `None` if `id` isn't one of them.+ fn run_ui_part3(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {+ let rect = app.canvas_rect;+ Some(match id {+ "view.zoomIn" | "view.zoomOut" => {+ if let Some(r) = rect {+ crate::canvas::zoom_at(app, r.center(), if id == "view.zoomIn" { 1.5 } else { 1.0 / 1.5 });+ }+ Ok(Value::Null)+ }+ "view.fitSelection" => {+ if let Some(r) = rect {+ crate::canvas::fit(app, r, "selection");+ }+ Ok(Value::Null)+ }+ "view.fitPage" | "view.fitSpread" | "view.entirePasteboard" => {+ if let Some(r) = rect {+ crate::canvas::fit(+ app,+ r,+ if id == "view.fitPage" {+ "page"+ } else if id == "view.fitSpread" {+ "spread"+ } else {+ "all"+ },+ );+ }+ Ok(Value::Null)+ }+ "view.actualSize" => {+ crate::canvas::set_zoom(app, 1.0);+ Ok(Value::Null)+ }+ "view.zoom" => {+ crate::canvas::set_zoom(app, p.get("zoom").and_then(Value::as_f64).unwrap_or(1.0));+ Ok(Value::Null)+ }+ "view.screenMode" => {+ let mode = match p.get("mode").and_then(Value::as_str).unwrap_or("normal") {+ "preview" => ScreenMode::Preview,+ "bleed" => ScreenMode::Bleed,+ "slug" => ScreenMode::Slug,+ "presentation" => ScreenMode::Presentation,+ _ => ScreenMode::Normal,+ };+ set_screen_mode(app, mode);+ Ok(Value::Null)+ }+ "view.togglePreview" => {+ let mode = if app.ui.screen_mode == ScreenMode::Normal { ScreenMode::Preview } else { ScreenMode::Normal };+ set_screen_mode(app, mode);+ Ok(Value::Null)+ }+ "view.togglePresentation" => {+ let mode = match (app.ui.screen_mode, app.ui.presentation_return) {+ // A settings file can hold Presentation as the return mode; leaving must still leave.+ (ScreenMode::Presentation, ScreenMode::Presentation) => ScreenMode::Normal,+ (ScreenMode::Presentation, back) => back,+ _ => ScreenMode::Presentation,+ };+ set_screen_mode(app, mode);+ Ok(Value::Null)+ }+ "color.defaultFillStroke" => crate::toolbar::default_fill_stroke(app),+ "color.swapFillStroke" => crate::toolbar::swap_fill_stroke(app),+ "color.toggleFillStroke" => crate::toolbar::toggle_fill_stroke(app),+ "color.applyColor" => crate::toolbar::apply_color(app),+ "color.applyGradient" => crate::toolbar::apply_gradient(app),+ "color.applyNone" => crate::toolbar::apply_none(app),+ "view.frameEdges" => flag(&mut app.ui.frame_edges),+ "view.overprintPreview" => {+ app.canvas.shown = None;+ flag(&mut app.ui.overprint_preview)+ }+ "view.fastDisplay" | "view.typicalDisplay" | "view.highQualityDisplay" => {+ use designcraft_render::DisplayQuality as Q;+ app.ui.display_quality = match id {+ "view.fastDisplay" => Q::Fast,+ "view.typicalDisplay" => Q::Typical,+ _ => Q::High,+ };+ // Redraw everything at the new quality.+ app.canvas.shown = None;+ Ok(Value::Null)+ }+ "view.rulers" => flag(&mut app.ui.rulers),+ "view.guides" => flag(&mut app.ui.guides),+ "view.lockGuides" => {+ app.ui.guides_locked = p.get("on").and_then(Value::as_bool).unwrap_or(!app.ui.guides_locked);+ Ok(json!(app.ui.guides_locked))+ }+ "view.snapToGuides" => flag(&mut app.ui.snap_to_guides),+ "view.snapToDocumentGrid" => flag(&mut app.ui.snap_to_document_grid),+ "view.smartGuides" => flag(&mut app.ui.smart_guides),+ "view.baselineGrid" => flag(&mut app.ui.baseline_grid),+ "view.documentGrid" => {+ // The grid is drawn into the canvas texture.+ app.canvas.shown = None;+ flag(&mut app.ui.document_grid)+ }+ "view.textThreads" => flag(&mut app.ui.text_threads),+ "view.hiddenCharacters" => flag(&mut app.ui.hidden_characters),+ "view.taggedFrames" => flag(&mut app.ui.tagged_frames),+ "view.storyEditorDepthRuler" => flag(&mut app.ui.story_editor_depth_ruler),+ "window.hidePanels" | "window.hidePanelsExceptTools" => {+ let mode = if id == "window.hidePanels" { 1 } else { 2 };+ app.ui.hidden_panels = if app.ui.hidden_panels == mode { 0 } else { mode };+ Ok(json!(app.ui.hidden_panels))+ }+ "window.nextDocument" | "window.previousDocument" => {+ let n = app.session.documents().len();+ if n > 1 {+ let cur = app.session.active_index().unwrap_or(0);+ let next = if id == "window.nextDocument" { (cur + 1) % n } else { (cur + n - 1) % n };+ app.session.set_active(next);+ }+ Ok(json!(app.session.active_index()))+ }+ "app.layerOptionsDialog" => crate::dialogs::open_layer_options(app, p.get("id").and_then(Value::as_u64)).map(|()| Value::Null),+ "app.swatchOptionsDialog" => {+ crate::dialogs::open_swatch_options(app, p.get("name").and_then(Value::as_str).unwrap_or("")).map(|()| Value::Null)+ }+ "app.colorGroupOptionsDialog" => {+ crate::dialogs::open_color_group_options(app, p.get("name").and_then(Value::as_str).unwrap_or("")).map(|()| Value::Null)+ }+ "app.layerOptions" => {+ let layers = match app.session.execute("object.pdfLayers", &json!({})) {+ Ok(v) => v,+ Err(e) => return Some(Err(e.to_string())),+ };+ app.ui.dialog = Some(crate::dialogs::Dialog::new(+ "layerOptions",+ json!({"useDefaults": !layers.as_array().and_then(|a| a.first()).and_then(|l| l["overridden"].as_bool()).unwrap_or(false), "layers": layers}),+ ));+ Ok(Value::Null)+ }+ "view.rotateSpread" => {+ // Turns the spread in the middle of the view (InDesign's Rotate Spread).+ let angle = p.get("angle").and_then(Value::as_i64).unwrap_or(90);+ let Some(st) = app.session.active() else { return Some(Err("no document".into())) };+ let layout = designcraft_tools::CanvasLayout::new(&st.doc, st.editing_parents);+ let Some(slot) = crate::canvas::current_slot(app, &layout).and_then(|i| layout.slots.get(i).copied()) else {+ return Some(Err("no spread".into()));+ };+ let designcraft_doc::SpreadRef::Doc(si) = slot.spread else { return Some(Err("parent spreads don't turn".into())) };+ let r = app.run("layout.rotateSpreadView", json!({"spread": si, "angle": angle}));+ if let Some(rect) = app.canvas_rect {+ crate::canvas::fit(app, rect, "spread");+ }+ app.canvas.shown = None;+ r.map(|v| v["rotation"].clone())+ }+ _ => return None,+ })+ }++ /// One slice of the UI commands: `None` if `id` isn't one of them.+ fn run_ui_part4(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {+ Some(match id {+ "view.proofColors" => {+ app.ui.proof_colors = p.get("on").and_then(Value::as_bool).unwrap_or(!app.ui.proof_colors);+ app.canvas.shown = None;+ Ok(json!(app.ui.proof_colors))+ }+ "view.proofSetup" => {+ if let Some(t) = p.get("target").and_then(Value::as_str) {+ let Some(t) = designcraft_color::cms::ProofTarget::parse(t) else { return Some(Err(format!("unknown proof target `{t}`"))) };+ app.ui.proof_setup.target = t;+ app.ui.proof_colors = true;+ }+ if let Some(i) = p.get("intent").and_then(Value::as_str) {+ let Some(i) = designcraft_color::cms::Intent::parse(i) else { return Some(Err(format!("unknown intent `{i}`"))) };+ app.ui.proof_setup.intent = i;+ }+ match p.get("simulatePaper") {+ Some(Value::Bool(b)) => app.ui.proof_setup.simulate_paper = *b,+ Some(Value::String(s)) if s == "toggle" => app.ui.proof_setup.simulate_paper = !app.ui.proof_setup.simulate_paper,+ _ => {}+ }+ app.canvas.shown = None;+ Ok(json!({"target": app.ui.proof_setup.target.id(), "simulatePaper": app.ui.proof_setup.simulate_paper, "on": app.ui.proof_colors}))+ }+ "app.colorSettings" => {+ let f = app.session.execute("color.settings", &json!({})).unwrap_or_default();+ app.ui.dialog = Some(crate::dialogs::Dialog::new("colorSettings", f));+ Ok(Value::Null)+ }+ "view.separations" => separations_view(app, p),+ "view.firstPage" | "view.previousPage" | "view.nextPage" | "view.lastPage" => {+ let n = app.session.active().map_or(0, |d| d.doc.page_count());+ if n > 0 {+ let cur = crate::canvas::current_page(app).unwrap_or(0);+ let to = match id {+ "view.firstPage" => 0,+ "view.previousPage" => cur.saturating_sub(1),+ "view.nextPage" => cur.saturating_add(1).min(n - 1),+ _ => n - 1,+ };+ crate::canvas::go_to_page(app, to);+ }+ Ok(Value::Null)+ }+ "view.goBack" | "view.goForward" => {+ crate::canvas::go_through_history(app, if id == "view.goBack" { -1 } else { 1 });+ Ok(Value::Null)+ }+ "view.nextSpread" | "view.previousSpread" => {+ crate::canvas::step_spread(app, if id == "view.nextSpread" { 1 } else { -1 });+ Ok(Value::Null)+ }+ "view.goToPage" => {+ match p.get("page") {+ Some(Value::Number(n)) => crate::canvas::go_to_page(app, (n.as_u64().unwrap_or(1) as usize).saturating_sub(1)),+ Some(Value::String(s)) => match app.session.resolve_page(s) {+ Some(abs) => crate::canvas::go_to_page(app, abs),+ None => return Some(Err(format!("no page \"{s}\""))),+ },+ _ => app.ui.dialog = Some(crate::dialogs::Dialog::new("goToPage", json!({}))),+ }+ Ok(Value::Null)+ }+ "app.characterPanel" | "app.paragraphPanel" | "app.glyphsPanel" | "app.characterStylesPanel" | "app.paragraphStylesPanel" => {+ let panel = match id {+ "app.characterPanel" => "character",+ "app.paragraphPanel" => "paragraph",+ "app.glyphsPanel" => "glyphs",+ "app.characterStylesPanel" => "characterStyles",+ _ => "paragraphStyles",+ };+ run_ui(app, "window.panel", &json!({"panel": panel})).unwrap_or(Ok(Value::Null))+ }+ "app.insertCurrentPageNumber" => app.run("text.insert", json!({"text": "\u{e000}", "raw": true})),+ // `panel_docking::command` takes the dock panels (and the Window › Styles group) first.+ "window.panel" => {+ let panel = p.get("panel").and_then(Value::as_str).unwrap_or("properties");+ if panel != "tabs" {+ return crate::panel_docking::command(app, "window.panel.activate", &json!({"panel": panel}));+ }+ toggle_tabs_panel(app);+ Ok(Value::Null)+ }+ "fit.fillFrameProportionally" | "fit.contentProportionally" | "fit.frameToContent" | "fit.contentToFrame" | "fit.centerContent" => {+ let mode = match id {+ "fit.fillFrameProportionally" => "fillProportionally",+ "fit.contentProportionally" => "fitProportionally",+ "fit.frameToContent" => "fitFrameToContent",+ "fit.contentToFrame" => "fitContentToFrame",+ _ => "centerContent",+ };+ app.run("object.fit", json!({"mode": mode}))+ }+ "app.keyboardShortcuts" => {+ let select = p.get("command").and_then(Value::as_str).map(|id| crate::keys::command_ref(id, p.get("params").unwrap_or(&Value::Null)));+ crate::shortcuts_dialog::open(app, select.as_ref());+ Ok(Value::Null)+ }+ "window.shortcutSets" => {+ let builtins = &crate::shortcuts_dialog::BUILTINS;+ if let Some(name) = p.get("select").and_then(Value::as_str) {+ if app.shortcut_dialog.is_some() {+ return Some(Err("close the Keyboard Shortcuts dialog first".into()));+ }+ if let Err(e) = app.ui.shortcut_sets.select(name, builtins) {+ return Some(Err(format!("{name}: {e}")));+ }+ crate::shortcuts_dialog::load_active_set(app);+ }+ let sets = &app.ui.shortcut_sets;+ Ok(+ json!({"active": sets.active_name(builtins), "sets": sets.names(builtins), "builtIn": builtins.iter().map(|(n, _)| *n).collect::<Vec<_>>()}),+ )+ }+ // The open Keyboard Shortcuts dialog edits the keys itself, and its Cancel puts back the+ // ones it started with, which would undo a change made here.+ "window.setShortcut" | "window.resetShortcuts" | "window.importShortcuts" if app.shortcut_dialog.is_some() => {+ Err("close the Keyboard Shortcuts dialog first".into())+ }+ "window.setShortcut" => {+ let Some(id) = p.get("id").and_then(Value::as_str) else { return Some(Err("missing id".into())) };+ let mut cmd = crate::keys::command_ref(id, p.get("params").unwrap_or(&Value::Null));+ // A bare tool id ("pen") names its tool.+ if app.keymap.bindable(&cmd).is_none() && designcraft_tools::tool_info(id).is_some() {+ cmd = crate::keys::tool(id);+ }+ let shortcut = match p.get("shortcut") {+ None | Some(Value::Null) => None,+ Some(Value::String(sc)) => Some(sc.as_str()),+ Some(_) => return Some(Err("shortcut: a string or null".into())),+ };+ let steal = p.get("steal").and_then(Value::as_bool).unwrap_or(false);+ let policy = if steal { craft_keymap::Policy::Steal } else { craft_keymap::Policy::Keep };+ let taken = match crate::keys::set(app, &cmd, shortcut, policy) {+ Ok(t) => t,+ Err(e) => return Some(Err(e)),+ };+ let mut conflicts: Vec<String> = taken.iter().filter(|c| !crate::keys::twins(&cmd, c)).map(|c| c.key()).collect();+ for key in crate::keys::conflicts(&app.keymap, &cmd) {+ if !conflicts.contains(&key) {+ conflicts.push(key);+ }+ }+ Ok(json!({"shortcut": crate::keys::shortcut(&app.keymap, &cmd), "conflicts": conflicts}))+ }+ "window.resetShortcuts" => {+ app.keymap.reset_all();+ crate::keys::store(app);+ Ok(Value::Null)+ }+ "window.importShortcuts" => {+ let text = match (p.get("text").and_then(Value::as_str), p.get("path").and_then(Value::as_str)) {+ (Some(text), _) => text.to_string(),+ (None, Some(path)) => match crate::shortcut_import::read_file(path) {+ Ok(text) => text,+ Err(e) => return Some(Err(e)),+ },+ (None, None) => return Some(Err("give the set's path or text".into())),+ };+ crate::shortcut_import::import(app, &text)+ }+ "view.snapPreferences" => {+ let b = |k: &str| p.get(k).and_then(Value::as_bool);+ let ui = &mut app.ui;+ ui.align_edges = b("alignEdges").unwrap_or(ui.align_edges);+ ui.align_centers = b("alignCenters").unwrap_or(ui.align_centers);+ ui.smart_dimensions = b("smartDimensions").unwrap_or(ui.smart_dimensions);+ ui.smart_spacing = b("smartSpacing").unwrap_or(ui.smart_spacing);+ if let Some(z) = p.get("zone").and_then(Value::as_f64).filter(|z| z.is_finite()) {+ ui.snap_zone = z.max(0.0);+ }+ Ok(json!({+ "alignEdges": ui.align_edges,+ "alignCenters": ui.align_centers,+ "smartDimensions": ui.smart_dimensions,+ "smartSpacing": ui.smart_spacing,+ "zone": ui.snap_zone,+ }))+ }+ _ => return None,+ })+ }++ /// One slice of the UI commands: `None` if `id` isn't one of them.+ fn run_ui_part5(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {+ Some(match id {+ "app.formattingAffectsText" => {+ app.ui.formatting_affects_text = p.get("on").and_then(Value::as_bool).unwrap_or(!app.ui.formatting_affects_text);+ Ok(json!({"on": app.ui.formatting_affects_text}))+ }+ "window.richBlack" => {+ app.ui.rich_black = p.get("on").and_then(Value::as_bool).unwrap_or(!app.ui.rich_black);+ app.canvas.shown = None;+ Ok(json!({"on": app.ui.rich_black}))+ }+ "window.uiScale" => {+ let v = p.get("scale").and_then(Value::as_f64).unwrap_or(1.0) as f32;+ app.ui.ui_scale = v.clamp(0.5, 3.0);+ Ok(json!({"scale": app.ui.ui_scale}))+ }+ "window.controlBar" => flag(&mut app.ui.control_bar),+ "view.flattenerPreview" => flag(&mut app.ui.flattener_preview),+ "view.tagMarkers" => {+ app.canvas.shown = None;+ flag(&mut app.ui.tag_markers)+ }+ "edit.dynamicSpelling" => flag(&mut app.ui.dynamic_spelling),+ "window.split" => {+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(!app.split);+ app.split = on;+ if on {+ if app.second_window {+ app.end_second_ime_viewport();+ }+ app.second_window = false;+ } else {+ app.switch_pane(0);+ app.focus_pane = 0;+ }+ Ok(json!(on))+ }+ "window.newWindow" => {+ // The second view moves into its own window (on the web: a floating window).+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(true);+ if app.second_window && !on {+ app.end_second_ime_viewport();+ }+ app.second_window = on;+ app.split = false;+ if !app.second_window {+ app.switch_pane(0);+ app.focus_pane = 0;+ }+ Ok(json!(app.second_window))+ }+ "window.taskBar" => flag(&mut app.ui.task_bar),+ "window.taskBarPin" => {+ let at = match p.get("at") {+ None | Some(Value::Null) => None,+ Some(v) => match v.as_array().map(|a| a.iter().map(Value::as_f64).collect::<Vec<_>>()).as_deref() {+ Some([Some(x), Some(y)]) if x.is_finite() && y.is_finite() => Some([x.clamp(-1e6, 1e6) as f32, y.clamp(-1e6, 1e6) as f32]),+ _ => return Some(Err("window.taskBarPin: `at` is [x, y] in points".into())),+ },+ };+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(at.is_some() || app.ui.task_bar_pin.is_none());+ app.ui.task_bar_pin = match (on, at.or(app.ui.task_bar_pin).or(app.ui.task_bar_at)) {+ (false, _) => None,+ (true, Some(at)) => Some(at),+ (true, None) => return Some(Err("window.taskBarPin: the Contextual Task Bar isn't showing; give `at`".into())),+ };+ Ok(json!(app.ui.task_bar_pin))+ }+ "window.taskBarReset" => {+ app.ui.task_bar_pin = None;+ Ok(Value::Null)+ }+ "help.about" => {+ if let Some(tab) = p.get("tab").and_then(Value::as_str) {+ let Some(i) = crate::about::ABOUT_TABS.iter().position(|t| t.eq_ignore_ascii_case(tab)) else {+ return Some(Err(format!("help.about: unknown tab `{tab}` (about, contributors, models)")));+ };+ app.ui.about_tab = u8::try_from(i).unwrap_or(0);+ }+ app.ui.about = p.get("open").and_then(Value::as_bool).unwrap_or(true);+ Ok(json!(app.ui.about))+ }+ "help.checkForUpdates" => crate::updates_ui::check(app),+ "help.app" => match p.get("app").and_then(Value::as_str) {+ Some(slug) if !slug.is_empty() && slug.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') => {+ let url = format!("{}/apps/{slug}", designcraft_engine::links::WEBSITE);+ app.ui.pending_urls.push(url.clone());+ Ok(json!({"url": url}))+ }+ _ => Err("help.app: give `app` (e.g. \"photocraft\")".into()),+ },+ h if h.starts_with("help.") && designcraft_engine::links::get(&h[5..]).is_some() => {+ let url = designcraft_engine::links::get(&h[5..]).unwrap_or_default().to_string();+ app.ui.pending_urls.push(url.clone());+ Ok(json!({"url": url}))+ }+ "window.toolsDoubleColumn" => {+ app.ui.tools_double_column = p.get("on").and_then(Value::as_bool).unwrap_or(!app.ui.tools_double_column);+ Ok(json!(app.ui.tools_double_column))+ }+ "window.newWorkspace" => {+ let Some(name) = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) else {+ app.ui.dialog =+ Some(crate::dialogs::Dialog::new("newWorkspace", json!({"name": "", "panelLocations": true, "menuCustomization": true})));+ return Some(Ok(Value::Null));+ };+ let u = &app.ui;+ let w = crate::SavedWorkspace {+ name: name.to_string(),+ control_bar: u.control_bar,+ task_bar: u.task_bar,+ task_bar_pin: u.task_bar_pin,+ tools_double_column: u.tools_double_column,+ dock_tab: u.dock_tab.clone(),+ dock_expanded: u.dock_expanded,+ open_panel: u.open_panel.clone(),+ floating: u.floating.clone(),+ docking: u.docking.clone(),+ docking_hidden: u.docking_hidden.clone(),+ icon_groups: u.icon_groups.clone(),+ keep_panels: !p.get("panelLocations").and_then(Value::as_bool).unwrap_or(true),+ hidden_menu_items: p.get("menuCustomization").and_then(Value::as_bool).unwrap_or(true).then(|| u.hidden_menu_items.clone()),+ };+ app.ui.custom_workspaces.retain(|x| x.name != name);+ app.ui.custom_workspaces.push(w);+ app.ui.workspace = name.to_string();+ Ok(Value::Null)+ }+ "window.deleteWorkspace" => {+ let name = p.get("name").and_then(Value::as_str).unwrap_or("");+ let n = app.ui.custom_workspaces.len();+ app.ui.custom_workspaces.retain(|x| x.name != name);+ if app.ui.custom_workspaces.len() == n {+ return Some(Err(format!("no saved workspace `{name}`")));+ }+ if app.ui.workspace == name {+ app.ui.workspace = "Essentials".into();+ }+ Ok(Value::Null)+ }+ "window.resetWorkspace" => {+ let name = app.ui.workspace.clone();+ return run_ui(app, "window.workspace", &json!({"name": name}));+ }+ "window.workspace" => {+ app.ui.docking_generation = app.ui.docking_generation.wrapping_add(1);+ crate::panel_docking::forget_panels(app);+ let name = p.get("name").and_then(Value::as_str).unwrap_or("Essentials");+ if let Some(w) = app.ui.custom_workspaces.iter().find(|w| w.name == name).cloned() {+ if let Some(hidden) = w.hidden_menu_items {+ app.ui.hidden_menu_items = hidden;+ }+ if w.keep_panels {+ app.ui.workspace = w.name;+ return Some(Ok(Value::Null));+ }+ app.ui.control_bar = w.control_bar;+ app.ui.task_bar = w.task_bar;+ app.ui.task_bar_pin = w.task_bar_pin;+ app.ui.tools_double_column = w.tools_double_column;+ app.ui.dock_tab = w.dock_tab;+ app.ui.dock_expanded = w.dock_expanded;+ app.ui.open_panel = w.open_panel;+ app.ui.floating = w.floating;+ app.ui.docking = w.docking;+ app.ui.docking_hidden = w.docking_hidden;+ app.ui.icon_groups = w.icon_groups;+ app.ui.workspace = w.name;+ return Some(Ok(Value::Null));+ }+ // Workspaces choose which bars and panels are visible.+ if app.ui.docking.is_some() {+ app.ui.floating.clear();+ }+ app.ui.docking = None;+ app.ui.docking_hidden.clear();+ app.ui.control_bar = matches!(name, "Advanced" | "Typography" | "Printing and Proofing" | "Book" | "Essentials Classic");+ // Essentials Classic: the Control panel and an iconic column of grouped panels, no+ // Properties stack.+ let groups = match name {+ "Essentials Classic" => Some(CLASSIC_GROUPS),+ "Typography" => Some(TYPOGRAPHY_GROUPS),+ _ => None,+ };+ app.ui.icon_groups = groups.map(|groups| groups.iter().map(|g| g.iter().map(ToString::to_string).collect()).collect());+ app.ui.dock_expanded = groups.is_none();+ let dock_tab = match name {+ "Interactive for PDF" | "Digital Publishing" => Some("pages"),+ _ => None,+ };+ if let Some(tab) = dock_tab {+ app.ui.dock_tab = tab.into();+ app.ui.dock_expanded = true;+ }+ app.ui.open_panel = workspace_open_panel(name).map(str::to_string);+ app.ui.workspace = name.to_string();+ Ok(Value::Null)+ }+ "window.brightness" => {+ let b = p.get("brightness").and_then(Value::as_str).and_then(crate::theme::Brightness::parse).unwrap_or(crate::theme::Brightness::Dark);+ app.ui.brightness = b;+ app.restyle = true;+ Ok(Value::Null)+ }+ _ => return None,+ })+ }++ /// Save by handing the serialized document to the host as a download (web).+ /// Switch screen modes; entering Presentation remembers the mode to return to.+ fn set_screen_mode(app: &mut DesignApp, mode: ScreenMode) {+ let presenting = app.ui.screen_mode == ScreenMode::Presentation;+ if mode == ScreenMode::Presentation && !presenting {+ app.ui.presentation_return = app.ui.screen_mode;+ // Presentation fits the spread to the screen; leaving it puts the user's view back.+ app.ui.presentation_view = app.view_key().zip(app.view().copied());+ app.ui.presentation_page = crate::canvas::page_in_view(app);+ app.ui.presentation_history = app.page_history().cloned();+ }+ if mode != ScreenMode::Presentation+ && presenting+ && let Some((k, v)) = app.ui.presentation_view.take()+ && app.views.contains_key(&k)+ {+ // Go Back sees the presentation as one jump to the last spread presented, and putting the+ // view back as a jump from there: the spreads in between would otherwise have replaced the+ // place the view was at with the presentation's.+ let shown = app.ui.presentation_page.take().zip(crate::canvas::page_in_view(app)).filter(|_| app.view_key() == Some(k));+ let h = app.page_history.entry(k).or_default();+ *h = app.ui.presentation_history.take().unwrap_or_default();+ if let Some(((from, at), (to, offset))) = shown {+ h.leave(from, at);+ h.visit(to, offset);+ h.visit(from, at);+ }+ if let Some(view) = app.views.get_mut(&k) {+ *view = v;+ }+ }+ app.ui.screen_mode = mode;+ }diff --cc crates/ui-egui/src/panels/properties/document.rsindex 000000000,d68d4531c..f8ea15451mode 000000,100644..100644--- a/crates/ui-egui/src/panels/properties/document.rs+++ b/crates/ui-egui/src/panels/properties/document.rs@@@ -1,0 -1,374 +1,394 @@@+ use super::{+ DesignApp, FIELD_H, NumField, Rect, Sense, Tokens, Ui, Value, block, button_pair, divider, dropdown, full_width, icon_toggle, icons, json,+ number, outline_button, place, pos2, rule, section, section_row, set_temp_bool, sub, temp_bool, units, vec2, widgets,+ };++ // ---------------------------------------------------------------- No Selection++ /// Page-size presets for the Document dropdown (portrait, points).+ pub(crate) const PAGE_PRESETS: &[(&str, f64, f64)] = &[+ ("Letter", 612.0, 792.0),+ ("Legal", 612.0, 1008.0),+ ("Tabloid", 792.0, 1224.0),+ ("Letter - Half", 396.0, 612.0),+ ("Legal - Half", 504.0, 612.0),+ ("A0", 841.0 * units::PT_PER_MM, 1189.0 * units::PT_PER_MM),+ ("A1", 594.0 * units::PT_PER_MM, 841.0 * units::PT_PER_MM),+ ("A2", 420.0 * units::PT_PER_MM, 594.0 * units::PT_PER_MM),+ ("A3", 841.89, 1190.55),+ ("A4", 595.276, 841.89),+ ("A5", 419.528, 595.276),+ ("A6", 297.638, 419.528),+ ("B5", 498.898, 708.661),+ ("US Business Card", 144.0, 252.0),+ ];++ pub(crate) fn preset_name(w: f64, h: f64) -> &'static str {+ let (a, b) = (w.min(h), w.max(h));+ PAGE_PRESETS.iter().find(|p| (p.1 - a).abs() < 0.6 && (p.2 - b).abs() < 0.6).map(|p| p.0).unwrap_or("Custom")+ }++ /// The preset dropdown and orientation toggles for one page; the new (width, height) when one changed.+ fn page_preset_row(ui: &mut Ui, lang: &str, w: f64, h: f64) -> Option<(f64, f64)> {+ let landscape = w > h;+ let b = block(ui, FIELD_H);+ let mut size = None;+ place(ui, sub(b, 0.0, 0.0, 93.0, FIELD_H), |ui| {+ let resp = dropdown(ui, crate::i18n::tr(lang, preset_name(w, h)), 93.0);+ egui::Popup::menu(&resp).show(|ui| {+ ui.set_min_width(140.0);+ for p in PAGE_PRESETS {+ if ui.selectable_label(preset_name(w, h) == p.0, crate::i18n::tr(lang, p.0)).clicked() {+ size = Some(if landscape { (p.2, p.1) } else { (p.1, p.2) });+ ui.close();+ }+ }+ });+ });+ place(ui, sub(b, 126.0, 0.0, 52.0, FIELD_H), |ui| {+ ui.spacing_mut().item_spacing.x = 4.0;+ if icon_toggle(ui, "orient-portrait", !landscape, crate::i18n::tr(lang, "Portrait")).clicked() && landscape {+ size = Some((h, w));+ }+ if icon_toggle(ui, "orient-landscape", landscape, crate::i18n::tr(lang, "Landscape")).clicked() && !landscape {+ size = Some((h, w));+ }+ });+ size+ }++ /// Properties with the Page tool (Properties › Edit Page), as InDesign's: a "Page" band with Back,+ /// Page Size for this page alone (which page, preset, orientation, W/H), Margins and Columns and-/// Quick Actions. Back returns to the Selection tool and the document's properties.-pub(super) fn page_sections(app: &mut DesignApp, ui: &mut Ui, page: usize) {++/// Quick Actions. Back leaves parent editing and returns to the Selection tool and document properties.++pub(super) fn page_sections(app: &mut DesignApp, ui: &mut Ui, spread: designcraft_doc::SpreadRef, page: usize) {+ let u = units(app);+ let lang = app.ui.language.clone();+ let Some(st) = app.session.active() else { return };+ let d = st.doc.clone();- let Some((si, pi)) = d.page_loc(page) else { return };- let Some(pg) = d.spreads.get(si).and_then(|s| s.pages.get(pi)).cloned() else { return };- let n = page + 1;++ let Some(sp) = d.spread(spread) else { return };++ let Some(pg) = sp.pages.get(page).cloned() else { return };+ let t = Tokens::get(ui.ctx());+ // The band: "Page", and Back at its end.+ let band = block(ui, 33.0);+ crate::rtl::paint(+ ui.painter(),+ pos2(band.min.x, band.center().y + 1.0),+ egui::Align2::LEFT_CENTER,+ crate::i18n::tr(&lang, "Page"),+ crate::theme::semibold(11.5),+ t.text_strong,+ );+ let back = place(ui, Rect::from_min_size(pos2(band.max.x - 58.0, band.center().y - 10.0), vec2(54.0, 20.0)), |ui| {+ outline_button(ui, crate::i18n::tr(&lang, "Back"), 54.0).clicked()+ });+ rule(ui);+ if back {++ if matches!(spread, designcraft_doc::SpreadRef::Parent(_)) {++ let _ = app.run("layout.parents.edit", json!({"on": false}));++ }+ let _ = app.run("layout.selectPage", json!({"page": null}));+ app.select_tool("selection");+ return;+ }+ section(ui, crate::i18n::tr(&lang, "Page Size"), true);+ // Which page.+ let b = block(ui, FIELD_H);- let names: Vec<String> = (0..d.page_count()).map(|i| app.session.page_label(i)).collect();++ let (names, selected): (Vec<String>, usize) = match spread {++ designcraft_doc::SpreadRef::Doc(si) => ((0..d.page_count()).map(|i| app.session.page_label(i)).collect(), d.first_page_of_spread(si) + page),++ designcraft_doc::SpreadRef::Parent(_) => {++ ((0..sp.pages.len()).map(|i| format!("{} · {}", sp.parent.as_ref().map(|p| p.label()).unwrap_or_default(), i + 1)).collect(), page)++ }++ };+ let picked = place(ui, sub(b, 0.0, 0.0, 93.0, FIELD_H), |ui| {- widgets::dropdown_list(ui, names.get(page).map_or("", String::as_str), 93.0, &names, Some(page))++ widgets::dropdown_list(ui, names.get(selected).map_or("", String::as_str), 93.0, &names, Some(selected))+ });+ if let Some(p) = picked {- let _ = app.run("layout.selectPage", json!({"page": p + 1}));- crate::canvas::go_to_page(app, p);++ match spread {++ designcraft_doc::SpreadRef::Doc(_) => {++ let _ = app.run("layout.selectPage", json!({"page": p + 1}));++ crate::canvas::go_to_page(app, p);++ }++ designcraft_doc::SpreadRef::Parent(_) => {++ let _ = app.run("layout.selectParentPage", json!({"parent": sp.id.0, "page": p}));++ }++ }+ return;+ }+ ui.add_space(3.0);+ // Preset and orientation: this page alone.+ let (w, h) = (pg.width, pg.height);+ let mut size = page_preset_row(ui, &lang, w, h);+ ui.add_space(3.0);+ let b = block(ui, 2.0 * FIELD_H + 5.0);+ for (row, (label, v, key)) in [("W:", w, "width"), ("H:", h, "height")].into_iter().enumerate() {+ let y = row as f32 * 26.0;+ place(ui, sub(b, 0.0, y, 20.0, FIELD_H), |ui| widgets::caption_w(ui, label, 20.0));+ let nv = place(ui, sub(b, 21.0, y, 72.0, FIELD_H), |ui| {+ NumField::measure(&format!("page_{key}"), Some(v), u).width(72.0).spinner().range(1.0, 15552.0).show(ui)+ });+ if let Some(nv) = nv {+ size = Some(if key == "width" { (nv, h) } else { (w, nv) });+ }+ }- if let Some((nw, nh)) = size {- let _ = app.run("layout.pageSize", json!({"pages": [n], "width": nw, "height": nh, "anchor": app.ui.ref_point.min(8)}));++ if let Some((nw, nh)) = size++ && let Some((cmd, params)) =++ designcraft_tools::layout::page_size_command(&d, spread, page, json!({"width": nw, "height": nh, "anchor": app.ui.ref_point.min(8)}))++ {++ let _ = app.run(cmd, params);+ }+ ui.add_space(6.0);+ let fw = full_width(ui);+ if outline_button(ui, crate::i18n::tr(&lang, "Margins and Columns"), fw).clicked() {- crate::canvas::go_to_page(app, page);++ match spread {++ designcraft_doc::SpreadRef::Doc(si) => crate::canvas::go_to_page(app, d.first_page_of_spread(si) + page),++ designcraft_doc::SpreadRef::Parent(_) => crate::canvas::show_spread(app, spread),++ }+ crate::menus::activate(app, "layout.marginsAndColumns", &Value::Null);+ }+ divider(ui);+ section(ui, crate::i18n::tr(&lang, "Quick Actions"), true);+ if outline_button(ui, crate::i18n::tr(&lang, "Import File"), fw).clicked() {+ let _ = app.run("app.placeDialog", json!({}));+ }+ }++ /// Page count field: add pages after the last one, or delete from the end, to reach `nv` (from `n`).+ fn resize_document(app: &mut DesignApp, n: usize, nv: f64) {+ let want = (nv.round() as usize).clamp(1, 9999);+ if want > n {+ let _ = app.run("layout.pages.insert", json!({"count": want - n, "after": n - 1}));+ } else if want < n {+ let _ = app.run("layout.pages.delete", json!({"pages": (want..n).collect::<Vec<_>>()}));+ }+ }++ /// The margins after field `k` (top, bottom, outside, inside) is set to `nv`; all four when linked.+ fn edited_margins(mut m: designcraft_doc::Margins, linked: bool, k: usize, nv: f64) -> designcraft_doc::Margins {+ if linked {+ return designcraft_doc::Margins { top: nv, bottom: nv, inside: nv, outside: nv };+ }+ match k {+ 0 => m.top = nv,+ 1 => m.bottom = nv,+ 2 => m.outside = nv,+ _ => m.inside = nv,+ }+ m+ }++ /// The page-size preset menu; the width and height of the preset chosen.+ fn page_preset_menu(ui: &mut Ui, pw: f64, ph: f64) -> Option<(f64, f64)> {+ let mut preset = None;+ let resp = dropdown(ui, preset_name(pw, ph), 93.0);+ egui::Popup::menu(&resp).show(|ui| {+ ui.set_min_width(140.0);+ for p in PAGE_PRESETS {+ if ui.selectable_label(preset_name(pw, ph) == p.0, p.0).clicked() {+ preset = Some((p.1, p.2));+ ui.close();+ }+ }+ });+ preset+ }++ /// As the status bar's page box: the page, or the parent shown ("A-Parent"); then the parents.+ fn page_box_field(app: &mut DesignApp, ui: &mut Ui, b: Rect) {+ let Some(pb) = crate::canvas::page_box(app) else { return };+ let picked = place(ui, sub(b, 0.0, 0.0, 93.0, FIELD_H), |ui| widgets::dropdown_list(ui, pb.current_name(), 93.0, &pb.names, Some(pb.current)));+ if let Some(i) = picked {+ crate::canvas::page_box_go(app, &pb, i);+ }+ }++ pub(super) fn document_sections(app: &mut DesignApp, ui: &mut Ui) {+ let u = units(app);+ let Some(st) = app.session.active() else { return };+ let d = st.doc.clone();+ let (pw, ph) = (d.settings.page_width, d.settings.page_height);+ section(ui, crate::i18n::tr(&app.ui.language, "Document"), true);+ // Preset dropdown + orientation.+ let b = block(ui, FIELD_H);+ let preset = place(ui, sub(b, 0.0, 0.0, 93.0, FIELD_H), |ui| page_preset_menu(ui, pw, ph));+ let landscape = pw > ph;+ let mut orient = None;+ place(ui, sub(b, 126.0, 0.0, 52.0, FIELD_H), |ui| {+ ui.spacing_mut().item_spacing.x = 4.0;+ if icon_toggle(ui, "orient-portrait", !landscape, crate::i18n::tr(&app.ui.language, "Portrait")).clicked() && landscape {+ orient = Some(());+ }+ if icon_toggle(ui, "orient-landscape", landscape, crate::i18n::tr(&app.ui.language, "Landscape")).clicked() && !landscape {+ orient = Some(());+ }+ });+ if let Some((w, h)) = preset {+ let (w, h) = if landscape { (h, w) } else { (w, h) };+ let _ = app.run("layout.documentSetup", json!({"width": w, "height": h}));+ }+ if orient.is_some() {+ let _ = app.run("layout.documentSetup", json!({"width": ph, "height": pw}));+ }+ ui.add_space(3.0);+ // W / H, page count, facing pages.+ let b = block(ui, 2.0 * FIELD_H + 5.0);+ for (row, (label, v, key)) in [("W:", pw, "width"), ("H:", ph, "height")].into_iter().enumerate() {+ let y = row as f32 * 26.0;+ place(ui, sub(b, 0.0, y, 20.0, FIELD_H), |ui| widgets::caption_w(ui, label, 20.0));+ let nv =+ place(ui, sub(b, 21.0, y, 72.0, FIELD_H), |ui| NumField::measure(key, Some(v), u).width(72.0).spinner().range(1.0, 15552.0).show(ui));+ if let Some(nv) = nv {+ let _ = app.run("layout.documentSetup", json!({key: nv}));+ }+ }+ let n = d.page_count();+ let t = Tokens::get(ui.ctx());+ icons::paint(ui.painter(), sub(b, 127.0, 2.0, 17.0, 17.0), "page-count", t.icon);+ let nv = place(ui, sub(b, 150.0, 0.0, 68.0, FIELD_H), |ui| number(ui, "pagecount", Some(n as f64), "", 68.0, 0));+ if let Some(nv) = nv {+ resize_document(app, n, nv);+ }+ let mut facing = d.settings.facing_pages;+ let changed = place(ui, sub(b, 126.0, 26.0, 100.0, FIELD_H), |ui| {+ widgets::checkbox(ui, &mut facing, crate::i18n::tr(&app.ui.language, "Facing Pages")).changed()+ });+ if changed {+ let _ = app.run("layout.documentSetup", json!({"facingPages": facing}));+ }+ // Margins.+ section(ui, crate::i18n::tr(&app.ui.language, "Margins"), true);+ let cur = crate::canvas::current_page(app).unwrap_or(0);+ // While parent spreads are edited the fields belong to the parent page in view; they used to+ // show (and change) the document pages instead, so nothing changed on the parent.+ let parent_target = crate::canvas::current_parent_page(app);+ let shown = match parent_target {+ Some((pi, qi)) => d.parents.get(pi).and_then(|s| s.pages.get(qi)).cloned(),+ None => d.page(cur).cloned(),+ };+ if let Some(p) = shown {+ let linked = temp_bool(ui, "margins_linked", true);+ let b = block(ui, 2.0 * FIELD_H + 5.0);+ let mut set: Option<designcraft_doc::Margins> = None;+ let fields = [+ ("margin-top", "Top", p.margins.top, 0.0, 0.0),+ ("margin-bottom", "Bottom", p.margins.bottom, 0.0, 26.0),+ ("margin-outside", if d.settings.facing_pages { "Outside" } else { "Right" }, p.margins.outside, 127.0, 0.0),+ ("margin-inside", if d.settings.facing_pages { "Inside" } else { "Left" }, p.margins.inside, 127.0, 26.0),+ ];+ for (k, (icon, tip, v, x, y)) in fields.into_iter().enumerate() {+ let ir = sub(b, x, y + 2.0, 17.0, 17.0);+ icons::paint(ui.painter(), ir, icon, t.icon);+ ui.interact(ir, ui.scope_id().with(("micon", k)), Sense::hover()).on_hover_ui(|ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, tip));+ });+ let nv = place(ui, sub(b, x + 20.0, y, 73.0, FIELD_H), |ui| {+ NumField::measure(tip, Some(v), u).width(73.0).spinner().range(0.0, 8000.0).show(ui)+ });+ if let Some(nv) = nv {+ set = Some(edited_margins(p.margins, linked, k, nv));+ }+ }+ let lr = sub(b, 99.0, 12.5, 22.0, FIELD_H);+ let clicked = place(ui, lr, |ui| {+ widgets::icon_toggle_sized(ui, if linked { "link" } else { "link-broken" }, linked, "Make all settings the same", vec2(22.0, 21.0))+ .clicked()+ });+ if clicked {+ set_temp_bool(ui, "margins_linked", !linked);+ }+ if let Some(m) = set {+ let params = match parent_target {+ // Both pages of a facing parent spread, so the margins show wherever the parent is used.+ Some((pi, _)) => {+ let n = app.session.active().and_then(|st| st.doc.parents.get(pi)).map_or(1, |sp| sp.pages.len());+ json!({"margins": m, "parent": pi, "pages": (0..n).collect::<Vec<_>>()})+ }+ None => json!({"margins": m}),+ };+ let _ = app.run("layout.marginsAndColumns", params);+ }+ }+ ui.add_space(6.0);+ let fw = full_width(ui);+ if outline_button(ui, crate::i18n::tr(&app.ui.language, "Adjust Layout"), fw).clicked() {+ crate::dialogs::open_document_setup(app);+ }+ divider(ui);+ // Page.+ section(ui, crate::i18n::tr(&app.ui.language, "Page"), true);+ let b = block(ui, FIELD_H);+ page_box_field(app, ui, b);+ let (add, del) = place(ui, sub(b, 172.0, 0.0, 50.0, FIELD_H), |ui| {+ ui.spacing_mut().item_spacing.x = 4.0;+ let a = widgets::icon_toggle_sized(ui, "style-new", false, "Insert Page", vec2(22.0, 21.0)).clicked();+ let d = widgets::icon_toggle_sized(ui, "trash", false, "Delete Page", vec2(22.0, 21.0)).clicked();+ (a, d)+ });+ if add {+ let _ = app.run("layout.pages.insert", json!({"after": cur, "count": 1}));+ }+ if del {+ let _ = crate::dialogs::delete_pages(app, vec![cur]);+ }+ ui.add_space(3.0);+ if outline_button(ui, crate::i18n::tr(&app.ui.language, "Edit Page"), fw).clicked() {+ // As in InDesign: the Page tool on this page; Properties shows the page's own settings.+ app.select_tool("page");+ let _ = app.run("layout.selectPage", json!({"page": cur + 1}));+ }+ divider(ui);+ // Rulers & Grids / Guides: icon toggle rows.+ let (mut rulers, mut bl, mut dg) = (app.ui.rulers, app.ui.baseline_grid, app.ui.document_grid);+ section_row(ui, crate::i18n::tr(&app.ui.language, "Rulers & Grids"), |ui| {+ ui.spacing_mut().item_spacing.x = 14.0;+ if icon_toggle(ui, "grid-document", dg, crate::i18n::tr(&app.ui.language, "Show Document Grid")).clicked() {+ dg = !dg;+ }+ if icon_toggle(ui, "grid-baseline", bl, crate::i18n::tr(&app.ui.language, "Show Baseline Grid")).clicked() {+ bl = !bl;+ }+ if icon_toggle(ui, "rulers", rulers, crate::i18n::tr(&app.ui.language, "Show Rulers")).clicked() {+ rulers = !rulers;+ }+ });+ if rulers != app.ui.rulers {+ let _ = app.run("view.rulers", json!({}));+ }+ if bl != app.ui.baseline_grid {+ let _ = app.run("view.baselineGrid", json!({}));+ }+ if dg != app.ui.document_grid {+ let _ = app.run("view.documentGrid", json!({}));+ }+ rule(ui);+ let (mut guides, mut locked, mut smart) = (app.ui.guides, app.ui.guides_locked, app.ui.smart_guides);+ section_row(ui, crate::i18n::tr(&app.ui.language, "Guides"), |ui| {+ ui.spacing_mut().item_spacing.x = 14.0;+ if icon_toggle(ui, "guides-smart", smart, crate::i18n::tr(&app.ui.language, "Smart Guides")).clicked() {+ smart = !smart;+ }+ if icon_toggle(ui, "guides-lock", locked, crate::i18n::tr(&app.ui.language, "Lock Guides")).clicked() {+ locked = !locked;+ }+ if icon_toggle(ui, "guides-show", guides, crate::i18n::tr(&app.ui.language, "Show Guides")).clicked() {+ guides = !guides;+ }+ });+ if guides != app.ui.guides {+ let _ = app.run("view.guides", json!({}));+ }+ if smart != app.ui.smart_guides {+ let _ = app.run("view.smartGuides", json!({}));+ }+ if locked != app.ui.guides_locked {+ let _ = app.run("view.lockGuides", json!({"on": locked}));+ }+ rule(ui);+ section(ui, crate::i18n::tr(&app.ui.language, "Quick Actions"), true);+ let (a, b) = button_pair(ui, crate::i18n::tr(&app.ui.language, "Import File"), crate::i18n::tr(&app.ui.language, "Insert Page"));+ if a {+ let _ = app.run("app.placeDialog", json!({}));+ }+ if b {+ let _ = app.run("layout.pages.insert", json!({"after": cur, "count": 1}));+ }+ }diff --cc docs/control-protocol.mdindex 1dc0eed49,92e7f108e..2d8fb7718--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@@ -48,7 -49,7 +49,7 @@@ so only enable it while you use it. Tra| `ui.dialog.set` / `ui.dialog.confirm` / `ui.dialog.cancel` | `{field, value}` | Fill and confirm the open dialog || `ui.resize`, `ui.focus` | | Window control || `ui.screenshot` | `{path?}` | PNG of the whole window |--| `ui.render` | `{path?, page?, scale?, bleed?}` | Render a page headlessly (PNG; base64 if no path) |++| `ui.render` | `{path?, page?, scale?, bleed?}` | Render a document page headlessly (PNG; base64 if no path); parent editing mode requires an explicit 0-based `page` || `app.open` / `app.save` / `app.export` | | Files || `app.quit` | | Quit without asking about unsaved changes (the `app.quit` command, like ⌘Q, asks) |diff --cc docs/roadmap.mdindex 7d471566f,1da9fabc5..ae162eedc--- a/docs/roadmap.md+++ b/docs/roadmap.md@@@ -1,6 -1,6 +1,6 @@@# DesignCraft roadmap (detail)- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (independent parent page resizing, #1620; .indd and .indt open through indd-utils; text threads by hand; the gate waits on the Primary Text Frame page fixes) · **Target:** Adobe InDesign 2026 (21.6)-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (.indd and .indt open through indd-utils; text threads by hand; the gate waits on the Primary Text Frame page fixes) · **Target:** Adobe InDesign 2026 (21.6)++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (independent parent page resizing, #1620; .indd and .indt open through indd-utils; text threads by hand; the gate waits on the Primary Text Frame page fixes) · **Target:** Adobe InDesign 2026 (21.6)Forward-looking plan. The one-page summary is [ROADMAP.md](../ROADMAP.md); numbers are in[target-app-parity.md](target-app-parity.md); the work list is [gaps.md](gaps.md). Hours are