DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge storytold/main (v0.14.0) into parent-page-display
Claude401928d0fc6a
diff --cc ROADMAP.mdindex d64f59c8d,c02176bab..8ee978b5d--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -348,7 -380,74 +380,75 @@@ list) · [roadmap.md](docs/roadmap.md)Newest first.+ - **2026-10-27** · An iconic panel's flyout stays open while you work in the canvas or a text field: Auto-Collapse Iconic Panels is off by default, and preferences saved with it on start with it off. Preferences › Interface › Panels holds the setting next to the column bar's menu item. No readiness percentage change.+ - **2026-10-24** · Column rules run from the top line's ascent to the bottom line's descent, as InDesign draws them, instead of from the top to the bottom of the columns, on screen, in PDF and in PowerPoint export. The top and bottom insets shorten the rule from those lines. Existing documents draw their column rules at the new length. No readiness percentage change.+ - **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change.+ - **2026-10-19** · Import InDesign Set… runs on craft-keymap's importer: a set's Window menu panel items (Layers F7, Pages F12, Swatches F5) and Tools items set the panel and tool shortcuts, all of an item's Default keys apply, and the report adds numeric keypad keys read as main keys and likely commands for unmatched items (`window.importShortcuts`). On InDesign's Windows defaults it matches 366 of 1,629 items (was 233) and changes 23 commands. No readiness percentage change.+ - **2026-10-19** · Keyboard shortcuts run on the shared craft-keymap crate. Panels take shortcuts, with InDesign's defaults where the key is free (Swatches F5, Color F6, Layers F7, Info F8, Stroke F10, Paragraph Styles F11, Character Styles Shift+F11, Pages F12, Align Shift+F7); tool keys are editable in Edit › Keyboard Shortcuts and `window.setShortcut`, and tools sharing a key take turns (B). Saved shortcuts load unchanged. No readiness percentage change.+ - **2026-10-16** · Edit › Keyboard Shortcuts imports a set saved by InDesign's Show Set (.txt, Windows or Mac key names, UTF-8 or UTF-16): matched commands take its Default shortcuts or lose theirs, other commands give up keys it takes, and a report lists what it changed and the items it could not match (`window.importShortcuts`, #1180). Tool keys stay fixed. No readiness percentage change.+ - **2026-10-20** · PDF/X-1a:2003 export (craft-libs#194): `file.exportPdf {standard: "x1a"}`, the Export PDF dialog's PDF/X-1a:2003 preset and standard. The PDF/X-4 print file is flattened in its inks by craft-prepress (no transparency; spot, process, overprint and live text kept; complex regions as DeviceN images at the Transparency Flattener preset's resolution), then written as PDF 1.4 with the X-1a identification and checked; `validate-pdf --standard x1a`. Soft drop shadows reach the flattener in their swatch's inks; other soft effects are still RGB images. No readiness percentage change.+ - **2026-10-20** · Print color (craft-libs#190): CMYK print PDFs blend in DeviceCMYK through craft-pdf's print settings instead of byte rewrites, with the CMYK working space as the output intent in PDF/X-4 only; overprint (Overprint Fill, Stroke and Gap, overprinting text, 100% [Black]) is written as `/op` `/OP` `/OPM 1`; Knockout Group writes `/K true` instead of becoming an image; File › Print prints the PDF Export PDF writes. No readiness percentage change.+ - **2026-10-20** · Separations Preview shows the plates the exported PDF prints, spot plates included: each visible spread is exported in memory with the Export PDF settings and separated by craft-prepress off the UI thread, then shown as all inks, one plate or an ink limit. The Ink Manager builds craft-prepress's `InkSet` from the document for export and preview. On the sample magazine the first preview of a spread takes about 0.6–1.1 s, most of it the PDF export. No readiness percentage change.+ - **2026-10-20** · Spot gradients print on their plates. A gradient stop keeps the swatch it was given (Gradient panel drop, `swatch.create {gradient}`, `object.gradient`, IDML `StopColor`), following its renames and edits. PDF export shades one spot with its tints or [Paper] as a Separation, and a spot with process inks or a second spot as DeviceN; a process gradient to [Paper] prints in DeviceCMYK. Documents with plain-color stops export as before. No readiness percentage change.+ - **2026-10-24** · Panels dock through the suite's shared docking (craft-libs), and on desktop a floating panel opens in its own window that can leave the main window: keys pressed there run the main window's shortcuts, clipboard and tool keys, and the canvas paints no tool cursor while another of the app's windows has the pointer. The web build keeps floating panels in the page. No readiness percentage change.+ - **2026-10-24** · Story Options rejects malformed or nonexistent explicit story/frame IDs without changing the selected story, including an invalid frame alongside a valid story. Null targets remain absent; omitted targets still use the selection. No readiness percentage change.+ - **2026-10-24** · Text Frame Options explains that a custom baseline-grid increment must be a measure greater than zero when zero, a negative value or a non-measure is entered. Validation is unchanged. No readiness percentage change.+ - **2026-10-24** · Renaming a paragraph or character style, or moving it into a style group, keeps its Export Tagging under the new name, and undo puts it back under the old one. Deleting a tagged style drops its tagging and leaves the replacement style's own tagging as it was. No readiness percentage change.+ - **2026-10-24** · Quick Apply and the application bar's search leave out the interface commands that failed or reset a setting when chosen there: those that need a workspace, a command and shortcut, a menu item, a panel, a window edge, an app page, a recent file or a swatch they can't give them, a Contextual Task Bar place, and Interface Color Theme, UI Scaling, Reset Shortcuts, the flattener preset, Screen Mode and Zoom To, which without a value switched to the dark theme, set 100%, cleared every custom shortcut or the preset, or went to Normal mode or 100% zoom. Each stays in the menu, panel or dialog that gives it the value. No readiness percentage change.+ - **2026-10-24** · EPUB Export Options › Split Document, a dialog before File › Export EPUB… saves (`document.epubSplit`, stored with the document): off, a single paragraph style, or based on paragraph style export tags, with Paragraph Style Options › Export Tagging's Split Document flag marking those styles. A reflowable EPUB is one content file unless Split Document is on; the split before each top-level h1 from #791 is gone. A split before a list item or preformatted line no longer leaves an unclosed list or block in a content file. IDML import and export keep the setting and the flag, and Load Styles the flag. No readiness percentage change.+ - **2026-10-18** · Repeated placed-PDF layer variants are prepared once per asset and hidden-name set, with recovery warnings retained. All-visible named layers keep their original source bytes, including PDFs whose cross-reference tables the reader repairs, in plain, PDF/X-4, booklet and book-merge output. Layer changes that require writing still reject an unusable cross-reference table with a file-named damage error; the first placement error is retained (#906). No readiness percentage change.+ - **2026-10-18** · Placed PDF optional-content defaults and per-frame overrides survive plain and PDF/X-4 vector export, including repeated placements, booklet output and book merging (#906). Source usage-application arrays are accepted; groups without a catalog configuration stay visible. Missing or unreadable default configurations and unsupported base states use all-ON defaults with a file-named export warning, retaining explicit frame overrides. Readable groups omitted from the catalog list are added with a distinct file-named warning, preserving their default ON/OFF states. Concurrent recovery warnings are combined. Malformed ON data is recoverable when a known ON base and empty OFF list prove it cannot hide artwork; missing display names are generated without changing known visibility when no override needs name matching. Contradictory states, unresolved references and ambiguous name overrides still fail export. Print-usage adjustments and IDML layer overrides remain follow-ups. No readiness percentage change.++ - **2026-10-24** · Optical Margin Alignment and hanging punctuation apply to lines with a tab or a right indent tab, as both composers already measured them: the edge glyphs hang, and tab stops stay where they are. Such a line was set without the hang: a justified line that fit only because its period or closing quote hangs had its word spaces squeezed to make up for it, and text after a right indent tab stopped at the measure instead of hanging. No readiness percentage change.+ - **2026-10-23** · `designcraft-cli mcp` takes `--automation-read-root` and `--automation-write-root` more than once, as the suite's other apps do (#1552): a path inside any root of its kind passes, and the roots' common parent, `..` or a link out of them and the other kind's roots stay refused. No readiness percentage change.+ - **2026-10-23** · Layout › Go Back and Go Forward (Cmd+Page Up / Cmd+Page Down, Ctrl on Windows and Linux) retrace the jumps between pages (Go to Page, the page and spread commands, the Pages panel) as InDesign's do, returning to where the view was on each page at the current zoom; a new jump after going back drops the pages ahead, scrolling adds no entry, and pages deleted since are skipped. No readiness percentage change.+ - **2026-10-24** · The Story Editor has InDesign's vertical depth ruler between the style column and the text, and View › Story Editor › Show/Hide Depth Ruler (`view.storyEditorDepthRuler`) shows or hides it in the Story Editor, remembered with the preferences. The ruler is marked in the document's vertical ruler units with how deep the story's text fills its frames, counted through its columns and threaded frames (lines set side by side, in the sub-columns of a split paragraph or on both sides of a wrap object, count once), and is shaded down to the overset point, where a red line now crosses the editor. No readiness percentage change.+ - **2026-10-24** · Split Note (`note.split {story, id, at}`, the Notes panel's Split Note button): as in InDesign, a note splits in two at the insertion point in its text. DesignCraft moves the text after it into a new note by the same author, anchored right after the first. No readiness percentage change.+ - **2026-10-24** · Type › Notes › Previous Note and Next Note (`note.previous`, `note.next`): as in InDesign, they move the insertion point from note to note in the story, putting the caret after the note's anchor. Each item is unavailable when no note lies in its direction in the story, or when the insertion point is in a table cell or a footnote. No readiness percentage change.+ - **2026-10-24** · Type › Notes › Convert to Note (`note.convertFromText {author?}`): as in InDesign, the selected text leaves the story and becomes the text of a new note, whose anchor takes its place; Convert Note to Text puts it back. DesignCraft refuses a selection in a table cell, or one that holds a note, footnote, endnote, anchored object, index marker, text anchor, cross-reference or table. No readiness percentage change.+ - **2026-10-23** · Effects dialog: with Use Global Light on, the Angle field (and the Bevel and Emboss one) stays editable and shows the document's global light angle; a change there sets the global light for every effect that uses it, applied with the effects in one undo step (`object.effects` takes `globalLight`). Before, the field was greyed out and the angle couldn't be changed in the dialog. No readiness percentage change.+ - **2026-10-24** · Story panel (Window › Type & Tables › Story): Optical Margin Alignment and its size for the stories of the text selection or the selected text frames, disabled without either; `type.selectionAttrs` reports them as `storyOptions`, null where the stories differ. The Paragraph panel menu has Ignore Optical Margin in place of the per-paragraph Optical Margin Alignment switch, which stays in `type.para`, and Paragraph Style Options › Indents and Spacing has Ignore Optical Margin (#947). No readiness percentage change.+ - **2026-10-24** · Optical Margin Alignment per story with a size (`story.options {opticalMargin, opticalMarginSize}`, off by default): when it is on, the story's paragraphs hang punctuation and letter edges by amounts set for that type size, except paragraphs with Ignore Optical Margin (`ignoreOpticalMargin` in `type.para` and paragraph styles). Table cells and footnotes don't take the story setting yet. When it is off, the per-paragraph switch still hangs at the text's own size. IDML imports and exports both (`StoryPreference/@OpticalMarginAlignment`, `@OpticalMarginSize`, `IgnoreEdgeAlignment`) (#947). No readiness percentage change.+ - **2026-10-24** · Text frames: a custom baseline grid's Relative To (Text Frame Options › Baseline Options, `object.textFrameOptions {baselineGrid: {relativeTo}}`, IDML `BaselineFrameGridRelativeOption`) measures the grid's start from the top of the page, the top margin, the top of the frame or its top inset. Text Frame Options had no custom baseline grid controls, imports dropped the setting and every frame grid started from the page top, so grid-aligned text in a frame measured from its own top sat on the wrong lines. No readiness percentage change.+ - **2026-10-24** · Paragraph Style Options › Indents and Spacing has an Align to Grid menu: None, All Lines or First Line Only. It shows the style's current setting. A First Line Only style could be set only in the CJK Grid Settings section, which shows only with CJK features on, or through commands. No readiness percentage change.+ - **2026-10-24** · Anchored text frames, such as marginal notes, compose where their host story places them: they align to the baseline grid at that position, and page-number markers and spine-relative alignment inside them read the host's page. They composed against a grid measured from their stored position and on no page, so a note set to Only Align First Line to Grid could sit a fraction of a line off the body text's grid line. No readiness percentage change.+ - **2026-10-24** · Tables: a gradient swatch in a cell fill draws as a gradient on the canvas and in PDF, in one gradient space for the whole table, so it runs across cells without restarting. Cells showed the gradient's first stop as a solid colour. No readiness percentage change.+ - **2026-10-24** · New documents start with Hyphenate Capitalized Words, Hyphenate Last Word and Hyphenate Across Column off in [Basic Paragraph], as in InDesign. Opened and imported files keep the values they carry. No readiness percentage change.+ - **2026-10-24** · The baseline grid's Relative To setting applies: with Top Margin, the grid starts at each page's own top margin in text composition, on the canvas and for snapping. It started at the page top, so grid-aligned text sat on the wrong lines and a page could fit one line fewer. No readiness percentage change.+ - **2026-10-24** · Custom-positioned anchored objects honour Relative to Spine (`anchored.options {spineRelative}`, IDML `SpineRelative`): the settings describe a left-hand page and mirror on a right-hand page, so marginal notes stay in the outside margin on both pages of a spread. On right-hand pages they took the left-hand placement and landed in the inside margin, across the spine or over the body text. No readiness percentage change.+ - **2026-10-24** · Text frames: a custom baseline grid (Text Frame Options › Baseline Options) from an IDML file sets lines from its start by its increment. The composer read the two values in the other order, so lines landed on the wrong grid. No readiness percentage change.+ - **2026-10-23** · File › File Info… edits the document's Document Title, Author, Description, Keywords, Copyright Notice and Copyright Info URL (`file.info`), and the document saves them. PDF export (PDF/X-4 and Print Booklet included) writes the title, author, description and keywords into the PDF's document information and XMP. EPUB export takes the title and author from File Info, and HTML export takes the title. A title or author given to the export replaces File Info's, and an empty Document Title leaves the document's name as the title. No readiness percentage change.+ - **2026-10-23** · Save and export dialogs (Save As, Save a Copy, Export PDF and the other exports, Package, libraries and books) start in the active document's folder once it has been saved, and for a document never saved in the folder of the last file saved or exported, remembered across sessions (#1653). A folder deleted since falls back to the system's choice. No readiness percentage change.+ - **2026-10-22** · Autoflow (Shift-click with the loaded text cursor, autoflow on Place, `text.thread {autoflow}`) fills the pages that follow before it adds any, as InDesign does: one frame per column on each following page, whatever else the page holds, then new pages at the end of the document. It inserted pages right after the story's last frame, in front of the document's own pages. Frames it set past the end of the text go again; a page the document had stays, and a page autoflow added only for such a frame goes with it. Smart Text Reflow of the primary text frame is unchanged. No readiness percentage change.+ - **2026-10-16** · Edit › Keyboard Shortcuts imports a set saved by InDesign's Show Set (.txt, Windows or Mac key names, UTF-8 or UTF-16): matched commands take its Default shortcuts or lose theirs, other commands give up keys it takes, and a report lists what it changed and the items it could not match (`window.importShortcuts`, #1180). Tool keys stay fixed. No readiness percentage change.+ - **2026-10-23** · Translations: a missing string shows in English and fails no test; `cargo xtask i18n-report`, run by `cargo xtask ci`, prints the missing strings per language. Tests keep duplicate-key and placeholder checks and the language mechanics (lookup, context captions, plural captions, right-to-left). No readiness percentage change.+ - **2026-10-22** · Hyphenation Settings, as in InDesign: the Paragraph panel menu's Hyphenation… (`app.hyphenationDialog`) sets the selected paragraphs' Hyphenate, Words with at Least, After First, Before Last, Hyphen Limit, Hyphenation Zone, the Better Spacing ↔ Fewer Hyphens slider (InDesign's 0–10 steps), Hyphenate Capitalized Words, Last Word and Across Column, with Preview, as one undo step; Paragraph Style Options › Hyphenation has the same form. The panel menu lists its items in InDesign's order. Replicated from a hyphenation tutorial: the same text in Minion Pro breaks into the same lines as InDesign's with hyphenation on, off, and at Fewer Hyphens. No readiness percentage change.+ - **2026-10-22** · Hyphenate Across Column (Hyphenation Settings; IDML HyphenateAcrossColumns) is applied: with it off, a paragraph whose line ending in an automatic hyphen would end a column or frame is re-composed without that hyphenation point, so the word moves on whole, as in InDesign. Opened and imported files keep their own setting, so their layouts don't change. No readiness percentage change.+ - **2026-10-22** · The Paragraph panel is laid out as InDesign's: the nine alignment buttons in groups; indent, spacing and drop cap fields by their icons in two columns, with Space Between Paragraphs Using Same Style (Ignore or a space); Shading and Border with the Paragraph Borders and Shading button and colour; Hyphenate with Do Not Align / Align to Baseline Grid. Its panel menu follows InDesign's order: Paragraph and Single-line Composer, Only Align First Line to Grid, Balance Ragged Lines, Optical Margin Alignment, Justification…, Keep Options…, Span Columns…, Hyphenation…, Drop Caps and Nested Styles…, GREP Styles… (these three now open for the selected paragraphs), Paragraph Rules…, Paragraph Borders and Shading…, Bullets and Numbering…, Restart/Continue Numbering, Define Lists… and the paragraph direction. Convert Bullets and Numbering to Text is listed but not available yet. No readiness percentage change.+ - **2026-10-22** · A ruler guide dragged with the Selection tools, out of a ruler, on its own or with other selected guides, snaps along its axis as objects do (#1221): to other ruler guides, margins, columns, bleed, page and object edges and centers (with the smart-guide mark) and the document grid, within the snap zone and following Snap to Guides and Smart Guides. Shift snaps to the ruler's ticks and Cmd suspends snapping. The preview line, the position readout and the drop use the same snapped position. No readiness percentage change.+ - **2026-10-22** · macOS: the app menu has a Language submenu after Settings… with each interface language in its own name and the current one checked, as in the suite's other apps; Preferences › General › Interface Language stays. No readiness percentage change.+ - **2026-10-23** · Type › Text Variables › Convert Variable to Text (`variables.convertToText`): the variable instances in the selected text, in a story, a table cell or a footnote, become plain text of the value each shows on its own page (a running header on page 3 becomes page 3's heading). `variables.convertAllToText {name}` does the same for every instance of one variable in the document, as the Text Variables dialog's Convert to Text button. The variable stays defined; one undo step. No readiness percentage change.+ - **2026-10-22** · macOS menu bar: the menus keep working after the interface language or Show CJK Features changes (a rebuilt menu bar lost every click, Quit included), and its key equivalents are the shortcuts in effect, so a shortcut moved in the Keyboard Shortcuts editor leaves its old menu item. No readiness percentage change.+ - **2026-10-22** · Paragraph rules: Rule Above's offset is measured from the first line's baseline to the rule's bottom edge, as in InDesign. Rules sat one ascent too high and crossed the previous paragraph's text (reported from an imported INDD document). No readiness percentage change.+ - **2026-10-21** · Ruler guides are selected like objects (#1282): a click with the Selection tools selects a guide (also where it crosses an object), Shift-click adds or removes one, a new guide from the rulers is selected, a marquee that touches no object selects the guides it crosses, and Edit › Select All Guides (⌥⌘G, `guide.selectAll`) selects every unlocked guide on the spread. Selected guides draw thicker in their layer's color, drag together (all of them shown moving), nudge with the arrow keys and go with Delete, each as one undo step (`guide.select`, `guide.deselect`, `guide.moveBy`, `guide.delete {}`). With one guide selected the Control bar's X (vertical guide) or Y (horizontal guide) field and Properties › Transform show where it is, as the rulers measure, and typing a value moves it there. No readiness percentage change.+ - **2026-10-17** · PDF/X-4 export warns about fonts drawing visible text without an embedded+ font program, including placed PDF forms; `validate-pdf` reports the font and page (#909).+ Invisible OCR text is exempt. Detection only: fonts are not embedded or outlined automatically.+ Repeated forms reuse context-aware font findings; a document-wide operation limit and a form-nesting depth limit+ report incomplete checks instead of allowing excessive nested-form traversal.+ No readiness percentage change.+ - **2026-10-16** · Selection: drag a column guide to move its gutter, as in InDesign (#1096). Both guides of the gutter move together and keep its width, stop at the neighbouring guides and the margins, and snap to the document grid, guides and objects, or with Shift to the ruler's tick marks; Escape cancels and the drag is one undo step. Locked column guides (the default) are not picked. A document page takes the result as its own columns; on a parent page it passes to the pages that follow it. `layout.moveColumnGuide` does the same over the control channel and MCP. No readiness percentage change.+ - **2026-10-16** · Layout: autoflow, inserted pages and new parents follow dragged column guides (#1096). Autoflow sets one frame per dragged column and counts the pages it adds from them; Insert Pages and New Parent keep the custom positions with the column count and gutter; a page that moves to the other side of the spine (inserted, deleted or moved pages, Duplicate Spread, a new parent's other page) has them mirrored across its margin box, as InDesign does; `document.inspect` reports each page's gutter, column rects and whether its columns are custom. No readiness percentage change.+ - **2026-10-16** · Layout: Margins and Columns keeps dragged column guides unless the column count or gutter changes (#1096). The dialog sends every field on OK, so a margin-only change re-divided the columns evenly. Margin changes keep the positions; the columns follow them only while they fit the margin box. No readiness percentage change.+ - **2026-10-16** · Lock Guides and Lock Column Guides are commands in View ▸ Grids & Guides (`view.lockGuides`, ⌥⌘;, and `view.lockColumnGuides`), so the control channel and MCP reach them. Lock Column Guides is an undo step, is saved with the document, on in new ones, and read from and written to IDML's `ColumnGuideLocked`, which export always wrote as locked (#1096). No readiness percentage change.+ - **2026-10-16** · IDML: a page keeps column guides that were dragged off centre (InDesign's Custom columns). They were divided evenly on import, so the gutter sprang back to the middle; the imported positions now place the columns, with the canvas guides, snapping and text placement following them, and they are written back on export. Layout › Margins and Columns re-divides them evenly when the count or gutter changes, as InDesign's does. No readiness percentage change.+ - **2026-10-16** · IDML: custom column positions are checked before they are used (#1096). A set must give two edges per column, ascending from the left margin to the right one; any other (a wrong count, unsorted or non-numeric values, a list longer than 216 columns allow, or positions left behind by a margin or page-size change) is the even split, in the canvas, on import and on export, instead of columns drawn outside the margins. No readiness percentage change.+ - **2026-10-21** · Properties › Character and Paragraph: ••• (More Options) expands the section in place, as InDesign's: Character adds vertical and horizontal scale, baseline shift, skew, language and OpenType, and All Caps, Small Caps, Superscript, Subscript, Underline and Strikethrough; Paragraph adds the left, right, first line and last line indents, space before and after, the drop cap's lines and characters, Align to Baseline Grid and Hyphenate. It used to open the Character or Paragraph panel; the language field moved under ••• as in InDesign. Found in the Learn Skills Daily course, chapter 16. No readiness percentage change.+ - **2026-10-21** · The text Control panel has InDesign's two modes: A (Character Formatting Controls: font and style, size and leading, All Caps/Superscript/Underline and Small Caps/Subscript/Strikethrough, kerning and tracking, vertical and horizontal scale, baseline shift and skew, character style and language) and ¶ (Paragraph Formatting Controls: the nine alignments, left/first line and right/last line indents, space before and after, the drop cap's lines and characters, paragraph style, Hyphenate and Align to Baseline Grid). It used to show a fixed mix of both. Found in the Learn Skills Daily course, chapter 16. No readiness percentage change.+ - **2026-10-20** · With the Type tool, the Control panel's font size, leading and tracking fields have a spinner and a list of common values, as in InDesign (auto leading in parentheses). No readiness percentage change.+ - **2026-10-21** · The ¶ (Paragraph Formatting Controls) mode of the text Control panel has InDesign's Bulleted List and Numbered List buttons (with the default hanging indent) and Shading and Border: a checkbox, a button opening Paragraph Borders and Shading on that tab, and the colour. Found in the Learn Skills Daily course, chapter 21. No readiness percentage change.+ - **2026-10-21** · The Bulleted and Numbered List buttons (Properties, and Type › Bulleted & Numbered Lists › Apply Bullets / Apply Numbers) work as InDesign's: a paragraph with no indents gets the default hanging indent (0.25 in, −0.25 in), so the text lines up after the bullet instead of at the next default tab stop, and pressing the button again removes the list and that indent (`list.bullets`, `list.numbers`). Found in the Learn Skills Daily course, chapter 21. No readiness percentage change.+- **2026-10-17** · Parent pages: a running-header variable shows its name in angle brackets on the parent (it was blank), and while parents are edited the document pages' hidden characters, spelling squiggles and other overlays no longer pile onto the right parent page. No readiness percentage change.- **2026-10-16** · Type › Reload Fonts (`font.reload`): fonts installed, edited or removed while DesignCraft runs are read again without a restart, and the open documents recompose with them (#328, #547). An edited font file is noticed by its length and modification time; bundled, added and document fonts stay as they are. InDesign does this by itself, so noticing changes automatically is still open (gap 6). No readiness percentage change.- **2026-10-16** · Parents can be deleted from their Pages-panel context menu or `layout.parents.delete {id}`. Applied-page and based-on references are cleared, local override copies survive, and Undo restores the parent. Addresses the deletion portion of #956; no readiness percentage change.- **2026-10-17** · File › Package writes the document's and the IDML's links relative to the package (`Links/logo.png`, `file:Links/logo.png`), so a package holds no path from the machine that made it; opening a document resolves them to the files beside it. Links › Copy Link(s) To still links by full path. (#340). No readiness percentage change.diff --cc crates/engine/src/cmd/variables/tests.rsindex 000000000,4a4832c84..1dee3f910mode 000000,100644..100644--- a/crates/engine/src/cmd/variables/tests.rs+++ b/crates/engine/src/cmd/variables/tests.rs@@@ -1,0 -1,356 +1,366 @@@+ use super::*;+++fn shown_on_parent(s: &Session, d: &designcraft_doc::Document, sid: designcraft_doc::StoryId) -> usize {++ let cs = s.cache.get(d, sid, None);++ cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum()++}+++ /// A parent-page page-number marker follows Numbering & Section Options: changing a section's+ /// start number renames its pages without changing their index or the number of sections, and+ /// the marker composed for a page shows the new name.+ #[test]+ fn parent_page_number_follows_section_renumbering() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 3, "facingPages": false})).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 sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, marker);+ let shown = |s: &Session, page: usize| -> usize {+ let d = s.doc().unwrap().doc.clone();+ let cs = s.cache.get(&d, sid, Some(page));+ 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!(shown(&s, 2), 1, "page 3");+ s.execute("layout.section", &json!({"page": 1, "startNumber": 100})).unwrap();+ assert_eq!(s.doc().unwrap().doc.page_name(2), "102");+ assert_eq!(shown(&s, 2), 3, "page 102 after renumbering");+ }++ /// A section marker character shows the marker text of the section of the page it is composed+ /// for: on each document page a parent-page frame is shown on, and in a frame on a document+ /// page. A section without marker text shows nothing; the parent page itself shows "Section".+ #[test]+ fn section_marker_shows_the_pages_section_marker() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 4, "facingPages": false})).unwrap();+ s.execute("layout.section", &json!({"page": 3, "startNumber": 1, "marker": "Intro"})).unwrap();+ let marker = designcraft_doc::story::SECTION_MARKER.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 parent = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;+ let sp = s.doc().unwrap().doc.page_loc(3).unwrap().0;+ let r = s.execute("frame.create", &json!({"spread": sp, "rect": [72, 200, 400, 260], "content": "text", "text": marker})).unwrap();+ let own = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;+ let shown = |s: &Session, sid, page: Option<usize>| -> usize {+ let d = s.doc().unwrap().doc.clone();+ let cs = s.cache.get(&d, sid, page);+ 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!(shown(&s, parent, Some(0)), 0, "the first section has no marker");+ assert_eq!(shown(&s, parent, Some(2)), "Intro".len());+ assert_eq!(shown(&s, parent, Some(3)), "Intro".len());+ assert_eq!(shown(&s, own, None), "Intro".len(), "a frame on a document page");+ assert_eq!(shown(&s, parent, None), "Section".len(), "the parent page itself");+ // Editing the marker recomposes.+ s.execute("layout.section", &json!({"page": 3, "marker": "Appendix"})).unwrap();+ assert_eq!(shown(&s, parent, Some(2)), "Appendix".len());+ assert_eq!(shown(&s, own, None), "Appendix".len());+ }++ /// Two sections that both number from 1 repeat page names ("1, 2, 1, 2"). A parent-page running+ /// header is composed for the page it is shown on, not the first page with that name.+ #[test]+ fn running_header_on_parent_page_with_repeated_page_numbers() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 4, "facingPages": false})).unwrap();+ s.execute("layout.section", &json!({"page": 3, "startNumber": 1})).unwrap();+ let names: Vec<String> = (0..4).map(|i| s.doc().unwrap().doc.page_name(i)).collect();+ assert_eq!(names, ["1", "2", "1", "2"]);+ s.execute("style.paragraph.create", &json!({"name": "Heading"})).ok();+ // The only heading is on the third page (the second section's page 1).+ let sp = s.doc().unwrap().doc.page_loc(2).unwrap().0;+ let r = s.execute("frame.create", &json!({"spread": sp, "rect": [72, 200, 400, 260], "content": "text", "text": "Epsilon"})).unwrap();+ let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 1})).unwrap();+ s.execute("style.paragraph.apply", &json!({"name": "Heading"})).unwrap();+ s.execute("variables.define", &json!({"name": "Chapter Head", "type": "runningHeader", "style": "Heading"})).unwrap();+ let r = s+ .execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 30, 500, 60], "content": "text", "text": ""}))+ .unwrap();+ let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();+ s.execute("variables.insert", &json!({"name": "Chapter Head"})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ let shown = |page: usize| -> usize {+ let cs = s.cache.get(&d, sid, Some(page));+ 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!(shown(0), 0, "no heading on or before the first page");+ assert_eq!(shown(2), "Epsilon".len(), "the third page (named 1) shows its own heading");+ assert_eq!(shown(3), "Epsilon".len(), "the fourth page (named 2) carries it");+ }++ /// Three pages with "Alpha" in the Heading style on page 1 and "Epsilon" on page 3, a+ /// `Chapter Head` running header on Heading, and a text frame on pages 1 and 3 that each hold+ /// "<head>|<head>" (two instances). Returns the two frames' stories.+ fn running_heads() -> (Session, designcraft_doc::StoryId, designcraft_doc::StoryId) {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 3, "facingPages": false})).unwrap();+ s.execute("style.paragraph.create", &json!({"name": "Heading"})).ok();+ let frame = |s: &mut Session, page: usize, y: f64, text: &str| {+ let sp = s.doc().unwrap().doc.page_loc(page).unwrap().0;+ let r = s.execute("frame.create", &json!({"spread": sp, "rect": [72, y, 400, y + 60.0], "content": "text", "text": text})).unwrap();+ s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story+ };+ for (page, text) in [(0, "Alpha"), (2, "Epsilon")] {+ let sid = frame(&mut s, page, 200.0, text);+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 1})).unwrap();+ s.execute("style.paragraph.apply", &json!({"name": "Heading"})).unwrap();+ }+ s.execute("variables.define", &json!({"name": "Chapter Head", "type": "runningHeader", "style": "Heading"})).unwrap();+ let c = var_char(s.doc().unwrap().doc.variable("Chapter Head").unwrap()).unwrap();+ let both = format!("{c}|{c}");+ let (p1, p3) = (frame(&mut s, 0, 400.0, &both), frame(&mut s, 2, 400.0, &both));+ (s, p1, p3)+ }++ /// Convert Variable to Text turns the selected instance into the value it shows on its own+ /// page (Epsilon on page 3, not page 1's Alpha); the other instance and the variable stay.+ #[test]+ fn convert_variable_to_text_uses_the_instances_page() {+ let (mut s, p1, p3) = running_heads();+ let c = var_char(s.doc().unwrap().doc.variable("Chapter Head").unwrap()).unwrap();+ let second = c.len_utf8() + 1;+ s.execute("text.select", &json!({"story": p3.0, "anchor": second, "focus": second + c.len_utf8()})).unwrap();+ s.execute("variables.convertToText", &json!({})).unwrap();+ let d = &s.doc().unwrap().doc;+ assert_eq!(d.story(p3).unwrap().text, format!("{c}|Epsilon"), "only the selected instance");+ assert_eq!(d.story(p1).unwrap().text, format!("{c}|{c}"));+ assert!(d.variable("Chapter Head").is_some(), "the variable stays defined");+ let t = s.doc().unwrap().selection.text.unwrap();+ assert_eq!((t.anchor, t.focus), (second, second + "Epsilon".len()), "the converted text stays selected");+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.story(p3).unwrap().text, format!("{c}|{c}"), "one undo step");+ }++ /// The menu item is enabled only for a selection that holds an instance: not a caret, not+ /// text without one.+ #[test]+ fn convert_variable_to_text_needs_a_selected_instance() {+ let (mut s, p1, _) = running_heads();+ let c = var_char(s.doc().unwrap().doc.variable("Chapter Head").unwrap()).unwrap();+ let bar = c.len_utf8();+ let enabled = |s: &Session| (crate::find_command("variables.convertToText").unwrap().enabled)(s).is_ok();+ for (anchor, focus) in [(0, 0), (bar, bar + 1)] {+ s.execute("text.select", &json!({"story": p1.0, "anchor": anchor, "focus": focus})).unwrap();+ assert!(!enabled(&s), "{anchor}..{focus}");+ }+ s.execute("text.select", &json!({"story": p1.0, "anchor": 0, "focus": bar})).unwrap();+ assert!(enabled(&s));+ }++ /// A story threaded from a frame on page 1, which holds only "Lead", to a frame on page 3,+ /// where the caret is left at the end of "Body". A cell's or a note's own byte 0 read in this+ /// story is on page 1, its anchor on page 3.+ fn threaded(s: &mut Session) -> designcraft_doc::StoryId {+ let sp1 = s.doc().unwrap().doc.page_loc(0).unwrap().0;+ let sp3 = s.doc().unwrap().doc.page_loc(2).unwrap().0;+ let r = s.execute("frame.create", &json!({"spread": sp1, "rect": [72, 500, 400, 520], "content": "text", "text": "Lead\nBody"})).unwrap();+ let from = r["id"].as_u64().unwrap();+ s.execute("text.thread", &json!({"from": from, "rect": [72, 500, 400, 700], "spread": sp3})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ let sid = d.item(designcraft_doc::ItemId(from)).unwrap().text_frame().unwrap().story;+ let cs = s.cache.get(&d, sid, None);+ let page = |pos| designcraft_compose::vars::page_of(&d, &cs, pos);+ assert_eq!((page(0), page("Lead\nB".len())), (Some(0), Some(2)), "Lead on page 1, Body on page 3");+ s.execute("text.select", &json!({"story": sid.0, "anchor": "Lead\nBody".len(), "focus": "Lead\nBody".len()})).unwrap();+ sid+ }++ /// An instance selected in a table cell becomes the value on the page of the table's anchor.+ #[test]+ fn convert_variable_to_text_in_a_table_cell() {+ let (mut s, ..) = running_heads();+ let c = var_char(s.doc().unwrap().doc.variable("Chapter Head").unwrap()).unwrap();+ let sid = threaded(&mut s);+ s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap();+ s.execute("table.setCell", &json!({"row": 0, "col": 0, "text": c.to_string()})).unwrap();+ let table = *s.doc().unwrap().doc.story(sid).unwrap().tables.keys().next().unwrap();+ let cell = designcraft_doc::CellAddr { table, row: 0, col: 0 };+ s.doc_mut().unwrap().selection =+ designcraft_doc::Selection::text(designcraft_doc::TextSel { story: sid, anchor: 0, focus: c.len_utf8(), frame: None, cell: Some(cell) });+ s.execute("variables.convertToText", &json!({})).unwrap();+ let d = &s.doc().unwrap().doc;+ assert_eq!(d.text_story(sid, Some(cell)).unwrap().text, "Epsilon");+ }++ /// An instance selected in a footnote becomes the value on the page of the note's reference.+ #[test]+ fn convert_variable_to_text_in_a_footnote() {+ let (mut s, ..) = running_heads();+ let c = var_char(s.doc().unwrap().doc.variable("Chapter Head").unwrap()).unwrap();+ let sid = threaded(&mut s);+ s.execute("footnote.insert", &json!({"text": c.to_string()})).unwrap();+ let id = s.doc().unwrap().doc.story(sid).unwrap().notes[0].id;+ let note = designcraft_doc::CellAddr::footnote(id);+ let at = s.doc().unwrap().doc.text_story(sid, Some(note)).unwrap().text.find(c).unwrap();+ s.doc_mut().unwrap().selection = designcraft_doc::Selection::text(designcraft_doc::TextSel {+ story: sid,+ anchor: at,+ focus: at + c.len_utf8(),+ frame: None,+ cell: Some(note),+ });+ s.execute("variables.convertToText", &json!({})).unwrap();+ let d = &s.doc().unwrap().doc;+ let text = &d.text_story(sid, Some(note)).unwrap().text;+ assert!(!text.contains(c) && text.ends_with("Epsilon"), "{text:?}");+ }++ /// Text Variables › Convert to Text turns every instance of the variable into the value on+ /// its page, in table cells, footnotes and endnotes on the page of their anchor, and keeps the+ /// variable.+ #[test]+ fn convert_all_instances_to_text() {+ let (mut s, p1, p3) = running_heads();+ let c = var_char(s.doc().unwrap().doc.variable("Chapter Head").unwrap()).unwrap();+ let sid = threaded(&mut s);+ let at_end = |s: &mut Session| {+ let n = s.doc().unwrap().doc.story(sid).unwrap().len();+ s.execute("text.select", &json!({"story": sid.0, "anchor": n, "focus": n})).unwrap();+ };+ s.execute("footnote.insert", &json!({"text": c.to_string()})).unwrap();+ at_end(&mut s);+ s.execute("endnote.insert", &json!({"text": c.to_string()})).unwrap();+ at_end(&mut s);+ s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap();+ s.execute("table.setCell", &json!({"row": 0, "col": 0, "text": c.to_string()})).unwrap();+ s.execute("variables.convertAllToText", &json!({"name": "Chapter Head"})).unwrap();+ let d = &s.doc().unwrap().doc;+ assert_eq!(d.story(p1).unwrap().text, "Alpha|Alpha");+ assert_eq!(d.story(p3).unwrap().text, "Epsilon|Epsilon");+ let st = d.story(sid).unwrap();+ assert_eq!(st.tables.values().next().unwrap().cells[0].text.text, "Epsilon", "table cell");+ assert!(st.notes[0].text.text.ends_with("Epsilon"), "footnote: {:?}", st.notes[0].text.text);+ assert!(st.endnotes[0].text.text.ends_with("Epsilon"), "endnote: {:?}", st.endnotes[0].text.text);+ assert!(d.variable("Chapter Head").is_some(), "the variable stays defined");+ }++ /// A caret in a table cell or a footnote after an instance stays after the value Convert to+ /// Text writes there, so typing lands after it.+ #[test]+ fn convert_all_keeps_the_caret_in_a_cell_or_a_footnote() {+ for footnote in [false, true] {+ let (mut s, ..) = running_heads();+ let c = var_char(s.doc().unwrap().doc.variable("Chapter Head").unwrap()).unwrap();+ let sid = threaded(&mut s);+ let text = format!("{c}|");+ let at = if footnote {+ s.execute("footnote.insert", &json!({"text": text})).unwrap();+ designcraft_doc::CellAddr::footnote(s.doc().unwrap().doc.story(sid).unwrap().notes[0].id)+ } else {+ s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap();+ s.execute("table.setCell", &json!({"row": 0, "col": 0, "text": text})).unwrap();+ let table = *s.doc().unwrap().doc.story(sid).unwrap().tables.keys().next().unwrap();+ designcraft_doc::CellAddr { table, row: 0, col: 0 }+ };+ let n = s.doc().unwrap().doc.text_story(sid, Some(at)).unwrap().text.len();+ s.doc_mut().unwrap().selection =+ designcraft_doc::Selection::text(designcraft_doc::TextSel { story: sid, anchor: n, focus: n, frame: None, cell: Some(at) });+ s.execute("variables.convertAllToText", &json!({"name": "Chapter Head"})).unwrap();+ s.execute("text.insert", &json!({"text": "x"})).unwrap();+ let text = &s.doc().unwrap().doc.text_story(sid, Some(at)).unwrap().text;+ assert!(text.ends_with("Epsilon|x"), "footnote {footnote}: {text:?}");+ }+ }++ /// Deleting a variable flattens its instances in table cells too and moves the instances of+ /// later variables down, so cells keep showing the same text.+ #[test]+ fn delete_variable_reaches_table_cells() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("variables.define", &json!({"name": "A", "type": "custom", "text": "Alpha"})).unwrap();+ let b = s.execute("variables.define", &json!({"name": "B", "type": "custom", "text": "Beta"})).unwrap()["index"].as_u64().unwrap() as usize;+ let a = s.doc().unwrap().doc.variable("A").unwrap();+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": ""})).unwrap();+ let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();+ s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap();+ let text = format!("{}|{}", var_char(a).unwrap(), var_char(b).unwrap());+ s.execute("table.setCell", &json!({"row": 0, "col": 0, "text": text})).unwrap();+ s.execute("variables.delete", &json!({"name": "A"})).unwrap();+ let d = &s.doc().unwrap().doc;+ let t = d.story(sid).unwrap().tables.values().next().unwrap();+ let nb = d.variable("B").unwrap();+ assert_eq!(t.cells[0].text.text, format!("Alpha|{}", var_char(nb).unwrap()));+ }++ /// Deleting a variable flattens its instances in footnotes and endnotes too and moves the+ /// instances of later variables down.+ #[test]+ fn delete_variable_reaches_notes() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("variables.define", &json!({"name": "A", "type": "custom", "text": "Alpha"})).unwrap();+ let b = s.execute("variables.define", &json!({"name": "B", "type": "custom", "text": "Beta"})).unwrap()["index"].as_u64().unwrap() as usize;+ let a = s.doc().unwrap().doc.variable("A").unwrap();+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "x"})).unwrap();+ let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;+ let text = format!("{}|{}", var_char(a).unwrap(), var_char(b).unwrap());+ s.execute("text.select", &json!({"story": sid.0, "anchor": 1, "focus": 1})).unwrap();+ s.execute("footnote.insert", &json!({"text": text})).unwrap();+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();+ s.execute("endnote.insert", &json!({"text": text})).unwrap();+ s.execute("variables.delete", &json!({"name": "A"})).unwrap();+ let d = &s.doc().unwrap().doc;+ let st = d.story(sid).unwrap();+ let want = format!("Alpha|{}", var_char(d.variable("B").unwrap()).unwrap());+ assert_eq!(st.notes[0].text.text, want);+ assert_eq!(st.endnotes[0].text.text, want);+ }++ #[test]+ fn running_header_on_parent_page_follows_headings() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 3, "facingPages": false})).unwrap();+ s.execute("style.paragraph.create", &json!({"name": "Heading"})).ok();+ // Headings on pages 1 and 3 (page 2 carries page 1's).+ for (page, text) in [(0, "Alpha"), (2, "Epsilon")] {+ let sp = s.doc().unwrap().doc.page_loc(page).unwrap().0;+ let r = s.execute("frame.create", &json!({"spread": sp, "rect": [72, 200, 400, 260], "content": "text", "text": text})).unwrap();+ let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 1})).unwrap();+ s.execute("style.paragraph.apply", &json!({"name": "Heading"})).unwrap();+ }+ s.execute("variables.define", &json!({"name": "Chapter Head", "type": "runningHeader", "style": "Heading"})).unwrap();+ s.execute("variables.define", &json!({"name": "Total", "type": "custom", "text": "of "})).unwrap();+ // A header frame on the parent with "<running header> · <page> / <last page>".+ let r = s+ .execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 30, 500, 60], "content": "text", "text": ""}))+ .unwrap();+ let fid = designcraft_doc::ItemId(r["id"].as_u64().unwrap());+ let sid = s.doc().unwrap().doc.item(fid).unwrap().text_frame().unwrap().story;+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();+ s.execute("variables.insert", &json!({"name": "Chapter Head"})).unwrap();+ s.execute("text.insert", &json!({"text": " · "})).unwrap();+ s.execute("variables.insert", &json!({"name": "Last Page Number"})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ assert!(matches!(d.find(fid).unwrap().spread, designcraft_doc::SpreadRef::Parent(0)));+ // Visible glyphs of the header composed for each page: "Alpha · 3" vs "Epsilon · 3".+ let shown = |page: usize| -> usize {+ let cs = s.cache.get(&d, sid, Some(page));+ cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum()+ };+ let (p1, p2, p3) = (shown(0), shown(1), shown(2));+ assert_eq!(p1, p2, "page 2 carries page 1's header");+ assert_eq!(p3, p1 + 2, "Epsilon is two letters longer than Alpha");+ let idx = s.cache.running_index(&d);+ assert_eq!(idx.value("Heading", false, Default::default(), 0), "Alpha");+ assert_eq!(idx.value("Heading", false, Default::default(), 1), "Alpha");+ assert_eq!(idx.value("Heading", false, Default::default(), 2), "Epsilon");+ let list = s.execute("variables.list", &json!({})).unwrap();+ assert!(list.as_array().unwrap().iter().any(|v| v["name"] == "Last Page Number" && v["value"] == "3"));++ // On the parent page itself the header shows which variable it holds, not a blank.++ let head = d.variable("Chapter Head").unwrap();++ assert_eq!(crate::compose::vars::values(&d, None, Some(&idx))[head], "<Chapter Head>");++ assert_eq!(crate::compose::vars::values(&d, Some(2), Some(&idx))[head], "Epsilon");++ assert!(shown_on_parent(&s, &d, sid) > p1, "the parent shows <Chapter Head>, longer than Alpha");+ // Deleting a variable flattens its instances to text.+ s.execute("variables.delete", &json!({"name": "Last Page Number"})).unwrap();+ assert!(s.doc().unwrap().doc.story(sid).unwrap().text.ends_with(" · 3"));+ }diff --cc crates/ui-egui/src/canvas/frames.rsindex 000000000,4ff09ab98..e5be4f7c6mode 000000,100644..100644--- a/crates/ui-egui/src/canvas/frames.rs+++ b/crates/ui-egui/src/canvas/frames.rs@@@ -1,0 -1,378 +1,381 @@@+ use super::page_decor::dashed;+ use super::render::c32;+ use super::rulers::hair;+ use super::text_overlay::draw_text_selection;+ use super::{+ Affine, CanvasLayout, Color32, Content, DRect, DesignApp, Document, Item, Point, Pos2, Rect, Selection, Stroke, StrokeKind, Xf, compose, pos2,+ vec2,+ };++ /// Spread-space → canvas transform for an item at `loc`.+ pub(super) fn item_canvas_xf(doc: &Document, layout: &CanvasLayout, id: designcraft_doc::ItemId) -> Option<(Affine, &'static str)> {+ let loc = doc.find(id)?;- Some((layout.xf(loc.spread) * doc.parent_xf(&loc), ""))++ // Items on spreads that aren't laid out (document pages while parents are being edited, or++ // the reverse) have no place on the canvas.++ let slot = layout.slot(loc.spread)?;++ Some((slot.xf * doc.parent_xf(&loc), ""))+ }++ pub(super) fn path_screen(it: &Item, xf: &Xf, a: Affine) -> Vec<Vec<Pos2>> {+ let bp = it.path.to_bezpath();+ let full = a * it.xf;+ let mut out = Vec::new();+ let mut cur: Vec<Pos2> = Vec::new();+ designcraft_geom::kurbo::flatten(&bp, 0.25 / xf.zoom.max(0.01), |el| {+ use designcraft_geom::PathEl::*;+ match el {+ MoveTo(p) => {+ if cur.len() > 1 {+ out.push(std::mem::take(&mut cur));+ }+ cur.clear();+ cur.push(xf.to_screen(full * p));+ }+ LineTo(p) => cur.push(xf.to_screen(full * p)),+ ClosePath => {+ if let Some(f) = cur.first().copied() {+ cur.push(f);+ }+ }+ _ => {}+ }+ });+ if cur.len() > 1 {+ out.push(cur);+ }+ out+ }++ pub(super) fn draw_frames(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document, layout: &CanvasLayout) {+ if !app.ui.frame_edges {+ return;+ }+ let ported = ported_frames(app, doc);+ for slot in &layout.slots {+ let Some(sp) = doc.spread(slot.spread) else { continue };+ let a = slot.xf;+ // Parent items on document pages, and base parents' items on a parent spread: dotted edges.+ for (pi, page) in sp.pages.iter().enumerate() {+ for (ppi, ppg) in doc.shown_parent_pages(slot.spread, pi) {+ let Some(parent) = doc.parents.get(ppi) else { continue };+ let Some(ppage) = parent.pages.get(ppg) else { continue };+ let dx = page.x - ppage.x;+ for it in &parent.items {+ if (parent.pages.len() > 1 && parent.page_at_x(it.bounds().center().x) != Some(ppg)) || page.overridden.contains(&it.id) {+ continue;+ }+ let col = doc.layer(it.layer).map(|l| c32(l.color)).unwrap_or(Color32::LIGHT_BLUE);+ for poly in path_screen(it, xf, a * Affine::translate((dx, 0.0))) {+ for w in poly.windows(2) {+ dashed(painter, w[0], w[1], Stroke::new(hair(painter), col.gamma_multiply(0.8)), 2.0, 2.0);+ }+ }+ }+ }+ }+ for it in &sp.items {+ draw_item_edges(painter, xf, doc, it, a);+ }+ // Every overset frame, selected or not and inside groups too, shows its red mark at the+ // out port (InDesign shows it only on the selected frame; a report in Preflight is easy+ // to miss while laying out).+ for (it, c) in overset_marks(app, doc, layout, &sp.items, xf.zoom, &ported) {+ let c = xf.to_screen(c);+ let s = designcraft_tools::thread::PORT_SIZE_PX as f32;+ painter.rect_filled(Rect::from_center_size(c, vec2(s, s)), 0.0, Color32::WHITE);+ painter.rect_stroke(Rect::from_center_size(c, vec2(s, s)), 0.0, Stroke::new(hair(painter), layer_color(doc, it)), StrokeKind::Inside);+ let red = Color32::from_rgb(230, 20, 20);+ painter.line_segment([c - vec2(2.5, 0.0), c + vec2(2.5, 0.0)], Stroke::new(1.5, red));+ painter.line_segment([c - vec2(0.0, 2.5), c + vec2(0.0, 2.5)], Stroke::new(1.5, red));+ }+ // Tagged frames in their tag's colour.+ if app.ui.tagged_frames {+ for top in &sp.items {+ top.walk(&mut |it: &Item| {+ if it.xml_tag.is_empty() {+ return;+ }+ let Some(t) = doc.xml.tags.iter().find(|t| t.name == it.xml_tag) else { return };+ let col = Color32::from_rgb(t.color[0], t.color[1], t.color[2]);+ for poly in path_screen(it, xf, a) {+ for w in poly.windows(2) {+ painter.line_segment([w[0], w[1]], Stroke::new(2.5, col));+ }+ }+ });+ }+ }+ }+ }++ fn draw_item_edges(painter: &egui::Painter, xf: &Xf, doc: &Document, it: &Item, a: Affine) {+ if it.hidden || doc.layer(it.layer).is_some_and(|l| !l.visible) {+ return;+ }+ let col = doc.layer(it.layer).map(|l| c32(l.color)).unwrap_or(Color32::LIGHT_BLUE);+ if let Content::Group { items } = &it.content {+ for c in items {+ draw_item_edges(painter, xf, doc, c, a * it.xf);+ }+ return;+ }+ // Frames without a stroke show their edge; shapes with strokes are visible already.+ let show = it.stroke.is_none() || matches!(it.content, Content::Text(_) | Content::Graphic(_));+ if show {+ for poly in path_screen(it, xf, a) {+ painter.add(egui::Shape::line(poly, Stroke::new(hair(painter), col.gamma_multiply(0.75))));+ }+ }+ // Empty graphic frame: the X.+ if it.object_style == designcraft_doc::BASIC_GRAPHICS_FRAME && matches!(it.content, Content::Unassigned) {+ let r = it.inner_bounds();+ let m = a * it.xf;+ let p = |x: f64, y: f64| xf.to_screen(m * Point::new(x, y));+ painter.line_segment([p(r.x0, r.y0), p(r.x1, r.y1)], Stroke::new(hair(painter), col.gamma_multiply(0.75)));+ painter.line_segment([p(r.x1, r.y0), p(r.x0, r.y1)], Stroke::new(hair(painter), col.gamma_multiply(0.75)));+ }+ }++ /// Layer colour of the first selected item: live-corner marks are outlined in it.+ pub(super) fn selection_color(app: &DesignApp) -> Color32 {+ let fallback = Color32::from_rgb(79, 153, 255);+ let Some(st) = app.session.active() else { return fallback };+ st.selection.items.first().and_then(|id| st.doc.item(*id)).map_or(fallback, |it| layer_color(&st.doc, it))+ }++ pub(super) fn layer_color(doc: &Document, it: &Item) -> Color32 {+ doc.layer(it.layer).map(|l| c32(l.color)).unwrap_or(Color32::from_rgb(79, 153, 255))+ }++ /// Draw selection chrome; returns the selection's screen bounds (for the Contextual Task Bar).+ pub(super) fn draw_selection(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document, layout: &CanvasLayout) -> Option<Rect> {+ let st = app.session.active()?;+ let sel: &Selection = &st.selection;+ let mut text_rect = None;+ // Text selection / caret.+ if let Some(ts) = sel.text {+ draw_text_selection(app, painter, xf, doc, layout, ts, sel.cells);+ let fid = ts.frame.or_else(|| {+ let cs = app.session.cache.get(doc, ts.story, None);+ compose::caret(&cs, ts.focus).and_then(|c| cs.frames.get(c.0)).map(|f| f.frame)+ });+ if let Some(fid) = fid+ && let (Some(it), Some((a, _))) = (doc.item(fid), item_canvas_xf(doc, layout, fid))+ {+ text_rect = Some(xf.rect(a.transform_rect_bbox(it.bounds())));+ }+ }+ let mut union: Option<Rect> = None;+ let mut color = Color32::from_rgb(79, 153, 255);+ for id in &sel.items {+ let (Some(it), Some((a, _))) = (doc.item(*id), item_canvas_xf(doc, layout, *id)) else { continue };+ color = layer_color(doc, it);+ for poly in path_screen(it, xf, a) {+ painter.add(egui::Shape::line(poly, Stroke::new(1.0, color)));+ }+ if sel.items.len() == 1 && sel.text.is_none() {+ // InDesign draws a 1 pt bounding box around the selection.+ painter.rect_stroke(xf.rect(a.transform_rect_bbox(it.bounds())), 0.0, Stroke::new(1.0, color), StrokeKind::Middle);+ } else if sel.key == Some(*id) {+ // The key object for Align: a thicker bounding box, as in InDesign.+ painter.rect_stroke(xf.rect(a.transform_rect_bbox(it.bounds())), 0.0, Stroke::new(3.0, color), StrokeKind::Middle);+ }+ let b = xf.rect(a.transform_rect_bbox(it.bounds()));+ union = Some(union.map_or(b, |u| u.union(b)));+ // Text frame ports, also of the frames inside a selected group (so an overset frame in a+ // group shows its red mark).+ let mut frames = Vec::new();+ text_frames_in(it, 0, &mut frames);+ for (frame, story) in frames {+ draw_ports(app, painter, xf, doc, layout, frame, story, color);+ }+ if let Content::Graphic(g) = &it.content+ && sel.content+ {+ let gb = xf.rect((a * it.xf).transform_rect_bbox(g.xf.transform_rect_bbox(DRect::new(0.0, 0.0, g.size.0, g.size.1))));+ let brown = Color32::from_rgb(196, 111, 43);+ painter.rect_stroke(gb, 0.0, Stroke::new(1.0, brown), StrokeKind::Middle);+ // Its own handles resize the graphic (InDesign's brown content bounding box).+ if sel.items.len() == 1 {+ for h in designcraft_tools::select::handles(DRect::new(gb.min.x as f64, gb.min.y as f64, gb.max.x as f64, gb.max.y as f64)) {+ let r = Rect::from_center_size(pos2(h.x as f32, h.y as f32), vec2(6.5, 6.5));+ painter.rect_filled(r, 0.0, Color32::WHITE);+ painter.rect_stroke(r, 0.0, Stroke::new(hair(painter), brown), StrokeKind::Inside);+ }+ }+ }+ }+ let direct = matches!(app.session.tool_id(), "directSelection" | "pen" | "addAnchor" | "deleteAnchor" | "convertDirection");+ if direct {+ for id in &sel.items {+ let (Some(it), Some((a, _))) = (doc.item(*id), item_canvas_xf(doc, layout, *id)) else { continue };+ let m = a * it.xf;+ let col = layer_color(doc, it);+ for sp in &it.path.subpaths {+ for an in &sp.anchors {+ let p = xf.to_screen(m * an.p);+ for (h, has) in [(an.h_in, an.has_in()), (an.h_out, an.has_out())] {+ if has {+ let hp = xf.to_screen(m * h);+ painter.line_segment([p, hp], Stroke::new(1.0, col));+ painter.circle_filled(hp, 2.5, col);+ }+ }+ let r = Rect::from_center_size(p, vec2(5.0, 5.0));+ painter.rect_filled(r, 0.0, Color32::WHITE);+ painter.rect_stroke(r, 0.0, Stroke::new(1.0, col), StrokeKind::Inside);+ }+ }+ }+ }+ if let Some(u) = union+ && sel.text.is_none()+ && !direct+ {+ if sel.items.len() > 1 {+ painter.rect_stroke(u, 0.0, Stroke::new(1.0, color), StrokeKind::Middle);+ }+ let hs = 6.5;+ // Centre point. The Selection tool draws the live-corner widget as an overlay.+ painter.rect_filled(Rect::from_center_size(u.center(), vec2(3.5, 3.5)), 0.0, color);+ // A selected placed graphic has its own handles instead of the frame's.+ let graphic_selected =+ sel.content && sel.items.len() == 1 && doc.item(sel.items[0]).is_some_and(|i| matches!(i.content, Content::Graphic(_)));+ for h in designcraft_tools::select::handles(DRect::new(u.min.x as f64, u.min.y as f64, u.max.x as f64, u.max.y as f64))+ .into_iter()+ .filter(|_| !graphic_selected)+ {+ let r = Rect::from_center_size(pos2(h.x as f32, h.y as f32), vec2(hs, hs));+ painter.rect_filled(r, 0.0, Color32::WHITE);+ painter.rect_stroke(r, 0.0, Stroke::new(hair(painter), color), StrokeKind::Inside);+ }+ }+ // Threads.+ if app.ui.text_threads || sel.items.iter().any(|i| doc.item(*i).is_some_and(|x| x.is_text_frame())) {+ for id in &sel.items {+ let Some(sid) = doc.item(*id).and_then(|i| i.text_frame()).map(|t| t.story) else { continue };+ let Some(story) = doc.story(sid) else { continue };+ for w in story.frames.windows(2) {+ let (Some(a), Some(b)) = (port_pos(doc, layout, w[0], true), port_pos(doc, layout, w[1], false)) else { continue };+ let col = doc.item(w[0]).map(|i| layer_color(doc, i)).unwrap_or(color);+ painter.line_segment([xf.to_screen(a), xf.to_screen(b)], Stroke::new(1.0, col));+ }+ }+ }+ text_rect.or(union)+ }++ /// How deep a selected group is walked for the text frames whose ports are drawn.+ const PORT_GROUP_DEPTH: usize = 32;++ /// The text frames whose ports `draw_selection` draws: the selected text frames and the text+ /// frames inside selected groups.+ pub(super) fn ported_frames(app: &DesignApp, doc: &Document) -> std::collections::HashSet<designcraft_doc::ItemId> {+ let mut frames = Vec::new();+ if let Some(st) = app.session.active() {+ for it in st.selection.items.iter().filter_map(|id| doc.item(*id)) {+ text_frames_in(it, 0, &mut frames);+ }+ }+ frames.into_iter().map(|(f, _)| f.id).collect()+ }++ /// Canvas centres of the always-on overset marks among `items`: the out port of every visible+ /// frame that ends an overset story, except the frames in `ported`, whose out port `draw_ports`+ /// already marks.+ pub(super) fn overset_marks<'a>(+ app: &DesignApp,+ doc: &Document,+ layout: &CanvasLayout,+ items: &'a [std::sync::Arc<Item>],+ zoom: f64,+ ported: &std::collections::HashSet<designcraft_doc::ItemId>,+ ) -> Vec<(&'a Item, Point)> {+ let mut frames = Vec::new();+ overset_frames(app, doc, items, 0, &mut frames);+ frames+ .into_iter()+ .filter(|it| !ported.contains(&it.id))+ .filter_map(|it| Some((it, designcraft_tools::thread::port_center(doc, layout, it.id, true, zoom)?)))+ .collect()+ }++ /// The visible text frames among `items` (groups walked) that end an overset story.+ pub(super) fn overset_frames<'a>(app: &DesignApp, doc: &Document, items: &'a [std::sync::Arc<Item>], depth: usize, out: &mut Vec<&'a Item>) {+ if depth > PORT_GROUP_DEPTH {+ return;+ }+ for it in items {+ if it.hidden || doc.layer(it.layer).is_some_and(|l| !l.visible) {+ continue;+ }+ match &it.content {+ Content::Text(tf) => {+ let Some(story) = doc.story(tf.story) else { continue };+ if story.frames.last() == Some(&it.id) && app.session.cache.get(doc, tf.story, None).is_overset() {+ out.push(it);+ }+ }+ Content::Group { items } => overset_frames(app, doc, items, depth + 1, out),+ _ => {}+ }+ }+ }++ /// `it` when it is a text frame, or every text frame nested in it when it is a group, each with+ /// its story.+ pub(super) fn text_frames_in<'a>(it: &'a Item, depth: usize, out: &mut Vec<(&'a Item, designcraft_doc::StoryId)>) {+ match &it.content {+ Content::Text(tf) => out.push((it, tf.story)),+ Content::Group { items } if depth < PORT_GROUP_DEPTH => {+ for child in items {+ text_frames_in(child, depth + 1, out);+ }+ }+ _ => {}+ }+ }++ /// Port location (canvas): out port at bottom-right, in port at top-left.+ fn port_pos(doc: &Document, layout: &CanvasLayout, id: designcraft_doc::ItemId, out: bool) -> Option<Point> {+ let it = doc.item(id)?;+ let (a, _) = item_canvas_xf(doc, layout, id)?;+ let r = it.inner_bounds();+ let p = if out { Point::new(r.x1 - 10.0, r.y1) } else { Point::new(r.x0 + 10.0, r.y0) };+ Some(a * it.xf * p)+ }++ #[allow(clippy::too_many_arguments)]+ fn draw_ports(+ app: &DesignApp,+ painter: &egui::Painter,+ xf: &Xf,+ doc: &Document,+ layout: &CanvasLayout,+ it: &Item,+ sid: designcraft_doc::StoryId,+ color: Color32,+ ) {+ let Some(story) = doc.story(sid) else { return };+ let pos = story.frames.iter().position(|f| *f == it.id).unwrap_or(0);+ let is_last = pos + 1 == story.frames.len();+ let cs = app.session.cache.get(doc, sid, None);+ let overset = is_last && cs.is_overset();+ let s = designcraft_tools::thread::PORT_SIZE_PX as f32;+ // In port on the left edge below the top-left corner; out port on the right edge above the+ // bottom-right corner. The Selection tool hit-tests the same places.+ let port = |out: bool| designcraft_tools::thread::port_center(doc, layout, it.id, out, xf.zoom).map(|c| xf.to_screen(c));+ let (Some(inp), Some(outp)) = (port(false), port(true)) else { return };+ for (c, has_link, is_out) in [(inp, pos > 0, false), (outp, !is_last, true)] {+ let pr = Rect::from_center_size(c, vec2(s, s));+ painter.rect_filled(pr, 0.0, Color32::WHITE);+ painter.rect_stroke(pr, 0.0, Stroke::new(hair(painter), color), StrokeKind::Inside);+ if is_out && overset {+ let red = Color32::from_rgb(230, 20, 20);+ painter.line_segment([c - vec2(2.5, 0.0), c + vec2(2.5, 0.0)], Stroke::new(1.5, red));+ painter.line_segment([c - vec2(0.0, 2.5), c + vec2(0.0, 2.5)], Stroke::new(1.5, red));+ } else if has_link {+ painter.add(egui::Shape::convex_polygon(vec![c + vec2(-2.0, -2.5), c + vec2(2.5, 0.0), c + vec2(-2.0, 2.5)], color, Stroke::NONE));+ }+ }+ }diff --cc crates/ui-egui/src/canvas/tests.rsindex 000000000,01300bdd0..ae53bfdc0mode 000000,100644..100644--- a/crates/ui-egui/src/canvas/tests.rs+++ b/crates/ui-egui/src/canvas/tests.rs@@@ -1,0 -1,2839 +1,2864 @@@+ use designcraft_geom::Unit;+ use egui_kittest::{Harness, kittest::Queryable};++ use super::*;++ #[test]+ fn a_press_after_a_drag_is_not_a_double_click() {+ let (delay, dist) = (0.3, 6.0);+ let press = |last, x: f32, now| press_count(last, pos2(x, 0.0), now, delay, dist);+ // Click, click: a double click.+ let n = press(None, 0.0, 0.0);+ let up = release_clicks(Clicks { at: f64::NEG_INFINITY, pos: pos2(0.0, 0.0), n }, pos2(0.0, 0.0), 0.1, dist);+ assert_eq!(press(Some(up), 1.0, 0.2), 2);+ // A drag from 0 to 100, then a fast press where it started or where it ended: a single click.+ let up = release_clicks(Clicks { at: f64::NEG_INFINITY, pos: pos2(0.0, 0.0), n: 1 }, pos2(100.0, 0.0), 0.1, dist);+ assert_eq!(press(Some(up), 0.0, 0.2), 1);+ assert_eq!(press(Some(up), 100.0, 0.2), 1);+ // Too slow: a single click.+ let up = release_clicks(Clicks { at: f64::NEG_INFINITY, pos: pos2(0.0, 0.0), n: 1 }, pos2(0.0, 0.0), 0.1, dist);+ assert_eq!(press(Some(up), 0.0, 1.0), 1);+ }++ /// While a page's render is on its way the page shows paper, not the black of its shadow.+ #[test]+ fn pages_show_paper_under_their_render() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", serde_json::json!({"pages": 3, "facingPages": true})).unwrap();+ let ctx = egui::Context::default();+ let mut shapes = Vec::new();+ for _ in 0..2 {+ let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui));+ out.textures_delta.clear();+ shapes = out.shapes;+ }+ let st = app.session.active().unwrap();+ let layout = CanvasLayout::new(&st.doc, false);+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());+ // The paper swatch on screen (white, as the colour settings show it).+ let [r, g, b, _] = st.doc.resolve_color(designcraft_color::swatch::PAPER, 1.0).unwrap().to_rgba8(1.0);+ let paper: Vec<Rect> = shapes+ .iter()+ .filter_map(|c| match &c.shape {+ egui::Shape::Rect(s) if s.fill == Color32::from_rgb(r, g, b) => Some(s.rect),+ _ => None,+ })+ .collect();+ // Each page on its own (a spread's pages may differ in size).+ assert_eq!(paper.len(), st.doc.page_count());+ for abs in 0..st.doc.page_count() {+ let want = xf.rect(layout.page_rect(&st.doc, abs).unwrap());+ assert!(paper.iter().any(|r| (r.min - want.min).length() < 0.01 && (r.max - want.max).length() < 0.01), "page {abs}");+ }+ }++ /// Bleed and Slug are preview modes: like Preview they hide the guides, and what the page+ /// shows widens to the bleed or the slug box. The slug guide is drawn in Normal, in its own+ /// colour, beside the bleed guide.+ #[test]+ fn bleed_and_slug_are_preview_modes_that_show_their_area() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", serde_json::json!({"bleed": 9, "slug": 18})).unwrap();+ let strokes = |app: &mut DesignApp, want: [u8; 3]| -> usize {+ let ctx = egui::Context::default();+ let mut shapes = Vec::new();+ for _ in 0..2 {+ let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(raw, |ui| show(app, ui));+ out.textures_delta.clear();+ shapes = out.shapes;+ }+ let want = c32(want);+ shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Rect(s) if s.stroke.color == want)).count()+ };+ let s = app.session.active().unwrap().doc.settings.clone();+ // Normal draws every guide, the slug's among them.+ app.ui.screen_mode = ScreenMode::Normal;+ assert!(strokes(&mut app, s.margin_color) > 0, "Normal draws the margin guide");+ assert!(strokes(&mut app, s.bleed_color) > 0, "Normal draws the bleed guide");+ assert!(strokes(&mut app, s.slug_color) > 0, "Normal draws the slug guide");+ // Every preview mode hides them.+ for mode in [ScreenMode::Preview, ScreenMode::Bleed, ScreenMode::Slug, ScreenMode::Presentation] {+ app.ui.screen_mode = mode;+ assert_eq!(strokes(&mut app, s.margin_color), 0, "{mode:?} hides the margin guide");+ assert_eq!(strokes(&mut app, s.slug_color), 0, "{mode:?} hides the slug guide");+ }+ }++ /// Each preview mode's shown area: Preview stops at the trim, Bleed reaches the bleed box and+ /// Slug the slug box. A slug narrower than the bleed never pulls the edge back in.+ #[test]+ fn shown_area_widens_to_the_bleed_and_slug_boxes() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", serde_json::json!({"bleed": 9, "slug": 18})).unwrap();+ let doc = app.session.active().unwrap().doc.clone();+ let layout = CanvasLayout::new(&doc, false);+ let xf = Xf::new(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0)), &View::default());+ let slot = &layout.slots[0];+ let area = |app: &mut DesignApp, mode| {+ app.ui.screen_mode = mode;+ shown_area(app, &doc, &xf, slot)+ };+ let trim = xf.rect(slot.bounds);+ assert_eq!(area(&mut app, ScreenMode::Preview), trim, "Preview stops at the trim");+ assert_eq!(area(&mut app, ScreenMode::Presentation), trim, "Presentation stops at the trim");+ let bleed = area(&mut app, ScreenMode::Bleed);+ let slug = area(&mut app, ScreenMode::Slug);+ assert!(bleed.contains_rect(trim) && bleed != trim, "Bleed reaches past the trim");+ assert!(slug.contains_rect(bleed) && slug != bleed, "Slug reaches past the bleed");+ // 9 pt of bleed and 18 pt of slug at this zoom, on every edge.+ let grew = |r: Rect, pt: f64| {+ let d = (pt * xf.zoom) as f32;+ (r.min - trim.min + vec2(d, d)).length() < 0.01 && (r.max - trim.max - vec2(d, d)).length() < 0.01+ };+ assert!(grew(bleed, 9.0), "Bleed grows by the bleed: {bleed:?}");+ assert!(grew(slug, 18.0), "Slug grows by the slug: {slug:?}");+ // A slug inside the bleed: Slug still shows every printing element, so the bleed too.+ app.run("file.new", serde_json::json!({"bleed": 18, "slug": 9})).unwrap();+ let doc = app.session.active().unwrap().doc.clone();+ app.ui.screen_mode = ScreenMode::Slug;+ assert!(grew(shown_area(&app, &doc, &xf, slot), 18.0), "the wider of the two boxes wins");+ // No bleed and no slug: nothing to widen to.+ app.run("file.new", serde_json::json!({})).unwrap();+ let doc = app.session.active().unwrap().doc.clone();+ for mode in [ScreenMode::Bleed, ScreenMode::Slug] {+ app.ui.screen_mode = mode;+ assert_eq!(shown_area(&app, &doc, &xf, slot), trim, "{mode:?} without a bleed or slug");+ }+ }++ /// Build the four-fps app harness used by canvas tests.+ fn harness(app: DesignApp) -> Harness<'static, DesignApp> {+ harness_with_step(app, 1.0 / 4.0)+ }++ /// A window whose frames last `step_dt` seconds. Wheel motion is tested at a realistic frame+ /// rate: egui ends a scroll action after 150 ms without wheel events, so quarter-second+ /// frames would split every motion into separate actions.+ fn harness_with_step(app: DesignApp, step_dt: f32) -> Harness<'static, DesignApp> {+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(step_dt).build_ui_state(+ |ui, app: &mut DesignApp| {+ let ctx = ui.ctx().clone();+ app.logic(&ctx);+ app.ui(ui);+ },+ app,+ );+ h.run_steps(4);+ h+ }++ #[test]+ fn display_option_change_drops_the_render_in_flight() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let shown = crate::Shown { doc: (1, 2, 3, false), origin: Point::new(0.0, 0.0), zoom: 1.0, size: (10.0, 10.0), editing_parents: false };+ invalidate_on_display_change(&mut app);+ app.canvas.shown = Some(shown);+ app.canvas.pending = Some((7, shown));+ // Nothing changed: the texture and the request stay.+ invalidate_on_display_change(&mut app);+ assert!(app.canvas.shown.is_some() && app.canvas.pending.is_some());+ // A display option changed while the render ran: its result must not be accepted.+ app.ui.display_quality = designcraft_render::DisplayQuality::Fast;+ invalidate_on_display_change(&mut app);+ assert!(app.canvas.shown.is_none() && app.canvas.pending.is_none() && app.canvas.pending_doc.is_none());+ // The document grid is drawn into the texture too.+ app.canvas.shown = Some(shown);+ app.ui.document_grid = !app.ui.document_grid;+ invalidate_on_display_change(&mut app);+ assert!(app.canvas.shown.is_none());+ }++ /// A primary-button drag from `a` to `b` over a few frames.+ fn drag(h: &mut Harness<'_, DesignApp>, a: Pos2, b: Pos2) {+ h.hover_at(a);+ h.step();+ h.event(egui::Event::PointerButton { pos: a, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });+ h.step();+ for k in 1..=4 {+ h.hover_at(a + (b - a) * (k as f32 / 4.0));+ h.step();+ }+ h.event(egui::Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });+ h.run_steps(3);+ }++ #[test]+ fn the_page_tool_draws_liquid_guides_from_the_rulers() {+ // Chris Cicchino's Page Tool and Liquid Layout video (11:00): with the Page tool, a guide+ // dragged from the ruler is a liquid guide (dashed).+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.session.set_tool("page");+ let mut h = harness(app);+ let r = h.state().canvas_rect.unwrap();+ let guides = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.spreads[0].pages[0].guides.clone();+ drag(&mut h, pos2(r.center().x, r.min.y - 8.0), r.center());+ let g = guides(&h);+ assert_eq!(g.len(), 1, "{g:?}");+ assert!(g[0].liquid && g[0].orientation == designcraft_doc::Orientation::Horizontal);+ // With the Selection tool it's a ruler guide.+ h.state_mut().session.set_tool("selection");+ drag(&mut h, pos2(r.center().x, r.min.y - 8.0), r.center() + vec2(0.0, 40.0));+ let g = guides(&h);+ assert_eq!(g.len(), 2);+ assert!(!g[1].liquid);+ }++ /// Dragging a column guide with the Selection tool moves its gutter (one undo step); with+ /// column guides locked the same drag leaves the columns alone.+ #[test]+ fn the_selection_tool_drags_a_column_guide() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ // Two columns across the 540 pt margin box: the gutter's left edge is at x = 300.+ app.run("layout.marginsAndColumns", json!({"parent": "A", "columns": 2, "gutter": 12})).unwrap();+ let mut h = harness(app);+ let page = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.spreads[0].pages[0].clone();+ let screen = |h: &Harness<'_, DesignApp>, x: f64| {+ let app = h.state();+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());+ let layout = CanvasLayout::new(&app.session.active().unwrap().doc, false);+ let slot = layout.slots.iter().find(|s| s.spread == SpreadRef::Doc(0)).unwrap();+ (xf.to_screen(slot.xf * Point::new(x, 400.0)), xf.zoom as f32)+ };+ let (at, zoom) = screen(&h, 300.0);+ drag(&mut h, at, at + vec2(72.0 * zoom, 0.0));+ assert_eq!(page(&h).columns.positions, None, "column guides are locked in a new document");+ h.hover_at(at);+ h.run_steps(2);+ assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeHorizontal);++ h.state_mut().run("view.lockColumnGuides", json!({"on": false})).unwrap();+ h.run_steps(2);+ let (at, zoom) = screen(&h, 300.0);+ drag(&mut h, at, at + vec2(72.0 * zoom, 0.0));+ let pg = page(&h);+ let cols = pg.column_rects();+ assert!((cols[0].x1 - 372.0).abs() < 1.0 && (cols[1].x0 - cols[0].x1 - 12.0).abs() < 1e-9, "{cols:?}");+ assert!(pg.local_margins, "the dragged page's columns are its own");+ // Over the moved guide: a resize cursor.+ h.hover_at(screen(&h, 372.0).0);+ h.run_steps(2);+ assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeHorizontal);+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(page(&h).columns.positions, None, "one undo step");++ // Escape during the drag puts the gutter back.+ h.hover_at(at);+ h.step();+ h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });+ h.step();+ h.hover_at(at + vec2(40.0, 0.0));+ h.step();+ assert!(page(&h).columns.positions.is_some(), "the drag previews");+ h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });+ h.step();+ h.event(egui::Event::PointerButton {+ pos: at + vec2(40.0, 0.0),+ button: egui::PointerButton::Primary,+ pressed: false,+ modifiers: Default::default(),+ });+ h.run_steps(3);+ assert_eq!(page(&h).columns.positions, None);+ assert!(!page(&h).local_margins);++ // Space pressed during the drag and the button released under it: the drag ends with the+ // release and the gutter stops following the pointer.+ let key = |pressed| egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Default::default() };+ h.hover_at(at);+ h.step();+ h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });+ h.step();+ h.hover_at(at + vec2(40.0, 0.0));+ h.step();+ h.event(key(true));+ h.step();+ h.event(egui::Event::PointerButton {+ pos: at + vec2(40.0, 0.0),+ button: egui::PointerButton::Primary,+ pressed: false,+ modifiers: Default::default(),+ });+ h.step();+ h.event(key(false));+ h.run_steps(2);+ let moved = page(&h).columns.positions;+ assert!(moved.is_some());+ h.hover_at(at + vec2(120.0, 0.0));+ h.run_steps(3);+ assert_eq!(page(&h).columns.positions, moved, "the gutter stays where the drag ended");+ assert!(h.state().session.active().unwrap().interaction.is_none());+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(page(&h).columns.positions, None, "the drag was one undo step");+ }++ /// A column guide is not picked where the screen mode hides guides, where an object on the+ /// parent being edited lies over it, or where its columns cannot move.+ #[test]+ fn column_guides_are_picked_only_where_a_drag_can_move_them() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 1})).unwrap();+ app.run("layout.marginsAndColumns", json!({"parent": "A", "columns": 2, "gutter": 12})).unwrap();+ app.run("view.lockColumnGuides", json!({"on": false})).unwrap();+ let mut h = harness(app);+ let hit = |h: &Harness<'_, DesignApp>, r: SpreadRef, x: f64| {+ let app = h.state();+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());+ let st = app.session.active().unwrap();+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ let slot = layout.slots.iter().find(|s| s.spread == r).unwrap();+ column_guide_at(app, &xf, xf.to_screen(slot.xf * Point::new(x, 400.0)))+ };+ assert!(hit(&h, SpreadRef::Doc(0), 300.0).is_some());+ h.state_mut().ui.screen_mode = ScreenMode::Preview;+ assert!(hit(&h, SpreadRef::Doc(0), 300.0).is_none(), "Preview hides the guides");+ h.state_mut().ui.screen_mode = ScreenMode::Normal;++ // Editing parent A: its right page (the one page 0 follows) and a frame over its gutter.+ h.state_mut().run("layout.parents.edit", json!({"on": true, "parent": "A-Parent"})).unwrap();+ h.run_steps(2);+ let parent = SpreadRef::Parent(0);+ let x = h.state().session.active().unwrap().doc.parents[0].pages[1].column_rects()[0].x1;+ assert!(hit(&h, parent, x).is_some());+ h.state_mut()+ .run("frame.create", json!({"spread": {"kind": "parent", "index": 0}, "rect": [x - 20.0, 300.0, x + 20.0, 500.0], "content": "text"}))+ .unwrap();+ h.run_steps(2);+ assert!(hit(&h, parent, x).is_none(), "the parent's frame takes the press");+ h.state_mut().run("layout.parents.edit", json!({"on": false})).unwrap();+ h.run_steps(2);++ // Gutters wider than the margin box: the even split cannot be moved.+ h.state_mut().run("layout.marginsAndColumns", json!({"pages": [0], "columns": 2, "gutter": 1000})).unwrap();+ h.run_steps(2);+ let x = h.state().session.active().unwrap().doc.spreads[0].pages[0].column_rects()[0].x1;+ assert!(hit(&h, SpreadRef::Doc(0), x).is_none());+ }++ fn right_click(h: &mut Harness<'_, DesignApp>, p: Pos2) {+ h.hover_at(p);+ h.step();+ for pressed in [true, false] {+ h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() });+ }+ h.run_steps(3);+ }++ fn new_document() -> Harness<'static, DesignApp> {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ harness(app)+ }++ /// [`new_document`] at 60 frames a second, the cadence a wheel motion really arrives at.+ fn new_document_60fps() -> Harness<'static, DesignApp> {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ harness_with_step(app, 1.0 / 60.0)+ }++ fn held(modifiers: egui::Modifiers) -> egui::Event {+ egui::Event::ModifiersChanged(modifiers)+ }++ /// Construct a point-unit vertical mouse-wheel event with an unknown source.+ fn wheel(phase: egui::TouchPhase, up: f32, modifiers: egui::Modifiers) -> egui::Event {+ egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, up), phase, modifiers, source: egui::MouseWheelSource::Unknown }+ }++ // Plays `events` with the pointer at `at`, a frame each, and lets the motion settle.+ fn play(h: &mut Harness<'_, DesignApp>, at: Pos2, events: &[egui::Event]) -> View {+ h.hover_at(at);+ for event in events {+ h.event(event.clone());+ h.step();+ }+ h.run_steps(30);+ *h.state().view().unwrap()+ }++ /// Alt + wheel scrolled the view like the plain wheel; it zooms at the pointer (#470).+ #[test]+ fn alt_wheel_zooms_at_the_pointer() {+ use egui::{Modifiers, TouchPhase::Move};+ let mut h = new_document();+ let rect = h.state().canvas_rect.unwrap();+ let at = rect.center() + vec2(150.0, 90.0);+ let before = *h.state().view().unwrap();+ let under = Xf::new(rect, &before).to_canvas(at);+ let zoomed = play(&mut h, at, &[held(Modifiers::ALT), wheel(Move, 100.0, Modifiers::ALT)]);+ assert!(zoomed.zoom > before.zoom * 1.2, "wheel up zooms in: {} -> {}", before.zoom, zoomed.zoom);+ let still = Xf::new(rect, &zoomed).to_canvas(at);+ assert!((still.x - under.x).abs() < 0.01 && (still.y - under.y).abs() < 0.01, "the point under the pointer stays: {under:?} -> {still:?}");+ let back = play(&mut h, at, &[held(Modifiers::ALT), wheel(Move, -100.0, Modifiers::ALT)]);+ assert!((back.zoom - before.zoom).abs() < 1e-6, "wheel down zooms out: {} -> {}", zoomed.zoom, back.zoom);+ // The plain wheel still scrolls.+ let scrolled = play(&mut h, at, &[held(Modifiers::NONE), wheel(Move, 100.0, Modifiers::NONE)]);+ assert!(scrolled.zoom == back.zoom && scrolled.origin.y < back.origin.y, "{back:?} -> {scrolled:?}");+ }++ /// Alt zooms exactly as Ctrl/Cmd does, also when the key is let go while the wheel's motion is+ /// still arriving: the rest of it zooms too and does not scroll the page.+ #[test]+ fn alt_wheel_zooms_like_ctrl_wheel_to_the_end_of_the_motion() {+ use egui::{+ Modifiers,+ TouchPhase::{End, Move, Start},+ };+ const NONE: Modifiers = Modifiers::NONE;+ // Each motion in steps; the views are compared after every step.+ let motions: [fn(Modifiers) -> Vec<Vec<egui::Event>>; 4] = [+ |key| vec![vec![held(key), wheel(Move, 100.0, key)]],+ // A wheel turned fast, the key let go a frame later.+ |key| vec![vec![held(key), wheel(Move, 400.0, key), held(NONE)]],+ // A trackpad swipe that coasts on after the key is let go; once it has ended, the wheel scrolls.+ |key| {+ vec![+ vec![held(key), wheel(Start, 0.0, key), wheel(Move, 50.0, key), held(NONE), wheel(Move, 200.0, NONE)],+ vec![wheel(End, 0.0, NONE), wheel(Move, 100.0, NONE)],+ ]+ },+ |key| vec![vec![held(key | Modifiers::SHIFT), wheel(Move, 100.0, key | Modifiers::SHIFT)]],+ ];+ for (i, motion) in motions.iter().enumerate() {+ let (mut with_alt, mut with_command) = (new_document_60fps(), new_document_60fps());+ let at = with_alt.state().canvas_rect.unwrap().center() + vec2(150.0, 90.0);+ let start = *with_alt.state().view().unwrap();+ for (alt, command) in motion(Modifiers::ALT).iter().zip(motion(Modifiers::COMMAND)) {+ let (alt, command) = (play(&mut with_alt, at, alt), play(&mut with_command, at, &command));+ assert!(command.zoom > start.zoom, "motion {i} zooms");+ assert_eq!(alt, command, "motion {i}");+ }+ }+ }++ fn units(h: &Harness<'_, DesignApp>) -> (Unit, Unit) {+ let s = &h.state().session.doc().unwrap().doc.settings;+ (s.horizontal_units, s.vertical_units)+ }++ fn zoom_app(tool: &str) -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.select_tool(tool);+ app.ui.rulers = false;+ app+ }++ /// Run one app frame with the supplied modifiers, install fonts, draw the canvas when ready and return the cursor icon.+ fn canvas_frame(app: &mut DesignApp, ctx: &egui::Context, m: egui::Modifiers, mut events: Vec<egui::Event>) -> egui::CursorIcon {+ events.insert(0, egui::Event::ModifiersChanged(m));+ let mut output =+ ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }, |ui| {+ app.logic(ui.ctx());+ // Fonts are installed by the first real UI pass, just as in the full application.+ app.ui_setup(ui.ctx());+ if app.fonts_ready {+ show(app, ui);+ }+ });+ output.textures_delta.clear();+ output.platform_output.cursor_icon+ }++ /// The cursor icon the canvas sets for `c` on this platform (bitmap and painted cursors+ /// report their own icon).+ fn shown(c: Cursor) -> egui::CursorIcon {+ crate::cursors::show(&egui::Context::default(), &mut crate::cursors::Images::default(), c, Pos2::ZERO)+ }++ fn space_key(pressed: bool, modifiers: egui::Modifiers) -> egui::Event {+ egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers }+ }++ fn press(pos: Pos2, pressed: bool, modifiers: egui::Modifiers) -> egui::Event {+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }+ }++ fn hover(app: &mut DesignApp, ctx: &egui::Context, p: Pos2) {+ for _ in 0..3 {+ canvas_frame(app, ctx, egui::Modifiers::NONE, vec![egui::Event::PointerMoved(p)]);+ }+ }++ const CMD: egui::Modifiers = egui::Modifiers { command: true, mac_cmd: true, ..egui::Modifiers::NONE };++ #[test]+ fn spring_zoom_click_is_anchored_view_only_and_release_restores_previous_tool() {+ for tool in ["rectangleFrame", "directSelection", "type", "hand", "zoom"] {+ let mut app = zoom_app(tool);+ if tool == "rectangleFrame" {+ let frame = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":"Hello"})).unwrap();+ app.run("text.select", json!({"story":frame["story"],"anchor":5})).unwrap();+ }+ let ctx = egui::Context::default();+ let p = pos2(300.0, 250.0);+ hover(&mut app, &ctx, p);+ let before = *app.view().unwrap();+ let doc = app.session.doc().unwrap().doc.clone();+ let selection = app.session.doc().unwrap().selection.clone();+ let history = app.run("document.history", json!({})).unwrap();+ let cursor = canvas_frame(&mut app, &ctx, CMD, vec![space_key(true, CMD)]);+ assert_eq!(cursor, shown(Cursor::ZoomIn), "{tool}");+ canvas_frame(&mut app, &ctx, CMD, vec![press(p, true, CMD)]);+ canvas_frame(&mut app, &ctx, CMD, vec![press(p, false, CMD)]);+ let after = *app.view().unwrap();+ assert_eq!(after.zoom, before.zoom * 2.0, "{tool}");+ let anchor = Xf::new(app.canvas_rect.unwrap(), &before).to_canvas(p);+ assert!((Xf::new(app.canvas_rect.unwrap(), &after).to_canvas(p) - anchor).hypot() < 1e-9);+ let cursor = canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![space_key(false, egui::Modifiers::NONE)]);+ assert_eq!(app.session.tool_id(), tool);+ let expected = app.session.cursor(anchor, Mods::default(), app.view_info());+ assert_eq!(cursor, shown(expected), "{tool}");+ assert!(std::sync::Arc::ptr_eq(&doc, &app.session.doc().unwrap().doc));+ assert_eq!(selection, app.session.doc().unwrap().selection);+ assert_eq!(history, app.run("document.history", json!({})).unwrap());+ }+ }++ #[test]+ fn spring_zoom_alt_clicks_out_and_modifier_release_switches_back_to_hand() {+ let mut app = zoom_app("rectangleFrame");+ let ctx = egui::Context::default();+ let p = pos2(300.0, 250.0);+ hover(&mut app, &ctx, p);+ let z = app.view().unwrap().zoom;+ let alt = egui::Modifiers { alt: true, ..CMD };+ assert_eq!(canvas_frame(&mut app, &ctx, CMD, vec![space_key(true, CMD)]), shown(Cursor::ZoomIn));+ assert_eq!(canvas_frame(&mut app, &ctx, alt, vec![]), shown(Cursor::ZoomOut));+ canvas_frame(&mut app, &ctx, alt, vec![press(p, true, alt)]);+ canvas_frame(&mut app, &ctx, alt, vec![press(p, false, alt)]);+ assert_eq!(app.view().unwrap().zoom, z * 0.5);+ assert_eq!(canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![]), shown(Cursor::Hand));+ let before = *app.view().unwrap();+ canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p, true, egui::Modifiers::NONE)]);+ canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![egui::Event::PointerMoved(p + vec2(80.0, 0.0))]);+ canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p + vec2(80.0, 0.0), false, egui::Modifiers::NONE)]);+ assert_eq!(app.view().unwrap().zoom, before.zoom);+ assert!(app.view().unwrap().origin.x < before.origin.x);+ assert_eq!(app.session.tool_id(), "rectangleFrame");+ }++ #[test]+ fn spring_zoom_scrubs_and_owns_pointer_release_after_shortcut_release() {+ let mut app = zoom_app("rectangleFrame");+ let ctx = egui::Context::default();+ let p = pos2(300.0, 250.0);+ hover(&mut app, &ctx, p);+ let z = app.view().unwrap().zoom;+ let doc = app.session.doc().unwrap().doc.clone();+ // Ctrl is the platform command modifier on Windows/Linux, using the same input path.+ let cmd = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE };+ canvas_frame(&mut app, &ctx, cmd, vec![space_key(true, cmd), press(p, true, cmd)]);+ let end = p + vec2(150.0, 0.0);+ canvas_frame(&mut app, &ctx, cmd, vec![egui::Event::PointerMoved(end)]);+ assert!((app.view().unwrap().zoom - z * std::f64::consts::E).abs() < 1e-9);+ let scrubbed = app.view().unwrap().zoom;+ assert_eq!(canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![space_key(false, egui::Modifiers::NONE)]), shown(Cursor::Crosshair));+ canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(end, false, egui::Modifiers::NONE)]);+ assert_eq!(app.view().unwrap().zoom, scrubbed, "no extra click zoom at the end of a scrub");+ assert!(std::sync::Arc::ptr_eq(&doc, &app.session.doc().unwrap().doc));+ // The original tool still draws after the temporary gesture.+ canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p, true, egui::Modifiers::NONE)]);+ canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![egui::Event::PointerMoved(p + vec2(50.0, 50.0))]);+ canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p + vec2(50.0, 50.0), false, egui::Modifiers::NONE)]);+ assert!(!std::sync::Arc::ptr_eq(&doc, &app.session.doc().unwrap().doc));+ assert_eq!(app.session.tool_id(), "rectangleFrame");+ }++ #[test]+ fn spring_zoom_is_suppressed_while_typing_in_a_text_frame() {+ let mut app = zoom_app("type");+ let frame = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":"Hello"})).unwrap();+ app.run("text.select", json!({"story":frame["story"],"anchor":5})).unwrap();+ assert!(app.session.wants_text());+ let ctx = egui::Context::default();+ let p = pos2(300.0, 250.0);+ hover(&mut app, &ctx, p);+ let before = *app.view().unwrap();+ let alt = egui::Modifiers { alt: true, ..CMD };+ for m in [CMD, alt] {+ app.run("text.select", json!({"story":frame["story"],"anchor":5})).unwrap();+ assert!(app.session.wants_text());+ assert!(!matches!(canvas_frame(&mut app, &ctx, m, vec![space_key(true, m)]), egui::CursorIcon::ZoomIn | egui::CursorIcon::ZoomOut));+ canvas_frame(&mut app, &ctx, m, vec![press(p, true, m)]);+ canvas_frame(&mut app, &ctx, m, vec![press(p, false, m)]);+ assert_eq!(app.view().unwrap().zoom, before.zoom);+ assert_eq!(app.view().unwrap().origin, before.origin);+ canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![space_key(false, egui::Modifiers::NONE)]);+ }+ }++ #[test]+ fn spring_zoom_is_suppressed_while_a_text_field_has_focus() {+ let mut app = zoom_app("rectangleFrame");+ let ctx = egui::Context::default();+ let mut text = String::new();+ let p = pos2(300.0, 250.0);+ hover(&mut app, &ctx, p);+ let before = *app.view().unwrap();+ for m in [egui::Modifiers::NONE, CMD, egui::Modifiers { alt: true, ..CMD }] {+ let mut output = ctx.run_ui(+ egui::RawInput {+ screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))),+ events: vec![egui::Event::ModifiersChanged(m), space_key(true, m), egui::Event::Text("x".into()), egui::Event::PointerMoved(p)],+ ..Default::default()+ },+ |ui| {+ ui.text_edit_singleline(&mut text).request_focus();+ show(&mut app, ui);+ },+ );+ output.textures_delta.clear();+ assert!(ctx.text_edit_focused());+ assert!(!matches!(output.platform_output.cursor_icon, egui::CursorIcon::ZoomIn | egui::CursorIcon::ZoomOut | egui::CursorIcon::Grab));+ assert_eq!(app.view().unwrap().zoom, before.zoom);+ assert_eq!(app.session.tool_id(), "rectangleFrame");+ }+ assert!(!text.is_empty(), "typing still reaches the field");+ }++ #[test]+ fn spring_zoom_does_not_interrupt_an_existing_tool_drag() {+ let mut app = zoom_app("rectangleFrame");+ let ctx = egui::Context::default();+ let p = pos2(300.0, 250.0);+ hover(&mut app, &ctx, p);+ let before = *app.view().unwrap();+ let doc = app.session.doc().unwrap().doc.clone();+ canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p, true, egui::Modifiers::NONE)]);+ let end = p + vec2(100.0, 100.0);+ canvas_frame(&mut app, &ctx, CMD, vec![space_key(true, CMD), egui::Event::PointerMoved(end)]);+ canvas_frame(&mut app, &ctx, CMD, vec![press(end, false, CMD)]);+ assert_eq!(app.view().unwrap().zoom, before.zoom);+ assert_eq!(app.view().unwrap().origin, before.origin);+ assert!(!std::sync::Arc::ptr_eq(&doc, &app.session.doc().unwrap().doc));+ }++ #[test]+ fn spring_zoom_does_not_zoom_on_the_rulers() {+ let mut app = zoom_app("rectangleFrame");+ app.ui.rulers = true;+ let ctx = egui::Context::default();+ hover(&mut app, &ctx, pos2(300.0, 250.0));+ let rect = app.canvas_rect.unwrap();+ let p = pos2(rect.min.x - RULER / 2.0, rect.center().y);+ hover(&mut app, &ctx, p);+ let before = *app.view().unwrap();+ canvas_frame(&mut app, &ctx, CMD, vec![space_key(true, CMD)]);+ canvas_frame(&mut app, &ctx, CMD, vec![press(p, true, CMD)]);+ canvas_frame(&mut app, &ctx, CMD, vec![press(p, false, CMD)]);+ assert_eq!(app.view().unwrap().zoom, before.zoom);+ assert_eq!(app.view().unwrap().origin, before.origin);+ }++ #[test]+ fn parent_guides_on_a_page_are_not_picked_there() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ // 100 pt into A's right page, which page 1 (a right page at x = 0) shows.+ let parent_guide = json!({"spread": {"kind": "parent", "index": 0}, "page": 1, "orientation": "vertical", "position": 712});+ app.run("guide.add", parent_guide).unwrap();+ let mut h = harness(app);+ let at = |app: &DesignApp| {+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());+ let layout = CanvasLayout::new(&app.session.active().unwrap().doc, false);+ let slot = layout.slots.iter().find(|s| s.spread == SpreadRef::Doc(0)).unwrap();+ guide_at(app, &xf, xf.to_screen(slot.xf * Point::new(100.0, 300.0)))+ };+ assert_eq!(at(h.state()), None, "the parent's guide is edited on the parent");+ h.state_mut().run("guide.add", json!({"orientation": "vertical", "position": 100})).unwrap();+ h.run_steps(2);+ assert!(matches!(at(h.state()), Some((SpreadRef::Doc(0), 0, 0, _))), "the page's own guide is");+ }++ #[test]+ fn mouse_double_clicking_a_frame_handle_fits_with_one_undo_step() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = designcraft_doc::ItemId(+ app.run("frame.create", json!({"rect": [100, 100, 400, 300], "content": "text", "text": "Fit this text"})).unwrap()["id"].as_u64().unwrap(),+ );+ app.run("selection.set", json!({"ids": [id.0]})).unwrap();+ let original = app.session.doc().unwrap().doc.item(id).unwrap().bounds();+ // 60 frames a second: the default 0.25 s step puts two clicks past egui's double-click delay.+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(+ |ui, app: &mut DesignApp| {+ let ctx = ui.ctx().clone();+ app.logic(&ctx);+ app.ui(ui);+ },+ app,+ );+ h.run_steps(4);+ let app = h.state();+ let st = app.session.doc().unwrap();+ let layout = CanvasLayout::new(&st.doc, false);+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());+ let p = xf.to_screen(layout.xf(SpreadRef::Doc(0)) * Point::new(original.x1, original.y1));+ h.hover_at(p);+ h.step();+ // Separate frames model the actual mouse, including egui's release-time double click.+ for _ in 0..2 {+ for pressed in [true, false] {+ h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });+ h.step();+ }+ }+ h.run_steps(2);+ let fitted = h.state().session.doc().unwrap().doc.item(id).unwrap().bounds();+ assert!(fitted.width() < original.width() && fitted.height() < original.height(), "{fitted:?}");+ assert_eq!(h.state().session.tool_id(), "selection");+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(h.state().session.doc().unwrap().doc.item(id).unwrap().bounds(), original);+ }++ const ART: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 50" width="100pt" height="50pt"><path d="M0,0 C30,0 70,50 100,50" fill="none" stroke="#000" stroke-width="2"/></svg>"##;++ #[test]+ fn pasting_svg_from_another_app_places_editable_paths_in_the_middle_of_the_view() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let mut h = harness(app);+ h.run_steps(2);+ let undo = h.state().session.doc().unwrap().history.undo.len();+ h.event(egui::Event::Paste(ART.into()));+ h.run_steps(2);+ let app = h.state();+ let st = app.session.doc().unwrap();+ assert_eq!(st.history.undo.len(), undo + 1, "one undo step");+ let id = *st.selection.items.first().expect("the pasted path is selected");+ let it = st.doc.item(id).unwrap();+ assert_eq!(it.shape, designcraft_doc::Shape::Path);+ assert_eq!(it.path.subpaths[0].anchors.len(), 2);+ assert!((it.stroke.weight - 2.0).abs() < 1e-9);+ // Centred where text from another app would go: the middle of the view.+ let (_, centre) = view_centre(app).unwrap();+ assert!((it.bounds().center() - centre).hypot() < 0.01, "{:?} vs {centre:?}", it.bounds());+ }++ #[test]+ fn the_paste_in_place_shortcut_pastes_in_place_and_plain_paste_offsets() {+ 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": [100, 100, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ let original = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().bounds();+ app.run("edit.copy", json!({})).unwrap();+ let clip = app.object_clip_text.clone().expect("the copy's placeholder text");+ let mut h = harness(app);+ let paste = |h: &mut Harness<'static, DesignApp>, modifiers: egui::Modifiers| {+ // As egui-winit delivers ⌃⌥⇧V: the chord's paste and the V release, no V press; here the+ // modifiers are released within the same frame.+ let release = egui::Event::Key { key: egui::Key::V, physical_key: None, pressed: false, repeat: false, modifiers };+ let none = egui::Event::ModifiersChanged(egui::Modifiers::NONE);+ h.input_mut().events.extend([egui::Event::ModifiersChanged(modifiers), egui::Event::Paste(clip.clone()), release, none]);+ h.run_steps(2);+ let st = h.state().session.doc().unwrap();+ let pasted = *st.selection.items.first().expect("the copy is selected");+ assert_ne!(pasted.0, id);+ st.doc.item(pasted).unwrap().bounds()+ };+ let linux = egui::Modifiers { alt: true, ctrl: true, shift: true, mac_cmd: false, command: true };+ assert_eq!(paste(&mut h, linux), original, "Paste in Place");+ let moved = paste(&mut h, egui::Modifiers::COMMAND);+ assert!((moved.x0 - original.x0 - 12.0).abs() < 1e-9 && (moved.y0 - original.y0 - 12.0).abs() < 1e-9, "{moved:?}");+ // The modifiers went down in an earlier frame than the paste.+ h.event_modifiers(egui::Event::Paste(clip.clone()), linux);+ h.run_steps(2);+ let st = h.state().session.doc().unwrap();+ let pasted = *st.selection.items.first().expect("the copy is selected");+ assert_eq!(st.doc.item(pasted).unwrap().bounds(), original);+ }++ #[test]+ fn edit_paste_from_the_menu_pastes_svg_on_the_system_clipboard_as_paths() {+ let services = crate::Services { clipboard_text: Some(Box::new(|| Some(ART.to_string()))), ..Default::default() };+ let mut app = DesignApp::new(designcraft_engine::Session::new(), services);+ app.native_menu = true;+ app.run("file.new", json!({})).unwrap();+ crate::menus::activate(&mut app, "edit.paste", &Value::Null);+ let st = app.session.doc().unwrap();+ let id = *st.selection.items.first().expect("the pasted path is selected");+ assert_eq!(st.doc.item(id).unwrap().shape, designcraft_doc::Shape::Path);+ assert!(st.selection.text.is_none(), "paths, not a text frame of markup");+ // With an insertion point, the markup is text like any other.+ let story = app.run("frame.create", json!({"rect": [10, 10, 300, 300], "content": "text"})).unwrap()["story"].clone();+ app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap();+ let items = app.session.doc().unwrap().doc.spreads[0].items.len();+ crate::menus::activate(&mut app, "edit.paste", &Value::Null);+ assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), items, "no paths added");+ }++ #[test]+ fn selected_merged_owners_paint_the_same_row_and_column_targets() {+ for column in [true, false] {+ for merged in [false, true] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 1})).unwrap();+ app.run("frame.create", json!({"rect": [36, 36, 300, 300], "content": "text"})).unwrap();+ app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap();+ if merged {+ let range = if column { json!({"rows": [0, 0], "cols": [0, 1]}) } else { json!({"rows": [0, 1], "cols": [0, 0]}) };+ app.run("table.select", range).unwrap();+ app.run("table.merge", json!({})).unwrap();+ }+ app.run("table.select", json!({"rows": [1, 1], "cols": [1, 1]})).unwrap();+ app.run(if column { "table.selectColumn" } else { "table.selectRow" }, json!({})).unwrap();+ let st = app.session.doc().unwrap();+ let selection = st.selection.clone();+ let ts = selection.text.unwrap();+ let selected = selection.cells.unwrap();+ assert_eq!(+ selected.range,+ if column { designcraft_doc::CellRange::new(0, 1, 1, 1) } else { designcraft_doc::CellRange::new(1, 0, 1, 1) }+ );+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ let cs = app.session.cache.get(&st.doc, ts.story, None);+ let ft = &cs.frames[0];+ let table = ft.tables.iter().find(|t| t.table == selected.table).unwrap();+ let (a, _) = item_canvas_xf(&st.doc, &layout, ft.frame).unwrap();+ let m = a * st.doc.text_xf(st.doc.item(ft.frame).unwrap());+ let xf = Xf { min: pos2(0.0, 0.0), origin: Point::new(0.0, 0.0), zoom: 1.0, rot: 0, pivot: pos2(0.0, 0.0) };+ let owners = if merged {+ [(0, 0), (1, 1)]+ } else if column {+ [(0, 1), (1, 1)]+ } else {+ [(1, 0), (1, 1)]+ };+ let expected: Vec<_> = owners+ .into_iter()+ .map(|(r, c)| {+ let rect = table.cells.iter().find(|cell| cell.row == r && cell.col == c).unwrap().rect;+ vec![+ xf.to_screen(m * Point::new(rect.x0, rect.y0)),+ xf.to_screen(m * Point::new(rect.x1, rect.y0)),+ xf.to_screen(m * Point::new(rect.x1, rect.y1)),+ xf.to_screen(m * Point::new(rect.x0, rect.y1)),+ ]+ })+ .collect();+ let ctx = egui::Context::default();+ let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {+ draw_text_selection(&app, ui.painter(), &xf, &st.doc, &layout, ts, Some(selected));+ });+ output.textures_delta.clear();+ let tint = Color32::from_rgba_unmultiplied(80, 140, 255, 90);+ let painted: Vec<_> = output+ .shapes+ .into_iter()+ .filter_map(|s| match s.shape {+ egui::Shape::Path(path) if path.fill == tint => {+ assert!(path.closed);+ assert_eq!(path.stroke, egui::epaint::PathStroke::NONE);+ Some(path.points)+ }+ _ => None,+ })+ .collect();+ assert_eq!(painted, expected, "only the two touched owners are tinted; column={column}, merged={merged}");+ assert_eq!(app.session.doc().unwrap().selection, selection);+ }+ }+ }++ /// A selected group lists the text frames inside it for ports.+ #[test]+ fn grouped_text_frames_get_ports() {+ let mut s = designcraft_engine::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let a = s.execute("frame.create", &json!({"rect": [10, 10, 110, 60], "content": "text"})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("frame.create", &json!({"rect": [10, 80, 110, 130]})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [a, b]})).unwrap();+ let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();+ let doc = &s.doc().unwrap().doc;+ let group = doc.item(designcraft_doc::ItemId(g)).unwrap();+ let mut out = Vec::new();+ text_frames_in(group, 0, &mut out);+ assert_eq!(out.iter().map(|(it, _)| it.id.0).collect::<Vec<_>>(), vec![a], "one text frame in the group");+ // A plain text frame lists itself.+ out.clear();+ text_frames_in(out_frame(doc, a), 0, &mut out);+ assert_eq!(out.len(), 1);+ }++ /// A selected group paints both ports of the overset text frame inside it, on top of the+ /// group's own selection marks.+ #[test]+ fn a_selected_group_paints_both_ports_of_its_text_frame() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let s = &mut app.session;+ let text = "far too much text for a frame this small, over and over again ".repeat(8);+ let a = s.execute("frame.create", &json!({"rect": [100, 100, 200, 140], "content": "text", "text": text})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("frame.create", &json!({"rect": [100, 200, 200, 260]})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [a, b]})).unwrap();+ let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();+ s.execute("transform.rotate", &json!({"angle": 30, "ids": [g]})).unwrap();+ s.execute("selection.set", &json!({"ids": [g]})).unwrap();+ let doc = app.session.doc().unwrap().doc.clone();+ let layout = CanvasLayout::new(&doc, false);+ let xf = Xf { min: pos2(0.0, 0.0), origin: Point::new(0.0, 0.0), zoom: 1.0, rot: 0, pivot: pos2(0.0, 0.0) };+ let ctx = egui::Context::default();+ let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {+ draw_selection(&app, ui.painter(), &xf, &doc, &layout);+ });+ output.textures_delta.clear();+ let white: Vec<Rect> = output+ .shapes+ .into_iter()+ .filter_map(|s| match s.shape {+ egui::Shape::Rect(r) if r.fill == Color32::WHITE => Some(r.rect),+ _ => None,+ })+ .collect();+ for out in [false, true] {+ let c = xf.to_screen(designcraft_tools::thread::port_center(&doc, &layout, designcraft_doc::ItemId(a), out, xf.zoom).unwrap());+ let port = white.iter().position(|r| (r.center() - c).length() < 0.01).unwrap_or_else(|| panic!("port (out: {out}) at {c:?}"));+ assert!(!white[port + 1..].iter().any(|r| r.contains(c)), "nothing painted later covers the port (out: {out})");+ }+ }++ fn out_frame(doc: &Document, id: u64) -> &Item {+ doc.item(designcraft_doc::ItemId(id)).unwrap()+ }++ /// An overset frame inside a group is listed for the red mark even when nothing is+ /// selected; a frame with room, or a hidden one, is not.+ #[test]+ fn overset_frames_are_found_inside_groups() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let s = &mut app.session;+ let frame_with = |s: &mut designcraft_engine::Session, rect: [f64; 4], text: &str| {+ s.execute("frame.create", &json!({"rect": rect, "content": "text", "text": text})).unwrap()["id"].as_u64().unwrap()+ };+ let tiny = frame_with(s, [10.0, 10.0, 40.0, 16.0], "far too much text for a frame this small, over and over again");+ let roomy = frame_with(s, [10.0, 100.0, 300.0, 300.0], "fits");+ s.execute("selection.set", &json!({"ids": [tiny, roomy]})).unwrap();+ s.execute("object.group", &json!({})).unwrap();+ s.execute("selection.set", &json!({"ids": []})).unwrap();+ let doc = app.session.doc().unwrap().doc.clone();+ let mut out = Vec::new();+ overset_frames(&app, &doc, &doc.spreads[0].items, 0, &mut out);+ assert_eq!(out.iter().map(|it| it.id.0).collect::<Vec<_>>(), vec![tiny]);+ // Hidden: no mark.+ app.session.execute("object.hide", &json!({"ids": [tiny]})).unwrap();+ let doc = app.session.doc().unwrap().doc.clone();+ out.clear();+ overset_frames(&app, &doc, &doc.spreads[0].items, 0, &mut out);+ assert!(out.is_empty());+ }+++/// While parents are edited, a document page's frames have no place on the canvas (they fell back++/// to the identity transform and their ¶ marks and other overlays piled onto the right parent++/// page), and the reverse.++#[test]++fn document_pages_have_no_place_on_the_parent_canvas() {++ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());++ app.run("file.new", json!({"pages": 2})).unwrap();++ let s = &mut app.session;++ let body =++ s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "one\ntwo"})).unwrap()["id"].as_u64().unwrap();++ let head = s++ .execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [36, 10, 300, 30], "content": "text", "text": "head"}))++ .unwrap()["id"]++ .as_u64()++ .unwrap();++ let doc = app.session.doc().unwrap().doc.clone();++ let (body, head) = (designcraft_doc::ItemId(body), designcraft_doc::ItemId(head));++ let pages = CanvasLayout::new(&doc, false);++ assert!(item_canvas_xf(&doc, &pages, body).is_some());++ assert!(item_canvas_xf(&doc, &pages, head).is_none());++ let parents = CanvasLayout::new(&doc, true);++ assert!(item_canvas_xf(&doc, &parents, body).is_none(), "a page frame is not drawn over the parent");++ assert!(item_canvas_xf(&doc, &parents, head).is_some());++}+++ /// The always-on overset mark sits at the frame's out port, a step along its own right edge+ /// (so a rotated frame gets it inside its edge, not straight up from the corner), and a+ /// selected overset frame gets only the mark its ports draw.+ #[test]+ fn overset_mark_sits_on_the_out_port_once() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let s = &mut app.session;+ let id = s+ .execute("frame.create", &json!({"rect": [100, 100, 200, 160], "content": "text", "text": "far too much text for a frame this small, over and over again ".repeat(8)}))+ .unwrap()["id"]+ .as_u64()+ .unwrap();+ s.execute("transform.rotate", &json!({"angle": 90, "ids": [id]})).unwrap();+ s.execute("selection.set", &json!({"ids": []})).unwrap();+ let doc = app.session.doc().unwrap().doc.clone();+ let layout = CanvasLayout::new(&doc, false);+ let zoom = 1.0;+ let marks = overset_marks(&app, &doc, &layout, &doc.spreads[0].items, zoom, &ported_frames(&app, &doc));+ assert_eq!(marks.len(), 1);+ let it = out_frame(&doc, id);+ let (a, _) = item_canvas_xf(&doc, &layout, it.id).unwrap();+ let m = a * it.xf;+ let r = it.inner_bounds();+ let corner = m * Point::new(r.x1, r.y1);+ let edge = (m * Point::new(r.x1, r.y0)) - corner;+ let d = marks[0].1 - corner;+ assert!((d.x * edge.y - d.y * edge.x).abs() < 1e-6, "the mark lies on the frame's right edge: {d:?} along {edge:?}");+ assert!((d.hypot() - 12.0 / zoom).abs() < 1e-6, "12 screen px from the corner: {d:?}");+ // Selected: the ports draw the mark, so no always-on mark is added.+ app.session.execute("selection.set", &json!({"ids": [id]})).unwrap();+ let marks = overset_marks(&app, &doc, &layout, &doc.spreads[0].items, zoom, &ported_frames(&app, &doc));+ assert!(marks.is_empty());+ }++ #[test]+ fn right_clicking_a_ruler_sets_that_rulers_units() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let mut h = harness(app);+ let rect = h.state().canvas_rect.unwrap();+ assert_eq!(units(&h), (Unit::Picas, Unit::Picas));+ // Vertical ruler: the current unit is checked; picking one sets only the vertical units.+ right_click(&mut h, pos2(rect.min.x - RULER / 2.0, rect.center().y));+ h.get_by_label("✓ Picas");+ h.get_by_label(" Millimeters").click();+ h.run_steps(3);+ assert_eq!(units(&h), (Unit::Picas, Unit::Millimeters));+ // Horizontal ruler.+ right_click(&mut h, pos2(rect.center().x, rect.min.y - RULER / 2.0));+ h.get_by_label("✓ Picas");+ h.get_by_label(" Inches").click();+ h.run_steps(3);+ assert_eq!(units(&h), (Unit::Inches, Unit::Millimeters));+ // The corner where the rulers meet sets both, as InDesign's: nothing is checked while+ // they differ.+ let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0);+ right_click(&mut h, corner);+ assert!(h.query_by_label("✓ Inches").is_none() && h.query_by_label("✓ Millimeters").is_none());+ let _ = h.get_by_label_contains("Hide Rulers");+ let _ = h.get_by_label(" Lock Zero Point");+ assert!(h.query_by_label(" Delete All Guides on Spread").is_none(), "only on the horizontal ruler");+ h.get_by_label(" Points").click();+ h.run_steps(3);+ assert_eq!(units(&h), (Unit::Points, Unit::Points));+ // InDesign's list: no Q or Ha.+ right_click(&mut h, corner);+ h.get_by_label("✓ Points");+ assert!(h.query_by_label(" Q").is_none() && h.query_by_label(" Ha").is_none());+ let _ = h.get_by_label(" Inches Decimal");+ // The horizontal ruler's menu also deletes the spread's guides; Hide Rulers hides them.+ right_click(&mut h, pos2(rect.center().x, rect.min.y - RULER / 2.0));+ let _ = h.get_by_label(" Delete All Guides on Spread");+ h.get_by_label_contains("Hide Rulers").click();+ h.run_steps(3);+ assert!(!h.state().ui.rulers);+ // The page opens no units menu.+ right_click(&mut h, rect.center());+ assert!(h.query_by_label(" Points").is_none());+ }++ /// The live-corner widget draws on a selected rectangle frame; clicking it draws the diamonds.+ #[test]+ fn live_corner_widget_and_diamonds_draw() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [100, 100, 300, 250], "content": "graphic"})).unwrap();+ let id = app.session.doc().unwrap().doc.spreads[0].items[0].id;+ app.run("selection.set", json!({"ids": [id.0]})).unwrap();+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_pixels_per_point(1.0).wgpu().build_ui_state(+ |ui, app: &mut DesignApp| {+ let ctx = ui.ctx().clone();+ app.logic(&ctx);+ app.ui(ui);+ },+ app,+ );+ h.run_steps(4);+ let screen = |h: &Harness<'_, DesignApp>, x: f64, y: f64| {+ let app = h.state();+ let layout = CanvasLayout::new(&app.session.doc().unwrap().doc, false);+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());+ xf.to_screen(layout.to_canvas(SpreadRef::Doc(0), Point::new(x, y)))+ };+ let widget = screen(&h, 300.0, 100.0) + vec2(0.0, 11.5);+ let diamond = screen(&h, 100.0, 100.0) + vec2(12.0, 0.0);+ let yellow = |h: &mut Harness<'_, DesignApp>, p: Pos2| -> Option<bool> {+ let img = match h.render() {+ Ok(img) => img,+ Err(e) => {+ eprintln!("skipped: no offscreen renderer ({e})");+ return None;+ }+ };+ let px = img.get_pixel(p.x.round() as u32, p.y.round() as u32).0;+ Some(px[0] > 200 && px[1] > 180 && px[2] < 100)+ };+ let Some(w) = yellow(&mut h, widget) else { return };+ assert!(w, "no widget at {widget:?}");+ assert_eq!(yellow(&mut h, diamond), Some(false));+ h.hover_at(widget);+ h.step();+ for pressed in [true, false] {+ h.event(egui::Event::PointerButton { pos: widget, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });+ h.step();+ }+ h.run_steps(3);+ assert_eq!(yellow(&mut h, diamond), Some(true), "no diamond at {diamond:?}");+ assert_eq!(yellow(&mut h, widget), Some(false));+ }++ /// A harness whose frames are 1 ms apart, so two clicks make a double-click.+ fn fast_harness(app: DesignApp) -> Harness<'static, DesignApp> {+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(0.001).build_ui_state(+ |ui, app: &mut DesignApp| {+ let ctx = ui.ctx().clone();+ app.logic(&ctx);+ app.ui(ui);+ },+ app,+ );+ h.run_steps(4);+ h+ }++ fn primary(h: &mut Harness<'_, DesignApp>, pos: Pos2, pressed: bool) {+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });+ h.run_steps(2);+ }++ fn corner_drag(h: &mut Harness<'_, DesignApp>, from: Pos2, to: Pos2) {+ h.hover_at(from);+ h.step();+ primary(h, from, true);+ h.event(egui::Event::PointerMoved(from + (to - from) / 2.0));+ h.run_steps(2);+ h.event(egui::Event::PointerMoved(to));+ h.run_steps(2);+ primary(h, to, false);+ }++ fn corner_click(h: &mut Harness<'_, DesignApp>, p: Pos2) {+ h.hover_at(p);+ h.step();+ primary(h, p, true);+ primary(h, p, false);+ }++ /// Where the rulers measure from (canvas coordinates): the document's zero point on the+ /// spread in view (its first page, for a page origin).+ fn ruler_zero(app: &DesignApp, doc: &Document, layout: &CanvasLayout) -> Option<Point> {+ ruler_pieces(app, doc, layout, doc.zero_point()).first().map(|p| p.2)+ }++ fn zero_point(h: &Harness<'_, DesignApp>) -> [f64; 2] {+ h.state().session.doc().unwrap().doc.settings.zero_point+ }++ #[test]+ fn the_ruler_corner_drags_resets_and_locks_the_zero_point() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 3})).unwrap();+ let mut h = fast_harness(app);+ let rect = h.state().canvas_rect.unwrap();+ let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0);+ // A click that stays in the corner leaves the zero point.+ corner_click(&mut h, corner);+ assert_eq!(zero_point(&h), [0.0, 0.0]);+ // Dragged out, it lands where released, measured from the spread in view.+ let dest = rect.min + vec2(80.0, 50.0);+ let expected = {+ let app = h.state();+ let st = app.session.active().unwrap();+ let layout = CanvasLayout::new(&st.doc, false);+ let slot = layout.slots[current_slot(app, &layout).unwrap()];+ let sp = slot.to_spread(Xf::new(rect, app.view().unwrap()).to_canvas(dest));+ let b = st.doc.spread(slot.spread).unwrap().bounds();+ [sp.x - b.x0, sp.y - b.y0]+ };+ corner_drag(&mut h, corner, dest);+ let zp = zero_point(&h);+ assert!((zp[0] - expected[0]).abs() < 0.5 && (zp[1] - expected[1]).abs() < 0.5, "{zp:?} vs {expected:?}");+ assert!(zp[0].abs() > 1.0 && zp[1].abs() > 1.0, "moved: {zp:?}");+ // The rulers measure from the point it was dropped on.+ {+ let app = h.state();+ let st = app.session.active().unwrap();+ let layout = CanvasLayout::new(&st.doc, false);+ let o = ruler_zero(app, &st.doc, &layout).unwrap();+ let on_screen = Xf::new(rect, app.view().unwrap()).to_screen(o);+ assert!((on_screen - dest).length() < 0.5, "{on_screen:?} vs {dest:?}");+ }+ // A double-click resets it.+ corner_click(&mut h, corner);+ corner_click(&mut h, corner);+ assert_eq!(zero_point(&h), [0.0, 0.0]);+ // Locked from the corner's context menu, the corner ignores drags and double-clicks.+ right_click(&mut h, corner);+ h.get_by_label(" Lock Zero Point").click();+ h.run_steps(3);+ assert!(h.state().session.doc().unwrap().doc.settings.zero_point_locked);+ corner_drag(&mut h, corner, dest);+ assert_eq!(zero_point(&h), [0.0, 0.0]);+ // Unlocked again from the same menu.+ right_click(&mut h, corner);+ h.get_by_label(" Unlock Zero Point").click();+ h.run_steps(3);+ corner_drag(&mut h, corner, dest);+ assert_ne!(zero_point(&h), [0.0, 0.0]);+ h.state_mut().run("view.lockZeroPoint", json!({"on": true})).unwrap();+ corner_click(&mut h, corner);+ corner_click(&mut h, corner);+ assert_ne!(zero_point(&h), [0.0, 0.0], "a locked zero point isn't reset");+ }++ #[test]+ fn cmd_dragging_the_ruler_corner_makes_a_guide_each_way() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let mut h = harness(app);+ let rect = h.state().canvas_rect.unwrap();+ let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0);+ let dest = rect.min + vec2(120.0, 90.0);+ let (r, at) = {+ let app = h.state();+ let st = app.session.active().unwrap();+ CanvasLayout::new(&st.doc, false).spread_at(Xf::new(rect, app.view().unwrap()).to_canvas(dest)).unwrap()+ };+ h.event(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND));+ h.step();+ corner_drag(&mut h, corner, dest);+ h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));+ h.step();+ let doc = h.state().session.doc().unwrap().doc.clone();+ let guides: Vec<_> = doc.spread(r).unwrap().pages.iter().flat_map(|p| p.guides.clone()).collect();+ assert_eq!(guides.len(), 2, "{guides:?}");+ let pos = |o: designcraft_doc::Orientation| guides.iter().find(|g| g.orientation == o).map(|g| g.position).unwrap();+ assert!((pos(designcraft_doc::Orientation::Horizontal) - at.y).abs() < 0.5);+ assert!((pos(designcraft_doc::Orientation::Vertical) - at.x).abs() < 0.5);+ assert!(guides.iter().all(|g| g.spread));+ assert_eq!(doc.settings.zero_point, [0.0, 0.0], "the zero point stays");+ }++ /// A guide being dragged out of a ruler says where it is, as the rulers measure it (#1282):+ /// from the zero point, in the ruler units, and the label follows the pointer while it moves.+ #[test]+ fn a_dragged_guide_shows_where_it_is() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap();+ let mut h = harness(app);+ let rect = h.state().canvas_rect.unwrap();+ let dest = rect.min + vec2(160.0, 110.0);+ let (xf, at) = {+ let app = h.state();+ let xf = Xf::new(rect, app.view().unwrap());+ let st = app.session.active().unwrap();+ (xf, CanvasLayout::new(&st.doc, false).spread_at(xf.to_canvas(dest)).unwrap().1)+ };+ let units = h.state().session.doc().unwrap().doc.settings.horizontal_units;+ for (orientation, label, want) in+ [(designcraft_doc::Orientation::Vertical, "X", at.x - 100.0), (designcraft_doc::Orientation::Horizontal, "Y", at.y - 50.0)]+ {+ let g = GuideDrag { orientation, from: None, at: Some(dest), mods: egui::Modifiers::NONE };+ let (l, v, _) = guide_measure(h.state(), &xf, &g).unwrap();+ assert_eq!(l, label);+ assert!((v - want).abs() < 1e-6, "{label}: {v} vs {want}");+ let text = guide_readout(h.state(), &xf, &g).unwrap();+ assert_eq!(text, format!("{label}: {}", designcraft_geom::units::format_measure(v, units)));+ }+ // While a guide is actually being dragged out of the top ruler, the readout is there.+ let ruler = pos2(rect.min.x + 200.0, rect.min.y - RULER / 2.0);+ h.hover_at(ruler);+ h.step();+ primary(&mut h, ruler, true);+ h.event(egui::Event::PointerMoved(dest));+ h.run_steps(2);+ let g = h.ctx.data(|d| d.get_temp::<GuideDrag>(egui::Id::unique(GUIDE_DRAG))).expect("dragging");+ assert_eq!(g.orientation, designcraft_doc::Orientation::Horizontal);+ assert!(guide_readout(h.state(), &xf, &g).is_some_and(|t| t.starts_with("Y: ")));+ primary(&mut h, dest, false);+ }++ /// Over a spread other than the one in the middle of the view, the readout measures that+ /// spread, the one the guide is dropped on: it reads the position the guide gets.+ #[test]+ fn the_guide_readout_measures_the_spread_under_the_pointer() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 5})).unwrap();+ app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap();+ let h = harness(app);+ let rect = h.state().canvas_rect.unwrap();+ let xf = Xf::new(rect, h.state().view().unwrap());+ let st = h.state().session.active().unwrap();+ let layout = CanvasLayout::new(&st.doc, false);+ let current = current_slot(h.state(), &layout).unwrap();+ // A point inside the last spread, well away from the one in view.+ let last = layout.slots.last().unwrap();+ assert_ne!(layout.slots.iter().position(|s| s.spread == last.spread), Some(current), "the last spread isn't the one in view");+ let inside = Point::new(last.bounds.center().x, last.bounds.y0 + (last.bounds.y1 - last.bounds.y0) * 0.3);+ let (r, sp) = layout.spread_at(inside).unwrap();+ assert_eq!(r, last.spread);+ let g =+ GuideDrag { orientation: designcraft_doc::Orientation::Horizontal, from: None, at: Some(xf.to_screen(inside)), mods: egui::Modifiers::NONE };+ let (label, v, _) = guide_measure(h.state(), &xf, &g).unwrap();+ assert_eq!(label, "Y");+ // The guide would be stored at `sp.y` on that spread, which its ruler reads from the zero point.+ // (To screen and back in f32: a few hundred-thousandths of a point.)+ assert!((v - (sp.y - 50.0)).abs() < 1e-3, "{v} vs {}", sp.y - 50.0);+ // An existing guide of another spread can't be dropped there (it only moves on its own+ // spread): no readout over this one, a readout over its own.+ let first = layout.slots[current].spread;+ let moving = GuideDrag {+ orientation: designcraft_doc::Orientation::Horizontal,+ from: Some((first, 0, 0)),+ at: Some(xf.to_screen(inside)),+ mods: egui::Modifiers::NONE,+ };+ assert!(guide_measure(h.state(), &xf, &moving).is_none(), "an existing guide over another spread");+ let own = layout.slots[current].bounds;+ let over_own = Point::new(own.center().x, own.y0 + (own.y1 - own.y0) * 0.3);+ let moving_here = GuideDrag { at: Some(xf.to_screen(over_own)), ..moving };+ assert!(guide_measure(h.state(), &xf, &moving_here).is_some(), "over its own spread");+ }++ /// The guide readout stays on the canvas: below right of the pointer in the open, flipped+ /// left or up near the right or bottom edge, and inside the canvas in every corner.+ #[test]+ fn the_guide_readout_stays_inside_the_canvas() {+ let area = Rect::from_min_max(pos2(50.0, 40.0), pos2(850.0, 640.0));+ let size = vec2(80.0, 14.0);+ let inside = |at: Pos2| {+ let r = Rect::from_min_size(at, size).expand(3.0);+ r.min.x >= area.min.x - 1e-3 && r.min.y >= area.min.y - 1e-3 && r.max.x <= area.max.x + 1e-3 && r.max.y <= area.max.y + 1e-3+ };+ assert_eq!(readout_at(pos2(400.0, 300.0), size, area), pos2(412.0, 312.0), "in the open: below right");+ let right = readout_at(pos2(845.0, 300.0), size, area);+ assert!(right.x + size.x < 845.0 && inside(right), "near the right edge: left of the pointer, {right:?}");+ let bottom = readout_at(pos2(400.0, 636.0), size, area);+ assert!(bottom.y + size.y < 636.0 && inside(bottom), "near the bottom: above it, {bottom:?}");+ for p in [area.min, pos2(area.max.x, area.min.y), area.max, pos2(area.min.x, area.max.y), pos2(-500.0, 2000.0)] {+ assert!(inside(readout_at(p, size, area)), "{p:?}");+ }+ // A canvas narrower than the label: pinned to its top left, not past it.+ let tiny = Rect::from_min_max(pos2(0.0, 0.0), pos2(40.0, 10.0));+ assert_eq!(readout_at(pos2(20.0, 5.0), size, tiny), pos2(3.0, 3.0));+ }++ #[test]+ fn rulers_and_xy_fields_measure_from_the_zero_point_on_every_spread() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ // Spread 0: page 1; spread 1: pages 2 and 3.+ app.run("file.new", json!({"pages": 3})).unwrap();+ app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap();+ app.session.prefs.dimensions_include_stroke = false;+ let mut h = harness(app);+ let rect = h.state().canvas_rect.unwrap();+ for (spread, x0) in [(0usize, 136.0), (1, 736.0)] {+ let app = h.state_mut();+ let id = app.run("frame.create", json!({"spread": spread, "rect": [x0, 70, x0 + 50.0, 120]})).unwrap()["id"].clone();+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ // X/Y (Control, Properties and Info panels).+ let r = crate::panels::sel_info(app).unwrap().page_rect;+ assert!((r.x0 - (x0 - 100.0)).abs() < 1e-6 && (r.y0 - 20.0).abs() < 1e-6, "spread {spread}: {r:?}");+ // The rulers, with that spread in view.+ let layout = CanvasLayout::new(&app.session.active().unwrap().doc, false);+ let slot = layout.slots[spread];+ let v = app.view_mut().unwrap();+ let zoom = v.zoom;+ let c = slot.bounds.center();+ v.origin = Point::new(c.x - rect.width() as f64 / 2.0 / zoom, c.y - rect.height() as f64 / 2.0 / zoom);+ h.run_steps(2);+ let app = h.state();+ let doc = app.session.active().unwrap().doc.clone();+ assert_eq!(current_slot(app, &layout), Some(spread));+ let o = ruler_zero(app, &doc, &layout).unwrap();+ assert!((o.x - slot.bounds.x0 - 100.0).abs() < 1e-6 && (o.y - slot.bounds.y0 - 50.0).abs() < 1e-6, "spread {spread}: {o:?}");+ }+ }++ /// Screen position of spread 0's point (x, y).+ fn screen_of(h: &Harness<'_, DesignApp>, x: f64, y: f64) -> Pos2 {+ let app = h.state();+ let st = app.session.active().unwrap();+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());+ xf.to_screen(CanvasLayout::new(&st.doc, st.editing_parents).xf(SpreadRef::Doc(0)) * Point::new(x, y))+ }++ /// A menu row: a button that isn't a toggle, named by its label, then its shortcut if it has+ /// one. Toggle buttons with the same name (the Task Bar's icons) don't match, nor do buttons+ /// right of the canvas (the Properties panel's Arrange).+ fn menu_row<'h>(h: &'h Harness<'_, DesignApp>, label: &'h str) -> Option<egui_kittest::Node<'h>> {+ let right = f64::from(h.state().canvas_rect.map_or(f32::INFINITY, |r| r.max.x));+ h.query_by(move |n| {+ n.role() == egui::accesskit::Role::Button+ && n.toggled().is_none()+ && n.bounding_box().is_none_or(|b| b.x0 < right)+ && n.label().is_some_and(|l| l == label || l.strip_prefix(label).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.contains(' ')))+ })+ }++ fn enabled(h: &Harness<'_, DesignApp>, label: &str) -> bool {+ use egui_kittest::kittest::NodeT;+ !menu_row(h, label).unwrap_or_else(|| panic!("no menu row {label}")).accesskit_node().is_disabled()+ }++ fn spread_items(h: &Harness<'_, DesignApp>) -> Vec<u64> {+ h.state().session.doc().unwrap().doc.spreads[0].items.iter().map(|i| i.id.0).collect()+ }++ fn selected(h: &Harness<'_, DesignApp>) -> Vec<u64> {+ h.state().session.doc().unwrap().selection.items.iter().map(|i| i.0).collect()+ }++ #[test]+ fn right_clicking_an_object_selects_it_and_its_menu_arranges_it() {+ 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": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ let b = app.run("frame.create", json!({"rect": [150, 150, 300, 300]})).unwrap()["id"].as_u64().unwrap();+ let mut h = harness(app);+ assert_eq!(selected(&h), [b]);+ let on_a = screen_of(&h, 60.0, 60.0);+ right_click(&mut h, on_a);+ assert_eq!(selected(&h), [a], "the object under the pointer is selected first");+ // An empty frame's menu: Content, but no Fitting (nothing to fit) and no text frame entries.+ assert!(menu_row(&h, "Content").is_some());+ assert!(menu_row(&h, "Fitting").is_none() && menu_row(&h, "Text Frame Options…").is_none());+ // Paste is available with nothing copied here: the system clipboard may hold another app's text.+ assert!(enabled(&h, "Copy") && enabled(&h, "Paste"));+ menu_row(&h, "Arrange").unwrap().click();+ h.run_steps(3);+ menu_row(&h, "Bring to Front").unwrap().click();+ h.run_steps(3);+ assert_eq!(spread_items(&h), [b, a]);+ assert!(menu_row(&h, "Arrange").is_none(), "choosing an entry closes the menu");+ }++ #[test]+ fn right_clicking_empty_canvas_offers_paste_after_a_copy() {+ 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": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ app.run("edit.copy", json!({})).unwrap();+ app.select_tool("rectangleFrame");+ let mut h = harness(app);+ let empty = screen_of(&h, 400.0, 500.0);+ right_click(&mut h, empty);+ assert_eq!(selected(&h), [a], "a right-click on nothing keeps the selection");+ assert!(menu_row(&h, "Arrange").is_none(), "the page menu, not the object menu");+ assert!(enabled(&h, "Paste in Place"));+ assert!(menu_row(&h, "✓ Show/Hide Rulers").is_some(), "toggles show their state");+ // Escape closes the menu and does nothing else: the tool would deselect, the shortcuts+ // would switch to the Selection tool.+ h.key_press(egui::Key::Escape);+ h.run_steps(3);+ assert!(menu_row(&h, "Paste in Place").is_none());+ assert_eq!((h.state().session.tool_id(), selected(&h)), ("rectangleFrame", vec![a]));+ right_click(&mut h, empty);+ menu_row(&h, "Paste").unwrap().click();+ h.run_steps(3);+ assert_eq!(spread_items(&h).len(), 2);+ }++ #[test]+ fn right_clicking_another_object_while_the_menu_is_open_reopens_it_there() {+ 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": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ let b = app.run("frame.create", json!({"rect": [36, 600, 200, 760]})).unwrap()["id"].as_u64().unwrap();+ let mut h = harness(app);+ // The menu opens down from A, with the pointer on its first row (no submenu open); B is below it.+ let (on_a, on_b) = (screen_of(&h, 60.0, 60.0), screen_of(&h, 50.0, 700.0));+ right_click(&mut h, on_a);+ assert_eq!(selected(&h), [a]);+ assert!(menu_row(&h, "Arrange").is_some());+ right_click(&mut h, on_b);+ assert_eq!(selected(&h), [b]);+ assert!(menu_row(&h, "Arrange").is_some(), "the menu reopens at the new click");+ }++ #[test]+ fn a_context_menu_in_one_pane_keeps_the_keys_from_the_other() {+ 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": [36, 36, 100, 100]})).unwrap()["id"].as_u64().unwrap();+ app.select_tool("rectangleFrame");+ app.split = true;+ let mut h = harness(app);+ // The focused pane is the left one; this point is near its right edge, away from the frame.+ let left = h.state().canvas_rect.unwrap();+ right_click(&mut h, pos2(left.max.x - 40.0, left.center().y));+ assert!(menu_row(&h, "Paste in Place").is_some());+ // Escape closes the left pane's menu before the right pane handles the keys.+ h.key_press(egui::Key::Escape);+ h.run_steps(3);+ assert!(menu_row(&h, "Paste in Place").is_none());+ assert_eq!((h.state().session.tool_id(), selected(&h)), ("rectangleFrame", vec![a]));+ }++ #[test]+ fn right_clicking_text_keeps_the_selected_text_or_places_the_caret() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [36, 36, 400, 200], "content": "text"})).unwrap();+ app.select_tool("type");+ app.run("text.insert", json!({"text": "Hello world"})).unwrap();+ let sid = *app.session.doc().unwrap().doc.stories.keys().next().unwrap();+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 5})).unwrap();+ let mut h = harness(app);+ let text_sel = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().selection.text.as_ref().map(|t| (t.anchor, t.focus));+ // Inside "Hello": the selection stays.+ let inside = screen_of(&h, 45.0, 44.0);+ right_click(&mut h, inside);+ assert_eq!(text_sel(&h), Some((0, 5)));+ assert!(menu_row(&h, "Paste without Formatting").is_some(), "the text menu");+ h.key_press(egui::Key::Escape);+ h.run_steps(3);+ // Past the end of the line: the caret goes there.+ let past_end = screen_of(&h, 300.0, 44.0);+ right_click(&mut h, past_end);+ assert_eq!(text_sel(&h), Some((11, 11)));+ assert!(menu_row(&h, "Paste without Formatting").is_some());+ }++ #[test]+ fn rows_hidden_in_the_menu_bar_are_hidden_in_context_menus() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap();+ app.ui.hidden_menu_items.push(crate::menus::menu_key("Object/Arrange", "Bring to Front"));+ let mut h = harness(app);+ let on_frame = screen_of(&h, 60.0, 60.0);+ right_click(&mut h, on_frame);+ menu_row(&h, "Arrange").unwrap().click();+ h.run_steps(3);+ assert!(menu_row(&h, "Bring to Front").is_none());+ assert!(menu_row(&h, "Send to Back").is_some());+ assert!(h.query_by_label("Show All Menu Items").is_some());+ }++ #[test]+ fn a_secondary_drag_neither_moves_marquees_nor_draws() {+ 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": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ let mut h = harness(app);+ // A secondary-button drag between spread points.+ let drag = |h: &mut Harness<'_, DesignApp>, from: (f64, f64), to: (f64, f64)| {+ let (from, to) = (screen_of(h, from.0, from.1), screen_of(h, to.0, to.1));+ h.hover_at(from);+ h.step();+ h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });+ h.step();+ for t in [0.25, 0.5, 0.75, 1.0] {+ h.event(egui::Event::PointerMoved(from + (to - from) * t));+ h.step();+ }+ h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });+ h.run_steps(3);+ };+ let xf = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.item(designcraft_doc::ItemId(a)).unwrap().xf;+ let before = xf(&h);+ // Selection tool: on the object (no move), and from empty page across it (no marquee).+ drag(&mut h, (100.0, 100.0), (300.0, 300.0));+ assert_eq!(xf(&h), before);+ h.state_mut().run("edit.deselectAll", json!({})).unwrap();+ drag(&mut h, (400.0, 400.0), (20.0, 20.0));+ assert!(selected(&h).is_empty());+ // Rectangle Frame tool: no frame.+ h.state_mut().select_tool("rectangleFrame");+ drag(&mut h, (300.0, 300.0), (500.0, 500.0));+ assert_eq!(spread_items(&h), [a]);+ }++ /// A text frame holding `text`, the Type tool, and a harness stepping at 60 fps (clicks in a+ /// row must land within the double-click delay).+ fn typing(text: &str) -> (Harness<'static, DesignApp>, u64) {+ 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, 400, 400], "content": "text", "text": text})).unwrap();+ let id = r["id"].as_u64().unwrap();+ app.run("tool.select", json!({"tool": "type"})).unwrap();+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(+ |ui, app: &mut DesignApp| {+ let ctx = ui.ctx().clone();+ app.logic(&ctx);+ app.ui(ui);+ },+ app,+ );+ h.run_steps(4);+ (h, id)+ }++ /// The screen point over the first line of frame `id` where a click puts the caret at a byte+ /// in `bytes`.+ fn screen_at(h: &mut Harness<'_, DesignApp>, id: u64, bytes: std::ops::Range<usize>) -> Pos2 {+ let mut x = 74.0;+ let p = loop {+ assert!(x < 400.0, "no point on the first line hits {bytes:?}");+ h.state_mut().run("text.placeCaret", json!({"frame": id, "point": [x, 80.0]})).unwrap();+ if h.state().session.doc().unwrap().selection.text.is_some_and(|t| bytes.contains(&t.focus)) {+ break Point::new(x, 80.0);+ }+ x += 1.0;+ };+ h.state_mut().run("edit.deselectAll", json!({})).unwrap();+ let app = h.state();+ let c = app.session.layout().to_canvas(SpreadRef::Doc(0), p);+ Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(c)+ }++ fn click(h: &mut Harness<'_, DesignApp>, p: Pos2) {+ for pressed in [true, false] {+ h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });+ h.step();+ }+ }++ fn selected_range(h: &Harness<'_, DesignApp>) -> std::ops::Range<usize> {+ h.state().session.doc().unwrap().selection.text.map(|t| t.range()).unwrap_or_default()+ }++ #[test]+ fn clicks_in_a_row_select_word_line_paragraph_with_return_and_story() {+ let text = "One two. Three four! Five six.\nSecond para here.";+ let (mut h, id) = typing(text);+ // Inside "Three": double-click selects the word, then line and paragraph with return.+ let p = screen_at(&mut h, id, 10..14);+ h.hover_at(p);+ h.step();+ let mut got = vec![];+ for _ in 0..5 {+ click(&mut h, p);+ let r = selected_range(&h);+ got.push(text[r].to_string());+ }+ assert_eq!(got[1..], ["Three", "One two. Three four! Five six.", "One two. Three four! Five six.\n", text], "{got:?}");+ assert!(got[0].is_empty(), "one click places the caret: {got:?}");+ }++ #[test]+ fn esc_that_closes_a_dialog_keeps_the_type_tool_and_its_text_selection() {+ let (mut h, id) = typing("One two three");+ // A click in the text gives the canvas the keyboard focus, as when typing.+ let p = screen_at(&mut h, id, 5..6);+ h.hover_at(p);+ h.step();+ for _ in 0..2 {+ click(&mut h, p);+ }+ h.run_steps(4);+ let words = selected_range(&h);+ assert_eq!(words, 4..7, "the double-click selects \"two\"");+ let app = h.state_mut();+ let name = app.run("style.character.create", json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();+ app.ui.dialog = Some(crate::dialogs::Dialog::new("characterStyleOptions", json!({"name": name})));+ h.run_steps(3);+ h.key_press(egui::Key::Escape);+ h.run_steps(3);+ assert!(h.state().ui.dialog.is_none(), "Esc closes the dialog");+ assert_eq!((h.state().session.tool_id(), selected_range(&h)), ("type", words));+ // With no dialog open, Esc in the text still leaves it for the Selection tool.+ h.key_press(egui::Key::Escape);+ h.run_steps(3);+ assert_eq!(h.state().session.tool_id(), "selection");+ }++ #[test]+ fn slow_clicks_do_not_add_up() {+ let (mut h, id) = typing("One two. Three four!");+ let p = screen_at(&mut h, id, 10..14);+ h.hover_at(p);+ h.step();+ for _ in 0..3 {+ click(&mut h, p);+ h.run_steps(30);+ }+ assert!(selected_range(&h).is_empty(), "three clicks half a second apart leave a caret: {:?}", selected_range(&h));+ }++ /// A viewport wider than the GPU's largest texture: the canvas texture is sampled down, and an+ /// edit repaints it whole. A region repainted in view pixels would land in the wrong place,+ /// or outside the texture (a wgpu validation error). A view that fits is still patched.+ #[test]+ fn an_edit_repaints_a_canvas_texture_sampled_down_to_the_gpu_limit_whole() {+ for (width, sampled_down) in [(1440.0, false), (2600.0, true)] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let frame = app.run("frame.create", json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Text"})).unwrap();+ let mut h = Harness::builder().with_size(vec2(width, 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 limit = h.ctx.input(|i| i.max_texture_side);+ let size = h.state().canvas.texture.as_ref().map(|t| t.size()).unwrap();+ assert!(size[0] <= limit && size[1] <= limit, "{size:?}");+ let shown = h.state().canvas.shown.unwrap().size;+ assert_eq!(shown.0 > limit as f32, sampled_down, "view {shown:?}, limit {limit}");+ let patches = h.state().canvas.patches;+ // A small edit: one more character in the frame.+ h.state_mut().run("text.insert", json!({"story": frame["story"], "at": 4, "text": "s"})).unwrap();+ h.run_steps(6);+ assert_eq!(h.state().canvas.patches == patches, sampled_down, "width {width}");+ assert_eq!(h.state().canvas.texture.as_ref().map(|t| t.size()), Some(size));+ }+ }++ /// ⌥E then I types "í" on a Mac: the input method composes the dead key's accent, which+ /// it does only for a window that turned it on. The canvas never did, so ⌥E typed "e".+ #[test]+ fn dead_keys_compose_through_the_input_method() {+ let (mut h, id) = typing("T");+ h.state_mut().run("text.placeCaret", json!({"frame": id, "point": [390.0, 80.0]})).unwrap();+ h.run_steps(2);+ assert!(h.output().platform_output.ime.is_some(), "a text caret turns the input method on");+ h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "´".into(), active_range_chars: None }));+ h.run_steps(2);+ let text = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.stories.values().map(|s| s.text.clone()).collect::<String>();+ assert_eq!(text(&h), "T´", "the accent being composed shows in the story");+ assert!(h.state().session.tool_composing(), "and is marked as composed, not typed");+ h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: String::new(), active_range_chars: None }));+ h.event(egui::Event::Ime(egui::ImeEvent::Commit("í".into())));+ h.run_steps(2);+ assert_eq!(text(&h), "Tí");+ assert!(!h.state().session.tool_composing());+ // Moving the caret mid-composition keeps the accent as typed and tells the input method+ // to drop its copy.+ h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "˜".into(), active_range_chars: None }));+ h.run_steps(2);+ h.state_mut().run("text.move", json!({"dir": "left"})).unwrap();+ h.step();+ assert_eq!(text(&h), "Tí˜");+ assert!(!h.state().session.tool_composing());+ assert!(h.output().platform_output.ime.as_ref().is_some_and(|i| i.should_interrupt_composition));+ assert!(h.state_mut().take_ime_discard());+ // Another tool takes no text: the input method is off.+ h.state_mut().run("tool.select", json!({"tool": "selection"})).unwrap();+ h.run_steps(2);+ assert!(h.output().platform_output.ime.is_none());+ }++ #[test]+ fn tools_show_their_own_cursors_over_the_page() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let mut h = harness(app);+ let p = h.state().canvas_rect.unwrap().center();+ let mut shown = |tool: &str| {+ h.state_mut().run("tool.select", json!({"tool": tool})).unwrap();+ h.hover_at(p);+ h.run_steps(2);+ let out = &h.output().platform_output;+ (out.cursor_icon, out.cursor_image.clone())+ };+ let (pen, direct, text, selection) = (shown("pen"), shown("directSelection"), shown("type"), shown("selection"));+ let ppp = h.ctx.pixels_per_point();+ let images = &mut h.state_mut().cursors;+ match crate::cursors::mode() {+ crate::cursors::Mode::Os => {+ assert_eq!(pen.1, images.get(Cursor::Pen, ppp), "Pen");+ assert_eq!(direct.1, images.get(Cursor::ArrowHollow, ppp), "Direct Selection");+ assert_eq!(selection.1, images.get(Cursor::Arrow, ppp), "Selection");+ assert_eq!(text, (egui::CursorIcon::Text, None), "the I-beam stays a system cursor");+ }+ crate::cursors::Mode::Painted => {+ assert_eq!((pen.0, direct.0, selection.0), (egui::CursorIcon::None, egui::CursorIcon::None, egui::CursorIcon::None));+ }+ crate::cursors::Mode::System => assert_eq!(pen, (egui::CursorIcon::Crosshair, None)),+ }+ }++ #[test]+ fn document_grid_is_drawn_where_points_snap_to_it() {+ use designcraft_tools::{SnapView, ToolContext};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let doc = app.session.active().unwrap().doc.clone();+ let layout = CanvasLayout::new(&doc, false);+ let sr = SpreadRef::Doc(0);+ // Where the grid snaps a point in the first page (72 pt / 8 subdivisions = 9 pt).+ let page = doc.spreads[0].pages[0].bounds();+ let sel = Selection::default();+ let cx = ToolContext {+ doc: &doc,+ selection: &sel,+ cache: &app.session.cache,+ layout: &layout,+ zoom: 1.0,+ layer: doc.layers[0].id,+ snap: SnapView { snap_to_document_grid: true, zone_px: 20.0, ..SnapView::OFF },+ unit: Unit::Points,+ stroke_in_front: false,+ };+ let (snapped, _) = designcraft_tools::snap::snap_point(&cx, sr, Point::new(page.x0 + 31.3, page.y0 + 47.9));+ assert_eq!((snapped.x - page.x0, snapped.y - page.y0), (27.0, 45.0));+ // Render 40 × 40 pt around it at 4 px/pt.+ let scale = 4.0;+ let corner = layout.xf(sr) * Point::new(snapped.x - 20.0, snapped.y - 20.0);+ let view = Affine::scale(scale) * Affine::translate((-corner.x, -corner.y));+ let placed: Vec<_> = layout.slots.iter().map(|s| designcraft_render::Placed { spread: s.spread, xf: s.xf }).collect();+ let render = |app: &DesignApp| {+ let opts = screen_options(app, &layout, false, 1.0);+ designcraft_render::Renderer::new().render(&doc, &app.session.cache, &placed, (160, 160), view, &opts)+ };+ // The snapped point is at pixel (80, 80); halfway to the next line is 18 px further.+ let darkest = |img: &designcraft_render::Rendered, xs: [u32; 2], ys: [u32; 2]| {+ (xs[0]..xs[1]).flat_map(|x| (ys[0]..ys[1]).map(move |y| (x, y))).map(|(x, y)| img.pixel(x, y)[0]).min().unwrap()+ };+ let off = render(&app);+ assert_eq!(darkest(&off, [78, 82], [60, 64]), 255, "no grid while it is hidden");+ app.run("view.documentGrid", json!({})).unwrap();+ let on = render(&app);+ assert!(darkest(&on, [79, 81], [60, 64]) < 250, "a vertical line at the snapped x");+ assert!(darkest(&on, [60, 64], [79, 81]) < 250, "a horizontal line at the snapped y");+ assert_eq!(darkest(&on, [96, 100], [96, 100]), 255, "nothing between lines");+ // Preview hides it.+ app.ui.screen_mode = ScreenMode::Preview;+ assert!(screen_options(&app, &layout, true, 1.0).document_grid.is_empty());+ }++ /// egui moves keyboard focus on a plain arrow key or Tab, and Space/Return then clicks the+ /// focused widget (e.g. the status bar's spread buttons) while typing still reaches the text.+ #[test]+ fn arrow_keys_and_tab_keep_keyboard_focus_on_the_canvas() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 3})).unwrap();+ let f = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Hello"})).unwrap();+ app.select_tool("type");+ let mut h = harness(app);+ let p = {+ let app = h.state();+ let st = app.session.active().unwrap();+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());+ xf.to_screen(layout.xf(SpreadRef::Doc(0)) * Point::new(100.0, 60.0))+ };+ h.hover_at(p);+ h.step();+ for pressed in [true, false] {+ h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });+ h.step();+ }+ h.run_steps(2);+ let focus = h.ctx.memory(|m| m.focused());+ assert!(focus.is_some(), "a click on the canvas takes keyboard focus");+ let view = *h.state().view().unwrap();+ for key in [egui::Key::ArrowDown, egui::Key::Space, egui::Key::ArrowRight, egui::Key::Enter, egui::Key::Tab, egui::Key::Escape] {+ h.key_press(key);+ if key == egui::Key::Space {+ h.event(egui::Event::Text(" ".into()));+ }+ h.run_steps(2);+ assert_eq!(h.ctx.memory(|m| m.focused()), focus, "{key:?} keeps keyboard focus on the canvas");+ }+ let v = *h.state().view().unwrap();+ assert_eq!((v.origin, v.zoom), (view.origin, view.zoom), "the view stays where it was");+ let text = h.state_mut().session.execute("story.get", &json!({"story": f["story"]})).unwrap()["text"].clone();+ assert_eq!(text, "Hello \n\t", "Space, Return and Tab reach the text");+ }++ #[test]+ fn rulers_open_no_units_menu_without_a_document() {+ let mut h = harness(DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()));+ let Some(rect) = h.state().canvas_rect else { return };+ right_click(&mut h, pos2(rect.center().x, rect.min.y - RULER / 2.0));+ assert!(h.query_by_label(" Points").is_none());+ }++ /// One frame of the whole app with `events`; returns what it asks of the system IME.+ fn ime_frame(app: &mut DesignApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Option<egui::output::IMEOutput> {+ let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), events, ..Default::default() };+ let mut out = ctx.run_ui(raw, |ui| {+ app.logic(ui.ctx());+ app.ui(ui);+ });+ out.textures_delta.clear();+ out.platform_output.ime+ }++ /// An edit patches the canvas texture in place only while that texture is at full resolution:+ /// past the GPU's texture limit `upload` shrinks it, and a full-resolution patch written into+ /// it is a renderer validation error.+ #[test]+ fn edits_patch_the_canvas_only_at_full_resolution() {+ for (max_side, patches) in [(None, true), (Some(1024), false)] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let frame = |app: &mut DesignApp| {+ // Wider than the limit (egui's font atlas needs at least 1024).+ let mut raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1900.0, 900.0))), ..Default::default() };+ if let Some(m) = max_side {+ raw.max_texture_side = Some(m);+ }+ let mut out = ctx.run_ui(raw, |ui| {+ app.logic(ui.ctx());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ app.run("file.new", json!({})).unwrap();+ for _ in 0..3 {+ frame(&mut app);+ }+ app.run("frame.create", json!({"rect": [36, 36, 60, 60]})).unwrap();+ frame(&mut app);+ let size = app.canvas.texture.as_ref().unwrap().size();+ assert!(max_side.is_none_or(|m| size[0] <= m && size[1] <= m), "{size:?}");+ assert_eq!(app.canvas.patches > 0, patches, "limit {max_side:?}");+ }+ }++ /// The Type tool's caret at the end of a new text frame holding `text`, the app's first frames+ /// drawn; returns the story id.+ fn typing_app(app: &mut DesignApp, ctx: &egui::Context, text: &str) -> Value {+ app.run("file.new", json!({})).unwrap();+ let f = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": text})).unwrap();+ let sid = f["story"].clone();+ app.session.execute("text.select", &json!({"story": sid, "anchor": text.len(), "focus": text.len()})).unwrap();+ app.select_tool("type");+ for _ in 0..4 {+ ime_frame(app, ctx, vec![]);+ }+ sid+ }++ fn story_text(app: &mut DesignApp, sid: &Value) -> String {+ app.session.execute("story.get", &json!({"story": sid})).unwrap()["text"].as_str().unwrap().to_string()+ }++ /// Spread point `p` on screen.+ fn on_screen(app: &DesignApp, p: Point) -> Pos2 {+ let st = app.session.active().unwrap();+ let c = CanvasLayout::new(&st.doc, st.editing_parents).to_canvas(SpreadRef::Doc(0), p);+ Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(c)+ }++ fn preedit(t: &str, c: usize) -> egui::Event {+ egui::Event::Ime(egui::ImeEvent::Preedit { text: t.into(), active_range_chars: Some(c..c) })+ }++ /// Extract `(surrounding text, cursor, anchor)` from an IME output.+ fn ime_payload(ime: &egui::output::IMEOutput) -> Option<(&str, usize, usize)> {+ ime.surrounding_text.available().map(|p| (p.text.as_str(), p.cursor, p.anchor))+ }++ /// Set an engine text selection for a test fixture.+ fn text_selection(app: &mut DesignApp, sid: &Value, anchor: usize, focus: usize) {+ app.session.execute("text.select", &json!({"story": sid, "anchor": anchor, "focus": focus})).unwrap();+ }++ struct NativeClickFixture {+ app: DesignApp,+ ctx: egui::Context,+ target: Value,+ old: Value,+ at: Pos2,+ focus: usize,+ }++ /// Build the old and target stories, measure an interior target caret, and leave the old story selected before the click.+ fn native_gui_click_fixture() -> NativeClickFixture {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let old = typing_app(&mut app, &ctx, "Old story");+ let frame = app.run("frame.create", json!({"rect": [36, 280, 300, 400], "content": "text", "text": "Target story"})).unwrap();+ let target = frame["story"].clone();+ // Measure an interior first-word caret through the engine, rather than guessing a+ // font-dependent screen pixel or clicking the frame's resize border.+ let (point, focus) = (50..180)+ .find_map(|x| {+ app.run("text.placeCaret", json!({"frame": frame["id"], "point": [x, 290]})).unwrap();+ let sel = app.session.doc().unwrap().selection.text.unwrap();+ assert_eq!(sel.story.0, target.as_u64().unwrap());+ (1..5).contains(&sel.focus).then_some((Point::new(f64::from(x), 290.0), sel.focus))+ })+ .expect("an interior point in the target's first word");+ text_selection(&mut app, &old, "Old story".len(), "Old story".len());+ for _ in 0..4 {+ ime_frame(&mut app, &ctx, vec![]);+ }+ let at = on_screen(&app, point);+ assert!(app.canvas_rect.unwrap().contains(at));+ ime_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);+ assert_eq!(app.session.doc().unwrap().selection.text.unwrap().story.0, old.as_u64().unwrap());+ NativeClickFixture { app, ctx, target, old, at, focus }+ }++ /// Build a primary pointer press or release event at a position.+ fn native_gui_button(pos: Pos2, pressed: bool) -> egui::Event {+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }+ }++ /// The 37-byte Devanagari line the native run had in the previous story.+ const NATIVE_GUI_OLD_DEVANAGARI: &str = "नमस्ते दुनिया";++ /// The click fixture with the non-empty selection in the previous story that the native+ /// Windows run had (37-byte Devanagari, 0..37). A non-empty selection shows the contextual+ /// task bar; keep it present but clear of the target click.+ fn native_gui_selected_old_click_fixture() -> NativeClickFixture {+ let mut f = native_gui_click_fixture();+ text_selection(&mut f.app, &f.old, 0, "Old story".len());+ f.app.run("text.insert", json!({"text": NATIVE_GUI_OLD_DEVANAGARI})).unwrap();+ text_selection(&mut f.app, &f.old, 0, NATIVE_GUI_OLD_DEVANAGARI.len());+ for _ in 0..4 {+ ime_frame(&mut f.app, &f.ctx, vec![]);+ }+ let sel = f.app.session.doc().unwrap().selection.text.unwrap();+ assert_eq!((sel.story.0, sel.anchor, sel.focus), (f.old.as_u64().unwrap(), 0, NATIVE_GUI_OLD_DEVANAGARI.len()));+ assert_eq!(NATIVE_GUI_OLD_DEVANAGARI.len(), 37, "the native fixture's Devanagari line was 37 UTF-8 bytes");+ assert!(!sel.is_caret(), "the previous story's selection is non-empty");+ assert!(!context_menu_open(&f.ctx), "no context menu owns this frame's keys");+ assert!(f.app.ui.dialog.is_none() && f.app.ui.palette.is_none(), "no modal owns the keyboard");+ assert!(!f.ctx.text_edit_focused(), "no text field owns the keyboard");+ assert_eq!(f.app.pane, f.app.focus_pane, "the canvas pane takes the keyboard");+ let task_bar = egui::Id::unique(("task_bar", f.ctx.viewport_id(), f.app.pane));+ let bar = f.ctx.memory(|m| m.area_rect(task_bar)).expect("the old selection shows the floating task bar");+ assert!(!bar.contains(f.at), "the floating task bar does not cover the target click at {bar:?}");+ f+ }++ /// Run one raw event batch, optionally force a discarded pass, and return the pointer edges observed by each pass.+ fn native_gui_input(f: &mut NativeClickFixture, events: Vec<egui::Event>, discard: bool) -> Vec<(bool, bool, bool)> {+ let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), events, ..Default::default() };+ let mut edges = Vec::new();+ let mut out = f.ctx.run_ui(raw, |ui| {+ edges.push(ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_released(), i.pointer.press_origin().is_some())));+ f.app.logic(ui.ctx());+ f.app.ui(ui);+ if discard && edges.len() == 1 {+ ui.ctx().request_discard("native same-batch click exactly-once regression");+ }+ });+ if discard {+ assert_eq!(out.platform_output.num_completed_passes, 2, "the requested discarded pass actually ran");+ }+ out.textures_delta.clear();+ edges+ }++ /// Assert that the primary button, canvas press state and tool gesture are all released.+ fn native_gui_released(f: &NativeClickFixture) {+ assert!(!f.ctx.input(|i| i.pointer.primary_down()), "the native primary button is up");+ let down = f.ctx.data(|d| d.get_temp::<bool>(egui::Id::unique(("canvas_pointer_down", f.app.pane)))).unwrap_or(false);+ assert!(!down, "the canvas retained a released pointer");+ assert!(!f.app.session.tool_busy(), "a released click must not leave a tool gesture");+ }++ /// Create an independently measured second-story caret farther apart than the double-click distance.+ fn native_gui_second_click_target(f: &mut NativeClickFixture) -> (Value, Pos2, usize) {+ let frame = f.app.run("frame.create", json!({"rect": [330, 280, 575, 400], "content": "text", "text": "Second story"})).unwrap();+ let story = frame["story"].clone();+ let (point, focus) = (345..465)+ .find_map(|x| {+ f.app.run("text.placeCaret", json!({"frame": frame["id"], "point": [x, 290]})).unwrap();+ let sel = f.app.session.doc().unwrap().selection.text.unwrap();+ assert_eq!(sel.story.0, story.as_u64().unwrap());+ (1..5).contains(&sel.focus).then_some((Point::new(f64::from(x), 290.0), sel.focus))+ })+ .expect("an independently measured interior caret in the second story");+ text_selection(&mut f.app, &f.old, "Old story".len(), "Old story".len());+ for _ in 0..4 {+ ime_frame(&mut f.app, &f.ctx, vec![]);+ }+ let at = on_screen(&f.app, point);+ assert!(f.app.canvas_rect.unwrap().contains(f.at));+ assert!(f.app.canvas_rect.unwrap().contains(at));+ let max_click_dist = f.ctx.options(|o| o.input_options.max_click_dist);+ assert!((at - f.at).length() > max_click_dist, "the two target presses must not form a double click");+ (story, at, focus)+ }++ /// Two completed clicks in one batch use the last press once, emit one caret/release pair, add no history, and type at the final caret.+ #[test]+ fn native_gui_two_completed_clicks_use_last_primary_press_once() {+ for reverse in [false, true] {+ for discard in [false, true] {+ let mut f = native_gui_click_fixture();+ let (second, second_at, second_focus) = native_gui_second_click_target(&mut f);+ let (first_at, last_at, final_story, final_focus) =+ if reverse { (second_at, f.at, f.target.clone(), f.focus) } else { (f.at, second_at, second.clone(), second_focus) };+ let initial = f.app.session.doc().unwrap().selection.text.unwrap();+ assert_eq!((initial.story.0, initial.anchor, initial.focus), (f.old.as_u64().unwrap(), "Old story".len(), "Old story".len()));+ let undo = f.app.session.doc().unwrap().history.undo.len();+ let journal = f.app.session.journal.len();+ let edges = native_gui_input(+ &mut f,+ vec![+ egui::Event::PointerMoved(first_at),+ native_gui_button(first_at, true),+ native_gui_button(first_at, false),+ egui::Event::PointerMoved(last_at),+ native_gui_button(last_at, true),+ native_gui_button(last_at, false),+ ],+ discard,+ );+ assert_eq!(edges[0], (true, true, false), "both completed clicks leave no held origin");+ assert_eq!(edges.iter().filter(|e| e.0).count(), 1, "discard must not replay either press");+ let sel = f.app.session.doc().unwrap().selection.text.unwrap();+ assert_eq!(+ (sel.story.0, sel.anchor, sel.focus),+ (final_story.as_u64().unwrap(), final_focus, final_focus),+ "reverse={reverse}, discard={discard}"+ );+ let commands = &f.app.session.journal[journal..];+ assert_eq!(+ commands.iter().filter(|(id, _)| id == "text.placeCaret").count(),+ 1,+ "one aggregate canvas selection, reverse={reverse}, discard={discard}"+ );+ assert_eq!(+ commands.iter().filter(|(id, _)| id == "text.release").count(),+ 1,+ "one corresponding release, reverse={reverse}, discard={discard}"+ );+ let clicks = f.ctx.data(|d| d.get_temp::<Clicks>(egui::Id::unique(("canvas_clicks", f.app.pane)))).expect("one recovered canvas press");+ assert_eq!(clicks.n, 1, "separated clicks and discarded passes must not select a word");+ assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo, "pointer selection adds no document history");+ native_gui_released(&f);+ native_gui_input(&mut f, vec![egui::Event::Text("!".into())], false);+ let mut target_text = "Target story".to_owned();+ let mut second_text = "Second story".to_owned();+ if reverse {+ target_text.insert(final_focus, '!');+ } else {+ second_text.insert(final_focus, '!');+ }+ assert_eq!(story_text(&mut f.app, &f.target), target_text);+ assert_eq!(story_text(&mut f.app, &second), second_text);+ assert_eq!(story_text(&mut f.app, &f.old), "Old story");+ assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo + 1, "typing at the final caret is one edit");+ native_gui_released(&f);+ }+ }+ }++ /// A non-finite final press rejects the click instead of reviving an earlier valid press; later motion cannot drag.+ #[test]+ fn native_gui_nonfinite_final_press_cannot_reuse_an_earlier_click() {+ for discard in [false, true] {+ let mut f = native_gui_click_fixture();+ let at = f.at;+ let initial = f.app.session.doc().unwrap().selection.text;+ let undo = f.app.session.doc().unwrap().history.undo.len();+ let journal = f.app.session.journal.len();+ let edges = native_gui_input(+ &mut f,+ vec![+ egui::Event::PointerMoved(at),+ native_gui_button(at, true),+ native_gui_button(at, false),+ native_gui_button(pos2(f32::NAN, at.y), true),+ egui::Event::PointerMoved(at),+ native_gui_button(at, false),+ ],+ discard,+ );+ assert_eq!(edges[0], (true, true, false));+ assert_eq!(edges.iter().filter(|e| e.0).count(), 1, "discard must not replay malformed input");+ assert_eq!(+ f.app.session.doc().unwrap().selection.text,+ initial,+ "discard={discard}: reject the last press instead of reviving an earlier valid one"+ );+ assert!(f.app.session.journal[journal..].iter().all(|(id, _)| id != "text.placeCaret" && id != "text.release"));+ assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo);+ assert_eq!(story_text(&mut f.app, &f.target), "Target story");+ assert_eq!(story_text(&mut f.app, &f.old), "Old story");+ native_gui_released(&f);+ native_gui_input(&mut f, vec![egui::Event::PointerMoved(at + vec2(90.0, 0.0))], false);+ assert_eq!(f.app.session.doc().unwrap().selection.text, initial, "motion after the invalid released press cannot drag");+ native_gui_released(&f);+ }+ }++ /// A same-batch click switches story exactly once; typing, undo and redo affect only the target story, including discarded-pass runs.+ #[test]+ fn native_gui_same_batch_click_switches_story_once_before_typing() {+ for discard in [false, true] {+ let mut f = native_gui_click_fixture();+ let undo = f.app.session.doc().unwrap().history.undo.len();+ let at = f.at;+ let edges = native_gui_input(&mut f, vec![egui::Event::PointerMoved(at), native_gui_button(at, true), native_gui_button(at, false)], discard);+ assert_eq!(edges[0], (true, true, false), "the real input consumed both edges and cleared the origin");+ assert_eq!(edges.iter().filter(|e| e.0).count(), 1, "a discarded pass must not replay the press");+ let selection = f.app.session.doc().unwrap().selection.text.unwrap();+ assert_eq!((selection.story.0, selection.anchor, selection.focus), (f.target.as_u64().unwrap(), f.focus, f.focus), "discard={discard}");+ let clicks = f.ctx.data(|d| d.get_temp::<Clicks>(egui::Id::unique(("canvas_clicks", f.app.pane)))).expect("one actual canvas click");+ assert_eq!(clicks.n, 1, "discard={discard}: replay must not turn a caret into word selection");+ native_gui_released(&f);+ assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo, "a click is not a document edit");+ let end = |pressed| egui::Event::Key { key: egui::Key::End, physical_key: None, pressed, repeat: false, modifiers: Default::default() };+ native_gui_input(&mut f, vec![end(true), end(false)], false);+ let caret = f.app.session.doc().unwrap().selection.text.unwrap();+ assert_eq!((caret.story.0, caret.focus), (f.target.as_u64().unwrap(), "Target story".len()));+ native_gui_input(&mut f, vec![egui::Event::Text("!".into())], false);+ assert_eq!(story_text(&mut f.app, &f.target), "Target story!");+ assert_eq!(story_text(&mut f.app, &f.old), "Old story");+ assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo + 1, "one typed edit, including discarded-pass control");+ f.app.run("edit.undo", json!({})).unwrap();+ assert_eq!(story_text(&mut f.app, &f.target), "Target story");+ assert_eq!(story_text(&mut f.app, &f.old), "Old story");+ f.app.run("edit.redo", json!({})).unwrap();+ assert_eq!(story_text(&mut f.app, &f.target), "Target story!");+ assert_eq!(story_text(&mut f.app, &f.old), "Old story");+ native_gui_released(&f);+ }+ }++ /// The native Windows failure: with a non-empty selection in another story, a click that+ /// switches stories followed by End in the same job left the new story's caret at the click+ /// point. End in a later job worked. Drive the actual app UI and actual pointer/key events in+ /// one batch, in split batches, and with End while the press is still held; discard a pass to+ /// cover replay. The End press must reach the type tool once and win over the click, wherever+ /// the pointer release falls, and typing must go there once.+ #[test]+ fn native_gui_click_then_end_in_one_batch_keeps_the_target_caret_at_the_story_end() {+ let names = ["same batch, click events first", "click batch then End batch", "End while the press is held"];+ for (layout, name) in names.into_iter().enumerate() {+ for discard in [false, true] {+ let mut f = native_gui_selected_old_click_fixture();+ let (at, target, old) = (f.at, f.target.clone(), f.old.clone());+ let undo = f.app.session.doc().unwrap().history.undo.len();+ let journal = f.app.session.journal.len();+ let moved = || egui::Event::PointerMoved(at);+ let down = || native_gui_button(at, true);+ let up = || native_gui_button(at, false);+ let end = |pressed| egui::Event::Key { key: egui::Key::End, physical_key: None, pressed, repeat: false, modifiers: Default::default() };+ let batches: Vec<Vec<egui::Event>> = match layout {+ 0 => vec![vec![moved(), down(), up(), end(true), end(false)]],+ 1 => vec![vec![moved(), down(), up()], vec![end(true), end(false)]],+ _ => vec![vec![moved(), down()], vec![end(true)], vec![up(), end(false)]],+ };+ for events in batches {+ native_gui_input(&mut f, events, discard);+ }+ let selection = f.app.session.doc().unwrap().selection.text.unwrap();+ assert_eq!(+ (selection.story.0, selection.anchor, selection.focus),+ (target.as_u64().unwrap(), "Target story".len(), "Target story".len()),+ "{name}, discard={discard}: End must win after the click, wherever the release falls"+ );+ let commands = &f.app.session.journal[journal..];+ assert_eq!(+ commands.iter().filter(|(id, _)| id == "text.move").count(),+ 1,+ "{name}, discard={discard}: the End press reached the type tool once"+ );+ let clicks = f.ctx.data(|d| d.get_temp::<Clicks>(egui::Id::unique(("canvas_clicks", f.app.pane)))).expect("one actual canvas click");+ assert_eq!(clicks.n, 1, "{name}, discard={discard}: a discarded pass must not replay the press as a word selection");+ native_gui_released(&f);+ native_gui_input(&mut f, vec![egui::Event::Text("!".into())], discard);+ assert_eq!(story_text(&mut f.app, &target), "Target story!", "{name}, discard={discard}: typing lands at the End caret once");+ assert_eq!(story_text(&mut f.app, &old), NATIVE_GUI_OLD_DEVANAGARI);+ assert_eq!(+ f.app.session.journal[journal..].iter().filter(|(id, _)| id == "text.insert").count(),+ 1,+ "{name}, discard={discard}: the text event is not replayed"+ );+ assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo + 1, "{name}, discard={discard}: one edit");+ }+ }+ }++ /// Pointer ownership survives a split press/move/release; a real drag selects, release ends it, and later motion cannot continue it.+ #[test]+ fn native_gui_split_click_and_drag_release_keep_pointer_ownership() {+ for drag in [false, true] {+ let mut f = native_gui_click_fixture();+ let at = f.at;+ native_gui_input(&mut f, vec![native_gui_button(at, true)], false);+ let sel = f.app.session.doc().unwrap().selection.text.unwrap();+ assert_eq!((sel.story.0, sel.focus), (f.target.as_u64().unwrap(), f.focus));+ assert!(f.ctx.input(|i| i.pointer.primary_down()));+ assert!(f.ctx.data(|d| d.get_temp::<bool>(egui::Id::unique(("canvas_pointer_down", f.app.pane)))).unwrap());+ if drag {+ let moved = at + vec2(60.0, 0.0);+ native_gui_input(&mut f, vec![egui::Event::PointerMoved(moved)], false);+ let sel = f.app.session.doc().unwrap().selection.text.unwrap();+ assert_eq!(sel.story.0, f.target.as_u64().unwrap());+ assert!(!sel.is_caret(), "a real held drag selects text");+ }+ let release = if drag { pos2(-20.0, at.y) } else { at };+ native_gui_input(&mut f, vec![egui::Event::PointerMoved(release), native_gui_button(release, false)], false);+ native_gui_released(&f);+ let selection = f.app.session.doc().unwrap().selection.text;+ native_gui_input(&mut f, vec![egui::Event::PointerMoved(at + vec2(90.0, 0.0))], false);+ assert_eq!(f.app.session.doc().unwrap().selection.text, selection, "motion after release cannot continue the old drag");+ assert_eq!(story_text(&mut f.app, &f.target), "Target story");+ assert_eq!(story_text(&mut f.app, &f.old), "Old story");+ }+ }++ /// An unowned outside press, and a press that dismisses an open menu, cannot move the selection or edit either story.+ #[test]+ fn native_gui_outside_press_and_open_menu_do_not_click_through() {+ for menu in [false, true] {+ let mut f = native_gui_click_fixture();+ let at = f.at;+ let selection = f.app.session.doc().unwrap().selection.text;+ if menu {+ let blank = f.app.canvas_rect.unwrap().max - vec2(30.0, 30.0);+ for pressed in [true, false] {+ let event = egui::Event::PointerButton { pos: blank, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() };+ native_gui_input(&mut f, vec![egui::Event::PointerMoved(blank), event], false);+ }+ assert!(context_menu_open(&f.ctx), "the actual secondary click opened the canvas menu");+ assert_eq!(f.app.session.doc().unwrap().selection.text, selection);+ native_gui_input(&mut f, vec![egui::Event::PointerMoved(at), native_gui_button(at, true), native_gui_button(at, false)], false);+ } else {+ let outside = pos2(-20.0, -20.0);+ assert!(!f.app.canvas_rect.unwrap().contains(outside));+ native_gui_input(+ &mut f,+ vec![+ egui::Event::PointerMoved(outside),+ native_gui_button(outside, true),+ egui::Event::PointerMoved(at),+ native_gui_button(at, false),+ ],+ false,+ );+ }+ assert_eq!(f.app.session.doc().unwrap().selection.text, selection, "menu={menu}: an unowned press cannot move the old caret");+ assert_eq!(story_text(&mut f.app, &f.target), "Target story");+ assert_eq!(story_text(&mut f.app, &f.old), "Old story");+ native_gui_released(&f);+ }+ }++ /// Font inventory distinguishes exact bundled faces, missing styles and missing families without accepting installed or injected substitutes.+ #[cfg(not(target_arch = "wasm32"))]+ #[test]+ fn native_gui_font_inventory_keeps_exact_regular_and_missing_style_diagnostics() {+ if designcraft_fonts::CRAFT_FONTS.is_empty() {+ assert!(std::env::var_os("CRAFT_FONTS_REQUIRED").is_none(), "required canonical fonts were not embedded");+ return; // The supported optional-input build has no central document fonts.+ }+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ for (family, text) in [("Noto Sans Hebrew", "שלום"), ("Noto Sans Devanagari", "नमस्ते")] {+ assert!(designcraft_fonts::CRAFT_FONTS.iter().any(|f| f.family == family && f.style == "Regular"), "canonical {family} Regular absent");+ for style in ["Regular", "Unavailable Native GUI Style"] {+ let frame = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap();+ app.run("text.select", json!({"story": frame["story"], "anchor": 0, "focus": text.len()})).unwrap();+ app.run("type.char", json!({"fontFamily": family, "fontStyle": style})).unwrap();+ }+ }+ let frame = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": "Missing"})).unwrap();+ app.run("text.select", json!({"story": frame["story"], "anchor": 0, "focus": 7})).unwrap();+ app.run("type.char", json!({"fontFamily": "Unavailable Native GUI Family", "fontStyle": "Regular"})).unwrap();+ let inventory = app.run("font.list", json!({})).unwrap();+ let rows = inventory.as_array().unwrap();+ assert_eq!(rows.len(), 5, "{inventory}");+ for family in ["Noto Sans Hebrew", "Noto Sans Devanagari"] {+ for style in ["Regular", "Unavailable Native GUI Style"] {+ let row = rows.iter().find(|r| r["family"] == family && r["style"] == style).unwrap();+ assert_eq!(row["missing"], false, "{row}");+ assert_eq!(row["styleMissing"], style != "Regular", "{row}");+ assert_eq!(row["matchStatus"], if style == "Regular" { "exact" } else { "styleSubstitute" }, "{row}");+ assert_eq!(row["resolvedFamily"], family, "{row}");+ assert_eq!(row["resolvedStyle"], "Regular", "{row}");+ assert_eq!(row["source"], "bundled", "an installed or injected face cannot satisfy this production contract: {row}");+ }+ }+ let missing = rows.iter().find(|r| r["family"] == "Unavailable Native GUI Family").unwrap();+ assert_eq!(missing["missing"], true, "{missing}");+ assert_eq!(missing["matchStatus"], "missing", "{missing}");+ assert!(missing["source"].is_null(), "{missing}");+ }++ #[test]+ #[allow(deprecated)] // `ImeEvent::Enabled` / `Disabled`: egui no longer sends them, other integrations may.+ fn ime_events_compose_in_the_story_with_the_candidate_window_at_the_caret() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let sid = typing_app(&mut app, &ctx, "曲:");+ // At a text caret the IME is allowed, its window on the caret as the canvas draws it.+ let ime = ime_frame(&mut app, &ctx, vec![]).expect("IME allowed at a text caret");+ let (top, bottom) = {+ let st = app.session.active().unwrap();+ let cs = app.session.cache.get(&st.doc, designcraft_doc::StoryId(sid.as_u64().unwrap()), None);+ let (fi, x, bl, asc, desc) = compose::caret(&cs, "曲:".len()).unwrap();+ let fid = cs.frames[fi].frame;+ let (a, _) = item_canvas_xf(&st.doc, &CanvasLayout::new(&st.doc, st.editing_parents), fid).unwrap();+ let m = a * st.doc.text_xf(st.doc.item(fid).unwrap());+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());+ (xf.to_screen(m * Point::new(x, bl - asc)), xf.to_screen(m * Point::new(x, bl + desc)))+ };+ assert!(ime.rect.expand(1.0).contains(top) && ime.rect.expand(1.0).contains(bottom), "{:?} vs {top:?}–{bottom:?}", ime.rect);+ assert_eq!(ime.cursor_rect, ime.rect);+ assert!(!ime.should_interrupt_composition);+ assert!(app.canvas_ime(), "the web build keeps whole words typed at the caret");+ // "ni" → に → 日, with the events winit sends.+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Enabled), preedit("ni", 2)]);+ assert_eq!(story_text(&mut app, &sid), "曲:ni", "marked text shows in place");+ assert!(app.session.tool_composing());+ // Keys, plain text, the clipboard and Undo (the native menu's ⌘Z) wait for the IME.+ let steps = app.session.doc().unwrap().history.undo.len();+ let key = |key, pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() };+ ime_frame(+ &mut app,+ &ctx,+ vec![key(egui::Key::Backspace, true), key(egui::Key::Backspace, false), egui::Event::Text("x".into()), egui::Event::Paste("y".into())],+ );+ crate::menus::activate(&mut app, "edit.undo", &Value::Null);+ assert!(!crate::menus::enabled(&app, "edit.undo"));+ assert_eq!(story_text(&mut app, &sid), "曲:ni");+ let ime2 = ime_frame(&mut app, &ctx, vec![preedit("に", 1)]).expect("IME allowed while composing");+ assert_eq!(story_text(&mut app, &sid), "曲:に");+ assert!(ime2.rect.center().x > ime.rect.center().x, "the window follows the IME's cursor: {:?} {:?}", ime2.rect, ime.rect);+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into())), egui::Event::Ime(egui::ImeEvent::Disabled)]);+ assert_eq!(story_text(&mut app, &sid), "曲:日");+ assert!(!app.session.tool_composing());+ assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "the commit is one undo step");+ assert_eq!(app.session.journal.last(), Some(&("text.insert".to_string(), json!({"text": "日"}))));+ // After the commit, typing and Undo work again.+ ime_frame(&mut app, &ctx, vec![egui::Event::Text("!".into())]);+ assert_eq!(story_text(&mut app, &sid), "曲:日!");+ crate::menus::activate(&mut app, "edit.undo", &Value::Null);+ crate::menus::activate(&mut app, "edit.undo", &Value::Null);+ assert_eq!(story_text(&mut app, &sid), "曲:");+ // Without a text caret the IME is off: single-key tool shortcuts keep working.+ app.select_tool("selection");+ assert!(ime_frame(&mut app, &ctx, vec![]).is_none());+ assert!(!app.canvas_ime());+ }++ /// Both panes of a split window see the same keyboard events: only the pane last clicked+ /// types them.+ #[test]+ fn a_split_window_types_once() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let sid = typing_app(&mut app, &ctx, "ab");+ app.run("window.split", json!({"on": true})).unwrap();+ for _ in 0..3 {+ ime_frame(&mut app, &ctx, vec![]);+ }+ assert!(app.other_pane.as_ref().and_then(|o| o.1).is_some(), "both panes are drawn");+ ime_frame(&mut app, &ctx, vec![egui::Event::Text("c".into())]);+ assert_eq!(story_text(&mut app, &sid), "abc");+ let key = |pressed| egui::Event::Key { key: egui::Key::Backspace, physical_key: None, pressed, repeat: false, modifiers: Default::default() };+ ime_frame(&mut app, &ctx, vec![key(true), key(false)]);+ assert_eq!(story_text(&mut app, &sid), "ab");+ ime_frame(&mut app, &ctx, vec![egui::Event::Paste("de".into())]);+ assert_eq!(story_text(&mut app, &sid), "abde");+ ime_frame(&mut app, &ctx, vec![preedit("に", 1)]);+ assert_eq!(story_text(&mut app, &sid), "abdeに");+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]);+ assert_eq!(story_text(&mut app, &sid), "abde日");+ }++ /// Surrounding text is committed text only, preserves reversed selection direction, and a commit keeps owner/generation while reporting `InputMethod`.+ #[test]+ fn ime_reports_the_committed_story_and_excludes_the_pre_edit() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let sid = typing_app(&mut app, &ctx, "a😀b");+ let len = "a😀b".len();+ text_selection(&mut app, &sid, 0, len);+ let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");+ assert_eq!(ime_payload(&ime), Some(("a😀b", len, 0)), "reversed selection keeps its direction");+ let owner = (ime.owner, ime.context_generation);+ // Marked text previews in the document but is not committed surrounding text.+ let ime = ime_frame(&mut app, &ctx, vec![preedit("に", 1)]).expect("a text caret");+ assert_eq!(ime_payload(&ime), Some(("a😀b", len, 0)));+ assert_eq!(ime.owner, owner.0);+ let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]).expect("a text caret");+ assert_eq!(ime_payload(&ime), Some(("日", 3, 3)));+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod);+ assert_eq!(story_text(&mut app, &sid), "日");+ assert_eq!(ime.owner, owner.0);+ assert_eq!(ime.context_generation, owner.1, "a commit is not a new context");+ let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");+ assert_eq!(ime_payload(&ime), Some(("日", 3, 3)), "a later pass reports the same committed text");+ assert_eq!((ime.owner, ime.context_generation), owner, "an unchanged pass keeps the context");+ }++ /// An empty story provides `("",0,0)`; long text is bounded and an out-of-window selection is explicitly unavailable.+ #[test]+ fn ime_empty_story_is_available_and_wide_text_is_bounded() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ typing_app(&mut app, &ctx, "");+ let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");+ assert_eq!(ime_payload(&ime), Some(("", 0, 0)), "an empty document is available, not unavailable");+ assert!(!app.session.tool_composing());++ let long = "a".repeat(5000);+ let sid = typing_app(&mut app, &ctx, &long);+ let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");+ let (text, _, _) = ime_payload(&ime).expect("a long document still has surrounding text");+ assert!(text.len() <= egui::output::MAX_IME_SURROUNDING_TEXT_BYTES, "{}", text.len());+ text_selection(&mut app, &sid, 0, 5000);+ let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");+ assert!(ime.surrounding_text.available().is_none(), "a selection beyond the bound is explicitly unavailable");+ }++ /// Caret movement preserves owner; changing story or document changes owner and generation.+ #[test]+ fn ime_owner_follows_the_story_and_the_document() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ typing_app(&mut app, &ctx, "ab");+ let first = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");+ app.session.execute("text.move", &json!({"dir": "left"})).unwrap();+ let moved = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");+ assert_eq!((moved.owner, moved.context_generation), (first.owner, first.context_generation), "a caret move keeps the context");++ let other = app.run("frame.create", json!({"rect": [400, 36, 200, 100], "content": "text", "text": "xy"})).unwrap();+ let other_sid = other["story"].clone();+ text_selection(&mut app, &other_sid, 2, 2);+ let second = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");+ assert_ne!(second.owner, first.owner, "another story is another owner");+ assert_ne!(second.context_generation, first.context_generation);++ app.run("file.new", json!({})).unwrap();+ let doc = app.run("frame.create", json!({"rect": [36, 36, 200, 100], "content": "text", "text": "z"})).unwrap();+ text_selection(&mut app, &doc["story"], 1, 1);+ let replaced = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");+ assert_ne!(replaced.owner, second.owner, "a new document is another owner");+ assert_eq!(ime_payload(&replaced), Some(("z", 1, 1)));+ }++ /// Pure commits report `InputMethod`; typing before or after a commit in one pass makes the cause `Other`.+ #[test]+ fn ime_cause_distinguishes_commits_from_application_edits() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ typing_app(&mut app, &ctx, "a");+ let committed = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]).expect("a text caret");+ assert_eq!(committed.change_cause, egui::output::ImeChangeCause::InputMethod);+ let typed = ime_frame(&mut app, &ctx, vec![egui::Event::Text("!".into())]).expect("a text caret");+ assert_eq!(typed.change_cause, egui::output::ImeChangeCause::Other, "ordinary typing is an application edit");+ assert_eq!(ime_payload(&typed), Some(("a日!", 5, 5)));++ // An application edit before the commit in one pass breaks the receipt chain.+ let mut before = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ typing_app(&mut before, &ctx, "a");+ let mixed = ime_frame(&mut before, &ctx, vec![egui::Event::Text("x".into()), egui::Event::Ime(egui::ImeEvent::Commit("日".into()))])+ .expect("a text caret");+ assert_eq!(mixed.change_cause, egui::output::ImeChangeCause::Other);+ assert_eq!(ime_payload(&mixed), Some(("ax日", 5, 5)));++ // An application edit after the commit in one pass also dominates.+ let mut after = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ typing_app(&mut after, &ctx, "a");+ let mixed = ime_frame(&mut after, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into())), egui::Event::Text("!".into())])+ .expect("a text caret");+ assert_eq!(mixed.change_cause, egui::output::ImeChangeCause::Other);+ assert_eq!(ime_payload(&mixed), Some(("a日!", 5, 5)));+ }++ /// The settled multipass result rebuilds the current surrounding text while retaining the accepted commit cause.+ #[test]+ fn ime_cause_and_context_survive_a_discarded_pass() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ typing_app(&mut app, &ctx, "a");+ let raw = egui::RawInput {+ screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))),+ events: vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))],+ ..Default::default()+ };+ let mut passes = 0;+ let mut out = ctx.run_ui(raw, |ui| {+ passes += 1;+ if passes == 1 {+ ui.ctx().request_discard("IME multipass regression");+ }+ app.logic(ui.ctx());+ app.ui(ui);+ });+ out.textures_delta.clear();+ assert_eq!(out.platform_output.num_completed_passes, 2, "the frame really was multipass");+ let ime = out.platform_output.ime.expect("a text caret");+ assert_eq!(ime_payload(&ime), Some(("a日", 4, 4)), "the second pass rebuilds the current text");+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod, "the discarded pass keeps the accepted commit's cause");+ }++ /// Autocorrected commit text is an application edit with cause `Other`.+ #[test]+ fn ime_autocorrect_is_not_an_input_method_cause() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ app.session.prefs.autocorrect = true;+ let sid = typing_app(&mut app, &ctx, "teh");+ let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit(" ".into()))]).expect("a text caret");+ assert_eq!(story_text(&mut app, &sid), "the ");+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::Other);+ }++ /// The selection stays selected and directed; byte partials leave whole characters; the deletion is one undo step.+ #[test]+ fn ime_delete_surrounding_excludes_the_selection_and_rounds_bytes_inward() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let sid = typing_app(&mut app, &ctx, "aé😀b");+ // Select é, which keeps its bytes and direction; 'a' before and 😀 after go.+ text_selection(&mut app, &sid, 1, 3);+ ime_frame(&mut app, &ctx, vec![]);+ let steps = app.session.doc().unwrap().history.undo.len();+ let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 2, after_bytes: 4 })])+ .expect("a text caret");+ assert_eq!(story_text(&mut app, &sid), "éb");+ let sel = app.session.doc().unwrap().selection.text.unwrap();+ assert_eq!((sel.anchor, sel.focus), (0, 2), "the selected text stays selected and directed");+ assert_eq!(ime_payload(&ime), Some(("éb", 2, 0)));+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod);+ assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "one deletion is one undo step");+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(story_text(&mut app, &sid), "aé😀b");+ ime_frame(&mut app, &ctx, vec![]);+ // The same deletion with a reversed selection keeps anchor > focus.+ text_selection(&mut app, &sid, 3, 1);+ ime_frame(&mut app, &ctx, vec![]);+ let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 2, after_bytes: 4 })])+ .expect("a text caret");+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod);+ let sel = app.session.doc().unwrap().selection.text.unwrap();+ assert_eq!(story_text(&mut app, &sid), "éb");+ assert_eq!((sel.anchor, sel.focus), (2, 0), "reversed selection stays reversed");++ // One byte of a two-byte character leaves the whole character.+ let partial = typing_app(&mut app, &ctx, "aé");+ text_selection(&mut app, &partial, 1, 1);+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 0, after_bytes: 1 })]);+ assert_eq!(story_text(&mut app, &partial), "aé");+ // A preceding count that lands inside the four-byte emoji leaves it whole too.+ let partial = typing_app(&mut app, &ctx, "a😀");+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 2, after_bytes: 0 })]);+ assert_eq!(story_text(&mut app, &partial), "a😀");+ }++ /// A 200-character request deletes the whole 100-character story.+ #[test]+ fn ime_delete_surrounding_has_no_sixty_four_character_cap() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let sid = typing_app(&mut app, &ctx, &"x".repeat(100));+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars: 200, after_chars: 0 })]);+ assert_eq!(story_text(&mut app, &sid), "");+ }++ /// Delete plus commit in one IME batch produces one undoable edit and reports the final surrounding text.+ #[test]+ fn ime_delete_and_commit_are_one_undo_step() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let sid = typing_app(&mut app, &ctx, "ab");+ text_selection(&mut app, &sid, 1, 2);+ ime_frame(&mut app, &ctx, vec![]);+ let steps = app.session.doc().unwrap().history.undo.len();+ let ime = ime_frame(+ &mut app,+ &ctx,+ vec![+ egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 }),+ egui::Event::Ime(egui::ImeEvent::Commit("X".into())),+ ],+ )+ .expect("a text caret");+ assert_eq!(story_text(&mut app, &sid), "X");+ assert_eq!(ime_payload(&ime), Some(("X", 1, 1)));+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod);+ assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "the IME batch is one undo step");+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(story_text(&mut app, &sid), "ab");+ }++ /// The input method's Commit for a composition a click ended earlier in the same event batch+ /// must not type the marked text again at the clicked caret.+ #[test]+ fn a_commit_after_a_click_in_the_same_batch_is_not_typed_twice() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let sid = typing_app(&mut app, &ctx, "ab");+ ime_frame(&mut app, &ctx, vec![preedit("い", 1)]);+ assert_eq!(story_text(&mut app, &sid), "abい");+ let p = on_screen(&app, Point::new(150.0, 120.0));+ let press = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };+ ime_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(p), press(true), egui::Event::Ime(egui::ImeEvent::Commit("い".into()))])+ .expect("still at a text caret");+ let typed = story_text(&mut app, &sid);+ assert_eq!(typed.matches('い').count(), 1, "the click typed the marked text once: {typed:?}");+ assert!(typed.starts_with("ab"), "{typed:?}");+ assert!(!app.session.tool_composing());+ assert!(app.take_ime_discard(), "the system IME is told to drop its copy");+ ime_frame(&mut app, &ctx, vec![press(false)]);+ }++ /// A delete-surrounding and its commit from the same ended composition must not edit the+ /// clicked caret's text either.+ #[test]+ fn a_delete_and_commit_after_a_click_in_the_same_batch_are_dropped() {+ for delete in [+ egui::ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 },+ egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 },+ ] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let sid = typing_app(&mut app, &ctx, "ab");+ ime_frame(&mut app, &ctx, vec![preedit("い", 1)]);+ let p = on_screen(&app, Point::new(150.0, 120.0));+ let press = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };+ ime_frame(+ &mut app,+ &ctx,+ vec![egui::Event::PointerMoved(p), press(true), egui::Event::Ime(delete), egui::Event::Ime(egui::ImeEvent::Commit("い".into()))],+ )+ .expect("still at a text caret");+ let typed = story_text(&mut app, &sid);+ assert_eq!(typed.matches('い').count(), 1, "the late commit is dropped: {typed:?}");+ assert!(typed.contains("ab"), "the click's text was not deleted: {typed:?}");+ assert!(app.take_ime_discard());+ ime_frame(&mut app, &ctx, vec![press(false)]);+ }+ }++ /// A byte-count delete that reaches past the bounded IME window is still exactly the requested+ /// input method mutation: the engine reports the ranges from the whole story.+ #[test]+ fn a_delete_beyond_the_surrounding_window_is_still_an_input_method_cause() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let sid = typing_app(&mut app, &ctx, &"x".repeat(5000));+ let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 4500, after_bytes: 0 })])+ .expect("a text caret");+ assert_eq!(story_text(&mut app, &sid).len(), 500);+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod);+ assert_eq!(ime_payload(&ime).map(|(text, cursor, anchor)| (text.len(), cursor, anchor)), Some((500, 500, 500)));+ }++ /// The pass's IME observation comes after the later UI sections: a click into the Story+ /// Editor's field takes the keyboard from the canvas in the same pass, so the composition+ /// ends there and the canvas reports no IME.+ #[test]+ fn a_later_field_taking_the_keyboard_ends_the_composition_in_that_pass() {+ 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": "ab"})).unwrap();+ let sid = f["story"].clone();+ app.select_tool("type");+ app.run("text.select", json!({"story": sid, "anchor": 2, "focus": 2})).unwrap();+ app.run("app.storyEditor", json!({"story": sid})).unwrap();+ let mut h = crate::test_window::open(app, egui::vec2(1440.0, 900.0));+ h.event(preedit("い", 1));+ h.run_steps(2);+ assert!(h.state().app.session.tool_composing());+ let canvas_owner = h.output().platform_output.ime.as_ref().expect("the canvas owns the composition").owner;+ let field = h.get_all_by_role(egui::accesskit::Role::MultilineTextInput).next().expect("the Story Editor's text field");+ field.click();+ h.run_steps(2);+ assert!(!h.state().app.session.tool_composing(), "the composition ended where the field took the keyboard");+ assert!(h.state_mut().app.take_ime_discard());+ assert!(h.get_all_by_role(egui::accesskit::Role::MultilineTextInput).next().unwrap().is_focused(), "the field has the keyboard");+ let ime = h.output().platform_output.ime.as_ref().expect("the focused Story Editor publishes its IME context");+ assert_ne!(ime.owner, canvas_owner, "the field owns the IME, not the canvas");+ let typed = story_text(&mut h.state_mut().app, &sid);+ assert!(typed.contains('い'), "the marked text stays as typed: {typed:?}");+ h.event(egui::Event::Ime(egui::ImeEvent::Commit("X".into())));+ h.run_steps(2);+ let edited = story_text(&mut h.state_mut().app, &sid);+ assert_eq!(edited.matches('X').count(), 1, "the field's next commit is applied once: {edited:?}");+ assert_eq!(edited.matches('い').count(), 1, "the old canvas composition is not replayed: {edited:?}");+ }++ #[test]+ fn clicking_away_mid_composition_keeps_the_text_and_interrupts_the_ime() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let sid = typing_app(&mut app, &ctx, "");+ ime_frame(&mut app, &ctx, vec![preedit("しょうこ", 4)]);+ assert!(app.session.tool_composing());+ // A click in the frame (macOS and Windows send nothing for it): the marked text stays as+ // typed and the IME is told to drop its composition, once.+ let p = on_screen(&app, Point::new(150.0, 120.0));+ let press = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };+ let ime = ime_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(p), press(true)]).expect("still at a text caret");+ assert!(ime.should_interrupt_composition);+ ime_frame(&mut app, &ctx, vec![press(false)]);+ assert!(!app.session.tool_composing());+ assert_eq!(story_text(&mut app, &sid), "しょうこ");+ assert!(app.take_ime_discard(), "the host tells the system IME to drop its marked text");+ assert!(!ime_frame(&mut app, &ctx, vec![]).expect("still at a text caret").should_interrupt_composition);+ assert!(!app.take_ime_discard());+ // A bare line break from the IME confirms a composition: the marked text, no new paragraph.+ ime_frame(&mut app, &ctx, vec![preedit("がく", 2)]);+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("\n".into()))]);+ assert!(!app.session.tool_composing());+ let typed = story_text(&mut app, &sid);+ assert!(typed.contains("がく") && typed.contains("しょうこ") && !typed.contains('\n'), "{typed:?}");+ }++ #[test]+ fn baseline_grid_lines_are_the_ones_on_the_page() {+ // A start far above the page used to be walked line by line, without end.+ for start in [-1e9, -1e17] {+ let mut far = baseline_grid_lines(start, 12.0, 792.0);+ assert_eq!((far.next(), far.count()), (Some(8.0), 65));+ }+ let lines = |start, increment, height| baseline_grid_lines(start, increment, height).collect::<Vec<_>>();+ assert_eq!(lines(36.0, 12.0, 72.0), [36.0, 48.0, 60.0], "the bottom edge is not a line");+ assert_eq!(lines(-30.0, 12.0, 30.0), [6.0, 18.0], "a start above the page keeps its rhythm");+ assert_eq!(lines(f64::NAN, 12.0, 792.0), [0.0; 0]);+ assert_eq!(baseline_grid_lines(0.0, 12.0, f64::INFINITY).count(), MAX_BASELINES);+ }++ #[test]+ fn enter_or_tab_in_a_panel_field_leave_the_selected_text_alone() {+ for key in [egui::Key::Enter, egui::Key::Tab] {+ 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": "Hello"})).unwrap();+ app.select_tool("type");+ app.run("text.select", json!({"story": f["story"], "anchor": 1, "focus": 4})).unwrap();+ assert!(app.session.wants_text());+ let mut h = harness(app);+ let size = h.get_all_by_role(egui::accesskit::Role::TextInput).find(|n| n.value().as_deref() == Some("12 pt")).unwrap();+ size.focus();+ h.run_steps(1);+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);+ h.run_steps(1);+ h.event(egui::Event::Text("18".into()));+ h.run_steps(1);+ h.key_press(key);+ h.run_steps(3);+ let text = h.state_mut().session.execute("story.get", &json!({"story": f["story"]})).unwrap()["text"].clone();+ assert_eq!(text, "Hello", "{key:?} confirms the field and leaves the story alone");+ let size = crate::panels::text_attrs(h.state_mut()).unwrap()["chars"]["size"].clone();+ assert_eq!(size, 18.0, "{key:?} applies the typed size");+ }+ }++ #[test]+ fn trailing_spaces_show_dots_before_the_paragraph_mark() {+ let text = "ab \ncd ";+ let mut d = Document::new(&designcraft_doc::build::NewDocument::default());+ let lid = d.default_layer();+ let rect = DRect::new(0.0, 0.0, 300.0, 100.0);+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), rect, lid, text, Default::default()).unwrap();+ let cs = compose::compose_story(&d, sid, &compose::ComposeOptions::default());+ let lines: Vec<_> = cs.frames.iter().flat_map(|f| &f.lines).collect();+ assert_eq!(lines.len(), 2);+ for (l, end_mark) in lines.iter().zip(["¶", "#"]) {+ let marks = hidden_marks(text, l);+ let dots: Vec<f64> = marks.iter().filter(|m| m.1 == "·").map(|m| m.0).collect();+ assert_eq!(dots.len(), 2, "a dot for each trailing space: {marks:?}");+ let &(para_x, mark, _) = marks.last().unwrap();+ assert_eq!(mark, end_mark);+ // The dots sit past the last letter, and the mark comes after both spaces.+ let space = l.glyphs.iter().rev().find(|g| g.len > 0).unwrap();+ assert!(dots.iter().all(|&x| x > l.end_x && x < para_x), "{dots:?} then {mark} at {para_x}");+ assert!(para_x >= space.x + space.adv, "{mark} at {para_x} overlaps the last space");+ }+ }