Compare commits

...
Author SHA1 Message Date
Martin BallandClaude Opus 5.5 be7624eb96 ROADMAP: remove two stray branch-name lines from the progress log
Leftovers from earlier merges: a line reading "fix/6146-touchpad-scroll-speed" and one reading "main" sat between progress-log entries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXtSjB6e5jmy9Uq7u8
2026-11-17 08:05:16 +00:00
Bryan MarkandClaude Opus 5.5 aeb9704d82 UI: CJK text gets an installed CJK font in builds without craft-fonts and craft-i18n (#4637)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:53:51 +01:00
Michael MuandClaude Sonnet 5.5 221faf2901 KeyTips: two-letter command badges can be completed (#4498) (#4499)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 08:40:33 +01:00
Dylan M. Taylor a5753be57e docs: prefer shared craft-libs implementations (#6862) 2026-11-17 08:27:16 +01:00
Valentin KleinandClaude Sonnet 5.5 caa4c4b114 Enter in a paragraph with a drop cap no longer copies the drop cap (#6793)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 08:10:58 +01:00
Mex ca075db458 M14: report missing --cmd values before CLI options (#6686) 2026-11-17 07:54:43 +01:00
Valentin KleinandClaude Opus 5.5 4e2a5c2b8f Table borders no longer look blue and uneven (#6048)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 07:42:09 +01:00
Thân Minh NghĩaandClaude Opus 5.5 54e82f7131 Table Design: show Shading label beside the color menu arrow (#2016)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 07:26:11 +01:00
224bfdb2a0 Layout: Word 2003's indent rules start a line right after a float before the indent (#5939) (#5940) (#6905)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: SenuraMalaka <19330762+SenuraMalaka@users.noreply.github.com>
2026-11-17 07:04:39 +01:00
Bardan Ghimire abc04c1b41 geom: fix Rect collapse, sanitize deserialized Rect, accept non-ASCII… (#5880) 2026-11-17 06:50:55 +01:00
reubgr 29d862fabc Compare: preserve per-segment formatting in word_diff (#3749, stage 0) (#5569) 2026-11-17 06:37:34 +01:00
socrabs151 406befeaa2 #3720: budget hostile large parameters, and cap the TOC title (#5824) 2026-11-17 06:19:32 +01:00
ljkxandClaude Opus 5.5 93bf14883c #3773: a WordCraft process saves only the preferences it changed (#5258)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 06:06:04 +01:00
Marc 0cb315edaf fix(ui): Recent shortens long names and paths to the row (#5212) (#5321) 2026-11-17 05:53:08 +01:00
.CooCoo 2dd0f9a67b Field dialog: text fields have a Format list for capitalization (#5062) 2026-11-17 05:37:06 +01:00
Mex 739cdcad0b M15: correct English proofing credits in README (#6681) 2026-11-17 05:15:46 +01:00
Mex b3f31666d3 M14: align release guide with scheduled dry runs (#6682) 2026-11-17 05:00:18 +01:00
Mex 68f758928e M14: keep the type_text description in one MCP table row (#6683) 2026-11-17 04:45:21 +01:00
Mex 840efd03fb M14: link PDF revision guidance to the workspace manifest (#6685) 2026-11-17 04:30:24 +01:00
Mex 8e8ab631fd M14: document optional run commands and PNG save options (#6687) 2026-11-17 04:16:20 +01:00
Mex 8a9d04eeb1 M14: restore save stamps after immediate web-save errors (#6824) 2026-11-17 03:59:04 +01:00
Mex 266407e840 M14: expose file-browser row names and selection (#6790) 2026-11-17 03:46:09 +01:00
Valentin KleinandClaude Sonnet 5.5 c817cc95c6 Render: keep a metafile with huge bitmaps in the cache instead of parsing it on every repaint (#5494)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 03:32:02 +01:00
Diego GueriniandClaude Opus 5.5 ff0823f40d Track Changes: a deleted list item's number is drawn as deleted text (#4828) (#4836)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:19:00 +01:00
Mex 211f62231d M14: correct control protocol parameter examples (#6684) 2026-11-17 03:03:15 +01:00
RickiNano 9144b9bfda Insert › Shapes: the Arrow tile is the block arrow it inserts (#6768) (#6882) 2026-11-17 02:45:40 +01:00
RickiNano a61cef5d45 edit.replace reports whether it replaced and what it selected (#6877) (#6879) 2026-11-17 02:29:41 +01:00
Mex 739491f5c7 M14: list xtask version and point layering help at public docs (#6688) 2026-11-17 02:13:51 +01:00
Mex 8377ea8e8f M7: document the explicit stop flag for protection (#6690) 2026-11-17 01:59:18 +01:00
Mex 4357166531 M14: report the supported ICO image bounds (#6694) 2026-11-17 01:28:39 +01:00
Mex 5d871d0519 M14: document the selection collapse end parameter (#6695) 2026-11-17 01:15:46 +01:00
Mex ae2d2b43d6 M3: describe the 32-bit comment identifier limit (#6696) 2026-11-17 01:03:22 +01:00
Mex cd23034f65 M14: clarify when layout tests need explicit font initialization (#6697) 2026-11-17 00:52:01 +01:00
Mex b2306fe5ef M3: explain invalid font name values (#6698) 2026-11-17 00:36:03 +01:00
Mex 646fbc7cd5 M10: clarify Zotero command response shapes (#6700) 2026-11-17 00:20:17 +01:00
Mex 4a347e070a M14: expose required command inputs in discovery (#6703) 2026-11-17 00:07:55 +01:00
Mex 3bf4c05461 M14: explain the bookmark name rules in validation errors (#6706) 2026-11-16 23:54:32 +01:00
Mex 7b26a94193 M14: clarify dictionary-folder auto reset (#6709) 2026-11-16 23:39:06 +01:00
Mex ace000b4a4 M14: expose table-style formatting names and selection (#6711) 2026-11-16 23:26:12 +01:00
Mex 7adbdc574c M14: describe canvas member listing without an index (#6714) 2026-11-16 23:12:16 +01:00
Mex f77eef9cb6 M14: expose the keyboard shortcut capture name and current key (#6716) 2026-11-16 22:57:20 +01:00
Mex a2f41d728e M14: distinguish font file and unpacked size limits in errors (#6719) 2026-11-16 22:41:53 +01:00
Mex 9fe9bd5042 M14: clarify initial and pane spelling-review wrapping (#6720) 2026-11-16 22:26:23 +01:00
Mex 83c3b5890b M14: describe all accepted mail-merge sort forms (#6724) 2026-11-16 22:15:32 +01:00
Mex f472620ac0 M14: explain invalid field code values (#6725) 2026-11-16 22:03:39 +01:00
FredApps 5467f998a0 Tests: set the fit-one-page fixtures in bundled Inter so FreeBSD pages them like other hosts (#6887)
* Tests: set the fit-one-page fixtures in bundled Inter

The fit-one-page fixtures count pages to the line, but they were set in the
default Aptos, which each host substitutes with whatever it has installed:
Arial on Windows, Liberation Sans on the Linux runners, DejaVu Sans on the
FreeBSD image (its only candidate). DejaVu Sans is taller, so at 11 pt it fits
27 of the fixture lines on a page where Arial fits 28, and the nightly FreeBSD
job failed fit_one_page_respects_step_pt and
fit_one_page_preserves_budget_across_document_serialization.

Set the fixtures in the bundled Inter, whose metrics keep a page boundary for
each 0.5 pt step, recount the fixed line counts for it, and start the boundary
searches below the boundary. The two tests that failed also assert that the
body is laid out in Inter, not a substitute.

* Tests: keep 7 to 12 body lines on the line-numbered fixture's final page

A boundary search left one body line on the final page, so counting the
line-number decorations too would still have stayed under the 12-line limit and
the test could not catch it. Use 33 lines, 8 on the final page in Inter, and
assert the body-only count is between 7 and 12.
2026-11-16 21:51:07 +01:00
Mex 78dfa8f648 M14: label Alt Text pane inputs for assistive technology (#6726) 2026-11-16 21:48:11 +01:00
Mex 82f0c467be M14: describe encrypted OpenDocument command support (#6776) 2026-11-16 21:32:11 +01:00
Mex 837a610133 M14: explain hyperlink URL input limits (#6789) 2026-11-16 21:20:15 +01:00
FredApps de977bcde6 Merge pull request #6658 from dotCooCoo/fix/issue-6636
Metafiles: draw EMF+ bitmaps, pattern fills, clips and pen styles from craft-metafile (#6636)
2026-11-16 17:28:06 +01:00
FredApps 4ba0595760 Merge pull request #6863 from storytold/refactor/shared-tiff-compression
geom: delegate TIFF compression inspection to craft-tiff
2026-11-16 16:48:47 +01:00
FredApps 6854bd1fb3 Merge remote-tracking branch 'origin/main' into pr6863 2026-11-16 16:05:20 +01:00
FredApps 4356771236 geom: pin craft-tiff to craft-libs main at the merge of #1867 (6ef2c053) 2026-11-16 16:05:20 +01:00
Dylan M. Taylor cdf146cabd Merge pull request #6759 from RickiNano/fix/6757-unequal-formats-linear
Layout: a paragraph over many pages lays out in linear time (#6757)
2026-11-16 07:38:06 -05:00
Martin BallandClaude Opus 5.5 54e3e1cf34 CI: fix red SonarCloud on main (#6859)
The coverage shards failed six tests on every main push:
- three UI glyph tests: the Sonar job had no craft-fonts. Pass the same
  fonts-ref as ci.yml.
- three layout linear-time tests: llvm-cov instrumentation pushes the
  8x time ratio past 24 (24.2-31.2). Ignore them under cfg(coverage),
  which cargo llvm-cov sets; the gate CI still runs them.


Claude-Session: https://claude.ai/code/session_01FypgCXtSjB6e5jmy9Uq7u8

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 12:06:41 +00:00
Dylan M. Taylor 97c13a2990 geom: delegate TIFF compression inspection to craft-tiff 2026-11-16 06:44:41 -05:00
Martin BallandClaude Opus 5.5 fe8a8a838c Header pictures: while editing the header, a click selects its Behind Text picture wherever no header text covers it (#5601)
* Header pictures: while editing the header, a click selects its Behind Text picture wherever no header text covers it

Header and footer Behind Text pictures skip the deferred drag-over-text path
where the plain hit test picked them with no text under them, and a right-click
selects them (and sets the page they were hit on) so Reset Picture and Wrap
Text act on them. Tests cover a header and a footer, a drag, and a repeated
picture right-clicked on another page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #5601: header Behind Text picture: a left-click selects the copy clicked on a repeated page

The press branch of pointer() selected the picture but left page_hint on the page being edited, so on a header picture repeated on page 2 the frame and handles were resolved and drawn on page 1. Set page_hint to the picked object's page, as select_at does for a right-click. Adds a left-click counterpart to the right-click test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #5601: header text hit test checks each line's own extent

CodeRabbit: hf_text_at took the whole paragraph's right edge from its last line, so
a click on a long first line past a short last line's end counted as clear of text
and selected the Behind Text picture under it. Each line now has its own band and
extent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #5601: pin that centred and right-aligned header lines cover their whole band

Line::left/right are the edges available to a line, not where its ink sits,
so a centred or right-aligned header line already covers the Behind Text
picture across its band (indent and floats narrow it) plus 40pt. Test pins
that, and the parity row now says what counts as covering the picture.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5601: pin Line.left/right as band edges in the header band test

Assert the band's left edge is the 150pt indent, the centred/right ink
starts well inside it, and a click between the indent and the ink is
text. Fails if Line.left were the ink extent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:08:59 +00:00
2bd6f372c5 File › Print: reopened, the page doesn't repeat the last job's message (#5597)
* File › Print: opened again, the page doesn't repeat the last job's message

"Print job submitted…" (or a failure) stayed on the Print page the next
time it was opened. The job's outcome is said once in the status bar, so a
fresh open drops it; a failure arriving while the page is open stays, and
printer status (finding printers, none found) still shows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCYPZSei56X4AGFPSu5

* Print page: the last job's marker is kept per window, since egui counts passes per viewport

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCYPZSei56X4AGFPSu5

* #5597: decide the Print page's hidden job message per window

The shared printing.message is no longer cleared on reopening Print (ui.printSettings
and other windows still report it). Each window remembers what it said (status bar or
Print page) and hides only that; a result that arrived under File's other pages is
not counted as said. Tests: failure-on-open-page now depends on reopen detection,
never-said and two-window state.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5597: follow the job message by generation, not by text

A retry that fails again with the same words is a new result and shows. A generation
(WordApp::print_gen) is bumped when a job starts and when the message changes; each
window's Print memo stores generations, so cross-window comparison is by identity too.
Also: update the print_memo doc comment, drop an empty branch, align the docs row date.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXtSjB6e5jmy9Uq7u8

---------

Co-authored-by: Martin Ball <martin.ball@ucsmedical.co.uk>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:07:57 +00:00
8a1f101c46 Save As and Export: Browse in WordCraft when the system dialog doesn't appear (#3535) (#3801) (#5790)
* Save As and Export: Browse in WordCraft when the system dialog doesn't appear (#3535) (#3801)

Ported from #3801 by VoiceLessQ onto current main.

Re-resolved against main:
- file_browser.rs tests: rebuilt whole, keeping main's #3859 tests (browser
  above the dialog, Escape, dialog closing into the browser, modeless
  keyboard, no keytips) and the PR's #3535 export tests.
- print_page.rs: EXPORT_FORMATS now carries main's OpenDocument Text
  Template (*.ott) and Flat OpenDocument Text (*.fodt) in main's order;
  main's tests module kept.
- docs/control-protocol.md: ui.fileBrowser purpose "export" added to main's
  current row (keeps ui.displayServer).
- docs/ui-parity.md: File dialogs row merged with main's Linux display
  server row, #3955 history row kept, status line and revision history
  bumped.

Added a test that the ott and fodt export types get their extension and
write the file.

Co-Authored-By: VoiceLessQ <44067308+VoiceLessQ@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCVCCEo7u5wetHaJRU4

* #3535: Word XML export from the system dialog adds .xml to a typed name

CodeRabbit: the system Save dialog accepts any name, and the engine takes the
explicit Flat OPC format only for an .xml path, so `letter` failed to export. The
extension is added as the built-in browser does; an existing file at the new name
is refused, since the dialog never confirmed replacing it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #3535: an existing file at the .xml name is refused on the status bar

CodeRabbit: export_dialog drops ask_file's result, so the refusal was silent with a
blocking Save dialog. finish_pick now puts it on the status bar as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #3535: Export refusals show on the Export page; a typed document extension gives way to the chosen type's

A refused or failed export is said on the Export page (Backstage hides the status bar), as Save As does. A known document extension on the typed name is replaced by the chosen Export type's, and any other is kept with the extension added.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #3535: Print page shows export errors; cancel clears them; export_name edge cases

The export error is drawn inside export_formats, so the Print page shows it as well as the Export page. Cancelling an export drops an earlier error. export_name treats a name that is only a known extension (.txt) as that extension and drops a trailing dot before adding the type's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXtSjB6e5jmy9Uq7u8

* #3535: Export error is per window; a dotfile export name gets a real extension

The export error moves from a shared Context-data id into per-window state (swapped with the window like missing_fonts), so one window's frame outside Backstage no longer erases another's message. export_name treats a dotfile name such as .docx as a stem, so the engine's explicit-format guard (Path::extension) accepts the result; Word 2003 XML exports are named the same way.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXtSjB6e5jmy9Uq7u8

---------

Co-authored-by: Martin Ball <martin.ball@ucsmedical.co.uk>
Co-authored-by: VoiceLessQ <44067308+VoiceLessQ@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 10:06:53 +00:00
42f8559b97 Review › Language: set the whole document's proofing language (#3518) (#5810)
* #3518: Review › Language can set the whole document's proofing language

review.language takes scope "selection" (default, unchanged) or "document":
every run and paragraph mark of every story (body, headers, footers, notes,
comments, text boxes, table cells, glossary) takes lang/noProof in one undo
step, selection unchanged, pending typing format follows. The Language dialog
gets an "Apply to the whole document" check box.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCVCCEo7u5wetHaJRU4

* #3518: whole-document OK sends only what was changed in the Language dialog

With "Apply to the whole document" ticked, OK sends noProof only if the user
changed it from the dialog's opening value, and lang if changed or if neither
changed (never the engine's en-US default). Heading reads "Mark the whole
document as:" while ticked. Glossary walker uses doc's PARA_WALK_DEPTH (now pub).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCVCCEo7u5wetHaJRU4

* #3518: whole-document OK with Do not check ticked marks the whole document

CodeRabbit: with the caret's text already not checked, the box was unchanged, so a
whole-document OK never sent noProof and the rest of the document stayed checked.
A ticked box is now always sent; an unticked, unchanged one is still omitted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #3518: refuse whole-document language changes under protection

Protection leaves only its exceptions editable, so document scope is refused before anything changes. The post-check now compares the glossary, which no story-level check reached.

* #3518: whole-document language keeps per-run proofing, returns selection, skips glossary while tracking

- Language dialog: whole-document OK sends noProof only when the box was changed, so a language-only change no longer marks everything no-proof.
- review.language scope "document" returns the caret/selection result (plus scope).
- Whole-document change skips glossary blocks while Track Changes and Track Formatting are on (tracked formatting does not cover them).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #3518: whole-document Do not check is sent when the box is clicked; report skipped glossary

- Language dialog: a whole-document OK sends noProof iff the Do-not-check box was clicked (proof_touched), so ticking it with the caret in a no-proof run still marks the whole document, while a language-only change leaves other runs alone.
- review.language document scope reports "glossarySkipped": true when the glossary was skipped under Track Changes + Track Formatting; doc comment reworded to state only the limitation.
- Docs status line and revision row bumped to 2026-11-16.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Martin Ball <martin.ball@ucsmedical.co.uk>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
2026-11-16 10:05:15 +00:00
Martin BallandClaude Sonnet 5.5 bf8b37759c Ctrl/Cmd+Shift+V pastes text only when no formatting was copied, as in Word (#1537) (#5616)
* #1537: Ctrl/Cmd+Shift+V pastes text only when no formatting was copied, as in Word for Windows

With formatting picked up by Ctrl/Cmd+Shift+C it still pastes the formatting.
Closes #1537, #4943; takes over #1562.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #1537: review — a browser's Mod+Shift+V paste event pastes text only, once (CodeRabbit)

On the web the key no longer pastes as well: the paste event that follows carries the text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #1537: review — copied formatting stays for every Mod+Shift+V; a browser's paste after it is ignored (wanikhawar)

Copy Formatting keeps its formatting apart from the one-shot Format Painter brush, so a second
Mod+Shift+V pastes formatting again instead of text, and Mod+Shift+C no longer arms the brush.
After Mod+Shift+V pastes formatting, the browser's paste event for the same keystroke is ignored;
paste events read the modifiers held in event order. Only Mod+Shift+V itself falls back to Keep
Text Only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCYPZSei56X4AGFPSu5

* #1537: review — one format buffer, formatting-only copy, browser paste suppression only where it exists

- ignore_next_paste armed only for Mod+Shift+V on platforms that send a paste event after it (web); never for a rebound key
- the ignored paste is dropped before equation and picture-file handling
- Event::Paste takes paste_mods so they don't leak into later pastes
- Copy Formatting and Format Painter replace each other; a used-up brush no longer hands over to older copied formatting
- copied formatting carries no hyperlink or revision marks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #1537: review — shared format buffer, no tracked paragraph changes, pointer press ends the paste wait

- picked_format strips ParaProps fmt_change/num_change
- Format Painter pick is stored in copied_format too; a used-up or cancelled brush leaves it
- a pointer press clears ignore_next_paste
- docs: repeat-until-replaced wording

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #1537: review — a caret Paste Formatting keeps the target's own link and tracked marks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #1537: review — an unrelated key's modifiers can't steer a later paste event

A separate paste_event_mods is set by Mod changes and Mod+V's press, and cleared by any other key, a pointer press or focus change; the release path keeps paste_mods.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #1537: review — the text-only paste test checks the destination's own formatting stays (CodeRabbit)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #1537: review — the docs say a Format Painter pick counts as picked-up formatting too (CodeRabbit)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #1537: review — a dropped paste uses up its modifiers; range Paste Formatting keeps the link (alehel)

- The browser paste event dropped after a formatting paste now clears paste_event_mods too, so a
  later menu-bar paste isn't read as Keep Text Only. Note the no-text clipboard case.
- Test that Paste Formatting over a selection keeps the target's hyperlink.
- session.rs: copied_format holds a Format Painter pick too.
- ROADMAP: entry moved up with the other 2026-11-04 entries; stray blank line dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #1537: review — the wait for Mod+Shift+V's browser paste ends after a second, so a later menu-bar paste isn't dropped (FredApps)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCX8G9hbs6XYZFsgjbL

* #1537: review — an expired paste wait drops the chord's noted Mod+Shift too (CodeRabbit)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCX8G9hbs6XYZFsgjbL

* #1537: review — dropping the paired paste uses up its modifiers; range Paste Formatting keeps the target's link

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #1537: review — restore ui-parity status line; add Paste Formatting row to typing-parity

docs/ui-parity.md: the rebase had replaced main's status line with an older one;
restore it and prepend this PR's entry. docs/typing-parity.md: add the
Ctrl/Cmd+Shift+V row to the Paste section, bump status line and history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #1537: Ctrl/Cmd+Shift+V's V release never pastes a second time

On desktop the chord's key-down path pastes (text, or the copied formatting) but didn't mark the
paste as done, so releasing Shift before V left a plain Mod+V release that ran Paste again through
the clipboard-picture hook, inserting the text twice. The canvas's chord now marks the paste done;
the global-shortcut path (canvas unfocused, no release seen) doesn't, and a focus change clears
the mark so a lost release can't swallow a later Mod+V picture.
Docs: web text paste needs the browser to send its paired Paste event; with formatting copied that
event is dropped only within about a second of the key.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:59:47 +00:00
FredApps 1ed889c24c Merge pull request #6448 from batistalucasv/fix/control-server-reset-closed
Tests: a reset control connection counts as closed (Windows Print flake)
2026-11-16 10:23:29 +01:00
FredApps 6a7af0d679 Merge pull request #6731 from batistalucasv/fix/6722-font-combo-select-without-dropdown
UI: select font box text on click without opening dropdown (#6722)
2026-11-16 10:21:19 +01:00
ce6e4094d5 Dialogs: group settings in soft panels of dialogs to improve readability (#4038)
* Dialog sections: heading, space above, soft panel (#4035)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Dialog sections: heading inside the panel, settings indented (#4035)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Dialog sections: more dialogs, anonymous and nested panels, scroll on short screens (#4035)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Format dialog accessibility updates

* Format reference dialog controls

* Replace deprecated egui IDs in dialogs

* Preserve stable IDs for dialog state

* Document dialog section parity update

* import layout test fixtures

* format merged code after fix

* Fix unused imports after dialog port

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Fluorine <joseph.anglada92@gmail.com>
2026-11-16 10:02:24 +01:00
FredApps 9088ed777d Merge pull request #6818 from storytold/extract/shared-engine-base64
Reuse shared Base64 encoding for engine payloads
2026-11-16 06:42:28 +01:00
Dylan M. Taylor cc90520b9d Merge pull request #5073 from AxylumRust/refactor/geom-clippy-pedantic
geom: satisfy Clippy pedantic lints (M14)
2026-11-15 16:49:58 -05:00
Dylan M. Taylor a95b065c2b M14: integrate current shared picture codecs and clarify refusals 2026-11-15 16:30:18 -05:00
FredApps 84026f98b2 Merge pull request #6817 from MMexicann/patch-45
M14: preserve existing PDF suffixes in web exports
2026-11-15 22:04:18 +01:00
Mex 5f228a0e24 M14: cover Unicode and misleading PDF filename suffixes
Added additional test cases for PDF file name handling in file dialogs.
2026-11-15 20:54:24 +01:00
Mex b354e0f870 M14: bound PDF suffix checks to four bytes 2026-11-15 20:53:49 +01:00
Dylan M. Taylor 86352d5cf3 Reuse shared Base64 encoding for engine payloads 2026-11-15 14:34:21 -05:00
Mex 3e776e4c7d M14: cover PDF suffix case in web downloads
Assert exact delivered filenames and PDF bytes for lowercase, uppercase, mixed-case Unicode and missing suffixes.
2026-11-15 20:27:16 +01:00
Mex a9a1aa36a2 M14: preserve existing PDF suffixes in web exports
Recognize an existing PDF extension without changing its case or the requested filename.
2026-11-15 20:26:14 +01:00
Valentin Klein bc0e51ee4d Interface size: Auto is capped to what fits the screen, Ctrl+Shift+0 returns to Auto (#4030) (#5203)
Fixes #4030

On a small screen (an 11-inch 1366x768 panel) the system can report a very large display scale. The Auto interface size followed it blindly, so the window and ribbon came out far bigger than the screen and File > Options, where the size is set, could not be reached.

What this changes:
- Auto interface size is now capped so a window of at least 900x460 points still fits the screen (about 152% on 1366x768). Scales that already fit (for example 1920x1080 at 100-150%, or 1366x768 at up to 150%) are unchanged. If the screen size is unknown there is no cap.
- A size chosen in File > Options is still taken as is. If a large size pushes the options out of reach, Ctrl+Shift+0 (Cmd+Shift+0 on Mac) returns to Auto from anywhere. Ctrl+Alt+0 is not used because it is AltGr+0 on some layouts and would type a character.
- `ui.interfaceSize` and the "Auto (n%)" label in Options report the capped value. The cap is never saved to `ui.json`.
- Tests: the cap for several screen sizes, the shortcut, AltGr+0 still typing, and the reported percent. Docs: ui-parity, control-protocol, ROADMAP progress log.

Not covered:
- The root cause of the oversized scale (X11 DPI detection) is handled by #721 and #3240. This change is separate and works with or without them.
- A manually chosen large size can still push controls off screen, but there is now a way back.
- Not tested on a real 1366x768 screen.

`cargo xtask ci` passed locally on the pushed code; GitHub CI has not run yet.

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

* **New Features**
  * Auto interface sizing now scales down on smaller displays to keep a window of at least 900×460 points within the screen. Sizes selected in Options remain uncapped, and the minimum Auto scale is 100%.
  * Press Ctrl+Shift+0 (⌘⇧0 on Mac) to restore Auto sizing. When Auto sizing is capped, the displayed zoom percentage reflects the screen-fit limit; the cap does not change the saved size.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-15 12:12:27 +01:00
batistalucasv ed66198574 .gitattributes: normalise text on add so CRLF cannot be committed again (#6543)
`cargo fmt --check` passes on CRLF (verified: exit 0, empty output), so the gate cannot see a commit that rewrites line endings. `#6537` did exactly that: 50 files, 35,102 lines, all CRLF, while declaring a one-line test change.

## Change

Adds the normalisation the repository lacks — `.gitattributes` only pins `craft-i18n.rev` today:

```
# Text lives in the repository with LF. A Windows checkout once committed 50 files with CRLF
# (#6537) and `cargo fmt --check` still passed, so the gate could not see it. Normalise on add.
* text=auto

craft-i18n.rev text eol=lf
```

`craft-i18n.rev` stays last so the specific rule still wins.

## Dependency

The repair landed first: #6541 merged as `eae8363e`, and `git grep -lI $'\r'` on that head finds **0** text files. This branch merges that `main` in `01617884`, so the rule now applies to a tree that is already LF.

`text=auto` is not an absolute enforcement gate. It normalises text on add, and it does not rewrite a blob already stored with CRLF: plain `git add` on such a file leaves `git ls-files --eol` at `i/mixed`, and only `git add --renormalize` rewrites it to `i/lf`. That is why the repair had to land first, and why this is a guard for future commits, not a fix for the past.

## Why it is safe

- Every text file in `main` is already LF (`git grep -lI $'\r'` = 0).
- No `.bat`/`.cmd` or CRLF fixture exists; the `.ps1` files under `packaging/windows/` are already LF in the repository.
- `cargo fmt --check` clean and `cargo test -p wordcraft-engine --lib` 1460 passed, unchanged.

## Why two PRs

#6541 was the repair; this is the guard, and it is a repository policy change rather than part of the fix, so it is separate and optional. If a repo-wide rule is more than you want, the narrower form is one pattern per line:

```
*.rs text eol=lf
*.toml text eol=lf
*.md text eol=lf
*.properties text eol=lf
```

Thanks for the syntax correction: the single-line fallback I wrote earlier was not valid attribute syntax.

@FredApps — the dependency is settled and this branch is on the new `main`. Ready for approval when you have a moment.
2026-11-15 12:11:56 +01:00
RickiNanoandClaude Opus 5.5 d53a740be1 #6757: lay out a paragraph over many pages in linear time
Each page's piece of a paragraph walked every line of the paragraph in
place_objects to find the pictures and shapes to draw with it, skipping
all but its own lines and the late-float anchor lines. A paragraph over
many pages was quadratic in its lines. A later piece now walks only its
own lines and the late-float anchor lines, in the same order.

unequal_formats_lay_out_in_linear_time reads 8.0x for 8x the runs in a
debug build, down from 15.0x, so it no longer fails in the slower
SonarCloud coverage build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 10:25:09 +01:00
Nine e9750c5cb7 Add Bosnian interface language (#4804)
Register Latin Bosnian as an interface language, with catalog-backed locale, plural and font regressions. Preserve the existing system-locale detector; POSIX script-modifier handling is outside this change.

Original contribution by @nine-codes.
2026-11-15 00:31:44 -06:00
3d5a153e3d Keep TOC entries for tab-numbered headings on one line (#6738)
Fixes #6486

Co-authored-by: cute-johnny <269855522+cute-johnny@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 02:23:52 +01:00
batistalucasv 7bff3b53e9 Test: assert egui popup state on font arrow toggle (#6722) 2026-11-14 18:35:40 -03:00
batistalucasv 0909b15eae UI: select font box text on click without opening dropdown (#6722) 2026-11-14 18:08:39 -03:00
Mex 52d17a91df M14: identify WordCraft correctly in the iframe title example (#6717)
Use word processor as the accessible iframe description instead of image editor.
2026-11-14 21:40:06 +01:00
batistalucasv 323cf78232 UI: open font dropdown and select font name on click (#5914) (#5926)
* UI: open font dropdown and select font name on click (#5914)

* UI: select font name only on opening dropdown and scope to search (#5914)

* UI: refresh highlight from current font whenever combo opens (#5914)

* UI: restore font order and match enter ordering for highlight (#5914)

* UI: address review comments on font dropdown interactions and docs (#5914)

* UI: handle system font action in dialog font combos and test focus selection (#5914)

* UI: reset highlight on open and preserve query on scrollbar focus (#5914)

* UI: drop dialog routing changes to keep scope narrow (#5914)

* UI: test genuine blur and refocus while font dropdown is open (#5914)
2026-11-14 21:22:27 +01:00
dotCooCoo e6e8c61dbf Merge main into fix/issue-6636 2026-11-14 12:11:53 -08:00
Dylan M. Taylor 42a5df5f94 chore: cut over image codecs and zip to craft-libs (#6661)
* chore: cut over image codecs and zip to craft-libs, fix main test regressions

* tests: store ODS mimetype and use standard ODF namespaces in mailings test

* Remove unused quick-xml workspace dependency

* fix: use standard ODF namespaces in file_dialogs test and preserve trailing line in markdown import_on_with_lines

* fix(geom): use png_chunks for PNG dimensions and p.fits(budget) in decode_for_drawing
2026-11-14 14:51:35 -05:00
dotCooCoo 1d150004f7 Tests: EMF+ only bitmaps are drawn over their EmfPlusDrawImage rectangle
The two EMF+ bitmap tests checked only that the bitmap is embedded. They now
also read the page through hayro's interpreter and check that the page draws
each bitmap over the right half of the picture, where its EmfPlusDrawImage
rectangle places it.
2026-11-14 11:40:21 -08:00
Cédric Legrand 0aefd4d025 fix(geom): M14: adapt picture error mapping 2026-11-14 18:00:04 +01:00
Cédric Legrand 235a38c665 style(geom): M14: remove review churn 2026-11-14 17:55:18 +01:00
Cédric Legrand 3bf7a5dbbe docs(geom): M14: qualify truncated TIFF errors 2026-11-14 17:55:18 +01:00
Cédric Legrand e40199bf6f docs(geom): M14: clarify truncated TIFF errors 2026-11-14 17:55:18 +01:00
Cédric Legrand e2f94ecef9 refactor(geom): clean up Clippy pedantic diagnostics (M14) 2026-11-14 17:55:18 +01:00
dotCooCoo 7ccfd4caef Tests: EMF+ only bitmaps in ARGB, RGB, PNG and JPEG are drawn
The page renderer and the PDF exporter each get a test that draws an
EmfPlusDrawImage bitmap in PixelFormat32bppARGB, 24bppRGB and 32bppRGB,
and a compressed PNG and JPEG bitmap, from an EMF+ only file.
2026-11-14 07:40:12 -08:00
dotCooCoo 7b3b6f8041 Merge main into fix/issue-6636 2026-11-14 07:32:49 -08:00
FredApps f8c66d0692 Merge pull request #6040 from FredApps/fix/artcraft-feature-names-20261108
Use Diagram and Decorative Text display names
2026-11-14 16:22:19 +01:00
dotCooCoo fecb717f99 Metafiles: read WMF, EMF and EMF+ with craft-metafile (#6636)
crates/metafile is deleted. formats, layout, render and pdf take their
WMF, EMF and EMF+ reader from craft-metafile (craft-libs 9dcbd90c, the
rev craft-docx is already pinned at), so EMF+ records are read: an EMF+
only file's DrawImage of a 32bppPARGB bitmap draws its pixels.

render and pdf draw what the shared model adds: pattern and hatch fills,
clip regions and clip paths, pen caps, joins, miter limits and dashes,
turned, skewed or mirrored bitmaps, and the opaque background behind
text. The text layout and the default font for a file that names none
(Arial, a 16-unit cell) move to layout, next to metafile_text_run.

layout/src/metafile.rs holds the rules both outputs follow: a negative
crop side draws as no crop, as before; a cosmetic pen's shortest dash
or gap is one output pixel; a dash pattern whose period is under a
pixel, or that would split a path into more than 100,000 pieces, draws
solid; and an invalid miter limit is 10. On screen, a pattern tile whose
sides are both under 1.5 device pixels fills with its average color,
computed once a tile, and the vector cache counts each item's clip
region, clip list and dash pattern.

Fixes #6636
2026-11-14 05:16:52 -08:00
FredApps aba890e8a6 fix(i18n): align Flatpak catalog pin with embedded catalogs 2026-11-14 14:05:33 +01:00
FredApps 0cc92c9744 #6040: pin merged feature catalogs and handle escaped character literals 2026-11-14 13:29:49 +01:00
FredApps b02baeba43 Merge pull request #2274 from FredApps/fix/1455-format-painter
Apply Format Painter on single-click release (#1455)
2026-11-14 12:16:34 +01:00
FredApps 3c77297b83 Merge branch 'main' into fix/artcraft-feature-names-20261108
# Conflicts:
#	crates/engine/src/tests/wordart.rs
2026-11-14 11:36:36 +01:00
Dylan M. Taylor 60415e055c fix(xtask): allow wordcraft-formats -> wordcraft-docx in INTRA_LAYER_ORDER (#6618) 2026-11-14 02:51:29 -05:00
Dylan M. Taylor 0db15a1d5e Merge pull request #6617 from storytold/fix/alt-chunks-missing-pictures-total
fix(docx): fix main CI wordcraft-docx integration test failures
2026-11-14 01:16:29 -05:00
Dylan M. Taylor 33afe69094 fix(docx): bump craft-docx/wordmodel, fix missing_pictures total, and dedup Arc<Graphic> 2026-11-14 06:16:12 +00:00
Dylan M. Taylor 669d5df0b1 Merge pull request #6612 from storytold/codex/fix-ci
Fix CI formatting and clippy lints after craft-libs cutover
2026-11-14 00:44:06 -05:00
FredApps 953f43baed Merge branch 'main' into fix/1455-format-painter
# Conflicts:
#	ROADMAP.md
#	crates/ui-egui/src/tests.rs
2026-11-13 20:47:47 +01:00
FredApps acf5eb8727 Merge branch 'main' into fix/artcraft-feature-names-20261108
# Conflicts:
#	crates/engine/src/tests/wordart.rs
2026-11-13 20:47:26 +01:00
batistalucasvandQwen-Coder bd188c19d8 Tests: only closure errors mean the control peer closed (#6448)
CodeRabbit pointed out that read_line returns InvalidData for bytes that are not UTF-8 while the socket stays open, and the helper treated every non-timeout error as a close. closed_by_peer() now accepts only ConnectionReset, ConnectionAborted, NotConnected and BrokenPipe, and the regression test pins InvalidData, TimedOut and WouldBlock as still open; the new assertion fails without the stricter match.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2026-11-12 16:42:47 -03:00
batistalucasv 56a28f33b7 Merge remote-tracking branch 'upstream/main' into fix/control-server-reset-closed 2026-11-12 16:35:04 -03:00
batistalucasvandQwen-Coder cd4ab71552 Tests: a reset control connection counts as closed (Windows Print flake)
The Windows Print job on #6232 failed in a_silent_connection_is_closed: quiet.closed() only accepted end of stream, but Windows can deliver a close with nothing to read as a reset. The test binary finished in 0.81 s, so it was not the 5 s read timeout. closed_by_peer() now counts a reset, abort, not-connected or broken pipe as closed, and only a read timeout as still open; the new regression test fails before the fix with ConnectionReset. A loaded Windows runner can also take seconds to schedule the connection thread, so the silent test waits up to 20 s and still requires the close within 10 s (the production budget is 30 s).

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2026-11-12 16:13:42 -03:00
FredApps 6272c9a4da naming: fail display guard when a source root is missing 2026-11-08 22:35:59 +01:00
FredApps 172e56f12e naming: guard production labels against regressions 2026-11-08 22:35:09 +01:00
FredApps b66122f718 naming: use Diagram and Decorative Text labels 2026-11-08 21:39:00 +01:00
FredApps 4e1b6a71ab Merge remote-tracking branch 'up/main' into fix/1455-format-painter
# Conflicts:
#	ROADMAP.md
2026-10-31 18:24:01 +01:00
FredApps b2ec73926f style: format relocated Format Painter assertion 2026-10-30 12:23:48 +01:00
FredApps 7f90fd0bf1 Merge current main and retain Format Painter regression coverage 2026-10-30 12:20:31 +01:00
FredApps 4388fba5b2 Merge tested upstream main into fix/1455-format-painter
Preserve existing PR behavior and reconcile documentation.
Validated against upstream 2f6311cc37 with full local CI.
2026-10-18 04:43:51 +02:00
FredApps c341669dbd Merge main and add browser Copy Formatting alias 2026-10-16 08:42:14 +02:00
FredApps a4d28e2586 Apply Format Painter on single-click release (#1455) 2026-10-16 00:33:35 +02:00
383 changed files with 11488 additions and 53548 deletions
+5 -1
View File
@@ -1 +1,5 @@
craft-i18n.rev text eol=lf
# Text lives in the repository with LF. A Windows checkout once committed 50 files with CRLF
# (#6537) and `cargo fmt --check` still passed, so the gate could not see it. Normalise on add.
* text=auto
craft-i18n.rev text eol=lf
+3
View File
@@ -18,4 +18,7 @@ jobs:
sonarcloud:
# Tracked at @main so org-wide CI improvements propagate without PR churn.
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
with:
# Same craft-fonts commit as ci.yml: the UI glyph tests need its CJK and Arabic fonts.
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
secrets: inherit
+4
View File
@@ -138,3 +138,7 @@ Progress docs: `ROADMAP.md` (stage, headline numbers, progress log), `docs/targe
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
New workspace crates include `workspace = true` under `[lints]` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them.
## Shared-library reuse
Before implementing file formats, codecs, protocols or reusable UI components, check [storytold/craft-libs](https://github.com/storytold/craft-libs) and relevant open PRs; reuse or extend shared APIs instead of duplicating app-local implementations. Keep app-specific policy and adapters local, preserve behavior and format fidelity, security and resource limits, repository layering and regression tests, and document any shared-API gap rather than silently reducing functionality.
Generated
+349 -100
View File
@@ -155,13 +155,28 @@ version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
[[package]]
name = "alloc-no-stdlib"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
[[package]]
name = "alloc-stdlib"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
dependencies = [
"alloc-no-stdlib",
"alloc-no-stdlib 2.0.4",
]
[[package]]
name = "alloc-stdlib"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
dependencies = [
"alloc-no-stdlib 3.0.0",
]
[[package]]
@@ -210,15 +225,6 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
dependencies = [
"derive_arbitrary",
]
[[package]]
name = "arboard"
version = "3.7.0"
@@ -523,6 +529,12 @@ dependencies = [
"serde",
]
[[package]]
name = "bit_field"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1"
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -614,9 +626,9 @@ version = "8.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
"brotli-decompressor",
"alloc-no-stdlib 2.0.4",
"alloc-stdlib 0.2.4",
"brotli-decompressor 5.0.3",
]
[[package]]
@@ -625,8 +637,18 @@ version = "5.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
"alloc-no-stdlib 2.0.4",
"alloc-stdlib 0.2.4",
]
[[package]]
name = "brotli-decompressor"
version = "6.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f"
dependencies = [
"alloc-no-stdlib 3.0.0",
"alloc-stdlib 0.3.0",
]
[[package]]
@@ -1022,17 +1044,17 @@ dependencies = [
[[package]]
name = "craft-cfb"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
[[package]]
name = "craft-doc-binary"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"chrono",
"craft-cfb",
@@ -1048,7 +1070,7 @@ dependencies = [
[[package]]
name = "craft-docx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"base64 0.23.1",
"chrono",
@@ -1068,7 +1090,7 @@ dependencies = [
[[package]]
name = "craft-drawingml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"craft-xml",
"kurbo",
@@ -1079,7 +1101,7 @@ dependencies = [
[[package]]
name = "craft-flow"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"craft-wordmodel",
"image",
@@ -1122,6 +1144,19 @@ name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
[[package]]
name = "craft-html"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"craft-codepage",
"craft-flow",
"craft-math",
"craft-mime",
"craft-wordmodel",
"encoding_rs",
]
[[package]]
name = "craft-i18n"
version = "0.1.0"
@@ -1145,19 +1180,83 @@ dependencies = [
"writeable",
]
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"craft-jpeg",
"craft-metadata",
"exr",
"flate2",
"half",
"image",
"image-webp",
"jpeg-encoder",
"png",
"rayon",
"serde_json",
"thiserror 2.0.21",
"tiff",
"zune-core",
"zune-jpeg",
"zune-jpegxl",
]
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-latex"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"craft-flow",
"craft-math",
"craft-mime",
"craft-wordmodel",
]
[[package]]
name = "craft-markdown"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"craft-flow",
"craft-html",
"craft-wordmodel",
]
[[package]]
name = "craft-math"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"craft-xml",
"serde",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"brotli-decompressor 6.3.1",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c)",
"quick-xml 0.41.0",
"serde",
]
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"encoding_rs",
"image",
@@ -1165,10 +1264,58 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"chardetng",
"chrono",
"craft-codepage",
"encoding_rs",
]
[[package]]
name = "craft-odf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"aes",
"base64 0.23.1",
"chrono",
"craft-flow",
"craft-math",
"craft-metafile",
"craft-wordmodel",
"craft-xml",
"craft-zip",
"flate2",
"getrandom 0.3.4",
"hmac",
"image",
"js-sys",
"log",
"sha1 0.11.0",
"sha2 0.11.1",
"thiserror 2.0.21",
"zeroize",
]
[[package]]
name = "craft-ods"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"craft-odf",
"craft-sheet",
"craft-xml",
"thiserror 2.0.21",
]
[[package]]
name = "craft-offcrypto"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"aes",
"base64 0.23.1",
@@ -1185,7 +1332,7 @@ dependencies = [
[[package]]
name = "craft-opc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"craft-xml",
"craft-zip",
@@ -1230,7 +1377,7 @@ dependencies = [
[[package]]
name = "craft-rtf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"craft-codepage",
"craft-flow",
@@ -1240,6 +1387,29 @@ dependencies = [
"image",
]
[[package]]
name = "craft-sheet"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1#6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -1284,7 +1454,7 @@ dependencies = [
"verifysign",
"winreg",
"winsafe",
"zip 9.1.0",
"zip",
]
[[package]]
@@ -1329,7 +1499,7 @@ dependencies = [
[[package]]
name = "craft-wordmodel"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"base64 0.23.1",
"craft-math",
@@ -1340,10 +1510,35 @@ dependencies = [
"unicode-segmentation",
]
[[package]]
name = "craft-xls"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"craft-cfb",
"craft-sheet",
"md-5",
"miniz_oxide 0.9.1",
"sha1 0.10.7",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xlsx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"craft-drawingml",
"craft-opc",
"craft-sheet",
"craft-xml",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"quick-xml 0.41.0",
"thiserror 2.0.21",
@@ -1352,11 +1547,11 @@ dependencies = [
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip 9.1.0",
"zip",
]
[[package]]
@@ -1484,17 +1679,6 @@ version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
[[package]]
name = "derive_arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "dify"
version = "0.8.0"
@@ -1906,6 +2090,22 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "exr"
version = "1.74.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6"
dependencies = [
"bit_field",
"half",
"lebe",
"miniz_oxide 0.8.9",
"multiversion",
"rayon-core",
"smallvec",
"zune-inflate",
]
[[package]]
name = "fastrand"
version = "2.5.0"
@@ -2954,6 +3154,7 @@ dependencies = [
"moxcms",
"num-traits",
"png",
"qoi",
"tiff",
"zune-core",
"zune-jpeg",
@@ -3102,6 +3303,12 @@ dependencies = [
"libc",
]
[[package]]
name = "jpeg-encoder"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f"
[[package]]
name = "js-sys"
version = "0.3.106"
@@ -3185,6 +3392,12 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
[[package]]
name = "lebe"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
[[package]]
name = "libc"
version = "0.2.191"
@@ -3273,6 +3486,16 @@ version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
[[package]]
name = "md-5"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
"cfg-if",
"digest 0.10.7",
]
[[package]]
name = "memchr"
version = "2.8.3"
@@ -3344,6 +3567,28 @@ dependencies = [
"pxfm",
]
[[package]]
name = "multiversion"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076"
dependencies = [
"multiversion-macros",
"target-features",
]
[[package]]
name = "multiversion-macros"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
"target-features",
]
[[package]]
name = "multiversion_no_op"
version = "1.0.0"
@@ -4287,6 +4532,15 @@ version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "qoi"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
dependencies = [
"bytemuck",
]
[[package]]
name = "quick-error"
version = "1.2.3"
@@ -5564,6 +5818,12 @@ dependencies = [
"xattr",
]
[[package]]
name = "target-features"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5"
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -7010,16 +7270,17 @@ dependencies = [
name = "wordcraft-cli"
version = "0.18.1"
dependencies = [
"craft-zip",
"image",
"serde_json",
"sys-locale",
"wordcraft-doc",
"wordcraft-engine",
"wordcraft-fonts",
"wordcraft-geom",
"wordcraft-mcp",
"wordcraft-render",
"wordcraft-zotero",
"zip 3.0.0",
]
[[package]]
@@ -7060,15 +7321,15 @@ dependencies = [
"cfb",
"craft-docx",
"craft-wordmodel",
"craft-xml",
"craft-zip",
"image",
"log",
"proptest",
"quick-xml 0.41.0",
"serde",
"serde_json",
"wordcraft-doc",
"wordcraft-geom",
"zip 3.0.0",
]
[[package]]
@@ -7079,7 +7340,9 @@ dependencies = [
"chrono",
"craft-font-catalog",
"craft-font-store",
"craft-mime",
"craft-proof",
"craft-zip",
"encoding_rs",
"getrandom 0.3.4",
"image",
@@ -7102,14 +7365,13 @@ dependencies = [
"wordcraft-pdf",
"wordcraft-render",
"zeroize",
"zip 3.0.0",
]
[[package]]
name = "wordcraft-fonts"
version = "0.18.1"
dependencies = [
"brotli-decompressor",
"brotli-decompressor 5.0.3",
"harfrust 0.13.3",
"kurbo",
"log",
@@ -7123,35 +7385,38 @@ dependencies = [
name = "wordcraft-formats"
version = "0.18.1"
dependencies = [
"aes",
"base64 0.23.1",
"cfb",
"chardetng",
"chrono",
"craft-flow",
"craft-html",
"craft-image-codecs",
"craft-latex",
"craft-markdown",
"craft-math",
"craft-metafile",
"craft-mime",
"craft-odf",
"craft-ods",
"craft-rtf",
"craft-sheet",
"craft-wordmodel",
"craft-xls",
"craft-xlsx",
"craft-zip",
"encoding_rs",
"getrandom 0.3.4",
"hmac",
"image",
"js-sys",
"log",
"miniz_oxide 0.9.1",
"proptest",
"quick-xml 0.41.0",
"sha1 0.11.0",
"sha2 0.11.1",
"wordcraft-doc",
"wordcraft-docx",
"wordcraft-geom",
"wordcraft-metafile",
"zeroize",
"zip 3.0.0",
]
[[package]]
name = "wordcraft-geom"
version = "0.18.1"
dependencies = [
"craft-image-codecs",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1)",
"image",
"serde",
]
@@ -7160,6 +7425,7 @@ dependencies = [
name = "wordcraft-layout"
version = "0.18.1"
dependencies = [
"craft-metafile",
"craft-proof",
"image",
"js-sys",
@@ -7173,7 +7439,6 @@ dependencies = [
"wordcraft-doc",
"wordcraft-fonts",
"wordcraft-geom",
"wordcraft-metafile",
]
[[package]]
@@ -7188,19 +7453,12 @@ dependencies = [
"wordcraft-render",
]
[[package]]
name = "wordcraft-metafile"
version = "0.18.1"
dependencies = [
"kurbo",
"thiserror 2.0.21",
]
[[package]]
name = "wordcraft-pdf"
version = "0.18.1"
dependencies = [
"chrono",
"craft-metafile",
"craft-pdf",
"hayro-cmap",
"hayro-interpret",
@@ -7214,13 +7472,13 @@ dependencies = [
"wordcraft-fonts",
"wordcraft-geom",
"wordcraft-layout",
"wordcraft-metafile",
]
[[package]]
name = "wordcraft-render"
version = "0.18.1"
dependencies = [
"craft-metafile",
"image",
"log",
"vello_cpu",
@@ -7228,7 +7486,6 @@ dependencies = [
"wordcraft-fonts",
"wordcraft-geom",
"wordcraft-layout",
"wordcraft-metafile",
]
[[package]]
@@ -7242,6 +7499,7 @@ dependencies = [
"craft-ui",
"craft-update",
"craft-window",
"craft-zip",
"egui",
"egui_extras",
"egui_kittest",
@@ -7261,7 +7519,6 @@ dependencies = [
"wordcraft-render",
"wordcraft-zotero",
"zbus",
"zip 3.0.0",
]
[[package]]
@@ -7333,7 +7590,7 @@ version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "200a7b806377b65f1ff9a985874332f15357c87e5dd7855f35f06dade95b8b3d"
dependencies = [
"brotli-decompressor",
"brotli-decompressor 5.0.3",
"bytes",
"flate2",
]
@@ -7693,20 +7950,6 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "zip"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12598812502ed0105f607f941c386f43d441e00148fce9dec3ca5ffb0bde9308"
dependencies = [
"arbitrary",
"crc32fast",
"flate2",
"indexmap",
"memchr",
"zopfli",
]
[[package]]
name = "zip"
version = "9.1.0"
@@ -7735,24 +7978,21 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zune-core"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
[[package]]
name = "zune-inflate"
version = "0.2.54"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
dependencies = [
"simd-adler32",
]
[[package]]
name = "zune-jpeg"
version = "0.5.15"
@@ -7762,6 +8002,15 @@ dependencies = [
"zune-core",
]
[[package]]
name = "zune-jpegxl"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"
dependencies = [
"zune-core",
]
[[package]]
name = "zvariant"
version = "5.15.0"
+23 -8
View File
@@ -36,7 +36,7 @@ wordcraft-mcp = { path = "crates/mcp" }
wordcraft-zotero = { path = "crates/zotero" }
wordcraft-control-key = { path = "crates/control-key" }
wordcraft-ui-egui = { path = "crates/ui-egui" }
wordcraft-metafile = { path = "crates/metafile" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -66,16 +66,29 @@ wuff = "0.2.9"
# `forbid(unsafe_code)` in its default build, no_std-capable (builds for wasm), BSD-3-Clause/MIT.
brotli-decompressor = "5"
vello_cpu = "0.2"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "bmp", "tiff"] }
image = { version = "0.25", default-features = false }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", version = "=0.1.0", default-features = false, features = ["write"] }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "75c70fa6a786240eb853e6267e25fc445f510cd0", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "75c70fa6a786240eb853e6267e25fc445f510cd0", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "75c70fa6a786240eb853e6267e25fc445f510cd0", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "75c70fa6a786240eb853e6267e25fc445f510cd0", version = "=0.1.0" }
quick-xml = "0.41"
zip = { version = "3", default-features = false, features = ["deflate"] }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
miniz_oxide = "0.9"
cfb = "0.15"
@@ -110,6 +123,8 @@ arboard = { version = "3.7", default-features = false, features = ["wayland-data
[workspace.lints.rust]
unsafe_code = "forbid"
# cargo llvm-cov sets `--cfg coverage`; timing tests skip themselves under its instrumentation.
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(coverage)"] }
[workspace.lints.clippy]
cognitive_complexity = "deny"
+5 -3
View File
@@ -124,7 +124,7 @@ Every screenshot below is WordCraft itself, rendered offscreen by its own UI tes
| **References** | Table of contents, footnotes and endnotes, citations and bibliography (APA, MLA, Chicago, IEEE), captions, table of figures, cross-references, index, table of authorities |
| **Review** | Spelling and grammar with suggestions (English and Polish, by each run's language), thesaurus, word count, comments in margin balloons or a pane, track changes, accept/reject, compare documents, restrict editing, accessibility checker, document inspector |
| **Mailings** | Mail merge from CSV, merge fields, address block, greeting line, rules, preview, finish to a document; envelopes and labels |
| **View** | Print layout, web layout, draft, read mode, focus, zoom, one/multiple pages, page width, Navigation pane, rulers, gridlines, dark mode; interface in English, 简体中文, 繁體中文, 日本語, Português (Brasil), Español, Українська, Српски / Srpski, Eesti, Türkçe, Русский, Italiano, Deutsch, Polski, Čeština, Magyar, Français, Български, Tiếng Việt, 한국어, Svenska, Hrvatski, Nederlands, Dansk, Română, العربية (mirrored) or Slovenščina (follows the system language by default) |
| **View** | Print layout, web layout, draft, read mode, focus, zoom, one/multiple pages, page width, Navigation pane, rulers, gridlines, dark mode; interface in English, 简体中文, 繁體中文, 日本語, Português (Brasil), Español, Українська, Српски / Srpski, Eesti, Türkçe, Русский, Italiano, Deutsch, Polski, Čeština, Magyar, Français, Български, Tiếng Việt, 한국어, Svenska, Hrvatski, Nederlands, Dansk, Română, العربية (mirrored) Slovenščina or Bosanski (follows the system language by default) |
| **Files** | .docx read/write, legacy 97-2003 .doc import, PDF export, .odt, .rtf, .html, .md, .tex, .txt import/export, page images |
The honest picture, area by area, is in [ROADMAP.md](ROADMAP.md), the
@@ -451,8 +451,10 @@ Copyright (c) 2026 ArtCraft Team and the WordCraft contributors. Required notice
Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md).
The English spelling dictionary and hyphenation come from Grady Ward's public-domain Moby
Hyphenator II word list. Polish spelling reads the Hunspell `pl_PL` dictionary installed on the system (not bundled), as
English spelling first tries a matching Hunspell dictionary from the Dictionaries folder.
Otherwise it uses dialect-specific SCOWL 2026 dictionaries when built with language data;
without it, spelling falls back to system Hunspell dictionaries or Grady Ward's public-domain
Moby Hyphenator II word list. English hyphenation uses the Moby list and patterns trained from it. Polish spelling reads the Hunspell `pl_PL` dictionary installed on the system (not bundled), as
do Russian, Portuguese, Czech, Italian, Croatian and Turkish spelling (how to install them:
[docs/spelling-dictionaries.md](docs/spelling-dictionaries.md)), and
Polish hyphenation the TeX patterns by Hanna Kołodziejska, Bogusław Jackowski and Marek Ryćko (MIT
+15 -3
View File
File diff suppressed because one or more lines are too long
+2 -1
View File
@@ -24,5 +24,6 @@ sys-locale = "0.3"
[dev-dependencies]
wordcraft-fonts = { workspace = true }
wordcraft-geom = { workspace = true, features = ["image"] }
image = { workspace = true }
zip = { workspace = true }
craft-zip = { workspace = true }
+9 -3
View File
@@ -35,10 +35,11 @@ USAGE:
--strict writes nothing and exits 3 if a character on the
page can't be drawn or a picture is missing or undecodable
(report on stderr, as for convert --strict)
wordcraft-cli run [--file F | --template T] [--script FILE|-] --cmd 'id={json}' [--cmd …]
[--save OUT] [--print] [--author NAME]
wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …]
[--save OUT] [--page N] [--scale S] [--print] [--author NAME]
run commands headlessly, then save (--author names
who tracked changes and comments are by).
PNG saves use --page (1-based, default 1) and --scale (default 2).
--script runs a JSON file (- is stdin) first:
{\"file\"?, \"template\"?, \"commands\": [{\"command\": id,
\"params\"?: {…}} | id, …], \"save\"?: [OUT, …]}; save
@@ -602,6 +603,11 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
write_stdout(|o| writeln!(o, "{r}"))
}
"run" => {
for (i, arg) in rest.iter().enumerate() {
if arg == "--cmd" && rest.get(i + 1).is_none_or(|value| value.starts_with("--")) {
return Err("--cmd needs a value".into());
}
}
validate_options("run", &rest, RUN_OPTIONS)?;
let page = parse_page_arg("run", &rest)?;
let scale = parse_scale_arg("run", &rest)?;
@@ -635,7 +641,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
let mut i = 0;
while i < rest.len() {
if rest.get(i).map(String::as_str) == Some("--cmd") {
let spec = rest.get(i + 1).ok_or("--cmd needs a value")?;
let spec = rest.get(i + 1).filter(|value| !value.starts_with("--")).ok_or("--cmd needs a value")?;
let (id, params) = match spec.split_once('=') {
Some((id, p)) => {
(id.to_string(), serde_json::from_str::<Value>(p).map_err(|e| engine_error(format!("{id}: bad JSON params: {e}")))?)
+21
View File
@@ -497,6 +497,27 @@ fn command_line_template_wins_over_the_scripts_file() {
assert!(std::fs::read_to_string(&b).unwrap().contains("FROM FILE"));
}
#[test]
fn cmd_value_missing_is_reported() {
let missing = std::env::temp_dir().join(format!(
"wc-cli-missing-cmd-{}-{}.docx",
std::process::id(),
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos()
));
assert!(!missing.exists());
let missing = missing.to_string_lossy();
for argv in [
vec!["run", "--cmd"],
vec!["run", "--cmd", "--save", "out.docx"],
vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"],
vec!["run", "--cmd", "--bogus"],
vec!["run", "--cmd", "--file", &missing],
] {
assert_eq!(run(&args(&argv)), Err("--cmd needs a value".into()), "{argv:?}");
}
assert!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])).is_ok());
}
#[test]
fn script_value_missing_is_reported() {
let e = run(&args(&["run", "--script", "--cmd", "caret.docEnd"])).unwrap_err().to_string();
+8 -10
View File
@@ -1,6 +1,5 @@
//! `convert --strict` (#6005): exit 3 and a report when a PDF or PNG would silently lack a
//! character or a picture, nothing written; exit 0 otherwise.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
@@ -64,11 +63,11 @@ fn uncovered() -> char {
}
fn png() -> Vec<u8> {
let mut out = Vec::new();
image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 90, 200, 255]))
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
.unwrap();
out
wordcraft_geom::picture::encode_format(
&image::DynamicImage::from(image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 90, 200, 255])).clone()),
image::ImageFormat::Png,
)
.unwrap()
}
fn pic(rid: &str) -> String {
@@ -106,7 +105,7 @@ fn package(document: &str, document_rels: &str, extra: &[(&str, &[u8])]) -> Vec<
r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId1" Type="{REL}/officeDocument" Target="word/document.xml"/></Relationships>"#
);
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="png" ContentType="image/png"/><Default Extension="bin" ContentType="application/octet-stream"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zip = craft_zip::Writer::new();
let mut parts: Vec<(&str, &[u8])> = vec![
("[Content_Types].xml", types.as_bytes()),
("_rels/.rels", rels.as_bytes()),
@@ -115,10 +114,9 @@ fn package(document: &str, document_rels: &str, extra: &[(&str, &[u8])]) -> Vec<
];
parts.extend_from_slice(extra);
for (name, bytes) in parts {
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(bytes).unwrap();
zip.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zip.finish().unwrap().into_inner()
zip.finish().unwrap()
}
#[test]
+40 -4
View File
@@ -369,8 +369,11 @@ mod tests {
impl Conn {
fn open(port: u16) -> Self {
Self::open_within(port, Duration::from_secs(5))
}
fn open_within(port: u16, read_timeout: Duration) -> Self {
let s = TcpStream::connect(("127.0.0.1", port)).unwrap();
s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
s.set_read_timeout(Some(read_timeout)).unwrap();
Self(BufReader::new(s.try_clone().unwrap()), s)
}
fn send(&mut self, line: &str) {
@@ -388,7 +391,24 @@ mod tests {
/// The server closed the connection.
fn closed(&mut self) -> bool {
let mut r = String::new();
matches!(self.0.read_line(&mut r), Ok(0))
closed_by_peer(self.0.read_line(&mut r))
}
}
/// Whether a read means the peer closed the connection. End of stream does; so does a reset,
/// which is how Windows can deliver a close when the writer had nothing to read back (the
/// Windows Print job failed here). Any other error, such as `InvalidData` for bytes that are
/// not UTF-8, leaves the connection open.
fn closed_by_peer(read: std::io::Result<usize>) -> bool {
match read {
Ok(n) => n == 0,
Err(e) => matches!(
e.kind(),
std::io::ErrorKind::ConnectionReset
| std::io::ErrorKind::ConnectionAborted
| std::io::ErrorKind::NotConnected
| std::io::ErrorKind::BrokenPipe
),
}
}
@@ -473,13 +493,29 @@ mod tests {
assert!(rx.try_recv().is_err());
}
#[test]
fn only_closure_errors_mean_the_peer_closed() {
use std::io::{Error, ErrorKind};
assert!(closed_by_peer(Ok(0)), "end of stream");
for kind in [ErrorKind::ConnectionReset, ErrorKind::ConnectionAborted, ErrorKind::NotConnected, ErrorKind::BrokenPipe] {
assert!(closed_by_peer(Err(Error::new(kind, "closed"))), "{kind:?}");
}
assert!(!closed_by_peer(Ok(1)), "a reply arrived");
// Not UTF-8, a timeout or a would-block leave the socket open.
for kind in [ErrorKind::InvalidData, ErrorKind::TimedOut, ErrorKind::WouldBlock] {
assert!(!closed_by_peer(Err(Error::new(kind, "still open"))), "{kind:?}");
}
}
#[test]
fn a_silent_connection_is_closed() {
let (port, rx) = boot_with(Duration::from_millis(300));
let mut quiet = Conn::open(port);
// A loaded Windows CI runner can take seconds to schedule the connection thread. The
// production deadline is 30 s, so 10 s still proves the server's own budget fired.
let mut quiet = Conn::open_within(port, Duration::from_secs(20));
let t0 = Instant::now();
assert!(quiet.closed());
assert!(t0.elapsed() < Duration::from_secs(3));
assert!(t0.elapsed() < Duration::from_secs(10), "{:?}", t0.elapsed());
// After an authorised request the connection may stay idle.
let mut busy = Conn::open(port);
assert_eq!(busy.call(&format!(r#"{{"id":1,"method":"auth","key":"{KEY}"}}"#))["ok"], true);
+164 -16
View File
@@ -23,6 +23,7 @@ mod graphics;
mod logging;
#[cfg(all(unix, not(target_os = "macos")))]
mod portal_save;
mod prefs_merge;
mod print;
mod region;
#[cfg(target_os = "macos")]
@@ -222,31 +223,44 @@ fn user_dict_path() -> Option<std::path::PathBuf> {
wordcraft_control_key::settings_dir().map(|b| b.join(wordcraft_engine::Session::USER_DICT_FILE))
}
fn load_user_dictionary(app: &mut WordApp) {
if !prefs_enabled() {
return;
}
if let Some(p) = user_dict_path() {
wordcraft_proof::load_user_dictionary(&p);
app.session.user_dict_path = Some(p);
}
}
/// Runs without preferences (`WORDCRAFT_NO_PREFS`, agents' test runs) neither read nor write them.
fn prefs_enabled() -> bool {
std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
}
/// The preferences as this process last loaded or saved them, which `save_prefs` compares with
/// to write only what this process changed since (#3773, see `prefs_merge`).
static LOADED_PREFS: std::sync::Mutex<Option<serde_json::Value>> = std::sync::Mutex::new(None);
/// Apply the saved preferences (`ui.json`) and the user dictionary to `app`, and remember the
/// result for `save_prefs`. Runs without preferences neither read nor keep them.
fn load_prefs(app: &mut WordApp) {
if !prefs_enabled() {
return;
}
if let Some(p) = prefs_path()
&& let Ok(bytes) = std::fs::read(&p)
let loaded = load_prefs_from(app, prefs_path().as_deref(), user_dict_path());
if let Ok(mut slot) = LOADED_PREFS.lock() {
*slot = loaded;
}
}
/// Apply the preferences saved at `prefs` to `app`, then load the user dictionary at `dict`
/// (`custom-dictionary.txt`, #40), and give back the preferences as `prefs()` does after both:
/// the words only the dictionary file has are part of what was loaded, so a word another process
/// removes from `ui.json` isn't written back as one added here (#3773).
fn load_prefs_from(app: &mut WordApp, prefs: Option<&std::path::Path>, dict: Option<std::path::PathBuf>) -> Option<serde_json::Value> {
if let Some(p) = prefs
&& let Ok(bytes) = std::fs::read(p)
&& let Some(ui) = UiState::from_json(&bytes)
{
app.apply_prefs(ui);
}
if let Some(p) = dict {
wordcraft_proof::load_user_dictionary(&p);
app.session.user_dict_path = Some(p);
}
// As `prefs()` gives them back, so a setting nobody touched compares equal at exit.
serde_json::to_value(app.prefs()).ok()
}
/// Fonts the user added (#582) live in `fonts` in the settings folder: load them, and store fonts
@@ -332,6 +346,8 @@ fn x11_libraries() -> Result<(), String> {
if missing.is_empty() { Ok(()) } else { Err(missing.join("; ")) }
}
/// Write `app`'s preferences to `ui.json`, merged with what other processes saved since this one
/// loaded it (`merged_prefs`).
fn save_prefs(app: &WordApp) {
if let Err(e) = try_save_prefs(app) {
log::warn!("preferences: {e}");
@@ -348,11 +364,79 @@ fn try_save_prefs(app: &WordApp) -> Result<bool, String> {
if let Some(dir) = p.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
}
let bytes = serde_json::to_vec_pretty(&app.prefs()).map_err(|e| format!("cannot serialize: {e}"))?;
write_prefs(&p, &bytes).map_err(|e| format!("cannot save {}: {e}", p.display()))?;
let ours = serde_json::to_value(app.prefs()).map_err(|e| format!("cannot serialize: {e}"))?;
let mut base = LOADED_PREFS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
save_merged(&p, &mut base, ours)?;
Ok(true)
}
/// Writes `ours` to `path`, merged with what other WordCraft processes saved there since this one
/// loaded or saved `base` (`merged_prefs`), and makes `ours` the new `base`: a setting changed here
/// before this save and by another process after it then takes the other's value at the next save.
/// Holds `lock_prefs` from the read to the rename.
fn save_merged(path: &std::path::Path, base: &mut Option<serde_json::Value>, ours: serde_json::Value) -> Result<(), String> {
let _lock = lock_prefs(path);
let merged = merged_prefs(path, base.as_ref(), ours.clone());
let bytes = serde_json::to_vec_pretty(&merged).map_err(|e| format!("cannot serialize: {e}"))?;
write_prefs(path, &bytes).map_err(|e| format!("cannot save {}: {e}", path.display()))?;
*base = Some(ours);
Ok(())
}
/// `ours` with what other WordCraft processes saved to `path` since this one loaded or saved
/// `base`, for the settings this one left alone (#3773, see `prefs_merge`). `ours` as it is when
/// there's no `base`, or the file is missing or isn't preferences now.
fn merged_prefs(path: &std::path::Path, base: Option<&serde_json::Value>, ours: serde_json::Value) -> serde_json::Value {
let Some(base) = base else { return ours };
let disk = match std::fs::read(path) {
Ok(bytes) => prefs_merge::as_read(&bytes),
Err(e) => {
if e.kind() != std::io::ErrorKind::NotFound {
log::debug!("preferences: cannot read {} to merge, saving this process's: {e}", path.display());
}
return ours;
}
};
match disk {
Some(disk) => prefs_merge::merge(base, ours, &disk),
None => {
log::debug!("preferences: {} isn't preferences, saving this process's", path.display());
ours
}
}
}
/// How long a save waits for another process's save to finish before going ahead anyway: a save
/// takes milliseconds, and a process stuck holding the lock mustn't stop this one from saving.
const PREFS_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
/// An advisory lock beside `path` (`.ui.json.lock`), held while it is returned, so that two
/// processes saving at once (logging out closes every window together) take turns at reading,
/// merging and replacing `ui.json` instead of one losing the other's changes. `None` (save
/// unlocked) when the lock file can't be opened or the lock isn't free within [`PREFS_LOCK_WAIT`].
fn lock_prefs(path: &std::path::Path) -> Option<std::fs::File> {
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "ui.json".into());
let lock = path.with_file_name(format!(".{name}.lock"));
let file = match std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(&lock) {
Ok(f) => f,
Err(e) => {
log::debug!("preferences: cannot open {}, saving without it: {e}", lock.display());
return None;
}
};
let start = std::time::Instant::now();
loop {
match file.try_lock() {
Ok(()) => return Some(file),
Err(std::fs::TryLockError::WouldBlock) if start.elapsed() < PREFS_LOCK_WAIT => std::thread::sleep(std::time::Duration::from_millis(10)),
Err(e) => {
log::warn!("preferences: {} is held, saving without it: {e}", lock.display());
return None;
}
}
}
}
/// Writes `bytes` to a sibling temporary file and renames it over `path`, so a failed or
/// interrupted write leaves the previous preferences in place.
fn write_prefs(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
@@ -626,7 +710,6 @@ fn main() -> eframe::Result {
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);
// A region chosen in File › Options replaces the system's for the first blank
@@ -839,7 +922,72 @@ mod launch_arg_tests {
#[cfg(test)]
mod prefs_tests {
use super::write_prefs;
use serde_json::{Value, json};
use wordcraft_ui_egui::{UiState, theme::Appearance};
use super::{load_prefs_from, lock_prefs, prefs_merge, save_merged, write_prefs};
/// The preferences saved with `theme` (every other setting at its default).
fn with_theme(theme: &str) -> Value {
prefs_merge::as_read(&serde_json::to_vec(&json!({"theme": theme})).unwrap()).unwrap()
}
/// The theme the next process loads from `path`.
fn saved_theme(path: &std::path::Path) -> Appearance {
UiState::from_json(&std::fs::read(path).unwrap()).unwrap().theme
}
#[test]
fn a_setting_changed_by_another_process_after_a_save_here_keeps_its_value() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("ui.json");
std::fs::write(&path, serde_json::to_vec(&with_theme("light")).unwrap()).unwrap();
// A loads Light, switches to Dark and saves before exiting (taking a document off the
// recent list does).
let mut a = Some(with_theme("light"));
save_merged(&path, &mut a, with_theme("dark")).unwrap();
assert_eq!(saved_theme(&path), Appearance::Dark);
// B starts, loads Dark, switches to Light and exits.
save_merged(&path, &mut Some(with_theme("dark")), with_theme("light")).unwrap();
// A exits without touching the theme since its save: B's choice, made later, stays.
save_merged(&path, &mut a, with_theme("dark")).unwrap();
assert_eq!(saved_theme(&path), Appearance::Light);
}
#[test]
fn the_loaded_preferences_include_the_words_of_the_dictionary_file() {
// A word only `custom-dictionary.txt` has is loaded, not added here: if another process
// removes it from `ui.json`, this one mustn't write it back.
let dir = tempfile::tempdir().unwrap();
let (prefs, dict) = (dir.path().join("ui.json"), dir.path().join("custom-dictionary.txt"));
std::fs::write(&prefs, br#"{"dictionary": ["zqxinjson"]}"#).unwrap();
std::fs::write(&dict, "zqxinfile\n").unwrap();
let mut app = wordcraft_ui_egui::WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
let loaded = load_prefs_from(&mut app, Some(&prefs), Some(dict)).unwrap();
let words = loaded["dictionary"].as_array().unwrap();
for word in ["zqxinjson", "zqxinfile"] {
assert!(words.contains(&json!(word)), "{word}: {words:?}");
}
wordcraft_engine::proof::remove_word("zqxinjson");
wordcraft_engine::proof::remove_word("zqxinfile");
}
#[test]
fn a_save_waits_for_another_process_saving_at_the_same_moment() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("ui.json");
// Another process is between reading and replacing `ui.json`.
let held = lock_prefs(&path).expect("the lock is free");
let saver = {
let path = path.clone();
std::thread::spawn(move || save_merged(&path, &mut None, with_theme("dark")))
};
std::thread::sleep(std::time::Duration::from_millis(200));
assert!(!path.exists(), "saved while another process held the lock");
drop(held);
saver.join().unwrap().unwrap();
assert_eq!(saved_theme(&path), Appearance::Dark);
}
#[test]
fn failed_preferences_write_keeps_the_old_file_and_reports_the_error() {
+550
View File
@@ -0,0 +1,550 @@
//! Several WordCraft processes share one `ui.json` (opening a file from the file manager starts
//! another). Each reads it at start-up and writes it at exit (and when a change must survive a
//! crash, like taking a document off the recent list), so without a merge the process that writes
//! last writes back what it loaded and loses the others' changes (#3773).
//!
//! The policy: when saving, read `ui.json` again as this version reads it ([`as_read`]: a setting
//! of the wrong type reads as its default, and keys it doesn't know or reads only to migrate are
//! left out), and write it with only what this process changed since it last loaded or saved its
//! preferences (`base`). Every other setting keeps what the file holds now, including the absence
//! of one another process removed (a shortcut, a task pane's place).
//!
//! - A setting both changed takes this process's value.
//! - Groups of settings (editing options, AutoCorrect's switches, keyboard shortcuts, the ribbon,
//! task pane places) merge entry by entry ([`rule`]). Any other object is one setting: the
//! window's size and place, or one task pane's place, are never mixed from two processes.
//! - Lists of user entries (AutoCorrect entries by the text they replace, its exceptions, removed
//! built-in shortcuts, ribbon tabs by name, Quick Access Toolbar commands, caption labels, pens,
//! custom dictionary words) merge entry by entry too ([`merge_entries`]): entries either process
//! added are kept, entries either process removed stay removed, and an entry both changed takes
//! this process's version. A ribbon or toolbar left as it comes counts as its default entries.
//! - Recent lists (documents, symbols, colours, fonts) take the entries this process added or used
//! again first, then the file's, without duplicates, without the entries this process removed,
//! and within each list's limit ([`merge_recent`]).
//! - Any other list (the task panes' order, a floating pane's rectangle) is one setting.
//!
//! What this process changed is found by comparing with `base`, not by recording each change: a
//! setting changed and then changed back counts as untouched, so the file's value stays, and a
//! recent entry used again without moving (it was already first) counts as not used.
use std::collections::{HashMap, HashSet};
use serde_json::{Map, Value};
use wordcraft_engine::ribbon::{DEFAULT_QAT, RibbonLayout};
use wordcraft_ui_egui::{MAX_RECENT, MAX_RECENT_FONTS, UiState, colors, dialogs_insert};
/// Whether two entries of a recent list are the same entry.
type Same = fn(&Value, &Value) -> bool;
/// What tells an entry of a list of user entries from the others. Entries with the same key are
/// told apart by their order ([`ids`]).
type Key = fn(&Value) -> String;
/// How a setting this process changed merges with the file's.
#[derive(Clone, Copy)]
enum Rule {
/// A group of settings: each entry on its own.
Group,
/// A recent list, most recent first: how many entries it keeps, and when two are the same.
Recent(usize, Same),
/// A list of user entries: each entry on its own.
Entries(Key),
/// One setting: this process's value.
Whole,
}
/// The rule for the setting at `path` (`ui.json`'s keys from the top).
fn rule(path: &[&str]) -> Rule {
match path {
[] | ["editing" | "keyboard" | "ribbon" | "panePlaces"] | ["editing", "markup" | "marks" | "autocorrect"] | ["keyboard", "assigned"] => {
Rule::Group
}
["recent"] => Rule::Recent(MAX_RECENT, same_entry),
["recentSymbols"] => Rule::Recent(dialogs_insert::RECENT_SYMBOLS, same_entry),
["recentColors"] => Rule::Recent(colors::RECENT_MAX, same_entry),
["recentFonts"] => Rule::Recent(MAX_RECENT_FONTS, same_font),
["editing", "autocorrect", "entries"] => Rule::Entries(replaced_text),
["ribbon", "tabs"] => Rule::Entries(tab_name),
["editing", "autocorrect", "removed" | "exceptions" | "exceptionsRemoved" | "initialCapsExceptions"]
| ["keyboard", "removed"]
| ["ribbon", "qat"]
| ["captionLabels" | "inkPens" | "dictionary"] => Rule::Entries(whole_entry),
_ => Rule::Whole,
}
}
/// What a setting saved only when it isn't its default stands for when it is missing: the
/// default ribbon tabs and Quick Access Toolbar, so that two processes customizing them from the
/// default merge entry by entry.
fn when_missing(path: &[&str]) -> Option<Value> {
match path {
["ribbon", "tabs"] => serde_json::to_value(RibbonLayout::default().tabs()).ok(),
["ribbon", "qat"] => serde_json::to_value(DEFAULT_QAT).ok(),
_ => None,
}
}
/// Entries saved alike (colours are saved normalised, `colors::push_recent`).
fn same_entry(a: &Value, b: &Value) -> bool {
a == b
}
/// Font names ignoring case, as `push_recent_font` compares them.
fn same_font(a: &Value, b: &Value) -> bool {
match (a.as_str(), b.as_str()) {
(Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
_ => a == b,
}
}
/// The entry as saved.
fn whole_entry(v: &Value) -> String {
v.to_string()
}
/// An AutoCorrect entry `[from, to]` by the text it replaces.
fn replaced_text(v: &Value) -> String {
v.get(0).unwrap_or(v).to_string()
}
/// A ribbon tab by its name, ignoring case as the ribbon does.
fn tab_name(v: &Value) -> String {
v.get("name").and_then(Value::as_str).map_or_else(|| v.to_string(), str::to_lowercase)
}
/// `ui.json`'s bytes as this version reads them, saved again: `None` when they aren't
/// preferences at all.
pub fn as_read(bytes: &[u8]) -> Option<Value> {
serde_json::to_value(UiState::from_json(bytes)?).ok()
}
/// The preferences to write: `ours` (this process's, now), with every value it left as it was in
/// `base` (what it last loaded or saved) taken from `disk` (what `ui.json` holds now, [`as_read`]).
pub fn merge(base: &Value, ours: Value, disk: &Value) -> Value {
let fallback = ours.clone();
merge_setting(&mut Vec::new(), Some(base), Some(ours), Some(disk)).unwrap_or(fallback)
}
/// One setting, at `path`. `None` for a setting left out (this process removed it, or it left it
/// alone and another process removed it).
fn merge_setting(path: &mut Vec<String>, base: Option<&Value>, ours: Option<Value>, disk: Option<&Value>) -> Option<Value> {
if base == ours.as_ref() {
// Unchanged here: whatever the file holds now.
return disk.cloned();
}
let ours = ours?;
let keys: Vec<&str> = path.iter().map(String::as_str).collect();
Some(match (rule(&keys), ours, base, disk) {
(Rule::Group, Value::Object(ours), Some(Value::Object(base)), Some(Value::Object(disk))) => {
Value::Object(merge_group(path, base, ours, disk))
}
(Rule::Recent(cap, same), Value::Array(ours), Some(Value::Array(base)), Some(Value::Array(disk))) => {
Value::Array(merge_recent(base, ours, disk, cap, same))
}
(Rule::Entries(key), Value::Array(ours), Some(Value::Array(base)), Some(Value::Array(disk))) => {
Value::Array(merge_entries(base, &ours, disk, key))
}
(_, ours, ..) => ours,
})
}
/// A group of settings, entry by entry: this process's entries in their order, then those only
/// the file or `base` has.
fn merge_group(path: &mut Vec<String>, base: &Map<String, Value>, mut ours: Map<String, Value>, disk: &Map<String, Value>) -> Map<String, Value> {
let mut names: Vec<String> = ours.keys().cloned().collect();
let mut seen: HashSet<String> = names.iter().cloned().collect();
for k in disk.keys().chain(base.keys()) {
if seen.insert(k.clone()) {
names.push(k.clone());
}
}
let mut merged = Map::new();
for k in names {
path.push(k.clone());
let keys: Vec<&str> = path.iter().map(String::as_str).collect();
let missing = when_missing(&keys);
let base_v = base.get(&k).cloned().or_else(|| missing.clone());
let disk_v = disk.get(&k).cloned().or_else(|| missing.clone());
let ours_v = ours.remove(&k).or_else(|| missing.clone());
let v = merge_setting(path, base_v.as_ref(), ours_v, disk_v.as_ref());
path.pop();
// A setting saved only when it isn't its default is left out when it is.
if let Some(v) = v.filter(|v| Some(v) != missing.as_ref()) {
merged.insert(k, v);
}
}
merged
}
/// A list entry: its key, and how many entries before it have the same key.
type Id = (String, usize);
/// The entries of `list` told apart by `key`, in order.
fn ids(list: &[Value], key: Key) -> Vec<Id> {
let mut seen: HashMap<String, usize> = HashMap::new();
list.iter()
.map(|v| {
let k = key(v);
let n = seen.entry(k.clone()).or_default();
*n += 1;
(k, *n - 1)
})
.collect()
}
/// A list of user entries, entry by entry. An entry either process added is kept, one either
/// removed stays removed, and one this process changed takes its version (else the file's). The
/// order is this process's if it reordered the entries it loaded, else the file's; an entry only
/// the other list has goes after the entry it follows there.
fn merge_entries(base: &[Value], ours: &[Value], disk: &[Value], key: Key) -> Vec<Value> {
let (base_ids, ours_ids, disk_ids) = (ids(base, key), ids(ours, key), ids(disk, key));
let index = |ids: &[Id], list: &[Value]| -> HashMap<Id, Value> { ids.iter().cloned().zip(list.iter().cloned()).collect() };
let (b, o, d) = (index(&base_ids, base), index(&ours_ids, ours), index(&disk_ids, disk));
let value = |id: &Id| -> Option<&Value> {
match (b.get(id), o.get(id), d.get(id)) {
// Left alone here: the file's, or gone if the other process removed it.
(Some(b), Some(o), d) if b == o => d,
// Added or changed here.
(_, Some(o), _) => Some(o),
// Removed here.
(Some(_), None, _) => None,
// Added there.
(None, None, d) => d,
}
};
let common = |ids: &[Id], other: &HashMap<Id, Value>| -> Vec<Id> { ids.iter().filter(|id| other.contains_key(*id)).cloned().collect() };
let reordered = common(&ours_ids, &b) != common(&base_ids, &o);
let (first, second) = if reordered { (&ours_ids, &disk_ids) } else { (&disk_ids, &ours_ids) };
let in_first: HashSet<&Id> = first.iter().collect();
let kept: HashSet<&Id> = first.iter().filter(|id| value(id).is_some()).collect();
// Entries only `second` has, by the kept entry they follow there (`None`: at the start).
let mut after: HashMap<Option<&Id>, Vec<&Id>> = HashMap::new();
let mut anchor = None;
for id in second {
if kept.contains(id) {
anchor = Some(id);
} else if !in_first.contains(id) && value(id).is_some() {
after.entry(anchor).or_default().push(id);
}
}
let mut merged = Vec::new();
let mut emit = |ids: &[&Id]| merged.extend(ids.iter().filter_map(|id| value(id).cloned()));
emit(after.get(&None).map_or(&[], Vec::as_slice));
for id in first.iter().filter(|id| kept.contains(id)) {
emit(&[id]);
emit(after.get(&Some(id)).map_or(&[], Vec::as_slice));
}
merged
}
/// The entries this process put at the front of `ours` ([`touched_len`]), then `disk`'s, leaving
/// out what this process removed (in `base` but no longer in `ours`), without duplicates and at
/// most `cap` entries. Entries are told apart by `same`.
fn merge_recent(base: &[Value], ours: Vec<Value>, disk: &[Value], cap: usize, same: Same) -> Vec<Value> {
let has = |list: &[Value], v: &Value| list.iter().any(|x| same(x, v));
let removed = |v: &Value| has(base, v) && !has(&ours, v);
let touched = &ours[..touched_len(base, &ours, same)];
let mut merged: Vec<Value> = Vec::new();
for v in touched.iter().cloned().chain(disk.iter().filter(|v| !removed(v)).cloned()) {
if merged.len() == cap {
break;
}
if !has(&merged, &v) {
merged.push(v);
}
}
merged
}
/// How many of `ours`'s first entries this process added or used again. Each use moves an entry
/// to the front of a recent list, so what it left alone is a tail of `ours` in `base`'s order: the
/// longest such tail is untouched, and everything before it (new entries, and entries that moved
/// ahead of one loaded before them) was touched. A use that leaves the order as it was loaded
/// (the first entry used again) can't be told from no use, and merges as none.
fn touched_len(base: &[Value], ours: &[Value], same: Same) -> usize {
let mut end = base.len();
for (i, v) in ours.iter().enumerate().rev() {
match base[..end].iter().rposition(|b| same(b, v)) {
Some(at) => end = at,
None => return i + 1,
}
}
0
}
#[cfg(test)]
mod tests {
use serde_json::{Value, json};
use wordcraft_ui_egui::UiState;
use super::{as_read, merge};
/// The preferences a process holds after loading a `ui.json` with `settings` (every other
/// setting at its default), as it saves them.
fn prefs(settings: Value) -> Value {
as_read(&serde_json::to_vec(&settings).unwrap()).unwrap()
}
/// What the next process loads from the merged preferences.
fn reloaded(merged: &Value) -> UiState {
UiState::from_json(&serde_json::to_vec(merged).unwrap()).unwrap()
}
/// `ui.json` after B and then A, which both loaded `loaded`, save `b` and `a`.
fn b_then_a(loaded: &Value, b: Value, a: Value) -> Value {
let after_b = merge(loaded, b, loaded);
merge(loaded, a, &after_b)
}
#[test]
fn two_processes_keep_each_others_changes() {
// #3773: A and B both start from the same file.
let loaded =
json!({"theme": "light", "author": "Ann", "recent": ["a.docx", "b.docx"], "editing": {"smartQuotes": true, "autoCapitalize": true}});
// B changes the theme and opens c.docx, then exits first.
let b = json!({"theme": "dark", "author": "Ann", "recent": ["c.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": false, "autoCapitalize": true}});
// A changes the author name and opens d.docx, then exits.
let a = json!({"theme": "light", "author": "Bo", "recent": ["d.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": true, "autoCapitalize": false}});
assert_eq!(
b_then_a(&loaded, b, a),
json!({"theme": "dark", "author": "Bo", "recent": ["d.docx", "c.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": false, "autoCapitalize": false}})
);
}
#[test]
fn a_process_that_changed_nothing_writes_the_file_back_as_it_is() {
let loaded = json!({"theme": "light", "recent": ["a.docx"]});
let disk = json!({"theme": "dark", "recent": ["b.docx", "a.docx"]});
assert_eq!(merge(&loaded, loaded.clone(), &disk), disk);
}
#[test]
fn this_process_wins_a_setting_both_changed() {
let loaded = json!({"theme": "light"});
assert_eq!(merge(&loaded, json!({"theme": "system"}), &json!({"theme": "dark"})), json!({"theme": "system"}));
}
#[test]
fn a_setting_changed_and_changed_back_counts_as_untouched() {
// Changes are found by comparing with what was loaded: A switched to dark and back.
let loaded = json!({"theme": "light"});
assert_eq!(merge(&loaded, json!({"theme": "light"}), &json!({"theme": "dark"})), json!({"theme": "dark"}));
}
#[test]
fn a_recent_entry_removed_here_stays_removed() {
let loaded = json!({"recent": ["a.docx", "b.docx"]});
let ours = json!({"recent": ["b.docx"]});
let disk = json!({"recent": ["c.docx", "a.docx", "b.docx"]});
assert_eq!(merge(&loaded, ours, &disk), json!({"recent": ["c.docx", "b.docx"]}));
// Clear Recent clears what the other process had added too only if it was loaded here.
assert_eq!(merge(&loaded, json!({"recent": []}), &json!({"recent": ["c.docx", "a.docx", "b.docx"]})), json!({"recent": ["c.docx"]}));
}
#[test]
fn a_recent_entry_used_again_here_moves_to_the_front() {
// Applying a font already in Recently Used Fonts moves it to the front without adding one.
let loaded = json!({"recentFonts": ["A", "B"]});
assert_eq!(merge(&loaded, json!({"recentFonts": ["B", "A"]}), &loaded), json!({"recentFonts": ["B", "A"]}));
// Here C was used again, D opened and A removed; the other process used B again and added E.
let loaded = json!({"recent": ["a.docx", "b.docx", "c.docx"]});
let ours = json!({"recent": ["d.docx", "c.docx", "b.docx"]});
let disk = json!({"recent": ["e.docx", "b.docx", "a.docx", "c.docx"]});
assert_eq!(merge(&loaded, ours, &disk), json!({"recent": ["d.docx", "c.docx", "e.docx", "b.docx"]}));
// Entries this process only kept, in the order it loaded them, don't override the file's order.
let loaded = json!({"recentSymbols": ["x", "y", "z"]});
let ours = json!({"recentSymbols": ["w", "x", "z"]});
let disk = json!({"recentSymbols": ["z", "x", "y"]});
assert_eq!(merge(&loaded, ours, &disk), json!({"recentSymbols": ["w", "z", "x"]}));
}
#[test]
fn recent_fonts_are_one_entry_whatever_their_case() {
// Recently Used Fonts ignores case (`push_recent_font`): Arial applied here as `arial` and
// there as `ARIAL` is one entry, and doesn't push a distinct font out of the ten.
let loaded = json!({"recentFonts": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "Arial"]});
let ours = json!({"recentFonts": ["arial", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
let disk = json!({"recentFonts": ["ARIAL", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
assert_eq!(merge(&loaded, ours, &disk), json!({"recentFonts": ["arial", "A", "B", "C", "D", "E", "F", "G", "H", "I"]}));
// Other lists compare their entries as saved.
let loaded = json!({"recent": ["a.docx"]});
assert_eq!(merge(&loaded, json!({"recent": ["A.docx", "a.docx"]}), &loaded), json!({"recent": ["A.docx", "a.docx"]}));
}
#[test]
fn merged_recent_lists_keep_their_limit() {
// Recently Used Fonts keeps ten.
let loaded = json!({"recentFonts": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]});
let ours = json!({"recentFonts": ["X", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
let disk = json!({"recentFonts": ["Y", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
assert_eq!(merge(&loaded, ours, &disk), json!({"recentFonts": ["X", "Y", "A", "B", "C", "D", "E", "F", "G", "H"]}));
}
#[test]
fn a_bad_recent_entry_in_the_file_is_not_carried_forward() {
// A non-string entry makes the whole list read as empty (`options::lenient` falls back per
// setting). Merging it in would keep Recent empty in every later session; instead the
// list reads as this version reads it, and the next save heals it.
let loaded = prefs(json!({"recent": []}));
let ours = prefs(json!({"recent": ["x.docx"]}));
let disk = as_read(br#"{"recent": [{"path": "y.docx"}, "z.docx"]}"#).unwrap();
let merged = merge(&loaded, ours, &disk);
assert_eq!(merged["recent"], json!(["x.docx"]));
assert_eq!(loaded_recent(&merged), ["x.docx"]);
// Same for recent symbols.
let ours = prefs(json!({"recentSymbols": [{"ch": "§", "font": "Arial"}]}));
let disk = as_read(r#"{"recentSymbols": [{"ch": "¶", "font": "Arial"}, 7]}"#.as_bytes()).unwrap();
assert_eq!(reloaded(&merge(&prefs(json!({})), ours, &disk)).recent_symbols.len(), 1);
}
/// The recent documents the next process loads.
fn loaded_recent(merged: &Value) -> Vec<String> {
reloaded(merged).recent
}
#[test]
fn only_keys_this_version_writes_are_kept() {
// A legacy key read once to migrate, and junk, are not written back, even from the file.
let loaded = prefs(json!({"theme": "light"}));
let disk = as_read(br#"{"theme": "light", "dark": true, "interfaceSize": 120, "junk": 1}"#).unwrap();
let merged = merge(&loaded, loaded.clone(), &disk);
for gone in ["dark", "interfaceSize", "junk"] {
assert!(merged.get(gone).is_none(), "{gone}");
}
assert_eq!(merged["theme"], "light");
}
#[test]
fn a_file_another_process_damaged_gives_way_to_ours() {
let loaded = json!({"theme": "light", "recent": ["a.docx"]});
let ours = json!({"theme": "dark", "recent": ["a.docx"]});
// Not preferences at all: everything comes from this process.
assert_eq!(as_read(b"\"garbage\""), None);
assert_eq!(merge(&loaded, ours.clone(), &json!("garbage")), ours);
// A list replaced by something else keeps ours.
assert_eq!(merge(&loaded, json!({"recent": ["b.docx", "a.docx"]}), &json!({"recent": 3})), json!({"recent": ["b.docx", "a.docx"]}));
}
#[test]
fn autocorrect_entries_and_exceptions_from_both_processes_are_kept() {
let loaded = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "the"]], "exceptions": ["approx."]}}}));
// B adds an entry and an exception; A adds another entry, changes `teh`'s replacement and
// removes `approx.`. Each added entry follows the entry it was added after.
let b = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "the"], ["teh2", "the"]], "exceptions": ["approx.", "fig."]}}}));
let a = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "THE"], ["adn", "and"]], "exceptions": []}}}));
let ac = reloaded(&b_then_a(&loaded, b, a)).editing.autocorrect;
let entries: Vec<(&str, &str)> = ac.entries.iter().map(|(f, t)| (f.as_str(), t.as_str())).collect();
assert_eq!(entries, [("teh", "THE"), ("adn", "and"), ("teh2", "the")]);
assert_eq!(ac.exceptions, ["fig."]);
}
#[test]
fn keyboard_customisations_merge_key_by_key() {
let loaded = prefs(json!({"keyboard": {"assigned": {"Mod+Shift+K": "format.bold"}, "removed": []}}));
// B takes Ctrl+B off Bold and deletes its own Mod+Shift+K; A takes Ctrl+I off Italic and
// assigns Mod+Shift+J.
let b = prefs(json!({"keyboard": {"assigned": {}, "removed": ["Mod+B"]}}));
let a = prefs(json!({"keyboard": {"assigned": {"Mod+Shift+K": "format.bold", "Mod+Shift+J": "format.italic"}, "removed": ["Mod+I"]}}));
let keys = reloaded(&b_then_a(&loaded, b, a)).keyboard;
assert_eq!(keys.assigned.into_iter().collect::<Vec<_>>(), [("Mod+Shift+J".to_string(), "format.italic".to_string())]);
assert_eq!(keys.removed.into_iter().collect::<Vec<_>>(), ["Mod+B", "Mod+I"]);
}
#[test]
fn ribbon_changes_from_both_processes_are_kept() {
// Both start from the default ribbon. B hides Draw; A adds a custom tab after Home.
let loaded = prefs(json!({}));
let b = prefs(json!({"ribbon": {"tabs": hide(default_tabs(), "Draw")}}));
let mut a_tabs = default_tabs();
a_tabs.insert(1, json!({"name": "Mine", "custom": true}));
let a = prefs(json!({"ribbon": {"tabs": a_tabs}}));
let mut want = hide(default_tabs(), "Draw");
want.insert(1, json!({"name": "Mine", "custom": true}));
assert_eq!(serde_json::to_value(loaded_ribbon(&b_then_a(&loaded, b, a)).tabs).unwrap(), Value::Array(want));
}
#[test]
fn a_toolbar_reset_by_one_process_stays_reset() {
// B resets its custom Quick Access Toolbar to the default; A, which left it alone, adds a
// custom tab. The toolbar stays the default.
let loaded = prefs(json!({"ribbon": {"qat": ["file.save", "format.bold"]}}));
let b = prefs(json!({}));
let mut a_tabs = default_tabs();
a_tabs.push(json!({"name": "Mine", "custom": true}));
let a = prefs(json!({"ribbon": {"tabs": a_tabs, "qat": ["file.save", "format.bold"]}}));
let merged = b_then_a(&loaded, b, a);
assert!(merged["ribbon"].get("qat").is_none(), "{}", merged["ribbon"]);
let ribbon = loaded_ribbon(&merged);
assert_eq!(ribbon.qat, None);
assert!(ribbon.tabs.iter().any(|t| t.name == "Mine"));
// Two processes customizing the default toolbar: both commands, Save removed by A gone.
let loaded = prefs(json!({}));
let b = prefs(json!({"ribbon": {"qat": ["file.save", "edit.undo", "edit.redo", "format.bold"]}}));
let a = prefs(json!({"ribbon": {"qat": ["edit.undo", "edit.redo", "format.italic"]}}));
assert_eq!(loaded_ribbon(&b_then_a(&loaded, b, a)).qat.unwrap(), ["edit.undo", "edit.redo", "format.italic", "format.bold"]);
}
/// The default ribbon tabs, as saved once the ribbon is customized.
fn default_tabs() -> Vec<Value> {
serde_json::from_value(serde_json::to_value(wordcraft_engine::RibbonLayout::default().tabs()).unwrap()).unwrap()
}
/// `tabs` with the tab `name` hidden.
fn hide(mut tabs: Vec<Value>, name: &str) -> Vec<Value> {
for t in &mut tabs {
if t["name"] == name {
t["hidden"] = json!(true);
}
}
tabs
}
/// The ribbon the next process loads.
fn loaded_ribbon(merged: &Value) -> wordcraft_engine::RibbonLayout {
reloaded(merged).ribbon
}
#[test]
fn a_pane_order_changed_by_the_other_process_is_kept() {
// `paneOrder` is saved only when it isn't the default. B reorders; A leaves it alone and
// switches to dark.
let loaded = prefs(json!({}));
let order = json!(["styles", "navigation"]);
let b = prefs(json!({"paneOrder": order}));
let merged = b_then_a(&loaded, b, prefs(json!({"theme": "dark"})));
assert_eq!((&merged["paneOrder"], &merged["theme"]), (&order, &json!("dark")));
// B goes back to the default order; A, which loaded B's order and left it, doesn't bring
// it back.
let loaded = prefs(json!({"paneOrder": order}));
let merged = b_then_a(&loaded, prefs(json!({})), prefs(json!({"paneOrder": order, "theme": "dark"})));
assert!(merged.get("paneOrder").is_none(), "{merged}");
assert_eq!(merged["theme"], "dark");
}
#[test]
fn the_window_and_a_pane_place_are_one_setting_each() {
// A moved its window and B resized its own: the window is A's, not A's place with B's size.
let window = |x: f32, width: f32| json!({"window": {"position": [x, 10.0], "width": width, "height": 600.0, "maximized": false}});
let loaded = prefs(window(0.0, 800.0));
let merged = b_then_a(&loaded, prefs(window(0.0, 1000.0)), prefs(window(300.0, 800.0)));
assert_eq!(merged["window"], prefs(window(300.0, 800.0))["window"]);
}
#[test]
fn pens_labels_and_dictionary_words_from_both_processes_are_kept() {
let pen = |color: &str| json!({"kind": "pen", "color": color, "width": 1.0});
let loaded = prefs(json!({"inkPens": [pen("FF0000"), pen("FF0000")], "captionLabels": ["Plate"], "dictionary": ["foo", "bar"]}));
// B adds a third red pen, a label and a word; A adds a blue pen, removes `bar` and adds a
// label of its own. Identical pens stay apart, by their order.
let b = prefs(
json!({"inkPens": [pen("FF0000"), pen("FF0000"), pen("FF0000")], "captionLabels": ["Plate", "Chart"], "dictionary": ["foo", "bar", "baz"]}),
);
let a = prefs(json!({"inkPens": [pen("FF0000"), pen("FF0000"), pen("0000FF")], "captionLabels": ["Plate", "Map"], "dictionary": ["foo"]}));
let merged = b_then_a(&loaded, b, a);
let ui = reloaded(&merged);
let colors: Vec<String> = ui.ink_pens.iter().map(|p| serde_json::to_value(p).unwrap()["color"].as_str().unwrap().to_string()).collect();
assert_eq!(colors, ["FF0000", "FF0000", "0000FF", "FF0000"]);
assert_eq!(ui.caption_labels, ["Plate", "Map", "Chart"]);
assert_eq!(merged["dictionary"], json!(["foo", "baz"]));
}
}
+1 -1
View File
@@ -1 +1 @@
1e515422afdda2f317af430c1f9d68a5f83935b4
e56d26244bbac099bfd42e23fb12f78a4be418a7
+16 -1
View File
@@ -727,9 +727,16 @@ impl Document {
}
/// Split the paragraph at `pos`; returns the start of the new (second) paragraph.
///
/// A split after the first letters leaves the drop cap on the first paragraph only: the new
/// one is plain (Word: Enter makes a normal paragraph). A split at offset 0 is unchanged.
/// A drop cap that comes from a paragraph style, not the paragraph, is not cleared.
pub fn split_paragraph(&mut self, pos: &Pos) -> Result<Pos> {
let i = pos.path.last();
let tail = self.para_mut(pos.story, &pos.path)?.split_off(pos.off)?;
let mut tail = self.para_mut(pos.story, &pos.path)?.split_off(pos.off)?;
if pos.off > 0 {
clear_drop_cap(&mut tail.props);
}
let bl = self.container_mut(pos.story, &pos.path)?;
bl.insert((i + 1).min(bl.len()), para_block(tail));
Ok(Pos { story: pos.story, path: pos.path.with_last(i + 1), off: 0 })
@@ -1599,5 +1606,13 @@ impl Document {
}
}
/// Take the drop cap (and its options) off a paragraph's properties.
fn clear_drop_cap(props: &mut crate::props::ParaProps) {
props.drop_cap = None;
props.drop_cap_margin = None;
props.drop_cap_distance = None;
props.drop_cap_font = None;
}
#[cfg(test)]
mod tests;
+35
View File
@@ -988,3 +988,38 @@ fn insert_fragment_remaps_conflicting_media_keys() {
let remapped = para.objects.iter().find_map(|o| if let InlineObject::Image { media, .. } = o { Some(media.as_str()) } else { None }).unwrap();
assert_eq!(remapped, other_key);
}
/// #6788: splitting a paragraph after its first letters leaves the drop cap on the first
/// paragraph only; the new one (also when it is empty) is plain. A split at offset 0 is unchanged.
#[test]
fn split_paragraph_keeps_the_drop_cap_on_the_first_paragraph_only() {
let drop_cap = |d: &Document, i: usize| {
let p = d.body.get(i).and_then(|b| b.as_para()).map(|p| p.props.clone()).unwrap_or_default();
(p.drop_cap, p.drop_cap_margin, p.drop_cap_distance, p.drop_cap_font)
};
let capped = |text: &str| {
let mut d = doc(&[text]);
if let Ok(p) = d.para_mut(StoryRef::Body, &Path::top(0)) {
p.props.drop_cap = Some(3);
p.props.drop_cap_margin = Some(true);
p.props.drop_cap_distance = Some(4.0);
p.props.drop_cap_font = Some("Serif".into());
}
d
};
let cap = (Some(3), Some(true), Some(4.0), Some("Serif".to_string()));
let plain = (None, None, None, None);
let mut d = capped("Sugar and knowledge");
d.split_paragraph(&Pos::body(0, 10)).unwrap();
assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), plain.clone()));
let mut d = capped("Sugar");
d.split_paragraph(&Pos::body(0, 5)).unwrap();
assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), plain.clone()));
// At offset 0 nothing changes: both paragraphs keep the properties, as before.
let mut d = capped("Sugar");
d.split_paragraph(&Pos::body(0, 0)).unwrap();
assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), cap));
}
+2 -2
View File
@@ -94,8 +94,8 @@ pub use settings::{
COMPAT_MODE_CURRENT, CoreProps, CustomProp, DEFAULT_GRID, DEFAULT_HYPHENATION_ZONE, LEGACY_COMPAT_MODE, OdfLayout, PagePicture, Settings, Source,
THEME_COLORS, Watermark, Zoom, ZoomFit,
};
pub(crate) use text_walk::{PARA_WALK_DEPTH, walk_between};
pub use text_walk::{count_chars, count_chars_no_spaces, count_words};
pub(crate) use text_walk::walk_between;
pub use text_walk::{PARA_WALK_DEPTH, count_chars, count_chars_no_spaces, count_words};
/// A document.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+7
View File
@@ -137,6 +137,12 @@ pub struct Settings {
/// Keep contextual paragraph spacing inside legacy table cells (`allowSpaceOfSameStyleInTable`).
/// Word ignores the layout override in compatibility mode 15, but the flag still round-trips.
pub allow_space_of_same_style_in_table: bool,
/// `w:doNotSuppressIndentation` (a `.doc`'s `Copts.fWW11IndentRules`): Word 2003's indent
/// rules beside floating objects. An unnumbered paragraph's line starts right after a floating
/// object before it on the line, its own indent ignored (ECMA-376 Part 4 §14.8.3.12). Word 2013's
/// layout (compatibility mode 15) does not use it.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub do_not_suppress_indentation: bool,
/// Drawing grid spacing in points, across and down (View › Gridlines); ECMA-376's default is 1/8 inch.
pub grid_h: f32,
pub grid_v: f32,
@@ -319,6 +325,7 @@ impl Default for Settings {
sum_paragraph_spacing: false,
do_not_expand_shift_return: false,
allow_space_of_same_style_in_table: false,
do_not_suppress_indentation: false,
grid_h: DEFAULT_GRID,
grid_v: DEFAULT_GRID,
math: None,
+1 -1
View File
@@ -48,7 +48,7 @@ pub fn count_chars_no_spaces(s: &str) -> usize {
}
/// How deep in nested tables [`Document::para_paths`] goes: cells below this are skipped.
pub(crate) const PARA_WALK_DEPTH: usize = 16;
pub const PARA_WALK_DEPTH: usize = 16;
/// The note and text box stories an object shows, for `Document::reachable`.
pub(crate) fn notes_and_boxes(o: &InlineObject) -> Vec<(u32, &'static [PartKind])> {
+3 -3
View File
@@ -12,16 +12,16 @@ workspace = true
craft-docx = { workspace = true }
craft-wordmodel = { workspace = true }
wordcraft-doc = { workspace = true }
quick-xml = { workspace = true }
craft-xml = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
[dev-dependencies]
wordcraft-doc = { workspace = true, features = ["test-support"] }
wordcraft-geom = { workspace = true }
wordcraft-geom = { workspace = true, features = ["image"] }
base64 = { workspace = true }
cfb = { workspace = true }
log = { workspace = true }
proptest = { workspace = true }
image = { workspace = true }
zip = { workspace = true }
craft-zip = { workspace = true }
+6 -27
View File
@@ -19,39 +19,18 @@ pub(crate) const KIND: &str = "wordcraft-fit-v1";
/// Serialize `fit` as the custom XML store.
pub(crate) fn write(fit: &FitState) -> Result<Vec<u8>, DocxError> {
let json = serde_json::to_string(fit).map_err(|e| DocxError::Xml(e.to_string()))?;
let esc_json = quick_xml::escape::escape(&json);
let esc_json = craft_xml::esc(&json);
Ok(format!(r#"<?xml version="1.0" encoding="UTF-8"?><{ROOT} xmlns="{NS}" kind="{KIND}"><fitState>{}</fitState></{ROOT}>"#, esc_json).into_bytes())
}
/// Read the state from a custom XML part's bytes, if it is ours.
pub(crate) fn read_from_bytes(bytes: &[u8]) -> Option<FitState> {
let mut reader = quick_xml::Reader::from_reader(bytes);
let mut buf = Vec::new();
let mut is_our_kind = false;
loop {
match reader.read_event_into(&mut buf) {
Ok(quick_xml::events::Event::Start(ref e)) => {
let name = e.local_name();
if name.as_ref() == ROOT.as_bytes() {
for attr in e.attributes().flatten() {
if attr.key.local_name().as_ref() == b"kind" && attr.value.as_ref() == KIND.as_bytes() {
is_our_kind = true;
}
}
} else if name.as_ref() == b"fitState" && is_our_kind {
let text = reader.read_text(e.to_end().name()).ok()?;
let s = std::str::from_utf8(text.as_ref()).ok()?;
let unescaped = quick_xml::escape::unescape(s).ok()?;
return serde_json::from_str(&unescaped).ok();
}
}
Ok(quick_xml::events::Event::Eof) | Err(_) => break,
_ => {}
}
buf.clear();
let root = craft_xml::parse(bytes).ok()?;
if root.local() != ROOT || root.attr("kind") != Some(KIND) {
return None;
}
None
let text = root.child_text("fitState")?;
serde_json::from_str(text.as_ref()).ok()
}
#[cfg(test)]
+57 -26
View File
@@ -1,5 +1,6 @@
//! Bounded conversion between craft-wordmodel and WordCraft's document model.
use std::collections::HashMap;
use std::sync::Arc;
use craft_docx::DocxError;
@@ -29,24 +30,29 @@ where
// From Shared Model -> WordCraft Document
// ---------------------------------------------------------------------------
fn blocks_from_shared(source: craft_wordmodel::Blocks) -> Result<wordcraft_doc::Blocks, DocxError> {
type GraphicCache = HashMap<usize, Arc<wordcraft_doc::graphic::Graphic>>;
fn blocks_from_shared(source: craft_wordmodel::Blocks, graphics: &mut GraphicCache) -> Result<wordcraft_doc::Blocks, DocxError> {
source
.into_iter()
.map(|block| {
let block = Arc::try_unwrap(block).unwrap_or_else(|shared| (*shared).clone());
block_value_from_shared(block).map(Arc::new)
block_value_from_shared(block, graphics).map(Arc::new)
})
.collect()
}
fn block_value_from_shared(source: craft_wordmodel::Block) -> Result<wordcraft_doc::Block, DocxError> {
fn block_value_from_shared(source: craft_wordmodel::Block, graphics: &mut GraphicCache) -> Result<wordcraft_doc::Block, DocxError> {
match source {
craft_wordmodel::Block::Para(paragraph) => paragraph_value_from_shared(paragraph).map(wordcraft_doc::Block::Para),
craft_wordmodel::Block::Table(table) => table_value_from_shared(table).map(wordcraft_doc::Block::Table),
craft_wordmodel::Block::Para(paragraph) => paragraph_value_from_shared(paragraph, graphics).map(wordcraft_doc::Block::Para),
craft_wordmodel::Block::Table(table) => table_value_from_shared(table, graphics).map(wordcraft_doc::Block::Table),
}
}
fn paragraph_value_from_shared(source: craft_wordmodel::para::Paragraph) -> Result<wordcraft_doc::para::Paragraph, DocxError> {
fn paragraph_value_from_shared(
source: craft_wordmodel::para::Paragraph,
graphics: &mut GraphicCache,
) -> Result<wordcraft_doc::para::Paragraph, DocxError> {
let craft_wordmodel::para::Paragraph { text, runs, props, mark, objects, section, .. } = source;
let mut paragraph = wordcraft_doc::para::Paragraph::new();
paragraph.text = text;
@@ -54,12 +60,15 @@ fn paragraph_value_from_shared(source: craft_wordmodel::para::Paragraph) -> Resu
runs.into_iter().map(|run| Ok(wordcraft_doc::para::Run { len: run.len, props: convert(run.props)? })).collect::<Result<_, DocxError>>()?;
paragraph.props = convert(props)?;
paragraph.mark = convert(mark)?;
paragraph.objects = objects.into_iter().map(object_value_from_shared).collect::<Result<_, _>>()?;
paragraph.objects = objects.into_iter().map(|o| object_value_from_shared(o, graphics)).collect::<Result<_, _>>()?;
paragraph.section = section.map(|section| convert(*section).map(Box::new)).transpose()?;
Ok(paragraph)
}
fn object_value_from_shared(source: craft_wordmodel::para::InlineObject) -> Result<wordcraft_doc::para::InlineObject, DocxError> {
fn object_value_from_shared(
source: craft_wordmodel::para::InlineObject,
graphics: &mut GraphicCache,
) -> Result<wordcraft_doc::para::InlineObject, DocxError> {
use craft_wordmodel::para::InlineObject as Source;
use wordcraft_doc::para::InlineObject as Target;
@@ -74,49 +83,70 @@ fn object_value_from_shared(source: craft_wordmodel::para::InlineObject) -> Resu
fx: convert(fx)?,
ole: ole.map(|o| convert(Arc::try_unwrap(o).unwrap_or_else(|s| (*s).clone())).map(Arc::new)).transpose()?,
}),
Source::Graphic { w, h, alt, float, graphic } => {
let key = Arc::as_ptr(&graphic) as usize;
let graphic = if let Some(cached) = graphics.get(&key) {
Arc::clone(cached)
} else {
let converted: Arc<wordcraft_doc::graphic::Graphic> = Arc::new(convert(Arc::try_unwrap(graphic).unwrap_or_else(|s| (*s).clone()))?);
graphics.insert(key, Arc::clone(&converted));
converted
};
Ok(Target::Graphic { w, h, alt, float: convert(float)?, graphic })
}
Source::Group { w, h, float, ch_w, ch_h, children, canvas } => Ok(Target::Group {
w,
h,
float: convert(float)?,
ch_w,
ch_h,
children: children.into_iter().map(group_child_value_from_shared).collect::<Result<_, _>>()?,
children: children.into_iter().map(|c| group_child_value_from_shared(c, graphics)).collect::<Result<_, _>>()?,
canvas: canvas.map(convert).transpose()?,
}),
other => convert(other),
}
}
fn group_child_value_from_shared(source: craft_wordmodel::para::GroupChild) -> Result<wordcraft_doc::para::GroupChild, DocxError> {
Ok(wordcraft_doc::para::GroupChild { x: source.x, y: source.y, obj: object_value_from_shared(source.obj)? })
fn group_child_value_from_shared(
source: craft_wordmodel::para::GroupChild,
graphics: &mut GraphicCache,
) -> Result<wordcraft_doc::para::GroupChild, DocxError> {
Ok(wordcraft_doc::para::GroupChild { x: source.x, y: source.y, obj: object_value_from_shared(source.obj, graphics)? })
}
fn table_value_from_shared(source: craft_wordmodel::table::Table) -> Result<wordcraft_doc::table::Table, DocxError> {
fn table_value_from_shared(source: craft_wordmodel::table::Table, graphics: &mut GraphicCache) -> Result<wordcraft_doc::table::Table, DocxError> {
Ok(wordcraft_doc::table::Table {
props: convert(source.props)?,
grid: source.grid,
rows: source.rows.into_iter().map(row_value_from_shared).collect::<Result<_, _>>()?,
rows: source.rows.into_iter().map(|r| row_value_from_shared(r, graphics)).collect::<Result<_, _>>()?,
controls: convert(source.controls)?,
})
}
fn row_value_from_shared(source: craft_wordmodel::table::Row) -> Result<wordcraft_doc::table::Row, DocxError> {
fn row_value_from_shared(source: craft_wordmodel::table::Row, graphics: &mut GraphicCache) -> Result<wordcraft_doc::table::Row, DocxError> {
Ok(wordcraft_doc::table::Row {
props: convert(source.props)?,
cells: source.cells.into_iter().map(cell_value_from_shared).collect::<Result<_, _>>()?,
cells: source.cells.into_iter().map(|c| cell_value_from_shared(c, graphics)).collect::<Result<_, _>>()?,
controls: convert(source.controls)?,
})
}
fn cell_value_from_shared(source: craft_wordmodel::table::Cell) -> Result<wordcraft_doc::table::Cell, DocxError> {
Ok(wordcraft_doc::table::Cell { props: convert(source.props)?, blocks: blocks_from_shared(source.blocks)?, controls: convert(source.controls)? })
fn cell_value_from_shared(source: craft_wordmodel::table::Cell, graphics: &mut GraphicCache) -> Result<wordcraft_doc::table::Cell, DocxError> {
Ok(wordcraft_doc::table::Cell {
props: convert(source.props)?,
blocks: blocks_from_shared(source.blocks, graphics)?,
controls: convert(source.controls)?,
})
}
fn part_value_from_shared(source: craft_wordmodel::Part) -> Result<wordcraft_doc::Part, DocxError> {
Ok(wordcraft_doc::Part { kind: convert(source.kind)?, blocks: blocks_from_shared(source.blocks)?, body: convert(source.body)? })
fn part_value_from_shared(source: craft_wordmodel::Part, graphics: &mut GraphicCache) -> Result<wordcraft_doc::Part, DocxError> {
Ok(wordcraft_doc::Part { kind: convert(source.kind)?, blocks: blocks_from_shared(source.blocks, graphics)?, body: convert(source.body)? })
}
fn glossary_value_from_shared(source: craft_wordmodel::BuildingBlock) -> Result<wordcraft_doc::BuildingBlock, DocxError> {
fn glossary_value_from_shared(
source: craft_wordmodel::BuildingBlock,
graphics: &mut GraphicCache,
) -> Result<wordcraft_doc::BuildingBlock, DocxError> {
Ok(wordcraft_doc::BuildingBlock {
name: source.name,
gallery: source.gallery,
@@ -126,7 +156,7 @@ fn glossary_value_from_shared(source: craft_wordmodel::BuildingBlock) -> Result<
style: source.style,
types: source.types,
behaviors: source.behaviors,
blocks: blocks_from_shared(source.blocks)?,
blocks: blocks_from_shared(source.blocks, graphics)?,
})
}
@@ -138,7 +168,7 @@ fn missing_pictures_from_shared(source: craft_wordmodel::MissingPictures) -> Res
target.part_names = source.part_names;
target.media_parts = source.media_parts;
for item in source.list {
target.push(convert(item)?);
target.list.push(convert(item)?);
}
Ok(target)
}
@@ -176,10 +206,11 @@ pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcr
..
} = source;
let mut graphics = GraphicCache::new();
let mut document = wordcraft_doc::Document::new();
document.body = blocks_from_shared(body)?;
document.body = blocks_from_shared(body, &mut graphics)?;
document.last_section = convert(last_section)?;
document.parts = parts.into_iter().map(|(id, part)| Ok((id, part_value_from_shared(part)?))).collect::<Result<_, DocxError>>()?;
document.parts = parts.into_iter().map(|(id, part)| Ok((id, part_value_from_shared(part, &mut graphics)?))).collect::<Result<_, DocxError>>()?;
document.styles = Arc::new(convert((*styles).clone())?);
document.numbering = Arc::new(convert((*numbering).clone())?);
document.comments = convert(comments)?;
@@ -192,7 +223,7 @@ pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcr
document.endnote_separators = convert(endnote_separators)?;
document.media = media;
document.passthrough = passthrough;
document.glossary = glossary.into_iter().map(glossary_value_from_shared).collect::<Result<_, _>>()?;
document.glossary = glossary.into_iter().map(|g| glossary_value_from_shared(g, &mut graphics)).collect::<Result<_, _>>()?;
document.missing_pictures = missing_pictures_from_shared(missing_pictures)?;
document.fit_state = fit_state;
Ok(document)
@@ -344,7 +375,7 @@ fn missing_pictures_to_shared(source: &wordcraft_doc::MissingPictures) -> Result
target.part_names = source.part_names.clone();
target.media_parts = source.media_parts.clone();
for item in &source.list {
target.push(convert_ref(item)?);
target.list.push(convert_ref(item)?);
}
Ok(target)
}
+9 -14
View File
@@ -1,8 +1,6 @@
//! Alternative format chunks (`w:altChunk`, ECMA-376 §17.17.2.1): content in another format that
//! is brought in where the chunk stands. All markup here is synthetic.
use std::io::Write;
use wordcraft_doc::{Block, Document, InlineObject, StoryRef};
use wordcraft_docx::{AltChunk, ReadOptions, read, read_with};
@@ -46,12 +44,11 @@ fn package_styled(body: &str, chunk: Option<(&str, &str, &[u8])>, styles: Option
}
types.push_str(r#"<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#);
files.push(("[Content_Types].xml".into(), types.into_bytes()));
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in files {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(&bytes).unwrap();
zw.add(&name, &bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
const CHUNK: &str = r#"<w:altChunk r:id="rIdC"/>"#;
@@ -144,12 +141,11 @@ fn package_with_stories(body: &str, stories: &[(&str, &str, String)], chunk: Opt
if let Some(c) = chunk {
files.push(("word/afchunk.docx".into(), c.to_vec()));
}
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in files {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(&bytes).unwrap();
zw.add(&name, &bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
/// A paragraph `text` that comment `id` (in the file) is anchored around.
@@ -395,17 +391,16 @@ fn inner_with_dropped_pictures(n: usize, external: bool) -> Vec<u8> {
(0..n).map(image).collect::<String>()
);
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in [
("[Content_Types].xml", types.as_bytes()),
("_rels/.rels", ROOT_RELS.as_bytes()),
("word/document.xml", doc.as_bytes()),
("word/_rels/document.xml.rels", rels.as_bytes()),
] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
/// A picture the chunk's own reader dropped is the file's too (#6005), named by the chunk part.
+6 -10
View File
@@ -2,18 +2,15 @@
//! complex-script font, size, bold and italic, and the bidi language. Fixtures are hand-written
//! from ECMA-376 Part 1 §17.3.1.6 (bidi), §17.3.2 (run properties).
use std::io::{Read, Write};
use wordcraft_doc::props::{Align, CharProps, ParaProps};
use wordcraft_doc::{Document, Paragraph, para_block};
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in entries {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
/// A package whose body is `body`.
@@ -31,10 +28,9 @@ fn paras(d: &Document) -> Vec<&Paragraph> {
/// `word/document.xml` of a written package.
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
/// Persian text with a ZWNJ (نیم‌فاصله), Persian digits, Latin and punctuation.
+3 -5
View File
@@ -6,7 +6,6 @@
//! direction changes and marks the right-to-left pieces `w:rtl`, as Word does with text typed
//! in a right-to-left paragraph.
use std::io::Read;
use std::sync::Arc;
use wordcraft_doc::props::CharProps;
@@ -14,10 +13,9 @@ use wordcraft_doc::{Document, Paragraph, para_block};
/// `word/document.xml` of a written package.
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
/// The runs of the first paragraph of `xml`: (has `w:rtl`, text with `w:br` as `\n`).
+6 -10
View File
@@ -2,8 +2,6 @@
//! `thinThickThinLargeGap`, ECMA-376 Part 1 §17.18.2 ST_Border) on paragraphs, table cells and
//! pages: written back as read, not as a single line. Fixtures are hand-written from the spec.
use std::io::{Read, Write};
use wordcraft_doc::props::BorderStyle;
const LINES: [(&str, BorderStyle); 9] = [
@@ -23,19 +21,17 @@ fn docx(body: &str) -> Vec<u8> {
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
fn side(name: &str, val: &str) -> String {
@@ -1,12 +1,10 @@
//! Original partial-cell-margin fixture (ECMA-376 §17.4.69).
use std::io::{Cursor, Read, Write};
fn fixture() -> Vec<u8> {
let document = r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:tbl><w:tblPr><w:tblCellMar><w:top w:w="55" w:type="dxa"/><w:left w:w="45" w:type="dxa"/><w:bottom w:w="55" w:type="dxa"/><w:right w:w="55" w:type="dxa"/></w:tblCellMar></w:tblPr><w:tblGrid><w:gridCol w:w="4320"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcMar><w:left w:w="0" w:type="dxa"/></w:tcMar></w:tcPr><w:p><w:r><w:t>Point</w:t></w:r></w:p></w:tc></w:tr></w:tbl></w:body></w:document>"#;
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
zip.start_file("word/document.xml", zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(document.as_bytes()).unwrap();
zip.finish().unwrap().into_inner()
let mut zip = craft_zip::Writer::new();
zip.add("word/document.xml", document.as_bytes(), craft_zip::Compression::Deflated).unwrap();
zip.finish().unwrap()
}
#[test]
@@ -19,9 +17,8 @@ fn partial_margin_stays_partial() {
let reopened = wordcraft_docx::read(&bytes).unwrap();
let cell = &reopened.body[0].as_table().unwrap().rows[0].cells[0];
assert_eq!(cell.props.resolved_margins([6.0, 7.0, 8.0, 9.0]), [6.0, 0.0, 8.0, 9.0]);
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
let mut xml = String::new();
zip.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
let margins = xml.split("<w:tcMar>").nth(1).unwrap().split("</w:tcMar>").next().unwrap();
assert!(margins.contains("<w:left w:w=\"0\""));
assert!(!margins.contains("<w:top"));
+11 -15
View File
@@ -2,18 +2,15 @@
//! `w:ind` `w:firstLineChars`, `w:hangingChars`, `w:leftChars` and `w:rightChars`, in hundredths
//! of a character. Fixtures are hand-written.
use std::io::{Read, Write};
use wordcraft_doc::Document;
use wordcraft_doc::props::ParaProps;
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in entries {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
/// A package whose body is `body`.
@@ -44,9 +41,9 @@ fn character_indents_read_and_round_trip() {
// Hostile values are clamped or dropped.
assert_eq!((p[3].indent_first_chars, p[3].indent_left_chars), (Some(1584.0), None));
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_docx::write(&d).unwrap())).unwrap();
let mut xml = String::new();
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
let _z_bytes = wordcraft_docx::write(&d).unwrap();
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
for attr in [r#"w:firstLineChars="200""#, r#"w:leftChars="150""#, r#"w:rightChars="50""#, r#"w:hangingChars="100""#, r#"w:firstLineChars="0""#] {
assert!(xml.contains(attr), "{attr} missing: {xml}");
}
@@ -71,9 +68,9 @@ fn automatic_spacing_reads_and_round_trips() {
assert_eq!((rp.space_before, rp.space_after, rp.before_auto), (14.0, 14.0, true), "automatic spacing is 14 pt");
assert_eq!(d.styles.resolve_para(&p[2]).space_after, 5.0);
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_docx::write(&d).unwrap())).unwrap();
let mut xml = String::new();
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
let _z_bytes = wordcraft_docx::write(&d).unwrap();
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
for attr in [r#"w:beforeAutospacing="1""#, r#"w:afterAutospacing="1""#, r#"w:beforeAutospacing="0""#] {
assert!(xml.contains(attr), "{attr} missing");
}
@@ -90,9 +87,8 @@ fn adjust_right_indent_is_preserved() {
assert_eq!(props(&d).iter().map(|p| p.adjust_right_indent).collect::<Vec<_>>(), [Some(false), Some(true), None]);
for _ in 0..2 {
let out = wordcraft_docx::write(&d).unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(out.clone())).unwrap();
let mut xml = String::new();
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
let mut z = craft_zip::Archive::open(&out, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"<w:adjustRightInd w:val="0""#), "explicit false was lost: {xml}");
assert!(xml.contains("<w:adjustRightInd/>"), "explicit true was lost: {xml}");
let tags = ["<w:adjustRightInd", "<w:snapToGrid", "<w:spacing", "<w:ind"];
+8 -13
View File
@@ -2,8 +2,6 @@
//! multi-paragraph results, and custom document properties round-trip. All markup here is
//! synthetic, written from ECMA-376.
use std::io::Write;
use wordcraft_doc::para::OBJ;
use wordcraft_doc::{CharProps, Document, InlineObject, Path, StoryRef};
use wordcraft_docx::{read, write};
@@ -16,12 +14,11 @@ const CITE_B: &str = r#""citationItems":[{"id":7,"uris":["http://zotero.org/user
const BIBL: &str = r#" ADDIN ZOTERO_BIBL {"uncited":[],"omitted":[],"custom":[]} CSL_BIBLIOGRAPHY "#;
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in entries {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
fn fld(kind: &str) -> String {
@@ -129,10 +126,9 @@ fn count(xml: &str, kind: &str) -> usize {
}
fn document_xml(docx: &[u8]) -> String {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
let mut s = String::new();
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut s).unwrap();
s
let mut z = craft_zip::Archive::open(docx, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
#[test]
@@ -174,9 +170,8 @@ fn custom_property_bookmark_links_survive_saves_and_value_edits() {
let before = d.custom_props.clone();
for _ in 0..2 {
let out = write(&d).unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&out)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut z.by_name("docProps/custom.xml").unwrap(), &mut xml).unwrap();
let mut z = craft_zip::Archive::open(&out, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(z.read("docProps/custom.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"linkTarget="OriginalBookmark""#), "{xml}");
assert!(xml.contains(r#"linkTarget="RawBookmark""#), "{xml}");
assert_eq!(xml.matches("linkTarget=").count(), 2, "unlinked properties stay unlinked");
@@ -1,7 +1,6 @@
//! Independent complex-script formatting through style inheritance and DOCX round trips.
//! Synthetic packages, written here; no external documents or installed fonts are needed.
use std::io::Write;
use wordcraft_doc::props::CharProps;
use wordcraft_doc::{Document, Paragraph, Run};
@@ -13,17 +12,16 @@ fn package(run: &str, defaults: &str, styles: &str, paragraph_style: &str) -> Ve
r#"<w:document {ns}><w:body><w:p><w:pPr>{paragraph_style}<w:bidi/></w:pPr><w:r><w:rPr>{run}</w:rPr><w:t>שָׁלוֹם ABC 123</w:t></w:r></w:p></w:body></w:document>"#
);
let styles = format!("<w:styles {ns}><w:docDefaults><w:rPrDefault><w:rPr>{defaults}</w:rPr></w:rPrDefault></w:docDefaults>{styles}</w:styles>");
let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut z = craft_zip::Writer::new();
for (name, data) in [
("_rels/.rels", root),
("word/_rels/document.xml.rels", rels),
("word/document.xml", document.as_str()),
("word/styles.xml", styles.as_str()),
] {
z.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
z.write_all(data.as_bytes()).unwrap();
z.add(name, data.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
z.finish().unwrap().into_inner()
z.finish().unwrap()
}
fn paragraph(d: &Document) -> &Paragraph {
@@ -180,9 +178,14 @@ fn split_runs_add_no_phantom_tracked_formatting() {
let run = r#"<w:sz w:val="24"/><w:rPrChange w:id="7" w:author="Synthetic Author" w:date="2026-10-11T00:00:00Z"><w:rPr><w:sz w:val="20"/></w:rPr></w:rPrChange>"#;
let d = wordcraft_docx::read(&package(run, "", "", "")).unwrap();
let bytes = wordcraft_docx::write(&d).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap().by_name("word/document.xml").unwrap(), &mut xml)
.unwrap();
let xml = String::from_utf8(
craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 })
.unwrap()
.read("word/document.xml", 16 << 20)
.unwrap()
.unwrap(),
)
.unwrap();
let runs: Vec<&str> = xml.split("<w:r>").skip(1).map(|r| r.split("</w:r>").next().unwrap()).collect();
assert!(runs.len() >= 2, "the mixed run is split: {xml}");
assert!(runs.iter().any(|r| r.contains("<w:rtl/>")), "{xml}");
@@ -136,18 +136,14 @@ fn the_controls_are_written_where_they_were() {
/// The names of the parts of a package, in the order they are in it.
fn part_names(bytes: &[u8]) -> Vec<String> {
let z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("zip");
z.file_names().map(str::to_string).collect()
let z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).expect("zip");
z.names().map(|n| n.into_owned()).collect()
}
/// The body of the document part of a package.
fn document_body(bytes: &[u8]) -> String {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("zip");
let mut xml = String::new();
{
use std::io::Read;
z.by_name("word/document.xml").expect("the document part").read_to_string(&mut xml).expect("read");
}
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).expect("zip");
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).expect("read").expect("the document part")).expect("utf8");
let rest = xml.split_once("<w:body>").expect("the body").1;
let body = rest.split_once("</w:body>").expect("the end of the body").0;
format!("<w:body>{body}</w:body>")
+6 -10
View File
@@ -2,8 +2,6 @@
//! All markup here is synthetic, written from ECMA-376 §17.5.2 and the [MS-DOCX] `w14`/`w15`
//! extensions.
use std::io::Write;
use wordcraft_doc::control::{ControlKind, ControlLock, ListItem};
use wordcraft_doc::{Block, ContentControl, Document, StoryRef};
use wordcraft_docx::{read, write};
@@ -13,12 +11,11 @@ const ROOT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.o
fn package(body: &str) -> Vec<u8> {
let doc = format!(r#"<w:document {NS}><w:body>{body}</w:body></w:document>"#);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in [("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", doc.as_bytes())] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
fn t(s: &str) -> String {
@@ -90,10 +87,9 @@ fn form() -> Vec<u8> {
}
fn document_xml(docx: &[u8]) -> String {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
let mut s = String::new();
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut s).unwrap();
s
let mut z = craft_zip::Archive::open(docx, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
fn controls(d: &Document) -> Vec<ContentControl> {
+7 -11
View File
@@ -1,6 +1,5 @@
//! Original synthetic custom XML stores, written from the public OOXML package contract.
use std::collections::BTreeMap;
use std::io::{Cursor, Read, Write};
use wordcraft_doc::{Path, StoryRef};
const REL_NS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
@@ -36,22 +35,19 @@ fn fixture() -> BTreeMap<String, Vec<u8>> {
}
fn zip(parts: &BTreeMap<String, Vec<u8>>) -> Vec<u8> {
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
let mut z = craft_zip::Writer::new();
for (name, bytes) in parts {
z.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
z.write_all(bytes).unwrap();
z.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
z.finish().unwrap().into_inner()
z.finish().unwrap()
}
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
let mut parts = BTreeMap::new();
for i in 0..z.len() {
let mut f = z.by_index(i).unwrap();
let name = f.name().to_string();
let mut bytes = Vec::new();
f.read_to_end(&mut bytes).unwrap();
for name in names {
let bytes = z.read(&name, 16 << 20).unwrap().unwrap();
assert!(parts.insert(name, bytes).is_none(), "duplicate ZIP entry");
}
parts
+6 -9
View File
@@ -1,7 +1,6 @@
//! The document default font size (`w:docDefaults/w:rPrDefault/w:rPr/w:sz`) across a save and
//! reopen. An unset default is resolved as `DEFAULT_FONT_SIZE`; the writer must say so, because
//! the reader reads an omitted size as 10 pt.
use std::io::{Read, Write};
use std::sync::Arc;
use wordcraft_doc::Document;
use wordcraft_doc::props::{CharProps, DEFAULT_FONT_SIZE};
@@ -9,10 +8,9 @@ fn resolved(d: &Document) -> f32 {
d.styles.resolve_char(None, &CharProps::default()).size
}
fn styles_xml(bytes: &[u8]) -> String {
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut xml = String::new();
archive.by_name("word/styles.xml").unwrap().read_to_string(&mut xml).unwrap();
xml
let mut archive = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(archive.read("word/styles.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
fn defaults(xml: &str) -> &str {
xml.split("<w:docDefaults>").nth(1).unwrap().split("</w:docDefaults>").next().unwrap()
@@ -47,12 +45,11 @@ fn a_file_that_omits_the_default_size_is_still_read_as_ten_points() {
let doc = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>x</w:t></w:r></w:p></w:body></w:document>"#;
let styles = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:docDefaults><w:rPrDefault><w:rPr/></w:rPrDefault></w:docDefaults></w:styles>"#;
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, body) in [("_rels/.rels", root), ("word/document.xml", doc), ("word/_rels/document.xml.rels", rels), ("word/styles.xml", styles)] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(body.as_bytes()).unwrap();
zw.add(name, body.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
let d = wordcraft_docx::read(&zw.finish().unwrap().into_inner()).unwrap();
let d = wordcraft_docx::read(&zw.finish().unwrap()).unwrap();
assert_eq!(d.styles.default_chr.size, Some(10.0));
}
#[test]
+4 -5
View File
@@ -1,5 +1,5 @@
//! Original nested-picture controls. No native output or external assets are embedded.
use std::{io::Write, sync::Arc};
use std::sync::Arc;
use wordcraft_doc::para::{Anchor, CanvasStyle, Float, GroupChild, ShapeKind, Wrap};
use wordcraft_doc::props::Rgb;
use wordcraft_doc::{Document, InlineObject, Paragraph, PartKind, Pos, StoryRef, TextBody, para_block};
@@ -71,7 +71,7 @@ fn check_box(doc: &Document) {
assert_eq!(doc.media[media].as_slice(), BLUE_PNG);
}
fn package(xml: &str) -> Vec<u8> {
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zip = craft_zip::Writer::new();
let rels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let docrels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdIsolationRect" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/isolation-blue.png"/></Relationships>"#;
let types = br#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="png" ContentType="image/png"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
@@ -82,10 +82,9 @@ fn package(xml: &str) -> Vec<u8> {
("word/_rels/document.xml.rels", docrels.as_slice()),
("word/media/isolation-blue.png", BLUE_PNG),
] {
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(bytes).unwrap();
zip.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zip.finish().unwrap().into_inner()
zip.finish().unwrap()
}
#[test]
fn model_nested_picture_roundtrip() {
+6 -10
View File
@@ -1,8 +1,6 @@
//! East Asian language attribute of a run (`w:lang/@w:eastAsia`, ISO/IEC 29500-1 §17.3.2.20).
//! Verifies that saving DOCX documents preserves the East Asian language of `w:lang`.
use std::io::{Read, Write};
fn docx(body: &str, styles: Option<&str>) -> Vec<u8> {
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
@@ -17,19 +15,17 @@ fn docx(body: &str, styles: Option<&str>) -> Vec<u8> {
format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{s}</w:styles>"#),
));
}
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, xml) in &parts {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(xml.as_bytes()).unwrap();
zw.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
}
fn run(text: &str, rpr: &str) -> String {
+6 -10
View File
@@ -2,8 +2,6 @@
//! two lines in one and horizontal in vertical are read and saved again. Fixtures are
//! hand-written from the spec.
use std::io::{Read, Write};
use wordcraft_doc::props::{CombineBrackets, EastAsianLayout};
fn docx(body: &str, styles: Option<&str>) -> Vec<u8> {
@@ -20,19 +18,17 @@ fn docx(body: &str, styles: Option<&str>) -> Vec<u8> {
format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{s}</w:styles>"#),
));
}
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, xml) in &parts {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(xml.as_bytes()).unwrap();
zw.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
}
fn run(text: &str, rpr: &str) -> String {
+5 -9
View File
@@ -1,8 +1,6 @@
//! Emphasis marks (`w:em`, ISO/IEC 29500-1 §17.3.2.12: Font › Emphasis mark) are read and
//! saved again, in their place in `w:rPr`. Fixtures are hand-written from the spec.
use std::io::{Read, Write};
use wordcraft_doc::props::EmphasisMark;
fn docx(body: &str) -> Vec<u8> {
@@ -10,12 +8,11 @@ fn docx(body: &str) -> Vec<u8> {
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, xml) in [("_rels/.rels", root.to_string()), ("word/document.xml", doc)] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(xml.as_bytes()).unwrap();
zw.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
fn marks(d: &wordcraft_doc::Document) -> Vec<Option<EmphasisMark>> {
@@ -39,9 +36,8 @@ fn emphasis_marks_are_read_and_saved() {
let want = [EmphasisMark::Dot, EmphasisMark::Comma, EmphasisMark::Circle, EmphasisMark::UnderDot, EmphasisMark::None].map(Some);
assert_eq!(marks(&d), want);
let saved = wordcraft_docx::write(&d).unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&saved)).unwrap();
let mut xml = String::new();
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
let mut z = craft_zip::Archive::open(&saved, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
// In its place: after w:cs, before w:lang.
assert!(xml.contains(r#"<w:cs/><w:em w:val="underDot"/><w:lang"#), "{xml}");
assert_eq!(marks(&wordcraft_docx::read(&saved).unwrap()), want);
+37 -51
View File
@@ -1,6 +1,5 @@
//! Hand-written minimal WordprocessingML fixtures (written for these tests from the spec).
use std::io::Write;
use std::sync::Arc;
use wordcraft_doc::fill::Fill;
@@ -13,12 +12,11 @@ const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingm
const ROOT_RELS: &str = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
pub fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in entries {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
fn rels(list: &[(&str, &str, &str)]) -> String {
@@ -1483,10 +1481,9 @@ fn word_watermark_survives_save() {
};
assert_eq!(headers(&d2), headers(&d));
assert_eq!(headers(&d2)[0], vec!["Header label".to_string(), "Second line".to_string()]);
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
for name in ["word/header1.xml", "word/header2.xml"] {
let mut xml = String::new();
std::io::Read::read_to_string(&mut z.by_name(name).unwrap(), &mut xml).unwrap();
let xml = String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap();
assert_eq!(xml.matches("<v:shape ").count(), 1, "{name}");
}
@@ -1662,14 +1659,12 @@ fn chart_docx() -> Vec<u8> {
/// The entries of a zip, by name.
fn unzip(bytes: &[u8]) -> std::collections::BTreeMap<String, Vec<u8>> {
use std::io::Read;
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
let mut out = std::collections::BTreeMap::new();
for i in 0..z.len() {
let mut f = z.by_index(i).unwrap();
let mut b = Vec::new();
f.read_to_end(&mut b).unwrap();
out.insert(f.name().to_string(), b);
for name in names {
let b = z.read(&name, 16 << 20).unwrap().unwrap();
out.insert(name, b);
}
out
}
@@ -2174,9 +2169,8 @@ fn formatting_revisions_round_trip() {
// Written back: each change is the last child of its parent, and reads back the same.
let bytes = wordcraft_docx::write(&d).unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
for (tag, parent) in [
("w:rPrChange", "</w:rPr></w:rPrChange></w:rPr>"),
("w:pPrChange", "</w:pPr></w:pPrChange></w:pPr>"),
@@ -2432,10 +2426,9 @@ fn note_separators_and_continuation_notice_round_trip() {
let out = wordcraft_docx::write(&d).unwrap();
let part = |name: &str| {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&out)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut z.by_name(name).unwrap(), &mut xml).unwrap();
xml
let mut z = craft_zip::Archive::open(&out, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
};
let notes = part("word/footnotes.xml");
for (kind, id) in [("separator", "-1"), ("continuationSeparator", "0"), ("continuationNotice", "1")] {
@@ -2558,13 +2551,12 @@ fn includepicture_keeps_its_embedded_picture() {
let bytes = docx(&format!("<w:p>{field}</w:p><w:sectPr/>"), &[("rIdPic", "image", "media/picture.png")], &[]);
let bytes = {
// `docx` takes text parts; add the picture bytes as a binary part.
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
let mut entries: Vec<(String, Vec<u8>)> = Vec::new();
for i in 0..z.len() {
let mut f = z.by_index(i).unwrap();
let mut v = Vec::new();
std::io::Read::read_to_end(&mut f, &mut v).unwrap();
entries.push((f.name().to_string(), v));
for name in names {
let v = z.read(&name, 16 << 20).unwrap().unwrap();
entries.push((name, v));
}
entries.push(("word/media/picture.png".into(), png.to_vec()));
zip(&entries.iter().map(|(n, v)| (n.as_str(), v.as_slice())).collect::<Vec<_>>())
@@ -2678,9 +2670,8 @@ fn rounded_rectangle_corners_are_read_and_saved() {
let d = read_body(&format!("<w:p>{body}</w:p>"));
assert_eq!(corners(&d), expected);
let bytes = wordcraft_docx::write(&d).unwrap();
let mut xml = String::new();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val 3565"/></a:avLst></a:prstGeom>"#), "{xml}");
assert_eq!(corners(&wordcraft_docx::read(&bytes).unwrap()), expected);
}
@@ -2745,9 +2736,8 @@ fn arrowheads_keep_their_kind_and_size() {
let d = read_body(&format!("<w:p>{body}</w:p>"));
assert_eq!(ends(&d), expected);
let bytes = wordcraft_docx::write(&d).unwrap();
let mut xml = String::new();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"<a:headEnd type="stealth" w="sm" len="lg"/>"#), "{xml}");
assert!(xml.contains(r#"<a:tailEnd type="diamond" w="lg" len="sm"/>"#), "{xml}");
assert_eq!(ends(&wordcraft_docx::read(&bytes).unwrap()), expected);
@@ -2870,9 +2860,8 @@ fn vml_preset_shape_survives_saving() {
r##"<w:p><w:r><w:pict>{VML_RIGHT_ARROW_TYPE}<v:shape type="#_x0000_t13" style="width:120pt;height:40pt" fillcolor="#ffa500"/></w:pict></w:r></w:p>"##
);
let saved = wordcraft_docx::write(&read_body(&body)).unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(saved.as_slice())).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut z = craft_zip::Archive::open(&saved, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"prst="rightArrow""#), "{xml}");
let again = wordcraft_docx::read(&saved).unwrap();
assert!(
@@ -2898,9 +2887,8 @@ fn vml_preset_shape_survives_saving() {
fn vml_nearest_preset_shape_survives_saving() {
let body = r##"<w:p><w:r><w:pict><v:shape type="#_x0000_t66" style="width:60pt;height:20pt" fillcolor="#ffa500"/></w:pict></w:r></w:p>"##;
let saved = wordcraft_docx::write(&read_body(body)).unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(saved.as_slice())).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut z = craft_zip::Archive::open(&saved, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"prst="leftArrow""#), "{xml}");
let again = wordcraft_docx::read(&saved).unwrap();
assert!(
@@ -3047,9 +3035,8 @@ fn drawingml_shapes_survive_saving() {
let again = wordcraft_docx::read(&bytes).unwrap();
assert_eq!(shapes(&again), read, "every shape survives saving");
assert_eq!(part_text_box(&again), "Floating text box");
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes[..])).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut z = craft_zip::Archive::open(&bytes[..], craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert_eq!(xml.matches("<wps:wsp>").count(), 7);
for p in presets.iter().chain(&["straightConnector1"]) {
assert!(xml.contains(&format!(r#"<a:prstGeom prst="{p}">"#)), "{p} is written");
@@ -4044,20 +4031,19 @@ fn hyperlink_with_empty_target_is_no_link() {
let bytes = docx(body, &[("rId2", "hyperlink", "https://x"), ("rId3", "hyperlink", "mailto:a@example.com")], &[]);
// Blank the first target and mark the mailto one external (the helper only does that for http).
let bytes = {
let mut zr = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut zr = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let names: Vec<String> = zr.names().map(|n| n.into_owned()).collect();
let mut entries = Vec::new();
for i in 0..zr.len() {
let mut f = zr.by_index(i).unwrap();
let mut buf = Vec::new();
std::io::Read::read_to_end(&mut f, &mut buf).unwrap();
if f.name() == "word/_rels/document.xml.rels" {
for name in names {
let mut buf = zr.read(&name, 16 << 20).unwrap().unwrap();
if name == "word/_rels/document.xml.rels" {
buf = String::from_utf8(buf)
.unwrap()
.replace("Target=\"https://x\"", "Target=\"\"")
.replace("a@example.com\"", "a@example.com\" TargetMode=\"External\"")
.into_bytes();
}
entries.push((f.name().to_string(), buf));
entries.push((name, buf));
}
let refs: Vec<(&str, &[u8])> = entries.iter().map(|(n, b)| (n.as_str(), b.as_slice())).collect();
zip(&refs)
@@ -4575,7 +4561,7 @@ fn shape_gradients_and_transparency_are_read_and_survive_saving() {
rot_with_shape: false,
flip: GradientFlip::Xy,
}))),
Some(grad(vec![stop(0.0, ph, 0.0), stop(100.0, Rgb(0x20, 0x40, 0x60), 0.0)], lin(90.0, false), true)),
Some(grad(vec![stop(0.0, ph, 0.0), stop(100.0, Rgb(44, 92, 140), 0.0)], lin(90.0, false), true)),
Some(grad(vec![stop(0.0, ph, 0.0), stop(100.0, black, 0.0)], centre, true)),
None,
];
+8 -11
View File
@@ -3,7 +3,6 @@
//! edited. Hand-written fixtures (from the spec), no files produced by Word.
use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::sync::Arc;
use wordcraft_doc::{Block, BuildingBlock, CharProps, Document, Paragraph, para_block};
@@ -15,22 +14,20 @@ const GLOSSARY_REL: &str = "http://schemas.openxmlformats.org/officeDocument/200
const GLOSSARY_CT: &str = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml";
fn zip(entries: &[(&str, Vec<u8>)]) -> Vec<u8> {
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in entries {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
let mut out = BTreeMap::new();
for i in 0..z.len() {
let mut f = z.by_index(i).unwrap();
let mut b = Vec::new();
f.read_to_end(&mut b).unwrap();
assert!(out.insert(f.name().to_string(), b).is_none(), "duplicate part {}", f.name());
for name in names {
let b = z.read(&name, 16 << 20).unwrap().unwrap();
assert!(out.insert(name.clone(), b).is_none(), "duplicate part {name}");
}
out
}
+3 -5
View File
@@ -2,7 +2,6 @@
//! `styles.xml` doesn't write `w:outlineLvl` (some producers leave it out). Word for Windows,
//! opening such a file, reports `OutlineLevel` 1 and 2 for "heading 1" and "heading 2" (whatever
//! their style ids) and body text for a custom style.
use std::io::Write;
use wordcraft_doc::Paragraph;
const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
@@ -12,14 +11,13 @@ fn package(styles: &str, body: &str) -> Vec<u8> {
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
let doc = format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="{W}"><w:body>{body}</w:body></w:document>"#);
let styles = format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="{W}">{styles}</w:styles>"#);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, body) in
[("_rels/.rels", root), ("word/document.xml", doc.as_str()), ("word/_rels/document.xml.rels", rels), ("word/styles.xml", styles.as_str())]
{
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(body.as_bytes()).unwrap();
zw.add(name, body.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
fn para(style: &str, text: &str) -> String {
+6 -10
View File
@@ -2,8 +2,6 @@
//! (`w:gridBefore`/`w:wBefore`, `w:gridAfter`/`w:wAfter`) through a round trip (#1174). All
//! markup here is synthetic, written from ECMA-376 §17.16.17 and §17.4.14-17.
use std::io::Write;
use wordcraft_doc::Block;
use wordcraft_docx::{read, write};
@@ -12,19 +10,17 @@ const ROOT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.o
fn package(body: &str) -> Vec<u8> {
let doc = format!(r#"<w:document {NS}><w:body>{body}</w:body></w:document>"#);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in [("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", doc.as_bytes())] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
fn document_xml(docx: &[u8]) -> String {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
let mut s = String::new();
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut s).unwrap();
s
let mut z = craft_zip::Archive::open(docx, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
fn resaved(body: &str) -> String {
+5 -8
View File
@@ -1,7 +1,6 @@
//! OpenType ligatures (`w14:ligatures`, [MS-DOCX]) in document defaults, styles and runs.
//! Synthetic packages, written here; no external documents are needed.
use std::io::Write;
use wordcraft_doc::props::Ligatures;
use wordcraft_doc::{Document, Paragraph};
@@ -15,17 +14,16 @@ fn package(defaults: &str, style: &str, run: &str) -> Vec<u8> {
let styles = format!(
r#"<w:styles {ns}><w:docDefaults><w:rPrDefault><w:rPr>{defaults}</w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="character" w:styleId="Fancy"><w:name w:val="Fancy"/><w:rPr>{style}</w:rPr></w:style></w:styles>"#
);
let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut z = craft_zip::Writer::new();
for (name, data) in [
("_rels/.rels", root),
("word/_rels/document.xml.rels", rels),
("word/document.xml", document.as_str()),
("word/styles.xml", styles.as_str()),
] {
z.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
z.write_all(data.as_bytes()).unwrap();
z.add(name, data.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
z.finish().unwrap().into_inner()
z.finish().unwrap()
}
fn paragraph(d: &Document) -> &Paragraph {
@@ -68,10 +66,9 @@ fn unknown_ligature_values_are_ignored() {
fn no_ligatures_element_without_a_value() {
let d = wordcraft_docx::read(&package("", "", "")).unwrap();
let out = wordcraft_docx::write(&d).unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(out)).unwrap();
let mut z = craft_zip::Archive::open(&out, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
for name in ["word/document.xml", "word/styles.xml"] {
let mut xml = String::new();
std::io::Read::read_to_string(&mut z.by_name(name).unwrap(), &mut xml).unwrap();
let xml = String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap();
assert!(!xml.contains("ligatures"), "{name}");
}
}
+3 -4
View File
@@ -9,12 +9,11 @@ const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingm
const ROOT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in entries {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
fn doc_zip(document_xml: &[u8]) -> Vec<u8> {
+8 -10
View File
@@ -1,18 +1,17 @@
//! Pictures dropped at open are recorded for strict export (#6005): a missing part, an external
//! target and a link-only picture (ECMA-376 Part 1 §20.1.8.13 `a:blip` `r:embed`/`r:link`).
//! Original synthetic packages; nothing is fetched, the reader has no network code.
use std::io::Write;
use wordcraft_doc::{Document, InlineObject, MissingPictureReason};
const 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:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:v="urn:schemas-microsoft-com:vml""#;
const REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
fn png() -> Vec<u8> {
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
wordcraft_geom::picture::encode_format(
&image::DynamicImage::from(image::RgbaImage::from_pixel(2, 2, image::Rgba([20, 90, 200, 255])).clone()),
image::ImageFormat::Png,
)
.unwrap()
}
fn blip(attrs: &str) -> String {
@@ -32,10 +31,9 @@ fn package(body: &str, doc_rels: &str, header: Option<(&str, &str)>, extra: &[(&
);
let drels = format!(r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{doc_rels}{hdr_rel}</Relationships>"#);
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="png" ContentType="image/png"/><Default Extension="bin" ContentType="application/octet-stream"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zip = craft_zip::Writer::new();
let mut put = |name: &str, bytes: &[u8]| {
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(bytes).unwrap();
zip.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
};
put("[Content_Types].xml", types.as_bytes());
put("_rels/.rels", rels.as_bytes());
@@ -51,7 +49,7 @@ fn package(body: &str, doc_rels: &str, header: Option<(&str, &str)>, extra: &[(&
for (n, b) in extra {
put(n, b);
}
zip.finish().unwrap().into_inner()
zip.finish().unwrap()
}
fn image_rel(id: &str, target: &str, external: bool) -> String {
+6 -10
View File
@@ -2,8 +2,6 @@
//! saved, even when it holds a single paragraph (ECMA-376 §17.5.2.29-30; [MS-DOCX] `w15`
//! repeating sections, which must wrap whole paragraphs or rows). All markup here is synthetic.
use std::io::Write;
use wordcraft_doc::{ContentControl, Document, StoryRef};
use wordcraft_docx::{read, write};
@@ -13,19 +11,17 @@ const ROOT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.o
fn package(body: &str) -> Vec<u8> {
let doc = format!(r#"<w:document {NS}><w:body>{body}</w:body></w:document>"#);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in [("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", doc.as_bytes())] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
fn document_xml(docx: &[u8]) -> String {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
let mut s = String::new();
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut s).unwrap();
s
let mut z = craft_zip::Archive::open(docx, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
fn t(s: &str) -> String {
+8 -11
View File
@@ -4,7 +4,6 @@
//! and extended properties. Hand-written fixtures (from the spec), no files produced by Word.
use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::sync::Arc;
const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
@@ -12,22 +11,20 @@ const R_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relati
const REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
fn zip(entries: &[(&str, Vec<u8>)]) -> Vec<u8> {
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in entries {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
let mut out = BTreeMap::new();
for i in 0..z.len() {
let mut f = z.by_index(i).unwrap();
let mut b = Vec::new();
f.read_to_end(&mut b).unwrap();
assert!(out.insert(f.name().to_string(), b).is_none(), "duplicate part {}", f.name());
for name in names {
let b = z.read(&name, 16 << 20).unwrap().unwrap();
assert!(out.insert(name.clone(), b).is_none(), "duplicate part {name}");
}
out
}
+18 -24
View File
@@ -1,16 +1,15 @@
//! 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<u8> {
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
wordcraft_geom::picture::encode_format(
&image::DynamicImage::from(image::RgbaImage::from_pixel(2, 2, image::Rgba([20, 90, 200, 255])).clone()),
image::ImageFormat::Png,
)
.unwrap()
}
/// An inline picture's run; `link` goes into its `wp:docPr`.
@@ -28,7 +27,7 @@ fn package(body: &str) -> Vec<u8> {
let doc_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdPic" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/square.png"/><Relationship Id="rIdWeb" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/picture" TargetMode="External"/><Relationship Id="rIdRun" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/run" TargetMode="External"/></Relationships>"#;
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="png" ContentType="image/png"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
let png = png();
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zip = craft_zip::Writer::new();
for (name, bytes) in [
("[Content_Types].xml", types.as_bytes()),
("_rels/.rels", rels.as_bytes()),
@@ -36,10 +35,9 @@ fn package(body: &str) -> Vec<u8> {
("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.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zip.finish().unwrap().into_inner()
zip.finish().unwrap()
}
/// The link on each picture of the first paragraph, in order.
@@ -53,10 +51,9 @@ fn picture_links(doc: &Document) -> Vec<Option<String>> {
}
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
}
#[test]
@@ -109,19 +106,16 @@ fn a_linked_picture_is_saved_with_its_link_on_the_drawing_too() {
// The drawing's link alone (as Word writes it) reads back the same.
let without_run_link = xml.replace(&format!(r#"<w:hyperlink r:id="{rid}" w:history="1">"#), "").replacen("</w:hyperlink>", "", 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();
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
let mut out = craft_zip::Writer::new();
for name in names {
let mut data = z.read(&name, 16 << 20).unwrap().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();
out.add(&name, &data, craft_zip::Compression::Deflated).unwrap();
}
let edited = out.finish().unwrap().into_inner();
let edited = out.finish().unwrap();
assert_eq!(picture_links(&wordcraft_docx::read(&edited).unwrap())[0], Some("https://example.com/saved".to_string()));
}
+6 -10
View File
@@ -1,7 +1,5 @@
//! Positional tabs (`w:ptab`, ECMA-376 Part 1 §17.3.3.23). Fixtures are hand-written from the spec.
use std::io::{Read, Write};
use wordcraft_doc::InlineObject;
use wordcraft_doc::para::{PTabAlign, PTabBase};
use wordcraft_doc::props::TabLeader;
@@ -11,19 +9,17 @@ fn docx(body: &str) -> Vec<u8> {
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
fn ptab(relative_to: &str, alignment: &str, leader: &str) -> String {
+10 -11
View File
@@ -2,28 +2,27 @@
//! (ECMA-376 Part 1 §17.15.1.69–70) are kept on save and honoured by the writer. Synthetic
//! fixtures written for these tests from the spec; the names are made up.
use std::collections::BTreeMap;
use std::io::{Cursor, Read, Write};
const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships""#;
const RT: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";
fn zip(entries: &[(&str, String)]) -> Vec<u8> {
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
let mut z = craft_zip::Writer::new();
for (name, text) in entries {
z.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
z.write_all(text.as_bytes()).unwrap();
z.add(name, text.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
z.finish().unwrap().into_inner()
z.finish().unwrap()
}
fn unzip(bytes: &[u8]) -> BTreeMap<String, String> {
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
let mut parts = BTreeMap::new();
for i in 0..z.len() {
let mut f = z.by_index(i).unwrap();
let mut s = String::new();
if f.read_to_string(&mut s).is_ok() {
parts.insert(f.name().to_string(), s);
for name in names {
if let Ok(Some(bytes)) = z.read(&name, 16 << 20)
&& let Ok(s) = String::from_utf8(bytes)
{
parts.insert(name, s);
}
}
parts
+87 -116
View File
@@ -63,7 +63,11 @@ fn para_runs(runs: &[(&str, CharProps)]) -> Paragraph {
fn tiny_png() -> Vec<u8> {
let img = image::RgbaImage::from_fn(3, 2, |x, y| image::Rgba([x as u8 * 80, y as u8 * 120, 200, 255]));
let mut out = std::io::Cursor::new(Vec::new());
img.write_to(&mut out, image::ImageFormat::Png).unwrap();
std::io::Write::write_all(
&mut out,
&wordcraft_geom::picture::encode_format(&image::DynamicImage::from(img.clone()), image::ImageFormat::Png).unwrap(),
)
.unwrap();
out.into_inner()
}
@@ -324,9 +328,8 @@ fn tracked_style_definition_change_round_trips() {
});
d.body = vec![para_block(Paragraph::with_text("x", CharProps::default()))];
let bytes = wordcraft_docx::write(&d).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/styles.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/styles.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains("<w:pPrChange") && xml.contains("<w:rPrChange"), "{xml}");
assert!(!xml.contains("stylePrChange"), "CT_Style has no such element: {xml}");
drop(zip);
@@ -748,9 +751,8 @@ fn note_options_round_trip_per_section() {
assert!(sections[1].1.footnote_pr.is_empty() && sections[1].1.endnote_pr.is_empty());
assert_eq!(r.note_options(sections[0].1, false).num_start, 7);
assert_eq!(r.note_options(sections[1].1, false).num_start, 4);
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
let at = |s: &str| xml.find(s).unwrap_or_else(|| panic!("{s} missing"));
assert!(
at("<w:footnotePr><w:numFmt w:val=\"lowerRoman\"/><w:numStart w:val=\"7\"/><w:numRestart w:val=\"eachSect\"/></w:footnotePr>")
@@ -773,9 +775,8 @@ fn note_never_references_itself() {
d.body = vec![para_block(p)];
let bytes = wordcraft_docx::write(&d).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/footnotes.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/footnotes.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(!xml.contains("<w:footnoteReference"), "a footnote cites itself: {xml}");
assert_eq!(xml.matches("<w:footnoteRef/>").count(), 1, "{xml}");
@@ -840,13 +841,12 @@ fn word_note_mark_round_trips_once() {
let mut doc = d;
for pass in 0..2 {
let bytes = wordcraft_docx::write(&doc).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
for (file, mark, reference, style) in [
("word/footnotes.xml", "<w:footnoteRef/>", "<w:footnoteReference", "FootnoteReference"),
("word/endnotes.xml", "<w:endnoteRef/>", "<w:endnoteReference", "EndnoteReference"),
] {
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name(file).unwrap(), &mut xml).unwrap();
let xml = String::from_utf8(zip.read(file, 16 << 20).unwrap().unwrap()).unwrap();
assert_eq!(xml.matches(mark).count(), 1, "pass {pass}: {xml}");
assert!(!xml.contains(reference), "pass {pass}: a note cites itself: {xml}");
assert!(xml.contains(&format!(r#"<w:rStyle w:val="{style}"/></w:rPr>{mark}"#)), "pass {pass}: {xml}");
@@ -894,9 +894,8 @@ fn toc_field_wraps_its_entries() {
let d = doc_with(blocks);
let bytes = wordcraft_docx::write(&d).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
let sdt = xml.find("<w:sdt>").expect("TOC content control");
assert!(xml.contains(r#"<w:docPartGallery w:val="Table of Contents"/>"#), "{xml}");
let (begin, fend) = (xml.find(r#"fldCharType="begin""#).unwrap(), xml.find(r#"fldCharType="end""#).unwrap());
@@ -933,9 +932,8 @@ fn cell_text_direction_round_trips() {
let mut d = Document::new();
d.body = vec![Arc::new(Block::Table(t)), para_block(Paragraph::new())];
let bytes = wordcraft_docx::write(&d).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"<w:textDirection w:val="tbRl"/>"#), "{xml}");
assert!(xml.contains(r#"<w:textDirection w:val="btLr"/>"#), "{xml}");
assert_eq!(xml.matches("w:textDirection").count(), 2, "horizontal cells write nothing: {xml}");
@@ -988,9 +986,8 @@ fn toc_field_skips_nested_stories() {
d.body = vec![para_block(head), para_block(last), para_block(Paragraph::with_text("Body", CharProps::default()))];
let bytes = wordcraft_docx::write(&d).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
let boxes: Vec<(usize, usize)> = xml.match_indices("<w:txbxContent>").map(|(a, _)| (a, a + xml[a..].find("</w:txbxContent>").unwrap())).collect();
assert_eq!(boxes.len(), 2, "{xml}");
let in_box = |i: usize| boxes.iter().any(|(a, b)| (*a..*b).contains(&i));
@@ -1054,9 +1051,8 @@ fn tracked_equations_round_trip() {
p.insert_object(end, InlineObject::Equation { linear: "z=1".into(), display: false, math: Default::default() }, &plain).unwrap();
d.body = vec![para_block(p.clone())];
let bytes = wordcraft_docx::write(&d).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"<w:ins w:id="1" w:author="Alice" w:date="2026-05-01T10:00:00Z"><m:oMath>"#), "ins directly encloses inline math: {xml}");
assert!(
xml.contains(r#"<w:del w:id="2" w:author="Bob" w:date="2026-05-02T10:00:00Z"><m:oMathPara>"#),
@@ -1119,9 +1115,8 @@ fn tracked_paragraph_marks_round_trip() {
let last = Paragraph::with_text("plain", CharProps::default());
d.body = vec![para_block(split), para_block(joined), para_block(last)];
let bytes = wordcraft_docx::write(&d).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"<w:rPr><w:ins w:id="#), "{xml}");
assert!(xml.contains(r#"<w:rPr><w:del w:id="#), "{xml}");
let r = wordcraft_docx::read(&bytes).expect("read");
@@ -1165,10 +1160,9 @@ fn fields_and_special_chars_round_trip() {
/// The `document.xml` of a written package.
fn document_xml(bytes: &[u8]) -> String {
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
xml
let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
/// #877: a field begin marker's `w:dirty` (the cached result is stale; Word refreshes it on
@@ -1446,9 +1440,8 @@ fn drawing_canvas_round_trips() {
p.insert_object(end, canvas, &CharProps::default()).unwrap();
d.body = vec![para_block(p)];
let bytes = wordcraft_docx::write(&d).unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains("wordprocessingCanvas") && xml.contains("<wpc:wpc>") && xml.contains("<wpc:bg>") && xml.contains("<wpc:whole>"), "{xml}");
let r = wordcraft_docx::read(&bytes).unwrap();
let got = paras(&r);
@@ -1494,9 +1487,8 @@ fn rotated_drawing_canvas_round_trips() {
let end = p.len();
p.insert_object(end, canvas(square), &CharProps::default()).unwrap();
let bytes = wordcraft_docx::write(&doc_with(vec![p])).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(
xml.contains(r#"<wpc:extLst><a:ext uri="urn:wordcraft:canvas-xfrm"><a:xfrm rot="1800000" flipH="1"/></a:ext></wpc:extLst></wpc:wpc>"#),
"{xml}"
@@ -1524,9 +1516,8 @@ fn table_contextual_spacing_compatibility_flag_round_trips() {
assert_eq!(r.settings.compat_mode, mode);
if allow {
let bytes = wordcraft_docx::write(&d).unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/settings.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap();
// CT_Compat requires the boolean option before compatSetting.
assert!(xml.find("<w:allowSpaceOfSameStyleInTable").unwrap() < xml.find("<w:compatSetting").unwrap());
}
@@ -1557,15 +1548,13 @@ fn attached_template_and_link_styles_round_trip() {
d.settings.mirror_margins = true;
d.settings.track_changes = true;
let bytes = wordcraft_docx::write(&d).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/settings.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap();
let at = |tag: &str| xml.find(tag).unwrap_or_else(|| panic!("{tag} missing: {xml}"));
assert!(at("<w:mirrorMargins") < at("<w:attachedTemplate"));
assert!(at("<w:attachedTemplate") < at("<w:linkStyles"));
assert!(at("<w:linkStyles") < at("<w:trackRevisions"));
let mut rels = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/_rels/settings.xml.rels").unwrap(), &mut rels).unwrap();
let rels = String::from_utf8(zip.read("word/_rels/settings.xml.rels", 16 << 20).unwrap().unwrap()).unwrap();
assert!(rels.contains("relationships/attachedTemplate") && rels.contains("TargetMode=\"External\""), "{rels}");
let r = wordcraft_docx::read(&bytes).expect("read");
@@ -1583,10 +1572,9 @@ fn attached_template_and_link_styles_round_trip() {
#[test]
fn zoom_round_trips() {
let settings = |bytes: &[u8]| {
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/settings.xml").unwrap(), &mut xml).unwrap();
xml
let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(zip.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap()
};
let plain = wordcraft_docx::write(&Document::new()).unwrap();
let xml = settings(&plain);
@@ -1649,10 +1637,9 @@ fn settings_core_theme_round_trip() {
}
fn part_xml(bytes: &[u8], name: &str) -> String {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut z.by_name(name).unwrap(), &mut xml).unwrap();
xml
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
}
/// Header parts in the document, by id.
@@ -2047,9 +2034,8 @@ fn char_border_written_between_u_and_shd() {
let c =
CharProps { border: Some(Border::single(0.5)), underline: Some(Underline::Single), shading: Some(Rgb(0xFF, 0xFF, 0)), ..Default::default() };
let bytes = wordcraft_docx::write(&doc_with(vec![para_runs(&[("x", c)])])).unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
let bdr = r#"<w:bdr w:val="single" w:sz="4" w:space="0" w:color="auto"/>"#;
assert_eq!(xml.matches(bdr).count(), 1, "{xml}");
let at = xml.find(bdr).unwrap();
@@ -2146,9 +2132,8 @@ fn ink_and_freeforms_round_trip_as_custom_geometry() {
}
let d = doc_with(vec![p]);
let bytes = wordcraft_docx::write(&d).unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert_eq!(xml.matches("<a:custGeom>").count(), 3, "{xml}");
assert!(xml.contains(r#"<a:path w="762000" h="254000" fill="none"><a:moveTo><a:pt x="12700" y="12700"/></a:moveTo><a:lnTo>"#), "{xml}");
assert!(xml.contains(r#"<a:alpha val="50000"/>"#) && xml.contains(r#"cap="rnd""#), "{xml}");
@@ -2188,9 +2173,8 @@ fn shape_effects_round_trip() {
let mut p = Paragraph::with_text("x", CharProps::default());
p.insert_object(1, shape, &CharProps::default()).unwrap();
let bytes = wordcraft_docx::write(&doc_with(vec![p])).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(
xml.contains(
r#"<a:outerShdw blurRad="50800" dist="38100" dir="8100000" algn="tr" rotWithShape="0"><a:srgbClr val="203040"><a:alpha val="40000"/>"#
@@ -2281,9 +2265,8 @@ fn rotation_and_flips_round_trip() {
}
d.body = vec![para_block(p)];
let bytes = wordcraft_docx::write(&d).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"<a:xfrm rot="1800000">"#), "{xml}");
assert!(xml.contains(r#"<a:xfrm rot="5400000" flipH="1">"#), "{xml}");
assert!(xml.contains(r#"<a:xfrm rot="18930000" flipV="1">"#), "{xml}");
@@ -2334,9 +2317,8 @@ fn rotated_group_and_shadow_rotation_round_trip() {
let mut p = Paragraph::with_text("g", CharProps::default());
p.insert_object(1, group, &CharProps::default()).unwrap();
let bytes = wordcraft_docx::write(&doc_with(vec![p])).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"<wpg:grpSpPr><a:xfrm rot="8100000" flipH="1">"#), "{xml}");
assert!(xml.contains(r#"rotWithShape="1""#) && xml.contains(r#"rotWithShape="0""#), "{xml}");
let r = wordcraft_docx::read(&bytes).expect("read");
@@ -2440,9 +2422,8 @@ fn a_corporate_author_round_trips() {
..Default::default()
});
let bytes = wordcraft_docx::write(&d).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes[..])).unwrap();
let mut item_xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("customXml/item1.xml").unwrap(), &mut item_xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes[..], craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let item_xml = String::from_utf8(zip.read("customXml/item1.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(item_xml.contains("<b:Author><b:Author><b:Corporate>World Health Organization</b:Corporate></b:Author><b:Editor>"), "{item_xml}");
assert!(item_xml.contains("<b:Corporate>Harbor Guild, Inc.</b:Corporate>"), "{item_xml}");
assert!(!item_xml.contains("<b:Last>Rivera</b:Last>"), "the corporate author takes the person authors' place: {item_xml}");
@@ -2452,23 +2433,20 @@ fn a_corporate_author_round_trips() {
}
fn assert_bibliography_parts(bytes: &[u8]) {
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
assert!(zip.by_name("customXml/item1.xml").is_ok());
assert!(zip.by_name("customXml/itemProps1.xml").is_ok());
assert!(zip.by_name("customXml/_rels/item1.xml.rels").is_ok());
let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
assert!(zip.contains("customXml/item1.xml"));
assert!(zip.contains("customXml/itemProps1.xml"));
assert!(zip.contains("customXml/_rels/item1.xml.rels"));
let mut rels_xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("_rels/.rels").unwrap(), &mut rels_xml).unwrap();
let rels_xml = String::from_utf8(zip.read("_rels/.rels", 16 << 20).unwrap().unwrap()).unwrap();
assert!(rels_xml.contains("relationships/customXml"), "{rels_xml}");
assert!(rels_xml.contains("Target=\"customXml/item1.xml\""), "{rels_xml}");
let mut ct_xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("[Content_Types].xml").unwrap(), &mut ct_xml).unwrap();
let ct_xml = String::from_utf8(zip.read("[Content_Types].xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(ct_xml.contains("PartName=\"/customXml/item1.xml\""), "{ct_xml}");
assert!(ct_xml.contains("PartName=\"/customXml/itemProps1.xml\""), "{ct_xml}");
let mut item_xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("customXml/item1.xml").unwrap(), &mut item_xml).unwrap();
let item_xml = String::from_utf8(zip.read("customXml/item1.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert_bibliography_types(&item_xml);
assert_bibliography_people(&item_xml);
assert_bibliography_details(&item_xml);
@@ -2596,9 +2574,8 @@ fn wrap_polygons_round_trip() {
}
d.body = vec![para_block(p)];
let bytes = wordcraft_docx::write(&d).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"<wp:wrapPolygon edited="1"><wp:start x="-300" y="0"/><wp:lineTo x="21600" y="1200"/>"#), "{xml}");
assert!(xml.contains(r#"<wp:lineTo x="-300" y="0"/></wp:wrapPolygon>"#), "closed: {xml}");
let r = unstacked(wordcraft_docx::read(&bytes).expect("read"));
@@ -2635,9 +2612,8 @@ fn enclosed_characters_round_trip_in_words_structure() {
}
let doc = doc_with(vec![p]);
let bytes = wordcraft_docx::write(&doc).unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.clone())).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"<w:instrText xml:space="preserve"> eq \o\ac(○</w:instrText>"#), "{xml}");
assert!(!xml.contains("separate") && !xml.contains("enlarge"), "{xml}");
// Shrink text at 11 pt: the character at 7.5 pt (half-points 15), raised.
@@ -2670,9 +2646,8 @@ fn ruby_phonetic_guide_round_trips_as_w_ruby() {
p.insert_object(5, ruby.clone(), &bold).unwrap();
let d = doc_with(vec![p]);
let bytes = wordcraft_docx::write(&d).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
for part in [
r#"<w:rubyAlign w:val="distributeSpace"/><w:hps w:val="11"/><w:hpsRaise w:val="20"/><w:hpsBaseText w:val="22"/><w:lid w:val="ja-JP"/>"#,
"<w:rt><w:r>",
@@ -2717,9 +2692,8 @@ fn wrap_text_sides_round_trip() {
}
d.body = vec![para_block(p)];
let bytes = wordcraft_docx::write(&d).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
for tag in [
r#"<wp:wrapSquare wrapText="left"/>"#,
r#"<wp:wrapTight wrapText="right">"#,
@@ -2784,9 +2758,8 @@ fn alt_text_title_and_decorative_round_trip_for_every_object() {
t.props.description = Some("Prices by year".into());
d.body = vec![para_block(p), Arc::new(Block::Table(t))];
let bytes = wordcraft_docx::write(&d).expect("write");
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"{C183D7F6-B498-43B3-948B-1728B52AA6E4}"><adec:decorative xmlns:adec="http://schemas.microsoft.com/office/drawing/2017/decorative" val="1"/>"#), "{xml}");
assert!(
xml.contains(r#"<w:tblLook "#) && xml.contains(r#"<w:tblCaption w:val="Prices"/><w:tblDescription w:val="Prices by year"/></w:tblPr>"#),
@@ -2865,9 +2838,8 @@ fn warps_and_glued_connectors_round_trip() {
// Hostile: an unknown warp, a huge adjust value, a glue to a missing shape.
let xml = wordcraft_docx::write(&r).unwrap();
let mut pkg = zip::ZipArchive::new(std::io::Cursor::new(xml)).unwrap();
let mut doc_xml = String::new();
std::io::Read::read_to_string(&mut pkg.by_name("word/document.xml").unwrap(), &mut doc_xml).unwrap();
let mut pkg = craft_zip::Archive::open(&xml, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let doc_xml = String::from_utf8(pkg.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
let doc_xml = doc_xml
.replace("prst=\"textArchUp\"", "prst=\"textNotAWarp\"")
.replace("a:stCxn id=\"5\" idx=\"3\"", "a:stCxn id=\"404\" idx=\"99999999999\"");
@@ -2880,29 +2852,29 @@ fn warps_and_glued_connectors_round_trip() {
/// `zip` with part `name` replaced by `data`.
fn replace_part(zip_bytes: &[u8], name: &str, data: &[u8]) -> Vec<u8> {
let mut src = zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)).unwrap();
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for i in 0..src.len() {
let mut f = src.by_index(i).unwrap();
let n = f.name().to_string();
out.start_file(n.as_str(), zip::write::SimpleFileOptions::default()).unwrap();
let mut src = craft_zip::Archive::open(zip_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let names: Vec<String> = src.names().map(|n| n.into_owned()).collect();
let mut out = craft_zip::Writer::new();
for n in names {
if n == name {
std::io::Write::write_all(&mut out, data).unwrap();
out.add(&n, data, craft_zip::Compression::Deflated).unwrap();
} else {
std::io::copy(&mut f, &mut out).unwrap();
let bytes = src.read(&n, 16 << 20).unwrap().unwrap();
out.add(&n, &bytes, craft_zip::Compression::Deflated).unwrap();
}
}
out.finish().unwrap().into_inner()
out.finish().unwrap()
}
/// A texture or picture page background (`v:background/v:fill`) survives a save (#999): the image
/// part, its relationship and the fill attributes.
#[test]
fn page_background_picture_round_trips() {
let mut png = Vec::new();
image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 150, 100, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let png = wordcraft_geom::picture::encode_format(
&image::DynamicImage::from(image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 150, 100, 255])).clone()),
image::ImageFormat::Png,
)
.unwrap();
let mut d = Document::new();
d.settings.page_color = Some(Rgb(0xFF, 0xFF, 0xCC));
d.media.insert("paper.png".into(), Arc::new(png.clone()));
@@ -2932,9 +2904,8 @@ fn drop_cap_options_round_trip() {
margin.props.drop_cap_margin = Some(true);
let d = doc_with(vec![dropped, margin]);
let bytes = wordcraft_docx::write(&d).expect("write");
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(xml.contains(r#"w:dropCap="drop" w:lines="2" w:hSpace="120""#), "{xml}");
assert!(xml.contains(r#"w:dropCap="margin" w:lines="4""#), "{xml}");
assert!(xml.contains(r#"w:ascii="Liberation Mono""#), "the letter's font on its run: {xml}");
@@ -1,26 +1,22 @@
//! Row-level table property exceptions (`w:tblPrEx` in `w:tr`, ECMA-376 Part 1 §17.4.61).
//! Fixtures are hand-written from the spec.
use std::io::{Read, Write};
fn docx(body: &str) -> Vec<u8> {
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
fn row(ex: &str, text: &str) -> String {
+6 -10
View File
@@ -1,7 +1,5 @@
//! Run and style properties that must survive repeated DOCX saves.
use std::io::{Read, Write};
fn docx(body: &str, styles: &str) -> Vec<u8> {
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
@@ -9,24 +7,22 @@ fn docx(body: &str, styles: &str) -> Vec<u8> {
r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}<w:sectPr/></w:body></w:document>"#
);
let styles = format!(r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{styles}</w:styles>"#);
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zip = craft_zip::Writer::new();
for (name, xml) in [
("_rels/.rels", root.to_string()),
("word/document.xml", document),
("word/_rels/document.xml.rels", rels.to_string()),
("word/styles.xml", styles),
] {
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(xml.as_bytes()).unwrap();
zip.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
zip.finish().unwrap().into_inner()
zip.finish().unwrap()
}
fn part(bytes: &[u8], name: &str) -> String {
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut xml = String::new();
zip.by_name(name).unwrap().read_to_string(&mut xml).unwrap();
xml
let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(zip.read(name, 16 << 20).unwrap().unwrap()).unwrap()
}
#[test]
@@ -1,26 +1,22 @@
//! Section form protection (`w:formProt` in `w:sectPr`, ECMA-376 Part 1 §17.6.6). Fixtures are
//! hand-written from the spec.
use std::io::{Read, Write};
fn docx(body: &str) -> Vec<u8> {
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
#[test]
+6 -10
View File
@@ -1,7 +1,5 @@
//! Section line numbering (`w:lnNumType` in `w:sectPr`, ECMA-376 Part 1 §17.6.8).
use std::io::{Read, Write};
use wordcraft_doc::section::{LineNumberRestart, LineNumbering};
/// Builds a minimal in-memory DOCX package archive containing the given XML body.
@@ -10,20 +8,18 @@ fn docx(body: &str) -> Vec<u8> {
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
/// Extracts the `word/document.xml` content string from a serialized DOCX package.
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
/// #6209: `<w:lnNumType>` without `w:countBy` leaves line numbering off, as Word does.
@@ -1,25 +1,21 @@
//! Section printer, note and chapter-number metadata survives DOCX and native JSON saves.
use std::io::{Read, Write};
fn docx(body: &str) -> Vec<u8> {
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let doc = format!(
r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="w15"><w:body>{body}</w:body></w:document>"#
);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
#[test]
@@ -1,26 +1,22 @@
//! Section page-number settings (`w:pgNumType` in `w:sectPr`, ECMA-376 Part 1 §17.6.12).
//! Fixtures are hand-written from the spec.
use std::io::{Read, Write};
fn docx(body: &str) -> Vec<u8> {
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
#[test]
+12 -17
View File
@@ -1,8 +1,6 @@
//! Section text direction (`w:textDirection` in `w:sectPr`, ECMA-376 Part 1 §17.6.20). Fixtures
//! are hand-written from the spec.
use std::io::{Read, Write};
use wordcraft_doc::props::TextDirection;
fn docx(body: &str) -> Vec<u8> {
@@ -10,16 +8,15 @@ fn docx(body: &str) -> Vec<u8> {
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
fn docx_with_styles(body: &str, styles: &str) -> Vec<u8> {
let mut bytes = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut bytes = craft_zip::Writer::new();
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let document_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
let doc = format!(
@@ -31,17 +28,15 @@ fn docx_with_styles(body: &str, styles: &str) -> Vec<u8> {
("word/document.xml", doc.as_bytes()),
("word/styles.xml", styles.as_bytes()),
] {
bytes.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
bytes.write_all(value).unwrap();
bytes.add(name, value, craft_zip::Compression::Deflated).unwrap();
}
bytes.finish().unwrap().into_inner()
bytes.finish().unwrap()
}
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
#[test]
@@ -122,8 +117,8 @@ fn paragraph_style_text_direction_is_preserved_and_direct_value_overrides_it() {
assert_eq!(xml.matches(r#"<w:pStyle w:val="Vertical"/>"#).count(), 2, "both paragraphs keep their style: {xml}");
assert!(xml.contains(r#"<w:pStyle w:val="Vertical"/><w:textDirection w:val="lrTb"/>"#), "direct horizontal is explicit: {xml}");
assert_eq!(xml.matches("w:textDirection").count(), 1, "only the direct paragraph writes a direction: {xml}");
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_docx::write(&d).unwrap())).unwrap();
let mut styles_xml = String::new();
z.by_name("word/styles.xml").unwrap().read_to_string(&mut styles_xml).unwrap();
let _z_bytes = wordcraft_docx::write(&d).unwrap();
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let styles_xml = String::from_utf8(z.read("word/styles.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(styles_xml.contains(r#"<w:textDirection w:val="tbRl"/>"#), "style value survives: {styles_xml}");
}
+6 -10
View File
@@ -1,8 +1,6 @@
//! Section vertical alignment (`w:vAlign` in `w:sectPr`, ECMA-376 Part 1 §17.6.23, values from
//! ST_VerticalJc). Fixtures are hand-written from the spec.
use std::io::{Read, Write};
use wordcraft_doc::section::PageVAlign;
fn docx(body: &str) -> Vec<u8> {
@@ -10,19 +8,17 @@ fn docx(body: &str) -> Vec<u8> {
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
/// #1320: "both" (Justified) reads as Justify and writes back as "both"; the others keep theirs.
+8 -11
View File
@@ -4,29 +4,26 @@
//! fixtures (from the spec), no files produced by Word.
use std::collections::BTreeMap;
use std::io::{Read, Write};
const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
const R_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
const REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
fn zip(entries: &[(&str, Vec<u8>)]) -> Vec<u8> {
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in entries {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
let mut out = BTreeMap::new();
for i in 0..z.len() {
let mut f = z.by_index(i).unwrap();
let mut b = Vec::new();
f.read_to_end(&mut b).unwrap();
assert!(out.insert(f.name().to_string(), b).is_none(), "duplicate part {}", f.name());
for name in names {
let b = z.read(&name, 16 << 20).unwrap().unwrap();
assert!(out.insert(name.clone(), b).is_none(), "duplicate part {name}");
}
out
}
+6 -10
View File
@@ -4,8 +4,6 @@
//! 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""#;
@@ -33,19 +31,17 @@ 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<u8> {
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in entries {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
fn solid(rgb: &str) -> String {
+6 -10
View File
@@ -3,8 +3,6 @@
//! Word sizes a line by it when a list label is larger than the text, so a save that drops it
//! moves every line after. Fixtures are hand-written from the spec.
use std::io::{Read, Write};
use wordcraft_doc::props::TextAlignment;
fn docx(body: &str) -> Vec<u8> {
@@ -12,19 +10,17 @@ fn docx(body: &str) -> Vec<u8> {
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
#[test]
+15 -11
View File
@@ -2,26 +2,22 @@
//! `wps:txbx/@id`, `wps:linkedTxbx`). Fixtures are hand-written from ECMA-376 Part 1 §20.4
//! (DrawingML WordprocessingML drawing) and §21.1.2.1.1 (`bodyPr`).
use std::io::{Read, Write};
use wordcraft_doc::para::ShapeKind;
use wordcraft_doc::props::{TextVert, VAlign};
use wordcraft_doc::{Document, InlineObject, PartKind, TextBody, para_block};
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in entries {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
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
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
/// The text boxes' stories in body order, a group's members among them
@@ -217,7 +213,15 @@ fn picture_in_box_keeps_its_frame() {
let outer = text_box(&mut d, "Label", body);
let id = outer.text_box().unwrap();
let mut bytes = std::io::Cursor::new(Vec::new());
image::RgbaImage::from_pixel(10, 4, image::Rgba([20, 40, 60, 255])).write_to(&mut bytes, image::ImageFormat::Png).unwrap();
std::io::Write::write_all(
&mut bytes,
&wordcraft_geom::picture::encode_format(
&image::DynamicImage::from(image::RgbaImage::from_pixel(10, 4, image::Rgba([20, 40, 60, 255])).clone()),
image::ImageFormat::Png,
)
.unwrap(),
)
.unwrap();
let media = d.add_media(bytes.into_inner(), "png");
let image = InlineObject::Image {
media: media.clone(),
+3 -5
View File
@@ -1,11 +1,10 @@
//! Original field-boundary fixtures from the public OOXML complex-field contract.
use std::io::Write;
use wordcraft_doc::{InlineObject, Path, StoryRef};
fn package(body: &str) -> Vec<u8> {
let xml = format!(r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#);
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zip = craft_zip::Writer::new();
for (name, value) in [
("word/document.xml", xml.as_str()),
(
@@ -13,10 +12,9 @@ fn package(body: &str) -> Vec<u8> {
r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="main" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#,
),
] {
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(value.as_bytes()).unwrap();
zip.add(name, value.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
zip.finish().unwrap().into_inner()
zip.finish().unwrap()
}
fn start(code: &str) -> String {
+3 -5
View File
@@ -1,7 +1,6 @@
//! A paragraph whose `w:pStyle` names a style `styles.xml` doesn't define is formatted as Normal,
//! as in Word, not with the document defaults alone (#5077). Pandoc writes footers as
//! `<w:pStyle w:val="Footer"/>` without defining Footer.
use std::io::Write;
use wordcraft_doc::props::LineSpacing;
use wordcraft_doc::{Block, Document, PartKind};
@@ -20,7 +19,7 @@ fn package(normal_id: &str) -> Vec<u8> {
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="{W}"><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="24"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="200"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="{normal_id}"><w:name w:val="Normal"/><w:pPr><w:spacing w:before="20" w:after="40" w:line="259" w:lineRule="auto"/></w:pPr><w:rPr><w:sz w:val="26"/></w:rPr></w:style></w:styles>"#
);
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/></Relationships>"#;
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, body) in [
("_rels/.rels", root),
("word/document.xml", doc.as_str()),
@@ -28,10 +27,9 @@ fn package(normal_id: &str) -> Vec<u8> {
("word/styles.xml", styles.as_str()),
("word/footer1.xml", footer.as_str()),
] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(body.as_bytes()).unwrap();
zw.add(name, body.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
fn footer_para(d: &Document) -> &wordcraft_doc::Paragraph {
+3 -6
View File
@@ -2,18 +2,15 @@
//! `coordsize`/`coordorigin` give them. Fixtures are hand-written from ECMA-376 Part 4
//! (VML, §14.1 `v:group`, `coordsize`, `coordorigin`; §14.2 shapes).
use std::io::Write;
use wordcraft_doc::para::ShapeKind;
use wordcraft_doc::{Document, InlineObject, Paragraph};
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, bytes) in entries {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
}
zw.finish().unwrap().into_inner()
zw.finish().unwrap()
}
/// A document whose body is `body`.
+5 -1
View File
@@ -20,7 +20,11 @@ fn part_text(doc: &Document, id: Option<u32>) -> String {
fn tiny_png_b64() -> String {
let img = image::RgbaImage::from_fn(2, 2, |x, y| image::Rgba([x as u8 * 100, y as u8 * 100, 50, 255]));
let mut out = std::io::Cursor::new(Vec::new());
img.write_to(&mut out, image::ImageFormat::Png).unwrap();
std::io::Write::write_all(
&mut out,
&wordcraft_geom::picture::encode_format(&image::DynamicImage::from(img.clone()), image::ImageFormat::Png).unwrap(),
)
.unwrap();
let b64 = base64::engine::general_purpose::STANDARD.encode(out.into_inner());
// Line breaks inside base64, as the formats write it.
b64.as_bytes().chunks(20).map(|c| std::str::from_utf8(c).unwrap()).collect::<Vec<_>>().join("\n")
+5 -1
View File
@@ -13,7 +13,11 @@ use wordcraft_docx::{XmlKind, read_xml, sniff_xml, write_wordml2003};
fn tiny_png() -> Vec<u8> {
let img = image::RgbaImage::from_fn(3, 2, |x, y| image::Rgba([x as u8 * 80, y as u8 * 120, 200, 255]));
let mut out = std::io::Cursor::new(Vec::new());
img.write_to(&mut out, image::ImageFormat::Png).unwrap();
std::io::Write::write_all(
&mut out,
&wordcraft_geom::picture::encode_format(&image::DynamicImage::from(img.clone()), image::ImageFormat::Png).unwrap(),
)
.unwrap();
out.into_inner()
}
+2 -2
View File
@@ -17,7 +17,7 @@ fn ragged_matrix_save_stays_small() {
let mut doc = Document::new();
doc.body = vec![para_block(p)];
let bytes = wordcraft_docx::write(&doc).unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let size = zip.by_name("word/document.xml").unwrap().size();
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let size = zip.declared_size("word/document.xml").unwrap();
assert!(size < 1_000_000, "document.xml is {size} bytes");
}
+2 -1
View File
@@ -15,6 +15,7 @@ workspace = true
test-support = []
[dependencies]
craft-mime.workspace = true
wordcraft-geom = { workspace = true, features = ["image"] }
wordcraft-doc = { workspace = true }
wordcraft-fonts = { workspace = true }
@@ -59,5 +60,5 @@ rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
[dev-dependencies]
wordcraft-doc = { workspace = true, features = ["test-support"] }
encoding_rs = { workspace = true }
zip = { workspace = true }
craft-zip = { workspace = true }
cfb = { workspace = true }
+2 -2
View File
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
.when(has_canvas)
.pure(),
CommandSpec::new("canvas.member", "Canvas Member", "Shape Format › Drawing Canvas", member)
.params(r#"{"index": n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; with no change, returns the members)"#)
.params(r#"{"index"?: n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; without index, returns the members)"#)
.when(has_canvas),
]
}
@@ -211,7 +211,7 @@ fn scale(s: &mut Session, v: &Value) -> CmdResult {
result(&o)
}
/// `canvas.member`: move, resize or remove one member; with no change, list the members.
/// `canvas.member`: move, resize or remove one member; without index, list the members.
fn member(s: &mut Session, v: &Value) -> CmdResult {
let pos = canvas_pos(s)?;
let Some(i) = p::u64(v, "index").and_then(|i| usize::try_from(i).ok()) else {
+1
View File
@@ -68,6 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
sel_result(s)
})
.key("Escape")
.params(r#"{"end"?: bool (default false: collapse to the start; true: to the end)}"#)
.pure(),
]
}
+2 -1
View File
@@ -63,7 +63,8 @@ pub fn specs() -> Vec<CommandSpec> {
let t = THEMES.iter().find(|t| t.0.eq_ignore_ascii_case(name)).ok_or_else(|| CmdError::Params(format!("unknown colours `{name}`")))?;
set_accent(s, t.3[0]);
sel_result(s)
}),
})
.params(r#"{"name": string (see design.themes)}"#),
CommandSpec::new("design.styleSet", "Style Set", "Design › Document Formatting", style_set)
.params(r#"{"name": "default|basic|lines|shaded|casual|centered|minimalist|title"}"#),
CommandSpec::new("design.paragraphSpacing", "Paragraph Spacing", "Design › Document Formatting", para_spacing)
+97 -17
View File
@@ -7,6 +7,13 @@ use wordcraft_doc::{Path, Pos, StoryRef};
use super::{delete_selection, find_pattern, pos_json, sel_result};
use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
/// Browsers reserve Mod+Shift+C for their inspector. Keep the desktop binding, but
/// advertise a web alternative through the same registry/keymap as every other command.
/// Mod+Alt+C already inserts copyright, and Mod+Alt+Shift+V is Keep Text Only.
fn copy_format_shortcut(web: bool) -> &'static str {
if web { "Mod+Alt+Shift+C / Mod+Shift+C" } else { "Mod+Shift+C" }
}
/// Undo several steps at once: the Undo button's list (#701). `count` is validated here and
/// clamped to the undo depth, so hostile numbers never reach the stack.
fn undo_to(s: &mut Session, v: &Value) -> CmdResult {
@@ -134,7 +141,9 @@ pub fn specs() -> Vec<CommandSpec> {
.key(super::mac_or("Mod+Shift+G / Mod+PageUp", "Mod+PageUp"))
.params(r#"{"text"?: string, "matchCase"?: bool, "wholeWord"?: bool, "regex"?: bool}"#)
.pure(),
CommandSpec::new("edit.replace", "Replace", "Home › Editing", replace).params(r#"{"text": string, "with": string, …options of edit.replaceAll}"#),
CommandSpec::new("edit.replace", "Replace", "Home › Editing", replace).params(
r#"{"text": string, "with": string, …options of edit.replaceAll} — Word's Replace button: replaces the match only when it is already selected, then selects the next one. The first call on a caret replaces nothing; call again to replace the selected match, or use edit.replaceAll for every match. Returns {"replaced": 0 | 1, "remaining": n, "selected": {start, end} | null}"#,
),
// Ctrl+H, Home › Replace: the Find and Replace dialog on its Replace tab (#712). Opening
// it changes nothing, so it is its own command and never marks the document edited.
CommandSpec::new("edit.findReplace", "Find and Replace", "Home › Editing", |s, v| {
@@ -165,10 +174,12 @@ pub fn specs() -> Vec<CommandSpec> {
.pure(),
CommandSpec::new("edit.formatPainter", "Format Painter", "Home › Clipboard", painter).params(r#"{"sticky"?: bool}"#).pure(),
CommandSpec::new("edit.copyFormat", "Copy Formatting", "Home › Clipboard", |s, _| {
painter_pick(s);
// One format buffer, as in Word: Copy Formatting replaces an armed Format Painter.
s.painter = None;
s.copied_format = Some(picked_format(s));
sel_result(s)
})
.key("Mod+Shift+C")
.key(copy_format_shortcut(cfg!(target_arch = "wasm32")))
.pure(),
CommandSpec::new("edit.pasteFormat", "Paste Formatting", "Home › Clipboard", paste_format).key("Mod+Shift+V"),
]
@@ -737,12 +748,21 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
let story = s.sel.focus.story;
let results = search_full(s, story, true)?;
let (a, b) = s.sel.ordered();
// Replace the current match if selected, then move to the next.
// Replace the current match if selected, then move to the next. The result says which
// happened (#6877): a first call that only selects a match reads as `replaced: 0`.
let mut replaced = 0;
if let Some(f) = results.into_iter().find(|f| f.a == a && f.b == b) {
super::paste_text(s, &f.rep.unwrap_or_default())?;
replaced = 1;
}
let _ = step(s, 1);
Ok(json!({"remaining": search(s, story)?.len()}))
let selected = match step(s, 1) {
Ok(_) => {
let (start, end) = s.sel.ordered();
json!({"start": pos_json(&start), "end": pos_json(&end)})
}
Err(_) => Value::Null,
};
Ok(json!({"replaced": replaced, "remaining": search(s, story)?.len(), "selected": selected}))
}
/// Every match replaced, last first so earlier positions stay valid (one undo step). A `\r` in
@@ -825,11 +845,21 @@ fn goto(s: &mut Session, v: &Value) -> CmdResult {
sel_result(s)
}
fn painter_pick(s: &mut Session) {
/// The character and paragraph formatting at the start of the selection.
fn picked_format(s: &Session) -> (wordcraft_doc::props::CharProps, wordcraft_doc::props::ParaProps) {
let f = s.sel.ordered().0;
// A symbol's own font isn't formatting to paint onto text.
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone().without_symbol()).unwrap_or_default();
let para = s.doc.para_at(&f).map(|p| p.props.clone()).unwrap_or_default();
// Formatting only: not the source's hyperlink or revision marks (#5616).
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone().without_symbol().formatting()).unwrap_or_default();
let para = s.doc.para_at(&f).map(|p| p.props.clone().formatting()).unwrap_or_default();
(chr, para)
}
fn painter_pick(s: &mut Session) {
let (chr, para) = picked_format(s);
// One format buffer, as in Word: the pick is also what the next Paste Formatting applies,
// and stays after the brush is used up or cancelled.
s.copied_format = Some((chr.clone(), para.clone()));
s.painter = Some((chr, para, false));
}
@@ -845,24 +875,28 @@ fn painter(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"active": true}))
}
/// Apply the format painter's formatting to the selection.
/// Apply the format painter's formatting to the selection, or else what Copy Formatting picked
/// up (which stays for the next Paste Formatting).
fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
let Some((chr, para, sticky)) = s.painter.clone() else { return Err(CmdError::Failed("no formatting copied".into())) };
let (chr, para, sticky) = match (s.painter.clone(), s.copied_format.clone()) {
(Some(brush), _) => brush,
(None, Some((chr, para))) => (chr, para, true),
(None, None) => return Err(CmdError::Failed("no formatting copied".into())),
};
let (a, b) = s.sel.ordered();
if a == b {
// No selection: apply paragraph formatting (and word formatting like Word).
let f = s.sel.focus.clone();
if let Some(pp) = s.doc.para_at(&f) {
let (x, y) = pp.word_at(f.off);
s.doc.format_range(&Pos { off: x, ..f.clone() }, &Pos { off: y, ..f.clone() }, &|c| *c = chr.cleared().overlaid(&chr))?;
// Word selection includes trailing spaces; a painter click formats just the word,
// matching the ordinary collapsed-caret formatting target.
let word_end = pp.text.get(x..y).map(|word| x + word.trim_end().len()).unwrap_or(y);
s.doc.format_range(&Pos { off: x, ..f.clone() }, &Pos { off: word_end, ..f.clone() }, &|c| *c = c.cleared().overlaid(&chr))?;
}
s.doc.format_paragraphs(&a, &b, &|p| *p = para.clone())?;
} else {
s.doc.format_range(&a, &b, &|c| {
let link = c.link.clone();
*c = c.cleared().overlaid(&chr);
c.link = link;
})?;
s.doc.format_range(&a, &b, &|c| *c = c.cleared().overlaid(&chr))?;
if a.path != b.path || a.off == 0 {
s.doc.format_paragraphs(&a, &b, &|p| *p = para.clone())?;
}
@@ -872,3 +906,49 @@ fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
}
sel_result(s)
}
#[cfg(test)]
mod shortcut_tests {
use super::*;
use crate::{KeyMap, Registry};
#[test]
fn copy_format_web_alias_is_unique_and_keeps_existing_shortcuts() {
for web in [false, true] {
let mut commands = super::super::registry().all().to_vec();
let copy = commands.iter_mut().find(|c| c.id == "edit.copyFormat").unwrap();
copy.shortcut = copy_format_shortcut(web);
let registry = Registry::new(commands);
let mut seen = std::collections::BTreeSet::new();
for command in registry.all() {
for key in command.shortcut.split(" / ").filter_map(crate::keymap::normalize) {
assert!(seen.insert(key.clone()), "duplicate binding: {key}");
}
}
let keys = KeyMap::default();
let resolve = |key| keys.resolve(&registry, key).map(|c| c.id);
assert_eq!(resolve("Mod+Shift+C"), Some("edit.copyFormat"));
assert_eq!(resolve("Mod+Alt+Shift+C"), web.then_some("edit.copyFormat"));
assert_eq!(resolve("Mod+Shift+V"), Some("edit.pasteFormat"));
assert_eq!(resolve("Mod+Alt+Shift+V"), Some("edit.pasteText"));
if !cfg!(target_os = "macos") {
assert_eq!(resolve("Mod+Alt+C"), Some("text.copyright"));
}
}
}
#[test]
fn copy_format_web_alias_respects_user_removal_and_reassignment() {
let mut commands = super::super::registry().all().to_vec();
commands.iter_mut().find(|c| c.id == "edit.copyFormat").unwrap().shortcut = copy_format_shortcut(true);
let registry = Registry::new(commands);
let mut keys = KeyMap::default();
assert_eq!(keys.keys_for(&registry, "edit.copyFormat").first().map(String::as_str), Some("Mod+Alt+Shift+C"));
assert!(keys.remove(&registry, "edit.copyFormat", "Mod+Alt+Shift+C").unwrap());
assert!(keys.resolve(&registry, "Mod+Alt+Shift+C").is_none());
keys.assign(&registry, "format.bold", "Mod+Alt+Shift+C").unwrap();
let restored = KeyMap::from_value(&serde_json::to_value(&keys).unwrap());
assert_eq!(restored.resolve(&registry, "Mod+Alt+Shift+C").map(|c| c.id), Some("format.bold"));
assert_eq!(restored.resolve(&registry, "Mod+Shift+C").map(|c| c.id), Some("edit.copyFormat"));
}
}
+6 -10
View File
@@ -103,7 +103,6 @@ fn gallery_lists_everything() {
/// A session on a DOCX whose only paragraph is `<m:oMath>{math}</m:oMath>`.
fn imported(math: &str) -> Session {
use std::io::Write;
let w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
let m = "http://schemas.openxmlformats.org/officeDocument/2006/math";
let parts = [
@@ -117,24 +116,21 @@ fn imported(math: &str) -> Session {
),
("word/document.xml", format!(r#"<w:document xmlns:w="{w}" xmlns:m="{m}"><w:body><w:p><m:oMath>{math}</m:oMath></w:p><w:sectPr/></w:body></w:document>"#)),
];
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, xml) in parts {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(xml.as_bytes()).unwrap();
zw.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
let bytes = zw.finish().unwrap().into_inner();
let bytes = zw.finish().unwrap();
let mut s = Session::new(wordcraft_docx::read(&bytes).unwrap());
s.run("equation.edit", &json!({})).unwrap();
s
}
fn document_xml(s: &Session) -> String {
use std::io::Read;
let bytes = wordcraft_docx::write(&s.doc).unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut xml = String::new();
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
xml
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
}
#[test]
+5 -2
View File
@@ -154,7 +154,7 @@ pub fn show_results(s: &mut Session) -> Result<(), CmdError> {
fn set_code(s: &mut Session, v: &Value) -> CmdResult {
let code = p::req_str(v, "code")?.trim().to_string();
if code.is_empty() || code.len() > MAX_CODE || code.contains(OBJ) {
return Err(CmdError::Params("bad field code".into()));
return Err(CmdError::Params("`code` must be non-empty, at most 4096 UTF-8 bytes, and contain no U+FFFC object markers".into()));
}
let Some(f) = selected(s).into_iter().next() else { return Err(none_selected()) };
with_field(s, &f.at, |o| match o {
@@ -441,7 +441,10 @@ mod tests {
s.run("fields.setCode", &json!({"code": "TITLE"})).unwrap();
let objs = |s: &Session| s.doc.body.first().and_then(|b| b.as_para()).map(|p| p.objects.clone()).unwrap_or_default();
assert!(matches!(objs(&s).first(), Some(InlineObject::Field { instr, result, .. }) if instr == "TITLE" && result == "Report"));
assert!(s.run("fields.setCode", &json!({"code": ""})).is_err());
assert!(matches!(
s.run("fields.setCode", &json!({"code": ""})),
Err(crate::CmdError::Params(message)) if message == "`code` must be non-empty, at most 4096 UTF-8 bytes, and contain no U+FFFC object markers"
));
// A locked field keeps its result.
s.run("fields.lock", &json!({})).unwrap();
+4 -4
View File
@@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("file.new", "New", "File", new).key("Mod+N").params(r#"{"template"?: "blank|sample|letter|resume|report"}"#).pure(),
CommandSpec::new("file.open", "Open", "File", open)
.key("Mod+O / Mod+F12 / Mod+Alt+F2")
.params(r#"{"path": string, "data"?: base64 (the file's bytes; `path` then only names it), "password"?: string (for a password-protected Word document)}"#)
.params(r#"{"path": string, "data"?: base64 (the file's bytes; `path` then only names it), "password"?: string (for a password-protected Word or OpenDocument text file)}"#)
.pure(),
CommandSpec::new("file.save", "Save", "File", save)
.key("Mod+S / Shift+F12 / Alt+Shift+F2")
@@ -100,7 +100,7 @@ pub fn specs() -> Vec<CommandSpec> {
// Pure: the password must not land in Repeat or a recorded macro, and it isn't an edit
// to undo; it marks the document as changed itself.
CommandSpec::new("file.encrypt", "Encrypt with Password", "File › Info › Protect Document", encrypt)
.params(r#"{"password": string (Word documents are saved encrypted with it) | null or "" (saved unencrypted)}"#)
.params(r#"{"password": string (Word packages and OpenDocument text files (.odt, .ott) are saved encrypted with it) | null or "" (saved unencrypted)}"#)
.pure(),
CommandSpec::new("file.exportPdf", "Export PDF", "File › Export", |s, v| {
// No path (the command search, say): the app asks where to save, as File › Export
@@ -368,8 +368,8 @@ fn close_document(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"closed": id, "active": s.document_id(), "documents": s.documents()}))
}
/// File › Info › Protect Document › Encrypt with Password: the password Word documents are saved
/// with from now on, or none.
/// File › Info › Protect Document › Encrypt with Password: the password Word packages and
/// OpenDocument text files (.odt, .ott) are saved with from now on, or none.
fn encrypt(s: &mut Session, v: &Value) -> CmdResult {
let password = match v.get("password") {
Some(Value::Null) => None,
+1 -1
View File
@@ -336,7 +336,7 @@ fn font(s: &mut Session, v: &Value) -> CmdResult {
let Some(n) = v.get(k) else { return Ok(None) };
let n = n.as_str().map(str::trim).unwrap_or("");
if n.is_empty() || n.len() > 128 {
return Err(CmdError::Params(format!("bad font name `{k}`")));
return Err(CmdError::Params(format!("`{k}` must be a non-empty font name of at most 128 bytes")));
}
Ok(Some(n.to_string()))
};
+4 -2
View File
@@ -51,7 +51,7 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
},
};
if url.is_empty() || url.len() > 4096 {
return Err(CmdError::Params("bad url".into()));
return Err(CmdError::Params("`url` must be non-empty and at most 4096 UTF-8 bytes".into()));
}
let style = Some("Hyperlink".to_string());
if s.sel.is_collapsed() {
@@ -188,7 +188,9 @@ pub(super) fn delete_bookmark(s: &mut Session, v: &Value) -> CmdResult {
pub(super) fn bookmark(s: &mut Session, v: &Value) -> CmdResult {
let name = p::req_str(v, "name")?.trim().to_string();
if !bookmark_name_ok(&name) {
return Err(CmdError::Params("bookmark names start with a letter, have no spaces and at most 40 characters".into()));
return Err(CmdError::Params(
"bookmark names start with a letter or underscore, contain only letters, numbers or underscores, and have at most 40 characters".into(),
));
}
// Replace an existing bookmark of the same name.
remove_bookmark(s, &name)?;
+1 -16
View File
@@ -71,22 +71,7 @@ pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
Some(out)
}
pub fn base64_encode(b: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(b.len().div_ceil(3) * 4);
for ch in b.chunks(3) {
let n =
(ch.first().copied().unwrap_or(0) as u32) << 16 | (ch.get(1).copied().unwrap_or(0) as u32) << 8 | ch.get(2).copied().unwrap_or(0) as u32;
for i in 0..4 {
if i <= ch.len() {
out.push(T[(n >> (18 - 6 * i) & 63) as usize] as char);
} else {
out.push('=');
}
}
}
out
}
pub use craft_mime::transfer::base64 as base64_encode;
pub(crate) fn picture(s: &mut Session, v: &Value) -> CmdResult {
let bytes = if let Some(d) = p::str(v, "data") {
+24 -6
View File
@@ -5,8 +5,7 @@ use super::*;
#[test]
fn a_huge_picture_width_keeps_the_size_finite() {
let img = image::RgbaImage::from_pixel(2, 400, image::Rgba([10, 20, 30, 255]));
let mut png = Vec::new();
image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let png = wordcraft_geom::picture::encode_format(&image::DynamicImage::ImageRgba8(img).clone(), image::ImageFormat::Png).unwrap();
let mut s = Session::new(wordcraft_doc::Document::new());
let r = s.run("insert.picture", &json!({"data": base64_encode(&png), "width": 3e38})).unwrap();
let (w, h) = (r["width"].as_f64().unwrap(), r["height"].as_f64().unwrap());
@@ -17,8 +16,8 @@ fn a_huge_picture_width_keeps_the_size_finite() {
/// A 4 × 4 RGB TIFF that says its strips are JPEG (they aren't): its header still reads.
fn jpeg_strip_tiff() -> Vec<u8> {
let mut t = Vec::new();
image::RgbImage::new(4, 4).write_to(&mut std::io::Cursor::new(&mut t), image::ImageFormat::Tiff).unwrap();
let mut t =
wordcraft_geom::picture::encode_format(&image::DynamicImage::from(image::RgbImage::new(4, 4).clone()), image::ImageFormat::Tiff).unwrap();
assert_eq!(&t[..4], b"II*\0");
let ifd = u32::from_le_bytes(t[4..8].try_into().unwrap()) as usize;
let n = usize::from(u16::from_le_bytes([t[ifd], t[ifd + 1]]));
@@ -37,8 +36,8 @@ fn tiffs_with_jpeg_strips_are_refused() {
let e = s.run("insert.picture", &json!({"data": base64_encode(&tiff)})).unwrap_err().to_string();
assert!(e.contains("TIFF"), "{e}");
assert!(s.doc.media.is_empty());
let mut plain = Vec::new();
image::RgbImage::new(4, 4).write_to(&mut std::io::Cursor::new(&mut plain), image::ImageFormat::Tiff).unwrap();
let plain =
wordcraft_geom::picture::encode_format(&image::DynamicImage::from(image::RgbImage::new(4, 4).clone()), image::ImageFormat::Tiff).unwrap();
s.run("insert.picture", &json!({"data": base64_encode(&plain)})).unwrap();
let e = s.run("picture.change", &json!({"data": base64_encode(&tiff)})).unwrap_err().to_string();
assert!(e.contains("TIFF"), "{e}");
@@ -416,3 +415,22 @@ fn local_civil_date_follows_the_utc_offset() {
assert!(crate::cmd::local_offset_secs(unix).abs() <= 26 * 3600);
}
}
#[test]
fn shared_base64_preserves_command_payload_bytes() {
for (plain, encoded) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foobar", "Zm9vYmFy")] {
assert_eq!(super::objects::base64_encode(plain.as_bytes()), encoded);
}
let bytes: Vec<u8> = (0..513).map(|i| (i % 256) as u8).collect();
for len in 0..=bytes.len() {
let encoded = super::objects::base64_encode(&bytes[..len]);
assert_eq!(encoded.len(), len.div_ceil(3) * 4);
assert!(!encoded.contains(['\r', '\n']));
assert_eq!(super::objects::base64_decode(&encoded), Some(bytes[..len].to_vec()));
}
assert_eq!(super::objects::base64_encode(&[251, 255, 255]), "+///");
// The existing decoder intentionally accepts URL-safe symbols, whitespace and optional padding.
assert_eq!(super::objects::base64_decode("-___"), Some(vec![251, 255, 255]));
assert_eq!(super::objects::base64_decode("Z g\n"), Some(b"f".to_vec()));
assert_eq!(super::objects::base64_decode("!!!!"), None);
}
+3 -2
View File
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
apply_filter(s);
filter_result(s)
})
.params(r#"{"rules"?: [{"field": string, "op": "equal|notEqual|less|greater|lessOrEqual|greaterOrEqual|blank|notBlank|contains|notContains", "value"?: string, "join"?: "and|or" (with the rule before; And binds tighter)}], "sort"?: [{"field": string, "descending"?: bool}]} (replaces the filter; `sort` too when given; {} clears both). Preview, Finish & Merge and labels use only the matching records, in sort order"#)
.params(r#"{"rules"?: [{"field": string, "op": "equal|notEqual|less|greater|lessOrEqual|greaterOrEqual|blank|notBlank|contains|notContains", "value"?: string, "join"?: "and|or" (with the rule before; And binds tighter)}], "sort"?: [{"field": string, "descending"?: bool}]} (replaces the filter; `sort` too when given; `sort` also accepts a field name, one key object or null; array entries may also be field names; {} clears both). Preview, Finish & Merge and labels use only the matching records, in sort order"#)
.when(has_list)
.pure(),
CommandSpec::new("mailings.sortRecipients", "Sort Recipients", "Mailings › Start Mail Merge › Edit Recipient List", |s, v| {
@@ -118,7 +118,7 @@ pub fn specs() -> Vec<CommandSpec> {
apply_filter(s);
filter_result(s)
})
.params(r#"{"sort"?: [{"field": string, "descending"?: bool}]} | {"field": string, "descending"?: bool} (no params: the list's own order)"#)
.params(r#"{"sort"?: [{"field": string, "descending"?: bool}]} | {"field": string, "descending"?: bool} (`sort` also accepts a field name, one key object or null; array entries may also be field names; no params: the list's own order)"#)
.when(has_list)
.pure(),
CommandSpec::new("mailings.insertField", "Insert Merge Field", "Mailings › Write & Insert Fields", |s, v| {
@@ -192,6 +192,7 @@ pub fn specs() -> Vec<CommandSpec> {
refresh(s);
Ok(json!({"record": idx + 1}))
})
.params(r#"{"text": string}"#)
.when(has_recipients),
CommandSpec::new("mailings.checkErrors", "Check for Errors", "Mailings › Finish", |s, _| {
let mut missing = Vec::new();
+1 -1
View File
@@ -255,7 +255,7 @@ pub(super) fn parse_sort(headers: &[String], v: Option<&Value>) -> Result<Vec<So
None | Some(Value::Null) => return Ok(Vec::new()),
Some(Value::Array(a)) => a.clone(),
Some(o @ (Value::Object(_) | Value::String(_))) => vec![o.clone()],
Some(_) => return Err(CmdError::Params("`sort` must be an array of {field, descending}".into())),
Some(_) => return Err(CmdError::Params("`sort` must be a field name, a {field, descending} object, an array of those, or null".into())),
};
if arr.len() > MAX_SORT_KEYS {
return Err(CmdError::Params(format!("at most {MAX_SORT_KEYS} sort keys")));
+3 -2
View File
@@ -107,7 +107,8 @@ fn condition(s: &Session, t: &str, row: usize) -> (bool, Vec<String>) {
let op: String = rest.trim_start().chars().take_while(|c| matches!(c, '<'..='>')).collect();
let mut texts = field_words(rest).into_iter().filter(|(_, q)| *q).map(|(w, _)| w);
let cmp = texts.next().unwrap_or_default();
let v = value(s, row, &field);
let tested = t.split_once('{').and_then(|(_, r)| r.split('}').next()).unwrap_or("");
let v = wordcraft_layout::fields::apply_case_switch(tested, value(s, row, &field));
// Numbers compare as numbers (Word: "7" = "7.0"), everything else as text.
let ord = match (v.trim().parse::<f64>(), cmp.trim().parse::<f64>()) {
(Ok(a), Ok(b)) => a.partial_cmp(&b),
@@ -134,7 +135,7 @@ fn keyword(instr: &str) -> String {
fn act(s: &Session, instr: &str, row: usize) -> Option<Act> {
let t = instr.trim();
if let Some(n) = mergefield_name(t) {
return Some(Act::Text(value(s, row, &n)));
return Some(Act::Text(wordcraft_layout::fields::apply_case_switch(t, value(s, row, &n))));
}
Some(match keyword(t).as_str() {
"ADDRESSBLOCK" => Act::Text(address_block(s, row)),
+33 -10
View File
@@ -147,6 +147,33 @@ fn merge_field_types_ignore_case() {
assert_eq!(s.doc.plain_text(StoryRef::Body), "Alpha\nBeta (b)");
}
/// A merge field's capitalization switch (`\* Upper`, `\* Lower`, `\* Caps`, `\* FirstCap`)
/// applies to the record's value in Preview Results and Finish & Merge.
#[test]
fn merge_fields_apply_their_capitalization_switch() {
let mut s = Session::new(Document::new());
s.run("mailings.recipients", &json!({"rows": [{"City": "new york", "Name": "ADA lovelace"}]})).unwrap();
s.run("insert.field", &json!({"instr": r"MERGEFIELD City \* Upper \* MERGEFORMAT", "result": ""})).unwrap();
s.run("text.insert", &json!({"text": " "})).unwrap();
s.run("insert.field", &json!({"instr": r#"MERGEFIELD "Name" \* Lower"#, "result": ""})).unwrap();
s.run("mailings.preview", &json!({"value": true})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "NEW YORK ada lovelace");
s.run("mailings.finish", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "NEW YORK ada lovelace");
}
/// An IF, NEXTIF or SKIPIF compares the tested merge field after its capitalization switch.
#[test]
fn rule_conditions_apply_the_tested_fields_capitalization_switch() {
let mut s = Session::new(Document::new());
s.run("mailings.recipients", &json!({"rows": [{"City": "new york"}, {"City": "paris"}]})).unwrap();
s.run("insert.field", &json!({"instr": r#"IF { MERGEFIELD City \* Upper } = "NEW YORK" "match" "other""#, "result": ""})).unwrap();
s.run("mailings.preview", &json!({"value": true})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "match");
s.run("mailings.next", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "other");
}
/// An IF is a merge rule only when the field it tests is a MERGEFIELD: the word in a quoted
/// value doesn't make `IF { PAGE } = "mergefield" …` one.
#[test]
@@ -189,22 +216,19 @@ fn merge_end_to_end() {
/// A typed list (#240) keeps its column order, and rows may be arrays in that order.
#[test]
fn recipients_from_a_workbook_ask_for_the_sheet_when_there_are_several() {
use std::io::Write;
let cell = |t: &str| format!(r#"<table:table-cell office:value-type="string"><text:p>{t}</text:p></table:table-cell>"#);
let row = |cells: &[&str]| format!("<table:table-row>{}</table:table-row>", cells.iter().map(|c| cell(c)).collect::<String>());
let content = format!(
r#"<office:document-content xmlns:office="o" xmlns:table="t" xmlns:text="x"><office:body><office:spreadsheet><table:table table:name="Notes">{}</table:table><table:table table:name="Guests">{}{}{}</table:table></office:spreadsheet></office:body></office:document-content>"#,
r#"<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:spreadsheet><table:table table:name="Notes">{}</table:table><table:table table:name="Guests">{}{}{}</table:table></office:spreadsheet></office:body></office:document-content>"#,
row(&["n"]),
row(&["Name", "", "Name"]),
row(&["Ada", "London", "A"]),
row(&["Alan", "Wilmslow", "B"]),
);
let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for (name, body) in [("mimetype", "application/vnd.oasis.opendocument.spreadsheet"), ("content.xml", content.as_str())] {
z.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
z.write_all(body.as_bytes()).unwrap();
}
let data = super::super::insert::base64_encode(&z.finish().unwrap().into_inner());
let mut z = craft_zip::Writer::new();
z.add("mimetype", b"application/vnd.oasis.opendocument.spreadsheet", craft_zip::Compression::Stored).unwrap();
z.add("content.xml", content.as_bytes(), craft_zip::Compression::Deflated).unwrap();
let data = super::super::insert::base64_encode(&z.finish().unwrap());
let mut s = Session::new(Document::new());
// Two sheets and none chosen: the names come back and nothing loads.
let r = s.run("mailings.recipients", &json!({"data": data})).unwrap();
@@ -593,8 +617,7 @@ fn recipients_from_an_xls_workbook() {
let book = wordcraft_formats::sheet::xls_fixture(&[(
"收件人",
vec![row(&["姓名", "城市", "数量"]), row(&["张三", "北京", "12"]), row(&["李四", "上海", "2"])],
)])
.unwrap();
)]);
let mut s = Session::new(Document::new());
let r = s.run("mailings.recipients", &json!({"path": "名单.xls", "data": b64(&book)})).unwrap();
assert_eq!(r, json!({"fields": ["姓名", "城市", "数量"], "records": 2, "sheet": "收件人"}));
+1 -2
View File
@@ -194,8 +194,7 @@ pub(super) fn adjust_media(
e => CmdError::Failed(format!("can't decode the picture: {e}")),
})?;
let out = f(img)?;
let mut png = Vec::new();
out.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| CmdError::Failed(e.to_string()))?;
let png = wordcraft_geom::picture::encode_png(&out).map_err(CmdError::Failed)?;
let key = s.doc.add_media(png, "png");
// Chain onto the ultimate original (the base's, or the current picture's when the base
// is itself derived), so Reset Picture always finds it.
+25 -31
View File
@@ -5,9 +5,8 @@ fn png(w: u32, h: u32) -> Vec<u8> {
let img = image::RgbaImage::from_fn(w, h, |x, y| {
if x > 2 && x < w - 3 && y > 2 && y < h - 3 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([255, 255, 255, 255]) }
});
let mut b = Vec::new();
image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png).unwrap();
b
wordcraft_geom::picture::encode_format(&image::DynamicImage::ImageRgba8(img).clone(), image::ImageFormat::Png).unwrap()
}
/// The laid-out area of the only picture or shape (not a text box).
fn object_area(s: &mut Session) -> wordcraft_layout::hit::ObjectHit {
@@ -451,8 +450,9 @@ fn remove_background_keeps_a_small_stack() {
/// 1 × 2,000,000 picture Thick Frame asked for about 1.8 TB and aborted the process.
#[test]
fn picture_styles_and_borders_check_the_size_they_draw() {
let mut thin = Vec::new();
image::GrayImage::new(1, 2_000_000).write_to(&mut std::io::Cursor::new(&mut thin), image::ImageFormat::Png).unwrap();
let thin =
wordcraft_geom::picture::encode_format(&image::DynamicImage::from(image::GrayImage::new(1, 2_000_000).clone()), image::ImageFormat::Png)
.unwrap();
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.picture", &json!({"data": super::super::insert::base64_encode(&thin)})).unwrap();
let media = s.doc.media.len();
@@ -526,7 +526,7 @@ fn transparency_is_absolute_from_the_original() {
let (_, o) = selected(s).unwrap();
let InlineObject::Image { media, .. } = o else { panic!("a picture") };
let bytes = s.doc.media.get(&media).cloned().unwrap();
image::load_from_memory(&bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>()
wordcraft_geom::picture::decode_memory(&bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>()
};
let alpha = |s: &Session| rgba(s).iter().map(|p| p[3]).collect::<Vec<_>>();
let orig = rgba(&s);
@@ -579,7 +579,7 @@ fn picture_edits_replace_the_file_corrections() {
let (_, o) = selected(s).unwrap();
let InlineObject::Image { media, fx, .. } = o else { panic!("a picture") };
let bytes = s.doc.media.get(&media).cloned().unwrap();
(media, fx, image::load_from_memory(&bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>())
(media, fx, wordcraft_geom::picture::decode_memory(&bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>())
};
let (orig_media, _, orig) = state(&s);
// Transparency 50%: 50% (not 75%), the file's transparency dropped, its lum kept.
@@ -670,7 +670,7 @@ fn picture_styles_borders_and_effects_replace_the_last_one() {
let bitmap = |s: &Session| {
let (_, o) = selected(s).unwrap();
let InlineObject::Image { media, .. } = o else { panic!("a picture") };
image::load_from_memory(&s.doc.media.get(&media).cloned().unwrap()).unwrap().to_rgba8()
wordcraft_geom::picture::decode_memory(&s.doc.media.get(&media).cloned().unwrap()).unwrap().to_rgba8()
};
let after = |cmds: &[(&str, Value)]| {
let mut s = picture();
@@ -1274,9 +1274,9 @@ fn arrange_bounds_on_header_picture_writes_page_anchored_odt_frame() {
assert_eq!((float.h_rel, float.v_rel), (Anchor::Page, Anchor::Page));
assert_eq!((float.x, float.y), (0.0, 0.0));
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_formats::odt::export(&s.doc).unwrap())).unwrap();
let mut styles = String::new();
std::io::Read::read_to_string(&mut z.by_name("styles.xml").unwrap(), &mut styles).unwrap();
let _z_bytes = wordcraft_formats::odt::export(&s.doc).unwrap();
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let styles = String::from_utf8(z.read("styles.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(styles.contains(r#"text:anchor-type="page""#), "frame should be page-anchored: {styles}");
assert!(styles.contains(r#"svg:x="0pt""#) && styles.contains(r#"svg:y="0pt""#), "offsets should be 0pt: {styles}");
assert!(!styles.contains(r#"text:anchor-type="paragraph""#), "frame should not be paragraph-anchored: {styles}");
@@ -1288,9 +1288,9 @@ fn arrange_bounds_on_header_picture_writes_page_anchored_odt_frame() {
assert_eq!((float.h_rel, float.v_rel), (Anchor::Page, Anchor::Page));
assert_eq!((float.x, float.y), (10.0, 20.0));
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_formats::odt::export(&s.doc).unwrap())).unwrap();
let mut styles = String::new();
std::io::Read::read_to_string(&mut z.by_name("styles.xml").unwrap(), &mut styles).unwrap();
let _z_bytes = wordcraft_formats::odt::export(&s.doc).unwrap();
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let styles = String::from_utf8(z.read("styles.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(styles.contains(r#"text:anchor-type="page""#), "{styles}");
assert!(styles.contains(r#"svg:x="10pt""#) && styles.contains(r#"svg:y="20pt""#), "{styles}");
}
@@ -1325,9 +1325,9 @@ fn a_moved_body_picture_is_placed_by_its_paragraph_even_when_fixed_to_the_page()
let hit = s.layout().object(&pos, 0).expect("laid out");
assert!((hit.rect.x - 50.0).abs() < 1.0 && (hit.rect.y - 80.0).abs() < 1.0, "dropped: {:?}", hit.rect);
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_formats::odt::export(&s.doc).unwrap())).unwrap();
let mut content = String::new();
std::io::Read::read_to_string(&mut z.by_name("content.xml").unwrap(), &mut content).unwrap();
let _z_bytes = wordcraft_formats::odt::export(&s.doc).unwrap();
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let content = String::from_utf8(z.read("content.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert!(content.contains(r#"text:anchor-type="paragraph""#), "body picture should export with paragraph anchor: {content}");
assert!(!content.contains("anchor-page-number"), "{content}");
}
@@ -1606,7 +1606,6 @@ fn mirrored_indents_make_no_extra_column() {
/// A Word file whose only paragraph holds a group of a rectangle and Word's own ink (with its
/// picture fallback).
fn group_with_word_ink() -> Vec<u8> {
use std::io::Write;
let ns = 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:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk""#;
let rect = r#"<wps:wsp><wps:cNvPr id="2" name="Box"/><wps:cNvSpPr/><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></wps:spPr><wps:bodyPr/></wps:wsp>"#;
let ink = r#"<mc:AlternateContent><mc:Choice Requires="wpi"><w14:contentPart bwMode="auto" r:id="rInk"><w14:nvContentPartPr><w14:cNvPr id="3" name="Ink 3"/><w14:cNvContentPartPr/></w14:nvContentPartPr><w14:xfrm><a:off x="914400" y="0"/><a:ext cx="914400" cy="457200"/></w14:xfrm></w14:contentPart></mc:Choice><mc:Fallback><pic:pic><pic:nvPicPr><pic:cNvPr id="3" name="Ink 3"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed="rPreview"/></pic:blipFill><pic:spPr><a:xfrm><a:off x="914400" y="0"/><a:ext cx="914400" cy="457200"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></mc:Fallback></mc:AlternateContent>"#;
@@ -1626,14 +1625,12 @@ fn group_with_word_ink() -> Vec<u8> {
),
("word/ink/ink1.xml", r#"<ink xmlns="http://www.w3.org/2003/InkML"><trace>0 0, 1 1</trace></ink>"#.to_string()),
];
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, xml) in parts {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(xml.as_bytes()).unwrap();
zw.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
zw.start_file("word/media/preview.png", zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(&png(8, 4)).unwrap();
zw.finish().unwrap().into_inner()
zw.add("word/media/preview.png", &png(8, 4), craft_zip::Compression::Deflated).unwrap();
zw.finish().unwrap()
}
fn ink_members(doc: &wordcraft_doc::Document) -> usize {
@@ -1653,7 +1650,6 @@ fn ink_members(doc: &wordcraft_doc::Document) -> usize {
/// yet), so open → Ungroup → save → reopen keeps the ink in the group with its part.
#[test]
fn ungroup_refuses_a_group_holding_word_ink_and_the_ink_survives_saving() {
use std::io::Read;
let mut s = Session::new(wordcraft_docx::read(&group_with_word_ink()).unwrap());
assert_eq!(ink_members(&s.doc), 1, "the fixture's ink is read into the group");
let pos = Pos::body(0, 0);
@@ -1666,16 +1662,14 @@ fn ungroup_refuses_a_group_holding_word_ink_and_the_ink_survives_saving() {
let err = ungroup(&mut s, &json!({})).unwrap_err();
assert!(matches!(err, CmdError::Disabled(_)), "{err:?}");
let bytes = wordcraft_docx::write(&s.doc).unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.clone())).unwrap();
let mut xml = String::new();
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
assert_eq!(xml.matches("<w14:contentPart").count(), 1, "{xml}");
assert!(xml.contains("<mc:Fallback>"), "{xml}");
assert_eq!(bytes, before, "the refused ungroup leaves the document unchanged");
let names: Vec<String> = z.file_names().map(String::from).collect();
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
assert_eq!(names.iter().filter(|n| n.starts_with("word/ink/")).count(), 1, "{names:?}");
let mut rels = String::new();
z.by_name("word/_rels/document.xml.rels").unwrap().read_to_string(&mut rels).unwrap();
let rels = String::from_utf8(z.read("word/_rels/document.xml.rels", 16 << 20).unwrap().unwrap()).unwrap();
assert_eq!(rels.matches("/customXml\"").count(), 1, "one ink relationship: {rels}");
let back = wordcraft_docx::read(&bytes).unwrap();
assert_eq!(ink_members(&back), 1);
+1 -1
View File
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("file.options", "Options", "File", options)
.params(
r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: the system locations only), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#,
r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: clear the configured folder), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#,
)
.pure(),
CommandSpec::new("text.overtype", "Overtype", "File › Options › Advanced", |s, v| {
+2 -1
View File
@@ -274,7 +274,8 @@ pub fn specs() -> Vec<CommandSpec> {
st.quick = on;
}
sel_result(s)
}),
})
.params(r#"{"style": string (name or id), "value"?: bool (default true)}"#),
// Advanced paragraph tools (#5043, as in WPS Office): conversions and cleanup over the
// selection, or the whole document with `scope: "all"`. One undo step per command.
CommandSpec::new("para.convertBreaks", "Convert Line Breaks to Paragraphs", "Home › Paragraph › Paragraph Tools", convert_breaks)
+4 -2
View File
@@ -22,7 +22,7 @@ const MODES: [&str; 5] = ["none", "readOnly", "comments", "trackedChanges", "for
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("review.restrict", "Restrict Editing", "Review › Protect", restrict).params(
r#"{"mode"?: "none|readOnly|comments|trackedChanges|forms" (start enforcing; "none" stops), "formatting"?: bool (limit formatting to unlocked styles), "lockedStyles"?: [style id or name] (the styles that can't be applied; every other style is unlocked), "password"?: string (set when enforcing; required to stop a password-protected document), "stop"?: bool, "exception"?: "add" (the selection stays editable for everyone) | "remove" (exceptions touching the selection) | "removeAll"} → state"#,
r#"{"mode"?: "none|readOnly|comments|trackedChanges|forms" (editing restriction; use "none" with "formatting": true for formatting-only protection), "formatting"?: bool (limit formatting to unlocked styles), "lockedStyles"?: [style id or name] (the styles that can't be applied; every other style is unlocked), "password"?: string (set when enforcing; required to stop a password-protected document), "stop"?: bool (true: stop protection), "exception"?: "add" (the selection stays editable for everyone) | "remove" (exceptions touching the selection) | "removeAll"} → state"#,
),
]
}
@@ -431,7 +431,8 @@ enum HoleMode {
/// run formatting and paragraph formatting outside the ranges `author` may edit, in every story,
/// and the formatting of every table, row and cell that holds any of that protected content, and what
/// reaches the whole document: page setup, the document defaults and the existing styles
/// (applying a style may add one), the document's settings and its metadata.
/// (applying a style may add one), the glossary's building blocks, the document's settings and
/// its metadata.
pub(crate) fn outside_unchanged(before: &Document, after: &Document, author: &str) -> bool {
// Protection can't change mid-command (`protection_lifted` guards undo and redo).
let mode = if Some("forms") == before.settings.protection.as_deref() { HoleMode::Controls } else { HoleMode::Perms(author.into()) };
@@ -444,6 +445,7 @@ pub(crate) fn outside_unchanged(before: &Document, after: &Document, author: &st
&& before.settings == after.settings
&& before.core == after.core
&& before.custom_props == after.custom_props
&& before.glossary == after.glossary
&& comments_unchanged(before, after)
&& lists_unchanged(before, after)
&& sources_unchanged(before, after)
+17
View File
@@ -428,6 +428,23 @@ fn the_post_check_compares_the_settings_and_the_metadata() {
assert!(super::outside_unchanged(&before, &before.clone(), "someone"), "an unchanged document isn't unchanged");
}
/// The glossary's building blocks reach the whole document, so the post-check compares them.
#[test]
fn the_post_check_compares_the_glossary() {
use wordcraft_doc::{BuildingBlock, CharProps, Paragraph};
let mut before = Document::from_text("Some text.");
before.glossary.push(BuildingBlock {
name: "g".into(),
blocks: vec![wordcraft_doc::para_block(Paragraph::with_text("Block", Default::default()))],
..Default::default()
});
assert!(super::outside_unchanged(&before, &before.clone(), "someone"), "an unchanged glossary is unchanged");
let mut after = before.clone();
after.glossary[0].blocks[0] =
wordcraft_doc::para_block(Paragraph::with_text("Block", CharProps { lang: Some("fr-FR".into()), ..Default::default() }));
assert!(!super::outside_unchanged(&before, &after, "someone"), "a relanguaged building block is a change");
}
/// Read only, no exceptions: going to a header the document doesn't have doesn't create
/// one, and loading or filtering recipients doesn't rewrite the merge fields' shown results
/// (both used to change the document from a non-mutating command, #1327).
+1 -1
View File
@@ -32,7 +32,7 @@ use toc::{insert_toc, remove_toc, toc_range};
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("references.toc", "Table of Contents", "References › Table of Contents", insert_toc).params(
r#"{"levels"?: 1-9, "title"?: string, "pageNumbers"?: bool, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none", "hyperlinks"?: bool, "headingStyles"?: bool, "outlineLevels"?: bool, "tcFields"?: bool, "styleLevels"?: {style name: 1-9}} (replaces an existing table; {} updates it)"#,
r#"{"levels"?: 1-9, "title"?: string (at most 1024 characters), "pageNumbers"?: bool, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none", "hyperlinks"?: bool, "headingStyles"?: bool, "outlineLevels"?: bool, "tcFields"?: bool, "styleLevels"?: {style name: 1-9}} (replaces an existing table; {} updates it)"#,
),
CommandSpec::new("references.updateToc", "Update Table", "References › Table of Contents", |s, _| {
update_toc(s)?;
+21 -12
View File
@@ -1,6 +1,18 @@
use super::properties::{new_property_value, text_result};
use super::*;
#[test]
fn a_toc_title_is_capped() {
let mut s = Session::new(wordcraft_doc::Document::new());
let before = s.doc.body.len();
let long = "x".repeat(super::toc::MAX_TOC_TITLE + 1);
let r = s.run("references.toc", &json!({"title": long}));
assert!(matches!(r, Err(crate::CmdError::Params(_))), "{r:?}");
assert_eq!(s.doc.body.len(), before, "a rejected title changes nothing");
let at_cap = "x".repeat(super::toc::MAX_TOC_TITLE);
s.run("references.toc", &json!({"title": at_cap})).unwrap();
}
fn fields(s: &Session) -> Vec<(String, String)> {
let mut out = Vec::new();
for path in s.doc.para_paths(StoryRef::Body) {
@@ -56,7 +68,7 @@ fn docx_styleref_header_shows_each_page_s_chapter() {
);
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdH" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/><Relationship Id="rIdS" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, text) in [
("_rels/.rels", root),
("word/document.xml", body.as_str()),
@@ -64,10 +76,9 @@ fn docx_styleref_header_shows_each_page_s_chapter() {
("word/header1.xml", header.as_str()),
("word/styles.xml", styles.as_str()),
] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
std::io::Write::write_all(&mut zw, text.as_bytes()).unwrap();
zw.add(name, text.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
let bytes = zw.finish().unwrap().into_inner();
let bytes = zw.finish().unwrap();
let headers = |s: &mut Session| -> Vec<String> {
s.layout()
.pages
@@ -714,12 +725,11 @@ fn output_numbers_text_box_captions_where_their_boxes_are_anchored() {
let body: String = paras.iter().map(|p| format!("<w:p>{p}</w:p>")).collect();
let document = format!("<w:document {ns}><w:body>{body}<w:sectPr/></w:body></w:document>");
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, text) in [("_rels/.rels", root), ("word/document.xml", document.as_str())] {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
std::io::Write::write_all(&mut zw, text.as_bytes()).unwrap();
zw.add(name, text.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
let s = Session::new(crate::io::open_bytes("boxes.docx", &zw.finish().unwrap().into_inner()).unwrap());
let s = Session::new(crate::io::open_bytes("boxes.docx", &zw.finish().unwrap()).unwrap());
let out = crate::cmd::references::output_fields(&s.doc).expect("fresh numbers");
// The SEQ and REF results in reading order, text boxes where they are anchored.
let mut results = Vec::new();
@@ -774,12 +784,11 @@ fn output_shows_references_to_bookmarks_outside_the_body() {
("word/endnotes.xml", endnotes),
("word/comments.xml", comments),
];
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let mut zw = craft_zip::Writer::new();
for (name, text) in &files {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
std::io::Write::write_all(&mut zw, text.as_bytes()).unwrap();
zw.add(name, text.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
let s = Session::new(crate::io::open_bytes("stories.docx", &zw.finish().unwrap().into_inner()).unwrap());
let s = Session::new(crate::io::open_bytes("stories.docx", &zw.finish().unwrap()).unwrap());
let out = crate::cmd::references::output_fields(&s.doc).expect("fresh references");
let mut results = Vec::new();
for path in out.para_paths(StoryRef::Body) {
+40 -10
View File
@@ -3,6 +3,18 @@ use super::{
StoryRef, TabAlign, TabLeader, TabStop, Value, delete_selection, p, sel_result,
};
/// A table-of-contents title is a heading, not document body: longer titles are rejected
/// instead of laying out megabytes of text (#3720).
pub(super) const MAX_TOC_TITLE: usize = 1024;
fn checked_title(v: &Value) -> Result<Option<&str>, CmdError> {
let Some(title) = p::str(v, "title") else { return Ok(None) };
if title.chars().count() > MAX_TOC_TITLE {
return Err(CmdError::Params(format!("`title` is longer than {MAX_TOC_TITLE} characters")));
}
Ok(Some(title))
}
/// A level range such as `1-3` (or one level, `2`), clamped to 1–9.
pub fn level_range(s: &str) -> Option<(u8, u8)> {
let mut it = s.split('-').map(|x| x.trim().parse::<u8>().ok());
@@ -67,13 +79,15 @@ pub fn toc_instr(v: &Value) -> String {
s
}
/// A TOC entry: the paragraph it points at, its level (0-based), its text, and the leading page
/// breaks of that paragraph (its page is where the text after them lands).
/// A TOC entry: the paragraph it points at, its level (0-based), its text, the leading page
/// breaks of that paragraph (its page is where the text after them lands), and, for a number
/// followed by a tab, how far the heading's text starts after where its number starts.
struct TocEntry {
path: Path,
level: u8,
text: String,
lead: usize,
number_gap: Option<f32>,
}
/// The headings of the body, in document order, as (body block, level 1–9, text, leading page
@@ -117,9 +131,13 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
.and_then(|n| counters.next_label(&s.doc.numbering, n.num, n.level))
.filter(|(label, def)| !label.is_empty() && !matches!(def.format, NumFormat::Bullet | NumFormat::None))
.map(|(label, def)| match def.suffix {
LevelSuffix::Tab => format!("{label}\t"),
LevelSuffix::Space => format!("{label} "),
LevelSuffix::Nothing => label,
LevelSuffix::Tab => {
let start = def.indent - def.hanging;
let gap = def.tab.filter(|t| *t > start).unwrap_or(def.indent) - start;
(format!("{label}\t"), Some(gap).filter(|g| g.is_finite() && *g > 0.0))
}
LevelSuffix::Space => (format!("{label} "), None),
LevelSuffix::Nothing => (label, None),
});
let style = p.props.style.as_deref().unwrap_or("Normal");
if style.starts_with("TOC") {
@@ -144,8 +162,9 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
if let Some(l) = by_style.or(by_outline).or(if hidden { None } else { by_heading }) {
let t = p.plain_text().replace(['\u{000C}', '\n', '\t'], " ").trim().to_string();
if !t.is_empty() {
let text = number.map_or_else(|| t.clone(), |n| format!("{n}{t}"));
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead });
let text = number.as_ref().map_or_else(|| t.clone(), |(n, _)| format!("{n}{t}"));
let number_gap = number.as_ref().and_then(|(_, g)| *g);
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead, number_gap });
}
}
if let Some(id) = &tc {
@@ -159,7 +178,7 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
let l = c.arg('l').and_then(|l| l.trim().parse::<u8>().ok()).unwrap_or(1).clamp(1, 9);
let text = c.args.first().map(|t| t.trim().to_string()).unwrap_or_default();
if (id.is_empty() || *id == kind) && (tc_levels.0..=tc_levels.1).contains(&l) && !text.is_empty() {
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead: off });
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead: off, number_gap: None });
}
}
}
@@ -375,6 +394,7 @@ pub(super) fn cached_toc_tabs(s: &Session) -> Vec<(String, Vec<TabStop>)> {
}
pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
let title = checked_title(v)?.unwrap_or("Contents").to_string();
let tabs = cached_toc_tabs(s);
range_toc_to_field(s)?;
let replace = v.as_object().is_some_and(|m| !m.is_empty());
@@ -403,7 +423,6 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
}
None => delete_selection(s)?,
};
let title = p::str(v, "title").unwrap_or("Contents").to_string();
if at.story != StoryRef::Body || at.path.depth() > 0 {
return Err(CmdError::Failed("a table of contents goes in the main text".into()));
}
@@ -433,6 +452,7 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
/// (`title_above_break`): the field takes `v`'s settings, the title `v`'s `title` if one is given
/// (otherwise it is kept, as Word's Insert Table of Contents keeps it), and the entries are rebuilt.
fn replace_toc_above_break(s: &mut Session, v: &Value, start: usize, tabs: &[(String, Vec<TabStop>)]) -> Result<(), CmdError> {
let new_title = checked_title(v)?;
let instr = toc_instr(v);
let field = s.doc.para_mut(StoryRef::Body, &Path::top(start))?;
for o in &mut field.objects {
@@ -446,7 +466,7 @@ fn replace_toc_above_break(s: &mut Session, v: &Value, start: usize, tabs: &[(St
}
}
field.touch();
if let (Some(title), Some(i)) = (p::str(v, "title"), start.checked_sub(1)) {
if let (Some(title), Some(i)) = (new_title, start.checked_sub(1)) {
let old = s.doc.para_mut(StoryRef::Body, &Path::top(i))?;
let mut head = Paragraph::with_text(title, old.props_of_char(0).clone());
head.props = old.props.clone();
@@ -595,6 +615,16 @@ fn regenerate_toc(s: &mut Session, leader: Option<TabLeader>, tabs: &[(String, V
para.mark = CharProps::default();
if e.text.contains('\t') {
para.props.tabs = tabs.iter().find(|(style, _)| Some(style) == para.props.style.as_ref()).map(|(_, tabs)| tabs.clone());
// Without a stop for the number (LibreOffice's Contents styles have only the page
// number's right stop), its tab would run to the page number: the entry gets a
// left stop as far after its indent as the heading's text is after its number.
let style = s.doc.styles.resolve_para(&para.props);
let has_stop =
style.tabs.iter().any(|t| t.pos < width - 1.0 && matches!(t.align, TabAlign::Left | TabAlign::Center | TabAlign::Decimal));
if let (None, false, Some(gap)) = (&para.props.tabs, has_stop, e.number_gap) {
let pos = style.indent_left.max(0.0) + gap;
para.props.tabs = (pos < width - 1.0).then(|| vec![TabStop { pos, align: TabAlign::Left, leader: TabLeader::None }]);
}
}
if show_page && sep.contains('\t') {
let right = TabStop { pos: width - 0.5, align: TabAlign::Right, leader };
+4 -4
View File
@@ -28,12 +28,12 @@ pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("review.newComment", "New Comment", "Review › Comments", new_comment).key(super::mac_or("Mod+Alt+A / Mod+Alt+M", "Mod+Alt+M")).params(r#"{"text": string}"#),
CommandSpec::new("review.reply", "Reply", "Review › Comments", reply)
.params(r#"{"id": non-negative JSON integer, "text": string}"#)
.params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#)
.when(comments_change),
CommandSpec::new("review.editComment", "Edit Comment", "Review › Comments", edit_comment)
.params(r#"{"id": non-negative JSON integer, "text": string}"#)
.params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#)
.when(comments_change),
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative JSON integer (omit to use the caret), "all"?: bool}"#),
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool}"#),
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", |s, v| {
validate_comment_id(v)?;
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
c.resolved = p::bool(v, "value").unwrap_or(!c.resolved);
sel_result(s)
})
.params(r#"{"id"?: non-negative JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
.params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
CommandSpec::new("review.nextComment", "Next", "Review › Comments", |s, _| nav_comment(s, 1)).pure(),
CommandSpec::new("review.previousComment", "Previous", "Review › Comments", |s, _| nav_comment(s, -1)).pure(),
CommandSpec::new("review.comments", "Show Comments", "Review › Comments", list_comments).pure(),
+9 -9
View File
@@ -28,7 +28,7 @@ const ITEMS: &str = r#"[string | {"text": string, "level"?: 0-7, "color"?: RRGGB
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("insert.smartArt", "SmartArt", "Insert › Illustrations", insert).params(
CommandSpec::new("insert.smartArt", "Diagram", "Insert › Illustrations", insert).params(
r#"{"layout"?: "basicList|process|cycle|hierarchy|pyramid|radial|matrix|venn", "items"?: [string | {"text": string, "level"?: 0-7, "color"?: RRGGBB}], "colors"?: "accent1…accent6|colorful", "width"?: pt, "height"?: pt} (no items: sample items for the layout)"#,
),
CommandSpec::new("smartArt.items", "Edit Items", "SmartArt Design › Create Graphic", |s, v| {
@@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
let below = p::bool(v, "below").unwrap_or(false);
edit(s, move |g| {
if g.items.len() >= MAX_ITEMS {
return Err(CmdError::Failed(format!("a SmartArt graphic holds at most {MAX_ITEMS} items")));
return Err(CmdError::Failed(format!("a diagram holds at most {MAX_ITEMS} items")));
}
let Some(last) = g.items.len().checked_sub(1) else {
g.items.push(SmartArtItem::new(text.clone(), 0));
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
})
.params(r#"{"layout": "basicList|process|cycle|hierarchy|pyramid|radial|matrix|venn"}"#)
.when(has_smart_art),
CommandSpec::new("smartArt.colors", "Change Colors", "SmartArt Design › SmartArt Styles", |s, v| {
CommandSpec::new("smartArt.colors", "Change Colors", "SmartArt Design › Diagram Styles", |s, v| {
let colors = colors_of(v)?.ok_or_else(|| CmdError::Params(format!("`variant` is required: {COLORS}")))?;
edit(s, move |g| {
g.colors = colors;
@@ -130,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> {
})
.params(r#"{"variant": "accent1|accent2|accent3|accent4|accent5|accent6|colorful"} (the items' own colours are dropped)"#)
.when(has_smart_art),
CommandSpec::new("smartArt.itemColor", "Item Color", "SmartArt Design › SmartArt Styles", |s, v| {
CommandSpec::new("smartArt.itemColor", "Item Color", "SmartArt Design › Diagram Styles", |s, v| {
let i = index(v, "index")?;
let color = match v.get("color") {
None | Some(Value::Null) => None,
@@ -174,9 +174,9 @@ fn has_smart_art(s: &Session) -> Option<&'static str> {
match selected(s) {
Some((_, InlineObject::Graphic { graphic, .. })) if graphic.smart_art.is_some() => None,
Some((_, InlineObject::Graphic { graphic, .. })) if graphic.kind == GraphicKind::Diagram => {
Some("this SmartArt was made in another program: WordCraft shows it but can't edit it")
Some("this diagram was made in another program: WordCraft shows it but can't edit it")
}
_ => Some("select a SmartArt graphic first"),
_ => Some("select a diagram first"),
}
}
@@ -299,9 +299,9 @@ fn insert(s: &mut Session, v: &Value) -> CmdResult {
/// Change the selected graphic's model with `f`, then lay it out again at its size.
fn edit(s: &mut Session, f: impl Fn(&mut SmartArtSpec) -> Result<(), CmdError>) -> CmdResult {
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("select a SmartArt graphic first".into()))?;
let InlineObject::Graphic { w, h, graphic, .. } = obj else { return Err(CmdError::Disabled("select a SmartArt graphic first".into())) };
let mut spec = graphic.smart_art.as_deref().cloned().ok_or_else(|| CmdError::Disabled("this SmartArt graphic can't be edited".into()))?;
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("select a diagram first".into()))?;
let InlineObject::Graphic { w, h, graphic, .. } = obj else { return Err(CmdError::Disabled("select a diagram first".into())) };
let mut spec = graphic.smart_art.as_deref().cloned().ok_or_else(|| CmdError::Disabled("this diagram can't be edited".into()))?;
f(&mut spec)?;
let next = Arc::new(smart_art_graphic(spec, &s.doc.settings.theme_colors, w, h));
let out = json!({"smartArt": next.smart_art.as_deref()});
+86 -3
View File
@@ -1,4 +1,5 @@
use super::{Arc, CmdError, CmdResult, Document, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p, sel_result};
use wordcraft_doc::CharProps;
/// Options › Language › Set as default: only the saved default proofing language (what future
/// blank documents are written in), as Word's Set as Preferred. A setting, like `file.options`: the
@@ -14,8 +15,19 @@ pub(super) fn preferred_language(s: &mut Session, v: &Value) -> CmdResult {
/// Set Proofing Language: the selection's language and "do not check spelling or grammar",
/// or (`default`) the document's default and the saved language for future blank documents;
/// `detect` is the per-user detection preference.
/// Nothing at all sets US English, as before.
/// Nothing at all sets US English, as before. `scope: "document"` sets it for every story.
pub(super) fn language(s: &mut Session, v: &Value) -> CmdResult {
// Checked first, so a bad scope changes nothing (not even the detect preference).
let whole_document = match v.get("scope") {
None | Some(Value::Null) => false,
Some(Value::String(t)) if t == "selection" => false,
Some(Value::String(t)) if t == "document" => true,
Some(other) => return Err(CmdError::Params(format!("`scope` must be \"selection\" or \"document\", not {other}"))),
};
// Protection leaves only its exceptions editable, so the whole document can't be one.
if whole_document && let Some(mode) = s.doc.settings.protection.as_deref() {
return Err(CmdError::Disabled(format!("review.language: stop protection ({mode}) before changing the whole document's proofing language")));
}
let lang = match p::str(v, "lang") {
Some(t) => Some(
wordcraft_proof::lang::normalize_tag(t)
@@ -45,20 +57,91 @@ pub(super) fn language(s: &mut Session, v: &Value) -> CmdResult {
if lang.is_none() && no_proof.is_none() {
return Ok(json!({"detect": s.prefs.detect_language}));
}
let result = crate::cmd::format::apply(s, &|c| {
let change = |c: &mut CharProps| {
if let Some(l) = &lang {
c.lang = Some(l.clone());
}
if let Some(np) = no_proof {
c.no_proof = Some(np);
}
})?;
};
let result = if whole_document {
let glossary_skipped = set_document_props(s, &change)?;
// The same caret/selection result as the selection path (the selection is untouched).
let mut r = sel_result(s)?;
if let Some(m) = r.as_object_mut() {
m.insert("scope".into(), json!("document"));
if glossary_skipped {
m.insert("glossarySkipped".into(), json!(true));
}
}
r
} else {
crate::cmd::format::apply(s, &change)?
};
if p::bool(v, "default") == Some(true) {
s.prefs.default_language = lang;
}
Ok(result)
}
/// Apply `f` to the character formatting of every story of the document (Language dialog, "Apply
/// to the whole document"): text and paragraph marks of the body, headers, footers, notes,
/// comments, text boxes (all `Document::parts`), table cells, and the glossary's building blocks.
/// The selection is untouched; formatting waiting for typing follows.
///
/// Glossary blocks are left alone while Track Changes and Track Formatting are both on: tracked
/// formatting (`fmt_revisions::record`) compares only the body and the parts, so a glossary change
/// would be an untracked edit. So those blocks keep their old language while tracking; the caller
/// reports it (`glossarySkipped`). Returns whether the glossary was skipped.
fn set_document_props(s: &mut Session, f: &dyn Fn(&mut CharProps)) -> Result<bool, CmdError> {
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
for story in stories {
for path in s.doc.para_paths(story) {
let para = s.doc.para_mut(story, &path)?;
let len = para.len();
para.format(0, len, f)?;
f(&mut para.mark);
para.touch();
}
}
let skipped = s.doc.settings.track_changes && s.prefs.markup.track_formatting;
if !skipped {
for block in &mut s.doc.glossary {
format_blocks(&mut block.blocks, f, 0);
}
}
if let Some(pend) = s.pending.as_mut() {
f(pend);
}
Ok(skipped)
}
/// [`set_document_props`] for a block list outside any story (depth-limited like `para_paths`).
fn format_blocks(blocks: &mut wordcraft_doc::Blocks, f: &dyn Fn(&mut CharProps), depth: usize) {
if depth > wordcraft_doc::PARA_WALK_DEPTH {
return;
}
for blk in blocks.iter_mut() {
match Arc::make_mut(blk) {
wordcraft_doc::Block::Para(p) => {
let len = p.len();
// A range inside the paragraph can't fail; the mark is formatted regardless.
let _ = p.format(0, len, f);
f(&mut p.mark);
p.touch();
}
wordcraft_doc::Block::Table(t) => {
for row in &mut t.rows {
for cell in &mut row.cells {
format_blocks(&mut cell.blocks, f, depth + 1);
}
}
}
}
}
}
pub(super) fn macros(s: &mut Session, v: &Value) -> CmdResult {
if let Some(d) = v.get("define") {
let name = d.get("name").and_then(Value::as_str).unwrap_or("Macro").to_string();
+135 -26
View File
@@ -34,6 +34,7 @@ struct DiffCtx<'a> {
opts: &'a CompareOptions,
budget: &'a mut u64,
char_fallbacks: &'a mut usize,
plain_revised: bool,
}
/// Changed paragraphs longer than this (in characters) are compared word by word even at
@@ -48,10 +49,12 @@ const MAX_CHAR_DIFF: usize = 2000;
/// [`MAX_CHAR_DIFF`] characters, it falls back to word-level diff for that paragraph, surfaces the
/// fallback count in `"characterFallback"`, and includes `"level"` in `"notHonoured"`.
pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
let revised = if let Some(t) = p::str(v, "text") {
Document::from_text(t)
// A revised side given as plain text carries no real runs or properties; one opened from a
// path does. The diff takes the revised formatting only in the latter case.
let (revised, plain_revised) = if let Some(t) = p::str(v, "text") {
(Document::from_text(t), true)
} else if let Some(path) = p::str(v, "path") {
crate::io::open_path(std::path::Path::new(path)).map_err(CmdError::Failed)?
(crate::io::open_path(std::path::Path::new(path)).map_err(CmdError::Failed)?, false)
} else {
return Err(CmdError::Params("`path` or `text` of the revised document is required".into()));
};
@@ -97,7 +100,7 @@ pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
let mut budget = MAX_COMPARE_CELLS;
let mut char_fallbacks = 0usize;
let ops = lcs_ops(&old.iter().map(key).collect::<Vec<_>>(), &new.iter().map(key).collect::<Vec<_>>(), &mut budget);
let mut ctx = DiffCtx { ins, del, opts: &opts, budget: &mut budget, char_fallbacks: &mut char_fallbacks };
let mut ctx = DiffCtx { ins, del, opts: &opts, budget: &mut budget, char_fallbacks: &mut char_fallbacks, plain_revised };
let mut out: Vec<Arc<Block>> = Vec::new();
let (mut i, mut j) = (0usize, 0usize);
let mut changes = 0usize;
@@ -393,9 +396,11 @@ fn flatten_region(out: &mut Vec<Op>, region: &[(Op, usize, Kind)]) {
/// A token of a changed paragraph: a word (or character), or an inline object without text
/// of its own (a text box anchor, a picture, a bookmark…), which is compared and kept whole.
/// Each token also carries the byte range it came from in its source paragraph, so the output
/// segment can take the formatting of the run it came from instead of the paragraph's first run.
enum Tok<'a> {
Text(String),
Obj(&'a InlineObject),
Text(String, std::ops::Range<usize>),
Obj(&'a InlineObject, std::ops::Range<usize>),
}
/// What a comparison sees of a token: the text as the options say, an object with the text of
@@ -421,52 +426,131 @@ fn same_objects(doc: &Document, a: &Paragraph, b: &Paragraph) -> bool {
}
/// Words with the spaces after them ("The ", "cat "), or single characters, and the objects
/// between them. Objects with text (fields, equations…) count as their text.
/// between them. Objects with text (fields, equations…) count as their text. Each token records
/// the byte range it came from in `p`, so its output segment can take that source run's
/// formatting. An object's flattened text (or a broken marker's placeholder) maps to the marker's
/// own range, which is the nearest formatting the object has.
fn tokens(p: &Paragraph, characters: bool) -> Vec<Tok<'_>> {
fn push(v: &mut Vec<Tok<'_>>, cur: &mut String, c: char, characters: bool) {
fn push(v: &mut Vec<Tok<'_>>, cur: &mut String, start: usize, end: usize, c: char, characters: bool) {
cur.push(c);
if characters || c == ' ' {
v.push(Tok::Text(std::mem::take(cur)));
v.push(Tok::Text(std::mem::take(cur), start..end));
}
}
let mut v = Vec::new();
let mut cur = String::new();
let mut cur_start = 0usize;
let mut objects = p.objects.iter();
for c in p.text.chars() {
for (i, c) in p.text.char_indices() {
let marker = i..i + OBJ.len_utf8();
if c != OBJ {
push(&mut v, &mut cur, c, characters);
if cur.is_empty() {
cur_start = i;
}
push(&mut v, &mut cur, cur_start, i + c.len_utf8(), c, characters);
continue;
}
match objects.next() {
Some(o) if o.plain_text().is_empty() => {
if !cur.is_empty() {
v.push(Tok::Text(std::mem::take(&mut cur)));
v.push(Tok::Text(std::mem::take(&mut cur), cur_start..i));
}
v.push(Tok::Obj(o, marker));
}
Some(o) => {
for c in o.plain_text().chars() {
if cur.is_empty() {
cur_start = i;
}
push(&mut v, &mut cur, cur_start, marker.end, c, characters);
}
v.push(Tok::Obj(o));
}
Some(o) => o.plain_text().chars().for_each(|c| push(&mut v, &mut cur, c, characters)),
None => {
// A marker without its object (a broken paragraph): kept as a visible
// placeholder, so the loss shows in the result instead of vanishing.
log::warn!("compare: an object marker without its object");
push(&mut v, &mut cur, char::REPLACEMENT_CHARACTER, characters);
if cur.is_empty() {
cur_start = i;
}
push(&mut v, &mut cur, cur_start, marker.end, char::REPLACEMENT_CHARACTER, characters);
}
}
}
if !cur.is_empty() {
v.push(Tok::Text(cur));
v.push(Tok::Text(cur, cur_start..p.text.len()));
}
v
}
/// One side's run formatting for `word_diff`: the paragraph's run ranges (from
/// [`Paragraph::run_ranges`]), walked with a forward cursor. `word_diff` consumes each side's
/// tokens in increasing offset order, so the cursor makes a token's lookup amortised O(1)
/// instead of rescanning the runs from the start for every token; an out-of-order offset falls
/// back to a binary search, so the lookup stays correct for any offset.
struct SideProps<'a> {
ranges: Vec<(std::ops::Range<usize>, &'a CharProps)>,
mark: &'a CharProps,
cursor: usize,
}
impl<'a> SideProps<'a> {
fn new(p: &'a Paragraph) -> Self {
SideProps { ranges: p.run_ranges().collect(), mark: &p.mark, cursor: 0 }
}
/// The props of the run holding byte `off`: that run's props, or the paragraph mark when
/// `off` is past the last run — the same answer `Paragraph::props_of_char` gives.
fn run_props(&mut self, off: usize) -> &'a CharProps {
while self.cursor < self.ranges.len() && self.ranges[self.cursor].0.end <= off {
self.cursor += 1;
}
if let Some((range, props)) = self.ranges.get(self.cursor)
&& range.contains(&off)
{
return props;
}
let idx = self.ranges.partition_point(|(r, _)| r.start <= off);
match idx.checked_sub(1).and_then(|i| self.ranges.get(i)) {
Some((range, props)) if range.contains(&off) => props,
_ => self.mark,
}
}
/// The formatting of the source run a token came from: the run holding the token's first
/// byte, with the revision metadata stripped. `ins`, `del` and `fmt_change` are indices into
/// the *source* document's own revision table, and the rebuilt paragraph lives in the result
/// document, whose table is a different one, so a source mark can never be carried across;
/// `word_diff` stamps the compare's own `ins`/`del` on the segments it marks. The consequence
/// is plain: a pre-existing pending revision inside a changed paragraph (say another author's
/// deletion) is superseded by the compare result rather than preserved. The hyperlink is
/// kept, because Reject restores it on a deleted run (at token granularity: the link is taken
/// from the token's first byte, so a token that starts unlinked can lose a mid-token link).
fn props_of(&mut self, t: &Tok<'_>) -> CharProps {
let off = match t {
Tok::Text(_, range) | Tok::Obj(_, range) => range.start,
};
let c = self.run_props(off);
CharProps { ins: None, del: None, fmt_change: None, ..c.clone() }
}
}
/// The props of an output token: those of the source run it came from, or — never expected, since
/// [`tokens`] and [`lcs_ops`] consume both sides in step — the given fallback. A miss is loud.
fn output_props(side: &mut SideProps<'_>, t: Option<&Tok<'_>>, fallback: &CharProps) -> CharProps {
if t.is_none() {
log::warn!("compare: a token range lookup missed; `tokens` and `lcs_ops` are out of step");
}
t.map(|t| side.props_of(t)).unwrap_or_else(|| fallback.clone())
}
/// Add a token at the end of `p` with `props`.
fn put(p: &mut Paragraph, t: Option<&Tok<'_>>, props: &CharProps) {
let at = p.len();
match t {
Some(Tok::Text(t)) => {
Some(Tok::Text(t, _)) => {
let _ = p.insert_text(at, t, props);
}
Some(Tok::Obj(o)) => {
Some(Tok::Obj(o, _)) => {
let _ = p.insert_object(at, (*o).clone(), props);
}
None => {}
@@ -500,10 +584,12 @@ fn word_diff(doc: &Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx<'_>
} else {
false
};
let plain_revised = ctx.plain_revised;
let (ta, tb) = (tokens(a, chars), tokens(b, chars));
let (mut a_props, mut b_props) = (SideProps::new(a), SideProps::new(b));
let key = |t: &Tok<'_>| match t {
Tok::Text(t) => Key::Text(ctx.opts.key(t)),
Tok::Obj(o) => obj_key(doc, o),
Tok::Text(t, _) => Key::Text(ctx.opts.key(t)),
Tok::Obj(o, _) => obj_key(doc, o),
};
let ops = lcs_ops(&ta.iter().map(key).collect::<Vec<_>>(), &tb.iter().map(key).collect::<Vec<_>>(), ctx.budget);
// Only at character granularity: a matched whole word almost never happens by coincidence,
@@ -511,23 +597,46 @@ fn word_diff(doc: &Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx<'_>
// a short interior match need folding back into its surrounding edit.
let ops = if chars { collapse_noise_matches(&ops) } else { ops };
let mut p = Paragraph::new();
p.props = b.props.clone();
let base = a.runs.first().map(|r| r.props.clone()).unwrap_or_default();
// The revised paragraph's properties are used with its revision bookkeeping stripped, like runs
// (`SideProps::props_of`) and the mark, because `fmt_change`/`num_change` are indices into the revised
// document's own revision table and are meaningless in the result document. A plain-text
// revised side, which carries no paragraph properties of its own, falls back to the original's,
// stripped the same way, so pre-existing revision state never leaks into the rebuilt paragraph.
p.props = if plain_revised && b.props.is_empty() { a.props.formatting() } else { b.props.formatting() };
// The paragraph mark (the formatting typing into the paragraph's end would get) is the revised
// paragraph's when it comes from a document, and the original's when the revised side is plain
// text and has no mark of its own. Its own revision bookkeeping (`ins`, `del`, `fmt_change`)
// is cleared because those indices belong to another document's revision table.
p.mark = if plain_revised {
CharProps { ins: None, del: None, fmt_change: None, ..a.mark.clone() }
} else {
CharProps { ins: None, del: None, fmt_change: None, ..b.mark.clone() }
};
let fallback = a.runs.first().map(|r| CharProps { ins: None, del: None, fmt_change: None, ..r.props.clone() }).unwrap_or_default();
let fallback_b = b.runs.first().map(|r| CharProps { ins: None, del: None, fmt_change: None, ..r.props.clone() }).unwrap_or_default();
let (mut i, mut j) = (0, 0);
for op in ops {
match op {
Op::Same => {
// Equal as compared (perhaps up to case or spacing): the revised text.
put(&mut p, tb.get(j), &base);
// Equal as compared (perhaps up to case or spacing): the revised text, but the
// formatting of the run it stands for. For a document revised side that is the
// revised run, as issue #3749 prescribes ("Copy unchanged tokens from the revised
// paragraph with their own properties"); a plain-text revised side has no runs to
// speak of, so the original run's formatting is kept instead.
let props =
if plain_revised { output_props(&mut a_props, ta.get(i), &fallback) } else { output_props(&mut b_props, tb.get(j), &fallback_b) };
put(&mut p, tb.get(j), &props);
i += 1;
j += 1;
}
Op::Del => {
put(&mut p, ta.get(i), &CharProps { del: Some(ctx.del), ..base.clone() });
let props = output_props(&mut a_props, ta.get(i), &fallback);
put(&mut p, ta.get(i), &CharProps { del: Some(ctx.del), ..props });
i += 1;
}
Op::Ins => {
put(&mut p, tb.get(j), &CharProps { ins: Some(ctx.ins), ..base.clone() });
let props = tb.get(j).map(|t| b_props.props_of(t)).unwrap_or_else(|| fallback.clone());
put(&mut p, tb.get(j), &CharProps { ins: Some(ctx.ins), ..props });
j += 1;
}
}
+1 -1
View File
@@ -340,7 +340,7 @@ pub fn specs() -> Vec<CommandSpec> {
})
.params(r#"{"format": "decimal|upperRoman|lowerLetter…", "text"?: "%1.", "start"?: n}"#),
CommandSpec::new("review.language", "Language", "Review › Language", language).params(
r#"{"lang"?: "en-US|en-GB|pl-PL|fr-FR|…" (BCP 47; default en-US), "noProof"?: bool, "detect"?: bool (detect language automatically, a preference), "default"?: bool (also the document's default and the saved language for future blank documents)}"#,
r#"{"lang"?: "en-US|en-GB|pl-PL|fr-FR|…" (BCP 47; default en-US), "noProof"?: bool, "detect"?: bool (detect language automatically, a preference), "default"?: bool (also the document's default and the saved language for future blank documents), "scope"?: "selection" (default) | "document" (every run and paragraph mark of every story: body, headers, footers, notes, comments, text boxes, tables, glossary (skipped while Track Changes and Track Formatting are on); one undo step, selection unchanged; returns the caret, "scope":"document" and "glossarySkipped":true when the glossary was skipped)}"#,
),
CommandSpec::new("review.language.preferred", "Set as Default Language", "File › Options › Language", preferred_language)
.params(r#"{"lang": "en-US|en-GB|pl-PL|nl-NL|…" (BCP 47)} — only the saved default proofing language, what future blank documents are written in, as Options › Language › Set as default does; the open document, the selection and the undo history don't change. Returns {"preferred": tag}."#)

Some files were not shown because too many files have changed in this diff Show More