Compare commits

..
Author SHA1 Message Date
FredApps f7db2c5845 Merge remote-tracking branch 'origin/main' into tc14-6913 2026-11-26 17:19:13 +07:00
FredApps 5239535f19 Merge remote-tracking branch 'origin/main' into tc14-6913 2026-11-26 16:37:47 +07:00
Martin BallandClaude Opus 5.5 39aa564f56 #4134: joined text's later lines clear the shared line when a large word wraps
The area that keeps a continuation's later lines below the shared line now starts just below the first row at the line breaker's row estimate, which is what the breaker tests rows with. The probe's first line can be taller than the real one when a large word fits it but wraps off the narrower shared line, and starting the area below that taller line let the real second line start inside the heading's line. The test adds a 30 pt word at three places that wrap it to the second line, in the body and in a cell.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-11-26 01:18:06 +00:00
Martin BallandClaude Opus 5.5 4c9614df84 #4134: joined text's first line shares the line again with exact spacing
The area that holds a joined paragraph's later lines below a taller shared
line started just below its first line. The line breaker checks a row
against wrap areas at its own estimate, the mark's font height, which is
taller than an exact line height below it: the first row then met the area
and moved below the shared line. The area now starts below whichever is
taller, so the first line shares the line under every line spacing rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-11-26 01:11:28 +00:00
Martin BallandClaude Opus 5.5 0b09f41983 #4134: joined text's later lines start below a taller shared line; table frames don't join
A paragraph going on from the line of one whose mark is hidden kept only its
first line clear of that line: under a taller heading its second line started
inside the heading's line, back at the left margin. Its later lines now keep
clear of the rest of the shared line, with the room for its bottom border, in
the body and in boxes (cells, headers, text boxes).

The guard against joining a text frame resolves the paragraph with the table's
paragraph formatting, as its layout does, so a frame given by the table style
is placed apart with its list number instead of joining.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 00:59:00 +00:00
Martin Ball 349d6ee444 Merge remote-tracking branch 'origin/main' into land/4134 2026-11-25 23:09:21 +00:00
Martin BallandClaude Opus 5.5 4d70405ab4 Layout: hidden-mark join fixes from review of #6913
- A paragraph moved off the shared line (next column or page) gets its
  own top and bottom border room again (flow.rs `Rooms` were stale).
- Hit testing cuts a line at a joined paragraph only when that paragraph
  still shares the line (`shares_line`), not when its first word wrapped below.
- A cell or header paragraph going on from a hidden mark takes the shared
  line's top as its paragraph origin, so paragraph-anchored drawings follow it.
- A text frame is placed apart: it is not joined, keeps its number.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 18:11:08 +00:00
bd3ca8d3ab Layout: a paragraph with a hidden mark is shown on one line with the next one (#3986) (#4134)
Lands #4134 rebased onto main; only docs conflicts were resolved (both sides kept).

Co-Authored-By: Menonro <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXtSjB6e5jmy9Uq7u8
2026-11-24 08:19:07 +00:00
219 changed files with 1422 additions and 263092 deletions
+1 -12
View File
@@ -2,15 +2,4 @@
# (#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
# These model sources and generated tables have byte hashes recorded in model/README.md.
# Keep checkout bytes stable even when core.autocrlf=true.
crates/validate/model/extract_content_model.py text eol=lf
crates/validate/model/generate_model.py text eol=lf
crates/validate/model/content_model_v2.json text eol=lf
crates/validate/model/content_model_v2_transitional.json text eol=lf
crates/validate/model/content_model_dml_v2.json text eol=lf
crates/validate/model/content_model_dml_v2_transitional.json text eol=lf
crates/validate/src/model.rs text eol=lf
crates/validate/model/extract_model_lf.py text eol=lf
craft-i18n.rev text eol=lf
-20
View File
@@ -1,20 +0,0 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+2 -37
View File
@@ -202,7 +202,7 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `crates/ui-egui/icons/insertLeft.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/insertRight.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/interfaceTheme.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/italic.svg` | WordCraft contributors | original: redrawn for #7694 | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/italic.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/justify.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/labels.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/language.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
@@ -339,7 +339,6 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `crates/ui-egui/icons/size.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/smartArt.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/smartArtColors.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/smartArtLayouts.svg` | WordCraft contributors | original: drawn for WordCraft in the style of the code-drawn icon set (#7149) | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/sort.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/sources.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/spaceAfter.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
@@ -359,8 +358,6 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `crates/ui-egui/icons/table.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/tableOfAuthorities.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/tableOfFigures.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/tableStyleOptions.svg` | WordCraft contributors | original: drawn for WordCraft in the style of the code-drawn icon set (#7149) | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/tableStyles.svg` | WordCraft contributors | original: drawn for WordCraft in the style of the code-drawn icon set (#7149) | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/textBox.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/textBoxLink.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/textBoxUnlink.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
@@ -378,7 +375,7 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `crates/ui-egui/icons/trackChanges.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/transform.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/translate.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/underline.svg` | WordCraft contributors | original: redrawn for #7694 | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/underline.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/undo.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/unlinkCitations.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/update.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
@@ -398,35 +395,3 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| craft-fonts (optional build input, not files in this repo): BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic | see https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | embedded only when built with `CRAFT_FONTS_DIR` (all official releases) | OFL-1.1 | Japanese and Chinese UI, Japanese document fallback |
| craft-i18n (optional build input, not files in this repo): the interface translations | see https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md, which credits every translator of WordCraft's former in-repo catalogs (`crates/ui-egui/src/i18n/*.tsv`, migrated at `wordcraft@806a945`) | embedded only when built with `CRAFT_I18N_DIR`, at the commit in `craft-i18n.rev` (all official releases) | MIT OR Apache-2.0 | Interface languages other than English; clean-room translations from the English interface labels |
| craft-i18n Language data (optional build input, not files in this repo): the spelling word lists and hyphenation patterns (`language-data/`: the Moby Hyphenator II list and our patterns for English, `en-extra.txt`, `en-variants.txt`, `ru-extra.txt`, and the hyph-utf8 German, Polish, Portuguese and Italian patterns) | see the Language data section of https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md (authors, upstream sources with SHA-256, licences); moved there from `assets/hyphenation/` and `assets/spelling/` byte for byte | embedded by craft-proof (storytold/craft-libs) only when built with `CRAFT_I18N_DIR`, at the commit in `craft-i18n.rev` (all official releases) | Public Domain / CC0-1.0, MIT, BSD-3-Clause, MIT OR Apache-2.0 (per file; see NOTICE) | Spelling and hyphenation; without it English spelling falls back to an installed Hunspell English or craft-proof's built-in Moby list, and pattern hyphenation is off |
| `crates/validate/corpus/calibration/00-control.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: valid control |
| `crates/validate/corpus/calibration/01-not-zip.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; contains no picture; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-NOT-ZIP defect fixture |
| `crates/validate/corpus/calibration/02-dup-entry.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-DUP-ENTRY defect fixture |
| `crates/validate/corpus/calibration/03-case-collision.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-CASE-COLLISION defect fixture |
| `crates/validate/corpus/calibration/04-no-content-types.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-NO-CONTENT-TYPES defect fixture |
| `crates/validate/corpus/calibration/05-no-main.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-NO-MAIN defect fixture |
| `crates/validate/corpus/calibration/06-ct-undeclared.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: CT-UNDECLARED defect fixture |
| `crates/validate/corpus/calibration/07-ct-main-type.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: CT-MAIN-TYPE defect fixture |
| `crates/validate/corpus/calibration/08-xml-malformed-main.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: XML-MALFORMED (main part) defect fixture |
| `crates/validate/corpus/calibration/09-xml-malformed-unused.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: XML-MALFORMED (unreferenced part) defect fixture |
| `crates/validate/corpus/calibration/10-xml-undeclared-prefix.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: XML-UNDECLARED-PREFIX defect fixture |
| `crates/validate/corpus/calibration/11-rel-dup-id.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REL-DUP-ID defect fixture |
| `crates/validate/corpus/calibration/12-rel-dangling.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REL-DANGLING defect fixture |
| `crates/validate/corpus/calibration/13-rel-typed.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REL-TYPED defect fixture |
| `crates/validate/corpus/calibration/14-comment-dup.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: ID-COMMENT-DUP defect fixture |
| `crates/validate/corpus/calibration/15-comment-ref.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REF-COMMENT defect fixture |
| `crates/validate/corpus/calibration/16-docpr-dup.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: ID-DOCPR-DUP defect fixture |
| `crates/validate/corpus/calibration/17-bookmark-dup.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: ID-BOOKMARK-DUP defect fixture |
| `crates/validate/corpus/calibration/18-revision-dup.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: ID-REVISION-DUP defect fixture |
| `crates/validate/corpus/calibration/19-note-ref.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REF-NOTE defect fixture |
| `crates/validate/corpus/calibration/20-header-ref.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REF-HEADER defect fixture |
| `crates/validate/corpus/calibration/21-style-ref.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REF-STYLE defect fixture |
| `crates/validate/corpus/calibration/22-fld-unbalanced.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: FLD-UNBALANCED defect fixture |
| `crates/validate/corpus/calibration/23-tc-no-p.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: STRUCT-TC-NO-P defect fixture |
| `crates/validate/corpus/calibration/24-deltext.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: STRUCT-DELTEXT defect fixture |
| `crates/validate/corpus/calibration/25-move-unpaired.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: STRUCT-MOVE-UNPAIRED defect fixture |
| `crates/validate/corpus/calibration/26-media-magic.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is a fixed JPEG-header stub defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: MEDIA-MAGIC defect fixture |
| `crates/validate/model/content_model_v2.json` | WordCraft contributors | generated by `crates/validate/model/extract_content_model.py` from the ECMA-376 Part 1 (5th ed.) Strict schemas (public specification; archive URL and SHA-256 in `crates/validate/model/README.md`); the schemas themselves are not copied | MIT OR Apache-2.0, like the code (element/type content models extracted from a public specification) | wordcraft-validate grammar tables: WML, Strict |
| `crates/validate/model/content_model_v2_transitional.json` | WordCraft contributors | generated by `crates/validate/model/extract_content_model.py` from the ECMA-376 Part 4 (5th ed.) Transitional schemas (public specification; archive URL and SHA-256 in `crates/validate/model/README.md`); the schemas themselves are not copied | MIT OR Apache-2.0, like the code (element/type content models extracted from a public specification) | wordcraft-validate grammar tables: WML, Transitional |
| `crates/validate/model/content_model_dml_v2.json` | WordCraft contributors | generated by `crates/validate/model/extract_content_model.py --profile dml` from the ECMA-376 Part 1 (5th ed.) Strict schemas (public specification; archive URL and SHA-256 in `crates/validate/model/README.md`); the schemas themselves are not copied | MIT OR Apache-2.0, like the code (element/type content models extracted from a public specification) | wordcraft-validate grammar tables: DrawingML, Strict |
| `crates/validate/model/content_model_dml_v2_transitional.json` | WordCraft contributors | generated by `crates/validate/model/extract_content_model.py --profile dml` from the ECMA-376 Part 4 (5th ed.) Transitional schemas (public specification; archive URL and SHA-256 in `crates/validate/model/README.md`); the schemas themselves are not copied | MIT OR Apache-2.0, like the code (element/type content models extracted from a public specification) | wordcraft-validate grammar tables: DrawingML, Transitional |
| `crates/validate/src/model.rs` | WordCraft contributors | generated by `crates/validate/model/generate_model.py` from the four `crates/validate/model/content_model_*.json` tables above and the `ST_NumberFormat` enumeration of the ECMA-376 Part 1 Strict `wml.xsd` | MIT OR Apache-2.0, like the code (data extracted from a public specification) | wordcraft-validate grammar tables compiled into the crate |
Generated
+2 -64
View File
@@ -247,15 +247,6 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
dependencies = [
"derive_arbitrary",
]
[[package]]
name = "arboard"
version = "3.7.0"
@@ -2356,7 +2347,7 @@ dependencies = [
"verifysign",
"winreg",
"winsafe",
"zip 9.1.0",
"zip",
]
[[package]]
@@ -2478,7 +2469,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip 9.1.0",
"zip",
]
[[package]]
@@ -2612,17 +2603,6 @@ version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
[[package]]
name = "derive_arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "dify"
version = "0.8.0"
@@ -9047,7 +9027,6 @@ dependencies = [
"wordcraft-geom",
"wordcraft-mcp",
"wordcraft-render",
"wordcraft-validate",
"wordcraft-zotero",
]
@@ -9297,21 +9276,6 @@ dependencies = [
"zbus",
]
[[package]]
name = "wordcraft-validate"
version = "0.18.1"
dependencies = [
"craft-image-codecs",
"craft-tiff",
"craft-xml",
"png 0.18.1",
"quick-xml 0.41.0",
"rayon",
"serde",
"serde_json",
"zip 3.0.0",
]
[[package]]
name = "wordcraft-web"
version = "0.18.1"
@@ -9795,20 +9759,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"
@@ -9837,18 +9787,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zune-core"
version = "0.5.3"
-3
View File
@@ -46,7 +46,6 @@ 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-validate = { path = "crates/validate" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
@@ -58,8 +57,6 @@ kurbo = { version = "0.13", features = ["serde"] }
thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
quick-xml = "0.41"
zip = { version = "3", default-features = false, features = ["deflate"] }
log = "0.4"
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
+627 -664
View File
File diff suppressed because one or more lines are too long
-1
View File
@@ -19,7 +19,6 @@ wordcraft-engine = { workspace = true }
wordcraft-render = { workspace = true }
wordcraft-mcp = { workspace = true }
wordcraft-zotero = { workspace = true }
wordcraft-validate = { workspace = true }
serde_json = { workspace = true }
sys-locale = "0.3"
+4 -135
View File
@@ -51,7 +51,6 @@ USAGE:
documents and with {\"id\": N} makes one active
wordcraft-cli commands [--json] list every command
wordcraft-cli parity [--markdown] feature-catalog parity
wordcraft-cli validate <file> [--json] structural integrity check (exit 0 pass, 1 fail, 2 incomplete, 3 usage/IO)
wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR [--author NAME]
MCP server on stdio, with a headless session.
Both roots are required: the agent's commands read
@@ -82,7 +81,7 @@ same output on every machine.
";
/// The subcommands, in `USAGE` order; `--help` or `-h` after any of them prints `USAGE` (#968).
const SUBCOMMANDS: &[&str] = &["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "validate", "mcp", "zotero"];
const SUBCOMMANDS: &[&str] = &["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "mcp", "zotero"];
fn wants_help(cmd: &str, rest: &[String]) -> bool {
SUBCOMMANDS.contains(&cmd) && rest.iter().any(|a| a == "--help" || a == "-h")
@@ -119,7 +118,7 @@ fn open(path: &Path, password: Option<&str>) -> Result<Session, Failure> {
/// The commands that open a file, and which positional argument it is, excluding option values.
/// `run` opens the value of `--file`.
const OPENS_FILE: &[(&str, usize)] = &[("convert", 0), ("info", 0), ("text", 0), ("inspect", 0), ("render", 0), ("validate", 0), ("zotero", 1)];
const OPENS_FILE: &[(&str, usize)] = &[("convert", 0), ("info", 0), ("text", 0), ("inspect", 0), ("render", 0), ("zotero", 1)];
/// The arguments as text. Only the file the command opens may have a name that isn't valid Unicode,
/// such as a Latin-1 one (#1440): it comes back as the path to open, and lossy among the arguments.
@@ -368,8 +367,6 @@ const RUN_OPTIONS: &[OptionSpec] = &[
];
const COMMANDS_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--json", takes_value: false }];
const PARITY_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--markdown", takes_value: false }];
const VALIDATE_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--json", takes_value: false }];
/// Why `mcp` won't start unconfined (shared rule 18, #7124).
const MCP_NEEDS_ROOTS: &str = "mcp: give both --automation-read-root DIR and --automation-write-root DIR: an agent's \
commands may read only inside the read root and write only inside the write root (the same folder may be both)";
@@ -394,10 +391,8 @@ enum Failure {
/// A real error, reported on stderr with a failing exit status.
Error(String),
/// Whoever read stdout closed it (`wordcraft-cli commands --json | head`): there is nobody left
/// to write to. Most commands exit 0; validation retains its verdict status.
/// to write to, so stop quietly and exit 0 like other command-line tools.
StdoutClosed,
/// The subcommand has already written its output and decided its own exit status (`validate`).
Status(u8),
/// `convert --strict` refused: the text for stderr (the report's lines, then its JSON line).
/// Exit status 3.
Strict(String),
@@ -408,7 +403,6 @@ impl fmt::Display for Failure {
match self {
Failure::Error(e) => f.write_str(e),
Failure::StdoutClosed => f.write_str("stdout closed"),
Failure::Status(code) => write!(f, "exit {code}"),
Failure::Strict(report) => f.write_str(report),
}
}
@@ -723,7 +717,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
for c in s.registry.all() {
writeln!(o, "{:<32} {:<36} {:<24} {}", c.id, c.label, c.shortcut, c.location)?;
}
writeln!(o, "{:<32} Structural integrity check", "validate")
Ok(())
})
}
}
@@ -737,7 +731,6 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
write_stdout(|o| writeln!(o, "{}", serde_json::to_string_pretty(&p).unwrap_or_default()))
}
}
"validate" => run_validate(file.as_deref(), &rest),
"mcp" => {
let (roots, rest) = automation_roots("mcp", &rest)?;
// Refused with or without a value, before the option check, so `--connect=…` gets this refusal rather than
@@ -904,129 +897,6 @@ fn parity_markdown(p: &Value) -> String {
s
}
/// `validate`: exactly one positional path (batch mode does not exist yet, so a surplus operand is
/// a usage error rather than a silently ignored second file). `file` is the preserved operand, so a
/// file name that is not valid Unicode still reaches the validator.
fn run_validate(file: Option<&Path>, rest: &[String]) -> Result<(), Failure> {
if let Err(e) = validate_options("validate", rest, VALIDATE_OPTIONS) {
eprintln!("wordcraft-cli: {e}");
return Err(Failure::Status(3));
}
let paths = positionals(rest, VALIDATE_OPTIONS);
if paths.len() != 1 {
eprintln!("wordcraft-cli: validate takes exactly one file\n\n{USAGE}");
return Err(Failure::Status(3));
}
let path = file.unwrap_or_else(|| Path::new(paths[0]));
let report = match wordcraft_validate::validate_path(path) {
Ok(report) => report,
Err(e) => {
eprintln!("wordcraft-cli: {}: {e}", path.display());
return Err(Failure::Status(3));
}
};
let written = if rest.iter().any(|a| a == "--json") {
let json = serde_json::to_string_pretty(&report).unwrap_or_default();
write_stdout(|o| writeln!(o, "{json}"))
} else {
write_stdout(|o| write_validate_report(o, &report))
};
match written {
// A reader closing early must not turn a FAIL or INCOMPLETE verdict into PASS.
Ok(()) | Err(Failure::StdoutClosed) => {}
Err(error) => {
eprintln!("wordcraft-cli: {error}");
return Err(Failure::Status(3));
}
}
match report.verdict {
wordcraft_validate::Verdict::Pass => Ok(()),
wordcraft_validate::Verdict::Fail => Err(Failure::Status(1)),
wordcraft_validate::Verdict::Incomplete => Err(Failure::Status(2)),
}
}
/// Write a `validate` report for people: the verdict, then one line per finding
/// (`SEVERITY RULE [part] message`), then the coverage notes.
fn write_validate_report(o: &mut std::io::StdoutLock<'static>, report: &wordcraft_validate::Report) -> std::io::Result<()> {
o.write_all(render_validate_report(report).as_bytes())
}
/// Render a `validate` report for people. Document-controlled text — a ZIP entry name flowing into
/// a finding part or coverage note — is escaped so a name cannot end its line or drive the
/// terminal; printable text, including Unicode, is left as written.
///
/// The `--json` form is not escaped by hand; it is the validator's own `serde_json` serialization.
/// `serde_json` escapes `U+0000`–`U+001F`, `"` and `\`; C1 controls such as `U+009B` and the bidi
/// embeddings/overrides (`U+202A`–`U+202E`, `U+2066`–`U+2069`) are emitted raw. So a control or bidi
/// run carried by a ZIP entry name survives into the JSON text; JSON is only safe because a
/// *parser* takes the string value as data. If that text is printed directly to a terminal, the raw
/// C1/bidi run reaches the terminal exactly as it would from any other text, so the JSON form is
/// not a terminal-safe rendering. Only the human report below escapes those characters, and it does
/// so to defend the terminal; keeping the JSON byte-for-byte the validator's own serialization is
/// why its escaping is left to `serde_json`.
fn render_validate_report(report: &wordcraft_validate::Report) -> String {
let mut out = format!("{}\n", verdict_label(report.verdict));
for f in &report.findings {
let severity = severity_label(f.severity);
match &f.part {
Some(part) => out.push_str(&format!("{severity} {} [{}] {}\n", f.rule, escape_report_text(part), escape_report_text(&f.message))),
None => out.push_str(&format!("{severity} {} {}\n", f.rule, escape_report_text(&f.message))),
}
}
for note in &report.coverage_notes {
out.push_str(&format!("note: {}\n", escape_report_text(note)));
}
out
}
/// Escape the control and invisible-formatting characters that could spoof a report line, in the
/// same escape *form* `escape_debug` uses (`\u{1b}`, `\n`); printable characters (including Unicode)
/// are left untouched. The *selection* is a hand-picked set ([`is_invisible_format`] plus
/// `char::is_control`), not `escape_debug`'s full non-printable set: it omits, for example, the
/// U+E0000 tag block, U+FFF9–U+FFFB and the Hangul fillers. None of those can end a line or drive a
/// terminal, which is the threat this guards against. Backslash is not escaped, so a name that
/// literally contains the text `\u{1b}` prints exactly like an escaped ESC and the output is not
/// injective.
fn escape_report_text(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if c.is_control() || is_invisible_format(c) {
out.extend(c.escape_debug());
} else {
out.push(c);
}
}
out
}
/// Invisible Unicode formatting characters and line/paragraph separators: no glyph, but they can
/// alter how a terminal renders the rest of the line (`char::is_control` covers C0/C1 controls).
fn is_invisible_format(c: char) -> bool {
matches!(
c,
'\u{00ad}' | '\u{061c}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{2028}'..='\u{202e}' | '\u{2060}'..='\u{206f}' | '\u{feff}'
)
}
/// Map a validation verdict enum to its human-readable uppercase display label.
fn verdict_label(v: wordcraft_validate::Verdict) -> &'static str {
match v {
wordcraft_validate::Verdict::Pass => "PASS",
wordcraft_validate::Verdict::Fail => "FAIL",
wordcraft_validate::Verdict::Incomplete => "INCOMPLETE",
}
}
/// Map a validation severity enum to its human-readable uppercase display label.
fn severity_label(s: wordcraft_validate::Severity) -> &'static str {
match s {
wordcraft_validate::Severity::Corrupt => "CORRUPT",
wordcraft_validate::Severity::Error => "ERROR",
wordcraft_validate::Severity::Warning => "WARNING",
}
}
/// The Launcher's Nightly bootstrap belongs to the desktop app: a CLI must not accept it, in the
/// separate-token or `=` form, so a mis-routed launch fails loudly instead of editing stable data.
fn launcher_profile_flag(args: &[OsString]) -> bool {
@@ -1050,7 +920,6 @@ fn main() -> ExitCode {
}
match run(&args) {
Ok(()) | Err(Failure::StdoutClosed) => ExitCode::SUCCESS,
Err(Failure::Status(code)) => ExitCode::from(code),
Err(Failure::Error(e)) => {
eprintln!("wordcraft-cli: {e}");
ExitCode::FAILURE
+1 -128
View File
@@ -230,12 +230,10 @@ fn only_the_opened_file_may_be_other_than_unicode() {
assert_eq!(ok(vec!["run".into(), "--print".into(), "--file".into(), latin1()]), Some(PathBuf::from(latin1())));
assert_eq!(ok(vec!["info".into(), "in.docx".into()]), None);
// Every command that opens a file reaches the open with it (no such file here), so
// `OPENS_FILE` and the commands' own arguments agree. `validate` takes exactly one path, so it
// is checked separately below, together with its exit-3 usage status.
// `OPENS_FILE` and the commands' own arguments agree.
let missing = || OsString::from_vec(b"/definitely/not/caf\xe9.docx".to_vec());
let mut opening: Vec<Vec<OsString>> = OPENS_FILE
.iter()
.filter(|(cmd, _)| *cmd != "validate")
.map(|(cmd, n)| [vec![(*cmd).into()], vec![OsString::from("refresh"); *n], vec![missing(), "out.png".into()]].concat())
.collect();
opening.push(vec!["run".into(), "--file".into(), missing()]);
@@ -243,7 +241,6 @@ fn only_the_opened_file_may_be_other_than_unicode() {
let e = run(&raw).unwrap_err().to_string();
assert!(e.contains("No such file"), "{raw:?}: {e}");
}
assert!(matches!(run(&["validate".into(), missing()]), Err(Failure::Status(3))));
for (raw, n) in [
(vec!["zotero".into(), latin1(), "in.docx".into()], 2),
(vec!["render".into(), "in.docx".into(), latin1()], 3),
@@ -301,7 +298,6 @@ fn every_agent_entry_point_refuses_to_start_without_both_roots() {
("run", NotAgent("runs the commands and script named on its command line, then exits")),
("commands", NotAgent("lists the commands; touches no file")),
("parity", NotAgent("prints the feature catalog; touches no file")),
("validate", NotAgent("validates the one file named on its command line, then exits")),
("mcp", Agent),
("zotero", NotAgent("runs one named Zotero command; Zotero's replies edit citations and name no file")),
];
@@ -704,114 +700,6 @@ fn script_parse_resolves_paths_against_the_base() {
assert_eq!(s.commands.len(), 1);
}
/// Finding 3: a surplus operand is a usage error (exit 3) rejected in the operand check, before any
/// file is validated, so a valid first path can no longer make `validate a.docx b.docx` print PASS.
/// The two paths are DIFFERENT files and validating either one would return `Ok`; the code path
/// returns `Status(3)` from the `paths.len() != 1` check before `validate_path` runs, so no file was
/// validated to produce it. (A `Status(3)` on its own does not prove that — `validate` also returns
/// it for an I/O error after a single valid operand reaches the validator — which is why the
/// operand check, not the status, is what establishes the rejection happened first.)
#[test]
fn validate_rejects_missing_or_surplus_operands_without_validating() {
let dir = std::env::temp_dir().join(format!("wc-cli-validate-args-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let first = dir.join("first.docx");
let second = dir.join("second.docx");
run(&args(&["run", "--template", "sample", "--save", &first.to_string_lossy()])).unwrap();
run(&args(&["run", "--template", "sample", "--save", &second.to_string_lossy()])).unwrap();
let (first, second) = (first.to_string_lossy().into_owned(), second.to_string_lossy().into_owned());
assert_ne!(first, second, "the two operands must be different files");
assert_eq!(run(&args(&["validate", &first])), Ok(()), "one valid path reports PASS");
assert_eq!(
run(&args(&["validate", &first, &second])),
Err(Failure::Status(3)),
"two different paths are a usage error; validating either would return Ok, so it validated neither"
);
assert_eq!(run(&args(&["validate"])), Err(Failure::Status(3)), "no path is a usage error");
let _ = std::fs::remove_dir_all(dir);
}
/// Finding 4: `validate` is in `OPENS_FILE`, so a file name that is not valid Unicode reaches the
/// validator by its preserved path rather than being rejected as a bad argument.
/// APFS refuses invalid UTF-8 file names, so macOS covers native path handling without creating one.
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn validate_accepts_a_file_name_that_is_not_unicode() {
use std::os::unix::ffi::OsStringExt;
let dir = std::env::temp_dir().join(format!("wc-cli-validate-nonutf8-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let doc = wordcraft_doc::Document::from_text("Bonjour");
let bytes = wordcraft_engine::io::save_bytes("x.docx", &doc).unwrap();
let mut name = dir.as_os_str().to_os_string().into_vec();
name.extend_from_slice(b"/caf\xe9.docx");
let path = PathBuf::from(OsString::from_vec(name));
std::fs::write(&path, bytes).unwrap();
let raw = vec![OsString::from("validate"), path.into_os_string()];
assert_eq!(run(&raw), Ok(()), "a non-Unicode path validates and reports PASS");
let _ = std::fs::remove_dir_all(dir);
}
/// A real `.docx` archive with `extra` parts added: content types, package relationships, the main
/// document and an empty main relationships part. Used to drive `validate_bytes` from real bytes so
/// a document-controlled entry name is shown to reach the report the way production does.
fn validate_fixture_zip(extra: &[(&str, &[u8])]) -> Vec<u8> {
let mut w = craft_zip::Writer::new();
w.add(
"[Content_Types].xml",
br#"<?xml version="1.0"?><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>"#,
craft_zip::Compression::Stored,
)
.unwrap();
w.add(
"_rels/.rels",
br#"<?xml version="1.0"?><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>"#,
craft_zip::Compression::Stored,
)
.unwrap();
w.add(
"word/document.xml",
br#"<?xml version="1.0"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body/></w:document>"#,
craft_zip::Compression::Stored,
)
.unwrap();
for (name, bytes) in extra {
w.add(name, bytes, craft_zip::Compression::Stored).unwrap();
}
w.finish().unwrap()
}
/// Finding 5: document-controlled text (a ZIP entry name) is escaped in the human report, while the
/// JSON form keeps serde's escaping. The input is a real archive whose entry name carries a control
/// character, so the test shows the name actually reaches the escaped fields (part and message).
#[test]
fn human_report_escapes_document_controlled_text() {
let evil = "word/evil\u{1b}[2J.bin";
let printable = "word/café—naïve.bin";
let zip = validate_fixture_zip(&[(evil, b"x"), (printable, b"x")]);
let report = wordcraft_validate::validate_bytes(&zip);
// The undeclared part carries the raw control character in its part field and its message.
let finding = report
.findings
.iter()
.find(|f| f.rule == "CT-UNDECLARED" && f.part.as_deref() == Some(evil))
.unwrap_or_else(|| panic!("expected CT-UNDECLARED at the control-character name: {:#?}", report.findings));
assert!(finding.message.contains(evil), "the name reaches the message too: {:?}", finding.message);
let human = render_validate_report(&report);
assert!(!human.contains('\u{1b}'), "no raw escape survives the human report: {human:?}");
assert!(human.contains("\\u{1b}"), "{human:?}");
assert!(human.contains("[2J"), "the surrounding name text is kept as written: {human:?}");
// Printable Unicode in a name is left as written.
assert!(human.contains(printable), "printable Unicode must be untouched: {human:?}");
// JSON output is unchanged by the human escaping: serde still emits the control character as
// its own JSON escape.
let json = serde_json::to_string(&report).unwrap();
assert!(json.contains("\\u001b"), "{json}");
}
#[test]
fn invisible_characters_are_escaped_and_json_lines_still_parse_back() {
let hidden = "a\u{ad}b\u{200b}c\u{200d}d\u{2060}e\u{2064}f\u{feff}g\u{e0041}h\u{e007f}i\u{85}j\u{202e}k";
@@ -827,18 +715,3 @@ fn invisible_characters_are_escaped_and_json_lines_still_parse_back() {
assert!(line.contains("\\ud800") || line.contains("\\udb40"), "{line}");
assert_eq!(serde_json::from_str::<Value>(&line).unwrap(), value);
}
/// Native non-Unicode paths survive argument parsing and reach the validator's I/O error path.
/// No file is created: APFS refuses invalid UTF-8 names. The original bytes, rather than their
/// lossy display spelling, must be retained even when options precede the operand.
#[cfg(unix)]
#[test]
fn validate_preserves_a_non_unicode_path_without_creating_a_file() {
use std::os::unix::ffi::OsStringExt;
let raw_path = OsString::from_vec(b"wordcraft-nonexistent-caf\xe9.docx".to_vec());
let raw = vec![OsString::from("validate"), OsString::from("--json"), raw_path.clone()];
let (_, parsed) = text_args(&raw).unwrap();
assert_eq!(parsed.as_deref(), Some(Path::new(&raw_path)));
assert!(parsed.as_deref().unwrap().to_str().is_none());
assert_eq!(run(&raw), Err(Failure::Status(3)), "native path reaches I/O handling");
}
+2 -64
View File
@@ -1,5 +1,5 @@
//! Readers closing stdout early must not panic (#508). Listing and MCP stop quietly;
//! validation retains its verdict exit status.
//! A reader that closes stdout early (`wordcraft-cli commands --json | head`) must end the CLI
//! quietly with exit 0, never with a panic (#508).
use std::io::{Read, Write};
use std::process::{Command, Stdio};
@@ -47,65 +47,3 @@ fn mcp_server_ends_cleanly_when_its_client_closes_stdout() {
assert!(out.status.success(), "status {:?}, stderr: {stderr}", out.status);
assert!(!stderr.contains("panicked"), "stderr: {stderr}");
}
/// A closed reader preserves validation's verdict for both report formats, including INCOMPLETE.
#[test]
fn validate_closed_stdout_preserves_verdict() {
let corpus = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/validate/corpus/calibration");
let sparse = std::env::temp_dir().join(format!("wordcraft-validate-closed-stdout-{}.docx", std::process::id()));
// The validator checks metadata before reading inputs over its 512 MiB limit.
std::fs::File::create(&sparse).unwrap().set_len((512 << 20) + 1).unwrap();
let pass = sparse.with_file_name(format!("wordcraft-validate-closed-stdout-pass-{}.docx", std::process::id()));
let bytes = wordcraft_engine::io::save_bytes("pass.docx", &wordcraft_doc::Document::from_text("Control")).unwrap();
std::fs::write(&pass, bytes).unwrap();
let mut results = Vec::new();
for (fixture, expected) in [(pass.clone(), 0), (corpus.join("14-comment-dup.docx"), 1), (sparse.clone(), 2)] {
for json in [false, true] {
let mut open = cli();
open.arg("validate").arg(&fixture);
if json {
open.arg("--json");
}
let open = open.output().unwrap();
// Close the only reader before spawning, so even a short report reliably gets BrokenPipe.
let (reader, writer) = std::io::pipe().unwrap();
drop(reader);
let mut closed = cli();
closed.arg("validate").arg(&fixture).stdout(writer);
if json {
closed.arg("--json");
}
results.push((fixture.clone(), json, expected, open, closed.output().unwrap()));
}
}
std::fs::remove_file(sparse).unwrap();
std::fs::remove_file(pass).unwrap();
for (fixture, json, expected, open, closed) in results {
assert_eq!(open.status.code(), Some(expected), "{}, json={json}: {open:?}", fixture.display());
assert_eq!(closed.status.code(), Some(expected), "{}, json={json}: {closed:?}", fixture.display());
assert!(!String::from_utf8_lossy(&closed.stderr).contains("panicked"), "{closed:?}");
}
}
/// Other report-write failures are I/O status 3; a child-only file-size limit forces EFBIG on stdout.
#[test]
fn validate_stdout_write_error_is_io_status() {
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/validate/corpus/calibration/14-comment-dup.docx");
let stdout = std::env::temp_dir().join(format!("wordcraft-validate-stdout-error-{}", std::process::id()));
let mut results = Vec::new();
for json in [false, true] {
// Ignore SIGXFSZ so the write returns an error rather than terminating the CLI.
let mut command = Command::new("/bin/sh");
command.args(["-c", "trap '' XFSZ; ulimit -f 0 || exit 99; exec \"$@\"", "sh", env!("CARGO_BIN_EXE_wordcraft-cli"), "validate"]);
command.arg(&fixture).stdout(std::fs::File::create(&stdout).unwrap());
if json {
command.arg("--json");
}
results.push((json, command.output().unwrap()));
}
std::fs::remove_file(stdout).unwrap();
for (json, output) in results {
assert_eq!(output.status.code(), Some(3), "json={json}: {output:?}");
assert!(!String::from_utf8_lossy(&output.stderr).contains("panicked"), "{output:?}");
}
}
-2
View File
@@ -209,7 +209,5 @@ real_name = "Helen Kwok"
[people.ashokram-si]
real_name = "Ashok Ram"
[people.reubgr]
real_name = "Reuben Grinberg"
[people.benandez]
sync_github_name = true
+24 -230
View File
@@ -7,7 +7,7 @@ use std::sync::Arc;
use serde::{Deserialize, Serialize};
use crate::para::{InlineObject, OBJ, Run};
use crate::para::{InlineObject, Run};
use crate::props::{CharProps, ParaProps};
use crate::{Block, Blocks, DocError, Document, Paragraph, Part, PartKind, Path, Pos, Result, para_block};
use crate::{Table, table::MAX_TABLE_DEPTH};
@@ -26,41 +26,8 @@ pub struct Fragment {
}
impl Fragment {
/// Text box story IDs referenced by the fragment's objects in document order, falling
/// back to the parts map's keys if no inline objects reference them.
fn text_box_ids(&self) -> Vec<u32> {
let mut ids = Vec::new();
for b in &self.blocks {
each_para(b, 0, &mut |p| {
for o in &p.objects {
for id in o.text_boxes() {
if self.parts.get(&id).is_some_and(|part| part.kind == crate::PartKind::TextBox) {
ids.push(id);
}
}
}
});
}
if ids.is_empty() {
ids.extend(self.parts.iter().filter(|(_, p)| p.kind == crate::PartKind::TextBox).map(|(id, _)| *id));
}
ids
}
/// The plain text representation of the fragment's body, falling back to text box part stories
/// when the body text has no real text (empty or only whitespace/object markers).
pub fn plain_text(&self) -> String {
let d = self.to_document();
let text = d.plain_text(crate::StoryRef::Body);
let has_body_text = text.chars().any(|c| !c.is_whitespace() && c != OBJ);
if !has_body_text && !self.parts.is_empty() {
let parts: Vec<String> =
self.text_box_ids().into_iter().map(|id| d.plain_text(crate::StoryRef::Part(id))).filter(|s| !s.is_empty()).collect();
if !parts.is_empty() {
return parts.join("\n");
}
}
text
self.to_document().plain_text(crate::StoryRef::Body)
}
/// The fragment as the body of a new document (default styles).
pub fn to_document(&self) -> Document {
@@ -100,20 +67,9 @@ impl Fragment {
found
}
/// The text a copy puts on the clipboard: [`Self::plain_text`] with symbol-font characters
/// (Wingdings…) as their Unicode equivalents. Falls back to text box part stories when body
/// text has no real text (empty or only whitespace/object markers).
/// (Wingdings…) as their Unicode equivalents.
pub fn clipboard_text(&self) -> String {
let d = self.to_document();
let text = d.shown_text(crate::StoryRef::Body);
let has_body_text = text.chars().any(|c| !c.is_whitespace() && c != OBJ);
if !has_body_text && !self.parts.is_empty() {
let parts: Vec<String> =
self.text_box_ids().into_iter().map(|id| d.shown_text(crate::StoryRef::Part(id))).filter(|s| !s.is_empty()).collect();
if !parts.is_empty() {
return parts.join("\n");
}
}
text
self.to_document().shown_text(crate::StoryRef::Body)
}
/// Add `piece` at the end, followed by a paragraph mark unless it already ends with one: how
/// Word's Spike collects what it cuts. The piece's text box stories get ids after this
@@ -647,48 +603,6 @@ fn remap_media_block(b: &mut Block, map: &BTreeMap<String, String>) {
});
}
/// Visit `(index, item)` in forward (`!last`) or reverse (`last`) order, returning the first `Some`.
fn find_in_slice<T>(slice: &[T], last: bool, mut f: impl FnMut(usize, &T) -> Option<Path>) -> Option<Path> {
if last { slice.iter().enumerate().rev().find_map(|(i, x)| f(i, x)) } else { slice.iter().enumerate().find_map(|(i, x)| f(i, x)) }
}
/// First (`last == false`) or last (`last == true`) paragraph path inside `blk`,
/// matching [`crate::text_walk::walk`] order and bounded by [`crate::PARA_WALK_DEPTH`].
fn edge_para_in_block(blk: &Block, prefix: &mut Vec<u32>, depth: usize, last: bool) -> Option<Path> {
if depth > crate::PARA_WALK_DEPTH {
return None;
}
match blk {
Block::Para(_) => Some(Path(prefix.clone())),
Block::Table(t) => find_in_slice(&t.rows, last, |r, row| {
find_in_slice(&row.cells, last, |c, cell| {
prefix.push(r as u32);
prefix.push(c as u32);
let found = find_in_slice(&cell.blocks, last, |bi, b| {
prefix.push(bi as u32);
let res = edge_para_in_block(b, prefix, depth + 1, last);
prefix.pop();
res
});
prefix.pop();
prefix.pop();
found
})
}),
}
}
/// Trim a paragraph to the offset range `from..to`, optionally clearing section breaks.
fn trim_para(para: &Paragraph, from: usize, to: usize, clear_section: bool) -> Paragraph {
let mut p = para.clone();
let _ = p.delete(to.min(p.len()), p.len());
let _ = p.delete(0, from.min(p.len()));
if clear_section {
p.section = None;
}
p
}
impl Document {
/// Convert notes between footnotes and endnotes: footnotes (`foot`) become endnotes and
/// endnotes (`end`) footnotes, both at once to swap them. Each note's kind changes, as do its
@@ -1426,22 +1340,6 @@ impl Document {
out
}
/// Copy paragraphs in linear document order between `a` and `b` inclusive (#5906).
fn copy_para_range(&self, a: &Pos, b: &Pos) -> Vec<Block> {
let (a, b) = order(a, b);
let mut out = Vec::new();
for p in self.paths_between(&a, &b) {
if let Some(para) = self.para(a.story, &p) {
let from = if p == a.path { a.off } else { 0 };
let to = if p == b.path { b.off } else { para.len() };
let clear = p == b.path && b.off < para.len();
out.push(Block::Para(trim_para(para, from, to, clear)));
}
}
out
}
/// Copy blocks spanning `a..b`, preserving whole tables when covered across containers (#5906).
fn copy_blocks(&self, a: &Pos, b: &Pos) -> Vec<Block> {
let (a, b) = order(a, b);
let mut out = Vec::new();
@@ -1454,17 +1352,21 @@ impl Document {
let Some(blk) = bl.get(i) else { break };
match &**blk {
Block::Para(p) => {
let mut p = p.clone();
let to = if i == b.path.last() { b.off } else { p.len() };
let from = if i == a.path.last() { a.off } else { 0 };
let clear = i == b.path.last() && to < p.len();
out.push(Block::Para(trim_para(p, from, to, clear)));
let _ = p.delete(to.min(p.len()), p.len());
let _ = p.delete(0, from.min(p.len()));
if i == b.path.last() && to < self.para(a.story, &b.path).map(Paragraph::len).unwrap_or(0) {
p.section = None;
}
out.push(Block::Para(p));
}
Block::Table(_) => out.push((**blk).clone()),
Block::Table(t) => out.push(Block::Table(t.clone())),
}
}
return out;
}
// Across the cells of a whole table: the table itself, not its cells' paragraphs (#1744).
if let Some(tp) = self.whole_table(&a, &b)
&& let Some(blk) = self.block(a.story, &tp)
@@ -1472,92 +1374,17 @@ impl Document {
out.push(blk.clone());
return out;
}
// Find the lowest common ancestor container.
let common = a.path.0.iter().zip(&b.path.0).take_while(|(x, y)| x == y).count();
let level = common.saturating_sub(common % 3);
let prefix = a.path.0.get(..level).unwrap_or_default().to_vec();
let block_path = |i: usize| {
let mut v = prefix.clone();
v.push(i as u32);
Path(v)
};
let (Some(&ia), Some(&ib)) = (a.path.0.get(level), b.path.0.get(level)) else {
return self.copy_para_range(&a, &b);
};
let (ia, ib) = (ia as usize, ib as usize);
if ia >= ib {
return self.copy_para_range(&a, &b);
}
let Some(bl) = self.container(a.story, &block_path(ia)) else {
return self.copy_para_range(&a, &b);
};
let edge_para = |i: usize, last: bool| -> Option<Path> {
let blk = bl.get(i)?;
if matches!(&**blk, Block::Para(_)) {
return None;
}
let mut pre = block_path(i).0;
edge_para_in_block(blk, &mut pre, level / 3, last)
};
let walked = |i: usize| bl.get(i).is_some_and(|b| !deeper_than_walk(b, level / 3));
let a_covers = if a.path.0.len() == level + 1 {
a.off == 0
} else {
a.path.0.len() > level + 1 && a.off == 0 && walked(ia) && edge_para(ia, false).as_ref() == Some(&a.path)
};
let b_at_end = self.para(b.story, &b.path).is_some_and(|p| p.len() == b.off);
let b_covers = if b.path.0.len() == level + 1 {
b_at_end
} else {
b.path.0.len() > level + 1 && walked(ib) && edge_para(ib, true).as_ref() == Some(&b.path) && b_at_end
};
// Start block ia:
if a_covers {
if let Some(blk) = bl.get(ia) {
out.push((**blk).clone());
}
} else if a.path.0.len() == level + 1 {
if let Some(blk) = bl.get(ia)
&& let Block::Para(p) = &**blk
{
out.push(Block::Para(trim_para(p, a.off, p.len(), false)));
}
} else if let Some(last_in_a) = edge_para(ia, true) {
let end_pos = Pos { story: a.story, path: last_in_a.clone(), off: self.para(a.story, &last_in_a).map_or(0, Paragraph::len) };
out.extend(self.copy_para_range(&a, &end_pos));
}
// Blocks strictly between ia and ib: whole blocks
for i in ia + 1..ib {
if let Some(blk) = bl.get(i) {
out.push((**blk).clone());
for p in self.paths_between(&a, &b) {
if let Some(para) = self.para(a.story, &p) {
let mut q = para.clone();
let to = if p == b.path { b.off } else { q.len() };
let from = if p == a.path { a.off } else { 0 };
let _ = q.delete(to.min(q.len()), q.len());
let _ = q.delete(0, from.min(q.len()));
q.section = None;
out.push(Block::Para(q));
}
}
// End block ib:
if b_covers {
if let Some(blk) = bl.get(ib) {
out.push((**blk).clone());
}
} else if b.path.0.len() == level + 1 {
if let Some(blk) = bl.get(ib)
&& let Block::Para(p) = &**blk
{
let clear = b.off < p.len();
out.push(Block::Para(trim_para(p, 0, b.off, clear)));
}
} else if let Some(first_in_b) = edge_para(ib, false) {
let start_pos = Pos { story: b.story, path: first_in_b, off: 0 };
out.extend(self.copy_para_range(&start_pos, &b));
}
out
}
@@ -1682,12 +1509,9 @@ impl Document {
if blocks.is_empty() {
return Ok(pos.clone());
}
let Some(dest_para) = self.para_at(pos) else {
if self.para_at(pos).is_none() {
return Err(DocError::BadPath(pos.path.to_string()));
};
let is_dest_empty = dest_para.is_empty();
let table_para = table_style_para(self, pos);
let destination_shading = self.styles.resolve_para_in(&dest_para.props, table_para.as_ref()).shading;
}
let mut parts = frag.parts.clone();
if !media_remap.is_empty() {
for b in &mut blocks {
@@ -1714,7 +1538,6 @@ impl Document {
&& let Some(Block::Para(src)) = blocks.first()
{
let src = src.clone();
let src_shading = self.styles.resolve_para(&src.props).shading;
let target = self.para_mut(pos.story, &pos.path)?;
let tail = target.split_off(pos.off)?;
let added = src.len();
@@ -1725,13 +1548,6 @@ impl Document {
target.append(src);
target.append(tail);
target.props = keep;
// Paragraph shading is the pasted text's background (HTML container backgrounds
// become paragraph shading), so an empty unshaded destination takes the source's.
// A paste without a paragraph mark into an existing paragraph leaves the
// destination paragraph's formatting unchanged (#6157).
if is_dest_empty && destination_shading.is_none() {
target.props.shading = src_shading;
}
target.section = sect;
return Ok(Pos { off: pos.off + added, ..pos.clone() });
}
@@ -1743,28 +1559,13 @@ impl Document {
let mut idx = left.last() + 1;
match first {
Block::Para(p) => {
let src_shading = self.styles.resolve_para(&p.props).shading;
let l = self.para_mut(pos.story, &left)?;
let keep = l.props.clone();
let keep_empty = keep.is_empty();
let keep_shading = keep.shading;
let mut p2 = p;
let pprops = p2.props.clone();
p2.section = None;
l.append(p2);
l.props = if keep_empty { pprops } else { keep };
if destination_shading.is_some() {
// When adopting a source paragraph style into an empty destination,
// preserve the destination background as a direct override so the
// source style's shading does not win over it (#6157).
if keep_empty && l.props.style.is_some() {
l.props.shading = destination_shading;
} else {
l.props.shading = keep_shading;
}
} else if is_dest_empty && !keep_empty && l.props.shading.is_none() {
l.props.shading = src_shading;
}
l.props = if keep.is_empty() { pprops } else { keep };
}
t @ Block::Table(_) => {
self.insert_block(pos.story, &left.with_last(idx), t)?;
@@ -1805,13 +1606,6 @@ impl Document {
}
}
/// Paragraph formatting of the table style enclosing `pos`, if any.
fn table_style_para(doc: &Document, pos: &Pos) -> Option<ParaProps> {
let (tp, _, _) = pos.path.cell()?;
let id = doc.table(pos.story, &tp)?.props.style.as_deref()?;
Some(doc.styles.table_style(id)?.para.clone())
}
/// 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;
-330
View File
@@ -118,182 +118,6 @@ fn copy_paste_round_trip() {
assert!(d.plain_text(StoryRef::Body).starts_with("XYalpha"));
}
/// Shading a pasted paragraph gets from its style is kept as direct shading on an empty unshaded destination (#6157).
#[test]
fn paste_keeps_source_style_shading() {
let mut d = doc(&[""]);
Arc::make_mut(&mut d.styles).upsert(crate::Style {
id: "SourceShaded".into(),
name: "Source Shaded".into(),
kind: crate::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
..Default::default()
});
let mut src = Paragraph::with_text("X", CharProps::default());
src.props.style = Some("SourceShaded".into());
let one = Fragment { blocks: vec![Block::Para(src)], ..Default::default() };
d.insert_fragment(&Pos::body(0, 0), &one).unwrap();
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
assert_eq!(p.props.shading, Some(crate::Rgb(0x33, 0x33, 0x33)), "source style shading is kept on empty destination");
}
/// A one-line paste without a paragraph mark into a non-empty paragraph leaves destination shading unshaded (#6157).
#[test]
fn single_block_paste_into_non_empty_paragraph_leaves_destination_unshaded() {
let mut d = doc(&["plain"]);
Arc::make_mut(&mut d.styles).upsert(crate::Style {
id: "SourceShaded".into(),
name: "Source Shaded".into(),
kind: crate::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
..Default::default()
});
let mut src = Paragraph::with_text("X", CharProps::default());
src.props.style = Some("SourceShaded".into());
let one = Fragment { blocks: vec![Block::Para(src)], ..Default::default() };
d.insert_fragment(&Pos::body(0, 5), &one).unwrap();
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
assert_eq!(p.props.shading, None, "one-line paste without a paragraph mark must not shade destination paragraph");
}
/// An empty destination with direct properties keeps the first pasted paragraph's style shading (#6157).
#[test]
fn multi_block_paste_keeps_source_style_shading() {
let mut d = doc(&[""]);
Arc::make_mut(&mut d.styles).upsert(crate::Style {
id: "SourceShaded".into(),
name: "Source Shaded".into(),
kind: crate::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
..Default::default()
});
let mut a = Paragraph::with_text("A", CharProps::default());
a.props.style = Some("SourceShaded".into());
let b = Paragraph::with_text("B", CharProps::default());
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().props.align = Some(crate::props::Align::Center);
d.insert_fragment(&Pos::body(0, 0), &frag).unwrap();
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
assert_eq!(p.props.shading, Some(crate::Rgb(0x33, 0x33, 0x33)), "first pasted paragraph keeps its style shading");
}
/// The destination's resolved (default) shading is not replaced by the source's direct shading (#6157).
#[test]
fn multi_block_paste_keeps_destination_default_shading() {
let mut d = doc(&["plain"]);
Arc::make_mut(&mut d.styles).default_para.shading = Some(crate::Rgb(0x22, 0x22, 0x22));
let mut a = Paragraph::with_text("A", CharProps::default());
a.props.shading = Some(crate::Rgb(0x11, 0x11, 0x11));
let b = Paragraph::with_text("B", CharProps::default());
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
d.insert_fragment(&Pos::body(0, 5), &frag).unwrap();
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
assert_eq!(p.props.shading, None, "source direct shading must not override the destination default");
assert_eq!(d.styles.resolve_para(&p.props).shading, Some(crate::Rgb(0x22, 0x22, 0x22)));
}
/// An empty destination with inherited shading keeps its shading when pasting a differently shaded source style (#6157).
#[test]
fn multi_block_paste_keeps_destination_inherited_shading_over_source_style() {
let mut d = doc(&["plain"]);
Arc::make_mut(&mut d.styles).default_para.shading = Some(crate::Rgb(0x22, 0x22, 0x22));
Arc::make_mut(&mut d.styles).upsert(crate::Style {
id: "SourceShaded".into(),
name: "Source Shaded".into(),
kind: crate::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
..Default::default()
});
let mut a = Paragraph::with_text("A", CharProps::default());
a.props.style = Some("SourceShaded".into());
let b = Paragraph::with_text("B", CharProps::default());
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
d.insert_fragment(&Pos::body(0, 5), &frag).unwrap();
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
assert_eq!(p.props.shading, Some(crate::Rgb(0x22, 0x22, 0x22)), "destination inherited shading is preserved as a direct override");
assert_eq!(
d.styles.resolve_para(&p.props).shading,
Some(crate::Rgb(0x22, 0x22, 0x22)),
"resolved shading must match the destination background, not the source style"
);
}
/// Multi-block paste into an empty unshaded destination keeps a shaded source style without
/// duplicating its color into direct paragraph shading (#6157).
#[test]
fn multi_block_paste_into_empty_destination_keeps_source_style_without_direct_shading() {
let mut d = doc(&[""]);
Arc::make_mut(&mut d.styles).upsert(crate::Style {
id: "SourceShaded".into(),
name: "Source Shaded".into(),
kind: crate::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
..Default::default()
});
let mut a = Paragraph::with_text("A", CharProps::default());
a.props.style = Some("SourceShaded".into());
let mut b = Paragraph::with_text("B", CharProps::default());
b.props.style = Some("SourceShaded".into());
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
d.insert_fragment(&Pos::body(0, 0), &frag).unwrap();
for idx in [0, 1] {
let p = d.para(StoryRef::Body, &Path::top(idx)).unwrap();
assert_eq!(p.props.style.as_deref(), Some("SourceShaded"));
assert_eq!(p.props.shading, None, "paragraph {idx} inherits from its style without redundant direct shading");
assert_eq!(d.styles.resolve_para(&p.props).shading, Some(crate::Rgb(0x33, 0x33, 0x33)));
}
}
/// Paragraph shading inherited from an enclosing table's style is preserved as destination shading (#6157).
#[test]
fn paste_keeps_destination_table_style_shading() {
let mut d = doc(&["outside"]);
Arc::make_mut(&mut d.styles).upsert(crate::Style {
id: "ShadedGrid".into(),
name: "Shaded Grid".into(),
kind: crate::StyleKind::Table,
para: ParaProps { shading: Some(crate::Rgb(0x22, 0x22, 0x22)), ..Default::default() },
..Default::default()
});
Arc::make_mut(&mut d.styles).upsert(crate::Style {
id: "SourceShaded".into(),
name: "Source Shaded".into(),
kind: crate::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: ParaProps { shading: Some(crate::Rgb(0x44, 0x44, 0x44)), ..Default::default() },
..Default::default()
});
let mut t = Table::new(1, 2, 200.0);
t.props.style = Some("ShadedGrid".into());
d.insert_block(StoryRef::Body, &Path::top(0), Block::Table(t)).unwrap();
// Single-block paste into cell (0, 0): table-style paragraph shading is not overridden.
let mut src = Paragraph::with_text("cell1", CharProps::default());
src.props.shading = Some(crate::Rgb(0x1e, 0x1e, 0x1e));
let one = Fragment { blocks: vec![Block::Para(src)], ..Default::default() };
let cell0 = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 0, 0]), off: 0 };
d.insert_fragment(&cell0, &one).unwrap();
let p0 = d.para(StoryRef::Body, &cell0.path).unwrap();
assert_eq!(p0.props.shading, None);
let tp = &d.styles.table_style("ShadedGrid").unwrap().para;
assert_eq!(d.styles.resolve_para_in(&p0.props, Some(tp)).shading, Some(crate::Rgb(0x22, 0x22, 0x22)));
// Multi-block paste with a differently shaded source style into empty cell (0, 1).
let mut a = Paragraph::with_text("A", CharProps::default());
a.props.style = Some("SourceShaded".into());
let b = Paragraph::with_text("B", CharProps::default());
let multi = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
let cell1 = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 0 };
d.insert_fragment(&cell1, &multi).unwrap();
let p1 = d.para(StoryRef::Body, &cell1.path).unwrap();
assert_eq!(d.styles.resolve_para_in(&p1.props, Some(tp)).shading, Some(crate::Rgb(0x22, 0x22, 0x22)));
}
/// The first paragraph of the deepest cell, following the first table at each level.
fn deepest(d: &Document) -> Path {
let (mut path, mut blocks) = (Vec::new(), &d.body);
@@ -480,33 +304,6 @@ fn fragment_without_parts_never_shows_an_unrelated_story() {
assert_eq!(got[2], None, "a header isn't a text box");
}
#[test]
fn fragment_extracts_text_box_stories_in_object_order() {
let mut p = Paragraph::new();
p.insert_object(0, box_shape(Some(20)), &CharProps::default()).unwrap();
p.insert_object(p.text.len(), box_shape(Some(10)), &CharProps::default()).unwrap();
let mut parts = BTreeMap::new();
parts.insert(
10,
crate::Part {
kind: PartKind::TextBox,
blocks: vec![para_block(Paragraph::with_text("Second", CharProps::default()))],
body: Default::default(),
},
);
parts.insert(
20,
crate::Part {
kind: PartKind::TextBox,
blocks: vec![para_block(Paragraph::with_text("First", CharProps::default()))],
body: Default::default(),
},
);
let f = Fragment { blocks: vec![Block::Para(p)], parts, ..Default::default() };
assert_eq!(f.plain_text(), "First\nSecond");
assert_eq!(f.clipboard_text(), "First\nSecond");
}
#[test]
fn self_nested_text_box_paste_is_bounded() {
let mut d = doc(&["x"]);
@@ -1226,130 +1023,3 @@ fn split_paragraph_keeps_the_drop_cap_on_the_first_paragraph_only() {
d.split_paragraph(&Pos::body(0, 0)).unwrap();
assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), cap));
}
/// #5906: Copying a range spanning from inside a table to an outside paragraph preserves the table.
#[test]
fn copy_range_preserves_table_structure_across_blocks() {
let mut d = Document::new();
let mut t = Table::new(2, 2, 200.0);
t.rows[0].cells[0].blocks = vec![para_block(Paragraph::with_text("A1", CharProps::default()))];
t.rows[0].cells[1].blocks = vec![para_block(Paragraph::with_text("B1", CharProps::default()))];
t.rows[1].cells[0].blocks = vec![para_block(Paragraph::with_text("A2", CharProps::default()))];
t.rows[1].cells[1].blocks = vec![para_block(Paragraph::with_text("B2", CharProps::default()))];
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::with_text("Trailing", CharProps::default())))];
let start = d.start_of(StoryRef::Body);
let end = d.end_of(StoryRef::Body);
let frag = d.copy_range(&start, &end);
assert_eq!(frag.blocks.len(), 2, "expected table and trailing paragraph, got {:?}", frag.blocks);
let Block::Table(tbl) = &frag.blocks[0] else { panic!("first block should be Table") };
assert_eq!(tbl.rows.len(), 2, "copied table row count");
assert_eq!(tbl.cols(), 2, "copied table col count");
let c00 = tbl.rows[0].cells[0].blocks.first().and_then(|b| match &**b {
Block::Para(p) => Some(p.text.as_str()),
_ => None,
});
assert_eq!(c00, Some("A1"), "cell (0, 0) text");
let Block::Para(trail) = &frag.blocks[1] else { panic!("second block should be Para") };
assert_eq!(trail.text.as_str(), "Trailing");
}
/// #5906: Copying a range enclosing a table between paragraphs preserves the table block.
#[test]
fn copy_range_preserves_table_between_paragraphs() {
let mut d = Document::new();
let mut t = Table::new(2, 2, 200.0);
t.rows[0].cells[0].blocks = vec![para_block(Paragraph::with_text("A1", CharProps::default()))];
t.rows[0].cells[1].blocks = vec![para_block(Paragraph::with_text("B1", CharProps::default()))];
t.rows[1].cells[0].blocks = vec![para_block(Paragraph::with_text("A2", CharProps::default()))];
t.rows[1].cells[1].blocks = vec![para_block(Paragraph::with_text("B2", CharProps::default()))];
d.body = vec![
Arc::new(Block::Para(Paragraph::with_text("Intro", CharProps::default()))),
Arc::new(Block::Table(t)),
Arc::new(Block::Para(Paragraph::with_text("Outro", CharProps::default()))),
];
let start = Pos { story: StoryRef::Body, path: Path(vec![0]), off: 0 };
let end = d.end_of(StoryRef::Body);
let frag = d.copy_range(&start, &end);
assert_eq!(frag.blocks.len(), 3, "expected intro, table, and outro, got {:?}", frag.blocks);
assert!(matches!(&frag.blocks[0], Block::Para(p) if p.text == "Intro"));
let Block::Table(tbl) = &frag.blocks[1] else { panic!("second block should be Table") };
assert_eq!(tbl.rows.len(), 2, "copied table row count");
assert_eq!(tbl.cols(), 2, "copied table col count");
assert!(matches!(&frag.blocks[2], Block::Para(p) if p.text == "Outro"));
}
/// #5906: Copy range across cells inside a table preserves all traversed paragraphs in linear order.
#[test]
fn copy_range_linear_cross_cells_preserves_all_traversed_paragraphs() {
let mut d = Document::new();
let mut t = Table::new(3, 3, 300.0);
for (r, row) in t.rows.iter_mut().enumerate() {
for (c, cell) in row.cells.iter_mut().enumerate() {
cell.blocks = vec![para_block(Paragraph::with_text(&format!("R{r}C{c}"), CharProps::default()))];
}
}
d.body = vec![Arc::new(Block::Table(t))];
// Start at (0, 1) offset 1 ("0C1"), end at (1, 1) offset 3 ("R1C")
let a = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 1 };
let b = Pos { story: StoryRef::Body, path: Path(vec![0, 1, 1, 0]), off: 3 };
let frag = d.copy_range(&a, &b);
assert_eq!(frag.blocks.len(), 4, "all 4 traversed cells in linear order");
let texts: Vec<&str> = frag
.blocks
.iter()
.filter_map(|b| match b {
Block::Para(p) => Some(p.text.as_str()),
_ => None,
})
.collect();
assert_eq!(texts, vec!["0C1", "R0C2", "R1C0", "R1C"]);
}
/// #5906: Copy range from paragraph before table into non-corner cell preserves all traversed text in linear order.
#[test]
fn copy_range_from_para_before_table_to_non_corner_cell() {
let mut d = Document::new();
let mut t = Table::new(3, 3, 300.0);
for (r, row) in t.rows.iter_mut().enumerate() {
for (c, cell) in row.cells.iter_mut().enumerate() {
cell.blocks = vec![para_block(Paragraph::with_text(&format!("R{r}C{c}"), CharProps::default()))];
}
}
d.body = vec![Arc::new(Block::Para(Paragraph::with_text("LeadingText", CharProps::default()))), Arc::new(Block::Table(t))];
let a = Pos { story: StoryRef::Body, path: Path(vec![0]), off: 7 };
let b = Pos { story: StoryRef::Body, path: Path(vec![1, 1, 1, 0]), off: 3 };
let frag = d.copy_range(&a, &b);
let texts: Vec<&str> = frag
.blocks
.iter()
.filter_map(|b| match b {
Block::Para(p) => Some(p.text.as_str()),
_ => None,
})
.collect();
assert_eq!(texts, vec!["Text", "R0C0", "R0C1", "R0C2", "R1C0", "R1C"]);
}
/// #5906: Copy range from non-corner cell into following paragraph preserves all traversed text in linear order.
#[test]
fn copy_range_from_cell_into_para_after_table() {
let mut d = Document::new();
let mut t = Table::new(2, 2, 200.0);
t.rows[0].cells[0].blocks = vec![para_block(Paragraph::with_text("Hello", CharProps::default()))];
t.rows[0].cells[1].blocks = vec![para_block(Paragraph::with_text("World", CharProps::default()))];
t.rows[1].cells[0].blocks = vec![para_block(Paragraph::with_text("Foo", CharProps::default()))];
t.rows[1].cells[1].blocks = vec![para_block(Paragraph::with_text("Bar", CharProps::default()))];
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::with_text("Trailing", CharProps::default())))];
let a = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 1 };
let b = Pos { story: StoryRef::Body, path: Path(vec![1]), off: 5 };
let frag = d.copy_range(&a, &b);
let texts: Vec<&str> = frag
.blocks
.iter()
.filter_map(|b| match b {
Block::Para(p) => Some(p.text.as_str()),
_ => None,
})
.collect();
assert_eq!(texts, vec!["orld", "Foo", "Bar", "Trail"]);
}
-1
View File
@@ -33,7 +33,6 @@ pub mod packs;
pub mod page;
pub mod para;
pub mod paste;
pub mod paste_cells;
pub mod phonetic;
pub mod protect;
pub mod references;
+6 -38
View File
@@ -35,32 +35,6 @@ pub fn selected_member(s: &Session) -> Option<(Pos, usize, &InlineObject)> {
Some((pos, m.index, &c.obj))
}
/// The canvas member whose text box story the caret is in (when no inner object is selected):
/// the canvas's position, the member's index and the member.
pub fn text_box_member(s: &Session) -> Option<(Pos, usize, &InlineObject)> {
if super::objects::selected(s).is_some() {
return None;
}
let StoryRef::Part(id) = s.sel.focus.story else { return None };
if !s.doc.parts.get(&id).is_some_and(|p| p.kind == PartKind::TextBox) {
return None;
}
let after = s.doc.text_box_anchor(id)?;
let pos = Pos { off: after.off.checked_sub(wordcraft_doc::para::OBJ.len_utf8())?, ..after };
let InlineObject::Group { children, canvas: Some(_), .. } = s.doc.para_at(&pos)?.object_at(pos.off)? else {
return None;
};
let (index, c) =
children.iter().enumerate().find(|(_, c)| pickable(c) && matches!(&c.obj, InlineObject::Shape { story: Some(sid), .. } if *sid == id))?;
Some((pos, index, &c.obj))
}
/// The canvas member object commands act on: one picked with `select.member`, or the text box
/// member whose text the caret is in.
pub(crate) fn active_member(s: &Session) -> Option<(Pos, usize, &InlineObject)> {
selected_member(s).or_else(|| text_box_member(s))
}
/// Whether a member can be picked on its own: a picture, shape or text box that is drawn (a
/// group inside a canvas isn't, nor a hidden member).
pub fn pickable(c: &GroupChild) -> bool {
@@ -321,13 +295,7 @@ pub(crate) fn member_command(s: &mut Session, id: &str, _: &Value) -> Option<Cmd
let replaces = (id.starts_with("text.") && id != "text.overtype")
|| matches!(
id,
"edit.paste"
| "edit.pasteText"
| "edit.pasteMerge"
| "edit.pasteNestedTable"
| "edit.pasteSpecial"
| "edit.pasteClipboardItem"
| "edit.pasteAllClipboard"
"edit.paste" | "edit.pasteText" | "edit.pasteMerge" | "edit.pasteSpecial" | "edit.pasteClipboardItem" | "edit.pasteAllClipboard"
);
if !replaces && !matches!(id, "edit.cut" | "edit.copy") {
return None;
@@ -382,7 +350,7 @@ fn remove_member(s: &mut Session, pos: &Pos, index: usize) -> Result<(), CmdErro
/// Move or Resize with a member picked: `x`/`y` (the page point of its top-left, as dragging its
/// frame gives it) and the size become its place and size in the canvas. `None`: no member.
pub(crate) fn member_bounds(s: &mut Session, v: &Value) -> Option<CmdResult> {
let (pos, index, obj) = active_member(s)?;
let (pos, index, obj) = selected_member(s)?;
let (w0, h0, _) = obj.frame()?;
let min = super::objects::min_size(obj);
let to = match (p::f32(v, "x"), p::f32(v, "y")) {
@@ -413,7 +381,7 @@ pub(crate) fn member_bounds(s: &mut Session, v: &Value) -> Option<CmdResult> {
/// Nudge with a member picked: it moves inside the canvas. `None`: no member.
pub(crate) fn member_nudge(s: &mut Session, dx: f32, dy: f32) -> Option<CmdResult> {
let (pos, index, _) = active_member(s)?;
let (pos, index, _) = selected_member(s)?;
Some(edit_member(s, &pos, index, |_, (sx, sy), c| {
c.x = (c.x + dx / sx).clamp(-MAX_SIDE, MAX_SIDE);
c.y = (c.y + dy / sy).clamp(-MAX_SIDE, MAX_SIDE);
@@ -438,10 +406,10 @@ fn edit_member(s: &mut Session, pos: &Pos, index: usize, f: impl FnOnce(wordcraf
Ok(json!({"object": member, "pos": super::pos_json(pos), "member": index}))
}
/// Change the active member's own object (Shape Format, Size, Rotate, Alt Text) when `pos` is its
/// canvas. `None`: no active member there.
/// Change the picked member's own object (Shape Format, Size, Rotate, Alt Text) when `pos` is its
/// canvas. `None`: no member picked there.
pub(crate) fn edit_member_object(s: &mut Session, pos: &Pos, f: impl Fn(&mut InlineObject)) -> Option<Result<InlineObject, CmdError>> {
let (at, index, _) = active_member(s).filter(|(at, ..)| at == pos)?;
let (at, index, _) = selected_member(s).filter(|(at, ..)| at == pos)?;
let mut out = None;
let r = edit_canvas(s, &at, |_, _, children| {
if let Some(c) = children.get_mut(index) {
-13
View File
@@ -182,9 +182,6 @@ pub(crate) fn dispatch(s: &mut Session, id: &str, mutates: bool, run: fn(&mut Se
_ if cells && (id.starts_with("table.") || matches!(id, "text.tab" | "text.backTab")) => run(s, v),
// Copy and Cut of whole cells take a table of them (#1744).
"edit.copy" | "edit.cut" if cells => run(s, v),
// Paste can lay a copied table over the selected cells. Let it inspect the selection
// before the ordinary column replacement deletes it.
"edit.paste" if cells => run(s, v),
"edit.copy" => copy(s, &segs),
"edit.cut" => {
let r = copy(s, &segs)?;
@@ -212,16 +209,6 @@ pub(crate) fn dispatch(s: &mut Session, id: &str, mutates: bool, run: fn(&mut Se
}
}
/// Delete the pieces of a selected cell rectangle for an ordinary Paste replacement.
pub(super) fn delete_cell_segments(s: &mut Session) -> Result<(), CmdError> {
if s.cell_range().is_some()
&& let Some(segments) = s.column_segments().map(<[(Pos, Pos)]>::to_vec)
{
delete(s, &segments)?;
}
Ok(())
}
/// Copy: one paragraph per block row (formatting kept); the plain text joins rows with newlines.
fn copy(s: &mut Session, segs: &[(Pos, Pos)]) -> CmdResult {
let mut blocks = Vec::new();
+6 -34
View File
@@ -39,7 +39,7 @@ fn has_text_sel(s: &Session) -> Option<&'static str> {
if s.sel.is_collapsed() { Some("nothing is selected") } else { None }
}
/// Something to cut: text, an object, or whole table cells (an empty cell's selection has no length, #1744).
/// Something to cut: text, or whole table cells (an empty cell's selection has no length, #1744).
fn has_sel(s: &Session) -> Option<&'static str> {
if s.sel.is_collapsed() && s.cell_range().is_none() { Some("nothing is selected") } else { None }
}
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
.key("Mod+Y / Mod+Shift+Z")
.pure(),
CommandSpec::new("edit.cut", "Cut", "Home › Clipboard", cut).key("Mod+X").when(has_sel),
CommandSpec::new("edit.copy", "Copy", "Home › Clipboard", copy).key("Mod+C / Mod+Insert").pure().when(has_sel),
CommandSpec::new("edit.copy", "Copy", "Home › Clipboard", copy).key("Mod+C / Mod+Insert").pure(),
// Word's Spike (Ctrl+F3, Ctrl+Shift+F3; ⌘ on the Mac): the AutoText entry "Spike", so Quick
// Parts and AutoText insert it without emptying it, as in Word.
CommandSpec::new("edit.spike", "Spike", "Editing", spike).key("Mod+F3").when(has_text_sel),
@@ -89,8 +89,6 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("edit.paste", "Paste", "Home › Clipboard", paste)
.key("Mod+V / Shift+Insert")
.params(r#"{"text"?: string, "html"?: string, "rtf"?: string, "privateClipboard"?: bool}"#),
CommandSpec::new("edit.pasteNestedTable", "Paste as Nested Table", "Home › Clipboard › Paste", paste_nested)
.params(r#"{"text"?: string, "html"?: string, "rtf"?: string, "privateClipboard"?: bool} (a copied table with the caret in a table cell nests in that cell; Paste instead inserts its rows or overwrites the cells from the caret's)"#),
CommandSpec::new("edit.pasteText", "Paste: Keep Text Only", "Home › Clipboard › Paste", paste_text)
.params(r#"{"text"?: string}"#)
.key("Mod+Shift+Alt+V"),
@@ -187,7 +185,6 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// Copy the selected text, object, or table cells to the clipboard.
fn copy(s: &mut Session, _: &Value) -> CmdResult {
let whole = super::table::selected_table(s);
copy_with(s, whole.as_ref())
@@ -221,7 +218,6 @@ pub(crate) fn copy_result(s: &mut Session) -> Value {
(s.clipboard_html, s.clipboard_rtf) = match &s.clipboard {
Some(f) => {
let mut d = f.to_document();
d.styles = s.doc.styles.clone();
if d.media.is_empty() {
d.media = s.doc.media.clone();
}
@@ -245,7 +241,6 @@ pub(crate) fn copy_result(s: &mut Session) -> Value {
r
}
/// Cut the selection, selected object, or whole table cells to the clipboard and remove it from the document.
fn cut(s: &mut Session, _: &Value) -> CmdResult {
let whole = super::table::selected_table(s);
let r = copy_with(s, whole.as_ref())?;
@@ -306,25 +301,8 @@ fn insert_spike(s: &mut Session, _: &Value) -> CmdResult {
/// else another program's HTML or RTF (#687). The system clipboard's text has none, so it pastes
/// as Keep Text Only does.
fn paste(s: &mut Session, v: &Value) -> CmdResult {
let pasted = super::paste::paste_content(s, v)?;
if let super::paste::Pasted::Fragment(frag) = &pasted
&& super::paste_cells::paste_over_selection(s, frag)?
{
return sel_result(s);
}
super::column::delete_cell_segments(s)?;
match pasted {
super::paste::Pasted::Fragment(frag) => super::paste::insert(s, frag)?,
super::paste::Pasted::Text(text) => super::paste::insert_text(s, &text)?,
}
sel_result(s)
}
/// Paste as Nested Table: like Paste, but a copied table goes inside the cell the caret is in
/// instead of laying its rows or cells over the table (#6739).
fn paste_nested(s: &mut Session, v: &Value) -> CmdResult {
match super::paste::paste_content(s, v)? {
super::paste::Pasted::Fragment(frag) => super::paste::insert_as_is(s, frag)?,
super::paste::Pasted::Fragment(frag) => super::paste::insert(s, frag)?,
super::paste::Pasted::Text(text) => super::paste::insert_text(s, &text)?,
}
sel_result(s)
@@ -466,17 +444,11 @@ fn paste_clip_item(s: &mut Session, v: &Value) -> CmdResult {
/// Every collected item, in the order they were copied (one undo step).
fn paste_all_clips(s: &mut Session, _: &Value) -> CmdResult {
let all: Vec<Fragment> = s.clip_history.items.iter().rev().map(|x| x.fragment.clone()).collect();
let multiple = all.len() > 1;
let mut r = sel_result(s)?;
for f in all {
if multiple {
// Insert each item at the end of the last one. Cell paste can overwrite a
// previous item or insert rows ahead of it.
super::paste::insert_as_is(s, f)?;
} else {
return paste_clip(s, f);
}
r = paste_clip(s, f)?;
}
sel_result(s)
Ok(r)
}
fn paste_text(s: &mut Session, v: &Value) -> CmdResult {
+2 -2
View File
@@ -32,11 +32,11 @@ pub(crate) use select::all_objects;
pub(crate) use select::{edit_obj, has_shape_or_canvas};
#[cfg(test)]
use select::{has_group, holds_ink, obj_size, with_obj};
pub use select::{min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects};
pub use select::{min_size, object_selection, picked_objects, selected, selected_all};
#[cfg(test)]
use shape::can_link;
pub(crate) use shape::set_text_body;
pub use shape::{text_box_target, text_box_targets};
pub use shape::text_box_target;
pub use specs::specs;
#[cfg(test)]
+5 -5
View File
@@ -1,4 +1,4 @@
use super::select::{edit_float, min_size, movable_story, obj_size, select_object, selected_or_text_box, with_obj};
use super::select::{edit_float, min_size, movable_story, obj_size, select_object, selected, with_obj};
use super::{CmdError, CmdResult, Float, InlineObject, Pos, Selection, Session, StoryRef, Value, Wrap, json, p};
/// Largest object offset or move, points.
@@ -9,7 +9,7 @@ pub(super) fn bounds(s: &mut Session, v: &Value) -> CmdResult {
if let Some(r) = crate::cmd::canvas::member_bounds(s, v) {
return r;
}
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let to = match (p::f32(v, "x"), p::f32(v, "y")) {
(Some(x), Some(y)) => Some((x, y)),
(None, None) => None,
@@ -88,7 +88,7 @@ fn move_in_text(s: &mut Session, pos: Pos, to: &Pos) -> Result<Pos, CmdError> {
/// (x, y), or for an In Line with Text object put it at the text position `to`, leaving the
/// original in place and the clipboard alone. The copy is selected.
pub(super) fn copy_to(s: &mut Session, v: &Value) -> CmdResult {
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let len = wordcraft_doc::para::OBJ.len_utf8();
let end = Pos { off: pos.off + len, ..pos.clone() };
if let Some(to) = text_target(v, &obj)? {
@@ -219,7 +219,7 @@ fn move_object_once(s: &mut Session, pos: &Pos, page: usize, x: f32, y: f32, (w,
/// column / paragraph that keeps it where it is, so it can be moved by an offset.
pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> {
use wordcraft_doc::para::Anchor;
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let Some((_, _, float)) = obj.frame() else { return Ok(()) };
if float.h_align.is_none() && float.v_align.is_none() {
return Ok(());
@@ -260,7 +260,7 @@ pub fn moves_with_text(f: &Float) -> bool {
/// object's vertical position to its paragraph or to the page, keeping it where it is now.
pub(super) fn move_with_text(s: &mut Session, with_text: bool) -> CmdResult {
use wordcraft_doc::para::Anchor;
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let Some((_, _, float)) = obj.frame() else { return Err(CmdError::Disabled("select a floating picture or shape first".into())) };
if moves_with_text(float) == with_text {
return Ok(json!({"object": serde_json::to_value(&obj).unwrap_or(Value::Null)}));
+18 -48
View File
@@ -1,5 +1,5 @@
use super::select::{edit_obj, is_shape_or_canvas, obj_size, selected, target_objects, with_obj};
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, Value, Wrap, json, p};
use super::select::{obj_size, selected, with_obj};
use super::{CmdError, CmdResult, InlineObject, Rgb, Session, Value, Wrap, p};
use wordcraft_doc::picfx::PicFx;
/// `picture.crop`: the crop, and optionally the new display size, as one edit. With a size, a
@@ -70,15 +70,19 @@ pub fn cropped_original_size(s: &Session, o: &InlineObject) -> Option<(f32, f32)
Some((orig.w * part(crop[0], crop[2]), orig.h * part(crop[1], crop[3])))
}
fn planned_size(s: &Session, o: &InlineObject, v: &Value) -> Result<(f32, f32), CmdError> {
/// Size: `scale` is a percentage of the current size, or with `original` of what the crop leaves
/// of the original size (`original` alone gives that back: the Size dialog's Reset); then `width`
/// and `height`, where one alone keeps the proportions unless `lockAspect` is false.
pub(super) fn size(s: &mut Session, v: &Value) -> CmdResult {
let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no object".into()))?;
let lock = p::bool(v, "lockAspect").unwrap_or(true);
let (w0, h0) = obj_size(o);
let (w0, h0) = obj_size(&o);
let (mut w, mut h) = (w0, h0);
let scale = p::f32(v, "scale");
let original = p::bool(v, "original").unwrap_or(false);
if original {
let (ow, oh) =
cropped_original_size(s, o).ok_or_else(|| CmdError::Disabled("only a picture whose image can be read has an original size".into()))?;
cropped_original_size(s, &o).ok_or_else(|| CmdError::Disabled("only a picture whose image can be read has an original size".into()))?;
let k = scale.unwrap_or(100.0) / 100.0;
(w, h) = (ow * k, oh * k);
} else if let Some(sc) = scale {
@@ -114,55 +118,21 @@ fn planned_size(s: &Session, o: &InlineObject, v: &Value) -> Result<(f32, f32),
// Sides set in proportion (from the original, or from a size whose sides both have a length)
// fit the limits together. Otherwise each side the call sets fits on its own, and a side it
// leaves as it was keeps its size, a straight line's 0 too.
if keep && (original || (w0 > 0.0 && h0 > 0.0 && (w, h) != (w0, h0))) {
Ok(fit_size(w, h, true))
let (w, h) = if keep && (original || (w0 > 0.0 && h0 > 0.0 && (w, h) != (w0, h0))) {
fit_size(w, h, true)
} else {
let (fw, fh) = fit_size(w, h, false);
let left = |new: f32, old: f32| !original && new == old;
Ok((if left(w, w0) { w } else { fw }, if left(h, h0) { h } else { fh }))
}
}
fn size_matching(s: &mut Session, v: &Value, pred: impl Fn(&InlineObject) -> bool, empty_msg: &str) -> CmdResult {
let targets = target_objects(s, pred);
if targets.is_empty() {
return Err(CmdError::Disabled(empty_msg.into()));
}
let planned: Vec<(Pos, f32, f32)> =
targets.into_iter().map(|(pos, o)| planned_size(s, &o, v).map(|(w, h)| (pos, w, h))).collect::<Result<Vec<_>, _>>()?;
(if left(w, w0) { w } else { fw }, if left(h, h0) { h } else { fh })
};
// Any drawing: a group's members scale with its frame (its child space is kept); a chart or
// SmartArt graphic lays itself out again at the new size.
let theme = s.doc.settings.theme_colors.clone();
let mut last = Value::Null;
for (pos, w, h) in &planned {
let o = edit_obj(s, pos, |o| {
o.set_size(*w, *h);
crate::cmd::chart::redraw(o, &theme);
crate::cmd::smart_art::redraw(o, &theme);
})?;
last = serde_json::to_value(o).unwrap_or(Value::Null);
}
Ok(json!({"object": last, "count": planned.len()}))
}
/// Size: `scale` is a percentage of the current size, or with `original` of what the crop leaves
/// of the original size (`original` alone gives that back: the Size dialog's Reset); then `width`
/// and `height`, where one alone keeps the proportions unless `lockAspect` is false.
pub(super) fn size(s: &mut Session, v: &Value) -> CmdResult {
size_matching(
s,
v,
|o| match o {
InlineObject::Graphic { graphic, .. } => graphic.chart.is_some() || graphic.smart_art.is_some(),
_ => o.is_drawing(),
},
"no object",
)
}
/// Shape Size: resizes only selected shapes, text boxes, and drawing canvases (or the active text box).
pub(super) fn shape_size(s: &mut Session, v: &Value) -> CmdResult {
size_matching(s, v, is_shape_or_canvas, "no shape selected")
with_obj(s, |o| {
o.set_size(w, h);
crate::cmd::chart::redraw(o, &theme);
crate::cmd::smart_art::redraw(o, &theme);
})
}
/// An object size within 1–4000 pt. With `keep`, both sides scale by one factor, the one nearest
+22 -104
View File
@@ -7,18 +7,16 @@ pub(super) fn has_picture(s: &Session) -> Option<&'static str> {
}
}
/// Guard returning `None` when a picture, shape, or active text box is selected.
pub(super) fn has_object(s: &Session) -> Option<&'static str> {
if selected_or_text_box(s).is_some() { None } else { Some("select a picture or shape first") }
if selected(s).is_some() { None } else { Some("select a picture or shape first") }
}
/// Guard returning `None` when a floating picture, shape, or active text box is selected.
pub(super) fn has_floating(s: &Session) -> Option<&'static str> {
// A canvas member moves inside its canvas.
if crate::cmd::canvas::active_member(s).is_some() {
if crate::cmd::canvas::selected_member(s).is_some() {
return None;
}
match selected_or_text_box(s) {
match selected(s) {
Some((_, InlineObject::Graphic { .. })) => Some(FROZEN),
Some((_, o)) if o.is_floating() => None,
_ => Some("select a floating picture or shape first"),
@@ -57,18 +55,10 @@ pub(super) fn has_movable(s: &Session) -> Option<&'static str> {
}
}
/// Guard returning `None` when at least one selected target (or active text box) is movable.
pub(super) fn has_any_movable(s: &Session) -> Option<&'static str> {
if !target_objects(s, |o| !matches!(o, InlineObject::Graphic { .. }) && o.is_drawing()).is_empty() {
return None;
}
has_movable(s)
}
/// `has_movable` for what places an object in the text (wrapping, position, alignment, Move with
/// Text): not for a member inside a drawing canvas, which the canvas places.
/// Text): not for a member picked inside a drawing canvas, which the canvas places.
pub(super) fn has_placeable(s: &Session) -> Option<&'static str> {
if crate::cmd::canvas::active_member(s).is_some() {
if crate::cmd::canvas::selected_member(s).is_some() {
return Some("a shape inside a drawing canvas is placed by the canvas");
}
has_movable(s)
@@ -92,33 +82,25 @@ pub(super) fn has_group(s: &Session) -> Option<&'static str> {
}
}
/// Whether `o` is a shape, text box, or drawing canvas.
pub(crate) fn is_shape_or_canvas(o: &InlineObject) -> bool {
matches!(o, InlineObject::Shape { .. }) || o.is_canvas()
}
/// Shape Fill and Shape Outline: any selected shape or Drawing Canvas, or the active text box.
/// Shape Fill and Shape Outline: a shape, or a Drawing Canvas's background and border.
pub(crate) fn has_shape_or_canvas(s: &Session) -> Option<&'static str> {
if target_objects(s, is_shape_or_canvas).is_empty() { Some("select a shape first") } else { None }
match selected(s) {
Some((_, o)) if o.is_canvas() => None,
_ => has_shape(s),
}
}
pub(super) fn can_group(s: &Session) -> Option<&'static str> {
if picked_objects(s).len() >= 2 { None } else { Some("select two or more pictures or shapes first (Shift+click)") }
}
/// Guard returning `None` when a shape or active text box is selected.
pub(super) fn has_shape(s: &Session) -> Option<&'static str> {
match selected_or_text_box(s) {
match selected(s) {
Some((_, InlineObject::Shape { .. })) => None,
_ => Some("select a shape first"),
}
}
/// Guard returning `None` when any selected object (or the active text box) is a shape.
pub(super) fn has_any_shape(s: &Session) -> Option<&'static str> {
if target_objects(s, |o| matches!(o, InlineObject::Shape { .. })).is_empty() { Some("select a shape first") } else { None }
}
/// The selection when it is exactly one picture, shape or text box (its U+FFFC), rather than
/// text: what clicking an object selects.
pub fn object_selection(s: &Session) -> Option<(Pos, &InlineObject)> {
@@ -205,51 +187,8 @@ pub(super) fn alt_text(s: &mut Session, v: &Value) -> CmdResult {
})
}
/// Returns the selected inline object, or the active text box containing the caret (including
/// a text box member inside a Drawing Canvas; never an enclosing group or canvas).
pub fn selected_or_text_box(s: &Session) -> Option<(Pos, InlineObject)> {
if let Some((pos, o)) = selected(s) {
return Some((pos, o));
}
if let Some((pos, _, member)) = crate::cmd::canvas::text_box_member(s) {
return Some((pos, member.clone()));
}
let (pos, id) = super::shape::text_box_target(s)?;
let o = s.doc.para_at(&pos)?.object_at(pos.off)?;
matches!(o, InlineObject::Shape { story: Some(sid), .. } if *sid == id).then(|| (pos, o.clone()))
}
/// Most objects one multi-object command changes.
pub(crate) const MAX_TARGET_OBJECTS: usize = 10_000;
/// Selected objects matching `pred` (in the selection range or added with `select.addObject`),
/// or — when nothing is selected — the active text box containing the caret if it matches `pred`.
pub fn target_objects(s: &Session, pred: impl Fn(&InlineObject) -> bool) -> Vec<(Pos, InlineObject)> {
if let Some((pos, _, member)) = crate::cmd::canvas::active_member(s) {
return if pred(member) { vec![(pos, member.clone())] } else { Vec::new() };
}
let mut out: Vec<(Pos, InlineObject)> = selected_all(s, MAX_TARGET_OBJECTS).into_iter().filter(|(_, o)| pred(o)).collect();
for pos in picked_objects(s) {
if !out.iter().any(|(p, _)| p == &pos)
&& let Some(o) = s.doc.para_at(&pos).and_then(|q| q.object_at(pos.off))
&& pred(o)
{
out.push((pos, o.clone()));
}
}
if out.is_empty()
&& selected(s).is_none()
&& let Some((pos, o)) = selected_or_text_box(s)
&& pred(&o)
{
out.push((pos, o));
}
out
}
/// Mutates the selected picture or shape, or the active text box containing the caret.
pub(super) fn with_obj(s: &mut Session, f: impl Fn(&mut InlineObject)) -> CmdResult {
let (pos, _) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let (pos, _) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let o = edit_obj(s, &pos, f)?;
Ok(json!({"object": serde_json::to_value(o).unwrap_or(Value::Null)}))
}
@@ -276,38 +215,17 @@ pub(super) fn edit_float(s: &mut Session, pos: &Pos, f: impl Fn(&mut Float)) ->
})
}
fn apply_float(o: &mut InlineObject, f: impl Fn(&mut Float)) {
if let Some(float) = o.float_mut() {
let was_inline = float.wrap == Wrap::Inline;
f(float);
// Word's distance from text for a newly wrapped object: 0.125" at the sides.
if was_inline && float.wrap != Wrap::Inline && float.dist == 0.0 {
float.dist = 9.0;
}
}
}
pub(super) fn with_float(s: &mut Session, f: impl Fn(&mut Float)) -> CmdResult {
with_obj(s, |o| apply_float(o, &f))
}
/// Mutates `Float` on all selected targets matching `pred` (or the active text box if it matches).
pub(super) fn with_floats_matching(s: &mut Session, pred: impl Fn(&InlineObject) -> bool, f: impl Fn(&mut Float)) -> CmdResult {
let targets = target_objects(s, pred);
if targets.is_empty() {
return Err(CmdError::Disabled("no picture or shape selected".into()));
}
let mut last = Value::Null;
for (pos, _) in &targets {
let o = edit_obj(s, pos, |o| apply_float(o, &f))?;
last = serde_json::to_value(o).unwrap_or(Value::Null);
}
Ok(json!({"object": last, "count": targets.len()}))
}
/// Mutates `Float` on all selected movable objects (or the active text box).
pub(super) fn with_movable_floats(s: &mut Session, f: impl Fn(&mut Float)) -> CmdResult {
with_floats_matching(s, |o| !matches!(o, InlineObject::Graphic { .. }) && o.is_drawing(), f)
with_obj(s, |o| {
if let Some(float) = o.float_mut() {
let was_inline = float.wrap == Wrap::Inline;
f(float);
// Word's distance from text for a newly wrapped object: 0.125" at the sides.
if was_inline && float.wrap != Wrap::Inline && float.dist == 0.0 {
float.dist = 9.0;
}
}
})
}
/// The selected pictures, shapes, text boxes and groups: the one the selection holds, then
+22 -41
View File
@@ -1,37 +1,16 @@
use super::select::{all_objects, edit_obj, picked_objects, selected, target_objects};
use super::select::{all_objects, edit_obj, picked_objects, selected, selected_all};
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, StoryRef, TextBody, Value, json, p};
pub(super) const NO_TEXT_BOX: &str = "select a text box first";
pub(super) fn has_text_box(s: &Session) -> Option<&'static str> {
if text_box_targets(s).is_empty() { Some(NO_TEXT_BOX) } else { None }
if text_box_target(s).is_some() { None } else { Some(NO_TEXT_BOX) }
}
fn is_text_box(s: &Session, id: u32) -> bool {
s.doc.parts.get(&id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::TextBox)
}
/// Target text boxes for Shape Format › Text commands: all selected text boxes (including
/// those added with `select.addObject` or the active canvas text box member), falling back
/// to the text box containing the caret when no object is selected.
pub fn text_box_targets(s: &Session) -> Vec<(Pos, u32)> {
let mut targets: Vec<(Pos, u32)> = target_objects(s, |o| matches!(o, InlineObject::Shape { story: Some(id), .. } if is_text_box(s, *id)))
.into_iter()
.filter_map(|(pos, o)| match o {
InlineObject::Shape { story: Some(id), .. } => Some((pos, id)),
_ => None,
})
.collect();
if targets.is_empty()
&& selected(s).is_none()
&& picked_objects(s).is_empty()
&& let Some(t) = text_box_target(s)
{
targets.push(t);
}
targets
}
/// The text box the Shape Format › Text commands work on: the selected one, or the one whose
/// text the caret is in. Its U+FFFC's position and its story.
pub fn text_box_target(s: &Session) -> Option<(Pos, u32)> {
@@ -49,22 +28,15 @@ pub fn text_box_target(s: &Session) -> Option<(Pos, u32)> {
Some((Pos { off, ..after }, id))
}
/// Change the target text boxes' text direction, alignment or link.
/// Change the target text box's text direction, alignment or link.
pub(crate) fn set_text_body(s: &mut Session, f: impl Fn(&mut TextBody)) -> CmdResult {
let targets = text_box_targets(s);
if targets.is_empty() {
return Err(CmdError::Disabled(NO_TEXT_BOX.into()));
}
let mut last_id = 0;
let mut last_body = TextBody::default();
for (pos, id) in targets {
let part = s.doc.parts.get_mut(&id).ok_or_else(|| CmdError::Failed("text box vanished".into()))?;
f(&mut part.body);
(last_id, last_body) = (id, part.body);
// Its paragraph is laid out again.
edit_obj(s, &pos, |_| {})?;
}
Ok(json!({"textBox": last_id, "body": last_body}))
let (pos, id) = text_box_target(s).ok_or_else(|| CmdError::Disabled(NO_TEXT_BOX.into()))?;
let part = s.doc.parts.get_mut(&id).ok_or_else(|| CmdError::Failed("text box vanished".into()))?;
f(&mut part.body);
let body = part.body;
// Its paragraph is laid out again.
edit_obj(s, &pos, |_| {})?;
Ok(json!({"textBox": id, "body": body}))
}
pub(super) fn can_link(s: &Session) -> Option<&'static str> {
@@ -109,6 +81,9 @@ pub(super) fn link_text_box(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"textBox": from, "next": to}))
}
/// Most shapes one `shape.effects` changes.
const MAX_EFFECT_SHAPES: usize = 10_000;
/// `shape.effects`: set or clear the shadow, glow and soft edges of the selected shapes.
pub(super) fn shape_effects(s: &mut Session, v: &Value) -> CmdResult {
use wordcraft_doc::effects::{Glow, Shadow, ShapeEffects};
@@ -158,13 +133,19 @@ pub(super) fn shape_effects(s: &mut Session, v: &Value) -> CmdResult {
Some(n @ Value::Number(_)) => Some(n.as_f64().map(|x| x as f32)),
Some(_) => return Err(CmdError::Params("`softEdge`: a radius in points or null".into())),
};
// The shapes in the selection, those added with `select.addObject`, or the active text box.
let targets = target_objects(s, |o| matches!(o, InlineObject::Shape { .. }));
// The shapes in the selection and those added to it (Shift+click).
let mut targets: Vec<Pos> =
selected_all(s, MAX_EFFECT_SHAPES).into_iter().filter(|(_, o)| matches!(o, InlineObject::Shape { .. })).map(|(pos, _)| pos).collect();
for pos in picked_objects(s) {
if !targets.contains(&pos) && matches!(s.doc.para_at(&pos).and_then(|q| q.object_at(pos.off)), Some(InlineObject::Shape { .. })) {
targets.push(pos);
}
}
if targets.is_empty() {
return Err(CmdError::Disabled("no shape selected".into()));
}
let mut last = ShapeEffects::default();
for (pos, _) in &targets {
for pos in &targets {
let o = edit_obj(s, pos, |o| {
if let InlineObject::Shape { effects, float, .. } = o {
let mut e = *effects;
+32 -113
View File
@@ -1,40 +1,14 @@
use super::arrange::{MAX_OFFSET, bounds, copy_to, move_with_text, unalign};
use super::group::{add_object, group, ungroup};
use super::picture::{adjust, adjust_media, clear_lum, crop, original_media, recolor, relook, remove_background, reset, shape_size, size};
use super::picture::{adjust, adjust_media, clear_lum, crop, original_media, recolor, relook, remove_background, reset, size};
use super::select::{
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_shape, has_floating, has_group, has_movable, has_object, has_picture,
has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box, target_objects,
with_float, with_floats_matching, with_movable_floats, with_obj,
all_objects, alt_text, can_group, edit_obj, has_floating, has_group, has_movable, has_object, has_picture, has_placeable, has_shape,
has_shape_or_canvas, has_sizable, obj_size, objects_list, selected, with_float, with_obj,
};
use super::shape::{NO_TEXT_BOX, can_link, has_text_box, link_text_box, set_text_body, shape_effects, text_box_target};
use super::{CmdError, CommandSpec, InlineObject, Pos, Rgb, Selection, Spin, TextVert, VAlign, Wrap, WrapText, json, p, sel_result};
use wordcraft_doc::picfx::PicFx;
fn run_rotation(s: &mut crate::Session, v: &serde_json::Value, pred: impl Fn(&InlineObject) -> bool) -> crate::CmdResult {
let deg = p::req_f32(v, "degrees")?;
let (fh, fv) = (p::bool(v, "flipH"), p::bool(v, "flipV"));
with_floats_matching(s, pred, |f| {
let cur = f.spin();
f.set_spin(Spin::new(deg, fh.unwrap_or(cur.flip_h), fv.unwrap_or(cur.flip_v)));
})
}
/// Returns the section properties of the target object's anchor story (including text boxes anchored
/// in a later body section or header/footer), falling back to `page::sect`.
fn target_sect(s: &crate::Session) -> wordcraft_doc::SectionProps {
if let Some((pos, _)) = selected_or_text_box(s) {
let i = match pos.story {
wordcraft_doc::StoryRef::Body => s.doc.section_index_of(pos.path.0.first().copied().unwrap_or(0) as usize),
wordcraft_doc::StoryRef::Part(id) => crate::cmd::page::section_of_part(s, id),
};
if let Some((_, sp)) = s.doc.sections().get(i) {
return (*sp).clone();
}
}
crate::cmd::page::sect(s)
}
/// Returns all command specifications for objects (pictures, shapes, text boxes, and drawing canvases).
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("picture.size", "Size", "Picture Format › Size", size)
@@ -212,15 +186,20 @@ pub fn specs() -> Vec<CommandSpec> {
"right" => Spin::new(90.0, false, false),
other => return Err(CmdError::Params(format!("unknown direction `{other}`"))),
};
with_movable_floats(s, |f| f.set_spin(f.spin().within(by)))
with_float(s, |f| f.set_spin(f.spin().within(by)))
})
.params(r#"{"direction": "right|left|flipVertical|flipHorizontal"} (turns 90° or mirrors the selected picture, shape or text box; its pixels are kept)"#)
.when(has_any_movable),
.when(has_movable),
CommandSpec::new("arrange.rotation", "Rotation", "Layout › Arrange", |s, v| {
run_rotation(s, v, |o| !matches!(o, InlineObject::Graphic { .. }) && o.is_drawing())
let deg = p::req_f32(v, "degrees")?;
let (fh, fv) = (p::bool(v, "flipH"), p::bool(v, "flipV"));
with_float(s, |f| {
let cur = f.spin();
f.set_spin(Spin::new(deg, fh.unwrap_or(cur.flip_h), fv.unwrap_or(cur.flip_v)));
})
})
.params(r#"{"degrees": number, "flipH"?: bool, "flipV"?: bool} (the exact angle, clockwise, of the selected picture, shape or text box; normalised to 0–360)"#)
.when(has_any_movable),
.when(has_movable),
CommandSpec::new("arrange.wrap", "Wrap Text", "Layout › Arrange", |s, v| {
let wrap: Wrap = serde_json::from_value(v.get("wrap").cloned().unwrap_or(json!("square"))).map_err(|e| CmdError::Params(e.to_string()))?;
with_float(s, |f| f.wrap = wrap)
@@ -240,8 +219,8 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("arrange.position", "Position", "Layout › Arrange", |s, v| {
let preset = p::str(v, "preset").unwrap_or("middleCenter").to_string();
let (x, y) = (p::f32(v, "x"), p::f32(v, "y"));
let sect = target_sect(s);
let size = selected_or_text_box(s).map(|(_, o)| obj_size(&o)).unwrap_or((72.0, 72.0));
let sect = crate::cmd::page::sect(s);
let size = selected(s).map(|(_, o)| obj_size(&o)).unwrap_or((72.0, 72.0));
with_float(s, |f| {
if f.wrap == Wrap::Inline {
f.wrap = Wrap::Square;
@@ -262,8 +241,8 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("arrange.sendBackward", "Send Backward", "Layout › Arrange", |s, _| with_float(s, |f| f.wrap = Wrap::BehindText)).when(has_placeable),
CommandSpec::new("arrange.align", "Align", "Layout › Arrange", |s, v| {
let h = p::str(v, "value").unwrap_or("center").to_string();
let tw = target_sect(s).text_width();
let w = selected_or_text_box(s).map(|(_, o)| obj_size(&o).0).unwrap_or(72.0);
let tw = crate::cmd::page::sect(s).text_width();
let w = selected(s).map(|(_, o)| obj_size(&o).0).unwrap_or(72.0);
with_float(s, |f| {
if f.wrap == Wrap::Inline {
f.wrap = Wrap::Square;
@@ -318,91 +297,31 @@ pub fn specs() -> Vec<CommandSpec> {
.params(r#"{"index"?: n}"#)
.pure(),
CommandSpec::new("shape.outline", "Shape Outline", "Shape Format › Shape Styles", |s, v| {
let color = match v.get("color") {
None => None,
Some(serde_json::Value::Null) => Some(None),
Some(_) => {
let hex = p::str(v, "color")
.and_then(Rgb::parse)
.ok_or_else(|| CmdError::Params("`color`: \"RRGGBB\" or null".into()))?;
Some(Some(hex))
}
};
let c = p::str(v, "color").and_then(Rgb::parse);
let w = p::f32(v, "width").map(|w| w.clamp(0.0, 72.0));
let dash = match v.get("dash") {
None => None,
Some(val) => {
let d = val.as_str().ok_or_else(|| {
CmdError::Params(
"`dash`: \"solid|dot|dash|lgDash|dashDot|lgDashDot|lgDashDotDot|sysDash|sysDot|sysDashDot|sysDashDotDot\"".into(),
)
})?;
let parsed = wordcraft_doc::line_dash::LineDash::from_ooxml(d);
if d != "solid" && parsed.is_solid() {
return Err(CmdError::Params(format!("unknown `dash` preset `{d}`")));
with_obj(s, |o| {
if let InlineObject::Shape { stroke, stroke_width, extra, .. } = o {
*stroke = c;
// A colour chosen here replaces an outline gradient from a file.
extra.outline_fill = None;
if let Some(w) = w {
*stroke_width = w;
}
} else if let Some(style) = crate::cmd::canvas::style_mut(o) {
style.stroke = c;
if let Some(w) = w {
style.stroke_width = w;
}
Some(parsed)
}
};
let cap = match v.get("cap") {
None => None,
Some(val) => {
let c = val.as_str().ok_or_else(|| CmdError::Params("`cap`: \"flat|rnd|sq\"".into()))?;
let parsed = wordcraft_doc::connector::LineCap::from_ooxml(c);
if c != "flat" && parsed.is_flat() {
return Err(CmdError::Params(format!("unknown `cap` style `{c}`")));
}
Some(parsed)
}
};
let targets = target_objects(s, is_shape_or_canvas);
if targets.is_empty() {
return Err(CmdError::Disabled("no shape selected".into()));
}
let mut last = serde_json::Value::Null;
for (pos, _) in &targets {
let o = edit_obj(s, pos, |o| {
if let InlineObject::Shape { stroke, stroke_width, extra, .. } = o {
if let Some(c) = color {
*stroke = c;
// A colour chosen here replaces an outline gradient from a file.
extra.outline_fill = None;
}
if let Some(w) = w {
*stroke_width = w;
}
if let Some(d) = dash.clone() {
extra.dash = d;
}
if let Some(cp) = cap {
extra.cap = cp;
}
} else if let Some(style) = crate::cmd::canvas::style_mut(o) {
if let Some(c) = color {
style.stroke = c;
}
if let Some(w) = w {
style.stroke_width = w;
}
}
})?;
last = serde_json::to_value(o).unwrap_or(serde_json::Value::Null);
}
Ok(json!({"object": last, "count": targets.len()}))
})
})
.params(r#"{"color"?: "RRGGBB" | null, "width"?: pt, "dash"?: "solid|dot|dash|lgDash|dashDot|lgDashDot|lgDashDotDot|sysDash|sysDot|sysDashDot|sysDashDotDot", "cap"?: "flat|rnd|sq"} (a selected drawing canvas: its border)"#)
.params(r#"{"color": "RRGGBB" | null, "width"?: pt} (a selected drawing canvas: its border)"#)
.when(has_shape_or_canvas),
CommandSpec::new("shape.size", "Size", "Shape Format › Size", shape_size)
.params(r#"{"width"?: pt, "height"?: pt, "lockAspect"?: bool, "scale"?: percent} (resizes the selected shapes, text boxes, and drawing canvases, or the active text box)"#)
.when(has_shape_or_canvas),
CommandSpec::new("shape.rotation", "Rotation", "Shape Format › Arrange", |s, v| run_rotation(s, v, is_shape_or_canvas))
.params(r#"{"degrees": number, "flipH"?: bool, "flipV"?: bool} (rotates the selected shapes, text boxes, and drawing canvases, or the active text box)"#)
.when(has_shape_or_canvas),
CommandSpec::new("shape.effects", "Shape Effects", "Shape Format › Shape Styles", shape_effects)
.params(
r#"{"shadow"?: preset|{"preset"?, "color"?: "RRGGBB", "transparency"?: %, "blur"?: pt, "distance"?: pt, "angle"?: deg}|null, "glow"?: pt|{"color"?: "RRGGBB", "size"?: pt, "transparency"?: %}|null, "softEdge"?: pt|null} (shadow presets: offsetBottomRight, offsetBottom, offsetBottomLeft, offsetRight, offsetCenter, offsetLeft, offsetTopRight, offsetTop, offsetTopLeft; an omitted key is left as it is; applies to every shape in the selection)"#,
)
.when(has_any_shape),
.when(has_shape),
CommandSpec::new("shape.change", "Change Shape", "Shape Format › Insert Shapes", |s, v| {
let kind: wordcraft_doc::para::ShapeKind = serde_json::from_value(v.get("kind").cloned().unwrap_or(json!("rectangle"))).map_err(|e| CmdError::Params(e.to_string()))?;
with_obj(s, |o| {
-448
View File
@@ -1797,451 +1797,3 @@ fn only_ink_members_pin_a_group() {
}
assert!(!holds_ink(&group), "a group of charts is not pinned");
}
/// Issue #5896: shape.outline can remove the frame (color: null), change width without
/// erasing stroke color, set dash and cap, and acts on a text box while typing inside it.
#[test]
fn shape_outline_and_fill_on_text_box() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.textBox", &json!({"text": "A text box with a frame"})).unwrap();
// While typing inside the text box:
// 1. shape.outline with {"color": null} removes the frame (stroke is None).
s.run("shape.outline", &json!({"color": null})).unwrap();
let (pos, _id) = text_box_target(&s).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let InlineObject::Shape { stroke, .. } = o else { panic!("{o:?}") };
assert_eq!(*stroke, None, "frame removed");
// 2. shape.outline can restore the frame with color, width, dash and cap:
s.run("shape.outline", &json!({"color": "156082", "width": 1.5, "dash": "dash", "cap": "rnd"})).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let InlineObject::Shape { stroke, stroke_width, extra, .. } = o else { panic!("{o:?}") };
assert_eq!(*stroke, Some(Rgb(0x15, 0x60, 0x82)));
assert_eq!(*stroke_width, 1.5);
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::Dash);
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Round);
// 3. Changing only the width preserves the stroke color:
s.run("shape.outline", &json!({"width": 3.0})).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let InlineObject::Shape { stroke, stroke_width, .. } = o else { panic!("{o:?}") };
assert_eq!(*stroke, Some(Rgb(0x15, 0x60, 0x82)), "color kept when width changed");
assert_eq!(*stroke_width, 3.0);
// 4. Malformed non-null colors are rejected before mutation:
assert!(matches!(s.run("shape.outline", &json!({"color": 123})), Err(CmdError::Params(_))));
assert!(matches!(s.run("shape.outline", &json!({"color": "not-a-hex"})), Err(CmdError::Params(_))));
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let InlineObject::Shape { stroke, .. } = o else { panic!("{o:?}") };
assert_eq!(*stroke, Some(Rgb(0x15, 0x60, 0x82)), "color preserved on error");
// 5. Unlocked size edits preserve the other dimension:
s.run("picture.size", &json!({"width": 100.0, "height": 80.0, "lockAspect": false})).unwrap();
s.run("picture.size", &json!({"width": 250.0, "lockAspect": false})).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let (w, h) = obj_size(o);
assert_eq!((w, h), (250.0, 80.0), "height preserved on width edit");
s.run("picture.size", &json!({"height": 150.0, "lockAspect": false})).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let (w, h) = obj_size(o);
assert_eq!((w, h), (250.0, 150.0), "width preserved on height edit");
// 6. shape.effects targets the active text box when typing inside it:
s.run("shape.effects", &json!({"shadow": "offsetBottomRight"})).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let InlineObject::Shape { effects, .. } = o else { panic!("{o:?}") };
assert!(effects.shadow.is_some(), "shadow applied to text box");
// 7. arrange.bounds targets the active text box when typing inside it:
let caret_sel = s.sel.clone();
s.run("arrange.bounds", &json!({"width": 300.0, "height": 180.0})).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let (w, h) = obj_size(o);
assert_eq!((w, h), (300.0, 180.0), "bounds applied to active text box");
// Restore typing caret inside text box so selected(&s) is None:
s.sel = caret_sel.clone();
assert!(selected(&s).is_none(), "caret is inside text box, no outer object selected");
// arrange.moveWithText targets the active text box once it is floating:
assert!(s.run("arrange.moveWithText", &json!({"value": true})).is_err(), "inline text box cannot move with text");
s.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
s.sel = caret_sel;
assert!(selected(&s).is_none(), "caret restored inside text box");
s.run("arrange.moveWithText", &json!({"value": false})).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let (_, _, float) = o.frame().unwrap();
assert_eq!(float.v_rel, wordcraft_doc::para::Anchor::Page, "moveWithText targets active floating text box");
// 8. When a picture is selected, shape.fill, shape.effects, and shape.outline do not target the text box:
let data = super::super::insert::base64_encode(&png(10, 10));
s.run("insert.picture", &json!({"data": data})).unwrap();
assert!(matches!(s.run("shape.fill", &json!({"color": "FF0000"})), Err(CmdError::Disabled(_))));
assert!(matches!(s.run("shape.effects", &json!({"shadow": "none"})), Err(CmdError::Disabled(_))));
assert!(matches!(s.run("shape.outline", &json!({"color": "FF0000"})), Err(CmdError::Disabled(_))));
// 9. fit_size normalizes NaN and clamps below 1 pt to 1 pt:
assert_eq!(super::picture::fit_size(f32::NAN, 0.0, false), (1.0, 1.0));
assert_eq!(super::picture::fit_size(-50.0, 0.0, false), (1.0, 1.0));
}
/// Issue #5896: `arrange.align` and `arrange.position` use the active text box's own
/// dimensions when invoked from a typing caret inside it, matching explicit object selection.
#[test]
fn arrange_align_and_position_on_active_text_box() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.textBox", &json!({"text": "Sized text box"})).unwrap();
let caret_sel = s.sel.clone();
let (pos, _) = text_box_target(&s).unwrap();
s.run("picture.size", &json!({"width": 250.0, "height": 140.0, "lockAspect": false})).unwrap();
let float_xy = |s: &Session| {
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let (_, _, f) = o.frame().unwrap();
(f.x, f.y)
};
for value in ["center", "right"] {
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("arrange.align", &json!({"value": "left"})).unwrap();
s.run("arrange.align", &json!({"value": value})).unwrap();
let from_selected = float_xy(&s).0;
s.sel = caret_sel.clone();
assert!(selected(&s).is_none(), "caret inside text box for align {value}");
s.run("arrange.align", &json!({"value": "left"})).unwrap();
s.run("arrange.align", &json!({"value": value})).unwrap();
let from_caret = float_xy(&s).0;
assert_eq!(from_caret, from_selected, "align {value} matches explicit selection");
}
for preset in ["middleCenter", "bottomRight"] {
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("arrange.position", &json!({"preset": "topLeft"})).unwrap();
s.run("arrange.position", &json!({"preset": preset})).unwrap();
let from_selected = float_xy(&s);
s.sel = caret_sel.clone();
assert!(selected(&s).is_none(), "caret inside text box for position {preset}");
s.run("arrange.position", &json!({"preset": "topLeft"})).unwrap();
s.run("arrange.position", &json!({"preset": preset})).unwrap();
let from_caret = float_xy(&s);
assert_eq!(from_caret, from_selected, "position {preset} matches explicit selection");
}
}
/// Issue #5896 P2: typing inside a canvas text box routes Fill, Outline, Effects, Size, and
/// Rotation to that text box member (leaving the canvas and siblings untouched), keeps
/// canvas-owned placement commands disabled, and keeps commands disabled inside a regular group.
#[test]
fn typing_in_canvas_text_box_formats_member_not_canvas() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.canvas", &json!({"width": 400, "height": 300, "fill": "FFF2CC", "outline": "1F4E79"})).unwrap();
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100, "height": 40})).unwrap();
s.run("select.objects", &json!({"index": 0})).unwrap();
let tb_res = s.run("insert.textBox", &json!({"text": "Canvas note"})).unwrap();
let tb_id = tb_res["story"].as_u64().unwrap() as u32;
assert_eq!(s.sel.focus.story, StoryRef::Part(tb_id));
assert!(selected(&s).is_none());
assert!(crate::cmd::canvas::selected_member(&s).is_none());
s.run("shape.fill", &json!({"color": "FF0000"})).unwrap();
s.run("shape.outline", &json!({"color": null})).unwrap();
let canvas_mid = all_objects(&s).into_iter().next().unwrap().1;
let InlineObject::Group { children: mid_children, .. } = &canvas_mid else { panic!("{canvas_mid:?}") };
assert!(matches!(&mid_children[1].obj, InlineObject::Shape { stroke: None, .. }));
assert_eq!(canvas_mid.canvas_style().and_then(|st| st.stroke), Rgb::parse("1F4E79"));
s.run("shape.outline", &json!({"color": "00AA00", "width": 2.0, "dash": "dash", "cap": "rnd"})).unwrap();
s.run("shape.effects", &json!({"shadow": "offsetBottomRight"})).unwrap();
s.run("picture.size", &json!({"width": 180.0, "height": 90.0, "lockAspect": false})).unwrap();
s.run("arrange.rotation", &json!({"degrees": 15.0})).unwrap();
let canvas = all_objects(&s).into_iter().next().unwrap().1;
let InlineObject::Group { w: cw, h: ch, float: cf, children, canvas: Some(style), .. } = &canvas else {
panic!("expected canvas: {canvas:?}");
};
assert_eq!((*cw, *ch, cf.spin().deg), (400.0, 300.0, 0.0));
assert_eq!(style.fill, Rgb::parse("FFF2CC").map(wordcraft_doc::fill::Fill::solid));
assert_eq!(style.stroke, Rgb::parse("1F4E79"));
assert_eq!(style.stroke_width, 0.75);
assert_eq!(obj_size(&children[0].obj), (100.0, 40.0), "sibling shape size untouched");
let InlineObject::Shape { effects: sib_fx, .. } = &children[0].obj else { panic!() };
assert!(sib_fx.shadow.is_none(), "sibling shape effects untouched");
let InlineObject::Shape { w, h, fill, stroke, stroke_width, float, effects, extra, story, .. } = &children[1].obj else {
panic!("expected text box member");
};
assert_eq!(*story, Some(tb_id));
assert_eq!((*w, *h), (180.0, 90.0));
assert_eq!(*fill, Rgb::parse("FF0000").map(wordcraft_doc::fill::Fill::solid));
assert_eq!(*stroke, Rgb::parse("00AA00"));
assert_eq!(*stroke_width, 2.0);
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::Dash);
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Round);
assert!(effects.shadow.is_some());
assert_eq!(float.spin().deg, 15.0);
for (cmd, params) in [
("arrange.wrap", json!({"wrap": "square"})),
("arrange.align", json!({"value": "center"})),
("arrange.position", json!({"preset": "middleCenter"})),
("arrange.moveWithText", json!({"value": true})),
("arrange.copyTo", json!({"x": 50.0, "y": 50.0})),
] {
assert!(matches!(s.run(cmd, &params), Err(CmdError::Disabled(_))), "{cmd} stays disabled for canvas member");
}
// Regular group: typing inside a grouped text box leaves shape commands disabled without modifying the group.
let mut g = Session::new(wordcraft_doc::Document::new());
g.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
g.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
g.sel = Selection::caret(g.doc.end_of(StoryRef::Body));
let grouped_tb_id = g.run("insert.textBox", &json!({"text": "Grouped note"})).unwrap()["story"].as_u64().unwrap() as u32;
g.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
g.run("select.objects", &json!({"index": 0})).unwrap();
g.run("select.addObject", &json!({"index": 1})).unwrap();
g.run("arrange.group", &json!({})).unwrap();
g.sel = Selection::caret(g.doc.end_of(StoryRef::Part(grouped_tb_id)));
let before_group = all_objects(&g).into_iter().next().unwrap().1;
for (cmd, params) in [
("shape.fill", json!({"color": "FF0000"})),
("shape.outline", json!({"color": null})),
("shape.effects", json!({"shadow": "offsetBottomRight"})),
("picture.size", json!({"width": 180.0, "lockAspect": false})),
("arrange.rotation", json!({"degrees": 15.0})),
] {
assert!(matches!(g.run(cmd, &params), Err(CmdError::Disabled(_))), "{cmd} disabled inside regular group");
}
assert_eq!(all_objects(&g).into_iter().next().unwrap().1, before_group);
}
/// Issue #5896: `shape.outline` rejects unknown or non-string `dash` and `cap` parameters
/// instead of silently falling back to Solid / Flat.
#[test]
fn shape_outline_rejects_unknown_dash_and_cap() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s.run("shape.outline", &json!({"color": "156082", "width": 2.0, "dash": "dash", "cap": "rnd"})).unwrap();
for bad in
[json!({"cap": "round"}), json!({"dash": "dotted"}), json!({"cap": 42}), json!({"dash": false}), json!({"dash": null}), json!({"cap": null})]
{
assert!(matches!(s.run("shape.outline", &bad), Err(CmdError::Params(_))), "expected Params error for {bad}");
}
let (_, o) = selected(&s).unwrap();
let InlineObject::Shape { stroke, stroke_width, extra, .. } = o else { panic!("{o:?}") };
assert_eq!(stroke, Rgb::parse("156082"));
assert_eq!(stroke_width, 2.0);
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::Dash);
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Round);
}
/// Issue #5896: with multiple shapes selected, Line and Layout commands update every selected target.
#[test]
fn multi_shape_selection_updates_outline_and_layout_on_all() {
let mut s = Session::new(wordcraft_doc::Document::new());
let id0 = s.run("insert.textBox", &json!({"text": "First", "width": 120.0, "height": 60.0})).unwrap()["story"].as_u64().unwrap() as u32;
s.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
let id1 = s.run("insert.textBox", &json!({"text": "Second", "width": 200.0, "height": 90.0})).unwrap()["story"].as_u64().unwrap() as u32;
s.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("select.addObject", &json!({"index": 1})).unwrap();
s.run("shape.outline", &json!({"color": "156082", "width": 2.5, "dash": "lgDash", "cap": "sq"})).unwrap();
s.run("picture.size", &json!({"width": 160.0, "lockAspect": false})).unwrap();
s.run("arrange.rotation", &json!({"degrees": 30.0})).unwrap();
s.run("shape.alignText", &json!({"anchor": "ctr"})).unwrap();
s.run("shape.textDirection", &json!({"dir": "vert"})).unwrap();
assert_eq!(picked_objects(&s).len(), 2, "multi-selection preserved across formatting and layout");
let objs = all_objects(&s);
assert_eq!(objs.len(), 2);
for (idx, ((_, o), expected_h)) in objs.iter().zip([60.0, 90.0]).enumerate() {
let InlineObject::Shape { w, h, stroke, stroke_width, float, extra, .. } = o else { panic!("{o:?}") };
assert_eq!((*w, *h), (160.0, expected_h), "box {idx} kept its own height");
assert_eq!(*stroke, Rgb::parse("156082"), "box {idx} stroke");
assert_eq!(*stroke_width, 2.5, "box {idx} stroke width");
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::LongDash, "box {idx} dash");
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Square, "box {idx} cap");
assert_eq!(float.spin().deg, 30.0, "box {idx} rotation");
}
for id in [id0, id1] {
let body = s.doc.parts.get(&id).unwrap().body;
assert_eq!(body.anchor, VAlign::Center);
assert_eq!(body.vert, TextVert::Vert);
}
s.run("shape.outline", &json!({"color": null})).unwrap();
for (_, o) in all_objects(&s) {
let InlineObject::Shape { stroke, .. } = o else { panic!("{o:?}") };
assert_eq!(stroke, None);
}
}
/// Issue #5896: "No line", dash preset, and line cap set via `shape.outline` survive a DOCX save/open round trip.
#[test]
fn shape_outline_no_line_dash_and_cap_round_trip_docx() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.textBox", &json!({"text": "Borderless"})).unwrap();
s.run("shape.outline", &json!({"color": null})).unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s.run("shape.outline", &json!({"color": "156082", "width": 2.25, "dash": "dashDot", "cap": "rnd"})).unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "ellipse"})).unwrap();
s.run("shape.outline", &json!({"color": "C00000", "width": 1.5, "dash": "sysDot", "cap": "sq"})).unwrap();
let bytes = crate::io::save_bytes("out.docx", &s.doc).unwrap();
let mut s2 = Session::new(wordcraft_doc::Document::new());
s2.run("file.open", &json!({"path": "out.docx", "data": crate::cmd::insert::base64_encode(&bytes)})).unwrap();
let objs = all_objects(&s2);
assert_eq!(objs.len(), 3);
let InlineObject::Shape { stroke: tb_stroke, story, .. } = &objs[0].1 else { panic!("{:?}", objs[0]) };
assert!(story.is_some());
assert_eq!(*tb_stroke, None, "No line preserved through DOCX round trip");
let InlineObject::Shape { stroke, stroke_width, extra, .. } = &objs[1].1 else { panic!("{:?}", objs[1]) };
assert_eq!(*stroke, Rgb::parse("156082"));
assert!((*stroke_width - 2.25).abs() < 0.05, "width {stroke_width}");
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::DashDot);
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Round);
let InlineObject::Shape { stroke, stroke_width, extra, .. } = &objs[2].1 else { panic!("{:?}", objs[2]) };
assert_eq!(*stroke, Rgb::parse("C00000"));
assert!((*stroke_width - 1.5).abs() < 0.05, "width {stroke_width}");
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::SystemDot);
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Square);
}
/// Issue #5896: mixed multi-selections enable `shape.fill`, `shape.outline`, `shape.effects`,
/// `shape.alignText`, and `shape.textDirection` whenever at least one selected target matches.
#[test]
fn mixed_object_multi_selection_enables_shape_and_text_box_commands() {
// Picture selected first + rectangle added via select.addObject.
let mut s = Session::new(wordcraft_doc::Document::new());
let data = super::super::insert::base64_encode(&png(12, 12));
s.run("insert.picture", &json!({"data": data, "width": 60})).unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("select.addObject", &json!({"index": 1})).unwrap();
s.run("shape.fill", &json!({"color": "00AA00"})).unwrap();
s.run("shape.outline", &json!({"color": "FF0000", "dash": "dash"})).unwrap();
s.run("shape.effects", &json!({"shadow": "offsetBottomRight"})).unwrap();
assert!(matches!(s.run("shape.alignText", &json!({"anchor": "b"})), Err(CmdError::Disabled(_))));
assert!(matches!(s.run("shape.textDirection", &json!({"dir": "vert"})), Err(CmdError::Disabled(_))));
let objs = all_objects(&s);
assert!(matches!(&objs[0].1, InlineObject::Image { .. }));
let InlineObject::Shape { fill, stroke, effects, extra, .. } = &objs[1].1 else { panic!("{:?}", objs[1]) };
assert_eq!(*fill, Rgb::parse("00AA00").map(wordcraft_doc::fill::Fill::solid));
assert_eq!(*stroke, Rgb::parse("FF0000"));
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::Dash);
assert!(effects.shadow.is_some());
// Plain shape selected first + text box added via select.addObject.
let mut s2 = Session::new(wordcraft_doc::Document::new());
s2.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s2.sel = Selection::caret(s2.doc.end_of(StoryRef::Body));
let tb_id = s2.run("insert.textBox", &json!({"text": "Mixed box"})).unwrap()["story"].as_u64().unwrap() as u32;
s2.run("select.objects", &json!({"index": 0})).unwrap();
s2.run("select.addObject", &json!({"index": 1})).unwrap();
s2.run("shape.alignText", &json!({"anchor": "b"})).unwrap();
s2.run("shape.textDirection", &json!({"dir": "vert270"})).unwrap();
let body = s2.doc.parts.get(&tb_id).unwrap().body;
assert_eq!(body.anchor, VAlign::Bottom);
assert_eq!(body.vert, TextVert::Vert270);
}
/// Issue #5896: `arrange.align` and `arrange.position` inside an active text box anchored in
/// a later section use that anchor section's margins rather than section 0's.
#[test]
fn arrange_align_and_position_use_text_box_anchor_section() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s.run("layout.margins", &json!({"left": 144.0, "right": 144.0})).unwrap();
let sect1_tw = crate::cmd::page::sect(&s).text_width();
let sect0_tw = s.doc.sections()[0].1.text_width();
assert!(sect1_tw < sect0_tw, "section 1 has narrower text area");
s.run("insert.textBox", &json!({"text": "Section 1 box", "width": 100.0, "height": 50.0})).unwrap();
s.run("arrange.align", &json!({"value": "right"})).unwrap();
let (pos, o) = selected_or_text_box(&s).unwrap();
let (_, _, f) = o.frame().unwrap();
assert!((f.x - (sect1_tw - 100.0)).abs() < 0.01, "aligned to section 1 right margin ({} vs {})", f.x, sect1_tw - 100.0);
s.run("arrange.position", &json!({"preset": "topRight"})).unwrap();
let o2 = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let (_, _, f2) = o2.frame().unwrap();
assert!((f2.x - (sect1_tw - 100.0)).abs() < 0.01, "positioned to section 1 right margin ({} vs {})", f2.x, sect1_tw - 100.0);
}
/// Issue #5896: bulk rotation commands stay enabled when a chart is primary selection and a
/// movable shape is added via `select.addObject`.
#[test]
fn chart_primary_with_added_shape_allows_rotation() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.chart", &json!({"type": "column"})).unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("select.addObject", &json!({"index": 1})).unwrap();
s.run("arrange.rotation", &json!({"degrees": 45.0})).unwrap();
s.run("arrange.rotate", &json!({"direction": "right"})).unwrap();
let objs = all_objects(&s);
let (_, _, chart_f) = objs[0].1.frame().unwrap();
let (_, _, shape_f) = objs[1].1.frame().unwrap();
assert_eq!(chart_f.spin().deg, 0.0);
assert_eq!(shape_f.spin().deg, 135.0);
}
/// Issue #5896: `shape.size` and `shape.rotation` only change shapes/canvases in a mixed
/// Picture + Chart + Shape selection, while generic `picture.size` keeps resizing all targets.
#[test]
fn shape_size_and_rotation_only_affect_shapes_in_mixed_selection() {
let mut s = Session::new(wordcraft_doc::Document::new());
let data = super::super::insert::base64_encode(&png(12, 12));
s.run("insert.picture", &json!({"data": data})).unwrap();
s.run("picture.size", &json!({"width": 60.0, "height": 40.0, "lockAspect": false})).unwrap();
s.run("arrange.rotation", &json!({"degrees": 10.0})).unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.chart", &json!({"type": "column"})).unwrap();
let (chart_w0, chart_h0, _) = all_objects(&s)[1].1.frame().unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "rectangle", "width": 150.0, "height": 80.0})).unwrap();
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("select.addObject", &json!({"index": 1})).unwrap();
s.run("select.addObject", &json!({"index": 2})).unwrap();
s.run("shape.size", &json!({"width": 210.0, "lockAspect": false})).unwrap();
s.run("shape.rotation", &json!({"degrees": 45.0})).unwrap();
assert_eq!(picked_objects(&s).len(), 3, "multi-selection preserved across shape.size and shape.rotation");
let objs = all_objects(&s);
let (pw, ph, pf) = objs[0].1.frame().unwrap();
assert_eq!((pw, ph, pf.spin().deg), (60.0, 40.0, 10.0), "picture untouched by shape.size/rotation");
let (cw, ch, _) = objs[1].1.frame().unwrap();
assert_eq!((cw, ch), (chart_w0, chart_h0), "chart untouched by shape.size");
let (sw, sh, sf) = objs[2].1.frame().unwrap();
assert_eq!((sw, sh, sf.spin().deg), (210.0, 80.0, 45.0), "shape updated");
// Generic picture.size continues to resize every sizable object in the selection.
s.run("picture.size", &json!({"width": 180.0, "lockAspect": false})).unwrap();
let objs2 = all_objects(&s);
assert_eq!(objs2[0].1.frame().unwrap().0, 180.0);
assert_eq!(objs2[1].1.frame().unwrap().0, 180.0);
assert_eq!(objs2[2].1.frame().unwrap().0, 180.0);
}
+1 -1
View File
@@ -224,7 +224,7 @@ fn manual_hyphenation(s: &mut Session, v: &Value) -> CmdResult {
Ok(best.map(|(_, v)| v).unwrap_or_else(|| json!({"done": true})))
}
pub(crate) fn section_of_part(s: &Session, id: u32) -> usize {
fn section_of_part(s: &Session, id: u32) -> usize {
let sections = s.doc.sections();
for (i, (_, sp)) in sections.iter().enumerate() {
if [sp.headers.default, sp.headers.first, sp.headers.even, sp.footers.default, sp.footers.first, sp.footers.even].contains(&Some(id)) {
+14 -64
View File
@@ -49,12 +49,10 @@ fn clip_text(s: &Session, v: &Value) -> Option<String> {
}
}
/// Whether the string starts with an RTF file header.
fn looks_like_rtf(t: &str) -> bool {
t.trim_start().starts_with("{\\rtf")
}
/// Whether the string looks like an HTML fragment.
fn looks_like_html(t: &str) -> bool {
let t = t.trim_start();
t.starts_with('<') && (t.contains("</") || t.contains("/>"))
@@ -67,53 +65,18 @@ fn owns_clipboard(v: &Value) -> bool {
p::bool(v, "privateClipboard").unwrap_or(true)
}
/// Accommodate macOS arboard wrapping: `<html><head>...</head><body>...</body></html>`.
fn extract_body(html: &str) -> Option<&str> {
let lower = html.to_ascii_lowercase();
let body_start = lower.find("<body")?;
let after_body = html.get(body_start..)?;
let tag_end_rel = after_body.find('>')?;
let tag_end = body_start.checked_add(tag_end_rel)?.checked_add(1)?;
let end = lower.rfind("</body>")?;
if tag_end <= end { html.get(tag_end..end) } else { None }
}
/// Whether the supplied HTML string matches WordCraft's session clipboard HTML,
/// accounting for macOS arboard wrapping.
fn html_matches_clipboard(h: &str, clip: &str) -> bool {
if h == clip {
return true;
}
if clip.is_empty() {
return false;
}
extract_body(h).is_some_and(|body| body == clip || body.trim() == clip.trim())
}
/// Whether the clipboard payload matches WordCraft's session clipboard copy, so the session's
/// formatted fragment can be used.
pub(crate) fn matches_session_clipboard(s: &Session, v: &Value) -> bool {
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
let html = p::str(v, "html");
let rtf = p::str(v, "rtf");
let has_rich = html.is_some_and(|h| !h.is_empty()) || rtf.is_some_and(|r| !r.is_empty());
let html_matches = html.is_none_or(|h| html_matches_clipboard(h, &s.clipboard_html));
let rtf_matches = rtf.is_none_or(|r| r == s.clipboard_rtf);
owns_clipboard(v)
&& s.clipboard.as_ref().is_some_and(|f| {
text.as_ref().is_none_or(|t| f.clipboard_text() == *t || (t.is_empty() && has_rich))
&& html_matches
&& rtf_matches
&& (text.is_some() || has_rich || (html.is_none() && rtf.is_none()))
})
}
/// The source for a format, if the clipboard has it.
fn source(s: &Session, v: &Value, fmt: &str) -> Option<String> {
let non_empty = |t: String| if t.is_empty() { None } else { Some(t) };
match fmt {
"formatted" if matches_session_clipboard(s, v) => Some(String::new()),
"formatted" if owns_clipboard(v) => {
let f = s.clipboard.as_ref()?;
// System clipboard text that isn't our own copy means someone else copied since.
match p::str(v, "text") {
Some(t) if f.clipboard_text() != t.replace("\r\n", "\n") => None,
_ => Some(String::new()),
}
}
"formatted" => None,
"rtf" => p::str(v, "rtf").map(str::to_string).or_else(|| clip_text(s, v).filter(|t| looks_like_rtf(t))).and_then(non_empty),
"html" => p::str(v, "html").map(str::to_string).or_else(|| clip_text(s, v).filter(|t| looks_like_html(t))).and_then(non_empty),
@@ -326,15 +289,17 @@ pub fn paste_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
}
fn clipboard_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
if matches_session_clipboard(s, v)
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
if owns_clipboard(v)
&& let Some(f) = &s.clipboard
&& text.as_ref().is_none_or(|t| f.clipboard_text() == *t)
&& (text.is_some() || (p::str(v, "html").is_none() && p::str(v, "rtf").is_none()))
{
return Ok(Pasted::Fragment(f.clone()));
}
if let Some(f) = rich_fragment(s, v) {
return Ok(Pasted::Fragment(f));
}
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
match text {
Some(t) if !t.is_empty() => Ok(Pasted::Text(t)),
_ => Err(CmdError::Failed("the clipboard is empty".into())),
@@ -400,19 +365,8 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
}
}
/// Paste `frag` at the selection. A copied table pasted with the caret in a table cell goes the way
/// Word's Paste does it (rows inserted or cells overwritten, #6739; see [`super::paste_cells`]);
/// anything else is [`insert_as_is`].
pub fn insert(s: &mut Session, frag: Fragment) -> Result<(), CmdError> {
if super::paste_cells::paste_cells(s, &frag)? {
return Ok(());
}
insert_as_is(s, frag)
}
/// Replace the selection with `frag`, marking it as an insertion under Track Changes. A table pasted
/// with the caret in a cell nests in that cell (Word's Paste as Nested Table).
pub fn insert_as_is(s: &mut Session, mut frag: Fragment) -> Result<(), CmdError> {
/// Replace the selection with `frag`, marking it as an insertion under Track Changes.
pub fn insert(s: &mut Session, mut frag: Fragment) -> Result<(), CmdError> {
// The pasted text keeps its own formatting; what Backspace carried over is not for after it (#6518).
s.forget_carried();
super::controls::prepare_edit(s)?;
@@ -438,11 +392,7 @@ pub fn insert_as_is(s: &mut Session, mut frag: Fragment) -> Result<(), CmdError>
});
}
}
let before_props = track.then(|| s.doc.para_at(&at).map(|p| p.props.clone())).flatten();
let end = s.doc.insert_fragment(&at, &frag)?;
if track && let Some(before) = before_props {
crate::cmd::fmt_revisions::record_para_props(s, at.story, &at.path, &before)?;
}
// The paragraph marks the paste added are inserted too, so rejecting it joins the
// paragraphs again. The last paragraph ends with the original mark and keeps it.
if let Some(r) = rid
-267
View File
@@ -1,267 +0,0 @@
//! Paste with the caret inside a table cell (#6739). Word does not nest a copied table there (that
//! is its Paste as Nested Table, `edit.pasteNestedTable` here); observed black-box with synthetic
//! tables:
//!
//! - a copied table (or whole rows) whose caret is in the first column of a table of the same
//! width: its rows are inserted above the caret's row;
//! - otherwise the copied cells overwrite the cells from the caret's cell rightwards and down,
//! adding the rows and columns they need (new cells empty).
//!
//! With a cell selection, Paste overwrites from its top-left, including when the copy is wider
//! than the selection.
//!
//! Pasted cells take the destination's cell formatting (Word's default keeps the source's; not
//! done yet). What this does not cover falls back to the old behaviour, a nested table (see
//! [`paste_cells`]).
use wordcraft_doc::edit::Fragment;
use wordcraft_doc::props::VMerge;
use wordcraft_doc::table::{MAX_COLS, MAX_ROWS};
use wordcraft_doc::{Block, Cell, InlineObject, Path, Pos, Row, StoryRef, Table};
use crate::{CmdError, Selection, Session};
/// The fragment's table when it is one table and nothing else (empty paragraphs around it aside).
fn lone_table(frag: &Fragment) -> Option<&Table> {
let mut table = None;
for b in &frag.blocks {
match b {
Block::Table(t) if table.is_none() => table = Some(t),
Block::Para(p) if p.is_empty() && p.objects.is_empty() => {}
_ => return None,
}
}
table
}
/// The width of a rectangular table that can be pasted cell by cell. Merges, offsets,
/// objects and content control wrappers require preserving the table structure.
fn plain_source(t: &Table) -> Option<usize> {
let cols = t.rows.first()?.cells.len();
let simple = |c: &Cell| {
c.span() == 1
&& c.props.vmerge == VMerge::None
&& !c.blocks.is_empty()
&& c.controls.is_empty()
&& c.blocks.iter().all(|b| matches!(&**b, Block::Para(p) if p.objects.is_empty() && p.section.is_none()))
};
let ok = cols > 0
&& t.controls.is_empty()
&& t.rows.iter().all(|r| {
r.cells.len() == cols
&& r.first_grid() == 0
&& r.grid_after() == 0
&& r.props.exceptions.is_none()
&& r.controls.is_empty()
&& r.cells.iter().all(simple)
});
ok.then_some(cols)
}
/// Whether the destination table's rows are a plain grid: one cell per grid column, no merges,
/// offsets or row exceptions.
fn plain_destination(t: &Table) -> bool {
let cols = t.grid.len();
cols > 0
&& t.rows.iter().all(|r| {
r.cells.len() == cols
&& r.first_grid() == 0
&& r.grid_after() == 0
&& r.props.exceptions.is_none()
&& r.cells.iter().all(|c| c.span() == 1 && c.props.vmerge == VMerge::None)
})
}
/// How deep [`has_control`] looks into tables nested in a cell; a deeper cell counts as holding a
/// control, so a hostile document can't make the walk recurse without bound.
const MAX_CONTROL_DEPTH: usize = 16;
/// Whether a cell holds a content control, or a control's start or end in its text, at any depth
/// of nested tables, or a text box anchor (whose story may hold one): overwriting the cell
/// replaces all of its blocks, which could remove a locked control (the caret's own cell is
/// checked by the caller's edit rules).
fn has_control(c: &Cell) -> bool {
cell_has_control(c, 0)
}
fn cell_has_control(c: &Cell, depth: usize) -> bool {
if !c.controls.is_empty() || depth > MAX_CONTROL_DEPTH {
return true;
}
c.blocks.iter().any(|b| match &**b {
// A text box (or a group holding one) anchored here has its own story, which may hold a locked
// control; it is not walked, so a cell with one counts as holding a control.
Block::Para(p) => {
p.objects.iter().any(|o| matches!(o, InlineObject::ControlStart { .. } | InlineObject::ControlEnd) || !o.text_boxes().is_empty())
}
Block::Table(t) => {
!t.controls.is_empty() || t.rows.iter().any(|r| !r.controls.is_empty() || r.cells.iter().any(|c| cell_has_control(c, depth + 1)))
}
})
}
/// What a paste into a cell does with the copied table `src` at (`row0`, `col0`) of `dest`.
enum Plan {
/// Insert the copy's rows above `row0`.
InsertRows,
/// Lay the copy's cells over the table from the cell.
Overwrite,
}
/// How `src` goes into `dest` at (`row0`, `col0`), or `None` when it can't be laid over it (the
/// paste nests the table instead).
fn plan(dest: &Table, src: &Table, src_cols: usize, row0: usize, col0: usize, allow_row_insertion: bool) -> Option<Plan> {
if !plain_destination(dest) || col0 >= dest.grid.len() || row0 >= dest.rows.len() {
return None;
}
let (src_rows, dest_cols) = (src.rows.len(), dest.grid.len());
// A one-column table is a layout wrapper more often than a grid: a wider copy nests in it.
if dest_cols == 1 && src_cols > 1 {
return None;
}
// Word inserts whole rows above the caret's row when the caret is in the first column and
// the rows are as wide as the table; a one-column table can't tell rows from a cell.
if allow_row_insertion && col0 == 0 && src_cols == dest_cols && dest_cols > 1 {
return (dest.rows.len().saturating_add(src_rows) <= MAX_ROWS).then_some(Plan::InsertRows);
}
if dest.rows.len().max(row0.saturating_add(src_rows)) > MAX_ROWS || dest_cols.max(col0.saturating_add(src_cols)) > MAX_COLS {
return None;
}
// A wrapper may open before the first overwritten row or cell and close after the last.
// Use ordinary paste for wrapped grids so an overwrite cannot bypass a structural control.
if !dest.controls.is_empty() || dest.rows.iter().any(|row| !row.controls.is_empty() || row.cells.iter().any(|cell| !cell.controls.is_empty())) {
return None;
}
let hit = |r: usize| dest.rows.get(r).is_some_and(|row| row.cells.iter().skip(col0).take(src_cols).any(has_control));
(!(row0..row0.saturating_add(src_rows).min(dest.rows.len())).any(hit)).then_some(Plan::Overwrite)
}
/// Overwrite cells from the top-left of a selection while it still identifies a rectangle.
pub(super) fn paste_over_selection(s: &mut Session, frag: &Fragment) -> Result<bool, CmdError> {
let Some(range) = s.cell_range() else { return Ok(false) };
if s.doc.settings.track_changes || s.doc.control_at(&s.sel.ordered().0).is_some() {
return Ok(false);
}
let Some(src) = lone_table(frag) else { return Ok(false) };
let Some(src_cols) = plain_source(src) else { return Ok(false) };
let (row, col) = (range.rows.0, range.cols.0);
let story = range.story;
let table = range.table.clone();
let Some(dest) = s.doc.table(story, &table) else { return Ok(false) };
let Some(edit) = plan(dest, src, src_cols, row, col, false) else { return Ok(false) };
apply_plan(s, src, story, &table, row, col, edit)?;
s.column = None;
s.goal_x = None;
s.pending = None;
Ok(true)
}
/// A copied table pasted with the caret in a table cell, as Word's default Paste does it.
/// `false` (nothing done; the caller pastes as before, nesting the table) when:
/// - the selection is not a caret in a cell, or the clipboard is not one table;
/// - Track Changes is on (the cell edits aren't tracked here);
/// - the copied table has merged cells, ragged rows, empty cells, pictures or other objects,
/// a paragraph with a section break, or a control wrapping the table, a row or a cell;
/// - the destination table has merged cells or offset rows, or an overwrite would affect a
/// destination with structural wrappers or a cell containing a control in its blocks;
/// - the caret is in a content control that shows its placeholder (the ordinary paste replaces
/// the placeholder);
/// - the destination has one column and the copy more (a layout wrapper), or the paste would pass
/// the limits on a table's rows or columns.
pub fn paste_cells(s: &mut Session, frag: &Fragment) -> Result<bool, CmdError> {
if s.doc.settings.track_changes || !s.sel.is_collapsed() || s.cell_range().is_some() {
return Ok(false);
}
let Some(src) = lone_table(frag) else { return Ok(false) };
let Some(src_cols) = plain_source(src) else { return Ok(false) };
let Some((tp, row0, col0)) = s.sel.focus.path.cell() else { return Ok(false) };
let Some(dest) = s.doc.table(s.sel.focus.story, &tp) else { return Ok(false) };
if plan(dest, src, src_cols, row0, col0, true).is_none() {
return Ok(false);
}
// A caret in a control that shows its placeholder: the edit rules would select the
// placeholder to replace it, which the row insertion would not do. The ordinary paste does.
// This also covers a caret at the edge of such a control (drop-down, check box): rows used to
// be inserted there, now the table nests. Overwrite already declined for cells with controls.
if s.doc.control_at(&s.sel.focus).is_some_and(|r| r.control.showing_placeholder) {
return Ok(false);
}
// Pasting ends Backspace's carried formatting, as in the ordinary paste path.
s.forget_carried();
// Protection: the edit rules may move the caret (to where typing goes) or refuse.
if super::controls::prepare_edit(s)?.is_some() {
// Normalizing the caret can enter a control and select its placeholder.
// Let ordinary paste replace that selection.
return Ok(false);
}
let at = s.sel.focus.clone();
let Some((tp, row0, col0)) = at.path.cell() else { return Ok(false) };
let story = at.story;
let Some(dest) = s.doc.table(story, &tp) else { return Ok(false) };
let Some(edit) = plan(dest, src, src_cols, row0, col0, true) else { return Ok(false) };
apply_plan(s, src, story, &tp, row0, col0, edit)?;
Ok(true)
}
fn apply_plan(s: &mut Session, src: &Table, story: StoryRef, tp: &Path, row0: usize, col0: usize, plan: Plan) -> Result<(), CmdError> {
let t = s.doc.table_mut(story, tp)?;
let first = match plan {
Plan::InsertRows => insert_source_rows(t, src, row0),
Plan::Overwrite => overwrite_cells(t, src, row0, col0),
};
super::table::touch_cells(s, tp)?;
let mut path = tp.0.clone();
path.extend([first.0 as u32, first.1 as u32, 0]);
s.sel = Selection::caret(Pos { story, path: Path(path), off: 0 });
Ok(())
}
/// Insert the rows of `src` above row `at` of `t` (same column count), formatted as that row.
/// Returns the (row, cell) of the first pasted cell.
fn insert_source_rows(t: &mut Table, src: &Table, at: usize) -> (usize, usize) {
let Some(template) = t.rows.get(at) else { return (at, 0) };
let new_rows: Vec<Row> = src
.rows
.iter()
.map(|sr| {
let mut row = Row { props: template.props.clone(), ..Row::default() };
row.props.header = false;
row.cells = template
.cells
.iter()
.zip(&sr.cells)
.map(|(dc, sc)| {
let mut c = Cell::empty();
c.props = dc.props.clone();
c.blocks = sc.blocks.clone();
c
})
.collect();
row
})
.collect();
t.rows.splice(at..at, new_rows);
(at, 0)
}
/// Lay the cells of `src` over those of `t` from (`row0`, column `col0`), adding the rows and
/// columns they need. Returns the (row, cell) of the first pasted cell.
fn overwrite_cells(t: &mut Table, src: &Table, row0: usize, col0: usize) -> (usize, usize) {
let src_cols = src.rows.first().map_or(0, |r| r.cells.len());
while t.grid.len() < col0.saturating_add(src_cols) && t.grid.len() < MAX_COLS {
t.insert_col(t.grid.len());
}
while t.rows.len() < row0.saturating_add(src.rows.len()) && t.rows.len() < MAX_ROWS {
let at = t.rows.len();
t.insert_row(at, at.saturating_sub(1));
}
for (i, sr) in src.rows.iter().enumerate() {
let Some(row) = t.rows.get_mut(row0 + i) else { break };
for (j, sc) in sr.cells.iter().enumerate() {
if let Some(dc) = row.cells.get_mut(col0 + j) {
dc.blocks = sc.blocks.clone();
}
}
}
(row0, col0)
}
-84
View File
@@ -1122,87 +1122,3 @@ mod spelling_navigation_tests {
}
}
}
/// #6086 review: A pre-existing table whose cell paragraphs and runs are all redlined (including an
/// empty cell with a deleted/inserted paragraph mark) is not a structural table revision; Accept
/// All / Reject All and whole-table selection resolution must preserve the table shell.
#[test]
fn preexisting_table_with_redlined_cell_content_preserves_table_shell() {
use std::sync::Arc;
use wordcraft_doc::{Block, CharProps, Paragraph, Path, Pos, Revision, RevisionKind, StoryRef, table::Table};
struct Cleanup(std::path::PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let dir = std::env::temp_dir().join(format!("wc-review-preexisting-tbl-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _cleanup = Cleanup(dir.clone());
let make_redlined_table = |del: bool| -> Document {
let mut d = Document::new();
let kind = if del { RevisionKind::Delete } else { RevisionKind::Insert };
d.revisions.push(Revision::new(kind, "Alice", "2026-11-24T00:00:00Z"));
let rev = Some(0);
let mark_props = if del { CharProps { del: rev, ..Default::default() } } else { CharProps { ins: rev, ..Default::default() } };
let mut p0 = Paragraph::with_text("Cell text", mark_props.clone());
p0.mark = mark_props.clone();
let mut p1 = Paragraph::new();
p1.mark = mark_props;
let mut t = Table::new(1, 2, 240.0);
t.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(p0))];
t.rows[0].cells[1].blocks = vec![Arc::new(Block::Para(p1))];
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::new()))];
d
};
let assert_shell_preserved = |doc: &Document, label: &str| {
let tables: Vec<&Table> = doc.body.iter().filter_map(|b| b.as_table()).collect();
assert_eq!(tables.len(), 1, "{label}: pre-existing table shell must remain");
assert_eq!(tables[0].rows.len(), 1, "{label}: row count must remain 1");
assert_eq!(tables[0].rows[0].cells.len(), 2, "{label}: cell count must remain 2");
assert_eq!(tables[0].rows[0].cells[0].blocks[0].as_para().unwrap().plain_text(), "", "{label}: cell 0 text cleared");
assert_eq!(tables[0].rows[0].cells[1].blocks[0].as_para().unwrap().plain_text(), "", "{label}: cell 1 stays empty");
};
for (del, all_cmd, sel_cmd, label) in [
(true, "review.acceptAll", "review.accept", "deleted cell content + Accept"),
(false, "review.rejectAll", "review.reject", "inserted cell content + Reject"),
] {
let doc = make_redlined_table(del);
// Global Accept All / Reject All in memory.
let mut s_all = Session::new(doc.clone());
s_all.run(all_cmd, &json!({})).unwrap();
assert_shell_preserved(&s_all.doc, &format!("{label} (in-memory all)"));
assert!(s_all.run("review.changes", &json!({})).unwrap().as_array().unwrap().is_empty());
// Whole-body selection Accept / Reject.
let mut s_body = Session::new(doc.clone());
s_body.run("select.all", &json!({})).unwrap();
s_body.run(sel_cmd, &json!({})).unwrap();
assert_shell_preserved(&s_body.doc, &format!("{label} (whole-body sel)"));
// Whole-table selection Accept / Reject.
let mut s_tbl = Session::new(doc.clone());
s_tbl.sel = crate::Selection {
anchor: Pos { story: StoryRef::Body, path: Path(vec![0, 0, 0, 0]), off: 0 },
focus: Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 0 },
};
s_tbl.run(sel_cmd, &json!({})).unwrap();
assert_shell_preserved(&s_tbl.doc, &format!("{label} (whole-table sel)"));
// DOCX save/open round-trip followed by Accept All / Reject All.
let path = dir.join(format!("preexisting-{del}.docx"));
crate::io::save_path(&path, &doc).unwrap();
let reopened = crate::io::open_path(&path).unwrap();
let mut s_rt = Session::new(reopened);
s_rt.run(all_cmd, &json!({})).unwrap();
assert_shell_preserved(&s_rt.doc, &format!("{label} (DOCX round-trip all)"));
assert!(s_rt.run("review.changes", &json!({})).unwrap().as_array().unwrap().is_empty());
}
}
+12 -3
View File
@@ -9,9 +9,11 @@ use wordcraft_doc::para::InlineObject;
use wordcraft_doc::props::Rgb;
use wordcraft_doc::wordart::GradStop;
use super::objects::{edit_obj, target_objects};
use super::objects::{edit_obj, picked_objects, selected_all};
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
/// Most shapes one command fills (a selection over a whole document).
const MAX_FILL_SHAPES: usize = 10_000;
/// Most stops read from a command (the fill keeps at most `MAX_STOPS` after sanitizing).
const MAX_PARAM_STOPS: usize = 64;
@@ -66,9 +68,16 @@ fn shape_fill(s: &mut Session, v: &Value) -> CmdResult {
Ok(serde_json::json!({"object": last, "count": targets.len()}))
}
/// The shapes and canvases in the selection, those added with `select.addObject`, or the active text box.
/// The shapes and canvases in the selection and those added to it (Shift+click).
fn targets(s: &Session) -> Vec<Pos> {
target_objects(s, |o| matches!(o, InlineObject::Shape { .. }) || o.is_canvas()).into_iter().map(|(pos, _)| pos).collect()
let fillable = |o: &InlineObject| matches!(o, InlineObject::Shape { .. }) || o.is_canvas();
let mut out: Vec<Pos> = selected_all(s, MAX_FILL_SHAPES).into_iter().filter(|(_, o)| fillable(o)).map(|(pos, _)| pos).collect();
for pos in picked_objects(s) {
if !out.contains(&pos) && s.doc.para_at(&pos).and_then(|q| q.object_at(pos.off)).is_some_and(fillable) {
out.push(pos);
}
}
out
}
fn color(v: &Value) -> Result<Rgb, CmdError> {
+100 -459
View File
@@ -1,5 +1,3 @@
use std::collections::BTreeMap;
use super::{
Arc, Block, CharProps, CmdError, CmdResult, Document, InlineObject, Paragraph, RevisionKind, Selection, Session, StoryRef, Value, json, p,
para_block,
@@ -29,17 +27,13 @@ impl CompareOptions {
}
}
/// Context and tracking counters for diffing document blocks and paragraph contents.
/// Context and tracking counters for diffing paragraph contents.
struct DiffCtx<'a> {
ins: u32,
del: u32,
opts: &'a CompareOptions,
author: &'a str,
date: &'a str,
budget: &'a mut u64,
char_fallbacks: &'a mut usize,
table_fallbacks: &'a mut usize,
changes: usize,
plain_revised: bool,
}
@@ -53,9 +47,7 @@ const MAX_CHAR_DIFF: usize = 2000;
/// headers and footers, footnotes, text boxes, fields) are accepted and listed in the result.
/// When character-level comparison is requested (`"level": "character"`) but any paragraph exceeds
/// [`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"`. When a
/// same-text table has media changes but an incompatible layout or exceeds [`wordcraft_doc::table::MAX_TABLE_DEPTH`],
/// structural table replacement is deferred and `"tables"` is listed in `"notHonoured"`.
/// fallback count in `"characterFallback"`, and includes `"level"` in `"notHonoured"`.
pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
// 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.
@@ -88,57 +80,91 @@ pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
["moves", "comments", "headersFooters", "footnotes", "textBoxes", "fields"].into_iter().filter(|k| v.get(*k).is_some()).collect();
let author = p::str(v, "author").map(str::trim).filter(|a| !a.is_empty()).map(str::to_string).unwrap_or_else(|| s.author.clone());
let date = crate::cmd::now_iso();
// Adopt media referenced by the revised body and reachable text boxes into the original
// document: identical bytes reuse the original's key (deduplicated by content), while
// replaced or new media receives a fresh key in s.doc.media so both media parts are
// preserved in the result (#6086). Unreferenced media in uncompared parts (e.g. headers
// and footers) is not imported.
let mut revised = revised;
let mut raw_media = std::mem::take(&mut revised.media);
let mut media_map = BTreeMap::new();
let old: Vec<Arc<Block>> = s.doc.body.clone();
let new: Vec<Arc<Block>> = if revised.parts.values().any(|p| p.kind == wordcraft_doc::PartKind::TextBox) {
let mut frag = revised.body_fragment();
for b in &mut frag.blocks {
remap_block_media(b, &mut |k| adopt_media_key(&mut s.doc, &mut raw_media, &mut media_map, k));
}
for part in frag.parts.values_mut() {
for b in &mut part.blocks {
remap_block_media(Arc::make_mut(b), &mut |k| adopt_media_key(&mut s.doc, &mut raw_media, &mut media_map, k));
}
}
// The revised document's text boxes get stories of their own in the result, so its
// boxes never show a story of the original's (or none at all).
s.doc.adopt_fragment(&frag).into_iter().map(Arc::new).collect()
s.doc.adopt_fragment(&revised.body_fragment()).into_iter().map(Arc::new).collect()
} else {
for b in &mut revised.body {
remap_block_media(Arc::make_mut(b), &mut |k| adopt_media_key(&mut s.doc, &mut raw_media, &mut media_map, k));
}
revised.body
revised.body.clone()
};
s.doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Insert, author: author.clone(), date: date.clone(), move_name: None });
let ins = (s.doc.revisions.len() - 1) as u32;
s.doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Delete, author: author.clone(), date: date.clone(), move_name: None });
let del = (s.doc.revisions.len() - 1) as u32;
let key = |b: &Arc<Block>| match &**b {
Block::Para(p) => opts.key(&p.plain_text()),
// Tables match as a whole, by their text.
Block::Table(_) => format!("\u{0}table\u{0}{}", opts.key(&block_text(b, 0))),
};
let mut budget = MAX_COMPARE_CELLS;
let mut char_fallbacks = 0usize;
let mut table_fallbacks = 0usize;
let (out, changes) = {
let mut ctx = DiffCtx {
ins,
del,
opts: &opts,
author: &author,
date: &date,
budget: &mut budget,
char_fallbacks: &mut char_fallbacks,
table_fallbacks: &mut table_fallbacks,
changes: 0,
plain_revised,
};
let out = diff_blocks(&mut s.doc, &old, &new, &mut ctx, 0);
(out, ctx.changes)
};
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, plain_revised };
let mut out: Vec<Arc<Block>> = Vec::new();
let (mut i, mut j) = (0usize, 0usize);
let mut changes = 0usize;
let mut k = 0;
while k < ops.len() {
match ops.get(k) {
Some(Op::Same) => {
let (a, b) = (old.get(i), new.get(j));
// The revised block, with its formatting changes tracked.
if let (Some(Block::Para(pa)), Some(Block::Para(pb))) = (a.map(|x| &**x), b.map(|x| &**x)) {
if !same_objects(&s.doc, pa, pb) {
// Same text, but objects (text boxes, pictures…) differ: diffed, so the
// original's objects aren't lost.
out.push(para_block(word_diff(&s.doc, pa, pb, &mut ctx)));
changes += 1;
i += 1;
j += 1;
k += 1;
continue;
}
let mut p = pb.clone();
if opts.formatting && pa.text == pb.text {
let before = s.doc.revisions.len();
crate::cmd::fmt_revisions::compare_formatting(pa, &mut p, &mut s.doc.revisions, &author, &date);
if s.doc.revisions.len() > before || p != *pb {
changes += 1;
}
}
out.push(para_block(p));
} else if let Some(x) = b.or(a) {
out.push(x.clone());
}
i += 1;
j += 1;
k += 1;
}
Some(_) => {
// A run of deletions and insertions: changed paragraphs pair up and are diffed
// word by word (or by character); the rest are deleted or inserted whole.
let run = ops.get(k..).unwrap_or_default().iter().take_while(|o| **o != Op::Same).count();
let dels = ops.get(k..k + run).unwrap_or_default().iter().filter(|o| **o == Op::Del).count();
let inss = run - dels;
for x in 0..dels.max(inss) {
let (a, b) = (if x < dels { old.get(i + x) } else { None }, if x < inss { new.get(j + x) } else { None });
match (a.map(|x| &**x), b.map(|x| &**x)) {
(Some(Block::Para(pa)), Some(Block::Para(pb))) => out.push(para_block(word_diff(&s.doc, pa, pb, &mut ctx))),
_ => {
if let Some(x) = a {
out.push(Arc::new(mark_block(x, &|c| c.del = Some(del), 0)));
}
if let Some(x) = b {
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ins), 0)));
}
}
}
changes += 1;
}
i += dels;
j += inss;
k += run.max(1);
}
None => break,
}
}
s.doc.body = out;
s.doc.ensure_nonempty();
s.note_body_replaced();
@@ -159,14 +185,6 @@ pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
not_honoured.push("level");
}
}
if table_fallbacks > 0 {
log::warn!(
"compare: {table_fallbacks} table(s) with media changes could not be compared cell by cell due to incompatible layout or nesting depth"
);
if !not_honoured.contains(&"tables") {
not_honoured.push("tables");
}
}
s.sel = Selection::caret(s.doc.start_of(StoryRef::Body));
Ok(json!({
"changes": changes,
@@ -176,401 +194,37 @@ pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
}))
}
/// Compare two block slices (`old` vs `new`) at table nesting `depth`, emitting tracked changes.
fn diff_blocks(doc: &mut Document, old: &[Arc<Block>], new: &[Arc<Block>], ctx: &mut DiffCtx<'_>, depth: usize) -> Vec<Arc<Block>> {
let key = |b: &Arc<Block>| match &**b {
Block::Para(p) => ctx.opts.key(&p.plain_text()),
// Tables match as a whole, by their text.
Block::Table(_) => format!("\u{0}table\u{0}{}", ctx.opts.key(&block_text(b, depth))),
};
let ops = lcs_ops(&old.iter().map(key).collect::<Vec<_>>(), &new.iter().map(key).collect::<Vec<_>>(), ctx.budget);
let mut out: Vec<Arc<Block>> = Vec::new();
let (mut i, mut j, mut k) = (0usize, 0usize, 0usize);
while k < ops.len() {
match ops.get(k) {
Some(Op::Same) => {
let (a, b) = (old.get(i), new.get(j));
// The revised block, with its formatting and object changes tracked.
if let (Some(Block::Para(pa)), Some(Block::Para(pb))) = (a.map(|x| &**x), b.map(|x| &**x)) {
if !same_objects(doc, pa, pb) {
// Same text, but objects (text boxes, pictures…) differ: diffed, so the
// original's objects aren't lost.
out.push(para_block(word_diff(doc, pa, pb, ctx)));
ctx.changes = ctx.changes.saturating_add(1);
} else {
let mut p = pb.clone();
if ctx.opts.formatting && pa.text == pb.text {
let before = doc.revisions.len();
crate::cmd::fmt_revisions::compare_formatting(pa, &mut p, &mut doc.revisions, ctx.author, ctx.date);
if doc.revisions.len() > before || p != *pb {
ctx.changes = ctx.changes.saturating_add(1);
}
}
out.push(para_block(p));
}
} else if let (Some(Block::Table(ta)), Some(Block::Table(tb))) = (a.map(|x| &**x), b.map(|x| &**x)) {
diff_matched_table(doc, (a, ta), (b, tb), ctx, depth, &mut out);
} else if let Some(x) = b.or(a) {
out.push(x.clone());
}
i += 1;
j += 1;
k += 1;
}
Some(_) => {
// A run of deletions and insertions: changed paragraphs pair up and are diffed
// word by word (or by character); the rest are deleted or inserted whole.
let run = ops.get(k..).unwrap_or_default().iter().take_while(|o| **o != Op::Same).count();
let dels = ops.get(k..k + run).unwrap_or_default().iter().filter(|o| **o == Op::Del).count();
let inss = run - dels;
for x in 0..dels.max(inss) {
let (a, b) = (if x < dels { old.get(i + x) } else { None }, if x < inss { new.get(j + x) } else { None });
match (a.map(|x| &**x), b.map(|x| &**x)) {
(Some(Block::Para(pa)), Some(Block::Para(pb))) => out.push(para_block(word_diff(doc, pa, pb, ctx))),
_ => {
if let Some(x) = a {
out.push(Arc::new(mark_block(x, &|c| c.del = Some(ctx.del))));
}
if let Some(x) = b {
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ctx.ins))));
}
}
}
ctx.changes = ctx.changes.saturating_add(1);
}
i += dels;
j += inss;
k += run.max(1);
}
None => break,
}
}
out
}
/// Emit a matched (`Op::Same`) table pair into `out`. Layout-only or media-identical matches keep
/// the revised table as on `main`; tables with media differences are diffed cell by cell when
/// compatible and within [`wordcraft_doc::table::MAX_TABLE_DEPTH`], or otherwise preserve the
/// original table and its media and record a `"tables"` fallback in `notHonoured` without
/// emitting duplicate table shells.
fn diff_matched_table(
doc: &mut Document,
(a, ta): (Option<&Arc<Block>>, &wordcraft_doc::table::Table),
(b, tb): (Option<&Arc<Block>>, &wordcraft_doc::table::Table),
ctx: &mut DiffCtx<'_>,
depth: usize,
out: &mut Vec<Arc<Block>>,
) {
if ta == tb || table_media_keys(ta) == table_media_keys(tb) {
if let Some(x) = b.or(a) {
out.push(x.clone());
}
} else if depth < wordcraft_doc::table::MAX_TABLE_DEPTH && same_table_cells(ta, tb, ctx) {
out.push(Arc::new(Block::Table(diff_table(doc, ta, tb, ctx, depth))));
} else {
if let Some(x) = a.or(b) {
out.push(x.clone());
}
*ctx.table_fallbacks = ctx.table_fallbacks.saturating_add(1);
}
}
/// Whether two tables have compatible grid widths, content controls, row counts, cell counts,
/// spans and vertical merges so their properties and cells can be diffed 1-to-1 without losing
/// untrackable layout changes.
fn same_table_cells(a: &wordcraft_doc::table::Table, b: &wordcraft_doc::table::Table, ctx: &DiffCtx<'_>) -> bool {
let track_fmt = ctx.opts.formatting && !ctx.plain_revised;
(!track_fmt || a.grid == b.grid)
&& a.controls == b.controls
&& a.rows.len() == b.rows.len()
&& a.rows.iter().zip(&b.rows).all(|(ra, rb)| {
ra.controls == rb.controls
&& ra.props.grid_before == rb.props.grid_before
&& ra.props.grid_after == rb.props.grid_after
&& ra.cells.len() == rb.cells.len()
&& ra
.cells
.iter()
.zip(&rb.cells)
.all(|(ca, cb)| ca.controls == cb.controls && ca.span() == cb.span() && ca.props.vmerge == cb.props.vmerge)
})
}
/// Strip revision bookkeeping from table properties for formatting comparison.
fn strip_table_props(t: &wordcraft_doc::props::TableProps) -> wordcraft_doc::props::TableProps {
wordcraft_doc::props::TableProps { fmt_change: None, ..t.clone() }
}
/// Strip revision bookkeeping from row properties (and any nested row table-property exceptions).
fn strip_row_props(r: &wordcraft_doc::props::RowProps) -> wordcraft_doc::props::RowProps {
wordcraft_doc::props::RowProps { fmt_change: None, exceptions: r.exceptions.as_deref().map(|e| Box::new(strip_table_props(e))), ..r.clone() }
}
/// Strip revision bookkeeping and structural merge fields from cell properties.
fn strip_cell_props(c: &wordcraft_doc::props::CellProps) -> wordcraft_doc::props::CellProps {
wordcraft_doc::props::CellProps { fmt_change: None, span: 0, vmerge: wordcraft_doc::props::VMerge::None, ..c.clone() }
}
/// Build a formatting [`wordcraft_doc::props::PropChange`] when formatting tracking is active and
/// `old` differs from `new`.
fn fmt_prop_change<T: PartialEq>(doc: &mut Document, ctx: &DiffCtx<'_>, old: T, new: &T) -> Option<Box<wordcraft_doc::props::PropChange<T>>> {
if !ctx.opts.formatting || ctx.plain_revised || old == *new {
return None;
}
let fmt_rev = format_revision(doc, ctx.author, ctx.date);
wordcraft_doc::props::PropChange::boxed(fmt_rev, old)
}
/// Like [`fmt_prop_change`], also counting a container-level formatting change in `ctx.changes`.
fn record_prop_change<T: PartialEq>(doc: &mut Document, ctx: &mut DiffCtx<'_>, old: T, new: &T) -> Option<Box<wordcraft_doc::props::PropChange<T>>> {
let ch = fmt_prop_change(doc, ctx, old, new);
if ch.is_some() {
ctx.changes = ctx.changes.saturating_add(1);
}
ch
}
/// Record a cell-property change when formatting tracking is active or the cell's background
/// picture changed (`#6086`), so replaced cell media stays rejectable even with `formatting: false`.
fn record_cell_change(
doc: &mut Document,
ctx: &mut DiffCtx<'_>,
ca: &wordcraft_doc::props::CellProps,
cb: &wordcraft_doc::props::CellProps,
) -> Option<Box<wordcraft_doc::props::PropChange<wordcraft_doc::props::CellProps>>> {
let old = strip_cell_props(ca);
let new = strip_cell_props(cb);
if ctx.plain_revised || (!ctx.opts.formatting && ca.picture == cb.picture) || old == new {
return None;
}
let fmt_rev = format_revision(doc, ctx.author, ctx.date);
ctx.changes = ctx.changes.saturating_add(1);
wordcraft_doc::props::PropChange::boxed(fmt_rev, old)
}
/// Diff two compatible tables cell by cell, tracking table, row, and cell property differences
/// alongside cell content edits.
fn diff_table(
doc: &mut Document,
a: &wordcraft_doc::table::Table,
b: &wordcraft_doc::table::Table,
ctx: &mut DiffCtx<'_>,
depth: usize,
) -> wordcraft_doc::table::Table {
let mut t = b.clone();
t.props = strip_table_props(&t.props);
t.props.fmt_change = record_prop_change(doc, ctx, strip_table_props(&a.props), &t.props);
for (ra, rb) in a.rows.iter().zip(&mut t.rows) {
rb.props = strip_row_props(&rb.props);
rb.props.fmt_change = record_prop_change(doc, ctx, strip_row_props(&ra.props), &rb.props);
for (ca, cb) in ra.cells.iter().zip(&mut rb.cells) {
cb.props.fmt_change = None;
cb.props.fmt_change = record_cell_change(doc, ctx, &ca.props, &cb.props);
if ca.blocks != cb.blocks {
cb.blocks = diff_blocks(doc, &ca.blocks, &cb.blocks, ctx, depth + 1);
if cb.blocks.is_empty() {
cb.blocks.push(para_block(Paragraph::new()));
}
}
}
}
t
}
/// Find or create the formatting revision entry for `author` and `date`.
fn format_revision(doc: &mut Document, author: &str, date: &str) -> u32 {
if let Some(i) = doc.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == author && r.date == date) {
return u32::try_from(i).unwrap_or(u32::MAX);
}
doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Format, author: author.to_string(), date: date.to_string(), move_name: None });
u32::try_from(doc.revisions.len().saturating_sub(1)).unwrap_or(u32::MAX)
}
/// Adopt `old_key` from `raw_media` into `doc` on first use, reusing the existing buffer without
/// cloning when uniquely owned, and memoizing the resulting media key in `media_map`.
fn adopt_media_key(
doc: &mut Document,
raw_media: &mut BTreeMap<String, Arc<Vec<u8>>>,
media_map: &mut BTreeMap<String, String>,
old_key: &str,
) -> Option<String> {
if let Some(k) = media_map.get(old_key) {
return Some(k.clone());
}
let data = raw_media.remove(old_key)?;
let ext = old_key.rsplit_once('.').map(|(_, e)| e).unwrap_or("bin");
let new_key = doc.add_media(Arc::unwrap_or_clone(data), ext);
media_map.insert(old_key.to_string(), new_key.clone());
Some(new_key)
}
/// Rewrites media keys in an inline object and all nested group children via `map`, returning
/// whether any media key changed.
pub(super) fn remap_object_media(root: &mut InlineObject, map: &mut dyn FnMut(&str) -> Option<String>) -> bool {
let mut changed = false;
let mut todo = vec![root];
while let Some(o) = todo.pop() {
match o {
InlineObject::Image { media, .. } => {
if let Some(k) = map(media)
&& k != *media
{
*media = k;
changed = true;
}
}
InlineObject::Graphic { graphic, .. } => {
let mut any = false;
for i in &graphic.items {
if let wordcraft_doc::graphic::GraphicItem::Image { media, .. } = i
&& map(media).is_some_and(|k| k != *media)
{
any = true;
}
}
if any {
for i in &mut Arc::make_mut(graphic).items {
if let wordcraft_doc::graphic::GraphicItem::Image { media, .. } = i
&& let Some(k) = map(media.as_str())
{
*media = k;
}
}
changed = true;
}
}
InlineObject::Group { children, .. } => {
for c in children {
todo.push(&mut c.obj);
}
}
_ => {}
}
}
changed
}
/// Rewrites media keys in all paragraphs and table cells within `b` via `map`.
fn remap_block_media(b: &mut Block, map: &mut dyn FnMut(&str) -> Option<String>) {
let mut todo = vec![b];
while let Some(b) = todo.pop() {
match b {
Block::Para(p) => {
let mut changed = false;
for o in &mut p.objects {
changed |= remap_object_media(o, map);
}
if changed {
p.touch();
}
}
Block::Table(t) => {
for row in &mut t.rows {
for cell in &mut row.cells {
if let Some(pic) = &mut cell.props.picture
&& let Some(k) = map(&pic.media)
{
pic.media = k;
}
todo.extend(cell.blocks.iter_mut().map(Arc::make_mut));
}
}
}
}
}
}
/// Collects media keys referenced by `root` and any nested graphic/group children iteratively.
fn collect_object_media<'a>(root: &'a InlineObject, out: &mut Vec<&'a str>) {
let mut todo = vec![root];
while let Some(o) = todo.pop() {
match o {
InlineObject::Image { media, .. } => out.push(media.as_str()),
InlineObject::Graphic { graphic, .. } => {
for item in &graphic.items {
if let wordcraft_doc::graphic::GraphicItem::Image { media, .. } = item {
out.push(media.as_str());
}
}
}
InlineObject::Group { children, .. } => {
for child in children.iter().rev() {
todo.push(&child.obj);
}
}
_ => {}
}
}
}
/// Collects media keys referenced by `table` across all cell pictures, paragraphs, and nested
/// tables in document order without recursion.
fn table_media_keys(table: &wordcraft_doc::table::Table) -> Vec<&str> {
enum Item<'a> {
Table(&'a wordcraft_doc::table::Table),
Block(&'a Block),
}
let mut keys = Vec::new();
let mut todo = vec![Item::Table(table)];
while let Some(item) = todo.pop() {
match item {
Item::Table(t) => {
for row in t.rows.iter().rev() {
for cell in row.cells.iter().rev() {
for block in cell.blocks.iter().rev() {
todo.push(Item::Block(block));
}
if let Some(pic) = &cell.props.picture {
keys.push(pic.media.as_str());
}
}
}
}
Item::Block(Block::Para(p)) => {
for o in &p.objects {
collect_object_media(o, &mut keys);
}
}
Item::Block(Block::Table(nested)) => {
todo.push(Item::Table(nested));
}
}
}
keys
}
/// A block's text (a table's cells in order), for matching blocks.
fn block_text(b: &Block, depth: usize) -> String {
match b {
Block::Para(p) => p.plain_text(),
Block::Table(t) if depth < wordcraft_doc::table::MAX_TABLE_DEPTH => {
Block::Table(t) if depth < 16 => {
t.rows.iter().flat_map(|r| r.cells.iter()).flat_map(|c| c.blocks.iter()).map(|x| block_text(x, depth + 1)).collect::<Vec<_>>().join("\t")
}
Block::Table(_) => String::new(),
}
}
/// Returns a copy of `b` with all text runs and paragraph marks across all nested table cells
/// updated by `f` iteratively, without recursion or depth truncation.
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
let mut out = b.clone();
let mut todo = vec![&mut out];
while let Some(blk) = todo.pop() {
match blk {
Block::Para(p) => {
let len = p.len();
let _ = p.format(0, len, f);
f(&mut p.mark);
p.touch();
}
Block::Table(t) => {
/// Returns a copy of `b` with all text runs and paragraph marks (or nested table cells) updated by `f`.
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps), depth: usize) -> Block {
match b {
Block::Para(p) => {
let mut p = p.clone();
let len = p.len();
let _ = p.format(0, len, f);
f(&mut p.mark);
Block::Para(p)
}
Block::Table(t) => {
let mut t = t.clone();
if depth < 16 {
for c in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) {
todo.extend(c.blocks.iter_mut().map(Arc::make_mut));
c.blocks = c.blocks.iter().map(|x| Arc::new(mark_block(x, f, depth + 1))).collect();
}
}
Block::Table(t)
}
}
out
}
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -919,7 +573,7 @@ fn para_exceeds_char_limit(p: &Paragraph, limit: usize) -> bool {
/// to `ctx.opts.characters`. When character-level diff is requested but either paragraph exceeds
/// [`MAX_CHAR_DIFF`] characters, falls back to word-level diff and increments `ctx.char_fallbacks`
/// so callers can discover the fallback.
fn word_diff(doc: &mut Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx<'_>) -> Paragraph {
fn word_diff(doc: &Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx<'_>) -> Paragraph {
let chars = if ctx.opts.characters {
if para_exceeds_char_limit(a, MAX_CHAR_DIFF) || para_exceeds_char_limit(b, MAX_CHAR_DIFF) {
*ctx.char_fallbacks = ctx.char_fallbacks.saturating_add(1);
@@ -933,14 +587,11 @@ fn word_diff(doc: &mut Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx
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 (ka, kb): (Vec<_>, Vec<_>) = {
let key = |t: &Tok<'_>| match t {
Tok::Text(t, _) => Key::Text(ctx.opts.key(t)),
Tok::Obj(o, _) => obj_key(doc, o),
};
(ta.iter().map(&key).collect(), tb.iter().map(&key).collect())
let key = |t: &Tok<'_>| match t {
Tok::Text(t, _) => Key::Text(ctx.opts.key(t)),
Tok::Obj(o, _) => obj_key(doc, o),
};
let ops = lcs_ops(&ka, &kb, ctx.budget);
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,
// but a matched single character very often does (digits, punctuation), so only there does
// a short interior match need folding back into its surrounding edit.
@@ -952,7 +603,6 @@ fn word_diff(doc: &mut Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx
// 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() };
p.props.fmt_change = fmt_prop_change(doc, ctx, a.props.formatting(), &p.props);
// 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`)
@@ -962,7 +612,6 @@ fn word_diff(doc: &mut Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx
} else {
CharProps { ins: None, del: None, fmt_change: None, ..b.mark.clone() }
};
p.mark.fmt_change = fmt_prop_change(doc, ctx, a.mark.formatting(), &p.mark.formatting());
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);
@@ -972,18 +621,10 @@ fn word_diff(doc: &mut Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx
// 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"), recording a formatting revision when
// `ctx.opts.formatting` is enabled so Reject All restores the original formatting;
// a plain-text revised side has no runs to speak of, so the original run's
// formatting is kept instead.
let old_props = output_props(&mut a_props, ta.get(i), &fallback);
let props = if plain_revised {
old_props
} else {
let mut p_b = output_props(&mut b_props, tb.get(j), &fallback_b);
p_b.fmt_change = fmt_prop_change(doc, ctx, old_props.formatting(), &p_b.formatting());
p_b
};
// 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;
-786
View File
@@ -558,792 +558,6 @@ fn compare_keeps_text_boxes_of_the_original() {
}
}
struct TempTestDir(std::path::PathBuf);
impl TempTestDir {
fn new(prefix: &str) -> Self {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("{prefix}-{}-{id}", std::process::id()));
std::fs::create_dir_all(&dir).expect("create temp test dir");
Self(dir)
}
fn path(&self, name: &str) -> std::path::PathBuf {
self.0.join(name)
}
}
impl Drop for TempTestDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// #6086: When base and revised have an embedded image at identical size and extents,
/// but the media bytes were replaced, Compare must emit a tracked deletion of the base
/// image and tracked insertion of the revised image, and keep both media parts in the
/// result package.
#[test]
fn compare_detects_replaced_image_bytes_with_unchanged_extents() {
let tmp = TempTestDir::new("wc-compare-img-replace");
let make_doc = |bytes: Vec<u8>| -> Document {
let mut d = Document::new();
let key = d.add_media(bytes, "png");
let mut p = Paragraph::new();
let img = InlineObject::Image {
media: key,
w: 120.0,
h: 80.0,
alt: "photo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
};
p.insert_object(0, img, &CharProps::default()).unwrap();
d.body = vec![Arc::new(Block::Para(p))];
d
};
let base_png = vec![0x89, b'P', b'N', b'G', 1, 1, 1, 1];
let rev_png = vec![0x89, b'P', b'N', b'G', 2, 2, 2, 2];
let base_doc = make_doc(base_png.clone());
let rev_doc = make_doc(rev_png.clone());
let path = tmp.path("revised.docx");
crate::io::save_path(&path, &rev_doc).unwrap();
let mut s = Session::new(base_doc);
let r = s.run("review.compare", &json!({"path": path.to_string_lossy(), "showIn": "new"})).unwrap();
assert!(r["changes"].as_u64().unwrap() >= 1, "an image byte change must be detected as a change");
let p = s.doc.body[0].as_para().expect("body has paragraph");
assert_eq!(p.objects.len(), 2, "paragraph must have both deleted and inserted images");
let objs: Vec<(usize, &InlineObject)> = p.objects_with_offsets().collect();
assert_eq!(objs.len(), 2, "paragraph must have two objects with offsets");
let (off_del, del_img) = objs[0];
let (off_ins, ins_img) = objs[1];
let (InlineObject::Image { media: m_del, .. }, InlineObject::Image { media: m_ins, .. }) = (del_img, ins_img) else {
panic!("both objects must be images");
};
assert_ne!(m_del, m_ins, "deleted and inserted images must have distinct media keys");
assert!(p.props_of_char(off_del).del.is_some(), "base image must have del revision mark");
assert!(p.props_of_char(off_ins).ins.is_some(), "revised image must have ins revision mark");
assert_eq!(s.doc.media.get(m_del).map(|b| &**b), Some(&base_png));
assert_eq!(s.doc.media.get(m_ins).map(|b| &**b), Some(&rev_png));
// And saving to DOCX and reading back preserves both media files in the package.
let out_path = tmp.path("out.docx");
crate::io::save_path(&out_path, &s.doc).unwrap();
let back = crate::io::open_path(&out_path).unwrap();
assert!(back.media.values().any(|b| **b == base_png), "result package must contain base image bytes");
assert!(back.media.values().any(|b| **b == rev_png), "result package must contain revised image bytes");
// Identical image bytes at identical size: no changes emitted.
let base_doc_same = make_doc(base_png.clone());
let same_path = tmp.path("same.docx");
crate::io::save_path(&same_path, &make_doc(base_png.clone())).unwrap();
let mut s_same = Session::new(base_doc_same);
let r_same = s_same.run("review.compare", &json!({"path": same_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_same["changes"], 0, "comparing identical image bytes must emit no changes");
// Extensionless media in revised document adopts with .bin extension fallback and preserves payload.
let extless_bytes = vec![0xFF, 0xD8, 0xFF, 0xE0, 1, 2, 3, 4];
let mut rev_doc_extless = Document::new();
rev_doc_extless.media.insert("rawimage".into(), Arc::new(extless_bytes.clone()));
let mut p_extless = Paragraph::new();
p_extless
.insert_object(
0,
InlineObject::Image {
media: "rawimage".into(),
w: 120.0,
h: 80.0,
alt: "photo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
rev_doc_extless.body = vec![Arc::new(Block::Para(p_extless))];
let extless_path = tmp.path("extless.json");
crate::io::save_path(&extless_path, &rev_doc_extless).unwrap();
let mut s_extless = Session::new(make_doc(base_png));
let _ = s_extless.run("review.compare", &json!({"path": extless_path.to_string_lossy(), "showIn": "new"})).unwrap();
let bin_entry = s_extless.doc.media.iter().find(|(k, _)| k.ends_with(".bin"));
assert!(bin_entry.is_some(), "extensionless media falls back to bin extension");
assert_eq!(bin_entry.map(|(_, b)| &***b), Some(&extless_bytes[..]));
// Media inside deeply nested groups is remapped iteratively without recursion limits.
let mut deep_obj = InlineObject::Image {
media: "deep_img.png".into(),
w: 50.0,
h: 50.0,
alt: "".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
};
for _ in 0..20 {
deep_obj = InlineObject::Group {
w: 50.0,
h: 50.0,
float: Default::default(),
ch_w: 50.0,
ch_h: 50.0,
children: vec![wordcraft_doc::para::GroupChild { x: 0.0, y: 0.0, obj: deep_obj }],
canvas: None,
};
}
let mut map: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
map.insert("deep_img.png".into(), "image99.png".into());
super::compare::remap_object_media(&mut deep_obj, &mut |k| map.get(k).cloned());
let mut cur = &deep_obj;
while let InlineObject::Group { children, .. } = cur {
cur = &children[0].obj;
}
if let InlineObject::Image { media, .. } = cur {
assert_eq!(media, "image99.png", "media inside 20-level group must be remapped");
} else {
panic!("innermost object must be Image");
}
}
/// #6086: When an image replacement in a same-text paragraph triggers `word_diff`, matched text,
/// paragraph mark, and paragraph formatting changes must also record `fmt_change` revisions when
/// `formatting` is enabled so Reject All restores both the original formatting and the original
/// image, while Accept All keeps the revised formatting and revised image.
#[test]
fn compare_replaced_image_in_paragraph_tracks_matched_formatting_for_reject() {
let tmp = TempTestDir::new("wc-compare-img-para-fmt");
let base_png = vec![0x89, b'P', b'N', b'G', 7, 7, 7, 7];
let rev_png = vec![0x89, b'P', b'N', b'G', 8, 8, 8, 8];
let make_para_doc = |bytes: Vec<u8>, bold: Option<bool>, align: Option<wordcraft_doc::props::Align>, mark_italic: Option<bool>| -> Document {
let mut d = Document::new();
let key = d.add_media(bytes, "png");
let mut p = Paragraph::with_text("Logo", CharProps { bold, ..Default::default() });
p.props.align = align;
p.mark = CharProps { italic: mark_italic, ..Default::default() };
let at = p.len();
p.insert_object(
at,
InlineObject::Image {
media: key,
w: 120.0,
h: 80.0,
alt: "logo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
d.body = vec![Arc::new(Block::Para(p))];
d
};
let base_doc = make_para_doc(base_png.clone(), None, None, None);
let rev_doc = make_para_doc(rev_png.clone(), Some(true), Some(wordcraft_doc::props::Align::Center), Some(true));
let rev_path = tmp.path("rev.docx");
crate::io::save_path(&rev_path, &rev_doc).unwrap();
let mut s = Session::new(base_doc.clone());
let r = s.run("review.compare", &json!({"path": rev_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r["changes"], 1);
let p = s.doc.body[0].as_para().expect("compared paragraph");
assert_eq!(p.props_of_char(0).bold, Some(true), "matched text carries revised bold");
assert!(p.props_of_char(0).fmt_change.is_some(), "matched text carries formatting revision");
assert_eq!(p.props.align, Some(wordcraft_doc::props::Align::Center));
assert!(p.props.fmt_change.is_some(), "paragraph properties carry formatting revision");
assert_eq!(p.mark.italic, Some(true));
assert!(p.mark.fmt_change.is_some(), "paragraph mark carries formatting revision");
let objs: Vec<(usize, &InlineObject)> = p.objects_with_offsets().collect();
assert_eq!(objs.len(), 2);
assert!(p.props_of_char(objs[0].0).del.is_some());
assert!(p.props_of_char(objs[1].0).ins.is_some());
// Round-trip through DOCX before resolving both ways.
let cmp_path = tmp.path("compared.docx");
crate::io::save_path(&cmp_path, &s.doc).unwrap();
let reopened = crate::io::open_path(&cmp_path).unwrap();
let mut accepted = Session::new(reopened.clone());
accepted.run("review.acceptAll", &json!({})).unwrap();
let p_acc = accepted.doc.body[0].as_para().unwrap();
assert_eq!(p_acc.props_of_char(0).bold, Some(true));
assert!(p_acc.props_of_char(0).fmt_change.is_none());
assert_eq!(p_acc.props.align, Some(wordcraft_doc::props::Align::Center));
assert_eq!(p_acc.mark.italic, Some(true));
let objs_acc: Vec<(usize, &InlineObject)> = p_acc.objects_with_offsets().collect();
assert_eq!(objs_acc.len(), 1);
let InlineObject::Image { media: m_acc, .. } = objs_acc[0].1 else { panic!("expected image") };
assert_eq!(accepted.doc.media.get(m_acc).map(|b| &**b), Some(&rev_png));
let mut rejected = Session::new(reopened);
rejected.run("review.rejectAll", &json!({})).unwrap();
let p_rej = rejected.doc.body[0].as_para().unwrap();
assert_ne!(p_rej.props_of_char(0).bold, Some(true), "Reject All must restore original non-bold text");
assert!(p_rej.props_of_char(0).fmt_change.is_none());
assert_eq!(p_rej.props.align, None, "Reject All must restore original paragraph alignment");
assert_ne!(p_rej.mark.italic, Some(true), "Reject All must restore original paragraph mark");
let objs_rej: Vec<(usize, &InlineObject)> = p_rej.objects_with_offsets().collect();
assert_eq!(objs_rej.len(), 1);
let InlineObject::Image { media: m_rej, .. } = objs_rej[0].1 else { panic!("expected image") };
assert_eq!(rejected.doc.media.get(m_rej).map(|b| &**b), Some(&base_png), "Reject All must restore original image");
// With formatting disabled, image del/ins marks remain while formatting revisions are omitted.
let mut s_no_fmt = Session::new(base_doc);
let r_no_fmt = s_no_fmt.run("review.compare", &json!({"path": rev_path.to_string_lossy(), "showIn": "new", "formatting": false})).unwrap();
assert_eq!(r_no_fmt["changes"], 1);
let p_nf = s_no_fmt.doc.body[0].as_para().unwrap();
assert!(p_nf.props_of_char(0).fmt_change.is_none());
assert!(p_nf.props.fmt_change.is_none());
assert!(p_nf.mark.fmt_change.is_none());
let objs_nf: Vec<(usize, &InlineObject)> = p_nf.objects_with_offsets().collect();
assert_eq!(objs_nf.len(), 2);
assert!(p_nf.props_of_char(objs_nf[0].0).del.is_some());
assert!(p_nf.props_of_char(objs_nf[1].0).ins.is_some());
}
/// #6086: Replaced image bytes inside a table whose text is unchanged must be tracked in the
/// cell paragraph (not silently applied unmarked), survive DOCX save/reopen, and resolve to the
/// revised or original image under Accept All and Reject All.
#[test]
fn compare_detects_replaced_image_bytes_inside_unchanged_text_table() {
let tmp = TempTestDir::new("wc-compare-tbl-img-replace");
let make_table_doc = |bytes: Vec<u8>| -> Document {
let mut d = Document::new();
let key = d.add_media(bytes, "png");
let mut p = Paragraph::with_text("Logo", CharProps::default());
let at = p.len();
p.insert_object(
at,
InlineObject::Image {
media: key,
w: 120.0,
h: 80.0,
alt: "logo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
let mut t = wordcraft_doc::table::Table::new(1, 1, 200.0);
t.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(p))];
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::new()))];
d
};
fn cell_para(doc: &Document) -> &Paragraph {
let t = doc.body[0].as_table().expect("body holds 1x1 table");
assert_eq!(doc.body.iter().filter(|b| b.as_table().is_some()).count(), 1, "body keeps one table");
assert_eq!(t.rows.len(), 1);
assert_eq!(t.rows[0].cells.len(), 1);
t.rows[0].cells[0].blocks[0].as_para().expect("cell holds paragraph")
}
let base_png = vec![0x89, b'P', b'N', b'G', 10, 20, 30, 40];
let rev_png = vec![0x89, b'P', b'N', b'G', 50, 60, 70, 80];
let orphan_hdr_png = vec![0x89, b'P', b'N', b'G', 99, 98, 97, 96];
let base_doc = make_table_doc(base_png.clone());
let mut rev_doc = make_table_doc(rev_png.clone());
// Attach an uncompared header part referencing media that nothing in the body uses.
let hdr_key = rev_doc.add_media(orphan_hdr_png.clone(), "png");
let mut hdr_para = Paragraph::new();
hdr_para
.insert_object(
0,
InlineObject::Image {
media: hdr_key,
w: 40.0,
h: 40.0,
alt: "hdr".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
let hdr_part = rev_doc.add_part(wordcraft_doc::PartKind::Header, vec![Arc::new(Block::Para(hdr_para))]);
rev_doc.last_section.headers.default = Some(hdr_part);
let rev_path = tmp.path("tbl-rev.docx");
crate::io::save_path(&rev_path, &rev_doc).unwrap();
let mut s = Session::new(base_doc);
let r = s.run("review.compare", &json!({"path": rev_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r["changes"], 1, "replaced image inside unchanged-text table must count as 1 change");
assert!(
!s.doc.media.values().any(|b| **b == orphan_hdr_png),
"unreferenced media from uncompared revised header parts must not stay in result media"
);
let check_tracked_cell = |doc: &Document| {
let p = cell_para(doc);
assert_eq!(p.plain_text(), "Logo");
let objs: Vec<(usize, &InlineObject)> = p.objects_with_offsets().collect();
assert_eq!(objs.len(), 2, "table cell must hold deleted base image and inserted revised image");
let (off_del, InlineObject::Image { media: m_del, .. }) = objs[0] else { panic!("expected base image") };
let (off_ins, InlineObject::Image { media: m_ins, .. }) = objs[1] else { panic!("expected revised image") };
assert_ne!(m_del, m_ins);
assert!(p.props_of_char(0).del.is_none() && p.props_of_char(0).ins.is_none(), "`Logo` text stays unmarked");
assert!(p.props_of_char(off_del).del.is_some(), "base table image must carry del mark");
assert!(p.props_of_char(off_ins).ins.is_some(), "revised table image must carry ins mark");
assert_eq!(doc.media.get(m_del).map(|b| &**b), Some(&base_png));
assert_eq!(doc.media.get(m_ins).map(|b| &**b), Some(&rev_png));
};
check_tracked_cell(&s.doc);
// Save compared result to DOCX and reopen: change marks and both payloads survive.
let cmp_path = tmp.path("tbl-cmp.docx");
crate::io::save_path(&cmp_path, &s.doc).unwrap();
let reopened = crate::io::open_path(&cmp_path).unwrap();
check_tracked_cell(&reopened);
// Accept All on reopened DOCX -> saves and reopens with only the revised image unmarked.
let mut accepted = Session::new(reopened.clone());
accepted.run("review.acceptAll", &json!({})).unwrap();
let acc_path = tmp.path("tbl-acc.docx");
crate::io::save_path(&acc_path, &accepted.doc).unwrap();
let acc_back = crate::io::open_path(&acc_path).unwrap();
let p_acc = cell_para(&acc_back);
assert_eq!(p_acc.plain_text(), "Logo");
let objs_acc: Vec<(usize, &InlineObject)> = p_acc.objects_with_offsets().collect();
assert_eq!(objs_acc.len(), 1, "Accept All must leave one image in the table cell");
let (off_acc, InlineObject::Image { media: m_acc, .. }) = objs_acc[0] else { panic!("expected image") };
assert!(p_acc.props_of_char(off_acc).ins.is_none() && p_acc.props_of_char(off_acc).del.is_none());
assert_eq!(acc_back.media.get(m_acc).map(|b| &**b), Some(&rev_png), "Accept All must keep revised image bytes");
// Reject All on reopened DOCX -> saves and reopens with only the original image unmarked.
let mut rejected = Session::new(reopened);
rejected.run("review.rejectAll", &json!({})).unwrap();
let rej_path = tmp.path("tbl-rej.docx");
crate::io::save_path(&rej_path, &rejected.doc).unwrap();
let rej_back = crate::io::open_path(&rej_path).unwrap();
let p_rej = cell_para(&rej_back);
assert_eq!(p_rej.plain_text(), "Logo");
let objs_rej: Vec<(usize, &InlineObject)> = p_rej.objects_with_offsets().collect();
assert_eq!(objs_rej.len(), 1, "Reject All must restore one image in the table cell");
let (off_rej, InlineObject::Image { media: m_rej, .. }) = objs_rej[0] else { panic!("expected image") };
assert!(p_rej.props_of_char(off_rej).ins.is_none() && p_rej.props_of_char(off_rej).del.is_none());
assert_eq!(rej_back.media.get(m_rej).map(|b| &**b), Some(&base_png), "Reject All must recover base image bytes");
// Identical image bytes inside an unchanged-text table: 0 changes and 1 unmarked image.
let same_tbl_path = tmp.path("tbl-same.docx");
crate::io::save_path(&same_tbl_path, &make_table_doc(base_png.clone())).unwrap();
let mut s_same = Session::new(make_table_doc(base_png));
let r_same = s_same.run("review.compare", &json!({"path": same_tbl_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_same["changes"], 0, "identical table image bytes must emit 0 changes");
assert_eq!(cell_para(&s_same.doc).objects.len(), 1);
}
/// #6086: Same-text tables up to `MAX_TABLE_DEPTH` recurse cell by cell for replaced media;
/// layout-only matches keep a single table as on `main`, while incompatible layouts or nesting
/// beyond `MAX_TABLE_DEPTH` with replaced media defer structural table changes and report `"tables"`
/// in `notHonoured` without leaving duplicate table shells.
#[test]
fn compare_table_image_replacement_handles_layout_fallbacks_and_max_depth() {
let tmp = TempTestDir::new("wc-compare-tbl-depth");
let base_png = vec![0x89, b'P', b'N', b'G', 10, 20, 30, 40];
let rev_png = vec![0x89, b'P', b'N', b'G', 50, 60, 70, 80];
let assert_single_table = |doc: &Document, want_rows: usize, want_cols: usize, label: &str| {
let tables: Vec<&wordcraft_doc::table::Table> = doc.body.iter().filter_map(|b| b.as_table()).collect();
assert_eq!(tables.len(), 1, "{label}: must keep a single table");
assert_eq!(tables[0].rows.len(), want_rows, "{label}: row count");
assert_eq!(tables[0].rows[0].cells.len(), want_cols, "{label}: col count");
};
// Reshaped tables (1x2 vs 2x1) with identical joined cell text and replaced image bytes:
// cannot diff 1-to-1 by cell, so structural table replacement is deferred with a single table
// and `"tables"` is reported in `notHonoured`.
let mut base_1x2 = Document::new();
let k1 = base_1x2.add_media(base_png.clone(), "png");
let mut p_c0 = Paragraph::with_text("Logo", CharProps::default());
let at_c0 = p_c0.len();
p_c0.insert_object(
at_c0,
InlineObject::Image {
media: k1,
w: 120.0,
h: 80.0,
alt: "logo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
let mut t_1x2 = wordcraft_doc::table::Table::new(1, 2, 200.0);
t_1x2.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(p_c0))];
t_1x2.rows[0].cells[1].blocks = vec![Arc::new(Block::Para(Paragraph::with_text("Caption", CharProps::default())))];
base_1x2.body = vec![Arc::new(Block::Table(t_1x2)), Arc::new(Block::Para(Paragraph::new()))];
let mut rev_2x1 = Document::new();
let k2 = rev_2x1.add_media(rev_png.clone(), "png");
let mut p_r0 = Paragraph::with_text("Logo", CharProps::default());
let at_r0 = p_r0.len();
p_r0.insert_object(
at_r0,
InlineObject::Image {
media: k2,
w: 120.0,
h: 80.0,
alt: "logo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
let mut t_2x1 = wordcraft_doc::table::Table::new(2, 1, 200.0);
t_2x1.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(p_r0))];
t_2x1.rows[1].cells[0].blocks = vec![Arc::new(Block::Para(Paragraph::with_text("Caption", CharProps::default())))];
rev_2x1.body = vec![Arc::new(Block::Table(t_2x1)), Arc::new(Block::Para(Paragraph::new()))];
let reshaped_path = tmp.path("tbl-reshaped.docx");
crate::io::save_path(&reshaped_path, &rev_2x1).unwrap();
let mut s_reshaped = Session::new(base_1x2);
let r_reshaped = s_reshaped.run("review.compare", &json!({"path": reshaped_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_reshaped["changes"], 0);
assert!(
r_reshaped["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"),
"incompatible reshaped table with replaced media must report `tables` in notHonoured"
);
let assert_table_image = |doc: &Document, expected: &[u8], label: &str| {
let t = doc.body.iter().find_map(|b| b.as_table()).expect("table");
let p = t.rows[0].cells[0].blocks[0].as_para().expect("cell para");
let objs: Vec<(usize, &InlineObject)> = p.objects_with_offsets().collect();
assert_eq!(objs.len(), 1, "{label}: expected single image");
let InlineObject::Image { media, .. } = objs[0].1 else { panic!("{label}: expected image") };
assert_eq!(doc.media.get(media).map(|b| b.as_slice()), Some(expected), "{label}: image payload");
};
assert_single_table(&s_reshaped.doc, 1, 2, "reshaped table compare");
assert_table_image(&s_reshaped.doc, &base_png, "reshaped table compare");
for cmd in ["review.acceptAll", "review.rejectAll"] {
let mut s_res = Session::new(s_reshaped.doc.clone());
s_res.run(cmd, &json!({})).unwrap();
assert_single_table(&s_res.doc, 1, 2, cmd);
assert_table_image(&s_res.doc, &base_png, cmd);
}
// Equal cell count but changed spans ([1, 2] vs [2, 1]):
// - with identical image (layout-only match): keeps single table with 0 changes and no fallback flag;
// - with replaced image: defers structural replacement and reports `tables` in notHonoured.
let make_span_doc = |spans: [u32; 2], bytes: Vec<u8>| -> Document {
let mut d = Document::new();
let k = d.add_media(bytes, "png");
let mut p = Paragraph::with_text("Logo", CharProps::default());
let at = p.len();
p.insert_object(
at,
InlineObject::Image {
media: k,
w: 120.0,
h: 80.0,
alt: "logo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
let mut t = wordcraft_doc::table::Table::new(1, 3, 300.0);
t.rows[0].cells.truncate(2);
t.rows[0].cells[0].props.span = spans[0];
t.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(p))];
t.rows[0].cells[1].props.span = spans[1];
t.rows[0].cells[1].blocks = vec![Arc::new(Block::Para(Paragraph::with_text("Caption", CharProps::default())))];
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::new()))];
d
};
let span_same_path = tmp.path("tbl-span-same.docx");
crate::io::save_path(&span_same_path, &make_span_doc([2, 1], base_png.clone())).unwrap();
let mut s_span_same = Session::new(make_span_doc([1, 2], base_png.clone()));
let r_span_same = s_span_same.run("review.compare", &json!({"path": span_same_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_span_same["changes"], 0, "layout-only span match keeps old single-table behavior");
assert!(!r_span_same["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"));
assert_single_table(&s_span_same.doc, 1, 2, "layout-only span match");
let span_diff_path = tmp.path("tbl-span-diff.docx");
crate::io::save_path(&span_diff_path, &make_span_doc([2, 1], rev_png.clone())).unwrap();
let mut s_span_diff = Session::new(make_span_doc([1, 2], base_png.clone()));
let r_span_diff = s_span_diff.run("review.compare", &json!({"path": span_diff_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_span_diff["changes"], 0);
assert!(r_span_diff["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"));
assert_single_table(&s_span_diff.doc, 1, 2, "incompatible span with replaced media");
assert_table_image(&s_span_diff.doc, &base_png, "incompatible span with replaced media");
let t_span = s_span_diff.doc.body[0].as_table().unwrap();
assert_eq!([t_span.rows[0].cells[0].span(), t_span.rows[0].cells[1].span()], [1, 2]);
// Nested tables up to MAX_TABLE_DEPTH (18 levels, leaf at depth 17) recursively retain one
// table per nesting level and track replaced image bytes at the leaf.
let make_nested_table_doc = |levels: usize, bytes: Vec<u8>| -> Document {
let mut d = Document::new();
let k = d.add_media(bytes, "png");
let mut p = Paragraph::with_text("Deep", CharProps::default());
let at = p.len();
p.insert_object(
at,
InlineObject::Image {
media: k,
w: 50.0,
h: 50.0,
alt: "deep".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
let mut blk = Block::Para(p);
for _ in 0..levels {
let mut t = wordcraft_doc::table::Table::new(1, 1, 200.0);
// Every OOXML table cell containing a nested table ends with a trailing paragraph.
t.rows[0].cells[0].blocks = vec![Arc::new(blk), Arc::new(Block::Para(Paragraph::new()))];
blk = Block::Table(t);
}
d.body = vec![Arc::new(blk), Arc::new(Block::Para(Paragraph::new()))];
d
};
let deep_path = tmp.path("tbl-deep.docx");
crate::io::save_path(&deep_path, &make_nested_table_doc(wordcraft_doc::table::MAX_TABLE_DEPTH, rev_png.clone())).unwrap();
let mut s_deep = Session::new(make_nested_table_doc(wordcraft_doc::table::MAX_TABLE_DEPTH, base_png.clone()));
let r_deep = s_deep.run("review.compare", &json!({"path": deep_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_deep["changes"], 1, "replaced image at MAX_TABLE_DEPTH must still be tracked");
assert!(!r_deep["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"));
let mut cur_blocks = &s_deep.doc.body;
for level in 0..wordcraft_doc::table::MAX_TABLE_DEPTH {
let lvl_tables: Vec<&wordcraft_doc::table::Table> = cur_blocks.iter().filter_map(|b| b.as_table()).collect();
assert_eq!(lvl_tables.len(), 1, "level {level} must retain one recursively diffed table");
cur_blocks = &lvl_tables[0].rows[0].cells[0].blocks;
}
let leaf_p = cur_blocks[0].as_para().expect("innermost cell holds leaf paragraph");
assert_eq!(leaf_p.plain_text(), "Deep");
let leaf_objs: Vec<(usize, &InlineObject)> = leaf_p.objects_with_offsets().collect();
assert_eq!(leaf_objs.len(), 2, "leaf at MAX_TABLE_DEPTH holds both deleted and inserted images");
let (off_d, InlineObject::Image { media: md, .. }) = leaf_objs[0] else { panic!("expected base leaf image") };
let (off_i, InlineObject::Image { media: mi, .. }) = leaf_objs[1] else { panic!("expected revised leaf image") };
assert!(leaf_p.props_of_char(off_d).del.is_some() && leaf_p.props_of_char(off_d).ins.is_none());
assert!(leaf_p.props_of_char(off_i).ins.is_some() && leaf_p.props_of_char(off_i).del.is_none());
assert_eq!(s_deep.doc.media.get(md).map(|b| &**b), Some(&base_png));
assert_eq!(s_deep.doc.media.get(mi).map(|b| &**b), Some(&rev_png));
// Beyond MAX_TABLE_DEPTH (19 nested tables, reaching depth == MAX_TABLE_DEPTH): defers structural
// replacement (single table, no duplicate empty shell) and reports `tables` in notHonoured.
let over_depth_path = tmp.path("tbl-over-depth.docx");
crate::io::save_path(&over_depth_path, &make_nested_table_doc(wordcraft_doc::table::MAX_TABLE_DEPTH + 1, rev_png.clone())).unwrap();
let mut s_over = Session::new(make_nested_table_doc(wordcraft_doc::table::MAX_TABLE_DEPTH + 1, base_png.clone()));
let r_over = s_over.run("review.compare", &json!({"path": over_depth_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_over["changes"], 0);
assert!(
r_over["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"),
"tables beyond MAX_TABLE_DEPTH with replaced media must report `tables` in notHonoured"
);
let mut over_blocks = &s_over.doc.body;
for _ in 0..wordcraft_doc::table::MAX_TABLE_DEPTH {
let lvl_tables: Vec<&wordcraft_doc::table::Table> = over_blocks.iter().filter_map(|b| b.as_table()).collect();
assert_eq!(lvl_tables.len(), 1);
over_blocks = &lvl_tables[0].rows[0].cells[0].blocks;
}
let cap_tables: Vec<&wordcraft_doc::table::Table> = over_blocks.iter().filter_map(|b| b.as_table()).collect();
assert_eq!(cap_tables.len(), 1, "at depth == MAX_TABLE_DEPTH, keeps single table without duplicate shell");
let over_leaf_p = cap_tables[0].rows[0].cells[0].blocks[0].as_para().expect("over-depth leaf para");
let over_leaf_objs: Vec<(usize, &InlineObject)> = over_leaf_p.objects_with_offsets().collect();
assert_eq!(over_leaf_objs.len(), 1, "over-depth table preserves single original image");
let InlineObject::Image { media: m_over, .. } = over_leaf_objs[0].1 else { panic!("expected over-depth image") };
assert_eq!(s_over.doc.media.get(m_over).map(|b| &**b), Some(&base_png));
}
/// #6086: Compatible tables with replaced media track table, row, and cell property differences
/// via undoable `fmt_change` revisions; image-free layout-only grid differences keep the old
/// single-table behavior without emitting two tables, and changed grid widths combined with
/// replaced media defer structural replacement when `formatting` is enabled (reporting `"tables"`
/// in `notHonoured`) while tracking the replaced media when `formatting` is false.
#[test]
fn compare_unchanged_text_table_tracks_table_row_cell_props_and_grid_widths() {
let tmp = TempTestDir::new("wc-compare-tbl-props");
let base_png = vec![0x89, b'P', b'N', b'G', 11, 22, 33, 44];
let rev_png = vec![0x89, b'P', b'N', b'G', 55, 66, 77, 88];
let make_styled_table_doc = |bytes: Vec<u8>, styled: bool, width: f32| -> Document {
let mut d = Document::new();
let k = d.add_media(bytes, "png");
let mut p = Paragraph::with_text("Logo", CharProps::default());
let at = p.len();
p.insert_object(
at,
InlineObject::Image {
media: k,
w: 100.0,
h: 60.0,
alt: "logo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
let mut t = wordcraft_doc::table::Table::new(1, 1, width);
if styled {
t.props.align = Some(wordcraft_doc::props::Align::Center);
t.rows[0].props.cant_split = true;
t.rows[0].cells[0].props.shading = Some(wordcraft_doc::props::Rgb(0xEE, 0xFF, 0xDD));
}
t.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(p))];
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::new()))];
d
};
let rev_styled_path = tmp.path("rev-styled.docx");
crate::io::save_path(&rev_styled_path, &make_styled_table_doc(rev_png.clone(), true, 200.0)).unwrap();
let mut s = Session::new(make_styled_table_doc(base_png.clone(), false, 200.0));
let r = s.run("review.compare", &json!({"path": rev_styled_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r["changes"], 4, "table, row, cell property changes + replaced cell image count as 4 changes");
assert!(!r["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"));
let t = s.doc.body[0].as_table().unwrap();
assert!(t.props.fmt_change.is_some(), "table property change recorded");
assert!(t.rows[0].props.fmt_change.is_some(), "row property change recorded");
assert!(t.rows[0].cells[0].props.fmt_change.is_some(), "cell property change recorded");
let cmp_styled_path = tmp.path("cmp-styled.docx");
crate::io::save_path(&cmp_styled_path, &s.doc).unwrap();
let reopened = crate::io::open_path(&cmp_styled_path).unwrap();
let mut accepted = Session::new(reopened.clone());
accepted.run("review.acceptAll", &json!({})).unwrap();
let t_acc = accepted.doc.body[0].as_table().unwrap();
assert_eq!(t_acc.props.align, Some(wordcraft_doc::props::Align::Center));
assert!(t_acc.rows[0].props.cant_split);
assert_eq!(t_acc.rows[0].cells[0].props.shading, Some(wordcraft_doc::props::Rgb(0xEE, 0xFF, 0xDD)));
let mut rejected = Session::new(reopened);
rejected.run("review.rejectAll", &json!({})).unwrap();
let t_rej = rejected.doc.body[0].as_table().unwrap();
assert_eq!(t_rej.props.align, None, "Reject All restores original table alignment");
assert!(!t_rej.rows[0].props.cant_split, "Reject All restores original row cant_split");
assert_eq!(t_rej.rows[0].cells[0].props.shading, None, "Reject All restores original cell shading");
let p_rej = t_rej.rows[0].cells[0].blocks[0].as_para().unwrap();
let objs_rej: Vec<(usize, &InlineObject)> = p_rej.objects_with_offsets().collect();
assert_eq!(objs_rej.len(), 1);
let InlineObject::Image { media: m_rej, .. } = objs_rej[0].1 else { panic!("expected image") };
assert_eq!(rejected.doc.media.get(m_rej).map(|b| &**b), Some(&base_png));
// Layout/formatting-only differences with identical media keep single-table behavior.
let rev_fmt_only_path = tmp.path("rev-fmt-only.docx");
crate::io::save_path(&rev_fmt_only_path, &make_styled_table_doc(base_png.clone(), true, 200.0)).unwrap();
let mut s_no_fmt = Session::new(make_styled_table_doc(base_png.clone(), false, 200.0));
let r_no_fmt =
s_no_fmt.run("review.compare", &json!({"path": rev_fmt_only_path.to_string_lossy(), "showIn": "new", "formatting": false})).unwrap();
assert_eq!(r_no_fmt["changes"], 0);
assert_eq!(s_no_fmt.doc.body.iter().filter(|b| b.as_table().is_some()).count(), 1);
// Image-free table with identical cell text and only a changed column width:
// keeps the old single-table behavior without emitting two tables or empty shells.
let make_grid_doc = |width: f32| -> Document {
let mut d = Document::new();
let mut t = wordcraft_doc::table::Table::new(1, 1, width);
t.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(Paragraph::with_text("Cell", CharProps::default())))];
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::new()))];
d
};
let grid_path = tmp.path("rev-grid.docx");
crate::io::save_path(&grid_path, &make_grid_doc(260.0)).unwrap();
let mut s_grid = Session::new(make_grid_doc(200.0));
let r_grid = s_grid.run("review.compare", &json!({"path": grid_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_grid["changes"], 0, "image-free grid width match keeps old single-table behavior");
assert!(!r_grid["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"));
let assert_single_grid_table = |doc: &Document| {
let tables: Vec<&wordcraft_doc::table::Table> = doc.body.iter().filter_map(|b| b.as_table()).collect();
assert_eq!(tables.len(), 1, "must keep a single table with no duplicate empty shell");
assert_eq!(tables[0].grid, vec![260.0]);
let p = tables[0].rows[0].cells[0].blocks[0].as_para().unwrap();
assert_eq!(p.plain_text(), "Cell");
assert!(p.runs.iter().all(|r| r.props.ins.is_none() && r.props.del.is_none()));
};
assert_single_grid_table(&s_grid.doc);
for cmd in ["review.acceptAll", "review.rejectAll"] {
let mut s_res = Session::new(s_grid.doc.clone());
s_res.run(cmd, &json!({})).unwrap();
assert_single_grid_table(&s_res.doc);
}
let cmp_grid_path = tmp.path("cmp-grid.docx");
crate::io::save_path(&cmp_grid_path, &s_grid.doc).unwrap();
let reopened_grid = crate::io::open_path(&cmp_grid_path).unwrap();
for cmd in ["review.acceptAll", "review.rejectAll"] {
let mut s_res = Session::new(reopened_grid.clone());
s_res.run(cmd, &json!({})).unwrap();
assert_single_grid_table(&s_res.doc);
}
// Replaced image + changed column grid width:
// - with formatting enabled: incompatible grid width defers structural change and reports `tables`;
// - with formatting disabled: tracks the replaced image in the single table.
let grid_img_path = tmp.path("rev-grid-img.docx");
crate::io::save_path(&grid_img_path, &make_styled_table_doc(rev_png.clone(), false, 260.0)).unwrap();
let mut s_grid_img = Session::new(make_styled_table_doc(base_png.clone(), false, 200.0));
let r_grid_img = s_grid_img.run("review.compare", &json!({"path": grid_img_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_grid_img["changes"], 0);
assert!(r_grid_img["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"));
assert_eq!(s_grid_img.doc.body.iter().filter(|b| b.as_table().is_some()).count(), 1);
let t_grid_img = s_grid_img.doc.body[0].as_table().unwrap();
assert_eq!(t_grid_img.grid, vec![200.0], "unsupported grid+media fallback preserves original table grid");
let assert_grid_base_img = |doc: &Document, label: &str| {
let p = doc.body[0].as_table().unwrap().rows[0].cells[0].blocks[0].as_para().unwrap();
let objs: Vec<(usize, &InlineObject)> = p.objects_with_offsets().collect();
assert_eq!(objs.len(), 1, "{label}");
let InlineObject::Image { media, .. } = objs[0].1 else { panic!("expected image") };
assert_eq!(doc.media.get(media).map(|b| &**b), Some(&base_png), "{label}");
};
assert_grid_base_img(&s_grid_img.doc, "unsupported grid+media fallback preserves original image");
let mut s_grid_img_kept = Session::new(s_grid_img.doc.clone());
s_grid_img_kept.run("review.rejectAll", &json!({})).unwrap();
assert_grid_base_img(&s_grid_img_kept.doc, "unsupported grid+media rejectAll keeps original image");
let mut s_grid_img_nf = Session::new(make_styled_table_doc(base_png.clone(), false, 200.0));
let r_grid_img_nf =
s_grid_img_nf.run("review.compare", &json!({"path": grid_img_path.to_string_lossy(), "showIn": "new", "formatting": false})).unwrap();
assert_eq!(r_grid_img_nf["changes"], 1, "with formatting false, replaced image inside grid-changed table is tracked");
assert!(!r_grid_img_nf["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"));
assert_eq!(s_grid_img_nf.doc.body.iter().filter(|b| b.as_table().is_some()).count(), 1);
let mut s_grid_img_rej = Session::new(s_grid_img_nf.doc.clone());
s_grid_img_rej.run("review.rejectAll", &json!({})).unwrap();
let p_grid_rej = s_grid_img_rej.doc.body[0].as_table().unwrap().rows[0].cells[0].blocks[0].as_para().unwrap();
let objs_grid_rej: Vec<(usize, &InlineObject)> = p_grid_rej.objects_with_offsets().collect();
assert_eq!(objs_grid_rej.len(), 1);
let InlineObject::Image { media: m_grid_rej, .. } = objs_grid_rej[0].1 else { panic!("expected image") };
assert_eq!(s_grid_img_rej.doc.media.get(m_grid_rej).map(|b| &**b), Some(&base_png));
}
#[test]
fn compare_with_a_revised_file_keeps_its_text_boxes_backed() {
// Text boxes in both documents, the revised one from a file: every anchor in the result
+1 -16
View File
@@ -443,22 +443,7 @@ impl Session {
crate::cmd::outline::after_command(self, sel_before, self.rev != rev_before);
// Extra selected objects last until something else is edited or selected; formatting
// them keeps them selected, as in Word.
let keeps_multi_select = matches!(id, "select.addObject" | "arrange.ungroup")
|| (self.sel == *sel_before
&& matches!(
id,
"shape.fill"
| "shape.effects"
| "shape.outline"
| "shape.size"
| "shape.rotation"
| "picture.size"
| "arrange.rotate"
| "arrange.rotation"
| "shape.alignText"
| "shape.textDirection"
));
if !keeps_multi_select && (spec.mutates || self.sel != *sel_before) {
if !matches!(id, "select.addObject" | "arrange.ungroup" | "shape.fill" | "shape.effects") && (spec.mutates || self.sel != *sel_before) {
self.also_selected.clear();
}
// A canvas member stays picked while its canvas does and nothing else is selected.
+4 -653
View File
@@ -20,7 +20,6 @@ mod fonts;
mod ime_noop;
mod page_number_formats_in_lists;
mod para_tools;
mod paste_table_in_cell;
mod revision_checks;
mod typing;
mod wordart;
@@ -1663,9 +1662,10 @@ fn copying_puts_rtf_on_the_clipboard() {
assert!(r["rtf"].as_str().is_some_and(|t| t.starts_with("{\\rtf1") && t.contains("bold")), "{r}");
assert_eq!(text(&s).lines().next(), Some("plain "));
// Nothing selected: Copy is refused, so nothing is copied.
// Nothing selected: nothing copied, no RTF.
run(&mut s, "caret.docEnd", json!({}));
assert!(s.run("edit.copy", &json!({})).is_err(), "Copy with nothing selected");
let r = run(&mut s, "edit.copy", json!({}));
assert!(r.get("rtf").is_none(), "{r}");
}
#[test]
@@ -2070,205 +2070,6 @@ fn paste_keeps_source_formatting_from_other_programs() {
assert_eq!(props_at(&s, 4).italic, Some(true));
}
/// Verify that pasting syntax-highlighted code from VS Code retains syntax colors and font styling
/// without inheriting dark background shading strips from outer container elements (#6157).
#[test]
fn pasted_code_from_vscode_has_syntax_colors_and_no_character_shading() {
// #6157: VS Code wraps copied code in an outer div with `background-color: #1e1e1e`.
// In Word and per CSS (background-color does not inherit), pasting into a document keeps the
// syntax colors and mono font without painting dark character shading strips over the runs.
let mut s = s();
let vscode_html = r#"<div style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas, 'Courier New', monospace;font-weight: normal;font-size: 14px;line-height: 19px;white-space: pre;"><div><span style="color: #569cd6;">const</span><span style="color: #d4d4d4;"> x = </span><span style="color: #b5cea8;">1</span><span style="color: #d4d4d4;">;</span></div></div>"#;
run(&mut s, "edit.paste", json!({"text": "const x = 1;", "html": vscode_html}));
assert_eq!(text(&s), "const x = 1;");
let p = s.doc.para_at(&s.sel.focus).unwrap();
for r in &p.runs {
assert_eq!(r.props.shading, None, "character should have no shading from container div");
}
assert_eq!(p.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "container background is kept as paragraph shading");
assert!(p.runs.iter().any(|r| r.props.color == Some(wordcraft_doc::TextColor::Rgb(wordcraft_doc::Rgb(0x56, 0x9c, 0xd6)))));
}
/// A multi-block paste keeps the first pasted paragraph's shading when the destination has its own properties (#6157).
#[test]
fn multi_block_paste_keeps_first_paragraph_shading() {
let mut s = s();
run(&mut s, "para.align", json!({"value": "center"}));
let html = r#"<div style="background-color:#1e1e1e"><p>one</p><p>two</p></div>"#;
run(&mut s, "edit.paste", json!({"text": "one\ntwo", "html": html}));
assert_eq!(text(&s), "one\ntwo");
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "first pasted paragraph keeps its shading");
}
/// A destination paragraph whose style shades keeps that shading when a shaded paragraph is pasted (#6157).
#[test]
fn paste_keeps_destination_style_shading() {
let mut s = s();
Arc::make_mut(&mut s.doc.styles).upsert(wordcraft_doc::Style {
id: "Shaded".into(),
name: "Shaded".into(),
kind: wordcraft_doc::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: wordcraft_doc::props::ParaProps { shading: Some(wordcraft_doc::Rgb(0x22, 0x22, 0x22)), ..Default::default() },
..Default::default()
});
run(&mut s, "para.style", json!({"style": "Shaded"}));
let html = r#"<div style="background-color:#1e1e1e"><span>text</span></div>"#;
run(&mut s, "edit.paste", json!({"text": "text", "html": html}));
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p.props.shading, None, "source shading must not override the destination style");
assert_eq!(
s.doc.styles.resolve_para(&p.props).shading,
Some(wordcraft_doc::Rgb(0x22, 0x22, 0x22)),
"destination style shading remains effective"
);
}
/// Multi-line VS Code paste keeps removable paragraph shading rather than stuck character shading,
/// so Shading › No Color, Clear All Formatting, and Merge Formatting all clear the dark background (#6157).
#[test]
fn pasted_code_from_vscode_shading_is_removable() {
let vscode_html = concat!(
r#"<div style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas, 'Courier New', monospace;font-size: 14px;white-space: pre;">"#,
r#"<div><span style="color: #569cd6;">const</span><span style="color: #d4d4d4;"> a = 1;</span></div>"#,
r#"<div><span style="color: #569cd6;">const</span><span style="color: #d4d4d4;"> b = 2;</span></div>"#,
r#"</div>"#,
);
let plain = "const a = 1;\nconst b = 2;";
// Home › Paragraph › Shading › No Color removes the dark background across all pasted lines.
let mut s = self::s();
run(&mut s, "edit.paste", json!({"text": plain, "html": vscode_html}));
assert_eq!(s.doc.body.len(), 2);
for b in &s.doc.body {
let p = b.as_para().unwrap();
assert_eq!(p.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
assert!(p.runs.iter().all(|r| r.props.shading.is_none()));
}
run(&mut s, "select.all", json!({}));
run(&mut s, "para.shading", json!({"color": null}));
for b in &s.doc.body {
let p = b.as_para().unwrap();
assert_eq!(p.props.shading, None, "Shading › No Color clears the container background");
assert!(p.runs.iter().all(|r| r.props.shading.is_none()));
}
// Clear All Formatting clears both the dark paragraph shading and light syntax colors.
let mut s = self::s();
run(&mut s, "edit.paste", json!({"text": plain, "html": vscode_html}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.clear", json!({}));
for b in &s.doc.body {
let p = b.as_para().unwrap();
assert_eq!(p.props.shading, None);
assert!(p.runs.iter().all(|r| r.props.shading.is_none() && r.props.color.is_none()));
}
// Paste › Merge Formatting drops the dark container background and light text colors up front.
let mut s = self::s();
run(&mut s, "edit.pasteMerge", json!({"text": plain, "html": vscode_html}));
for b in &s.doc.body {
let p = b.as_para().unwrap();
assert_eq!(p.props.shading, None);
assert!(p.runs.iter().all(|r| r.props.shading.is_none() && r.props.color.is_none()));
}
}
/// Copying a paragraph shaded via its style writes `background-color` to the clipboard HTML (#6157).
#[test]
fn copy_exports_style_inherited_paragraph_shading_to_clipboard_html() {
let mut s = s();
Arc::make_mut(&mut s.doc.styles).upsert(wordcraft_doc::Style {
id: "CodeBlock".into(),
name: "Code Block".into(),
kind: wordcraft_doc::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: wordcraft_doc::props::ParaProps { shading: Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), ..Default::default() },
..Default::default()
});
run(&mut s, "document.setText", json!({"text": "const x = 1;"}));
run(&mut s, "para.style", json!({"style": "CodeBlock"}));
run(&mut s, "select.all", json!({}));
let r = run(&mut s, "edit.copy", json!({}));
let html = r["html"].as_str().unwrap_or_default();
assert!(html.contains("background-color:#1E1E1E"), "clipboard HTML carries style paragraph shading: {html}");
let mut dst = self::s();
run(&mut dst, "edit.paste", json!({"text": "const x = 1;", "html": html, "privateClipboard": false}));
let p = dst.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
}
/// Pasting a single inline-highlighted word into the middle of an unshaded paragraph keeps run
/// shading on that word alone and leaves the destination paragraph unshaded (#6157).
#[test]
fn pasting_inline_highlighted_word_mid_paragraph_keeps_run_shading_only() {
for (html, want) in [
(r#"<span style="background-color:yellow">word</span>"#, wordcraft_doc::Rgb(0xff, 0xff, 0x00)),
(r"<mark>word</mark>", wordcraft_doc::Rgb(0xff, 0xff, 0x00)),
(r#"<code style="background-color:#eeeeee">word</code>"#, wordcraft_doc::Rgb(0xee, 0xee, 0xee)),
] {
let mut s = self::s();
run(&mut s, "document.setText", json!({"text": "before after"}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 7}, "focus": {"block": 0, "off": 7}}));
run(&mut s, "edit.paste", json!({"text": "word", "html": html}));
assert_eq!(text(&s), "before word after", "{html}");
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p.props.shading, None, "destination paragraph stays unshaded: {html}");
assert_eq!(p.props_of_char(0).shading, None, "{html}");
assert_eq!(p.props_of_char(7).shading, Some(want), "pasted word keeps run shading: {html}");
assert_eq!(p.props_of_char(12).shading, None, "{html}");
}
}
/// Pasting a container-wrapped one-line snippet (no paragraph break) into the middle of a
/// paragraph leaves the destination paragraph unshaded (#6157).
#[test]
fn container_wrapped_one_line_paste_mid_paragraph_leaves_paragraph_unshaded() {
let mut s = self::s();
run(&mut s, "document.setText", json!({"text": "Call now."}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 5}, "focus": {"block": 0, "off": 5}}));
let vscode_html = r#"<div style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas, 'Courier New', monospace;font-size: 14px;white-space: pre;"><span style="color: #569cd6;">foo</span></div>"#;
run(&mut s, "edit.paste", json!({"text": "foo", "html": vscode_html}));
assert_eq!(text(&s), "Call foo now.");
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p.props.shading, None, "destination paragraph stays unshaded");
assert_eq!(p.props_of_char(0).shading, None);
assert_eq!(p.props_of_char(5).shading, None);
}
/// Under Track Changes, rejecting a paste restores the destination paragraph formatting (#6157).
#[test]
fn tracked_paste_reject_restores_destination_paragraph_shading() {
let mut s = self::s();
run(&mut s, "document.setText", json!({"text": "Call now."}));
run(&mut s, "review.trackChanges", json!({"enabled": true}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 5}, "focus": {"block": 0, "off": 5}}));
let vscode_html = r#"<div style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas, 'Courier New', monospace;font-size: 14px;white-space: pre;"><span style="color: #569cd6;">foo</span></div>"#;
run(&mut s, "edit.paste", json!({"text": "foo", "html": vscode_html}));
assert_eq!(text(&s), "Call foo now.");
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p.props.shading, None);
run(&mut s, "review.rejectAll", json!({}));
assert_eq!(text(&s), "Call now.");
let p_after = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p_after.props.shading, None, "rejecting paste leaves paragraph unshaded");
// Also verify that pasting into an empty paragraph under Track Changes restores the empty
// paragraph's unshaded state on Reject All.
let mut s2 = self::s();
run(&mut s2, "review.trackChanges", json!({"enabled": true}));
run(&mut s2, "edit.paste", json!({"text": "foo", "html": vscode_html}));
assert_eq!(text(&s2), "foo");
let p2 = s2.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p2.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
run(&mut s2, "review.rejectAll", json!({}));
assert_eq!(text(&s2), "");
let p2_after = s2.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p2_after.props.shading, None, "rejecting paste into empty paragraph clears paragraph shading");
}
/// A CF_HTML ("HTML Format") clipboard payload around `html`, with the byte offsets Windows writes.
fn cf_html(html: &str) -> String {
let n = "Version:1.0\r\nStartHTML:0000000000\r\nEndHTML:0000000000\r\nStartFragment:0000000000\r\nEndFragment:0000000000\r\n".len();
@@ -2616,122 +2417,6 @@ fn copy_whole_table_pastes_a_table() {
assert_eq!(body_table_cells(&s), vec![want.clone(), want]);
}
/// #5906: Copying select-all in a document starting with a table must preserve the table.
#[test]
fn select_all_in_document_starting_with_table_preserves_table() {
let mut s = s();
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
run(&mut s, "text.insert", json!({"text": "A1"}));
run(&mut s, "select.all", json!({"whole": true}));
run(&mut s, "edit.copy", json!({}));
let clip = s.clipboard.as_ref().unwrap();
assert!(
clip.blocks.iter().any(|b| matches!(b, wordcraft_doc::Block::Table(_))),
"copying select-all in a document starting with a table must preserve table structure, got {:?}",
clip.blocks
);
let table = clip
.blocks
.iter()
.find_map(|b| match b {
wordcraft_doc::Block::Table(t) => Some(t),
_ => None,
})
.expect("table block in clipboard");
assert_eq!(table.rows.len(), 2, "copied table row count");
assert_eq!(table.cols(), 2, "copied table col count");
let c00 = table.rows[0].cells[0].blocks.first().and_then(|b| match &**b {
wordcraft_doc::Block::Para(p) => Some(p.text.as_str()),
_ => None,
});
assert_eq!(c00, Some("A1"), "cell (0, 0) text");
}
/// #5906: Cut and Spike across table cells with non-corner endpoints must preserve every removed character.
#[test]
fn cut_and_spike_across_table_cells_preserves_every_removed_character() {
// 1. Test Spike then insertSpike
{
let mut s = s();
run(&mut s, "insert.table", json!({"rows": 3, "cols": 3}));
for (i, text) in ["R0C0", "R0C1", "R0C2", "R1C0", "R1C1", "R1C2", "R2C0", "R2C1", "R2C2"].iter().enumerate() {
if i > 0 {
run(&mut s, "text.tab", json!({}));
}
run(&mut s, "text.insert", json!({"text": text}));
}
// Set linear text range across non-corner cells: (0, 1) off 1 ("0C1") through (1, 1) off 3 ("R1C").
// Traversed in linear document order: (0, 1) "0C1", (0, 2) "R0C2", (1, 0) "R1C0", (1, 1) "R1C".
s.sel = crate::Selection {
anchor: wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path(vec![0, 0, 1, 0]), off: 1 },
focus: wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path(vec![0, 1, 1, 0]), off: 3 },
};
s.column = None;
run(&mut s, "edit.spike", json!({}));
// Verify the table content after spike:
// (0, 1) has "R" remaining, (0, 2) emptied, (1, 0) emptied, (1, 1) has "1" remaining.
let cells_after = body_table_cells(&s);
assert_eq!(
cells_after,
vec![vec!["R0C0".to_string(), "R".into(), "".into(), "".into(), "1".into(), "R1C2".into(), "R2C0".into(), "R2C1".into(), "R2C2".into(),]]
);
// Paste the spike at the end of the document: all 4 removed pieces must be present.
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "edit.insertSpike", json!({}));
let texts = body_texts(&s);
assert!(
texts.iter().any(|t| t == "0C1")
&& texts.iter().any(|t| t == "R0C2")
&& texts.iter().any(|t| t == "R1C0")
&& texts.iter().any(|t| t == "R1C"),
"every removed character must be preserved and inserted from spike, got: {:?}",
texts
);
}
// 2. Test Cut then paste
{
let mut s = s();
run(&mut s, "insert.table", json!({"rows": 3, "cols": 3}));
for (i, text) in ["R0C0", "R0C1", "R0C2", "R1C0", "R1C1", "R1C2", "R2C0", "R2C1", "R2C2"].iter().enumerate() {
if i > 0 {
run(&mut s, "text.tab", json!({}));
}
run(&mut s, "text.insert", json!({"text": text}));
}
s.sel = crate::Selection {
anchor: wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path(vec![0, 0, 1, 0]), off: 1 },
focus: wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path(vec![0, 1, 1, 0]), off: 3 },
};
s.column = None;
run(&mut s, "edit.cut", json!({}));
let cells_after_cut = body_table_cells(&s);
assert_eq!(
cells_after_cut,
vec![vec!["R0C0".to_string(), "R".into(), "".into(), "".into(), "1".into(), "R1C2".into(), "R2C0".into(), "R2C1".into(), "R2C2".into(),]]
);
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "edit.paste", json!({}));
let texts_cut = body_texts(&s);
assert!(
texts_cut.iter().any(|t| t == "0C1")
&& texts_cut.iter().any(|t| t == "R0C2")
&& texts_cut.iter().any(|t| t == "R1C0")
&& texts_cut.iter().any(|t| t == "R1C"),
"every removed character must be preserved and inserted from cut, got: {:?}",
texts_cut
);
}
}
/// #1744: Select Table → Cut removes the whole table, and one Undo brings it back.
#[test]
fn cut_whole_table_removes_it_and_undoes() {
@@ -2950,20 +2635,6 @@ fn tracked_cut_of_a_table_or_row_marks_text_deleted() {
assert_eq!(body_table_final(&s), full);
}
/// Cut and Copy are off with nothing selected (the ribbon buttons read this) and on with text selected.
#[test]
fn cut_and_copy_are_disabled_without_a_selection() {
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "text.insert", json!({"text": "Hello"}));
for id in ["edit.cut", "edit.copy"] {
assert!(s.why_disabled(id).is_some(), "{id} with a caret only");
}
run(&mut s, "select.text", json!({"text": "Hello"}));
for id in ["edit.cut", "edit.copy"] {
assert!(s.why_disabled(id).is_none(), "{id} with a selection");
}
}
/// #1744 review: Cut of a table, or of cells, holding a content control locked against deletion
/// is refused and changes nothing in the document; the copy is made first, so the clipboard
/// holds the table, as for any refused Cut.
@@ -3329,19 +3000,11 @@ fn tables_nest_only_as_deep_as_a_json_save_reads() {
let e = s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap_err();
assert!(e.to_string().contains(&format!("{MAX_TABLE_DEPTH} deep")), "{e}");
assert_eq!(s.doc, before);
// Paste as Nested Table is the path the depth guard sits on: the table's text comes as paragraphs.
run(&mut s, "edit.pasteNestedTable", json!({"text": "b", "html": "<table><tr><td>b</td></tr></table>"}));
run(&mut s, "edit.paste", json!({"text": "b", "html": "<table><tr><td>b</td></tr></table>"}));
let cell = s.sel.focus.path.clone();
let blocks: Vec<_> = (0..).map_while(|i| s.doc.block(StoryRef::Body, &cell.with_last(i))).collect();
assert!(blocks.iter().all(|b| b.as_table().is_none()), "no table below the limit");
assert!(blocks.iter().any(|b| b.as_para().is_some_and(|p| p.text.contains('b'))), "the pasted text is there");
// Paste lays a one-cell table over the cell (#6739): no new level either.
run(&mut s, "edit.paste", json!({"text": "c", "html": "<table><tr><td>c</td></tr></table>"}));
let cell = s.sel.focus.path.clone();
let blocks: Vec<_> = (0..).map_while(|i| s.doc.block(StoryRef::Body, &cell.with_last(i))).collect();
assert!(blocks.iter().all(|b| b.as_table().is_none()), "no table below the limit");
assert!(blocks.iter().any(|b| b.as_para().is_some_and(|p| p.text.contains('c'))), "the pasted text is there");
assert_eq!(s.sel.focus.path.depth(), MAX_TABLE_DEPTH);
}
/// #3618: a text box story sits two JSON levels below the body, and its deepest cell still reads
@@ -6176,318 +5839,6 @@ fn copy_paste_text_box_makes_an_independent_copy() {
assert_eq!(s.doc.parts.len(), parts);
}
/// Copying and pasting a selected custom text box duplicates its dimensions, styling, and text
/// while giving the copy an independent story ID.
#[test]
fn copy_and_paste_selected_custom_text_box_duplicates_dimensions_styling_and_text() {
let mut s = s();
let id = run(
&mut s,
"insert.textBox",
json!({
"text": "Custom content",
"width": 180.0,
"height": 90.0
}),
)["story"]
.as_u64()
.unwrap() as u32;
// Apply custom styling (fill and outline).
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "shape.fill", json!({"color": "FFEEDD"}));
run(&mut s, "shape.outline", json!({"color": "112233", "width": 2.5}));
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
let orig_obj = para.objects[0].clone();
let wordcraft_doc::InlineObject::Shape { w, h, stroke_width, fill, stroke, .. } = &orig_obj else { panic!("not a shape") };
assert_eq!((*w, *h), (180.0, 90.0));
assert_eq!(*stroke_width, 2.5);
assert!(fill.is_some());
assert!(stroke.is_some());
// Copy selected custom text box (non-collapsed, object_selection, #5785, #5859).
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
assert!(crate::cmd::objects::object_selection(&s).is_some());
let copy_res = run(&mut s, "edit.copy", json!({}));
assert_eq!(copy_res["text"], "Custom content");
assert_eq!(s.clipboard_text, "Custom content");
assert!(s.clipboard.is_some());
// Move caret after original and paste.
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 3)}));
run(&mut s, "edit.paste", json!({}));
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
assert_eq!(para.objects.len(), 2);
let pasted = &para.objects[1];
let wordcraft_doc::InlineObject::Shape { w: pw, h: ph, stroke_width: psw, fill: pfill, stroke: pstroke, story: pstory, .. } = pasted else {
panic!("pasted not a shape");
};
assert_eq!((*pw, *ph), (180.0, 90.0), "dimensions duplicated");
assert_eq!(*psw, 2.5, "stroke width duplicated");
assert_eq!(pfill, fill, "fill duplicated");
assert_eq!(pstroke, stroke, "stroke duplicated");
assert!(pstory.is_some());
assert_ne!(pstory.unwrap(), id, "independent story ID");
assert_eq!(s.doc.plain_text(StoryRef::Part(pstory.unwrap())), "Custom content", "inner text duplicated");
// Cut the pasted text box by selecting it (non-collapsed, object_selection).
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 3), "focus": Pos::body(0, 6)}));
assert!(crate::cmd::objects::object_selection(&s).is_some());
let cut_res = run(&mut s, "edit.cut", json!({}));
assert_eq!(cut_res["text"], "Custom content");
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
assert_eq!(para.objects.len(), 1);
assert_eq!(para.objects[0].text_box(), Some(id));
// Paste it back.
run(&mut s, "edit.paste", json!({}));
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
assert_eq!(para.objects.len(), 2);
// Copy and paste a shape without text.
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 6)}));
run(&mut s, "insert.shape", json!({"kind": "star", "width": 64.0, "height": 48.0}));
run(&mut s, "shape.fill", json!({"color": "00FF00"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 6), "focus": Pos::body(0, 9)}));
run(&mut s, "edit.copy", json!({}));
assert!(s.clipboard.is_some());
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 9)}));
run(&mut s, "edit.paste", json!({}));
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
assert_eq!(para.objects.len(), 4);
let star_copy = &para.objects[3];
let wordcraft_doc::InlineObject::Shape { kind, w, h, fill, .. } = star_copy else { panic!("not a shape") };
assert_eq!(*kind, wordcraft_doc::para::ShapeKind::Star);
assert_eq!((*w, *h), (64.0, 48.0));
assert!(fill.is_some());
}
/// Cut and Copy with a bare caret beside an object (collapsed selection) change nothing (#5859).
#[test]
fn cut_and_copy_with_bare_caret_beside_object_change_nothing() {
let mut s = s();
let id = run(&mut s, "insert.textBox", json!({"text": "Box content"}))["story"].as_u64().unwrap() as u32;
// 1. Bare caret immediately before the object (Pos::body(0, 0)).
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
assert!(s.sel.is_collapsed());
assert!(crate::cmd::objects::object_selection(&s).is_none());
let copy_res = s.run("edit.copy", &json!({}));
assert!(matches!(copy_res, Err(crate::CmdError::Disabled(_))), "copy on bare caret is disabled");
assert!(s.clipboard.is_none(), "clipboard remains unset");
let cut_res = s.run("edit.cut", &json!({}));
assert!(matches!(cut_res, Err(crate::CmdError::Disabled(_))), "cut on bare caret is disabled");
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
assert_eq!(para.objects.len(), 1, "object was not deleted");
assert_eq!(para.objects[0].text_box(), Some(id));
// 2. Bare caret immediately after the object (Pos::body(0, 3)).
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 3)}));
assert!(s.sel.is_collapsed());
assert!(crate::cmd::objects::object_selection(&s).is_none());
let copy_res = s.run("edit.copy", &json!({}));
assert!(matches!(copy_res, Err(crate::CmdError::Disabled(_))), "copy on bare caret is disabled");
assert!(s.clipboard.is_none(), "clipboard remains unset");
let cut_res = s.run("edit.cut", &json!({}));
assert!(matches!(cut_res, Err(crate::CmdError::Disabled(_))), "cut on bare caret is disabled");
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
assert_eq!(para.objects.len(), 1, "object was not deleted");
assert_eq!(para.objects[0].text_box(), Some(id));
}
/// Fallback plain text / clipboard text when paragraphs contain text boxes (#5785).
#[test]
fn fallback_plain_text_extracts_text_box_story_when_body_contains_paragraph_marks() {
let mut f = wordcraft_doc::edit::Fragment::default();
let mut p = wordcraft_doc::Paragraph::new();
p.text = format!("{}\n", wordcraft_doc::para::OBJ);
let mut part_p = wordcraft_doc::Paragraph::new();
part_p.text = "Box text".to_string();
let part = wordcraft_doc::Part {
kind: wordcraft_doc::PartKind::TextBox,
blocks: vec![std::sync::Arc::new(wordcraft_doc::Block::Para(part_p))],
body: Default::default(),
};
f.blocks = vec![wordcraft_doc::Block::Para(p)];
f.parts.insert(100, part);
assert_eq!(f.plain_text(), "Box text");
assert_eq!(f.clipboard_text(), "Box text");
}
/// Pasting formatted content with matching RTF but mismatched HTML from an external app prefers HTML (#5785).
#[test]
fn paste_content_prefers_external_html_when_rtf_matches_session_clipboard() {
let mut s = s();
run(&mut s, "insert.textBox", json!({"text": "Internal text"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "edit.copy", json!({}));
let my_rtf = s.clipboard_rtf.clone();
let external_html = "<p>External rich text</p>";
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"html": external_html, "rtf": my_rtf}));
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
assert_eq!(frag.plain_text(), "External rich text");
}
}
/// Pasting with no text payload or empty text but matching HTML and RTF uses WordCraft's session clipboard
/// fragment, preserving custom text box parts (#5785, #5859).
#[test]
fn paste_content_uses_session_clipboard_when_html_and_rtf_match_without_text() {
let mut s = s();
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "edit.copy", json!({}));
let my_html = s.clipboard_html.clone();
let my_rtf = s.clipboard_rtf.clone();
assert!(!my_html.is_empty());
assert!(!my_rtf.is_empty());
assert!(s.clipboard.as_ref().is_some_and(|f| !f.parts.is_empty()));
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"html": my_html, "rtf": my_rtf}));
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
assert_eq!(frag.parts.len(), 1, "session text box parts preserved");
assert_eq!(frag.plain_text(), "Internal text box");
}
let pasted_with_empty_text = crate::cmd::paste::paste_content(&mut s, &json!({"text": "", "html": my_html, "rtf": my_rtf}));
assert!(matches!(pasted_with_empty_text, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_with_empty_text {
assert_eq!(frag.parts.len(), 1, "session text box parts preserved with empty text");
assert_eq!(frag.plain_text(), "Internal text box");
}
let avail = crate::cmd::paste::available(&s, &json!({"text": "", "html": my_html, "rtf": my_rtf}));
assert!(avail.contains(&"formatted"), "formatted format is available for pasteSpecial when text is empty but rich formats match");
let paste_special_res = s.run("edit.pasteSpecial", &json!({"as": "formatted", "text": "", "html": my_html, "rtf": my_rtf}));
assert!(paste_special_res.is_ok(), "pasteSpecial as formatted succeeds with empty text and matching rich formats");
}
/// On macOS, arboard wraps HTML in `<html><head>…</head><body>…</body></html>`, so the
/// round-tripped HTML never equals what WordCraft stored. The session clipboard must still be
/// recognised when RTF matches or HTML matches after unwrapping (#5859).
#[test]
fn paste_content_uses_session_clipboard_when_macos_wraps_html() {
let mut s = s();
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "edit.copy", json!({}));
let my_rtf = s.clipboard_rtf.clone();
assert!(!my_rtf.is_empty());
assert!(s.clipboard.as_ref().is_some_and(|f| !f.parts.is_empty()));
// Simulate macOS wrapping: HTML is wrapped by arboard, RTF is raw.
let wrapped_html =
format!("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"></head><body>{}</body></html>", s.clipboard_html);
assert_ne!(wrapped_html, s.clipboard_html, "wrapped HTML differs from stored");
// With empty text (front-end path for shapes/text-boxes without text), session clipboard matched.
let pasted = crate::cmd::paste::paste_content(&mut s, &json!({"text": "", "html": wrapped_html, "rtf": my_rtf}));
assert!(matches!(pasted, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted {
assert_eq!(frag.parts.len(), 1, "session text box parts preserved despite wrapped HTML");
assert_eq!(frag.plain_text(), "Internal text box");
}
// With non-empty text that matches, session clipboard matched via main's text rule.
let my_text = s.clipboard_text.clone();
let pasted_text = crate::cmd::paste::paste_content(&mut s, &json!({"text": my_text, "html": wrapped_html, "rtf": my_rtf}));
assert!(matches!(pasted_text, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_text {
assert_eq!(frag.parts.len(), 1, "session text box parts preserved with text match");
}
// Paste Special as formatted is available despite wrapped HTML.
let avail = crate::cmd::paste::available(&s, &json!({"text": my_text, "html": wrapped_html, "rtf": my_rtf}));
assert!(avail.contains(&"formatted"), "formatted format is available for pasteSpecial when HTML is wrapped on macOS");
}
/// Pasting external RTF when HTML matches WordCraft's session clipboard does not return the old
/// session fragment with its custom parts (#5785, #5859).
#[test]
fn paste_content_does_not_use_session_clipboard_when_html_matches_but_rtf_differs() {
let mut s = s();
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "edit.copy", json!({}));
let my_html = s.clipboard_html.clone();
let external_rtf = "{\\rtf1\\ansi External rich text}";
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"html": my_html, "rtf": external_rtf}));
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
assert!(frag.parts.is_empty(), "session text box parts not reused when RTF differs");
}
}
/// Pasting external RTF when plain text matches WordCraft's session clipboard does not return the
/// old session fragment with its custom parts, even when privateClipboard is omitted (#5785, #5859).
#[test]
fn paste_content_does_not_use_session_clipboard_when_text_matches_but_rtf_differs() {
let mut s = s();
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "edit.copy", json!({}));
let my_text = s.clipboard_text.clone();
let external_rtf = "{\\rtf1\\ansi External rich text}";
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"text": my_text, "rtf": external_rtf}));
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
assert!(frag.parts.is_empty(), "session text box parts not reused when RTF differs");
}
let avail = crate::cmd::paste::available(&s, &json!({"text": my_text, "rtf": external_rtf}));
assert!(!avail.contains(&"formatted"), "formatted is unavailable when supplied RTF differs");
}
/// When another app copies different RTF (`privateClipboard: false`), plain text matching
/// WordCraft's session clipboard does not return the old session fragment (#5785, #5859).
#[test]
fn paste_content_does_not_use_session_clipboard_when_another_app_copied_rtf() {
let mut s = s();
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "edit.copy", json!({}));
let my_text = s.clipboard_text.clone();
let external_rtf = "{\\rtf1\\ansi External rich text}";
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"privateClipboard": false, "text": my_text, "rtf": external_rtf}));
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
assert!(frag.parts.is_empty(), "session text box parts not reused when another app copied");
}
}
/// The public `edit.paste` command does not reuse session text box parts when supplied RTF differs,
/// even when privateClipboard is omitted (#5859).
#[test]
fn paste_command_does_not_use_session_clipboard_when_text_matches_but_rtf_differs() {
let mut s = s();
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "edit.copy", json!({}));
let my_text = s.clipboard_text.clone();
let external_rtf = "{\\rtf1\\ansi External rich text}";
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "edit.paste", json!({"text": my_text, "rtf": external_rtf}));
assert_eq!(s.doc.parts.len(), 1, "no second text box part created from session fragment");
assert!(s.doc.plain_text(StoryRef::Body).contains("External rich text"));
}
#[test]
fn word_count_includes_text_boxes_by_default() {
let mut s = s();
@@ -1,532 +0,0 @@
//! #6739: a copied table pasted with the caret in a table cell does what Word's Paste does (rows
//! inserted above, or cells overwritten from the caret's), and nests only when asked to.
use std::sync::Arc;
use serde_json::json;
use wordcraft_doc::edit::Fragment;
use wordcraft_doc::{Block, Cell, Document, Paragraph, Path, Pos, StoryRef, Table, para_block};
use crate::cmd::table::cell_text;
use crate::{Selection, Session};
/// A table of `rows` x `cols` cells whose texts are `<prefix><row><col>` (from 1), 100 pt wide cells.
fn table(prefix: &str, rows: usize, cols: usize) -> Table {
let mut t = Table::new(rows, cols, 100.0 * cols as f32);
for (r, row) in t.rows.iter_mut().enumerate() {
for (c, cell) in row.cells.iter_mut().enumerate() {
cell.blocks = Cell::with_text(&format!("{prefix}{}{}", r + 1, c + 1)).blocks;
}
}
t
}
/// A document of the 3 x 3 table d11..d33 and an empty paragraph, the caret in cell (`row`, `col`).
fn dest(row: usize, col: usize) -> Session {
let mut d = Document::new();
d.body = vec![Arc::new(Block::Table(table("d", 3, 3))), para_block(Paragraph::new())];
let mut s = Session::new(d);
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, row as u32, col as u32, 0]), 0));
s
}
fn copy(s: &mut Session, t: Table) {
s.clipboard = Some(Fragment { blocks: vec![Block::Table(t)], ..Default::default() });
}
fn paste(s: &mut Session) {
s.run("edit.paste", &json!({})).unwrap();
}
fn t0(s: &Session) -> &Table {
s.doc.body[0].as_table().expect("the table")
}
/// The texts of the table's rows, a nested table shown as `[nested]`.
fn grid(t: &Table) -> Vec<Vec<String>> {
t.rows
.iter()
.map(|r| r.cells.iter().map(|c| if c.blocks.iter().any(|b| b.as_table().is_some()) { "[nested]".into() } else { cell_text(c) }).collect())
.collect()
}
fn rows(spec: &[&str]) -> Vec<Vec<String>> {
spec.iter().map(|r| r.split(',').map(str::to_string).collect()).collect()
}
fn nested(t: &Table) -> bool {
t.rows.iter().flat_map(|r| &r.cells).any(|c| c.blocks.iter().any(|b| b.as_table().is_some()))
}
#[test]
fn paste_all_keeps_tables_in_copy_order_inside_the_cell() {
for col in [0, 1] {
let mut s = dest(1, col);
for prefix in ["first", "second"] {
copy(&mut s, table(prefix, 1, 3));
let frag = s.clipboard.as_ref().unwrap();
s.clip_history.push(frag, &frag.clipboard_text());
}
s.run("edit.pasteAllClipboard", &json!({})).unwrap();
let pasted: Vec<_> = t0(&s).rows[1].cells[col].blocks.iter().filter_map(|b| b.as_table()).map(|t| cell_text(&t.rows[0].cells[0])).collect();
assert_eq!(pasted, ["first11", "second11"]);
}
}
#[test]
fn a_copied_table_over_selected_cells_overwrites_from_the_top_left() {
for (source_cols, expected) in
[(2, rows(&["s11,s12,d13", "s21,s22,d23", "d31,d32,d33"])), (3, rows(&["s11,s12,s13", "s21,s22,s23", "d31,d32,d33"]))]
{
let mut s = dest(1, 1);
crate::cmd::table::extend_selection(&mut s, Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0]), 0));
let range = s.cell_range().unwrap();
assert_eq!((range.rows, range.cols, range.stream), ((0, 1), (0, 1), false));
copy(&mut s, table("s", 2, source_cols));
paste(&mut s);
assert_eq!(grid(t0(&s)), expected, "source width {source_cols}");
assert_eq!(s.sel, Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0]), 0)));
assert!(s.cell_range().is_none());
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(grid(t0(&s)), grid(&table("d", 3, 3)));
s.run("edit.redo", &json!({})).unwrap();
assert_eq!(grid(t0(&s)), expected);
let reopened = wordcraft_docx::read(&wordcraft_docx::write(&s.doc).unwrap()).unwrap();
assert_eq!(grid(reopened.body[0].as_table().unwrap()), expected);
}
}
#[test]
fn plain_text_paste_still_replaces_a_cell_rectangle() {
let mut s = dest(0, 0);
crate::cmd::table::extend_selection(&mut s, Pos::new(StoryRef::Body, Path(vec![0, 1, 1, 0]), 0));
s.run("edit.paste", &json!({"text": "replacement"})).unwrap();
assert_eq!(grid(t0(&s)), rows(&["replacement,,d13", ",,d23", "d31,d32,d33"]));
}
#[test]
fn a_whole_table_with_the_caret_in_the_first_column_inserts_its_rows_above() {
for (row, want) in [
(1, rows(&["d11,d12,d13", "s11,s12,s13", "s21,s22,s23", "s31,s32,s33", "d21,d22,d23", "d31,d32,d33"])),
(0, rows(&["s11,s12,s13", "s21,s22,s23", "s31,s32,s33", "d11,d12,d13", "d21,d22,d23", "d31,d32,d33"])),
] {
let mut s = dest(row, 0);
copy(&mut s, table("s", 3, 3));
paste(&mut s);
assert_eq!(grid(t0(&s)), want, "caret in row {row}");
assert!(!nested(t0(&s)));
assert_eq!(s.doc.body.iter().filter(|b| b.as_table().is_some()).count(), 1);
}
}
#[test]
fn a_whole_table_with_the_caret_further_right_overwrites_cells_and_grows_the_table() {
let mut s = dest(1, 2);
copy(&mut s, table("s", 3, 3));
paste(&mut s);
let want = rows(&["d11,d12,d13,,", "d21,d22,s11,s12,s13", "d31,d32,s21,s22,s23", ",,s31,s32,s33"]);
assert_eq!(grid(t0(&s)), want);
assert_eq!(t0(&s).grid.len(), 5);
assert!(t0(&s).rows.iter().all(|r| r.cells.len() == 5));
// The last cell of the last row: the table grows two columns and two rows.
let mut s = dest(2, 2);
copy(&mut s, table("s", 3, 3));
paste(&mut s);
let want = rows(&["d11,d12,d13,,", "d21,d22,d23,,", "d31,d32,s11,s12,s13", ",,s21,s22,s23", ",,s31,s32,s33"]);
assert_eq!(grid(t0(&s)), want);
}
#[test]
fn cells_copied_from_part_of_a_table_overwrite_from_the_caret_in_any_column() {
// Two cells of one column (Word: s12, s22 into the cells below the caret).
let mut s = dest(1, 0);
copy(&mut s, table("s", 2, 1));
paste(&mut s);
assert_eq!(grid(t0(&s)), rows(&["d11,d12,d13", "s11,d22,d23", "s21,d32,d33"]));
// At the last row a row is added.
let mut s = dest(2, 0);
copy(&mut s, table("s", 2, 1));
paste(&mut s);
assert_eq!(grid(t0(&s)), rows(&["d11,d12,d13", "d21,d22,d23", "s11,d32,d33", "s21,,"]));
// Two columns wide, from the middle column: it fits the table.
let mut s = dest(0, 1);
copy(&mut s, table("s", 2, 2));
paste(&mut s);
assert_eq!(grid(t0(&s)), rows(&["d11,s11,s12", "d21,s21,s22", "d31,d32,d33"]));
}
#[test]
fn one_copied_cell_replaces_the_cell_it_is_pasted_in() {
for (r, c) in [(0, 0), (1, 2), (2, 2)] {
let mut s = dest(r, c);
copy(&mut s, table("s", 1, 1));
paste(&mut s);
let mut want = grid(&table("d", 3, 3));
want[r][c] = "s11".into();
assert_eq!(grid(t0(&s)), want, "cell ({r}, {c})");
}
}
#[test]
fn the_caret_goes_to_the_first_pasted_cell() {
let mut s = dest(1, 0);
copy(&mut s, table("s", 3, 3));
paste(&mut s);
assert_eq!(s.sel.focus.path, Path(vec![0, 1, 0, 0]));
assert!(s.sel.is_collapsed());
}
#[test]
fn paste_as_nested_table_nests_the_table_in_the_cell() {
let mut s = dest(1, 0);
copy(&mut s, table("s", 3, 3));
s.run("edit.pasteNestedTable", &json!({})).unwrap();
let t = t0(&s);
assert_eq!(t.rows.len(), 3, "no rows inserted");
assert!(t.rows[1].cells[0].blocks.iter().any(|b| b.as_table().is_some()), "a table nests in the cell");
assert_eq!(cell_text(&t.rows[1].cells[1]), "d22");
}
#[test]
fn pasting_a_wrapped_table_keeps_its_source_controls() {
use wordcraft_doc::{ContentControl, ControlKind};
for on_row in [false, true] {
// A same-width copy can insert rows at column zero or overwrite cells further right.
for col in [0, 1] {
let mut s = dest(1, col);
let mut source = table("s", 2, 3);
let controls = if on_row { &mut source.rows[0].controls } else { &mut source.controls };
let mut wrapper = ContentControl::new(ControlKind::RichText);
wrapper.tag = "source wrapper".into();
controls.open.push(wrapper);
controls.close = 1;
let expected = controls.clone();
copy(&mut s, source);
paste(&mut s);
let pasted = t0(&s).rows[1].cells[col]
.blocks
.iter()
.find_map(|b| b.as_table())
.unwrap_or_else(|| panic!("the wrapped source should nest (row wrapper: {on_row}, column: {col})"));
let controls = if on_row { &pasted.rows[0].controls } else { &pasted.controls };
assert_eq!(controls, &expected, "row wrapper: {on_row}, column: {col}");
}
}
}
#[test]
fn what_cannot_be_laid_over_the_cells_nests_as_before() {
let nests = |s: &mut Session| {
paste(s);
assert!(nested(t0(s)), "nested");
assert_eq!(t0(s).rows.len(), 3);
};
// Merged cells in the copy.
let mut merged = table("s", 2, 3);
merged.rows[0].cells[0].props.span = 2;
merged.rows[0].cells.remove(1);
let mut s = dest(1, 0);
copy(&mut s, merged);
nests(&mut s);
// Ragged rows in the copy.
let mut ragged = table("s", 2, 3);
ragged.rows[1].cells.pop();
let mut s = dest(1, 0);
copy(&mut s, ragged);
nests(&mut s);
// More columns than a table may have.
let mut s = dest(1, 2);
copy(&mut s, table("s", 1, 62));
nests(&mut s);
// A table inside a copied cell.
let mut inner = table("s", 1, 1);
inner.rows[0].cells[0].blocks = vec![Arc::new(Block::Table(table("n", 1, 1)))];
let mut s = dest(1, 0);
copy(&mut s, inner);
nests(&mut s);
// Merged cells in the destination.
let mut s = dest(1, 0);
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
t.rows[1].cells[0].props.span = 2;
t.rows[1].cells.remove(1);
}
copy(&mut s, table("s", 1, 1));
nests(&mut s);
// A copied cell without any block (hostile fragment): nothing to lay over the cell.
let mut hollow = table("s", 1, 1);
hollow.rows[0].cells[0].blocks.clear();
let mut s = dest(1, 0);
copy(&mut s, hollow);
let _ = s.run("edit.paste", &json!({}));
assert_eq!(t0(&s).rows.len(), 3, "nothing laid over the cells");
// A wider copy into a one-column table (a layout wrapper) nests instead of widening it.
let mut s = dest(1, 0);
s.doc.body[0] = Arc::new(Block::Table(table("w", 3, 1)));
copy(&mut s, table("s", 2, 3));
paste(&mut s);
assert!(nested(t0(&s)));
assert_eq!(t0(&s).grid.len(), 1);
// A content control in a cell the copy would overwrite.
let mut s = dest(1, 0);
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
t.rows[2].cells[0].controls.close = 1;
}
copy(&mut s, table("s", 3, 1));
nests(&mut s);
// Row exceptions on the destination.
let mut s = dest(1, 0);
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
t.rows[0].props.exceptions = Some(Default::default());
}
copy(&mut s, table("s", 1, 1));
nests(&mut s);
// Track Changes on.
let mut s = dest(1, 0);
s.doc.settings.track_changes = true;
copy(&mut s, table("s", 3, 3));
nests(&mut s);
}
#[test]
fn hostile_shapes_never_panic() {
// An empty table, a table with empty rows, 30,000 columns and 30,000 rows in a copy.
let mut wide = table("s", 1, 1);
wide.grid = vec![1.0; 30_000];
wide.rows[0].cells = (0..30_000).map(|_| Cell::empty()).collect();
let mut tall = table("s", 1, 2);
tall.rows = (0..30_000).map(|_| tall.rows[0].clone()).collect();
let mut no_rows = table("s", 1, 1);
no_rows.rows.clear();
let mut no_cells = table("s", 1, 1);
no_cells.rows[0].cells.clear();
// 30,000 columns and empty tables can't be laid over the cells: they nest (the old path).
for t in [wide, no_rows, no_cells] {
for (r, c) in [(0, 0), (2, 2)] {
let mut s = dest(r, c);
copy(&mut s, t.clone());
let _ = s.run("edit.paste", &json!({}));
assert_eq!((t0(&s).rows.len(), t0(&s).grid.len()), (3, 3), "unchanged table");
}
}
// 30,000 rows are laid over the cells: rows are added up to the limit, never past it.
for (r, c) in [(0, 0), (2, 1)] {
let mut s = dest(r, c);
copy(&mut s, tall.clone());
s.run("edit.paste", &json!({})).unwrap();
assert_eq!(t0(&s).rows.len(), r + 30_000);
assert!(t0(&s).rows.iter().all(|row| row.cells.len() == t0(&s).grid.len()));
}
// More rows than a table may have nest instead.
let mut huge = table("s", 1, 2);
huge.rows = (0..wordcraft_doc::table::MAX_ROWS).map(|_| huge.rows[0].clone()).collect();
let mut s = dest(1, 1);
copy(&mut s, huge);
let _ = s.run("edit.paste", &json!({}));
assert_eq!(t0(&s).rows.len(), 3);
// A caret path that is not a cell of the table.
let mut s = dest(0, 0);
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 9, 9, 0]), 0));
copy(&mut s, table("s", 1, 1));
let _ = s.run("edit.paste", &json!({}));
assert_eq!(t0(&s).rows.len(), 3);
}
#[test]
fn a_copied_table_with_empty_paragraphs_around_it_is_laid_over_the_cells_too() {
let mut s = dest(1, 0);
s.clipboard = Some(Fragment {
blocks: vec![Block::Para(Paragraph::new()), Block::Table(table("s", 1, 3)), Block::Para(Paragraph::new())],
..Default::default()
});
paste(&mut s);
assert_eq!(grid(t0(&s)), rows(&["d11,d12,d13", "s11,s12,s13", "d21,d22,d23", "d31,d32,d33"]));
}
#[test]
fn undo_takes_the_paste_back_in_one_step_and_redo_does_it_again() {
for (row, col) in [(1, 0), (1, 2)] {
let mut s = dest(row, col);
let before = t0(&s).clone();
copy(&mut s, table("s", 3, 3));
paste(&mut s);
let after = t0(&s).clone();
assert_ne!(after, before);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(t0(&s), &before, "one undo restores the table ({row}, {col})");
s.run("edit.redo", &json!({})).unwrap();
assert_eq!(t0(&s), &after);
}
}
#[test]
fn the_pasted_rows_survive_saving_and_reopening_as_docx() {
let mut s = dest(1, 0);
copy(&mut s, table("s", 3, 3));
paste(&mut s);
let bytes = crate::io::save_bytes("t.docx", &s.doc).unwrap();
let back = crate::io::open_bytes("t.docx", &bytes).unwrap();
let t = back.body.iter().find_map(|b| b.as_table()).expect("a table");
assert_eq!(grid(t), grid(t0(&s)));
let mut s = dest(1, 2);
copy(&mut s, table("s", 3, 3));
paste(&mut s);
let back = crate::io::open_bytes("t.docx", &crate::io::save_bytes("t.docx", &s.doc).unwrap()).unwrap();
let t = back.body.iter().find_map(|b| b.as_table()).expect("a table");
assert_eq!((t.rows.len(), t.grid.len()), (4, 5));
assert_eq!(grid(t), grid(t0(&s)));
}
#[test]
fn a_paste_into_a_cell_of_a_table_inside_a_cell_works_on_that_table() {
let mut inner_host = table("o", 1, 1);
inner_host.rows[0].cells[0].blocks = vec![Arc::new(Block::Table(table("d", 3, 3))), para_block(Paragraph::new())];
let mut d = Document::new();
d.body = vec![Arc::new(Block::Table(inner_host)), para_block(Paragraph::new())];
let mut s = Session::new(d);
// Body table 0, row 0, cell 0, its block 0 (the inner table), row 1, cell 0, block 0.
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0, 1, 0, 0]), 0));
copy(&mut s, table("s", 3, 3));
paste(&mut s);
let inner = t0(&s).rows[0].cells[0].blocks[0].as_table().expect("the inner table").clone();
assert_eq!(grid(&inner).len(), 6);
assert!(!nested(&inner));
}
/// A locked control in a table nested in a cell the copy would overwrite is not deleted: the
/// paste nests instead (#6739 review).
#[test]
fn a_locked_control_in_a_nested_table_of_an_overwritten_cell_is_kept() {
use wordcraft_doc::{ContentControl, ControlKind, ControlLock};
let mut s = dest(0, 0);
let mut inner = table("n", 1, 1);
let mut ctl = ContentControl::new(ControlKind::RichText);
ctl.lock = ControlLock::SdtContentLocked;
inner.rows[0].cells[0].controls.open.push(ctl);
inner.rows[0].cells[0].controls.close = 1;
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
t.rows[1].cells[0].blocks = vec![Arc::new(Block::Table(inner)), para_block(Paragraph::new())];
}
let before = t0(&s).rows[1].cells[0].clone();
// Copy one cell, caret above the cell with the nested table: it would be overwritten.
copy(&mut s, table("s", 2, 1));
paste(&mut s);
let kept = |t: &Table| t.rows.iter().flat_map(|r| &r.cells).any(|c| c.blocks == before.blocks);
assert!(kept(t0(&s)), "the cell with the locked control survives");
}
/// A caret in a control that shows its placeholder: no rows are inserted above the caret's row;
/// the table nests in the cell as the ordinary paste does (#6739 review).
#[test]
fn a_control_showing_its_placeholder_gets_the_ordinary_paste_not_inserted_rows() {
let mut s = dest(1, 0);
s.run("developer.plainText", &json!({})).unwrap();
let before = s.doc.body[0].as_table().map(|t| t.rows.len());
copy(&mut s, table("s", 3, 3));
paste(&mut s);
assert_eq!(t0(&s).rows.len(), before.unwrap_or(0), "no rows inserted above the caret's row");
assert!(nested(t0(&s)), "the table nests in the cell");
}
#[test]
fn paste_from_before_a_block_control_replaces_its_placeholder() {
let mut s = dest(1, 0);
let start = s.sel.focus.clone();
s.run("developer.plainText", &json!({})).unwrap();
let range = s.doc.control_at(&s.sel.focus).unwrap();
assert_eq!(range.start, start);
assert!(range.control.showing_placeholder);
let placeholder = s.doc.para_at(&start).unwrap().text[range.content_start().off..range.end.off].to_owned();
assert!(!placeholder.is_empty());
s.doc.control_mut(&start).unwrap().block = true;
s.sel = Selection::caret(start);
copy(&mut s, table("s", 1, 3));
paste(&mut s);
assert_eq!(t0(&s).rows.len(), 3);
assert!(nested(t0(&s)));
assert!(!cell_text(&t0(&s).rows[1].cells[0]).contains(&placeholder));
}
/// A locked control in a text box anchored in a cell the copy would overwrite is not lost: the
/// paste nests instead (#6739 review).
#[test]
fn a_locked_control_in_a_text_box_of_an_overwritten_cell_is_kept() {
use wordcraft_doc::para::ShapeKind;
use wordcraft_doc::{ContentControl, ControlKind, ControlLock, InlineObject, PartKind};
let mut s = dest(0, 0);
let mut ctl = ContentControl::new(ControlKind::RichText);
ctl.lock = ControlLock::SdtContentLocked;
let mut inner = Paragraph::with_text("Locked", Default::default());
inner.insert_object(0, InlineObject::ControlStart { control: Box::new(ctl) }, &Default::default()).unwrap();
let end = inner.text.chars().count();
inner.insert_object(end, InlineObject::ControlEnd, &Default::default()).unwrap();
let id = s.doc.add_part(PartKind::TextBox, vec![para_block(inner)]);
let shape = InlineObject::Shape {
kind: ShapeKind::TextBox,
w: 72.0,
h: 36.0,
fill: None,
stroke: None,
stroke_width: 0.75,
float: Default::default(),
story: Some(id),
freeform: None,
effects: Default::default(),
extra: Default::default(),
};
let mut anchor = Paragraph::with_text("Box", Default::default());
anchor.insert_object(0, shape, &Default::default()).unwrap();
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
t.rows[1].cells[0].blocks = vec![para_block(anchor)];
}
let before = t0(&s).rows[1].cells[0].blocks.clone();
// One column of two cells from the caret in the top cell: the cell with the box is overwritten.
copy(&mut s, table("s", 2, 1));
paste(&mut s);
let kept = |t: &Table| t.rows.iter().flat_map(|r| &r.cells).any(|c| c.blocks == before);
assert!(kept(t0(&s)), "the cell anchoring the text box survives");
assert!(nested(t0(&s)), "the table nests in the cell instead");
}
/// A row-level content control on a row the copy would overwrite is not bypassed: the paste nests
/// instead (#6739 review).
#[test]
fn a_row_level_control_on_an_overwritten_row_declines_the_overwrite() {
use wordcraft_doc::{ContentControl, ControlKind, ControlLock};
let mut s = dest(0, 0);
let mut ctl = ContentControl::new(ControlKind::RichText);
ctl.lock = ControlLock::SdtContentLocked;
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
t.rows[1].controls.open.push(ctl);
t.rows[1].controls.close = 1;
}
let before = grid(t0(&s));
copy(&mut s, table("s", 2, 1));
paste(&mut s);
assert_eq!(grid(t0(&s))[1], before[1], "the row under the control is not overwritten");
assert!(nested(t0(&s)), "the table nests in the cell instead");
}
#[test]
fn an_overwrite_inside_a_spanning_row_control_preserves_the_row() {
use wordcraft_doc::{ContentControl, ControlKind, ControlLock};
let mut s = dest(1, 1);
let mut control = ContentControl::new(ControlKind::RichText);
control.lock = ControlLock::SdtContentLocked;
let destination = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
destination.rows[0].controls.open.push(control);
destination.rows[2].controls.close = 1;
copy(&mut s, table("s", 1, 1));
paste(&mut s);
let table = t0(&s);
let cell = &table.rows[1].cells[1];
assert!(cell_text(cell).lines().any(|line| line == "d22"));
assert!(cell.blocks.iter().any(|block| block.as_table().is_some()));
assert_eq!(table.rows[0].controls.open[0].lock, ControlLock::SdtContentLocked);
assert_eq!(table.rows[2].controls.close, 1);
}
+2 -18
View File
@@ -30,7 +30,7 @@ pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled};
use fallback_data::{Coverage, RUN_FALLBACK_CACHE_CHARS, SYS_FALLBACK_MAX_FILE, file_coverage, ranges_hold};
#[cfg(not(target_arch = "wasm32"))]
use fallback_data::{CoverageIndex, SysFallback};
use fallback_data::{DiagramFallbackCache, FallbackCache, RunFallbackCache};
use fallback_data::{FallbackCache, RunFallbackCache};
#[cfg(not(target_arch = "wasm32"))]
use names::CatalogEntry;
pub use names::{LocalName, base_style, name_language_matches, system_font_dirs};
@@ -56,13 +56,6 @@ pub struct FontDb {
/// (Thai, #59) got slower with every font loaded.
fallbacks: RwLock<FallbackCache>,
run_fallbacks: RwLock<RunFallbackCache>,
diagram_fallbacks: RwLock<DiagramFallbackCache>,
#[cfg(test)]
diagram_searches: std::sync::atomic::AtomicU64,
#[cfg(test)]
diagram_search_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
#[cfg(test)]
diagram_publish_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
#[cfg(not(target_arch = "wasm32"))]
catalog: RwLock<Vec<CatalogEntry>>,
/// Fonts the user added at run time, and the folder they are stored in (#582).
@@ -126,13 +119,6 @@ impl FontDb {
hinters: Mutex::new(HashMap::new()),
fallbacks: RwLock::new(FallbackCache::default()),
run_fallbacks: RwLock::new(RunFallbackCache::default()),
diagram_fallbacks: RwLock::new(DiagramFallbackCache::default()),
#[cfg(test)]
diagram_searches: std::sync::atomic::AtomicU64::new(0),
#[cfg(test)]
diagram_search_hook: Mutex::new(None),
#[cfg(test)]
diagram_publish_hook: Mutex::new(None),
#[cfg(not(target_arch = "wasm32"))]
catalog: RwLock::new(Vec::new()),
user: RwLock::new(user::UserFonts::default()),
@@ -161,10 +147,8 @@ impl FontDb {
self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled = on;
}
// Misses remembered while it was off may be found now.
self.generation.fetch_add(1, Ordering::AcqRel);
*self.fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner) = FallbackCache::default();
self.fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner).map.clear();
*self.run_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner) = RunFallbackCache::default();
*self.diagram_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner) = DiagramFallbackCache::default();
#[cfg(target_arch = "wasm32")]
let _ = on;
}
-171
View File
@@ -396,147 +396,6 @@ impl FontFace {
pub fn is_east_asian(&self) -> bool {
self.skrifa().is_some_and(|f| east_asian_font(&f))
}
/// Is this a serif face? Checks family name conventions (e.g. Mincho, Song, Times vs Sans, Gothic, Arial),
/// falling back to the OS/2 family class and Panose serif style.
pub fn is_serif(&self) -> bool {
if is_explicit_sans(&self.family) {
return false;
}
if is_explicit_serif(&self.family) {
return true;
}
use skrifa::raw::TableProvider;
if let Some(sk) = self.skrifa()
&& let Ok(os2) = sk.os2()
{
let class_id = (os2.s_family_class() >> 8) as u8;
if (1..=5).contains(&class_id) || class_id == 7 {
return true;
}
if class_id == 8 {
return false;
}
let panose = os2.panose_10();
if panose[0] == 2 {
let serif_style = panose[1];
if (2..=10).contains(&serif_style) {
return true;
}
if (11..=15).contains(&serif_style) {
return false;
}
}
}
false
}
}
/// Tokens identifying known sans-serif font families by naming convention (#5672).
const SANS_TOKENS: &[&str] = &[
"sans",
"gothic",
"hei",
"yahei",
"simhei",
"zenhei",
"heiti",
"meiryo",
"pingfang",
"dotum",
"gulim",
"malgun",
"arial",
"calibri",
"aptos",
"carlito",
"inter",
"helvetica",
"segoe",
"tahoma",
"verdana",
];
/// Tokens identifying known serif font families by naming convention (#5672).
const SERIF_TOKENS: &[&str] = &[
"serif",
"mincho",
"song",
"songti",
"simsun",
"nsimsun",
"fangsong",
"ming",
"mingti",
"batang",
"sun",
"times",
"cambria",
"georgia",
"garamond",
"palatino",
"century",
"bookman",
"baskerville",
"caladea",
"tinos",
];
/// Split a font family name into lowercased tokens along non-alphanumeric boundaries,
/// camelCase / acronym transitions, and letter-to-digit/digit-to-letter boundaries (#5672).
fn font_name_tokens(name: &str) -> Vec<String> {
let mut tokens = Vec::new();
let mut current = String::new();
let mut prev_char: Option<char> = None;
let mut chars = name.chars().peekable();
while let Some(c) = chars.next() {
if !c.is_alphanumeric() {
if !current.is_empty() {
tokens.push(std::mem::take(&mut current).to_ascii_lowercase());
}
prev_char = None;
continue;
}
let next_lower = chars.peek().is_some_and(|n| n.is_lowercase());
let is_split = if let Some(prev) = prev_char {
(prev.is_lowercase() && c.is_uppercase())
|| (prev.is_uppercase() && c.is_uppercase() && next_lower)
|| (prev.is_alphabetic() && c.is_numeric())
|| (prev.is_numeric() && c.is_alphabetic())
} else {
false
};
if is_split && !current.is_empty() {
tokens.push(std::mem::take(&mut current).to_ascii_lowercase());
}
current.push(c);
prev_char = Some(c);
}
if !current.is_empty() {
tokens.push(current.to_ascii_lowercase());
}
let flattened: String = name.chars().filter(|c| c.is_alphanumeric()).collect::<String>().to_ascii_lowercase();
if !flattened.is_empty() && !tokens.iter().any(|t| t == &flattened) {
tokens.push(flattened);
}
tokens
}
/// Does a family name explicitly identify a sans-serif font by whole tokens?
fn is_explicit_sans(name: &str) -> bool {
let tokens = font_name_tokens(name);
tokens.iter().any(|t| SANS_TOKENS.contains(&t.as_str()))
}
/// Does a family name explicitly identify a serif font by whole tokens?
fn is_explicit_serif(name: &str) -> bool {
let tokens = font_name_tokens(name);
tokens.iter().any(|t| SERIF_TOKENS.contains(&t.as_str()))
}
pub(super) static NEXT_ID: AtomicU32 = AtomicU32::new(1);
@@ -601,33 +460,3 @@ impl OutlinePen for FlipPen {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn whole_token_serif_sans_matching() {
// #5672: Whole tokens match rather than bare substrings ("hei", "sun").
assert!(!is_explicit_sans("Heisei Mincho"), "Heisei Mincho must not match sans 'hei'");
assert!(is_explicit_serif("Heisei Mincho"), "Heisei Mincho is serif");
assert!(!is_explicit_serif("Sunflower"), "Sunflower must not match serif 'sun'");
assert!(!is_explicit_sans("Sunflower"));
assert!(is_explicit_sans("SimHei"));
assert!(is_explicit_sans("STHeiti"));
assert!(is_explicit_sans("BIZ UDPGothic"));
assert!(is_explicit_sans("MS PGothic"));
assert!(is_explicit_sans("Microsoft YaHei"));
assert!(is_explicit_sans("WenQuanYi Zen Hei"));
assert!(is_explicit_sans("Source Sans 3"));
assert!(is_explicit_serif("SimSun"));
assert!(is_explicit_serif("NSimSun"));
assert!(is_explicit_serif("BIZ UDPMincho"));
assert!(is_explicit_serif("MS PMincho"));
assert!(is_explicit_serif("Shippori Mincho"));
assert!(is_explicit_serif("Source Serif 4"));
}
}
+21 -195
View File
@@ -1,9 +1,7 @@
use super::face::{FALLBACK_FAMILY, FontFace};
#[cfg(not(target_arch = "wasm32"))]
use super::fallback_data::{CoverageIndex, IndexedFile, SYS_MISSES_MAX, SYSTEM_FALLBACKS, file_stamp, ranges_hold, read_fallback_file};
use super::fallback_data::{
DiagramFallbackKey, FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block, fallback_order,
};
use super::fallback_data::{FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block, fallback_order};
use super::{Arc, FontDb};
#[cfg(not(target_arch = "wasm32"))]
use super::{HashMap, Ordering};
@@ -31,35 +29,28 @@ impl FontDb {
Some(if styled.family.eq_ignore_ascii_case(&base.family) && styled.covers(c) && styled.id != exclude { styled } else { base })
}
/// The fallback search, cached per (character, excluded face) until loaded faces or font
/// generation change.
/// The fallback search, cached per (character, excluded face) until more faces load.
fn cached_fallback(&self, c: char, exclude: u32) -> Option<Arc<FontFace>> {
let generation = self.generation();
let n = self.read_faces().len();
{
let cache = self.fallbacks.read().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.faces == n
&& cache.generation == generation
&& let Some(hit) = cache.map.get(&(c, exclude))
{
return hit.clone();
}
}
let (found, n) = self.search_fallback(c, exclude);
// Keyed by the face count and generation the answer was chosen from (a system fallback may
// have loaded fonts, and another thread may have loaded or changed fonts since: an answer
// from before that change is returned but not cached under the new state).
if n != self.read_faces().len() || generation != self.generation() {
// Keyed by the face count the answer was chosen from (a system fallback may have loaded
// fonts, and another thread may have loaded more since: an answer from before that load
// is returned but not cached under the new count).
if n != self.read_faces().len() {
return found;
}
let mut cache = self.fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner);
if n != self.read_faces().len() || generation != self.generation() {
return found;
}
if cache.faces != n || cache.generation != generation || cache.map.len() >= FALLBACK_CACHE_MAX {
if cache.faces != n || cache.map.len() >= FALLBACK_CACHE_MAX {
cache.map.clear();
cache.faces = n;
cache.generation = generation;
}
cache.map.insert((c, exclude), found.clone());
found
@@ -160,36 +151,23 @@ impl FontDb {
set.sort_unstable();
set.dedup();
let key = (set, exclude, bold, italic);
let generation = self.generation();
let n = self.read_faces().len();
{
let cache = self.run_fallbacks.read().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.faces == n
&& cache.generation == generation
&& let Some(hit) = cache.map.get(&key)
{
return hit.clone();
}
}
// Keyed by the face count and generation the search last looked at, not the state after it:
// a face loaded or changed meanwhile by another thread (one its search, a family named by a
// document, or a user font change) must not be overwritten with a stale answer.
// Keyed by the face count the search last looked at, not the count after it: a face loaded
// meanwhile by another thread (one its search, or a family named by a document) must make
// a miss count as stale, not as the answer for the new count.
let (found, n) = self.search_run(&key.0, exclude, bold, italic);
if n != self.read_faces().len() || generation != self.generation() {
return found;
}
let mut cache = self.run_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner);
if n != self.read_faces().len() || generation != self.generation() {
return found;
}
if cache.faces != n
|| cache.generation != generation
|| cache.map.len() >= RUN_FALLBACK_CACHE_MAX
|| cache.chars.saturating_add(key.0.len()) > RUN_FALLBACK_CACHE_CHARS
{
if cache.faces != n || cache.map.len() >= RUN_FALLBACK_CACHE_MAX || cache.chars.saturating_add(key.0.len()) > RUN_FALLBACK_CACHE_CHARS {
cache.map.clear();
cache.faces = n;
cache.generation = generation;
cache.chars = 0;
}
cache.chars = cache.chars.saturating_add(key.0.len());
@@ -235,11 +213,7 @@ impl FontDb {
(true, false) => "Bold",
_ => "Italic",
};
let before_style = self.read_faces().len();
let styled = self.face(&base.family, style);
if before_style == checked {
checked = self.read_faces().len();
}
let face = if styled.family.eq_ignore_ascii_case(&base.family) && chars.iter().all(|c| styled.covers(*c)) && styled.id != exclude {
styled
} else {
@@ -260,140 +234,11 @@ impl FontDb {
(found, faces.len())
}
/// First face covering all characters in `chars`, preferring faces matching `prefer_serif`
/// (so a diagram maintains a consistent fallback face across its nodes matching the
/// diagram's primary style, #5672). Does not alter body text fallback ordering. Cached until
/// the loaded faces or font database generation changes, so page redraws do not repeat system scans.
pub fn fallback_for_diagram(&self, chars: &[char], exclude: u32, prefer_serif: bool) -> Option<Arc<FontFace>> {
if chars.is_empty() {
return None;
}
let mut set: Vec<char> = chars.to_vec();
set.sort_unstable();
set.dedup();
let key: DiagramFallbackKey = (set, exclude, prefer_serif);
let generation = self.generation();
let n = self.read_faces().len();
{
let cache = self.diagram_fallbacks.read().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.faces == n
&& cache.generation == generation
&& let Some(hit) = cache.map.get(&key)
{
return hit.clone();
}
}
// Keyed by the face count and generation the search last looked at, not the state after it:
// a face loaded or added meanwhile (for instance via `add_font`) must not be shadowed by
// caching an older answer under the newer face count.
let (found, n) = self.search_diagram(&key.0, exclude, prefer_serif);
if n != self.read_faces().len() || generation != self.generation() || key.0.len() > RUN_FALLBACK_CACHE_CHARS {
return found;
}
#[cfg(test)]
if let Some(hook) = self.diagram_publish_hook.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() {
hook(self);
}
let mut cache = self.diagram_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner);
if n != self.read_faces().len() || generation != self.generation() {
return found;
}
if cache.faces != n
|| cache.generation != generation
|| cache.map.len() >= RUN_FALLBACK_CACHE_MAX
|| cache.chars.saturating_add(key.0.len()) > RUN_FALLBACK_CACHE_CHARS
{
cache.map.clear();
cache.faces = n;
cache.generation = generation;
cache.chars = 0;
}
cache.chars = cache.chars.saturating_add(key.0.len());
cache.map.insert(key, found.clone());
found
}
/// The face covering a diagram's missing character set, and the face count it was chosen from.
/// Prefers faces matching `prefer_serif`; when the best loaded face has a mismatched serif
/// classification, checks system font candidates and retains the loaded face only when no
/// matching candidate covers the full set (#5672).
fn search_diagram(&self, chars: &[char], exclude: u32, prefer_serif: bool) -> (Option<Arc<FontFace>>, usize) {
#[cfg(test)]
self.diagram_searches.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
#[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
let (mut base, mut checked) = self.loaded_diagram_covering(chars, exclude, prefer_serif);
#[cfg(not(target_arch = "wasm32"))]
if base.is_none() || base.as_ref().is_some_and(|f| f.is_serif() != prefer_serif) {
for c in chars {
if self.read_faces().iter().any(|f| f.id != exclude && f.covers(*c) && f.is_serif() == prefer_serif) {
continue;
}
if self.system_fallback_matching(*c, Some((exclude, prefer_serif))) {
let (cand, cand_checked) = self.loaded_diagram_covering(chars, exclude, prefer_serif);
let matching = cand.as_ref().is_some_and(|f| f.is_serif() == prefer_serif);
if let Some(f) = cand {
base = Some(f);
checked = cand_checked;
} else if base.is_none() {
checked = cand_checked;
}
if matching {
break;
}
}
}
if base.as_ref().is_none_or(|f| f.is_serif() != prefer_serif) {
self.indexed_run_fallback_matching(chars, Some((exclude, prefer_serif)));
let (cand, cand_checked) = self.loaded_diagram_covering(chars, exclude, prefer_serif);
if let Some(f) = cand {
base = Some(f);
checked = cand_checked;
} else if base.is_none() {
checked = cand_checked;
}
}
}
#[cfg(test)]
if let Some(hook) = self.diagram_search_hook.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() {
hook(self);
}
(base, checked)
}
/// The first face covering every char in `chars`, preferring matching `prefer_serif`,
/// and the number of loaded faces it was chosen from.
fn loaded_diagram_covering(&self, chars: &[char], exclude: u32, prefer_serif: bool) -> (Option<Arc<FontFace>>, usize) {
let faces = self.read_faces();
let rtl = chars.iter().any(|c| crate::is_rtl(*c) || arabic_block(*c));
let complex = chars.iter().copied().find(|c| crate::needs_layout_tables(*c));
let mut candidates: Vec<&Arc<FontFace>> = faces.iter().filter(|f| f.id != exclude && chars.iter().all(|c| f.covers(*c))).collect();
let rank = |f: &FontFace| {
if rtl { RTL_FALLBACKS.iter().position(|n| f.family.eq_ignore_ascii_case(n)).unwrap_or(RTL_FALLBACKS.len()) } else { 0 }
};
let shaping = |f: &FontFace| match complex {
Some(c) => (!f.has_layout_tables(), crate::fallback_rank(c, &f.family)),
None => (false, 0),
};
let serif_mismatch = |f: &FontFace| f.is_serif() != prefer_serif;
candidates.sort_by_cached_key(|f| {
(rank(f), shaping(f), serif_mismatch(f), !f.family.eq_ignore_ascii_case(FALLBACK_FAMILY), f.italic, (f.weight - 400.0).abs() as i32)
});
(candidates.first().map(|f| (*f).clone()), faces.len())
}
/// Load a system font covering `c` (preferred fallback families first, then any cataloged
/// file under 40 MB, both found through the coverage index). Returns true if one was loaded.
/// Misses are remembered.
#[cfg(not(target_arch = "wasm32"))]
fn system_fallback(&self, c: char) -> bool {
self.system_fallback_matching(c, None)
}
/// Like [`Self::system_fallback`], optionally requiring the covering face to not be `exclude`
/// and to match `prefer_serif` (so a loaded mismatched face does not short-circuit the search
/// before a matching installed candidate is checked, #5672).
#[cfg(not(target_arch = "wasm32"))]
fn system_fallback_matching(&self, c: char, style: Option<(u32, bool)>) -> bool {
if c.is_control() || c.is_whitespace() {
return false;
}
@@ -403,9 +248,7 @@ impl FontDb {
return false;
}
}
let covered = |db: &FontDb| {
db.read_faces().iter().any(|f| f.covers(c) && style.is_none_or(|(exclude, prefer_serif)| f.id != exclude && f.is_serif() == prefer_serif))
};
let covered = |db: &FontDb| db.read_faces().iter().any(|f| f.covers(c));
let cataloged: Vec<String> = self.read_catalog().iter().map(|e| e.family.clone()).collect();
let rtl = crate::is_rtl(c) || arabic_block(c);
let preferred = RTL_FALLBACKS.iter().filter(|_| rtl);
@@ -427,20 +270,14 @@ impl FontDb {
return true;
}
}
if style.is_none() {
if self.indexed_fallback(c) {
return true;
}
} else if self.load_indexed_matching(&[c], false, style) {
if self.indexed_fallback(c) {
return true;
}
if style.is_none() || !self.read_faces().iter().any(|f| f.covers(c)) {
let mut sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if sys.misses.len() >= SYS_MISSES_MAX {
sys.misses.clear();
}
sys.misses.insert(c);
let mut sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if sys.misses.len() >= SYS_MISSES_MAX {
sys.misses.clear();
}
sys.misses.insert(c);
false
}
@@ -487,7 +324,7 @@ impl FontDb {
/// now covers `c`.
#[cfg(not(target_arch = "wasm32"))]
fn indexed_fallback(&self, c: char) -> bool {
self.load_indexed_matching(&[c], false, None)
self.load_indexed(&[c], false)
}
/// Load the family of the first cataloged font file (in path order) that maps every char of a
@@ -495,17 +332,10 @@ impl FontDb {
/// before the Regular.
#[cfg(not(target_arch = "wasm32"))]
fn indexed_run_fallback(&self, chars: &[char]) {
self.indexed_run_fallback_matching(chars, None);
}
/// Like [`Self::indexed_run_fallback`], optionally requiring a loaded face matching
/// `(exclude, prefer_serif)` to stop scanning (#5672).
#[cfg(not(target_arch = "wasm32"))]
fn indexed_run_fallback_matching(&self, chars: &[char], style: Option<(u32, bool)>) {
if !self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled || chars.iter().any(|c| c.is_control()) {
return;
}
self.load_indexed_matching(chars, true, style);
self.load_indexed(chars, true);
}
/// Load the cataloged font files (in path order) that map every char of `chars`, reading the
@@ -514,12 +344,8 @@ impl FontDb {
/// of it isn't loaded yet). A collection's faces only together may map them: the search then
/// goes on. Returns whether a loaded face now covers them all.
#[cfg(not(target_arch = "wasm32"))]
fn load_indexed_matching(&self, chars: &[char], whole_family: bool, style: Option<(u32, bool)>) -> bool {
let covered = |db: &FontDb| {
db.read_faces().iter().any(|f| {
style.is_none_or(|(exclude, prefer_serif)| f.id != exclude && f.is_serif() == prefer_serif) && chars.iter().all(|c| f.covers(*c))
})
};
fn load_indexed(&self, chars: &[char], whole_family: bool) -> bool {
let covered = |db: &FontDb| db.read_faces().iter().any(|f| chars.iter().all(|c| f.covers(*c)));
let cps: Vec<u32> = chars.iter().map(|c| u32::from(*c)).collect();
let maps_all = |ranges: &[(u32, u32)]| cps.iter().all(|cp| ranges_hold(ranges, *cp));
let mut index = self.coverage_index();
+1 -18
View File
@@ -281,7 +281,6 @@ pub(super) fn arabic_block(c: char) -> bool {
#[derive(Default)]
pub(super) struct FallbackCache {
pub(super) faces: usize,
pub(super) generation: u64,
pub(super) map: HashMap<(char, u32), Option<Arc<FontFace>>>,
}
@@ -289,31 +288,15 @@ pub(super) struct FallbackCache {
pub(super) type RunFallbackKey = (Vec<char>, u32, bool, bool);
/// [`FontDb::fallback_for_run`] results: (sorted, deduplicated chars, excluded face, bold,
/// italic) → face, valid while the loaded face count is `faces` and [`FontDb::generation`] is
/// `generation`.
/// italic) → face, valid while the loaded face count is `faces`.
#[derive(Default)]
pub(super) struct RunFallbackCache {
pub(super) faces: usize,
pub(super) generation: u64,
/// Chars held in the keys (bounds memory: hostile runs can be long).
pub(super) chars: usize,
pub(super) map: HashMap<RunFallbackKey, Option<Arc<FontFace>>>,
}
/// What a diagram-level fallback lookup is keyed by: sorted, deduplicated chars, excluded face,
/// serif preference.
pub(super) type DiagramFallbackKey = (Vec<char>, u32, bool);
/// [`FontDb::fallback_for_diagram`] results, valid while the loaded face count and generation match.
#[derive(Default)]
pub(super) struct DiagramFallbackCache {
pub(super) faces: usize,
pub(super) generation: u64,
/// Chars held in the keys (bounds memory: diagram text can be long).
pub(super) chars: usize,
pub(super) map: HashMap<DiagramFallbackKey, Option<Arc<FontFace>>>,
}
/// Most cached run-level fallbacks, and most chars in their keys, before the cache is reset.
pub(super) const RUN_FALLBACK_CACHE_MAX: usize = 4096;
-199
View File
@@ -893,202 +893,3 @@ fn catalog_postscript_names() {
assert!(!has(&db.families(), "SysfontSans-Bold"));
std::fs::remove_dir_all(dir).unwrap();
}
/// Diagram fallback matches the primary font's serif/sans classification while body-text
/// fallback preserves loaded order (#5672), and changing user fonts invalidates run fallbacks.
#[test]
fn fallback_order_matches_primary_font_serif_nature() {
// #5672: When picking fallback faces for diagrams, sans-serif primary fonts prefer sans-serif
// fallback fonts, and serif primary fonts prefer serif fallback fonts. Body text fallback
// order remains unaffected.
use crate::fontdb::fallback_data::fallback_order;
let dir = font_dir("serif-sans-fallback");
std::fs::write(dir.join("TestMincho.ttf"), mapping("SourceSans3-Regular.ttf", "Test Mincho 1", 0xF_0010, 0xF_0011)).unwrap();
std::fs::write(dir.join("TestGothic.ttf"), mapping("SourceSans3-Regular.ttf", "Test Gothic 1", 0xF_0010, 0xF_0011)).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
db.set_system_fallback(false);
let mincho = db.face("Test Mincho 1", "Regular");
let gothic = db.face("Test Gothic 1", "Regular");
assert!(mincho.is_serif(), "Mincho is serif");
assert!(!gothic.is_serif(), "Gothic is sans");
let sans_primary = db.face("Source Sans 3", "Regular");
let serif_primary = db.face("Source Serif 4", "Regular");
// Diagram fallback: matches serif/sans nature of primary font.
let diag_run = ['\u{F0010}', '\u{F0011}'];
let diag_sans = db.fallback_for_diagram(&diag_run, sans_primary.id(), sans_primary.is_serif()).unwrap();
assert_eq!(diag_sans.family, "Test Gothic 1", "sans-serif diagram prefers sans-serif fallback (Gothic)");
let diag_serif = db.fallback_for_diagram(&diag_run, serif_primary.id(), serif_primary.is_serif()).unwrap();
assert_eq!(diag_serif.family, "Test Mincho 1", "serif diagram prefers serif fallback (Mincho)");
// Body text fallback: fallback_order is not altered by the primary font's serif/sans nature.
let faces = db.read_faces();
let for_sans = fallback_order(&faces, sans_primary.id(), false, None);
let for_serif = fallback_order(&faces, serif_primary.id(), false, None);
let mincho_sans = for_sans.iter().position(|f| f.family == "Test Mincho 1").unwrap();
let gothic_sans = for_sans.iter().position(|f| f.family == "Test Gothic 1").unwrap();
let mincho_serif = for_serif.iter().position(|f| f.family == "Test Mincho 1").unwrap();
let gothic_serif = for_serif.iter().position(|f| f.family == "Test Gothic 1").unwrap();
assert_eq!(mincho_sans < gothic_sans, mincho_serif < gothic_serif, "body text fallback order does not invert between sans and serif primaries");
drop(faces);
// Replacing a user font with another of the same face count invalidates both fallbacks and run_fallbacks.
db.install_font("UserGothic.ttf", &mapping("SourceSans3-Regular.ttf", "User1 Gothic1", 0xF_0001, 0xF_0002)).unwrap();
let run = ['\u{F0001}', '\u{F0002}'];
let first_char = db.fallback_for('\u{F0001}', serif_primary.id()).unwrap();
assert_eq!(first_char.family, "User1 Gothic1");
assert_eq!(db.fallbacks.read().unwrap().generation, db.generation());
let first = db.fallback_for_run(&run, serif_primary.id(), false, false).unwrap();
assert_eq!(first.family, "User1 Gothic1");
let face_count = db.read_faces().len();
db.remove_user_font("User1 Gothic1").unwrap();
db.install_font("UserMincho.ttf", &mapping("SourceSans3-Regular.ttf", "User2 Mincho2", 0xF_0001, 0xF_0002)).unwrap();
assert_eq!(db.read_faces().len(), face_count);
let updated_char = db.fallback_for('\u{F0001}', serif_primary.id()).unwrap();
assert_eq!(updated_char.family, "User2 Mincho2");
assert_eq!(db.fallbacks.read().unwrap().generation, db.generation());
let updated = db.fallback_for_run(&run, serif_primary.id(), false, false).unwrap();
assert_eq!(updated.family, "User2 Mincho2");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn diagram_fallback_checks_system_fonts_when_loaded_face_mismatches_serif() {
let dir = font_dir("diag-mismatch");
let regular = "SourceSans3-Regular.ttf";
// Put a preferred non-covering family ("Malgun Gothic") and an alphabetically earlier serif
// font ("AA Sys Mincho") in the directory alongside the matching sans CJK candidate
// ("Sys Gothic 11"). Neither the non-covering preferred family nor the earlier serif font may
// short-circuit the search just because a mismatched loaded face already covers the chars.
std::fs::write(dir.join("00_MalgunGothic.ttf"), mapping(regular, "Malgun Gothic", 0x0041, 0x005A)).unwrap();
std::fs::write(dir.join("AA_SysMincho.ttf"), mapping(regular, "AA Sys Mincho", 0xF_0020, 0xF_0021)).unwrap();
std::fs::write(dir.join("SysGothic.ttf"), mapping(regular, "Sys Gothic 11", 0xF_0020, 0xF_0021)).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
// Pre-load a serif font covering the same characters into db as a document font.
db.add_document_fonts(vec![(mapping(regular, "Load Mincho 1", 0xF_0020, 0xF_0021), "Load Mincho 1".to_string())]);
let mincho = db.face("Load Mincho 1", "Regular");
assert!(mincho.is_serif());
// 1. Single-character sans-serif diagram: loaded face is serif (mismatched), so search_diagram
// must check past Malgun Gothic (non-covering preferred family) and AA Sys Mincho (earlier
// serif cataloged file) to find & load "Sys Gothic 11" (sans-serif).
let single = ['\u{F0020}'];
let sans = db.fallback_for_diagram(&single, 0, false).unwrap();
assert_eq!(sans.family, "Sys Gothic 11", "sans diagram checks system fonts to find matching sans candidate");
assert!(!sans.is_serif());
// 2. Multi-character run also resolves to the matching sans candidate.
let run = ['\u{F0020}', '\u{F0021}'];
let sans_run = db.fallback_for_diagram(&run, 0, false).unwrap();
assert_eq!(sans_run.family, "Sys Gothic 11");
// 3. When no matching candidate covers the run, retain the mismatched loaded face.
let uncataloged_run = ['\u{F0020}'];
let retained = db.fallback_for_diagram(&uncataloged_run, sans.id(), false).unwrap();
assert_eq!(retained.family, "Load Mincho 1", "retains loaded face when no matching candidate covers the run");
db.remove_document_fonts(&["Load Mincho 1"]);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn diagram_fallback_caches_a_mismatched_loaded_face_after_system_search() {
let dir = font_dir("diag-fallback-cache");
let regular = "SourceSans3-Regular.ttf";
std::fs::write(dir.join("CacheGothic.ttf"), mapping(regular, "Cache Gothic1", 0xF_0030, 0xF_0031)).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
db.add_document_fonts(vec![(mapping(regular, "Loaded Gothic", 0xF_0030, 0xF_0031), "Loaded Gothic".to_string())]);
let primary = db.face("Source Serif 4", "Regular");
let run = ['\u{F0030}', '\u{F0031}'];
let first = db.fallback_for_diagram(&run, primary.id(), true).unwrap();
assert_eq!(first.family, "Loaded Gothic", "retain the loaded mismatched face when no serif face covers the run");
let reads = db.coverage.lock().unwrap().reads;
assert!(reads > 0, "the initial search reaches the system-font coverage index");
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), 1);
assert_eq!(db.fallback_for_diagram(&run, primary.id(), true).unwrap().id(), first.id());
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), 1, "the redraw reuses the diagram fallback");
assert_eq!(db.coverage.lock().unwrap().reads, reads);
db.install_font("UserMincho.ttf", &mapping(regular, "User Mincho 1", 0xF_0030, 0xF_0031)).unwrap();
assert_eq!(db.fallback_for_diagram(&run, primary.id(), true).unwrap().family, "User Mincho 1");
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), 2, "adding a user font invalidates the cached result");
let face_count = db.read_faces().len();
db.remove_user_font("User Mincho 1").unwrap();
db.install_font("UserMincho.ttf", &mapping(regular, "User Mincho 2", 0xF_0030, 0xF_0031)).unwrap();
assert_eq!(db.read_faces().len(), face_count);
assert_eq!(db.fallback_for_diagram(&run, primary.id(), true).unwrap().family, "User Mincho 2");
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), 3, "generation invalidates the cache when face count stays unchanged");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn diagram_fallback_skips_stale_cache_publish_when_add_font_arrives_between_selection_and_publication() {
let dir = font_dir("diag-concurrent-add-font");
let regular = "SourceSans3-Regular.ttf";
let italic = "SourceSans3-It.ttf";
let db = FontDb::with_font_dirs(vec![dir.clone()]);
let primary = db.face("Source Sans 3", "Regular");
assert!(!primary.is_serif());
// 1. A matching sans face arrives via `add_font` (no generation bump) after `search_diagram`
// selects the loaded mismatched serif face and before `search_diagram` returns its count.
assert!(db.add_font(mapping(regular, "Load Mincho A", 0xF_0040, 0xF_0041)) > 0);
let arriving_a = mapping(regular, "New Gothic AA", 0xF_0040, 0xF_0041);
*db.diagram_search_hook.lock().unwrap() = Some(Box::new(move |db| {
assert!(db.add_font(arriving_a) > 0);
}));
let gen_before = db.generation();
let run_a = ['\u{F0040}', '\u{F0041}'];
let first_a = db.fallback_for_diagram(&run_a, primary.id(), false).unwrap();
assert_eq!(first_a.family, "Load Mincho A");
assert_eq!(db.generation(), gen_before, "add_font does not change generation");
assert_ne!(
db.diagram_fallbacks.read().unwrap().faces,
db.read_faces().len(),
"stale selection from before add_font must not be cached under the newer face count"
);
let second_a = db.fallback_for_diagram(&run_a, primary.id(), false).unwrap();
assert_eq!(second_a.family, "New Gothic AA", "subsequent lookup sees the newly added matching face");
assert_eq!(db.diagram_fallbacks.read().unwrap().faces, db.read_faces().len());
let searches_after_a = db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed);
assert_eq!(db.fallback_for_diagram(&run_a, primary.id(), false).unwrap().id(), second_a.id());
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), searches_after_a);
// 2. Fast-path match (no system search): an upright sans face arrives via `add_font` after
// `loaded_diagram_covering` picks an italic sans face and before `search_diagram` returns.
assert!(db.add_font(mapping(italic, "Load Gothic C", 0xF_0060, 0xF_0061)) > 0);
let arriving_c = mapping(regular, "New Gothic CC", 0xF_0060, 0xF_0061);
*db.diagram_search_hook.lock().unwrap() = Some(Box::new(move |db| {
assert!(db.add_font(arriving_c) > 0);
}));
let run_c = ['\u{F0060}', '\u{F0061}'];
let first_c = db.fallback_for_diagram(&run_c, primary.id(), false).unwrap();
assert_eq!(first_c.family, "Load Gothic C");
assert_eq!(db.generation(), gen_before);
assert_ne!(db.diagram_fallbacks.read().unwrap().faces, db.read_faces().len());
let second_c = db.fallback_for_diagram(&run_c, primary.id(), false).unwrap();
assert_eq!(second_c.family, "New Gothic CC", "fast-path selection also avoids caching under a newer face count");
// 3. A matching sans face arrives via `add_font` after `search_diagram` returns and before
// `diagram_fallbacks.write()` publishes the entry.
assert!(db.add_font(mapping(regular, "Load Mincho B", 0xF_0050, 0xF_0051)) > 0);
let arriving_b = mapping(regular, "New Gothic BB", 0xF_0050, 0xF_0051);
*db.diagram_publish_hook.lock().unwrap() = Some(Box::new(move |db| {
assert!(db.add_font(arriving_b) > 0);
}));
let run_b = ['\u{F0050}', '\u{F0051}'];
let first_b = db.fallback_for_diagram(&run_b, primary.id(), false).unwrap();
assert_eq!(first_b.family, "Load Mincho B");
assert_eq!(db.generation(), gen_before);
assert_ne!(db.diagram_fallbacks.read().unwrap().faces, db.read_faces().len());
let second_b = db.fallback_for_diagram(&run_b, primary.id(), false).unwrap();
assert_eq!(second_b.family, "New Gothic BB");
let _ = std::fs::remove_dir_all(dir);
}
+1 -18
View File
@@ -481,21 +481,6 @@ impl FontDb {
added
}
/// Remove document fonts added for `families`: their faces leave the font list
/// and cached fallback choices are forgotten ([`FontDb::generation`]).
#[cfg(any(test, feature = "test-support"))]
pub fn remove_document_fonts(&self, families: &[&str]) {
let ids: Vec<u32> = {
let faces = self.read_faces();
faces.iter().filter(|f| families.iter().any(|name| f.named(name))).map(|f| f.id).collect()
};
if ids.is_empty() {
return;
}
self.faces.write().unwrap_or_else(|e| e.into_inner()).retain(|f| !ids.contains(&f.id));
self.fonts_changed();
}
/// Check the faces in `sfnt` and add the new ones, recording them as a user font.
fn add_user_faces(&self, name: &str, sfnt: Vec<u8>, path: Option<PathBuf>) -> Result<UserFont, UserFontError> {
if self.read_user().fonts.len() >= MAX_USER_FONTS {
@@ -558,10 +543,8 @@ impl FontDb {
/// Forget cached fallback choices and tell watchers ([`FontDb::generation`]).
fn fonts_changed(&self) {
self.fallbacks.write().unwrap_or_else(|e| e.into_inner()).map.clear();
self.generation.fetch_add(1, Ordering::AcqRel);
*self.fallbacks.write().unwrap_or_else(|e| e.into_inner()) = super::FallbackCache::default();
*self.run_fallbacks.write().unwrap_or_else(|e| e.into_inner()) = super::RunFallbackCache::default();
*self.diagram_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner) = super::DiagramFallbackCache::default();
}
/// Remove the user fonts that added `family` (a typographic or legacy family name): their
-51
View File
@@ -1207,54 +1207,3 @@ fn latex_export_keeps_repeated_spaces() {
let d = crate::import("tex", tex.as_bytes()).unwrap().unwrap();
assert_eq!(para_texts(&d), vec!["a b c".to_string()]);
}
/// Container `background-color` imports and round-trips as paragraph shading (including mixed
/// inline highlights and blank lines), while inline `<span style="background-color:...">` and
/// `<mark>` highlights remain character shading (#6157).
#[test]
fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_runs() {
let html = concat!(
r#"<div style="background-color:#1e1e1e"><p><span style="color:#569cd6">const</span> x = 1;</p></div>"#,
r#"<p><span style="background-color:#ffff00">highlighted</span></p>"#,
r#"<p><mark>marked</mark></p>"#,
r#"<div style="background-color:#1e1e1e"><p>text <code style="background-color:#eeeeee">x</code></p></div>"#,
r#"<div style="background-color:#1e1e1e"><div>a</div><div>&nbsp;</div><div>b</div></div>"#,
);
let doc = crate::html::import(html);
assert_eq!(doc.body.len(), 7);
let Block::Para(code) = &*doc.body[0] else { panic!("expected code paragraph") };
assert_eq!(code.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
assert!(code.runs.iter().all(|r| r.props.shading.is_none()), "container background must not leak to runs");
let Block::Para(span_hl) = &*doc.body[1] else { panic!("expected highlighted paragraph") };
assert_eq!(span_hl.props.shading, None, "inline span highlight must not become paragraph shading");
assert_eq!(span_hl.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)));
let Block::Para(mark_hl) = &*doc.body[2] else { panic!("expected mark paragraph") };
assert_eq!(mark_hl.props.shading, None, "inline <mark> must not become paragraph shading");
assert_eq!(mark_hl.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)));
let Block::Para(mixed) = &*doc.body[3] else { panic!("expected mixed paragraph") };
assert_eq!(mixed.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
assert_eq!(mixed.props_of_char(0).shading, None, "unhighlighted text in shaded container has no run shading");
assert_eq!(mixed.props_of_char(5).shading, Some(wordcraft_doc::Rgb(0xee, 0xee, 0xee)), "inline <code> keeps its own run shading");
for idx in [4, 5, 6] {
let Block::Para(line) = &*doc.body[idx] else { panic!("expected block {idx}") };
assert_eq!(line.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "line {idx} (blank included) keeps container shading");
}
for exported in [crate::html::export(&doc), crate::html::export_fragment(&doc)] {
let back = crate::html::import(&exported);
let Block::Para(p0) = &*back.body[0] else { panic!("expected paragraph 0") };
let Block::Para(p1) = &*back.body[1] else { panic!("expected paragraph 1") };
let Block::Para(p2) = &*back.body[2] else { panic!("expected paragraph 2") };
assert_eq!(p0.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "{exported}");
assert!(p0.runs.iter().all(|r| r.props.shading.is_none()), "{exported}");
assert_eq!(p1.props.shading, None, "{exported}");
assert_eq!(p1.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)), "{exported}");
assert_eq!(p2.props.shading, None, "<p><mark>x</mark></p> round-trips as run shading: {exported}");
assert_eq!(p2.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)), "{exported}");
}
}
+11 -108
View File
@@ -10,63 +10,8 @@ pub(super) fn graphic_draws(doc: &Document, g: &Graphic, rect: Rect, alpha: f32)
let (sx, sy) = (scale_of(rect.w, g.w), scale_of(rect.h, g.h));
let k = (sx + sy) / 2.0;
let inside = |r: &[f32; 4]| Rect::new(rect.x + r[0] * sx, rect.y + r[1] * sy, r[2] * sx, r[3] * sy);
let joins = |c: char| c.is_whitespace() || wordcraft_doc::math_linear::is_combining(c);
let db = wordcraft_fonts::FontDb::global();
// A graphic (SmartArt diagram or chart) should maintain a consistent fallback font family
// across all its text nodes (#5672). Collect all characters across the graphic that each
// item's primary font lacks, and find one fallback face that covers them all (or, when
// unrelated symbols need another face, one fallback face that covers all missing East Asian
// characters). The serif/sans preference comes from the first text item with a missing
// character (or the first with a missing East Asian character on the East Asian-only retry),
// so mixed-style graphics follow that leading label's style across nodes.
let mut text_resolved: Vec<Option<wordcraft_fonts::word::Resolved>> = Vec::with_capacity(g.items.len());
let mut diagram_chars: Vec<char> = Vec::new();
let mut cjk_chars: Vec<char> = Vec::new();
let mut primary_face: Option<FaceRef> = None;
let mut cjk_primary_face: Option<FaceRef> = None;
for it in &g.items {
if let GraphicItem::Text { text, font, bold, .. } = it {
let family = font.as_deref().filter(|f| !f.is_empty()).unwrap_or(&doc.settings.minor_font);
let resolved = wordcraft_fonts::word::resolve(family, *bold, false);
let primary = resolved.face;
for c in text.chars() {
if !joins(c) && !primary.covers(c) {
if primary_face.is_none() {
primary_face = Some(primary);
}
diagram_chars.push(c);
if crate::para::is_east_asian(c) {
if cjk_primary_face.is_none() {
cjk_primary_face = Some(primary);
}
cjk_chars.push(c);
}
}
}
text_resolved.push(Some(resolved));
} else {
text_resolved.push(None);
}
}
let diagram_fallback = if !diagram_chars.is_empty() {
let prefer_serif = primary_face.is_some_and(|p| p.get().is_serif());
let exclude = primary_face.map_or(0, |p| p.id());
db.fallback_for_diagram(&diagram_chars, exclude, prefer_serif).or_else(|| {
if !cjk_chars.is_empty() {
let cjk_prefer_serif = cjk_primary_face.is_some_and(|p| p.get().is_serif());
let cjk_exclude = cjk_primary_face.map_or(0, |p| p.id());
db.fallback_for_diagram(&cjk_chars, cjk_exclude, cjk_prefer_serif)
} else {
None
}
})
} else {
None
};
let mut out = Vec::with_capacity(g.items.len());
for (i, it) in g.items.iter().enumerate() {
for it in &g.items {
match it {
GraphicItem::Shape { rect: r, kind, fill, stroke, stroke_width } => out.push(Draw::Shape {
rect: inside(r),
@@ -97,16 +42,12 @@ pub(super) fn graphic_draws(doc: &Document, g: &Graphic, rect: Rect, alpha: f32)
let (cx, cy) = (at.x + at.w / 2.0, at.y + at.h / 2.0);
let quarter = ((angle / 90.0).round() as i64).rem_euclid(2) == 1;
let level = if quarter { Rect::new(cx - at.h / 2.0, cy - at.w / 2.0, at.h, at.w) } else { at };
let resolved = text_resolved.get(i).copied().flatten();
let items = text_glyphs(doc, level, it, alpha, k, resolved, diagram_fallback.as_ref());
let items = text_glyphs(doc, level, it, alpha, k);
if !items.is_empty() {
out.push(Draw::Rotated { cx, cy, spin: Spin::new(*angle, false, false), items });
}
}
GraphicItem::Text { rect: r, .. } => {
let resolved = text_resolved.get(i).copied().flatten();
out.extend(text_glyphs(doc, inside(r), it, alpha, k, resolved, diagram_fallback.as_ref()));
}
GraphicItem::Text { rect: r, .. } => out.extend(text_glyphs(doc, inside(r), it, alpha, k)),
GraphicItem::Image { rect: r, media } => out.push(Draw::Image {
rect: inside(r),
media: media.clone(),
@@ -350,28 +291,18 @@ pub fn seg_path(segs: &[PathSeg]) -> BezPath {
/// in body text: one draw per run of a face, in reading order. Empty when there is nothing to draw,
/// or the item's rectangle or size isn't a finite number (a degenerate scale: `r` itself is always
/// finite, as [`Rect::new`] makes it).
fn text_glyphs(
doc: &Document,
r: Rect,
it: &GraphicItem,
alpha: f32,
k: f32,
resolved: Option<wordcraft_fonts::word::Resolved>,
diagram_fallback: Option<&std::sync::Arc<wordcraft_fonts::FontFace>>,
) -> Vec<Draw> {
fn text_glyphs(doc: &Document, r: Rect, it: &GraphicItem, alpha: f32, k: f32) -> Vec<Draw> {
let GraphicItem::Text { rect, text, size, color, bold, align, font, .. } = it else { return Vec::new() };
let size = *size * k;
if !rect.iter().chain([&size]).all(|v| v.is_finite()) {
return Vec::new();
}
let family = font.as_deref().filter(|f| !f.is_empty()).unwrap_or(&doc.settings.minor_font);
let size = size.clamp(1.0, 400.0);
let resolved = resolved.unwrap_or_else(|| {
let family = font.as_deref().filter(|f| !f.is_empty()).unwrap_or(&doc.settings.minor_font);
wordcraft_fonts::word::resolve(family, *bold, false)
});
let resolved = wordcraft_fonts::word::resolve(family, *bold, false);
let primary = resolved.face;
let scale = |f: FaceRef| size / f.upem.max(1.0) as f32;
let runs: Vec<_> = face_runs(text, primary, *bold, diagram_fallback)
let runs: Vec<_> = face_runs(text, primary, *bold)
.into_iter()
.map(|(face, s)| (face, s, wordcraft_fonts::shape(face.get(), s, &[], |c| c)))
.filter(|(_, _, shaped)| !shaped.is_empty())
@@ -418,12 +349,7 @@ fn text_glyphs(
/// fallback face. A run the primary lacks takes one face covering all of it when one does (so a
/// Chinese label doesn't mix serif and sans glyphs), else each character its own fallback. Spaces
/// and combining marks stay in the run before them; a character no face has stays in `primary`.
fn face_runs<'a>(
text: &'a str,
primary: FaceRef,
bold: bool,
diagram_fallback: Option<&std::sync::Arc<wordcraft_fonts::FontFace>>,
) -> Vec<(FaceRef, &'a str)> {
fn face_runs(text: &str, primary: FaceRef, bold: bool) -> Vec<(FaceRef, &str)> {
let joins = |c: char| c.is_whitespace() || wordcraft_doc::math_linear::is_combining(c);
// (start, end, drawn by `primary`)
let mut spans: Vec<(usize, usize, bool)> = Vec::new();
@@ -444,25 +370,7 @@ fn face_runs<'a>(
continue;
}
let chars: Vec<char> = s.chars().filter(|c| !joins(*c)).collect();
let df_face_for = |df: &std::sync::Arc<wordcraft_fonts::FontFace>, covered: &[char]| {
if bold {
let styled = db.face(&df.family, "Bold");
if styled.family.eq_ignore_ascii_case(&df.family) && covered.iter().all(|c| styled.covers(*c)) {
return FaceRef::of(&styled);
}
}
FaceRef::of(df)
};
// A single SmartArt or chart diagram maintains a consistent fallback face across its labels (#5672).
if let Some(df) = diagram_fallback
&& chars.iter().all(|c| df.covers(*c))
{
out.push((df_face_for(df, &chars), s));
continue;
}
if diagram_fallback.is_none_or(|df| !chars.iter().any(|c| df.covers(*c)))
&& let Some(f) = db.fallback_for_run(&chars, primary.id(), bold, false)
{
if let Some(f) = db.fallback_for_run(&chars, primary.id(), bold, false) {
out.push((FaceRef::of(&f), s));
continue;
}
@@ -470,13 +378,8 @@ fn face_runs<'a>(
// in one run.
let mut run: Option<(FaceRef, usize)> = None;
for (i, c) in s.char_indices() {
let face = if joins(c) {
None
} else if let Some(df) = diagram_fallback.filter(|df| df.covers(c)) {
Some(df_face_for(df, &[c]))
} else {
Some(db.fallback_styled(c, primary.id(), bold, false).map(|f| FaceRef::of(&f)).unwrap_or(primary))
};
let face =
if joins(c) { None } else { Some(db.fallback_styled(c, primary.id(), bold, false).map(|f| FaceRef::of(&f)).unwrap_or(primary)) };
match (run, face) {
(Some((cur, from)), Some(f)) if f.id() != cur.id() => {
out.extend(s.get(from..i).map(|t| (cur, t)));
+4 -31
View File
@@ -279,19 +279,6 @@ fn story_items(page: &Page, story: StoryRef) -> Box<dyn Iterator<Item = &Placed>
}
}
/// The topmost uncovered table cell in `story` under `(x, y)` on `page`.
fn story_cell_at(page: &Page, story: StoryRef, x: f32, y: f32) -> Option<(&Path, usize, usize)> {
let pt = Point::new(x, y);
story_items(page, story)
.filter_map(|it| match it {
Placed::Cell { rect, table, row, cell, story: s, covered: false, .. } if *s == story && rect.contains(pt) => Some((table, *row, *cell)),
_ => None,
})
// Nested tables emit their cells before the enclosing cell, so prefer the deepest match
// and keep the last (topmost) cell on ties at the same nesting level.
.max_by_key(|(table, _, _)| table.0.len())
}
/// Whether header/footer part `id` has text near (x, y) on the page (its header or footer
/// lines). Used so an object behind the header text is only grabbed where there's no text,
/// mirroring `text_at` for the body.
@@ -464,31 +451,17 @@ impl DocLayout {
// other text on the page: below one, it goes to the text beside or after it (#2038).
let floats = if story == StoryRef::Body { float_table_areas(p) } else { Vec::new() };
let away = |path: &Path| floats.iter().any(|(t, r)| path.0.len() > t.0.len() && path.0.starts_with(&t.0) && !r.contains(Point::new(x, y)));
let cell = story_cell_at(p, story, x, y);
let in_cell = |path: &Path, table: &Path, row: usize, col: usize| {
path.0.starts_with(&table.0) && path.0.get(table.0.len()) == Some(&(row as u32)) && path.0.get(table.0.len() + 1) == Some(&(col as u32))
};
// Turned cell text takes a click up to 2pt outside it, so outside a floating table too,
// but a click inside one table cell must never be stolen by a neighbouring cell's text.
let skip_turned = |path: &Path| away(path) || cell.is_some_and(|(table, row, col)| !in_cell(path, table, row, col));
if let Some(pos) = turned_hit(p, story, x, y, &skip_turned) {
// Turned cell text takes a click up to 2pt outside it, so outside a floating table too.
if let Some(pos) = turned_hit(p, story, x, y, &away) {
return Some(pos);
}
let lines = page_lines(p, story);
let nearest = |a: &&LineHit, b: &&LineHit| score(a, x, y).total_cmp(&score(b, x, y));
let at = |l: &LineHit| Pos { story: l.story, path: l.path.clone(), off: l.para.off_at_x(l.li, x - l.x) };
if let Some((table, row, col)) = cell {
if let Some(best) = lines.iter().filter(|l| in_cell(l.path, table, row, col)).min_by(nearest) {
return Some(at(best));
}
if let Some(pos) = nearest_turned(p, story, x, y, &|path| !in_cell(path, table, row, col)) {
return Some(pos);
}
}
if lines.is_empty() {
// A page of turned text (a vertical section): the nearest turned line.
return nearest_turned(p, story, x, y, &away).or_else(|| nearest_turned(p, story, x, y, &|_: &Path| false));
}
let nearest = |a: &&LineHit, b: &&LineHit| score(a, x, y).total_cmp(&score(b, x, y));
let at = |l: &LineHit| Pos { story: l.story, path: l.path.clone(), off: l.para.off_at_x(l.li, x - l.x) };
if let Some(best) = lines.iter().filter(|l| !away(l.path)).min_by(nearest) {
return Some(at(best));
}
-447
View File
@@ -2906,239 +2906,6 @@ fn tables_lay_out_cells() {
assert!(l.cell_at(0, c.x, c.top + 2.0).is_some());
}
#[test]
fn clicking_in_a_table_cell_stays_in_that_cell_even_away_from_center() {
use wordcraft_doc::props::VAlign;
crate::test_fonts();
let mut d = Document::from_text("before\nafter");
let mut t = Table::new(2, 3, 468.0);
// Row 0, Cell 0 has one short line:
t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Short", Default::default()))];
// Row 0, Cell 1 has multiple lines, making the row tall:
t.rows[0].cells[1].blocks =
vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6", Default::default()))];
// Row 0, Cell 2 is empty:
t.rows[0].cells[2].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::new())];
// Row 1, Cell 0 is vertically centered:
t.rows[1].cells[0].props.valign = Some(VAlign::Center);
t.rows[1].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Centered", Default::default()))];
// Row 1, Cell 1 is tall:
t.rows[1].cells[1].blocks =
vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("R1 L1\nR1 L2\nR1 L3\nR1 L4\nR1 L5", Default::default()))];
// Row 1, Cell 2 has turned text:
t.rows[1].cells[2].props.text_direction = TextDirection::Down;
t.rows[1].cells[2].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Turned", Default::default()))];
d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let cell_rect = |r: usize, c: usize| {
l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, row, cell, .. } if *row == r && *cell == c => Some(*rect),
_ => None,
})
.unwrap()
};
let r00 = cell_rect(0, 0);
let r02 = cell_rect(0, 2);
let r10 = cell_rect(1, 0);
let r12 = cell_rect(1, 2);
// 1. Click near the bottom of Row 0, Cell 0 (away from its short text, near row boundary):
let click00 = l.hit(0, r00.x + 10.0, r00.bottom() - 4.0, StoryRef::Body).unwrap();
assert_eq!(click00.path, Path(vec![1, 0, 0, 0]), "click in (0, 0) must stay in (0, 0), got {:?}", click00.path);
// 2. Click in the middle/bottom of empty Row 0, Cell 2:
let click02 = l.hit(0, r02.x + 20.0, r02.y + r02.h * 0.75, StoryRef::Body).unwrap();
assert_eq!(click02.path, Path(vec![1, 0, 2, 0]), "click in empty (0, 2) must stay in (0, 2), got {:?}", click02.path);
// 3. Click near top of vertically centered Row 1, Cell 0 (above centered text):
let click10_top = l.hit(0, r10.x + 15.0, r10.y + 4.0, StoryRef::Body).unwrap();
assert_eq!(click10_top.path, Path(vec![1, 1, 0, 0]), "click near top of centered (1, 0) must stay in (1, 0), got {:?}", click10_top.path);
// 4. Click near bottom of vertically centered Row 1, Cell 0 (below centered text):
let click10_bot = l.hit(0, r10.x + 15.0, r10.bottom() - 4.0, StoryRef::Body).unwrap();
assert_eq!(click10_bot.path, Path(vec![1, 1, 0, 0]), "click near bottom of centered (1, 0) must stay in (1, 0), got {:?}", click10_bot.path);
// 5. Click in turned text Row 1, Cell 2 (away from text edge, inside cell):
let click12 = l.hit(0, r12.x + 10.0, r12.bottom() - 6.0, StoryRef::Body).unwrap();
assert_eq!(click12.path, Path(vec![1, 1, 2, 0]), "click in turned cell (1, 2) must stay in (1, 2), got {:?}", click12.path);
}
#[test]
fn clicking_in_a_nested_table_cell_stays_in_nested_cell() {
crate::test_fonts();
let mut d = Document::new();
let mut outer = Table::new(1, 1, 468.0);
let mut inner = Table::new(1, 2, 300.0);
inner.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Inner", Default::default()))];
inner.rows[0].cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("L1\nL2\nL3\nL4\nL5", Default::default()))];
outer.rows[0].cells[0].blocks = vec![
wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Outer\n\n\n\n\n\n", Default::default())),
wordcraft_doc::Block::Table(inner).into(),
];
d.body = vec![wordcraft_doc::Block::Table(outer).into()];
let l = lay(&d);
let inner_cell = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, table, row, cell, .. } if table.0 == vec![0, 0, 0, 1] && *row == 0 && *cell == 0 => Some(*rect),
_ => None,
})
.unwrap();
// Click near the bottom of inner cell (0, 0), closer to outer cell's bottom or away from "Inner":
let click = l.hit(0, inner_cell.x + 10.0, inner_cell.bottom() - 4.0, StoryRef::Body).unwrap();
assert_eq!(click.path, Path(vec![0, 0, 0, 1, 0, 0, 0]), "click in nested cell must stay in nested cell, got {:?}", click.path);
}
#[test]
fn clicking_in_a_turned_cell_on_an_all_turned_page_stays_in_that_cell() {
crate::test_fonts();
let mut d = Document::new();
let mut t = Table::new(1, 2, 468.0);
// TextDirection::Up places text on the left side of each cell, so a click near the right
// edge of cell 0 is much closer to cell 1's text than cell 0's own text.
t.rows[0].cells[0].props.text_direction = TextDirection::Up;
t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Left", Default::default()))];
t.rows[0].cells[1].props.text_direction = TextDirection::Up;
t.rows[0].cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Right", Default::default()))];
d.body = vec![wordcraft_doc::Block::Table(t).into()];
let l = lay(&d);
assert!(crate::hit::page_lines(&l.pages[0], StoryRef::Body).is_empty(), "page should have only turned lines");
let left_cell = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, row, cell, .. } if *row == 0 && *cell == 0 => Some(*rect),
_ => None,
})
.unwrap();
let click_right = l.hit(0, left_cell.right() - 4.0, left_cell.y + 10.0, StoryRef::Body).unwrap();
assert_eq!(click_right.path, Path(vec![0, 0, 0, 0]), "click on right of turned cell 0 must stay in cell 0, got {:?}", click_right.path);
}
#[test]
fn clicking_near_shared_edge_within_turned_tolerance_stays_in_clicked_cell() {
crate::test_fonts();
let mut d = Document::new();
let mut t = Table::new(1, 2, 468.0);
// Cell 0 is empty; Cell 1 has TextDirection::Up, which places turned text near Cell 1's left
// edge (the shared border with Cell 0) so its 2pt expanded hit box reaches into Cell 0.
t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::new())];
t.rows[0].cells[1].props.margins = Some([0.0; 4]);
t.rows[0].cells[1].props.text_direction = TextDirection::Up;
t.rows[0].cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Turned", Default::default()))];
d.body = vec![wordcraft_doc::Block::Table(t).into()];
let l = lay(&d);
let cell0 = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, row, cell, .. } if *row == 0 && *cell == 0 => Some(*rect),
_ => None,
})
.unwrap();
let turned_bounds = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Lines { path, .. } if path == &Path(vec![0, 0, 1, 0]) => it.turned_bounds(),
_ => None,
})
.unwrap();
// Click inside Cell 0, 0.5pt left of the shared border, and confirm it lies within the 2pt
// expanded turned_bounds of Cell 1.
let click_x = cell0.right() - 0.5;
let click_y = turned_bounds.y + turned_bounds.h * 0.5;
assert!(cell0.contains(wordcraft_geom::Point::new(click_x, click_y)));
assert!(turned_bounds.expand(2.0).contains(wordcraft_geom::Point::new(click_x, click_y)));
let hit = l.hit(0, click_x, click_y, StoryRef::Body).unwrap();
assert_eq!(hit.path, Path(vec![0, 0, 0, 0]), "click inside cell 0 within 2pt of cell 1's turned text must stay in cell 0, got {:?}", hit.path);
// Outside the table, the 2pt tolerance on turned text still applies.
let mut d_out = Document::new();
let mut t_out = Table::new(1, 1, 468.0);
t_out.rows[0].cells[0].props.margins = Some([0.0; 4]);
t_out.rows[0].cells[0].props.text_direction = TextDirection::Up;
t_out.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Edge", Default::default()))];
d_out.body = vec![
wordcraft_doc::Block::Table(t_out).into(),
wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Upright", Default::default())),
];
let l_out = lay(&d_out);
let out_cell = l_out.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, .. } => Some(*rect),
_ => None,
})
.unwrap();
let out_bounds = l_out.pages[0].items.iter().find_map(|it| it.turned_bounds()).unwrap();
let out_x = out_bounds.x - 1.0;
let out_y = out_bounds.y + out_bounds.h * 0.5;
assert!(!out_cell.contains(wordcraft_geom::Point::new(out_x, out_y)));
assert!(out_bounds.expand(2.0).contains(wordcraft_geom::Point::new(out_x, out_y)));
let out_hit = l_out.hit(0, out_x, out_y, StoryRef::Body).unwrap();
assert_eq!(out_hit.path, Path(vec![0, 0, 0, 0]));
// Beyond the 2pt tolerance, the upright paragraph is hit instead (proving tolerance is required).
let far_hit = l_out.hit(0, out_bounds.x - 3.0, out_y, StoryRef::Body).unwrap();
assert_eq!(far_hit.path, Path(vec![1]));
}
#[test]
fn clicking_in_a_header_or_footer_table_cell_stays_in_that_cell() {
crate::test_fonts();
let mut d = Document::from_text("Body text");
let mut ht = Table::new(1, 2, 468.0);
ht.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Short", Default::default()))];
ht.rows[0].cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("H1\nH2\nH3\nH4\nH5", Default::default()))];
let hid = d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::Block::Table(ht).into()]);
d.last_section.headers.default = Some(hid);
let mut ft = Table::new(1, 2, 468.0);
ft.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("FShort", Default::default()))];
ft.rows[0].cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("F1\nF2\nF3\nF4\nF5", Default::default()))];
let fid = d.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::Block::Table(ft).into()]);
d.last_section.footers.default = Some(fid);
let l = lay(&d);
let h_cell0 = l.pages[0]
.header
.iter()
.find_map(|it| match it {
Placed::Cell { rect, story, row, cell, .. } if *story == StoryRef::Part(hid) && *row == 0 && *cell == 0 => Some(*rect),
_ => None,
})
.unwrap();
let h_hit = l.hit(0, h_cell0.x + 10.0, h_cell0.bottom() - 4.0, StoryRef::Part(hid)).unwrap();
assert_eq!(h_hit.path, Path(vec![0, 0, 0, 0]), "click in header cell (0, 0) must stay in (0, 0), got {:?}", h_hit.path);
let f_cell0 = l.pages[0]
.footer
.iter()
.find_map(|it| match it {
Placed::Cell { rect, story, row, cell, .. } if *story == StoryRef::Part(fid) && *row == 0 && *cell == 0 => Some(*rect),
_ => None,
})
.unwrap();
let f_hit = l.hit(0, f_cell0.x + 10.0, f_cell0.bottom() - 4.0, StoryRef::Part(fid)).unwrap();
assert_eq!(f_hit.path, Path(vec![0, 0, 0, 0]), "click in footer cell (0, 0) must stay in (0, 0), got {:?}", f_hit.path);
}
#[test]
fn a_tables_own_space_above_and_below_moves_the_text() {
// ODT tables' `fo:margin-top`/`fo:margin-bottom`: added to the spacing around the table.
@@ -9223,220 +8990,6 @@ fn chart_text_the_font_lacks_is_drawn_in_a_fallback_face() {
assert!(xs.windows(2).all(|w| w[0] <= w[1]), "{xs:?}");
}
/// A bundled Source Sans 3 font patched so its last cmap group (U+1F916) maps `first..=last`,
/// registered in [`wordcraft_fonts::FontDb::global`] under `family`.
fn diagram_test_font(family: &str, first: u32, last: u32) -> (Vec<u8>, String) {
let mut data = std::fs::read(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf")).unwrap();
let from = [0x0001_F916_u32.to_be_bytes(); 2].concat();
let to = [first.to_be_bytes(), last.to_be_bytes()].concat();
let mut patched = 0;
while let Some(at) = data.windows(from.len()).position(|w| w == from) {
data[at..at + to.len()].copy_from_slice(&to);
patched += 1;
}
assert!(patched > 0);
(data, family.to_string())
}
/// RAII guard to clean up test document fonts added to [`wordcraft_fonts::FontDb::global`].
struct CleanupDocumentFonts<'a>(&'a wordcraft_fonts::FontDb, &'static [&'static str]);
impl Drop for CleanupDocumentFonts<'_> {
fn drop(&mut self) {
self.0.remove_document_fonts(self.1);
}
}
/// SmartArt diagram CJK labels keep one consistent fallback font across nodes,
/// matching the diagram's primary serif/sans nature, including when a label contains a symbol (#5672).
#[test]
fn smart_art_diagram_cjk_labels_maintain_consistent_fallback_font() {
crate::test_fonts();
// #5672: CJK labels in a SmartArt diagram rendered in two different fallback fonts
// (first node serif Mincho, rest sans). The diagram must maintain a consistent fallback font
// matching the diagram's primary font style, even when another character needs a separate symbol
// fallback face. Both sans-serif and serif primaries are tested with synthetic fonts.
use wordcraft_doc::graphic::{Graphic, GraphicItem, GraphicKind, TextAlign};
use wordcraft_doc::props::Rgb;
let db = wordcraft_fonts::FontDb::global();
const TEST_FONTS: &[&str] = &["DiagBothMincho", "DiagBothGothic", "DiagOnlySymbol"];
let _cleanup = CleanupDocumentFonts(db, TEST_FONTS);
db.add_document_fonts(vec![
diagram_test_font("DiagBothMincho", 0x3FF21, 0x3FF22),
diagram_test_font("DiagBothGothic", 0x3FF21, 0x3FF22),
diagram_test_font("DiagOnlySymbol", 0xF0129, 0xF0129),
]);
// 1. Sans-serif diagram: prefers DiagBothGothic over DiagBothMincho.
let sans_items = ["\u{3FF21} \u{F0129}", "\u{3FF22}", "\u{F0129}"]
.iter()
.enumerate()
.map(|(i, &label)| GraphicItem::Text {
rect: [0.0, (i as f32) * 30.0, 100.0, 20.0],
text: label.into(),
size: 12.0,
color: Rgb::BLACK,
bold: false,
align: TextAlign::Center,
font: Some("Source Sans 3".into()),
angle: 0.0,
})
.collect();
let sans_graphic = Graphic { kind: GraphicKind::Diagram, items: sans_items, ..Default::default() };
let sans_obj = InlineObject::Graphic { w: 300.0, h: 200.0, alt: String::new(), float: Default::default(), graphic: Arc::new(sans_graphic) };
let mut sans_doc = Document::from_text("Diagram");
sans_doc.insert_object(&Pos::body(0, 0), sans_obj, &Default::default()).unwrap();
let sans_draws = flat(display::page_display(&sans_doc, &lay(&sans_doc).pages[0], &Default::default()));
let sans_cjk_draws: Vec<_> = sans_draws
.iter()
.filter_map(|x| if let display::Draw::Glyphs { face, text, .. } = x { Some((text.as_str(), *face)) } else { None })
.filter(|(t, _)| t.contains('\u{3FF21}') || t.contains('\u{3FF22}'))
.collect();
assert_eq!(sans_cjk_draws.len(), 2, "both CJK labels drawn in sans diagram");
for (t, face) in &sans_cjk_draws {
assert_eq!(face.family, "DiagBothGothic", "CJK label {t:?} should use sans fallback DiagBothGothic");
assert!(!face.is_serif(), "fallback face must be sans");
}
let sans_sym_draws: Vec<_> = sans_draws
.iter()
.filter_map(|x| if let display::Draw::Glyphs { face, text, .. } = x { Some((text.as_str(), *face)) } else { None })
.filter(|(t, _)| t.contains('\u{F0129}'))
.collect();
assert_eq!(sans_sym_draws.len(), 2, "symbol drawn in both mixed and standalone nodes");
for (_, face) in &sans_sym_draws {
assert_eq!(face.family, "DiagOnlySymbol");
}
// 2. Serif diagram: prefers DiagBothMincho over DiagBothGothic.
let serif_items = ["\u{3FF21} \u{F0129}", "\u{3FF22}", "\u{F0129}"]
.iter()
.enumerate()
.map(|(i, &label)| GraphicItem::Text {
rect: [0.0, (i as f32) * 30.0, 100.0, 20.0],
text: label.into(),
size: 12.0,
color: Rgb::BLACK,
bold: false,
align: TextAlign::Center,
font: Some("Source Serif 4".into()),
angle: 0.0,
})
.collect();
let serif_graphic = Graphic { kind: GraphicKind::Diagram, items: serif_items, ..Default::default() };
let serif_obj = InlineObject::Graphic { w: 300.0, h: 200.0, alt: String::new(), float: Default::default(), graphic: Arc::new(serif_graphic) };
let mut serif_doc = Document::from_text("Diagram");
serif_doc.insert_object(&Pos::body(0, 0), serif_obj, &Default::default()).unwrap();
let serif_draws = flat(display::page_display(&serif_doc, &lay(&serif_doc).pages[0], &Default::default()));
let serif_cjk_draws: Vec<_> = serif_draws
.iter()
.filter_map(|x| if let display::Draw::Glyphs { face, text, .. } = x { Some((text.as_str(), *face)) } else { None })
.filter(|(t, _)| t.contains('\u{3FF21}') || t.contains('\u{3FF22}'))
.collect();
assert_eq!(serif_cjk_draws.len(), 2, "both CJK labels drawn in serif diagram");
for (t, face) in &serif_cjk_draws {
assert_eq!(face.family, "DiagBothMincho", "CJK label {t:?} should use serif fallback DiagBothMincho");
assert!(face.is_serif(), "fallback face must be serif");
}
// 3. Real CJK check (reconciled with synthetic fixtures, #5672):
// Synthetic fixtures above provide deterministic coverage for both sans-serif and serif
// diagrams across all platforms and CI runners without depending on installed CJK fonts.
// When the host environment does have a real sans-serif CJK candidate available, also
// verify that real CJK labels in a SmartArt diagram resolve consistently to a sans-serif
// fallback face across nodes.
let labels = ["新建文档", "施加样式", "导出验证"];
let label_chars: Vec<char> = labels.iter().flat_map(|s| s.chars()).collect();
let minor = wordcraft_fonts::word::resolve(&Document::default().settings.minor_font, false, false);
if db.fallback_for_diagram(&label_chars, minor.face.id(), false).is_some_and(|f| !f.is_serif()) {
let real_items = ["新建文档 \u{F0129}", "施加样式", "导出验证", "\u{F0129}"]
.iter()
.enumerate()
.map(|(i, &label)| GraphicItem::Text {
rect: [0.0, (i as f32) * 30.0, 100.0, 20.0],
text: label.into(),
size: 12.0,
color: Rgb::BLACK,
bold: false,
align: TextAlign::Center,
font: None,
angle: 0.0,
})
.collect();
let real_graphic = Graphic { kind: GraphicKind::Diagram, items: real_items, ..Default::default() };
let real_obj = InlineObject::Graphic { w: 300.0, h: 200.0, alt: String::new(), float: Default::default(), graphic: Arc::new(real_graphic) };
let mut real_doc = Document::from_text("Diagram");
real_doc.insert_object(&Pos::body(0, 0), real_obj, &Default::default()).unwrap();
let real_draws = flat(display::page_display(&real_doc, &lay(&real_doc).pages[0], &Default::default()));
let real_cjk_draws: Vec<_> = real_draws
.iter()
.filter_map(|x| if let display::Draw::Glyphs { face, text, .. } = x { Some((text.clone(), *face)) } else { None })
.filter(|(text, _)| labels.iter().any(|l| text.trim().starts_with(l)))
.collect();
assert_eq!(real_cjk_draws.len(), 3, "all three real CJK diagram labels were drawn");
let first_family = real_cjk_draws[0].1.family.clone();
assert!(!real_cjk_draws[0].1.is_serif(), "diagram fallback font should be sans-serif, was {first_family}");
for (text, face) in &real_cjk_draws {
assert_eq!(face.family, first_family, "label {text:?} used a different font family from first node");
assert!(!face.is_serif(), "label {text:?} rendered in serif font {}", face.family);
}
} else {
eprintln!("skipped real CJK check: no sans-serif CJK font covers all diagram labels");
}
}
/// In a mixed-font diagram where the first label's primary font covers characters missing from
/// later labels, later labels use the diagram fallback face, which here is that same font.
#[test]
fn mixed_font_diagram_uses_covering_fallback_for_later_missing_characters() {
crate::test_fonts();
use wordcraft_doc::graphic::{Graphic, GraphicItem, GraphicKind, TextAlign};
use wordcraft_doc::props::Rgb;
let db = wordcraft_fonts::FontDb::global();
const TEST_FONTS: &[&str] = &["DiagPartAGothic", "DiagPartBGothic", "DiagWholeGothic"];
let _cleanup = CleanupDocumentFonts(db, TEST_FONTS);
db.add_document_fonts(vec![
diagram_test_font("DiagPartAGothic", 0x3FF11, 0x3FF11),
diagram_test_font("DiagPartBGothic", 0x3FF12, 0x3FF12),
diagram_test_font("DiagWholeGothic", 0x3FF11, 0x3FF12),
]);
let items = [
("\u{3FF11}", Some("DiagWholeGothic".to_string())),
("\u{3FF11}", Some("Source Sans 3".to_string())),
("\u{3FF12}", Some("Source Sans 3".to_string())),
]
.into_iter()
.enumerate()
.map(|(i, (label, font))| GraphicItem::Text {
rect: [0.0, (i as f32) * 30.0, 100.0, 20.0],
text: label.into(),
size: 12.0,
color: Rgb::BLACK,
bold: false,
align: TextAlign::Center,
font,
angle: 0.0,
})
.collect();
let graphic = Graphic { kind: GraphicKind::Diagram, items, ..Default::default() };
let obj = InlineObject::Graphic { w: 300.0, h: 200.0, alt: String::new(), float: Default::default(), graphic: Arc::new(graphic) };
let mut d = Document::from_text("Diagram");
d.insert_object(&Pos::body(0, 0), obj, &Default::default()).unwrap();
let draws = flat(display::page_display(&d, &lay(&d).pages[0], &Default::default()));
let cjk_faces: Vec<_> = draws
.iter()
.filter_map(|x| if let display::Draw::Glyphs { face, text, .. } = x { Some((text.as_str(), *face)) } else { None })
.filter(|(t, _)| t.contains('\u{3FF11}') || t.contains('\u{3FF12}'))
.collect();
assert_eq!(cjk_faces.len(), 3, "all three labels drawn");
for (text, face) in &cjk_faces {
assert_eq!(face.family, "DiagWholeGothic", "label {text:?} should use the shared diagram fallback face");
}
}
/// The draws with figures opened up.
fn flat(draws: Vec<display::Draw>) -> Vec<display::Draw> {
draws.into_iter().flat_map(|x| if let display::Draw::Figure { draws, .. } = x { draws } else { vec![x] }).collect()
+1 -1
View File
@@ -1,3 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<path d="M8 5.4 L13.8 5.4 L13.8 7 L11.6 7 L10.3 14.9 L12 14.9 L12 16.5 L6.2 16.5 L6.2 14.9 L8.4 14.9 L9.7 7 L8 7 Z" fill="currentColor"/>
<path d="M8.6 5.4 L13.2 5.4 M6.8 16.5 L11.4 16.5 M10.9 5.4 L9.1 16.5" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 231 B

After

Width:  |  Height:  |  Size: 242 B

-7
View File
@@ -1,7 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<rect x="3" y="3" width="6" height="6" rx="1" fill="#1E6FD9" class="accent" fill-opacity="0.251"/>
<rect x="3" y="3" width="6" height="6" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
<rect x="11" y="3" width="6" height="6" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
<rect x="3" y="11" width="6" height="6" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
<rect x="11" y="11" width="6" height="6" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
</svg>

Before

Width:  |  Height:  |  Size: 612 B

@@ -1,9 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<rect x="3" y="3" width="14" height="4" rx="1" fill="#1E6FD9" class="accent"/>
<rect x="3" y="3" width="14" height="14" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M3 7 L17 7" fill="none" stroke="currentColor" stroke-width="1.25"/>
<rect x="5" y="9" width="2.5" height="2.5" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M9.5 10.25 L15 10.25" fill="none" stroke="currentColor" stroke-width="1.25"/>
<rect x="5" y="13" width="2.5" height="2.5" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M9.5 14.25 L15 14.25" fill="none" stroke="currentColor" stroke-width="1.25"/>
</svg>

Before

Width:  |  Height:  |  Size: 738 B

-9
View File
@@ -1,9 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<rect x="3" y="3" width="14" height="4" rx="1" fill="#1E6FD9" class="accent"/>
<rect x="3" y="11" width="14" height="3" fill="#1E6FD9" class="accent" fill-opacity="0.251"/>
<rect x="3" y="3" width="14" height="14" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M3 7 L17 7" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M3 11 L17 11" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M3 14 L17 14" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M8 7 L8 17" fill="none" stroke="currentColor" stroke-width="1.25"/>
</svg>

Before

Width:  |  Height:  |  Size: 694 B

+2 -1
View File
@@ -1,3 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<path d="M5.4 5.4 L7.8 5.4 L7.8 11.45 C7.8 13.57 8.6 14.38 10 14.38 C11.4 14.38 12.2 13.57 12.2 11.45 L12.2 5.4 L14.6 5.4 L14.6 11.66 C14.6 14.89 12.8 16.5 10 16.5 C7.2 16.5 5.4 14.89 5.4 11.66 Z M4.6 17.7 L15.4 17.7 L15.4 19.2 L4.6 19.2 Z" fill="currentColor"/>
<path d="M5.8 4.24 L5.8 10.4 C5.8 13.1 7.4 14.6 10 14.6 C12.6 14.6 14.2 13.1 14.2 10.4 L14.2 4.24" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/>
<path d="M5 17 L15 17" fill="none" stroke="currentColor" stroke-width="1.25"/>
</svg>

Before

Width:  |  Height:  |  Size: 356 B

After

Width:  |  Height:  |  Size: 352 B

-4
View File
@@ -17,8 +17,6 @@ mod commands;
mod control;
mod files;
pub(crate) use files::Closing;
#[cfg(test)]
pub(crate) use files::suggested_stem;
pub(crate) mod fonts;
mod frame;
mod input;
@@ -80,7 +78,6 @@ impl WordApp {
dialog_hooks,
dialog_answers,
edits,
edits_gesture,
keytips_active,
options_state,
print,
@@ -168,7 +165,6 @@ impl WordApp {
dialog_hooks,
dialog_answers,
edits,
edits_gesture,
keytips_active,
options_state,
print,
+1 -20
View File
@@ -5,7 +5,6 @@ use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use craft::keymap::Overrides;
use craft::ui::runtime::commands::CommandSet as _;
use craft::ui::runtime::commands::{
AppCatalog, Binding, CommandDef, CommandInput, CommandRef, CommandState, CommandStates, FireSource, Scope, TypingRule,
};
@@ -140,13 +139,6 @@ fn gate_registered(app: &WordApp, id: &str) -> (bool, Option<&'static str>) {
(reason.is_none(), reason)
}
/// The framework edit commands the app's engine commands of the same id run through: the linked set owns their
/// definition, the engine owns their chords.
const LINKED_EDIT: [craft::ui::runtime::commands::EditCommands; 5] = {
use craft::ui::runtime::commands::EditCommands::{Copy, Cut, Paste, Redo, Undo};
[Cut, Copy, Paste, Undo, Redo]
};
impl WordApp {
/// The app's commands as the keymap knows them: every engine command with its default
/// chords, then the interface commands. The interface commands come last because a tie in the
@@ -179,9 +171,7 @@ impl WordApp {
}
defs.push(def);
}
// The framework's edit set defines Cut, Copy, Paste, Undo and Redo: a catalog def for them is shadowed (and
// warned about), so their chords go in as the set's replaced defaults (the `LINKED_EDIT` fold below).
for spec in registry.all().iter().filter(|spec| seen.insert(spec.id) && !LINKED_EDIT.iter().any(|c| c.id() == spec.id)) {
for spec in registry.all().iter().filter(|spec| seen.insert(spec.id)) {
let mut def = CommandDef::new(CommandRef::new(spec.id), tl!(spec.label), Scope::app());
for binding in default_bindings(spec.shortcut) {
def = def.with_default(binding);
@@ -201,8 +191,6 @@ impl WordApp {
interface(CommandRef::new("ui.collapseRibbon"), "Collapse the Ribbon", "Mod+Alt+R");
}
interface(CommandRef::new("ui.resetInterfaceSize"), "Reset Interface Size", "Mod+Shift+0");
// The File keytips fire it (one badge per page); without an entry it shows its id as its label.
defs.push(CommandDef::new(CommandRef::new("ui.backstage"), tl!("File"), Scope::app()));
for (id, label) in GATED_UI_COMMANDS {
defs.push(CommandDef::new(CommandRef::new(*id), tl!(*label), Scope::app()));
}
@@ -216,10 +204,6 @@ impl WordApp {
match AppCatalog::new(defs, generation) {
Ok(catalog) => {
let catalog = catalog.typing_rule(TypingRule::PlainKeysWait);
let catalog = LINKED_EDIT.iter().fold(catalog, |catalog, command| {
let chords = registry.get(command.id()).map(|spec| default_bindings(spec.shortcut).collect()).unwrap_or_default();
catalog.replace_defaults(command.id(), chords)
});
self.command_catalog = Some((registry, with_word_chords(catalog)));
}
Err(error) => {
@@ -344,7 +328,6 @@ impl WordApp {
let mut host = std::mem::take(&mut self.edits);
host.before_undo(ctx, self);
self.edits = host;
self.edits_gesture = None;
}
let result = if fired.source == FireSource::Automation { self.execute(id, params) } else { self.run(id, params) };
if from_key && result.is_ok() {
@@ -414,13 +397,11 @@ mod tests {
app.run_fired(&ctx, &output);
let after_undo = app.session.undo_depth();
assert_eq!(after_undo + 1, before, "the gesture left no step, and Undo took the one from before it");
assert!(app.edits_gesture.is_none(), "Undo clears running edit gesture state");
let mut end = EditEvents::new();
end.push(EditEvent::commit(id, Mixed::Same(11.0_f32), 20.0_f32));
crate::undo_marks::apply_edits(&mut app, end, apply);
assert_eq!(app.session.undo_depth(), after_undo, "the late Commit of the taken-back gesture adds no step");
assert!(app.edits_gesture.is_none());
}
/// #7310: unimplemented Word feature catalog commands publish a disabled state so ribbon
+7 -7
View File
@@ -176,7 +176,7 @@ pub(crate) fn show(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
match command {
BackstagePageCommand::Back => {
let _ = app.run("ui.backstage", json!({"value": false}));
app.canvas.focus_page_after_pass();
app.canvas.focus_page(&ctx);
}
// PLAN: `print_requested(app, ctx)` is chrome-w10's new `pub(crate)` fn in print_page.rs (S-L263).
BackstagePageCommand::Print if app.ui.backstage_page == "print" => crate::print_page::print_requested(app, &ctx),
@@ -209,7 +209,7 @@ pub(crate) fn show(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
});
});
if let Some(id) = choice.page.take() {
go_to_page(app, id);
go_to_page(app, id, &ctx);
}
if choice.about.get() {
let _ = crate::dialogs::open(app, "about", &json!({}));
@@ -309,7 +309,7 @@ fn page_rows(ui: &mut Ui, current: &str, has_document: bool, choice: &MenuChoice
let on = has_document || works_without_document(id);
let row = Button::new(label(name))
.id_salt(("backstage-page", id))
.icon(crate::icons::spec(icon))
.icon(crate::icons::id(icon))
.variant(Variant::GHOST)
.sizing(Sizing::FillWidth)
// Icon and name at the reading start of the full-width row, as production's menu.
@@ -325,7 +325,7 @@ fn page_rows(ui: &mut Ui, current: &str, has_document: bool, choice: &MenuChoice
/// Opens a side-menu page, as a click on it (or its keytip) does. Without a document only the
/// pages that work without one open.
pub(crate) fn go_to_page(app: &mut WordApp, id: &str) {
pub(crate) fn go_to_page(app: &mut WordApp, id: &str, ctx: &egui::Context) {
if !app.has_document() && !works_without_document(id) {
return;
}
@@ -340,7 +340,7 @@ pub(crate) fn go_to_page(app: &mut WordApp, id: &str) {
let r = app.run("file.save", json!({}));
if r.is_ok_and(|v| v.get("saved").and_then(serde_json::Value::as_bool) == Some(true) || v.get("downloaded").is_some()) {
app.ui.backstage = false;
app.canvas.focus_page_after_pass();
app.canvas.focus_page(ctx);
} else {
app.ui.backstage_page = "saveAs".into();
}
@@ -391,10 +391,10 @@ fn matching_personal(query: &str, list: &[PersonalTemplate]) -> Vec<PersonalTemp
/// Make a new document from the personal template at `path` and close File; a template that
/// can't be read keeps File open so the gallery can say why.
fn open_personal(app: &mut WordApp, path: &str) -> Result<(), String> {
fn open_personal(app: &mut WordApp, path: &str, ctx: &egui::Context) -> Result<(), String> {
app.run("file.newFromTemplate", json!({"path": path}))?;
app.ui.backstage = false;
app.canvas.focus_page_after_pass();
app.canvas.focus_page(ctx);
Ok(())
}
+6 -8
View File
@@ -30,7 +30,7 @@ pub(super) fn template_cards(list: &[(&str, &str)]) -> Vec<Template> {
/// Runs what the user did on a start screen or recent list. A failed open stays on the page as its
/// error (`BackstageState::open_error`); a later success clears it.
fn run_actions(app: &mut WordApp, actions: Vec<StartAction>) {
fn run_actions(app: &mut WordApp, ctx: &egui::Context, actions: Vec<StartAction>) {
for action in actions {
match action {
StartAction::New | StartAction::MoreTemplates => app.ui.backstage_page = "new".into(),
@@ -40,7 +40,7 @@ fn run_actions(app: &mut WordApp, actions: Vec<StartAction>) {
StartAction::OpenRecent(path) => {
let failed = open_recent(app, &path.to_string_lossy()).err();
if failed.is_none() {
app.canvas.focus_page_after_pass();
app.canvas.focus_page(ctx);
}
app.backstage_state.open_error = failed;
}
@@ -53,7 +53,7 @@ fn run_actions(app: &mut WordApp, actions: Vec<StartAction>) {
StartAction::UseTemplate(id) => {
let _ = app.run("file.new", json!({"template": id}));
app.ui.backstage = false;
app.canvas.focus_page_after_pass();
app.canvas.focus_page(ctx);
}
// Pins, folders and reveal are not part of File.
_ => {}
@@ -84,9 +84,6 @@ pub(super) fn home(ui: &mut Ui, app: &mut WordApp) {
let (mut view, mut sort) = (RecentView::List, RecentSort::Opened);
let out = StartScreen::new(Bind::bound(&mut view), Bind::bound(&mut sort), &recent)
.layout(StartLayout::Greeting)
// The File rail beside the page has New and Open; production's Home had no second pair.
.offers_new(false)
.offers_open(false)
.title(label(greeting))
.templates(&cards)
.more_templates(label("More templates →"))
@@ -96,11 +93,12 @@ pub(super) fn home(ui: &mut Ui, app: &mut WordApp) {
.page_paper(DataColor::new(Color32::WHITE))
.thumbnails(&store, &source)
.show(ui);
run_actions(app, out.actions);
run_actions(app, &ctx, out.actions);
}
/// Open: Browse for a file, then the recent documents.
pub(super) fn open(ui: &mut Ui, app: &mut WordApp) {
let ctx = ui.ctx().clone();
heading(ui, "Open");
if clicked(&Button::new(label("Browse…")).id_salt("open-browse").show(ui)) {
let _ = app.run("ui.openFileDialog", json!({}));
@@ -121,5 +119,5 @@ pub(super) fn open(ui: &mut Ui, app: &mut WordApp) {
}
let recent = recent_files(app);
let out = RecentList::new(&recent).max_recent(app.ui.recent_shown()).empty(label("Documents you open will show up here.")).show(ui);
run_actions(app, out.actions);
run_actions(app, &ctx, out.actions);
}
+5 -5
View File
@@ -3,7 +3,7 @@
use std::borrow::Cow;
use craft::behavior::keyed;
use craft::behavior::{IconId, keyed};
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::contract::{
@@ -12,7 +12,7 @@ use craft::ui::contract::{
use craft::ui::layout_components::Stack;
use craft::ui::list::ThumbAspect;
use craft::ui::notices::Notice;
use craft::ui::primitives::ContentPainterCx;
use craft::ui::primitives::{ContentPainterCx, IconSpec};
use craft::ui::runtime::env::Label;
use craft::ui::shell::{Template, ThumbKey};
use craft::ui::style::DataColor;
@@ -64,7 +64,7 @@ fn read_listing(app: &WordApp) -> PersonalListing {
pub(super) fn paint_personal_card(cx: &ContentPainterCx, rect: Rect) {
cx.data_shapes([Shape::rect_filled(rect, 2.0, Color32::WHITE)]);
let icon_rect = Rect::from_center_size(rect.center(), vec2(44.0, 44.0));
cx.icon(icon_rect, &crate::icons::spec("documentTemplate").data_color(DataColor::new(Color32::from_gray(150))));
cx.icon(icon_rect, &IconSpec::svg(IconId::new("documentTemplate")).data_color(DataColor::new(Color32::from_gray(150))));
}
/// New: the whole template gallery with a search box, then the personal templates (#2852); no
@@ -112,7 +112,7 @@ pub(super) fn show(ui: &mut Ui, app: &mut WordApp) {
for id in activated(out.response.events) {
let _ = app.run("file.new", json!({"template": id}));
app.ui.backstage = false;
app.canvas.focus_page_after_pass();
app.canvas.focus_page(&ctx);
}
}
// Personal: the user templates folder's templates; a folder per category, as in Word.
@@ -147,7 +147,7 @@ pub(super) fn show(ui: &mut Ui, app: &mut WordApp) {
Tile::new(Label::from(p.label.clone())).thumb(ThumbAspect::new(PAGE_WIDE, PAGE_HIGH), paint_personal_card).tooltip(p.path.clone())
});
for path in activated(out.response.events) {
let failed = open_personal(app, &path).err();
let failed = open_personal(app, &path, &ctx).err();
app.backstage_state.personal_error = failed;
}
}
+4 -7
View File
@@ -3,7 +3,7 @@
use craft::i18n::Direction;
use craft::ui::buttons::Button;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Gap, LeastWidth, Props as _, Show as _, ShowContainer as _, Sizing, clicked};
use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _, Sizing, clicked};
use craft::ui::display::Text;
use craft::ui::form::{Field, FieldGroup};
use craft::ui::layout_components::{Row, Stack};
@@ -16,6 +16,7 @@ use crate::WordApp;
/// Recovery is a separate copy. Leaving this page never discards it.
pub(super) fn recovery(ui: &mut Ui, app: &mut WordApp) {
let ctx = ui.ctx().clone();
heading(ui, "Recover documents");
let _ = Text::new(label("Restore opens an unsaved copy. Your original file stays unchanged.")).show(ui);
if app.session.password.is_some() {
@@ -47,7 +48,7 @@ pub(super) fn recovery(ui: &mut Ui, app: &mut WordApp) {
let _ = Row::new().gap(Gap::Tight).show(ui, |ui, _| {
if clicked(&Button::new(label("Continue without restoring")).id_salt("recover-continue").show(ui)) {
let _ = app.run("ui.backstage", json!({"value": false}));
app.canvas.focus_page_after_pass();
app.canvas.focus_page(&ctx);
}
if clicked(&Button::new(label("Refresh")).id_salt("recover-refresh").enabled(!busy && app.session.recovery_ready()).show(ui)) {
let _ = app.run("file.recover", json!({"refresh": true}));
@@ -208,9 +209,5 @@ pub(super) fn export(ui: &mut Ui, app: &mut WordApp) {
}
heading(ui, "Export");
let _ = Text::new(label("Save a copy in another format. Printing goes through a PDF you can print from any viewer.")).show(ui);
// The Print page's settings column: the format buttons fill it, not the page (as production's 320 pt rows).
// The row keeps the page's width from reaching the column, so the column is as wide as its least width.
let _ = Row::new().show(ui, |ui, _| {
let _ = Stack::new().least_width(LeastWidth::Dialog).gap(Gap::Stack).show(ui, |ui, _| crate::print_page::export_formats(app, ui));
});
crate::print_page::export_formats(app, ui);
}
-47
View File
@@ -892,50 +892,3 @@ fn file_open_recent_list_has_no_thumbnail_letterboxing() {
let row = recent_row(&h2, "sample.docx").expect("recent row renders");
assert!(row.rect().height() > 0.0, "recent row has non-zero height: {:?}", row.rect());
}
/// #2931: File › New › Blank document with a document open returns to the editor without
/// AccessKit losing the focused node; and so does Home's Blank document tile and Escape.
#[test]
fn blank_document_from_the_file_page_with_accessibility_on() {
let work = || {
let a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Work")), Services::default());
harness(a, egui::vec2(1440.0, 900.0))
};
for page in ["new", "home"] {
// A fresh "Work" document each time, so each path must really make a blank one.
let mut h = work();
h.state_mut().run("ui.backstage", json!({"value": true, "page": page})).unwrap();
h.run_steps(4);
h.get_by_label("Blank document").click();
h.run_steps(4);
assert!(!h.state().ui.backstage, "{page}: Blank document returns to the editor");
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), "", "{page}: a new blank document");
assert!(h.state().dialog_host.is_empty(), "{page}: nothing asks first");
}
let mut h = work();
h.state_mut().run("ui.backstage", json!({"value": true})).unwrap();
h.run_steps(4);
h.get_by_label("Back").click();
h.run_steps(4);
assert!(!h.state().ui.backstage, "the Back button closes the File page");
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), "Work", "Back keeps the document");
}
/// #3041: clicking the plain sidebar background next to the back arrow must not also close
/// the File page — only the button itself does (#2972, #3041).
#[test]
fn clicking_beside_the_back_arrow_does_not_close_the_file_page() {
let a = new_app();
let mut h = harness(a, egui::vec2(1440.0, 900.0));
h.state_mut().run("ui.backstage", json!({"value": true})).unwrap();
h.run_steps(4);
assert!(h.state().ui.backstage, "File page opened");
let back = h.get_by_label("Back").rect();
// Well clear of the back button but still inside the side menu rail.
let beside = egui::pos2(back.max.x + 50.0, back.center().y);
h.event(egui::Event::PointerMoved(beside));
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
h.run_steps(4);
assert!(h.state().ui.backstage, "clicking beside the arrow leaves the File page open");
}
+2 -10
View File
@@ -9,7 +9,6 @@ use std::cell::Cell;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use craft::behavior::intent::EditCommand;
use craft::behavior::kurbo::{Point, Size};
use craft::pages::layout::{Fit, LayoutOptions, PageDisplay, SCREEN_POINTS_PER_POINT};
use craft::pages::ui::reading::{ReadingMetrics, reading_size};
@@ -18,7 +17,7 @@ use craft::ui::canvas::{Autoscroll, ContextSource, MiddleButton, NavigationOptio
use craft::ui::contract::Show as _;
use craft::ui::runtime::env::Env;
use craft::ui::runtime::focus::{self, EditSet, FocusTarget};
use craft::ui::runtime::focus::{self, FocusTarget};
use craft::ui::style::DataColor;
use egui::{Color32, Pos2, Rect, Ui, pos2, vec2};
use serde_json::json;
@@ -645,7 +644,7 @@ fn sync_view_state(app: &WordApp, state: &mut PageViewState) {
// A wheel or pinch zoom is the view's own, anchored at the pointer, and reaches the session rounded to a whole
// percent (`show_pages`): the view keeps its exact zoom while it rounds to the session's, or the rounding would
// move the place under the pointer on the next pass.
let session_zoom = f64::from(if v.zoom.is_finite() { v.zoom.clamp(0.1, 5.0) } else { 1.0 });
let session_zoom = f64::from(v.zoom.clamp(0.1, 5.0));
if (state.zoom * 100.0).round() != (session_zoom * 100.0).round() {
state.zoom = session_zoom;
}
@@ -809,19 +808,12 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
let mut fix = ScrollFix::default();
// The caret the follow wants whose page the pass did not place: its page, the page's height and the caret.
let mut unplaced = None;
// The page answers for the linked Cut and Copy while it has focus: with nothing selected they are inactive, so the
// ribbon, the context menu and the command search grey them as production did.
let inactive_edits = [(EditCommand::Cut, "edit.cut"), (EditCommand::Copy, "edit.copy")]
.into_iter()
.filter(|(_, id)| !crate::app::command_board::command_enabled(app, id))
.fold(EditSet::NONE, |set, (command, _)| set.with(command));
let out = PageView::new(tl!("Document"), &source, &mut state, paper)
.options(options)
// Hide White Space cuts each page to its text area: without the bodies the pages show whole.
.bodies(&bodies)
.navigation(navigation_options())
.editor(craft::ui::primitives::EditorPurpose::Text)
.inactive_edits(inactive_edits)
.rulers(show_rulers)
.snap(crate::objects::snap(app, layout))
.tool_regions(regions)
+2 -3
View File
@@ -67,7 +67,7 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui, opener: &Response, ask: Optio
}
None => {}
}
if !open || app.modal_open() {
if !open {
app.canvas.context_menu_open = false;
app.canvas.context_menu_at = None;
return;
@@ -107,8 +107,7 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui, opener: &Response, ask: Optio
/// A row labelled `label` that runs command `id` with `params`; its chord, enabled state and
/// action come from the command, its wording from the menu (one command id serves several rows).
fn item(ui: &mut Ui, label: &str, id: &str, params: Value) {
// `MenuItem::command`, not `new(..).command(..)`: only the row's own binding shows the command's chord.
let _ = MenuItem::command(CommandRef::with_params(id, params)).label(tl!(label).to_string()).show(ui);
let _ = MenuItem::new(tl!(label).to_string()).command(CommandRef::with_params(id, params)).show(ui);
}
fn rule(ui: &mut Ui) {
-123
View File
@@ -2319,126 +2319,3 @@ fn a_linked_text_box_shows_and_follows_its_link_from_inside() {
let (start, _) = wordcraft_engine::cmd::insert::bookmark_range(&s.doc, "Spot").unwrap();
assert!(s.sel.is_collapsed() && s.sel.focus == start, "the caret went to the bookmark: {:?}", s.sel);
}
/// Unit-level checks for #7742 (`hostile_numbers_are_ignored` logic): invalid `ScrollSpeed`
/// codes, non-finite framework wheel/ease inputs, out-of-range `view.zoom` commands, and
/// `sync_view_state` recovery from non-finite `session.view.zoom`.
#[test]
fn hostile_scroll_and_zoom_logic_is_ignored() {
use crate::scroll::ScrollSpeed;
use craft::behavior::{Wheel, WheelEase, WheelPhase, WheelUnit};
use craft::keymap::{Mods, Platform};
use craft::ui::canvas::{NavigationOptions, WheelInput, WheelNavigation};
use egui::Vec2;
for bad in ["", "warp", "NaN", "infinity"] {
assert_eq!(ScrollSpeed::from_code(bad), None);
assert_eq!(ScrollSpeed::from(bad.to_string()), ScrollSpeed::Normal);
}
for speed in ScrollSpeed::ALL {
assert!(speed.wheel_factor().is_finite() && speed.wheel_factor() > 0.0);
assert!(speed.touchpad_factor().is_finite() && speed.touchpad_factor() > 0.0);
}
let mut nav_wheel = WheelNavigation::default();
let opts = NavigationOptions::default();
let wheel_input = |scroll: Vec2, zoom: f32| {
WheelInput::of(&Wheel::new(scroll, Mods::NONE, WheelUnit::Point, WheelPhase::Move).zoom(zoom), 16.0, Platform::current())
};
assert!(nav_wheel.classify(wheel_input(Vec2::new(f32::NAN, f32::INFINITY), 1.0), &opts).is_none());
assert!(nav_wheel.classify(wheel_input(Vec2::new(0.0, f32::NEG_INFINITY), 1.0), &opts).is_none());
for bad_zoom in [f32::NAN, f32::INFINITY, 0.0, -1.0] {
assert!(nav_wheel.classify(wheel_input(Vec2::ZERO, bad_zoom), &opts).is_none());
}
let mut ease = WheelEase::default();
ease.feed(Vec2::new(f32::NAN, f32::INFINITY), 1.0);
ease.feed(Vec2::new(0.0, -30.0), f64::NAN);
assert!(!ease.owes());
ease.feed(Vec2::new(0.0, -30.0), 1.0);
assert_eq!(ease.step(f64::NAN), Vec2::ZERO);
assert!(!ease.owes());
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
for bad_cmd in [json!({"value": -10.0}), json!({"value": 1e30}), json!({"value": "warp"})] {
assert!(app.run("view.zoom", bad_cmd).is_err());
}
let mut state = PageViewState::default();
state.zoom = 1.5;
for bad_zoom in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
app.session.view.zoom = bad_zoom;
sync_view_state(&app, &mut state);
assert_eq!(state.zoom, 1.0, "non-finite session zoom {bad_zoom:?} falls back to 1.0");
}
app.session.view.zoom = 1.25;
sync_view_state(&app, &mut state);
assert_eq!(state.zoom, 1.25);
}
/// Restored from pre-#7101 `scroll::tests::hostile_numbers_are_ignored` (#7317) against the
/// post-#7101 `ScrollSpeed` + `PageView` canvas wheel/zoom pipeline: hostile zoom/rotation
/// events, extreme finite wheel deltas, and non-finite view state are ignored or bounded
/// without poisoning `offset` or `zoom`.
#[test]
fn hostile_numbers_are_ignored() {
use egui::{Event, Modifiers, MouseWheelSource, MouseWheelUnit, TouchPhase, Vec2};
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("text.insert", json!({"text": "Page text"})).unwrap();
a.run("layout.break", json!({"kind": "page"})).unwrap();
a.run("view.commentsPane", json!({"value": false})).unwrap();
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(|_| a);
h.run_steps(2);
let at = h.state().canvas.shown.rect.center();
let wheel = |unit, delta, modifiers, source| Event::MouseWheel { unit, delta, phase: TouchPhase::Move, modifiers, source };
let finite_view = |app: &WordApp| {
let v = &app.canvas.view;
v.offset.0.is_finite() && v.offset.1.is_finite() && v.zoom.is_finite() && v.zoom > 0.0 && app.session.view.zoom.is_finite()
};
let start_offset = h.state().canvas.view.offset;
let start_zoom = h.state().canvas.view.zoom;
// Hostile zoom and rotation events over the canvas are ignored.
h.event(Event::PointerMoved(at));
for bad in [
Event::Zoom(f32::NAN),
Event::Zoom(f32::INFINITY),
Event::Zoom(0.0),
Event::Zoom(-1.0),
Event::Rotate(f32::NAN),
Event::Rotate(f32::INFINITY),
] {
h.event(bad);
}
h.run_steps(1);
assert!(finite_view(h.state()));
assert_eq!(h.state().canvas.view.offset, start_offset);
assert_eq!(h.state().canvas.view.zoom, start_zoom);
// Normal touchpad input scrolls down cleanly after hostile events.
h.event(wheel(MouseWheelUnit::Point, Vec2::new(0.0, -30.0), Modifiers::NONE, MouseWheelSource::Trackpad));
h.run_steps(1);
let scrolled_offset = h.state().canvas.view.offset;
assert!(scrolled_offset.1 > start_offset.1, "normal wheel input scrolls down: {scrolled_offset:?} vs {start_offset:?}");
// Huge finite deltas in both point and line units stay finite and clamped to document bounds.
h.event(wheel(MouseWheelUnit::Point, Vec2::new(0.0, -1e30), Modifiers::NONE, MouseWheelSource::Trackpad));
h.run_steps(1);
assert!(finite_view(h.state()));
assert!(h.state().canvas.view.offset.1.abs() < 1e6, "offset stays clamped to document bounds: {:?}", h.state().canvas.view.offset);
h.event(wheel(MouseWheelUnit::Line, Vec2::new(0.0, 1e30), Modifiers::NONE, MouseWheelSource::Wheel));
h.run_steps(1);
assert!(finite_view(h.state()));
assert!(h.state().canvas.view.offset.1.abs() < 1e6);
// Non-finite session zoom is clamped/recovered on the next pass without poisoning canvas state.
h.state_mut().session.view.zoom = f32::NAN;
h.run_steps(1);
assert!(h.state().canvas.view.zoom.is_finite() && h.state().canvas.view.zoom > 0.0);
assert!(h.state().canvas.view.offset.0.is_finite() && h.state().canvas.view.offset.1.is_finite());
}
@@ -273,38 +273,6 @@ fn a_bordered_table_shows_no_gridlines() {
assert_eq!(segs(&mut a), 6 * 4, "every edge of the six cells");
}
/// #5967: the gridlines of a table with very many rows are found in one pass over the rules, not
/// by re-sorting every rule on a line for each cell edge on it (a long table repainted slowly).
#[test]
fn table_gridlines_of_a_many_row_table_are_fast() {
const ROWS: usize = 30_000;
let line = wordcraft_doc::props::Border::single(0.5);
let mut items = Vec::new();
for i in 0..ROWS {
let y = i as f32 * 10.0;
items.push(Placed::Cell {
rect: wordcraft_geom::Rect::new(0.0, y, 10.0, 10.0),
covered: false,
table: Default::default(),
row: i,
cell: 0,
story: StoryRef::Body,
clip: false,
});
// One border piece per row on each side, so both vertical lines carry a rule per row.
for x in [0.0, 10.0] {
items.push(Placed::Rule { x0: x, y0: y, x1: x, y1: y + 10.0, border: line });
}
}
let page = Page { items, ..Default::default() };
let start = std::time::Instant::now();
let segs = gridline_segments(&page, true, None);
// Both sides are covered; the top and bottom of every cell are not.
assert_eq!(segs.len(), 2 * ROWS);
assert!(segs.iter().all(|(a, b)| a.y == b.y));
assert!(start.elapsed() < std::time::Duration::from_secs(5), "took {:?}", start.elapsed());
}
/// The drawing grid the page shows starts at the text area's top left, stays inside it, spaces
/// its lines by the settings the same both ways or differently across and down, and falls back
/// to the spec's 1/8 inch for a missing spacing.
+1 -1
View File
@@ -235,7 +235,7 @@ fn controls(app: &mut WordApp, ui: &mut Ui, fit: usize) -> Option<egui::Rect> {
// No command carries a checked state, so the view is given at the button (S-L415).
let out = ToggleButton::new(name.to_string(), Bind::given(on))
.command(CommandRef::new(id))
.icon(crate::icons::spec(icon))
.icon(crate::icons::id(icon))
.icon_only()
.tooltip(TooltipSpec::new(name.to_string()))
.show(ui);
-256
View File
@@ -164,31 +164,6 @@ fn undo_list_row_returns_focus_to_the_document() {
);
}
/// #1903: Cancel closes the undo list popover without undoing any steps.
#[test]
fn undo_list_cancel_closes_without_undoing() {
use egui::accesskit::Role;
let mut a = new_app();
a.run("text.insert", json!({"text": "Hello"})).unwrap();
let before: Vec<String> = a.session.undo_history().into_iter().map(str::to_string).collect();
assert!(!before.is_empty());
let text_before = a.session.doc.plain_text(wordcraft_doc::StoryRef::Body).to_string();
let mut h = harness(a);
h.get_by_label("Undo History").click();
crate::test_harness::frames(&mut h, 3);
assert_eq!(h.query_all_by_role(Role::ListBoxOption).count(), 1, "one row for typing");
let cancel = h.get_by_role_and_label(Role::Button, "Cancel");
cancel.click();
crate::test_harness::frames(&mut h, 3);
let after: Vec<String> = h.state().session.undo_history().into_iter().map(str::to_string).collect();
assert_eq!(after, before, "nothing undone");
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), text_before, "document text unchanged");
assert_eq!(h.query_all_by_role(Role::ListBoxOption).count(), 0, "Cancel closes the list");
}
/// #1975: the zoom percentage gains and loses digits (9% → 100% → 500%); the controls to its
/// left must not shift with it.
#[test]
@@ -523,144 +498,6 @@ fn status_bar_texts_stop_before_the_controls_in_a_narrow_window() {
assert!(painted_on_row_of(&wide, focus).iter().any(|(t, _)| t == "Track Changes: On"), "a wide window shows everything");
}
/// #5886: `Fit` picks the fullest step that fits, settles in one pass per unmeasured step, and drops stale
/// widths when a step's own width changes.
#[test]
fn status_fit_settles_and_resizes_without_discard_loops() {
let mut fit = super::Fit::default();
assert_eq!(fit.step(), 0);
// Narrow room (200): measures step 0 (300), then step 1 (180 <= 200), and settles at step 1.
assert!(fit.note(0, 300.0, 200.0));
assert_eq!(fit.step(), 1);
assert!(fit.note(1, 180.0, 200.0));
assert_eq!(fit.step(), 1);
assert!(!fit.note(1, 180.0, 200.0));
// Widening room (400) immediately selects cached step 0 without re-measuring step 1.
assert!(fit.note(1, 180.0, 400.0));
assert_eq!(fit.step(), 0);
assert!(!fit.note(0, 300.0, 400.0));
// A width change at step 0 invalidates cached widths for other steps.
assert!(fit.note(0, 320.0, 200.0));
assert_eq!(fit.step(), 1);
}
/// #5886: status bar controls fit is per-window and settles without repaint or discard loops across wide and narrow windows.
#[test]
fn status_bar_controls_width_cache_is_per_window_and_avoids_discard_loops() {
use std::time::Duration;
use craft_ui_test_kit::windows::Windows as Kit;
use egui::{Pos2, Rect, ViewportId, ViewportInfo, vec2};
// 1. Multi-window rendering (`Kit`): both wide (800 pt root) and narrow (400 pt child) windows
// render together on the same egui context each frame without overwriting each other's `status_fit`.
let kit = Kit::new();
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello")), crate::Services::default());
let win1 = a.windows.shown();
a.new_window();
let win2 = a.windows.shown();
assert_ne!(win1, win2, "two distinct windows open");
let info = |rect: Rect, is_focused: bool| ViewportInfo {
focused: Some(is_focused),
inner_rect: Some(rect),
outer_rect: Some(rect),
..Default::default()
};
let wide_rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
let narrow_rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 600.0));
let step_kit = |a: &mut WordApp, focus_root: bool| {
kit.root_info(info(wide_rect, focus_root));
kit.child_info(info(narrow_rect, !focus_root));
craft::ui::shell::embed::before_input(&kit.ctx, |out| a.frame_input(out));
kit.frame(Vec::new(), Vec::new(), |ui| {
a.logic(ui.ctx());
craft::ui::shell::embed::logic(ui.ctx(), || a.close_decision());
a.ui(ui);
})
};
let mut out = step_kit(&mut a, true);
for _ in 0..2 {
out = step_kit(&mut a, true);
}
let child_vp = out.trees.iter().map(|(id, _)| *id).find(|id| *id != ViewportId::ROOT).expect("child viewport rendered");
assert!(a.enter_window(win1));
let fit1 = a.chrome.status_fit.clone();
assert!(a.enter_window(win2));
let fit2 = a.chrome.status_fit.clone();
assert_eq!(fit1.step(), 0, "wide window stays at full controls step: {fit1:?}");
assert!(fit2.step() >= 1, "narrow window compacts controls (step >= 1): {fit2:?}");
assert_ne!(fit1, fit2, "per-window status fits are distinct");
let has_zoom_slider = |out: &craft_ui_test_kit::windows::Out, vp: ViewportId| {
let (_, tree) = out.trees.iter().find(|(id, _)| *id == vp).expect("viewport access tree");
tree.keys().into_iter().any(|key| tree.role_of(key) == Some(craft::ui::contract::Role::SLIDER) && tree.name_of(key) == Some("Zoom"))
};
assert!(has_zoom_slider(&out, ViewportId::ROOT), "wide window keeps the Zoom slider");
assert!(!has_zoom_slider(&out, child_vp), "narrow window drops the Zoom slider at step >= 1");
let frame_out = step_kit(&mut a, false);
assert!(has_zoom_slider(&frame_out, ViewportId::ROOT), "child-focused frame: wide window keeps Zoom slider");
assert!(!has_zoom_slider(&frame_out, child_vp), "child-focused frame: narrow window keeps compact controls");
assert!(a.enter_window(win1));
assert_eq!(a.chrome.status_fit, fit1, "wide window 1 settled without changes");
assert!(a.enter_window(win2));
assert_eq!(a.chrome.status_fit, fit2, "narrow window 2 settled without changes");
// 2. Direct single-pass inspection (`ctx.run_ui`): reuse `a` with one window, verify narrow (400 pt)
// and wide (1200 pt) layouts settle to distinct steps and run in 1 pass with no immediate repaint loop.
a.close_window(win2);
assert!(a.enter_window(win1));
let settle_one_pass = |app: &mut WordApp, width: f32, expect_compact: bool| -> super::Fit {
let run_pass = |app: &mut WordApp| -> (usize, Duration) {
let mut passes = 0;
craft::ui::shell::embed::before_input(&kit.ctx, |out| app.frame_input(out));
let full = kit.ctx.run_ui(
egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(width, 700.0))), ..Default::default() },
|ui| {
crate::test_harness::logic(ui.ctx(), app);
app.ui(ui);
passes += 1;
},
);
let delay = full.viewport_output.get(&ViewportId::ROOT).map_or(Duration::MAX, |v| v.repaint_delay);
full.drop_without_applying_deltas();
(passes, delay)
};
for _ in 0..4 {
let (_, delay) = run_pass(app);
let step_ok = if expect_compact { app.chrome.status_fit.step() >= 1 } else { app.chrome.status_fit.step() == 0 };
if delay > Duration::ZERO && step_ok {
break;
}
}
let settled = app.chrome.status_fit.clone();
if expect_compact {
assert!(settled.step() >= 1, "width {width}: settled at compact step: {settled:?}");
} else {
assert_eq!(settled.step(), 0, "width {width}: settled at full step: {settled:?}");
}
let (passes, delay) = run_pass(app);
assert_eq!(passes, 1, "width {width}: completed in 1 pass (no discard loop)");
assert!(delay > Duration::ZERO, "width {width}: requested no immediate repaint (delay {delay:?})");
assert_eq!(app.chrome.status_fit, settled, "width {width}: status_fit remained unchanged");
settled
};
let settled_narrow = settle_one_pass(&mut a, 400.0, true);
let settled_wide = settle_one_pass(&mut a, 1200.0, false);
assert_ne!(settled_narrow, settled_wide);
}
/// Finds the painted track and knob rects inside a rendered `craft::ui::choice::Switch`.
/// `Switch` sets `PARTS = false` and exposes only its `Role::Switch` node and toggled state, so
/// the thumb position is read from the unblurred filled shapes painted inside the switch rect.
@@ -751,99 +588,6 @@ fn the_autosave_knob_sits_right_when_on_and_mirrors_right_to_left() {
assert!(((ltr_off_knob.center().x - ltr_off_track.min.x) - (rtl_off_track.max.x - rtl_off_knob.center().x)).abs() <= 0.5);
}
/// Refs #7320: hovering buttons across the Ribbon, title bar (Quick Access Toolbar), and status
/// bar produces a settled rounded hover fill matching the active theme's hover state token, and
/// clears when unhovered.
#[test]
fn ribbon_and_chrome_buttons_have_responsive_hover_lighting_and_contrast() {
use egui::accesskit::Role;
fn to_color32(rgba: craft::theme::Rgba) -> egui::Color32 {
egui::Color32::from(craft::theme::Srgba::from(rgba))
}
fn collect_shapes<'a>(shapes: &'a [egui::epaint::ClippedShape], out: &mut Vec<&'a egui::Shape>) {
for clipped in shapes {
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
match shape {
egui::Shape::Vec(children) => {
for child in children {
walk(child, out);
}
}
other => out.push(other),
}
}
walk(&clipped.shape, out);
}
}
fn find_button_fill(shapes: &[egui::epaint::ClippedShape], rect: egui::Rect) -> Option<(egui::Color32, egui::CornerRadius)> {
let mut flattened = Vec::new();
collect_shapes(shapes, &mut flattened);
flattened.into_iter().find_map(|s| match s {
egui::Shape::Rect(r)
if (r.rect.min.x - rect.min.x).abs() <= 1.5
&& (r.rect.max.x - rect.max.x).abs() <= 1.5
&& (r.rect.min.y - rect.min.y).abs() <= 1.5
&& (r.rect.max.y - rect.max.y).abs() <= 1.5
&& r.fill != egui::Color32::TRANSPARENT =>
{
Some((r.fill, r.corner_radius))
}
_ => None,
})
}
for theme in ["light", "dark"] {
let mut a = new_app();
a.run("text.insert", json!({"text": "Hello"})).unwrap();
a.run("select.all", json!({})).unwrap();
a.run("ui.theme", json!({"value": theme})).unwrap();
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 700.0)).with_step_dt(0.016).build_ui_state(app_frame, a);
// Ensure animation time is enabled so responsive tweening runs as in a live window.
h.ctx.all_styles_mut(|s| s.animation_time = egui::Style::default().animation_time);
crate::test_harness::frames(&mut h, 10);
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
let expected_hover = to_color32(env.tokens.color.state.hover);
// Test representative buttons across Ribbon, title bar QAT, and status bar.
for (role, label, desc) in [
(Role::Button, "Cut", "Ribbon tool button"),
(Role::Button, "Save", "Quick Access Toolbar button"),
(Role::Button, "100%", "Status bar zoom button"),
] {
let node = h.get_by_role_and_label(role, label);
let rect = node.rect();
assert!(rect.is_positive(), "{theme}: {desc} ({label}) must have positive rect");
// Before hover: no hover fill plate
let fill_before = find_button_fill(&h.output().shapes, rect);
assert_eq!(fill_before, None, "{theme}: {desc} ({label}) must have no hover fill before hover");
// Hover the control and allow animation to settle
node.hover();
crate::test_harness::frames(&mut h, 8);
let fill_settled = find_button_fill(&h.output().shapes, rect);
assert!(fill_settled.is_some(), "{theme}: {desc} ({label}) must produce settled hover shape");
let (settled, radius) = fill_settled.unwrap();
assert_eq!(settled, expected_hover, "{theme}: {desc} ({label}) settled hover fill must match theme hover token");
assert!(
radius.nw > 0 && radius.nw == radius.ne && radius.nw == radius.sw && radius.nw == radius.se,
"{theme}: {desc} ({label}) corner radius must be uniformly rounded: {:?}",
radius
);
// Leaving hover clears the hover fill plate
h.event(egui::Event::PointerMoved(egui::pos2(0.0, 0.0)));
crate::test_harness::frames(&mut h, 8);
let fill_after = find_button_fill(&h.output().shapes, rect);
assert_eq!(fill_after, None, "{theme}: {desc} ({label}) must clear hover fill after unhovering");
}
}
}
/// #7311: the title bar's Discord community button keeps its solid accent fill and contrasting
/// `on_strong` icon/label in both wide (pill with label) and narrow (compact icon-only) windows,
/// across Light and Dark themes, and still dispatches `ui.discord` when clicked.
+1 -1
View File
@@ -540,7 +540,7 @@ pub fn more_colors(current: Option<Rgb>, key: String, tab: ColorPickerTab) -> Co
}
/// Opens the Colors dialog for `target`, remembering where its answer goes.
pub(crate) fn open_for(app: &mut WordApp, target: &Target, current: Option<Rgb>, tab: ColorPickerTab) -> DialogId {
fn open_for(app: &mut WordApp, target: &Target, current: Option<Rgb>, tab: ColorPickerTab) -> DialogId {
app.more_colors.insert(MORE_KEY.to_string(), target.clone());
crate::dialogs::host::open_with(app, None, more_colors(current, MORE_KEY.to_string(), tab), DialogHooks { prepare: None, settle: settle_more })
}
+2 -40
View File
@@ -245,40 +245,13 @@ impl WordForm for CompareForm {
fn applied(&mut self, app: &mut WordApp, filed: Filed, outcome: Result<&[Value], &str>) {
if matches!(filed, Filed::Ok)
&& let Ok(results) = outcome
&& let Some(result) = results.first()
&& let Some(changes) = results.first().and_then(|r| r.get("changes")).and_then(Value::as_u64)
{
app.status(compare_status_message(result));
app.status(format!("Compared: {changes} changes"));
}
}
}
fn compare_status_message(v: &Value) -> String {
let n = v.get("changes").and_then(Value::as_u64).unwrap_or(0).to_string();
let base = crate::i18n::fmt(tl!("Compared: {changes} changes"), &[("changes", &n)]);
let unsupported: Vec<&str> = v
.get("notHonoured")
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(Value::as_str)
.filter(|k| matches!(*k, "tables" | "level"))
.map(|k| match k {
"tables" => tl!("Tables"),
"level" => tl!("Character level"),
_ => k,
})
.collect()
})
.unwrap_or_default();
if unsupported.is_empty() {
base
} else {
let list = unsupported.join(", ");
crate::i18n::fmt(tl!("{status} (not compared: {items})"), &[("status", &base), ("items", &list)])
}
}
// ---------------------------------------------------------------------------------------------
// AutoCorrect Options
@@ -773,15 +746,4 @@ mod tests {
let (left, right) = (h.get_by_label("Character level").rect(), h.get_by_label("Show changes in:").rect());
assert!(right.left() >= left.right(), "the columns overlap: {left:?} {right:?}");
}
#[test]
fn compare_status_message_surfaces_not_honoured_limitations() {
assert_eq!(compare_status_message(&json!({"changes": 3, "notHonoured": []})), "Compared: 3 changes");
assert_eq!(compare_status_message(&json!({"changes": 1, "notHonoured": ["moves", "comments"]})), "Compared: 1 changes");
assert_eq!(compare_status_message(&json!({"changes": 0, "notHonoured": ["moves", "tables"]})), "Compared: 0 changes (not compared: Tables)");
assert_eq!(
compare_status_message(&json!({"changes": 2, "notHonoured": ["tables", "level"]})),
"Compared: 2 changes (not compared: Tables, Character level)"
);
}
}
-26
View File
@@ -113,12 +113,6 @@ fn confirm(h: &mut egui_kittest::Harness<'_, WordApp>, id: DialogId) {
h.run_steps(3);
}
fn cancel(h: &mut egui_kittest::Harness<'_, WordApp>, id: DialogId) {
let ctx = h.ctx.clone();
h.state_mut().dialog_host.cancel_by_id(&ctx, id);
h.run_steps(3);
}
/// Opens the Paragraph dialog, edits what it shows through its fields, as automation does, and answers OK.
fn apply_paragraph(h: &mut egui_kittest::Harness<'_, WordApp>, edit: impl FnOnce(&mut ParagraphFormat)) {
let id = open_named(h, "paragraph", json!({}));
@@ -792,26 +786,6 @@ fn font_dialog_sets_the_asian_and_latin_fonts_separately() {
assert_ne!(fonts(h.state()).0.as_deref(), Some("Georgia"));
}
/// #3859: the page's context menu closes when a modal dialog opens (Ctrl+D),
/// while modeless dialogs (Find/Replace) leave it open.
#[test]
fn a_modal_dialog_closes_the_context_menu() {
let mut h = app_harness(WordApp::new(Session::new(wordcraft_doc::Document::from_text("Kilns")), crate::Services::default()));
h.run_steps(6);
let find_id = open_named(&mut h, "find", json!({}));
h.run_steps(2);
h.state_mut().run("ui.contextMenu", json!({})).unwrap();
h.run_steps(2);
assert!(h.state().canvas.context_menu_open, "a modeless dialog keeps the context menu open");
cancel(&mut h, find_id);
let id = open_named(&mut h, "font", json!({}));
h.run_steps(2);
assert!(!h.state().canvas.context_menu_open, "the modal dialog closed it");
cancel(&mut h, id);
}
#[test]
fn font_dialog_ok_keeps_what_the_user_left_alone() {
// Issue #466: OK sent every field, clearing small caps, spacing and double underline
-24
View File
@@ -439,28 +439,4 @@ mod tests {
a.run("file.new", json!({})).unwrap();
assert_eq!(titles(&a), ["Document1", "Document2"]);
}
/// #7672: a template opened from File › Home after Ctrl+W takes typing without a click on the page. The tile's
/// press moves egui focus at the end of its pass, so a focus request made in that pass was lost.
#[test]
fn a_template_opened_from_home_after_closing_takes_typing() {
use egui_kittest::kittest::Queryable;
let mut h = harness(app());
crate::test_harness::frames(&mut h, 3);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::W);
crate::test_harness::frames(&mut h, 4);
h.state_mut().run("ui.backstage", json!({"page": "home"})).unwrap();
crate::test_harness::frames(&mut h, 4);
let at = h.get_by_label("Studio handbook (sample)").rect().center();
let button =
|pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
h.input_mut().events.extend([egui::Event::PointerMoved(at), button(true)]);
crate::test_harness::frames(&mut h, 1);
h.event(button(false));
crate::test_harness::frames(&mut h, 6);
assert!(!h.state().ui.backstage, "the tile opened the template");
h.event(egui::Event::Text("QQ".into()));
crate::test_harness::frames(&mut h, 3);
assert!(text(h.state()).contains("QQ"), "the typing reached the page");
}
}
+10 -10
View File
@@ -208,7 +208,7 @@ fn builtin_menu(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
pub fn insert_button(ui: &mut Ui, app: &mut WordApp) {
SplitButton::<bool>::command("insert.equation", SplitMenu::Body(Box::new(|ui, cx| builtin_menu(ui, cx, app))))
.label(tl!("Equation").to_string())
.icon(crate::icons::spec("equation"))
.icon(IconId::new("equation"))
.arrangement(Arrangement::Stacked)
.show(ui);
}
@@ -279,22 +279,22 @@ pub fn show(row: &mut RibbonRow<'_>, app: &mut WordApp) {
let numbered = info.is_some_and(|(_, linear)| linear.contains('#'));
let latex = app.session.math_latex;
let normal_text = app.session.math_normal_text;
row.group(RibbonGroup::new("tools", tl!("Tools").to_string(), crate::icons::spec("equation")), |ui| {
row.group(RibbonGroup::new("tools", tl!("Tools").to_string(), IconId::new("equation").into()), |ui| {
math_menu_button(ui, EQUATION_PICTURE, "Equation", |ui, cx| builtin_menu(ui, cx, app));
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
ToggleButton::command(CommandRef::with_params("equation.inputFormat", json!({"format": "unicode"})))
.label(tl!("Unicode").to_string())
.icon(crate::icons::spec("equation"))
.icon(IconId::new("equation"))
.tooltip(tl!("Type equations in the linear format (UnicodeMath)").to_string())
.selected(!latex)
.show(ui);
ToggleButton::command(CommandRef::with_params("equation.inputFormat", json!({"format": "latex"})))
.label(tl!("LaTeX").to_string())
.icon(crate::icons::spec("formula"))
.icon(IconId::new("formula"))
.tooltip(tl!("Type equations in LaTeX").to_string())
.selected(latex)
.show(ui);
let face = Button::new(tl!("Convert").to_string()).icon(crate::icons::spec("replace"));
let face = Button::new(tl!("Convert").to_string()).icon(IconId::new("replace"));
let _ = menu_button(ui, face, tl!("Convert").to_string(), None, |ui, _| {
for (label, to, all) in [
("Current - Professional", "professional", false),
@@ -311,20 +311,20 @@ pub fn show(row: &mut RibbonRow<'_>, app: &mut WordApp) {
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
ToggleButton::command(CommandRef::new("equation.normalText"))
.label(tl!("Normal Text").to_string())
.icon(crate::icons::spec("case"))
.icon(IconId::new("case"))
.tooltip(tl!("Type normal (non-math) text in the equation").to_string())
.selected(normal_text)
.show(ui);
});
});
row.group(RibbonGroup::new("symbols", tl!("Symbols").to_string(), crate::icons::spec("symbol")), |ui| symbols(ui, app));
row.group(RibbonGroup::new("structures", tl!("Structures").to_string(), crate::icons::spec("equation")), |ui| {
row.group(RibbonGroup::new("symbols", tl!("Symbols").to_string(), IconId::new("symbol").into()), |ui| symbols(ui, app));
row.group(RibbonGroup::new("structures", tl!("Structures").to_string(), IconId::new("equation").into()), |ui| {
for g in STRUCTURES {
let id = g.id;
math_menu_button(ui, button_picture(id), g.label, |ui, cx| structure_menu(ui, cx, app, id));
}
});
row.group(RibbonGroup::new("equationOptions", tl!("Equation Options").to_string(), crate::icons::spec("equation")), |ui| {
row.group(RibbonGroup::new("equationOptions", tl!("Equation Options").to_string(), IconId::new("equation").into()), |ui| {
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
ToggleButton::command(CommandRef::with_params("equation.display", json!({"value": true})))
.label(tl!("Display").to_string())
@@ -340,7 +340,7 @@ pub fn show(row: &mut RibbonRow<'_>, app: &mut WordApp) {
.show(ui);
ToggleButton::command(CommandRef::new("equation.number"))
.label(tl!("Number").to_string())
.icon(crate::icons::spec("numbering"))
.icon(IconId::new("numbering"))
.tooltip(tl!("Number the equation; the number sits at the right margin (or type # then the number)").to_string())
.selected(numbered)
.show(ui);
-55
View File
@@ -45,58 +45,3 @@ fn a_dialog_closing_into_the_browser_leaves_it_the_keyboard() {
let after_doc = h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body);
assert_eq!(after_doc, before_doc, "typing does not leak into the document behind the browser");
}
/// #3859: no keytips behind the browser.
#[test]
fn no_keytips_behind_the_browser() {
let a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
let mut h = crate::test_harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
crate::test_harness::logic(&ctx, app);
app.ui(ui);
},
a,
);
crate::test_harness::frames(&mut h, 4);
let ctx = h.ctx.clone();
h.state_mut().canvas.focus_page(&ctx);
crate::test_harness::frames(&mut h, 2);
let keytip_badges = |h: &egui_kittest::Harness<'_, WordApp>| -> Vec<String> {
const TAB_BADGES: [&str; 11] = ["F", "H", "N", "D", "G", "P", "S", "M", "R", "W", "Y"];
h.output()
.shapes
.iter()
.filter_map(|s| match &s.shape {
egui::Shape::Text(t) if TAB_BADGES.contains(&t.galley.text()) => Some(t.galley.text().to_string()),
_ => None,
})
.collect()
};
assert!(!h.state().keytips_active, "keytips start off");
assert!(keytip_badges(&h).is_empty(), "no keytip badges start painted: {:?}", keytip_badges(&h));
let folders = FolderCache::new(Arc::new(FakeDirectories::new().folder("/d/drafts")), Arc::new(ManualJobs::new()), Wake::none());
let req = PickRequest::open("document").directory("/d").fallback(true);
h.state_mut().dialog_host.open(FileChooser::new(req, None, folders));
crate::test_harness::frames(&mut h, 4);
assert!(h.state().dialog_host.is_open::<FileChooser>(), "the browser is open");
h.key_press(egui::Key::F10);
crate::test_harness::frames(&mut h, 2);
assert!(!h.state().keytips_active, "F10 does not activate keytips while the browser is open");
assert!(keytip_badges(&h).is_empty(), "no keytip badges are painted behind the browser: {:?}", keytip_badges(&h));
// Close the browser and check F10 works as a control.
h.key_press(egui::Key::Escape);
crate::test_harness::frames(&mut h, 4);
assert!(!h.state().dialog_host.is_open::<FileChooser>(), "Escape closes the browser");
assert!(!h.state().modal_open(), "no modal remains open after closing the browser");
h.key_press(egui::Key::F10);
crate::test_harness::frames(&mut h, 2);
assert!(h.state().keytips_active, "F10 activates keytips once the browser is closed");
assert!(!keytip_badges(&h).is_empty(), "keytip badges paint once the browser is closed");
}
+16 -703
View File
@@ -1,10 +1,11 @@
//! The Format Shape pane (Shape Fill › More Gradients…, a shape's Format Shape…): the selected
//! shapes' fill, outline, and layout settings (size, rotation, text direction, and alignment).
//! Every change runs the corresponding shape command; a drag applies as it goes and undoes in one step.
//! shapes' fill, as Word's Fill section: no fill, a solid colour with its transparency, or a
//! gradient (preset, type, direction, angle, stops, rotate with shape). Every change runs
//! `shape.fill` with the whole fill; a drag applies as it goes and undoes in one step.
use std::sync::Arc;
use craft::behavior::{EditEvents, Mixed, Value};
use craft::behavior::{EditEvents, Value};
use craft::color_ui::gradient::{ColorStop, GradientStops, StopRows, StopRules};
use craft::color_ui::ui::gradient::{GradientEditor, StopRef};
// PLAN: assumed craft::draw::ui exports these (ch.C15)
@@ -23,10 +24,8 @@ use craft::ui::pickers::Select;
use craft::ui::popover::Popover;
use craft::ui::runtime::env::{Label, UnitKind};
use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value};
use craft::ui::sections::{HeaderStrength, Section};
use craft::ui::text::NumberField;
use egui::{Ui, pos2};
use serde_json::json;
use wordcraft_doc::Rgb;
use wordcraft_doc::fill::{Fill, Gradient, GradientKind, PathShape};
use wordcraft_doc::para::InlineObject;
@@ -59,129 +58,15 @@ pub(crate) fn remember_variation(app: &mut WordApp, pos: wordcraft_doc::Pos, fil
app.shape_variation = Some(Variation(pos, fill, base));
}
/// All selected shapes and drawing canvases (or the active text box containing the caret).
fn target_shapes(app: &WordApp) -> Vec<(wordcraft_doc::Pos, InlineObject)> {
wordcraft_engine::cmd::objects::target_objects(&app.session, |o| matches!(o, InlineObject::Shape { .. }) || o.is_canvas())
}
/// The first selected shape's or canvas's object: `None` with no shape or canvas active.
pub(crate) fn current_object(app: &WordApp) -> Option<(wordcraft_doc::Pos, InlineObject)> {
target_shapes(app).into_iter().next()
}
fn fill_of(o: &InlineObject) -> Option<Fill> {
match o {
InlineObject::Shape { fill, .. } => fill.clone(),
o => o.canvas_style().and_then(|c| c.fill.clone()),
}
}
fn fill_kind_of(fill: &Option<Fill>) -> u8 {
match fill {
None => 0,
Some(Fill::Solid { .. }) => 1,
Some(Fill::Gradient(_)) => 2,
}
}
/// The first selected shape's or canvas's fill: `None` with no shape selected.
pub(crate) fn current(app: &WordApp) -> Option<Option<Fill>> {
let (_, o) = current_object(app)?;
let (_, o) = wordcraft_engine::cmd::objects::selected(&app.session)?;
match o {
InlineObject::Shape { fill, .. } => Some(fill),
o => o.canvas_style().map(|c| c.fill.clone()),
}
}
/// The selected shape's outline properties (summarized across all selected shapes/canvases).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct CurrentLine {
/// Whether all targets have a line (`Some(true)`), none do (`Some(false)`), or mixed (`None`).
pub has_line: Option<bool>,
/// The representative stroke colour (`None` when no target has an outline).
pub stroke: Option<Rgb>,
/// The representative stroke width in points.
pub width: f32,
/// The representative dash style.
pub dash: wordcraft_doc::line_dash::LineDash,
/// Whether selected non-canvas shapes disagree on dash style.
pub dash_mixed: bool,
/// The representative line cap style.
pub cap: wordcraft_doc::connector::LineCap,
/// Whether selected non-canvas shapes disagree on cap style.
pub cap_mixed: bool,
/// Whether all targets are drawing canvases (canvas outlines do not support dash or cap styles).
pub is_canvas: bool,
}
fn line_item(o: &InlineObject) -> Option<(Option<Rgb>, f32, wordcraft_doc::line_dash::LineDash, wordcraft_doc::connector::LineCap, bool)> {
match o {
InlineObject::Shape { stroke, stroke_width, extra, .. } => Some((*stroke, *stroke_width, extra.dash.clone(), extra.cap, false)),
o => o
.canvas_style()
.map(|c| (c.stroke, c.stroke_width, wordcraft_doc::line_dash::LineDash::Solid, wordcraft_doc::connector::LineCap::Flat, true)),
}
}
/// The selected shapes' or canvases' outline summary: `None` when no shape or canvas is selected.
pub(crate) fn current_line(app: &WordApp) -> Option<CurrentLine> {
let shapes = target_shapes(app);
let items: Vec<_> = shapes.iter().filter_map(|(_, o)| line_item(o)).collect();
let first = items.first()?;
let any_line = items.iter().any(|x| x.0.is_some());
let all_line = items.iter().all(|x| x.0.is_some());
let has_line = (all_line || !any_line).then_some(all_line);
let rep = items.iter().find(|x| x.0.is_some()).unwrap_or(first);
let shape_items: Vec<_> = items.iter().filter(|x| !x.4).collect();
let shape_rep = shape_items.first().copied().unwrap_or(rep);
let dash_mixed = shape_items.windows(2).any(|w| w[0].2 != w[1].2);
let cap_mixed = shape_items.windows(2).any(|w| w[0].3 != w[1].3);
Some(CurrentLine {
has_line,
stroke: rep.0,
width: rep.1,
dash: shape_rep.2.clone(),
dash_mixed,
cap: shape_rep.3,
cap_mixed,
is_canvas: items.iter().all(|x| x.4),
})
}
/// The selected shape's or text box's layout properties.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct CurrentLayout {
/// Width in points.
pub width: f32,
/// Height in points.
pub height: f32,
/// Rotation in degrees.
pub rotation: f32,
/// Whether any target is a text box.
pub is_text_box: bool,
/// The primary target text box's body properties.
pub text_body: Option<wordcraft_doc::TextBody>,
/// Whether selected text boxes disagree on vertical alignment.
pub anchor_mixed: bool,
/// Whether selected text boxes disagree on text direction.
pub vert_mixed: bool,
}
/// The selected shapes' or text boxes' layout: size, rotation, and text body settings.
pub(crate) fn current_layout(app: &WordApp) -> Option<CurrentLayout> {
let (_, o) = current_object(app)?;
let (width, height, float) = o.frame()?;
let bodies: Vec<wordcraft_doc::TextBody> = wordcraft_engine::cmd::objects::text_box_targets(&app.session)
.into_iter()
.filter_map(|(_, id)| app.session.doc.parts.get(&id).map(|p| p.body))
.collect();
let is_text_box = !bodies.is_empty();
let text_body = bodies.first().copied();
let anchor_mixed = bodies.windows(2).any(|w| w[0].anchor != w[1].anchor);
let vert_mixed = bodies.windows(2).any(|w| w[0].vert != w[1].vert);
Some(CurrentLayout { width, height, rotation: float.spin().deg, is_text_box, text_body, anchor_mixed, vert_mixed })
}
/// Sets the selected shapes' fill.
fn apply(app: &mut WordApp, fill: Option<&Fill>) {
let _ = app.run("shape.fill", shape_fill::params(fill));
@@ -252,17 +137,17 @@ pub(crate) fn fill_tile(fill: &Fill) -> (GradientStops, GradientTile) {
/// The pane, while open.
pub fn pane(app: &mut WordApp, ui: &mut Ui) {
let shapes = target_shapes(app);
let Some((_, first)) = shapes.first() else {
Notice::new(Tone::Neutral, tl!("Select a shape, text box or drawing canvas to format it.")).show(ui);
let Some(fill) = current(app) else {
Notice::new(Tone::Neutral, tl!("Select a shape, text box or drawing canvas to format its fill.")).show(ui);
return;
};
let fill = fill_of(first);
let theme = app.session.doc.settings.theme_colors.clone();
let first_kind = fill_kind_of(&fill);
let fill_mixed = shapes.iter().skip(1).any(|(_, o)| fill_kind_of(&fill_of(o)) != first_kind);
let shown_kind = if fill_mixed { Mixed::Mixed } else { Mixed::Same(first_kind) };
let shown = RadioGroup::new(tl!("Fill"), Bind::given(shown_kind)).show(ui, |ui, _| {
let kind: u8 = match &fill {
None => 0,
Some(Fill::Solid { .. }) => 1,
Some(Fill::Gradient(_)) => 2,
};
let shown = RadioGroup::new(tl!("Fill"), Bind::given(kind)).show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
Radio::new(0u8).label(tl!("No fill")).show(ui);
Radio::new(1u8).label(tl!("Solid fill")).show(ui);
@@ -270,7 +155,7 @@ pub fn pane(app: &mut WordApp, ui: &mut Ui) {
});
});
if let Some(pick) = shown.output.events.committed().copied()
&& (fill_mixed || pick != first_kind)
&& pick != kind
{
let accent1 = theme.get(4).copied().unwrap_or(Rgb(68, 114, 196));
let main = fill.as_ref().map_or(accent1, Fill::main_color);
@@ -287,218 +172,6 @@ pub fn pane(app: &mut WordApp, ui: &mut Ui) {
Some(Fill::Gradient(g)) => gradient(app, ui, &g),
None => {}
}
if let Some(line) = current_line(app) {
Section::fixed(tl!("Line")).show(ui, |ui, _| line_section(app, ui, &theme, &line));
}
if let Some(layout) = current_layout(app) {
Section::fixed(tl!("Layout & Properties")).show(ui, |ui, _| layout_section(app, ui, &layout));
}
}
/// Draws a labelled preset Select for an optional current choice (`None` when mixed or custom)
/// and returns the newly picked preset parameter when the selection changes.
fn preset_select<'a>(
ui: &mut Ui,
label_text: &str,
id_salt: &str,
options: &[(&str, &'a str)],
orig_idx: Option<usize>,
mixed: bool,
custom_label: Option<&str>,
) -> Option<&'a str> {
let entries: Vec<Entry<usize>> = options.iter().enumerate().map(|(i, (opt_label, _))| Entry::new(i, tl!(opt_label).to_owned())).collect();
let shown = if mixed { Mixed::Mixed } else { Mixed::Same(orig_idx.unwrap_or(usize::MAX)) };
let label = Label::from(label_text.to_owned());
let custom = custom_label.map(|c| Label::from(c.to_owned()));
let picked = Field::new(label.clone())
.id_salt(id_salt)
.show(ui, |ui, _| {
let mut select = Select::new(label.clone(), Bind::given(shown), &entries);
if let Some(custom) = custom.clone() {
select = select.placeholder(custom);
}
select.show(ui).events.committed().copied()
})
.inner
.flatten();
picked.filter(|&i| Some(i) != orig_idx).and_then(|i| options.get(i).map(|o| o.1))
}
/// Draws the Line section: No line or Solid line (color, width, dash type, cap type).
fn line_section(app: &mut WordApp, ui: &mut Ui, theme: &[Rgb], line: &CurrentLine) {
let has_line = line.has_line.map_or(Mixed::Mixed, Mixed::Same);
let shown = RadioGroup::new(tl!("Line"), Bind::given(has_line)).show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
Radio::new(false).label(tl!("No line")).show(ui);
Radio::new(true).label(tl!("Solid line")).show(ui);
});
});
if let Some(solid_line) = shown.output.events.committed().copied()
&& line.has_line != Some(solid_line)
{
if !solid_line {
let _ = app.run("shape.outline", json!({"color": null}));
} else {
let accent1 = theme.get(4).copied().unwrap_or(Rgb(68, 114, 196));
let w = if line.width > 0.0 { line.width } else { 0.75 };
let _ = app.run("shape.outline", json!({"color": accent1.hex(), "width": w}));
}
return;
}
if let Some(color) = line.stroke {
let palette = Palette { theme: theme.to_vec(), recent: Vec::new() };
let mut hex = color.hex();
let label: Label = tl!("Color").into();
let picked = ui.push_id("line_color", |ui| color_field(ui, &label, &mut hex, &ColorFieldEmpty::NoColor, &palette)).inner;
if picked.more_colors {
colors::open_for(app, &Target::cmd("shape.outline"), Some(color), craft::color_ui::ui::ColorPickerTab::Standard);
return;
}
if picked.changed {
if hex.is_empty() {
let _ = app.run("shape.outline", json!({"color": null}));
return;
}
if let Some(n) = Rgb::parse(&hex) {
let _ = app.run("shape.outline", json!({"color": n.hex()}));
}
}
let mut width_events = EditEvents::new();
Field::new(tl!("Width")).id_salt("format_shape.line_width").show(ui, |ui, _| {
width_events = NumberField::new(tl!("Width"), Bind::given(Some(f64::from(line.width))))
.unit_kind(UnitKind::Points)
.range(0.25..=72.0)
.step(0.25)
.fixed_decimals(2)
.show(ui)
.edit
.events;
});
crate::undo_marks::apply_edits(app, width_events, |app, v: Option<f64>| {
if let Some(w) = v.filter(|w| (0.25..=72.0).contains(w)) {
let _ = app.run("shape.outline", json!({"width": w}));
}
});
if !line.is_canvas {
const DASHES: [(&str, &str); 11] = [
("Solid", "solid"),
("Round Dot", "dot"),
("Square Dot", "sysDot"),
("Dash", "dash"),
("Dash Dot", "dashDot"),
("Long Dash", "lgDash"),
("Long Dash Dot", "lgDashDot"),
("Long Dash Dot Dot", "lgDashDotDot"),
("System Dash", "sysDash"),
("System Dash Dot", "sysDashDot"),
("System Dash Dot Dot", "sysDashDotDot"),
];
let is_custom = !line.dash_mixed && matches!(line.dash, wordcraft_doc::line_dash::LineDash::Custom(_));
let orig_dash_idx = if line.dash_mixed || is_custom {
None
} else {
let current_dash_str = line.dash.ooxml().unwrap_or("solid");
DASHES.iter().position(|(_, k)| *k == current_dash_str).or(Some(0))
};
if let Some(dash) = preset_select(
ui,
tl!("Dash type"),
"format_shape.dash_type",
&DASHES,
orig_dash_idx,
line.dash_mixed,
is_custom.then(|| tl!("Custom")),
) {
let _ = app.run("shape.outline", json!({"dash": dash}));
}
const CAPS: [(&str, &str); 3] = [("Flat", "flat"), ("Round", "rnd"), ("Square", "sq")];
let orig_cap_idx = if line.cap_mixed {
None
} else {
let current_cap_str = line.cap.ooxml();
CAPS.iter().position(|(_, k)| *k == current_cap_str).or(Some(0))
};
if let Some(cap) = preset_select(ui, tl!("Cap type"), "format_shape.cap_type", &CAPS, orig_cap_idx, line.cap_mixed, None) {
let _ = app.run("shape.outline", json!({"cap": cap}));
}
}
}
}
/// Draws the Size & Properties / Text Box layout section.
fn layout_section(app: &mut WordApp, ui: &mut Ui, layout: &CurrentLayout) {
for (label, id_salt, key, value) in
[(tl!("Width"), "format_shape.layout_width", "width", layout.width), (tl!("Height"), "format_shape.layout_height", "height", layout.height)]
{
let mut events = EditEvents::new();
Field::new(label).id_salt(id_salt).show(ui, |ui, _| {
events = NumberField::new(label, Bind::given(Some(f64::from(value))))
.unit_kind(UnitKind::Points)
.range(1.0..=4000.0)
.commit_decimals(1)
.show(ui)
.edit
.events;
});
crate::undo_marks::apply_edits(app, events, move |app, v: Option<f64>| {
if let Some(val) = v.filter(|val| (1.0..=4000.0).contains(val)) {
let _ = app.run("shape.size", json!({ key: val, "lockAspect": false }));
}
});
}
let mut rot_events = EditEvents::new();
Field::new(tl!("Rotation")).id_salt("format_shape.rotation").show(ui, |ui, _| {
rot_events = NumberField::new(tl!("Rotation"), Bind::given(Some(f64::from(layout.rotation))))
.unit_kind(UnitKind::Degrees)
.range(0.0..=360.0)
.commit_decimals(1)
.show(ui)
.edit
.events;
});
crate::undo_marks::apply_edits(app, rot_events, |app, v: Option<f64>| {
if let Some(degrees) = v.filter(|d| (0.0..=360.0).contains(d)) {
let _ = app.run("shape.rotation", json!({"degrees": degrees}));
}
});
if layout.is_text_box || layout.text_body.is_some() {
let body = layout.text_body.unwrap_or_default();
Section::fixed(tl!("Text Box")).strength(HeaderStrength::Caption).show(ui, |ui, _| {
const VALIGNS: [(wordcraft_doc::props::VAlign, &str, &str); 3] = [
(wordcraft_doc::props::VAlign::Top, "Top", "t"),
(wordcraft_doc::props::VAlign::Center, "Middle", "ctr"),
(wordcraft_doc::props::VAlign::Bottom, "Bottom", "b"),
];
const VALIGN_OPTS: [(&str, &str); 3] = [("Top", "t"), ("Middle", "ctr"), ("Bottom", "b")];
let orig_valign_idx = (!layout.anchor_mixed).then(|| VALIGNS.iter().position(|(a, _, _)| *a == body.anchor).unwrap_or(0));
if let Some(anchor) =
preset_select(ui, tl!("Vertical alignment"), "format_shape.valign", &VALIGN_OPTS, orig_valign_idx, layout.anchor_mixed, None)
{
let _ = app.run("shape.alignText", json!({"anchor": anchor}));
}
const DIRS: [(wordcraft_doc::props::TextVert, &str, &str); 4] = [
(wordcraft_doc::props::TextVert::Horz, "Horizontal", "horz"),
(wordcraft_doc::props::TextVert::Vert, "Rotate all text 90°", "vert"),
(wordcraft_doc::props::TextVert::Vert270, "Rotate all text 270°", "vert270"),
(wordcraft_doc::props::TextVert::Stacked, "Stacked", "wordArtVert"),
];
const DIR_OPTS: [(&str, &str); 4] =
[("Horizontal", "horz"), ("Rotate all text 90°", "vert"), ("Rotate all text 270°", "vert270"), ("Stacked", "wordArtVert")];
let orig_dir_idx = (!layout.vert_mixed).then(|| DIRS.iter().position(|(d, _, _)| *d == body.vert).unwrap_or(0));
if let Some(dir) =
preset_select(ui, tl!("Text direction"), "format_shape.text_direction", &DIR_OPTS, orig_dir_idx, layout.vert_mixed, None)
{
let _ = app.run("shape.textDirection", json!({"dir": dir}));
}
});
}
}
/// Draws a solid fill's colour field and transparency slider, applying each changed fill as a
@@ -511,8 +184,9 @@ fn solid(app: &mut WordApp, ui: &mut Ui, theme: &[Rgb], color: Rgb, transparency
let picked = color_field(ui, &label, &mut hex, &ColorFieldEmpty::NoColor, &palette);
if picked.changed
&& let Some(n) = Rgb::parse(&hex)
&& n != color
{
let _ = app.run("shape.fill", json!({"color": n.hex()}));
apply(app, Some(&Fill::Solid { color: n, transparency }));
return;
}
let out = SliderField::new(tl!("Transparency"), Bind::given(f64::from(transparency)), 0.0..=100.0).unit_kind(UnitKind::Percent).show(ui);
@@ -781,201 +455,6 @@ mod tests {
assert_eq!(h.state().session.undo_depth(), depth);
}
fn stroke(app: &WordApp) -> Option<wordcraft_doc::Rgb> {
match super::current_object(app) {
Some((_, InlineObject::Shape { stroke, .. })) => stroke,
o => panic!("{o:?}"),
}
}
/// Issue #5896: Format Shape pane provides Line settings: "No line" removes the frame,
/// and "Solid line" restores it with color and width.
#[test]
fn format_shape_pane_removes_and_restores_line() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.textBox", json!({"text": "Hello"})).unwrap();
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let mut h = harness(a);
h.run_steps(4);
assert_eq!(stroke(h.state()), Some(wordcraft_doc::Rgb::BLACK), "default textbox has black frame");
// Click "No line" in the Format Shape pane:
h.get_by_label("No line").click();
h.run_steps(3);
assert_eq!(stroke(h.state()), None, "No line removes the frame");
// Click "Solid line" in the Format Shape pane:
h.get_by_label("Solid line").click();
h.run_steps(3);
assert!(stroke(h.state()).is_some(), "Solid line restores the frame");
}
/// Format Shape pane displays layout and text box sections, allowing layout adjustments.
#[test]
fn format_shape_pane_exposes_layout_and_text_box() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.textBox", json!({"text": "Box content"})).unwrap();
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let mut h = harness(a);
h.run_steps(4);
assert!(h.query_by_role_and_label(egui::accesskit::Role::Heading, "Layout & Properties").is_some());
assert!(h.query_by_role_and_label(egui::accesskit::Role::Heading, "Text Box").is_some());
assert!(h.query_by_label("Vertical alignment").is_some());
assert!(h.query_by_label("Text direction").is_some());
}
/// Showing the pane leaves a shape with dimensions outside the NumberField range alone.
#[test]
fn format_shape_pane_leaves_out_of_range_layout_alone() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
a.run("picture.size", json!({"width": 2500.0, "lockAspect": false})).unwrap();
let (doc, depth) = (a.session.doc.clone(), a.session.undo_depth());
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let mut h = harness(a);
h.run_steps(4);
assert_eq!(h.state().session.undo_depth(), depth, "opening pane does not mutate size");
assert!(h.state().session.doc == doc);
}
/// A drawing canvas outline hides dash and cap type controls.
#[test]
fn format_shape_pane_hides_dash_and_cap_for_canvas() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.canvas", json!({"width": 300, "height": 200})).unwrap();
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let mut h = harness(a);
h.run_steps(4);
assert!(h.query_by_role_and_label(egui::accesskit::Role::Heading, "Line").is_some());
assert!(h.query_by_label("Solid line").is_some());
assert!(h.query_by_label("Dash type").is_none(), "canvas does not show dash type");
assert!(h.query_by_label("Cap type").is_none(), "canvas does not show cap type");
}
/// System dash presets and custom dashes are preserved and displayed correctly.
#[test]
fn format_shape_pane_preserves_custom_and_system_dashes() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
a.run("shape.outline", json!({"dash": "sysDash"})).unwrap();
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let mut h = harness(a);
h.run_steps(4);
let line = super::current_line(h.state()).expect("shape has line");
assert_eq!(line.dash, wordcraft_doc::line_dash::LineDash::SystemDash);
// Custom dashes show as "Custom" and are preserved:
let (pos, _) = wordcraft_engine::cmd::objects::selected(&h.state().session).unwrap();
let p = h.state_mut().session.doc.para_mut(pos.story, &pos.path).unwrap();
let InlineObject::Shape { extra, .. } = p.object_at_mut(pos.off).unwrap() else { panic!("expected shape") };
extra.dash = wordcraft_doc::line_dash::LineDash::Custom(vec![(100_000, 100_000)]);
h.run_steps(4);
let line = super::current_line(h.state()).expect("shape has line");
assert!(matches!(line.dash, wordcraft_doc::line_dash::LineDash::Custom(_)), "custom dash is preserved");
}
/// Issue #5896 P2: when typing inside a text box inside a drawing canvas, Format Shape shows
/// the member's controls and "No line" removes the member's border without clearing the canvas's.
#[test]
fn format_shape_pane_targets_canvas_text_box_member_while_typing() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.canvas", json!({"width": 300, "height": 200, "outline": "1F4E79"})).unwrap();
a.run("insert.textBox", json!({"text": "Canvas text"})).unwrap();
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let mut h = harness(a);
h.run_steps(4);
assert!(h.query_by_label("Dash type").is_some(), "member text box shows Dash type");
assert!(h.query_by_label("Cap type").is_some(), "member text box shows Cap type");
assert!(h.query_by_role_and_label(egui::accesskit::Role::Heading, "Text Box").is_some(), "member text box shows Text Box section");
h.get_by_label("No line").click();
h.run_steps(3);
let canvas = h.state().session.doc.body.first().and_then(|b| b.as_para()).and_then(|p| p.objects.first()).unwrap();
assert_eq!(canvas.canvas_style().and_then(|st| st.stroke), Some(wordcraft_doc::Rgb(0x1F, 0x4E, 0x79)));
let InlineObject::Group { children, .. } = canvas else { panic!("{canvas:?}") };
assert!(matches!(&children[0].obj, InlineObject::Shape { stroke: None, .. }));
}
/// Issue #5896: on a mixed selection where the primary shape has no line and another shape
/// has an outline (or where a text box is added after a rectangle), clicking "No line" applies
/// to every selected shape and the Text Box section remains accessible.
#[test]
fn format_shape_pane_applies_line_choice_to_mixed_selection() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
a.run("shape.outline", json!({"color": null})).unwrap();
a.session.sel = wordcraft_engine::Selection::caret(a.session.doc.end_of(wordcraft_doc::StoryRef::Body));
a.run("insert.textBox", json!({"text": "Mixed"})).unwrap();
a.run("select.objects", json!({"index": 0})).unwrap();
a.run("select.addObject", json!({"index": 1})).unwrap();
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let line = super::current_line(&a).expect("mixed selection has line info");
assert_eq!(line.has_line, None, "mixed No line / Solid line state");
let layout = super::current_layout(&a).expect("mixed selection has layout info");
assert!(layout.is_text_box, "added text box exposes Text Box section");
let mut h = harness(a);
h.run_steps(4);
assert!(h.query_by_role_and_label(egui::accesskit::Role::Heading, "Text Box").is_some(), "Text Box controls shown for added text box");
// Primary shape has no line, second shape has an outline: clicking "No line" clears both.
h.get_by_label("No line").click();
h.run_steps(3);
let para = h.state().session.doc.body.first().and_then(|b| b.as_para()).unwrap();
for (i, off) in para.object_offsets().into_iter().enumerate() {
let InlineObject::Shape { stroke, .. } = para.object_at(off).unwrap() else { panic!("expected shape {i}") };
assert_eq!(*stroke, None, "shape {i} outline cleared");
}
}
/// Issue #5896: dragging a Format Shape slider/NumberField joins updates into its initial
/// undo checkpoint on the fly so drags past MAX_UNDO (500) never evict earlier undo steps.
#[test]
fn format_shape_pane_drag_coalesces_into_single_undo_step() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
a.run("shape.fill", json!({"color": "156082"})).unwrap();
a.run("arrange.rotation", json!({"degrees": 180.0})).unwrap();
let depth_before = a.session.undo_depth();
let mut h = crate::test_harness::builder().with_size(egui::vec2(600.0, 800.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
super::pane(app, ui);
},
a,
);
h.run_steps(2);
let rot_rect = h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Rotation").rect();
let mut pos = rot_rect.center();
h.event(egui::Event::PointerMoved(pos));
h.step();
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
h.step();
// 510 changed frames (> MAX_UNDO = 500): sweep within 80..=280 so no frame clamps to a no-op.
for i in 0..510 {
let dx = if (i / 100) % 2 == 0 { 1.0 } else { -1.0 };
pos.x += dx;
h.event(egui::Event::PointerMoved(pos));
h.step();
}
assert_eq!(h.state().session.undo_depth(), depth_before + 1, "all 510 drag frames share one checkpoint without eviction");
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
assert_eq!(h.state().session.undo_depth(), depth_before + 1);
assert_ne!(super::current_layout(h.state()).unwrap().rotation, 180.0, "drag changed rotation");
assert!(h.state_mut().session.undo());
assert_eq!(super::current_layout(h.state()).unwrap().rotation, 180.0, "single Undo restores pre-drag angle");
assert_eq!(h.state().session.undo_depth(), depth_before, "earlier undo history stayed intact");
}
/// Calls `variation_base` and `remember_variation` directly: the menu tiles that drive them are
/// `ribbon::gradient_menu`'s (ribbon-w18).
///
@@ -998,170 +477,4 @@ mod tests {
assert_eq!(super::variation_base(&a, &pos, &now), base, "the variation shown keeps the colour it was made from");
assert_eq!(super::variation_base(&a, &pos, &solid), solid.main_color(), "another fill does not");
}
/// Mixed canvas + dashed/round-capped shape selection reads dash and cap from the shape,
/// not from the canvas placeholder.
#[test]
fn current_line_reads_dash_and_cap_from_non_canvas_shape() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.canvas", json!({"width": 300, "height": 200, "outline": "1F4E79"})).unwrap();
a.session.sel = wordcraft_engine::Selection::caret(a.session.doc.end_of(wordcraft_doc::StoryRef::Body));
a.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
a.run("shape.outline", json!({"dash": "dash", "cap": "rnd"})).unwrap();
a.run("select.objects", json!({"index": 0})).unwrap();
a.run("select.addObject", json!({"index": 1})).unwrap();
let line = super::current_line(&a).expect("mixed selection has line info");
assert!(!line.dash_mixed);
assert!(!line.cap_mixed);
assert_eq!(line.dash, wordcraft_doc::line_dash::LineDash::Dash);
assert_eq!(line.cap, wordcraft_doc::connector::LineCap::Round);
}
/// Mixed fill selection (first shape has no fill, second has solid fill) lets clicking
/// "No fill" clear the second shape's fill.
#[test]
fn format_shape_pane_no_fill_clears_mixed_selection() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
a.run("shape.fill", json!({"color": null})).unwrap();
a.session.sel = wordcraft_engine::Selection::caret(a.session.doc.end_of(wordcraft_doc::StoryRef::Body));
a.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
a.run("shape.fill", json!({"color": "156082"})).unwrap();
a.run("select.objects", json!({"index": 0})).unwrap();
a.run("select.addObject", json!({"index": 1})).unwrap();
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let mut h = harness(a);
h.run_steps(4);
h.get_by_label("No fill").click();
h.run_steps(3);
let para = h.state().session.doc.body.first().and_then(|b| b.as_para()).unwrap();
for (i, off) in para.object_offsets().into_iter().enumerate() {
let InlineObject::Shape { fill, .. } = para.object_at(off).unwrap() else { panic!("expected shape {i}") };
assert_eq!(*fill, None, "shape {i} fill cleared");
}
}
/// Selecting More Colors… in the Line color picker opens the Colors dialog and applies
/// the chosen color through `shape.outline`.
#[test]
fn format_shape_pane_line_more_colors_applies_outline() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.textBox", json!({"text": "Hello"})).unwrap();
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let mut h = harness(a);
h.run_steps(4);
h.query_all_by_role_and_label(egui::accesskit::Role::Button, "Color #000000").last().expect("line color field").click();
h.run_steps(3);
h.get_by_label("More Colors…").click();
h.run_steps(3);
let dialog = h.state_mut().dialog_host.get_mut::<craft::color_ui::ui::ColorPickerDialog>().expect("Colors dialog opened");
dialog.set_color(craft::color_ui::ui::PickedColor::rgb(craft::theme::Srgba::rgb(1.0, 0.0, 0.0)));
let ctx = h.ctx.clone();
assert!(h.state_mut().dialog_host.confirm::<craft::color_ui::ui::ColorPickerDialog>(&ctx));
crate::dialogs::host::settle(h.state_mut(), &ctx);
assert_eq!(stroke(h.state()), Some(wordcraft_doc::Rgb(255, 0, 0)));
}
fn png_data() -> String {
let img = image::RgbaImage::from_fn(20, 10, |x, y| {
if x > 2 && x < 17 && y > 2 && y < 7 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([255, 255, 255, 255]) }
});
let b = wordcraft_geom::picture::encode_format(&image::DynamicImage::ImageRgba8(img), image::ImageFormat::Png).unwrap();
wordcraft_engine::cmd::insert::base64_encode(&b)
}
fn body_objects(app: &WordApp) -> Vec<&InlineObject> {
let para = app.session.doc.body.first().and_then(|b| b.as_para()).unwrap();
para.object_offsets().into_iter().filter_map(|off| para.object_at(off)).collect()
}
fn edit_layout_spin(h: &mut egui_kittest::Harness<'static, WordApp>, label: &str, text: &str) {
let mut matches: Vec<_> = h.query_all_by_role_and_label(egui::accesskit::Role::SpinButton, label).collect();
let node = matches.pop().expect("layout spin button");
drop(matches);
node.click();
crate::test_harness::frames(h, 2);
let mut matches: Vec<_> = h.query_all_by_role_and_label(egui::accesskit::Role::SpinButton, label).collect();
matches.pop().expect("layout spin button").type_text(text);
crate::test_harness::frames(h, 2);
h.key_press(egui::Key::Enter);
crate::test_harness::frames(h, 3);
}
/// Issue #5896: with a Picture and a Shape selected (distinct dimensions and rotation),
/// Format Shape shows the shape's layout and Width/Height/Rotation only edit the shape.
#[test]
fn format_shape_pane_mixed_picture_and_shape_shows_and_updates_shape_only() {
use egui_kittest::kittest::NodeT;
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.picture", json!({"data": png_data()})).unwrap();
a.run("picture.size", json!({"width": 60.0, "height": 40.0, "lockAspect": false})).unwrap();
a.run("arrange.rotation", json!({"degrees": 15.0})).unwrap();
a.session.sel = wordcraft_engine::Selection::caret(a.session.doc.end_of(wordcraft_doc::StoryRef::Body));
a.run("insert.shape", json!({"kind": "rectangle", "width": 150.0, "height": 90.0})).unwrap();
a.run("select.objects", json!({"index": 0})).unwrap();
a.run("select.addObject", json!({"index": 1})).unwrap();
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let shown_layout = super::current_layout(&a).expect("mixed selection has shape layout");
assert_eq!((shown_layout.width, shown_layout.height, shown_layout.rotation), (150.0, 90.0, 0.0));
let mut h = harness(a);
h.run_steps(4);
let width_val = h.query_all_by_role_and_label(egui::accesskit::Role::SpinButton, "Width").last().unwrap().accesskit_node().numeric_value();
let height_val = h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Height").accesskit_node().numeric_value();
let rot_val = h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Rotation").accesskit_node().numeric_value();
assert_eq!(width_val, Some(150.0));
assert_eq!(height_val, Some(90.0));
assert_eq!(rot_val, Some(0.0));
edit_layout_spin(&mut h, "Width", "210");
edit_layout_spin(&mut h, "Height", "115");
edit_layout_spin(&mut h, "Rotation", "35");
let objs = body_objects(h.state());
assert_eq!(objs.len(), 2);
let (pw, ph, pf) = objs[0].frame().unwrap();
assert_eq!((pw, ph, pf.spin().deg), (60.0, 40.0, 15.0), "picture dimensions and rotation stay untouched");
let (sw, sh, sf) = objs[1].frame().unwrap();
assert_eq!((sw, sh, sf.spin().deg), (210.0, 115.0, 35.0), "shape updated by Format Shape layout controls");
assert_eq!(wordcraft_engine::cmd::objects::picked_objects(&h.state().session).len(), 2, "multi-selection preserved");
}
/// Issue #5896: with an editable Chart and a Shape selected (distinct dimensions),
/// Format Shape shows the shape's layout and Width/Height only edit the shape.
#[test]
fn format_shape_pane_mixed_chart_and_shape_shows_and_updates_shape_only() {
use egui_kittest::kittest::NodeT;
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.chart", json!({"type": "column"})).unwrap();
let (chart_w0, chart_h0, _) = body_objects(&a)[0].frame().unwrap();
a.session.sel = wordcraft_engine::Selection::caret(a.session.doc.end_of(wordcraft_doc::StoryRef::Body));
a.run("insert.shape", json!({"kind": "rectangle", "width": 140.0, "height": 70.0})).unwrap();
assert_ne!((chart_w0, chart_h0), (140.0, 70.0), "distinct initial dimensions");
a.run("select.objects", json!({"index": 0})).unwrap();
a.run("select.addObject", json!({"index": 1})).unwrap();
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let mut h = harness(a);
h.run_steps(4);
let width_val = h.query_all_by_role_and_label(egui::accesskit::Role::SpinButton, "Width").last().unwrap().accesskit_node().numeric_value();
let height_val = h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Height").accesskit_node().numeric_value();
assert_eq!(width_val, Some(140.0));
assert_eq!(height_val, Some(70.0));
edit_layout_spin(&mut h, "Width", "220");
edit_layout_spin(&mut h, "Height", "105");
let objs = body_objects(h.state());
assert_eq!(objs.len(), 2);
let (cw, ch, _) = objs[0].frame().unwrap();
assert_eq!((cw, ch), (chart_w0, chart_h0), "chart dimensions stay untouched");
let (sw, sh, _) = objs[1].frame().unwrap();
assert_eq!((sw, sh), (220.0, 105.0), "shape updated by Format Shape layout controls");
}
}
+5 -100
View File
@@ -4,8 +4,6 @@
use std::borrow::Cow;
use craft::behavior::IconId;
mod glyphs;
use craft::ui::primitives::{AppIcons, Glyph, IconSpec, register_app_icons};
use craft::ui::style::UiTokens;
use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, pos2, vec2};
@@ -288,7 +286,6 @@ static WORDCRAFT_ICONS_TABLE: &[(&str, &[u8])] = &[
("size", include_bytes!("../icons/size.svg")),
("smartArt", include_bytes!("../icons/smartArt.svg")),
("smartArtColors", include_bytes!("../icons/smartArtColors.svg")),
("smartArtLayouts", include_bytes!("../icons/smartArtLayouts.svg")),
("sort", include_bytes!("../icons/sort.svg")),
("sources", include_bytes!("../icons/sources.svg")),
("spaceAfter", include_bytes!("../icons/spaceAfter.svg")),
@@ -308,8 +305,6 @@ static WORDCRAFT_ICONS_TABLE: &[(&str, &[u8])] = &[
("table", include_bytes!("../icons/table.svg")),
("tableOfAuthorities", include_bytes!("../icons/tableOfAuthorities.svg")),
("tableOfFigures", include_bytes!("../icons/tableOfFigures.svg")),
("tableStyleOptions", include_bytes!("../icons/tableStyleOptions.svg")),
("tableStyles", include_bytes!("../icons/tableStyles.svg")),
("textBox", include_bytes!("../icons/textBox.svg")),
("textBoxLink", include_bytes!("../icons/textBoxLink.svg")),
("textBoxUnlink", include_bytes!("../icons/textBoxUnlink.svg")),
@@ -357,15 +352,6 @@ pub fn register() {
/// The app icons whose names the framework's catalog also has. The catalog wins a clash, so the
/// app registers its own drawings of these as `wordcraft.<name>`, and [`id`] names them so.
/// The icon art's fixed inks, the same in every theme: the red, green, orange and pink the SVG
/// icon set draws with (`icons/*.svg`), and the soft shadow under the Text Effects letter. The
/// text-drawn glyphs (`glyphs.rs`) take theirs from here; every other ink comes from the theme.
pub(crate) const ART_RED: Color32 = Color32::from_rgb(0xD1, 0x3B, 0x3B);
pub(crate) const ART_GREEN: Color32 = Color32::from_rgb(0x2E, 0x8B, 0x57);
pub(crate) const ART_ORANGE: Color32 = Color32::from_rgb(0xE0, 0x7B, 0x1F);
pub(crate) const ART_PINK: Color32 = Color32::from_rgb(0xE8, 0x6F, 0xA0);
pub(crate) const ART_SHADOW: Color32 = Color32::from_rgba_premultiplied(0, 0, 0, 40);
const OWN_OVER_CATALOG: &[(&str, &str)] = &[
("bookmark", "wordcraft.bookmark"),
("check", "wordcraft.check"),
@@ -402,15 +388,6 @@ pub fn id(name: &'static str) -> IconId {
}
}
/// The icon `name` shows in a ribbon button or group: the icon is drawn as text in the interface font
/// when it shows a letter or a symbol (see `glyphs`), else it is the SVG document of [`id`].
pub fn spec(name: &'static str) -> IconSpec<'static> {
match glyphs::ICONS.iter().find(|icon| icon.0 == name) {
Some(icon) => IconSpec::glyph(icon),
None => IconSpec::svg(id(name)),
}
}
/// The icon a command's button shows outside its own ribbon group (custom groups, the Quick
/// Access Toolbar): the one its ribbon button uses, which is usually named after the id's last
/// part. A name the set doesn't have draws the framework's fallback tile.
@@ -442,15 +419,11 @@ pub fn for_command(id: &str) -> IconSpec<'static> {
Some((_, icon)) => Cow::Borrowed(icon),
None => Cow::Owned(id.rsplit('.').next().unwrap_or(id).to_owned()),
};
// A text glyph is found by the plain name (`pilcrow`); the app's own SVG of a catalog name
// (`wordcraft.pilcrow`) applies only to the SVG fallback.
if let Some(icon) = glyphs::ICONS.iter().find(|icon| icon.0 == name) {
return IconSpec::glyph(icon);
}
match OWN_OVER_CATALOG.iter().find(|(plain, _)| *plain == name) {
Some((_, own)) => IconSpec::svg(IconId::new(own)),
None => IconSpec::svg(IconId::from(name)),
}
let name = match OWN_OVER_CATALOG.iter().find(|(plain, _)| *plain == name) {
Some((_, own)) => Cow::Borrowed(*own),
None => name,
};
IconSpec::svg(IconId::from(name))
}
/// An Insert › Icons library icon as a value glyph, drawn from the same path data the inserted
@@ -493,17 +466,6 @@ impl Glyph for LibraryGlyph {
mod tests {
use super::*;
/// #7694: Bold, Italic and Underline draw their filled SVGs while the other letter icons beside them are
/// drawn as text.
#[test]
fn bold_italic_and_underline_are_svgs_beside_the_text_letters() {
use craft::ui::primitives::IconSource;
for name in ["bold", "italic", "underline"] {
assert!(matches!(spec(name).source, IconSource::Svg(_)), "{name} should draw its SVG");
}
assert!(matches!(spec("strike").source, IconSource::Glyph(_)));
}
/// The numbers of the outline path's `d` attribute, in order (the arrow's paths are only M, L, Z). The
/// icon fills the tail and the head as two translucent paths and ends with the stroked outline of the
/// whole arrow, which is the last.
@@ -536,13 +498,6 @@ mod tests {
assert_eq!(undo, "wordcraft.undo");
}
/// QAT and custom-group buttons draw `view.marks` as the pilcrow text glyph, as the ribbon does, not the
/// app's SVG of the same name.
#[test]
fn for_command_picks_the_text_glyph_before_the_own_svg() {
assert!(matches!(for_command("view.marks").source, craft::ui::primitives::IconSource::Glyph(_)));
}
/// #6768: the Insert › Shapes Arrow tile is the block arrow that tile inserts, outlined as the
/// document draws it, not a thin line with a head.
#[test]
@@ -558,56 +513,6 @@ mod tests {
}
}
/// #7149 item 8: every icon name the UI source gives a button, group or menu exists in the app set or the
/// catalog; a name that does not paints nothing. Names built at run time are not found here.
#[test]
fn every_icon_name_the_ui_uses_resolves() {
fn rs_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let path = entry.path();
if path.is_dir() {
rs_files(&path, out);
} else if path.extension().is_some_and(|e| e == "rs") {
out.push(path);
}
}
}
register();
let mut files = Vec::new();
rs_files(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut files);
let (mut seen, mut missing, mut svg_only) = (0, Vec::new(), Vec::new());
for file in files.iter().filter(|f| !f.ends_with("icons.rs")) {
let text = std::fs::read_to_string(file).unwrap_or_default();
for call in ["IconId::new(\"", "icons::id(\"", "icons::spec(\""] {
for part in text.split(call).skip(1) {
let Some(name) = part.split('"').next() else { continue };
seen += 1;
// A text glyph resolves only through `icons::spec`; the SVG-only calls draw its SVG instead.
if call != "icons::spec(\"" && glyphs::ICONS.iter().any(|g| g.0 == name) {
svg_only.push(format!("{name} ({}): use icons::spec", file.display()));
continue;
}
let known = match call {
"IconId::new(\"" => craft::ui::primitives::has_icon(&IconId::from(Cow::Owned(name.to_owned()))),
_ => {
glyphs::ICONS.iter().any(|g| g.0 == name)
|| craft::ui::primitives::has_icon(&match OWN_OVER_CATALOG.iter().find(|(p, _)| *p == name) {
Some((_, own)) => IconId::new(own),
None => IconId::from(Cow::Owned(name.to_owned())),
})
}
};
if !known {
missing.push(format!("{name} ({})", file.display()));
}
}
}
}
assert!(seen > 200, "the scan found only {seen} names");
assert!(missing.is_empty(), "icons used but not in the app set or the catalog: {missing:?}");
assert!(svg_only.is_empty(), "text glyphs passed through the SVG-only IconId::new / icons::id: {svg_only:?}");
}
/// #7317: the `fitOnePage` app icon is a document the registry resolves and the rasteriser draws.
/// A document the engine fails to parse or draw gives no texture, and so no shape: the tile would
/// be blank. The pre-#7101 test painted the hand-written vector path; this checks the same icon
-477
View File
@@ -1,477 +0,0 @@
//! The ribbon icons that show a letter or a symbol, drawn as text in the interface font.
//!
//! The SVG icon documents have no `<text>` element (the framework's icon parser takes shapes only), so a
//! letter in them is a hand-built path that differs from the interface font's letter. These icons are drawn
//! as a framework value glyph instead: the 20-unit grid, the pen width 1.25 and the text positions of the
//! code-drawn set the icons were exported from. Original artwork; the letters come from the theme's fonts.
use craft::ui::primitives::Glyph;
use craft::ui::style::{UiTokens, rgba_color};
use egui::{Color32, FontId, Painter, Pos2, Rect, Shape, Stroke, pos2, vec2};
/// Every icon `paint` knows.
pub(super) static ICONS: &[TextIcon] = &[
TextIcon("addressBlock"),
TextIcon("case"),
TextIcon("ccPlainText"),
TextIcon("ccRichText"),
TextIcon("charborder"),
TextIcon("citation"),
TextIcon("clear"),
TextIcon("documentTemplate"),
TextIcon("dropCap"),
TextIcon("editor"),
TextIcon("effects"),
TextIcon("enclose"),
TextIcon("endnote"),
TextIcon("equation"),
TextIcon("fontcolor"),
TextIcon("fonts"),
TextIcon("footnote"),
TextIcon("formula"),
TextIcon("greetingLine"),
TextIcon("grow"),
TextIcon("help"),
TextIcon("highlightFields"),
TextIcon("hyphenation"),
TextIcon("index"),
TextIcon("inkToMath"),
TextIcon("language"),
TextIcon("lineNumbers"),
TextIcon("markCitation"),
TextIcon("markEntry"),
TextIcon("matchFields"),
TextIcon("mergeField"),
TextIcon("multilevel"),
TextIcon("nextFootnote"),
TextIcon("numbering"),
TextIcon("pageNumber"),
TextIcon("phonetic"),
TextIcon("pilcrow"),
TextIcon("preview"),
TextIcon("readAloud"),
TextIcon("replace"),
TextIcon("rules"),
TextIcon("shrink"),
TextIcon("sort"),
TextIcon("spelling"),
TextIcon("strike"),
TextIcon("styles"),
TextIcon("stylesPane"),
TextIcon("subscript"),
TextIcon("superscript"),
TextIcon("symbol"),
TextIcon("tableOfAuthorities"),
TextIcon("textBox"),
TextIcon("textDirection"),
TextIcon("textFill"),
TextIcon("textOutline"),
TextIcon("thesaurus"),
TextIcon("transform"),
TextIcon("translate"),
TextIcon("watermark"),
TextIcon("wordArt"),
TextIcon("wordCount"),
TextIcon("zoom100"),
];
/// An icon drawn as text and lines; the name picks the drawing.
#[derive(craft::ui::contract::MemoProps)]
pub(super) struct TextIcon(pub(super) &'static str);
impl Glyph for TextIcon {
fn paint(&self, painter: &Painter, tokens: &UiTokens, rect: Rect, color: Color32, _mirrored: bool) {
// The framework passes `text.disabled` as `color` to a disabled button, and a glyph has no other way
// to learn that; then both inks go grey (the accent ink would stay bright on a disabled button).
let disabled = color == rgba_color(tokens.color.text.disabled);
let accent = if disabled { color } else { rgba_color(tokens.color.accent.solid) };
let pen = Pen { p: painter, r: rect, c: color, a: accent, w: 1.25, d: disabled };
paint(&pen, self.0);
}
}
struct Pen<'a> {
p: &'a Painter,
r: Rect,
c: Color32,
a: Color32,
w: f32,
/// Disabled: the fixed colours (a red bar, a green tick) go grey too, as an SVG's fixed layers do.
d: bool,
}
impl Pen<'_> {
/// `colour`, or the disabled ink when the button is disabled.
fn fixed(&self, colour: Color32) -> Color32 {
if self.d { self.c } else { colour }
}
fn s(&self) -> f32 {
self.r.width().min(self.r.height()) / 20.0
}
fn pt(&self, x: f32, y: f32) -> Pos2 {
let s = self.s();
let o = self.r.center() - vec2(10.0 * s, 10.0 * s);
pos2(o.x + x * s, o.y + y * s)
}
fn stroke(&self, c: Color32) -> Stroke {
Stroke::new(self.w * self.s(), c)
}
fn line(&self, pts: &[(f32, f32)]) {
self.line_c(pts, self.c);
}
fn line_c(&self, pts: &[(f32, f32)], c: Color32) {
let v: Vec<Pos2> = pts.iter().map(|&(x, y)| self.pt(x, y)).collect();
self.p.add(Shape::line(v, self.stroke(c)));
}
fn closed(&self, pts: &[(f32, f32)], c: Color32) {
let v: Vec<Pos2> = pts.iter().map(|&(x, y)| self.pt(x, y)).collect();
self.p.add(Shape::closed_line(v, self.stroke(c)));
}
fn fill(&self, pts: &[(f32, f32)], c: Color32) {
let v: Vec<Pos2> = pts.iter().map(|&(x, y)| self.pt(x, y)).collect();
self.p.add(Shape::convex_polygon(v, c, Stroke::NONE));
}
fn rect(&self, x0: f32, y0: f32, x1: f32, y1: f32, c: Color32) {
self.p.rect_stroke(Rect::from_min_max(self.pt(x0, y0), self.pt(x1, y1)), 1.0, self.stroke(c), egui::StrokeKind::Middle);
}
fn frect(&self, x0: f32, y0: f32, x1: f32, y1: f32, c: Color32) {
self.p.rect_filled(Rect::from_min_max(self.pt(x0, y0), self.pt(x1, y1)), 0.5, c);
}
fn circle(&self, x: f32, y: f32, r: f32, c: Color32) {
self.p.circle_stroke(self.pt(x, y), r * self.s(), self.stroke(c));
}
fn text(&self, x: f32, y: f32, size: f32, t: &str, c: Color32, bold: bool) {
let font = if bold { crate::theme::semibold(size * self.s()) } else { FontId::proportional(size * self.s()) };
self.p.text(self.pt(x, y), egui::Align2::CENTER_CENTER, t, font, c);
}
/// Horizontal text lines (a paragraph).
fn lines(&self, x0: f32, x1: f32, ys: &[f32]) {
for y in ys {
self.line(&[(x0, *y), (x1, *y)]);
}
}
/// A page outline with a folded corner.
fn page(&self, x0: f32, y0: f32, x1: f32, y1: f32) {
self.closed(&[(x0, y0), (x1 - 4.0, y0), (x1, y0 + 4.0), (x1, y1), (x0, y1)], self.c);
self.line(&[(x1 - 4.0, y0), (x1 - 4.0, y0 + 4.0), (x1, y0 + 4.0)]);
}
}
/// Draws `name`; false when it is not one of [`ICONS`].
fn paint(pen: &Pen, name: &str) -> bool {
let (c, a) = (pen.c, pen.a);
let red = pen.fixed(super::ART_RED);
let green = pen.fixed(super::ART_GREEN);
let orange = pen.fixed(super::ART_ORANGE);
match name {
"strike" => {
pen.text(10.0, 10.0, 12.0, "ab", c, false);
pen.line_c(&[(3.0, 10.5), (17.0, 10.5)], c);
}
"charborder" => {
pen.rect(3.0, 3.0, 17.0, 17.0, a);
pen.text(10.0, 6.0, 9.0, "A", c, false);
}
"enclose" => {
pen.circle(10.0, 10.5, 7.5, a);
pen.text(10.0, 10.5, 9.0, "A", c, false);
}
"subscript" => {
pen.text(8.0, 9.0, 13.0, "x", c, false);
pen.text(15.0, 14.5, 8.0, "2", a, true);
}
"superscript" => {
pen.text(8.0, 11.0, 13.0, "x", c, false);
pen.text(15.0, 5.0, 8.0, "2", a, true);
}
"grow" => {
pen.text(8.0, 11.0, 15.0, "A", c, false);
pen.fill(&[(14.5, 6.0), (18.5, 6.0), (16.5, 3.0)], a);
}
"shrink" => {
pen.text(8.0, 12.0, 11.0, "A", c, false);
pen.fill(&[(14.5, 4.0), (18.5, 4.0), (16.5, 7.0)], a);
}
"case" => pen.text(10.0, 10.5, 12.0, "Aa", c, false),
"clear" => {
pen.text(8.0, 9.0, 13.0, "A", c, false);
pen.fill(&[(10.0, 15.0), (14.0, 11.0), (18.0, 15.0), (14.0, 19.0)], pen.fixed(super::ART_PINK));
}
"phonetic" => {
pen.text(10.0, 5.0, 7.5, "abc", a, false);
pen.text(10.0, 13.5, 12.5, "A", c, false);
}
"fontcolor" => {
pen.text(10.0, 9.0, 14.0, "A", c, false);
pen.frect(2.0, 16.5, 18.0, 19.0, red);
}
"effects" => {
pen.text(10.0, 10.0, 15.0, "A", a, true);
let shadow = if pen.d { Color32::TRANSPARENT } else { super::ART_SHADOW };
pen.text(10.5, 10.5, 15.0, "A", shadow, true);
}
"numbering" => {
for (i, y) in [5.0, 10.0, 15.0].iter().enumerate() {
pen.text(4.0, *y, 6.0, &(i + 1).to_string(), if i == 0 { a } else { c }, true);
pen.line(&[(7.5, *y), (17.0, *y)]);
}
}
"multilevel" => {
pen.text(3.5, 4.5, 5.5, "1", a, true);
pen.line(&[(6.5, 4.5), (17.0, 4.5)]);
pen.text(6.5, 10.0, 5.5, "a", c, true);
pen.line(&[(9.5, 10.0), (17.0, 10.0)]);
pen.text(9.5, 15.5, 5.5, "i", c, true);
pen.line(&[(12.0, 15.5), (17.0, 15.5)]);
}
"sort" => {
pen.text(6.0, 5.5, 7.0, "A", c, true);
pen.text(6.0, 14.5, 7.0, "Z", c, true);
pen.line_c(&[(14.0, 3.0), (14.0, 17.0)], a);
pen.line_c(&[(11.5, 14.5), (14.0, 17.0), (16.5, 14.5)], a);
}
"pilcrow" => pen.text(10.0, 10.5, 15.0, "", c, false),
"replace" => {
pen.text(6.0, 6.0, 8.0, "ab", c, false);
pen.text(13.0, 15.0, 8.0, "ac", a, false);
pen.line(&[(13.0, 3.5), (16.0, 3.5), (16.0, 8.5)]);
pen.line(&[(14.5, 7.0), (16.0, 8.5), (17.5, 7.0)]);
}
"editor" | "spelling" => {
pen.text(8.0, 7.0, 9.0, "abc", c, true);
pen.line_c(&[(5.0, 13.0), (8.5, 16.5), (16.0, 9.0)], green);
}
"styles" => {
pen.text(10.0, 10.0, 14.0, "A", a, false);
pen.line(&[(13.0, 15.0), (17.0, 11.0)]);
}
"stylesPane" => {
pen.rect(3.0, 3.0, 17.0, 17.0, c);
pen.line(&[(11.0, 3.0), (11.0, 17.0)]);
pen.text(7.0, 10.0, 8.0, "A", a, false);
}
"pageNumber" => {
pen.page(4.0, 2.0, 16.0, 18.0);
pen.text(10.0, 13.0, 7.0, "#", a, true);
}
"textBox" => {
pen.rect(3.0, 3.0, 17.0, 17.0, c);
pen.text(10.0, 10.0, 10.0, "A", a, false);
}
"wordArt" => {
pen.text(10.0, 10.5, 15.0, "A", a, true);
pen.line_c(&[(3.0, 17.5), (17.0, 17.5)], orange);
}
"textFill" => {
pen.text(10.0, 8.5, 13.0, "A", c, true);
pen.frect(3.0, 15.0, 17.0, 18.5, a);
}
"textOutline" => {
pen.text(10.0, 8.5, 13.0, "A", a, false);
pen.rect(3.0, 15.0, 17.0, 18.5, c);
}
"transform" => {
// Letters along an arch.
let arc: Vec<(f32, f32)> = (0..=12)
.map(|i| {
let t = std::f32::consts::PI * (1.0 - i as f32 / 12.0);
(10.0 + 7.5 * t.cos(), 15.0 - 9.0 * t.sin())
})
.collect();
pen.line_c(&arc, a);
pen.text(10.0, 13.0, 8.0, "A", c, true);
pen.line(&[(2.5, 17.5), (17.5, 17.5)]);
}
"dropCap" => {
pen.text(6.0, 8.0, 12.0, "A", a, true);
pen.lines(11.0, 17.0, &[4.0, 8.0, 12.0]);
pen.lines(3.0, 17.0, &[16.0]);
}
"equation" => pen.text(10.0, 10.0, 17.0, "π", a, false),
"symbol" => pen.text(10.0, 10.0, 17.0, "Ω", c, false),
"inkToMath" => {
pen.line_c(&[(3.0, 12.0), (5.0, 7.0), (7.0, 12.0)], a);
pen.text(13.5, 10.0, 11.0, "√", c, false);
}
"fonts" => pen.text(10.0, 10.0, 13.0, "Aa", a, false),
"watermark" => {
pen.page(4.0, 2.0, 16.0, 18.0);
pen.text(10.0, 11.0, 7.0, "W", a.linear_multiply(0.6), true);
}
"lineNumbers" => {
for (i, y) in [4.0, 8.0, 12.0, 16.0].iter().enumerate() {
pen.text(4.0, *y, 5.0, &(i + 1).to_string(), a, true);
pen.line(&[(7.0, *y), (17.0, *y)]);
}
}
"hyphenation" => {
pen.text(7.0, 7.0, 8.0, "ab-", c, false);
pen.text(9.0, 14.5, 8.0, "cd", a, false);
}
"footnote" => {
pen.text(6.5, 7.0, 10.0, "ab", c, false);
pen.text(13.5, 4.5, 6.0, "1", a, true);
pen.line(&[(3.0, 13.0), (9.0, 13.0)]);
pen.lines(3.0, 17.0, &[16.0]);
}
"endnote" => {
pen.text(6.5, 7.0, 10.0, "ab", c, false);
pen.text(13.5, 4.5, 6.0, "i", a, true);
pen.lines(3.0, 17.0, &[13.0, 16.0]);
}
"nextFootnote" => {
pen.text(7.0, 7.0, 8.0, "ab", c, false);
pen.text(13.0, 5.0, 6.0, "1", a, true);
pen.line_c(&[(6.0, 15.0), (14.0, 15.0)], a);
pen.line_c(&[(11.5, 12.5), (14.0, 15.0), (11.5, 17.5)], a);
}
"citation" => {
pen.text(6.0, 9.0, 14.0, "“", a, true);
pen.lines(9.0, 17.0, &[6.0, 10.0, 14.0]);
}
"markEntry" | "index" | "markCitation" | "tableOfAuthorities" => {
pen.page(4.0, 2.0, 16.0, 18.0);
pen.text(10.0, 10.0, 8.0, if name == "index" || name == "markEntry" { "A" } else { "§" }, a, true);
}
"mergeField" | "addressBlock" | "greetingLine" | "rules" | "matchFields" | "highlightFields" => {
pen.rect(2.5, 6.0, 17.5, 14.0, c);
pen.text(10.0, 10.0, 7.0, "«»", a, true);
}
"preview" => {
pen.text(10.0, 10.0, 8.0, "ABC", a, true);
pen.rect(2.5, 5.0, 17.5, 15.0, c);
}
"thesaurus" => {
pen.rect(3.5, 2.5, 16.5, 17.5, c);
pen.text(10.0, 9.5, 8.0, "Aa", a, true);
}
"wordCount" => pen.text(10.0, 10.0, 9.0, "123", a, true),
"readAloud" => {
pen.text(6.0, 10.0, 10.0, "A", c, false);
pen.line_c(&[(12.0, 7.0), (13.5, 10.0), (12.0, 13.0)], a);
pen.line_c(&[(14.5, 5.0), (17.0, 10.0), (14.5, 15.0)], a);
}
"translate" | "language" => {
pen.text(6.5, 7.0, 9.0, "A", c, true);
// あ drawn as strokes, like the rest of the icon set: the interface fonts need not
// carry Japanese (craft-fonts is optional), and a letter without a glyph drew a box.
pen.line_c(&[(11.6, 10.8), (15.4, 10.8)], a);
pen.line_c(&[(13.5, 8.8), (13.5, 13.9)], a);
pen.line_c(&[(11.0, 13.9), (16.2, 13.9)], a);
pen.circle(13.5, 16.1, 1.8, a);
pen.line_c(&[(15.0, 17.1), (15.8, 18.0)], a);
}
"zoom100" => pen.text(10.0, 10.0, 7.5, "100", a, true),
"documentTemplate" => {
pen.page(4.0, 2.0, 16.0, 18.0);
pen.frect(6.0, 5.0, 11.5, 7.0, a);
pen.text(10.0, 13.0, 8.0, "A", a, false);
}
"textDirection" => {
pen.text(9.0, 10.0, 10.0, "A", c, false);
pen.line_c(&[(15.5, 4.0), (15.5, 16.0)], a);
pen.line_c(&[(13.5, 14.0), (15.5, 16.0), (17.5, 14.0)], a);
}
"formula" => pen.text(10.0, 10.0, 12.0, "fx", a, false),
"help" => {
pen.circle(10.0, 10.0, 7.0, c);
pen.text(10.0, 10.0, 10.0, "?", a, true);
}
"ccRichText" => {
pen.rect(2.5, 5.0, 17.5, 15.0, a);
pen.text(7.5, 10.0, 8.0, "A", c, true);
pen.text(13.0, 10.5, 7.0, "a", c, false);
}
"ccPlainText" => {
pen.rect(2.5, 5.0, 17.5, 15.0, a);
pen.text(8.0, 10.0, 8.0, "A", c, false);
pen.line(&[(12.0, 7.5), (12.0, 12.5)]);
}
_ => return false,
}
true
}
#[cfg(test)]
mod tests {
use super::*;
/// Every name in `ICONS` has a drawing, and a name outside it has none.
#[test]
fn every_text_icon_has_a_drawing() {
let ctx = egui::Context::default();
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let painter = ui.painter().clone();
let pen =
Pen { p: &painter, r: Rect::from_min_size(pos2(0.0, 0.0), vec2(20.0, 20.0)), c: Color32::BLACK, a: Color32::BLUE, w: 1.25, d: false };
for icon in ICONS {
assert!(paint(&pen, icon.0), "{} has no drawing", icon.0);
}
assert!(!paint(&pen, "notAnIcon"));
});
out.textures_delta.clear();
}
/// Every colour the shapes of `shape` paint with.
fn ink_of(shape: &Shape, out: &mut Vec<Color32>) {
match shape {
Shape::Vec(v) => v.iter().for_each(|s| ink_of(s, out)),
Shape::LineSegment { stroke, .. } => out.push(stroke.color),
Shape::Path(p) => {
out.push(p.fill);
if let egui::epaint::ColorMode::Solid(c) = p.stroke.color {
out.push(c);
}
}
Shape::Circle(c) => out.extend([c.stroke.color, c.fill]),
Shape::Rect(r) => out.extend([r.stroke.color, r.fill]),
Shape::Text(t) => {
out.push(t.fallback_color);
out.extend(t.galley.job.sections.iter().map(|s| s.format.color));
}
_ => {}
}
}
/// A disabled button hands its glyph `text.disabled` as the colour: every shape is then in that colour
/// or invisible, with no accent and no fixed colour such as the font colour's red bar (production painted
/// a disabled icon all grey). Enabled, the glyphs do use the accent.
#[test]
fn a_disabled_text_glyph_paints_only_the_disabled_ink() {
use craft::theme::{Appearance, Contrast, Mode, Size, TextSize};
let themes = craft::theme::builtins();
let theme = themes.iter().find(|theme| theme.id.as_str() == craft::theme::SUITE_DEFAULT).unwrap();
let appearance = Appearance {
mode: Mode::Light,
contrast: Contrast::Standard,
size: Size::Compact,
text_size: TextSize::default(),
reduced_motion: false,
};
let tokens = UiTokens::new(std::sync::Arc::new(craft::theme::resolve(theme, appearance, None).tokens), Contrast::Standard, Size::Compact);
let (accent, disabled, normal) =
(rgba_color(tokens.color.accent.solid), rgba_color(tokens.color.text.disabled), rgba_color(tokens.color.text.normal));
assert_ne!(accent, disabled);
let inks = |color: Color32| {
let mut out = Vec::new();
let ctx = egui::Context::default();
let mut run = ctx.run_ui(egui::RawInput::default(), |ui| {
let painter = ui.painter().clone();
for icon in ICONS {
icon.paint(&painter, &tokens, Rect::from_min_size(pos2(0.0, 0.0), vec2(20.0, 20.0)), color, false);
}
});
run.textures_delta.clear();
run.shapes.iter().for_each(|clipped| ink_of(&clipped.shape, &mut out));
out
};
assert!(inks(normal).contains(&accent), "an enabled glyph uses the accent ink");
// A shade of the disabled ink (a lighter "W" behind a letter) counts as that ink.
let same_hue = |ink: Color32| {
let (x, y) = (ink.to_opaque(), disabled.to_opaque());
[x.r().abs_diff(y.r()), x.g().abs_diff(y.g()), x.b().abs_diff(y.b())].iter().all(|d| *d <= 2)
};
let stray: Vec<Color32> = inks(disabled).into_iter().filter(|ink| ink.a() > 0 && !same_hue(*ink)).collect();
assert!(stray.is_empty(), "a disabled glyph painted in another colour: {stray:?}");
}
}
+1 -1
View File
@@ -489,7 +489,7 @@ fn show_replay(app: &mut WordApp, ui: &mut Ui, body: &PageBody) {
}
let playing = r.playing_from.is_some();
let (icon, name) = if playing { ("replayPause", tl!("Pause")) } else { ("replayPlay", tl!("Play")) };
if IconButton::new(crate::icons::spec(icon)).label(name.to_string()).show(ui).clicks > 0 {
if IconButton::new(crate::icons::id(icon)).label(name.to_string()).show(ui).clicks > 0 {
let here = r.at(now);
if playing {
r.pause_at(here);
+6 -32
View File
@@ -1,7 +1,7 @@
// PLAN: the Insert key has no editor input, so the overtype switch is the shortcut layer's (shell-w6).
use craft::behavior::editor::{EditorInput, SurroundingUnit};
use craft::behavior::intent::{EditCommand, Granularity, MoveMods, NavMove};
use craft::platform::clipboard::{HTML, RGBA8, RTF, URI_LIST};
use craft::platform::clipboard::{RGBA8, URI_LIST};
use craft::ui::canvas::ToolPass;
use craft::ui::runtime::commands::{ClipItem, ClipboardHandle};
@@ -553,20 +553,13 @@ fn move_input(app: &mut WordApp, mv: NavMove, m: MoveMods) {
fn edit_command(app: &mut WordApp, ctx: &egui::Context, cmd: EditCommand) {
match cmd {
// The chord runs only what the greyed button would (`command_enabled`): with nothing selected, and for Cut
// also where protection or Markdown Source greys the button, it does nothing, silently, rather than put
// "not available" on the status bar.
EditCommand::Cut => {
if crate::app::command_board::command_enabled(app, "edit.cut")
&& let Ok(r) = app.run("edit.cut", json!({}))
{
if let Ok(r) = app.run("edit.cut", json!({})) {
crate::system_clipboard::put_result(app, ctx, &r);
}
}
EditCommand::Copy => {
if crate::app::command_board::command_enabled(app, "edit.copy") {
let _ = app.run("edit.copy", json!({}));
}
let _ = app.run("edit.copy", json!({}));
}
EditCommand::Paste => paste(app, ctx),
EditCommand::SelectAll => {
@@ -585,12 +578,12 @@ fn edit_command(app: &mut WordApp, ctx: &egui::Context, cmd: EditCommand) {
}
}
/// Paste from the clipboard: copied picture files insert as pictures (#45), text, rich text
/// (HTML/RTF) and a clipboard picture go through `edit.paste`.
/// Paste from the clipboard: copied picture files insert as pictures (#45), text and a clipboard
/// picture go through `edit.paste`.
fn paste(app: &mut WordApp, ctx: &egui::Context) {
let clip = ClipboardHandle::of(ctx);
let text = clip.read_text().ok().flatten();
if text.is_none() && !clip.has(&[RGBA8, URI_LIST, HTML, RTF]) {
if text.is_none() && !clip.has(&[RGBA8, URI_LIST]) {
return;
}
if let Some(t) = &text
@@ -765,22 +758,3 @@ fn inserted_literal_at(app: &WordApp, text: &str, start: &wordcraft_doc::Pos) ->
let Some(end) = start.off.checked_add(text.len()) else { return false };
para.text.get(start.off..end) == Some(text)
}
#[cfg(test)]
mod tests {
use super::*;
/// #7675: Cut and Copy with only a caret are silent (no "not available" status line) and change nothing.
#[test]
fn cut_and_copy_with_nothing_selected_stay_silent() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
app.run("text.insert", json!({"text": "Kilns fire clay"})).unwrap();
assert!(app.session.sel.is_collapsed());
let ctx = egui::Context::default();
for cmd in [EditCommand::Copy, EditCommand::Cut] {
edit_command(&mut app, &ctx, cmd);
assert!(app.status.is_none(), "{cmd:?}: nothing selected, nothing said");
assert_eq!(app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "Kilns fire clay", "{cmd:?}: the text is untouched");
}
}
}
-146
View File
@@ -201,9 +201,6 @@ fn user_assignments_become_overrides() {
),
(Some(("Mod+F1", "view.focus")), "Mod+F1", command("view.focus")),
(Some(("Alt+Q", "view.focus")), "Alt+Q", if mac { command("view.focus") } else { tell_me.clone() }),
(None, "Mod+R", command("para.alignRight")),
(None, "Alt+R", None),
(None, "Mod+Alt+Shift+R", None),
];
for (assign, ask, want) in rows {
let mut h = alt_frame_app();
@@ -312,43 +309,6 @@ fn the_ignored_paste_uses_up_its_paste_modifiers() {
assert_eq!(state.get("italic").and_then(serde_json::Value::as_bool), Some(true), "a later menu-bar paste keeps clipboard formatting: {state}");
}
/// #5616: on a desktop no paste event follows Mod+Shift+V's key, so none is swallowed: a later
/// `Mod+V` paste with a clipboard offer pastes.
#[test]
fn a_desktop_paste_after_mod_shift_v_is_not_swallowed() {
let mut h = app_harness(copied_bold_app());
let chord = Modifiers { shift: true, ..mod_held() };
mods_frame(&mut h, chord, vec![key_event(Key::V, true, chord)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
assert_eq!(body(h.state()), "source target");
assert!(is_bold(&mut h));
run(&mut h, "select.text", json!({"text": "target"}));
offer(&h, bold_flavours("later"));
let ctrl = mod_held();
mods_frame(&mut h, ctrl, vec![key_event(Key::V, true, ctrl)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
assert_eq!(body(h.state()), "source later");
}
/// #5616: Mod+Shift+C (Copy Formatting), Shift released, Mod still held or released: Mod+C's
/// chord isn't the paste's modifiers, so a subsequent Mod+V paste keeps HTML's formatting (bold).
#[test]
fn an_unrelated_keys_modifiers_do_not_steer_a_later_paste() {
for mod_still_held in [false, true] {
let mut h = alt_frame_app();
offer(&h, bold_flavours("external"));
let chord = Modifiers { shift: true, ..mod_held() };
mods_frame(&mut h, chord, vec![key_event(Key::C, true, chord)]);
let after = if mod_still_held { mod_held() } else { Modifiers::NONE };
mods_frame(&mut h, after, vec![key_event(Key::C, false, after)]);
let ctrl = mod_held();
mods_frame(&mut h, ctrl, vec![key_event(Key::V, true, ctrl)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
assert_eq!(body(h.state()), "external");
assert!(is_bold(&mut h), "held={mod_still_held}: Mod+V keeps the HTML's bold");
}
}
/// Paste Formatting on a chord the user bound pastes the copied formatting once.
#[test]
fn paste_formatting_on_another_key_pastes_the_copied_formatting() {
@@ -393,84 +353,6 @@ fn mod_v_released_mod_first_pastes_the_clipboard_picture() {
assert_eq!(pictures(h.state_mut()), 1);
}
/// #5859: Mod+V admits a rich-only clipboard (HTML or RTF with no plain-text or picture flavor)
/// and still routes an image+HTML clipboard with no plain-text flavor to picture paste.
#[test]
fn mod_v_pastes_rich_only_clipboard_and_preserves_picture_routing() {
let ctrl = mod_held();
let mut h = alt_frame_app();
offer(&h, vec![ClipItem::Html("<p><b>html-only</b></p>".into())]);
mods_frame(&mut h, ctrl, vec![key_event(Key::V, true, ctrl)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
assert_eq!(body(h.state()), "html-only", "Mod+V pastes HTML-only clipboard");
assert!(is_bold(&mut h), "HTML-only paste keeps formatting");
let mut h = alt_frame_app();
offer(&h, vec![ClipItem::Rtf(r"{\rtf1\ansi {\b rtf-only}}".into())]);
mods_frame(&mut h, ctrl, vec![key_event(Key::V, true, ctrl)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
assert_eq!(body(h.state()), "rtf-only", "Mod+V pastes RTF-only clipboard");
assert!(is_bold(&mut h), "RTF-only paste keeps formatting");
let mut h = alt_frame_app();
offer(
&h,
vec![
ClipItem::Image(std::sync::Arc::new(egui::ColorImage::from_rgba_unmultiplied([4, 4], &[200u8; 4 * 4 * 4]))),
ClipItem::Html("<p><b>fallback</b></p>".into()),
],
);
mods_frame(&mut h, ctrl, vec![key_event(Key::V, true, ctrl)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
assert_eq!(pictures(h.state_mut()), 1, "image+HTML with no plain text routes to picture paste");
assert_eq!(body(h.state()), "", "picture paste does not fall back to HTML text");
let dir = std::env::temp_dir().join(format!("wc-mod-v-uri-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let png = dir.join("clip.png");
std::fs::write(&png, crate::paste_picture::png_from_rgba(4, 4, vec![200; 64]).unwrap()).unwrap();
let raw = png.to_string_lossy().replace('\\', "/").replace(' ', "%20");
let uri = if raw.starts_with('/') { format!("file://{raw}\r\n") } else { format!("file:///{raw}\r\n") };
let mut h = alt_frame_app();
offer(&h, vec![ClipItem::custom(craft::platform::clipboard::URI_LIST, uri.into_bytes()), ClipItem::Html("<p><b>fallback</b></p>".into())]);
mods_frame(&mut h, ctrl, vec![key_event(Key::V, true, ctrl)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(pictures(h.state_mut()), 1, "URI list+HTML with no plain text routes to picture file paste");
assert_eq!(body(h.state()), "", "picture file paste does not fall back to HTML text");
}
/// #819: Alt+Q reaches Search/commands even when the canvas does not hold focus.
#[test]
fn alt_shortcuts_work_without_the_canvas_focused() {
if cfg!(target_os = "macos") {
return;
}
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Text")), Default::default());
app.run("view.focus", json!({})).unwrap();
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
crate::test_harness::frames(&mut h, 4);
if let Some(focused_id) = h.ctx.memory(|m| m.focused()) {
h.ctx.memory_mut(|m| m.surrender_focus(focused_id));
}
crate::test_harness::frames(&mut h, 1);
assert!(!h.state().canvas.focused(&h.ctx.clone()), "canvas is unfocused");
let alt = egui::Modifiers { alt: true, ..Default::default() };
mods_frame(&mut h, alt, vec![key_event(Key::Q, true, alt)]);
crate::test_harness::frames(&mut h, 2);
use egui_kittest::kittest::Queryable as _;
assert!(h.query_by_role(egui::accesskit::Role::Dialog).is_some(), "Alt+Q opens Search/commands with canvas unfocused");
}
/// Alt held, keypad 0 2 3 3, Alt released: é (й on a Russian system) is typed, the digits
/// aren't, and keytips stay off (#961). Linux sends each digit's text too; Windows may send the
/// composed character.
@@ -1368,34 +1250,6 @@ fn oversized_ime_events_are_ignored() {
assert!(resynced(&h), "the refused commit starts the composition afresh");
}
#[test]
fn observe_ime_drops_a_preedit_without_focus() {
let a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default());
let mut h = crate::test_harness::builder().allow_missing_glyphs().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
crate::test_harness::frames(&mut h, 6);
assert!(h.state().canvas.focused(&h.ctx.clone()), "canvas starts focused");
h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "に".into(), active_range_chars: Some(0..1) }));
crate::test_harness::frames(&mut h, 1);
assert_eq!(h.state().canvas.ime_preedit.as_str(), "に");
assert_eq!(h.state().canvas.ime_preedit_range, Some(0..1));
if let Some(focused_id) = h.ctx.memory(|m| m.focused()) {
h.ctx.memory_mut(|m| m.surrender_focus(focused_id));
}
crate::test_harness::frames(&mut h, 1);
assert!(!h.state().canvas.focused(&h.ctx.clone()), "focus moved off canvas");
assert!(h.state().canvas.ime_preedit.is_empty(), "no composition is kept for an unfocused editor");
assert_eq!(h.state().canvas.ime_preedit_range, None);
}
#[test]
fn typing_with_smart_art_selected_types_into_an_item() {
let mut h = alt_frame_app();
+1 -19
View File
@@ -142,24 +142,6 @@ fn legacy() -> &'static [(&'static str, CommandRef)] {
})
}
/// Cached `Phase::Tabs` keytip sequences (`SEARCH_LETTER` when Backstage is closed, plus Word
/// 2003 legacy menu keys on non-macOS).
fn sequences(backstage: bool) -> &'static [(&'static str, CommandRef)] {
static WITH_SEARCH: OnceLock<Vec<(&'static str, CommandRef)>> = OnceLock::new();
static SEARCH_ONLY: OnceLock<[(&'static str, CommandRef); 1]> = OnceLock::new();
match (cfg!(target_os = "macos"), backstage) {
(true, true) => &[],
(true, false) => SEARCH_ONLY.get_or_init(|| [(SEARCH_LETTER, CommandRef::new("tools.search"))]),
(false, true) => legacy(),
(false, false) => WITH_SEARCH.get_or_init(|| {
let mut v = legacy().to_vec();
v.push((SEARCH_LETTER, CommandRef::new("tools.search")));
v
}),
}
}
/// The letter badge for a tab (empty when it has none).
pub fn tab_letter(tab: &str) -> &'static str {
TAB_LETTERS.iter().chain(&TABLE_TAB_LETTERS).find(|(t, _)| *t == tab).map(|(_, l)| *l).unwrap_or("")
@@ -544,7 +526,7 @@ pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>
None => KeytipCache::new(app, &app.ui.tab),
};
let controls: &[KeytipControl<'_>] = if app.ui.backstage { backstage_controls() } else { &cache.tab_controls };
let sequences = sequences(app.ui.backstage);
let sequences: &[(&str, CommandRef)] = if cfg!(target_os = "macos") { &[] } else { legacy() };
// A hidden toolbar has no badges, and a disabled command's button has none to press.
let digits: Vec<CommandRef> = if app.ui.quick_access_toolbar {
app.session
-53
View File
@@ -397,59 +397,6 @@ fn long_qat_badges_wait_for_the_complete_number_and_escape_cancels() {
}
}
/// #819: Alt (or F10), then Q opens Search in the title bar, ends keytips, and never types into
/// the document; while the Backstage is open, Q does not open Search.
#[test]
fn alt_then_q_opens_search() {
let mut h = harness(app());
assert!(!crate::chrome::search::is_open(h.state()), "Search starts closed");
// F10, then Q works on every platform (including macOS, where bare Option types characters).
h.input_mut().events.push(key_event(egui::Key::F10, true, egui::Modifiers::NONE));
crate::test_harness::frame(&mut h);
assert!(h.state().keytips_active, "F10 activates keytips");
h.input_mut().events.extend([key_event(egui::Key::Q, true, egui::Modifiers::NONE), egui::Event::Text("q".into())]);
crate::test_harness::frames(&mut h, 2);
assert!(!h.state().keytips_active, "Q ends keytips");
assert!(crate::chrome::search::is_open(h.state()), "F10, Q opens Search");
assert!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).is_empty(), "Q does not type into the document");
// On non-macOS, a bare Alt tap followed by Q opens Search without typing into the document.
if !cfg!(target_os = "macos") {
h.state_mut().chrome.search = false;
let ctx = h.ctx.clone();
h.state_mut().canvas.focus_page(&ctx);
crate::test_harness::frame(&mut h);
let alt = egui::Modifiers { alt: true, ..Default::default() };
h.input_mut().events.extend([key_event(egui::Key::AltLeft, true, egui::Modifiers::NONE), egui::Event::ModifiersChanged(alt)]);
crate::test_harness::frame(&mut h);
h.input_mut().events.extend([key_event(egui::Key::AltLeft, false, alt), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]);
crate::test_harness::frame(&mut h);
assert!(h.state().keytips_active, "a bare Alt tap activates keytips");
h.input_mut().events.extend([key_event(egui::Key::Q, true, egui::Modifiers::NONE), egui::Event::Text("q".into())]);
crate::test_harness::frames(&mut h, 2);
assert!(!h.state().keytips_active, "Q ends keytips after bare Alt");
assert!(crate::chrome::search::is_open(h.state()), "Alt, Q opens Search");
assert!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).is_empty(), "Alt, Q does not type into the document");
}
// With Backstage open, Q does not open Search behind it.
h.state_mut().chrome.search = false;
h.state_mut().run("ui.backstage", serde_json::json!({"value": true})).unwrap();
crate::test_harness::frame(&mut h);
assert!(h.state().ui.backstage, "Backstage is open");
h.input_mut().events.push(key_event(egui::Key::F10, true, egui::Modifiers::NONE));
crate::test_harness::frame(&mut h);
h.input_mut().events.extend([key_event(egui::Key::Q, true, egui::Modifiers::NONE), egui::Event::Text("q".into())]);
crate::test_harness::frames(&mut h, 2);
assert!(!crate::chrome::search::is_open(h.state()), "Q does not open Search while Backstage is open");
assert!(h.state().dialog_host.open_dialogs().is_empty(), "Q does not open the Search dialog while Backstage is open");
}
#[test]
fn qat_keytips_follow_custom_order_and_skip_disabled_commands() {
let mut a = app();
-2
View File
@@ -548,8 +548,6 @@ pub struct WordApp {
pub(crate) dialog_answers: Vec<(craft::ui::dialog::DialogId, String, serde_json::Value)>,
/// Field gestures as undo steps ([`undo_marks`]).
pub(crate) edits: craft::ui::edit::GestureHost<WordApp>,
/// Active gesture id and whether an edit was applied for it ([`undo_marks`]).
pub(crate) edits_gesture: Option<(craft::behavior::GestureId, bool)>,
/// The Equation tab's symbol set.
pub(crate) equation_symbol_set: usize,
/// The gradient variation memory of Format Shape.
+2 -2
View File
@@ -215,7 +215,7 @@ pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
for (id, icon, tip) in
[("format.growFont", "grow", tl!("Increase Font Size")), ("format.shrinkFont", "shrink", tl!("Decrease Font Size"))]
{
let b = Button::command(CommandRef::new(id)).icon(crate::icons::spec(icon)).tooltip(tip.to_string()).show(ui);
let b = Button::command(CommandRef::new(id)).icon(crate::icons::id(icon)).tooltip(tip.to_string()).show(ui);
preview_on_hover(app, b.hover, b.response.enabled(), id, json!({}), preview);
}
});
@@ -289,7 +289,7 @@ fn follow_list<T>(app: &mut WordApp, preview: bool, event: &Preview<T>, command:
/// command carries no checked state, so the value is bound here and only draws the button.
fn toggle(ui: &mut Ui, app: &mut WordApp, id: &str, icon: &'static str, on: bool, preview: bool) {
let r = <ToggleButton as Props>::command(ToggleButton::new(Label::Empty, Bind::given(on)), CommandRef::new(id))
.icon(crate::icons::spec(icon))
.icon(crate::icons::id(icon))
.icon_only()
.show(ui);
preview_on_hover(app, r.hover, r.response.enabled(), id, json!({}), preview);
-14
View File
@@ -76,20 +76,6 @@ fn system_help(h: &egui_kittest::Harness<'static, WordApp>) -> Option<String> {
h.query_by_label_contains("Your system has animation effects").and_then(|n| n.accesskit_node().label()).map(|s| s.to_string())
}
/// Deserializing settings with thousands of unknown keys runs in linear time and does not fail.
#[test]
fn unknown_settings_keys_load_in_linear_time() {
let mut map = serde_json::Map::new();
for i in 0..20_000 {
map.insert(format!("unknownKey{i}"), json!(i));
}
map.insert("miniToolbar".into(), json!(false));
let bytes = serde_json::to_vec(&serde_json::Value::Object(map)).unwrap();
let (prefs, errors) = legacy_ui_json(&bytes).unwrap();
assert!(errors.is_empty());
assert!(!prefs.mini_toolbar);
}
/// File › Options must not offer a way around the protected document's author check.
#[test]
fn user_name_field_disables_when_protection_starts() {
+3 -1
View File
@@ -1,7 +1,9 @@
use craft::behavior::IconId;
use craft::ui::buttons::{Button, IconButton};
use craft::ui::contract::{Props, Show, ShowContainer};
use craft::ui::display::{Shade, Text};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::primitives::IconSpec;
use craft::ui::sections::GroupBox;
use egui::Ui;
use serde_json::{Value, json};
@@ -77,7 +79,7 @@ fn level_row(ui: &mut Ui, caption: &str, value: &str, none: bool, tip: &str, not
Text::new(tl!(caption).to_owned()).shade(Shade::Muted).show(ui);
Row::new().show(ui, |ui, _| {
Text::new(value.to_owned()).shade(if none { Shade::Faint } else { Shade::Normal }).show(ui);
let clear = IconButton::new(crate::icons::spec("clear")).label(tl!(tip).to_owned()).enabled(!nothing_to_clear).show(ui);
let clear = IconButton::new(IconSpec::svg(IconId::new("clear"))).label(tl!(tip).to_owned()).enabled(!nothing_to_clear).show(ui);
clicked = clear.clicked();
});
});
+3 -1
View File
@@ -1,5 +1,6 @@
//! Language-aware proofing task pane, laid out from black-box observation of Word on Windows.
use craft::behavior::IconId;
use craft::behavior::{DisplayOrder, ItemSource};
use craft::theme::variant::Tone;
use craft::ui::buttons::{Button, IconButton};
@@ -9,6 +10,7 @@ use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::{List, ListRow};
use craft::ui::menu::Menu;
use craft::ui::notices::Notice;
use craft::ui::primitives::IconSpec;
use craft::ui::style::{Span, TypeRole};
use craft::ui::text::TextField;
use egui::Ui;
@@ -182,7 +184,7 @@ fn body(app: &mut WordApp, ui: &mut Ui, form: &mut SpellingForm) {
Row::new().show(ui, |ui, _| {
Text::styled(spans.clone()).show(ui);
// PLAN: assumed IconSpec::svg("readAloud") from WORDCRAFT_ICONS (rb.A7, ribbon-w13); the icon is registered by name
if IconButton::new(crate::icons::spec("readAloud")).label(tl!("Read Aloud")).show(ui).clicked() {
if IconButton::new(IconSpec::svg(IconId::new("readAloud"))).label(tl!("Read Aloud")).show(ui).clicked() {
ask = Some(Ask::ReadAloud);
}
});
+1 -1
View File
@@ -114,7 +114,7 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui) {
run = Some(("readAloud.previous", json!({})));
}
let (icon, tip) = if state == State::Playing { ("pause", tl!("Pause")) } else { ("play", tl!("Play")) };
if IconButton::new(crate::icons::spec(icon)).label(tip).tooltip(tip).show(ui).clicked() {
if IconButton::new(crate::icons::id(icon)).label(tip).tooltip(tip).show(ui).clicked() {
run = Some(("readAloud.playPause", json!({})));
}
let next = IconButton::new(IconId::new("step_forward"))
+5 -4
View File
@@ -150,10 +150,11 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) -> RibbonOutput<String> {
.checked(track),
];
let ends = [
// The strip lays these out start to end, so Share, the old strip's outermost button, comes last. Comments and
// Editing are plain (ghost) buttons, as in v0.18.1; Share is a filled accent button.
StripEnd::command(tl!("Comments").to_string(), IconSpec::svg(IconId::new("comment")), CommandRef::new("view.commentsPane")),
StripEnd::menu(editing_label.to_string(), IconSpec::svg(IconId::new("wordcraft.pencil")), &modes),
// The strip lays these out start to end, so Share, the old strip's outermost button, comes last. As the old
// strip drew them: Comments and Editing outlined, Share a filled accent button.
StripEnd::command(tl!("Comments").to_string(), IconSpec::svg(IconId::new("comment")), CommandRef::new("view.commentsPane"))
.variant(Variant::SECONDARY),
StripEnd::menu(editing_label.to_string(), IconSpec::svg(IconId::new("wordcraft.pencil")), &modes).variant(Variant::SECONDARY),
StripEnd::command(
tl!("Share").to_string(),
IconSpec::svg(IconId::new("share")),
+2 -5
View File
@@ -40,7 +40,7 @@ pub(super) fn design(row: &mut RibbonRow<'_>, app: &mut WordApp) {
);
menu_button(
ui,
Button::new(crate::tl!("Fonts")).icon(crate::icons::spec("fonts")).tooltip(crate::tl!("Theme Fonts")),
Button::new(crate::tl!("Fonts")).icon(IconId::new("fonts")).tooltip(crate::tl!("Theme Fonts")),
crate::tl!("Theme Fonts"),
Some("design.themeFonts"),
|ui, _| {
@@ -87,10 +87,7 @@ pub(super) fn design(row: &mut RibbonRow<'_>, app: &mut WordApp) {
row.group(RibbonGroup::new("Page Background", crate::tl!("Page Background"), IconId::new("pageColor").into()), |ui| {
menu_button(
ui,
Button::new(crate::tl!("Watermark"))
.icon(crate::icons::spec("watermark"))
.tooltip(crate::tl!("Watermark"))
.arrangement(Arrangement::Stacked),
Button::new(crate::tl!("Watermark")).icon(IconId::new("watermark")).tooltip(crate::tl!("Watermark")).arrangement(Arrangement::Stacked),
crate::tl!("Watermark"),
Some("design.watermark"),
|ui, _| {
+5 -5
View File
@@ -8,7 +8,7 @@ use craft::ui::buttons::{Arrangement, Button, SplitButton, SplitMenu, ToggleButt
use craft::ui::contract::{Gap, Props as _, Show as _, ShowContainer as _};
use craft::ui::layout_components::Stack;
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::primitives::IconMark;
use craft::ui::primitives::{IconMark, IconSpec};
use craft::ui::style::DataColor;
use wordcraft_doc::freeform::InkTool;
@@ -33,7 +33,7 @@ pub(super) fn draw(row: &mut RibbonRow<'_>, app: &mut WordApp) {
] {
ToggleButton::command(CommandRef::with_params(id, json!({})))
.label(crate::tl!(label))
.icon(crate::icons::spec(key))
.icon(crate::icons::id(key))
.arrangement(Arrangement::Stacked)
.selected(on)
.show(ui);
@@ -75,7 +75,7 @@ pub(super) fn draw(row: &mut RibbonRow<'_>, app: &mut WordApp) {
})),
)
.label(crate::tl!("Color"))
.icon(crate::icons::spec("fontcolor").with_mark(IconMark::bar(DataColor::new(ink))))
.icon(IconSpec::from(IconId::new("fontcolor")).with_mark(IconMark::bar(DataColor::new(ink))))
.show(ui);
menu_button(
ui,
@@ -111,7 +111,7 @@ pub(super) fn draw(row: &mut RibbonRow<'_>, app: &mut WordApp) {
.show(ui);
Button::command(CommandRef::with_params("draw.inkToMath", json!({})))
.label(crate::tl!("Ink to\nMath"))
.icon(crate::icons::spec("inkToMath"))
.icon(IconId::new("inkToMath"))
.arrangement(Arrangement::Stacked)
.show(ui);
});
@@ -169,7 +169,7 @@ fn gallery_pen(ui: &mut egui::Ui, i: usize, pen: wordcraft_engine::cmd::draw::Cu
let tip = format!("{kind}: {size}, #{}", pen.color.hex());
let response = ToggleButton::command(CommandRef::with_params(pen_command(pen.kind), json!({"color": pen.color.hex(), "width": pen.width})))
.label(kind)
.icon(crate::icons::spec(glyph).with_mark(IconMark::weighted_bar(DataColor::new(color), bar)))
.icon(IconSpec::from(crate::icons::id(glyph)).with_mark(IconMark::weighted_bar(DataColor::new(color), bar)))
.arrangement(Arrangement::Stacked)
.tooltip(tip)
.selected(active)
+2 -1
View File
@@ -11,6 +11,7 @@ use craft::ui::contract::{
};
use craft::ui::list::{ThumbAspect, ThumbSize};
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::primitives::IconSpec;
use craft::ui::primitives::textures::Revision;
use craft::ui::runtime::commands::resolve;
use craft::ui::runtime::env::Env;
@@ -282,7 +283,7 @@ pub(crate) fn shapes(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
.enabled(enabled)
.show_items(ui, &Indexed(SHAPE_TILES.len()), &mut |at, _| {
let (label, _, icon) = SHAPE_TILES.get(*at).copied().unwrap_or(("", "", "shape.rectangle"));
Tile::new(crate::tl!(label)).icon(crate::icons::spec(icon))
Tile::new(crate::tl!(label)).icon(IconSpec::svg(crate::icons::id(icon)))
});
if let Some((_, kind, _)) = picked(&out.response.events).and_then(|at| SHAPE_TILES.get(at))
&& app.run("insert.shape", json!({"kind": kind})).is_ok()
+19 -72
View File
@@ -24,7 +24,7 @@ use crate::colors::{Remember, Target};
/// A ribbon group titled `title`, with the Dialog Launcher `launcher` when it has one.
fn ribbon_group(key: &'static str, title: &str, icon: &'static str, launcher: Option<&str>) -> RibbonGroup<'static> {
let group = RibbonGroup::new(key, tl!(title).to_string(), crate::icons::spec(icon));
let group = RibbonGroup::new(key, tl!(title).to_string(), crate::icons::id(icon).into());
match launcher {
Some(id) => group.launcher(CommandRef::new(id)),
None => group,
@@ -157,7 +157,6 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
("Paste", "edit.paste"),
("Keep Text Only", "edit.pasteText"),
("Merge Formatting", "edit.pasteMerge"),
("Paste as Nested Table", "edit.pasteNestedTable"),
("Paste Special…", "edit.pasteSpecial"),
] {
MenuItem::command(CommandRef::new(id)).label(tl!(label).to_string()).show(ui);
@@ -166,7 +165,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
for (icon, label, id) in [("cut", "Cut", "edit.cut"), ("copy", "Copy", "edit.copy")] {
Button::command(CommandRef::new(id))
.icon(crate::icons::spec(icon))
.icon(crate::icons::id(icon))
.label(tl!(label).to_string())
.tooltip(tl!(label).to_string())
.show(ui);
@@ -189,9 +188,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
let mut size = st.get("size").and_then(Value::as_f64).map(fmt).unwrap_or_default();
let sizes: Vec<Entry<String>> =
wordcraft_engine::cmd::format::SIZES.iter().map(|s| Entry::new(fmt(f64::from(*s)), fmt(f64::from(*s)))).collect();
let out = craft::ui::pickers::ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut size), &sizes)
.tooltip(tl!("Font Size").to_string())
.show(ui);
let out = craft::ui::pickers::ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut size), &sizes).show(ui);
if let Some(v) = out.edit.events.committed()
&& let Ok(x) = v.trim().parse::<f64>()
{
@@ -199,12 +196,12 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
}
for (icon, tip, id) in [("grow", "Increase Font Size", "format.growFont"), ("shrink", "Decrease Font Size", "format.shrinkFont")]
{
IconButton::command(crate::icons::spec(icon), CommandRef::new(id))
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
.label(tl!(tip).to_string())
.tooltip(tl!(tip).to_string())
.show(ui);
}
let face = Button::new(tl!("Change Case").to_string()).icon(crate::icons::spec("case")).tooltip(tl!("Change Case").to_string());
let face = Button::new(tl!("Change Case").to_string()).icon(IconId::new("case")).tooltip(tl!("Change Case").to_string());
menu_button(ui, face, tl!("Change Case").to_string(), Some("format.changeCase"), |ui, _| {
for (label, mode) in [
("Sentence case.", "sentence"),
@@ -219,7 +216,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
}
});
for (icon, tip, id) in [("clear", "Clear All Formatting", "format.clear"), ("phonetic", "Phonetic Guide", "format.phonetic")] {
IconButton::command(crate::icons::spec(icon), CommandRef::new(id))
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
.label(tl!(tip).to_string())
.tooltip(tl!(tip).to_string())
.show(ui);
@@ -229,7 +226,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
for (icon, tip, id, on) in [("bold", "Bold", "format.bold", flag("bold")), ("italic", "Italic", "format.italic", flag("italic"))]
{
ToggleButton::command(CommandRef::new(id))
.icon(crate::icons::spec(icon))
.icon(crate::icons::id(icon))
.icon_only()
.selected(on)
.tooltip(tl!(tip).to_string())
@@ -239,7 +236,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
CommandRef::with_params("format.underline", json!({})),
SplitMenu::Body(Box::new(|ui, _| underline_menu(ui, app))),
)
.icon(crate::icons::spec("underline"))
.icon(IconId::new("underline"))
.selected(flag("underline"))
.tooltip(tl!("Underline").to_string())
.show(ui);
@@ -250,18 +247,18 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
("charborder", "Character Border", "format.border", flag("border")),
] {
ToggleButton::command(CommandRef::new(id))
.icon(crate::icons::spec(icon))
.icon(crate::icons::id(icon))
.icon_only()
.selected(on)
.tooltip(tl!(tip).to_string())
.show(ui);
}
IconButton::command(crate::icons::spec("enclose"), CommandRef::new("format.enclose"))
IconButton::command(IconId::new("enclose"), CommandRef::new("format.enclose"))
.label(tl!("Enclose Characters").to_string())
.tooltip(tl!("Enclose Characters").to_string())
.show(ui);
let face = Button::new(tl!("Text Effects and Typography").to_string())
.icon(crate::icons::spec("effects"))
.icon(IconId::new("effects"))
.tooltip(tl!("Text Effects and Typography").to_string());
menu_button(ui, face, tl!("Text Effects and Typography").to_string(), None, |ui, cx| text_effects_menu(ui, cx, app));
crate::colors::highlight_split(ui, app, tl!("Text Highlight Color"));
@@ -307,7 +304,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
.show(ui);
})),
)
.icon(crate::icons::spec("numbering"))
.icon(IconId::new("numbering"))
.selected(lists.numbering)
.tooltip(tl!("Numbering").to_string())
.show(ui);
@@ -344,20 +341,20 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
}
})),
)
.icon(crate::icons::spec("multilevel"))
.icon(IconId::new("multilevel"))
.selected(lists.multilevel)
.tooltip(tl!("Multilevel List").to_string())
.show(ui);
for (icon, tip, id) in
[("outdent", "Decrease Indent", "para.outdent"), ("indent", "Increase Indent", "para.indent"), ("sort", "Sort", "para.sort")]
{
IconButton::command(crate::icons::spec(icon), CommandRef::new(id))
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
.label(tl!(tip).to_string())
.tooltip(tl!(tip).to_string())
.show(ui);
}
ToggleButton::command(CommandRef::new("view.marks"))
.icon(crate::icons::spec("pilcrow"))
.icon(IconId::new("wordcraft.pilcrow"))
.icon_only()
.selected(marks)
.tooltip(tl!("Show/Hide ¶").to_string())
@@ -373,7 +370,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
("textRtl", "Right-to-Left Text Direction", "para.rtl", rtl),
] {
ToggleButton::command(CommandRef::new(id))
.icon(crate::icons::spec(icon))
.icon(crate::icons::id(icon))
.icon_only()
.selected(on)
.tooltip(tl!(tip).to_string())
@@ -427,7 +424,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
// whole document with Ctrl+A first (the commands take `scope: "all"` for that as well).
row.group(ribbon_group("paragraphTools", "Paragraph Tools", "pilcrow", None), |ui| {
let face = Button::new(tl!("Paragraph\nTools").to_string())
.icon(crate::icons::spec("pilcrow"))
.icon(IconId::new("wordcraft.pilcrow"))
.tooltip(tl!("Paragraph Tools").to_string())
.arrangement(Arrangement::Stacked);
menu_button(ui, face, tl!("Paragraph Tools").to_string(), None, |ui, _| {
@@ -473,7 +470,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
}
});
Button::command(CommandRef::with_params("ui.dialog", json!({"name": "replace"})))
.icon(crate::icons::spec("replace"))
.icon(IconId::new("replace"))
.label(tl!("Replace").to_string())
.tooltip(tl!("Replace").to_string())
.show(ui);
@@ -494,59 +491,9 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
});
row.group(ribbon_group("editor", "Editor", "editor", None), |ui| {
Button::command(CommandRef::new("review.spelling"))
.icon(crate::icons::spec("editor"))
.icon(IconId::new("editor"))
.label(tl!("Editor").to_string())
.arrangement(Arrangement::Stacked)
.show(ui);
});
}
#[cfg(test)]
mod tests {
use crate::WordApp;
use crate::test_harness::AppFrames as _;
use egui::accesskit::Role;
use egui::vec2;
use egui_kittest::kittest::{By, Queryable};
use serde_json::json;
use wordcraft_engine::Session;
/// #7317: focusing a real ribbon control (`Bold` -> `Tab`) via keyboard shows its hint only
/// after `tooltip::DELAY`, and hides it while a ribbon menu is open.
#[test]
fn keyboard_focus_shows_the_hint_after_a_delay_but_not_over_a_menu() {
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample")), crate::Services::default());
app.ui.language = "en".into();
app.run("ui.tab", json!({"tab": "Home"})).unwrap();
let mut h = crate::test_harness::builder().with_size(vec2(2560.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
crate::test_harness::cjk_stand_in(&h.ctx);
crate::test_harness::frames(&mut h, 4);
let tooltip_visible = |h: &egui_kittest::Harness<'static, WordApp>| h.query_all_by_label_contains("Home › Font").count() > 0;
let bold = h.query_all(By::new().role(Role::Button).label("Bold")).next().expect("ribbon Bold button");
bold.focus();
h.app_frame();
h.event(egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE });
h.app_frame();
assert!(!tooltip_visible(&h), "just focused: hint should not show before tooltip delay");
let delay_frames = (craft::ui::contract::tooltip::DELAY / 0.25).ceil() as usize + 3;
for _ in 0..delay_frames {
h.step();
}
assert!(tooltip_visible(&h), "focused ribbon control should show its hint after tooltip delay");
let case_btn = h.query_all(By::new().role(Role::Button).label("Change Case")).next().expect("ribbon Change Case button");
case_btn.click();
crate::test_harness::frames(&mut h, 3);
assert!(!tooltip_visible(&h), "hint must not remain visible over an open ribbon menu");
}
}
+11 -11
View File
@@ -10,7 +10,7 @@ use craft::ui::display::Divider;
use craft::ui::layout_components::Stack;
use craft::ui::list::ThumbAspect;
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::primitives::{HAlign, TextRun};
use craft::ui::primitives::{HAlign, IconSpec, TextRun};
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
use egui::Ui;
@@ -125,7 +125,7 @@ pub(super) fn insert(row: &mut RibbonRow<'_>, app: &mut WordApp) {
] {
MenuItem::command(CommandRef::with_params("insert.shape", json!({"kind": kind, "arrow": arrow})))
.label(crate::tl!(label))
.icon(crate::icons::spec(glyph))
.icon(crate::icons::id(glyph))
.show(ui);
}
let _ = cx;
@@ -135,7 +135,7 @@ pub(super) fn insert(row: &mut RibbonRow<'_>, app: &mut WordApp) {
for (key, label, id) in
[("icons", "Icons", "insert.icon"), ("smartArt", "Diagram", "insert.smartArt"), ("chart", "Chart", "insert.chart")]
{
Button::command(CommandRef::with_params(id, json!({}))).label(crate::tl!(label)).icon(crate::icons::spec(key)).show(ui);
Button::command(CommandRef::with_params(id, json!({}))).label(crate::tl!(label)).icon(crate::icons::id(key)).show(ui);
}
});
});
@@ -196,7 +196,7 @@ pub(super) fn insert(row: &mut RibbonRow<'_>, app: &mut WordApp) {
menu_button(
ui,
Button::new(crate::tl!("Page\nNumber"))
.icon(crate::icons::spec("pageNumber"))
.icon(IconId::new("pageNumber"))
.tooltip(crate::tl!("Page Number"))
.arrangement(Arrangement::Stacked),
crate::tl!("Page Number"),
@@ -216,10 +216,10 @@ pub(super) fn insert(row: &mut RibbonRow<'_>, app: &mut WordApp) {
},
);
});
row.group(RibbonGroup::new("Text", crate::tl!("Text"), crate::icons::spec("textBox")), |ui| {
row.group(RibbonGroup::new("Text", crate::tl!("Text"), IconId::new("textBox").into()), |ui| {
Button::command(CommandRef::with_params("insert.textBox", json!({})))
.label(crate::tl!("Text\nBox"))
.icon(crate::icons::spec("textBox"))
.icon(IconId::new("textBox"))
.arrangement(Arrangement::Stacked)
.show(ui);
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
@@ -242,7 +242,7 @@ pub(super) fn insert(row: &mut RibbonRow<'_>, app: &mut WordApp) {
);
menu_button(
ui,
Button::new(crate::tl!("Decorative Text")).icon(crate::icons::spec("wordArt")).tooltip(crate::tl!("Decorative Text")),
Button::new(crate::tl!("Decorative Text")).icon(IconId::new("wordArt")).tooltip(crate::tl!("Decorative Text")),
crate::tl!("Decorative Text"),
Some("insert.wordArt"),
|ui, cx| {
@@ -251,7 +251,7 @@ pub(super) fn insert(row: &mut RibbonRow<'_>, app: &mut WordApp) {
);
menu_button(
ui,
Button::new(crate::tl!("Drop Cap")).icon(crate::icons::spec("dropCap")).tooltip(crate::tl!("Drop Cap")),
Button::new(crate::tl!("Drop Cap")).icon(IconId::new("dropCap")).tooltip(crate::tl!("Drop Cap")),
crate::tl!("Drop Cap"),
Some("insert.dropCap"),
|ui, _| drop_cap_items(ui, app),
@@ -263,18 +263,18 @@ pub(super) fn insert(row: &mut RibbonRow<'_>, app: &mut WordApp) {
("dateTime", "Date & Time", "ui.dialog", json!({"name": "dateTime"})),
("object", "Object", "insert.object", json!({})),
] {
IconButton::command(crate::icons::spec(key), CommandRef::with_params(id, params))
IconButton::command(IconSpec::from(crate::icons::id(key)), CommandRef::with_params(id, params))
.label(crate::tl!(tip))
.tooltip(crate::tl!(tip))
.show(ui);
}
});
});
row.group(RibbonGroup::new("Symbols", crate::tl!("Symbols"), crate::icons::spec("symbol")), |ui| {
row.group(RibbonGroup::new("Symbols", crate::tl!("Symbols"), IconId::new("symbol").into()), |ui| {
crate::equation_tab::insert_button(ui, app);
menu_button(
ui,
Button::new(crate::tl!("Symbol")).icon(crate::icons::spec("symbol")).tooltip(crate::tl!("Symbol")).arrangement(Arrangement::Stacked),
Button::new(crate::tl!("Symbol")).icon(IconId::new("symbol")).tooltip(crate::tl!("Symbol")).arrangement(Arrangement::Stacked),
crate::tl!("Symbol"),
Some("insert.symbol"),
|ui, cx| {
+2 -2
View File
@@ -75,7 +75,7 @@ pub(super) fn layout(row: &mut RibbonRow<'_>, app: &mut WordApp) {
// Text Direction works on what the caret is in: table cells, a text box, else the section.
let dir = wordcraft_engine::cmd::page::text_direction_at(&app.session);
let stacked =
|label: &'static str, icon: &'static str| Button::new(tl!(label)).icon(crate::icons::spec(icon)).arrangement(Arrangement::Stacked);
|label: &'static str, icon: &'static str| Button::new(tl!(label)).icon(crate::icons::id(icon)).arrangement(Arrangement::Stacked);
menu_button(ui, stacked("Text\nDirection", "textDirection"), tl!("Text Direction"), Some("layout.textDirection"), |ui, _| {
use wordcraft_doc::props::TextDirection;
for (label, d) in [
@@ -96,7 +96,7 @@ pub(super) fn layout(row: &mut RibbonRow<'_>, app: &mut WordApp) {
menu_button(ui, stacked("Size", "size"), tl!("Size"), Some("layout.size"), |ui, _| size_menu(ui, app));
menu_button(ui, stacked("Columns", "columns"), tl!("Columns"), Some("layout.columns"), |ui, _| columns_items(ui, app));
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
let inline = |label: &'static str, icon: &'static str| Button::new(tl!(label)).icon(crate::icons::spec(icon));
let inline = |label: &'static str, icon: &'static str| Button::new(tl!(label)).icon(crate::icons::id(icon));
menu_button(ui, inline("Breaks", "breaks"), tl!("Breaks"), Some("layout.break"), |ui, _| {
MenuItem::heading(tl!("Page Breaks")).show(ui);
for (l, k) in [("Page", "page"), ("Column", "column"), ("Text Wrapping", "textWrapping")] {
+9 -8
View File
@@ -7,6 +7,7 @@ use craft::ui::buttons::{Arrangement, Button, IconButton};
use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::menu::MenuItem;
use craft::ui::primitives::IconSpec;
use craft::ui::text::NumberField;
pub(super) fn mailings(row: &mut RibbonRow<'_>, app: &mut WordApp) {
@@ -14,7 +15,7 @@ pub(super) fn mailings(row: &mut RibbonRow<'_>, app: &mut WordApp) {
for (key, label, id) in [("envelope", "Envelopes", "mailings.envelopes"), ("labels", "Labels", "mailings.labels")] {
Button::command(CommandRef::with_params(id, json!({})))
.label(crate::tl!(label))
.icon(crate::icons::spec(key))
.icon(crate::icons::id(key))
.arrangement(Arrangement::Stacked)
.show(ui);
}
@@ -69,7 +70,7 @@ pub(super) fn mailings(row: &mut RibbonRow<'_>, app: &mut WordApp) {
.arrangement(Arrangement::Stacked)
.show(ui);
});
row.group(RibbonGroup::new("Write & Insert Fields", crate::tl!("Write & Insert Fields"), crate::icons::spec("mergeField")), |ui| {
row.group(RibbonGroup::new("Write & Insert Fields", crate::tl!("Write & Insert Fields"), IconId::new("mergeField").into()), |ui| {
for (key, label, id) in [
("highlightFields", "Highlight\nMerge Fields", "mailings.highlightFields"),
("addressBlock", "Address\nBlock", "mailings.addressBlock"),
@@ -78,7 +79,7 @@ pub(super) fn mailings(row: &mut RibbonRow<'_>, app: &mut WordApp) {
] {
Button::command(CommandRef::with_params(id, json!({})))
.label(crate::tl!(label))
.icon(crate::icons::spec(key))
.icon(crate::icons::id(key))
.arrangement(Arrangement::Stacked)
.show(ui);
}
@@ -86,7 +87,7 @@ pub(super) fn mailings(row: &mut RibbonRow<'_>, app: &mut WordApp) {
// The merge rules the engine knows; If and Skip Record If ask for their condition.
menu_button(
ui,
Button::new(crate::tl!("Rules")).icon(crate::icons::spec("rules")).tooltip(crate::tl!("Rules")),
Button::new(crate::tl!("Rules")).icon(IconId::new("rules")).tooltip(crate::tl!("Rules")),
crate::tl!("Rules"),
Some("mailings.rules"),
|ui, _| {
@@ -99,20 +100,20 @@ pub(super) fn mailings(row: &mut RibbonRow<'_>, app: &mut WordApp) {
);
Button::command(CommandRef::with_params("mailings.matchFields", json!({})))
.label(crate::tl!("Match Fields"))
.icon(crate::icons::spec("matchFields"))
.icon(IconId::new("matchFields"))
.show(ui);
});
});
row.group(RibbonGroup::new("Preview Results", crate::tl!("Preview Results"), crate::icons::spec("preview")), |ui| {
row.group(RibbonGroup::new("Preview Results", crate::tl!("Preview Results"), IconId::new("preview").into()), |ui| {
Button::command(CommandRef::with_params("mailings.preview", json!({})))
.label(crate::tl!("Preview\nResults"))
.icon(crate::icons::spec("preview"))
.icon(IconId::new("preview"))
.arrangement(Arrangement::Stacked)
.show(ui);
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
let nav = |ui: &mut egui::Ui, key: &'static str, tip: &'static str, id: &'static str| {
IconButton::command(crate::icons::spec(key), CommandRef::with_params(id, json!({})))
IconButton::command(IconSpec::from(crate::icons::id(key)), CommandRef::with_params(id, json!({})))
.label(crate::tl!(tip))
.tooltip(crate::tl!(tip))
.show(ui);
+17 -17
View File
@@ -57,10 +57,10 @@ pub(super) fn references(row: &mut RibbonRow<'_>, app: &mut WordApp) {
.show(ui);
});
});
row.group(RibbonGroup::new("Footnotes", crate::tl!("Footnotes"), crate::icons::spec("footnote")).launcher("references.noteOptions"), |ui| {
row.group(RibbonGroup::new("Footnotes", crate::tl!("Footnotes"), IconId::new("footnote").into()).launcher("references.noteOptions"), |ui| {
Button::command(CommandRef::with_params("references.footnote", json!({})))
.label(crate::tl!("Insert\nFootnote"))
.icon(crate::icons::spec("footnote"))
.icon(IconId::new("footnote"))
.arrangement(Arrangement::Stacked)
.show(ui);
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
@@ -69,7 +69,7 @@ pub(super) fn references(row: &mut RibbonRow<'_>, app: &mut WordApp) {
("nextFootnote", "Next Footnote", "references.nextFootnote"),
("showNotes", "Show Notes", "references.notes"),
] {
Button::command(CommandRef::with_params(id, json!({}))).label(crate::tl!(label)).icon(crate::icons::spec(key)).show(ui);
Button::command(CommandRef::with_params(id, json!({}))).label(crate::tl!(label)).icon(crate::icons::id(key)).show(ui);
}
});
});
@@ -80,12 +80,12 @@ pub(super) fn references(row: &mut RibbonRow<'_>, app: &mut WordApp) {
.arrangement(Arrangement::Stacked)
.show(ui);
});
row.group(RibbonGroup::new("Citations & Bibliography", crate::tl!("Citations & Bibliography"), crate::icons::spec("citation")), |ui| {
row.group(RibbonGroup::new("Citations & Bibliography", crate::tl!("Citations & Bibliography"), IconId::new("citation").into()), |ui| {
// The document's sources to cite, then a new one (Create Source, #402).
menu_button(
ui,
Button::new(crate::tl!("Insert\nCitation"))
.icon(crate::icons::spec("citation"))
.icon(IconId::new("citation"))
.tooltip(crate::tl!("Insert Citation"))
.arrangement(Arrangement::Stacked),
crate::tl!("Insert Citation"),
@@ -112,7 +112,7 @@ pub(super) fn references(row: &mut RibbonRow<'_>, app: &mut WordApp) {
let label = crate::i18n::fmt(crate::tl!("Style: {style}"), &[("style", &current)]);
menu_button(
ui,
Button::new(label).icon(crate::icons::spec("styles")).tooltip(crate::tl!("Citation Style")),
Button::new(label).icon(IconId::new("styles")).tooltip(crate::tl!("Citation Style")),
crate::tl!("Citation Style"),
Some("references.citationStyle"),
|ui, _| {
@@ -144,28 +144,28 @@ pub(super) fn references(row: &mut RibbonRow<'_>, app: &mut WordApp) {
] {
Button::command(CommandRef::with_params(id, json!({})))
.label(crate::tl!(label))
.icon(crate::icons::spec(key))
.icon(crate::icons::id(key))
.tooltip(crate::tl!(tip))
.show(ui);
}
});
});
row.group(RibbonGroup::new("Index", crate::tl!("Index"), crate::icons::spec("index")), |ui| {
row.group(RibbonGroup::new("Index", crate::tl!("Index"), IconId::new("index").into()), |ui| {
Button::command(CommandRef::with_params("references.markEntry", json!({})))
.label(crate::tl!("Mark\nEntry"))
.icon(crate::icons::spec("markEntry"))
.icon(IconId::new("markEntry"))
.arrangement(Arrangement::Stacked)
.show(ui);
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
for (key, label, id) in [("index", "Insert Index", "references.index"), ("update", "Update Index", "references.updateIndex")] {
Button::command(CommandRef::with_params(id, json!({}))).label(crate::tl!(label)).icon(crate::icons::spec(key)).show(ui);
Button::command(CommandRef::with_params(id, json!({}))).label(crate::tl!(label)).icon(crate::icons::id(key)).show(ui);
}
});
});
row.group(RibbonGroup::new("Table of Authorities", crate::tl!("Table of Authorities"), crate::icons::spec("tableOfAuthorities")), |ui| {
row.group(RibbonGroup::new("Table of Authorities", crate::tl!("Table of Authorities"), IconId::new("tableOfAuthorities").into()), |ui| {
Button::command(CommandRef::with_params("references.markCitation", json!({})))
.label(crate::tl!("Mark\nCitation"))
.icon(crate::icons::spec("markCitation"))
.icon(IconId::new("markCitation"))
.arrangement(Arrangement::Stacked)
.show(ui);
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
@@ -173,7 +173,7 @@ pub(super) fn references(row: &mut RibbonRow<'_>, app: &mut WordApp) {
("tableOfAuthorities", "Insert Table of Authorities", "references.tableOfAuthorities"),
("update", "Update Table", "references.updateAuthorities"),
] {
Button::command(CommandRef::with_params(id, json!({}))).label(crate::tl!(label)).icon(crate::icons::spec(key)).show(ui);
Button::command(CommandRef::with_params(id, json!({}))).label(crate::tl!(label)).icon(crate::icons::id(key)).show(ui);
}
});
});
@@ -184,14 +184,14 @@ pub(super) fn zotero(row: &mut RibbonRow<'_>, _app: &mut WordApp) {
let big = |ui: &mut egui::Ui, key: &'static str, label: &'static str, id: &'static str| {
Button::command(CommandRef::with_params(id, json!({})))
.label(crate::tl!(label))
.icon(crate::icons::spec(key))
.icon(crate::icons::id(key))
.arrangement(Arrangement::Stacked)
.show(ui);
};
row.group(RibbonGroup::new("Provider", crate::tl!("Provider"), crate::icons::spec("citation")), |ui| {
row.group(RibbonGroup::new("Provider", crate::tl!("Provider"), IconId::new("citation").into()), |ui| {
menu_button(
ui,
Button::new(crate::tl!("Provider")).icon(crate::icons::spec("citation")).tooltip(crate::tl!("Citation Provider")),
Button::new(crate::tl!("Provider")).icon(IconId::new("citation")).tooltip(crate::tl!("Citation Provider")),
crate::tl!("Citation Provider"),
Some("ui.citations.provider"),
|ui, _| {
@@ -202,7 +202,7 @@ pub(super) fn zotero(row: &mut RibbonRow<'_>, _app: &mut WordApp) {
},
);
});
row.group(RibbonGroup::new("Citations", crate::tl!("Citations"), crate::icons::spec("citation")), |ui| {
row.group(RibbonGroup::new("Citations", crate::tl!("Citations"), IconId::new("citation").into()), |ui| {
big(ui, "citation", "Add/Edit\nCitation", "ui.zotero.addEditCitation");
big(ui, "addNote", "Add\nNote", "ui.zotero.addNote");
big(ui, "pastCitation", "Move Past\nCitation", "caret.pastCitation");
+14 -14
View File
@@ -12,24 +12,24 @@ use super::{WordApp, json};
/// The Review tab.
pub(super) fn review(row: &mut RibbonRow<'_>, app: &mut WordApp) {
row.group(RibbonGroup::new("review.proofing", tl!("Proofing").to_string(), crate::icons::spec("spelling")), |ui| {
row.group(RibbonGroup::new("review.proofing", tl!("Proofing").to_string(), IconId::new("spelling").into()), |ui| {
Button::command(CommandRef::new("review.spelling"))
.label(tl!("Spelling &\nGrammar").to_string())
.icon(crate::icons::spec("spelling"))
.icon(IconId::new("spelling"))
.arrangement(Arrangement::Stacked)
.show(ui);
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
Button::command(CommandRef::new("review.thesaurus")).label(tl!("Thesaurus").to_string()).icon(crate::icons::spec("thesaurus")).show(ui);
Button::command(CommandRef::new("review.thesaurus")).label(tl!("Thesaurus").to_string()).icon(IconId::new("thesaurus")).show(ui);
Button::command(CommandRef::with_params("ui.dialog", json!({"name": "wordCount"})))
.label(tl!("Word Count").to_string())
.icon(crate::icons::spec("wordCount"))
.icon(IconId::new("wordCount"))
.show(ui);
});
});
row.group(RibbonGroup::new("review.speech", tl!("Speech").to_string(), crate::icons::spec("readAloud")), |ui| {
row.group(RibbonGroup::new("review.speech", tl!("Speech").to_string(), IconId::new("readAloud").into()), |ui| {
Button::command(CommandRef::new("review.readAloud"))
.label(tl!("Read\nAloud").to_string())
.icon(crate::icons::spec("readAloud"))
.icon(IconId::new("readAloud"))
.arrangement(Arrangement::Stacked)
.show(ui);
});
@@ -40,13 +40,13 @@ pub(super) fn review(row: &mut RibbonRow<'_>, app: &mut WordApp) {
.arrangement(Arrangement::Stacked)
.show(ui);
});
row.group(RibbonGroup::new("review.language", tl!("Language").to_string(), crate::icons::spec("language")), |ui| {
row.group(RibbonGroup::new("review.language", tl!("Language").to_string(), IconId::new("language").into()), |ui| {
Button::command(CommandRef::new("review.translate"))
.label(tl!("Translate").to_string())
.icon(crate::icons::spec("translate"))
.icon(IconId::new("translate"))
.arrangement(Arrangement::Stacked)
.show(ui);
let face = Button::new(tl!("Language").to_string()).icon(crate::icons::spec("language")).arrangement(Arrangement::Stacked);
let face = Button::new(tl!("Language").to_string()).icon(IconId::new("language")).arrangement(Arrangement::Stacked);
menu_button(ui, face, tl!("Language").to_string(), None, |ui, _| language_menu(ui, app));
});
row.group(RibbonGroup::new("review.comments", tl!("Comments").to_string(), IconId::new("newComment").into()), |ui| {
@@ -188,7 +188,7 @@ pub(super) fn review(row: &mut RibbonRow<'_>, app: &mut WordApp) {
/// Developer › Controls: content controls.
pub(super) fn developer(row: &mut RibbonRow<'_>, app: &mut WordApp) {
let design = app.session.view.design_mode;
row.group(RibbonGroup::new("developer.controls", tl!("Controls").to_string(), crate::icons::spec("ccRichText")), |ui| {
row.group(RibbonGroup::new("developer.controls", tl!("Controls").to_string(), IconId::new("ccRichText").into()), |ui| {
let rows: [[(&'static str, &str); 3]; 3] = [
[("ccRichText", "developer.richText"), ("ccPlainText", "developer.plainText"), ("ccPicture", "developer.picture")],
[("ccGallery", "developer.buildingBlock"), ("ccCheckBox", "developer.checkBox"), ("ccComboBox", "developer.comboBox")],
@@ -199,7 +199,7 @@ pub(super) fn developer(row: &mut RibbonRow<'_>, app: &mut WordApp) {
for cells in rows {
Row::new().show(ui, |ui, _| {
for (icon_name, id) in cells {
IconButton::command(crate::icons::spec(icon_name), CommandRef::new(id)).show(ui);
IconButton::command(crate::icons::id(icon_name), CommandRef::new(id)).show(ui);
}
});
}
@@ -217,15 +217,15 @@ pub(super) fn developer(row: &mut RibbonRow<'_>, app: &mut WordApp) {
/// The Help tab.
pub(super) fn help(row: &mut RibbonRow<'_>, _app: &mut WordApp) {
row.group(RibbonGroup::new("help.help", tl!("Help").to_string(), crate::icons::spec("help")), |ui| {
row.group(RibbonGroup::new("help.help", tl!("Help").to_string(), IconId::new("help").into()), |ui| {
Button::command(CommandRef::with_params("ui.dialog", json!({"name": "about"})))
.label(tl!("Help").to_string())
.icon(crate::icons::spec("help"))
.icon(IconId::new("help"))
.arrangement(Arrangement::Stacked)
.show(ui);
Button::command(CommandRef::new("ui.checkForUpdates"))
.label(tl!("Check for\nUpdates…").to_string())
.icon(IconId::new("update"))
.icon(IconId::new("checkForUpdates"))
.arrangement(Arrangement::Stacked)
.show(ui);
Button::command(CommandRef::new("ui.discord"))
+5 -6
View File
@@ -116,18 +116,17 @@ pub(super) fn shape_format(row: &mut RibbonRow<'_>, app: &mut WordApp) {
});
}
row.group(RibbonGroup::new("shape.wordart", tl!("Decorative Text Styles"), IconId::new("wordcraft.more").into()), |ui| {
let styles =
Button::new(tl!("Styles")).icon(crate::icons::spec("wordArt")).tooltip(tl!("Decorative Text Styles")).arrangement(Arrangement::Stacked);
let styles = Button::new(tl!("Styles")).icon(IconId::new("wordArt")).tooltip(tl!("Decorative Text Styles")).arrangement(Arrangement::Stacked);
menu_button(ui, styles, tl!("Decorative Text Styles"), None, |ui, cx| super::galleries::wordart(ui, cx, app, "wordArt.style"));
let outline = crate::wordart_menus::current_outline(app);
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
menu_button(ui, Button::new(tl!("Text Fill")).icon(crate::icons::spec("textFill")), tl!("Text Fill"), None, |ui, cx| {
menu_button(ui, Button::new(tl!("Text Fill")).icon(IconId::new("textFill")), tl!("Text Fill"), None, |ui, cx| {
crate::wordart_menus::fill_menu(ui, cx, app, &theme)
});
menu_button(ui, Button::new(tl!("Text Outline")).icon(crate::icons::spec("textOutline")), tl!("Text Outline"), None, |ui, _| {
menu_button(ui, Button::new(tl!("Text Outline")).icon(IconId::new("textOutline")), tl!("Text Outline"), None, |ui, _| {
crate::wordart_menus::outline_menu(ui, app, outline)
});
menu_button(ui, Button::new(tl!("Text Effects")).icon(crate::icons::spec("transform")), tl!("Text Effects"), None, |ui, _| {
menu_button(ui, Button::new(tl!("Text Effects")).icon(IconId::new("transform")), tl!("Text Effects"), None, |ui, _| {
crate::wordart_menus::effects_menu(ui, app, true)
});
});
@@ -163,7 +162,7 @@ fn shape_text_group(row: &mut RibbonRow<'_>, app: &mut WordApp) {
let body = target.and_then(|(_, id)| app.session.doc.parts.get(&id).map(|p| p.body)).unwrap_or_default();
row.group(RibbonGroup::new("shape.text", tl!("Text"), IconId::new("wordcraft.more").into()), |ui| {
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
menu_button(ui, Button::new(tl!("Text Direction")).icon(crate::icons::spec("textDirection")), tl!("Text Direction"), None, |ui, _| {
menu_button(ui, Button::new(tl!("Text Direction")).icon(IconId::new("textDirection")), tl!("Text Direction"), None, |ui, _| {
for (label, vert) in [
("Horizontal", TextVert::Horz),
("Rotate all text 90°", TextVert::Vert),
+8 -17
View File
@@ -1,15 +1,12 @@
use craft::behavior::{ColumnWidth, IconId};
use craft::keymap::CommandRef;
use craft::menu::ribbon::{RibbonGroup, RibbonRow};
use craft::theme::ControlSize;
use craft::ui::buttons::{Arrangement, Button, IconButton, ToggleButton};
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _};
use craft::ui::display::Text;
use craft::ui::layout::{GridFit, empty_cell};
use craft::ui::layout_components::{Grid, Row, Stack};
use craft::ui::menu::MenuItem;
use craft::ui::style::TypeRole;
use craft::ui::text::NumberField;
use super::common::menu_button;
@@ -71,7 +68,7 @@ pub(super) fn table_design(row: &mut RibbonRow<'_>, app: &mut WordApp) {
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
let _ = menu_button(
ui,
Button::new(tl!("Styles").to_string()).icon(crate::icons::spec("styles")),
Button::new(tl!("Styles").to_string()).icon(IconId::new("styles")),
tl!("Styles").to_string(),
Some("table.style"),
|ui, _| {
@@ -145,20 +142,14 @@ fn cell_size_boxes(ui: &mut Ui, app: &mut WordApp) {
let w0 = laid.map(|x| x.w).or(stored_w).unwrap_or(0.0);
let exact = row.height_rule == wordcraft_doc::props::HeightRule::Exact;
let (height_units, width_units) = (crate::options::lengths(app.session.units()), crate::options::lengths(app.session.units()));
// As the old ribbon and Layout › Paragraph: a visible label beside each field, two decimals ("0.20").
let caption = |label: &'static str| Text::new(tl!(label)).role(TypeRole::Caption);
Grid::new(&[ColumnWidth::Content; 2]).gap(Gap::Tight).show(ui, |ui, _| {
caption("Height:").show(ui);
let field = NumberField::length(tl!("Height:").to_string(), Bind::given(Some(f64::from(h0))), height_units).range(CELL_SIZE_RANGE);
let out = field.fixed_decimals(2).size(ControlSize::Sm).show(ui);
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
let out = NumberField::length(tl!("Height:").to_string(), Bind::given(Some(f64::from(h0))), height_units).range(CELL_SIZE_RANGE).show(ui);
apply_edits(app, out.edit.events, |app, v| {
if let Some(h) = v {
let _ = app.run("table.rowHeight", json!({"height": h, "rule": if exact { "exact" } else { "atLeast" }}));
}
});
caption("Width:").show(ui);
let field = NumberField::length(tl!("Width:").to_string(), Bind::given(Some(f64::from(w0))), width_units).range(CELL_SIZE_RANGE);
let out = field.fixed_decimals(2).size(ControlSize::Sm).show(ui);
let out = NumberField::length(tl!("Width:").to_string(), Bind::given(Some(f64::from(w0))), width_units).range(CELL_SIZE_RANGE).show(ui);
apply_edits(app, out.edit.events, |app, v| {
if let Some(w) = v {
let _ = app.run("table.columnWidth", json!({"width": w}));
@@ -279,7 +270,7 @@ pub(super) fn table_layout(row: &mut RibbonRow<'_>, app: &mut WordApp) {
});
Button::command(CommandRef::new("table.textDirection"))
.label(tl!("Text\nDirection").to_string())
.icon(crate::icons::spec("textDirection"))
.icon(IconId::new("textDirection"))
.arrangement(Arrangement::Stacked)
.show(ui);
Button::command(CommandRef::new("table.cellMargins"))
@@ -288,10 +279,10 @@ pub(super) fn table_layout(row: &mut RibbonRow<'_>, app: &mut WordApp) {
.arrangement(Arrangement::Stacked)
.show(ui);
});
row.group(RibbonGroup::new("data", tl!("Data").to_string(), crate::icons::spec("sort")), |ui| {
row.group(RibbonGroup::new("data", tl!("Data").to_string(), IconId::new("sort").into()), |ui| {
Button::command(CommandRef::new("table.sort"))
.label(tl!("Sort").to_string())
.icon(crate::icons::spec("sort"))
.icon(IconId::new("sort"))
.arrangement(Arrangement::Stacked)
.show(ui);
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
@@ -300,7 +291,7 @@ pub(super) fn table_layout(row: &mut RibbonRow<'_>, app: &mut WordApp) {
.icon(IconId::new("repeatHeader"))
.show(ui);
Button::command(CommandRef::new("table.toText")).label(tl!("Convert to Text").to_string()).icon(IconId::new("toText")).show(ui);
Button::command(CommandRef::new("table.formula")).label(tl!("Formula").to_string()).icon(crate::icons::spec("formula")).show(ui);
Button::command(CommandRef::new("table.formula")).label(tl!("Formula").to_string()).icon(IconId::new("formula")).show(ui);
});
});
}
-86
View File
@@ -161,89 +161,3 @@ pub fn resolve_tab<'a>(current: &'a str, available: &[&str]) -> &'a str {
pub fn in_table_public(app: &WordApp) -> bool {
app.session.sel.focus.path.cell().is_some()
}
#[cfg(test)]
mod tests {
use crate::WordApp;
fn collect_rects(shape: &egui::Shape, out: &mut Vec<egui::epaint::RectShape>) {
match shape {
egui::Shape::Rect(r) => out.push(r.clone()),
egui::Shape::Vec(v) => {
for s in v {
collect_rects(s, out);
}
}
_ => {}
}
}
fn underline_x(output: egui::FullOutput, tab_bottom: f32) -> f32 {
let mut rects = Vec::new();
for cs in &output.shapes {
collect_rects(&cs.shape, &mut rects);
}
output.drop_without_applying_deltas();
rects
.into_iter()
.filter(|r| {
r.fill != egui::Color32::TRANSPARENT
&& (r.rect.height() - 3.0).abs() < 0.6
&& r.rect.width() >= 15.0
&& r.rect.width() <= 150.0
&& r.rect.bottom() <= tab_bottom + 6.0
})
.map(|r| r.rect.center().x)
.next()
.expect("ribbon 3pt tab underline rect")
}
fn run_pass(ctx: &egui::Context, app: &mut WordApp, now: f64) -> egui::FullOutput {
craft::ui::shell::embed::before_input(ctx, |out| app.frame_input(out));
let input = egui::RawInput {
time: Some(now),
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 400.0))),
..Default::default()
};
ctx.run_ui(input, |ui| {
crate::test_harness::logic(ui.ctx(), app);
app.ui(ui);
})
}
/// Switching tabs slides the real ribbon's 3pt underline between tabs and reverses mid-motion.
#[test]
fn tab_underline_slides_and_can_reverse_mid_motion() {
let ctx = crate::test_harness::context();
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
app.ui.animations = crate::theme::Animations::On;
let mut now = 1.0;
for _ in 0..5 {
now += 1.0 / 60.0;
run_pass(&ctx, &mut app, now).drop_without_applying_deltas();
}
now += 1.0 / 60.0;
let x0 = underline_x(run_pass(&ctx, &mut app, now), 80.0);
app.ui.tab = "Layout".into();
run_pass(&ctx, &mut app, now).drop_without_applying_deltas();
now += 0.05;
let x_mid = underline_x(run_pass(&ctx, &mut app, now), 80.0);
assert!(x_mid > x0 + 5.0, "underline starts sliding right toward Layout: x0={x0}, x_mid={x_mid}");
now += 0.05;
let x_mid2 = underline_x(run_pass(&ctx, &mut app, now), 80.0);
assert!(x_mid2 > x_mid, "underline continues sliding right: x_mid={x_mid}, x_mid2={x_mid2}");
app.ui.tab = "Home".into();
run_pass(&ctx, &mut app, now).drop_without_applying_deltas();
now += 0.05;
let x_rev = underline_x(run_pass(&ctx, &mut app, now), 80.0);
assert!(x_rev < x_mid2, "reversing mid-motion moves underline back toward Home: x_rev={x_rev}, x_mid2={x_mid2}");
now += 1.0;
let x_end = underline_x(run_pass(&ctx, &mut app, now), 80.0);
assert!((x_end - x0).abs() < 2.0, "underline settles back under Home: x0={x0}, x_end={x_end}");
}
}
-91
View File
@@ -703,70 +703,6 @@ fn shading_options() -> String {
crate::i18n::fmt(tl!("{name} options"), &[("name", tl!("Shading"))])
}
#[test]
fn table_shading_label_is_painted_beside_its_arrow() {
use egui::accesskit::Role;
// Vietnamese and German labels need the embedded catalogs (CI has them); English always runs in both themes.
let cases: &[(&str, egui::Theme)] = if crate::i18n::catalogs_embedded() {
&[("en", egui::Theme::Light), ("en", egui::Theme::Dark), ("vi", egui::Theme::Light), ("de", egui::Theme::Light)]
} else {
&[("en", egui::Theme::Light), ("en", egui::Theme::Dark)]
};
let ctx = crate::test_harness::context();
ctx.enable_accesskit();
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 100.0));
for (idx, &(language, theme)) in cases.iter().enumerate() {
app.run("ui.language", json!({"value": language})).unwrap();
app.run("ui.theme", json!({"value": if theme == egui::Theme::Dark { "dark" } else { "light" }})).unwrap();
ctx.set_theme(theme);
let raw = egui::RawInput { focused: true, time: Some(idx as f64 * 0.1), screen_rect: Some(screen), ..Default::default() };
craft::ui::shell::embed::before_input(&ctx, |out| app.frame_input(out));
let mut out = ctx.run_ui(raw, |ui| {
let _ = crate::colors::shading_split(
ui,
&mut app,
tl!("Shading").to_string(),
crate::colors::Target::cmd("table.shading").remember(crate::colors::Remember::Shading),
);
});
out.textures_delta.clear();
assert_eq!(ctx.global_style().visuals.dark_mode, theme == egui::Theme::Dark, "{language}/{theme:?}: palette active");
let label = tl!("Shading");
let arrow_label = shading_options();
let nodes = &out.platform_output.accesskit_update.as_ref().expect("accesskit update").nodes;
let button_rect = |name: &str| {
nodes
.iter()
.find_map(|(_, n)| {
(n.role() == Role::Button && n.label() == Some(name))
.then(|| {
n.bounds().map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)))
})
.flatten()
})
.unwrap_or_else(|| panic!("{language}: missing button {name:?}"))
};
let main = button_rect(label);
let arrow = button_rect(&arrow_label);
assert!((main.top() - arrow.top()).abs() < 0.01 && (main.bottom() - arrow.bottom()).abs() < 0.01);
assert!((main.right() - arrow.right()).abs() < 0.01 && arrow.left() > main.left(), "{language}: {main:?}, {arrow:?}");
let text = out
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::Shape::Text(t) if t.galley.text() == label => Some(t),
_ => None,
})
.expect("Shading is drawn as text, not just a hover tip");
let text_rect = egui::Rect::from_min_size(text.pos, text.galley.size());
assert!(main.contains_rect(text_rect), "{language}: {text_rect:?} outside {main:?}");
assert!(text_rect.left() >= main.left() + 24.0, "the label starts after the icon");
assert!(text_rect.right() <= arrow.left(), "{language}: label {text_rect:?} overlaps arrow {arrow:?}");
}
crate::i18n::apply_language(crate::i18n::Lang::EN);
}
fn first_cell_shading(app: &WordApp) -> Option<wordcraft_doc::Rgb> {
app.session.doc.body.iter().find_map(|b| b.as_table()).unwrap().rows[0].cells[0].props.shading
}
@@ -1295,30 +1231,3 @@ fn the_styles_gallery_reads_from_the_right_in_a_right_to_left_interface() {
);
}
}
#[test]
fn a_combo_field_reached_with_tab_shows_its_hint_after_a_delay() {
use egui::accesskit::Role;
let app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample")), crate::Services::default());
let mut h = tab_harness(app, "Home");
// Focus the Font box right before Font Size, then Tab onto Font Size.
h.get(By::new().role(Role::ComboBox).label("Font")).focus();
h.step();
for _ in 0..4 {
h.key_press(egui::Key::Tab);
h.step();
if h.query(By::new().role(Role::ComboBox).label("Font Size")).is_some_and(|n| n.is_focused()) {
break;
}
}
assert!(h.get(By::new().role(Role::ComboBox).label("Font Size")).is_focused(), "Tab should focus Font Size");
assert_eq!(h.query_all_by_label("Font Size").count(), 1, "hint must not show immediately before delay");
let frames = ((craft::ui::contract::tooltip::DELAY * 60.0).ceil() as usize) + 5;
for _ in 0..frames {
h.step();
}
assert!(h.query_all_by_label("Font Size").count() >= 2, "hint must show after tooltip delay");
}
+3 -3
View File
@@ -86,7 +86,7 @@ pub(super) fn view(row: &mut RibbonRow<'_>, app: &mut WordApp) {
.show(ui);
Button::command(CommandRef::new("view.zoom100"))
.label(tl!("100%").to_string())
.icon(crate::icons::spec("zoom100"))
.icon(IconId::new("zoom100"))
.arrangement(Arrangement::Stacked)
.show(ui);
// Step the zoom up and down by 10% (issue #67), from whatever the page shows now.
@@ -191,10 +191,10 @@ pub(super) fn view(row: &mut RibbonRow<'_>, app: &mut WordApp) {
.arrangement(Arrangement::Stacked)
.show(ui);
});
row.group(RibbonGroup::new("view.templates", tl!("Templates").to_string(), crate::icons::spec("documentTemplate")), |ui| {
row.group(RibbonGroup::new("view.templates", tl!("Templates").to_string(), IconId::new("documentTemplate").into()), |ui| {
Button::command(CommandRef::new("tools.templates"))
.label(tl!("Templates").to_string())
.icon(crate::icons::spec("documentTemplate"))
.icon(IconId::new("documentTemplate"))
.arrangement(Arrangement::Stacked)
.show(ui);
});
+7 -4
View File
@@ -24,7 +24,7 @@ const MAX_PIXELS: usize = 50_000_000;
/// The commands that paste the clipboard.
pub(crate) fn is_paste(id: &str) -> bool {
matches!(id, "edit.paste" | "edit.pasteText" | "edit.pasteMerge" | "edit.pasteNestedTable" | "edit.pasteSpecial")
matches!(id, "edit.paste" | "edit.pasteText" | "edit.pasteMerge" | "edit.pasteSpecial")
}
/// Most format names an error lists.
@@ -471,8 +471,9 @@ mod tests {
a.run("caret.docEnd", json!({})).unwrap();
assert!(a.session.sel.is_collapsed());
// Copy is greyed with nothing selected (#7675), so the command is refused before it reaches the clipboard.
assert!(a.run("edit.copy", json!({})).is_err(), "Copy with nothing selected is refused");
let ctx = a.ctx.clone().unwrap();
let empty_r = a.run("edit.copy", json!({})).unwrap();
put_result(&mut a, &ctx, &empty_r);
assert!(a.clipboard_published, "empty copy must not change published-copy state");
let clip = handle(&a).unwrap();
@@ -481,7 +482,9 @@ mod tests {
let mut a2 = app_holding(&[]);
assert!(!a2.clipboard_published);
assert!(a2.run("edit.copy", json!({})).is_err(), "Copy with nothing selected is refused");
let ctx2 = a2.ctx.clone().unwrap();
let empty_r2 = a2.run("edit.copy", json!({})).unwrap();
put_result(&mut a2, &ctx2, &empty_r2);
assert!(!a2.clipboard_published, "empty copy must not change published-copy state when false");
}
}
-211
View File
@@ -27,27 +27,6 @@ fn mod_key(key: egui::Key) -> egui::Event {
egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }
}
/// #5793: a name from a paragraph's first words, as Word suggests one: up to the first sentence or
/// clause end, without what a file name can't hold, at most 50 characters at a word's end.
#[test]
fn a_suggested_name_is_the_first_words_of_the_text() {
use crate::app::suggested_stem as stem;
assert_eq!(stem("Quarterly report for the board. More follows here.").as_deref(), Some("Quarterly report for the board"));
assert_eq!(stem("Minutes of the meeting, 6 November").as_deref(), Some("Minutes of the meeting, 6 November"));
assert_eq!(stem("What happened? Nobody knows").as_deref(), Some("What happened"));
assert_eq!(stem("Plan: phase one").as_deref(), Some("Plan"));
assert_eq!(stem("Q3 / Q4 \"draft\" <final> *v2* | a\\b").as_deref(), Some("Q3 Q4 draft final v2 a b"));
assert_eq!(stem(" Leading and inner spaces ").as_deref(), Some("Leading and inner spaces"));
assert_eq!(stem("日本語の文書\u{3002}続きの文").as_deref(), Some("日本語の文書"));
let long = "Annual report of the regional committee on transport and infrastructure planning";
let got = stem(long).unwrap();
assert!(got.chars().count() <= 50 && long.starts_with(&got) && long[got.len()..].starts_with(' '), "{got:?}");
assert_eq!(stem(&"x".repeat(80)).map(|s| s.chars().count()), Some(50), "one long word is cut at 50");
for nothing in ["", " ", "...", "?", "/ * |", "\u{1}"] {
assert_eq!(stem(nothing), None, "{nothing:?}");
}
}
/// #5793: Save As suggests the first words for a document that was never saved and has no title
/// of its own (the first paragraph with text, past empty ones); a title, a file name or a path
/// still name it.
@@ -374,23 +353,6 @@ fn default_chords_fire_their_commands() {
}
}
/// Issue #772: the Find and Replace dialog left focus on the document, so typing didn't go into
/// Find what. (Ctrl/⌘+F now searches in the Navigation pane, as in Word (#712), so this opens
/// the dialog with Ctrl/⌘+H.)
#[test]
fn find_shortcut_focuses_find_what() {
let mut h = blank_rig();
press(&mut h, egui::Key::H, egui::Modifiers::COMMAND);
assert!(h.state().dialog_host.open_dialogs().iter().any(|d| d.key.as_deref() == Some("find")), "Find and Replace is open");
h.event(egui::Event::Text("abc".into()));
h.step();
h.step();
assert!(body_text(h.state()).is_empty(), "nothing was typed into the document");
let (key, fields) = open_dialog(h.state()).expect("Find dialog open");
assert_eq!(key, "find");
assert!(fields["find"].as_str().unwrap_or_default().ends_with("abc"), "typing went into Find what: {fields:?}");
}
/// The key of the dialog a command opened, read off its reply.
fn pending_of(reply: &Value) -> Option<&str> {
reply.get("pending").and_then(Value::as_str)
@@ -2007,130 +1969,6 @@ fn the_ribbon_boxes_name_themselves_for_a_screen_reader() {
}
}
/// All title-bar inputs have accessible names. Clicking the title opens Rename Document, and
/// clicking Account opens Backstage options.
#[test]
fn title_and_account_buttons_work() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
let mut h = harness(app());
h.run_steps(2);
for (role, label) in [
(Role::Switch, "AutoSave"),
(Role::Button, "Save"),
(Role::Button, "Undo"),
(Role::Button, "Redo"),
(Role::Button, "Undo History"),
(Role::Button, "Customize Quick Access Toolbar"),
(Role::Button, "Document1 \u{2014} Not saved"),
(Role::Button, "Discord"),
(Role::Button, "WordCraft User"),
] {
assert!(h.query_by_role_and_label(role, label).is_some(), "title bar missing {role:?} {label:?}");
}
assert!(h.query_by_label("Search commands and help").is_some(), "title bar missing Search commands and help");
h.get_by_role_and_label(Role::Button, "Document1 \u{2014} Not saved").click();
h.step();
let id = craft::ui::dialog::dialog_id("renameDocument");
assert!(h.state().dialog_host.open_dialogs().iter().any(|d| d.id == id), "renameDocument dialog is open");
h.get_by_role_and_label(Role::Button, "Rename").click();
h.run_steps(2);
assert!(h.state().dialog_host.open_dialogs().is_empty());
assert!(h.state().session.file_name.is_none());
assert!(!h.state().session.dirty);
h.get_by_role_and_label(Role::Button, "Document1 \u{2014} Not saved").click();
h.step();
assert!(h.state().dialog_host.open_dialogs().iter().any(|d| d.id == id), "renameDocument dialog is open");
h.event(egui::Event::Key {
key: egui::Key::A,
physical_key: None,
pressed: true,
repeat: false,
modifiers: egui::Modifiers { command: true, ..Default::default() },
});
h.event(egui::Event::Text("Project notes".into()));
h.step();
h.get_by_role_and_label(Role::Button, "Rename").click();
h.run_steps(2);
assert!(h.state().dialog_host.open_dialogs().is_empty());
assert_eq!(h.state().title_stem(), "Project notes");
assert_eq!(h.state().default_save_name(), "Project notes.docx");
assert!(h.state().session.doc.core.title.is_empty());
assert!(!h.state().session.dirty);
// A long name remains clickable, and Escape leaves it unchanged.
let long_name = "Notes ".repeat(25);
h.state_mut().run("file.rename", json!({"name": long_name})).unwrap();
h.step();
h.get_by_role_and_label(Role::Button, &format!("{} \u{2014} Not saved", long_name.trim())).click();
h.step();
assert!(h.state().dialog_host.open_dialogs().iter().any(|d| d.key.as_deref() == Some("renameDocument")));
h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });
h.run_steps(2);
assert!(h.state().dialog_host.open_dialogs().is_empty());
assert_eq!(h.state().title_stem(), long_name.trim());
h.get_by_role_and_label(Role::Button, "WordCraft User").click();
h.run_steps(2);
assert!(h.state().ui.backstage);
assert_eq!(h.state().ui.backstage_page, "options");
assert_eq!(h.state().ui.options_pane, "general");
assert!(h.query_by_label("User name:").is_some());
}
/// A pointer drag on a pane's resize edge leaves no keyboard focus behind, so Ctrl and
/// F-key shortcuts run right after it, docked or floating (#1756).
#[test]
fn shortcuts_run_after_a_pane_resize() {
use egui::accesskit::Role;
use egui_kittest::kittest::{By, Queryable};
type H = egui_kittest::Harness<'static, WordApp>;
fn key(h: &mut H, key: egui::Key, modifiers: egui::Modifiers) {
h.key_press_modifiers(modifiers, key);
h.step();
}
fn drag(h: &mut H, from: egui::Pos2, by: egui::Vec2) {
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
h.event(egui::Event::PointerMoved(from));
h.event(button(from, true));
h.step();
h.event(egui::Event::PointerMoved(from + by));
h.step();
h.event(button(from + by, false));
h.step();
}
let find_open = |h: &H| h.state().dialog_host.open_dialogs().iter().any(|d| d.key.as_deref() == Some("find"));
let styles_pane =
|h: &H| h.query_all(By::new().role(Role::Group).label("Styles")).map(|n| n.rect()).find(|r| r.height() > 300.0).expect("Styles pane frame");
let mut a = app();
a.run("view.stylesPane", json!({"value": true})).unwrap();
let mut h = harness(a);
h.step();
let pane = styles_pane(&h);
// On the pane's inner edge: drag left by 40 px to widen it.
drag(&mut h, egui::pos2(pane.left() + 1.0, pane.center().y), egui::vec2(-40.0, 0.0));
let width = h.state().ui.styles_pane_width.unwrap_or_default();
assert!((width - 290.0).abs() <= 2.0, "the drag widened the docked pane: {width}");
key(&mut h, egui::Key::H, egui::Modifiers::COMMAND);
assert!(find_open(&h), "Ctrl+H runs after the docked drag");
key(&mut h, egui::Key::Escape, egui::Modifiers::NONE);
assert!(h.state().dialog_host.open_dialogs().is_empty(), "Escape closes Replace");
h.state_mut().run("view.stylesPaneDock", json!({"dock": "float"})).unwrap();
h.step();
let float_pane = styles_pane(&h);
let before = h.state().ui.styles_pane_float;
// Drag the bottom-right corner.
drag(&mut h, float_pane.max - egui::vec2(2.0, 2.0), egui::vec2(30.0, 30.0));
assert_ne!(h.state().ui.styles_pane_float, before, "the drag resized the floating pane");
key(&mut h, egui::Key::H, egui::Modifiers::COMMAND);
assert!(find_open(&h), "Ctrl+H runs after the floating pane's resize");
}
/// #3172: the Paste button is named "Paste": its tooltip adds the key as the platform writes it,
/// so its name no longer carries macOS's "⌘V", which screen readers read on Windows as "Paste (⌘V)".
#[test]
@@ -3340,32 +3178,6 @@ fn task_panes_share_an_edge_close_and_keep_the_styles_place() {
assert!(junk.session.view.nav_pane, "the rest of the file still loads");
}
/// #2526: the Navigation pane stays as the person left it at the next launch, and a
/// `ui.json` from before the setting leaves it closed.
#[test]
fn navigation_pane_visibility_survives_restart() {
let mut first = app();
assert!(!first.session.view.nav_pane);
first.session.view.nav_pane = true;
let saved = serde_json::to_vec(&first.prefs()).unwrap();
let mut second = app();
second.apply_prefs(serde_json::from_slice(&saved).unwrap());
assert!(second.session.view.nav_pane, "the pane is open again");
let mut closed = app();
closed.session.view.nav_pane = true;
closed.session.view.nav_pane = false;
let saved = serde_json::to_vec(&closed.prefs()).unwrap();
let mut third = app();
third.apply_prefs(serde_json::from_slice(&saved).unwrap());
assert!(!third.session.view.nav_pane, "a closed pane stays closed");
let mut old = app();
old.apply_prefs(serde_json::from_str(r#"{"navTab": "headings"}"#).unwrap());
assert!(!old.session.view.nav_pane, "no saved value: closed");
}
/// The same across windows: Check spelling as you type turned off in a second window on a document
/// stays off when the first window's own view of it comes back, in a window on another document,
/// back in the second window, and in the saved settings (#5740).
@@ -4131,29 +3943,6 @@ fn shift_f10_opens_the_context_menu_at_the_caret() {
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), "Kilns fire");
}
/// #7673: with nothing selected the text menu greys Cut and Copy, as production did; a selection enables them.
#[test]
fn the_context_menu_greys_cut_and_copy_without_a_selection() {
use egui_kittest::kittest::{NodeT, Queryable};
let row = |h: &Rig, name: &str| {
let node = h.query_all_by_label(name).find(|node| node.accesskit_node().role() == egui::accesskit::Role::MenuItem);
node.expect("the menu row").accesskit_node().is_disabled()
};
let mut h = harness(app());
h.run_steps(4);
h.event(egui::Event::Text("Kilns fire".into()));
h.run_steps(2);
h.state_mut().run("ui.contextMenu", json!({})).unwrap();
h.run_steps(4);
assert!(row(&h, "Cut") && row(&h, "Copy"), "nothing is selected");
h.key_press(egui::Key::Escape);
h.run_steps(2);
h.state_mut().run("select.all", json!({})).unwrap();
h.state_mut().run("ui.contextMenu", json!({})).unwrap();
h.run_steps(4);
assert!(!row(&h, "Cut") && !row(&h, "Copy"), "the text is selected");
}
/// A file dropped in the first two font-warm-up passes is taken before the early return;
/// eframe does not preserve dropped files for a later frame.
#[cfg(not(target_arch = "wasm32"))]
-29
View File
@@ -847,35 +847,6 @@ fn alt_q_opens_search_and_typing_goes_there() {
assert_eq!(h.state().session.find.results.len(), 1);
}
/// #5398 (review): Tab / Down arrow moves from the Search box to its results, and Enter / Tab runs the command.
#[test]
fn tab_moves_to_a_search_result_and_enter_runs_it() {
let mut h = harness(app());
h.run_steps(6);
let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let _ = h.state_mut().run("ui.dialog", json!({"name": "commands"}));
h.step();
h.step();
assert!(crate::chrome::search::is_open(h.state()), "Search is open");
h.event(egui::Event::Text("word count".into()));
h.step();
h.step();
assert_eq!(search_text(&h).as_deref(), Some("word count"));
let edit = h.ctx.memory(|m| m.focused());
assert!(edit.is_some(), "the box has the keys");
// In the craft-libs CommandPalette architecture, a text opener driving a popup list accepts/activates
// the lead match on Tab or Enter:
h.event(key(egui::Key::Tab));
h.run_steps(4);
assert!(!crate::chrome::search::is_open(h.state()), "Tab activates the match and closes Search");
assert!(
h.state().dialog_host.open_dialogs().iter().any(|d| d.key.as_deref() == Some("wordCount")),
"its dialog is open, not closed by the activation key"
);
}
/// #5398 (review): Focus hides the Search box, so Search there is the dialog, even on the frame
/// Focus comes on; and Search left open when Focus comes on doesn't keep Escape from leaving it.
#[test]

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