diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2951acfc3a..89d3b647b1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,7 +18,14 @@ concurrency: cancel-in-progress: false jobs: + # Regenerates contributors/contributors.json for the release commit; every build bundles it. + credits: + permissions: + contents: read + pull-requests: read + uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main release: + needs: credits # Only this job publishes the GitHub release, so only it gets write access. permissions: contents: write @@ -31,6 +38,7 @@ jobs: craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 web-craft-fonts: true version: ${{ inputs.version }} + contributors-artifact: ${{ needs.credits.outputs.artifact-name }} secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} diff --git a/ROADMAP.md b/ROADMAP.md index 22cc84263e..1c0e109c65 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,14 +1,18 @@ # WordCraft roadmap +> **CLI path update:** 2026-11-04 · Options before a non-Unicode input filename no longer make the CLI reject that filename; text option values still require Unicode; `run --file` and `run --script` retain native paths. No ranked gap or readiness estimate changes. + > **Highlight update:** 2026-10-25 · Highlight shortcut toggles the last chosen colour off when the whole selection has it; explicit colour commands remain setters (#4085). Readiness estimates unchanged. **Stage: alpha** · next: beta, ~15 points (60% → 75% ready for real work) and ~150–230 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** trivial (dark-theme interface text on Linux no longer looks semi-bold); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT heading text of another size); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: a shape dropped just after a page break inside a paragraph stays on the new page, #4262); previously trivial (progress log: a float anchored on a later page of a long paragraph is drawn there, #4250); previously minor (progress log: `file.closeDocument` over the control channel and MCP bridge is refused while the document it names has unsaved changes; previously trivial (progress log: ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: Shape Format › Size in the interface unit, #4196); previously trivial (progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, observed in Word for Windows on #4938 (#4917)); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: justified and distributed lines keep the width of the spaces before their first character); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (progress log: a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (progress log: the Print panel's printer list no longer waits on printer drivers, #5710); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (progress log: Times and Courier take their Windows counterparts' line spacing; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: the status bar's count can be words, characters or characters without spaces, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (progress log: Linux Read Aloud through Speech Dispatcher, #4576); previously trivial (progress log: a click just outside a floating table by turned cell text, #4181; previously minor: progress log: Spanish proofing, #3360, #3553; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: MHT quoted MIME parameters); previously trivial (progress log: CLI convert format options); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` is preserved through style resolution and ordered DOCX saves); previously trivial (per-page ink object lookups, #3614); previously trivial (progress log: ODT display settings removed); previously trivial (progress log: dialogs are modal except the five Word keeps modeless, and a press beside one shakes it, #3859); previously trivial (progress log: picture brightness, contrast and transparency, ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (progress log: fonts that aren't installed are flagged in the font box and status bar); previously trivial (progress log: ODT sections inside text boxes); previously trivial (progress log: ODT definitions sharing a name, sections around tables, stacking order); previously trivial (progress log: ODT forms and indexes written as read); previously trivial (progress log: ODT table styles saved, WordCraft-origin documents checked in LibreOffice); previously trivial (progress log: ODT interpretation profile); previously trivial (progress log: ODT controls, custom shapes, in-line placement); previously trivial (progress log: ODT charts kept, frame outlines, header height); previously trivial (progress log: ODT header rows); previously trivial (progress log: ODT layout setting, padding, columns); previously trivial (progress log: ODT tables, header spacing, picture paragraphs); previously trivial (progress log: ODT round trips keep their page count); previously trivial (progress log: emphasis marks, SET fields, ODT page backgrounds and tables); previously trivial (progress log: ODT checked against LibreOffice's templates); previously trivial (progress log: ODT at ~90%); previously trivial (progress log: ODT read and written nearly whole); previously trivial (progress log: ODT text boxes); previously trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: Options › Language redesign, CP4.3); previously trivial (progress log: the missing-pack bar on a fresh install, the caret's typing language, and the spelling menu heading in the interface language, CP4.3); previously trivial (progress log: Language pack languages in every language list, CP4.3); previously trivial (progress log: craft-proof pin, French elision and Valencian, CP4.3); previously trivial (progress log: a long comment's card and balloon stop at ten lines, #3382); previously trivial (progress log: a pasted text box story is charged for the formatting it copies); previously trivial (progress log: a .doc table row keeps one override per cell); previously trivial (progress log: a .doc file's sections find their paragraphs by index); previously minor (Arabic interface language with mirrored UI, #1195); previously trivial (progress log: Replace and Remove Table of Contents with Word's title above a section break, #4041); previously trivial (progress log: a password-protected file named on the command line asks for its password after the startup document is replaced, #5299); previously trivial (progress log: language-packs-2 published and pinned, 75 Language packs); previously trivial (progress log: language-packs-1 published and pinned, CP4.4); previously trivial (progress log: Language packs, CP4);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (progress log: a list inside a Markdown block quote stays quoted); previously trivial (progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (progress log: the line between columns for selected text, #5178); previously trivial (progress log: .doc standard font, #5066); previously trivial (progress log: a table row doesn't split off a picture that doesn't fit, #4272); previously trivial (progress log: a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (progress log: tab leader dots spaced and placed as in Word); previously trivial (progress log: a list level above counts its first number at the first deeper item); previously trivial (progress log: paragraph side borders lie outside the text, #5036); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** trivial (dark-theme interface text on Linux no longer looks semi-bold); previously trivial (progress log: the Arabic interface's Styles gallery reads from the right (#5566)); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT pictures offered in several formats); previously trivial (progress log: ODT heading text of another size); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: a shape dropped just after a page break inside a paragraph stays on the new page, #4262); previously trivial (progress log: a float anchored on a later page of a long paragraph is drawn there, #4250); previously minor (progress log: `file.closeDocument` over the control channel and MCP bridge is refused while the document it names has unsaved changes; previously trivial (progress log: ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: Shape Format › Size in the interface unit, #4196); previously trivial (progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, observed in Word for Windows on #4938 (#4917)); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: justified and distributed lines keep the width of the spaces before their first character); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (progress log: a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (progress log: the Print panel's printer list no longer waits on printer drivers, #5710); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (progress log: Times and Courier take their Windows counterparts' line spacing; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: the status bar's count can be words, characters or characters without spaces, #2797); previously trivial (Linux display server setting in File › Options › Advanced, #2184); previously trivial (progress log: Linux Read Aloud through Speech Dispatcher, #4576); previously trivial (progress log: a click just outside a floating table by turned cell text, #4181; previously minor: progress log: Spanish proofing, #3360, #3553; previously trivial: progress log: Insert › Table's grid previews the hovered table on the page, #3931; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial (progress log: MHT quoted MIME parameters); previously trivial (progress log: CLI convert format options); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` is preserved through style resolution and ordered DOCX saves); previously trivial (per-page ink object lookups, #3614); previously trivial (progress log: ODT display settings removed); previously trivial (progress log: dialogs are modal except the five Word keeps modeless, and a press beside one shakes it, #3859); previously trivial (progress log: picture brightness, contrast and transparency, ODT element audit, ODT checked against 220 files from other applications, ODT display styles); previously trivial (progress log: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (progress log: fonts that aren't installed are flagged in the font box and status bar); previously trivial (progress log: ODT sections inside text boxes); previously trivial (progress log: ODT definitions sharing a name, sections around tables, stacking order); previously trivial (progress log: ODT forms and indexes written as read); previously trivial (progress log: ODT table styles saved, WordCraft-origin documents checked in LibreOffice); previously trivial (progress log: ODT interpretation profile); previously trivial (progress log: ODT controls, custom shapes, in-line placement); previously trivial (progress log: ODT charts kept, frame outlines, header height); previously trivial (progress log: ODT header rows); previously trivial (progress log: ODT layout setting, padding, columns); previously trivial (progress log: ODT tables, header spacing, picture paragraphs); previously trivial (progress log: ODT round trips keep their page count); previously trivial (progress log: emphasis marks, SET fields, ODT page backgrounds and tables); previously trivial (progress log: ODT checked against LibreOffice's templates); previously trivial (progress log: ODT at ~90%); previously trivial (progress log: ODT read and written nearly whole); previously trivial (progress log: ODT text boxes); previously trivial (progress log: ODT layout settings); previously trivial (progress log: ODT character styles); previously trivial (progress log: ODT custom styles); previously trivial (progress log: ODT equations saved); previously trivial (progress log: ODT floating pictures); previously trivial (progress log: ODT paragraph borders); previously trivial (progress log: ODT heading numbering); previously trivial (progress log: ODT table borders); previously trivial (progress log: ODT heading styles); previously trivial (progress log: ODT tab stops); previously trivial (progress log: ODT character formatting); previously trivial (progress log: ODT lists); previously trivial (progress log: ODT comments); previously trivial (progress log: ODT footnotes and endnotes); previously trivial (progress log: ODT headers, footers and fields); previously trivial (progress log: ODT paragraph spacing); previously trivial (progress log: Options › Language redesign, CP4.3); previously trivial (progress log: the missing-pack bar on a fresh install, the caret's typing language, and the spelling menu heading in the interface language, CP4.3); previously trivial (progress log: Language pack languages in every language list, CP4.3); previously trivial (progress log: craft-proof pin, French elision and Valencian, CP4.3); previously trivial (progress log: a long comment's card and balloon stop at ten lines, #3382); previously trivial (progress log: a pasted text box story is charged for the formatting it copies); previously trivial (progress log: a .doc table row keeps one override per cell); previously trivial (progress log: a .doc file's sections find their paragraphs by index); previously minor (Arabic interface language with mirrored UI, #1195); previously trivial (progress log: Replace and Remove Table of Contents with Word's title above a section break, #4041); previously trivial (progress log: a password-protected file named on the command line asks for its password after the startup document is replaced, #5299); previously trivial (progress log: language-packs-2 published and pinned, 75 Language packs); previously trivial (progress log: language-packs-1 published and pinned, CP4.4); previously trivial (progress log: Language packs, CP4);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (progress log: a list inside a Markdown block quote stays quoted); previously trivial (progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes); previously trivial (progress log: the line between columns for selected text, #5178); previously trivial (progress log: .doc standard font, #5066); previously trivial (progress log: a table row doesn't split off a picture that doesn't fit, #4272); previously trivial (progress log: a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (progress log: tab leader dots spaced and placed as in Word); previously trivial (progress log: a list level above counts its first number at the first deeper item); previously trivial (progress log: paragraph side borders lie outside the text, #5036); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > > **Recipient CSV update:** 2026-10-27 · Complete quoted header records choose the delimiter (#4249); detection and regressions follow the current mailings module split. Recipient limits and readiness estimates are unchanged. > > **Headered CSV prefix update:** 2026-10-31 · Unquoted whitespace-only prefix lines are skipped before choosing recipient headers (#4249); quoted whitespace headers, headerless records, the shared CSV reader and recipient limits remain unchanged. + +> **Page Setup update:** 2026-11-07 · Page Setup number boxes keep long input inside the field, including accepted margin values after focus leaves (#5650); accepted ranges and readiness estimates are unchanged. > **Printing update:** 2026-10-12 · direct desktop printing through craft-print; details below. > **Legacy form update:** 2026-10-22 · trivial: numeric XML references decode in field names and labels; readiness estimates unchanged. @@ -144,8 +148,20 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm ## Progress log +- 2026-11-06: Arabic interface: the Home tab's Styles gallery reads from the right, as the rest of the mirrored ribbon does (#5566). Normal is the rightmost tile, the next styles follow leftwards and the scroll arrows and More sit at the gallery's left end; left to right is unchanged. Readiness unchanged. - 2026-11-05: ODT heading text of another size keeps it (gap 19): a smaller word in a heading came back at the heading's size in LibreOffice after a save. +- 2026-11-05: ODT table rows kept from breaking across pages stay so (gap 19): they came back from a save free to break. +- 2026-11-05: ODT: a watermark added, changed or removed, and Different Odd & Even Pages turned on or off, in a file read from ODT are saved. +- 2026-11-05: ODT font declarations are kept (gap 19): replacing them made LibreOffice pick other substitutes for fonts not installed, reflowing a document from 83 pages to 70 on a save with no edits. - 2026-11-05: ODT pictures offered in several formats show and survive a save (gap 19): LibreOffice's letter templates lost theirs. +- 2026-11-07: An in-line picture lowered past its own height (`w:position`) lowers its line as far, as in Word; all 156 synthetic lines measured for #3984 match Word (#5796). Exact spacing keeps the line's baseline. +- 2026-11-03: Search types in place: a click on the title bar's Search box, or Alt+Q, takes the typing in that box, with the results under it, as in Word, instead of a second box in a dialog (#5398). +- 2026-10-31: List labels: a numbering level with format `none` and literal text, such as `RESPONSE:` with a one-inch hanging indent, shows that text as its label, as Word does; it used to show nothing. As in Word, a `none` level still counts and restarts the levels below it, its own number is empty (in legal numbering too), and an empty label still tabs the text to the indent (#4985). Readiness unchanged. +- 2026-10-31: Font menus draw their entries from a few shared textures written in place, as the Equation tab's pictures are (#1002), instead of a texture per font: on Windows (DirectX 12) browsing the list showed the names on black strips in light mode and white or red ones in dark mode (#5105). Readiness unchanged. +- 2026-11-02: A picture linked from its context menu shows its address on hover and opens it with Ctrl/⌘+click, in line or floating, as linked text does; DOCX files keep the link where Word does, on the drawing (`a:hlinkClick`), so links on pictures from Word open too (#5267). Readiness unchanged. +- 2026-11-01: DOCX tables keep rows and cells wrapped in `mc:AlternateContent`, selecting one supported Choice or Fallback with the existing reader policy (#5219). Original synthetic checks cover namespace aliases, unsupported requirements, nested row/cell content controls and two save/reopen cycles; broader corpus and native Word qualification remain open. + +- 2026-11-01: Shapes: a line's arrowheads are as long and as wide as Word draws them: 2, 3 or 5 times the line's width for small, medium and large (a line under 2 points as a 2-point one). Their kind, width and length are read from DOCX (DrawingML and VML) and saved back; before, every arrowhead was one size and saved as a medium triangle. - 2026-11-06: Windows print submissions run in separate helper processes (#5710). A helper acknowledges cancellation before it stops, so a driver stalled in a cancelled job cannot hold another job’s provider lock. A private temporary PDF and bounded settings messages cross the process boundary; normal shutdown reaps helpers and removes their inputs. The helper erases its plaintext inputs before driver work; a hard app crash during startup can still leave private temporary files. Jobs already sending still complete. Readiness estimates unchanged. - 2026-11-06: File › Print: before sending starts, Cancel printing stops a waiting job, frees the Print page and keeps the settings; a successfully cancelled job is never sent. Cancellation remains available after the last document closes. Quitting cancels waiting jobs and joins jobs already sending (#5710). On Windows, winprint repeats the DEVMODE conversion after sending starts. A stall during that repeat prevents cancellation and can keep shutdown waiting, even before a native job exists. Readiness estimates unchanged. - 2026-11-06: File › Print on Windows no longer waits on printer drivers to list printers (#5710). The list used to wait until each printer's driver said whether it prints on both sides, and a networked printer asleep in power save could keep it empty with Refresh unavailable; now discovery asks no driver (the Windows spooler still supplies the list), and printing still checks the job's options with the driver. The reporter's sleeping printer has not been retested yet. Readiness estimates unchanged. @@ -153,6 +169,11 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm - 2026-11-04: MHT import keeps semicolons and escaped quotes inside quoted MIME parameters, so an unrelated parameter cannot supply a false multipart boundary and hide the document text. Readiness estimates unchanged. - 2026-10-30: Equations: `\int`, `\sum` and the other n-ary operators typed with AutoCorrect wait for their limits. `\int` + Space, then `_0^1` and Space, gives ∫ with its limits and the caret in its operand, and `\int_0^1` typed in one go does the same, since any character that can't continue `\name` corrects it; this is observed in Word for Windows on #4938. Enter or an arrow key builds it without going into the operand, and `∫∫` puts the operand in the inner operator; those two are not observed in Word (#4917). Readiness unchanged. +- 2026-11-04: RTF import skips the declared Unicode fallback count even when it exceeds eight fallback units, so longer ANSI alternatives do not leak into the document text. Skipping stays bounded by the available input and ends at a group boundary. Readiness estimates unchanged. +- 2026-11-05: Linux: a WordCraft started by an AppImage app no longer takes that app's file for its own (#5653). The AppImage runtime's `APPIMAGE`, `APPDIR`, `ARGV0` and `OWD` pass to whatever the app starts, so an installed WordCraft opened through `xdg-open` saw another program's `APPIMAGE`, and its self-update replaced that program's file. The app now starts over without those variables unless its executable is under `APPDIR`, so the update goes through the package or plain file it really is. Should starting over fail, the self-update is off in that window and Help › Check for Updates says why. Readiness estimates unchanged. +- 2026-11-05: A Word template (`.dotx`, `.dotm`, `.dot`) opened from the file manager, the command line or the Finder starts a new, untitled document based on it, as Word's default verb for a template does (#3433). It opened the template itself, so Save (and AutoSave) wrote over it. The new document is attached to the template and Save asks where to write; a protected template asks for its password and still starts a new document. File › Open and a file dropped on the window still open a template itself, to edit it. +- 2026-11-05: Arabic letters join across a change of formatting (gap 16, #4093). Each run was shaped on its own, so a letter at a run's edge took the form of a word's start or end: a coloured letter stood apart, and a word edited with Track Changes on read with a space in it (ال ذكاء). Each run is now shaped knowing the text shown on either side, past hidden or deleted text left out of the view, as for Syriac, Mongolian and the other joining scripts. Readiness estimates unchanged. +- 2026-11-05: Shapes, text boxes, groups and drawing canvases in Strict Open XML documents open (#3548). Strict puts them in its one drawing namespace, where Transitional documents use Word 2010's `wps`, `wpg` and `wpc`, and Word writes a Strict text box's text in `wne:txbxContent`; the reader knew neither, so a Strict file opened with its text and no shapes at all. They now read like their Transitional twins and are saved as Transitional. Charts and SmartArt in Strict namespaces are not mapped yet. - 2026-10-28: Ink replay, eraser picking, lasso selection and arrow-candidate discovery reuse the paragraph prefixes they have already scanned (#3614). Page item order, stroke geometry and saved data retain their behavior. This narrows the stability work; ink import fidelity, native pen input and broader corpus qualification remain open. - 2026-10-29: Page drawing finds text-box warps without rescanning the paragraph for every box (#3614). Only requested offsets are indexed, and each paragraph walk stops after its last requested character. Original Linux discovery, complete display-output and CLI/MCP save/reopen controls; native Word comparison untested. Readiness estimates unchanged. - 2026-10-28: Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged. Existing mutation and protection checks retain their costs; this does not close the broader performance gap. @@ -202,11 +223,16 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm - 2026-10-31: ODT: paragraph spacing, indents and line spacing are read and written, and an ODT's own default spacing (none, single lines) replaces Word's 8 pt after and 1.15 lines, so LibreOffice documents keep their vertical rhythm on open and save (gap 19). Readiness unchanged. - 2026-11-01: PDF export, printing and page images show the body's SEQ, STYLEREF and REF fields with their current results, as Word fills them in when it prints or exports even with Update fields before printing off: a caption numbered 7 when it is the first shows 1 on paper, and a REF to a bookmark the document lacks prints Word's "Error! Reference source not found.". NUMWORDS, FILENAME, the document properties, formulas and locked fields keep their stored results there, as in Word; the editor and the saved document keep every stored result. - 2026-10-28: Print Markup HTML, Markdown and text copies discover comment anchors in one paragraph walk, so unrelated bookmark markers no longer cause repeated prefix scans (#3614). Existing quotes, replies, order and export limits are unchanged; original synthetic semantic and scaling regressions cover the traversal. +- 2026-11-04: Table Sort refuses malformed and nonexistent explicit columns before reordering rows (#5531). Omitted column 0, valid columns, header/order/language behavior and Undo/Redo are retained. Original Linux CLI/MCP controls and repeated native/DOCX reopens cover the command; native Word and desktop comparison remain untested. Readiness estimates unchanged. - 2026-10-30: Layout resource caps (#3867, #4385) and linear-time passes (#3866, #4392): repeated table-header rows are capped by item counts, a clipped group counting every nested member, the wrap cache by decoded pixels and the widths a linked text box chain lays out by their lines and items; PDF export, hit testing, tracked-change and clipped-table costs, and long endnote selections no longer grow quadratically. Synthetic regression tests only; no new Word comparison. - 2026-11-03: Proofing (CP4.3): craft-proof moves to craft-libs main with #589 and #590. French spelling suggestions offer the elided form first (`Jadore` → `J'adore`, before `J adore`), and Valencian text (`ca-ES-valencia`) is proofed with the `ca-valencia` pack instead of plain Catalan. Readiness unchanged. +- 2026-11-03: Security: PDF export leaves the document's author out of the PDF's properties when "Remove personal information from file properties on save" is on, as DOCX saving already does. Readiness unchanged. - 2026-11-03: A long comment no longer grows its card or balloon without limit (#3382). Its field in the Comments pane and in a selected balloon stops at ten lines and scrolls, keeping the caret in view; a balloon that isn't selected shows the first ten lines of the comment and of each reply, and clicking it opens the scrolling field. The buttons and the next comment stay in view. - 2026-11-03: Arabic dialogs: the dialogs of the mirrored interface now read right to left. Rows of a label and its field, lists of columns (Compare, AutoCorrect, Special Characters, Track Changes Options, the Columns widths), the tile galleries (chart types, SmartArt layouts) and the ribbon Paragraph group start at the right edge, through an `rtl::Table` helper that is an `egui::Grid` in English; the Add >> and << Remove arrows swap, the Columns preset captions and the Macros buttons no longer overlap, and the Recipient List grid and About › Models scroll instead of running past the left edge. Readiness unchanged. - 2026-11-03: Shape Format › Size: the width and height fields show the interface unit (centimetres, inches…) instead of always points, and take a size typed in any unit, such as `3 cm` or `300 px`, applied once typed (Esc cancels), each side on its own, as Picture Format › Size does (#4196). In both, a field clicked and left with Enter or Tab without typing no longer resizes the object by the rounding of the size it shows (a 100 pt shape became 100.08 pt in inches). +- 2026-11-03: Security: Paste Special with picture files on the clipboard refuses anything that isn't a regular file (a pipe or device reports no length and can produce endless data), and `cargo xtask stats` no longer follows directory symlinks. Readiness unchanged. +- 2026-11-03: Size keeps the side it isn't asked to change (#5469): typing only the width of a straight line keeps its height of 0 instead of making it 1 pt; the 1–4000 pt limits apply only to the sides a `picture.size` call changes. Readiness unchanged. +- 2026-11-03: Find and Replace: a keyboard apostrophe also finds typographic single quotes, so smart-quoted typing stays searchable (#5388). Regex, wildcards, literal searches and numeric character codes remain exact. Original UTF-8 match ranges and replacement spelling are preserved; readiness unchanged. - 2026-11-03: Security: pasting text boxes charges each copied story for its formatting too (run, mark, paragraph and section properties), not only its text and objects, so a story with huge style or font names can't copy past the paste's 32 MiB text box budget. Readiness unchanged. - 2026-11-03: Security: `.doc` import keeps one width, shading, alignment and merge override per table cell, the last one winning as before, instead of a copy every time a paragraph's properties repeat the sprm, so a shared PAPX can't pile up copies on every paragraph mark. Readiness unchanged. - 2026-11-03: Security: `.doc` import attaches each section to the paragraph that ends it through an index of paragraph ends, instead of scanning every paragraph for every section, so a file with a thousand sections that end nowhere can't multiply the work over its paragraphs. Readiness unchanged. @@ -217,6 +243,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm - 2026-11-02: Language packs (CP4.4): craft-i18n's first pack release, language-packs-1, is published and WordCraft pins its index (sha256): 61 languages install from File › Options › Language, among them Lithuanian (#4707), Romanian (#3438), Catalan (#2895, #4947), French (#1325), Greek (#2561), Slovak (#3806), Serbian (#4968) and Latvian (#4438). Dutch (#4145, #2505), German and the other compounding languages wait on craft-proof engine support. Readiness unchanged. - 2026-11-01: Language packs (CP4.3–CP4.5): languages beyond English install their spelling dictionary and hyphenation as a pack from File › Options › Language, or from a bar a document in that language shows ("Polish proofing isn't installed. Install (4.6 MB)"), through the font store and its single download setting; About › Language data shows every licence; `proof.packs`, `proof.installPack` and `proof.removePack` for agents. Install works once language-packs-1 is published (until then with a test index); the default build then embeds English data only, and keeps today's carry-over data embedded until then (`cargo xtask language`). Lithuanian (#4707) and Romanian (#3438) are available as a Language pack once language-packs-1 is published; the Dutch, Catalan, French, Greek, Slovak, Serbian and Latvian packs (#4145, #2505, #2895, #4947, #1325, #2561, #3806, #4968, #4438) are defined and wait on craft-proof engine support (FLAG long/num, OCONV, ISO 8859-7, CIRCUMFIX, FULLSTRIP). Readiness unchanged. - 2026-11-01: DOCX tables keep rows and cells wrapped in `mc:AlternateContent`, selecting one supported Choice or Fallback with the existing reader policy (#5219). Original synthetic checks cover namespace aliases, unsupported requirements, nested row/cell content controls and two save/reopen cycles; broader corpus and native Word qualification remain open.- 2026-11-01: Shapes: a line's arrowheads are as long and as wide as Word draws them: 2, 3 or 5 times the line's width for small, medium and large (a line under 2 points as a 2-point one). Their kind, width and length are read from DOCX (DrawingML and VML) and saved back; before, every arrowhead was one size and saved as a medium triangle. +- 2026-11-02: Page break before applies to a paragraph opening a continuous section mid-page in paginated layout (#5287). The original Word for Mac 16.113 probe puts each heading on a new page. At the top of a later column in such a section, the break also starts a new page; that case remains unmeasured in Word. Readiness unchanged. - 2026-11-01: Columns with Line between, made for selected text (a section in the middle of a page), draw their line; the line runs as tall as the section's text on the page, not the whole page (#5178). Readiness unchanged. - 2026-10-31: `.doc` import: text that names no font takes the stylesheet's standard font, so a Word 365 `.doc` in Aptos opens in Aptos (or its substitute) instead of Times New Roman, the font table's first entry (#5066). Readiness unchanged. - 2026-10-31: Tables: a row that doesn't fit at the bottom of a page no longer splits off its picture. When a cell's inline picture (one line, which is never split) or first line runs past the room left on a page that already holds something, the row moves to the next page whole instead of leaving the other cells' text beside an empty cell, so a photo row at least 193 pt tall grown to 207 pt by its picture goes on in one piece (#4272). At the top of a page such a row still splits. The reporter's 4-page file is still 5 pages: there the row has less room than its minimum and already moves on whole (#1742); the extra page now comes from the pages above taking more room than in Word. @@ -318,6 +345,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target - 2026-10-15: Find opens Navigation on Results; editing the query restores Results after manual Headings/Pages navigation. Typed and selected-text searches retain document contents (#2096). | Date | What landed | +| 2026-11-04 | The CLI opens a non-Unicode input filename even after options such as `--page 2` or `--format flatopc`; text option values still require Unicode; `run --file` and `run --script` retain native paths. | | 2026-11-04 | Pictures keep the brightness, contrast and transparency their file gives them (#1711, #1766): a "Washout" picture watermark (VML `gain`/`blacklevel`) and a washed-out letterhead picture behind the text (`a:lum`) are drawn faded on screen and in PDF instead of at full colour, with the pixel curve measured on Word's own PDF export; `a:alphaModFix` transparency too. Saved back as DrawingML (and as VML `gain`/`blacklevel` in Word 2003 XML, without the transparency). Picture Format › Corrections, Transparency and Color › Washout replace the file's values (other Color modes leave them alone), and Reset Picture discards them all, as in Word; the PDF embeds the corrected pixels once per picture | |---|---| | 2026-10-17 | Copies keep their formatting in programs that read RTF rather than HTML: Copy and Cut put RTF beside the text and HTML on the system clipboard on Windows, macOS and Wayland (an X11 copy stays text and HTML, since arboard owns the selection there; a copy of only pictures or shapes carries no HTML or RTF, so pasting it back keeps every detail), and Paste reads another program's RTF on macOS and X11 too, not only on Windows and Wayland | @@ -466,6 +494,8 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target | 2026-10-17 | Non-overlapping body floating tables clear header tables. Original native controls distinguish never-overlap from allowed overlap. | | 2026-10-14 | Comment text being typed is no longer lost or misplaced (#1348): an edit or reply the document refuses (for example read-only protection) keeps the typed text in its field and says why on the status line; drafts belong to their document, so after New or Open a comment with the same number shows its own text; Save, Export, Print, Close, New and Open write pending comment text first; if the document refuses it, Save, Export and Print carry on with the stored comments and show why on the status line (a refused draft is dropped when Save is the only change), while Close, New and Open show the Save Changes prompt (Don't Save drops text the document refuses); Escape discards what was typed; in a document protected as read only or for forms the comment fields can't be typed in | |---|---| +| 2026-11-07 | Page Setup also bounds the unfocused margin display after a long numeric paste; the accepted value is retained (#5650). | +| 2026-11-05 | Page Setup's margin, paper-size and document-grid number boxes scroll long text inside the field instead of enlarging the dialog (#5650). Readiness estimates unchanged. | | 2026-10-29 | Print Markup discovers comment balloon anchors in one forward paragraph-object walk; anchor positions, filtering and the existing cap stay unchanged (#3614) | | 2026-10-26 | Spelling & Grammar opens a right-side Proofing task pane observed in Word for Windows: sentence context, directly clickable suggestion cards and ignore/dictionary actions. Current-story traversal and stale-target checks are retained. Right-click keeps its compact menu. | | 2026-10-22 | Documents that keep content in another format (`w:altChunk`: a web page, RTF, text or another Word document, as generators and mail-merge tools write them) show it where it stands, as Word does, instead of leaving it out; one such file in the docxide-pdf corpus opened as an empty page and now matches Word's 8 pages. `.mht` web archives open, and web pages open the way Word opens them (style sheets, paragraph margins, Times New Roman, single lines, automatic spacing). Insert › Text from File keeps the inserted file's pictures | @@ -797,11 +827,18 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target Footer page-table height and body wrapping are corrected. Other pagination gaps remain open. +Quoted field escapes are interpreted like Word, and body `PAGE` fields use their active section number format in paragraphs and tables. Synthetic regressions cover fields and section layout. + Section page-numbering settings preserve `w:chapStyle` values across the full unsigned-byte range. MATH glyphs that reference the same construction now share its immutable variants and assembly data (#3630). Glyph mappings, values and the existing partial-record fallback stay unchanged. Repeated glyph IDs keep their last valid reference without retaining superseded constructions. Distinct overlapping constructions and assembly-only sharing remain separate. ## Revision history +> 2026-11-05 · Linux self-update ignores another program's AppImage variables (#5653); recorded in the progress log, readiness unchanged. +> 2026-11-05 · A template opened from the file manager starts a new document instead of being edited and saved over (#3433); recorded in the progress log, readiness unchanged. +> 2026-11-05 · Arabic letters join across a change of formatting and past hidden or deleted text (#4093); recorded in the progress log, readiness unchanged. +> 2026-11-05 · Shapes, text boxes, groups and canvases in Strict Open XML documents open (#3548); recorded in the progress log, readiness unchanged. +> > 2026-11-03 · Arabic dialogs read right to left (rtl::Table); recorded in the progress log, readiness unchanged. > > 2026-10-30 · Technical synchronization: retain the Proofing pane and command/selection/undo contracts on main `3b7f7ed`; new-SHA validation pending, readiness unchanged. @@ -814,6 +851,15 @@ MATH glyphs that reference the same construction now share its immutable variant | Date | Change | Summary | |---|---|---| +| 2026-11-06 | trivial | Progress log: the Arabic interface's Styles gallery reads from the right (#5566) | +| 2026-11-07 | trivial | Page Setup also bounds the unfocused margin display after a long numeric paste; the accepted value is retained (#5650). | +| 2026-11-05 | trivial | Page Setup's margin, paper-size and document-grid number boxes scroll long text inside the field instead of enlarging the dialog (#5650). Readiness estimates unchanged. | +| 2026-11-07 | trivial | Progress log: An in-line picture lowered past its own height (`w:position`) lowers its line as far, as in Word; all 156 synthetic lines measured for #3984 match Word (#5796). | +| 2026-11-03 | trivial | Progress log: the title bar's Search box takes the typing in place (#5398) | +| 2026-10-31 | trivial | Progress log: a numFmt none list level shows its literal text (#4985); readiness unchanged | +| 2026-10-31 | trivial | Progress log: font menu entries are drawn from shared textures (#5105) | +| 2026-11-02 | trivial | Progress log: a linked picture shows and follows its link; DOCX `a:hlinkClick` (#5267) | +| 2026-11-02 | trivial | Progress log: alternative format chunks and MHT open | | 2026-11-06 | trivial | Print helpers remove loaded PDF/settings files before driver work, tolerate prior removal and report cleanup errors; a held-driver regression checks the files are already absent (#5710) | | 2026-11-06 | trivial | Windows print submissions isolated per helper process; cancelled driver work cannot block a retry (#5710) | | 2026-11-06 | trivial | Progress log: print cancellation before sending, including without a document, and the Windows repeated-conversion limitation (#5710) | @@ -822,9 +868,14 @@ MATH glyphs that reference the same construction now share its immutable variant | 2026-11-04 | trivial | Progress log: CLI convert format options; readiness estimates unchanged | | 2026-11-04 | trivial | Progress log: MHT quoted MIME parameters; readiness estimates unchanged | | 2026-10-30 | trivial | Progress log: typed n-ary operators such as ∫ and ∑ wait for their limits, and any character that cannot continue a math name corrects it, as observed in Word for Windows on #4938; Enter, arrow keys and nested operators are WordCraft's own choices (#4917); readiness unchanged | +| 2026-11-04 | trivial | CLI input paths keep their native filename when a value-taking option comes first; regression coverage includes conversion to Flat OPC and rejection of non-Unicode option values. | | 2026-11-05 | trivial | DOCX paragraph `w:adjustRightInd` is preserved with true, false and absent values; OOXML properties follow schema order. Grid layout remains open. | +| 2026-11-04 | trivial | Progress log: RTF Unicode fallback counts; readiness estimates unchanged | | 2026-10-28 | trivial | Per-page ink object lookups, #3614. Drawing order, geometry and saved data retain their behavior; no readiness estimate change | | 2026-11-05 | trivial | Progress log: ODT heading text of another size (gap 19) | +| 2026-11-05 | trivial | Progress log: ODT table rows that don't break (gap 19) | +| 2026-11-05 | trivial | Progress log: a watermark or odd and even headers change to a file is saved | +| 2026-11-05 | trivial | Progress log: ODT font declarations kept (gap 19) | | 2026-11-05 | trivial | Progress log: ODT pictures offered in several formats (gap 19) | | 2026-10-28 | trivial | Shared MATH construction records reuse variants and assembly data without changing glyph mappings or existing limits (#3630); readiness estimates unchanged | | 2026-10-29 | trivial | Page drawing indexes text-box warp lookups per paragraph (#3614); requested offsets only, bounded prefix traversal, original Linux display and persistence controls; readiness estimates unchanged | @@ -852,13 +903,14 @@ MATH glyphs that reference the same construction now share its immutable variant | 2026-11-03 | trivial | Progress log: craft-proof pin, French elision suggestions and Valencian (CP4.3) | | 2026-11-03 | trivial | Progress log: a long comment's card and balloon stop at ten lines (#3382) | | 2026-11-03 | trivial | Progress log: Shape Format › Size in the interface unit (#4196) | +| 2026-11-03 | trivial | Find smart-quoted text with a keyboard apostrophe (#5388); exact search modes and replacement spelling preserved. | | 2026-11-03 | trivial | Progress log: Replace and Remove Table of Contents with Word's title above a section break (#4041) | | 2026-11-03 | trivial | Progress log: language-packs-2 published and pinned, 75 Language packs | | 2026-11-02 | trivial | Progress log: language-packs-1 published and pinned, 61 Language packs (CP4.4) | | 2026-11-01 | trivial | Progress log: Language packs install from File › Options › Language and the missing-pack bar once language-packs-1 is published (CP4) | | 2026-11-01 | trivial | Progress log: English spelling reads SCOWL 2026 (CP2) | +| 2026-11-02 | trivial | Honor page break before at a continuous section's mid-page top (#5287); its later-column case remains unmeasured in Word. Readiness unchanged. | | 2026-11-01 | trivial | Progress log: arrowheads keep their kind, width and length and are drawn at Word's sizes | -| 2026-11-02 | trivial | Progress log: alternative format chunks and MHT open | | 2026-11-01 | trivial | Progress log: columns for selected text draw their line between (#5178) | | 2026-10-31 | trivial | Progress log: a Word 365 .doc in Aptos opens in Aptos (#5066); readiness unchanged | | 2026-10-31 | trivial | Progress log: a table row doesn't split off a picture that doesn't fit (#4272) | diff --git a/apps/wordcraft-cli/src/main.rs b/apps/wordcraft-cli/src/main.rs index 669da7c377..3d4235786d 100644 --- a/apps/wordcraft-cli/src/main.rs +++ b/apps/wordcraft-cli/src/main.rs @@ -98,8 +98,8 @@ fn open(path: &Path, password: Option<&str>) -> Result { Ok(s) } -/// The commands that open a file, and which of their arguments not starting with `--` it is (as -/// `pos` counts). `run` opens the value of `--file`. +/// The commands that open a file, and which positional argument it is, excluding option values. +/// `run` opens the value of `--file`. const OPENS_FILE: &[(&str, usize)] = &[("convert", 0), ("info", 0), ("text", 0), ("inspect", 0), ("render", 0), ("zotero", 1)]; /// The arguments as text. Only the file the command opens may have a name that isn't valid Unicode, @@ -108,8 +108,14 @@ const OPENS_FILE: &[(&str, usize)] = &[("convert", 0), ("info", 0), ("text", 0), fn text_args>(raw: &[S]) -> Result<(Vec, Option), String> { let args: Vec = raw.iter().map(|a| a.as_ref().to_string_lossy().into_owned()).collect(); let cmd = args.first().map(String::as_str).unwrap_or(""); + let specs = match cmd { + "convert" => CONVERT_OPTIONS, + "render" => RENDER_OPTIONS, + "zotero" => ZOTERO_OPTIONS, + _ => PASSWORD_OPTIONS, + }; let file_at = match OPENS_FILE.iter().find(|(c, _)| *c == cmd) { - Some((_, n)) => args.iter().enumerate().skip(1).filter(|(_, a)| !a.starts_with("--")).nth(*n).map(|(i, _)| i), + Some((_, n)) => positional_indices(args.get(1..).unwrap_or_default(), specs).get(*n).map(|i| i + 1), None if cmd == "run" => args.iter().position(|a| a == "--file").map(|i| i + 1), None => None, }; @@ -145,8 +151,13 @@ fn password_from(args: &[String]) -> Result, String> { } /// The positional arguments, skipping every option's value so an option value is never read as a -/// path. Mirrors [`validate_options`], which has already checked the options are known. +/// path. Uses the same option specifications as [`validate_options`]. fn positionals<'a>(args: &'a [String], specs: &[OptionSpec]) -> Vec<&'a String> { + positional_indices(args, specs).into_iter().filter_map(|i| args.get(i)).collect() +} + +/// Keep the original indices too, so [`text_args`] can open a positional path by its native name. +fn positional_indices(args: &[String], specs: &[OptionSpec]) -> Vec { let mut out = Vec::new(); let mut i = 0; while let Some(arg) = args.get(i) { @@ -156,7 +167,7 @@ fn positionals<'a>(args: &'a [String], specs: &[OptionSpec]) -> Vec<&'a String> i += 2; } else { if !arg.starts_with("--") { - out.push(arg); + out.push(i); } i += 1; } diff --git a/apps/wordcraft-cli/src/tests.rs b/apps/wordcraft-cli/src/tests.rs index 209fb546e7..844dda5689 100644 --- a/apps/wordcraft-cli/src/tests.rs +++ b/apps/wordcraft-cli/src/tests.rs @@ -211,6 +211,10 @@ fn only_the_opened_file_may_be_other_than_unicode() { let ok = |raw: Vec| text_args(&raw).unwrap().1; assert_eq!(ok(vec!["zotero".into(), "refresh".into(), latin1()]), Some(PathBuf::from(latin1()))); assert_eq!(ok(vec!["render".into(), latin1(), "out.png".into(), "--page".into(), "2".into()]), Some(PathBuf::from(latin1()))); + assert_eq!(ok(vec!["render".into(), "--page".into(), "2".into(), latin1(), "out.png".into()]), Some(PathBuf::from(latin1()))); + assert_eq!(ok(vec!["convert".into(), "--format".into(), "flatopc".into(), latin1(), "out.xml".into()]), Some(PathBuf::from(latin1()))); + assert_eq!(ok(vec!["info".into(), "--password".into(), "secret".into(), latin1()]), Some(PathBuf::from(latin1()))); + assert_eq!(ok(vec!["zotero".into(), "--port".into(), "23119".into(), "refresh".into(), latin1()]), Some(PathBuf::from(latin1()))); assert_eq!(ok(vec!["run".into(), "--print".into(), "--file".into(), latin1()]), Some(PathBuf::from(latin1()))); assert_eq!(ok(vec!["info".into(), "in.docx".into()]), None); // Every command that opens a file reaches the open with it (no such file here), so @@ -228,6 +232,7 @@ fn only_the_opened_file_may_be_other_than_unicode() { for (raw, n) in [ (vec!["zotero".into(), latin1(), "in.docx".into()], 2), (vec!["render".into(), "in.docx".into(), latin1()], 3), + (vec!["render".into(), "--page".into(), latin1(), "in.docx".into(), "out.png".into()], 3), (vec!["run".into(), "--save".into(), latin1()], 3), (vec!["commands".into(), latin1()], 2), ] { diff --git a/apps/wordcraft-cli/tests/it/non_utf8_args.rs b/apps/wordcraft-cli/tests/it/non_utf8_args.rs index fef340285b..032a28b09f 100644 --- a/apps/wordcraft-cli/tests/it/non_utf8_args.rs +++ b/apps/wordcraft-cli/tests/it/non_utf8_args.rs @@ -53,6 +53,15 @@ fn the_file_a_command_opens_may_have_any_name() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn an_option_before_the_input_keeps_its_native_name() { + let (dir, file) = folder("option-first"); + let saved = dir.join("out.xml"); + ok(&cli(&["convert".into(), "--format".into(), "flatopc".into(), file, saved.clone().into()])); + assert!(std::fs::read_to_string(saved).unwrap().contains("Bonjour")); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn any_other_such_argument_is_an_error_naming_it() { let (dir, file) = folder("error"); diff --git a/apps/wordcraft/src/appimage_env.rs b/apps/wordcraft/src/appimage_env.rs new file mode 100644 index 0000000000..9772244621 --- /dev/null +++ b/apps/wordcraft/src/appimage_env.rs @@ -0,0 +1,139 @@ +//! An AppImage's environment inherited from another program (#5653). +//! +//! The AppImage runtime gives the program it starts `APPIMAGE` (the image's file), `APPDIR` (where +//! it is mounted), `ARGV0` and `OWD`, and whatever that program starts inherits them. So an AppImage +//! app that opens a document through `xdg-open` starts an installed WordCraft with *its* `APPIMAGE`, +//! and the self-update, which trusts that variable, replaces the other app's file with WordCraft. +//! +//! This copy is in the image only when its executable is under `APPDIR`. Otherwise the variables +//! are another program's, and the process starts over without them, before anything reads them. +//! (Removing them in place is `unsafe` under this edition, and `exec` keeps the process id, the +//! arguments and the standard streams.) + +use std::ffi::OsStr; +use std::io::Write; +use std::os::unix::process::CommandExt; +use std::path::Path; +use std::process::Command; + +/// What the AppImage runtime sets; the same list as the documented workaround on the issue. +const RUNTIME_VARS: [&str; 4] = ["APPIMAGE", "APPDIR", "ARGV0", "OWD"]; + +/// Whether the executable runs from the image mounted at `appdir`. Anything unclear counts as not: +/// the update then goes through the package or the plain file this copy really is, and at worst +/// says it can't, where the other answer would overwrite a file that isn't WordCraft's. +fn runs_from_image(exe: Option<&Path>, appdir: Option<&OsStr>) -> bool { + let (Some(exe), Some(appdir)) = (exe, appdir) else { return false }; + let appdir = Path::new(appdir); + if !appdir.is_absolute() { + return false; + } + let Ok(appdir) = appdir.canonicalize() else { return false }; + // No image mounts at the root, where every program on the machine would count as inside it. + appdir.parent().is_some() && exe.starts_with(&appdir) +} + +/// Starts this process over without another program's AppImage variables; returns only when there +/// are none to drop (`None`) or starting over failed. Call it first, before any other thread starts. +pub(crate) fn drop_inherited() -> Option { + let appimage = std::env::var_os("APPIMAGE")?; + let exe = std::env::current_exe().ok(); + if runs_from_image(exe.as_deref(), std::env::var_os("APPDIR").as_deref()) { + return None; + } + // The logger isn't up yet, and wouldn't survive `exec`. Unlike `eprintln!`, never panics. + let _ = writeln!(std::io::stderr(), "wordcraft: ignoring the AppImage {:?} inherited from another program", Path::new(&appimage)); + let mut args = std::env::args_os(); + // This file, whatever has happened to its path since it started. + let mut again = Command::new("/proc/self/exe"); + if let Some(arg0) = args.next() { + again.arg0(arg0); + } + again.args(args); + for var in RUNTIME_VARS { + again.env_remove(var); + } + Some(again.exec()) +} + +#[cfg(test)] +mod tests { + use super::runs_from_image; + use std::path::{Path, PathBuf}; + + /// A folder of its own for one test, removed when it ends. + struct Tmp(PathBuf); + + impl Tmp { + /// An empty folder named after `test` and this process, made afresh. + fn new(test: &str) -> Tmp { + let dir = std::env::temp_dir().join(format!("wordcraft-appimage-{test}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Tmp(dir) + } + } + + impl Drop for Tmp { + /// Removes the folder and what the test left in it. + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + /// A mount with the executable inside it, by real path (`/tmp` may be a link). + fn mount(root: &Path, name: &str) -> (PathBuf, PathBuf) { + let dir = root.join(name); + std::fs::create_dir_all(dir.join("usr/bin")).unwrap(); + let dir = dir.canonicalize().unwrap(); + let exe = dir.join("usr/bin/wordcraft"); + (dir, exe) + } + + #[test] + fn an_executable_in_the_mount_is_the_image() { + let tmp = Tmp::new("own"); + let (dir, exe) = mount(&tmp.0, ".mount_WordCr"); + assert!(runs_from_image(Some(&exe), Some(dir.as_os_str()))); + } + + #[test] + fn a_link_to_the_mount_is_the_same_mount() { + let tmp = Tmp::new("link"); + let (dir, exe) = mount(&tmp.0, ".mount_WordCr"); + let link = tmp.0.join("link"); + std::os::unix::fs::symlink(&dir, &link).unwrap(); + assert!(runs_from_image(Some(&exe), Some(link.as_os_str()))); + } + + #[test] + fn an_installed_executable_is_not_in_another_programs_mount() { + let tmp = Tmp::new("other"); + let (other, _) = mount(&tmp.0, ".mount_other"); + assert!(!runs_from_image(Some(Path::new("/usr/bin/wordcraft")), Some(other.as_os_str()))); + } + + /// Paths compare by component: one mount's name can start with another's. + #[test] + fn a_mount_whose_name_starts_the_same_is_another_mount() { + let tmp = Tmp::new("prefix"); + let (other, _) = mount(&tmp.0, ".mount_ab"); + let (_, exe) = mount(&tmp.0, ".mount_abc"); + assert!(!runs_from_image(Some(&exe), Some(other.as_os_str()))); + } + + #[test] + fn anything_unclear_is_not_the_image() { + let tmp = Tmp::new("unclear"); + let (dir, exe) = mount(&tmp.0, ".mount_WordCr"); + // No `APPDIR`, one that's gone (the other program has exited) or empty. + assert!(!runs_from_image(Some(&exe), None)); + assert!(!runs_from_image(Some(&exe), Some(tmp.0.join("gone").as_os_str()))); + assert!(!runs_from_image(Some(&exe), Some("".as_ref()))); + // The root, and a relative path that happens to lead here. + assert!(!runs_from_image(Some(&exe), Some("/".as_ref()))); + assert!(!runs_from_image(Some(&exe), Some(".".as_ref()))); + // No executable path at all. + assert!(!runs_from_image(None, Some(dir.as_os_str()))); + } +} diff --git a/apps/wordcraft/src/apple_events.rs b/apps/wordcraft/src/apple_events.rs index e79d923a9a..56a284c0cb 100644 --- a/apps/wordcraft/src/apple_events.rs +++ b/apps/wordcraft/src/apple_events.rs @@ -36,14 +36,15 @@ impl AppleEvents { /// Open the documents and act on the quit requests that arrived since the last frame. A document /// opens like File › Open: beside the open ones, in place of an untouched blank one, or, when it -/// is already open, by showing it. Quitting closes the window, which asks about every document +/// is already open, by showing it; a Word template starts a new document based on it, as Word's +/// default verb for one does (#3433). Quitting closes the window, which asks about every document /// with unsaved changes. pub fn poll(inbox: &Inbox, app: &mut WordApp, ctx: &egui::Context) { for e in inbox.drain() { match e { Event::Open(paths) => { for p in paths.iter().filter_map(|p| p.to_str()) { - match app.open_file(p, None) { + match app.open_from_platform(p, None) { // Leave Backstage, as opening from the Open dialog does. Ok(_) => app.ui.backstage = false, Err(e) => { diff --git a/apps/wordcraft/src/main.rs b/apps/wordcraft/src/main.rs index 2c9eb1d679..1c29e22899 100644 --- a/apps/wordcraft/src/main.rs +++ b/apps/wordcraft/src/main.rs @@ -10,6 +10,8 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod animations; +#[cfg(target_os = "linux")] +mod appimage_env; #[cfg(target_os = "macos")] mod apple_events; mod clipboard; @@ -421,14 +423,15 @@ fn without_launch_args(args: Vec) -> Vec { /// Open a file whose name isn't valid Unicode (#1440). `file.open` takes its path as text, so it /// gets the file's bytes under the lossy name, and the document then keeps the real path to save to. -/// The bytes are read as `file.open` reads a path: only a regular file, and at most 2 GB. +/// The bytes are read as `file.open` reads a path: only a regular file, and at most 2 GB. A Word +/// template starts a new document instead ([`WordApp::open_from_platform`]), which has no path. fn open_non_unicode(app: &mut WordApp, path: &std::path::Path) { let name = path.to_string_lossy(); let opened = wordcraft_engine::io::read_document(path) - .and_then(|bytes| app.run("file.open", serde_json::json!({"path": name, "data": wordcraft_engine::cmd::insert::base64_encode(&bytes)}))); + .and_then(|bytes| app.open_from_platform(&name, Some(&wordcraft_engine::cmd::insert::base64_encode(&bytes)))); match opened { // Not when it waits for a password: that open names the document itself. - Ok(r) if r.get("pending").is_none() => app.session.path = Some(path.into()), + Ok(r) if r.get("pending").is_none() && !wordcraft_ui_egui::documents::is_word_template(&name) => app.session.path = Some(path.into()), Ok(_) => {} Err(e) => { app.report_open_failure(&name, &e); @@ -449,9 +452,22 @@ fn main() -> eframe::Result { if let Some(result) = craft_update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { std::process::exit(i32::from(result.is_err())); } + // Linux: before anything reads another program's AppImage variables, or a thread starts (#5653). + #[cfg(target_os = "linux")] + let start_over_failed = appimage_env::drop_inherited(); + // Still carrying them, this process must never update itself: the update would replace the + // other program's file. + #[cfg(target_os = "linux")] + let updates_unsafe = start_over_failed.is_some(); + #[cfg(not(target_os = "linux"))] + let updates_unsafe = false; // First, so the panic hook and every start-up warning are recorded (`logging`). let logger = logging::install(); logging::install_panic_hook(); + #[cfg(target_os = "linux")] + if let Some(e) = start_over_failed { + log::error!("couldn't start again without another program's AppImage variables, so the self-update is off in this window: {e}"); + } let mut control_port: Option = std::env::var("WORDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok()); let mut files = Vec::new(); let mut sample = false; @@ -566,6 +582,10 @@ fn main() -> eframe::Result { let mut app = WordApp::new(session, services(file_dialog, &cc.egui_ctx)); app.set_startup_update_check(true); load_prefs(&mut app); + // After the preferences, so the reason it gives is in the interface language. + if updates_unsafe { + app.disable_self_update(); + } load_user_dictionary(&mut app); // Language packs from the suite's font store; an Install click is the person's own. wordcraft_engine::packs::use_font_store(true); @@ -605,8 +625,9 @@ fn main() -> eframe::Result { if files.is_empty() && other_files.is_empty() && !sample && control_port.is_none() { app.start_screen(); } + // A Word template named here starts a new document based on it (#3433). for f in files { - if let Err(e) = app.run("file.open", serde_json::json!({"path": f})) { + if let Err(e) = app.open_from_platform(&f, None) { app.report_open_failure(&f, &e); } } diff --git a/apps/wordcraft/tests/it/appimage_env.rs b/apps/wordcraft/tests/it/appimage_env.rs new file mode 100644 index 0000000000..e1de2f0040 --- /dev/null +++ b/apps/wordcraft/tests/it/appimage_env.rs @@ -0,0 +1,99 @@ +//! A WordCraft started by an AppImage app inherits that app's `APPIMAGE`, which the self-update +//! would take for this copy's file and replace (#5653). The real program, started both ways. + +use std::ffi::OsString; +use std::os::unix::ffi::OsStringExt; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output, Stdio}; +use std::time::{Duration, Instant}; + +const NOTICE: &str = "ignoring the AppImage"; + +/// A folder of its own for one test, removed when it ends. +struct Tmp(PathBuf); + +impl Tmp { + /// An empty folder named after `test` and this process, made afresh. + fn new(test: &str) -> Tmp { + let dir = std::env::temp_dir().join(format!("wordcraft-appimage-it-{test}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Tmp(dir) + } +} + +impl Drop for Tmp { + /// Removes the folder and what the test left in it. + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Runs the real app with `args`, as an AppImage app with `appimage` mounted at `appdir` would +/// start it, and waits up to 30 s for it to exit (with no display it can't open a window). +fn app(args: &[OsString], appimage: &Path, appdir: &Path) -> Output { + let mut child = Command::new(env!("CARGO_BIN_EXE_wordcraft")) + .args(args) + .env("APPIMAGE", appimage) + .env("APPDIR", appdir) + .env("ARGV0", "other-app") + .env("OWD", "/") + // With no display, an app that tries to open a window fails at once instead. + .env_remove("DISPLAY") + .env_remove("WAYLAND_DISPLAY") + .env_remove("WAYLAND_SOCKET") + .env_remove("WORDCRAFT_CONTROL_PORT") + .env("WORDCRAFT_NO_PREFS", "1") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + // A start-over that kept the variables would start over for ever, and end here. + let deadline = Instant::now() + Duration::from_secs(30); + while child.try_wait().unwrap().is_none() { + if Instant::now() > deadline { + let _ = child.kill(); + panic!("wordcraft {args:?} was still running after 30 s"); + } + std::thread::sleep(Duration::from_millis(50)); + } + child.wait_with_output().unwrap() +} + +/// The notice comes once: the program it started over as no longer sees the variables. +#[test] +fn another_programs_variables_are_dropped_once_and_the_program_carries_on() { + let tmp = Tmp::new("dropped"); + let other = tmp.0.join("other-app.AppImage"); + std::fs::write(&other, b"another program").unwrap(); + let out = app(&["--version".into()], &other, &tmp.0); + let (stdout, stderr) = (String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + assert!(out.status.success(), "status {:?}, stderr: {stderr}", out.status); + assert!(stdout.starts_with("wordcraft "), "stdout: {stdout}"); + assert_eq!(stderr.matches(NOTICE).count(), 1, "stderr: {stderr}"); + assert!(stderr.contains("other-app.AppImage"), "stderr: {stderr}"); + assert_eq!(std::fs::read(&other).unwrap(), b"another program"); +} + +/// Arguments reach the program it starts over as byte for byte, even one that isn't Unicode. +#[test] +fn starting_over_keeps_the_arguments() { + let tmp = Tmp::new("args"); + let out = app(&["--sample".into(), "--control".into(), OsString::from_vec(b"79\xe981".to_vec())], &tmp.0.join("gone"), &tmp.0); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(2), "stderr: {stderr}"); + assert!(stderr.contains("argument 3 is not valid Unicode: 79\u{FFFD}81"), "stderr: {stderr}"); +} + +/// Its own image's variables stay, or the self-update couldn't find the file to replace. +#[test] +fn its_own_images_variables_stay() { + let exe = Path::new(env!("CARGO_BIN_EXE_wordcraft")).canonicalize().unwrap(); + let mount = exe.parent().unwrap(); + let out = app(&["--version".into()], &mount.join("WordCraft.AppImage"), mount); + let (stdout, stderr) = (String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + assert!(out.status.success(), "status {:?}, stderr: {stderr}", out.status); + assert!(stdout.starts_with("wordcraft "), "stdout: {stdout}"); + assert!(!stderr.contains(NOTICE), "stderr: {stderr}"); +} diff --git a/apps/wordcraft/tests/it/main.rs b/apps/wordcraft/tests/it/main.rs index 9c26dc905b..cfa99b937d 100644 --- a/apps/wordcraft/tests/it/main.rs +++ b/apps/wordcraft/tests/it/main.rs @@ -1,3 +1,5 @@ +#[cfg(target_os = "linux")] +mod appimage_env; mod control_arg; mod help; #[cfg(unix)] diff --git a/crates/doc/src/kept.rs b/crates/doc/src/kept.rs index ee0d3e9a1a..4f9437972f 100644 --- a/crates/doc/src/kept.rs +++ b/crates/doc/src/kept.rs @@ -478,8 +478,9 @@ fn family_fingerprint(doc: &crate::Document, root: u32, replies: &HashMap u64 { let mut sections: Vec<&crate::SectionProps> = doc.body.iter().filter_map(|b| b.as_para()).filter_map(|p| p.section.as_deref()).collect(); sections.push(&doc.last_section); @@ -490,8 +491,10 @@ pub fn pages_fingerprint(doc: &crate::Document) -> u64 { match serde_json::to_vec(&( sections, parts, + s.even_odd_headers, &s.page_color, &s.page_picture, + s.watermark.as_ref().filter(|w| !w.text.trim().is_empty()), (&s.footnote_format, &s.endnote_format, &s.footnote_pr, &s.endnote_pr), (&doc.footnote_separators, &doc.endnote_separators), )) { diff --git a/crates/doc/src/link.rs b/crates/doc/src/link.rs index 7ceeabb37b..5ef9e0e752 100644 --- a/crates/doc/src/link.rs +++ b/crates/doc/src/link.rs @@ -125,6 +125,7 @@ mod tests { ("HYPERLINK\t\"http://example.com\"", Some("http://example.com")), (r#"HYPERLINK"http://example.com""#, Some("http://example.com")), (r#"HYPERLINK "http://example.com/path\latest""#, Some("http://example.com/pathlatest")), + (r#"HYPERLINK "x \* Upper""#, Some("x * Upper")), (r#"HYPERLINK "C:\\Docs\\My file.docx""#, Some(r"C:\Docs\My file.docx")), (r#"HYPERLINK "say \"hi\"""#, Some(r#"say "hi""#)), (r#"HYPERLINK " http://example.com ""#, Some("http://example.com")), diff --git a/crates/doc/src/numbering.rs b/crates/doc/src/numbering.rs index a5d2ec6e10..5ab94ea877 100644 --- a/crates/doc/src/numbering.rs +++ b/crates/doc/src/numbering.rs @@ -228,7 +228,7 @@ impl Numbering { /// Whether a paragraph in list `num` at `level` gets a label ([`Counters::next_label`] gives /// one), without counting it. pub fn shows_label(&self, num: u32, level: u8) -> bool { - self.abstract_of(num).is_some() && self.level(num, level.min(8)).is_some_and(|d| d.format != NumFormat::None) + self.abstract_of(num).is_some() && self.level(num, level.min(8)).is_some() } pub fn level(&self, num: u32, level: u8) -> Option<&Level> { if let Some((_, l)) = self.num(num)?.level_overrides.iter().find(|(i, _)| *i == level) { @@ -325,12 +325,9 @@ impl Counters { let lv = (level as usize).min(8); // This list's own definition of a level wins over its abstract list's. let level_def = |k: usize| numbering.level(num, k as u8); + // A "none" level (Word's numFmt none) still counts and restarts the levels below it; only + // its number reads as nothing, so its literal text ("RESPONSE:") shows (#4985). let def = level_def(lv)?.clone(); - // A "none" level shows no label at all (Word's numFmt none) — not even its text. - if def.format == NumFormat::None { - self.labels.insert((abs.id, lv as u8), CountedLabel { label: None, levels: Vec::new() }); - return None; - } let st = self.state.entry(abs.id).or_insert([0; 9]); let fl = self.flags.entry(abs.id).or_default(); // Only this level's override, not the num's others: the counters are shared by every @@ -382,7 +379,14 @@ impl Counters { let started = *fl; let numeric = def.format != NumFormat::Bullet; let label = if numeric { render_label(numbering, num, &def, &vals, &started) } else { def.text.clone() }; - self.labels.insert((abs.id, lv as u8), CountedLabel { label: numeric.then(|| label.clone()), levels: template_levels(&def.text) }); + // A "none" level shows its literal text, but has no number of its own for a reference to + // show (#4985): it is kept as one that shows none. + let counted = if def.format == NumFormat::None { + CountedLabel { label: None, levels: Vec::new() } + } else { + CountedLabel { label: numeric.then(|| label.clone()), levels: template_levels(&def.text) } + }; + self.labels.insert((abs.id, lv as u8), counted); Some((label, def)) } /// Which levels of `num`'s list have counted a paragraph yet (a level never used has no @@ -455,9 +459,9 @@ fn render_label(numbering: &Numbering, num: u32, def: &Level, vals: &[u32; 9], s let counted = started.get(k).is_some_and(|f| f.started); let val = if counted { val } else { level_def(k).map(|l| l.start).unwrap_or(1) }; // Legal numbering (w:isLgl) shows every level in Arabic digits, whatever its own - // format (二 of a Chinese outline becomes 2 in "2.1"). + // format (二 of a Chinese outline becomes 2 in "2.1"); a "none" level stays empty. let fmt = match level_def(k).map(|l| l.format).unwrap_or(NumFormat::Decimal) { - NumFormat::DecimalZero => NumFormat::DecimalZero, + f @ (NumFormat::DecimalZero | NumFormat::None) => f, _ if def.legal => NumFormat::Decimal, f => f, }; @@ -556,6 +560,27 @@ mod tests { assert_eq!(n.level(id, 2).map(|l| l.format), Some(NumFormat::DecimalZero)); } + #[test] + fn a_none_level_shows_its_text_and_still_counts() { + // As Word shows them (#4985): a "none" level's literal text is its label, its own number + // reads as nothing (also in legal numbering), and it restarts the levels below it. + let mut n = Numbering::default(); + let id = n.add_list(ListKind::Numbered); + let lvl = |format, text: &str| Level { format, text: text.into(), ..Level::default() }; + let legal = Level { legal: true, ..lvl(NumFormat::Decimal, "%2.%3") }; + if let Some(num) = n.nums.iter_mut().find(|x| x.id == id) { + num.level_overrides = vec![(0, lvl(NumFormat::None, "RESPONSE:")), (1, lvl(NumFormat::None, "[%2]")), (2, legal)]; + } + assert!(n.shows_label(id, 0)); + let mut c = Counters::default(); + assert_eq!(c.next_label(&n, id, 0).unwrap().0, "RESPONSE:"); + assert_eq!(c.next_label(&n, id, 1).unwrap().0, "[]"); + assert_eq!(c.next_label(&n, id, 2).unwrap().0, ".1"); + assert_eq!(c.next_label(&n, id, 2).unwrap().0, ".2"); + assert_eq!(c.next_label(&n, id, 1).unwrap().0, "[]"); + assert_eq!(c.next_label(&n, id, 2).unwrap().0, ".1"); + } + #[test] fn a_start_override_restarts_only_its_own_level_of_a_shared_list() { // One abstract list numbers the headings through two nums: one for levels 1-4, and one diff --git a/crates/doc/src/section.rs b/crates/doc/src/section.rs index 1d72468f6f..0918cb961c 100644 --- a/crates/doc/src/section.rs +++ b/crates/doc/src/section.rs @@ -289,13 +289,14 @@ impl NumFormat { pub fn from_ooxml(s: &str) -> NumFormat { NumFormat::ALL.into_iter().find(|f| f.ooxml() == s).unwrap_or(NumFormat::Decimal) } - /// Format `n` (1-based). Formats WordCraft doesn't draw yet (Hebrew, Hindi, Thai, - /// Vietnamese, text amounts) show decimal, as do values past a sequence's end - /// (the 21st item of ①…⑳). + /// Format `n` (1-based). Formats WordCraft doesn't draw yet (Hebrew, Hindi, Thai letters + /// and counting, Vietnamese, text amounts) show decimal, as do values past a sequence's end + /// (the 21st item of ①…⑳). Thai numbers are the decimal number in Thai digits (๑, ๒ … ๑๐). pub fn format(self, n: u32) -> String { use crate::cjk_numbers as cjk; match self { NumFormat::DecimalZero => format!("{n:02}"), + NumFormat::ThaiNumbers => thai_digits(n), NumFormat::UpperRoman => roman(n).to_uppercase(), NumFormat::LowerRoman => roman(n), NumFormat::UpperLetter => letters(n).to_uppercase(), @@ -349,7 +350,6 @@ impl NumFormat { | NumFormat::HindiNumbers | NumFormat::HindiCounting | NumFormat::ThaiLetters - | NumFormat::ThaiNumbers | NumFormat::ThaiCounting | NumFormat::BahtText | NumFormat::DollarText => n.to_string(), @@ -357,6 +357,11 @@ impl NumFormat { } } +/// `n` in Thai digits, ๐ (U+0E50) to ๙ (#5757). +fn thai_digits(n: u32) -> String { + n.to_string().chars().filter_map(|c| c.to_digit(10).and_then(|d| char::from_u32(0x0E50 + d))).collect() +} + /// Chicago Manual of Style note marks: *, †, ‡, §, then doubled (**, ††, …) and so on. fn chicago(n: u32) -> String { const MARKS: [char; 4] = ['*', '\u{2020}', '\u{2021}', '\u{a7}']; @@ -999,6 +1004,18 @@ mod tests { assert_eq!(NumFormat::from_ooxml("klingon"), NumFormat::Decimal, "unknown formats are decimal"); } + /// #5757: Thai numbers are the decimal number in Thai digits, every digit, at any length. + #[test] + fn thai_numbers_use_thai_digits() { + let labels: Vec = [1, 2, 3, 9, 10, 11, 20, 105, 2569].iter().map(|n| NumFormat::ThaiNumbers.format(*n)).collect(); + assert_eq!(labels.join(" "), "๑ ๒ ๓ ๙ ๑๐ ๑๑ ๒๐ ๑๐๕ ๒๕๖๙"); + assert_eq!(NumFormat::ThaiNumbers.format(0), "๐"); + assert_eq!(NumFormat::ThaiNumbers.format(u32::MAX), "๔๒๙๔๙๖๗๒๙๕"); + assert_eq!(NumFormat::from_ooxml("thaiNumbers"), NumFormat::ThaiNumbers); + // Formats not drawn yet still show decimal. + assert_eq!(NumFormat::ThaiLetters.format(3), "3"); + } + #[test] fn russian_letters_follow_word() { // Word's own labels for a russianLower list: no ё, й, ъ or ь, then doubled letters. diff --git a/crates/docbin/src/fkp.rs b/crates/docbin/src/fkp.rs index 8ed395ac7c..3de272da26 100644 --- a/crates/docbin/src/fkp.rs +++ b/crates/docbin/src/fkp.rs @@ -7,9 +7,26 @@ use crate::DocbinError; /// Largest bin table (entries) we accept. const MAX_BINS: usize = 100_000; +/// A Chpx grpprl and the FCs `[lo, hi)` for which it is the one [`Bins::chpx`] returns. +#[derive(Clone, Copy)] +pub(crate) struct ChpxRun<'w> { + pub(crate) grpprl: &'w [u8], + lo: u32, + hi: u32, +} + +impl ChpxRun<'_> { + pub(crate) fn contains(&self, fc: u32) -> bool { + self.lo <= fc && fc < self.hi + } +} + /// A parsed `PlcBte*`: FC breakpoints and the FKP page each range lives in. pub(crate) struct Bins { fcs: Vec, + /// `fcs` ascends, so the bin of an FC holds every FC up to the next breakpoint (a corrupt + /// table that does not gets no cached ranges, [`ChpxRun`]). + sorted: bool, /// Page number (× 512 = byte offset in the WordDocument stream). pns: Vec, } @@ -20,7 +37,7 @@ impl Bins { let fc = fc as usize; let lcb = lcb as usize; if lcb < 4 || !(lcb - 4).is_multiple_of(8) { - return Ok(Bins { fcs: Vec::new(), pns: Vec::new() }); + return Ok(Bins { fcs: Vec::new(), sorted: true, pns: Vec::new() }); } let end = fc.checked_add(lcb).ok_or_else(|| DocbinError::Malformed("bin table overflow".into()))?; let plc = table.get(fc..end).ok_or_else(|| DocbinError::Malformed("bin table outside the Table stream".into()))?; @@ -38,36 +55,58 @@ impl Bins { // PnBte* keeps the page number in its low bits; the rest must be zero. pns.push(at(n + 1 + i).ok_or_else(|| DocbinError::Malformed("truncated bin aPn".into()))? & 0x003F_FFFF); } - Ok(Bins { fcs, pns }) + let sorted = fcs.windows(2).all(|w| w.first() <= w.get(1)); + Ok(Bins { fcs, sorted, pns }) } - /// The page containing `fc`, as a slice of the WordDocument stream. - fn page<'w>(&self, word: &'w [u8], fc: u32) -> Option<&'w [u8]> { + /// The page containing `fc`, as a slice of the WordDocument stream, and the FC range + /// `[lo, hi)` of its bin (`hi` is `u32::MAX` for the last; an empty range when the table + /// is not ascending, so nothing is cached from it). + fn page<'w>(&self, word: &'w [u8], fc: u32) -> Option<(&'w [u8], u32, u32)> { let i = self.fcs.partition_point(|&f| f <= fc).checked_sub(1)?; let pn = *self.pns.get(i)?; let at = pn.checked_mul(512)? as usize; - word.get(at..at.checked_add(512)?) + let page = word.get(at..at.checked_add(512)?)?; + if !self.sorted { + return Some((page, 1, 0)); + } + let lo = self.fcs.get(i).copied().unwrap_or(0); + let hi = self.fcs.get(i + 1).copied().unwrap_or(u32::MAX); + Some((page, lo, hi)) } /// The grpprl of the Chpx covering `fc` ([MS-DOC] ChpxFkp: rgfc u32s, rgb offsets ×2, /// crun in the last byte). pub(crate) fn chpx<'w>(&self, word: &'w [u8], fc: u32) -> &'w [u8] { - let Some(page) = self.page(word, fc) else { return &[] }; - let Some(&crun) = page.get(511) else { return &[] }; + self.chpx_run(word, fc).grpprl + } + + /// [`Bins::chpx`] with the FC range over which the same grpprl is the answer, so a walk + /// over consecutive characters looks it up once per run, not once per character. + pub(crate) fn chpx_run<'w>(&self, word: &'w [u8], fc: u32) -> ChpxRun<'w> { + let none = ChpxRun { grpprl: &[], lo: 1, hi: 0 }; + let Some((page, page_lo, page_hi)) = self.page(word, fc) else { return none }; + let Some(&crun) = page.get(511) else { return none }; let crun = crun.min(0x65) as usize; let rgfc = |i: usize| -> Option { page.get(i * 4..i * 4 + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) }; // rgb array sits right after rgfc (crun+1 u32s); each byte is a half-offset into the // region between rgb's end and crun. let rgb_at = (crun + 1) * 4; + // The last run starting at or before `fc`. It stays the answer for every FC from its own + // start up to the smallest start after it (also in a page whose starts do not ascend). let j = (0..crun).rev().find(|&j| rgfc(j).is_some_and(|f| f <= fc)); - let Some(j) = j else { return &[] }; - let Some(&off) = page.get(rgb_at + j) else { return &[] }; + let first_after = j.map_or(0, |j| j + 1); + let hi = (first_after..crun).filter_map(rgfc).min().map_or(page_hi, |m| m.min(page_hi)); + let lo = j.and_then(rgfc).map_or(page_lo, |f| f.max(page_lo)); + let run = |grpprl: &'w [u8]| ChpxRun { grpprl, lo, hi }; + let Some(j) = j else { return run(&[]) }; + let Some(&off) = page.get(rgb_at + j) else { return run(&[]) }; if off == 0 { - return &[]; + return run(&[]); } let at = off as usize * 2; - let Some(&cb) = page.get(at) else { return &[] }; - page.get(at + 1..at + 1 + cb as usize).unwrap_or(&[]) + let Some(&cb) = page.get(at) else { return run(&[]) }; + run(page.get(at + 1..at + 1 + cb as usize).unwrap_or(&[])) } /// The (istd, grpprl) of the Papx of the paragraph whose mark is just before `fc` @@ -75,7 +114,7 @@ impl Bins { /// entries (1 offset byte + 12 PHE bytes), crun in the last byte; the PAPX itself is a /// PapxInFkp with the cb/cb' size quirk). Query with the FC of the character after the mark. pub(crate) fn papx<'w>(&self, word: &'w [u8], fc: u32) -> (u16, &'w [u8]) { - let Some(page) = self.page(word, fc) else { return (0, &[]) }; + let Some((page, _, _)) = self.page(word, fc) else { return (0, &[]) }; let Some(&crun) = page.get(511) else { return (0, &[]) }; // BX is 13 bytes; cap crun at what fits before byte 511. let max_run = (511usize.saturating_sub((crun as usize + 1) * 4)) / 13; diff --git a/crates/docbin/src/lib.rs b/crates/docbin/src/lib.rs index e97e2676d3..a2461d3fb2 100644 --- a/crates/docbin/src/lib.rs +++ b/crates/docbin/src/lib.rs @@ -502,29 +502,37 @@ struct ParaBuild { runs: Vec, props: wordcraft_doc::props::ParaProps, mark: CharProps, - /// The current run's properties, so runs only break when formatting changes. - cur: Option, + /// Which resolved formatting ([`FmtState::generation`]) the last character came from, while + /// the last run is still the one it extended: the same generation means equal properties. + run_gen: Option, /// Inline objects, each anchored at a U+FFFC pushed into `text`. objects: Vec, } impl ParaBuild { fn push(&mut self, c: char, props: CharProps) { + self.run_gen = None; let len = c.len_utf8(); - match &self.cur { - Some(p) if *p == props => { - if let Some(r) = self.runs.last_mut() { - r.len += len; - } - } - _ => { - self.runs.push(Run { len, props: props.clone() }); - self.cur = Some(props); - } + match self.runs.last_mut() { + Some(r) if r.props == props => r.len += len, + _ => self.runs.push(Run { len, props }), } self.text.push(c); } + /// [`ParaBuild::push`] for properties that are resolved once and shared by many characters: + /// they are cloned only when a run starts, and not even compared while `generation` stays + /// the same. + fn push_shared(&mut self, c: char, props: &CharProps, generation: u64) { + let len = c.len_utf8(); + match self.runs.last_mut() { + Some(r) if self.run_gen == Some(generation) || r.props == *props => r.len += len, + _ => self.runs.push(Run { len, props: props.clone() }), + } + self.run_gen = Some(generation); + self.text.push(c); + } + /// Append `c` to the current run, whose properties the caller knows it matches. fn extend(&mut self, c: char) { if let Some(r) = self.runs.last_mut() { @@ -552,7 +560,7 @@ fn walk<'a>(ctx: &WalkCtx<'a>, cp_start: u32, cp_end: u32, pics: &mut media::Pic // Field assembly state: instruction characters are swallowed, the result is kept until // the end character, then emitted as one object (hyperlinks keep their result text). let mut field: Option = None; - let mut memo: Option> = None; + let mut fmt = FmtState::default(); while cp < cp_end { // Bookmark boundaries at this CP (main-document walks only; subdocument walks get // an empty table and `cp` never matches the main-document CPs). @@ -715,16 +723,16 @@ fn walk<'a>(ctx: &WalkCtx<'a>, cp_start: u32, cp_end: u32, pics: &mut media::Pic pb.objects.push(InlineObject::NoteRef { kind: *kind, id: *id, custom: String::new() }); } } - '\t' => push_formatted(&mut pb, cp, '\t', ctx, field.as_mut(), &mut memo), - '\u{B}' => push_formatted(&mut pb, cp, '\n', ctx, field.as_mut(), &mut memo), - '\u{C}' => push_formatted(&mut pb, cp, '\u{C}', ctx, field.as_mut(), &mut memo), - '\u{E}' => push_formatted(&mut pb, cp, '\u{E}', ctx, field.as_mut(), &mut memo), - '\u{1E}' => push_formatted(&mut pb, cp, '\u{2011}', ctx, field.as_mut(), &mut memo), - '\u{1F}' => push_formatted(&mut pb, cp, '\u{AD}', ctx, field.as_mut(), &mut memo), + '\t' => push_formatted(&mut pb, cp, '\t', ctx, field.as_mut(), &mut fmt), + '\u{B}' => push_formatted(&mut pb, cp, '\n', ctx, field.as_mut(), &mut fmt), + '\u{C}' => push_formatted(&mut pb, cp, '\u{C}', ctx, field.as_mut(), &mut fmt), + '\u{E}' => push_formatted(&mut pb, cp, '\u{E}', ctx, field.as_mut(), &mut fmt), + '\u{1E}' => push_formatted(&mut pb, cp, '\u{2011}', ctx, field.as_mut(), &mut fmt), + '\u{1F}' => push_formatted(&mut pb, cp, '\u{AD}', ctx, field.as_mut(), &mut fmt), // Object anchors, comment references and other special characters are dropped // (or handled by later passes). c if (c as u32) < 0x20 => {} - c => push_formatted(&mut pb, cp, c, ctx, field.as_mut(), &mut memo), + c => push_formatted(&mut pb, cp, c, ctx, field.as_mut(), &mut fmt), } cp = cp.saturating_add(units); } @@ -854,34 +862,53 @@ fn num_of(ilfo: i32) -> Option { /// plus the piece's Prm, over the paragraph style's base character props. Inside a field, /// the character is recorded into the instruction or the cached result instead of (or as /// well as) the visible text. -fn push_formatted<'a>(pb: &mut ParaBuild, cp: u32, c: char, ctx: &WalkCtx<'a>, field: Option<&mut FieldBuild>, memo: &mut Option>) { - let fc = ctx.pieces.fc_of_cp(cp).unwrap_or(0); - let grpprl = ctx.chpx_bins.chpx(ctx.word, fc); - let prm = ctx.pieces.prm_of(cp); - let style = pb.props.style.as_deref(); - let mut props = match memo.as_ref().filter(|m| std::ptr::eq(m.chpx, grpprl) && m.prm == prm && m.style.as_deref() == style) { - Some(m) => m.props.clone(), +fn push_formatted<'a>(pb: &mut ParaBuild, cp: u32, c: char, ctx: &WalkCtx<'a>, field: Option<&mut FieldBuild>, st: &mut FmtState<'a>) { + // The piece and the CHPX run of the previous character usually cover this one too. + let span = match st.span.filter(|s| s.contains(cp)) { + Some(s) => Some(s), None => { - let default; - let base = match style.and_then(|id| ctx.sheet.get(id)) { - Some(st) => &st.chr, - None => { - default = CharProps::default(); - &default - } - }; - let mut props = char_props(grpprl, ctx.fonts, base); - apply_prm(&mut props, ctx.pieces.piece_prm(cp), ctx.fonts, base, ctx.work); - *memo = Some(FmtMemo { chpx: grpprl, prm, style: style.map(str::to_owned), props: props.clone() }); - props + st.span = ctx.pieces.span(cp); + st.span } }; + let fc = span.and_then(|s| s.fc_at(cp)).unwrap_or(0); + let run = match st.chpx.filter(|r| r.contains(fc)) { + Some(r) => r, + None => { + let r = ctx.chpx_bins.chpx_run(ctx.word, fc); + st.chpx = Some(r); + r + } + }; + let grpprl = run.grpprl; + let prm = span.map_or(0, |s| s.prm()); + let style = pb.props.style.as_deref(); + let hit = st.memo.as_ref().is_some_and(|m| std::ptr::eq(m.chpx, grpprl) && m.prm == prm && m.style.as_deref() == style); + if !hit { + let default; + let base = match style.and_then(|id| ctx.sheet.get(id)) { + Some(sty) => &sty.chr, + None => { + default = CharProps::default(); + &default + } + }; + let mut props = char_props(grpprl, ctx.fonts, base); + apply_prm(&mut props, ctx.pieces.piece_prm(cp), ctx.fonts, base, ctx.work); + st.memo = Some(FmtMemo { chpx: grpprl, prm, style: style.map(str::to_owned), props }); + st.generation += 1; + } + let Some(m) = st.memo.as_ref() else { return }; // A symbol character (Insert › Symbol) is stored as the placeholder U+0028 with // sprmCSymbol carrying the font and the character code ([MS-DOC] §2.6.1). + let symbol = if c == '(' { symbol_operand(grpprl) } else { None }; + if field.is_none() && symbol.is_none() { + pb.push_shared(c, &m.props, st.generation); + return; + } + let mut props = m.props.clone(); let mut c = c; - if c == '(' - && let Some((ftc, xchar)) = symbol_operand(grpprl) - { + if let Some((ftc, xchar)) = symbol { if let Some(font) = ctx.fonts.get(usize::from(ftc)) { props.font = Some(font.clone()); } @@ -900,6 +927,18 @@ fn push_formatted<'a>(pb: &mut ParaBuild, cp: u32, c: char, ctx: &WalkCtx<'a>, f } } +/// What the walk carries from one character to the next while it resolves formatting: the piece +/// and the CHPX run the last character was in (so most characters need no search), and the last +/// formatting resolved. +#[derive(Default)] +struct FmtState<'a> { + span: Option>, + chpx: Option>, + memo: Option>, + /// Counts the memo's replacements, so equal values mean the same properties. + generation: u64, +} + /// The last character formatting resolved, reused while the CHPX, the piece's Prm and the /// paragraph style stay the same, so a Prm grpprl (up to 64 KB) is interpreted once per /// formatting change, not once per character (#3692). diff --git a/crates/docbin/src/piece.rs b/crates/docbin/src/piece.rs index d52f968b7a..fda4e5470c 100644 --- a/crates/docbin/src/piece.rs +++ b/crates/docbin/src/piece.rs @@ -117,12 +117,6 @@ impl PieceTable { } } - /// The raw Prm of the piece holding `cp` (0, no properties, when there is none): two CPs - /// with the same value get the same [`PrmRef`]. - pub(crate) fn prm_of(&self, cp: u32) -> u16 { - self.piece_of(cp).map_or(0, |p| p.prm) - } - fn piece_of(&self, cp: u32) -> Option<&Pcd> { let i = self.cps.partition_point(|&c| c <= cp).checked_sub(1)?; if i >= self.pieces.len() { @@ -143,6 +137,17 @@ impl PieceTable { if p.compressed { p.fc.checked_add(step)?.checked_div(2) } else { p.fc.checked_add(step) } } + /// The piece holding `cp`, with the CP range it covers: for every CP in that range the + /// answers of [`PieceTable::fc_of_cp`] and the piece's Prm come from this span alone, + /// so a sequential walk searches the piece table once per piece. + pub(crate) fn span(&self, cp: u32) -> Option> { + let i = self.cps.partition_point(|&c| c <= cp).checked_sub(1)?; + let pcd = self.pieces.get(i)?; + let cp_lo = *self.cps.get(i)?; + let cp_hi = *self.cps.get(i + 1)?; + Some(PieceSpan { cp_lo, cp_hi, pcd }) + } + /// The CP just past the last piece: no text exists at or beyond it. pub(crate) fn cp_end(&self) -> u32 { self.cps.last().copied().unwrap_or(0) @@ -187,6 +192,31 @@ impl PieceTable { } } +/// One piece and the CPs `[cp_lo, cp_hi)` it covers ([`PieceTable::span`]). +#[derive(Clone, Copy)] +pub(crate) struct PieceSpan<'a> { + cp_lo: u32, + cp_hi: u32, + pcd: &'a Pcd, +} + +impl PieceSpan<'_> { + pub(crate) fn contains(&self, cp: u32) -> bool { + self.cp_lo <= cp && cp < self.cp_hi + } + + /// [`PieceTable::fc_of_cp`] for a CP inside the span. + pub(crate) fn fc_at(&self, cp: u32) -> Option { + let step = cp.checked_sub(self.cp_lo)?.checked_mul(2)?; + if self.pcd.compressed { self.pcd.fc.checked_add(step)?.checked_div(2) } else { self.pcd.fc.checked_add(step) } + } + + /// The raw Prm of the piece: two CPs with the same value get the same [`PrmRef`]. + pub(crate) fn prm(&self) -> u16 { + self.pcd.prm + } +} + /// What a piece's `Prm` refers to. pub(crate) enum PrmRef<'a> { None, diff --git a/crates/docbin/src/tests.rs b/crates/docbin/src/tests.rs index 1128eca38a..22ec2fc1e4 100644 --- a/crates/docbin/src/tests.rs +++ b/crates/docbin/src/tests.rs @@ -2880,3 +2880,153 @@ fn field_results_keep_their_text_and_runs() { p.objects ); } + +/// A one-page CHPX bin table over `page`: FCs 0..`end` live in page 1 of the returned stream. +fn one_page_bins(page: &[u8], end: u32) -> (Vec, crate::fkp::Bins) { + let mut word = vec![0u8; 512]; + word.extend_from_slice(page); + let plc = [0u32.to_le_bytes().as_slice(), end.to_le_bytes().as_slice(), 1u32.to_le_bytes().as_slice()].concat(); + let bins = crate::fkp::Bins::parse(&plc, 0, 12).expect("bins"); + (word, bins) +} + +/// The CHPX run a lookup reports covers exactly the FCs that give the same grpprl: the walk +/// reuses it for the following characters without asking again. +#[test] +fn a_chpx_run_covers_the_fcs_with_the_same_answer() { + let runs = [(0u32, grpprl(&[(0x0835, &[1])])), (5, Vec::new()), (9, grpprl(&[(0x0836, &[1])])), (30, grpprl(&[(0x0835, &[1])]))]; + let (word, bins) = one_page_bins(&chpx_fkp(&runs, 60), 0x2000); + for fc in (fc_of(0) - 4)..(fc_of(70)) { + let run = bins.chpx_run(&word, fc); + assert_eq!(run.grpprl, bins.chpx(&word, fc), "fc {fc}"); + for other in (fc_of(0) - 4)..(fc_of(70)) { + if run.contains(other) { + assert_eq!(bins.chpx(&word, other), run.grpprl, "fc {fc} run reused at {other}"); + } + } + } + assert!(bins.chpx_run(&word, fc_of(6)).contains(fc_of(8)) && !bins.chpx_run(&word, fc_of(6)).contains(fc_of(9))); +} + +/// A page whose run starts do not ascend (a corrupt file) gives the same answers as before and +/// a range that never claims an FC with a different answer. +#[test] +fn a_chpx_run_is_sound_on_a_page_whose_starts_do_not_ascend() { + let runs = [(10u32, grpprl(&[(0x0835, &[1])])), (3, grpprl(&[(0x0836, &[1])])), (20, Vec::new()), (7, grpprl(&[(0x0835, &[1])]))]; + let (word, bins) = one_page_bins(&chpx_fkp(&runs, 60), 0x2000); + for fc in (fc_of(0) - 4)..(fc_of(70)) { + let run = bins.chpx_run(&word, fc); + assert_eq!(run.grpprl, bins.chpx(&word, fc)); + for other in (fc_of(0) - 4)..(fc_of(70)) { + if run.contains(other) { + assert_eq!(bins.chpx(&word, other), run.grpprl, "fc {fc} run reused at {other}"); + } + } + } +} + +/// A piece span answers exactly what the per-CP lookup answers, in every piece (compressed +/// and UTF-16) and past the last. +#[test] +fn a_piece_span_matches_the_per_cp_lookups() { + let doc = text_doc( + &[ + Piece { compressed: true, text: "abc".into() }, + Piece { compressed: false, text: "d\u{e9}fgh".into() }, + Piece { compressed: true, text: "ij".into() }, + ], + &[], + 0, + ); + let mut comp = crate::open_container(&doc).expect("container"); + let table = crate::stream(&mut comp, "0Table").expect("table"); + let pieces = crate::piece::PieceTable::parse(&table, CLX_AT, table.len() as u32 - CLX_AT).expect("pieces"); + for cp in 0..14 { + let span = pieces.span(cp); + assert_eq!(span.and_then(|s| s.fc_at(cp)), pieces.fc_of_cp(cp), "cp {cp}"); + for other in 0..14 { + if span.is_some_and(|s| s.contains(other)) { + assert_eq!(pieces.span(other).and_then(|s| s.fc_at(other)), pieces.fc_of_cp(other)); + } + } + } + assert!(pieces.span(10).is_none(), "past the last piece"); +} + +/// Characters of one formatting share one `CharProps`: it is cloned when a run starts, and not +/// even compared while the formatting stays the same. +#[test] +fn shared_props_start_one_run_per_formatting() { + use wordcraft_doc::props::CharProps; + let bold = CharProps { bold: Some(true), ..Default::default() }; + let mut pb = super::ParaBuild::default(); + for _ in 0..100_000 { + pb.push_shared('a', &bold, 1); + } + pb.push_shared('b', &CharProps::default(), 2); + pb.push_shared('c', &bold, 3); + pb.push_shared('d', &bold, 4); + assert_eq!(pb.runs.iter().map(|r| r.len).collect::>(), [100_000, 1, 2], "equal props under a new generation join the run"); + pb.push('e', bold.clone()); + pb.push_shared('f', &bold, 4); + assert_eq!( + pb.runs.iter().map(|r| r.len).collect::>(), + [100_000, 1, 4], + "a plain push forgets the generation but still joins an equal run" + ); + assert_eq!(pb.text.len(), 100_005); +} + +/// Several bins, equal and descending breakpoints, a missing page and the last FC: wherever a +/// run is reported as valid it gives the answer a fresh lookup gives. +#[test] +fn chpx_runs_are_sound_across_bins() { + let page_a = chpx_fkp(&[(0, grpprl(&[(0x0835, &[1])])), (8, grpprl(&[(0x0836, &[1])]))], 20); + let page_b = chpx_fkp(&[(20, Vec::new()), (26, grpprl(&[(0x0835, &[1])]))], 40); + let mut word = vec![0u8; 512]; + word.extend_from_slice(&page_a); + word.extend_from_slice(&page_b); + let (a, b, end) = (fc_of(20), fc_of(40), fc_of(60)); + let plc = |fcs: &[u32], pns: &[u32]| { + [fcs.iter().flat_map(|f| f.to_le_bytes()).collect::>(), pns.iter().flat_map(|p| p.to_le_bytes()).collect()].concat() + }; + let tables = [ + ("two bins", plc(&[0, a, end], &[1, 2])), + ("an empty bin", plc(&[0, a, a, end], &[1, 2, 2])), + ("a missing page", plc(&[0, a, end], &[1, 9])), + ("descending breakpoints", plc(&[0, b, a, end], &[1, 2, 1])), + ("fcs up to the maximum", plc(&[0, a, u32::MAX], &[1, 2])), + ]; + for (what, t) in &tables { + let bins = crate::fkp::Bins::parse(t, 0, t.len() as u32).expect("bins"); + let probes: Vec = (0..fc_of(50)).step_by(2).chain([u32::MAX - 1, u32::MAX]).collect(); + for &fc in &probes { + let run = bins.chpx_run(&word, fc); + assert_eq!(run.grpprl, bins.chpx(&word, fc), "{what}: fc {fc}"); + for &other in &probes { + if run.contains(other) { + assert_eq!(bins.chpx(&word, other), run.grpprl, "{what}: fc {fc} run reused at {other}"); + } + } + } + } +} + +/// The same formatting changes through a whole read: runs break exactly where the CHPX changes +/// (with a field and a symbol character in between), and nowhere else. +#[test] +fn formatting_runs_break_where_the_chpx_changes() { + let spec = RichSpec { + text: "aaaabbbb\u{13}PAGE\u{14}12\u{15}ccdd(ee\r", + styles: vec![(1, 0x0FFF, "Normal", Vec::new(), Vec::new())], + fonts: vec!["Times New Roman", "Arial"], + chpx_runs: vec![(0, grpprl(&[(0x0835, &[1])])), (4, Vec::new()), (8, grpprl(&[(0x0835, &[1])])), (20, grpprl(&[(0x0836, &[1])]))], + papx_entries: vec![(30, 0, Vec::new())], + }; + let doc = read(&rich_doc(&spec)).expect("opens"); + let p = para0(&doc); + let shape: Vec<(usize, Option, Option)> = p.runs.iter().map(|r| (r.len, r.props.bold, r.props.italic)).collect(); + // "aaaa" bold, "bbbb" plain plus the field's anchor (3 bytes, default formatting), "ccd" bold + // (the run from the field to CP 20), "d(ee" italic. + assert_eq!(shape, [(4, Some(true), None), (7, None, None), (3, Some(true), None), (4, None, Some(true))], "{shape:?}"); +} diff --git a/crates/docx/src/read/story/drawing.rs b/crates/docx/src/read/story/drawing.rs index 3a69dcc4e3..1481df8745 100644 --- a/crates/docx/src/read/story/drawing.rs +++ b/crates/docx/src/read/story/drawing.rs @@ -118,9 +118,33 @@ impl Reader<'_> { Some(obj) } + /// The hyperlink Word keeps on a drawing itself: its `wp:docPr`'s `a:hlinkClick` (ECMA-376 + /// Part 1 §20.4.2.5, §21.1.2.3.5) naming an external hyperlink relationship. Word stores a + /// picture's link there rather than in a `w:hyperlink` around its run (#5267). Its `#name` + /// part, when the address has one, stays part of the address. + pub(super) fn drawing_link(d: &El, rels: &Rels) -> Option { + let frame = d.child("wp:inline").or_else(|| d.child("wp:anchor"))?; + let id = frame.child("wp:docPr")?.child("a:hlinkClick")?.attr("r:id")?; + let rel = rels.by_id(id).filter(|r| r.external && crate::package::rel_is(&r.kind, rt::HYPERLINK))?; + Some(rel.target.trim().to_string()).filter(|u| !u.is_empty()) + } + + /// Native ink or an Office 2016 chart kept with its fallback (`mc:AlternateContent`), and the + /// [`Self::drawing_link`] of the choice it was read from, else of its fallback: another + /// choice's link is not this object's. + pub(super) fn read_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option<(InlineObject, Option)> { + let (object, choice) = match self.read_ink_alternate(sc, ac, rels) { + Some(o) => (o, children_of_choice(ac).filter(|e| e.name == "mc:Choice")), + None => (self.read_chartex_alternate(sc, ac, rels)?, chartex_choice(ac)), + }; + let link = + [choice, ac.child("mc:Fallback")].into_iter().flatten().filter_map(|e| e.child("w:drawing")).find_map(|d| Self::drawing_link(d, rels)); + Some((object, link)) + } + /// Keep the selected native-ink branch and its picture fallback as one object. Reading only /// the fallback flattens the ink; reading only the choice loses its preview on the next save. - pub(super) fn read_ink_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option { + fn read_ink_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option { let choice = children_of_choice(ac).filter(|e| e.name == "mc:Choice")?; let drawing = choice.child("w:drawing")?; if drawing.find("a:graphicData")?.attr("uri") != Some(INK_URI) { @@ -149,10 +173,8 @@ impl Reader<'_> { /// An Office 2016 chart (`cx:chart`: waterfall, sunburst, box & whisker…) drawn from its /// fallback picture, keeping both branches so saving writes the chart back rather than only /// the picture. `None` (read the fallback alone) when it can't be kept whole. - pub(super) fn read_chartex_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option { - let choice = ac - .children("mc:Choice") - .find(|c| c.child("w:drawing").and_then(|d| d.find("a:graphicData")).and_then(|g| g.attr("uri")) == Some(CHARTEX_URI))?; + fn read_chartex_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option { + let choice = chartex_choice(ac)?; // A requirement in a namespace we can't name couldn't be written back. let requires = choice.attr("Requires").unwrap_or(""); if requires.split_whitespace().next().is_none() || requires.split_whitespace().any(|p| p == "?") { @@ -563,6 +585,11 @@ impl Reader<'_> { } } +/// The `mc:Choice` holding an Office 2016 chart (`cx:chart`) in an `mc:AlternateContent`. +fn chartex_choice(ac: &El) -> Option<&El> { + ac.children("mc:Choice").find(|c| c.child("w:drawing").and_then(|d| d.find("a:graphicData")).and_then(|g| g.attr("uri")) == Some(CHARTEX_URI)) +} + /// The alternative text of a `wp:docPr`, `pic:cNvPr` or `wps:cNvPr` (ECMA-376 /// `CT_NonVisualDrawingProps`): the description (the title when there is none, as before), and /// the title and decorative mark (the `adec:decorative` extension of [MS-ODRAWXML]). diff --git a/crates/docx/src/read/story/runs.rs b/crates/docx/src/read/story/runs.rs index 9dec4c5b48..d43cc3a214 100644 --- a/crates/docx/src/read/story/runs.rs +++ b/crates/docx/src/read/story/runs.rs @@ -98,9 +98,9 @@ impl Reader<'_> { } } "mc:AlternateContent" => { - if let Some(o) = self.read_ink_alternate(sc, k, rels).or_else(|| self.read_chartex_alternate(sc, k, rels)) { + if let Some((o, link)) = self.read_alternate(sc, k, rels) { let props = self.run_props_none(ctx); - self.emit_obj(sc, pb, o, &props); + self.emit_linked_obj(sc, pb, o, &props, link); } else if let Some(c) = children_of_choice(k) { self.read_inline_children(sc, pb, c, rels, ctx, depth + 1); } @@ -237,7 +237,7 @@ impl Reader<'_> { }, "w:drawing" => { if let Some(o) = self.read_drawing(sc, k, rels) { - self.emit_obj(sc, pb, o, props); + self.emit_linked_obj(sc, pb, o, props, Self::drawing_link(k, rels)); } } "w:pict" => { @@ -298,8 +298,8 @@ impl Reader<'_> { ), "w:ruby" => self.read_ruby(sc, pb, k, props), "mc:AlternateContent" => { - if let Some(o) = self.read_ink_alternate(sc, k, rels).or_else(|| self.read_chartex_alternate(sc, k, rels)) { - self.emit_obj(sc, pb, o, props); + if let Some((o, link)) = self.read_alternate(sc, k, rels) { + self.emit_linked_obj(sc, pb, o, props, link); } else if let Some(c) = children_of_choice(k) { for x in c.els() { self.read_run_child(sc, pb, x, (props, rels), note, depth + 1); @@ -376,6 +376,14 @@ impl Reader<'_> { } } + /// [`Self::emit_obj`] for a drawing that carries its own `link`: a link around the run wins. + fn emit_linked_obj(&mut self, sc: &mut StoryCtx, pb: &mut PB, o: InlineObject, props: &CharProps, link: Option) { + match link.filter(|_| props.link.is_none()) { + Some(link) => self.emit_obj(sc, pb, o, &CharProps { link: Some(link), ..props.clone() }), + None => self.emit_obj(sc, pb, o, props), + } + } + pub(super) fn emit_obj(&mut self, sc: &mut StoryCtx, pb: &mut PB, o: InlineObject, props: &CharProps) { match sink(sc) { Some(f) => { diff --git a/crates/docx/src/write/story/drawing.rs b/crates/docx/src/write/story/drawing.rs index f82a736fab..0edb1117ee 100644 --- a/crates/docx/src/write/story/drawing.rs +++ b/crates/docx/src/write/story/drawing.rs @@ -10,9 +10,19 @@ pub(super) struct DrawingInfo<'a> { pub docpr: &'a str, pub name: &'a str, pub alt: &'a str, + /// The relationship id of the drawing's hyperlink (`a:hlinkClick`), see [`Writer::drawing_link`]. + pub link: Option<&'a str>, } impl Writer<'_> { + /// The relationship of the hyperlink a drawing in a run with `props` carries on itself, as + /// Word writes a picture's link (`wp:docPr/a:hlinkClick`, #5267): a web or file address. A + /// link to a place in the document (`#name`) is only the `w:hyperlink` around the run. + pub(super) fn drawing_link(props: &wordcraft_doc::CharProps, rels: &mut PartRels) -> Option { + let url = props.link.as_deref().filter(|l| !l.is_empty() && !l.starts_with('#'))?; + Some(rels.add(rt::HYPERLINK, url, true)) + } + /// A picture's `pic:pic` (the image in `media/{file}`), at `off` in its group (or 0, 0). pub(super) fn pic(&mut self, w: &mut W, o: &InlineObject, file: &str, off: (f32, f32), rels: &mut PartRels) { let InlineObject::Image { media, w: iw, h: ih, alt, crop, float, fx, .. } = o else { return }; @@ -20,7 +30,7 @@ impl Writer<'_> { self.used_media.insert(media.clone()); w.open("pic:pic", &[]); w.open("pic:nvPicPr", &[]); - nv_props(w, "pic:cNvPr", "0", file, alt, &float.alt, float.hidden); + nv_props(w, "pic:cNvPr", ("0", file), alt, &float.alt, float.hidden, None); w.open("pic:cNvPicPr", &[]); w.empty("a:picLocks", &[("noChangeAspect", "1"), ("noChangeArrowheads", "1")]); w.close("pic:cNvPicPr"); @@ -66,7 +76,7 @@ impl Writer<'_> { w.open("wps:wsp", &[]); if let Some(id) = id { let name = shape_name(*kind, freeform.as_deref(), id); - nv_props(w, "wps:cNvPr", id, &name, &float.alt.text, &float.alt, float.hidden); + nv_props(w, "wps:cNvPr", (id, &name), &float.alt.text, &float.alt, float.hidden, None); } if kind.is_connector() { // A connector's glued ends (ECMA-376 §20.1.2.2.8 `cNvCxnSpPr`). @@ -235,7 +245,7 @@ impl Writer<'_> { } pub(super) fn drawing_open(&mut self, w: &mut W, info: DrawingInfo<'_>) { - let DrawingInfo { float, size: (iw, ih), docpr, name, alt } = info; + let DrawingInfo { float, size: (iw, ih), docpr, name, alt, link } = info; let (cx, cy) = (emu(iw.max(0.0)), emu(ih.max(0.0))); if float.wrap == Wrap::Inline { w.open("wp:inline", &[("distT", "0"), ("distB", "0"), ("distL", "0"), ("distR", "0")]); @@ -316,7 +326,7 @@ impl Writer<'_> { Wrap::TopAndBottom => w.empty("wp:wrapTopAndBottom", &[]), Wrap::BehindText | Wrap::InFrontOfText => w.empty("wp:wrapNone", &[]), } - nv_props(w, "wp:docPr", docpr, name, alt, &float.alt, float.hidden); + nv_props(w, "wp:docPr", (docpr, name), alt, &float.alt, float.hidden, link); } } @@ -502,8 +512,9 @@ pub(in super::super) fn spin_attrs(spin: wordcraft_geom::Spin) -> Vec<(&'static /// A drawing's `wp:docPr` (or a group member's `pic:cNvPr`/`wps:cNvPr`, ECMA-376 /// `CT_NonVisualDrawingProps`) with its alt text `descr`, its title, and the decorative mark as /// the `adec:decorative` extension ([MS-ODRAWXML]). A description that is only the title (read -/// from a file with no description) is not written twice. -pub(in super::super) fn nv_props(w: &mut W, tag: &str, id: &str, name: &str, descr: &str, alt: &AltText, hidden: bool) { +/// from a file with no description) is not written twice. `link` is the relationship id of the +/// drawing's hyperlink (`a:hlinkClick`, the first child the schema allows). +pub(in super::super) fn nv_props(w: &mut W, tag: &str, (id, name): (&str, &str), descr: &str, alt: &AltText, hidden: bool, link: Option<&str>) { let mut attrs = vec![("id", id), ("name", name)]; if descr != alt.title || descr.is_empty() { attrs.push(("descr", descr)); @@ -514,16 +525,21 @@ pub(in super::super) fn nv_props(w: &mut W, tag: &str, id: &str, name: &str, des if hidden { attrs.push(("hidden", "1")); } - if !alt.decorative { + if !alt.decorative && link.is_none() { w.empty(tag, &attrs); return; } w.open(tag, &attrs); - w.open("a:extLst", &[]); - w.open("a:ext", &[("uri", crate::xml::DECORATIVE_EXT)]); - w.empty("adec:decorative", &[("xmlns:adec", crate::xml::DECORATIVE_NS), ("val", "1")]); - w.close("a:ext"); - w.close("a:extLst"); + if let Some(rid) = link { + w.empty("a:hlinkClick", &[("r:id", rid)]); + } + if alt.decorative { + w.open("a:extLst", &[]); + w.open("a:ext", &[("uri", crate::xml::DECORATIVE_EXT)]); + w.empty("adec:decorative", &[("xmlns:adec", crate::xml::DECORATIVE_NS), ("val", "1")]); + w.close("a:ext"); + w.close("a:extLst"); + } w.close(tag); } diff --git a/crates/docx/src/write/story/object.rs b/crates/docx/src/write/story/object.rs index ef6c338216..5e8bc21ba8 100644 --- a/crates/docx/src/write/story/object.rs +++ b/crates/docx/src/write/story/object.rs @@ -220,13 +220,18 @@ impl Writer<'_> { w.open("mc:Choice", &[("Requires", requires)]); } let docpr = self.next_docpr(); + let link = Self::drawing_link(props, rels); let name = match graphic.kind { wordcraft_doc::graphic::GraphicKind::Chart => format!("Chart {docpr}"), wordcraft_doc::graphic::GraphicKind::Diagram => format!("Diagram {docpr}"), wordcraft_doc::graphic::GraphicKind::Ink => format!("Ink {docpr}"), }; let z = self.z; - self.graphic_frame(w, DrawingInfo { float, size: (*gw, *gh), docpr: &docpr, name: &name, alt }, native.unwrap_or(&root)); + self.graphic_frame( + w, + DrawingInfo { float, size: (*gw, *gh), docpr: &docpr, name: &name, alt, link: link.as_deref() }, + native.unwrap_or(&root), + ); if let Some(fallback) = fallback { w.close("mc:Choice"); match picture { @@ -234,7 +239,11 @@ impl Writer<'_> { // Both branches are one object: same id and stacking order. self.z = z; w.open("mc:Fallback", &[]); - self.graphic_frame(w, DrawingInfo { float, size: (*gw, *gh), docpr: &docpr, name: &name, alt }, picture); + self.graphic_frame( + w, + DrawingInfo { float, size: (*gw, *gh), docpr: &docpr, name: &name, alt, link: link.as_deref() }, + picture, + ); w.close("mc:Fallback"); } None => w.raw(&fallback.to_xml()), @@ -266,8 +275,9 @@ impl Writer<'_> { self.rpr(w, props); w.open("w:drawing", &[]); let docpr = self.next_docpr(); + let link = Self::drawing_link(props, rels); let name = format!("Picture {docpr}"); - self.drawing_open(w, DrawingInfo { float, size: (*iw, *ih), docpr: &docpr, name: &name, alt }); + self.drawing_open(w, DrawingInfo { float, size: (*iw, *ih), docpr: &docpr, name: &name, alt, link: link.as_deref() }); w.empty("wp:cNvGraphicFramePr", &[]); w.open("a:graphic", &[]); w.open("a:graphicData", &[("uri", "http://schemas.openxmlformats.org/drawingml/2006/picture")]); @@ -355,6 +365,7 @@ impl Writer<'_> { self.rpr(w, props); w.open("w:drawing", &[]); let docpr = self.shape_docpr(extra.id); + let link = Self::drawing_link(props, rels); // Ink is told apart by its name (and its pen), which reading looks for. let name = shape_name(*kind, freeform.as_deref(), &docpr); // The effect extent leaves room for the shadow and glow. @@ -369,7 +380,7 @@ impl Writer<'_> { .map(std::sync::Arc::new); } let float = &float; - self.drawing_open(w, DrawingInfo { float, size: (*sw, *sh), docpr: &docpr, name: &name, alt: o.alt_text() }); + self.drawing_open(w, DrawingInfo { float, size: (*sw, *sh), docpr: &docpr, name: &name, alt: o.alt_text(), link: link.as_deref() }); w.empty("wp:cNvGraphicFramePr", &[]); w.open("a:graphic", &[]); w.open("a:graphicData", &[("uri", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape")]); @@ -389,8 +400,9 @@ impl Writer<'_> { self.rpr(w, props); w.open("w:drawing", &[]); let docpr = self.next_docpr(); + let link = Self::drawing_link(props, rels); let name = format!("{} {docpr}", if canvas.is_some() { "Canvas" } else { "Group" }); - self.drawing_open(w, DrawingInfo { float, size: (*gw, *gh), docpr: &docpr, name: &name, alt: o.alt_text() }); + self.drawing_open(w, DrawingInfo { float, size: (*gw, *gh), docpr: &docpr, name: &name, alt: o.alt_text(), link: link.as_deref() }); w.empty("wp:cNvGraphicFramePr", &[]); w.open("a:graphic", &[]); let outer = match canvas { diff --git a/crates/docx/src/xml.rs b/crates/docx/src/xml.rs index 0436265b0f..f14991673a 100644 --- a/crates/docx/src/xml.rs +++ b/crates/docx/src/xml.rs @@ -94,6 +94,49 @@ fn prefix_for(uri: &[u8], extra: &[(&'static str, &str)]) -> &'static str { "?" } +/// Word's 2006 namespace (`wne`). A Strict document from Word keeps a text box's content in +/// `wne:txbxContent`; a Transitional one uses `w:txbxContent`. +const WNE: &[u8] = b"http://schemas.microsoft.com/office/word/2006/wordml"; + +/// The canonical prefix of an element named `local` in namespace `uri`, inside an element +/// named `parent` (canonical, `None` at the root). This is [`prefix_for`] with two exceptions +/// for Strict documents (#3548): +/// +/// - Shapes, groups and canvases (`wsp`, `wgp`, `wpc`) and their parts are elements of the +/// WordprocessingDrawing namespace in ECMA-376 Part 1, 5th edition (`dml-wordprocessingDrawing.xsd`, +/// Strict and Transitional alike). A Strict document from Word puts them there; a Transitional +/// one uses Word 2010's own namespaces, whose names the reader knows. So they read as `wps:`, +/// `wpg:` and `wpc:` (see [`drawing_prefix`]). +/// - A shape's text box content reads as `w:txbxContent` from the drawing namespace (the +/// schema's name) and from Word's `wne:txbxContent`. +fn element_prefix(uri: &[u8], local: &str, parent: Option<&str>, extra: &[(&'static str, &str)]) -> &'static str { + match prefix_for(uri, extra) { + "wp" => drawing_prefix(local, parent), + "?" if uri == WNE && local == "txbxContent" && parent == Some("wps:txbx") => "w", + p => p, + } +} + +/// The prefix for `local`, an element of the WordprocessingDrawing namespace inside `parent`. +/// Word 2010's namespaces split what this one holds: a shape and its parts are `wps:`, a group +/// (`wgp`, a nested `grpSp`) and a graphic frame in it are `wpg:`, and a canvas is `wpc:`. Its +/// members are named for what they are. A text box's content is `w:txbxContent`, and anything +/// else (`inline`, `anchor`, `docPr`…) stays `wp:`. +fn drawing_prefix(local: &str, parent: Option<&str>) -> &'static str { + match (parent, local) { + (_, "wsp") => "wps", + (_, "wgp" | "grpSp" | "graphicFrame") => "wpg", + (_, "wpc") => "wpc", + (Some("wps:wsp"), "cNvPr" | "cNvSpPr" | "cNvCnPr" | "spPr" | "style" | "extLst" | "txbx" | "linkedTxbx" | "bodyPr") => "wps", + (Some("wps:txbx"), "txbxContent") => "w", + (Some("wps:txbx" | "wps:linkedTxbx"), "extLst") => "wps", + (Some("wpg:wgp" | "wpg:grpSp"), "cNvPr" | "cNvGrpSpPr" | "grpSpPr" | "extLst") => "wpg", + (Some("wpg:graphicFrame"), "cNvPr" | "cNvFrPr" | "xfrm" | "extLst") => "wpg", + (Some("wpc:wpc"), "bg" | "whole" | "extLst") => "wpc", + _ => "wp", + } +} + /// Compatibility feature namespaces whose elements are not otherwise handled by this tree. /// Keep the reader's existing feature set when canonicalizing `mc:Choice/@Requires` aliases. fn requirement_prefix(uri: &[u8]) -> &'static str { @@ -342,8 +385,8 @@ fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool) -> Res loop { buf.clear(); let (res, ev) = r.read_resolved_event_into(&mut buf).map_err(|e| DocxError::Xml(e.to_string()))?; - let el_prefix = match &res { - ResolveResult::Bound(ns) => Some(prefix_for(ns.as_ref(), extra)), + let el_ns = match &res { + ResolveResult::Bound(ns) => Some(ns.as_ref()), _ => None, }; match ev { @@ -356,8 +399,8 @@ fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool) -> Res return Err(DocxError::Limit("too many XML elements".into())); } let local = String::from_utf8_lossy(e.local_name().as_ref()).into_owned(); - let name = match el_prefix { - Some(p) => format!("{p}:{local}"), + let name = match el_ns { + Some(ns) => format!("{}:{local}", element_prefix(ns, &local, stack.last().map(|p| p.name.as_str()), extra)), None => local, }; let mut el = El { name, attrs: Vec::new(), kids: Vec::new() }; @@ -593,6 +636,42 @@ mod tests { assert!(parse(b"").is_ok(), "lenient parsing still stops at the root"); } + /// Every element name in `e`, depth first. + fn names(e: &El, out: &mut Vec) { + out.push(e.name.clone()); + for c in e.els() { + names(c, out); + } + } + + #[test] + fn strict_drawing_names_read_as_word_2010_names() { + // A Strict shape with a text box, a group with a nested group and a graphic frame, and + // a canvas, each in the one Strict WordprocessingDrawing namespace (#3548). + let xml = br#" + + + + + + +"#; + let mut got = Vec::new(); + names(&parse(xml).unwrap(), &mut got); + let want = "w:body wp:anchor wp:extent wp:docPr wp:cNvGraphicFramePr a:graphic a:graphicData \ + wps:wsp wps:cNvPr wps:cNvSpPr wps:spPr wps:style wps:extLst wps:txbx w:txbxContent w:p wps:bodyPr \ + wpg:wgp wpg:cNvPr wpg:cNvGrpSpPr wpg:grpSpPr wpg:grpSp wpg:cNvGrpSpPr wpg:grpSpPr wps:wsp wps:cNvCnPr wps:spPr wps:linkedTxbx wps:bodyPr \ + wpg:graphicFrame wpg:cNvPr wpg:cNvFrPr wpg:xfrm a:graphic wpg:extLst wpg:extLst \ + wpc:wpc wpc:bg wpc:whole wps:wsp wps:spPr wps:txbx w:txbxContent wps:extLst wpg:wgp wpg:grpSpPr wpc:extLst \ + ?:txbxContent wp:inline wp:docPr wp:bodyPr wp:bg"; + assert_eq!(got.join(" "), want); + // The Transitional namespaces read as before. + let xml = br#""#; + let mut got = Vec::new(); + names(&parse(xml).unwrap(), &mut got); + assert_eq!(got.join(" "), "w:body wp:inline wp:docPr wps:wsp wps:txbx w:txbxContent ?:toolbars"); + } + #[test] fn a_relationship_attribute_is_the_namespaced_one_or_the_alias_of_one() { // The relationship namespace, and VML's `o:relid`. diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 1df2e96f9a..cb892282f8 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -1766,12 +1766,27 @@ const CT_CHARTEX: &str = "application/vnd.ms-office.chartex+xml"; /// A package holding one box & whisker chart the way Word writes it: the `cx:chart` in an /// `mc:Choice` requiring `requires` (bound to `requires_ns`), a picture of it in the `mc:Fallback`. fn chartex_docx(requires: &str, requires_ns: &str) -> Vec { - let frame = r#""#; + chartex_docx_linked(requires, requires_ns, false) +} + +/// [`chartex_docx`], its drawing linked to a web address (`wp:docPr/a:hlinkClick`) when `link`, +/// after a first choice linked elsewhere, which needs a namespace no reader knows, so a reader +/// takes the chart's choice. +fn chartex_docx_linked(requires: &str, requires_ns: &str, link: bool) -> Vec { + let click = if link { r#""# } else { "" }; + let other = if link { + r#""# + } else { + "" + }; + let frame = format!( + r#"{click}"# + ); let body = format!( - r#"Spread{frame}{frame}"# + r#"Spread{other}{frame}{frame}"# ); let doc = format!(r#"{body}"#); - let doc_rels = r#""#; + let doc_rels = r#""#; let chart_rels = r#""#; let types = format!( r#""# @@ -1827,6 +1842,25 @@ fn office_2016_chart_keeps_its_chart_part_and_fallback_through_saves() { } } +/// #5267: a link on an Office 2016 chart's drawing is the chart's link (not an earlier choice's), +/// and saving keeps it on both branches (the writer rebuilds their frames). +#[test] +fn a_link_on_an_office_2016_charts_drawing_is_kept() { + let mut d = wordcraft_docx::read(&chartex_docx_linked("cx1", "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex", true)).unwrap(); + for _ in 0..2 { + let p = d.body[0].as_para().unwrap(); + let off = p.object_offsets().into_iter().find(|o| matches!(p.object_at(*o), Some(InlineObject::Graphic { .. }))).unwrap(); + assert_eq!(p.props_of_char(off).link.as_deref(), Some("https://example.com/chart")); + let files = unzip(&wordcraft_docx::write(&d).unwrap()); + let body = text(&files, "word/document.xml"); + let ids = attr_values(&body, "a:hlinkClick", "r:id"); + assert_eq!(ids.len(), 2, "on the chart and its fallback picture: {body}"); + assert_eq!(rel(&text(&files, "word/_rels/document.xml.rels"), &ids[0]).1, "https://example.com/chart"); + let entries: Vec<_> = files.iter().map(|(name, bytes)| (name.as_str(), bytes.as_slice())).collect(); + d = wordcraft_docx::read(&zip(&entries)).unwrap(); + } +} + #[test] fn resized_office_2016_chart_resizes_its_fallback_too() { let mut d = wordcraft_docx::read(&chartex_docx("cx1", "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex")).unwrap(); @@ -2462,6 +2496,31 @@ fn east_asian_number_formats_read_label_and_round_trip() { assert_eq!(formats(&back), want); } +/// #4985: a level with numFmt none and literal text (`RESPONSE:`) labels its paragraph with that +/// text, as in Word, and keeps both through a save. +#[test] +fn a_none_level_s_literal_text_is_its_label() { + use wordcraft_doc::numbering::Counters; + use wordcraft_doc::section::NumFormat; + let numbering = format!( + r#""# + ); + let body = r#"X"#; + let bytes = docx(body, &[("rId1", "numbering", "numbering.xml")], &[("word/numbering.xml", &numbering)]); + let label = |d: &Document| { + let n = paras(d).first().and_then(|p| p.props.numbering)?; + Counters::default().next_label(&d.numbering, n.num, n.level).map(|l| l.0) + }; + let d = wordcraft_docx::read(&bytes).unwrap(); + assert_eq!(label(&d).as_deref(), Some("RESPONSE:")); + let back = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap(); + assert_eq!( + back.numbering.level(1, 0).map(|l| (l.format, l.text.as_str(), l.indent, l.hanging)), + Some((NumFormat::None, "RESPONSE:", 72.0, 72.0)) + ); + assert_eq!(label(&back).as_deref(), Some("RESPONSE:")); +} + /// #464: a bookmark whose end follows the document's final table keeps its end (it goes into /// the table's last cell) and is saved as a matched pair. #[test] diff --git a/crates/docx/tests/it/main.rs b/crates/docx/tests/it/main.rs index e54afbd5f5..8a1addee7d 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -23,6 +23,7 @@ mod ligatures; mod malformed; mod note_comments; mod passthrough; +mod picture_links; mod positional_tabs; mod privacy; mod roundtrip; @@ -34,6 +35,7 @@ mod section_page_number_type; mod section_text_direction; mod section_valign; mod settings_merge; +mod strict_drawings; mod text_alignment; mod text_boxes; mod toc_ranges; diff --git a/crates/docx/tests/it/picture_links.rs b/crates/docx/tests/it/picture_links.rs new file mode 100644 index 0000000000..e7b5e44c22 --- /dev/null +++ b/crates/docx/tests/it/picture_links.rs @@ -0,0 +1,127 @@ +//! A picture's hyperlink (#5267): Word keeps it on the drawing (`wp:docPr/a:hlinkClick`, +//! ECMA-376 Part 1 §20.4.2.5) rather than in a `w:hyperlink` around the run. Original +//! synthetic packages; the 2×2 picture is generated in code. +use std::io::{Read, Write}; +use std::sync::Arc; +use wordcraft_doc::{CharProps, Document, InlineObject, Pos}; + +fn png() -> Vec { + let mut out = Vec::new(); + image::RgbaImage::from_pixel(2, 2, image::Rgba([20, 90, 200, 255])) + .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) + .unwrap(); + out +} + +/// An inline picture's run; `link` goes into its `wp:docPr`. +fn picture_run(id: u32, link: &str) -> String { + format!( + r#"{link}"# + ) +} + +fn package(body: &str) -> Vec { + let xml = format!( + r#"{body}"# + ); + let rels = r#""#; + let doc_rels = r#""#; + let types = r#""#; + let png = png(); + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in [ + ("[Content_Types].xml", types.as_bytes()), + ("_rels/.rels", rels.as_bytes()), + ("word/document.xml", xml.as_bytes()), + ("word/_rels/document.xml.rels", doc_rels.as_bytes()), + ("word/media/square.png", png.as_slice()), + ] { + zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(bytes).unwrap(); + } + zip.finish().unwrap().into_inner() +} + +/// The link on each picture of the first paragraph, in order. +fn picture_links(doc: &Document) -> Vec> { + let p = doc.body[0].as_para().unwrap(); + p.object_offsets() + .into_iter() + .filter(|off| matches!(p.object_at(*off), Some(InlineObject::Image { .. }))) + .map(|off| p.props_of_char(off).link.clone()) + .collect() +} + +fn part(bytes: &[u8], name: &str) -> String { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut s = String::new(); + z.by_name(name).unwrap().read_to_string(&mut s).unwrap(); + s +} + +#[test] +fn a_link_on_a_pictures_drawing_is_read() { + let body = format!( + "{}{}{}{}", + // Word's way: the link on the drawing. + picture_run(1, r#""#), + // A click naming a relationship that is no hyperlink, and one naming none. + picture_run(2, r#""#), + picture_run(3, r#""#), + // A link around the run wins over the drawing's. + picture_run(4, r#""#), + ); + let doc = wordcraft_docx::read(&package(&body)).unwrap(); + assert_eq!(picture_links(&doc), [Some("https://example.com/picture".to_string()), None, None, Some("https://example.com/run".to_string())]); +} + +#[test] +fn a_linked_picture_is_saved_with_its_link_on_the_drawing_too() { + let mut doc = Document::new(); + doc.media.insert("square.png".into(), Arc::new(png())); + let picture = || InlineObject::Image { + media: "square.png".into(), + w: 20.0, + h: 20.0, + alt: String::new(), + float: Default::default(), + crop: [0.0; 4], + ole: None, + fx: Default::default(), + }; + let linked = |l: &str| CharProps { link: Some(l.to_string()), ..Default::default() }; + // A place in this document stays a `w:hyperlink w:anchor` only: `a:hlinkClick` names a relationship. + doc.insert_object(&Pos::body(0, 0), picture(), &linked("#Spot")).unwrap(); + doc.insert_object(&Pos::body(0, 0), picture(), &linked("https://example.com/saved")).unwrap(); + let bytes = wordcraft_docx::write(&doc).unwrap(); + let xml = part(&bytes, "word/document.xml"); + let clicks: Vec<&str> = xml.match_indices("").unwrap(), "{xml}"); + let rels = part(&bytes, "word/_rels/document.xml.rels"); + assert!(rels.contains(&format!(r#"Id="{rid}""#)) && rels.contains(r#"Target="https://example.com/saved""#), "{rels}"); + // The run's own hyperlink names the same relationship, so the address is stored once. + assert_eq!(rels.matches("https://example.com/saved").count(), 1, "{rels}"); + let back = wordcraft_docx::read(&bytes).unwrap(); + assert_eq!(picture_links(&back), [Some("https://example.com/saved".to_string()), Some("#Spot".to_string())]); + // The drawing's link alone (as Word writes it) reads back the same. + let without_run_link = xml.replace(&format!(r#""#), "").replacen("", "", 1); + assert_ne!(without_run_link, xml); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap(); + let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for i in 0..z.len() { + let mut f = z.by_index(i).unwrap(); + let name = f.name().to_string(); + let mut data = Vec::new(); + f.read_to_end(&mut data).unwrap(); + if name == "word/document.xml" { + data = without_run_link.clone().into_bytes(); + } + out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + out.write_all(&data).unwrap(); + } + let edited = out.finish().unwrap().into_inner(); + assert_eq!(picture_links(&wordcraft_docx::read(&edited).unwrap())[0], Some("https://example.com/saved".to_string())); +} diff --git a/crates/docx/tests/it/strict_drawings.rs b/crates/docx/tests/it/strict_drawings.rs new file mode 100644 index 0000000000..70d78ae7bd --- /dev/null +++ b/crates/docx/tests/it/strict_drawings.rs @@ -0,0 +1,182 @@ +//! Shapes, text boxes, groups and canvases in a Strict document (#3548). ISO/IEC 29500 Strict +//! puts them in the one WordprocessingDrawing namespace, where Transitional documents use Word +//! 2010's `wps`, `wpg` and `wpc` namespaces. Fixtures are original and hand-written from +//! ECMA-376 Part 1, 5th edition (`dml-wordprocessingDrawing.xsd`, Strict and Transitional): each +//! drawing is written once and filled in with either set of namespaces. + +use std::io::{Read, Write}; + +use wordcraft_doc::{Document, InlineObject, PartKind}; + +const STRICT_NS: &str = r#"xmlns:w="http://purl.oclc.org/ooxml/wordprocessingml/main" xmlns:r="http://purl.oclc.org/ooxml/officeDocument/relationships" xmlns:wp="http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing" xmlns:a="http://purl.oclc.org/ooxml/drawingml/main" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" w:conformance="strict""#; +const TRANSITIONAL_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas""#; +const STRICT_RELS: &str = r#""#; +const TRANSITIONAL_RELS: &str = r#""#; + +/// How a fixture names its drawing elements: the shape, group and canvas prefixes, and the +/// text box content element. +struct Names { + ns: &'static str, + rels: &'static str, + shape: &'static str, + group: &'static str, + canvas: &'static str, + content: &'static str, +} + +/// Word's Strict output: everything in `wp:`, text box content in `wne:txbxContent`. +const STRICT_WORD: Names = Names { ns: STRICT_NS, rels: STRICT_RELS, shape: "wp", group: "wp", canvas: "wp", content: "wne:txbxContent" }; +/// The Strict schema's own names: the text box content in `wp:` too. +const STRICT_SCHEMA: Names = Names { ns: STRICT_NS, rels: STRICT_RELS, shape: "wp", group: "wp", canvas: "wp", content: "wp:txbxContent" }; +/// The same drawings in a Transitional document. +const TRANSITIONAL: Names = + Names { ns: TRANSITIONAL_NS, rels: TRANSITIONAL_RELS, shape: "wps", group: "wpg", canvas: "wpc", content: "w:txbxContent" }; + +fn zip(entries: &[(&str, &[u8])]) -> Vec { + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in entries { + zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap(); + zw.write_all(bytes).unwrap(); + } + zw.finish().unwrap().into_inner() +} + +fn document_xml(bytes: &[u8]) -> String { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut s = String::new(); + z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap(); + s +} + +fn solid(rgb: &str) -> String { + format!(r#""#) +} + +/// A `wsp` at (`x`, `y`) EMUs in its group, `cx` × `cy`. `text` gives it a text box. +fn shape(n: &Names, prst: &str, (x, y, cx, cy): (u32, u32, u32, u32), fill: &str, text: Option<&str>) -> String { + let s = n.shape; + let connector = prst.contains("Connector"); + let nv = if connector { + format!("<{s}:cNvCnPr/>") + } else if text.is_some() { + format!(r#"<{s}:cNvSpPr txBox="1"/>"#) + } else { + format!("<{s}:cNvSpPr/>") + }; + let fill = if connector { String::new() } else { solid(fill) }; + let line = + if connector { r#""# } else { "" }; + let txbx = match text { + Some(t) => { + let c = n.content; + format!(r#"<{s}:txbx><{c}>{t}"#) + } + None => String::new(), + }; + format!( + r#"<{s}:wsp><{s}:cNvPr id="{cx}" name="{prst}"/>{nv}<{s}:spPr>{fill}{line}{txbx}<{s}:bodyPr anchor="ctr"/>"# + ) +} + +/// Drawing `id`, anchored `x` EMUs from the page's left edge, 1 in × ½ in. +fn anchor(id: u32, x: u32, uri: &str, payload: &str) -> String { + format!( + r#"{x}914400{payload}"# + ) +} + +/// A rectangle, a text box, an arrow, a group holding a nested group, and a canvas holding a +/// shape and a group, each 1 in × ½ in. +fn package(n: &Names) -> Vec { + const WPS: &str = "http://schemas.microsoft.com/office/word/2010/wordprocessingShape"; + const WPG: &str = "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"; + const WPC: &str = "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas"; + let full = (0, 0, 914_400, 457_200); + let half = (0, 0, 457_200, 457_200); + let g = n.group; + let group_xfrm = |(x, y, cx, cy): (u32, u32, u32, u32)| { + format!( + r#"<{g}:cNvGrpSpPr/><{g}:grpSpPr>{}"#, + solid("F39C12") + ) + }; + let group = format!( + "<{g}:wgp>{}{}<{g}:grpSp>{}{}", + group_xfrm(full), + shape(n, "ellipse", half, "28B463", None), + group_xfrm((457_200, 0, 457_200, 457_200)), + shape(n, "triangle", half, "8E44AD", None), + ); + let c = n.canvas; + let canvas = format!( + r#"<{c}:wpc><{c}:bg>{}<{c}:whole>{}{}<{g}:wgp>{}{}"#, + solid("FDF2E9"), + solid("A04000"), + shape(n, "roundRect", (45_720, 45_720, 365_760, 365_760), "16A085", None), + group_xfrm((457_200, 45_720, 365_760, 365_760)), + shape(n, "diamond", (0, 0, 365_760, 365_760), "2E86C1", None), + ); + let drawings = [ + anchor(1, 914_400, WPS, &shape(n, "rect", full, "C0392B", None)), + anchor(2, 2_286_000, WPS, &shape(n, "rect", full, "EAF2F8", Some("Strict text box"))), + anchor(3, 3_657_600, WPS, &shape(n, "straightConnector1", full, "", None)), + anchor(4, 5_029_200, WPG, &group), + anchor(5, 6_400_800, WPC, &canvas), + ]; + let doc = format!( + r#"Shapes{}"#, + n.ns, + drawings.concat() + ); + zip(&[("_rels/.rels", n.rels.as_bytes()), ("word/document.xml", doc.as_bytes())]) +} + +fn objects(d: &Document) -> Vec { + d.body[0].as_para().unwrap().objects.clone() +} + +/// The text of each text box story, in reading order. +fn box_texts(d: &Document) -> Vec { + let mut ids = Vec::new(); + d.objects_in_reading_order(&mut |o| ids.extend(o.text_boxes())); + ids.iter() + .filter_map(|id| d.parts.get(id).filter(|p| p.kind == PartKind::TextBox)) + .map(|p| p.blocks.iter().filter_map(|b| b.as_para()).map(|p| p.text.clone()).collect::>().join("\n")) + .collect() +} + +#[test] +fn strict_shapes_read_like_their_transitional_twins() { + let transitional = wordcraft_docx::read(&package(&TRANSITIONAL)).unwrap(); + let want = objects(&transitional); + // The twin itself reads every drawing: a rectangle, a text box, an arrow, a group whose + // nested group is flattened into it, and a canvas with its background. + assert_eq!(want.len(), 5, "{want:#?}"); + assert!(matches!(&want[0], InlineObject::Shape { story: None, freeform: None, .. }), "{:?}", want[0]); + assert!(matches!(&want[1], InlineObject::Shape { story: Some(_), .. }), "{:?}", want[1]); + assert!(matches!(&want[3], InlineObject::Group { children, canvas: None, .. } if children.len() == 2), "{:?}", want[3]); + assert!( + matches!(&want[4], InlineObject::Group { children, canvas: Some(c), .. } if children.len() == 2 && c.fill.is_some() && c.stroke.is_some()), + "{:?}", + want[4] + ); + assert_eq!(box_texts(&transitional), ["Strict text box"]); + for (name, names) in [("Word's Strict names", &STRICT_WORD), ("the Strict schema's names", &STRICT_SCHEMA)] { + let strict = wordcraft_docx::read(&package(names)).unwrap(); + assert_eq!(objects(&strict), want, "{name}"); + assert_eq!(box_texts(&strict), ["Strict text box"], "{name}"); + } +} + +#[test] +fn strict_shapes_are_saved_and_reopened() { + let strict = wordcraft_docx::read(&package(&STRICT_WORD)).unwrap(); + let saved = wordcraft_docx::write(&strict).unwrap(); + let xml = document_xml(&saved); + for name in ["", "", "", "", "", " CmdResult { } let st = s.sel.focus.story; s.sel = Selection { anchor: s.doc.start_of(st), focus: s.doc.end_of(st) }; + s.pending = None; s.column = None; s.column_mode = false; sel_result(s) @@ -332,6 +333,7 @@ fn select_range(s: &mut Session, v: &Value) -> CmdResult { let a = v.get("anchor").and_then(parse_pos).ok_or_else(|| CmdError::Params("bad `anchor`".into()))?; let b = v.get("focus").and_then(parse_pos).ok_or_else(|| CmdError::Params("bad `focus`".into()))?; s.sel = Selection { anchor: s.doc.clamp(&a), focus: s.doc.clamp(&b) }; + s.pending = None; sel_result(s) } @@ -392,6 +394,7 @@ fn select_unit(s: &mut Session, unit: Unit) -> CmdResult { if s.doc.para_at(&f).is_some() { let (a, b) = unit_range(s, &f, unit); s.sel = Selection { anchor: a, focus: b }; + s.pending = None; } sel_result(s) } @@ -486,6 +489,9 @@ fn select_text(s: &mut Session, v: &Value) -> CmdResult { if count == n { s.sel = Selection { anchor: Pos { story, path: path.clone(), off: i }, focus: Pos { story, path: path.clone(), off: i + needle.len() } }; + // Formatting picked for the old caret doesn't carry over (as `select.word`): what + // replaces the selection takes its formatting. + s.pending = None; return sel_result(s); } } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 67284a2474..c9d523c5d6 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -253,27 +253,8 @@ fn open(s: &mut Session, v: &Value) -> CmdResult { ); } let password = p::str(v, "password"); - let (mut doc, encrypted) = if let Some(data) = p::str(v, "data") { - let bytes = super::insert::base64_decode(data).ok_or_else(|| CmdError::Params("bad base64".into()))?; - // An empty file (File Explorer's New › Microsoft Word Document makes one) opens as a new - // blank document that saves back to it (#1384). - if bytes.is_empty() { - (normal_document(s), false) - } else { - crate::io::open_bytes_in(path, &bytes, password, &s.region()).map_err(CmdError::Failed)? - } - } else if crate::io::is_empty_file(std::path::Path::new(path)) { - (normal_document(s), false) - } else { - crate::io::open_path_in(std::path::Path::new(path), password, &s.region()).map_err(CmdError::Failed)? - }; - // Plain text and Markdown carry no language: they are in the editing language. - let ext = std::path::Path::new(path).extension().and_then(std::ffi::OsStr::to_str).unwrap_or("").to_ascii_lowercase(); - if let Some(lang) = s.prefs.default_language.as_ref().or(s.editing_lang.as_ref()) - && matches!(ext.as_str(), "txt" | "text" | "md" | "markdown") - { - Arc::make_mut(&mut doc.styles).default_chr.lang = Some(lang.clone()); - } + // An empty file opens as a new blank document that saves back to it (#1384). + let (doc, encrypted) = read_document(s, path, v)?; match s.used_because() { None => s.set_document(doc), Some(why) => { @@ -294,6 +275,53 @@ fn open(s: &mut Session, v: &Value) -> CmdResult { ) } +/// The document the file at `path` holds (or its bytes, base64 in `data`, with `path` only +/// naming it), read with `password`, and whether it was encrypted: what `file.open` and +/// `file.newFromTemplate` read. An empty file (File Explorer's New › Microsoft Word Document makes +/// one) is a new blank document (#1384). Plain text and Markdown carry no language, so they are +/// in the editing language. +fn read_document(s: &Session, path: &str, v: &Value) -> Result<(Document, bool), CmdError> { + let password = p::str(v, "password"); + let (mut doc, encrypted) = if let Some(data) = p::str(v, "data") { + let bytes = super::insert::base64_decode(data).ok_or_else(|| CmdError::Params("bad base64".into()))?; + if bytes.is_empty() { + (normal_document(s), false) + } else { + crate::io::open_bytes_in(path, &bytes, password, &s.region()).map_err(CmdError::Failed)? + } + } else if crate::io::is_empty_file(std::path::Path::new(path)) { + (normal_document(s), false) + } else { + crate::io::open_path_in(std::path::Path::new(path), password, &s.region()).map_err(CmdError::Failed)? + }; + let ext = std::path::Path::new(path).extension().and_then(std::ffi::OsStr::to_str).unwrap_or("").to_ascii_lowercase(); + if let Some(lang) = s.prefs.default_language.as_ref().or(s.editing_lang.as_ref()) + && matches!(ext.as_str(), "txt" | "text" | "md" | "markdown") + { + Arc::make_mut(&mut doc.styles).default_chr.lang = Some(lang.clone()); + } + Ok((doc, encrypted)) +} + +/// File › New from a template (#2852): a new, untitled document with the template's content, +/// attached to the template as in Word, read as `file.open` reads a file (`data`, `password`). +/// It opens beside the open documents, as `file.new` does. With `replaceBlank` an untouched blank +/// document gives way to it, as to a file `file.open` opens: that is how a template the platform +/// hands the app starts (#3433). The template is only read; the new document has no file, so +/// saving it asks where to write, and a protected template's password doesn't come along. +pub(crate) fn new_from_template(s: &mut Session, v: &Value) -> CmdResult { + let path = p::req_str(v, "path")?; + let (mut doc, _) = read_document(s, path, v)?; + doc.settings.attached_template = Some(path.to_string()); + if p::bool(v, "replaceBlank") == Some(true) && s.used_because().is_none() { + s.set_document(doc); + } else { + s.add_document(doc); + } + s.dirty = true; + sel_result(s) +} + /// Close a document with no window to ask about it (agents, headless sessions). fn close_document(s: &mut Session, v: &Value) -> CmdResult { let id = match v.get("id").filter(|x| !x.is_null()) { diff --git a/crates/engine/src/cmd/find_pattern.rs b/crates/engine/src/cmd/find_pattern.rs index 6ceab28a00..104b3d3e91 100644 --- a/crates/engine/src/cmd/find_pattern.rs +++ b/crates/engine/src/cmd/find_pattern.rs @@ -198,7 +198,9 @@ fn special(query: &str, o: &Opts) -> (String, bool) { if (o.ignore_punct && is_punct(c)) || (o.ignore_space && is_space(c)) { continue; } - atoms.push(lit(c)); + // A keyboard apostrophe also finds text produced by smart quotes. Explicit character + // codes above, and literal/regex/wildcard searches, keep exact character matching. + atoms.push(if c == '\'' { "['‘’]".into() } else { lit(c) }); } let filler = match (o.ignore_punct, o.ignore_space) { (true, true) => r"[\p{P} \t\x{A0}]*", diff --git a/crates/engine/src/cmd/insert/links.rs b/crates/engine/src/cmd/insert/links.rs index b280d449bb..2a0535a651 100644 --- a/crates/engine/src/cmd/insert/links.rs +++ b/crates/engine/src/cmd/insert/links.rs @@ -63,6 +63,17 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult { let end = s.doc.insert_text(&at, &text, &props)?; s.sel = Selection::caret(end); s.pending = Some(CharProps::default()); + } else if let Some(text) = retyped_text(s, v) { + // Text to display changed: the selection is retyped with it, then linked (as in Word). + crate::cmd::paste_text(s, &text)?; + let end = s.sel.focus.clone(); + let start = Pos { off: end.off.saturating_sub(text.len()), ..end.clone() }; + s.doc.format_range(&start, &end, &|c| { + c.link = Some(url.clone()); + c.style = style.clone(); + })?; + s.sel = Selection::caret(end); + s.pending = Some(CharProps::default()); } else { let (a, b) = s.sel.ordered(); s.doc.format_range(&a, &b, &|c| { @@ -73,6 +84,33 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult { sel_result(s) } +/// The `text` to retype a selection with before linking it: only when it differs from the selected +/// text and both fit in one line of one paragraph without pictures or fields, outside any field's +/// result. Otherwise (as Word shows `<>`) the selection keeps its text. +fn retyped_text(s: &Session, v: &Value) -> Option { + use wordcraft_doc::para::{COLUMN_BREAK, LINE_BREAK, OBJ, PAGE_BREAK}; + /// What can't stand in one line of text: breaks, and pictures or fields. + const NOT_ONE_LINE: [char; 7] = [LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ]; + let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?; + if text.contains(NOT_ONE_LINE) { + return None; + } + let (a, b) = s.sel.ordered(); + if a.story != b.story || a.path != b.path { + return None; + } + let shown = s.doc.para(a.story, &a.path)?.text.get(a.off..b.off)?; + if shown.contains(NOT_ONE_LINE) || shown == text { + return None; + } + // A selection in a field's result (between its markers, which it doesn't hold) is retyped by + // the next update of the field, not here. + if s.doc.field_ranges(a.story).iter().any(|r| r.start < b && a <= r.end) { + return None; + } + Some(text.to_string()) +} + /// Whether `name` can name a bookmark: starts with a letter or underscore, contains only alphanumeric characters /// or underscores, and is at most 40 characters (#3491). Word allows leading underscores for hidden bookmarks (_Toc, _Ref). pub fn bookmark_name_ok(name: &str) -> bool { diff --git a/crates/engine/src/cmd/lists.rs b/crates/engine/src/cmd/lists.rs index 1338eeb5e1..987e9fd537 100644 --- a/crates/engine/src/cmd/lists.rs +++ b/crates/engine/src/cmd/lists.rs @@ -452,6 +452,36 @@ mod tests { assert_eq!(numbered(&mut b), want); } + /// #5757: a list numbered in Thai digits shows them on the page, with the level's text around + /// them (`๑.`, `(๒)`), and keeps its format through a save to .docx and back. + #[test] + fn a_thai_numbered_list_shows_thai_digits_and_survives_docx() { + let mut s = Session::new(Document::new()); + for (i, t) in ["หนึ่ง", "สอง", "สาม", "a", "b", "c", "d", "e", "f", "g", "h"].iter().enumerate() { + if i > 0 { + s.run("text.newParagraph", &json!({})).unwrap(); + } + s.run("text.insert", &json!({"text": t})).unwrap(); + } + s.run("select.all", &json!({})).unwrap(); + let levels = json!([{"format": "thaiNumbers", "text": "%1.", "start": 1}]); + s.run("list.define", &json!({"levels": levels})).unwrap(); + let page: Vec> = numbered(&mut s).into_iter().map(|x| x.0).collect(); + let want: Vec> = + ["๑.", "๒.", "๓.", "๔.", "๕.", "๖.", "๗.", "๘.", "๙.", "๑๐.", "๑๑."].iter().map(|l| Some(l.to_string())).collect(); + assert_eq!(page, want); + let back = wordcraft_docx::read(&wordcraft_docx::write(&s.doc).unwrap()).unwrap(); + let mut b = Session::new(back); + let again: Vec> = numbered(&mut b).into_iter().map(|x| x.0).collect(); + assert_eq!(again, want, "thaiNumbers survives .docx"); + // In parentheses too. + let mut s = Session::new(Document::new()); + s.run("text.insert", &json!({"text": "x"})).unwrap(); + s.run("select.all", &json!({})).unwrap(); + s.run("list.define", &json!({"levels": [{"format": "thaiNumbers", "text": "(%1)", "start": 2}]})).unwrap(); + assert_eq!(numbered(&mut s)[0].0.as_deref(), Some("(๒)")); + } + /// #1793: the other heading presets of Word's List Library, level by level. #[test] fn every_heading_preset_numbers_three_heading_levels() { @@ -459,7 +489,8 @@ mod tests { ("headings", [Some("1"), Some("1.1"), Some("1.1.1")]), ("article", [Some("Article I."), Some("Section 1.01"), Some("(a)")]), ("outlineHeadings", [Some("I."), Some("A."), Some("1.")]), - ("chapter", [Some("Chapter 1"), None, None]), + // The lower levels are "none" levels with no text: an empty label, as in Word (#4985). + ("chapter", [Some("Chapter 1"), Some(""), Some("")]), ] { let mut s = headings("Heading3"); s.run("list.multilevelPreset", &json!({"preset": preset})).unwrap(); diff --git a/crates/engine/src/cmd/objects/picture.rs b/crates/engine/src/cmd/objects/picture.rs index 3b514a21e5..a254e0a762 100644 --- a/crates/engine/src/cmd/objects/picture.rs +++ b/crates/engine/src/cmd/objects/picture.rs @@ -76,9 +76,11 @@ pub fn cropped_original_size(s: &Session, o: &InlineObject) -> Option<(f32, f32) pub(super) fn size(s: &mut Session, v: &Value) -> CmdResult { let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no object".into()))?; let lock = p::bool(v, "lockAspect").unwrap_or(true); - let (mut w, mut h) = obj_size(&o); + let (w0, h0) = obj_size(&o); + let (mut w, mut h) = (w0, h0); let scale = p::f32(v, "scale"); - if p::bool(v, "original").unwrap_or(false) { + let original = p::bool(v, "original").unwrap_or(false); + if original { let (ow, oh) = cropped_original_size(s, &o).ok_or_else(|| CmdError::Disabled("only a picture whose image can be read has an original size".into()))?; let k = scale.unwrap_or(100.0) / 100.0; @@ -113,7 +115,16 @@ pub(super) fn size(s: &mut Session, v: &Value) -> CmdResult { (None, None) => true, _ => lock, }; - let (w, h) = fit_size(w, h, keep); + // Sides set in proportion (from the original, or from a size whose sides both have a length) + // fit the limits together. Otherwise each side the call sets fits on its own, and a side it + // leaves as it was keeps its size, a straight line's 0 too. + let (w, h) = if keep && (original || (w0 > 0.0 && h0 > 0.0 && (w, h) != (w0, h0))) { + fit_size(w, h, true) + } else { + let (fw, fh) = fit_size(w, h, false); + let left = |new: f32, old: f32| !original && new == old; + (if left(w, w0) { w } else { fw }, if left(h, h0) { h } else { fh }) + }; // Any drawing: a group's members scale with its frame (its child space is kept); a chart or // SmartArt graphic lays itself out again at the new size. let theme = s.doc.settings.theme_colors.clone(); diff --git a/crates/engine/src/cmd/objects/specs.rs b/crates/engine/src/cmd/objects/specs.rs index 639b05dc68..dfc3cc76a7 100644 --- a/crates/engine/src/cmd/objects/specs.rs +++ b/crates/engine/src/cmd/objects/specs.rs @@ -13,7 +13,7 @@ pub fn specs() -> Vec { vec![ CommandSpec::new("picture.size", "Size", "Picture Format › Size", size) .params( - r#"{"width"?: pt, "height"?: pt, "lockAspect"?: bool, "scale"?: percent, "original"?: bool} (scale: of the current size, or with original of the picture's original size, its pixels at 96 ppi less what is cropped; original alone restores that size; one side alone keeps the proportions unless lockAspect is false; 1–4000 pt: when the proportions are kept, a side past 4000 pt shrinks the other with it)"#, + r#"{"width"?: pt, "height"?: pt, "lockAspect"?: bool, "scale"?: percent, "original"?: bool} (scale: of the current size, or with original of the picture's original size, its pixels at 96 ppi less what is cropped; original alone restores that size; one side alone keeps the proportions unless lockAspect is false; 1–4000 pt: when the proportions are kept (from the original, or with both sides having a length), a side past 4000 pt shrinks the other with it; a side the call leaves as it was keeps its size, a straight line's 0 too)"#, ) .when(has_sizable), CommandSpec::new("picture.crop", "Crop", "Picture Format › Size", crop) diff --git a/crates/engine/src/cmd/objects/tests.rs b/crates/engine/src/cmd/objects/tests.rs index cdb2bb9946..51d04872d1 100644 --- a/crates/engine/src/cmd/objects/tests.rs +++ b/crates/engine/src/cmd/objects/tests.rs @@ -1034,6 +1034,66 @@ fn picture_size_past_the_limit_keeps_the_proportions() { } } +/// A side the call leaves as it was keeps its size, even outside 1–4000 pt: a straight line's 0 +/// stays 0 when only its length is typed. Sides set in proportion (the original, or a size whose +/// sides both have a length) fit the limits together; any other side the call sets, on its own. +#[test] +fn picture_size_keeps_the_side_it_leaves() { + let mut s = Session::new(wordcraft_doc::Document::new()); + s.run("insert.shape", &json!({"kind": "straightConnector", "width": 100.0, "height": 0.0})).unwrap(); + let size = |s: &Session| obj_size(&selected(s).unwrap().1); + // A side a scale sets on its own: 0 has no length to scale. + let scaled = |x: f32, k: f32| if x == 0.0 { 0.0 } else { (x * k).clamp(1.0, 4000.0) }; + // Sizes with both sides follow each other: they fit 1–4000 pt by the one factor nearest 1, worked out by hand + // for the calls `width` locked, `height` locked, `scale` 50 and `scale` 200 with a width (in that order). + let states = [ + ((100.0, 0.0), None), + ((0.0, 100.0), None), + ((5000.0, 0.0), None), + ((0.0, 5000.0), None), + ((100.0, 0.5), Some([(200.0, 1.0), (4000.0, 20.0), (200.0, 1.0), (200.0, 1.0)])), + ((5000.0, 50.0), Some([(200.0, 2.0), (4000.0, 40.0), (2500.0, 25.0), (200.0, 2.0)])), + ((100.0, 50.0), Some([(200.0, 100.0), (400.0, 200.0), (50.0, 25.0), (200.0, 100.0)])), + ]; + for ((w0, h0), together) in states { + let follow = |i: usize, alone: (f32, f32)| together.map_or(alone, |t: [(f32, f32); 4]| t[i]); + let cases = [ + (json!({"width": 200.0, "lockAspect": false}), (200.0, h0)), + (json!({"height": 200.0, "lockAspect": false}), (w0, 200.0)), + (json!({"width": 200.0}), follow(0, (200.0, h0))), + (json!({"height": 200.0}), follow(1, (w0, 200.0))), + (json!({"scale": 50}), follow(2, (scaled(w0, 0.5), scaled(h0, 0.5)))), + (json!({"scale": 200, "width": 200.0}), follow(3, (200.0, scaled(h0, 2.0)))), + (json!({"scale": 100}), (w0, h0)), + (json!({}), (w0, h0)), + // The Size dialog: both sides sent, the height as it was. + (json!({"width": 200.0, "height": h0, "lockAspect": false}), (200.0, h0)), + (json!({"width": 200.0, "height": 300.0}), (200.0, 300.0)), + ]; + for (v, (ew, eh)) in cases { + with_obj(&mut s, |o| o.set_size(w0, h0)).unwrap(); + s.run("picture.size", &v).unwrap(); + let (w, h) = size(&s); + assert!((w - ew).abs() < 1e-3 && (h - eh).abs() < 1e-3, "{w0}×{h0} {v}: {w}×{h}, not {ew}×{eh}"); + } + } + // Both sides of a picture's original size fit together, whatever size it had, even when the + // height comes out as it was: 4050×1012.5 pt is 4000×1000, not 4000×1012.5. + let data = super::super::insert::base64_encode(&png(400, 100)); + s.run("insert.picture", &json!({"data": data})).unwrap(); + for (w0, h0) in [(3000.0, 1012.5), (4050.0, 0.0), (100.0, 100.0)] { + with_obj(&mut s, |o| o.set_size(w0, h0)).unwrap(); + s.run("picture.size", &json!({"original": true, "scale": 1350})).unwrap(); + let (w, h) = size(&s); + assert!((w - 4000.0).abs() < 0.01 && (h - 1000.0).abs() < 0.01, "{w0}×{h0}: {w}×{h}"); + } + // A height the original sets is set, though it is the one the picture had: 300×75 pt at + // 5400 % is 16200×4050, so with a width of 200 the height fits to 4000. + with_obj(&mut s, |o| o.set_size(100.0, 4050.0)).unwrap(); + s.run("picture.size", &json!({"original": true, "scale": 5400, "width": 200.0, "lockAspect": false})).unwrap(); + assert_eq!(size(&s), (200.0, 4000.0)); +} + /// A crop handle drop: `picture.crop` with the new size is one edit, one undo step. #[test] fn picture_crop_with_size_is_one_undo_step() { diff --git a/crates/engine/src/cmd/para.rs b/crates/engine/src/cmd/para.rs index 2941925c5f..a96e16562c 100644 --- a/crates/engine/src/cmd/para.rs +++ b/crates/engine/src/cmd/para.rs @@ -183,9 +183,17 @@ pub fn specs() -> Vec { .key(if cfg!(target_os = "macos") { "Ctrl+Shift+Right" } else { "Alt+Shift+Right" }), CommandSpec::new("para.shading", "Shading", "Home › Paragraph", |s, v| { let c = p::str(v, "color").and_then(Rgb::parse); + // Text selected within one paragraph is shaded itself, as in Word, so No Color takes + // off a shading a file gave the text (#4685); a caret or paragraphs shade paragraphs. + // `paragraph` (Borders and Shading › Apply to: Paragraph) shades the paragraphs anyway. + if p::bool(v, "paragraph") != Some(true) && shades_text(s) { + return super::format::apply(s, &|x| x.shading = c); + } fmt(s, &|p| p.shading = c) }) - .params(r#"{"color": "RRGGBB" | null}"#), + .params( + r#"{"color": "RRGGBB" | null, "paragraph"?: bool} (text selected inside one paragraph is shaded itself, as in Word; `paragraph: true` shades the paragraphs instead, as Borders and Shading › Apply to: Paragraph)"#, + ), CommandSpec::new("para.borders", "Borders", "Home › Paragraph", borders).params( r#"{"kind": "bottom|top|left|right|none|all|outside|inside|horizontalLine", "width"?: pt, "color"?: "RRGGBB", "style"?: "single|double|dotted|dashed|thick|triple|dotDash|wave", "sides"?: Sides} where Sides = {"top"|"left"|"bottom"|"right"|"between": {"style"?, "width"?: pt, "color"?: "RRGGBB"} | null}: exactly these sides (others off), instead of `kind`"#, ), @@ -264,3 +272,21 @@ pub fn specs() -> Vec { }), ] } + +/// Whether Shading applies to the selected text rather than to paragraphs: a selection inside one +/// paragraph, short of its mark. A selection reaching past the mark ends at the next paragraph's +/// start, so all of a paragraph's text is still text, except in the last paragraph of its story, +/// cell or box, where it stands for the paragraph with its mark. A selected picture, shape or text +/// box is its object character, not text (a field's object character is). +fn shades_text(s: &Session) -> bool { + let (a, b) = s.sel.ordered(); + if a == b || a.story != b.story || a.path != b.path { + return false; + } + let Some(p) = s.doc.para_at(&a) else { return false }; + if super::objects::object_selection(s).is_some() { + return false; + } + let last = s.doc.next_para(a.story, &a.path).is_none_or(|q| q.parent() != a.path.parent()); + !(last && a.off == 0 && b.off >= p.len()) +} diff --git a/crates/engine/src/cmd/references.rs b/crates/engine/src/cmd/references.rs index 0cfeda45a4..5fb6195e8e 100644 --- a/crates/engine/src/cmd/references.rs +++ b/crates/engine/src/cmd/references.rs @@ -103,8 +103,9 @@ pub fn specs() -> Vec { /// A field instruction split into its name, positional arguments and switches (ECMA-376 /// §17.16.1): `TOC \o "1-3" \h` → name `TOC`, switches `o` = `1-3` and `h`. Quoted text stays -/// whole (without the quotes; `\"` and `\\` inside it are a quote and a backslash). A switch -/// takes the word after it as its argument unless that word is another switch. +/// whole (without the quotes; a backslash inside it makes the next character literal, as in Word: +/// `\"` is a quote, `\\` a backslash, `\*` an asterisk). A switch takes the word after it as its +/// argument unless that word is another switch. #[derive(Clone, Debug, Default, PartialEq)] pub struct FieldCode { pub name: String, @@ -126,7 +127,7 @@ pub fn field_words(instr: &str) -> Vec<(String, bool)> { while let Some(c) = chars.next() { match c { '"' => break, - '\\' if matches!(chars.peek(), Some('"' | '\\')) => w.extend(chars.next()), + '\\' if chars.peek().is_some() => w.extend(chars.next()), c => w.push(c), } } diff --git a/crates/engine/src/cmd/references/tests.rs b/crates/engine/src/cmd/references/tests.rs index d28b0a0c8e..63b624f387 100644 --- a/crates/engine/src/cmd/references/tests.rs +++ b/crates/engine/src/cmd/references/tests.rs @@ -1,3 +1,4 @@ +use super::properties::{new_property_value, text_result}; use super::*; fn fields(s: &Session) -> Vec<(String, String)> { @@ -446,7 +447,7 @@ fn update_fields_apply_the_capitalization_switches() { "seventh", "Seventh", "BUDGET", - "new \\* Upper" + "new * Upper" ] ); } @@ -548,6 +549,85 @@ fn caption_for_an_object_in_a_cell_stays_in_the_cell() { assert_eq!(texts.get(1).map(String::as_str), Some("Figure 1"), "{texts:?}"); } +/// A fresh scratch directory for the file-name tests below. +#[cfg(not(target_arch = "wasm32"))] +fn filename_scratch_dir(tag: &str) -> std::path::PathBuf { + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("wordcraft-filename-field-{tag}-{}-{nanos}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// #3796: after Save As to a new name, Update Field with the caret in a header shows the new +/// name for FILENAME and the new full path for FILENAME \p. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn filename_fields_in_a_header_follow_save_as() { + let dir = filename_scratch_dir("save-as"); + let (mut s, hdr) = header_fields_session(wordcraft_doc::Document::from_text("body"), &["FILENAME", r"FILENAME \p"]); + let first = dir.join("report_v1.docx"); + let second = dir.join("report_v2.docx"); + s.run("file.save", &json!({"path": first.to_string_lossy()})).unwrap(); + s.run("references.updateFields", &json!({})).unwrap(); + let got = story_fields(&s, StoryRef::Part(hdr)); + assert_eq!(got[0].1, "report_v1.docx"); + assert_eq!(got[1].1, first.to_string_lossy()); + + s.run("file.saveAs", &json!({"path": second.to_string_lossy()})).unwrap(); + s.run("references.updateFields", &json!({})).unwrap(); + let got = story_fields(&s, StoryRef::Part(hdr)); + assert_eq!(got[0].1, "report_v2.docx"); + assert_eq!(got[1].1, second.to_string_lossy()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// #3796: a Word-style `FILENAME \* MERGEFORMAT` field whose cached text names the old file +/// shows the new name after Save As and Update Field. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn filename_mergeformat_field_replaces_its_cached_name_after_save_as() { + let dir = filename_scratch_dir("mergeformat"); + let (mut s, hdr) = header_fields_session(wordcraft_doc::Document::from_text("body"), &[r"FILENAME \* MERGEFORMAT"]); + let first = dir.join("report_v1.docx"); + s.run("file.save", &json!({"path": first.to_string_lossy()})).unwrap(); + // The cached text a file written earlier would carry. + let path = s.doc.para_paths(StoryRef::Part(hdr)).remove(0); + if let Some(InlineObject::Field { result, .. }) = s.doc.para_mut(StoryRef::Part(hdr), &path).unwrap().objects.first_mut() { + *result = "report_v1.docx".into(); + } + s.run("file.saveAs", &json!({"path": dir.join("report_v2.docx").to_string_lossy()})).unwrap(); + s.run("references.updateFields", &json!({})).unwrap(); + assert_eq!(story_fields(&s, StoryRef::Part(hdr))[0].1, "report_v2.docx"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// #3796: renaming the document (File > Info) changes what FILENAME shows on the next Update +/// Field; the extension stays. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn filename_field_in_a_header_follows_rename() { + let dir = filename_scratch_dir("rename"); + let (mut s, hdr) = header_fields_session(wordcraft_doc::Document::from_text("body"), &["FILENAME"]); + s.run("file.save", &json!({"path": dir.join("report_v1.docx").to_string_lossy()})).unwrap(); + s.run("file.rename", &json!({"name": "report_v3"})).unwrap(); + s.run("references.updateFields", &json!({})).unwrap(); + assert_eq!(story_fields(&s, StoryRef::Part(hdr))[0].1, "report_v3.docx"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A backslash in a quoted field argument makes the next character literal, so `\*` there is an +/// asterisk and not the `\* Upper` switch (Word shows `x * Upper` for `TITLE "x \* Upper"`). +#[test] +fn quoted_field_argument_backslash_escapes() { + for (instr, shown) in [(r#"TITLE "x \* Upper""#, "x * Upper"), (r#"TITLE "x \\* Upper""#, r"x \* Upper"), (r#"TITLE "a \"b\" c""#, r#"a "b" c"#)] + { + let value = new_property_value(instr).unwrap(); + assert_eq!(value, shown, "{instr}"); + assert_eq!(text_result(instr, value), shown, "{instr}"); + } + assert_eq!(text_result(r#"TITLE "ab" \* Upper"#, new_property_value(r#"TITLE "ab" \* Upper"#).unwrap()), "AB"); +} + /// Output (PDF, print, page images) shows the body's unlocked SEQ, STYLEREF and REF fields with /// their fresh results, as Word fills them in when it prints or exports even with "Update fields /// before printing" off; NUMWORDS and a locked field keep their stored results there, and the diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs index 6734e050c4..925e1f6cab 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -195,7 +195,7 @@ pub fn specs() -> Vec { }) .params(r#"{"text"?: string, "title"?: string} (empty clears)"#)), t(CommandSpec::new("table.sort", "Sort", "Table Layout › Data", sort_table) - .params(r#"{"column"?: n, "descending"?: bool, "header"?: bool}"#)), + .params(r#"{"column"?: non-negative JSON integer (0-based, default 0; must name a column in the table), "descending"?: bool, "header"?: bool}"#)), t(CommandSpec::new("table.toText", "Convert to Text", "Table Layout › Data", to_text) .params(r#"{"separator"?: "tab|comma|paragraph|other", "char"?: string (with other)} (the selected rows, or the whole table)"#)), t(CommandSpec::new("table.formula", "Formula", "Table Layout › Data", formula).params(r#"{"formula"?: "=SUM(ABOVE)"}"#)), diff --git a/crates/engine/src/cmd/table/convert.rs b/crates/engine/src/cmd/table/convert.rs index f8cb418863..e92ce29d9e 100644 --- a/crates/engine/src/cmd/table/convert.rs +++ b/crates/engine/src/cmd/table/convert.rs @@ -8,11 +8,18 @@ use super::{ /// Sort the table's rows by a column. Numbers are read in each cell's language (`1,5` is one and /// a half in Polish) and sort first, numerically; other text sorts in the column's language. pub(super) fn sort_table(s: &mut Session, v: &Value) -> CmdResult { - let col = p::u64(v, "column").unwrap_or(0) as usize; + let column = match v.get("column") { + None => 0, + Some(value) => value.as_u64().ok_or_else(|| CmdError::Params("`column` must be a non-negative JSON integer".into()))?, + }; let desc = p::bool(v, "descending").unwrap_or(false); let header = p::bool(v, "header"); let (tp, _, _) = cell(s)?; let t = s.doc.table(s.sel.focus.story, &tp).ok_or_else(|| CmdError::Failed("no table".into()))?; + let col = usize::try_from(column) + .ok() + .filter(|&col| t.rows.iter().any(|row| col < row.cells.len())) + .ok_or_else(|| CmdError::Params("`column` is outside the table".into()))?; let skip = usize::from(header.unwrap_or(t.rows.first().is_some_and(|r| r.props.header))).min(t.rows.len()); let column = || t.rows.iter().skip(skip).map(|r| r.cells.get(col)); let lang = column().flatten().find_map(|c| cell_lang(&s.doc, c)).or_else(|| crate::cmd::default_lang(s)); diff --git a/crates/engine/src/cmd/tools/specs.rs b/crates/engine/src/cmd/tools/specs.rs index 636faf15b2..f9a9684d5f 100644 --- a/crates/engine/src/cmd/tools/specs.rs +++ b/crates/engine/src/cmd/tools/specs.rs @@ -121,17 +121,11 @@ pub fn specs() -> Vec { CommandSpec::new("file.recover", "Recover Unsaved Documents", "File › Info", |s, v| s.recover(v)) .params(r#"{"restore"?: recoveryId, "discard"?: recoveryId, "refresh"?: true}; desktop only; returns {enabled,busy,documents,error}; restore loads asynchronously without a file path"#) .pure(), - CommandSpec::new("file.newFromTemplate", "New from Template", "File › New", |s, v| { - let path = p::req_str(v, "path")?; - let mut doc = crate::io::open_path(std::path::Path::new(path)).map_err(CmdError::Failed)?; - // As in Word, the new document is attached to the template it came from (#2852). - doc.settings.attached_template = Some(path.to_string()); - s.add_document(doc); - s.dirty = true; - sel_result(s) - }) - .params(r#"{"path": string} → a new, untitled document from the template, attached to it"#) - .pure(), + CommandSpec::new("file.newFromTemplate", "New from Template", "File › New", crate::cmd::file::new_from_template) + .params( + r#"{"path": string, "data"?: base64 (the template's bytes; `path` then only names it), "password"?: string (for a password-protected template), "replaceBlank"?: bool (an untouched blank document gives way to it, as to a file file.open opens)} → a new, untitled document from the template, attached to it"#, + ) + .pure(), CommandSpec::new("file.saveTemplate", "Save as Template", "File › Save As", |s, v| { let path = p::req_str(v, "path")?; // A .dotm keeps its name (#2852); anything else becomes a .dotx. diff --git a/crates/engine/src/cmd/user_templates.rs b/crates/engine/src/cmd/user_templates.rs index 9180a8fe34..ff7b5bca87 100644 --- a/crates/engine/src/cmd/user_templates.rs +++ b/crates/engine/src/cmd/user_templates.rs @@ -337,6 +337,73 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// #3433: a template the platform hands the app takes an untouched blank document's place + /// (`replaceBlank`), as a file `file.open` opens does; otherwise, and without the flag, the + /// new document opens beside the others, as File › New's does. Either way the template on + /// disk is only read: the new document has no path, so a save can't write over it. + #[test] + fn new_from_template_replaces_an_untouched_blank_document_only_when_asked() { + let d = scratch("replace-blank"); + let path = d.join("Letterhead.dotx"); + template(&path, "Letterhead text", ""); + let bytes = std::fs::read(&path).unwrap(); + let from = json!({"path": path.to_string_lossy(), "replaceBlank": true}); + + let mut s = Session::new(wordcraft_doc::Document::new()); + s.run("file.newFromTemplate", &from).unwrap(); + assert_eq!(s.documents().len(), 1, "the untouched blank document gave way"); + assert_eq!(s.path, None); + assert!(s.dirty); + assert_eq!(s.doc.settings.attached_template.as_deref(), Some(path.to_string_lossy().as_ref())); + assert!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).contains("Letterhead text")); + let saved = s.run("file.save", &json!({})).unwrap(); + assert_eq!(saved["saved"], json!(false), "no file to save to: Save As asks where"); + assert_eq!(std::fs::read(&path).unwrap(), bytes, "the template is never written over"); + + // The new document has unsaved changes, so a second one opens beside it. + s.run("file.newFromTemplate", &from).unwrap(); + assert_eq!(s.documents().len(), 2); + // Without the flag, even an untouched blank document stays (File › New). + let mut s = Session::new(wordcraft_doc::Document::new()); + s.run("file.newFromTemplate", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(s.documents().len(), 2); + assert_eq!(std::fs::read(&path).unwrap(), bytes); + let _ = std::fs::remove_dir_all(&d); + } + + /// #3433: a protected template asks for its password like `file.open`, and the document made + /// from it isn't protected; a template's bytes can come in `data` (a file name that isn't + /// valid Unicode, #1440), its path then only naming it. + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn new_from_template_reads_a_protected_template_and_bytes_like_file_open() { + let d = scratch("protected"); + let path = d.join("Locked.dotx"); + let mut t = Session::new(wordcraft_doc::Document::from_text("Locked template")); + t.run("file.save", &json!({"path": path.to_string_lossy(), "password": "sesame"})).unwrap(); + let name = path.to_string_lossy(); + + let mut s = Session::new(wordcraft_doc::Document::new()); + let e = s.run("file.newFromTemplate", &json!({"path": name})).unwrap_err().to_string(); + assert!(crate::io::needs_password(&e), "{e}"); + let e = s.run("file.newFromTemplate", &json!({"path": name, "password": "wrong"})).unwrap_err().to_string(); + assert!(crate::io::wrong_password(&e), "{e}"); + assert_eq!(s.documents().len(), 1, "nothing opened yet"); + s.run("file.newFromTemplate", &json!({"path": name, "password": "sesame", "replaceBlank": true})).unwrap(); + assert!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).contains("Locked template")); + assert_eq!((s.path.as_ref(), s.password.is_some()), (None, false)); + + let plain = d.join("Plain.dotx"); + template(&plain, "From bytes", ""); + let data = crate::cmd::insert::base64_encode(&std::fs::read(&plain).unwrap()); + let mut s = Session::new(wordcraft_doc::Document::new()); + s.run("file.newFromTemplate", &json!({"path": "Pl\u{FFFD}in.dotx", "data": data, "replaceBlank": true})).unwrap(); + assert!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).contains("From bytes")); + assert_eq!(s.doc.settings.attached_template.as_deref(), Some("Pl\u{FFFD}in.dotx")); + assert_eq!(s.path, None); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn the_templates_folder_option_is_saved_and_checked() { let d = scratch("option"); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e13cf934b7..10591fa908 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12,6 +12,7 @@ use crate::{Session, cmd}; mod bidi; mod documents; +mod find_apostrophes; mod font_sizes; mod fonts; mod ime_noop; @@ -4681,10 +4682,8 @@ fn typed_paragraphs_are_capped_for_every_caller() { assert!(!body_texts(&s).iter().any(|p| p.contains('y'))); } -#[test] -fn hostile_params_never_panic() { - let reg = cmd::registry(); - let junk = [ +fn hostile_junk() -> [serde_json::Value; 8] { + [ json!(null), json!({}), json!({"text": 5, "size": "x", "path": [], "pos": {"block": 9999, "off": 99999}}), @@ -4693,11 +4692,23 @@ fn hostile_params_never_panic() { json!({"page": 0, "x": 1e30, "y": -1e30, "extend": 1}), json!({"width": 1e-9, "height": 1e30, "top": -1e9, "left": 1e9}), json!({"section": {"pageW": -1e308, "pageH": 0, "marginTop": 1e30, "header": -5, "columns": {"count": 1000000, "space": -1e300, "widths": [[0, 0]]}}}), - ]; + ] +} + +/// `file.*`, `insert.picture` and `insert.textFromFile`: `hostile_file_params_never_panic` runs +/// them, held to a folder of its own, and `hostile_params_never_panic` every other command. +fn reaches_files(id: &str) -> bool { + id.starts_with("file.") || id == "insert.picture" || id == "insert.textFromFile" +} + +#[test] +fn hostile_params_never_panic() { + let reg = cmd::registry(); + let junk = hostile_junk(); for spec in reg.all() { - // These reach outside the session (files). Read Aloud (`review.readAloud`, `readAloud.*`) - // is fuzzed too: under `cfg(test)` its backend is the silent `Hold`, asserted below. - if spec.id.starts_with("file.") || spec.id == "insert.picture" || spec.id == "insert.textFromFile" { + // Read Aloud (`review.readAloud`, `readAloud.*`) is fuzzed too: under `cfg(test)` its + // backend is the silent `Hold`, asserted below. + if reaches_files(spec.id) { continue; } for j in &junk { @@ -4711,6 +4722,127 @@ fn hostile_params_never_panic() { } } +/// `file.*`, `insert.picture` and `insert.textFromFile` take junk params and paths to files they +/// can't use (#3719). They may read only `in` and write only `out`, so a save can't replace a file +/// another run is meant to find broken, and nothing outside those folders is touched. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn hostile_file_params_never_panic() { + /// What is directly in `dir`: each name with its bytes (`None` for a folder). + fn contents(dir: &std::path::Path) -> std::collections::BTreeMap>> { + let entries = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().path()); + entries.map(|p| (p.file_name().unwrap().to_string_lossy().into_owned(), std::fs::read(&p).ok())).collect() + } + /// The names whose bytes differ, so a failure lists them instead of printing every file. + fn changed(before: &std::collections::BTreeMap>>, dir: &std::path::Path) -> Vec { + let after = contents(dir); + let names: std::collections::BTreeSet<_> = before.keys().chain(after.keys()).collect(); + names.into_iter().filter(|n| before.get(*n) != after.get(*n)).cloned().collect() + } + let reg = cmd::registry(); + let base = scratch_dir("hostile-files"); + let (input, output, outside) = (base.join("in"), base.join("out"), base.join("outside")); + for dir in [&outside, &input.join("folder.docx"), &output.join("folder.docx")] { + std::fs::create_dir_all(dir).unwrap(); + } + let at = |dir: &std::path::Path, name: &str| dir.join(name).to_string_lossy().into_owned(); + + // Fixed bytes, so a failure comes back on the next run. + let noise: Vec = (0..512u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as u8).collect(); + let picture_exts = ["png", "jpg", "gif", "bmp", "svg", "emf"]; + let mut paths = vec![]; + for ext in crate::io::OPEN_EXTS.iter().chain(&picture_exts) { + let name = format!("random.{ext}"); + std::fs::write(input.join(&name), &noise).unwrap(); + paths.push(at(&input, &name)); + } + paths.extend(crate::io::SAVE_EXTS.iter().map(|ext| at(&output, &format!("new.{ext}")))); + std::fs::write(input.join("empty"), b"").unwrap(); + std::fs::write(input.join("empty.docx"), b"").unwrap(); + std::fs::write(input.join("good.txt"), "Good text").unwrap(); + std::fs::write(input.join("good.png"), tiny_png()).unwrap(); + paths.extend(["empty", "empty.docx", "folder.docx", "missing", "missing.docx"].map(|name| at(&input, name))); + paths.extend(["folder.docx", "missing/new.docx", &format!("{}.docx", "x".repeat(5000))].map(|name| at(&output, name))); + // Outside the roots, however it is spelled, and not paths at all. + paths.extend(["new.docx", "new"].map(|name| at(&outside, name))); + paths.push(format!("{}/../outside/new.docx", input.to_string_lossy())); + paths.extend(["hostile-relative.docx", "hostile-relative", "", "\0", "a\0b.docx"].map(String::from)); + + // Every path alone; each of these also with every other kind of junk param. The numbers that + // cost time (`copies`, `scale`) stay small: huge ones are #3720. + let mut params: Vec = hostile_junk().into(); + params.extend(paths.iter().map(|p| json!({"path": p}))); + for name in [ + "in/random.docx", + "in/empty.docx", + "in/folder.docx", + "in/missing.docx", + "in/good.txt", + "in/good.png", + "out/new.docx", + "out/new.pdf", + "out/new.png", + ] { + let path = at(&base, name); + params.extend([ + json!({"path": path, "password": "x", "format": "wordml2003", "markup": "x", "confirmDamaged": 1}), + json!({"path": path, "password": 5, "format": 5, "markup": true}), + json!({"path": path, "page": 0, "scale": 0, "width": -1e308, "alt": 5}), + json!({"path": path, "data": "not base64!"}), + json!({"path": path, "data": "AAAA"}), + json!({"path": path, "pagesPerSheet": 7, "range": "x", "pages": "9-1,,", "parity": "x", "copies": 3, "paper": "x"}), + json!({"dir": path, "name": path, "template": path, "userTemplatesFolder": path, "id": 1e30, "restore": 1e30, "save": path}), + ]); + } + + let before = contents(&input); + let working_dir = std::path::Path::new("."); + let working_dir_before = contents(working_dir); + let roots = crate::file_access::AutomationRoots::new(Some(&input), Some(&output)).unwrap(); + let confined = |s: &mut Session, id: &str, v: &serde_json::Value| crate::file_access::confine(roots.as_ref(), || s.run(id, v)); + for spec in reg.all() { + if !reaches_files(spec.id) { + continue; + } + for v in ¶ms { + let mut s = Session::new(crate::sample::sample_document()); + let r = confined(&mut s, spec.id, v); + assert!(!caught_panic(®, &r), "{} panicked on {v}: {r:?}", spec.id); + s.clamp_selection(); + let _ = s.layout(); + } + } + + let nothing = Vec::::new(); + assert_eq!(changed(&before, &input), nothing, "the read root is only read"); + assert_eq!(changed(&Default::default(), &outside), nothing, "nothing outside the write root"); + // Every name counts: an empty path comes out as `.pdf` or `.dotx` here. + assert_eq!(changed(&working_dir_before, working_dir), nothing, "nothing in the working directory"); + + // The junk above met the files, not a closed door: usable files work through the same roots... + let mut s = s(); + confined(&mut s, "file.open", &json!({"path": at(&input, "good.txt")})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "Good text"); + confined(&mut s, "insert.textFromFile", &json!({"path": at(&input, "good.txt")})).unwrap(); + confined(&mut s, "insert.picture", &json!({"path": at(&input, "good.png")})).unwrap(); + let saved: [(&str, &str, &[u8]); 3] = + [("file.saveAs", "control.docx", b"PK\x03\x04"), ("file.exportPdf", "control.pdf", b"%PDF-"), ("file.exportPng", "control.png", b"\x89PNG")]; + for (id, name, signature) in saved { + confined(&mut s, id, &json!({"path": at(&output, name)})).unwrap(); + assert_eq!(std::fs::read(output.join(name)).unwrap().get(..signature.len()), Some(signature), "{name}"); + } + // ...the noise is refused by the reader, and only a path outside by the roots. + let refused = |s: &mut Session, path: String| match confined(s, "file.open", &json!({"path": path})) { + Err(crate::CmdError::Failed(m)) => m, + r => panic!("not refused: {r:?}"), + }; + let unreadable = refused(&mut s, at(&input, "random.docx")); + assert!(!unreadable.contains("automation path rejected"), "{unreadable}"); + let rejected = refused(&mut s, at(&outside, "new.docx")); + assert!(rejected.contains("automation path rejected"), "{rejected}"); + let _ = std::fs::remove_dir_all(&base); +} + /// A panic that `Session::run`'s guard turned into an error, in a command or one it ran: still a /// crash path (#3718). Only the guard's own `"{id} panicked: "` counts, not an error that echoes /// those words. @@ -7812,6 +7944,97 @@ fn colour_commands_take_any_custom_hex() { assert_eq!(s.doc.settings.page_color, wordcraft_doc::Rgb::parse("123ABC")); } +/// #4685: Home › Paragraph › Shading on text selected inside a paragraph shades that text, as in +/// Word, so No Color takes off a text shading a file gave it (an orange "highlight" from a .docx is +/// `w:shd`, which Text Highlight Color › No Color leaves, in Word too). A caret or a whole +/// paragraph still shades the paragraph. +#[test] +fn shading_selected_text_shades_the_text_and_no_color_clears_it() { + let orange = wordcraft_doc::Rgb::parse("FFA500"); + let mut s = s(); + run(&mut s, "text.insert", json!({"text": "Orange text here"})); + run(&mut s, "select.text", json!({"text": "Orange"})); + run(&mut s, "para.shading", json!({"color": "FFA500"})); + let p = s.doc.para_at(&s.sel.focus).unwrap(); + assert_eq!((p.props.shading, p.props_of_char(0).shading, p.props_of_char(7).shading), (None, orange, None)); + // Highlight › No Color doesn't take it off; Shading › No Color does. + run(&mut s, "format.highlight", json!({"color": "none"})); + assert_eq!(s.doc.para_at(&s.sel.focus).unwrap().props_of_char(0).shading, orange); + run(&mut s, "para.shading", json!({"color": null})); + assert_eq!(s.doc.para_at(&s.sel.focus).unwrap().props_of_char(0).shading, None); + // A caret, or the whole paragraph, shades the paragraph and leaves the text alone. + for whole in [false, true] { + let mut s = self::s(); + run(&mut s, "text.insert", json!({"text": "Orange text here"})); + run(&mut s, if whole { "select.all" } else { "caret.left" }, json!({})); + run(&mut s, "para.shading", json!({"color": "FFA500"})); + let p = s.doc.para_at(&s.sel.focus).unwrap(); + assert_eq!((p.props.shading, p.props_of_char(0).shading), (orange, None), "whole: {whole}"); + } + // All the text of a paragraph that isn't the last is still text: a selection with its mark + // would end at the next paragraph's start. + let mut s = self::s(); + run( + &mut s, + "document.setText", + json!({"text": "Word +More"}), + ); + run(&mut s, "select.text", json!({"text": "Word"})); + run(&mut s, "para.shading", json!({"color": "FFA500"})); + let p = s.doc.para_at(&s.sel.focus).unwrap(); + assert_eq!((p.props.shading, p.props_of_char(0).shading), (None, orange)); + // A selected text box shades its anchor's paragraph, not every line of the box. + let mut s = self::s(); + run(&mut s, "text.insert", json!({"text": "Anchor"})); + run(&mut s, "insert.textBox", json!({"text": "Inside"})); + let id = s.doc.parts.iter().find(|(_, p)| p.kind == wordcraft_doc::PartKind::TextBox).map(|(id, _)| *id).unwrap(); + let end = s.doc.text_box_anchor(id).unwrap(); + let start = wordcraft_doc::Pos { off: end.off - wordcraft_doc::para::OBJ.len_utf8(), ..end.clone() }; + run(&mut s, "select.range", json!({"anchor": start, "focus": end})); + run(&mut s, "para.shading", json!({"color": "FFA500"})); + let boxed = s.doc.parts.get(&id).and_then(|p| p.blocks.first()).and_then(|b| b.as_para()).unwrap(); + assert_eq!(boxed.props_of_char(0).shading, None, "the box's text isn't shaded"); + assert_eq!(s.doc.para_at(&end).unwrap().props.shading, orange); + // A selected field is text (its object character isn't a drawing): No Color clears its shading. + let mut s = self::s(); + run(&mut s, "text.insert", json!({"text": "Page "})); + run(&mut s, "insert.pageNumber", json!({"position": "current"})); + let end = s.sel.focus.clone(); + let start = wordcraft_doc::Pos { off: end.off - wordcraft_doc::para::OBJ.len_utf8(), ..end.clone() }; + run(&mut s, "select.range", json!({"anchor": start, "focus": end})); + run(&mut s, "para.shading", json!({"color": "FFA500"})); + let p = s.doc.para_at(&end).unwrap(); + assert_eq!((p.props.shading, p.props_of_char(start.off).shading), (None, orange), "the field is shaded"); + run(&mut s, "para.shading", json!({"color": null})); + assert_eq!(s.doc.para_at(&end).unwrap().props_of_char(start.off).shading, None); + // Borders and Shading › Apply to: Paragraph shades the paragraph, whatever is selected. + run(&mut s, "select.text", json!({"text": "Page"})); + run(&mut s, "para.shading", json!({"color": "FFA500", "paragraph": true})); + let p = s.doc.para_at(&s.sel.focus).unwrap(); + assert_eq!((p.props.shading, p.props_of_char(0).shading), (orange, None)); +} + +/// #4685 review: in a cell's last paragraph all of its text stands for the paragraph with its +/// mark (a selection can't reach the next paragraph's start there), so Shading shades the +/// paragraph; part of the text is text. +#[test] +fn shading_all_of_a_cells_last_paragraph_shades_the_paragraph() { + let orange = wordcraft_doc::Rgb::parse("FFA500"); + for (from, to, paragraph) in [(0, 9, true), (0, 4, false)] { + let mut s = s(); + run(&mut s, "insert.table", json!({"rows": 1, "cols": 1})); + run(&mut s, "text.insert", json!({"text": "Cell text"})); + let cell = s.sel.focus.clone(); + assert!(cell.path.cell().is_some()); + run(&mut s, "select.range", json!({"anchor": Pos { off: from, ..cell.clone() }, "focus": Pos { off: to, ..cell.clone() }})); + run(&mut s, "para.shading", json!({"color": "FFA500"})); + let p = s.doc.para_at(&cell).unwrap(); + let want = if paragraph { (orange, None) } else { (None, orange) }; + assert_eq!((p.props.shading, p.props_of_char(0).shading), want, "{from}..{to}"); + } +} + /// #2738: Home › Underline › Underline Color sets the underline's own colour and leaves its style /// alone; `auto` drops it again. One undo step each, kept through a DOCX round trip, and junk is /// a params error that changes nothing. @@ -10167,6 +10390,73 @@ fn column_texts(s: &Session) -> Vec { t.rows.iter().map(|r| r.cells[0].blocks.iter().filter_map(|b| b.as_para()).map(|p| p.plain_text()).collect::()).collect() } +#[test] +fn table_sort_rejects_invalid_columns_without_changing_rows_or_history() { + for column in [ + json!(-1), + json!(0.5), + json!(0.0), + json!("0"), + json!(null), + json!(true), + json!([]), + json!({}), + json!(1), + json!(u32::MAX as u64 + 1), + json!(u64::MAX), + ] { + let mut s = column_table("en-US", &["Charlie", "Alpha", "Bravo"]); + s.close_typing(); + run(&mut s, "text.insert", json!({"text": "!"})); + let before = s.doc.clone(); + let selection = s.sel.clone(); + let dirty = s.dirty; + assert!(s.run("table.sort", &json!({"column": column, "header": false})).is_err(), "column {column}"); + assert_eq!(s.doc, before, "column {column}"); + assert_eq!(s.sel, selection, "column {column}"); + assert_eq!(s.dirty, dirty, "column {column}"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(column_texts(&s), ["Charlie", "Alpha", "Bravo"], "column {column}: refusal must not consume Undo"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc, before, "column {column}: Redo must restore the preceding edit"); + } +} + +#[test] +fn table_sort_keeps_default_and_valid_columns() { + let mut s = s(); + run(&mut s, "insert.table", json!({"rows": 3, "cols": 2})); + for (k, value) in ["Charlie", "1", "Alpha", "3", "Bravo", "2"].into_iter().enumerate() { + if k > 0 { + run(&mut s, "text.tab", json!({})); + } + run(&mut s, "text.insert", json!({"text": value})); + } + let original = s.doc.clone(); + for params in [json!({"header": false}), json!({"column": 0, "header": false})] { + run(&mut s, "table.sort", params); + assert_eq!(column_texts(&s), ["Alpha", "Bravo", "Charlie"]); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, original); + } + run(&mut s, "table.sort", json!({"column": 1, "header": false})); + assert_eq!(column_texts(&s), ["Charlie", "Bravo", "Alpha"]); + run(&mut s, "table.sort", json!({"column": 1, "header": false, "descending": true})); + assert_eq!(column_texts(&s), ["Alpha", "Bravo", "Charlie"]); + // A column may be missing in some rows. Its present cells still sort normally. + let at = s.doc.body.iter().position(|b| b.as_table().is_some()).unwrap() as u32; + let table = s.doc.table_mut(StoryRef::Body, &wordcraft_doc::Path(vec![at])).unwrap(); + table.rows[0].cells.remove(1); + run(&mut s, "table.sort", json!({"column": 1, "header": false})); + assert_eq!(column_texts(&s), ["Charlie", "Bravo", "Alpha"]); + + let mut s = column_table("en-US", &["Title", "3", "1", "2"]); + let at = s.doc.body.iter().position(|b| b.as_table().is_some()).unwrap() as u32; + s.doc.table_mut(StoryRef::Body, &wordcraft_doc::Path(vec![at])).unwrap().rows[0].props.header = true; + run(&mut s, "table.sort", json!({"column": 0})); + assert_eq!(column_texts(&s), ["Title", "1", "2", "3"]); +} + /// #836: table sort reads numbers in the text's language: `1,5` is one and a half in Polish. #[test] fn table_sort_reads_decimal_comma_in_polish() { diff --git a/crates/engine/src/tests/find_apostrophes.rs b/crates/engine/src/tests/find_apostrophes.rs new file mode 100644 index 0000000000..c06bb381fe --- /dev/null +++ b/crates/engine/src/tests/find_apostrophes.rs @@ -0,0 +1,48 @@ +use super::*; + +/// Keyboard smart quotes stay searchable, and replacement keeps their original spelling. +#[test] +fn keyboard_apostrophe_finds_smart_quoted_typing() { + let mut s = s(); + for ch in "Tau'va".chars() { + run(&mut s, "text.insert", json!({"text": ch.to_string()})); + } + assert_eq!(text(&s), "Tau’va"); + for query in ["Tau'", "Tau'v", "Tau'va", "tau'VA"] { + assert_eq!(run(&mut s, "edit.find", json!({"text": query}))["count"], 1, "{query}"); + } + assert_eq!(run(&mut s, "edit.find", json!({"text": "tau'va", "matchCase": true}))["count"], 0); + assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "Tau'va", "with": "[^&]", "matchCase": false}))["replaced"], 1); + assert_eq!(text(&s), "[Tau’va]"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(text(&s), "Tau’va"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(text(&s), "[Tau’va]"); +} + +/// Normal search uses raw UTF-8 ranges while explicit syntax and modifier letters stay exact. +#[test] +fn normal_apostrophe_search_keeps_exact_modes_and_original_byte_ranges() { + let mut s = s(); + let original = "🙂 Tau'va Tau’va Tau‘va Tauʼva"; + run(&mut s, "document.setText", json!({"text": original})); + let found = run(&mut s, "edit.find", json!({"text": "Tau'va", "wholeWord": true})); + assert_eq!(found["count"], 3); + let ranges: Vec<_> = + found["matches"].as_array().unwrap().iter().map(|m| (m["start"]["off"].as_u64().unwrap(), m["end"]["off"].as_u64().unwrap())).collect(); + assert_eq!(ranges, [(5, 11), (12, 20), (21, 29)]); + for options in [json!({"special": false}), json!({"wildcards": true}), json!({"regex": true})] { + let mut exact = super::s(); + run(&mut exact, "document.setText", json!({"text": original})); + let mut params = options; + params["text"] = json!("Tau'va"); + assert_eq!(run(&mut exact, "edit.find", params)["count"], 1); + } + for query in ["Tau^u39va", "Tau^u8217va", "Tau’va", "Tau‘va", "Tauʼva"] { + assert_eq!(run(&mut s, "edit.find", json!({"text": query}))["count"], 1, "{query}"); + } + assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "Tau'va", "with": "<^&>"}))["replaced"], 3); + assert_eq!(text(&s), "🙂 Tauʼva"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(text(&s), original); +} diff --git a/crates/engine/src/tests/typing.rs b/crates/engine/src/tests/typing.rs index 574ee1368c..01ab762111 100644 --- a/crates/engine/src/tests/typing.rs +++ b/crates/engine/src/tests/typing.rs @@ -1539,6 +1539,110 @@ fn typing_at_either_end_of_a_link_is_not_linked() { assert_eq!(links(&s), [("sixte".into(), false), (String::new(), false)]); } +#[test] +fn a_link_on_a_selection_shows_the_text_to_display() { + // Ctrl+K on selected text with a new Text to display: the selection is retyped with it and + // linked, keeping its formatting; typing after it stays outside the link (as in Word). + let mut s = typed("go see kiln now"); + run(&mut s, "select.text", json!({"text": "kiln"})); + run(&mut s, "format.bold", json!({})); + run(&mut s, "insert.link", json!({"url": "https://example.org/", "text": "Oven"})); + typ(&mut s, "!"); + assert_eq!(texts(&s), ["go see oven! now"]); + assert_eq!(links(&s), [("Oven".into(), false)]); + let p = s.doc.body.iter().find_map(|b| b.as_para()).unwrap(); + assert!(p.run_ranges().any(|(r, c)| &p.text[r] == "Oven" && c.bold == Some(true)), "the new text keeps the selection's formatting"); + // The same text, or text that can't stand in one line, leaves the selection as it is. + run(&mut s, "select.text", json!({"text": "see"})); + run(&mut s, "insert.link", json!({"url": "https://example.org/", "text": "see"})); + run(&mut s, "select.text", json!({"text": "now"})); + run(&mut s, "insert.link", json!({"url": "https://example.org/", "text": "two\nlines"})); + assert_eq!(texts(&s), ["go see oven! now"]); +} + +#[test] +fn a_new_selection_drops_the_formatting_left_after_a_link() { + // A link leaves plain formatting for what is typed after it. A selection made next doesn't + // take it: retyping that selection keeps its own formatting. + let bold_run = |s: &Session, text: &str| { + let p = s.doc.body.iter().find_map(|b| b.as_para()).unwrap(); + p.run_ranges().any(|(r, c)| &p.text[r] == text && c.bold == Some(true)) + }; + let mut s = typed("kiln"); + run(&mut s, "select.text", json!({"text": "kiln"})); + run(&mut s, "format.bold", json!({})); + run(&mut s, "insert.link", json!({"url": "https://example.org/", "text": "Oven"})); + run(&mut s, "select.all", json!({})); + run(&mut s, "insert.link", json!({"url": "https://example.org/", "text": "Stove"})); + assert!(bold_run(&s, "Stove"), "select.all"); + run(&mut s, "select.word", json!({})); + run(&mut s, "insert.link", json!({"url": "https://example.org/", "text": "Range"})); + assert!(bold_run(&s, "Range"), "select.word"); + let anchor = serde_json::to_value(s.doc.start_of(s.sel.focus.story)).unwrap(); + let focus = serde_json::to_value(s.sel.focus.clone()).unwrap(); + run(&mut s, "select.range", json!({"anchor": anchor, "focus": focus})); + run(&mut s, "insert.link", json!({"url": "https://example.org/", "text": "Hob"})); + assert!(bold_run(&s, "Hob"), "select.range"); +} + +#[test] +fn a_link_over_two_paragraphs_keeps_their_text() { + // Word shows <> for such a selection: the text to display is ignored. + let mut s = typed("one\ntwo"); + run(&mut s, "select.all", json!({})); + run(&mut s, "insert.link", json!({"url": "https://example.org/", "text": "both"})); + assert_eq!(texts(&s), ["one", "two"]); + assert_eq!(links(&s), [("One".into(), false), ("two".into(), false)]); +} + +#[test] +fn a_retyped_link_text_is_tracked() { + let mut s = typed("go see kiln now"); + run(&mut s, "review.trackChanges", json!({"value": true})); + run(&mut s, "select.text", json!({"text": "kiln"})); + run(&mut s, "insert.link", json!({"url": "https://example.org/", "text": "Oven"})); + let p = s.doc.body.iter().find_map(|b| b.as_para()).unwrap(); + assert!(p.run_ranges().any(|(r, c)| &p.text[r] == "kiln" && c.del.is_some()), "the old text stays as a deletion"); + assert!(p.run_ranges().any(|(r, c)| &p.text[r] == "Oven" && c.ins.is_some() && c.link.is_some())); +} + +#[test] +fn a_link_keeps_a_selection_it_cannot_retype() { + use wordcraft_doc::props::CharProps; + use wordcraft_doc::{InlineObject, Path}; + let url = "https://example.org/"; + // A second retyped link keeps its own selection's formatting: the first one's left no + // formatting pending for it. + let mut s = typed("go see kiln and vat now"); + run(&mut s, "select.text", json!({"text": "kiln"})); + run(&mut s, "insert.link", json!({"url": url, "text": "Oven"})); + run(&mut s, "select.text", json!({"text": "vat"})); + run(&mut s, "format.bold", json!({})); + run(&mut s, "insert.link", json!({"url": url, "text": "Tub"})); + let p = s.doc.body.iter().find_map(|b| b.as_para()).unwrap(); + assert!(p.run_ranges().any(|(r, c)| &p.text[r] == "Tub" && c.bold == Some(true) && c.link.is_some()), "{:?}", p.text); + // A selection holding a manual line break keeps both lines. + let mut s = typed("one"); + run(&mut s, "text.lineBreak", json!({})); + typ(&mut s, "two"); + run(&mut s, "select.all", json!({})); + run(&mut s, "insert.link", json!({"url": url, "text": "both"})); + assert_eq!(s.doc.plain_text(StoryRef::Body), "one\ntwo"); + // A selection in a field's result is only linked; the field's next update owns that text. + let mut doc = wordcraft_doc::Document::from_text("See "); + let c = CharProps::default(); + let p = doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + let start = p.len(); + p.insert_object(start, InlineObject::FieldStart { instr: "ADDIN ZOTERO_ITEM CSL_CITATION {}".into(), locked: false, dirty: false }, &c).unwrap(); + let n = p.insert_text(p.len(), "(Smith 2020)", &c).unwrap(); + p.insert_object(start + 3 + n, InlineObject::FieldEnd, &c).unwrap(); + let mut s = Session::new(doc); + run(&mut s, "select.text", json!({"text": "Smith"})); + run(&mut s, "insert.link", json!({"url": url, "text": "Jones"})); + assert_eq!(s.doc.plain_text(StoryRef::Body), "See (Smith 2020)"); + assert_eq!(s.doc.field_ranges(StoryRef::Body).len(), 1); +} + #[test] fn typing_then_selecting_then_typing_are_two_undo_steps() { // #419: a selection that moves the insertion point ends the typing group, like a caret move. diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index b99e03b8ff..7305f5af5b 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -21,7 +21,7 @@ pub use fontdb::{ pub use harfrust::Feature; use harfrust::{Direction, ShapeOptions, ShapePlan, ShapePlanKey, Shaper, Tag, UnicodeBuffer}; pub use kurbo::BezPath; -pub use script::{fallback_rank, is_emoji, needs_layout_tables, script_fallbacks}; +pub use script::{fallback_rank, is_emoji, joins_cursively, needs_layout_tables, script_fallbacks}; use skrifa::MetadataProvider; use skrifa::instance::Size; pub use ui_fallback::{ @@ -185,13 +185,34 @@ fn direction_runs(text: &str) -> Vec<(std::ops::Range, bool)> { /// order: right-to-left runs are shaped right to left, then their clusters put back in text /// order (each cluster's glyphs keep the shaper's order); line layout reorders them visually. pub fn shape(face: &FontFace, text: &str, features: &[Feature], map: impl Fn(char) -> char) -> Vec { + shape_in(face, text, features, map, ShapeContext::default()) +} + +/// The text shown on either side of what is being shaped. Only a letter's form depends on it: the +/// letters of an Arabic word join across a change of formatting, so each piece has to know what +/// it continues (#4093). Nothing outside the shaped text is drawn or measured. +#[derive(Clone, Copy, Debug, Default)] +pub struct ShapeContext<'a> { + pub before: &'a str, + pub after: &'a str, +} + +impl<'a> ShapeContext<'a> { + /// This context for the part `r` of `text`: what's beyond `text` where `r` reaches its edge. + fn at_edges_of(self, text: &str, r: &std::ops::Range) -> ShapeContext<'a> { + ShapeContext { before: if r.start == 0 { self.before } else { "" }, after: if r.end == text.len() { self.after } else { "" } } + } +} + +/// [`shape`] of a piece of longer text (see [`ShapeContext`]). +pub fn shape_in(face: &FontFace, text: &str, features: &[Feature], map: impl Fn(char) -> char, around: ShapeContext<'_>) -> Vec { if !text.chars().any(is_rtl) { - return shape_dir(face, text, features, &map, false); + return shape_dir(face, text, features, &map, false, around); } let mut out = Vec::with_capacity(text.len()); for (r, rtl) in direction_runs(text) { let Some(sub) = text.get(r.clone()) else { continue }; - let mut g = shape_run(face, sub, features, &map, rtl); + let mut g = shape_run_in(face, sub, features, &map, rtl, around.at_edges_of(text, &r)); for x in &mut g { x.cluster += r.start; } @@ -205,7 +226,19 @@ pub fn shape(face: &FontFace, text: &str, features: &[Feature], map: impl Fn(cha /// mark positioning. Glyphs come back in logical order like [`shape`]: clusters in text order, /// each cluster's glyphs in the shaper's (visual) order. pub fn shape_run(face: &FontFace, text: &str, features: &[Feature], map: impl Fn(char) -> char, rtl: bool) -> Vec { - let g = shape_dir(face, text, features, &map, rtl); + shape_run_in(face, text, features, map, rtl, ShapeContext::default()) +} + +/// [`shape_run`] of a piece of longer text (see [`ShapeContext`]). +pub fn shape_run_in( + face: &FontFace, + text: &str, + features: &[Feature], + map: impl Fn(char) -> char, + rtl: bool, + around: ShapeContext<'_>, +) -> Vec { + let g = shape_dir(face, text, features, &map, rtl, around); if !rtl { return g; } @@ -221,7 +254,14 @@ pub fn shape_run(face: &FontFace, text: &str, features: &[Feature], map: impl Fn groups.into_iter().flatten().collect() } -fn shape_dir(face: &FontFace, text: &str, features: &[Feature], map: &impl Fn(char) -> char, rtl: bool) -> Vec { +fn shape_dir( + face: &FontFace, + text: &str, + features: &[Feature], + map: &impl Fn(char) -> char, + rtl: bool, + around: ShapeContext<'_>, +) -> Vec { let mut out = Vec::with_capacity(text.len()); let shaped = face.hb().map(|hb| { let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build(); @@ -234,6 +274,10 @@ fn shape_dir(face: &FontFace, text: &str, features: &[Feature], map: &impl Fn(ch for (i, c) in sub.char_indices() { buf.add(map(c), (r.start + i) as u32); } + // After the text: adding to a buffer clears what follows it. + let around = around.at_edges_of(text, &r); + buf.set_pre_context(around.before); + buf.set_post_context(around.after); buf.guess_segment_properties(); buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight }); let plan = shape_plan(face, &shaper, &buf, features); @@ -386,7 +430,10 @@ mod tests { gb.glyph_infos().iter().zip(gb.glyph_positions()).map(|(i, p)| (i.glyph_id, i.cluster, p.x_advance, p.x_offset, p.y_offset)).collect() }; let kept = |face: &FontFace, text: &str, features: &[Feature], rtl: bool| -> Vec<(u32, u32, i32, i32, i32)> { - shape_dir(face, text, features, &|c| c, rtl).iter().map(|g| (g.gid, g.cluster as u32, g.x_advance, g.x_offset, g.y_offset)).collect() + shape_dir(face, text, features, &|c| c, rtl, ShapeContext::default()) + .iter() + .map(|g| (g.gid, g.cluster as u32, g.x_advance, g.x_offset, g.y_offset)) + .collect() }; let db = FontDb::global(); let faces = [db.face(DEFAULT_FAMILY, "Regular"), db.face(DEFAULT_FAMILY, "Italic"), db.face("Source Sans 3", "Regular")]; @@ -421,7 +468,8 @@ mod tests { for n in 0..3 * MAX_SHAPE_PLANS as u32 { let features = [feature_value(b"kern", n % 2), feature_value(b"liga", n)]; let rtl = n % 3 == 0; - let kept: Vec<(u32, i32)> = shape_dir(&face, "office", &features, &|c| c, rtl).iter().map(|g| (g.gid, g.x_advance)).collect(); + let kept: Vec<(u32, i32)> = + shape_dir(&face, "office", &features, &|c| c, rtl, ShapeContext::default()).iter().map(|g| (g.gid, g.x_advance)).collect(); assert_eq!(kept, fresh(&features, rtl), "{n}"); assert!(kept_shape_plans() <= MAX_SHAPE_PLANS, "{}", kept_shape_plans()); } diff --git a/crates/fonts/src/script.rs b/crates/fonts/src/script.rs index e97de89ce7..51c9d252c5 100644 --- a/crates/fonts/src/script.rs +++ b/crates/fonts/src/script.rs @@ -18,6 +18,28 @@ fn real_script(c: char) -> Option