Compare commits

...
Author SHA1 Message Date
dependabot[bot] c6cd5617af chore(deps): bump the cargo-dependencies group across 1 directory with 9 updates
Bumps the cargo-dependencies group with 9 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [log](https://github.com/rust-lang/log) | `0.4.34` | `0.4.35` |
| [unicode-script](https://github.com/unicode-rs/unicode-script) | `0.5.8` | `0.5.9` |
| [regex](https://github.com/rust-lang/regex) | `1.13.1` | `1.13.2` |
| [regex-automata](https://github.com/rust-lang/regex) | `0.4.18` | `0.4.19` |
| [wuff](https://github.com/nicoburns/wuff) | `0.2.9` | `0.2.10` |
| [encoding_rs](https://github.com/hsivonen/encoding_rs) | `0.8.42` | `0.8.44` |
| [aes](https://github.com/RustCrypto/block-ciphers) | `0.9.3` | `0.9.4` |
| [zeroize](https://github.com/RustCrypto/utils) | `1.9.1` | `1.9.2` |
| [toml_edit](https://github.com/toml-rs/toml) | `0.25.15+spec-1.1.0` | `0.25.21+spec-1.1.0` |



Updates `log` from 0.4.34 to 0.4.35
- [Release notes](https://github.com/rust-lang/log/releases)
- [Changelog](https://github.com/rust-lang/log/blob/main/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/log/compare/0.4.34...v0.4.35)

Updates `unicode-script` from 0.5.8 to 0.5.9
- [Commits](https://github.com/unicode-rs/unicode-script/compare/v0.5.8...v0.5.9)

Updates `regex` from 1.13.1 to 1.13.2
- [Release notes](https://github.com/rust-lang/regex/releases)
- [Changelog](https://github.com/rust-lang/regex/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/regex/compare/1.13.1...1.13.2)

Updates `regex-automata` from 0.4.18 to 0.4.19
- [Release notes](https://github.com/rust-lang/regex/releases)
- [Changelog](https://github.com/rust-lang/regex/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/regex/commits)

Updates `wuff` from 0.2.9 to 0.2.10
- [Changelog](https://github.com/nicoburns/wuff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/nicoburns/wuff/compare/v0.2.9...v0.2.10)

Updates `encoding_rs` from 0.8.42 to 0.8.44
- [Commits](https://github.com/hsivonen/encoding_rs/compare/v0.8.42...v0.8.44)

Updates `aes` from 0.9.3 to 0.9.4
- [Commits](https://github.com/RustCrypto/block-ciphers/compare/aes-v0.9.3...aes-v0.9.4)

Updates `zeroize` from 1.9.1 to 1.9.2
- [Commits](https://github.com/RustCrypto/utils/compare/zeroize-v1.9.1...zeroize-v1.9.2)

Updates `toml_edit` from 0.25.15+spec-1.1.0 to 0.25.21+spec-1.1.0
- [Commits](https://github.com/toml-rs/toml/compare/v0.25.15...v0.25.21)

---
updated-dependencies:
- dependency-name: aes
  dependency-version: 0.9.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: encoding_rs
  dependency-version: 0.8.44
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: log
  dependency-version: 0.4.35
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: regex
  dependency-version: 1.13.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: regex-automata
  dependency-version: 0.4.19
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: toml_edit
  dependency-version: 0.25.21+spec-1.1.0
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: unicode-script
  dependency-version: 0.5.9
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: wuff
  dependency-version: 0.2.10
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: zeroize
  dependency-version: 1.9.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-12-02 11:10:55 +00:00
autocraft-bot[bot] 3035dda6d4 Merge pull request #6936 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] 8d9eb6fc0f Merge pull request #6832 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] 6b0c47d2a8 Merge pull request #6523 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] 93abd12f9f Merge pull request #6213 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] 1a8e4ac2d3 Merge pull request #6468 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] f722a2f80b Merge pull request #5505 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] afba11d6e0 Merge pull request #6529 2026-12-02 07:39:07 +00:00
FredApps 836799463a Merge pull request #4169 from marcoarnulfo/fix/arrows-enter-equation
Equations: Left and Right step into an equation next to the caret, as in Word
2026-12-02 08:39:07 +01:00
FredApps e70879e085 Merge pull request #4055 from matstrange/fix/mailings-csv-limits
Mail merge: a recipient list over what it keeps is refused while it is read
2026-12-02 08:38:16 +01:00
FredApps f416b3f1a5 Merge branch 'main' into fix/arrows-enter-equation 2026-12-02 08:15:09 +01:00
FredApps 9af6bdea33 Merge branch 'main' into fix/mailings-csv-limits 2026-12-02 08:15:02 +01:00
FredApps 4cf4eacc91 Merge pull request #3181 from SlavenDj/fix/3126-empty-window
Offer Blank document, Browse… and Home in the empty window (#3126)
2026-12-02 08:14:20 +01:00
FredApps 733a410095 Merge pull request #2011 from justinjohn0306/codex/fix-1913-line-spacing
Design: apply paragraph spacing presets to built-in styles (#1913)
2026-12-02 08:13:42 +01:00
FredApps 20fc916072 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	ROADMAP.md
#	docs/typing-parity.md
2026-12-02 13:24:55 +07:00
FredApps 64ec14c3df Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	ROADMAP.md
2026-12-02 13:24:47 +07:00
FredApps 5c9f816ad2 Merge branch 'main' into fix/3126-empty-window 2026-12-02 07:21:59 +01:00
FredApps eff3740ec5 Merge branch 'main' into codex/fix-1913-line-spacing 2026-12-02 07:21:52 +01:00
FredApps c5375d8186 Merge pull request #2899 from maxm11/feat/docx-corpus-harness
M15 #1: opt-in DOCX corpus harness
2026-12-02 07:21:02 +01:00
FredApps 11871dc9a5 Merge pull request #4188 from RatkoR/fix/4126-enter-on-picture
A selected picture survives Enter and breaks (#4126)
2026-12-02 07:20:25 +01:00
FredApps 8e5200fc47 Merge pull request #2186 from D13GOOOO/rtl-numbers-latin
Right-to-left text: Latin text keeps its digits, spaces and punctuation in order (#2150)
2026-12-02 07:19:42 +01:00
FredApps 7a49244c7a Empty window test: check the page gets the keyboard after Blank document
As CodeRabbit noted, text.insert does not depend on focus, so the test
passed without focus_page_after_pass. Assert the canvas is focused and
type through the harness instead.
2026-12-02 12:40:44 +07:00
FredApps c0b8362187 Empty window: keep Home a quiet link-style button after the craft::ui port
The port to craft::ui made Home a regular button, though its comment
(and the original change) has it reading as a link beside Blank
document and Browse…. Use the ghost variant, as other quiet buttons do.
2026-12-02 12:40:01 +07:00
FredApps a65a49f9a2 docs: fix the #1913 history rows from the main merge
The progress-log row had a third cell in a two-column table, the
ui-parity rows sat above the table's separator, and two rows described
template UI that this PR does not add. Rows now sit in date order.
2026-12-02 12:38:52 +07:00
FredApps 05bfd76bcf Merge branch 'main' into fix/arrows-enter-equation 2026-12-02 06:25:42 +01:00
FredApps ff5aff859b Merge branch 'main' into fix/mailings-csv-limits 2026-12-02 06:25:35 +01:00
FredApps f6461d4f18 Merge branch 'main' into feat/docx-corpus-harness 2026-12-02 06:25:29 +01:00
FredApps 81d3713818 Merge branch 'main' into fix/4126-enter-on-picture 2026-12-02 06:25:22 +01:00
FredApps d41b7e38f4 Merge branch 'main' into rtl-numbers-latin 2026-12-02 06:25:16 +01:00
FredApps 6c53e35c16 Merge pull request #3972 from Silvertree2010/fix/3678-audit-minor-json-open-doesn-t-re
Reconcile inline objects with U+FFFC markers on .json open
2026-12-02 06:24:20 +01:00
FredApps b324cbab29 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	crates/doc/src/tests.rs
2026-12-02 11:55:22 +07:00
FredApps b065d1a70e Merge branch 'main' into fix/3126-empty-window 2026-12-02 05:50:06 +01:00
FredApps bbf6ac60cb Merge branch 'main' into codex/fix-1913-line-spacing 2026-12-02 05:50:00 +01:00
FredApps d66724fba0 Merge branch 'main' into rtl-numbers-latin 2026-12-02 05:49:53 +01:00
FredApps 3cc3ef1d51 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	ROADMAP.md
#	docs/typing-parity.md
2026-12-02 11:47:40 +07:00
FredApps 878f3ef2ca Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	ROADMAP.md
2026-12-02 11:47:33 +07:00
FredApps cc2c37232a Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	ROADMAP.md
2026-12-02 11:47:27 +07:00
FredApps 7cd6dcdbc2 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	docs/typing-parity.md
2026-12-02 11:47:14 +07:00
FredApps 866b188e2a Merge pull request #4823 from OPUZZLES/fix/pdf-figure-object-lookups
PDF: reuse paragraph-prefix lookups for figure tags (#3614)
2026-12-02 05:26:11 +01:00
FredApps b472bdef73 Merge pull request #8179 from reubgr/fix/review-resolution-preserved-refs-8129
Review: Accept/Reject All keeps revision records still referenced by untouched stories (#8129)
2026-12-02 05:25:34 +01:00
FredApps e01bf4a57b Merge pull request #8175 from reubgr/fix/delta8-residue-7643
validate: OMML name list, JPEGTables splice + Tech Note #2 structure, TIFF depth pins (#7643)
2026-12-02 05:24:59 +01:00
FredApps 057a8b79b1 Merge pull request #3925 from Jayesh-Prajapati9/fix/3639-header-commands-own-section
#3639: Header and footer commands change the section of the header the caret is in
2026-12-02 05:24:22 +01:00
FredApps 3a93ffab6d Merge branch 'main' into fix/3126-empty-window
Resolved progress-doc conflicts: kept main's status headers and added this PR's revision-history rows.
2026-12-02 11:04:46 +07:00
FredApps f72124cfdd Merge branch 'main' into rtl-numbers-latin
Resolved progress-doc conflicts: kept main's status headers and added this PR's revision-history rows.
2026-12-02 11:04:42 +07:00
FredApps 3311690632 Merge branch 'main' into codex/fix-1913-line-spacing
Resolved docs/target-app-parity.md: kept main's table and re-applied this PR's #1913 note and its two revision-history rows.
2026-12-02 11:03:08 +07:00
FredApps 25f34eec75 Merge branch 'main' into fix/pdf-figure-object-lookups 2026-12-02 05:02:51 +01:00
FredApps b2a4699384 Merge branch 'main' into fix/review-resolution-preserved-refs-8129 2026-12-02 04:53:07 +01:00
FredApps d23ae8609b Merge branch 'main' into fix/delta8-residue-7643 2026-12-02 04:53:01 +01:00
FredApps 80f01dabb8 Merge branch 'main' into fix/3639-header-commands-own-section 2026-12-02 04:52:41 +01:00
autocraft-bot[bot] e9da627bfe Merge pull request #4405 2026-12-02 00:36:36 +00:00
autocraft-bot[bot] 6c93357f0e Merge pull request #3834 2026-12-02 00:36:36 +00:00
autocraft-bot[bot] 7b180bcf1e Merge pull request #4436 2026-12-02 00:36:36 +00:00
autocraft-bot[bot] 32d96170e1 Merge pull request #3228 2026-12-02 00:36:36 +00:00
autocraft-bot[bot] aa3e7b9d5f Merge pull request #3513 2026-12-02 00:36:36 +00:00
FredApps 359999c32e Merge pull request #8092 from reubgr/feat/doctype-measured-cells
validate: complete the measured grading of XML-DOCTYPE interim cells
2026-12-02 01:36:36 +01:00
FredApps 15fc342b11 Merge current main into WordCraft #8175 2026-12-02 01:26:40 +01:00
FredApps 93f8cefacf Merge branch 'main' into feat/doctype-measured-cells 2026-12-02 01:08:37 +01:00
Martin BallandClaude Opus 5.5 012afe2dcf Symbol: the Special Characters "Shortcut key:" header is not clipped (#7982) (#8226)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 23:50:30 +00:00
Martin BallandClaude Opus 5.5 6c7d31aa6f Customize Ribbon: the "Show" column header is not clipped (#7981) (#8212)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 23:50:23 +00:00
Martin BallandClaude Opus 5.5 830e629541 Equation tab: the Tools group keeps its labels (#7975) (#8198)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 23:50:17 +00:00
FredApps c6b037d6c0 Merge branch 'main' into feat/doctype-measured-cells 2026-12-02 00:39:46 +01:00
Martin BallandClaude Opus 5.5 8b5bfa78bf fix(options): show the Read Aloud speed with two decimals (#7987) (#8259)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:49:04 +00:00
Martin BallandClaude Opus 5.5 313e14885f fix(chrome): widen the command search drop-down (#7983) (#8258)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:48:56 +00:00
Martin BallandClaude Opus 5.5 9a8786a3ab fix(chrome): mute the AutoSave label while AutoSave is off (#7681) (#8257)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:48:47 +00:00
Martin BallandClaude Opus 5.5 4b5a96163c fix(dialogs): frame the Macros list (#8017) (#8256)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:48:39 +00:00
Martin BallandClaude Opus 5.5 5a68da541f fix(dialogs): frame the Bookmark list and put Cancel last (#7979) (#8255)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:48:31 +00:00
FredApps f7e2e88133 Merge branch 'main' into feat/doctype-measured-cells 2026-12-01 18:33:02 +01:00
reubgr 7dce30c8af validate: a stored nested zip as the final part no longer disputes the outer directory (#8128)
* fix(validate): ignore unreachable EOCDs inside verified entry payloads (#7035)

* test(validate): expect PASS for stored_nested_zip and guard payload reachability (#7035)

* fix(validate): restrict dispute clearance to final entry with verified local header (#7035)

* test(validate): regress non-final entry and inconsistent local header disputes (#7035)

* fix(validate): require central-last entry to be physically last for dispute clearance (#7035)

* test(validate): regress CD-last but physically non-last stored nested zip (#7035)

* fix(validate): start ZIP64 footer span at adjacent ZIP64 EOCD record (#7035)

* test(validate): regress straddling ZIP64 footer and embedded ZIP64 clearance (#7035)
2026-12-01 17:51:38 +01:00
BFlat b4efb2fef1 Merge pull request #8180 from shantanuo/codex/add-hindi-language
Add Hindi to Review language list
2026-12-01 22:18:53 +07:00
BFlat 30b8f025d2 Merge pull request #8252 from ruchirguitar/hi-interface
i18n: Hindi (hi) as an interface language
2026-12-01 22:18:09 +07:00
Martin BallandClaude Opus 5.5 27efb34a95 Repin craft-libs to d73e274a (egui 07c20531, winit 0dfcec0e) (#8250)
* chore(deps): repin craft-libs to d73e274a, egui to 07c20531, winit to 0dfcec0e

Moves every craft-libs rev (including craft-nightly and the craft-libs
patches) from 7097741460 to craft-libs main d73e274a, and the egui and
winit forks to the revs craft-libs builds with at that commit. Cargo.lock
holds one egui and one winit; only the affected git packages changed.

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

* fix(ui-egui): adapt to craft-libs d73e274a API

RibbonLook::body takes a RibbonBody (Band keeps the ruled fill), the
GalleryMore::Body closure takes a BodyCx, ToggleButtonOutput is read
through .edit.response, and DrawEnv has a mark field.

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

* test(ui-egui): follow craft-libs name and list changes

Tests that look controls up by access name or by list contents follow
intended craft-libs changes. No assertion is removed or weakened.

- Split arrows are named "<label> options" and a stacked label's line
  break reads as a space (craft-libs 487b29c55): Bullets arrow, Switch
  Windows arrow; the View ribbon's Web Layout and Print Layout buttons now
  share a name with the status bar toggles, so the toggle is picked by state.
- The table size picker names squares "<columns>x<rows> Table" (was
  "<rows> × <columns>").
- A dropdown list ends on its last whole row and scrolls the rest
  (craft-libs f2b9450d8): the font size list no longer holds 28 unscrolled,
  so the tests use 24, which is shown.

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

* fix(wordcraft): adapt the ui.json import to craft-libs LegacyFile

LegacyFile takes the old files as `paths` and its parse gets one slot per
path (bytes, absent or a read error). The ui.json import passes its one
path and a small wrapper over legacy_ui_json; behaviour is unchanged.

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

* fix(ui-egui): pass grid rows to TileGrid max_rows after the craft-libs repin

craft-libs a84275d0d/f6ae74bf4 make a grid's max_rows count visual rows, not
items, so the tile_rows_cap workaround (rows*columns items) now asked for up to
128 rows and the Symbols map grew to ~3600 px. Drop the workaround and pass the
row counts (Symbols 8, Insert Diagram 3) directly.

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

* fix(wordcraft-web): adapt the web host to craft-libs d73e274a

The web app still used the old craft-libs API, so it no longer compiled
(CodeRabbit on #8250; macOS Print / lint):
- LegacyFile now takes `paths` and a slot-based parse. The slot adapter
  moves from the desktop app into ui-egui as `legacy_ui_json_slots`, and
  both hosts use it.
- web-host's `Message::Open` name is now `Option<String>`; a missing name
  becomes `Document.docx` as a blank one did.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:50:18 +00:00
bflatastic 61c69fceca docs: the catalog range takes in Hindi's 2,800 entries 2026-12-01 21:16:41 +07:00
RickiNanoandFredApps 199162f96a #7818: Review › Delete: Delete All Comments in Document and Delete All Resolved Comments (#7836)
* #7818: Review › Delete: Delete All Comments in Document and Delete All Resolved Comments

Review › Comments › Delete becomes a split button whose menu has Delete,
Delete All Comments in Document (the existing review.deleteComment
{"all": true}) and Delete All Resolved Comments, a new
review.deleteComment {"resolved": true} that deletes each resolved
comment with its replies and keeps the open ones, in one undo step.

thread_of becomes threads_of, taking several roots and building the
reply map once, so deleting many resolved threads stays one pass.

* #7818: regenerate the parity checklist after merging main

main added the headless count; with this PR's two commands it is 512.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-01 12:24:20 +01:00
ruchirguitar ea7322efac ROADMAP: Hindi coverage as i18n-report measures it 2026-12-01 16:48:27 +05:30
reubgrandMuse 3e64bba9bb validate: keep established TIFF cycle defects when a sibling hits the depth bound (#8186) (#8223)
* fix(validate): preserve established TIFF graph defects across traversal bounds (#8186)

* test(validate): probe adjacent TIFF cycle, malformed, and bound shapes (#8186)

* chore(validate): satisfy clippy::obfuscated_if_else in TIFF tests (#8186)

* fix(validate): preserve established TIFF edges across budget stops and charge examined directories (#8186)

* fix(validate): defer TIFF walk continuation past initial part assessments (#8186)

* fix(validate): disclose every affected TIFF and budget-stopped part in canonical order (#8186)

* test(validate): add discriminating tests for #8186 round-1 findings and box PausedWalk

* fix(validate): install cached TIFF chain edges as soon as chain role is established (#8186)

* fix(validate): confine multi-part decode-stop disclosure to TIFF parts (#8186)

* test(validate): add discriminating tests for #8186 round-2 findings

* chore(validate): satisfy clippy in TIFF chain-role helper and tests (#8186)

* test(validate): match all three TIFF admission outcomes in graph oracle (#8186)

Match Admission::Admitted, Admission::MalformedOrCyclic, and Admission::Limited explicitly in media_magic_tiff_admission_is_a_function_of_the_directory_graph instead of collapsing Limited and MalformedOrCyclic via matches!, and key the sampled report-level check to the same three-way outcome.

---------

Co-authored-by: Muse <muse@Mac-mini.local>
2026-12-01 11:45:11 +01:00
reubgr 5d93167fe0 Doc: collect text boxes inside nested shape groups (#8068) (#8158)
* fix(doc): collect text boxes inside nested shape groups (#8068)

Walk InlineObject::Group trees iteratively in member order in both
InlineObject::text_boxes and InlineObject::text_box_slots so text boxes
nested inside groups of groups are collected, kept alive by
Document::prune_text_boxes, and repointed consistently during fragment
adoption and comparison.

* test(doc,engine): cover nested-group text box collection, pruning and Session survival (#8068)

Add wordcraft-doc unit tests for nested-group text_boxes and text_box_slots
collection across depths 1..40, prune_text_boxes preservation with chain links
and unreachable boxes, and cyclic nested-group story termination. Add an
end-to-end wordcraft-engine Session test verifying nested-group text boxes
survive mutating commands and copy/paste adoption.

* test(doc): flatten text_box_slots iterator to satisfy clippy (#8068)
2026-12-01 11:42:20 +01:00
RickiNano 6659ce4adc #7443: Insert Citation cites the source it just edited, not the last one (#7965)
references.citation with a source and no tag now cites the tag that
source was added or edited under, instead of the last source in the
list. Manage Sources' add step moves into add_source, which returns
that tag.
2026-12-01 11:39:54 +01:00
RickiNanoandSilvertree2010 43632f571c #3670: Insert Index doesn't add a second index when the existing one is in a table or text box (#8036)
* #3670: Insert Index doesn't add a second index when the existing one is in a table or text box

Insert Index looked for the INDEX field only in top-level body paragraphs.
An index in a table cell, a text box, a header or a footer (as imported
documents can have it) was missed, so a second index went in at the caret,
and Update Index reported success without rebuilding it.

Both commands now refuse with a message saying where the index is, the way
an index can't be inserted outside the main text either. Rebuilding an
index where it sits is not supported.

Builds on #3961 by @Silvertree2010; this version also finds an index
held as a range field (as Word files hold it) or in a text box.

Co-authored-by: Silvertree2010 <133535268+Silvertree2010@users.noreply.github.com>

* #3670: Insert Index counts only the headers a page shows, and leaves a range-field index to Update Index

* #3670: refuse a range-field index that follows text, and prove Update Index rebuilds one that starts its paragraph

* #3670: refuse an index in a table or box even when the main text has one too

---------

Co-authored-by: Silvertree2010 <133535268+Silvertree2010@users.noreply.github.com>
2026-12-01 11:36:36 +01:00
Lucas Batista Vargas 0e3f5f3ea6 Linux: restore GNOME Wayland window controls without bundled fonts (#5814, #5375) (#6078)
* Linux: restore GNOME Wayland window controls without bundled fonts (#5814, #5375)

* Verify Linux target section for winit Wayland decorations in test

* test(linux): check forbidden font crates across entire Cargo.lock

* test(linux): check sctk-adwaita dependency path instead of workspace-wide Cargo.lock (#5814)
2026-12-01 11:30:13 +01:00
reubgr 3c8a1eeb2d Doc: next_shape_id walks nested groups and all stories (#8157) (#8169)
* fix(doc): inspect nested shape groups in Document::next_shape_id (#8157)

Walk InlineObject::Group trees iteratively with a worklist in
Document::next_shape_id so ShapeExtra::id values on shapes inside nested
groups are accounted for at any nesting depth without unbounded recursion.

* test(doc): cover nested-group, flat, ungrouped, and cyclic-story shape ID allocation (#8157)

Verify Document::next_shape_id accounts for shapes inside doubly-nested,
5-level, and 40-level groups across body and secondary stories, preserves
existing allocation for empty, ungrouped, flat-group, and u32::MAX cases,
and terminates cleanly on cyclic nested-group text-box story graphs.

* fix(doc): avoid reissuing u32::MAX in Document::next_shape_id (#8157)

Replace saturating increment with free_id in Document::next_shape_id so
that when u32::MAX is already in use (including inside nested groups),
allocation falls back to the smallest unused non-zero ID rather than
reissuing u32::MAX. Update the overflow assertion and add tests covering
the u32::MAX - 1 boundary and u32::MAX overflow fallback.

* fix(doc): walk note-separator stories in Document::next_shape_id (#8157)

Include footnote_separators and endnote_separators (separator,
continuation_separator, and continuation_notice) in Document::next_shape_id
so shape IDs living only in separator stories are never reissued, including
under nested groups, tables, and u32::MAX overflow fallback.
2026-12-01 11:27:03 +01:00
ruchirguitar 3b7779df34 craft-i18n.rev at 217f413: Hindi WordCraft catalog (craft-i18n #579)
Moves the pin and the flatpak manifest's craft-i18n commit together and
fills in the Hindi catalog's size (2,800 rows) in the docs.
2026-12-01 15:50:49 +05:30
RickiNano e7588ff931 #7874: Home › Borders with whole table cells selected borders the cells (#7946)
* #7874: Home › Borders with whole table cells selected borders the cells

Home › Paragraph › Borders always set paragraph borders, so with the
table (or rows, columns or a block of cells) selected, All Borders drew
a separate box around each paragraph instead of a grid on the cell
edges. With whole cells selected, para.borders now applies the kind to
the cells as one block: all borders every cell, outside the block's
edges, inside the lines between its cells, none clears every side, and
one side toggles along that edge. A caret or text selection still
borders the paragraphs.

* #7874: block borders reach the cells beyond the edge and rows with gridBefore

Review fixes for #7946. Each cell draws its own sides, so a line set on
the selected block's edge is now also set on the facing side of the cell
beyond it: No Border on a row no longer leaves the neighbouring rows'
lines showing. A row's first and last cells count as the block's outer
edge when the row skips grid columns (gridBefore/gridAfter), as the
layout draws them.

* #7874: Borders on whole cells judges the block's edges by the cells picked, and toggles a line the table style draws

A row that skips the selected grid columns (w:gridBefore) leaves a gap: the selected cells above
and below it now face it with an outer edge, so Outside draws those lines and Inside doesn't.

One side now toggles on the line the cells show, the table style's included: the layout's cell
border resolution is cell_borders in wordcraft-layout, and the first press on a Table Grid line
takes it off.

* #7874: Borders on whole cells looks up the selected cells by row, and toggles a line off only when it runs all along the edge

A line the cells beyond an edge draw counts as shown only when every one of them draws it, so a
line along part of a wide cell's edge is completed rather than taken off.

* #7874: Borders on whole cells resolves the table's style, borders and grid width once per press

wordcraft_layout::CellBorders resolves them for one table; cell_borders stays a wrapper.

* #7874: Borders on whole cells takes in all of a vertically merged cell

Selecting a cell merged over several rows from its first row selects only that row; the rest of
the merge now counts as selected, so No Border clears the whole cell's outline.

* #7874: Borders on whole cells counts a line beyond an edge as shown only where it spans the whole edge

A row below that skips columns (w:gridAfter) draws the facing line along part of the edge only;
the press now completes the line instead of taking it off.
2026-12-01 11:17:38 +01:00
Martin BallandClaude Opus 5.5 ba1ed225c0 Bookmark: the Sort by label is back (#7976) (#8196)
The Sort by radio group had no caption row after the craft-ui port; wrap it in captioned() as #8026 did for the other dialogs.


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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:13:54 +01:00
36e7ee7ade #6851: tracked changes are dated in local time, as Word reads w:date (#6876)
* #6851: date tracked changes in local time, as Word reads w:date

Word writes w:date as the local wall-clock time with a Z it doesn't mean,
and reads it back the same way. WordCraft stamped new tracked changes with
UTC, so Word showed them shifted by the author's offset from UTC.

Typing, deletions, moves, formatting changes and Compare's result now take
cmd::revision_date(): the local time from the existing local_offset_secs
helper, written with a Z. Comments keep their w16cex:dateUtc and are
unchanged.

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

* #6851: the local-time test accepts any second between its samples

Review on #6876: the tracked change may be stamped a second after the
first sample and before the second, so compare against the interval, in
order, rather than its two ends.

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

* #6851: check the stamp against each second's own local time

Review on #6876: across a backward daylight-saving change the local times
of the two samples no longer bound the stamp. Sample the UTC clock instead
and accept the local time of any second between the samples.

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

* #6851: the local-time test pins its zone and covers every revision

A test-only, per-thread zone for revision_date() lets tracked_changes_carry_the_local_time
stamp at UTC+8:45 on any runner. On CI's UTC runner a UTC stamp was also the local one, so
switching a call site back to now_iso() passed. The test now makes a revision through each
place that dates one: typing, a paragraph tool, formatting, AutoFormat's border line, a tracked
cut pasted as a move, and Compare.

* #6851: keep tracked change dates in UTC; convert w:date at the DOCX boundary

The document keeps the UTC instant, so revision grouping tells apart two
edits an hour apart in the repeated hour as daylight saving time ends.
Saving .docx/.docm/.dotx/.dotm or Word XML writes w:date as local
wall-clock time with a Z, as Word writes and reads it; opening them reads
it back to UTC. Tests set the clock and zone per thread.

* Dependencies: take craft-libs main at 8a5b916541

8a5b916541 is craft-libs#3220: craft-docx reads and writes w16du:dateUtc
on tracked changes and keeps it in the shared model's Revision, so two
changes with one local w:date stay two. #6876 (#6851) builds on it.

The egui and winit forks craft-libs builds with are unchanged
(b9770908e0, a517b3846e). Cargo.lock: the craft-libs sources move to the
new rev and craft-control-protocol, a craft-libs crate, is added.

* #6851: tracked changes keep their UTC time beside w:date

A revision now has date_utc, as comments do, read from and written to
w16du:dateUtc by craft-docx. Changes made here are stamped with both in
UTC, grouped by the UTC instant, and a Word save writes their w:date in
local wall-clock time, as Word does, with dateUtc beside it. A change read
from a file is written as read: open no longer guesses the zone a w:date
without dateUtc was written in. review.changes reports the UTC time when
it is known.

Two edits in the repeated hour reopen as two changes, and Reject on the
second leaves the first pending.

* Dependencies: section metadata test expects w16du in mc:Ignorable

craft-libs#3220 declares the w16du namespace in body parts and lists it
in mc:Ignorable, so readers that don't know it ignore it.

* #6851: rustfmt the test revisions

* #6851: docs describe dateUtc and dates written as read

* #6851: date a change in local time when it is made, not when it is saved

The save treated a revision whose w:date equals its dateUtc as made here
and moved its w:date to local time. A file written in UTC has the two
equal too, so saving it in another zone moved the time Word shows for an
edit nobody touched.

A change made here now gets its local w:date when it is made
(cmd::made_revision), with its UTC time in date_utc, and saves write
every revision as it is. Nothing is inferred from the dates.

* #6851: OpenDocument dates a tracked change by its UTC time

A change made here keeps Word's local wall-clock time in `date`, which
the ODF writer wrote verbatim as dc:date, an instant, so an edit at
08:33 UTC at UTC+8 was exported as 16:33 UTC. The ODT, OTT and Flat ODF
exports now date a change by its UTC time where it is known, and by
`date` otherwise.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Martin Ball <98639962+benandez@users.noreply.github.com>
2026-12-01 10:54:25 +01:00
Martin BallandClaude Opus 5.5 14112e7137 Title bar: the search box is a quiet field again (#7682) (#8197)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 01:15:08 +00:00
Reuben Grinberg 17c6d87f0d review: assert full document equality on second-pass idempotence test (#8129) 2026-11-30 22:44:04 +00:00
ruchirguitar b4fffa91cc docs: the Hindi interface doesn't set the language of new documents 2026-11-30 20:07:21 +05:30
ruchirguitar 5ad1c48b3e i18n: add Hindi (hi) to the interface languages
Lists hi in LANGUAGES (editing_lang None: WordCraft doesn't proof Hindi
yet), adds its system-locale test row, and updates the localization
docs and progress log.
2026-11-30 20:04:05 +05:30
fluorine 592d3cb902 Merge remote-tracking branch 'upstream/main' into cursor-arrow-off-paper 2026-11-30 10:14:41 -04:00
fluorine fd81fadba7 Merge remote-tracking branch 'upstream/main' into layout-cache-test-page-bound 2026-11-30 10:14:24 -04:00
Martin BallandClaude Opus 5.5 4daed0b5ad Undo History: the list keeps its rows while the popover fades out (#8141) (#8154)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:33:42 +00:00
Martin BallandClaude Opus 5.5 d22500664d View tab: Views and Zoom keep their labels at 1440 pt (#7985) (#8156)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:28:24 +00:00
Martin BallandClaude Opus 5.5 effb736735 File rail: the Back arrow reads in the rail's ink (#7707) (#8155)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:28:17 +00:00
Martin BallandClaude Opus 5.5 d7aac19341 docs: refresh roadmap and parity summary against the 28 Nov parity run (#8059)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:38:44 +00:00
Martin BallandClaude Opus 5.5 055a9065f5 docs(7822): the root window is never shown (amend ADR 0001) (#8110)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:38:37 +00:00
Hagai Baram 5265924f29 Word Count: keep automation changes to includeTextBoxes while open (#8139) (#8150) 2026-11-30 09:17:26 +00:00
Lucas Batista Vargas 0f241aef67 Mini toolbar: restore live preview and current-choice mark for Automatic and No Color (#7956) (#7957) 2026-11-30 08:19:15 +00:00
MaheshDesu 6478152244 UI: the Caption preview is its own label, not a field prefix (#8042) (#8043) 2026-11-30 08:09:02 +00:00
shantanuo 1ec6f0bb58 Add Hindi to Review language list 2026-11-30 10:34:11 +05:30
Reuben Grinberg a8f1edb45c review: avoid per-block/object heap allocation in revision retention walk (#8129)
Dispatch paragraphs directly in collect_block and non-Group inline
objects directly in collect_object/remap_object, initializing iterative
stacks lazily with Vec::new() so heap allocation occurs only for tables
nested inside tables or non-empty groups nested inside groups. On the
common no-surviving-references fast path, retain_referenced_revisions
performs zero heap allocations for paragraphs, non-nested tables, and
non-nested inline objects while keeping every resolution output identical.
2026-11-30 03:24:23 +00:00
Reuben Grinberg a0d4edccd6 validate(scan): distinguish unresolved-namespace AlternateContent in F11 pairing note (#7643)
In note_scan_incomplete (crates/validate/src/scan.rs:1373), the F11
coverage note previously stated that the part 'skipped
mc:AlternateContent', which overclaimed when enter_alt matched an
AlternateContent element of unresolved namespace (scan.rs:1445) or an
empty AlternateContent tag (Event::Empty, scan.rs:1178).

Reword the note so every clause holds on every path reaching line 1373:
the part contains an element treated as mc:AlternateContent
(mc:AlternateContent or AlternateContent of unresolved namespace) whose
contents are not scanned for pairing, has pending
field/move/bookmark/comment pairing, and completion-dependent pairing
checks were not run.

Part of #7643 (F11 fix round 2).
2026-11-29 21:16:54 -06:00
Reuben Grinberg d0f25cd896 review: reach fixed point in one pass on malformed PropChange chains (#8129)
Stop descending into PropChange::old during revision collection when the
outer PropChange::rev is out of bounds, matching step_prop_change which
discards the outer PropChange and any buried indices together. This
ensures retain_referenced_revisions leaves only genuinely referenced
records in doc.revisions after a single Accept/Reject All pass.

Add regression tests covering an invalid outer formatting change burying
a valid inner index (both standalone and mixed with valid/nested chains)
and asserting full document equality on a second resolution pass.
2026-11-30 03:09:25 +00:00
Reuben Grinberg b743dbad0a validate(media): drop unused Debug derive on PrefixResume for observation gate
Part of #7643 (F9).
2026-11-29 20:20:34 -06:00
Reuben Grinberg 45956f85bd validate(scan): reword skipped AlternateContent pairing note without positional claim
note_scan_incomplete previously claimed that the part had 'open
field/move/bookmark/comment ranges across skipped mc:AlternateContent',
even though skipped_content and completion_dependent_pending establish
only that mc:AlternateContent was skipped somewhere in the part and
that some completion-dependent pairing remained pending at the end of
the scan (a skipped block can precede the only range start).

Reword the note to describe the skipped mc:AlternateContent, the
pending field/move/bookmark/comment pairing, and the withheld
completion-dependent pairing checks without making an unsupported
positional claim, and pin the completed-AlternateContent-before-start
case in scan unit tests.

Part of #7643 (F11).
2026-11-29 20:04:58 -06:00
Reuben Grinberg 1201692df6 validate(media): preserve JPEG prefix fill position and marker state on resume
When a 0xFF marker-fill run or straddling marker reached the JPEGTables
prefix boundary, walk_jpeg_markers rewound to marker_start before the
entire fill run, forcing every strip chunk to rescan the same prefix
bytes.

Record the boundary resume state (AtMarker, InFill, or AfterCode(u8))
in JpegHeaderScan so each chunk resumes at the consumed position
without rescanning prefix fill bytes, and pin the splice-boundary
fill/marker/SOF/SOS cases in media_workspace unit tests.

Part of #7643 (F9).
2026-11-29 20:03:28 -06:00
Reuben Grinberg 2f33435bb8 review: test surviving refs across stories and table-clear fast path (#8129) 2026-11-30 01:42:05 +00:00
Reuben Grinberg a03307d6b0 validate(media): enforce TIFF Tech Note #2 per-stream JPEGTables split
Keep spliced-stream JPEG workspace accounting unchanged so zune-jpeg's
memory stays accurately bounded, and add an independent per-stream
conformance check (media_workspace::tiff_jpeg_tables_conforming) for
ModernJPEG pages carrying JPEGTables (tag 347):
- JPEGTables must be an ITU-T T.81 Annex B.5 tables-only abbreviated
  stream (SOI, tables/misc segments only, EOI; no SOF, SOS, or
  straddling segments);
- each strip or tile must independently start with SOI and carry its
  own complete SOF frame header before SOS.

Non-conforming splits return AlternateAssessment::Unusable so a sole
SOF placed in tag 347 no longer earns a Warning grade while proper
splits continue to pass.

Part of #7643 (F9).
2026-11-29 19:38:29 -06:00
Reuben Grinberg 8b4335903a review: retain referenced revisions on Accept/Reject All (#8129)
Compact doc.revisions instead of unconditionally clearing it in
resolve_all, keeping entries still referenced by surviving stories or
metadata (such as Ruby or content-control run properties) and remapping
every surviving reference consistently. When no references survive,
clear doc.revisions directly as before.
2026-11-30 01:37:03 +00:00
Reuben Grinberg 929950acff validate(media): dereference Copy JpegHeaderScan instead of cloning 2026-11-29 18:27:29 -06:00
Reuben Grinberg 4868d7947d validate(media): pin TIFF peer-chain depth and SubIFD depth-bound handling
Pin verified TIFF 6.0 §2 and Adobe TIFF Technical Note #1 depth behaviour
in media_magic_tiff_depth_is_the_minimum_over_routes:
- a 12-page main next-IFD chain (> max_depth = 10) remains at depth 0
  and decodes cleanly to Warning;
- a valid IFD0 with a depth-6 SubIFD tree (> tiff_ifd::MAX_SUB_DEPTH = 4,
  <= max_depth = 10) decodes cleanly to Warning, while depth 11 stops at
  the validator depth bound as Incomplete without grading.

Part of #7643 (F8).
2026-11-29 18:26:04 -06:00
Reuben Grinberg 0d31f95102 validate(scan): include comment ranges in pairing coverage note wording
note_scan_incomplete emitted 'field/move/bookmark' in its three pairing
incompleteness notes, omitting 'comment' even though finish_completion,
completion_dependent_pending, and unresolved_pairing_pending all cover
four pairing families (FLD-UNBALANCED, STRUCT-MOVE-UNPAIRED,
BOOKMARK-UNPAIRED, and COMMENT-RANGE-UNPAIRED).

Update all three notes to 'field/move/bookmark/comment' and pin the
unresolved comment-range note with a unit test.

Part of #7643 (F11).
2026-11-29 18:24:42 -06:00
Reuben Grinberg 76ee611ed5 validate(media): splice TIFF JPEGTables into JPEG strip workspace check
TIFF Technical Note #2 defines JPEGTables (tag 347) as an ITU-T T.81
Annex B.5 abbreviated table-specification datastream (SOI..EOI), but
tiff 0.11 strips its last two bytes and prepends them to each ModernJPEG
strip/tile (after stripping the chunk's first two bytes) before handing
the spliced bytes straight to zune-jpeg.

media_workspace::jpeg_strip_decoder previously inspected each raw chunk
in isolation, missing SOF/SOS segments placed in JPEGTables or marker
framing that crosses the splice boundary. Extract tag 347 in
tiff_admission::jpeg_tables and walk the shared prefix once before
resuming on each strip's suffix in O(|prefix| + sum(|chunk_headers|))
time with no heap allocation.

Part of #7643 (F9).
2026-11-29 18:22:35 -06:00
Reuben Grinberg aa0a0b990a validate(scan): align OMML element name list to all 124 ECMA-376 §22.1.2 elements
Compare scan::OMML_NAMES against shared-math.xsd (ECMA-376 Part 1 §22.1.2,
extracted into model::ELEMENTS): four real OMML elements were missing
(defJc, deg, wrapIndent, wrapRight) and two non-schema names were
spuriously present (gc, wrap), yielding 122 instead of 124.

Replace the match list with a sorted 124-entry table pinned directly
against model::ELEMENTS, and verify that unresolved deg withholds
MATH-PLACEMENT while non-OMML gc and wrap do not.

Part of #7643.
2026-11-29 18:10:41 -06:00
Dylan M. Taylor aaaeff2b94 ci(nightly): enable automated daily schedule and Stage 2 signer dispatch (#8054) 2026-11-29 16:16:22 -05:00
Dylan M. Taylor e1f261501c ci(sonarcloud): give each main commit its own concurrency group (#8144) 2026-11-29 16:05:30 -05:00
Lucas Batista Vargas 837999196a Picture and Shape: restore unit hints on size fields (#7952) (#7953) 2026-11-29 20:42:14 +00:00
Lucas Batista Vargas 13f5e9702c Manage Styles: open on the caret's current style (#7950) (#7951) 2026-11-29 20:42:09 +00:00
codeiou 0eace8de49 Search: the title bar keeps its command index between passes (#7674) (#7881) 2026-11-29 20:42:04 +00:00
codeiou 63863ec62d Caret: a window in the background shows no caret and stops repainting for it (#7674) (#7882) 2026-11-29 20:41:59 +00:00
codeiou b4f0a3abad Track Changes Options: the By author swatch shows the author colours side by side again (#7671) (#8011) 2026-11-29 20:41:54 +00:00
MaheshDesu ff98927ea6 UI: the Format Painter icon keeps its full outline (#7683) (#8044) 2026-11-29 20:41:48 +00:00
Lucas Batista Vargas fff580d8f0 perf(engine,ui-egui): skip char scans in word count, memoize format::state, and cache ribbon pickers (#7903) (#7913) 2026-11-29 20:41:43 +00:00
Lucas Batista Vargas 4b3e5d52df perf(ui-egui): defer closed Undo history rows and QAT menu assembly until opened (#7902) (#7912) 2026-11-29 20:38:45 +00:00
Dylan M. Taylor 53bbaa8978 test(nightly): retain exact launcher query and profile coverage (#8136) 2026-11-29 15:22:43 -05:00
Lucas Batista Vargas 813f069712 Styles pane: do not apply a style on right-click (#7958) (#7959) 2026-11-29 20:17:36 +00:00
Lucas Batista Vargas 43c38dfb56 Word Count: preserve the "Count words in text boxes and notes" preference on open (#7941) (#7942) 2026-11-29 19:55:25 +00:00
Dylan M. Taylor 6d6ab5f4dc feat: wire craft-nightly for self-isolated nightly launches (#8126) 2026-11-29 13:48:48 -05:00
Rees 0c72c0a013 #3614: integrate current PDF tag order with figure lookups 2026-11-29 08:02:19 +01:00
Martin BallandClaude Opus 5.5 54f6709a97 UI port: Colors dialog shows no colour, not black, for an unknown Current (#7984) (#8048)
* fix(colors): Colors dialog shows no colour, not black, for an unknown Current; Current reads more targets (#7984)

Needs craft-libs ColorPickerDialog::no_current and the Colors: heading
(craft-libs branch fix/7984-colors-compare-none); waits for the pin to move.

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

* fix(colors): table shading Current skips cells a ragged table lacks (#7984)

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

* fix(colors): Current reads the run shading the command changes (#7984)

para.shading shades the selected text, not its paragraph, when the selection is text within one
paragraph. Current now reads the selected runs' shading (new "shading" key in format.state, None
when mixed or unset) under the engine's own shades_text rule, now pub. shape.effects Current reads
shapes only, as the command applies glow to shapes only.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 04:41:41 +00:00
Reuben Grinberg 12545dd771 validate: scope diagram definition external DOCTYPE tolerance to SYSTEM 2026-11-28 22:17:00 -06:00
Martin BallandClaude Opus 5.5 c6d71b829a fix(formats): an ODT list item's later paragraphs stay in the item (repin regression) (#8089)
craft-libs 9c27cebc14 reads an ODT list item's further paragraphs as unnumbered
paragraphs marked ParaProps.list_item. WordCraft's ParaProps had no such field,
so the bridge dropped it and HTML/Markdown export restarted numbering after the
item. Add the field, same type and serde name as craft-wordmodel's.


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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:43:20 +00:00
Martin BallandClaude Opus 5.5 af26131063 fix(dialogs): Borders and Shading draws its preview at sample size (#7977) (#8088)
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:42:47 +00:00
Dylan M. Taylor 9b13180006 fix(nightly): enable Linux package_formats (including Flatpak) in signing policy (#8091) 2026-11-28 22:42:19 -05:00
Martin BallandClaude Opus 5.5 2ca5bf5dfa fix(options): Initials shows its default-initials placeholder again (#8018) (#8081)
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:41:59 +00:00
Martin BallandClaude Opus 5.5 1f6cf16029 fix(docx): a text box in a hyperlinked nested group survives an edit (repin regression) (#8087)
craft-libs 6a46b44449 keeps a hyperlinked nested group as a nested
InlineObject::Group. WordCraft looks one level deep, so prune_text_boxes
dropped the nested box's story on the first edit. The bridge now lifts nested
members into the parent group, offsets composed, as the reader does for
unlinked groups.


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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:39:45 +00:00
Martin BallandClaude Opus 5.5 18bbf00090 UI port: Customize Keyboard categories, Customize Ribbon layout, command search locations (#7671) (#8024)
* fix(keyboard): Customize Keyboard lists the ribbon tabs as Categories, in a dialog of set size (#7971)

Catalog commands carry their English ribbon location as a menu path; Categories are
the ribbon tabs (from ribbon::TABS), Contextual Tabs, Other and All Commands.

Partial: the Commands list still gets no room until the craft-libs fix (a7d6dcfcbb on
fix/7971-keyboard-categories-height) is synced to main and WordCraft repins.

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

* fix(ribbon): Customize Ribbon and Quick Access panes share the width (#7981)

Tab names are no longer truncated and Up/Down no longer overlap the list.

Partial: the lists are still unframed (craft-libs List has no frame option).

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

* fix(search): command search shows each command's ribbon location (#7983)

Partial: the shortcut per row and the popup width are not done.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:25:47 +00:00
Reuben Grinberg 5e4243bf2a validate: update observation and entry-loss contracts for rels owner completeness 2026-11-28 21:07:50 -06:00
Reuben Grinberg d80fb49267 validate: require complete archive discovery in rels XML-DOCTYPE owner gate 2026-11-28 21:07:50 -06:00
Reuben Grinberg 93ce16e0f7 validate: reconcile DOCTYPE observation-contract prose with EVIDENCE.md batch-4 totals 2026-11-28 20:43:12 -06:00
Reuben Grinberg c70841a895 validate: record #7735 batch-4 PUBLIC DOCTYPE measurements in EVIDENCE.md 2026-11-28 20:30:17 -06:00
Reuben Grinberg a27d6de7e1 validate: record #7735 batch-3 PUBLIC DOCTYPE measurements in EVIDENCE.md 2026-11-28 20:21:15 -06:00
Reuben Grinberg bed86ba38e validate: scope classificationlabels and webextension external DOCTYPE to SYSTEM 2026-11-28 20:12:01 -06:00
Reuben Grinberg a16543415e validate: clarify tolerated consumer coverage in EVIDENCE.md 2026-11-28 18:48:02 -06:00
Reuben Grinberg 1cf8870549 validate: require uniquely resolved owner for rels XML-DOCTYPE evidence 2026-11-28 18:46:11 -06:00
Martin Ball a3b0f9835f Merge pull request #8072 from storytold/chore/craft-libs-repin-2026-11-28
chore(deps): repin craft-libs to 7097741460
2026-11-29 00:33:18 +00:00
Reuben Grinberg 0b37a15d5d validate: record #7735 batch measurements in EVIDENCE.md and add tests
Record batches 1, 2a, and 2b (issue #7735 comments 7243358292,
7245685323, and 7246172147) in corpus/EVIDENCE.md with Windows and
Word for the web outcomes, noting Mac legs still owed and keeping
interim labelling on unmeasured cells.

Add integration tests covering every newly adverse cell group (batch 1
part roles, batch 2a part roles, batch 2b diagramData, batch 2a
story-owner rels, and batch 2a external rels) and asserting unmoved
cells stay put (diagram definitions external, chart-rels ATTLIST,
footnotes-rels ATTLIST, main-document rels ATTLIST).
2026-11-28 18:19:15 -06:00
Reuben Grinberg 9c84f895cb validate: grade measured #7735 DOCTYPE relationships cells as Error/Observed
Move the relationships DOCTYPE cells measured adverse in issue #7735
batch 2a (comment 7245685323) to Error/Observed:
- story-owner rels (header, footer, endnotes, comments): ATTLIST and
  external-identifier forms (refused on Word for the web; union rule)
- package rels (_rels/.rels), main-document rels, customXml item rels:
  external-identifier form (refused on Windows and web)
- chart-owner rels, footnotes-owner rels: external-identifier form
  (refused on Word for the web; union rule)

Unchanged cells:
- package, customXml item, and chart rels ATTLIST remain Error/Observed
  as shipped from the 2026-11-22–23 isolated series
- footnotes rels internal forms remain tolerated Warning/ByConstruction
- main-document rels ATTLIST remains Warning/ByConstruction (not
  measured in batch 2a; historical dtd-attlist.docx excluded from matrix)

Update the XML-DOCTYPE observation contract summary and regenerate
observation-contracts.md.
2026-11-28 18:15:43 -06:00
Reuben Grinberg cc2a5161c7 validate: grade measured #7735 DOCTYPE part-role cells as Error/Observed
Move the ATTLIST and external-identifier DOCTYPE cells measured adverse
in issue #7735 batches 1, 2a, and 2b (comments 7243358292, 7245685323,
and 7246172147) to Error/Observed:
- batch 1: header, footer, footnotes, endnotes, comments, glossary,
  chart, customXml item, core-properties
- batch 2a: commentsExtended, commentsIds, people, classificationlabels,
  webextension (union rule: web refuses labels and webextension)
- batch 2b: diagramData

Diagram definition parts (layout, colors, quickStyle) in external form
remain Warning/ByConstruction (tolerated on Windows and web).
2026-11-28 18:13:26 -06:00
Martin BallandClaude Opus 5.5 5f06b28447 Land 14 approved PRs with stale CI (#8069)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 23:19:22 +00:00
Martin BallandClaude Opus 5.5 4c913ffd28 fix(docx): keep hide-spelling and hide-grammar settings on save (repin)
craft-docx now owns w:hideSpellingErrors and w:hideGrammaticalErrors in
settings.xml; wordcraft_doc::Settings lacked both, so the serde bridge
dropped them. Also fixes the mc:Ignorable order in the section test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-11-28 23:02:17 +00:00
Martin BallandClaude Opus 5.5 e3f1356360 chore(deps): repin craft-libs to 7097741460 (#7671)
Moves every craft-libs rev and the egui/winit fork pins to craft-libs main.
Mechanical API fixes: AppShell slots take a version (None, as before),
GroupChild gains `link`, Settings::compat_mode is an Option (the docx bridge
maps an omitted mode to Word 2007's 12 as before), ProofLang::Gu/Hi names,
and w16du joins mc:Ignorable in the docx test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-11-28 22:57:45 +00:00
Rees 303c80a253 Layout: index numbering definition lookups (#4640)
Co-Authored-By: OPUZZLES <109076338+OPUZZLES@users.noreply.github.com>
2026-11-28 22:56:50 +00:00
Martin BallandClaude Opus 5.5 9e899aaae9 UI port: Symbol and Diagram galleries show their grids, Diagram Design and Equation tab pictures draw (#7671) (#8030)
* fix(symbol): show the Symbols map in rows, with the Recently used heading and from Unicode (hex) (#7972)

max_rows counts items, not grid rows, so the 8-row cap showed one row; cap it by items.
The Recently used row already existed; its heading now shows (as the row's label) while
the row is empty too, and the code field says it is Unicode hex.

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

* fix(diagram): Insert Diagram shows every layout (#7973)

The same max_rows item-count cap showed 3 of 8 layouts. Partial: the names "Basic Process"
and "Basic Pyramid" are still elided, since wider cells break the pinned 75x93 cell size test
and two-line captions need card text the dialog does not use.

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

* fix(ribbon): Diagram Design layouts in one strip, Size fields labelled H:/W: (#7974)

size_field is shared, so Picture Format and Shape Format Size also gain the visible H:/W: labels.

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

* fix(equation): draw symbol and structure pictures without the checkerboard, symbols at a readable size (#7975)

Pictures are alpha ink masks drawn without the transparency grid. The symbol strip requests
its picture from the tile's short side (the tiles are 24 x 52 pt and the picture is fitted),
and sets symbols at 22 pt, so they read at about 16 pt.

Partial: the Tools labels (Unicode, LaTeX, Normal Text) are still icon-only at 1440, as the
ribbon fit keeps Tools at the compact level.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:36:20 +00:00
Mex 8e52baaf18 README: qualify the default Windows graphics backend (#6702)
Co-Authored-By: MMexicann <44814932+MMexicann@users.noreply.github.com>
2026-11-28 22:27:33 +00:00
RickiNano 1b75d8dfd4 Find and Replace: a quote typed in Replace with goes in curly when smart quotes are on (#7949)
Co-Authored-By: RickiNano <81099017+RickiNano@users.noreply.github.com>
2026-11-28 21:59:13 +00:00
dedd658cb0 Deps: webbrowser 1.2.6 for its WSL command-injection fix (GHSA-j2mc-vg6q-w75p) (#5997)
Lands #5997 by @naxvog.

Co-Authored-By: naxvog <4963183+naxvog@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:54:40 +00:00
f28896acc1 Paragraph dialog: indents in points win over indents in characters (#6186)
Lands #6186 by @pakiat.

Co-Authored-By: pakiat <49967840+pakiat@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:54:39 +00:00
f3b51422b0 Caret: a click glides to its new place like a key does (#6360)
Lands #6360 by @fluorine.

Co-Authored-By: fluorine <1832604+fluorine@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:54:39 +00:00
11b1b69457 #6326: text typed into an inserted table row keeps the row's font (#6370)
Lands #6370 by @Nghiathan13.

Co-Authored-By: Nghiathan13 <201675788+Nghiathan13@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:54:39 +00:00
2b3b9c8460 #6013: a new table's cells are in the language of the text it is inserted in (#6381)
Lands #6381 by @Nghiathan13.

Co-Authored-By: Nghiathan13 <201675788+Nghiathan13@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:54:38 +00:00
ff0d327056 #5534: floating pictures are drawn over the shading of the paragraphs below them (#6395)
Lands #6395 by @Nghiathan13.

Co-Authored-By: Nghiathan13 <201675788+Nghiathan13@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:54:38 +00:00
194ca941bf Layout: the underline and selection over hanging spaces stop at the margin (#6434) (#6487)
Lands #6487 by @Nghiathan13.

Co-Authored-By: Nghiathan13 <201675788+Nghiathan13@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:54:37 +00:00
f0dfe49348 #5947: a paragraph style resets direct formatting as Word does (#6511)
Lands #6511 by @Nghiathan13.

Co-Authored-By: Nghiathan13 <201675788+Nghiathan13@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:54:37 +00:00
df3279f87e M7: explain the one-based sheet selector requirement (#6699)
Lands #6699 by @MMexicann.

Co-Authored-By: MMexicann <44814932+MMexicann@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:54:37 +00:00
45a851dee2 M14: explain interface size clamping in input errors (#6708)
Lands #6708 by @MMexicann.

Co-Authored-By: MMexicann <44814932+MMexicann@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:54:36 +00:00
1857c7e41b M14: list null among supported spreadsheet cell values (#6802)
Lands #6802 by @MMexicann.

Co-Authored-By: MMexicann <44814932+MMexicann@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:54:36 +00:00
106622972b M14: explain rejected custom table separators (#6812)
Lands #6812 by @MMexicann.

Co-Authored-By: MMexicann <44814932+MMexicann@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:54:36 +00:00
b6a402597f M14: trim author whitespace exposed by removed controls (#6814)
Lands #6814 by @MMexicann.

Co-Authored-By: MMexicann <44814932+MMexicann@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:54:35 +00:00
18368bae46 M14: prevent selection occurrence wrap on 32-bit targets (#6825)
Lands #6825 by @MMexicann.

Co-Authored-By: MMexicann <44814932+MMexicann@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:54:35 +00:00
reubgrandClaude Sonnet 5.5 4767a33981 validate: grade a settings DOCTYPE by its measured cell whatever the content-type casing (#8004)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 21:31:12 +00:00
Martin BallandClaude Opus 5.5 4699c8d7c7 fix(dialogs): frame the lists of Customize Ribbon and Quick Access Toolbar (#8037)
Part of #7981. v0.19.1 drew a border around these lists; after the port an
empty or short list has no visible bounds. Uses SurfaceKind::Frame, which List
already takes through its surface prop.


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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:12:00 +00:00
Dylan M. Taylor 7abfe7d86a ci: pin storytold/craft-common-actions to @main universally (#8065) 2026-11-28 16:07:48 -05:00
Martin BallandClaude Opus 5.5 08a4392b18 fix(layout): keep a negatively indented table inside the Read Mode column (#8020) (#8039)
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 20:57:02 +00:00
Dylan M. Taylor d1bb1ff547 ci(nightly): enable all signed Linux package formats (deb, rpm, appimage, flatpak, oci, arch) (#8061) 2026-11-28 15:32:06 -05:00
Martin BallandClaude Opus 5.5 56512dbc1d UI port: dialog captions, previews and clipped text (#7671) (#8026)
* fix(dialogs): draw captions for bare fields and radio groups (part of #7976)

A text box, number box, drop-down or radio group names itself for assistive
technology but draws no caption, so dialogs showed bare controls. Add
host::labelled (caption beside) and host::captioned (caption above), both over
craft's Field, which names the control by the same label, and use them where a
dialog drew a bare control: Envelopes, Labels, Table Properties, Custom
Properties, Index, Merge To, Insert Merge Field, Find Recipient, Rule If/Skip
If, Paste Special, Page Numbers, Line Numbers, Sort, Table Formula, Drop Cap,
Define List, Define Bullet, Enclose, Recipient List and the Borders/Shading
colour rows. The shared number helpers (count/length/percent/named field) label
every dialog that uses them (Hyphenation, Page Setup size, Insert Table...).

Partial: the Bookmark Sort by group is left to the Bookmark fix. Cross-reference and
Language lists get a plain caption line (a Field would rename the list), and the
Borders/Shading colour rows get plain text beside them (a Field would drop the
spoken colour). A group inside a titled section uses radios_in_section, and a box
after a same-named radio uses count_box, so no caption is drawn twice.

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

* fix(dialogs): draw previews at a sample size, not the icon side (part of #7977)

A Picture takes the icon side as its height unless given an extent, so the
Enclose, Define Bullet, Define List and Manage Styles previews shrank to
icons. Give them PictureSize::Sample(Large) (the style preview its device-pixel
size). Borders, Page Borders, Shading and Columns draw their previews inside
craft widgets (EdgePicker, the Columns dialog), so they need a craft-libs fix.

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

* fix(dialogs): Custom Properties footer, Recipient List headers, Special Characters shortcuts (part of #7982)

- Custom Properties: with no properties the list's own empty text is measured
  shorter than it is drawn, so the dialog was a row short and its footer was
  drawn over the Value box and the hint. The empty text is now a plain line.
- Recipient List: the columns shared the dialog's width, so six field names
  were cut to "First N", "Addre"; each column now takes a fixed share of control
  heights and the grid scrolls.
- Special Characters: the Shortcut key column took a third of the list and cut
  "Ctrl+Shift+..."; it now takes a fixed width.
Insert Chart type names, Page Setup margins, File Home/New names, the zoom label
and the Paragraph preview are craft widgets and need their own fixes.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 20:19:59 +00:00
Martin BallandClaude Opus 5.5 4deb338b44 UI port: Symbol tiles and Equation/SmartArt pictures follow the craft theme's colours (#7671) (#8046)
* fix(symbol): glyph tiles follow the theme's light or dark mode (#8021)

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

* fix(theme): Equation and SmartArt pictures take the craft theme's text colours, not egui's visuals (Part of #7975)

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 20:18:24 +00:00
Martin BallandClaude Opus 5.5 0c6c377681 fix(backstage): File menu page rows a theme gap apart, as v0.19.1 (#8022) (#8047)
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 20:18:18 +00:00
Martin BallandClaude Opus 5.5 17c163c425 Read Mode: 4 columns at 1440 px as before (#8019) (#8038)
* fix(read-mode): lay out 4 columns at 1440 px, not 2 (#8019)

craft's reading_size takes its column target from the body text's measure
(66 characters), which is wider than the 295 px v0.19.1 used. Keep the
gaps from the tokens and pin the target and least width to the old values.

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

* fix(read-mode): page arrows back at the bottom right, as v0.19.1 (#8019)

The page-turn row sat at the bottom left (craft's ReadingNav start). Lay it out from the far end, inset by the page view's side margin token; it mirrors to the bottom left in a right-to-left interface.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 20:18:12 +00:00
Martin BallandClaude Opus 5.5 6fbf780789 UI port: Cell Margins shows lengths in the interface unit; Organizer shows both style lists (#7671) (#8031)
* fix(dialogs): Cell Margins shows points in the interface unit, not as cm (#7970)

The fields held points but only labelled them with the unit, so 5.4 pt read 5.4 cm. They now declare points and a length unit, so the field converts as every other length field does. OK without an edit never wrote margins (the dialog compares against the stored values); the test pins that and the shown unit.

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

* fix(dialogs): Organizer shows both style lists with Copy, Delete and Rename between (#7980)

The lists sat in one row that the first list filled, which pushed the other file's list off the dialog. Three grid columns, as the old dialog had; Rename starts the list's own rename field.

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

* test(dialogs): Cell Margins converts a typed length back to points (#7970)

Cover the typed path CodeRabbit asked about: 1 cm typed in the field reaches the table as about 28.35 pt.

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

* fix(dialogs): frame the Organizer's Document and Template lists

Part of #7980. v0.19.1 drew a border around both lists; after the port an
empty list has no visible bounds. Uses SurfaceKind::Frame, which List already
takes through its surface prop. Builds on the Organizer layout of #8031.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 18:51:07 +00:00
Martin BallandClaude Opus 5.5 57fb4544f2 UI port: Read Mode table fit, Options slider, Apply/Clear and hints (#7671) (#8025)
* fix(layout): Read Mode fits a wide table to its column (#7988)

In the reading view a table with its own width is scaled to the column,
less its start offset (indent plus half border), mirrored tables too.

Not addressed here: Read Mode laying out 2 wider columns where v0.19.1
laid out 4, and the pager moving from bottom right to bottom left.

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

* fix(options): Read Aloud slider, one Agents heading, hints, Apply/Clear on folders (#7987)

Part of #7987. Fixed: the Read Aloud speed is a slider again; the Agents
page no longer repeats its heading; the Display and Save hints sit under
the rows they explain (they were page footnotes), and the Privacy hint
is back; User templates and Dictionaries folder have v0.19.1's Apply and
Clear and the placeholder again (typing saves nothing until Apply or
Enter; Clear returns to the default).

Still open: the General > Initials placeholder (RowKind::Text has no
placeholder, needs craft-libs); the speed slider's accessible value text
does not carry the x unit. Reset Section at the bottom of Advanced is
not a defect: the page scrolls.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 18:50:56 +00:00
Dylan M. Taylor eeeb31d85f ci(nightly): roll out signing pin, macOS docs layout, and profile reopen fix (#8045) 2026-11-28 11:56:37 -05:00
FredApps e7587b4b1b Merge origin/main into codex/fix-1913-line-spacing
# Conflicts:
#	ROADMAP.md
#	crates/engine/src/cmd/design.rs
#	crates/ui-egui/src/backstage.rs
#	crates/ui-egui/src/file_dialogs.rs
#	crates/ui-egui/src/i18n/bg.tsv
#	crates/ui-egui/src/i18n/cs.tsv
#	crates/ui-egui/src/i18n/de.tsv
#	crates/ui-egui/src/i18n/es.tsv
#	crates/ui-egui/src/i18n/et.tsv
#	crates/ui-egui/src/i18n/fr.tsv
#	crates/ui-egui/src/i18n/hr.tsv
#	crates/ui-egui/src/i18n/hu.tsv
#	crates/ui-egui/src/i18n/it.tsv
#	crates/ui-egui/src/i18n/ja.tsv
#	crates/ui-egui/src/i18n/ko.tsv
#	crates/ui-egui/src/i18n/pl.tsv
#	crates/ui-egui/src/i18n/pt-br.tsv
#	crates/ui-egui/src/i18n/ru.tsv
#	crates/ui-egui/src/i18n/sr-latn.tsv
#	crates/ui-egui/src/i18n/sr.tsv
#	crates/ui-egui/src/i18n/sv.tsv
#	crates/ui-egui/src/i18n/tr.tsv
#	crates/ui-egui/src/i18n/uk.tsv
#	crates/ui-egui/src/i18n/vi.tsv
#	crates/ui-egui/src/i18n/zh-hans.tsv
#	crates/ui-egui/src/i18n/zh-hant.tsv
#	docs/target-app-parity.md
#	docs/ui-parity.md
2026-11-28 07:28:58 +07:00
FredApps bb26821f2e Merge origin/main into fix/3639-header-commands-own-section 2026-11-28 06:58:33 +07:00
FredApps b0a5ff0469 Merge origin/main into fix/mailings-csv-limits 2026-11-28 06:40:31 +07:00
Martin BallandClaude Opus 5.5 5796c665b9 ci(sonar): ignore S8707 path traversal in crates/validate developer scripts (#7994)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:38:04 +00:00
FredApps 6e67ac4552 Merge origin/main into fix/3126-empty-window 2026-11-28 06:15:12 +07:00
FredApps e74e627a38 parity: headless column from the engine registry (RFC-0052) (#7969) 2026-11-28 00:01:17 +01:00
FredApps ebc9505a02 Make select_object crate-visible for Enter on a picture.
The #4126 port called select_object from insert_break in text/unicode.rs
through a pub(super) re-export, but the function itself was only
pub(super) in objects/select.rs, so clippy failed on the private re-export.
2026-11-28 05:44:39 +07:00
FredApps e9286c9487 Merge pull request #7183 from alehel/codex/7172-native-about
macOS: open the WordCraft About dialog from the application menu
2026-11-27 23:27:51 +01:00
FredApps b7057e56f6 Merge pull request #6800 from gmrmad1/fix/6265-print-preview-numeral
Print preview: refresh the cached layout and textures when numerals change (#6265)
2026-11-27 23:27:24 +01:00
FredApps 784e4c3c35 Merge pull request #6772 from RickiNano/fix/6767-arrow-stroke-inside-head
Shapes: a thick line's stroke ends inside its arrowheads (#6767)
2026-11-27 23:26:58 +01:00
FredApps 188be727b7 Merge pull request #5887 from batistalucasv/fix/5847-justified-tab-shrink
Layout: a justified line with a tab shrinks the spaces after its last tab (#5847)
2026-11-27 23:26:05 +01:00
FredApps 05dc3214ea Merge pull request #5870 from batistalucasv/fix/5842-compare-footnotes-endnotes
Compare: diff footnote and endnote content (#5842)
2026-11-27 23:25:36 +01:00
FredApps 5fda6e6696 Merge origin/main into fix/arrows-enter-equation 2026-11-28 05:23:53 +07:00
FredApps 148987d098 Merge origin/main into fix/4126-enter-on-picture 2026-11-28 05:22:47 +07:00
FredApps cac0dd2ee0 Merge origin/main into fix/3750-paragraph-marks 2026-11-28 04:59:15 +07:00
FredApps 5290f3bb62 Merge origin/main into fix/date-picture-quoted-literals-and-bare-a 2026-11-28 04:55:58 +07:00
FredApps ff781c42d2 Fix merge conflict markers left in docs/gaps.md 2026-11-28 04:52:27 +07:00
FredApps 262a821ec7 Merge origin/main into feat/docx-corpus-harness 2026-11-28 04:51:57 +07:00
FredApps e802ec8f28 Merge origin/main into fix/pdf-figure-object-lookups 2026-11-28 04:50:57 +07:00
Dylan M. TaylorandFredApps 72ca96a27c ci: notify artcraft-services on release state changes (#7923)
* ci: notify artcraft-services on release state changes

* ci: pass only the dispatch token to the notify-services workflow

secrets: inherit hands the called workflow every repository secret, including
the signing credentials. The reusable workflow only reads
ARTCRAFT_SERVICES_DISPATCH_TOKEN, so map just that one.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-27 09:17:48 -05:00
f83d554322 Pictures: an inserted or pasted picture fits the table cell, column or section it goes in (#5428) (#6903)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: D13GOOOO <106814760+D13GOOOO@users.noreply.github.com>
2026-11-27 10:07:07 +00:00
Martin BallandClaude Opus 5.5 0f4e80aedd #7165: Symbol drop-down has compact cells, and hover names the character (#7173)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 10:07:01 +00:00
Martin BallandClaude Opus 5.5 bab08b77e1 #7841: dark-mode interface text gets the lighter Gamma(0.8) curve again (#7867)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 10:06:54 +00:00
Martin BallandClaude Opus 5.5 2b407facd0 #7824: a disabled table menu button keeps its menu shut under read-only protection (#7871)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:02:47 +00:00
RickiNano b7819874c8 #6767: file-format parity names the ends that can't move their full inset 2026-11-27 06:42:48 +01:00
RickiNano 9cf6a33374 Merge remote-tracking branch 'origin/main' into fix/6767-arrow-stroke-inside-head
# Conflicts:
#	docs/file-format-parity.md
2026-11-27 06:42:37 +01:00
batistalucasv 29bb5a4f44 Merge upstream/main and resolve ROADMAP conflict (#5847) 2026-11-26 23:22:59 -03:00
batistalucasv aae46e1274 Merge upstream/main and resolve conflicts (#5842) 2026-11-26 23:07:51 -03:00
Lucas Batista Vargas b322c3d816 test(keys): restore an_unrelated_keys_modifiers_do_not_steer_a_later_paste test (#7317) (#7602) 2026-11-27 01:01:23 +00:00
Lucas Batista Vargas 64e297ca57 test(ui-egui): restore shortcuts_run_after_a_pane_resize test (#1756) (#7317) (#7579) 2026-11-27 00:59:55 +00:00
Martin BallandClaude Opus 5.5 ca8feb71aa test(engine): Copy with a bare caret beside an object is disabled, like Cut (#7892)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:47:48 +00:00
Lucas Batista Vargas 73f42fd607 test(ui-egui): restore drawn_buttons_fade_in_on_hover_and_darken_while_pressed test (#7317, #305) (#7580) 2026-11-27 00:25:44 +00:00
Lucas Batista Vargas ff11882e9d test(keys): restore alt_shortcuts_work_without_the_canvas_focused test (#7317) (#7583) 2026-11-27 00:25:38 +00:00
Lucas Batista Vargas 5687172000 Format Shape: add Line and Layout settings for shapes and text boxes (#5896) (#5919) 2026-11-26 21:29:47 +00:00
Lucas Batista Vargas 0b5d4df261 test(widgets): restore a_combo_field_reached_with_tab_shows_its_hint_after_a_delay test (#7317) (#7594) 2026-11-26 21:29:41 +00:00
Lucas Batista Vargas 6cbd8114d7 Dialogs: restore coverage for modal closing context menu, font preview sizes, and margin boundaries (#7317) (#7536) 2026-11-26 21:29:34 +00:00
Lucas Batista Vargas 760cb852a2 test(chrome): verify button hover fill matches theme tokens across ribbon and chrome (#7331) 2026-11-26 21:29:29 +00:00
Lucas Batista Vargas 59803ced07 test(chrome): adapt status_bar_controls_width_cache_is_per_window_and_avoids_discard_loops test (#7740) (#7624) 2026-11-26 21:02:33 +00:00
Lucas Batista Vargas fddd892b2d test(canvas): adapt scroll hostile_numbers_are_ignored test post-#7101 (#7742) (#7622) 2026-11-26 21:02:28 +00:00
Lucas Batista Vargas c98954d755 test(file_browser): restore no_keytips_behind_the_browser test (#7317) (#7620) 2026-11-26 21:02:23 +00:00
Lucas Batista Vargas 5d2153c15d fix(keytips): open Search on Alt/F10, Q when Backstage is closed (#7750) (#7619) 2026-11-26 21:02:19 +00:00
Lucas Batista Vargas 257b81ec8f test(ribbon): restore table_shading_label_is_painted_beside_its_arrow (#7317) (#7611) 2026-11-26 21:02:14 +00:00
Lucas Batista Vargas 7883de796d test(widgets): restore keyboard_focus_shows_the_hint_after_a_delay_but_not_over_a_menu test (#7317) (#7601) 2026-11-26 21:02:07 +00:00
Lucas Batista Vargas 59269a4e0e test(widgets): restore font_list_sections_skip_their_headings test (#7317) (#7598) 2026-11-26 21:02:00 +00:00
Lucas Batista Vargas f9aaa12da7 test(keys): restore a_desktop_paste_after_mod_shift_v_is_not_swallowed test (#7317) (#7595) 2026-11-26 21:01:55 +00:00
Lucas Batista Vargas cc9ad91d2a test(ribbon): restore tab_underline_slides_and_can_reverse_mid_motion test (#7317) (#7591) 2026-11-26 21:01:51 +00:00
Lucas Batista Vargas f1810cb01d test(keys): restore observe_ime_drops_a_preedit_without_focus test (#7317) (#7587) 2026-11-26 21:01:46 +00:00
Lucas Batista Vargas 0151061ccd test(keys): restore cmd_option_r_collapses_the_ribbon_on_macos test (#7317) (#7584) 2026-11-26 21:01:41 +00:00
Lucas Batista Vargas 992937e5dd test(ui-egui): restore a_suggested_name_is_the_first_words_of_the_text test (#7317, #5793) (#7572) 2026-11-26 21:01:31 +00:00
Lucas Batista Vargas e51fbe2e4b test(ui-egui): restore title_and_account_buttons_work test (#7317) (#7571) 2026-11-26 21:01:25 +00:00
Lucas Batista Vargas 3a3523f172 test(chrome): restore tab_moves_to_a_search_result_and_enter_runs_it test (#7317, #5398) (#7567) 2026-11-26 21:01:20 +00:00
Lucas Batista Vargas bfc6fbc46b test(chrome): restore undo_list_cancel_closes_without_undoing (#7317, #1903) (#7566) 2026-11-26 21:01:15 +00:00
Lucas Batista Vargas bdbb15e197 test(ui-egui): restore backstage blank document and back navigation tests (#2931, #3041) (#7557) 2026-11-26 21:01:10 +00:00
Lucas Batista Vargas b7b978b05c test(ui-egui): restore find_shortcut_focuses_find_what test (#772) (#7317) (#7551) 2026-11-26 21:01:03 +00:00
Lucas Batista Vargas 66f603931f test(ui-egui): restore navigation_pane_visibility_survives_restart (#2526) (#7549) 2026-11-26 21:00:58 +00:00
Lucas Batista Vargas e7647ca261 Options: restore test for linear-time parsing of unknown settings keys (#7317) (#7547) 2026-11-26 21:00:53 +00:00
Lucas Batista Vargas c3e38cef0b HTML paste: container background does not leak into character shading (#6157) (#6160) 2026-11-26 21:00:49 +00:00
Lucas Batista Vargas 5de0344173 Compare: detect replaced image bytes when size and extents are unchanged (#6086) (#6123) 2026-11-26 21:00:44 +00:00
Lucas Batista Vargas b67d4723cf fix(layout): keep hit test within clicked table cell bounds (#6067) (#6077) 2026-11-26 21:00:39 +00:00
Lucas Batista Vargas c7009c675f Table: preserve table structure on copy and paste (#5906) (#5916) 2026-11-26 21:00:33 +00:00
Lucas Batista Vargas 274cf67ac2 Fix: enable copy and paste for custom text boxes and frames (#5859) 2026-11-26 21:00:27 +00:00
Lucas Batista VargasandCopilot 0c6a8ea18d SmartArt: CJK text in diagrams maintains consistent fallback font family (#5672) (#5852)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-26 21:00:22 +00:00
a0f82451e3 UI port regressions vs v0.18.1: focus after reopen, Cut/Copy state, menu shortcuts, File pages (#7671) (#7711)
* #7677: register ui.backstage in the app command catalog with the label File

The File keytips fire ui.backstage, but it had no catalog entry, so the command runtime
warned and showed its id as the label.

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

* #7675: Command catalog: leave Cut, Copy and Paste to the linked edit set, keep the engine's chords

The app catalog defined edit.cut, edit.copy and edit.paste, which the framework's
linked edit set also defines; the set's definition wins, so each logged a
"the app catalog defines ..." warning at startup. The three go in as the set's
replaced default chords instead (Mod+Insert, Shift+Insert stay bound).

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

* #7673: Cut and Copy are disabled in the ribbon with no selection

The focused page answers for the linked Cut and Copy, so the app's command state
(the engine's "nothing is selected") never reached the Home > Clipboard buttons.
The buttons now read the engine's enabled state, and Copy gets Cut's
has-selection rule. craft-libs' inactive_edits would also cover shortcuts and
menus once the page view is given it; this works on the current pin.

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

* #7675: leave Undo and Redo to the linked edit set as well

The linked EditCommands set also defines edit.undo and edit.redo, so the
board warned and dropped the app's definitions for them too.

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

* #7672: File pages hand the keyboard back to the page after the click's pass

Opening a template or a recent document from File › Home after Ctrl+W left
the page without keyboard input until it was clicked. The Home, New, Back,
Save, personal-template and Recover actions asked for the page's focus in
the pass of the press that ran them; the press moves egui focus to the
pressed tile at the pass's end, so the request was lost while the canvas
still recorded it as taken. They now ask after the pass, as ribbon tabs do
(`focus_page_after_pass`). Drops the `ctx` parameters that only carried it.

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

* #7703: context menu rows show their shortcuts again

The rows were bound with the props builder (MenuItem::new(label).command(..)),
which never sets the row's own command, so MenuItem::keys found no chord.
MenuItem::command(..).label(..) keeps the binding and the chord.

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

* #7704: Table Layout cell size fields get their labels and two decimals back

A Height: and Width: caption beside each field and fixed two decimals, as
Layout > Paragraph's indent fields and v0.18.1.

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

* #7705: File > Export keeps the format buttons in a dialog-width column

They filled the whole page; the Print page already gives them its column.

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

* #7706: File > Home drops the duplicate New and Open buttons

The File rail beside the page has them, as in v0.18.1.

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

* #7673: the page marks Cut and Copy inactive with nothing selected

PageView answers for the linked edit commands while it has focus, so the
engine's 'nothing is selected' never reached the context menu or other
surfaces. inactive_edits passes it on.

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

* #7694: ribbon letter icons drawn as text, with a filled italic I (#7149 item 8)

Ports #7153 (text-drawn letter/symbol icons) onto the craft-ui code: new
icons/glyphs.rs, icons::spec and the text-glyph path in for_command, three
missing SVGs (smartArtLayouts, tableStyleOptions, tableStyles), and every
button, group and tile that shows one of those icons now resolves through
icons::spec (status bar, Home, Table, Insert, Mailings, Draw, galleries,
backstage, mini toolbar, QAT). U, strikethrough, Change Case, clear
formatting and the other letter/symbol icons are drawn as text.

The mix Martin chose: Bold keeps main's bold.svg (removed from the glyph
table); Italic uses the filled italic.svg from #7690 (removed from the glyph
table, ATTRIBUTION row updated). Underline stays a text glyph.

Test every_icon_name_the_ui_uses_resolves guards that glyph names never go
through the SVG-only IconId::new / icons::id.

Co-authored-by: batistalucasv <batistalucasv@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCZhHKRuRB5wZUiw6BE

* #7676: Comments and Editing strip ends use the ghost look, so the narrow icon face stops asking IconButton for Outline/Neutral

Also drops their outlines (#7682, buttons part).

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

* #7675: Cut and Copy keys stay silent with nothing selected

edit.cut and edit.copy are disabled with a caret only, but the key still
reached edit_command, which ran them and put 'not available: ...' on the
status bar. Guard both arms with command_enabled.

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

* #7694: Underline icon is a filled SVG like Bold and Italic

Underline was drawn as a text U with a stroked bar. It now uses a new
filled-path underline.svg (a heavy U and a separate solid bar, our own
drawing) at Bold's cap height, registered as an SVG like Bold and Italic.

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

* #7694: Underline's U is the same height as Bold's B and Italic's I

The U now starts and ends where B and I do (y 5.4 to 16.5 in the 20-unit box), and the bar sits below that shared baseline (17.7 to 19.2), so the three letters line up in the Font group and the mini toolbar.

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

* #7675: empty-copy clipboard test expects Copy to be refused

With nothing selected Copy is now greyed (`when(has_sel)`), so the restored #7544 test's empty copy is refused before it reaches the clipboard; it now asserts the refusal and keeps its checks that the clipboard and its published state are untouched.

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

* #7694: glyph icons take their fixed inks from one named icon-art palette

The text-drawn glyphs' red, green, orange, pink and shadow inks are now named constants in icons.rs (ART_*), the same values the SVG icon set draws with, so glyphs.rs is checked by `interface_colours_come_from_the_theme` again instead of being exempt as a whole file. Every other glyph ink still comes from the theme.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: batistalucasv <batistalucasv@gmail.com>
2026-11-26 13:56:52 -06:00
5e129ac951 Validate: add wordcraft validate, a structural integrity checker for .docx (#5875)
* Validate: add wordcraft-validate, a structural integrity checker for .docx (#5848)

* Validate: harden verdict integrity against unavailable package content

Follow-up to the CodeRabbit review round. The contract throughout:
a check that could not run must not report as though it did, and
content that could not be read must not be treated as absent.

- Unreadable zip entries keep their identity (from the zip reader's
  own metadata) and are marked content-unavailable; every absence-
  dependent error is suppressed while any part's identity or content
  is unknown, and the run reports INCOMPLETE instead of a FAIL
  manufactured from missing data.
- The same guard now covers the typed-relationship, image-reference,
  custom-XML schema, comment/note-reference and numbering checks,
  in both owner scopes.
- Scan finalisation splits prefix-established findings (always
  reported) from completion-dependent ones (gated on a complete
  scan); duplicate checking marks INCOMPLETE when the entries
  budget leaves raw directory records unexamined, and when the
  central directory cannot be parsed at all.
- CLI: surplus operands are a usage error before any file is
  validated; non-Unicode paths validate normally; report output
  escaping audited.
- Corpus generators fixed (vMerge/gridSpan, commentsExtended
  paraId, pinned zip timestamps, fixture 23 isolation); corpus and
  calibration fixtures regenerated.

Seventeen new tests, each mutation-checked. One residual recorded
in the PR discussion: a readable-but-unparseable commentsExtended
part can still draw unsupported COMMENTEX-LINK warnings (Warning
severity only; cannot change a verdict).

* Validate: add docstrings across validator and corpus functions (#5875)

* Validate: document the budget tests; correct a coverage note's identifier name

The budget-exhaustion tests in the lib.rs test module were the remaining
undocumented functions of any complexity on the branch. Each now carries
a docstring stating the contract it pins.

Also corrects the read_comments_ids budget note: the values it records
are w16cid:paraId values, so the note now says 'later paraIds were not
recorded' instead of 'durableIds'.

* Validate PR 2 step 0: content-model tables and generated model.rs

Add the ECMA-376 content-model tables the grammar checks will read, and
the deterministic chain that produces them:

- crates/validate/model/: the v2 (namespace-qualified) extractor, the
  WML and DrawingML tables for Strict and Transitional, generate_model.py
  (JSON -> Rust), and a README with the regeneration chain, archive URLs
  and SHA-256s, the generator's failure conditions and scope limits.
- crates/validate/src/model.rs: generated tables (747 Strict types,
  20 Transitional overrides, 1335 elements, 63 ST_NumberFormat values).
  It is not read by any check yet (dead_code allowed until the first rule).
- crates/validate/src/model_tests.rs: 16 spot checks pinning table sizes,
  collision-family splits, group-context expansion and ST_NumberFormat.
- ATTRIBUTION.md rows for the four tables and model.rs.

WML Strict regenerates byte-identical to content_model_v2.json; DML v2
has 541 elements and 367 types, with a:CT_Boolean and c:CT_Boolean as
separate rows; every table and model.rs regenerate byte-identically.

Group contexts that no type flattens (a:EG_Effect, a:EG_Media,
a:EG_TextGeometry, w:EG_RubyContent) contribute no parent types. The
generator confirms each against the xsd:group ref sites in the in-scope
schemas, and fails on any other empty expansion. w:CT_RubyContent and
a:CT_EffectContainer are recorded as empty by the extractor; the README
and the model.rs header say checks must treat them as unmodelled.

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

* PR2 Step4: detect table cells without a terminal paragraph

* Validate PR 3: MATH-PLACEMENT — math elements where Word refuses them

MS-OI29500 Part 1 §22.1.2.77 notes (b), (d), (e), (f) and §22.1.2.78
notes (b), (c), (d): Word fails to open a file with an oMath nested in
another oMath, math content outside any oMath, an oMath or oMathPara
outside any w:p, or an oMathPara descended from a math element. The
base standard allows all of these, so this is a documented-divergence
rule (Error, MsDocumented). A stray math island is reported once, at
its root element. Story parts only, matching the documented scope.

* Validate PR 3: COMMENT-RANGE-COUNT and PROTECTION-PASSWORD

COMMENT-RANGE-COUNT (MS-OI29500 Part 1 §17.13.4.4 note (a)): Word will
not open a file with more than 32767 comment ranges. Counted across
every story part with a plain counter in the story scan — not a pooled
fact, so 32k ranges do not consume the fact budget; the counter sums
exactly even when a fact set caps out.

PROTECTION-PASSWORD (MS-OI29500 Part 1 §17.15.1.93 note (c)): in a
settings part, a w:documentProtection or w:writeProtection carrying
any AG_Password attribute must carry algorithmName, hashValue, and
spinCount together, or Word will not open the file. Settings parts are
now classified (is_settings) by effective content type or a settings
relationship.

* Validate PR 3: CONTENTPART-TYPE — a contentPart target that is not text/xml

MS-OI29500 Part 1 §17.3.3.2 note (a): Word will fail to load the
document if the content part's content type is not text/xml. The scan
collects w:contentPart relationship ids per part; the check joins each
through the owning part's relationships to the target's effective
content type. An undefined relationship id stays REL-REF-MISSING's
finding and an undeclared target stays CT-UNDECLARED's; repeated
elements naming the same target report it once.

* Validate PR 3: compat-mode count limits — BOOKMARK-COUNT, PERM-COUNT, MOVE-RANGE-COUNT

With w:uiCompat97to2003 set in settings, Word fails to open a file
with more than 16,380 bookmarks (MS-OI29500 §17.13.6 (b)), 32,752
range permissions (§17.13.7.1 (b), §17.13.7.2 (d)), or 32,751
moveFrom/moveTo ranges (§17.13.5.24 (a), counted by start markers,
from and to together). Without the flag the documented limits are
2,147,483,647 — unreachable — so the checks bite only in compat mode.

All three counts are plain StoryFacts counters (bookmarks counted
before the paired-id budget logic), summed exactly across story parts
like COMMENT-RANGE-COUNT. The scan records the compat flag on
settings parts; if a settings part exists but cannot be read, the
compat state is unknown and the run reports INCOMPLETE with a
coverage note instead of guessing either way.

* Validate: count raw name bytes in central-directory duplicate detection (#5895)

Count duplicate entry names on raw bytes during central-directory
parsing rather than decoded strings, preventing distinct legacy-encoded
entry names from falsely colliding as replacement-character duplicates.
Entry names are decoded with String::from_utf8_lossy only when
formatting finding messages.

Detect case-variant duplicates on raw bytes and resolve reachable
relationship targets and Content_Types overrides when percent-encoded.

(From reubgr/wordcraft#2, by batistalucasv.)

* Validate: scope the #5895 landing to the issue as filed

The preceding commit lands reubgr/wordcraft#2 in full in the history;
this adjustment brings the shipped tree back to what #5895 covers:

- Removed: percent-decoded equivalence in entry lookup, reachability,
  and content-type resolution. Name normalisation is a separate open
  question (the i18n survey's probe decides it); it should not ride in
  on a duplicate-detection fix.
- Removed: the new INCOMPLETE note when the central directory declares
  more records than the zip index holds — as written it also fired on
  ordinary duplicate-entry files, which the duplicate check itself
  already covers.
- Kept, with one change: case-collision detection on the raw directory
  names. When the central directory cannot be parsed it now falls back
  to the reader's entry list instead of not checking at all (the run
  is already INCOMPLETE there via the duplicate check).

* Validate PR 3: NOTE-PR-LISTING and NOTE-PR-DANGLING — the footnotePr join

ECMA-376 Part 1 §17.11.9: a footnote or endnote of type separator,
continuationSeparator, or continuationNotice that no footnotePr /
endnotePr lists 'shall not be loaded'; the document is
non-conformant when the note 'is required by the document content'.
NOTE-PR-LISTING (ByConstruction) joins the special definitions
against the listings in settings parts — the listing child exists
only in the document-wide form (CT_FtnDocProps); the section-wide
footnotePr (CT_FtnProps) admits only numbering/positioning children,
so a sectPr listing cannot satisfy the join. Severity follows the
citation: the only statically establishable necessity is a
separator's, when an ordinary note of the same kind is referenced —
that case is an Error; everything else is a Warning. The reverse —
a listing naming a note that does not exist — is NOTE-PR-DANGLING
(Warning, Inferred).

Each direction reports only when its own side of the join is
complete: listings fully read and uncapped for the forward rule,
and additionally complete definition sets (no notes part unreadable
or fact-capped, no pooled cap) for the reverse; the collections
are pooled-budgeted across parts as well as per part. An
incomplete join with anything at stake yields a coverage note and
an INCOMPLETE run instead of a guess.

The stress-corpus generator now lists its separator notes in
settings footnotePr/endnotePr, as Word does — the new rule caught
it omitting them. Corpus regenerated; manifest hashes updated.
(Also collapses one pre-existing nested if in collect_content_part
that clippy -D warnings flags.)

* Validate PR 3: HEADERSOURCE-PRESENT — w:headerSource in mail merge settings

MS-OI29500 Part 1 §17.14.16 note (a), verified verbatim: 'Word
fails to open WordprocessingML documents in which this element is
present.' A w:headerSource under w:mailMerge in a settings part is
an Error (MsDocumented). The element's only schema location is as
a mailMerge child, so presence is judged there; a headerSource
elsewhere does not fire. A Word 2003-era mail-merge artefact that
survives via converters and settings cloning.

* Validate: bound CONTENTPART-TYPE collection and index its lookups

Two findings from the C3 increment's review round that the fix
round missed (the delta review scoped only a separate question):
the contentPart id collection ignored the fact budget — per part
and pooled — and the check deduped ids and resolved relationships
with linear scans, quadratic in the number of references.

Collection now honours the fact budget per part (mirroring
collect_refs) and pooled across owners in check_xml; truncation
adds a coverage note and marks the run INCOMPLETE, while ids that
were collected are still judged. Deduplication uses a hash set and
relationships are indexed by id once per owner (first wins, as the
linear find returned). Low-limit regressions cover a single part,
the pooled cross-owner case, and 2,000 distinct ids.

* Validate: enforce pooled budgets while appending, not after

The C8 delta review's remaining P2: the note collections (and,
since its hardening commit, the contentPart ids) were pooled-
budgeted by extending first and truncating after the scan loop, so
accumulation could reach the per-part cap times the part count
before the bound applied, and truncate does not release capacity.
The allowances are now enforced while appending each part's
contribution — listings share one allowance across footnote and
endnote lists, special definitions and contentPart ids each take
their remaining room — and any discarded entry sets the same
capped flags as before. Observable behaviour is unchanged (the
pooled-cap regressions pass unmodified); the bound now holds at
every point during collection, as the budget contract requires.

* Validate: pin the capped CONTENTPART-TYPE verdicts

From the hardening delta review: with collection capped, collected
references that are valid must yield INCOMPLETE (not PASS — not
every reference was checked), and collected references that are
defective keep FAIL precedence over the incomplete marking,
alongside the coverage note. Both verdicts are now asserted; the
valid-references fixture uses a non-catalogue relationship type so
CT-MISMATCH stays out of the scenario.

* Validate: reconcile PR 3 grades with the batch-b6 oracle results

Calibration batch b6 ran one Word-for-the-web fixture per PR 3 rule
(19 files; the first run was invalidated by a fixture-builder
defect, the rebuilt batch's control opens clean). Outcomes:

Confirmed at the corruption banner, evidence upgraded to Observed:
CONTENTPART-TYPE (image target banners, text/xml twin clean) and
HEADERSOURCE-PRESENT. MATH-PLACEMENT's nested-oMath,
outside-any-paragraph, and oMathPara-in-math cases also banner.

Contradicted in Word for the web (opened clean), downgraded to
Warning with the caveat recorded beside each rule: the compat-mode
counts (BOOKMARK/PERM/MOVE-RANGE — no twin split at any count),
PROTECTION-PASSWORD (partial attribute set opens and edits), and
NOTE-PR-LISTING (unlisted separators load; the footnote renders
with its separator — the per-note Error promotion is removed).
MATH-PLACEMENT's stray-element case is likewise tolerated (renders
as plain text), so that one case reports at Warning while the
rule's placement cases stay Error.

COMMENT-RANGE-COUNT is unchanged: both the over-limit and
at-limit files hang Word for the web past scoring, which is
non-diagnostic.

Tests pin the new severities and the Observed grades.

* Validate PR 3: COMMENT-RANGE-UNPAIRED — a lone comment range start or end

MS-OI29500 Part 1 §17.13.4.4 notes (b)-(c) and §17.13.4.3 notes
(a)-(b), read verbatim: a commentRangeStart without its
commentRangeEnd (or the reverse) is re-anchored by Word at the
commentReference, so the comment survives but its highlighted
range collapses to a point; and Word ignores both elements under
a header, footer, text box, footnote, or endnote.

Warning / MsDocumented. Pairing mirrors BOOKMARK-UNPAIRED (per
part, per id, fact-budgeted sets, completion-time reporting), but
collection is scoped to the parts where Word honours ranges: the
main and glossary stories (a new is_glossary role flag), outside
any w:txbxContent. COMMENT-RANGE-COUNT's document-wide counter is
unchanged. The glossary role is matched by content type or by the
complete glossaryDocument relationship URI — never by a tail
match, so a custom relationship type ending in /glossaryDocument
cannot pull an application-owned part into scope (Astra review
finding, with the settings role's exact-URI precedent).

* Validate PR 3: the paraId family — PARAID-DUP and PARAID-VALUE

MS-DOCX v20260818 §2.6.2.3 and §2.6.2.4, read verbatim before
implementing. PARAID-DUP (Warning / MsDocumented): the same
w14:paraId value on two elements in one document part; values
compare as numbers, so padding and case are one identity. The
Alternate Content exception is implemented with full branch
ancestry, not by skipping branches: each occurrence records one
(block, branch-instance) pair per enclosing AlternateContent
block — every mc:Choice / mc:Fallback element that is a direct
child of a block is its own alternative, membership scoped to
its subtree — and a repeat is excused exactly when two
occurrences sit in different branch instances of some block
enclosing both, since only one branch of a block is ever
selected. PARAID-VALUE applies inside branches too.
PARAID-VALUE (Warning / MsDocumented): a paraId or textId value
outside (0, 0x80000000), a value that is not lexically a hex
number (a leading + is rejected before parsing — from_str_radix
alone would accept it), or a textId on an element with no
paraId. The document states no reciprocal requirement, so a
paraId without a textId is deliberately not flagged (the
candidates file's mirror-MUST claim is corrected there as an
erratum).

Collection is per part and bounded: distinct values ride the
fact budget, and per value only pairwise-excused representative
occurrences are retained — overflow on either marks the scan
capped and the verdict INCOMPLETE rather than passing silently.
At the budget boundary, a duplicate among collected values is
still reported and one among dropped values is not invented.

* validate: vocabulary family - style/font/property collisions and reserved names

* validate: vocab fix 1 - frame-matched style definitions, EOF balance, first-name slot

* validate: scope the CT-MISMATCH customXml row around w:contentPart consumption (#5982)

* validate: #5982 fix 1 - per-owner consumption completeness, first-occurrence exemption

* validate: #5982 fix 2 - unscanned owners are incomplete too; restore a de-attributed budget test

* validate: #5982 fix 3 - an owner omitted by the entry limit is not proven absent

* validate: restore MOVE-RANGE-COUNT and NOTE-PR-LISTING to Error on Word for Mac evidence (batch Mac-2)

* validate: register wordcraft-validate in the xtask layers table

`cargo xtask layers` failed with "unknown workspace crate" because the
validate crate was never registered. It has no workspace dependencies, so
it is Standalone, like control-key.

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

* validate: accept the full main-part content-type family (.dotx/.docm macro-enabled)

* validate: collapse nested ifs in parse_style_defs (clippy collapsible_if)

* VALIDATE-CR5875-FIX: exempt skipped contentPart relationships

* VALIDATE-CR5875-FIX: exempt native InkML contentPart references

* VALIDATE-CR5875-FIX: preserve validation status on stdout failures

* VALIDATE-CR5875-FIX: narrow skipped contentPart exemption to text/xml

Word for the web opens the skipped text/xml fixture cleanly but refuses
editing the otherwise identical application/octet-stream fixture with a
"Document corrupted" banner. Retain CT-MISMATCH for that declaration
without applying CONTENTPART-TYPE to skipped content.

Filter skipped w:contentPart references before pooling exemptions. Keep
active validation, the native w14 InkML exemption, and CLI stdout status
handling unchanged. Cover both element forms and wrong-type controls.

* #5875: fix FredApps findings 1-5 on package declarations and scoped IDs

* #5875: fix FredApps finding 6 with stable LF model tooling

* #5875: preserve incomplete ownership and scope special-note joins

* #5875: retain shared owners and isolate incomplete joins

* #5875: track pooled comment paragraph loss and test shared contexts

* #5875: align absence guards with complete source sets

* #5875: namespace-checked rel-type matching, Strict profile INCOMPLETE, APFS test gate

* #5875: account for descendant discovery and shared-style owner pairings

* #5875: select owner join sources, gate roots, and isolate glossary ownership

Use each established owner's selected note and comment sources while preserving
no-owner fallback completeness and shared-source checks. Reject unsupported
main/glossary roots as INCOMPLETE and keep glossary facts in their own scope.

Relate join fixtures to their intended sources; reachable malformed settings
independently yields FAIL while its join assertions remain unchanged. Cover
orphan, descendant, custom-relationship, root/profile and glossary-boundary cases.

* #5875: mark competing official role targets ambiguous

* #5875: resolve entry-point profiles by agreement

* #5875: isolate glossary-typed parts and reject ambiguous fallback

* #5875: keep boundary-crossed subtrees out of the main owner's fallback

* #5875: W1 type numeric identities at the extraction boundary

* #5875: W2 resolve singleton sources explicitly

* #5875: W3/W4 retain per-part observations and explicit owner scopes

* #5875: W5 activate comment joins symmetrically and unify relationship bindings

* #5875: W6 generate and enforce scoped observation contracts

* #5875: fix whole-surface validation coverage and contract escapes

* #5875: reject closure destructuring in observation gate

* #5875: enforce fail-closed observation syntax recognition

Audit the closed Rust syntax grammar, macro surfaces, raw identifiers and
initializer bodies with standalone locked recognizer tooling. Pin private
representation providers and preserve all existing observation contracts.
Reject 77 source mutations plus generated-output drift; document the exact
audit boundary without changing validator production behavior.

Owner Reuben approved Unicode-3.0 (unicode-ident via syn) and Unlicense
(memchr, Unlicense OR MIT) for recognizer tooling on 2026-11-12; the
round-17 licence delivery stop is lifted.

Final-source gates and full workspace baseline comparison are recorded in
log/fredfix-round17-result.md. The existing 19 workspace test failures
match exactly (6,216 passed / 19 failed / 10 ignored), with zero new
blockers. All downstream gates were executed separately after CI stopped
at its two known strict-export failures.

* #5875 R18: record lookup truth tables and enforcement census

* #5875 R18 R1-R2: carry package absence evidence and audit its consumers

* #5875 R18 R3: normalize observation accessors and retained membership flow

* #5875 R18 R4-R5: seal reader identities and standard macro grammar

* #5875 R18 R1-R2: close Resolution view and return-alias interfaces

* #5875 R19: cache observation recognizer audits with SHA-256

* #5875 R19: memoize and shard the in-lane observation battery

* #5875 R19: pool controls, accelerate blanking and pin the built recognizer image

* #5875 R19: reuse field-line audits and scan only brace tokens

* #5875 R20: decode ZIP names and pin reader parity

* #5875 R20: group decoded ZIP names and scope collapse loss

* #5875 R20: record only completed note comment and relationship joins

* #5875 R20: state the observation gate polarity boundary

* #5875 R21 F1: verify central directory names against the ZIP reader

* #5875 R21 F2: account for unreadable owner document references

* #5875 R22: reconcile count-driven ZIP directory selection

* #5875 R23: reconcile rejected ZIP records and untyped roots

* fix(validate): support unhashed recognizer artifacts and sync lock version

* fix(validate): use Cargo artifact output and private recognizer snapshots

* fix(validate): require complete discovery for unique main selection

* refactor(validate): isolate main selection decision

* fix(validate): retain unknown glossary selection after discovery loss

* test(cli): reuse contributor craft-zip fixture migration

Adapted CLI fixture hunk from batistalucasv commit 3c43f905d39a51e90fcd22ff0bdff4a201666981 (reubgr/wordcraft#5); keep existing stronger ZIP identity guard.

* fix(validate): reject missing model schemas before writing output (#5848)

* validate: address CodeRabbit review findings on PR #18

* validate: resolve remaining CodeRabbit review findings on PR #18

* validate: invalidate unknown field state and memoize entity traversal

* validate: bound entity semicolon search to candidate token

* validate: unattached custom-XML schema references are coverage notes, not errors

Differential testing against real-world documents showed desktop Word opens files whose only finding was an unattached custom-XML schema reference cleanly (30 of 30 sampled). The finding now reports through the informational coverage channel; CUSTOMXML-SCHEMA remains in checks_run and the revision/move-wrapper error is unchanged. Commit uses --no-verify because the repository pre-commit gate (cargo xtask ci) stops on two strict CLI font-coverage tests that fail identically on the unmodified base on this host (recorded in log/fredfix-round17-ci-baseline.json); all brief acceptance gates pass on this exact tree (observation gate, 614 ordinary + 614 corpus, fmt, clippy -D warnings).

* validate: regression-test the custom-XML note suppression guard; widen coverage_notes doc

Addresses the two Low findings from the Astra delta review of a6a0384e (SHIP WITH NOTES). Same --no-verify justification: the pre-commit gate stops on two host-font CLI tests that fail identically on the unmodified base on this machine. Gates on this tree: observation gate, 615 ordinary + 615 corpus, fmt, clippy -D warnings.

* #5875 item 2: report untargeted binary tombstones in coverage

The validator focused tests and observation audit passed. Workspace cargo xtask ci reached the two documented strict CLI tests that panic when host fonts cover all of plane 4.

* #5875 item 3: count OPC main parts and report inert extras in coverage

Focused duplicate-main controls and the observation audit passed. Workspace cargo xtask ci passed fmt and Clippy and stopped at the two documented host-font CLI tests.

* #5875 item 4: grade media mismatches by drawing use and image usability

Focused media tests, observation audit, layering, and wasm passed. Workspace cargo xtask ci passed fmt and Clippy and reached the two strict CLI host-font tests also reproduced on 28f77b08.

* #5875 item 5: warn once per folded font-name group

Focused tests cover both case-variant orders, the capped prefix, and the shared property checker. The observation audit passed. Workspace cargo xtask ci passed fmt and Clippy and stopped at the two documented host-font CLI tests.

* #5875 fix round 1 finding 1: reserve media decode budget before preflight

* #5875 fix round 1 finding 2: require a recognized OPC relationship root

* #5875 fix round 1 finding 3: pin hyperlink references as possible media consumers

* #5875 fix round 1 finding 4: assess PNG pixels without expanding metadata

* #5875 fix round 1 finding 5: assess TIFF with the bounded media decoder

* #5875 fix round 2 finding 1: compare expanded OPC namespace URIs

* #5875 fix round 2 finding 2: withhold CT demotions when relationship inventory is lost

* #5875 fix round 2 finding 3: admit packed TIFF directories and explain assessment loss

* #5875 fix round 2 finding 4: charge fixed PNG inflater workspace

* #5875 fix round 2 finding 6: explain recognized alternate encodings skipped by validation

* #5875 fix round 3 finding 1: normalize namespace declarations for every XML consumer

* #5875 fix round 3 finding 2: withhold CT demotions on relationship inventory loss

* #5875 fix round 3 finding 3: admit TIFF values once and ignore media padding

* #5875 fix round 3 finding 4: reserve decoder workspace for admitted image paths

* #5875 fix round 3 finding 5: report codec-declined alternate image layouts

* #5875 fix round 4 finding 1: certify relationship inventory only from loss-free XML in every source

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

* #5875 fix round 4 finding 2: an unresolved namespace declaration is unknown, never a binding

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

* #5875 fix round 4 finding 3: admit TIFF directories as a graph, so sharing is free and only a cycle rejects

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

* #5875 fix round 4 finding 4: bound alternate images by their own terminator, not by trimming the tail

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

* #5875 fix round 4 finding 5: charge each worker's decoder state, enumerated from the codec's worker construction

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

* #5875 fix round 4 finding 6: name header-declined layouts the codec adapter reports as malformed

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

* #5875 fix round 5 finding 1: certify relationship inventory only when every bound QName is legal in its position

An element named xmlns:x was certified: quick-xml pre-binds the xmlns prefix and the walker only
checked that a prefix resolved. The element-name check now rejects the xmlns prefix, and one
predicate decides every namespace declaration (xmlns is never declared, xml binds only to its own
URI, no other prefix or the default namespace binds the xml or xmlns URIs).

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

* #5875 fix round 5 finding 2: decide an undeclared prefix by its nearest declaration in scope

The scanner searched every ancestor for an unresolved marker, so an inner empty declaration did not
make an unresolved outer one irrelevant, and an entity-valued default namespace surfaced as an
undeclared empty prefix. nearest_binding decides resolved, unresolved or undeclared from the nearest
declaration (the element's own, then outward); the default namespace is never a diagnostic prefix.
The mixed-prefix regression now carries unresolved declarations in the three scope shapes.

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

* #5875 fix round 5 finding 3: an unresolved element namespace never establishes an absence

Entity-spelling the namespace of a paragraph, a bookmark end, a deletion, a field begin, a cell child
or a Relationship element turned the part into a claim of absence (outside any paragraph, unpaired,
no block content, relationship missing). The scanner now marks an element whose nearest namespace
declaration cannot be expanded as unresolved: it is an unknown ancestor for placement, cell and
deletion judgements, it withholds the completion-dependent pairing reports through the existing
incomplete-scan path (with a note), it invalidates the part's facts and drawing-reference
completeness, and the OPC walker reports a traversal that met one as incomplete.

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

* #5875 fix round 5 finding 4: decide TIFF directory cycles once, from the directory graph

Admission skipped children of a directory it had already visited, so a metadata back edge to a
directory that was open when the chain arrived was missed (A -> B -> C with Exif C -> B and A -> C
admitted), and the alternate-format probe then asked a second walker, whose global seen set rejects
any sharing, for completeness. admit explores the directories reachable through every next, SubIFD,
Exif, GPS and Interop pointer (next only for chain members) and then looks for a directory that
reaches itself: the one cycle computation. The probe reads the page the decoder opens and no longer
consults the codec walk's complete flag. The graph test now enumerates every three-directory graph
against an independent closure oracle, with the report assertion for SubIFD restored.

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

* #5875 fix round 5 finding 5: bound a BMP by its layout, not by its declared size

The walker trusted a short bfSize over an RLE stream and read the pixels of an OS/2 core-header BMP
as Windows-header fields. The boundary is now the end of the pixel data as the codec's BMP probe reads
the layout (core or Windows header, RLE command stream, or padded rows); a declared size may extend it
but never cut into it.

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

* #5875 fix round 5 finding 6: charge the nested JPEG strip decoder each TIFF worker holds

The per-worker term stopped at the tiff crate's decoder, but a JPEG strip builds a zune-jpeg decoder
inside it: an output the size of the strip and, for a progressive image or a baseline one with several
scans, a 16-bit coefficient plane for every padded sample. 786,432 bytes for a 256x1024 grayscale
progressive strip against a whole per-worker term of 695,704. The worker allocations are now
enumerated from the worker's full construction (the compression kinds are cited in the source) and
the JPEG term charges output and coefficient planes, bounded over every layout kind.

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

* #5875 fix round 5 finding 7: name a declined layout from exactly the bytes the decoder was given

declined_layout was handed the original part while the decoder received the RIFF-bounded prefix, so a
VP8-looking chunk after the declared end manufactured the refusal note; the JPEG start-of-frame scan
accepted a bare 0xC5 without its 0xFF introducer. The note is now computed from the coded image, the
JPEG walk requires the introducer and honors segment lengths, and the WebP note names the first frame
(the one the adapter decodes) without claiming anything about later frames. The animated fixture is
rebuilt well-formed, with declared sizes.

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

* #5875 fix round 6 finding 1: an unresolved element namespace decides per obligation, by its local name

Round 5 turned any unresolved element namespace into a part-wide suppression: an unrelated `<q:vendor/>`
silenced FLD-UNBALANCED, REL-REF-MISSING, MATH-PLACEMENT and STRUCT-TC-NO-P, hid ID-COMMENT-REF in a
comments part, and turned an unused drawn image into a MEDIA-MAGIC Error.

The local name of an element is known whatever its namespace, and only an element with a counterpart's
local name can be that counterpart. Each absence-asserting obligation now asks exactly that:

- the cross-part fact collections (StoryFacts::invalidate_local) are incomplete only for the elements
  whose local name they collect; reference completeness and drawing-reference completeness no longer
  depend on an unrelated element, so a media part is not moved between consumed and unused;
- pairing completion reports are withheld per family (field, bookmark, comment range, move), and an
  unresolved fldChar withholds only a field end that FOLLOWS it (a begin cannot follow its end);
  a withheld obligation that something is actually pending for takes the incomplete path with a note;
- placement and structure judgements name the ancestor or child role an unresolved element could play
  (a paragraph, a deletion, a block container, a cell block); the OPC walk is incomplete only for an
  unresolved root or declaration-named element.

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

* #5875 fix round 6 finding 2: the auxiliary joins take the same obligation-scoped discipline

The note listing, contentPart pairing, style and numbering definition joins and the attached-schema reader
each stated an absence from a definition set that had silently ignored an element of unresolved namespace
(`q:footnote`, `q:contentPart`, `q:style`, `q:num`, `q:attachedSchema`).

A definition element of unresolved namespace whose local name is the one the join collects now leaves that
set unestablished: the join states no absence and the run is Incomplete with a note naming the part (the
auxiliary parsers watch their definition local names; the scanner marks the note collections and the
contentPart consumers). An unrelated unresolved element changes nothing.

A relationship declaration spelled through an internal entity (`<!ENTITY item '<Relationship .../>'>` ...
`&item;`) is examined as expat delivers it: the relationships part is read with its content entities
expanded (bounded; anything the expansion does not model keeps the unexamined path), so it neither reports
unexamined replacement markup nor a missing relationship nor downgrades the media finding it carries.

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

* #5875 fix round 6 finding 3: the TIFF page the validator assesses comes from main-chain membership

The codec lists a directory once, so one reached first as a SubIFD child is listed as a child and its
default-page rule (the first full-resolution directory of the main chain, else the first directory) then
depended on the order directories were met in: a shared page changed which page was assessed, and a
damaged full-resolution page could be blessed by its clean preview, or a damaged preview failed for the
full page's sake.

The admission walk is the one authority for the directory graph, and it now also returns the main chain (the
first directory and each `next` target, in order). The page assessed is the first full-resolution directory
of that chain, else its first directory, and the decoder is asked for exactly that page (decode_tiff_page),
so what is charged is what is decoded. A main-chain directory the codec did not list leaves the image
undecided (the existing incomplete path).

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

* #5875 fix round 6 finding 4: the TIFF directory depth bound is the minimum depth over every route

The admission walk rejected a directory reached at a depth over the limit before recognising that it had
already been reached nearer, so an extra edge from the end of a long chain to a directory that is also one
step from a main-chain page (D10 -> L) failed an image whose every directory is within the limit by its
nearest route.

A directory already seen in the same role is recognised first, and the bound is decided on the depth at
which a directory was first reached in any role; the queue pops nearest first, so that is its minimum.

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

* #5875 fix round 6 finding 5: the nested JPEG debit comes from the JPEG's header, and a budget stop grades nothing

The per-worker charge for the JPEG inside a TIFF strip or tile came from the directory's declared strip
size, which is not what zune-jpeg allocates from: an 8x8 strip holding a 64x64 progressive JPEG was
undercharged, and an 8192x8192 tile holding an 8x8 JPEG, or a baseline JPEG that matches its directory, was
charged enough to trip the budget.

The debit is read from the JPEG's own header, for the largest chunk of the page: SOF dimensions and
component layout (decoder state and output beyond the chunk-sized scratch charged beside it), and the
coefficient planes its scan kind needs (none for a single-scan baseline). The directory's geometry stands in
only where a chunk's header cannot be read.

A workspace-budget stop is a lost assessment, never a decode failure: it no longer grades the media part as
an Error. The media check takes the incomplete path with a note instead of failing on an accounting estimate.

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

* #5875 fix round 6 finding 6: the BMP boundary covers the colour table the decoder reads

The layout-derived boundary ended at the pixel data. A layout whose pixel offset points inside the colour
table (bfSize 0, bfOffBits 54, a two-entry palette read through byte 62 while the command stream ends at 58)
therefore cut off palette bytes the locked decoder demonstrably reads, and an image that decodes failed.

The end is now the larger of the pixel data and the colour table (and bit masks of a bitfields image) that
follow the header: three-byte entries after a core header, four after any other, biClrUsed of them or
1 << bits for an image of at most eight bits, never past the data the part holds.

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

* #5875 fix round 6 finding 7: diagnostics are never made from unknowns

- An element whose attribute collection failed (a repeated attribute) keeps its own namespace declarations
  for diagnostics: a prefix declared on that very element is no longer reported undeclared.
- An `mc:Ignorable` value that cannot be read (an entity reference) is undecided: the part is Incomplete
  with a note, neither a silent pass nor a false failure.
- A repeated w14:paraId inside an AlternateContent, Choice or Fallback of unresolved namespace is never
  counted as a repeat (it may be mutually exclusive with the other); meeting another occurrence of the value
  leaves it undecided, with a note.
- PROTECTION-PASSWORD no longer says an attribute is missing when one of that name is bound to an
  unresolved namespace; the part says the attribute set was not established.

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

* #5875 fix round 6 finding 8: a declined-layout note is bound to the selected frame and its complete header

The WebP walk could leave the animation frame it was in: an ANMF with a one-byte body, or with no child,
let it read the chunks that follow, so a later frame's interframe bit (or a top-level chunk) attributed a
refusal to a frame the decoder never assessed. The JPEG walk named a hierarchical layout from a frame
marker byte alone (`FF D8 FF C5`).

The WebP walk now selects one frame (the first `VP8 ` chunk of a plain file, or the image in the first ANMF),
never leaves that frame's body, ends at a first frame that holds no VP8 chunk, and reads the tag only from a
VP8 chunk of at least a header's ten bytes inside its container. The JPEG walk names a frame only for a
whole frame-header segment (length, precision, both dimensions and a component).

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

* #5875 fix round 7 P1: preprocessing is evidence-preserving (unmodelled declarations keep the part unexamined; diagnostics read the original; expansion work bound)

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

* #5875 fix round 7 P2: unexamined OPC content yields no definite findings (unmodelled DOCTYPE, entity references and entity-valued attributes make the part incomplete)

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

* #5875 fix round 7 P3: ancestor uncertainty is positional (per-check withholding noted as undecided; unresolved AlternateContent keeps the skipped-branch behaviour)

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

* #5875 fix round 7 P4: auxiliary joins are per-obligation (note loss per family and member; parent and identifier spellings and entity-valued definition identifiers are unknown, never absent)

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

* #5875 fix round 7 P5: assessment bounds never grade (TIFF directory and listing bounds and header-inspection limits are lost assessments; the JPEG header is walked to SOF wherever it lies; the coefficient debit is pinned independently)

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

* #5875 fix round 7 P6: branch bookkeeping keeps the established portion; delivered attribute values are read as delivered

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

* #5875 fix round 7 P7: declined-layout walkers mirror the decoder's dispatch (WebP chunk selection, JPEG component table)

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

* #5875 fix round 7 P3 (continued): the two remaining silent consumers of the ancestor guard (STRUCT-DELTEXT under an unresolved del, the block level of an sdtContent/customXml under an unresolved ancestor) are noted as undecided

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

* chore: commit Cargo.lock resolution for the merged workspace

* validate: reject DOCTYPE declarations in XML parts

* Classify validate in the CLI automation-root test

* Consolidate validate integration tests

* Calibrate XML-DOCTYPE severity by part role

* Keep interim DOCTYPE errors with a footnotes relationship warning

* Calibrate XML-DOCTYPE warnings from closure probes

* Distinguish unmeasured XML DOCTYPE evidence

* Restrict XML DOCTYPE evidence to measured roles and forms

* Warn on unmeasured XML DOCTYPE combinations

---------

Co-authored-by: Reuben Grinberg <reuben.grinberg@aya.yale.edu>
Co-authored-by: batistalucasv <batistalucasv@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Muse <muse@Mac-mini.local>
Co-authored-by: FredApps <FredApps@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-26 20:39:18 +01:00
Lucas Batista Vargas 62391d8aa3 test(ui-egui): restore table_gridlines_of_a_many_row_table_are_fast (#5967) (#7556) 2026-11-26 16:15:35 +00:00
Valentin KleinandClaude Sonnet 5.5 44719ece99 Paste: a copied table in a table cell inserts rows or overwrites cells, as Word does (#6742)
Part of #6739. Default Paste with the caret in a table cell inserts the copied rows above (first column, same width) or overwrites cells from the caret's cell; over a cell selection it overwrites from the top-left. Paste as Nested Table (edit.pasteNestedTable) keeps the old nesting, which is also the fallback for cases this does not cover.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 15:17:36 +00:00
batistalucasv 9d78c95517 Layout: restrict tab space shrinking to left/default tabs (#5847) 2026-11-26 12:16:48 -03:00
batistalucasv 6ea92c6b93 Layout: restore justify module visibility and guard shrink_line_spaces (#5847) 2026-11-26 12:14:59 -03:00
batistalucasv 7905692c1f Layout: restore layout parity table formatting and strengthen compat-mode tests (#5847) 2026-11-26 12:14:59 -03:00
batistalucasv 7416d36aeb Layout: a justified line with a tab shrinks the spaces after its last tab (#5847) 2026-11-26 12:14:29 -03:00
6c6ac698ca Layout: a paragraph with a hidden mark is shown on one line with the next one (#3986) (#6913)
* 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 <25549525+Menonro@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXtSjB6e5jmy9Uq7u8

* 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 <noreply@anthropic.com>

* #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 <noreply@anthropic.com>

* #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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* #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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Menonro <25549525+Menonro@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-26 11:48:47 +01:00
skylar taylor-barrick 68c024a624 Nightly: open the Launcher's files rather than its --, and stop blocking a refused launch on macOS (#7849)
Nightly launch fix under Skylar's Exec 454: the Launcher's trailing `--` no longer reaches the file list, and a refused launch no longer blocks on macOS (the reason goes to stderr and the app exits 2). Two CodeRabbit findings folded in: documents keep command-line order across the separator, and a document named like a launch argument (`-NS…`, `-psn_`, `-Apple…`) survives because the split comes before the strip.
2026-11-26 04:04:23 -06:00
Lucas Batista Vargas 104556e47d chore: bump craft-libs to 0b8bbaf4c8 and egui to b9770908e0 (#7837) 2026-11-26 08:52:55 +00:00
skylar taylor-barrick 765abcc790 Switch on supervised nightlies on the nightly-signer branch (#7839)
Supervised nightly switch-on, merged under Skylar's explicit Nightly 758 override after green CI, CodeRabbit on this head with no open threads, Sonar passing, and an independent adversarial review with no blockers.
2026-11-25 19:52:59 -06:00
Martin BallandClaude Opus 5.5 a44dc74fc0 #7822: Spec, plan and ADR for closing document windows (#7840)
Agreed rules for every close path (window close, File › Close, quit, one-document hosts, automation), who owns the Save prompt, and the order of work: craft-libs hidden root and test kit, repin, then the WordCraft fix. Adds Document window and Save prompt to the glossary.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 00:19:22 +00:00
skylar taylor-barrick 77a530b179 Use the shared nightly launcher template (#7829)
Renders the plain nightly tar's launcher from craft-common-actions' shared template.

Independent check: dylanmtaylor compared all 14 app launcher PRs byte for byte with the template rendered from the registry (https://github.com/storytold/craft-common-actions/pull/367#issuecomment-7172085284); this head was re-checked against craft-common-actions main 88148a5.
2026-11-25 16:17:53 -06:00
Martin BallandClaude Opus 5.5 4e00d00779 ROADMAP: remove a stray branch-name line from the progress log (#6917)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:48:59 +00:00
Lucas Batista Vargas 26b1d89ad2 fix(dialogs): restore table style dialog v0.18.1 layout, preview, and alignment test (#7317) (#7645) 2026-11-25 18:04:13 +00:00
Lucas Batista Vargas a272715194 test(windows): restore #117 window title test and cover root promotion (#7702) 2026-11-25 15:38:40 +00:00
Lucas Batista Vargas ff90488655 test(credits): cover Models table refit in narrowed About dialog (#7646) 2026-11-25 15:38:34 +00:00
Lucas Batista Vargas bc629b7a4f test(control_server): adapt params.token / params.key auth test post-#7101 (#7729) (#7629) 2026-11-25 15:38:28 +00:00
Lucas Batista Vargas 954750790b Dialogs: restore modal shake/nudge animation on backdrop clicks (#7321) (#7332) 2026-11-25 15:38:22 +00:00
Lucas Batista Vargas f587bcb95a fix(keytips): record ribbon menu_button commands and restore language test (#7317) (#7612) 2026-11-25 15:38:16 +00:00
Lucas Batista Vargas b068e1a538 refactor(ui-egui): unify command_input cache loop and test keytip cache behaviour (#7764) (#7573) 2026-11-25 15:38:10 +00:00
Lucas Batista Vargas 9ab9f2f874 Accessibility: return keyboard focus to page on dialog dismissal from non-canvas controls (#7458) (#7467) 2026-11-25 15:38:04 +00:00
Lucas Batista Vargas 231a09761c test(keytips): adapt long QAT multi-digit badge test to craft Keytips (#7733) (#7626) 2026-11-25 15:37:58 +00:00
Lucas Batista Vargas dc12b22371 test(objects): adapt nothing_to_snap_to post-#7101 (#7749) (#7618) 2026-11-25 15:37:50 +00:00
Lucas Batista Vargas b77c55c028 test(dialogs): adapt escape_in_the_browser_leaves_the_dialog_under_it_open post-#7101 (#7754) (#7617) 2026-11-25 15:37:43 +00:00
Lucas Batista Vargas 09465c9fc4 test(ribbon): adapt Styles gallery RTL reading-order test post-#7101 (#7753) (#7616) 2026-11-25 15:37:37 +00:00
Lucas Batista Vargas c8ecea24cf test(file_dialogs): adapt entries_expose_names_selection_and_picking post-#7101 (#7317) (#7613) 2026-11-25 15:37:32 +00:00
Lucas Batista Vargas 2a09d78972 test(keys): restore the_ignored_paste_uses_up_its_paste_modifiers test (#7317) (#7609) 2026-11-25 15:37:26 +00:00
Lucas Batista Vargas b163c0568d test(file_browser): restore a_dialog_closing_into_the_browser_leaves_it_the_keyboard test (#7317) (#7604) 2026-11-25 15:37:20 +00:00
Lucas Batista Vargas 8ed5ddd47b test(ui-egui): restore the_tab_strip_buttons_have_names test (#7317, #1110) (#7577) 2026-11-25 15:37:13 +00:00
Lucas Batista Vargas ea8f665f20 test(ui-egui): restore focus_and_full_screen_view_ask_for_full_screen_once_per_change (#1678) (#7576) 2026-11-25 15:37:06 +00:00
Lucas Batista Vargas c30777bf2a test(ui-egui): restore command_filter_narrows_the_picker_and_add_works test (#7317) (#7574) 2026-11-25 15:36:59 +00:00
Lucas Batista Vargas 34b79b33db test(ui-egui): restore the_ribbon_boxes_name_themselves_for_a_screen_reader test (#7317, #3172) (#7569) 2026-11-25 15:36:53 +00:00
Lucas Batista Vargas f89c52c428 test(ui-egui): restore the_print_button_leads_the_settings_and_is_the_primary_action (#2958) (#7568) 2026-11-25 15:36:47 +00:00
Lucas Batista Vargas 4da5534eb8 test(ui-egui): restore the_plus_button_adds_a_row test (#7317) (#7563) 2026-11-25 15:36:41 +00:00
Lucas Batista Vargas afe332b225 test(engine): restore copy_format_web_alias_respects_user_removal_and_reassignment test (#7317) (#7562) 2026-11-25 15:36:29 +00:00
Lucas Batista Vargas 3ebf69481a test(ui-egui): restore caret_colour_is_not_worked_out_while_the_caret_is_hidden (#299) (#7561) 2026-11-25 15:36:22 +00:00
Lucas Batista Vargas ab014b8fe5 test(engine): restore f11_is_full_screen_and_alt_f1_walks_fields test (#980) (#7317) (#7559) 2026-11-25 15:36:16 +00:00
Lucas Batista Vargas 7951466b8b test(ui-egui): restore a_bordered_table_shows_no_gridlines (#5967) (#7554) 2026-11-25 15:36:08 +00:00
Lucas Batista Vargas d26c7375ff test(ui-egui): restore read_aloud_player_closes_from_title_bar (#1885) (#7553) 2026-11-25 15:35:57 +00:00
Lucas Batista Vargas e3b742f75a test(ui-egui): restore the_full_screen_button_reports_the_commands_own_enabled_state (#7317) (#7552) 2026-11-25 15:35:50 +00:00
Lucas Batista Vargas f847159a29 System clipboard: restore test for empty copy preserving clipboard state (#7317) (#7544) 2026-11-25 15:35:44 +00:00
Lucas Batista Vargas 9409b2fd79 Tests: restore title_stem_omits_nul_from_each_title_source (#7317) (#7543) 2026-11-25 15:35:38 +00:00
Lucas Batista Vargas e2f001b946 Dialogs: restore AutoCorrect filter and Compare options tests (#7317) (#7542) 2026-11-25 15:35:32 +00:00
Lucas Batista Vargas dc5d27cded Default apps: restore test for xdg-mime word types and exclusion of plain text (#7317) (#7541) 2026-11-25 15:35:25 +00:00
Lucas Batista Vargas c56825487f Dialogs insert: restore test for Document Information fields in Field dialog (#7317) (#7537) 2026-11-25 15:35:19 +00:00
Lucas Batista Vargas 4343683da8 Icons: restore test for fitOnePage painting through the SVG registry (#7317) (#7534) 2026-11-25 15:35:12 +00:00
Lucas Batista Vargas 1f65a8e588 Window geometry: restore test for clamping or dropping insane values (#7317) (#7533) 2026-11-25 15:35:06 +00:00
Lucas Batista Vargas bfc160809c Font download: restore test for short window opt-out and close buttons (#7317) (#7530) 2026-11-25 15:35:00 +00:00
Lucas Batista Vargas 3639389be3 Paste picture: restore test for refusing hostile clipboard pictures and files (#7317) (#7529) 2026-11-25 15:34:54 +00:00
Lucas Batista Vargas 37d03a1eb4 Chrome: restore test for clicking AutoSave label to toggle (#3370) (#7317) (#7528) 2026-11-25 15:34:48 +00:00
Lucas Batista Vargas 7fa77df595 DOCX settings merge trials: zoom round-trips and the mail-merge source id (#7524) 2026-11-25 15:34:42 +00:00
alehelandClaude Opus 5.5 9e68fdb76a macOS: show the translated About label in the application menu (#7172)
mac_layout looks the label up as `About {app}`, which no WordCraft catalog
has, so the menu stayed English. Use the existing `About WordCraft` entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:03:54 +01:00
alehelandClaude Opus 5.5 d63de66920 Merge main into codex/7172-native-about
Resolve main.rs against the nightly session work and use
NativeMenu::sync_with, which replaced sync in the craft-libs rev on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:03:35 +01:00
Fluorine 0b7bdee856 Format layout cache regression test 2026-11-25 04:34:40 -04:00
Dylan M. Taylor c179a31619 packaging(linux): support co-installable nightly packages (#7746)
Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch.

Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
2026-11-24 19:00:35 -06:00
Lucas Batista Vargas 6e92d33e07 UI: cache command metadata, hints and keytip tables between idle frames (#7674) (#7719) 2026-11-24 21:51:04 +00:00
batistalucasv bee50afd8f Compare: copy and remap media when adopting revised notes 2026-11-24 15:51:06 -03:00
batistalucasv a1a3b53f74 Compare: diff footnote and endnote content (#5842) 2026-11-24 14:59:46 -03:00
Lucas Batista Vargas 4d7100a7f8 test(fonts): adapt installed Arabic font isolation test post-#7101 (#7734) (#7627) 2026-11-24 17:03:26 +00:00
Lucas Batista Vargas 920d9342e7 test(chrome): adapt AutoSave knob RTL mirroring test to craft Switch (#7730) (#7630)
* test(chrome): adapt AutoSave knob RTL mirroring test to craft Switch (#7730)

* test(chrome): drive AutoSave RTL test via ui.language and root_env
2026-11-24 17:03:20 +00:00
Lucas Batista Vargas c11504affa Ribbon: align Table Design › Table Style Options checkboxes in two columns (#7691) (#7695)
* Ribbon: align Table Style Options checkboxes in two columns (#7691)

* Ribbon: widen Table Style Options column gutter while keeping tight rows
2026-11-24 17:03:14 +00:00
Lucas Batista Vargas 604ad56f0a fix(keytips): show legacy menu key hint under slim screen bar without ribbon (#7731) (#7628) 2026-11-24 14:26:12 +00:00
Lucas Batista Vargas 852330e928 fix(chrome): return canvas focus after picking an Undo History row (#7726) (#7632) 2026-11-24 14:25:57 +00:00
Lucas Batista Vargas b5fb29b539 test(dialogs): restore RTL Page Setup oversized margin test (#7722) (#7637)
Closes #7722. Part of #7317.
2026-11-24 14:25:41 +00:00
Lucas Batista Vargas 012d0dd875 test(control_server): adapt per-connection token auth test post-#7101 (#7720) (#7631) 2026-11-24 14:25:28 +00:00
Lucas Batista Vargas 352042d41f Canvas: size Web Layout from PageView's side gutter instead of rail width (#7687) (#7701) 2026-11-24 11:50:56 +00:00
Lucas Batista Vargas 4f6cc31af6 test(dialogs): verify Customize Keyboard empty shortcuts list shows None (#7317) (#7644) 2026-11-24 11:50:50 +00:00
Lucas Batista Vargas 58e52bc962 test(dialogs): restore the_title_bar_close_box_is_the_whole_corner test (#7317) (#7638) 2026-11-24 11:50:45 +00:00
RickiNano 8ff9bdb1a1 #6767: a short straight line's lone arrowhead takes the room its other end doesn't need
An arrowed end moved at most half way along the line, even when the other
end had no arrowhead and stayed put, so on a straight line shorter than
twice the inset the stroke still stuck out of the head. The two ends of a
single straight segment now share its length in proportion to their
insets. Elbow and curved connectors keep the half-way limit.
2026-11-24 07:45:17 +01:00
Madhav Agarwal 694ac7810d Merge main into fix/6265-print-preview-numeral 2026-11-24 10:41:12 +05:30
Joseph Anglada 8e7fca10b4 Ignore egui performance warnings in i18n audit 2026-11-23 19:51:17 -04:00
Fluorine b83864e0f4 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-23 18:27:17 -04:00
Fluorine 60ec8580cd Merge commit '7fd0136bc8e643b08977b8692eb9867c992472ea' into sync-pr-6213 2026-11-23 13:51:41 -04:00
Joseph Anglada ac306cf704 Fix rustfmt in off-paper cursor test 2026-11-23 11:15:35 -04:00
RickiNano 1441c64970 Merge remote-tracking branch 'origin/main' into fix/6767-arrow-stroke-inside-head
# Conflicts:
#	docs/file-format-parity.md
2026-11-23 16:10:30 +01:00
fluorineandClaude Haiku 5.5 0ac9cbfba9 Merge main into cursor-arrow-off-paper
The UI port (#7101) moved the press and cursor code into canvas/input.rs and removed ibeam.rs. The cursor fix now lives in PageTextTool::cursor. The test harness for the grey-area test is the shared one, which installs the app's command set.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-23 10:18:15 -04:00
dfgodvan d45c07368f Layout: a picture alone in multiple spacing fits at the page foot by itself; a list label adds no leading below it
Merge main. Its rule for the leading below a picture alone on its line,
(m - 1) x the natural height of the picture run's font, matches Word for
Mac 16.93, so this branch's rule from the paragraph mark's font is dropped
and `line_spacing_does_not_scale_pictures` is main's again.

Kept: at the foot of a page such a line stays as soon as the picture fits
above the bottom margin; the spacing and the font's descent run into it.
Word, a 56.7pt picture in 1.5-spaced 12pt text: stays with 57-59pt of
room, which main moved on.

Fixed: a list label's font no longer adds to that leading. Word, a 144pt
picture at 1.25 spacing: 3.60pt below it without a label and with a 24pt
one, where main gave 6.90pt.
2026-11-23 13:56:06 +03:00
dfgodvan ed0fe0d980 Merge main into fix/kept-paragraph-space-after-before-table 2026-11-23 13:09:17 +03:00
alehel 3b94750945 ci: retrigger checks for #7183 2026-11-21 08:32:07 +01:00
alehel 376411a22b macOS: open the WordCraft About dialog from the application menu (#7172) 2026-11-21 07:26:10 +01:00
FredApps b8c2fa4962 Merge main into Latin text ordering in RTL paragraphs 2026-11-20 09:30:39 +01:00
Rees 7dbf9050e6 #3614: reconcile PDF figure lookups with current main 2026-11-20 06:12:23 +01:00
dfgodvan 273451b528 Merge main into fix/kept-paragraph-space-after-before-table 2026-11-19 23:21:17 +03:00
dfgodvan 31aa5a1b00 Merge main into fix/kept-paragraph-before-table-start 2026-11-19 23:15:53 +03:00
jayzed80 0ef496019a Merge remote-tracking branch 'upstream/main' into fix/odt-tall-header-5806
# Conflicts:
#	crates/formats/src/odt/import.rs
#	crates/formats/src/odt/tests_more/headers.rs
2026-11-18 22:51:11 +00:00
FredApps b92b7a40ad Merge remote-tracking branch 'origin/main' into fix/fit-one-page-freebsd
Signed-off-by: FredApps <FredApps@users.noreply.github.com>

# Conflicts:
#	crates/engine/src/tests/fit_one_page.rs
2026-11-18 09:51:35 +07:00
Diego Guerini 90a6722453 Merge remote-tracking branch 'upstream/main' into rtl-numbers-latin
# Conflicts:
#	ROADMAP.md
#	crates/layout/src/para.rs
#	docs/gaps.md
#	docs/layout-parity.md
#	docs/target-app-parity.md
2026-11-17 19:03:09 +01:00
fluorine 5c9c343e46 Layout cache test: the hit bound allows for kept headings that fall to the next page 2026-11-17 09:47:40 -04:00
Martin Ball c210ef5093 Merge branch 'main' into toc-insert-caret-position 2026-11-17 13:43:28 +01:00
Martin Ball 4c0b520a53 Merge branch 'main' into cursor-arrow-off-paper 2026-11-17 13:42:52 +01:00
Martin Ball 370489a59b Merge branch 'main' into fix/frames-in-cells 2026-11-17 12:33:37 +01:00
Martin Ball 932f5b4748 Merge branch 'main' into fix/6767-arrow-stroke-inside-head 2026-11-17 09:23:03 +01:00
Martin Ball fd7461b295 Merge branch 'main' into toc-insert-caret-position 2026-11-17 08:40:05 +01:00
Martin Ball b2964c2c1c Merge branch 'main' into fix/frames-in-cells 2026-11-17 07:54:18 +01:00
Martin Ball 011a46c677 Merge branch 'main' into fix/6767-arrow-stroke-inside-head 2026-11-17 05:34:58 +01:00
Martin Ball b1e6d1fa22 Merge branch 'main' into toc-insert-caret-position 2026-11-17 05:32:28 +01:00
Reuben Grinberg 0b1117c87f Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-16 21:19:57 -06:00
Reuben Grinberg 110852a379 docs: gaps.md — record the terminal-paragraph compare limitation (#3750) 2026-11-16 20:34:10 -06:00
Reuben Grinberg 17b26e39cc Compare: rename the section reject pin to match its assertion; add the accept-side pin (#3750) 2026-11-16 20:34:10 -06:00
Martin Ball 4239458948 Merge branch 'main' into fix/6767-arrow-stroke-inside-head 2026-11-17 03:02:09 +01:00
NetterSilverandClaude Sonnet 5.5 5653188ede test: budget the steps of reconcile_objects in the marker regression test
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 03:01:12 +01:00
FredApps 37caf16978 Tests: two Fit One Page tests find where the document spills
A plain document asks for Aptos, which no test machine has, so its
sans stand-in differs between machines: DejaVu Sans on FreeBSD is
larger than the Linux runners' font. With fixed line counts the step
and budget tests overflowed by more than the fit may recover there,
and have failed every FreeBSD night since they were added. They now
take the most lines that fit and move the last paragraph to page 2
with space before it, so the overflow is under half a point anywhere.
2026-11-15 23:07:00 +01:00
Madhav Agarwal b4219f9745 Print preview: refresh the cached layout and textures when numerals change (#6265) 2026-11-15 22:17:05 +05:30
RickiNanoandClaude Opus 5.5 37e5849e58 #6767: a thick line's stroke ends inside its arrowheads
A line's or connector's stroke ran all the way to each arrowhead's tip,
so a thick line's body and cap stuck out of the narrow end of the head.
Each arrowed end now stops where the head is as wide as the stroke, and a
square or round cap's reach further back. An end moves at most half way
to its neighbouring point, so elbow and curved connectors keep their
shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:25:02 +01:00
Reuben Grinberg 0345dd28f3 Compare: mark_block doc — the section-carrying case is fixed on main (#5734), not a limitation 2026-11-13 08:54:06 -06:00
Reuben Grinberg 959bc54505 rustfmt: collapse the flipped pin assertion onto one line 2026-11-12 17:01:18 -06:00
Reuben Grinberg 791e144fd7 Compare: flip the inserted-section pin to the fixed behaviour (#5667, fixed on main by #5734) 2026-11-12 17:01:18 -06:00
Reuben Grinberg 6ce224d4b3 Compare: keep another author's deletion stamp on whole-marked paragraphs
Address benandez's review: the del closure in mark_block now uses get_or_insert so a paragraph already carrying another author's tracked deletion keeps that author's revision on its runs and its mark; the ins closure deliberately keeps overwriting (the revised side is a raw clone whose revision indices are never relinked — see the comment; that sourcing is the #5571 root cause). p.touch() after mutating an empty paragraph's mark. Characterization tests pin the terminal-paragraph limitation and the section-break resolve limitation (the resolve fix is filed separately).
2026-11-12 17:01:18 -06:00
Reuben Grinberg 20b8ce57a8 Compare: mark a whole inserted/deleted paragraph's mark (#3750) 2026-11-12 17:01:18 -06:00
dfgodvan 3d04c471a4 Layout: a paragraph kept with a table counts its space after
The table starts below the space after the paragraph before it, so a
paragraph kept with a table needs that space too, as Word has it: with 12 pt
after a caption, Word moves the caption with the table once the header row and
the start of the first row don't fit under the caption and its space after
(measured in Word for Mac, compatibility modes 12 and 15).
2026-11-12 23:21:55 +03:00
jayzed80 9f34d3790e ODT: a header as tall as the page leaves the text room (#5806)
A header's fo:min-height raised to the page height made the text's top
margin the bottom of the page, so each page drew one line off the paper
and the rest of the body was lost from the render and PDF. Header and
footer bands now grow the margins only while the text keeps half an
inch, as Page Setup's margins must; the smaller band is kept whole.
2026-11-12 20:19:30 +00:00
dfgodvan 69578bbc6f Layout: a kept paragraph fits by itself where its last line's text does
Keep with next moves a paragraph only when it fits on the page by itself, and
that check took its whole height, while placing the lines lets the last
line's extra leading (multiple spacing above single) run into the bottom
margin. A double-spaced caption whose text ends above the margin then stayed
alone at the foot of the page, its table on the next. Word moves it with the
table (measured in Word for Mac: Times New Roman 12 pt, double spacing, the
caption 0, 4 and 8 pt below 52 exactly 12 pt lines; not kept, it stays on
page 1). The check now uses the fit the lines are placed with (`fit_height`).
2026-11-12 23:18:00 +03:00
dfgodvan ee424da341 Layout: a row starts whole only where the border below it fits too, as placing it needs
row_can_start took a row as fitting where its height did, while place_table
also wants the border below it (the row's edge). A first row that can't split
then looked as if it started under a kept caption that it actually left
alone at the foot of the page. The whole-row check and the start estimate
include the edge.
2026-11-12 23:16:57 +03:00
dfgodvan fe1cecbb90 Layout: a paragraph kept with a table needs its header rows and the start of its first row
Keep with next asked a table that follows for a flat 24 pt. Word keeps the
paragraph (a table caption, typically) with the table's repeated header rows
and the start of its first row: when they don't fit under it, the paragraph
goes over with the table instead of staying alone at the foot of the page.
The first row need not fit whole; the least room it can start in is enough
(two lines of a cell's text with widow/orphan control, compatibility mode 15).

table_start_need lays the table out and finds that room with row_can_start.
The look-ahead restores the list and equation counters, so numbered items in
the table's cells are counted once.
2026-11-12 23:16:57 +03:00
Fin Warman c37ee263ce Turned text in a merged cell wraps to its rows' minimum height 2026-11-12 16:19:00 +00:00
Fin Warman 07e4b515fc Turned text in an at-least row wraps to its minimum height 2026-11-12 16:17:27 +00:00
Fin Warman f438ec2943 Page-anchored frames in a table cell stay in the cell 2026-11-12 16:01:31 +00:00
fluorine 021269b675 Cursor test: set the Ctrl modifier and check the unit selection starts 2026-11-11 11:10:11 -04:00
fluorine b395c45437 Canvas: classify a press by its own position and gate unit drags on it
A press and a move in one frame no longer let the move decide whether the press began on the paper. A unit selection that began in the grey keeps the arrow.
2026-11-11 10:57:15 -04:00
fluorineandClaude Sonnet 5.5 68c5dfe8c7 Canvas: remember where a press began so scrolling cannot change the pointer
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 10:34:47 -04:00
NetterSilverandClaude Sonnet 5.5 1b8934c823 fix: reconcile unmatched U+FFFC markers in one linear pass (no cap)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 01:18:16 +01:00
NetterSilverandClaude Opus 5.5 519ddb612b Reconcile inline objects with U+FFFC markers on .json open
Fixes #3678

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 01:09:47 +01:00
Fluorine eac757af34 Keep off-paper drag cursor as arrow 2026-11-10 19:07:59 -04:00
fluorineandClaude Sonnet 5.5 3c159e2331 Canvas: keep the arrow off the paper, show the text pointer only over a page
The grey around and between pages and the rulers showed the I-beam although no text
can be typed there. They keep the arrow now; a drag begun on the page keeps its I-beam.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 16:04:10 -04:00
Max Murphy f211d2914a M15 #1: list every docx-corpus option in xtask help; record the harness in gap #1
The top-level help listed only --dir and --out, hiding --all-pages,
--timeout and --cli. The ranked gap #1 row still said the DOCX fidelity
corpus was not started; it now records that the runner is complete while
the real-world corpus and the Word comparison remain, so the gap stays
open. Status lines and revision histories follow the repo convention.

Signed-off-by: Max Murphy <maxmrphy@gmail.com>
2026-11-10 20:22:30 +01:00
Max Murphy 2b99488c4b Merge remote-tracking branch 'origin/main' into feat/docx-corpus-harness
Signed-off-by: Max Murphy <maxmrphy@gmail.com>
2026-11-10 20:22:30 +01:00
Michael c15eb8077a Merge branch 'main' of https://github.com/storytold/wordcraft into toc-insert-caret-position
# Conflicts:
#	crates/engine/src/cmd/references/tests.rs
2026-11-08 10:59:45 +08:00
Michael d572fff4cb Merge branch 'main' of https://github.com/storytold/wordcraft into toc-insert-caret-position
# Conflicts:
#	crates/engine/src/cmd/references/tests.rs
2026-11-08 09:11:43 +08:00
Michael ad721fc2b5 Merge remote-tracking branch 'upstream/main' into toc-insert-caret-position 2026-11-06 08:44:51 +08:00
MichaelandClaude Opus 5.5 1a86fd08fe TOC: the caret after the table sits past the next heading's bookmark
Review follow-up. When the paragraph after the table is a heading, the rebuilt entries give it a
`_Toc` bookmark at offset zero, so the caret placed at offset zero sat before the bookmark and
Delete removed it instead of the heading's first character, leaving the entry without its target.
The caret now goes past the markers the paragraph starts with.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:20:05 +08:00
MichaelandClaude Opus 5.5 0d4717cea6 TOC: the caret goes after a table replaced above a section break; page numbers count the added paragraph
Review follow-up. Replacing Word's TOC whose title sits above a section break returned before the
caret was placed, so a caret in the title stayed there and typing changed the title; that branch
now places it after the table too. When a table follows the TOC, the paragraph added for the
caret came after the entries were paginated; the entries are now rebuilt once it is there (with
the tabs and leader they now have), so their page numbers count it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:08:23 +08:00
Michael 60a150ab5b Merge branch 'main' of https://github.com/storytold/wordcraft into toc-insert-caret-position
# Conflicts:
#	crates/engine/src/cmd/references/tests.rs
2026-11-05 06:57:47 +08:00
dfgodvan 431251e139 Layout: drop a needless conversion in the picture line test (clippy) 2026-11-03 21:29:01 +03:00
dfgodvan 5cac512cfa Layout: rustfmt the picture line test 2026-11-03 21:29:01 +03:00
dfgodvan ace8f18c5a Layout: a picture line in multiple spacing takes the leading of its text, or of the paragraph mark alone
Measured in Word for Mac 16.93 (a 2cm picture, 1.15/2/3 spacing, Times New Roman and Arial
text, 8-20pt runs and marks): under a picture taller than the text Word puts the text's
descent plus (m - 1) x its natural height, and on a line of only pictures (m - 1) x the
paragraph mark's natural height, with no descent floor and never from the picture's own run.
The engine matches Word within 0.6pt in all 36 cases and keeps every page break.
2026-11-03 21:29:01 +03:00
dfgodvan c7bb6f6da2 Layout: a picture line in multiple spacing takes the text's leading and fits at the page foot like Word
Under multiple spacing above single, Word puts the text's extra leading,
(m - 1) x its natural height, below an inline picture taller than the text
instead of the descent, and lets a page's last line run that leading into the
bottom margin as it does for text: only the picture has to fit.

Measured in Word for Windows (compatibility mode 15) on a 64-page document
with 1.5-spaced 12pt text (natural 12.59pt, descent 2.63pt): a 472pt picture
stayed on its page with 1.7pt to spare above the bottom margin, and the lines
after 438pt and 616pt pictures started 6.3pt below them. WordCraft needed the
picture plus the descent to fit, moved the picture to the next page and ended
with 65 pages; it now lays the document out on 64, the pictures on Word's pages.

The descent stays the floor, so single and slightly-above-single spacing
(1.08, 1.15) keep their line heights.
2026-11-03 21:29:01 +03:00
Max Murphy c2e4a05df1 M15 #1: rebuild wordcraft-cli before every DOCX corpus run
Signed-off-by: Max Murphy <maxmrphy@gmail.com>
2026-11-02 22:38:29 +01:00
Max Murphy 77060f63ab M15 #1: put --release after the cargo build subcommand
Signed-off-by: Max Murphy <maxmrphy@gmail.com>
2026-11-02 22:38:29 +01:00
Max Murphy cee47681a3 M15 #1: add opt-in DOCX corpus harness
Adds cargo xtask docx-corpus: every .docx under a local corpus is opened and inspected, rendered to PNG (page 1 or all pages), saved to a temporary copy, reopened and compared by plain text and page count. Each stage runs in a bounded child wordcraft-cli process, failures are classified, and one bad file never stops the run.

The JSON report is sorted and timestamp-free, with a Markdown summary and rendered pages beside it. Missing and empty corpora exit successfully. The harness is local-only: /corpus stays git-ignored, only corpus/docx/README.md is tracked, and no Word-produced file or Word-vs-WordCraft visual comparison is added.
2026-11-02 22:38:29 +01:00
Florent Siegenthaler 47039c163f Info.plist: say where the language list comes from, and that AppKit follows the macOS language 2026-10-30 21:18:40 +01:00
Florent Siegenthaler b585ac4493 Merge remote-tracking branch 'origin/main' into macos-dialog-localizations 2026-10-30 21:18:26 +01:00
OPUZZLES 34b9e6aacc #3614: reconcile PDF figure lookups with main 2026-10-30 18:20:09 +01:00
Marco Arnulfo ce1f7ecb63 Equations: Left and Right open the equation through edit_at, not a JSON round trip (#4138) 2026-10-30 03:14:45 +01:00
Marco Arnulfo 57427c7b98 Equations: progress docs for Left and Right next to an equation (#4138) 2026-10-30 03:11:45 +01:00
Marco Arnulfo dfb1341d72 Equations: Left and Right next to an equation pinned through the keyboard path, also between two equations (#4138) 2026-10-30 03:11:40 +01:00
Marco Arnulfo 32922ec9a4 Equations: typing parity documents Left and Right next to an equation (#4138) 2026-10-30 03:05:47 +01:00
Marco Arnulfo 7cfa807dc3 Equations: Left and Right step into an equation next to the caret, as in Word (fixes #4138) 2026-10-30 03:00:31 +01:00
Mat Strange aec899bbee A table that can't hold the list refuses it, not cuts it
Insert › Table › Spreadsheet Table made a table of the rows
`insert.table` inserts — at most a thousand — and then wrote the
parsed records into it. A longer list lost everything above that,
quietly, and the command said it had worked.

The list is now held to what the table can take: its columns, and its
rows. One over either is refused with a message that says which. The
row count the table command clamps to is now a named constant
(`insert::MAX_TABLE_ROWS`), so the two read the same number.

The record limit of a recipient list is a separate matter, and
#1927 changes that line: it makes the reader keep one record past the
limit so the list can be told it is too long, rather than cut.
2026-10-29 14:00:49 +00:00
Mat Strange 0f84914edc #4053: A recipient list over what it keeps is refused while it is read
The CSV reader had no field cap: every comma became a String, so a
38 MB file of commas was forty million of them — a gigabyte of memory
for a list that came back empty. The field cap that did exist was
applied afterwards, to a list that had already been built, and every
record of a wide header is padded to its width, so 605 KB of CSV grew
to 4.7 GB.

The reader now keeps its limits while it reads: at most 1,000 columns
in a record, 2,000,000 cells (the records times the widest record,
which is what a list costs once every record is padded to the header's
width) and 64 MiB of cell text. A list over them is refused with a
message that says which limit it is over, rather than built and cut.

Those are the numbers the spreadsheet path already keeps
(crates/formats/src/sheet.rs), so a list read as a CSV and the same
list read as a workbook are held to one budget.

Measured through the file route (wordcraft-cli), before and after:

  40,000,000 commas (38 MB): 1,003 MB → 128 MB, refused
  1,000 columns over 100,000 records (605 KB): 4,610 MB → 13 MB, refused
  100,000 records of 10 columns: 0.16 s, the same peak memory, before
  and after

The reader keeps the separator detection main has (the separator is
counted outside quotes) and the record limit of 100,000 is untouched:
that line is #1927's, and it changes the same function.

The spreadsheet path and the typed `rows` list are untouched, and a
list is still stored twice and cloned on every filter; those are the
auditor's #3616, which stays open.
2026-10-29 14:00:45 +00:00
OPUZZLES 6b3555e831 M12: assert PDF figure roles and selected page order (#3614) 2026-10-29 10:03:58 +01:00
OPUZZLES 0e96d0abd0 M12: reuse PDF figure object lookups (#3614) 2026-10-29 09:34:06 +01:00
MichaelandClaude Sonnet 5.5 07544f5078 Merge upstream main into toc-insert-caret-position
references.rs was split into references/; the caret-placement change and its
tests move to references/toc.rs and references/tests.rs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 09:41:53 +08:00
Florent Siegenthaler af4608d7f0 Declare the UI languages to AppKit so the open and save panels are translated 2026-10-26 09:24:47 +01:00
Jayesh Prajapati 082d47c8a2 Merge branch 'main' of https://github.com/storytold/wordcraft into fix/3639-header-commands-own-section
# Conflicts:
#	ROADMAP.md
#	docs/ui-parity.md
2026-10-26 10:03:24 +05:30
Jayesh Prajapati c70807b8a9 Merge branch 'main' of https://github.com/storytold/wordcraft into fix/3639-header-commands-own-section
# Conflicts:
#	ROADMAP.md
#	docs/ui-parity.md
2026-10-26 08:14:22 +05:30
ratkoandClaude Opus 5.5 dd7b12f504 A selected picture survives Enter and breaks (#4126)
Enter on a selected picture or shape deleted it, like selected text.
In Word for Mac, Enter does nothing there, inline or floating, however
many times it is pressed. Shift+Enter and a page break go in front of
the picture and keep it selected, so it moves down a line or to the
next page; a column break does the same. A break on a picture inside a
Picture content control goes in front of the control, and the picture
stays selected.

A selected text box is unchanged: in the app, Enter puts the caret in
its text.

Tested by the developer in the app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 08:54:25 +01:00
Diego GueriniandClaude Opus 5.5 e525617d55 Merge upstream/main into rtl-numbers-latin
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 08:03:45 +01:00
Diego GueriniandClaude Opus 5.5 98bbdb506e Merge upstream/main into rtl-numbers-latin
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 21:02:21 +02:00
Diego GueriniandClaude Opus 5.5 b2c985ba06 Merge upstream/main into rtl-numbers-latin
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 16:04:12 +02:00
Jayesh Prajapati 0db3ce644a Merge branch 'main' of https://github.com/storytold/wordcraft into fix/3639-header-commands-own-section
# Conflicts:
#	ROADMAP.md
#	docs/ui-parity.md
2026-10-24 11:03:07 +05:30
Jayesh Prajapati 96eddcfe69 #3639: Header and footer commands use the section of the caret's page in a linked header 2026-10-24 11:02:42 +05:30
Diego GueriniandClaude Opus 5.5 633f5bc212 Merge upstream/main into rtl-numbers-latin
#2150 review: docs/layout-parity.md keeps one bidirectional row (the updated one, where main has it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 21:02:45 +02:00
Jayesh Prajapati 85ad49db32 #3639: Edit Header/Footer from a header opens the one the section is linked to
With no page given and the caret in a header or footer, Edit Footer took
only the caret's section's own footer, so a section linked to the
previous one got a new footer of its own and lost the link. It now walks
back to the footer the section shows, as layout does.
2026-10-23 18:17:16 +05:30
Jayesh Prajapati 7c1792867d #3639: Header and footer commands change the section of the header the caret is in
With the caret in a header or footer, Link to Previous, Header/Footer
Position, Insert Header/Footer, Edit Header/Footer and Page Borders read
the header's paragraph index as a body paragraph index, so section 2's
header changed section 1. They now find the caret's section with
section_index_of_focus, as Page Setup already does (#2072).
2026-10-23 13:44:17 +05:30
Divyanshu Gupta c2cb17cb36 fix(engine): support quoted literals and preserve bare 'a' in date pictures
In format_date_parts, strip single quotes around literal text sections, preserve bare 'a'/'A' characters instead of treating them as AM/PM tokens, and zero-pad 12-hour clock hours when 'hh' is specified.

Closes #3488
2026-10-22 00:19:56 +05:30
Diego GueriniandClaude Sonnet 5.5 ad4d2dfec0 Merge upstream/main into rtl-numbers-latin
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 09:54:54 +02:00
MichaelandClaude Sonnet 5 c08be77357 TOC: check the block after the table is a paragraph, not just present
CodeRabbit found a real edge case: when a table of contents already has
entries, is immediately followed by a table (nothing paragraph-shaped in
between), and gets replaced in place by a settings change, the "does a
block already exist after the table" check used Option::is_none, so it
reused that existing block's path as the caret's position regardless of
its type - landing the selection at the table's own top-level path.
clamp_selection then silently snaps that invalid position back to the
nearest *preceding* paragraph, i.e. back inside the table's own entries,
reproducing a milder form of the very bug this PR fixes.

Check the block is actually a paragraph before reusing it; insert one
otherwise, same as when nothing is there at all.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-20 13:02:31 +08:00
MichaelandClaude Sonnet 5 a552c4bdda TOC: leave the caret after the table, not inside its own title
insert_toc builds the title paragraph, the field, and the entries, but
never moves the selection afterward — whatever it was before the command
(the document's original, now-displaced paragraph) stays put, which after
a brand-new TOC on an otherwise-empty document is offset 0 of the
TOCHeading paragraph itself, right before "Contents".

Confirmed against real Word (16.0.20527.20054): Insert > Table of Contents
leaves the caret in a fresh paragraph right after the table, ready to keep
typing. Anyone following that same natural workflow in WordCraft today -
insert a TOC placeholder, write headings and body text, call Update Table
once done - ends up typing inside the TOC's own title paragraph instead,
and the later Update Table call then splices "Contents" out of its own
paragraph and onto whatever body paragraph happened to end up right before
the entries, leaving the title blank.

Move the selection to a paragraph right after the table once it's built
(reusing one that's already there, or adding an empty one if the table
ends the document), matching Word's placement and keeping the title and
entries intact however the user continues from there.

Fixes #3227.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-20 12:50:47 +08:00
SlavenDj 913d9fa5ab Offer Blank document, Browse… and Home in the empty window (#3126)
With no document open (Esc on the Start screen, File › Close) the page area
was blank while the ribbon was greyed out, so the only way back to the
Start screen was the account button. It now says no document is open and
offers Blank document, Browse… and Home; Home returns to the Start screen
without creating a document, and Blank document opens one ready for
typing.
2026-10-19 23:43:49 +02:00
Diego GueriniandClaude Opus 5.5 0d75ca3bf6 #2150: gap #16 and the progress log record Latin text kept in order in right-to-left lines
CodeRabbit: `docs/gaps.md` still listed the right-to-left gap without this change and
`ROADMAP.md` had no progress entry. Both are added, with their status lines and revision
histories.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 07:25:54 +02:00
Diego GueriniandClaude Opus 5.5 71d341fcfb #2150: a combining mark between a right-to-left letter and Latin text keeps its letter's level
CodeRabbit: with no space between them, an Arabic or Persian letter's combining mark (NSM) began
the segment the Latin span is found in, so the span gave it the Latin level and the mark was
shaped apart from its letter. The marks the span starts with are left at their own level.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 23:25:30 +02:00
Diego Guerini 3bf1a0a81c Merge remote-tracking branch 'upstream/main' into rtl-numbers-latin
# Conflicts:
#	docs/layout-parity.md
#	docs/target-app-parity.md
2026-10-18 23:15:43 +02:00
Diego Guerini 6e8820dc5d Merge remote-tracking branch 'upstream/main' into rtl-numbers-latin
# Conflicts:
#	docs/layout-parity.md
2026-10-18 16:09:02 +02:00
Diego GueriniandClaude Opus 5.5 213b75ce02 #2150: a combining mark ending the right-to-left word keeps its level
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 12:37:08 +02:00
Diego Guerini 8883429285 Merge remote-tracking branch 'upstream/main' into rtl-numbers-latin
# Conflicts:
#	docs/layout-parity.md
#	docs/target-app-parity.md
2026-10-18 11:26:24 +02:00
Diego GueriniandClaude Opus 5.5 62bf70beb3 #2150: neutrals inside an explicit embedding keep the embedding's level
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 11:25:41 +02:00
Diego Guerini b0a2b71cbe Merge remote-tracking branch 'upstream/main' into rtl-numbers-latin
# Conflicts:
#	docs/layout-parity.md
2026-10-18 10:29:35 +02:00
justinjohn0306andClaude Opus 5.5 1d890c0932 #1913: translate "Browse templates…" in every interface catalog
The i18n audit failed on the new Backstage button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 16:41:47 +05:30
justinjohn0306 3d3e7ac5ef Merge commit 'eae2421' into HEAD 2026-10-16 16:37:24 +05:30
justinjohn0306 73f0701255 #1913: expose spacing templates in Backstage 2026-10-16 13:43:51 +05:30
Diego GueriniandClaude Opus 5.5 1f2510ddda #2150: Latin text keeps its digits, spaces and punctuation in order in right-to-left text
UAX #9 alone showed "2-naphthol" after a Persian word as "naphthol-2" in a
right-to-left paragraph (the hyphen went with the Persian text) and "11
Windows" for "Windows 11", and in a left-to-right paragraph the digit after
Arabic letters became an Arabic number placed before the Persian word.

bidi_levels now keeps Latin text together: from the word with the first
left-to-right letter to the word with the last letter or digit after it,
without crossing a right-to-left letter, a tab or an explicit embedding mark,
everything takes the letters' level, except sentence punctuation at either
end. The spaces and punctuation between it and the right-to-left text take
the paragraph's level (rule N2). Numbers alone and text across tabs are left
to UAX #9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 20:48:33 +02:00
justinjohn0306 734dedde28 #1913: apply paragraph spacing presets to styles 2026-10-15 12:12:27 +05:30
490 changed files with 293254 additions and 3313 deletions
+12 -1
View File
@@ -2,4 +2,15 @@
# (#6537) and `cargo fmt --check` still passed, so the gate could not see it. Normalise on add.
* text=auto
craft-i18n.rev text eol=lf
craft-i18n.rev 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
+16
View File
@@ -0,0 +1,16 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
+117
View File
@@ -0,0 +1,117 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/wordcraft",
"repository_id": 1408489772,
"producer_workflow_id": 429734489,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "main",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "main",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "wordcraft-nightly-20261124",
"repository": "storytold/wordcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135788,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_wordcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_wordcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [
"github-actions[bot]"
],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
},
"package_formats": [
"appimage",
"arch",
"deb",
"flatpak",
"oci",
"rpm"
]
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
+227
View File
@@ -0,0 +1,227 @@
name: Nightly build check
# Builds the unsigned WordCraft Nightly the way the producer does (packaging/linux/nightly.sh,
# packaging/windows/package.ps1 -Nightly, packaging/macos/nightly.sh) and checks each archive as the
# Launcher unpacks it. No secrets and no environment: the real Nightly is signed by the shared
# release-ref signer (craft-common-actions), which calls packaging/macos/nightly-sign.sh and the
# app's sign.ps1.
on:
# The platform runners are shared with release builds: pull requests run this only with the
# `full-ci` label, never by changed paths. `labeled` so adding it starts a run.
pull_request:
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
permissions:
contents: read
# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci`
# label, or another label added) gets a group of its own, so it never cancels a real build.
concurrency:
group: nightly-build-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
linux:
name: Nightly tar (x86_64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: ubuntu-latest
timeout-minutes: 120
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install the system libraries the GUI links
run: sudo apt-get update && sudo apt-get install -y pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
- name: Prepare a Nightly identity for this commit
shell: bash
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "WORDCRAFT_BUILD_SHA=$sha"
echo "WORDCRAFT_BUILD_DATE=$date"
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
echo "DIST=$RUNNER_TEMP/nightly-dist"
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
echo "CRAFT_FONTS_REQUIRED=1"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly tar
run: bash packaging/linux/nightly.sh --arch x86_64
- name: Check the tar as the Launcher unpacks it, and ask its version
shell: bash
run: |
set -euo pipefail
work="$RUNNER_TEMP/nightly-check"
mkdir -p "$work"
archive="$DIST/wordcraft-$WORDCRAFT_VERSION-linux-x86_64-nightly.tar.gz"
# The launcher and the GUI it starts, the icon and the notices; the embedded fonts'
# OFL-*.txt licences appear when the build has CRAFT_FONTS_DIR.
core="$(tar -tzf "$archive" | sort | grep -Ev '^OFL-[A-Za-z0-9_.-]+\.txt$' | tr '\n' ' ')"
[ "$core" = "ATTRIBUTION.md LICENSE-APACHE LICENSE-MIT NOTICE README.md wordcraft wordcraft-bin wordcraft-nightly.png " ] \
|| { echo "unexpected members: $core"; exit 1; }
tar -xzf "$archive" -C "$work"
[ -x "$work/wordcraft" ] && [ ! -L "$work/wordcraft" ]
[ "$(stat -c %a "$work/wordcraft")" = 755 ]
[ -x "$work/wordcraft-bin" ] && [ ! -L "$work/wordcraft-bin" ]
mkdir -p "$work/home" "$work/profile"
chmod 700 "$work/home" "$work/profile"
out="$(env -i HOME="$work/home" PATH=/usr/bin:/bin "$work/wordcraft" --version 2>"$work/stderr")" \
|| { cat "$work/stderr"; exit 1; }
[ ! -s "$work/stderr" ]
[ "$out" = "WordCraft $WORDCRAFT_VERSION (nightly-v1)" ]
out="$(env -i HOME="$work/home" PATH=/usr/bin:/bin "$work/wordcraft" --launch-profile nightly-v1 --profile-root "$work/profile" --version)"
[ "$out" = "WordCraft $WORDCRAFT_VERSION (nightly-v1)" ]
[ "$(head -c 2 "$work/wordcraft")" = '#!' ]
echo "==> verified (unsigned): $out"
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: wordcraft-nightly-linux-x86_64-unsigned
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-linux-x86_64-nightly.tar.gz
if-no-files-found: error
retention-days: 7
compression-level: 0
windows:
name: Nightly ZIP (x86_64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: windows-latest
timeout-minutes: 150
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
defaults:
run:
shell: pwsh
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
targets: x86_64-pc-windows-msvc
- name: Prepare a Nightly identity for this commit
shell: bash
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "WORDCRAFT_BUILD_SHA=$sha"
echo "WORDCRAFT_BUILD_DATE=$date"
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
echo "DIST=$RUNNER_TEMP/nightly-dist"
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
echo "CRAFT_FONTS_REQUIRED=1"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly intermediate
run: ./packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly -Target x86_64-pc-windows-msvc -TargetDir $env:CARGO_TARGET_DIR -Dist $env:DIST
- name: Run the packaging contracts (no signing material)
run: ./packaging/windows/nightly-package-tests.ps1 -FixtureRoot $env:RUNNER_TEMP
- name: Run the signing contracts (dummy keys, no signing)
run: ./packaging/windows/nightly-signing-tests.ps1 -FixtureRoot $env:RUNNER_TEMP
- name: Keep the unsigned intermediate
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: wordcraft-nightly-windows-x86_64-unsigned
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-windows-x86_64-nightly.unsigned.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
macos:
name: Nightly .app (aarch64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: macos-15
timeout-minutes: 120
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
targets: aarch64-apple-darwin
- name: Prepare a Nightly identity for this commit
shell: bash
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "WORDCRAFT_BUILD_SHA=$sha"
echo "WORDCRAFT_BUILD_DATE=$date"
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
echo "DIST=$RUNNER_TEMP/nightly-dist"
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
echo "CRAFT_FONTS_REQUIRED=1"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly bundle
run: bash packaging/macos/nightly.sh --arch aarch64
- name: Check the archive and the bundle version
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$DIST/wordcraft-$WORDCRAFT_VERSION-macos-aarch64-nightly.zip"
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: wordcraft-nightly-macos-aarch64-unsigned
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-macos-aarch64-nightly.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
+72
View File
@@ -0,0 +1,72 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [WordCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
# Automatic Stage 2 signer dispatch for completed scheduled nightly producer runs.
if: >-
github.repository == 'storytold/wordcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected signer-branch validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/wordcraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/wordcraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/wordcraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/wordcraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'wordcraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
+59
View File
@@ -0,0 +1,59 @@
name: WordCraft release-ref nightly signer
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: wordcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/wordcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
with:
tooling-revision: main
app-name: wordcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment (which trusts release and
# nightly-signer) and export keys in its signing step.
+36
View File
@@ -0,0 +1,36 @@
name: WordCraft unsigned nightly
# Automated daily unsigned nightly build at 07:00 UTC plus supervised manual runs.
on:
schedule:
- cron: '0 7 * * *'
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/wordcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
with:
tooling-revision: main
app-name: wordcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
+20
View File
@@ -0,0 +1,20 @@
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 }}
+25 -2
View File
@@ -5,9 +5,9 @@ name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
pull_request:
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
workflow_dispatch:
permissions:
@@ -49,3 +49,26 @@ jobs:
- name: Build and check non-executable installer fixtures
shell: pwsh
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
nightly-source-contract:
name: Nightly source contracts (no build or signing)
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Enforce nightly serialization and synthetic packaging contracts
run: python3 packaging/nightly-tests.py
- name: Check the Arch Nightly handoff launcher (no build)
run: bash packaging/linux/nightly-arch-tar-test.sh
- name: Render and run the Nightly tar launcher (no build)
run: bash packaging/linux/nightly-package-test.sh
- name: Check the flat Nightly tar's shared template launcher (no build)
run: bash packaging/linux/nightly-tar-launch-test.sh
+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
+8 -1
View File
@@ -2,9 +2,16 @@
plan/
/target
/dist
/corpus
/corpus/*
!/corpus/docx/
/corpus/docx/*
!/corpus/docx/README.md
/log
.DS_Store
/.claude/
/target-*/
/craft-fonts/
/.nightly-tools
/.nightly-input
/craft-i18n
__pycache__/
+1
View File
@@ -74,5 +74,6 @@ WordCraft is a Rust word processor targeting Microsoft Word parity, for macOS, W
- Attribution: `ATTRIBUTION.md`, a row per asset file, checked by `cargo xtask assets`. Icons are our own SVG set in `crates/ui-egui/icons/` (draw new icons there); sample content is in `crates/engine/src/sample.rs` and `cmd/design.rs`.
- Fonts and language data come from other repositories as optional build inputs: craft-fonts through `CRAFT_FONTS_DIR`, and craft-i18n's `language-data/` through `CRAFT_I18N_DIR` (pinned by `craft-i18n.rev`; CI checks it out). Without craft-i18n the app builds with fallback spelling and no pattern hyphenation, so proofing tests need it. Proprietary font requests use installed fonts or the open substitutes in `crates/fonts/src/word.rs`. Layout tests use the fixed fonts in `assets/fonts/` ([docs/testing.md](docs/testing.md)).
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR` (both required; `--connect` is refused until the app confines its control channel, #3695), see `docs/mcp.md`.
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog feature `headless: yes` only when its command is in the engine registry that `wordcraft-cli` and the MCP server load (never a `ui.*` id). A missing feature takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `crates/engine/src/catalog.rs`, or reads `unknown`. When a command lands, delete its mark; `headless_marks_are_current` fails on a stale one.
- Notes and progress: `plan/` is an optional gitignored notebook. Committed: `ROADMAP.md` (progress log), `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md`, `docs/architecture.md` and the parity checklists.
- Contributor credits: `docs/contributors.md`.
+44 -2
View File
@@ -26,6 +26,12 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.wordcraft.svg` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
| `assets/app-icon/hicolor/48x48/apps/ai.storyteller.wordcraft.png` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.wordcraft.png` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
| `assets/app-icon/wordcraft-nightly.png` | WordCraft contributors | derived from `assets/app-icon/hicolor/256x256/apps/ai.storyteller.wordcraft.png` by `packaging/nightly-icons.py` (nightly field `#232c67`); input hashes and the recipe are in `assets/app-icon/nightly-provenance.json` | MIT OR Apache-2.0 | Nightly 256 px render; the icon the Linux Nightly tar ships |
| `assets/app-icon/wordcraft-nightly-1024.png` | WordCraft contributors | derived from `assets/app-icon/wordcraft-1024.png` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | 1024 px master the Nightly `.icns` is generated from |
| `assets/app-icon/wordcraft-nightly.ico` | WordCraft contributors | derived from `assets/app-icon/wordcraft.ico` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | Windows Nightly icon (16-256 px), embedded by `apps/wordcraft/build.rs` into the Nightly executable only |
| `assets/app-icon/wordcraft-nightly.icns` | WordCraft contributors | derived from `assets/app-icon/wordcraft.icns` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | macOS Nightly bundle icon (`CFBundleIconFile wordcraft-nightly`) |
| `assets/app-icon/nightly-provenance.json` | WordCraft contributors | original work for this repository | MIT OR Apache-2.0 | The exact inputs, palette and transform that produced the Nightly icon set |
| `assets/app-icon/README.md` | WordCraft contributors | original description of this repository's own icon artwork | MIT OR Apache-2.0 | Names the master, the sizes and the regeneration steps |
| `assets/fonts/Inter-Medium.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
| `assets/fonts/Inter-Regular.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
| `assets/fonts/Inter-SemiBold.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
@@ -196,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: 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/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 |
@@ -252,6 +258,7 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `crates/ui-egui/icons/pageNumber.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/pageWidth.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/painter.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/painter-fill.svg` | WordCraft contributors | original: the Format Painter's yellow bar, split out as the fill drawn under `painter.svg` | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/paraSpacing.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/pastCitation.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/paste.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 |
@@ -333,6 +340,7 @@ 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 |
@@ -352,6 +360,8 @@ 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 |
@@ -369,7 +379,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: 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/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 |
@@ -389,3 +399,35 @@ 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
+395 -179
View File
File diff suppressed because it is too large Load Diff
+57 -53
View File
@@ -37,26 +37,30 @@ wordcraft-pdf = { path = "crates/pdf" }
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
# store's `language-pack` kind is #486 (CP4.1).
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
wordcraft-engine = { path = "crates/engine" }
wordcraft-mcp = { path = "crates/mcp" }
wordcraft-zotero = { path = "crates/zotero" }
wordcraft-control-key = { path = "crates/control-key" }
wordcraft-ui-egui = { path = "crates/ui-egui" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
wordcraft-validate = { path = "crates/validate" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
# foundation
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"] }
@@ -81,28 +85,28 @@ wuff = "0.2.9"
brotli-decompressor = "5"
vello_cpu = "0.2"
image = { version = "0.25", default-features = false }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", default-features = false, features = ["write"] }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false, features = ["write"] }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
miniz_oxide = "0.9"
cfb = "0.15"
@@ -170,27 +174,27 @@ debug = 0
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
# and the egui and winit forks it builds with.
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
+13
View File
@@ -66,3 +66,16 @@ _Avoid_: Tofu, box, notdef character
A picture the document refers to that the output cannot include: its part is absent, its data
cannot be decoded, its format is unsupported, or it is linked from outside the file.
_Avoid_: Broken image, dropped image
## Windows
**Document window**:
A top-level window showing one open document. A document can be shown in several document windows
at once (View › New Window); each window shows exactly one.
_Avoid_: Viewport (that is the framework's surface), root window, tab
**Save prompt**:
The question "Save changes?" asked when the last document window showing a document with unsaved
changes is about to close. It belongs to that window and appears there; while it is up, the other
windows wait.
_Avoid_: Close guard, save dialog, unsaved-changes dialog
+31
View File
@@ -188,3 +188,34 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Linux Wayland window decorations
-------------------------------
sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux
for vector window controls. Its title-font features are disabled: no Cantarell
font is embedded by this dependency and no font file is added to this repo.
sctk-adwaita's MIT licence:
MIT License
Copyright (c) 2022 Bartłomiej Maryńczak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+2 -1
View File
@@ -282,7 +282,8 @@ into `%LOCALAPPDATA%\Programs\ArtCraft\WordCraft`, and needs no administrator ri
and asks for an administrator. Install only one copy: a copy for another scope is refused, so
uninstall first to change who WordCraft is installed for. Installers and executables are code-signed.
**If the app doesn't open on Windows:** the desktop app initializes only DirectX 12 by default.
**If the app doesn't open on Windows:** on 64-bit builds with a usable DirectX 12 GPU, the
desktop app initializes only DirectX 12 by default.
Letting wgpu also create an OpenGL instance can crash some graphics drivers (AMD's
`atio6axx.dll`) before the window appears, so the app would flash in Task Manager and quit.
`WGPU_BACKEND` overrides the default for troubleshooting (for example `dx12` or `vulkan`). In
+682 -620
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -19,6 +19,7 @@ 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"
+159 -4
View File
@@ -51,6 +51,7 @@ 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
@@ -81,7 +82,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", "mcp", "zotero"];
const SUBCOMMANDS: &[&str] = &["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "validate", "mcp", "zotero"];
fn wants_help(cmd: &str, rest: &[String]) -> bool {
SUBCOMMANDS.contains(&cmd) && rest.iter().any(|a| a == "--help" || a == "-h")
@@ -118,7 +119,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), ("zotero", 1)];
const OPENS_FILE: &[(&str, usize)] = &[("convert", 0), ("info", 0), ("text", 0), ("inspect", 0), ("render", 0), ("validate", 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.
@@ -367,6 +368,8 @@ 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)";
@@ -391,8 +394,10 @@ 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, so stop quietly and exit 0 like other command-line tools.
/// to write to. Most commands exit 0; validation retains its verdict status.
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),
@@ -403,6 +408,7 @@ 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),
}
}
@@ -717,7 +723,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)?;
}
Ok(())
writeln!(o, "{:<32} Structural integrity check", "validate")
})
}
}
@@ -731,6 +737,7 @@ 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
@@ -882,6 +889,17 @@ fn parity_markdown(p: &Value) -> String {
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
s += &format!("| {} | {} | {} |\n", t["tab"].as_str().unwrap_or(""), t["live"], t["total"]);
}
let h = &p["headless"];
s += &format!(
"\n**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.\n",
h["yes"],
h["no"]["window"].as_u64().unwrap_or(0) + h["no"]["os"].as_u64().unwrap_or(0) + h["no"]["engine-gap"].as_u64().unwrap_or(0),
h["no"]["window"],
h["no"]["os"],
h["no"]["engine-gap"],
h["partial"],
h["unknown"]
);
s += "\n## Missing\n\n";
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
let m = t["missing"].as_array().cloned().unwrap_or_default();
@@ -897,8 +915,144 @@ 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 {
args.iter().any(|arg| {
let arg = arg.to_string_lossy();
arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")
})
}
fn main() -> ExitCode {
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
if launcher_profile_flag(&args) {
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
return ExitCode::from(2);
}
// Language packs installed in the suite's font store are used; `proof.installPack` installs
// only while the person has turned downloading on in the app.
wordcraft_engine::packs::use_font_store(false);
@@ -907,6 +1061,7 @@ 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
+145 -1
View File
@@ -1,6 +1,23 @@
use super::*;
use std::io::Read;
/// The desktop app's Nightly bootstrap is never a CLI option, in either spelling.
#[test]
fn the_launcher_profile_bootstrap_is_refused_in_both_forms() {
for argv in [
&["--launch-profile", "nightly-v1", "--profile-root", "/nightly/profiles/wordcraft", "--version"][..],
&["--launch-profile=nightly-v1", "--profile-root=/nightly/profiles/wordcraft"][..],
&["--profile-root", "/nightly/profiles/wordcraft"][..],
] {
let argv: Vec<std::ffi::OsString> = argv.iter().map(std::ffi::OsString::from).collect();
assert!(launcher_profile_flag(&argv), "{argv:?}");
}
for argv in [&["--version"][..], &["proof.check", "--launch-profiles"][..], &["--profile-roots"][..]] {
let argv: Vec<std::ffi::OsString> = argv.iter().map(std::ffi::OsString::from).collect();
assert!(!launcher_profile_flag(&argv), "{argv:?}");
}
}
fn args(values: &[&str]) -> Vec<String> {
values.iter().map(|value| (*value).into()).collect()
}
@@ -213,10 +230,12 @@ 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.
// `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.
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()]);
@@ -224,6 +243,7 @@ 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),
@@ -281,6 +301,7 @@ 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")),
];
@@ -683,6 +704,114 @@ 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";
@@ -698,3 +827,18 @@ 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");
}
+64 -2
View File
@@ -1,5 +1,5 @@
//! A reader that closes stdout early (`wordcraft-cli commands --json | head`) must end the CLI
//! quietly with exit 0, never with a panic (#508).
//! Readers closing stdout early must not panic (#508). Listing and MCP stop quietly;
//! validation retains its verdict exit status.
use std::io::{Read, Write};
use std::process::{Command, Stdio};
@@ -47,3 +47,65 @@ 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:?}");
}
}
+8 -8
View File
@@ -37,9 +37,9 @@ use std::rc::Rc;
use std::sync::Arc;
use std::sync::Mutex;
use craft::host::{FileError, Files, PickId, PickRequest, Picked, WriteIntent};
use craft::host::{FileError, Files, PendingPick, PickId, PickRequest, Picked, WriteIntent};
use craft::platform::browser_files::BrowserFiles;
use craft::platform::open::{DropTarget, DroppedFile, IntakeSender};
use craft::platform::open::{DroppedFile, IntakeSender};
use craft::web_host::web::{FileData, Host, Message};
use wordcraft_ui_egui::{Services, WordApp};
@@ -110,7 +110,7 @@ impl Bridge {
fn listen(&self, intake: IntakeSender) {
self.host.listen(move |message| {
if let Message::Open { name, data } = message {
deliver_open(&intake, &name, &data);
deliver_open(&intake, name.as_deref().unwrap_or("document"), &data);
}
});
}
@@ -119,7 +119,7 @@ impl Bridge {
/// The file an open message carries, queued for the next frame like a dropped file. A host's file
/// is untrusted input: an oversized one is refused before it is copied into the app's memory (the
/// data's own length, not the host's claim). The crate has cleaned the name (and cut it to 255
/// characters); a blank one comes as `document` and becomes `Document.docx`.
/// characters); a missing one comes as `None` and becomes `Document.docx`.
fn deliver_open(intake: &IntakeSender, name: &str, data: &FileData) {
let name = if name == "document" { DEFAULT_NAME } else { name }.to_string();
let FileData::Bytes(array) = data else {
@@ -131,7 +131,7 @@ fn deliver_open(intake: &IntakeSender, name: &str, data: &FileData) {
return;
}
let file = DroppedFile { path: None, name, bytes: Some(Arc::from(array.to_vec())) };
intake.dropped(vec![file], DropTarget::Elsewhere);
intake.dropped(vec![file]);
}
/// The files of a hosted page: reads go to the browser's files, but a save goes to the host page,
@@ -167,8 +167,8 @@ impl Files for HostedFiles {
}
}
fn pick_pending(&self) -> bool {
self.inner.pick_pending()
fn pending_pick(&self) -> Option<PendingPick> {
self.inner.pending_pick()
}
fn read(&self, path: &Path) -> Result<Vec<u8>, FileError> {
@@ -192,7 +192,7 @@ impl Files for HostedFiles {
let answer = match sent {
// A Save As or first Save makes the page hold the document as this file: the answer
// names it, and the next Save posts the name with `save_as` false.
Ok(()) if request.save_as => Picked::Paths(vec![PathBuf::from(&name)]),
Ok(()) if request.save_as => Picked::Saved { path: PathBuf::from(&name), file_type: None },
// An overwrite of the opened file, or a copy: the document's file stays as it is.
Ok(()) => Picked::Downloaded(name),
Err(error) => Picked::Failed(error),
+2 -2
View File
@@ -13,14 +13,14 @@ pub fn open() -> (SharedSettings<Prefs>, craft::settings::LoadReport) {
use std::time::Duration;
use craft::settings::{LegacyFile, LocalStorageFiles, Location, OpenOptions, SettingsStore};
use wordcraft_ui_egui::prefs::legacy_ui_json;
use wordcraft_ui_egui::prefs::legacy_ui_json_slots;
/// Largest stored value read back (`localStorage` holds about 5 MB per site).
const MAX_STORED: usize = 4 << 20;
let options = OpenOptions::new(Location::Dir("wordcraft".into()))
.files(Arc::new(LocalStorageFiles::new(MAX_STORED)))
.debounce(Duration::ZERO)
.legacy(vec![LegacyFile { path: "wordcraft.ui".into(), parse: legacy_ui_json }]);
.legacy(vec![LegacyFile { paths: vec!["wordcraft.ui".into()], parse: legacy_ui_json_slots }]);
let (store, report) = SettingsStore::open_with(options);
(SharedSettings::new(store), report)
}
+3 -3
View File
@@ -10,7 +10,7 @@ use craft::host::{Files, Host, Wake};
use craft::platform::appearance::SystemReader;
use craft::platform::browser_files::BrowserFiles;
use craft::platform::clipboard::{Clipboard, ClipboardError, EventClipboard, Flavor, LateOffers, TEXT};
use craft::platform::open::{DropTarget, DroppedFile, FileIntake, IntakeSender};
use craft::platform::open::{DroppedFile, FileIntake, IntakeSender};
use craft::print::spool::Spool;
use craft::settings::SharedSettings;
use craft::ui::InstallSpec;
@@ -227,7 +227,7 @@ impl eframe::App for WebShell {
match f.bytes_async().await {
Ok(bytes) => {
let file = DroppedFile { path: None, name, bytes: Some(Arc::from(bytes)) };
sender.dropped(vec![file], DropTarget::Elsewhere);
sender.dropped(vec![file]);
}
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
}
@@ -412,7 +412,7 @@ fn guard_unload(dirty: Rc<Cell<bool>>, files: Arc<BrowserFiles>) -> Result<(), S
let window = web_sys::window().ok_or("no window")?;
let on_unload = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::BeforeUnloadEvent)>::new(move |e: web_sys::BeforeUnloadEvent| {
// A save still in the browser's picker hasn't written anything yet.
if dirty.get() || files.pick_pending() {
if dirty.get() || files.pending_pick().is_some() {
e.prevent_default();
// Older browsers ask only when `returnValue` is set.
e.set_return_value("unsaved changes");
+15 -2
View File
@@ -25,6 +25,9 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "
egui = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# The nightly launch profile's refusal dialog (a native message box, like the app's other OS errors).
rfd = { workspace = true }
thiserror = { workspace = true }
# The suite's shared libraries: the runtime hooks (`ui`, `ui-app`), file dialogs, the control
# channel's arguments, the GPU choice, printing, settings and window placement, the OS appearance
# reader and the system clipboard.
@@ -40,6 +43,7 @@ craft = { workspace = true, features = [
"platform-appearance",
"platform-clipboard-system",
] }
craft-nightly = { workspace = true }
[dev-dependencies]
# Temporary settings folders for the `prefs` tests.
@@ -54,10 +58,16 @@ winresource = "0.1"
[target.'cfg(target_os = "macos")'.dependencies]
# Finder double-click, Open With, Dock drops and `open -a WordCraft letter.docx` arrive as a
# kAEOpenDocuments Apple event, which winit doesn't handle (#27).
craft = { workspace = true, features = ["platform-apple-events"] }
craft = { workspace = true, features = ["platform-apple-events", "menu"] }
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))'.dependencies]
winit = { version = "0.30", default-features = false, features = ["x11"] }
[target.'cfg(target_os = "linux")'.dependencies]
# Retain X11 fallback; draw Wayland client-side controls without bundled title fonts.
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
winit = { version = "0.30", default-features = false, features = ["x11"] }
# Check that the libraries winit's X11 backend opens are installed before choosing XWayland (see
# `x11_libraries` in main.rs). Both are already in the build through winit's `x11` feature, at
# these versions and with this feature.
@@ -68,3 +78,6 @@ xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
# The update helper: a copy of this program started with `--finish-update`
# (`craft::update::self_update::finish`).
craft = { workspace = true, features = ["update"] }
# The nightly Windows identity: an explicit AppUserModelID, so Nightly gets its own taskbar
# button instead of sharing the stable app's (#16335's rule for the suite).
winsafe = { version = "=0.0.29", default-features = false, features = ["user", "shell"] }
+43 -5
View File
@@ -1,25 +1,63 @@
//! Windows only: embed the app icon and version info (VERSIONINFO) into `wordcraft.exe`, so it
//! shows in Explorer, the taskbar, the Start menu and Alt-Tab.
//!
//! On every other target this does nothing. A missing resource compiler is a warning, so a
//! cross-compile from macOS or Linux still links, unless `WORDCRAFT_REQUIRE_WINRES=1` turns it
//! The build channel (`WORDCRAFT_BUILD_CHANNEL`) is decided here, before any code is compiled: a
//! nightly-v1 build gets its own cfg, its own icon and its exact feed version in VERSIONINFO.
//! On every other target this does nothing but that. A missing resource compiler is a warning, so
//! a cross-compile from macOS or Linux still links, unless `WORDCRAFT_REQUIRE_WINRES=1` turns it
//! into an error (for release builds).
#[path = "src/build_channel.rs"]
mod build_channel;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=WORDCRAFT_BUILD_CHANNEL");
println!("cargo:rustc-check-cfg=cfg(wordcraft_nightly_v1)");
let nightly = match std::env::var("WORDCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=wordcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported WORDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
println!("cargo:rerun-if-changed=../../assets/app-icon/wordcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/wordcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=WORDCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=WORDCRAFT_VERSION");
let built_version = if nightly {
match std::env::var("WORDCRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit WORDCRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=WORDCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
res.set_icon("../../assets/app-icon/wordcraft.ico")
.set("ProductName", "WordCraft")
.set("FileDescription", "WordCraft word processor")
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "WordCraft Nightly" } else { "WordCraft" })
.set("FileDescription", if nightly { "WordCraft Nightly word processor" } else { "WordCraft word processor" })
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the WordCraft authors. MIT OR Apache-2.0.")
.set("OriginalFilename", "wordcraft.exe")
.set("InternalName", "wordcraft");
if nightly {
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("WORDCRAFT_REQUIRE_WINRES").is_some() {
eprintln!("embedding Windows resources failed: {e}");
+54
View File
@@ -0,0 +1,54 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/wordcraft-nightly.ico" } else { "../../assets/app-icon/wordcraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/wordcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/wordcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.18.1-nightly.20261124.17.1.gabcdef012345"));
for invalid in [
"",
"0.18.1",
"0.18.1-nightly",
"0.18.1-nightly.20261124",
"0.18.1-nightly.20261124.17.1.gABCDEF012345",
"0.18.1-nightly.20261124.17.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.18.1-nightly.20261124.1.1.gabcdef012345",
"0.18.1-nightly.20261124.1.1.gabcdef012345/other",
"0.18.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
+66
View File
@@ -0,0 +1,66 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use std::ffi::OsString;
pub use craft_nightly::BuildFlavor;
pub const COMPILED: BuildFlavor = if cfg!(wordcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
/// The Launcher's version line: `WordCraft <version> (nightly-v1)` for a nightly build.
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("WordCraft {stable} (nightly-v1)"),
}
}
/// A plain `--version` / `-V`: the only arguments, answered before any startup work.
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
#[cfg(test)]
mod tests {
use super::{BuildFlavor, needs_native_error, version, version_query};
use craft_nightly::{Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup};
use std::ffi::OsString;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn direct_nightly_launch_self_isolates_into_canonical_profile_root() {
let spec = crate::profile_root::spec();
let expected_root = canonical_profile_root(spec.app_id).unwrap();
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("letter.docx")], &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert_eq!(launch.passthrough_args, vec![OsString::from("letter.docx")]);
}
#[test]
fn stable_build_refuses_nightly_launch_flags() {
let spec = crate::profile_root::spec();
let args = craft_nightly::launch_arguments(std::path::Path::new(crate::launch_profile::launcher_root()), &[]);
let err = parse_startup(BuildFlavor::Stable, &spec, args, &StartupOptions::new()).unwrap_err();
assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild));
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.18.1"), "0.18.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.18.1"), "WordCraft 0.18.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
+163
View File
@@ -123,4 +123,167 @@ mod tests {
assert!(supplied.exists());
let _ = std::fs::remove_dir_all(&dir);
}
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
fn boot() -> (u16, Receiver<ControlRequest>, Control) {
let options = ControlOptions { token: Some(TOKEN.to_string()), ..ControlOptions::default() };
let (rx, control) = start(&options, 0, host(), None).unwrap();
let port = control.listening.addr.port();
(port, rx, control)
}
/// Answer the next request that reaches the UI with `ok`, and return it.
fn answer(rx: &Receiver<ControlRequest>) -> ControlRequest {
let req = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
let _ = req.reply.send(serde_json::json!({"ok": true, "result": {}}));
req
}
/// One connection, several lines.
struct Conn(std::io::BufReader<std::net::TcpStream>, std::net::TcpStream);
impl Conn {
fn open(port: u16) -> Self {
let s = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
s.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap();
Self(std::io::BufReader::new(s.try_clone().unwrap()), s)
}
fn send(&mut self, line: &str) {
use std::io::Write;
writeln!(self.1, "{line}").unwrap();
}
fn recv(&mut self) -> serde_json::Value {
use std::io::BufRead;
let mut r = String::new();
let n = self.0.read_line(&mut r).expect("read reply line");
assert!(n > 0, "unexpected EOF while waiting for reply");
serde_json::from_str(&r).expect("reply is valid JSON")
}
fn call(&mut self, line: &str) -> serde_json::Value {
self.send(line);
self.recv()
}
/// The server closed the connection.
fn closed(&mut self) -> bool {
use std::io::BufRead;
let mut r = String::new();
match self.0.read_line(&mut r) {
Ok(0) => true,
Err(e) => matches!(
e.kind(),
std::io::ErrorKind::ConnectionReset
| std::io::ErrorKind::ConnectionAborted
| std::io::ErrorKind::NotConnected
| std::io::ErrorKind::BrokenPipe
),
_ => false,
}
}
}
/// Post-#7101 adaptation of `the_key_on_each_request` (#124, tracked under #7317 / #7720):
/// `craft::automation::server` replaced the legacy per-request `"key"` field with one-time
/// per-connection token authentication (`docs/control-protocol.md`, Token).
#[test]
fn a_connection_authenticates_once_with_the_token_and_unauthenticated_requests_are_refused() {
let (port, rx, control) = boot();
// Authenticate once per connection with `params.token`.
let mut c = Conn::open(port);
let auth_resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#));
assert_eq!(auth_resp, serde_json::json!({"id": 1, "ok": true, "result": {"authenticated": true}}));
// Subsequent requests on the authenticated connection carry no token and reach the UI.
c.send(r#"{"id":7,"method":"document.inspect","params":{"text":true}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"text": true})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(7)));
c.send(r#"{"id":8,"method":"document.inspect","params":{"text":false}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"text": false})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(8)));
drop(c);
// An unauthenticated connection is refused and closed without reaching the UI.
let mut unauth = Conn::open(port);
let r = unauth.call(r#"{"id":9,"method":"document.inspect"}"#);
assert_eq!(r, serde_json::json!({"id": 9, "ok": false, "error": "authentication required"}));
assert!(unauth.closed());
assert!(rx.try_recv().is_err(), "unauthenticated request must not reach the UI");
drop(unauth);
// Legacy pre-#7101 per-request `"key"` does not bypass `auth` and closes the connection.
let mut legacy = Conn::open(port);
let r = legacy.call(&format!(r#"{{"id":10,"key":"{TOKEN}","method":"document.inspect","params":{{"text":true}}}}"#));
assert_eq!(r, serde_json::json!({"id": 10, "ok": false, "error": "authentication required"}));
assert!(legacy.closed());
assert!(rx.try_recv().is_err(), "legacy per-request key must not reach the UI");
drop(legacy);
control.shut_down();
}
/// Post-#7101 adaptation of `params_key_is_only_a_secret_for_auth` (#124, tracked under #7317 / #7729):
/// `craft::automation::server` replaced legacy `"key"` / `params.key` secrets with one-time
/// per-connection `auth` using `params.token` (`docs/control-protocol.md`, Token).
#[test]
fn params_token_is_only_a_secret_for_auth() {
let (port, rx, control) = boot();
// Neither `params.token` on a non-`auth` method nor legacy `params.key` on
// `document.inspect` or `auth` authenticates.
for (id, line) in [
(1, format!(r#"{{"id":1,"method":"document.inspect","params":{{"token":"{TOKEN}"}}}}"#)),
(2, format!(r#"{{"id":2,"method":"document.inspect","params":{{"key":"{TOKEN}"}}}}"#)),
(3, format!(r#"{{"id":3,"method":"auth","params":{{"key":"{TOKEN}"}}}}"#)),
] {
let mut c = Conn::open(port);
assert_eq!(c.call(&line), serde_json::json!({"id": id, "ok": false, "error": "authentication required"}));
assert!(c.closed());
}
assert!(rx.try_recv().is_err(), "refused requests must not reach the UI");
// Authenticate once with `params.token`; `params.key` and `params.token` on subsequent
// non-`auth` methods are forwarded untouched as ordinary parameters.
let mut c = Conn::open(port);
let auth_resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#));
assert_eq!(auth_resp, serde_json::json!({"id": 1, "ok": true, "result": {"authenticated": true}}));
c.send(r#"{"id":2,"method":"ui.key","params":{"key":"Enter"}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("ui.key", &serde_json::json!({"key": "Enter"})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(2)));
c.send(r#"{"id":3,"method":"document.inspect","params":{"token":"ordinary"}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"token": "ordinary"})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(3)));
drop(c);
control.shut_down();
}
/// Post-#7101 adaptation of `a_wrong_key_is_refused_and_closed` (#124, tracked under #7317):
/// wrong, short, and long `params.token` values are refused and close the connection without
/// reaching the UI.
#[test]
fn a_wrong_token_is_refused_and_closed() {
let (port, rx, control) = boot();
let wrong = TOKEN.replace('0', "1");
let long = format!("{TOKEN}0");
for token in ["nope", wrong.as_str(), &TOKEN[..63], long.as_str()] {
let mut c = Conn::open(port);
let resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{token}"}}}}"#));
assert_eq!(resp, serde_json::json!({"id": 1, "ok": false, "error": "authentication required"}), "{token}");
assert!(c.closed(), "{token}");
}
assert!(rx.try_recv().is_err(), "refused auth attempts must not reach the UI");
control.shut_down();
}
}
+17
View File
@@ -54,6 +54,23 @@ pub fn identity() -> AppIdentity {
mod tests {
use super::*;
/// Every type the button claims is included in identity, and plain text/Markdown are never claimed.
#[test]
fn xdg_mime_sets_every_word_type_in_one_call() {
let id = identity();
assert_eq!(id.desktop_id, "ai.storyteller.wordcraft.desktop");
assert_eq!(id.registered_name, "WordCraft");
for t in [
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/msword",
"application/rtf",
"application/vnd.oasis.opendocument.text",
] {
assert!(id.mime_types.iter().any(|a| a == t), "{t}");
}
assert!(!id.mime_types.iter().any(|a| a == "text/plain" || a == "text/markdown"), "plain text and Markdown are never claimed");
}
/// Every type the button claims is one the desktop entry declares, or desktops ignore it.
#[test]
fn the_desktop_entry_declares_every_claimed_type() {
+170
View File
@@ -0,0 +1,170 @@
//! Nightly-v1 bootstrap backed by `craft-nightly`. Selected before logging, preferences, fonts or
//! saved state. Stable launches retain their original arguments and directory policy.
use std::ffi::{OsStr, OsString};
pub use craft_nightly::Profile;
/// Returns the active launch profile for this process, defaulting to [`Profile::Stable`] before
/// `craft_nightly::prepare_launch` installs one.
pub fn current() -> &'static Profile {
static STABLE: Profile = Profile::Stable;
craft_nightly::current().unwrap_or(&STABLE)
}
fn is_nightly_flag_token(arg: &OsStr) -> bool {
arg.to_str().is_some_and(|s| {
s == craft_nightly::LAUNCH_PROFILE_FLAG
|| s == craft_nightly::PROFILE_ROOT_FLAG
|| s.starts_with("--launch-profile=")
|| s.starts_with("--profile-root=")
})
}
/// Returns `true` when `args` starts with nightly launch protocol flags followed by `--`.
/// `craft_nightly::parse_startup` consumes that `--`; preserving it lets `main.rs`'s
/// `split_at_delimiter` treat every argument after `--` as a document path.
pub fn had_launcher_separator(args: &[OsString]) -> bool {
if !args.first().is_some_and(|arg| is_nightly_flag_token(arg)) {
return false;
}
let mut idx = 0;
while let Some(arg) = args.get(idx) {
if arg == "--" {
return true;
}
if arg == craft_nightly::LAUNCH_PROFILE_FLAG || arg == craft_nightly::PROFILE_ROOT_FLAG {
idx += 2;
} else if arg.to_str().is_some_and(|s| s.starts_with("--launch-profile=") || s.starts_with("--profile-root=")) {
idx += 1;
} else {
break;
}
}
false
}
/// Re-attaches the `--` separator when `craft_nightly` stripped one from an explicit launcher
/// header, leaving direct-launch arguments untouched.
pub fn passthrough_args(args: Vec<OsString>, had_separator: bool) -> Vec<OsString> {
if had_separator { std::iter::once(OsString::from("--")).chain(args).collect() } else { args }
}
/// The root the Launcher hands a nightly on this platform, in that platform's own spelling: `C:\NightlyData\profiles\wordcraft`
/// on Windows, `/nightly-data/profiles/wordcraft` elsewhere. A test that fixtures the hand-off uses this rather than a
/// literal, because a root literal in the other platform's spelling is not absolute here and validation refuses it (#7849).
#[cfg(test)]
pub(crate) fn launcher_root() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\wordcraft" } else { "/nightly-data/profiles/wordcraft" }
}
#[cfg(test)]
mod tests {
use super::{had_launcher_separator, launcher_root, passthrough_args};
use craft_nightly::{
BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup, validate_and_prepare_root,
};
use std::ffi::OsString;
use std::path::PathBuf;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
launcher_root()
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
let spec = crate::profile_root::spec();
for argv in [args(&[]), args(&["--control", "7981", "a.docx"]), args(&["--", "--launch-profile", "file.docx"])] {
let had_sep = had_launcher_separator(&argv);
assert!(!had_sep);
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::Stable);
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), argv);
}
}
#[test]
fn direct_nightly_launch_resolves_canonical_root_and_preserves_user_arguments() {
let spec = crate::profile_root::spec();
let expected_root = canonical_profile_root(spec.app_id).unwrap();
let argv = args(&["--sample", "letter.docx"]);
let had_sep = had_launcher_separator(&argv);
assert!(!had_sep);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), argv);
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let spec = crate::profile_root::spec();
let mut argv = nightly();
argv.extend(args(&["--profile-root", "letter with spaces.docx"]));
let had_sep = had_launcher_separator(&argv);
assert!(had_sep);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), args(&["--", "--profile-root", "letter with spaces.docx"]));
}
#[test]
fn missing_duplicate_and_unknown_profile_arguments_are_refused() {
let spec = crate::profile_root::spec();
for argv in [
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
] {
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).is_err());
}
}
/// #7849: `/nightly-data/...` carries no drive prefix and so is not absolute on Windows, and `C:\...`
/// is one relative name on Unix. A launch that carries the other platform's root spelling is refused
/// instead of run against a directory this platform never meant.
#[test]
fn a_root_absolute_only_in_the_other_platforms_spelling_is_refused() {
let spec = crate::profile_root::spec();
let foreign = if cfg!(windows) { "/nightly-data/profiles/wordcraft" } else { r"C:\NightlyData\profiles\wordcraft" };
let err = validate_and_prepare_root(std::path::Path::new(foreign), &spec).unwrap_err();
assert!(matches!(err, ProfileError::RelativeProfileRoot(_)), "the other platform's root spelling must not stand in: {foreign}");
}
#[test]
fn launcher_and_plain_version_queries_are_recognized() {
let spec = crate::profile_root::spec();
let pair = &["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT];
for flag in ["--version", "-V"] {
let plain = parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap();
assert!(plain.is_version_query());
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
let direct = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert!(direct.is_version_query());
argv.push("letter with spaces.docx".into());
let with_document = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
assert!(!with_document.is_version_query());
assert_eq!(with_document.passthrough_args, args(&[flag, "letter with spaces.docx"]));
let mut with_sep = args(form);
with_sep.push("--".into());
with_sep.push(flag.into());
let separated = parse_startup(BuildFlavor::NightlyV1, &spec, with_sep, &StartupOptions::new()).unwrap();
assert!(separated.is_version_query());
}
}
}
}
+398 -31
View File
@@ -14,9 +14,18 @@
#[cfg(target_os = "linux")]
mod appimage_env;
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
mod default_apps;
mod launch_profile;
#[cfg(target_os = "macos")]
mod native_menu;
mod nightly_session;
mod prefs;
mod process_identity;
mod profile_root;
mod region;
use std::path::PathBuf;
@@ -31,7 +40,7 @@ use craft::platform::appearance::SystemReader;
use craft::platform::clipboard::{Clipboard, ClipboardImage, SystemClipboard};
use craft::platform::default_app::{DefaultApp, DefaultAppError};
use craft::platform::logs::{self, LogNames, crash};
use craft::platform::open::{DropTarget, DroppedFile, FileIntake, IntakeSender};
use craft::platform::open::{DroppedFile, FileIntake, IntakeSender};
use craft::print::spool::Spool;
use craft::settings::SharedSettings;
use craft::ui::InstallSpec;
@@ -47,6 +56,8 @@ use wordcraft_ui_egui::{Services, WordApp, prefs::Prefs};
/// exit, the print spool it waits for at exit and the control server it stops at exit.
struct App {
app: WordApp,
#[cfg(target_os = "macos")]
native_menu: Option<craft::menu::NativeMenu>,
/// The native panels behind the file service the app reaches through `Host::files`.
panels: FilePanels,
/// Feeds the files dropped on the window into the app's intake (`Services::intake`), the one
@@ -58,13 +69,28 @@ struct App {
spool: Spool,
/// The control server, when `--control` started one; it removes the token file it made.
control: Option<control_server::Control>,
/// The app binary's last step as the app leaves, run once at the end of `finish` (a Nightly
/// quit ends the process inside AppKit's terminate, after eframe's `on_exit`).
exit: Option<Box<dyn FnOnce()>>,
}
impl App {
fn before_input(&mut self, ctx: &egui::Context) {
#[cfg(target_os = "macos")]
if let Some(menu) = &mut self.native_menu {
menu.poll(ctx);
}
embed::before_input(ctx, |out| self.app.frame_input(out));
}
/// One frame's logic: what the OS asked, the app, its file dialogs, then the root window's close
/// path. Without `frame` (a test over no window) the dialogs have no parent window.
fn logic_pass(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
self.app.logic(ctx);
#[cfg(target_os = "macos")]
if let Some(menu) = &mut self.native_menu {
native_menu::update(menu, &mut self.app, ctx);
}
self.panels.pump_with(self.app.dialog_host_mut(), frame);
// A quit that waits for nothing (the documents are answered for) closes the root window.
if self.app.quit_requested && !self.app.printing.busy() {
@@ -95,7 +121,12 @@ impl App {
if let Some(control) = self.control.take() {
control.shut_down();
}
self.app.start_pending_update();
if !launch_profile::current().is_nightly() {
self.app.start_pending_update();
}
if let Some(exit) = self.exit.take() {
exit();
}
}
}
@@ -106,9 +137,9 @@ impl eframe::App for App {
// Once per frame, before any pass; the files stay in `raw` for the runtime's own reading.
let files = dropped_files(raw);
if !files.is_empty() {
self.drops.dropped(files, DropTarget::Elsewhere);
self.drops.dropped(files);
}
embed::before_input(ctx, |out| self.app.frame_input(out));
self.before_input(ctx);
}
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
self.logic_pass(ctx, Some(frame));
@@ -202,10 +233,12 @@ type MakeDefault = Box<dyn Fn() -> Result<DefaultApp, DefaultAppError>>;
/// What the app takes from its host beyond the runtime: File › Print through the system spooler,
/// personal templates (#2852, made on first save in `Templates` in the settings folder), and making
/// WordCraft the default app for Word documents (#295; macOS has no way to, so no button there).
fn services(spool: Spool, intake: FileIntake) -> Services {
fn services(spool: Spool, intake: FileIntake, nightly: bool) -> Services {
// Nightly never claims the stable app's file associations: the button would rewrite the same
// OS registration the stable WordCraft owns.
#[cfg(any(unix, windows))]
let make_default_app =
(!cfg!(target_os = "macos")).then(|| -> MakeDefault { Box::new(|| craft::platform::default_app::make_default(&default_apps::identity())) });
let make_default_app = (!cfg!(target_os = "macos") && !nightly)
.then(|| -> MakeDefault { Box::new(|| craft::platform::default_app::make_default(&default_apps::identity())) });
#[cfg(not(any(unix, windows)))]
let make_default_app: Option<MakeDefault> = None;
Services {
@@ -256,11 +289,35 @@ fn build_sha() -> &'static str {
option_env!("WORDCRAFT_BUILD_SHA").map(|s| s.get(..8).unwrap_or(s)).unwrap_or("dev")
}
/// Split the command line at its first `--`: the options before it, the documents after it. The
/// Launcher's nightly hand-off arrives as `--` followed by the file names (`launch_profile::parse`
/// puts that separator first), so it is dropped here rather than opened as a document.
fn split_at_delimiter(args: Vec<String>) -> (Vec<String>, Vec<String>) {
match args.iter().position(|a| a == "--") {
Some(i) => {
let mut options = args;
let files = options.split_off(i + 1);
options.pop();
(options, files)
}
None => (args, Vec::new()),
}
}
/// The documents to open, in the order the command line gave them: the words before `--` that the flag
/// loop kept, then the ones after it. The separator moves no document, and the Launcher, which sends
/// none before it, opens just its own file names in order.
fn documents_to_open(before: Vec<String>, after: Vec<String>) -> Vec<String> {
let mut documents = before;
documents.extend(after);
documents
}
/// The arguments as text, and apart the files whose names aren't valid Unicode, such as a Latin-1
/// one (#1440). A `--control` port, a token or a token file that isn't is an error.
fn text_args() -> (Vec<String>, Vec<std::path::PathBuf>) {
fn text_args(arguments: Vec<std::ffi::OsString>) -> (Vec<String>, Vec<std::path::PathBuf>) {
let (mut args, mut files) = (Vec::new(), Vec::new());
for (i, a) in std::env::args_os().skip(1).enumerate() {
for (i, a) in arguments.into_iter().enumerate() {
match a.into_string() {
Ok(a) => args.push(a),
Err(a) if args.last().is_some_and(|p| matches!(p.as_str(), "--control" | "--control-token" | "--control-token-file")) => {
@@ -318,18 +375,112 @@ fn complain(message: std::fmt::Arguments<'_>) {
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("wordcraft: {message}\n"));
}
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
process_identity::initialize(
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
wordcraft_ui_egui::os_window::id_for(wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1),
)
}
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// Tell the person why a Launcher launch was refused: on standard error always, and with a native
/// message box on a desktop session whose modal renders without the app's run loop (Windows,
/// X11/Wayland) — a Launcher start has no terminal to read standard error from, and on macOS a modal
/// before the event loop never appears.
fn report_launch_profile_error(error: &str) {
complain(format_args!("launch profile: {error}"));
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if let Err(identity) = initialize_nightly_process_identity() {
complain(format_args!("launch profile: {identity}"));
return;
}
let _ = rfd::MessageDialog::new()
.set_title("WordCraft Nightly")
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch profile before any startup service or side effect.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The launch profile is decided before logging, crash handling, the update helper,
// fonts, preferences or the settings folder.
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version` / `-V` on nightly: answered before root resolution, validation,
// process identity, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
return None;
}
let had_separator = launch_profile::had_launcher_separator(&argv);
let early = craft_nightly::prepare_launch(build_flavor::COMPILED, &profile_root::spec(), argv, &craft_nightly::StartupOptions::new())
.unwrap_or_else(|error| {
report_launch_profile_error(&error.to_string());
std::process::exit(2)
});
// Launcher `--launch-profile nightly-v1 --profile-root <dir> [--] --version` / `-V`:
// `craft_nightly::prepare_launch` skips root validation and profile installation for
// version queries, so answer and exit before any startup side effect.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
return None;
}
if let Err(error) = initialize_nightly_process_identity() {
report_launch_profile_error(&error.to_string());
std::process::exit(2);
}
let identity = if early.profile.is_nightly() {
wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1
} else {
wordcraft_ui_egui::os_window::LaunchIdentity::Stable
};
if let Err(error) = wordcraft_ui_egui::os_window::select_identity(identity) {
report_launch_profile_error(&error);
std::process::exit(2);
}
// One data root for everything the app keeps: preferences, window place, logs, recovery,
// fonts, templates, dictionaries and control token files all come from it.
if let Some(root) = launch_profile::current().root()
&& let Err(error) = wordcraft_control_key::use_settings_dir(root.to_path_buf())
{
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(launch_profile::passthrough_args(early.passthrough_args, had_separator))
}
/// Parses the command line, installs logging and the panic hook, restores preferences and window
/// geometry, opens requested documents or the Start screen, starts the control server when
/// asked, and runs the eframe event loop.
fn main() -> eframe::Result {
// Windows: the print helper is a copy of this program that runs one job in its own process.
// It reads only its own job folder, so it runs before the launch profile is parsed: a Nightly
// wants a profile on every start, and the helper must print without one.
#[cfg(windows)]
if let Some(code) = craft::print::spool::isolated::helper_main() {
std::process::exit(code);
}
let Some(arguments) = prepare_launch() else { return Ok(()) };
// Windows: the update helper is a copy of this program started with `--finish-update`.
// A Nightly never updates itself: the Launcher owns its updates.
#[cfg(windows)]
if let Some(result) = craft::update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if !launch_profile::current().is_nightly()
&& let Some(result) = craft::update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &arguments)
{
std::process::exit(i32::from(result.is_err()));
}
// Linux: before anything reads another program's AppImage variables, or a thread starts (#5653).
@@ -350,11 +501,16 @@ fn main() -> eframe::Result {
log::error!("couldn't start again without another program's AppImage variables, so the self-update is off in this window: {e}");
}
let mut flags = ControlOptions::default();
let mut files = Vec::new();
let mut sample = false;
let (args, other_files) = text_args();
// Only macOS (Finder / LaunchServices) adds these; elsewhere `-NS…` could be a real file name.
let (args, other_files) = text_args(arguments);
// The Launcher's own hand-off: `--` ends the options, so nothing after it is read as one and
// the separator itself never becomes a document.
let (args, after_separator) = split_at_delimiter(args);
// Only macOS (Finder / LaunchServices) adds these, and only to the options: a Finder launch carries
// no separator for them to sit after, and the Launcher starts the app itself, so a document whose
// name merely looks like one of these (`-NSNotes.docx`) is still opened (#7849 review).
let args = if cfg!(target_os = "macos") { without_launch_args(args) } else { args };
let mut documents: Vec<String> = Vec::new();
let mut bad_control: Option<Option<String>> = None;
let mut missing_value: Option<&'static str> = None;
let mut args = args.into_iter().peekable();
@@ -388,6 +544,7 @@ fn main() -> eframe::Result {
},
"--sample" => sample = true,
"--version" => {
// A nightly build reported its channel line before this parser ran.
println!("wordcraft {} ({})", env!("CARGO_PKG_VERSION"), build_sha());
return Ok(());
}
@@ -396,9 +553,12 @@ fn main() -> eframe::Result {
let _ = std::io::Write::write_all(&mut std::io::stdout(), USAGE.as_bytes());
return Ok(());
}
_ => files.push(a),
_ => documents.push(a),
}
}
// After the loop, so a document before `--` opens before the ones after it (a stable launch's
// `a.docx -- b.docx` used to be reversed when the Launcher's list was the one collected first).
let files = documents_to_open(documents, after_separator);
// After the loop, so `--version` later on the line still wins.
if let Some(port) = bad_control {
let got = port.map(|p| format!(", got {p:?}")).unwrap_or_default();
@@ -422,6 +582,13 @@ fn main() -> eframe::Result {
complain(format_args!("--control needs a port number from 1 to 65535, got \"0\""));
std::process::exit(2);
}
// Nightly runs the Launcher's documents only: no control server, token file or automation
// switch, and none inherited from a stable launch's environment.
if launch_profile::current().is_nightly() && (control.port.is_some() || control.token.is_some() || control.token_file.is_some()) {
complain(format_args!("a WordCraft Nightly window does not start a control server; open documents through ArtCraft Launcher"));
std::process::exit(2);
}
let nightly = launch_profile::current().is_nightly();
let settings_dir = wordcraft_control_key::settings_dir();
// The log file lives in the settings directory, next to the preferences; opened after the
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
@@ -440,10 +607,16 @@ fn main() -> eframe::Result {
None => logger.stderr_only(),
}
}
// A Nightly window always carries its own id; a stable one keeps the Flatpak sandbox's id
// when it runs inside one (so docks match the flatpak's desktop file).
let app_id = match launch_profile::current().root() {
Some(_) => wordcraft_ui_egui::os_window::app_id().to_string(),
None => std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| wordcraft_ui_egui::os_window::APP_ID.to_string()),
};
let mut options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("WordCraft")
.with_app_id("ai.storyteller.wordcraft")
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
.with_app_id(app_id)
.with_inner_size([1440.0, 920.0])
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
.with_drag_and_drop(true)
@@ -504,9 +677,33 @@ fn main() -> eframe::Result {
let _apple_events = craft::platform::open::apple_events::install(sender);
#[cfg(not(target_os = "macos"))]
drop(sender);
// Nightly's own health record: one owner per profile, cleared only by a controlled return.
let (nightly_record, health_unavailable) = match nightly_session::Session::begin_with_health(
launch_profile::current().root(),
env!("WORDCRAFT_BUILT_VERSION"),
option_env!("WORDCRAFT_BUILD_SHA"),
) {
Ok(pair) => pair,
Err(error) => {
log::warn!("Nightly session health is unavailable: {error}");
(None, launch_profile::current().is_nightly())
}
};
let session_health_warning: Option<String> = health_unavailable.then(|| {
"WordCraft Nightly could not record session health in its private profile. You can still edit, but abnormal-exit detection is unavailable."
.to_string()
});
let previous_nightly_unclean = nightly_record.as_ref().is_some_and(nightly_session::Session::previous_unclean);
let nightly_watch: nightly_session::Shared = Arc::new(Mutex::new(nightly_record));
let unclean_notice_shown = Arc::new(std::sync::atomic::AtomicBool::new(false));
// The window body and its exit hook each take a clone of the flag; the return path keeps the
// other, so a start that created no window can still finish the record.
let session_for_exit = nightly_watch.clone();
let noticed_for_exit = unclean_notice_shown.clone();
let noticed_in_window = unclean_notice_shown.clone();
let exit_settings = settings.clone();
let result = eframe::run_native(
"WordCraft",
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
options,
Box::new(move |cc| {
let ctx = cc.egui_ctx.clone();
@@ -528,7 +725,7 @@ fn main() -> eframe::Result {
);
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
.app_id("ai.storyteller.wordcraft")
.app_id(wordcraft_ui_egui::os_window::app_id())
.system(SystemReader::start(wake))
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
.placement(placement);
@@ -547,19 +744,31 @@ fn main() -> eframe::Result {
prefs::load_user_dictionary(&mut session, &settings, path);
}
let spool = Spool::new(host.jobs_shared().clone());
let mut app = WordApp::new(session, services(spool.clone(), intake)).with_host(host).with_settings(settings.clone());
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
// the region check below reads the saved region the settings apply.
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
app = app.with_fallback_chooser(true);
}
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
if nightly {
// The Launcher installs Nightly; Help › Check for Updates says so instead.
app.use_launcher_updates();
} else {
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
}
}
// Language packs from the suite's font store; an Install click is the person's own.
wordcraft_engine::packs::use_font_store(true);
// Nightly keeps its own store in the profile, so a pack installed there is not a
// change to the stable apps' shared fonts.
match launch_profile::current().root() {
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
None => {
wordcraft_engine::packs::use_font_store(true);
}
}
// A region chosen in File › Options replaces the system's for the first blank
// document too (#838).
if !sample && app.session.prefs.region.is_some() {
@@ -576,7 +785,8 @@ fn main() -> eframe::Result {
}
}
let mut control_server = None;
if let Some(port) = control.port
if !nightly
&& let Some(port) = control.port
&& let Some((rx, started)) =
control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
{
@@ -598,9 +808,34 @@ fn main() -> eframe::Result {
for f in other_files {
open_non_unicode(&mut app, &f);
}
Ok(Box::new(App { app, panels, drops, settings, spool, control: control_server }))
// The personal agent files, the session record and the control token all live in the
// profile; the app's own services are built with the nightly rule in mind.
if let Some(warning) = &session_health_warning {
app.status_long(warning.clone());
}
if previous_nightly_unclean {
app.status_long(
"The previous WordCraft Nightly session did not finish normally. You can report a problem from Help › About. No diagnostics have been sent.",
);
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
}
Ok(Box::new(App {
#[cfg(target_os = "macos")]
native_menu: native_menu::install(&ctx, &app),
app,
panels,
drops,
settings,
spool,
control: control_server,
exit: Some(Box::new(move || {
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
})),
}))
}),
);
// The exit hook has run; this is the no-op fallback for a start that created no window.
nightly_session::finish_once(&nightly_watch, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
// The app is dropped by now: whatever it saved on the way out is in the store.
if let Err(e) = exit_settings.lock().flush() {
log::warn!("preferences: {e}");
@@ -802,15 +1037,30 @@ mod smoke {
let (intake, sender) = FileIntake::new(Wake::new(|| {}));
let drops = intake.sender();
let session = Session::new(wordcraft_doc::Document::new());
let app = WordApp::new(session, services(spool.clone(), intake)).with_host(host).with_settings(settings.clone());
Run { app: App { app, panels, drops, settings, spool, control: None }, frames, ctx, sender }
let app = WordApp::new(session, services(spool.clone(), intake, false)).with_host(host).with_settings(settings.clone());
Run {
app: App {
#[cfg(target_os = "macos")]
native_menu: None,
app,
panels,
drops,
settings,
spool,
control: None,
exit: None,
},
frames,
ctx,
sender,
}
}
/// One frame as eframe runs it: the input hook once, the logic once, the UI per pass.
/// Returns whether the frame sent a close command.
fn step(&mut self, events: Vec<egui::Event>) -> bool {
let Run { app, frames, ctx, .. } = self;
embed::before_input(ctx, |out| app.app.frame_input(out));
app.before_input(ctx);
let mut first = true;
frames.frame_without_input(events, |ui| {
if std::mem::take(&mut first) {
@@ -833,7 +1083,7 @@ mod smoke {
/// cancelling the close.
fn close_request_is_let_through(&mut self) -> bool {
let Run { app, ctx, .. } = self;
embed::before_input(ctx, |out| app.app.frame_input(out));
app.before_input(ctx);
let mut input =
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 920.0))), ..Default::default() };
input.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { events: vec![egui::ViewportEvent::Close], ..Default::default() });
@@ -867,7 +1117,7 @@ mod smoke {
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("dropped.txt");
std::fs::write(&path, "Dropped words").unwrap();
run.sender.dropped(vec![DroppedFile { path: Some(path), name: "dropped.txt".into(), bytes: None }], DropTarget::Elsewhere);
run.sender.dropped(vec![DroppedFile { path: Some(path), name: "dropped.txt".into(), bytes: None }]);
run.settle();
assert!(run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body).contains("Dropped words"), "the dropped file opened");
let _ = std::fs::remove_dir_all(dir);
@@ -907,4 +1157,121 @@ mod smoke {
assert!(closed, "Don't Save lets the close through");
}
}
/// A native menu selection reaches the hosted About dialog, including its credits, and Escape
/// dismisses it without changing the document. The fake backend supplies the OS selection.
#[cfg(target_os = "macos")]
#[test]
fn native_about_shows_credits_and_closes_with_escape() {
use craft::menu::{Backend, Dispatch, Event, ItemRole, MenuBar, NativeMenu};
struct Selection(Vec<Event>);
impl Backend for Selection {
fn sync(&mut self, _: &MenuBar) {}
fn attach(&mut self, _: Dispatch) {}
fn drain(&mut self) -> Vec<Event> {
std::mem::take(&mut self.0)
}
}
let mut run = Run::new();
run.app.app.start_screen();
run.settle();
let before = run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body);
let layout = native_menu::layout(&str::to_owned);
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap().command.clone();
run.app.native_menu = Some(NativeMenu::new(Box::new(Selection(vec![Event::Click(about)]))));
run.settle();
assert!(run.app.app.dialog_host_mut().shows_modal());
let tree = run.frames.tree();
for label in ["WordCraft", "Contributors", "Models", "Language data"] {
assert!(tree.keys().into_iter().any(|key| craft::ui::testing::access::name(&tree, key) == Some(label)), "About exposes {label}");
}
run.step(vec![egui::Event::Key {
key: egui::Key::Escape,
physical_key: None,
pressed: true,
repeat: false,
modifiers: egui::Modifiers::NONE,
}]);
run.settle();
assert!(run.app.app.dialog_host_mut().is_empty(), "Escape dismisses About");
assert_eq!(run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), before);
}
}
#[cfg(test)]
mod command_line_tests {
use super::{documents_to_open, split_at_delimiter};
/// The argv the Launcher starts a nightly with, as `prepare_launch` hands it on. The root is the one this
/// platform would pass: `/nightly-data/...` has no drive prefix, so on Windows validation rightly refuses it.
fn launcher_argv(tail: &[&str]) -> Vec<String> {
let mut argv: Vec<std::ffi::OsString> = ["--launch-profile", "nightly-v1", "--profile-root", super::launch_profile::launcher_root(), "--"]
.iter()
.map(std::ffi::OsString::from)
.collect();
argv.extend(tail.iter().map(std::ffi::OsString::from));
let had_separator = super::launch_profile::had_launcher_separator(&argv);
let launch = craft_nightly::parse_startup(
crate::build_flavor::BuildFlavor::NightlyV1,
&crate::profile_root::spec(),
argv,
&craft_nightly::StartupOptions::new(),
)
.unwrap();
super::launch_profile::passthrough_args(launch.passthrough_args, had_separator).iter().map(|a| a.to_string_lossy().into_owned()).collect()
}
#[test]
fn the_launchers_separator_is_never_a_document() {
let (options, files) = split_at_delimiter(launcher_argv(&[]));
assert!(options.is_empty(), "{options:?}");
assert!(files.is_empty(), "the separator must not reach the documents: {files:?}");
}
#[test]
fn documents_after_the_separator_are_kept_in_order() {
let (options, files) = split_at_delimiter(launcher_argv(&["a.file"]));
assert!(options.is_empty(), "{options:?}");
assert_eq!(files, ["a.file"]);
let (_, files) = split_at_delimiter(launcher_argv(&["a.file", "--version", "--sample"]));
assert_eq!(files, ["a.file", "--version", "--sample"], "after -- every word is a document");
// A real document path, as Windows hands one on: kept whole, in order, backslashes and spaces intact.
let (_, files) = split_at_delimiter(launcher_argv(&[r"C:\Users\user\Holiday letter.docx", "a.file"]));
assert_eq!(files, [r"C:\Users\user\Holiday letter.docx", "a.file"], "a real path after -- stays a document, in order");
}
/// A document whose name looks like a LaunchServices option is one only after the separator: the strip
/// for macOS runs on the options, after the split, so `-- -NSNotes.docx report.docx` opens both.
#[test]
fn a_document_named_like_a_launch_argument_survives_the_separator() {
let (options, after) = split_at_delimiter(["-psn_0_12345", "--", "-NSNotes.docx", "report.docx"].map(String::from).to_vec());
assert!(super::without_launch_args(options).is_empty(), "the option before the separator goes");
let hazard: Vec<String> = ["-NSNotes.docx", "report.docx"].map(String::from).to_vec();
assert!(super::without_launch_args(hazard).is_empty(), "before the split the strip takes the document and the one after it");
assert_eq!(documents_to_open(Vec::new(), after), ["-NSNotes.docx", "report.docx"], "what follows the separator is opened, in order");
}
/// A stable line that carries its own separator: `a.file` before `--` opens before `b.file` after it.
/// The flag loop keeps `a.file` (its `_` arm, one push) and `documents_to_open` puts the two lists
/// back in command-line order; the reverse, appending the loop's list to the separator's, opened them
/// backwards (found in review of #7849).
#[test]
fn documents_before_the_separator_keep_their_place_before_the_ones_after_it() {
let (options, after) = split_at_delimiter(["--sample", "a.file", "--", "b.file"].map(String::from).to_vec());
assert_eq!(options, ["--sample", "a.file"], "--sample is a switch and a.file is left for the loop");
assert_eq!(documents_to_open(vec!["a.file".into()], after), ["a.file", "b.file"]);
let (_, after) = split_at_delimiter(launcher_argv(&["b.file"]));
assert_eq!(documents_to_open(Vec::new(), after), ["b.file"], "the Launcher sends nothing before the separator");
}
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
use crate::build_flavor::BuildFlavor;
assert!(super::refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!super::refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!super::refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!super::refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
+64
View File
@@ -0,0 +1,64 @@
//! The macOS application menu uses the same About dialog as File › About.
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, NativeMenu, mac_layout};
use serde_json::json;
use wordcraft_ui_egui::{WordApp, i18n};
const APP_NAME: &str = "WordCraft";
const ABOUT: &str = "About WordCraft";
/// The application menu, with `tr` the translation of an English string.
pub(super) fn layout(tr: &dyn Fn(&'static str) -> String) -> Layout {
let about = Item::new(CommandRef::with_params("ui.dialog", json!({"name": "about"})), tr(ABOUT)).role(ItemRole::About);
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into()]).role(MenuRole::App)]);
// `mac_layout` words About as the template; WordCraft's catalogs translate the whole label.
let label = |s: &'static str| tr(if s == "About {app}" { ABOUT } else { s });
let mut layout = mac_layout(&bar, &LayoutOptions::new(APP_NAME).label(&label));
// WordCraft's document menus live in its ribbon; keep only the application menu.
layout.bar.menus.retain(|menu| menu.role == MenuRole::App);
layout
}
fn lang(app: &WordApp) -> i18n::Lang {
i18n::Lang::from_pref(&app.ui.language)
}
fn layout_in(lang: i18n::Lang) -> Layout {
layout(&|s| i18n::tr(lang, s).to_owned())
}
pub(super) fn install(ctx: &egui::Context, app: &WordApp) -> Option<NativeMenu> {
let menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
if menu.is_none() {
log::warn!("the WordCraft application menu could not be installed");
}
menu
}
pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Context) {
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
for command in menu.take_clicks(ctx) {
if let Err(error) = app.run(&command.id, command.params) {
log::warn!("application menu: {error}");
}
}
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
let lang = lang(app);
for clash in menu.sync_with(lang.code(), || layout_in(lang)) {
log::warn!("application menu: {clash:?}");
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The catalogs translate "About WordCraft" and have no "About {app}" row.
#[test]
fn about_shows_the_catalogs_translation() {
let translate = |s: &'static str| if s == "About WordCraft" { "Über WordCraft".to_owned() } else { s.to_owned() };
let layout = layout(&translate);
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
assert_eq!(about.label, "Über WordCraft");
}
}
+266
View File
@@ -0,0 +1,266 @@
//! App-private Nightly session health, not telemetry or a Launcher protocol.
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
use std::fs::{File, OpenOptions};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// Write `bytes` to `path` through a fresh temporary file in the same folder and a rename: the
/// destination entry is replaced, never followed, so a link planted at `path` is not written
/// through. The file is synced and the folder is synced after the rename.
fn write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let directory = path.parent().ok_or_else(|| io::Error::other("the session record has no folder"))?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let temporary = directory.join(format!(".{name}.{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
let mut file = OpenOptions::new().write(true).create_new(true).open(&temporary)?;
let written = std::io::Write::write_all(&mut file, bytes).and_then(|()| file.sync_all());
drop(file);
if let Err(error) = written {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
if let Err(error) = std::fs::rename(&temporary, path) {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
if let Ok(directory) = File::open(directory) {
let _ = directory.sync_all();
}
Ok(())
}
/// The owner's session, shared by the app's exit hook (macOS: a quit ends the process inside
/// AppKit's terminate) and the code after the event loop.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage,
/// while Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version, commit)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is stable or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit.filter(|value| !value.is_empty()),
}))?;
write_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed
/// it yet, the record is left for the next owner to report; otherwise this is [`Self::complete`].
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Controlled event-loop completion includes a handled startup error, not only exit 0.
/// An unwind, abort, forced exit or killed process never calls this method.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path =
std::env::temp_dir().join(format!("wordcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unimportant = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
assert!(!unimportant.previous_unclean());
drop(unimportant); // Unwind/abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
// The window never started: no notice was shown.
let failed = Session::begin(Some(&fixture.0), "startup-failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The next start still sees the interruption and shows it.
let next = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
// The exit hook (macOS quit: the only path that runs there).
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
assert!(!successor.previous_unclean());
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
successor.complete().unwrap();
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
assert!(data["commit"].is_null(), "missing provenance must not be invented");
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
}
+6 -4
View File
@@ -10,14 +10,16 @@ use std::path::{Path, PathBuf};
use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SettingsStore, SharedSettings, Source};
use craft::window::restore::Store;
use wordcraft_ui_egui::prefs::{Prefs, import_legacy_window, legacy_ui_json};
use wordcraft_ui_egui::prefs::{Prefs, import_legacy_window, legacy_ui_json_slots};
/// The most of an old `ui.json` read for its window entry; the file is a few kilobytes.
const LEGACY_LIMIT: u64 = 8 << 20;
/// Whether this run reads and writes preferences. `WORDCRAFT_NO_PREFS` turns them off.
/// Whether this run reads and writes preferences. `WORDCRAFT_NO_PREFS` turns them off; a Nightly
/// profile always keeps its own, so an inherited developer switch cannot leave the app with no
/// preferences folder at all.
pub fn enabled() -> bool {
std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
crate::launch_profile::current().is_nightly() || std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
}
/// `custom-dictionary.txt` in the settings folder: the words Add to Dictionary kept (#40).
@@ -39,7 +41,7 @@ fn open_in(dir: Option<PathBuf>, placement: &mut Store) -> (SharedSettings<Prefs
None => OpenOptions::new(Location::Memory),
};
if let Some(dir) = &dir {
options = options.legacy(vec![LegacyFile { path: dir.join("ui.json"), parse: legacy_ui_json }]);
options = options.legacy(vec![LegacyFile { paths: vec![dir.join("ui.json")], parse: legacy_ui_json_slots }]);
}
let (store, report) = SettingsStore::<Prefs>::open_with(options);
if let Source::Legacy(path) = &report.source {
+70
View File
@@ -0,0 +1,70 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
use std::sync::OnceLock;
#[derive(Clone, Debug, thiserror::Error)]
pub enum IdentityError {
#[error("{0}")]
Configuration(String),
}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError::Configuration)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
+217
View File
@@ -0,0 +1,217 @@
//! App-owned nightly profile specification for `craft-nightly`; no stable fallback, migration or
//! process environment changes.
//!
//! WordCraft keeps all of its user state in one settings folder (`wordcraft_control_key::settings_dir`):
//! `config.toml`, `window.json`, `logs/`, `recovery/`, `fonts/`, `Templates/`,
//! `custom-dictionary.txt` and the control token files. The suite's shared font store
//! (`Craft Fonts` / `craft-fonts`, which also holds installed Language packs) is the one other
//! per-user folder the app writes, and Nightly points it at the profile too
//! (`wordcraft_engine::packs::use_font_store_in`). Every stable location of either is fenced here.
use std::ffi::OsString;
use std::path::PathBuf;
use craft_nightly::AppProfileSpec;
pub const APP_ID: &str = "wordcraft";
pub const DISPLAY_NAME: &str = "WordCraft";
pub const STABLE_PACKAGE_ID: &str = "ai.storyteller.wordcraft";
pub const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.wordcraft.nightly";
pub const STABLE_DIR_NAMES: &[&str] = &["wordcraft", "WordCraft", "craft-fonts", "Craft Fonts"];
pub const FORBIDDEN_ENV_VARS: &[&str] = &["WORDCRAFT_PROFILE_DIR"];
pub const FOLDER_ONLY_ENTRIES: &[&str] = &["recovery", "logs", "fonts", "Templates", "FontStore"];
/// Returns WordCraft's `craft-nightly` isolation specification, including OS-specific installation
/// and sandbox roots that must never overlap a nightly profile.
pub fn spec() -> AppProfileSpec {
spec_with(|key| std::env::var_os(key))
}
fn spec_with(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
AppProfileSpec {
app_id: APP_ID,
display_name: DISPLAY_NAME,
stable_dir_names: STABLE_DIR_NAMES,
stable_package_id: STABLE_PACKAGE_ID,
nightly_package_id: NIGHTLY_PACKAGE_ID,
profile_root_env: None,
forbidden_env_vars: FORBIDDEN_ENV_VARS,
portable_markers: &[],
folder_only_entries: FOLDER_ONLY_ENTRIES,
extra_forbidden_roots: extra_forbidden_roots_with(env),
}
}
#[cfg(any(unix, target_os = "windows"))]
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
let value = env(key)?;
if value.is_empty() {
return None;
}
let path = PathBuf::from(value);
if path.is_absolute() { Some(path) } else { None }
}
fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
let mut roots = Vec::new();
#[cfg(target_os = "windows")]
{
// Per-user and per-machine MSI install locations.
if let Some(local) =
non_empty_abs(&env, "LOCALAPPDATA").or_else(|| non_empty_abs(&env, "USERPROFILE").map(|p| p.join("AppData").join("Local")))
{
roots.push(local.join("Programs").join("ArtCraft").join("WordCraft"));
}
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs(&env, key) {
roots.push(base.join("ArtCraft").join("WordCraft"));
}
}
}
#[cfg(all(unix, not(target_os = "macos")))]
{
// Native packages' locations and the stable Flatpak's per-app data folder.
roots.extend(["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"].map(PathBuf::from));
if let Some(home) = non_empty_abs(&env, "HOME") {
roots.push(home.join(".var/app/ai.storyteller.wordcraft"));
}
}
#[cfg(target_os = "macos")]
{
roots.push(PathBuf::from("/Applications/WordCraft.app"));
if let Some(home) = non_empty_abs(&env, "HOME") {
let library = home.join("Library");
roots.push(library.join("Preferences/ai.storyteller.wordcraft.plist"));
roots.push(library.join("Saved Application State/ai.storyteller.wordcraft.savedState"));
roots.push(home.join("Applications/WordCraft.app"));
}
}
#[cfg(not(any(unix, target_os = "windows")))]
let _ = env;
roots
}
#[cfg(test)]
mod tests {
use super::{
APP_ID, DISPLAY_NAME, FOLDER_ONLY_ENTRIES, FORBIDDEN_ENV_VARS, NIGHTLY_PACKAGE_ID, STABLE_DIR_NAMES, STABLE_PACKAGE_ID,
extra_forbidden_roots_with, spec_with,
};
use craft_nightly::{ProfileError, validate_and_prepare_root};
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
struct TempRoot(PathBuf);
impl TempRoot {
fn new(label: &str) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate = std::env::temp_dir().join(format!(
"wordcraft-profile-spec-{label}-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
Self(root)
}
}
impl Drop for TempRoot {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn spec_preserves_wordcraft_isolation_contract() {
let spec = spec_with(|_| None);
assert_eq!(spec.app_id, APP_ID);
assert_eq!(spec.display_name, DISPLAY_NAME);
assert_eq!(spec.stable_dir_names, STABLE_DIR_NAMES);
assert_eq!(spec.stable_package_id, STABLE_PACKAGE_ID);
assert_eq!(spec.nightly_package_id, NIGHTLY_PACKAGE_ID);
assert_eq!(spec.profile_root_env, None);
assert_eq!(spec.forbidden_env_vars, FORBIDDEN_ENV_VARS);
assert!(spec.portable_markers.is_empty());
assert_eq!(spec.folder_only_entries, FOLDER_ONLY_ENTRIES);
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn linux_extra_forbidden_roots_cover_native_packages_and_stable_flatpak() {
let env = BTreeMap::from([(String::from("HOME"), OsString::from("/home/tester"))]);
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
assert!(roots.contains(&PathBuf::from("/usr/bin/wordcraft")));
assert!(roots.contains(&PathBuf::from("/usr/local/bin/wordcraft")));
assert!(roots.contains(&PathBuf::from("/opt/wordcraft")));
assert!(roots.contains(&PathBuf::from("/home/tester/.var/app/ai.storyteller.wordcraft")));
}
#[cfg(target_os = "macos")]
#[test]
fn macos_extra_forbidden_roots_cover_bundles_plist_and_saved_state() {
let env = BTreeMap::from([(String::from("HOME"), OsString::from("/Users/tester"))]);
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
assert!(roots.contains(&PathBuf::from("/Applications/WordCraft.app")));
assert!(roots.contains(&PathBuf::from("/Users/tester/Applications/WordCraft.app")));
assert!(roots.contains(&PathBuf::from("/Users/tester/Library/Preferences/ai.storyteller.wordcraft.plist")));
assert!(roots.contains(&PathBuf::from("/Users/tester/Library/Saved Application State/ai.storyteller.wordcraft.savedState")));
}
#[cfg(target_os = "windows")]
#[test]
fn windows_extra_forbidden_roots_cover_per_user_and_machine_installs() {
let env = BTreeMap::from([
(String::from("LOCALAPPDATA"), OsString::from(r"C:\Users\tester\AppData\Local")),
(String::from("ProgramFiles"), OsString::from(r"C:\Program Files")),
(String::from("ProgramFiles(x86)"), OsString::from(r"C:\Program Files (x86)")),
]);
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
assert!(roots.contains(&PathBuf::from(r"C:\Users\tester\AppData\Local\Programs\ArtCraft\WordCraft")));
assert!(roots.contains(&PathBuf::from(r"C:\Program Files\ArtCraft\WordCraft")));
assert!(roots.contains(&PathBuf::from(r"C:\Program Files (x86)\ArtCraft\WordCraft")));
}
#[test]
fn nightly_profile_reopens_and_enforces_folder_only_entries_and_extra_fences() {
let temp = TempRoot::new("reopen");
let fenced = temp.0.join("fenced-stable");
let mut spec = spec_with(|_| None);
spec.extra_forbidden_roots.push(fenced.clone());
let overlap = validate_and_prepare_root(&fenced.join("nightly"), &spec).unwrap_err();
assert!(matches!(overlap, ProfileError::ForbiddenRootOverlap { .. }));
assert!(!fenced.exists());
let private = temp.0.join("nightly-private");
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in FOLDER_ONLY_ENTRIES {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
assert_eq!(std::fs::read(private.join(name)).unwrap(), b"saved profile data", "{name} remains intact after reopen");
}
for name in FOLDER_ONLY_ENTRIES {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
let err = validate_and_prepare_root(&private, &spec).unwrap_err();
assert!(matches!(err, ProfileError::ExpectedDirectoryEntry(_)), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
}
@@ -0,0 +1,167 @@
//! Integration test for Linux Wayland client-side window decoration controls (#5814, #5375).
//!
//! Ensures that on Linux, client-side window controls use font-free Adwaita vector paths
//! so the close button is rendered as a clean vector cross rather than a square fallback,
//! and that sctk-adwaita has proper license attribution in NOTICE without bundling font files.
use std::path::Path;
/// Strips an unquoted TOML `#` comment from a single line.
fn strip_toml_comment(line: &str) -> &str {
let mut in_double = false;
let mut in_single = false;
for (idx, ch) in line.char_indices() {
match ch {
'"' if !in_single => in_double = !in_double,
'\'' if !in_double => in_single = !in_single,
'#' if !in_double && !in_single => return &line[..idx],
_ => {}
}
}
line
}
/// Extracts the comment-stripped body of a TOML table section by exact `[header]`.
fn toml_section(content: &str, header: &str) -> String {
let mut in_section = false;
let mut out = String::new();
for raw_line in content.lines() {
let line = strip_toml_comment(raw_line).trim();
if line.starts_with('[') && line.ends_with(']') {
if in_section {
break;
}
in_section = line == header;
continue;
}
if in_section && !line.is_empty() {
out.push_str(line);
out.push('\n');
}
}
assert!(in_section, "expected target section {header} in apps/wordcraft/Cargo.toml");
out
}
/// Parses the `features = [...]` string array from the `winit = { ... }` dependency entry in a TOML section.
fn winit_features(section: &str) -> Vec<&str> {
let winit_start = section.find("winit").expect("target section must declare a winit dependency");
let after_winit = &section[winit_start..];
let table_end = after_winit.find('}').expect("winit inline table must close with '}'");
let winit_table = &after_winit[..=table_end];
let features_start = winit_table.find("features").expect("winit dependency must declare features");
let after_features = &winit_table[features_start..];
let open_bracket = after_features.find('[').expect("winit features must open with '['");
let after_open = &after_features[open_bracket + 1..];
let close_bracket = after_open.find(']').expect("winit features must close with ']'");
let array_body = &after_open[..close_bracket];
array_body.split(',').map(|item| item.trim().trim_matches('"')).filter(|item| !item.is_empty()).collect()
}
/// Verifies that `apps/wordcraft/Cargo.toml` enables `wayland-csd-adwaita-notitle` for Linux.
#[test]
fn linux_manifest_enables_wayland_csd_adwaita_notitle() {
let cargo_toml = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
let content = std::fs::read_to_string(&cargo_toml).expect("read apps/wordcraft/Cargo.toml");
let linux_section = toml_section(&content, "[target.'cfg(target_os = \"linux\")'.dependencies]");
let linux_features = winit_features(&linux_section);
assert!(
linux_features.contains(&"x11") && linux_features.contains(&"wayland-csd-adwaita-notitle"),
"Linux winit dependency must enable x11 and wayland-csd-adwaita-notitle, got: {linux_features:?}"
);
let other_unix_section = toml_section(&content, "[target.'cfg(all(unix, not(any(target_os = \"macos\", target_os = \"linux\"))))'.dependencies]");
let other_unix_features = winit_features(&other_unix_section);
assert!(
other_unix_features.contains(&"x11") && !other_unix_features.contains(&"wayland-csd-adwaita-notitle"),
"Non-Linux Unix winit dependency must enable x11 without wayland-csd-adwaita-notitle, got: {other_unix_features:?}"
);
}
/// Verifies that `NOTICE` documents sctk-adwaita and its MIT licence.
#[test]
fn notice_documents_sctk_adwaita_attribution() {
let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().and_then(Path::parent).expect("workspace root");
let notice = std::fs::read_to_string(workspace_root.join("NOTICE")).expect("read NOTICE");
assert!(notice.contains("Linux Wayland window decorations"), "NOTICE must include 'Linux Wayland window decorations'");
assert!(notice.contains("sctk-adwaita"), "NOTICE must document sctk-adwaita");
assert!(notice.contains("Bartłomiej Maryńczak"), "NOTICE must retain sctk-adwaita's author copyright");
}
/// Parses `[[package]]` entries from `Cargo.lock` as `(name, version, dependencies)`.
fn parse_lockfile_packages(lockfile: &str) -> Vec<(&str, &str, Vec<&str>)> {
lockfile
.split("[[package]]")
.skip(1)
.filter_map(|chunk| {
let mut name = None;
let mut version = None;
let mut deps = Vec::new();
let mut in_deps = false;
for raw_line in chunk.lines() {
let line = raw_line.trim();
if in_deps {
if line == "]" {
in_deps = false;
continue;
}
let dep = line.trim_end_matches(',').trim().trim_matches('"');
if !dep.is_empty() {
deps.push(dep);
}
continue;
}
if let Some(rest) = line.strip_prefix("name = ") {
name = Some(rest.trim_matches('"'));
} else if let Some(rest) = line.strip_prefix("version = ") {
version = Some(rest.trim_matches('"'));
} else if line == "dependencies = [" {
in_deps = true;
}
}
Some((name?, version?, deps))
})
.collect()
}
/// Verifies that WordCraft's resolved Linux `winit` -> `sctk-adwaita` dependency path in
/// `Cargo.lock` does not pull in any title-font renderer crates.
#[test]
fn cargo_lock_contains_font_free_sctk_adwaita() {
use std::collections::{HashSet, VecDeque};
let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().and_then(Path::parent).expect("workspace root");
let lockfile = std::fs::read_to_string(workspace_root.join("Cargo.lock")).expect("read Cargo.lock");
let packages = parse_lockfile_packages(&lockfile);
let has_dep = |pkg_name: &str, target: &str| {
packages.iter().any(|(name, _, deps)| *name == pkg_name && deps.iter().any(|spec| spec.split_whitespace().next() == Some(target)))
};
assert!(has_dep("winit", "sctk-adwaita"), "winit in Cargo.lock must depend on sctk-adwaita");
let mut queue = VecDeque::new();
let mut visited = HashSet::new();
for (idx, (name, _, _)) in packages.iter().enumerate() {
if *name == "sctk-adwaita" && visited.insert(idx) {
queue.push_back(idx);
}
}
assert!(!queue.is_empty(), "Cargo.lock must include sctk-adwaita");
let forbidden = ["fontdue", "ab_glyph", "cosmic-text", "crossfont"];
while let Some(idx) = queue.pop_front() {
let (name, _, deps) = &packages[idx];
assert!(!forbidden.contains(name), "sctk-adwaita's resolved dependency path must not include title-font renderer {name}");
for spec in deps {
let mut parts = spec.split_whitespace();
let dep_name = parts.next().expect("dependency name");
let dep_ver = parts.next();
for (next_idx, (cand_name, cand_ver, _)) in packages.iter().enumerate() {
if *cand_name == dep_name && dep_ver.is_none_or(|v| v == *cand_ver) && visited.insert(next_idx) {
queue.push_back(next_idx);
}
}
}
}
}
+2
View File
@@ -2,5 +2,7 @@
mod appimage_env;
mod control_arg;
mod help;
#[cfg(target_os = "linux")]
mod linux_decorations;
#[cfg(unix)]
mod non_utf8_args;
+39
View File
@@ -0,0 +1,39 @@
# WordCraft app icon
A **page and pen**: a sheet of paper with a folded corner and ruled lines, with a fountain pen
lying across its lower right, on the app's blue field. It is drawn in the canvas palette the app's
own artwork uses (`#3b5bdb` field, `#efe9dc` paper, `#0b0b0c` ink).
`wordcraft.svg` is the canonical master: a full-bleed 512-unit tile with a rounded square
(`rx=112`) and no border. Windows and Linux use the tile as it is; the macOS renders sit on
Apple's grid, an 824/1024 body with a transparent margin.
## Files
- `wordcraft.svg`: canonical master (also the hicolor scalable icon).
- `wordcraft-1024.png`: 1024 px full-bleed render.
- `wordcraft-macos-512.png`: the padded macOS render (Dock, window icon; embedded by the app).
- `wordcraft.icns`: macOS bundle icon (`CFBundleIconFile`), padded frames.
- `wordcraft.ico`: Windows icon, 16–256 px, embedded in `wordcraft.exe` by
`apps/wordcraft/build.rs`.
- `hicolor/<size>/apps/ai.storyteller.wordcraft.png` (16–512) and `hicolor/scalable/...svg`:
Linux icon theme.
## Regenerate
Replace `wordcraft.svg`, then run `packaging/icons.sh`. It needs `resvg`, plus `iconutil` on macOS;
`cargo run -p xtask -- ico` packs the Windows icon.
## Nightly channel
The Nightly icons keep the drawing, its alpha and the macOS padding exactly as the stable renders
have them. Only the background contribution changes: from the app blue to the deeper Nightly
background `#232c67`. There is no letter badge, crescent or other mark; the app and the Launcher
name the channel in text.
`packaging/nightly-icons.py` derives the four files from the committed stable renders (the `.ico`
frames, the `.icns` slots, the 256 px hicolor render and the padded 512 px macOS master) and
records their hashes in [`nightly-provenance.json`](nightly-provenance.json). `--check` re-derives
them and compares. The three smallest macOS slots (16, 32 and 64 px) are box-filtered from the
padded master; every other frame is the same size as the stable frame it comes from, so nothing is
upscaled. The stable files are not modified.
+72
View File
@@ -0,0 +1,72 @@
{
"title": "WordCraft nightly deep-background icons",
"author": "@skylartaylor",
"license": "MIT OR Apache-2.0",
"source_commit": null,
"inputs": [
{
"path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.wordcraft.png",
"sha256": "7c1791408282d01e8c5d0cb1f4080971eaa412c60518694a1cec1e60b23c7406",
"purpose": "Windows/Linux native256 master"
},
{
"path": "assets/app-icon/wordcraft.ico",
"sha256": "53a23dcf66260f44d87d4d143d633395f3e967f391eda47e6e9cc3a52f820225",
"purpose": "nine full-bleed frames, 16-256 px"
},
{
"path": "assets/app-icon/wordcraft.icns",
"sha256": "02ac9dcb7ee06858416c7ef70ca2b359cad38dbef4a0b526bb1f28953d90170f",
"purpose": "padded macOS frames, 32-1024 px"
},
{
"path": "assets/app-icon/wordcraft-macos-512.png",
"sha256": "5a8a4476c1fb67123f803a8ab7a7a0dbd9912675ae54d695c17e74454913ceae",
"purpose": "padded macOS master (box-filtered down to the 16/32/64 px slots, never upscaled)"
}
],
"method": {
"kind": "derived from the project-owned stable renders by a committed, reproducible script",
"original_palette": {
"ink": "#0b0b0c",
"paper": "#efe9dc",
"background": "#3b5bdb"
},
"nightly_background": "#232c67",
"transform": "Decompose every pixel in the stable three-colour palette (ink, paper, background) and rebuild it with the Nightly background, keeping the ink and paper weights, alpha and padding. Clamped and renormalised where an antialiased pixel falls outside the triangle. No crescent, letter or badge.",
"generator": "packaging/nightly-icons.py",
"generator_sha256": "7a31bc6d3a00d991cf4fd6b1f2ce06b3bdc9201525d207ba84a935a877ee8e4a",
"reproduce": "python3 packaging/nightly-icons.py --check"
},
"outputs": {
"assets/app-icon/wordcraft-nightly.png": "43a002255f6db703599de99224cd47274905b8742d92f91d0f7c41c8cb5656e2",
"assets/app-icon/wordcraft-nightly.ico": "f4bb314bb6c8c131c7250e441407be5e22e645579881f0a80fe7bd963adda54a",
"assets/app-icon/wordcraft-nightly-1024.png": "36e21d31b852ac222c787ee27af45667882353eb9b1c3bfb62a9038c17843b25",
"assets/app-icon/wordcraft-nightly.icns": "0b359aa7f07fda079298a97215da207486ca092bbe9c6b277a5de3d3fbc4f9ef"
},
"ico_frame_sizes": [
16,
20,
24,
32,
40,
48,
64,
128,
256
],
"icns_png_slots": {
"icp4": 16,
"icp5": 32,
"icp6": 64,
"ic07": 128,
"ic08": 256,
"ic13": 256,
"ic09": 512,
"ic14": 512,
"ic10": 1024,
"ic11": 32,
"ic12": 64
},
"validation": "Every output is re-derived from the committed inputs by the committed script (--check) and compared by SHA-256; the frames' pixel dimensions and the containers' members are checked while deriving; the foreground and padding were compared visually against the stable renders. Native Explorer/Finder qualification is unrun."
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

+2
View File
@@ -209,5 +209,7 @@ real_name = "Helen Kwok"
[people.ashokram-si]
real_name = "Ashok Ram"
[people.reubgr]
real_name = "Reuben Grinberg"
[people.benandez]
sync_github_name = true
+96
View File
@@ -0,0 +1,96 @@
# DOCX corpus (local only)
This directory is where a local, real-world DOCX corpus can live for the opt-in
`cargo xtask docx-corpus` harness. **The corpus is never committed.** `/corpus` is
git-ignored; only this README is tracked. Never commit Word-produced files, documents
you do not have the right to redistribute, or any proprietary template, theme, font
or image. Word-produced documents are useful locally, including ones you made
yourself, but they must stay untracked.
## Populate it
Put `.docx` files anywhere under this directory (subfolders are walked, symlinks are
skipped):
```sh
mkdir -p corpus/docx/mine
cp ~/Documents/report.docx corpus/docx/mine/
```
Useful sources for a local corpus:
- documents you wrote yourself, exported from Word, Google Docs, LibreOffice or Pages;
- public-domain or openly licensed DOCX samples whose licence allows local testing;
- synthetic files generated by WordCraft (`wordcraft-cli run --template sample --save …`);
- deliberately broken files for the failure path (a text file renamed `.docx`, a
truncated ZIP, a package missing `word/document.xml`).
Keep a note of where each file came from. If a corpus must be shared, share the
manifest and the harness report, not the documents.
## Run it
```sh
# The runner builds wordcraft-cli before every run (a no-op when it is current).
cargo xtask docx-corpus --dir corpus/docx
cargo xtask docx-corpus --dir corpus/docx --out target/docx-corpus/report.json
cargo xtask docx-corpus --dir corpus/docx --all-pages
cargo xtask docx-corpus --dir corpus/docx --timeout 120 --cli target/debug/wordcraft-cli
```
Options:
| Option | Meaning |
|---|---|
| `--dir <path>` | corpus directory (required) |
| `--out <path>` | JSON report path (default `target/docx-corpus/report.json`); the Markdown summary is written beside it with an `.md` extension |
| `--all-pages` | render every page instead of only page 1 (capped at 2,000 pages per file) |
| `--timeout <secs>` | per-child-process timeout, default 60, maximum 3,600 |
| `--cli <path>` | use a specific `wordcraft-cli` binary |
| `-h`, `--help` | usage |
A missing or empty corpus directory is not an error: the command explains what is
missing and exits successfully.
## What each file goes through
Every `.docx` is handled in child `wordcraft-cli` processes, each with the timeout
above, so one hostile or hanging file cannot stop the run:
1. **Open + inspect** — `wordcraft-cli info` gives page and word counts; `wordcraft-cli text`
gives the plain text baseline.
2. **Render** — page 1 to PNG (`--all-pages` renders every page). Images go to
`<report-stem>-artifacts/<index>-<file>/page-NNNN.png` beside the report.
3. **Save** — `wordcraft-cli convert` writes a temporary `.docx` copy under the system
temporary directory.
4. **Reopen + compare** — the copy is opened again for page count and plain text. The
temporary copy is then deleted.
The report records file name, bytes, open time, page count, word count, render time,
round-trip time, rendered images, and every failure. Failures are classified as:
| Kind | Meaning |
|---|---|
| `open` | the file could not be opened or inspected (invalid package, encrypted, timeout, oversized, …) |
| `render` | page rendering failed |
| `save` | saving the temporary copy failed |
| `reopen` | the saved copy could not be opened or its text read |
| `text_mismatch` | reopened plain text differs from the original |
| `page_count_delta` | reopened page count differs from the original |
The JSON report is deterministic for the same corpus and arguments apart from the
timing fields: files are sorted by relative path, failure counts are always present,
and there is no timestamp. The Markdown summary is a short human-readable table.
## Limits
- This harness measures open/render/save/reopen and text/page stability. It does **not**
compare with Word's own rendering or page count, and it does not fix document bugs.
A Word-vs-WordCraft visual comparison is a separate task.
- PNG rendering is a smoke test that the page can be produced, not a fidelity score.
- Files are treated as hostile: recursion depth, file count, file size, render pages and
child output are capped, and symlinks are skipped. The caps are deliberately generous
for normal documents; a file above them is reported as a failure rather than skipped
silently.
- The corpus and its reports stay local. `target/` is git-ignored too, so reports do not
enter commits.
+1 -1
View File
@@ -1 +1 @@
e56d26244bbac099bfd42e23fb12f78a4be418a7
217f4130d7d3dbb21a160f23f6b0021918906cc0
+33 -1
View File
@@ -4,14 +4,34 @@
use std::path::{Path, PathBuf};
/// The folder the desktop app chose before any of its state was read: a Launcher-selected
/// Nightly profile (`launch_profile`). Set once, at startup, before the first [`settings_dir`]
/// call; tests and the CLI leave it unset.
static CHOSEN: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
/// Point [`settings_dir`] at `dir` for this process. Fails when a folder was already chosen.
pub fn use_settings_dir(dir: PathBuf) -> Result<(), String> {
CHOSEN.set(dir).map_err(|_| "the settings folder was already selected".into())
}
/// The app's settings folder (preferences, logs, token files): macOS
/// `~/Library/Application Support/WordCraft`, Windows `%APPDATA%\WordCraft`, otherwise
/// `$XDG_CONFIG_HOME/wordcraft` or `~/.config/wordcraft`.
/// `WORDCRAFT_PROFILE_DIR` overrides the entire folder for isolated runs.
/// A folder chosen by the app through [`use_settings_dir`] wins: it is a launch decision, not
/// an environment variable a child or a wrapper might have inherited. `WORDCRAFT_PROFILE_DIR`
/// overrides the entire folder for isolated runs otherwise.
pub fn settings_dir() -> Option<PathBuf> {
if let Some(path) = CHOSEN.get() {
return Some(path.clone());
}
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
return Some(PathBuf::from(path));
}
platform_settings_dir()
}
/// The platform's own folder, when nothing chose one (see [`settings_dir`]).
fn platform_settings_dir() -> Option<PathBuf> {
if cfg!(target_os = "macos") {
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
} else if cfg!(windows) {
@@ -67,6 +87,18 @@ mod tests {
assert_eq!(parse_instance_id("app=ai.storyteller.wordcraft\n"), None);
}
#[test]
fn a_chosen_folder_wins_over_the_environment() {
// The chosen folder is process-wide and set once, so this test only reads the rule when
// nothing chose one (the crate's own tests and the CLI never do).
if CHOSEN.get().is_none() {
assert_eq!(settings_dir(), super::platform_settings_dir());
assert!(use_settings_dir(PathBuf::from("/chosen/profile")).is_ok());
assert_eq!(settings_dir().as_deref(), Some(std::path::Path::new("/chosen/profile")));
assert!(use_settings_dir(PathBuf::from("/other")).is_err(), "the folder is selected once");
}
}
#[test]
fn key_file_per_instance() {
let dir = Path::new("/settings/wordcraft");
+30 -8
View File
@@ -703,25 +703,44 @@ impl Document {
}
/// A drawing id no shape uses yet (for gluing a connector to a shape that has none).
///
/// Returns one past the largest in-use shape id across the body, all secondary parts, and
/// footnote/endnote separator stories (walking nested groups and tables); if `u32::MAX` is
/// already in use, falls back via [`free_id`] to the smallest unused non-zero id (or `0` only
/// if every non-zero `u32` id is taken).
pub fn next_shape_id(&self) -> u32 {
let mut max = 0u32;
let mut largest: Option<u32> = None;
let mut used: Vec<u32> = Vec::new();
let mut record = |id: u32| {
if id != 0 {
largest = largest.max(Some(id));
used.push(id);
}
};
let mut see = |o: &InlineObject| match o {
InlineObject::Shape { extra, .. } => max = max.max(extra.id),
InlineObject::Shape { extra, .. } => record(extra.id),
InlineObject::Group { children, .. } => {
for c in children {
if let InlineObject::Shape { extra, .. } = &c.obj {
max = max.max(extra.id);
let mut todo: Vec<&InlineObject> = children.iter().map(|c| &c.obj).collect();
while let Some(obj) = todo.pop() {
match obj {
InlineObject::Shape { extra, .. } => record(extra.id),
InlineObject::Group { children, .. } => todo.extend(children.iter().map(|c| &c.obj)),
_ => {}
}
}
}
_ => {}
};
for blocks in std::iter::once(&self.body).chain(self.parts.values().map(|p| &p.blocks)) {
let sep_stories = [&self.footnote_separators, &self.endnote_separators]
.into_iter()
.flat_map(|s| [&s.separator, &s.continuation_separator, &s.continuation_notice])
.flatten();
for blocks in std::iter::once(&self.body).chain(self.parts.values().map(|p| &p.blocks)).chain(sep_stories) {
for b in blocks {
edit::each_para(b, 0, &mut |p| p.objects.iter().for_each(&mut see));
}
}
max.saturating_add(1).max(1)
free_id(largest, used.into_iter(), 1).unwrap_or(0)
}
/// Change every inline object in every story (paragraphs inside tables too), copying only
@@ -798,7 +817,10 @@ impl Document {
stories.extend(self.parts.values_mut().map(|p| &mut p.blocks));
for blocks in stories {
for b in blocks.iter_mut() {
edit::each_para_mut(Arc::make_mut(b), 0, &mut Paragraph::normalize);
edit::each_para_mut(Arc::make_mut(b), 0, &mut |p: &mut Paragraph| {
p.normalize();
p.reconcile_objects();
});
}
}
}
+277 -50
View File
@@ -7,7 +7,7 @@ use std::sync::Arc;
use serde::{Deserialize, Serialize};
use crate::para::{InlineObject, Run};
use crate::para::{InlineObject, OBJ, 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,8 +26,41 @@ 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 {
self.to_document().plain_text(crate::StoryRef::Body)
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
}
/// The fragment as the body of a new document (default styles).
pub fn to_document(&self) -> Document {
@@ -67,9 +100,20 @@ impl Fragment {
found
}
/// The text a copy puts on the clipboard: [`Self::plain_text`] with symbol-font characters
/// (Wingdings…) as their Unicode equivalents.
/// (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).
pub fn clipboard_text(&self) -> String {
self.to_document().shown_text(crate::StoryRef::Body)
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
}
/// 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
@@ -603,6 +647,61 @@ fn remap_media_block(b: &mut Block, map: &BTreeMap<String, String>) {
});
}
/// Remaps media references across `blocks` and any text box stories in `parts`.
fn remap_media_in(blocks: &mut [Block], parts: &mut BTreeMap<u32, Part>, map: &BTreeMap<String, String>) {
if map.is_empty() {
return;
}
for b in blocks {
remap_media_block(b, map);
}
for part in parts.values_mut() {
for b in &mut part.blocks {
remap_media_block(Arc::make_mut(b), map);
}
}
}
/// 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
@@ -1340,6 +1439,22 @@ 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();
@@ -1352,21 +1467,17 @@ 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 _ = 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));
let clear = i == b.path.last() && to < p.len();
out.push(Block::Para(trim_para(p, from, to, clear)));
}
Block::Table(t) => out.push(Block::Table(t.clone())),
Block::Table(_) => out.push((**blk).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)
@@ -1374,17 +1485,92 @@ impl Document {
out.push(blk.clone());
return out;
}
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));
// 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());
}
}
// 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
}
@@ -1470,13 +1656,41 @@ impl Document {
Some(id)
}
/// The blocks of `frag`, a fragment of another document, with every text box given a new
/// story of its own here copied from the fragment's parts (as a paste does), to place them
/// in this document; a box the fragment has no story for keeps none.
/// Copies `media` into `self.media`, returning a remap for keys whose bytes differ from an
/// existing entry under the same key.
fn adopt_media(&mut self, media: &BTreeMap<String, Arc<Vec<u8>>>) -> BTreeMap<String, String> {
let mut media_remap = BTreeMap::new();
for (k, v) in media {
if let Some(existing) = self.media.get(k) {
if existing.as_slice() != v.as_slice() {
let ext = k.rsplit_once('.').map_or("png", |(_, ext)| ext);
let new_key = self.add_media((**v).clone(), ext);
media_remap.insert(k.clone(), new_key);
}
} else {
self.media.insert(k.clone(), v.clone());
}
}
media_remap
}
/// The blocks of `frag`, a fragment of another document, with its media copied (remapping
/// conflicting keys) and every text box given a new story of its own here copied from the
/// fragment's parts (as a paste does), to place them in this document; a box the fragment
/// has no story for keeps none.
pub fn adopt_fragment(&mut self, frag: &Fragment) -> Vec<Block> {
let media_remap = self.adopt_media(&frag.media);
let mut blocks = frag.blocks.clone();
let mut remapped_parts;
let parts = if media_remap.is_empty() {
&frag.parts
} else {
remapped_parts = frag.parts.clone();
remap_media_in(&mut blocks, &mut remapped_parts, &media_remap);
&remapped_parts
};
let mut budget = BoxBudget { local: false, ..BoxBudget::new() };
self.adopt_text_boxes(&mut blocks, &frag.parts, 0, &mut budget);
self.adopt_text_boxes(&mut blocks, parts, 0, &mut budget);
if budget.skipped > 0 {
log::warn!(
"{} text boxes are left empty; their stories are past what one copy brings ({MAX_PASTED_BOXES} stories, {MAX_PASTED_BOX_BYTES} bytes)",
@@ -1488,18 +1702,7 @@ impl Document {
/// Insert a fragment at `pos`; returns the position after the pasted content.
pub fn insert_fragment(&mut self, pos: &Pos, frag: &Fragment) -> Result<Pos> {
let mut media_remap = BTreeMap::new();
for (k, v) in &frag.media {
if let Some(existing) = self.media.get(k) {
if existing.as_slice() != v.as_slice() {
let ext = k.rsplit_once('.').map_or("png", |(_, ext)| ext);
let new_key = self.add_media((**v).clone(), ext);
media_remap.insert(k.clone(), new_key);
}
} else {
self.media.insert(k.clone(), v.clone());
}
}
let media_remap = self.adopt_media(&frag.media);
// Tables that would nest deeper than the limit here become their paragraphs (#1596).
let room = MAX_TABLE_DEPTH.saturating_sub(pos.path.depth());
let mut blocks = Vec::with_capacity(frag.blocks.len());
@@ -1509,20 +1712,14 @@ impl Document {
if blocks.is_empty() {
return Ok(pos.clone());
}
if self.para_at(pos).is_none() {
let Some(dest_para) = self.para_at(pos) else {
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 {
remap_media_block(b, &media_remap);
}
for part in parts.values_mut() {
for b in &mut part.blocks {
remap_media_block(Arc::make_mut(b), &media_remap);
}
}
}
remap_media_in(&mut blocks, &mut parts, &media_remap);
// Pasted text boxes get stories of their own (never shared with the copy's source).
let mut budget = BoxBudget::new();
self.adopt_text_boxes(&mut blocks, &parts, 0, &mut budget);
@@ -1538,6 +1735,7 @@ 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();
@@ -1548,6 +1746,13 @@ 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() });
}
@@ -1559,13 +1764,28 @@ 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.is_empty() { pprops } else { keep };
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;
}
}
t @ Block::Table(_) => {
self.insert_block(pos.story, &left.with_last(idx), t)?;
@@ -1606,6 +1826,13 @@ 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;
+385
View File
@@ -118,6 +118,182 @@ 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);
@@ -304,6 +480,33 @@ 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"]);
@@ -989,6 +1192,61 @@ fn insert_fragment_remaps_conflicting_media_keys() {
assert_eq!(remapped, other_key);
}
#[test]
fn adopt_fragment_copies_and_remaps_conflicting_media_in_blocks_and_text_boxes() {
let mut d = doc(&["destination"]);
d.media.insert("image1.png".into(), Arc::new(vec![1, 1, 1]));
let mut frag_media = std::collections::BTreeMap::new();
frag_media.insert("image1.png".into(), Arc::new(vec![2, 2, 2]));
frag_media.insert("missing.png".into(), Arc::new(vec![3, 3, 3]));
let img = |key: &str| InlineObject::Image {
media: key.into(),
w: 10.0,
h: 10.0,
alt: String::new(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
};
let mut tb_para = Paragraph::with_text(&crate::para::OBJ.to_string(), CharProps::default());
tb_para.objects.push(img("image1.png"));
let mut parts = std::collections::BTreeMap::new();
parts.insert(7, Part { kind: PartKind::TextBox, blocks: vec![para_block(tb_para)], body: Default::default() });
let mut top_para = Paragraph::with_text(&format!("{}{}", crate::para::OBJ, crate::para::OBJ), CharProps::default());
top_para.objects.push(img("missing.png"));
top_para.objects.push(InlineObject::Shape {
kind: crate::para::ShapeKind::TextBox,
w: 40.0,
h: 40.0,
fill: None,
stroke: None,
stroke_width: 1.0,
float: Default::default(),
story: Some(7),
freeform: None,
effects: Default::default(),
extra: Default::default(),
});
let frag = Fragment { blocks: vec![Block::Para(top_para)], parts, media: frag_media };
let adopted = d.adopt_fragment(&frag);
assert_eq!(d.media["image1.png"].as_slice(), &[1, 1, 1]);
assert_eq!(d.media["missing.png"].as_slice(), &[3, 3, 3]);
let remapped_key = d.media.keys().find(|k| k.as_str() != "image1.png" && k.as_str() != "missing.png").unwrap();
assert_eq!(d.media[remapped_key].as_slice(), &[2, 2, 2]);
let adopted_para = adopted[0].as_para().unwrap();
assert!(matches!(&adopted_para.objects[0], InlineObject::Image { media, .. } if media == "missing.png"));
let adopted_tb_id = adopted_para.objects[1].text_box().unwrap();
let adopted_tb_para = d.parts[&adopted_tb_id].blocks[0].as_para().unwrap();
assert!(matches!(&adopted_tb_para.objects[0], InlineObject::Image { media, .. } if media == remapped_key));
}
/// #6788: splitting a paragraph after its first letters leaves the drop cap on the first
/// paragraph only; the new one (also when it is empty) is plain. A split at offset 0 is unchanged.
#[test]
@@ -1023,3 +1281,130 @@ 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"]);
}
+145 -9
View File
@@ -109,6 +109,55 @@ pub struct Numbering {
pub nums: Vec<Num>,
}
/// Borrowed definition lookups for a walk over immutable numbering. The first occurrence of
/// each id wins, as in the linear methods; the public vectors and saved data are unchanged.
pub struct NumberingIndex<'a> {
nums: HashMap<u32, &'a Num>,
abstracts: HashMap<u32, &'a AbstractNum>,
}
impl<'a> NumberingIndex<'a> {
pub fn new(numbering: &'a Numbering) -> Self {
let mut nums = HashMap::new();
let mut abstracts = HashMap::new();
for n in &numbering.nums {
nums.entry(n.id).or_insert(n);
}
for a in &numbering.abstracts {
abstracts.entry(a.id).or_insert(a);
}
Self { nums, abstracts }
}
pub fn num(&self, id: u32) -> Option<&'a Num> {
self.nums.get(&id).copied()
}
pub fn abstract_of(&self, num: u32) -> Option<&'a AbstractNum> {
self.abstract_for(self.num(num)?)
}
fn abstract_for(&self, num: &Num) -> Option<&'a AbstractNum> {
self.abstracts.get(&num.abstract_id).copied()
}
pub fn level(&self, num: u32, level: u8) -> Option<&'a Level> {
let n = self.num(num)?;
n.level(self.abstract_for(n), level)
}
/// Whether a paragraph has a defined label, without advancing the counters.
pub fn shows_label(&self, num: u32, level: u8) -> bool {
self.num(num).is_some_and(|n| self.abstract_for(n).is_some_and(|a| n.level(Some(a), level.min(8)).is_some()))
}
}
impl Num {
fn level<'a>(&'a self, abstract_num: Option<&'a AbstractNum>, level: u8) -> Option<&'a Level> {
self.level_overrides.iter().find(|(i, _)| *i == level).map(|(_, l)| l).or_else(|| abstract_num?.levels.get(level as usize))
}
}
/// Built-in list kinds for the Bullets / Numbering / Multilevel galleries.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -321,10 +370,28 @@ impl Counters {
/// Advance the counter for `num`/`level` and return the label (`"1."`, `"a)"`, `"•"`).
pub fn next_label(&mut self, numbering: &Numbering, num: u32, level: u8) -> Option<(String, Level)> {
let n = numbering.num(num)?;
let abs = numbering.abstracts.iter().find(|a| a.id == n.abstract_id)?;
self.next_label_from(n, abs, level)
}
/// Like [`Self::next_label`], using one walk's borrowed definition index.
pub fn next_label_indexed(&mut self, numbering: &NumberingIndex<'_>, num: u32, level: u8) -> Option<(String, Level)> {
let n = numbering.num(num)?;
let abs = numbering.abstract_for(n)?;
self.next_label_from(n, abs, level)
}
/// Like [`Self::values`], using one walk's borrowed definition index.
pub fn values_indexed(&self, numbering: &NumberingIndex<'_>, num: u32) -> Option<[u32; 9]> {
let abs = numbering.abstract_of(num)?;
Some(self.state.get(&abs.id).copied().unwrap_or([0; 9]))
}
fn next_label_from(&mut self, n: &Num, abs: &AbstractNum, level: u8) -> Option<(String, Level)> {
let num = n.id;
let lv = (level as usize).min(8);
// This list's own definition of a level wins over its abstract list's.
let level_def = |k: usize| numbering.level(num, k as u8);
let level_def = |k: usize| n.level(Some(abs), k as u8);
// A "none" level (Word's numFmt none) still counts and restarts the levels below it; only
// its number reads as nothing, so its literal text ("RESPONSE:") shows (#4985).
let def = level_def(lv)?.clone();
@@ -378,7 +445,7 @@ impl Counters {
let vals = *st;
let started = *fl;
let numeric = def.format != NumFormat::Bullet;
let label = if numeric { render_label(numbering, num, &def, &vals, &started) } else { def.text.clone() };
let label = if numeric { render_label(level_def, &def, &vals, &started) } else { def.text.clone() };
// A "none" level shows its literal text, but has no number of its own for a reference to
// show (#4985): it is kept as one that shows none.
let counted = if def.format == NumFormat::None {
@@ -400,18 +467,19 @@ impl Counters {
/// the last paragraph at that level showed (`"14."` while walking clause 14's sub-clauses).
/// `None` for a bullet or "none" level, or a level the list doesn't define.
pub fn current_label(&self, numbering: &Numbering, num: u32, level: u8) -> Option<String> {
let abs = numbering.abstract_of(num)?;
let n = numbering.num(num)?;
let abs = numbering.abstracts.iter().find(|a| a.id == n.abstract_id)?;
if let Some(last) = self.labels.get(&(abs.id, level.min(8))) {
return last.label.clone();
}
// A deeper item can count a level implicitly without rendering a paragraph there.
let def = numbering.level(num, level.min(8))?;
let def = n.level(Some(abs), level.min(8))?;
if matches!(def.format, NumFormat::None | NumFormat::Bullet) {
return None;
}
let vals = self.state.get(&abs.id).copied().unwrap_or([0; 9]);
let started = self.flags.get(&abs.id).copied().unwrap_or_default();
Some(render_label(numbering, num, def, &vals, &started))
Some(render_label(|k| n.level(Some(abs), k as u8), def, &vals, &started))
}
/// Levels shown by the last rendered label, or the current definition for an implicit level.
@@ -444,8 +512,7 @@ pub fn template_levels(text: &str) -> Vec<usize> {
}
/// Render a list label without advancing counters, retaining the existing hostile-input caps.
fn render_label(numbering: &Numbering, num: u32, def: &Level, vals: &[u32; 9], started: &[LevelFlags; 9]) -> String {
let level_def = |k: usize| numbering.level(num, k as u8);
fn render_label<'a>(level_def: impl Fn(usize) -> Option<&'a Level>, def: &Level, vals: &[u32; 9], started: &[LevelFlags; 9]) -> String {
let mut label = String::new();
// Word's level text is short; .docx and the lists command already cap it at 64.
let mut chars = def.text.chars().take(MAX_LEVEL_TEXT).peekable();
@@ -457,10 +524,11 @@ fn render_label(numbering: &Numbering, num: u32, def: &Level, vals: &[u32; 9], s
let k = (d as usize).saturating_sub(1).min(8);
let val = vals.get(k).copied().unwrap_or(0);
let counted = started.get(k).is_some_and(|f| f.started);
let val = if counted { val } else { level_def(k).map(|l| l.start).unwrap_or(1) };
let level = level_def(k);
let val = if counted { val } else { level.map_or(1, |l| l.start) };
// Legal numbering (w:isLgl) shows every level in Arabic digits, whatever its own
// format (二 of a Chinese outline becomes 2 in "2.1"); a "none" level stays empty.
let fmt = match level_def(k).map(|l| l.format).unwrap_or(NumFormat::Decimal) {
let fmt = match level.map_or(NumFormat::Decimal, |l| l.format) {
f @ (NumFormat::DecimalZero | NumFormat::None) => f,
_ if def.legal => NumFormat::Decimal,
f => f,
@@ -773,4 +841,72 @@ mod tests {
let mut c = Counters::default();
assert_eq!(c.next_label(&n, r, 0).unwrap().0, "Part V");
}
#[test]
fn definition_index_keeps_first_ids_overrides_and_missing_definitions() {
let override_level = Level { start: 0, text: "own %1".into(), ..Default::default() };
let n = Numbering {
abstracts: vec![
AbstractNum { id: 7, levels: levels_for(ListKind::Numbered), ..Default::default() },
AbstractNum { id: 7, levels: levels_for(ListKind::Bullet), ..Default::default() },
AbstractNum { id: 8, levels: Vec::new(), ..Default::default() },
],
nums: vec![
Num { id: 0, abstract_id: 7, ..Default::default() },
Num { id: 1, abstract_id: 7, ..Default::default() },
Num { id: 1, abstract_id: 8, ..Default::default() },
Num { id: 2, abstract_id: 99, level_overrides: vec![(0, override_level.clone())], ..Default::default() },
Num { id: 3, abstract_id: 8, level_overrides: vec![(0, override_level), (0, Level::default())], ..Default::default() },
],
};
let index = NumberingIndex::new(&n);
for id in [0, 1, 2, 3, 7, 99, u32::MAX] {
assert_eq!(index.num(id), n.num(id));
assert_eq!(index.abstract_of(id), n.abstract_of(id));
for level in [0, 1, 2, 8, 9, u8::MAX] {
assert_eq!(index.level(id, level), n.level(id, level));
assert_eq!(index.shows_label(id, level), n.shows_label(id, level));
}
}
assert_eq!(index.level(3, 0).unwrap().start, 0);
assert!(index.level(2, 0).is_some(), "a local override exists even without its abstract");
assert!(!index.shows_label(2, 0), "counting still requires the abstract list");
}
#[test]
fn indexed_counters_preserve_shared_state_starts_and_restarts() {
let mut n = Numbering::default();
let a = n.add_list(ListKind::Legal);
let b = n.restart(a).unwrap();
let bullet = n.add_list(ListKind::Bullet);
let none = n.add_list(ListKind::Numbered);
n.abstracts[0].levels[0].start = 0;
n.abstracts[0].levels[1].restart_after = Some(1);
n.abstracts[0].levels[2].restart = false;
n.abstracts[0].levels[3].format = NumFormat::DecimalZero;
n.nums[0].start_overrides = vec![(1, 5), (1, 99)];
n.nums[1].start_overrides = vec![(0, 9), (2, 0)];
n.nums[1].level_overrides = vec![
(2, Level { format: NumFormat::UpperRoman, text: "%1.%2.%3.".into(), legal: true, ..Default::default() }),
(2, Level { format: NumFormat::None, ..Default::default() }),
];
let literal = &mut n.abstracts.last_mut().unwrap().levels[0];
literal.format = NumFormat::None;
literal.text = "RESPONSE: %1".into();
literal.legal = true;
let index = NumberingIndex::new(&n);
let (mut linear, mut indexed) = (Counters::default(), Counters::default());
let sequence = [(a, 2), (a, 0), (a, 1), (a, 2), (a, 1), (b, 2), (b, 0), (a, 2), (a, 3), (bullet, 0), (none, 0), (a, 255), (999, 0)];
for (num, level) in sequence.into_iter().cycle().take(120) {
assert_eq!(indexed.next_label_indexed(&index, num, level), linear.next_label(&n, num, level), "{num}/{level}");
for id in [a, b, bullet, none, 999] {
assert_eq!(indexed.values_indexed(&index, id), linear.values(&n, id));
}
}
assert!(index.shows_label(none, 0));
assert_eq!(indexed.next_label_indexed(&index, none, 0).unwrap().0, "RESPONSE: ");
assert_eq!(indexed.next_label_indexed(&index, none, 0), linear.next_label(&n, none, 0));
assert_eq!(indexed.current_label(&n, none, 0), None);
assert_eq!(indexed.current_label(&n, a, 0), linear.current_label(&n, a, 0));
}
}
+66
View File
@@ -340,6 +340,72 @@ impl Paragraph {
self.runs = out;
}
/// Make the objects match the U+FFFC markers one to one (files lie): drop surplus objects,
/// and remove markers past the last object. Runs must already cover the text.
///
/// One scan finds the unmatched markers, one pass removes them and the runs and objects are
/// fixed up once, so the cost is linear in the paragraph however many markers are unmatched.
/// There is no cap on the markers: stopping early would leave markers without objects.
pub fn reconcile_objects(&mut self) {
let keep = self.objects.len();
// Byte offsets of the unmatched markers (every marker after the first `keep`), ascending.
let mut seen = 0usize;
let mut drop: Vec<usize> = Vec::new();
for (i, _) in self.text.match_indices(OBJ) {
crate::work::steps(1);
if seen >= keep {
drop.push(i);
}
seen += 1;
}
if self.objects.len() > seen {
self.objects.truncate(seen);
self.touch();
}
if drop.is_empty() {
return;
}
let w = OBJ.len_utf8();
if self.text.len() == drop.len() * w {
// Emptying: the mark keeps the formatting of what was deleted (as `delete` does).
let revisions = (self.mark.ins, self.mark.del, self.mark.fmt_change.clone());
let mut mark = self.props_of_char(0).clone();
(mark.ins, mark.del, mark.fmt_change) = revisions;
self.mark = mark;
}
// Shrink the runs: each removed marker takes `w` bytes off the run that holds it.
let mut d = 0usize;
let mut start = 0usize;
for r in &mut self.runs {
crate::work::steps(1);
let re = start + r.len;
let mut cut = 0usize;
while let Some(&off) = drop.get(d) {
crate::work::steps(1);
if off >= re {
break;
}
if off >= start {
cut += w;
}
d += 1;
}
start = re;
r.len -= cut.min(r.len);
}
let mut out = String::with_capacity(self.text.len() - drop.len() * w);
// The pieces between markers; marker `k` sits before piece `k + 1` and stays if matched.
for (k, piece) in self.text.split(OBJ).enumerate() {
if k > 0 && k <= keep {
out.push(OBJ);
}
out.push_str(piece);
}
self.text = out;
self.normalize();
self.touch();
}
/// Delete `a..b` (bytes). Objects inside are removed.
pub fn delete(&mut self, a: usize, b: usize) -> Result<()> {
let (a, b) = (a.min(b), a.max(b));
+32 -10
View File
@@ -291,25 +291,47 @@ impl InlineObject {
_ => None,
}
}
/// The text box stories this object shows: a text box's, or its group members'.
/// The text box stories this object shows: a text box's, or its group members' (nested groups
/// included, in member order).
pub fn text_boxes(&self) -> Vec<u32> {
match self {
InlineObject::Shape { story: Some(id), .. } => vec![*id],
InlineObject::Group { children, .. } => children.iter().filter_map(|c| c.obj.text_box()).collect(),
InlineObject::Group { children, .. } => {
let mut out = Vec::new();
let mut todo: Vec<&InlineObject> = children.iter().rev().map(|c| &c.obj).collect();
while let Some(obj) = todo.pop() {
match obj {
InlineObject::Shape { story: Some(id), .. } => out.push(*id),
InlineObject::Group { children, .. } => {
todo.extend(children.iter().rev().map(|c| &c.obj));
}
_ => {}
}
}
out
}
_ => Vec::new(),
}
}
/// The text box story slots of this object and its group members, to repoint.
/// The text box story slots of this object and its group members (nested groups included, in
/// member order), to repoint.
pub fn text_box_slots(&mut self) -> Vec<&mut Option<u32>> {
match self {
InlineObject::Shape { story, .. } => vec![story],
InlineObject::Group { children, .. } => children
.iter_mut()
.filter_map(|c| match &mut c.obj {
InlineObject::Shape { story, .. } => Some(story),
_ => None,
})
.collect(),
InlineObject::Group { children, .. } => {
let mut out = Vec::new();
let mut todo: Vec<&mut InlineObject> = children.iter_mut().rev().map(|c| &mut c.obj).collect();
while let Some(obj) = todo.pop() {
match obj {
InlineObject::Shape { story, .. } => out.push(story),
InlineObject::Group { children, .. } => {
todo.extend(children.iter_mut().rev().map(|c| &mut c.obj));
}
_ => {}
}
}
out
}
_ => Vec::new(),
}
}
+5
View File
@@ -506,6 +506,11 @@ pub struct ParaProps {
/// file (not laid out yet); Word sizes a line by it, so dropping it changes Word's pages.
#[serde(skip_serializing_if = "Option::is_none")]
pub text_alignment: Option<TextAlignment>,
/// A list item's paragraph after its first (or a list header's), with no number of its own,
/// at this list level (0..=8): formats with list items (ODT, HTML, Markdown) keep it in the
/// item. Set only directly, never by a style.
#[serde(skip_serializing_if = "Option::is_none")]
pub list_item: Option<u8>,
}
impl ParaProps {
+17 -1
View File
@@ -42,11 +42,27 @@ pub struct Revision {
/// insertion or deletion.
#[serde(skip_serializing_if = "Option::is_none")]
pub move_name: Option<String>,
/// The change's UTC timestamp: from the file (`w16du:dateUtc`, where `date` is the local time
/// Word writes in `w:date`), or the time WordCraft stamped the change with. `None` when the
/// file doesn't give it.
#[serde(skip_serializing_if = "Option::is_none")]
pub date_utc: Option<String>,
}
impl Revision {
pub fn new(kind: RevisionKind, author: impl Into<String>, date: impl Into<String>) -> Revision {
Revision { kind, author: author.into(), date: date.into(), move_name: None }
Revision { kind, author: author.into(), date: date.into(), move_name: None, date_utc: None }
}
/// A change made here: `date` is the local wall-clock time it was made at, as Word writes
/// `w:date`, and `date_utc` the same instant in UTC.
pub fn made_at(kind: RevisionKind, author: impl Into<String>, date: impl Into<String>, utc: impl Into<String>) -> Revision {
Revision { kind, author: author.into(), date: date.into(), move_name: None, date_utc: Some(utc.into()) }
}
/// The instant changes are grouped by: the UTC time when it is known, else `date`.
pub fn instant(&self) -> &str {
self.date_utc.as_deref().unwrap_or(&self.date)
}
}
+9
View File
@@ -183,6 +183,13 @@ pub struct Settings {
/// comments and tracked changes are saved without `w:date`.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub remove_date_time: bool,
/// Hide spelling errors in this document only (`w:hideSpellingErrors`): no squiggles under
/// misspelled words.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub hide_spelling_errors: bool,
/// Hide grammar errors in this document only (`w:hideGrammaticalErrors`).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub hide_grammar_errors: bool,
/// The document was opened from ODF: the standard's rules that differ from Word's apply as
/// it is laid out.
#[serde(skip_serializing_if = "Option::is_none")]
@@ -349,6 +356,8 @@ impl Default for Settings {
zoom: None,
remove_personal_info: false,
remove_date_time: false,
hide_spelling_errors: false,
hide_grammar_errors: false,
odf: None,
}
}
+43
View File
@@ -221,6 +221,17 @@ impl Table {
}
row.cells.push(nc);
}
// #6326: text typed into a new cell gets the font formatting of the cell it was copied
// from, as in Word: that of the first character of the source cell's first paragraph (its
// mark when it's empty), never a link, revision mark or symbol's own font.
for (nc, c) in row.cells.iter_mut().zip(&src.cells) {
let mark = c.blocks.iter().find_map(|b| b.as_para()).map(|p| p.props_at(0).formatting().without_symbol());
if let Some(mark) = mark
&& let Some(crate::Block::Para(p)) = nc.blocks.first_mut().map(std::sync::Arc::make_mut)
{
p.mark = mark;
}
}
self.rows.insert(at.min(self.rows.len()), row);
}
@@ -744,6 +755,38 @@ mod tests {
t.delete_col(99);
}
/// #6326: a new row's empty cells type in the font formatting of the cells it was copied
/// from, as in Word: that of the first character of the source cell's first paragraph (not
/// its mark), or the mark of an empty one; never its link or revision marks.
#[test]
fn insert_row_types_in_the_source_cells_font() {
let courier = crate::CharProps {
font: Some("Courier New".into()),
size: Some(16.0),
bold: Some(true),
link: Some("https://example.com".into()),
ins: Some(0),
..Default::default()
};
let mut p = Paragraph::with_text("A", courier.clone());
p.insert_text(1, "B", &crate::CharProps { font: Some("Georgia".into()), ..Default::default() }).unwrap();
p.mark = crate::CharProps { font: Some("Arial".into()), ..Default::default() };
let mut empty = Paragraph::new();
empty.mark = crate::CharProps { italic: Some(true), size: Some(20.0), ..Default::default() };
let mut t = Table::new(2, 2, 200.0);
t.rows[0].cells[0].blocks = vec![para_block(p)];
t.rows[0].cells[1].blocks = vec![para_block(empty)];
t.insert_row(1, 0);
t.insert_row(0, 0);
let want = crate::CharProps { link: None, ins: None, ..courier };
let italic = crate::CharProps { italic: Some(true), size: Some(20.0), ..Default::default() };
for r in [0, 2] {
let mark = |c: usize| t.rows[r].cells[c].blocks[0].as_para().map(|p| (p.text.clone(), p.mark.clone()));
assert_eq!(mark(0), Some((String::new(), want.clone())), "row {r}");
assert_eq!(mark(1), Some((String::new(), italic.clone())), "row {r}");
}
}
/// #3637: a `.json` file can give a cell any span; inserting a column through it, merging it
/// or deleting a column under it doesn't overflow, and the span it gets is in 1..=MAX_COLS.
#[test]
+409
View File
@@ -440,6 +440,116 @@ fn prune_text_boxes_drops_only_unshown_ones() {
assert_eq!(d.prune_text_boxes(), 0);
}
/// A text-box shape (`story: Some(id)`) or plain shape (`story: None`) for nested-group tests.
fn test_shape(story: Option<u32>) -> InlineObject {
InlineObject::Shape {
kind: para::ShapeKind::TextBox,
w: 50.0,
h: 20.0,
fill: None,
stroke: None,
stroke_width: 0.0,
float: Default::default(),
story,
freeform: None,
effects: Default::default(),
extra: Default::default(),
}
}
/// A group holding `children`.
fn test_group(children: Vec<InlineObject>) -> InlineObject {
InlineObject::Group {
w: 100.0,
h: 100.0,
float: Default::default(),
ch_w: 100.0,
ch_h: 100.0,
children: children.into_iter().map(|obj| para::GroupChild { x: 0.0, y: 0.0, obj }).collect(),
canvas: None,
}
}
/// `obj` wrapped inside `levels` nested [`InlineObject::Group`]s.
fn nested_group(levels: usize, obj: InlineObject) -> InlineObject {
(0..levels).fold(obj, |inner, _| test_group(vec![inner]))
}
#[test]
fn nested_group_text_boxes_are_collected_and_slots_repointed_in_order() {
let mut outer = test_group(vec![
test_shape(Some(1)),
test_shape(None),
nested_group(1, test_shape(Some(2))), // depth 2 from outer
test_group(vec![nested_group(1, test_shape(Some(3))), test_shape(Some(4))]), // depth 3 and depth 2
nested_group(39, test_shape(Some(5))), // depth 40 from outer
]);
assert_eq!(outer.text_boxes(), vec![1, 2, 3, 4, 5]);
let slots = outer.text_box_slots();
assert_eq!(slots.len(), 6);
for id in slots.into_iter().flatten() {
*id += 100;
}
assert_eq!(outer.text_boxes(), vec![101, 102, 103, 104, 105]);
}
#[test]
fn prune_text_boxes_keeps_nested_group_boxes_and_drops_unreachable() {
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
let mut d = Document::from_text("body");
let depth2 = d.add_part(PartKind::TextBox, para_of("depth 2"));
let depth3 = d.add_part(PartKind::TextBox, para_of("depth 3"));
let deep = d.add_part(PartKind::TextBox, para_of("depth 40"));
let linked_live = d.add_part(PartKind::TextBox, para_of("linked follower"));
let orphan = d.add_part(PartKind::TextBox, para_of("unreachable"));
let orphan_nested = d.add_part(PartKind::TextBox, para_of("inside unreachable"));
// Live link between two nested-group boxes and a dangling link to an unreachable box.
d.parts.get_mut(&depth2).unwrap().body.next = Some(linked_live);
d.parts.get_mut(&depth3).unwrap().body.next = Some(orphan);
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(depth2))), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group(3, test_shape(Some(depth3))), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group(40, test_shape(Some(deep))), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(linked_live))), &CharProps::default()).unwrap();
let at_orphan = Pos { story: StoryRef::Part(orphan), path: Path::top(0), off: 0 };
d.insert_object(&at_orphan, nested_group(2, test_shape(Some(orphan_nested))), &CharProps::default()).unwrap();
assert_eq!(d.prune_text_boxes(), 2);
let kept: Vec<u32> = d.parts.keys().copied().collect();
assert_eq!(kept, vec![depth2, depth3, deep, linked_live]);
assert_eq!(d.plain_text(StoryRef::Part(depth2)), "depth 2");
assert_eq!(d.plain_text(StoryRef::Part(depth3)), "depth 3");
assert_eq!(d.plain_text(StoryRef::Part(deep)), "depth 40");
assert_eq!(d.parts.get(&depth2).unwrap().body.next, Some(linked_live), "live chain link stays");
assert_eq!(d.parts.get(&depth3).unwrap().body.next, None, "dangling chain link is cleared");
assert_eq!(d.prune_text_boxes(), 0);
}
#[test]
fn prune_text_boxes_terminates_on_cyclic_nested_group_stories() {
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
let mut d = Document::from_text("body");
let a = d.add_part(PartKind::TextBox, para_of("a"));
let b = d.add_part(PartKind::TextBox, para_of("b"));
let dead_c = d.add_part(PartKind::TextBox, para_of("dead c"));
let dead_d = d.add_part(PartKind::TextBox, para_of("dead d"));
let at = |id| Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 };
// Reachable cycle: body -> nested group -> a -> nested group -> b -> nested group -> (a, b).
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(a))), &CharProps::default()).unwrap();
d.insert_object(&at(a), nested_group(2, test_shape(Some(b))), &CharProps::default()).unwrap();
d.insert_object(&at(b), nested_group(2, test_group(vec![test_shape(Some(a)), test_shape(Some(b))])), &CharProps::default()).unwrap();
// Unreachable cycle: dead_c <-> dead_d through nested groups.
d.insert_object(&at(dead_c), nested_group(2, test_shape(Some(dead_d))), &CharProps::default()).unwrap();
d.insert_object(&at(dead_d), nested_group(2, test_shape(Some(dead_c))), &CharProps::default()).unwrap();
assert_eq!(d.prune_text_boxes(), 2);
let kept: Vec<u32> = d.parts.keys().copied().collect();
assert_eq!(kept, vec![a, b]);
assert_eq!(d.counted_stories(), vec![StoryRef::Body, StoryRef::Part(a), StoryRef::Part(b)]);
}
/// `blocks` in the only cell of `levels` tables, each nested in the next.
fn nested_tables(levels: usize, blocks: Blocks) -> Blocks {
(0..levels).fold(blocks, |inner, _| {
@@ -818,3 +928,302 @@ fn missing_pictures_are_capped_deduplicated_and_not_content() {
assert!(!serde_json::to_string(&d).unwrap().contains("p0"));
assert_eq!(MissingPictureReason::ExternalTarget.label(), "external target");
}
#[test]
fn normalize_runs_reconciles_objects_with_markers() {
let c = CharProps::default();
let markers = |p: &Paragraph| p.text.chars().filter(|ch| *ch == '\u{FFFC}').count();
let build = || {
let mut d = Document::from_text("abc");
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.insert_object(1, fs("A"), &c).unwrap();
p.insert_object(5, fs("B"), &c).unwrap();
d
};
// More objects than markers (as a hand-edited .json can say): the surplus goes.
let mut d = build();
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().objects.push(fs("C"));
d.normalize_runs();
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
assert_eq!((markers(p), p.objects.len()), (2, 2));
assert_eq!(p.objects, vec![fs("A"), fs("B")]);
// More markers than objects: the unmatched marker goes, runs still cover the text.
let mut d = build();
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.text.push('\u{FFFC}');
p.runs[0].len += 3;
d.normalize_runs();
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
assert_eq!((markers(p), p.objects.len()), (2, 2));
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len());
// Deleting the first marker keeps B on the second.
p.delete(1, 4).unwrap();
assert_eq!(p.objects, vec![fs("B")]);
// The cost is linear: the markers and runs `reconcile_objects` walks (`crate::work`), not a
// timing. 8x the unmatched markers cost about 8x the steps, far more if each removal rescans.
let reconcile = |extra: usize| {
let mut p = Paragraph::default();
p.objects = vec![fs("A")];
p.text = format!("\u{FFFC}{}x", "\u{FFFC}".repeat(extra));
p.runs = vec![Run { len: p.text.len(), props: c.clone() }];
crate::work::count(|| {
p.reconcile_objects();
assert_eq!(p.text, "\u{FFFC}x");
std::hint::black_box(&p);
})
};
let (s1, s8) = (reconcile(2_000), reconcile(16_000));
assert!(s1 > 0, "no steps counted, so the walk this test watches no longer counts them (crate::work)");
let ratio = s8 as f64 / s1 as f64;
assert!(ratio <= 12.0, "8x the markers cost {ratio:.1}x the steps ({s1} -> {s8})");
}
#[test]
fn reconcile_objects_drops_many_unmatched_markers_in_one_pass() {
let c = CharProps::default();
let mut d = Document::from_text("");
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.insert_object(0, fs("A"), &c).unwrap();
p.insert_object(p.text.len(), fs("B"), &c).unwrap();
let extra = 50_000;
// "<A>x<B>" followed by many unmatched markers around more text, in one run.
p.text = format!("\u{FFFC}x\u{FFFC}{}y{}z", "\u{FFFC}".repeat(extra), "\u{FFFC}".repeat(extra));
p.runs = vec![Run { len: p.text.len(), props: c.clone() }];
p.reconcile_objects();
assert_eq!(p.text, "\u{FFFC}x\u{FFFC}yz");
assert_eq!(p.objects, vec![fs("A"), fs("B")]);
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len());
}
#[test]
fn reconcile_objects_keeps_every_matched_object() {
let c = CharProps::default();
let n = 100_050;
let mut d = Document::from_text("");
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.text = "\u{FFFC}".repeat(n);
p.objects = (0..n).map(|_| fs("A")).collect();
p.runs = vec![Run { len: p.text.len(), props: c }];
p.reconcile_objects();
assert_eq!(p.objects.len(), n);
assert_eq!(p.text.matches('\u{FFFC}').count(), n);
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len());
}
#[test]
fn reconcile_objects_keeps_run_props_across_several_runs() {
let (plain, bold) = (CharProps::default(), CharProps { bold: Some(true), ..CharProps::default() });
let italic = CharProps { italic: Some(true), ..CharProps::default() };
let mut d = Document::from_text("");
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.objects = vec![fs("A")];
// Runs: plain "a<A>b<X>" | bold "<X><X>" (only unmatched, becomes empty) | italic "<X>c<X>" | plain "d".
let x = "\u{FFFC}";
let parts = [
(format!("a\u{FFFC}b{x}"), plain.clone()),
(format!("{x}{x}"), bold),
(format!("{x}c{x}"), italic.clone()),
("d".to_string(), plain.clone()),
];
p.text = parts.iter().map(|(t, _)| t.as_str()).collect();
p.runs = parts.iter().map(|(t, c)| Run { len: t.len(), props: c.clone() }).collect();
p.reconcile_objects();
assert_eq!(p.text, "a\u{FFFC}bcd");
assert_eq!(p.objects, vec![fs("A")]);
let got: Vec<(usize, CharProps)> = p.runs.iter().map(|r| (r.len, r.props.clone())).collect();
// "a<A>b" plain (5 bytes: 1 + 3 + 1), "c" italic, "d" plain.
assert_eq!(got, vec![(5, plain.clone()), (1, italic), (1, plain)]);
}
#[test]
fn reconcile_objects_marker_on_run_boundary_shrinks_the_right_run() {
let (plain, bold) = (CharProps::default(), CharProps { bold: Some(true), ..CharProps::default() });
let mut d = Document::from_text("");
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
let x = "\u{FFFC}";
// plain "ab" | bold "<X>cd" : the marker is the first byte of the second run.
p.text = format!("ab{x}cd");
p.runs = vec![Run { len: 2, props: plain.clone() }, Run { len: 2 + x.len(), props: bold.clone() }];
p.reconcile_objects();
assert_eq!(p.text, "abcd");
let got: Vec<(usize, CharProps)> = p.runs.iter().map(|r| (r.len, r.props.clone())).collect();
assert_eq!(got, vec![(2, plain), (2, bold)]);
}
#[test]
fn reconcile_objects_all_unmatched_markers_empties_the_paragraph() {
let bold = CharProps { bold: Some(true), ..CharProps::default() };
let mut d = Document::from_text("");
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.text = "\u{FFFC}".repeat(3);
p.runs = vec![Run { len: p.text.len(), props: bold.clone() }];
p.mark = CharProps { ins: Some(7), ..CharProps::default() };
p.reconcile_objects();
assert_eq!(p.text, "");
assert!(p.objects.is_empty());
assert!(p.runs.is_empty());
// The mark takes the deleted formatting but keeps its own revision.
assert_eq!(p.mark, CharProps { bold: Some(true), ins: Some(7), ..CharProps::default() });
}
fn shape_with_id(id: u32, story: Option<u32>) -> InlineObject {
InlineObject::Shape {
kind: para::ShapeKind::Rectangle,
w: 50.0,
h: 20.0,
fill: None,
stroke: None,
stroke_width: 0.0,
float: Default::default(),
story,
freeform: None,
effects: Default::default(),
extra: connector::ShapeExtra { id, ..Default::default() },
}
}
fn group_of(children: Vec<InlineObject>) -> InlineObject {
InlineObject::Group {
w: 100.0,
h: 100.0,
float: Default::default(),
ch_w: 100.0,
ch_h: 100.0,
children: children.into_iter().map(|obj| para::GroupChild { x: 0.0, y: 0.0, obj }).collect(),
canvas: None,
}
}
fn nested_group_of(depth: usize, leaf: InlineObject) -> InlineObject {
(0..depth).fold(leaf, |inner, _| group_of(vec![inner]))
}
#[test]
fn next_shape_id_accounts_for_shapes_in_nested_groups() {
// Doubly-nested group carrying shape id 1: must not reissue id 1.
let mut d = Document::from_text("body");
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(1, None)), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 2);
// Deeper nesting (5-level and 40-level groups) with mixed siblings.
d.insert_object(
&Pos::body(0, 0),
nested_group_of(5, group_of(vec![shape_with_id(42, None), nested_group_of(35, shape_with_id(99, None))])),
&CharProps::default(),
)
.unwrap();
assert_eq!(d.next_shape_id(), 100);
// Nested group inside a secondary story (part).
let hdr = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("hdr", CharProps::default()))]);
let at_hdr = Pos { story: StoryRef::Part(hdr), path: Path::top(0), off: 0 };
d.insert_object(&at_hdr, nested_group_of(3, shape_with_id(150, None)), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 151);
}
#[test]
fn next_shape_id_preserves_flat_group_and_ungrouped_allocation() {
let mut d = Document::from_text("body");
assert_eq!(d.next_shape_id(), 1);
// Ungrouped shapes (including id 0).
d.insert_object(&Pos::body(0, 0), shape_with_id(0, None), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 1);
d.insert_object(&Pos::body(0, 0), shape_with_id(3, None), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), shape_with_id(7, None), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 8);
// Flat (1-level) group.
d.insert_object(&Pos::body(0, 0), group_of(vec![shape_with_id(12, None), shape_with_id(4, None)]), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 13);
// At u32::MAX, overflow falls back to an unused non-zero id rather than reissuing u32::MAX.
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(u32::MAX, None)), &CharProps::default()).unwrap();
let id = d.next_shape_id();
assert_ne!(id, 0);
for used in [3, 4, 7, 12, u32::MAX] {
assert_ne!(id, used);
}
assert_eq!(id, 1);
}
#[test]
fn next_shape_id_avoids_reissuing_u32_max_on_overflow() {
// Non-overflow boundary: u32::MAX - 1 still advances to u32::MAX.
let mut d = Document::from_text("body");
d.insert_object(&Pos::body(0, 0), shape_with_id(u32::MAX - 1, None), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), u32::MAX);
// Once u32::MAX is in use inside a nested group, allocator must not reissue any in-use id.
let hdr = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("hdr", CharProps::default()))]);
let at_hdr = Pos { story: StoryRef::Part(hdr), path: Path::top(0), off: 0 };
d.insert_object(&Pos::body(0, 0), shape_with_id(1, None), &CharProps::default()).unwrap();
d.insert_object(&at_hdr, nested_group_of(2, shape_with_id(2, None)), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group_of(3, shape_with_id(u32::MAX, None)), &CharProps::default()).unwrap();
let in_use = [1, 2, u32::MAX - 1, u32::MAX];
let first = d.next_shape_id();
assert_ne!(first, 0);
assert!(!in_use.contains(&first), "reissued in-use shape id {first}");
assert_eq!(first, 3);
// Using the returned id advances to the next unused id rather than repeating it.
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(first, None)), &CharProps::default()).unwrap();
let second = d.next_shape_id();
assert_ne!(second, 0);
assert_ne!(second, first);
assert!(!in_use.contains(&second), "reissued in-use shape id {second}");
assert_eq!(second, 4);
}
#[test]
fn next_shape_id_terminates_on_cyclic_nested_group_stories() {
// InlineObject::Group owns Vec<GroupChild> by value (and unsafe is forbidden), so a cyclic
// in-memory Group tree cannot be constructed in safe Rust; mirror #8068 by constructing a
// cyclic text-box story graph through nested groups instead.
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
let mut d = Document::from_text("body");
let a = d.add_part(PartKind::TextBox, para_of("a"));
let b = d.add_part(PartKind::TextBox, para_of("b"));
let at = |id| Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 };
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(5, Some(a))), &CharProps::default()).unwrap();
d.insert_object(&at(a), nested_group_of(2, shape_with_id(10, Some(b))), &CharProps::default()).unwrap();
d.insert_object(&at(b), nested_group_of(2, shape_with_id(25, Some(a))), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 26);
}
#[test]
fn next_shape_id_accounts_for_shapes_in_note_separators() {
let blocks_with = |obj: InlineObject| -> Blocks {
let mut p = Paragraph::with_text("sep", CharProps::default());
p.insert_object(0, obj, &CharProps::default()).unwrap();
vec![para_block(p)]
};
// A shape ID used only in a footnote separator story must not be reissued.
let mut d = Document::from_text("body");
d.footnote_separators.separator = Some(blocks_with(shape_with_id(1, None)));
assert_eq!(d.next_shape_id(), 2);
// Every footnote and endnote separator slot is walked, including nested groups and tables.
d.footnote_separators.continuation_separator = Some(blocks_with(nested_group_of(2, shape_with_id(2, None))));
d.footnote_separators.continuation_notice = Some(nested_tables(1, blocks_with(shape_with_id(5, None))));
assert_eq!(d.next_shape_id(), 6);
d.endnote_separators.separator = Some(blocks_with(shape_with_id(9, None)));
assert_eq!(d.next_shape_id(), 10);
d.endnote_separators.continuation_separator = Some(blocks_with(nested_group_of(3, shape_with_id(14, None))));
assert_eq!(d.next_shape_id(), 15);
// Overflow fallback also respects IDs held exclusively in note-separator stories.
d.endnote_separators.continuation_notice = Some(blocks_with(nested_group_of(2, shape_with_id(u32::MAX, None))));
let allocated = d.next_shape_id();
assert_ne!(allocated, 0);
for used in [1, 2, 5, 9, 14, u32::MAX] {
assert_ne!(allocated, used);
}
assert_eq!(allocated, 3);
}
+2 -1
View File
@@ -175,6 +175,7 @@ mod tests {
ch_w: 64.0,
ch_h: 48.0,
children: vec![craft_wordmodel::para::GroupChild {
link: None,
x: 4.0,
y: 6.0,
obj: craft_wordmodel::para::InlineObject::Field {
@@ -202,7 +203,7 @@ mod tests {
..Default::default()
},
);
source.settings.compat_mode = 11;
source.settings.compat_mode = Some(11);
let image = Arc::new(vec![0x5a; 1 << 20]);
source.media.insert("image1.png".into(), image.clone());
+28 -7
View File
@@ -100,18 +100,35 @@ fn object_value_from_shared(
float: convert(float)?,
ch_w,
ch_h,
children: children.into_iter().map(|c| group_child_value_from_shared(c, graphics)).collect::<Result<_, _>>()?,
children: group_children_from_shared(children, graphics)?,
canvas: canvas.map(convert).transpose()?,
}),
other => convert(other),
}
}
fn group_child_value_from_shared(
source: craft_wordmodel::para::GroupChild,
/// A group's members. The shared reader keeps a hyperlinked nested group whole; WordCraft's
/// text box, layout and edit code looks one level deep, so lift its members into this group
/// (their offsets composed, scaled from the nested group's child space), as the reader does for
/// an unlinked one. The nested group's own link is dropped.
// lean: nested groups are flattened until WordCraft supports them (follow-up issue).
fn group_children_from_shared(
children: Vec<craft_wordmodel::para::GroupChild>,
graphics: &mut GraphicCache,
) -> Result<wordcraft_doc::para::GroupChild, DocxError> {
Ok(wordcraft_doc::para::GroupChild { x: source.x, y: source.y, obj: object_value_from_shared(source.obj, graphics)? })
) -> Result<Vec<wordcraft_doc::para::GroupChild>, DocxError> {
let mut out = Vec::with_capacity(children.len());
for c in children {
let (x, y) = (c.x, c.y);
match object_value_from_shared(c.obj, graphics)? {
wordcraft_doc::para::InlineObject::Group { w, h, ch_w, ch_h, children, .. } => {
let (kx, ky) = (if ch_w > 0.0 { w / ch_w } else { 1.0 }, if ch_h > 0.0 { h / ch_h } else { 1.0 });
// `children` is already flat: the recursion converted the nested group first.
out.extend(children.into_iter().map(|m| wordcraft_doc::para::GroupChild { x: x + m.x * kx, y: y + m.y * ky, obj: m.obj }));
}
obj => out.push(wordcraft_doc::para::GroupChild { x, y, obj }),
}
}
Ok(out)
}
fn table_value_from_shared(source: craft_wordmodel::table::Table, graphics: &mut GraphicCache) -> Result<wordcraft_doc::table::Table, DocxError> {
@@ -215,7 +232,10 @@ pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcr
document.numbering = Arc::new(convert((*numbering).clone())?);
document.comments = convert(comments)?;
document.revisions = convert(revisions)?;
// The shared model keeps an omitted `compatibilityMode` as `None` (Word 2007 rules); the app model has no `None`.
let compat_mode = settings.effective_compat_mode();
document.settings = convert(settings)?;
document.settings.compat_mode = compat_mode;
document.core = convert(core)?;
document.sources = convert(sources)?;
document.custom_props = convert(custom_props)?;
@@ -321,7 +341,7 @@ fn object_value_to_shared(source: &wordcraft_doc::para::InlineObject) -> Result<
}
fn group_child_value_to_shared(source: &wordcraft_doc::para::GroupChild) -> Result<craft_wordmodel::para::GroupChild, DocxError> {
Ok(craft_wordmodel::para::GroupChild { x: source.x, y: source.y, obj: object_value_to_shared(&source.obj)? })
Ok(craft_wordmodel::para::GroupChild { link: None, x: source.x, y: source.y, obj: object_value_to_shared(&source.obj)? })
}
fn table_value_to_shared(source: &wordcraft_doc::table::Table) -> Result<craft_wordmodel::table::Table, DocxError> {
@@ -558,6 +578,7 @@ mod tests {
ch_w: 64.0,
ch_h: 48.0,
children: vec![craft_wordmodel::para::GroupChild {
link: None,
x: 4.0,
y: 6.0,
obj: craft_wordmodel::para::InlineObject::Field {
@@ -585,7 +606,7 @@ mod tests {
..Default::default()
},
);
source.settings.compat_mode = 11;
source.settings.compat_mode = Some(11);
let image = Arc::new(vec![0x5a; 1 << 16]);
source.media.insert("image1.png".into(), image.clone());
+17
View File
@@ -4781,3 +4781,20 @@ fn vml_horizontal_rules_are_read_and_kept() {
let d = read_body(&body);
assert_eq!(rules(&d).iter().map(|r| r.0).collect::<Vec<_>>(), [None, None]);
}
#[test]
fn hide_spelling_and_grammar_errors_survive_a_save() {
let settings_xml = |d: &Document| {
let bytes = wordcraft_docx::write(d).unwrap();
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
String::from_utf8(z.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap()
};
let d = with_settings(Some("<w:hideSpellingErrors/><w:hideGrammaticalErrors/>"));
let saved = settings_xml(&d);
assert!(saved.contains("<w:hideSpellingErrors") && saved.contains("<w:hideGrammaticalErrors"), "{saved}");
let again = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
let saved = settings_xml(&again);
assert!(saved.contains("<w:hideSpellingErrors") && saved.contains("<w:hideGrammaticalErrors"), "second save: {saved}");
let plain = settings_xml(&with_settings(Some("")));
assert!(!plain.contains("hideSpellingErrors") && !plain.contains("hideGrammaticalErrors"), "not invented: {plain}");
}
+65 -10
View File
@@ -229,6 +229,7 @@ fn every_para_prop_round_trips() {
fmt_change: None,
snap_to_grid: Some(false),
text_alignment: Some(TextAlignment::Top),
list_item: None, // not a DOCX property
};
let variants = [
ParaProps { line_spacing: Some(LineSpacing::AtLeast(14.0)), indent_first: Some(24.0), align: Some(Align::Center), ..Default::default() },
@@ -315,7 +316,13 @@ fn styles_and_lists_round_trip() {
#[test]
fn tracked_style_definition_change_round_trips() {
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Format, author: "Ana".into(), date: "2026-10-17T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision {
kind: RevisionKind::Format,
author: "Ana".into(),
date: "2026-10-17T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
std::sync::Arc::make_mut(&mut d.styles).upsert(Style {
id: "Mine".into(),
name: "Mine".into(),
@@ -1004,8 +1011,20 @@ fn toc_field_skips_nested_stories() {
#[test]
fn tracked_changes_round_trip() {
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Alice".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Bob".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.settings.track_changes = true;
let ins = CharProps { ins: Some(0), ..Default::default() };
let del = CharProps { del: Some(1), bold: Some(true), ..Default::default() };
@@ -1033,8 +1052,20 @@ fn tracked_changes_round_trip() {
fn tracked_equations_round_trip() {
// Issue #6011: equations saved with tracked revision marks (w:ins / w:del) around math.
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Alice".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Bob".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.settings.track_changes = true;
let ins = CharProps { ins: Some(0), ..Default::default() };
let del = CharProps { del: Some(1), ..Default::default() };
@@ -1088,8 +1119,20 @@ fn tracked_equations_round_trip() {
fn nested_omath_para_revisions_read() {
// Defensive reader check: w:ins and w:del nested inside m:oMathPara.
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Charles".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Ada".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Charles".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
let doc_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><w:body><w:p><m:oMathPara><w:ins w:id="1" w:author="Ada" w:date="2026-05-01T10:00:00Z"><m:oMath><m:r><m:t>x+1</m:t></m:r></m:oMath></w:ins><w:del w:id="2" w:author="Charles" w:date="2026-05-02T10:00:00Z"><m:oMath><m:r><m:t>y-1</m:t></m:r></m:oMath></w:del></m:oMathPara></w:p></w:body></w:document>"#;
let base = wordcraft_docx::write(&d).unwrap();
let bytes = replace_part(&base, "word/document.xml", doc_xml.as_bytes());
@@ -1107,8 +1150,20 @@ fn tracked_paragraph_marks_round_trip() {
// Issue #229: an inserted / deleted paragraph mark is `w:ins` / `w:del` in the mark's
// `w:rPr` (ECMA-376 §17.13.5.16, §17.13.5.15), alone or with mark formatting.
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Alice".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Bob".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
let mut split = Paragraph::with_text("Owned ALPHA ", CharProps::default());
split.mark.ins = Some(0);
let mut joined = Paragraph::with_text("Owned BETA", CharProps::default());
@@ -1862,7 +1917,7 @@ fn kitchen_sink() -> Document {
let f = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Note", CharProps::default()))]);
let c = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Comment", CharProps::default()))]);
d.comments.insert(3, Comment { author: "X".into(), part: c, ..Default::default() });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None, date_utc: None });
d.last_section.headers.default = Some(h);
let mut blocks: Blocks = Vec::new();
let mut p = para_runs(&[
@@ -37,7 +37,7 @@ fn section_metadata_survives_native_json_and_two_docx_save_reopen_cycles() {
assert!(xml.contains(r#"<w15:footnoteColumns w:val="3"/>"#), "cycle {cycle}: {xml}");
assert!(xml.contains(r#"w:chapStyle="1" w:chapSep="hyphen""#), "cycle {cycle}: {xml}");
assert!(xml.contains(r#"w:chapStyle="10" w:chapSep="colon""#), "cycle {cycle}: {xml}");
assert!(xml.contains("xmlns:w15=") && xml.contains("mc:Ignorable=\"w14 w15 wp14\""), "cycle {cycle}: {xml}");
assert!(xml.contains("xmlns:w15=") && xml.contains("mc:Ignorable=\"w14 w15 wp14 w16du\""), "cycle {cycle}: {xml}");
document = wordcraft_docx::read(&bytes).unwrap();
let json = serde_json::to_vec(&document).unwrap();
document = serde_json::from_slice(&json).unwrap();
+42 -1
View File
@@ -110,7 +110,17 @@ fn unmodelled_settings_survive_a_save_and_owned_ones_follow_the_model() {
assert!(!s.contains("trackRevisions"), "{s}");
assert_eq!(s.matches("compatibilityMode").count(), 1, "{s}");
assert!(s.contains("mailMerge"), "{s}");
assert!(text(&files, "word/_rels/settings.xml.rels").contains("file:///__wordcraft_missing_source__/letters.xlsx"));
let rel_id = s
.split("<w:dataSource")
.nth(1)
.and_then(|after| after.split("r:id=\"").nth(1))
.and_then(|after| after.split('"').next())
.expect("dataSource r:id");
let rels = text(&files, "word/_rels/settings.xml.rels");
let expected_rel = format!(
r#"<Relationship Id="{rel_id}" Type="{REL}/mailMergeSource" Target="file:///__wordcraft_missing_source__/letters.xlsx" TargetMode="External"/>"#
);
assert!(rels.contains(&expected_rel), "missing matching relationship for {rel_id}: {rels}");
// The privacy options are the model's (#1062): written once each, and gone when turned off.
assert_eq!(s.matches("removePersonalInformation").count(), 1, "{s}");
assert_eq!(s.matches("removeDateAndTime").count(), 1, "{s}");
@@ -132,6 +142,37 @@ fn unmodelled_settings_survive_a_save_and_owned_ones_follow_the_model() {
assert_eq!(text(&save(&again), "word/settings.xml"), s);
}
#[test]
fn changed_zoom_survives_merged_settings_and_reads_back_as_page_width() {
let old_zoom = r#"<w:zoom w:percent="120"/>"#;
let updated_zoom = r#"<w:zoom w:val="bestFit" w:percent="145"/>"#;
for original in [SETTINGS.to_string(), SETTINGS.replace(old_zoom, "")] {
let mut doc = wordcraft_docx::read(&with_settings(&original)).unwrap();
assert!(doc.passthrough.contains_key("wordcraft:settings.orig"));
doc.settings.zoom = Some(wordcraft_doc::Zoom { percent: 145, fit: Some(wordcraft_doc::ZoomFit::PageWidth) });
let bytes = wordcraft_docx::write(&doc).unwrap();
let settings = text(&unzip(&bytes), "word/settings.xml");
assert_eq!(settings.matches("<w:zoom ").count(), 1, "{settings}");
assert!(settings.contains(updated_zoom), "{settings}");
// The retained root and unrelated child bytes still belong to the original file.
let root_end = original.find("><w:").unwrap() + 1;
assert!(settings.starts_with(&original[..root_end]), "{settings}");
for kept in [
r#"<w:proofState w:spelling="clean" w:grammar="clean"/>"#,
r#"<w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars>"#,
r#"<w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids>"#,
] {
assert!(settings.contains(kept), "{kept} lost: {settings}");
}
assert!(pos(&settings, "<w:zoom ") < pos(&settings, "<w:proofState"));
let again = wordcraft_docx::read(&bytes).unwrap();
let zoom = again.settings.zoom.unwrap();
assert_eq!(zoom.percent, 145);
assert!(matches!(zoom.fit, Some(wordcraft_doc::ZoomFit::PageWidth)));
assert_eq!(text(&save(&again), "word/settings.xml"), settings);
}
}
#[test]
fn settings_written_by_wordcraft_keep_no_original() {
let doc = wordcraft_doc::Document::new();
+20
View File
@@ -265,3 +265,23 @@ fn story_shared_by_many_shapes_is_written_once() {
// fallback. The other shapes do not repeat it.
assert_eq!(xml.matches(text.as_str()).count(), 2);
}
#[test]
fn text_box_in_a_linked_nested_group_survives_pruning() {
// The shared reader keeps a hyperlinked nested group whole; the box inside must still be
// reachable (`text_boxes` looks one level deep), or the first edit's prune deletes its story.
let inner = r#"<wpg:grpSp><wpg:cNvPr id="3" name="Inner"><a:hlinkClick r:id="rId9"/></wpg:cNvPr><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="635000" y="0"/><a:ext cx="635000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="635000" cy="635000"/></a:xfrm></wpg:grpSpPr><wps:wsp><wps:cNvPr id="4" name="Box"/><wps:cNvSpPr txBox="1"/><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="635000" cy="635000"/></a:xfrm><a:prstGeom prst="rect"/></wps:spPr><wps:txbx><w:txbxContent><w:p><w:r><w:t>Inside</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp></wpg:grpSp>"#;
let doc = format!(
r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><w:body><w:p><w:r><w:drawing><wp:inline><wp:extent cx="1270000" cy="635000"/><wp:docPr id="1" name="Outer"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><wpg:wgp><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1270000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="1270000" cy="635000"/></a:xfrm></wpg:grpSpPr>{inner}</wpg:wgp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p></w:body></w:document>"#
);
let rels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let doc_rels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/" TargetMode="External"/></Relationships>"#;
let bytes = zip(&[("_rels/.rels", rels), ("word/document.xml", doc.as_bytes()), ("word/_rels/document.xml.rels", doc_rels)]);
let mut d = wordcraft_docx::read(&bytes).unwrap();
assert_eq!(boxes(&d).len(), 1);
// What every mutating command does after it runs.
d.prune_text_boxes();
assert_eq!(boxes(&d).len(), 1, "the nested box lost its story");
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
assert!(xml.contains("Inside"), "{xml}");
}
+1 -1
View File
@@ -41,7 +41,7 @@ fn sample() -> Document {
let foot = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Sown in May.", CharProps::default()))]);
let com = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Too short?", CharProps::default()))]);
d.comments.insert(3, Comment { author: "Bo".into(), part: com, ..Default::default() });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
d.last_section.headers.default = Some(head);
let mut p = Paragraph::new();
+139 -1
View File
@@ -298,6 +298,8 @@ Review|Language|Translate|review.translate
Review|Language|Language|review.language
Review|Comments|New Comment|review.newComment
Review|Comments|Delete|review.deleteComment
Review|Comments|Delete All Comments in Document|review.deleteComment
Review|Comments|Delete All Resolved Comments|review.deleteComment
Review|Comments|Previous|review.previousComment
Review|Comments|Next|review.nextComment
Review|Comments|Show Comments|review.comments
@@ -532,6 +534,98 @@ Tools|Templates|Templates and Add-ins|tools.templates
Tools|Views|Full Screen View|view.fullScreenView
";
/// RFC-0052 hand marks for catalog features with no engine command: `id|headless|reach|why`.
///
/// `headless` is `no` or `partial`, `reach` is `window` (needs a desktop window, dialog or
/// pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could
/// be an engine command, isn't one yet). `yes` is never written here: a feature is `yes` only when
/// its id is in the engine registry that `wordcraft-cli` and the MCP server load, and a mark on such
/// an id is stale (`headless_errors`). A missing feature with no mark is `unknown`.
pub const HEADLESS: &str = "\
tools.dictate|no|os|speech recognition service
insert.onlinePicture|no|os|online image search service
insert.model3d|no|engine-gap|3-D model files could be inserted by a command
insert.screenshot|no|os|screen capture of other windows
addins.get|no|os|add-in store service
insert.video|no|os|online video service
insert.inkEquation|no|window|drawn with a pen or pointer
draw.inkToMath|no|os|handwriting recognition service
review.translate|no|os|online translation service
review.blockAuthors|no|os|co-authoring service
view.readLayout|no|window|Read Mode window layout
";
/// One feature's RFC-0052 `headless:` value and, for `no`/`partial`, its `reach:` and reason.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Headless {
pub value: &'static str,
pub reach: Option<&'static str>,
pub why: &'static str,
}
const REACHES: [&str; 3] = ["window", "os", "engine-gap"];
/// Parsed `HEADLESS`-format marks: (id, value, reach, why). A malformed line is an error.
pub fn headless_marks(src: &'static str) -> Result<Vec<(&'static str, Headless)>, String> {
let mut out = Vec::new();
for line in src.lines().filter(|l| !l.trim().is_empty()) {
let f: Vec<&'static str> = line.splitn(4, '|').collect();
let [id, value, reach, why] = f[..] else {
return Err(format!("headless mark `{line}`: want `id|headless|reach|why`"));
};
if !matches!(value, "no" | "partial") {
return Err(format!("headless mark `{id}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)"));
}
if !REACHES.contains(&reach) {
return Err(format!("headless mark `{id}`: reach `{reach}` is not window, os or engine-gap"));
}
if out.iter().any(|(m, _)| *m == id) {
return Err(format!("headless mark `{id}` is written twice"));
}
out.push((id, Headless { value, reach: Some(reach), why }));
}
Ok(out)
}
/// The `headless:` value of a catalog feature: `yes` when the engine registry has its id, else its
/// hand mark, else `unknown`.
pub fn headless_of(id: &str, live: bool, marks: &[(&'static str, Headless)]) -> Headless {
if live {
return Headless { value: "yes", reach: None, why: "" };
}
marks.iter().find(|(m, _)| *m == id).map(|(_, h)| *h).unwrap_or(Headless { value: "unknown", reach: None, why: "" })
}
/// Problems with the marks against the catalog and the registry's ids: unknown ids, and marks on
/// ids the engine registry has (they would hide a `yes`).
pub fn headless_errors(src: &'static str, catalog: &[(&str, &str, &str, &str)], live: impl Fn(&str) -> bool) -> Vec<String> {
let marks = match headless_marks(src) {
Ok(m) => m,
Err(e) => return vec![e],
};
let mut errs = Vec::new();
for (id, _) in &marks {
if !catalog.iter().any(|e| e.3 == *id) {
errs.push(format!("headless mark `{id}` is not a catalog id"));
} else if live(id) {
errs.push(format!("headless mark `{id}` is stale: the engine registry has it, so it is `yes`"));
}
}
errs
}
/// Headless counts in the RFC-0052 summary shape.
fn headless_summary(values: &[Headless]) -> Value {
let count = |v: &str| values.iter().filter(|h| h.value == v).count();
let no = |r: &str| values.iter().filter(|h| h.value == "no" && h.reach == Some(r)).count();
json!({
"yes": count("yes"),
"no": {"window": no("window"), "os": no("os"), "engine-gap": no("engine-gap")},
"partial": count("partial"),
"unknown": count("unknown"),
})
}
/// Catalog entries: (tab, group, feature, id).
pub fn entries() -> Vec<(&'static str, &'static str, &'static str, &'static str)> {
CATALOG
@@ -546,9 +640,13 @@ pub fn entries() -> Vec<(&'static str, &'static str, &'static str, &'static str)
/// Parity summary: per tab and overall, with the missing features.
pub fn parity(reg: &Registry) -> Value {
let e = entries();
let marks = headless_marks(HEADLESS).unwrap_or_default();
let mut values = Vec::with_capacity(e.len());
let mut tabs: Vec<(&str, usize, usize, Vec<String>)> = Vec::new();
for (tab, group, label, id) in &e {
let have = reg.get(id).is_some();
let h = headless_of(id, have, &marks);
values.push(h);
let t = match tabs.iter_mut().find(|t| t.0 == *tab) {
Some(t) => t,
None => {
@@ -564,7 +662,8 @@ pub fn parity(reg: &Registry) -> Value {
if have {
t.1 += 1;
} else {
t.3.push(format!("{group} › {label} (`{id}`)"));
let reach = h.reach.map(|r| format!(", reach: {r} ({})", h.why)).unwrap_or_default();
t.3.push(format!("{group} › {label} (`{id}`): headless: {}{reach}", h.value));
}
}
let live = tabs.iter().map(|t| t.1).sum::<usize>();
@@ -573,6 +672,7 @@ pub fn parity(reg: &Registry) -> Value {
"live": live,
"total": total,
"percent": if total == 0 { 0.0 } else { (live as f64 * 1000.0 / total as f64).round() / 10.0 },
"headless": headless_summary(&values),
"tabs": tabs.iter().map(|t| json!({"tab": t.0, "live": t.1, "total": t.2, "missing": t.3})).collect::<Vec<_>>(),
})
}
@@ -597,6 +697,44 @@ mod tests {
assert!(pct >= 90.4, "parity {pct}%");
}
#[test]
fn headless_marks_are_current() {
let reg = crate::cmd::registry();
let errs = headless_errors(HEADLESS, &entries(), |id| reg.get(id).is_some());
assert!(errs.is_empty(), "{errs:?}");
}
#[test]
fn headless_yes_comes_only_from_the_registry() {
let marks = headless_marks("a.b|no|window|pointer\n").unwrap();
assert_eq!(headless_of("a.b", true, &marks).value, "yes", "a live id is yes whatever the mark says");
assert_eq!(headless_of("a.b", false, &marks).reach, Some("window"));
assert_eq!(headless_of("c.d", false, &marks).value, "unknown");
assert!(headless_marks("a.b|yes|window|x\n").is_err(), "a hand-written yes is refused");
assert!(headless_marks("a.b|no|desk|x\n").is_err(), "reach must be window, os or engine-gap");
assert!(headless_marks("a.b|no\n").is_err());
assert!(headless_marks("a.b|no|os|x\na.b|partial|os|y\n").is_err(), "one mark per id");
}
#[test]
fn headless_errors_flag_stale_and_unknown_marks() {
let cat = [("T", "G", "F", "a.b"), ("T", "G", "H", "c.d")];
let errs = headless_errors("a.b|no|os|x\nz.z|no|os|y\n", &cat, |id| id == "a.b");
assert!(errs.iter().any(|e| e.contains("`a.b` is stale")), "{errs:?}");
assert!(errs.iter().any(|e| e.contains("`z.z` is not a catalog id")), "{errs:?}");
assert!(headless_errors("bad\n", &cat, |_| false).len() == 1);
}
#[test]
fn parity_counts_every_feature_once_in_the_headless_summary() {
let p = parity(&crate::cmd::registry());
let h = &p["headless"];
let n = |v: &Value| v.as_u64().unwrap_or(0);
let no = n(&h["no"]["window"]) + n(&h["no"]["os"]) + n(&h["no"]["engine-gap"]);
assert_eq!(n(&h["yes"]) + no + n(&h["partial"]) + n(&h["unknown"]), n(&p["total"]));
assert_eq!(n(&h["yes"]), n(&p["live"]), "every live feature is an engine command here");
}
#[test]
fn read_mode_view_menu_is_catalogued() {
let e = entries();
+28 -2
View File
@@ -33,6 +33,7 @@ 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;
@@ -209,14 +210,21 @@ pub fn new_revision(s: &mut Session, kind: RevisionKind) -> u32 {
.iter()
.enumerate()
.rev()
.find(|(i, r)| r.kind == kind && r.author == s.author && r.date == date && r.move_name.is_none() && held != Some(*i as u32))
.find(|(i, r)| r.kind == kind && r.author == s.author && r.instant() == date && r.move_name.is_none() && held != Some(*i as u32))
{
return i as u32;
}
s.doc.revisions.push(Revision { kind, author: s.author.clone(), date, move_name: None });
s.doc.revisions.push(made_revision(kind, s.author.clone(), date));
(s.doc.revisions.len() - 1) as u32
}
/// A revision record for a change made at `utc` (ISO 8601, UTC): dated in local wall-clock time,
/// as Word writes `w:date`, with the UTC time beside it, so a save writes it as it is (#6851).
pub fn made_revision(kind: RevisionKind, author: String, utc: String) -> Revision {
let date = crate::io_ext::word_date(&utc, local_offset_secs).unwrap_or_else(|| utc.clone());
Revision::made_at(kind, author, date, utc)
}
/// Whether the paragraph at `path` is followed by another paragraph in the same container (so
/// its paragraph mark can be removed by joining the two).
pub fn has_next_para(s: &Session, story: StoryRef, path: &wordcraft_doc::Path) -> bool {
@@ -555,6 +563,10 @@ pub fn iso_from_unix_secs(secs: u64) -> String {
/// Seconds since the Unix epoch (UTC): the system clock, or the browser's on the web.
pub fn now_unix() -> u64 {
#[cfg(test)]
if let Some(now) = TEST_NOW.with(std::cell::Cell::get) {
return now;
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
{
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
@@ -576,9 +588,23 @@ pub fn now_iso() -> String {
/// The local time zone's offset from UTC in seconds (east positive) at `unix`, daylight saving
/// included: the system's zone, or the browser's on the web. 0 (UTC) when it can't be found.
pub fn local_offset_secs(unix: u64) -> i64 {
#[cfg(test)]
if let Some(zone) = TEST_ZONE.with(std::cell::Cell::get) {
return zone(unix);
}
system_offset_secs(unix).clamp(-26 * 3600, 26 * 3600)
}
#[cfg(test)]
thread_local! {
/// The clock [`now_unix`] reads on this thread in place of the system's, so a test can make
/// edits at the instants it needs.
pub static TEST_NOW: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
/// The zone [`local_offset_secs`] gives on this thread in place of the system's. CI runs on
/// UTC, where local time is UTC, so a test sets a zone that isn't to tell them apart.
pub static TEST_ZONE: std::cell::Cell<Option<fn(u64) -> i64>> = const { std::cell::Cell::new(None) };
}
#[cfg(not(target_arch = "wasm32"))]
fn system_offset_secs(unix: u64) -> i64 {
use chrono::Offset;
+38 -6
View File
@@ -35,6 +35,32 @@ 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 {
@@ -295,7 +321,13 @@ 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.pasteSpecial" | "edit.pasteClipboardItem" | "edit.pasteAllClipboard"
"edit.paste"
| "edit.pasteText"
| "edit.pasteMerge"
| "edit.pasteNestedTable"
| "edit.pasteSpecial"
| "edit.pasteClipboardItem"
| "edit.pasteAllClipboard"
);
if !replaces && !matches!(id, "edit.cut" | "edit.copy") {
return None;
@@ -350,7 +382,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) = selected_member(s)?;
let (pos, index, obj) = active_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")) {
@@ -381,7 +413,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, _) = selected_member(s)?;
let (pos, index, _) = active_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);
@@ -406,10 +438,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 picked member's own object (Shape Format, Size, Rotate, Alt Text) when `pos` is its
/// canvas. `None`: no member picked there.
/// Change the active member's own object (Shape Format, Size, Rotate, Alt Text) when `pos` is its
/// canvas. `None`: no active member there.
pub(crate) fn edit_member_object(s: &mut Session, pos: &Pos, f: impl Fn(&mut InlineObject)) -> Option<Result<InlineObject, CmdError>> {
let (at, index, _) = selected_member(s).filter(|(at, ..)| at == pos)?;
let (at, index, _) = active_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) {
+26 -2
View File
@@ -1,7 +1,9 @@
//! Caret movement and selection.
use serde_json::Value;
use wordcraft_doc::{Pos, StoryRef};
use wordcraft_doc::math_edit::MathPos;
use wordcraft_doc::para::OBJ;
use wordcraft_doc::{InlineObject, Pos, StoryRef};
use wordcraft_layout::ViewMode;
use super::{parse_pos, sel_result};
@@ -119,9 +121,31 @@ fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
if bidi_para(s) {
return visual_lr(s, v, is_left);
}
if !extend(v)
&& !s.math_left
&& let Some(r) = into_equation(s, is_left)
{
return r;
}
mv(s, v, if is_left { left } else { right })
}
/// Left/Right onto an equation opens it, at its end from the right and at its start from the
/// left, as in Word (#4138). Leaving it puts the caret on the far side, so the same arrow then
/// moves on instead of going back in. A caret.left/right that itself left an equation (sent
/// while editing one) moves on too.
fn into_equation(s: &mut Session, is_left: bool) -> Option<CmdResult> {
let f = s.sel.focus.clone();
let off = if is_left { f.off.checked_sub(OBJ.len_utf8())? } else { f.off };
if !matches!(s.doc.para_at(&f)?.object_at(off), Some(InlineObject::Equation { .. })) {
return None;
}
s.sel = Selection::caret(Pos { off, ..f });
s.goal_x = None;
s.pending = None;
Some(super::equation::edit_at(s, (!is_left).then(MathPos::default)))
}
/// Left/Right in bidirectional text: one caret position to the left or right on the screen.
/// Past the line's visual end the caret goes to the neighbouring line in reading order (the
/// previous line when moving toward the paragraph's start edge).
@@ -477,7 +501,7 @@ fn drag_unit(s: &mut Session, v: &Value) -> CmdResult {
/// Select the n-th occurrence of `text` in the body (agents: "select the word X").
fn select_text(s: &mut Session, v: &Value) -> CmdResult {
let needle = p::req_str(v, "text")?;
let n = p::u64(v, "occurrence").unwrap_or(1).max(1) as usize;
let n = p::u64(v, "occurrence").unwrap_or(1).max(1);
if needle.is_empty() {
return Err(CmdError::Params("`text` is empty".into()));
}
+1 -1
View File
@@ -35,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("references.sources", "Manage Sources", "References › Citations & Bibliography", sources)
.params(r#"{"add"?: Source, "remove"?: tag, "import"?: path (a Word bibliography file, `b:Sources` / `Sources.xml`)} → list"#),
CommandSpec::new("references.citation", "Insert Citation", "References › Citations & Bibliography", citation).params(r#"{"tag"?: string, "source"?: Source (added if new), "pages"?: string}"#),
CommandSpec::new("references.citation", "Insert Citation", "References › Citations & Bibliography", citation).params(r#"{"tag"?: string, "source"?: Source (added, or edited when its tag exists, and cited when no tag is given), "pages"?: string}"#),
CommandSpec::new("references.citationStyle", "Style", "References › Citations & Bibliography", |s, v| {
let st = p::str(v, "style").unwrap_or("APA");
let st = find_style(st).ok_or_else(|| {
+33 -25
View File
@@ -37,22 +37,7 @@ fn auto_tag_base(src: &Source) -> String {
/// document's sources. `import` reads a Word bibliography file (`b:Sources`, #2640).
pub(super) fn sources(s: &mut Session, v: &Value) -> CmdResult {
if let Some(a) = v.get("add") {
let mut src: Source = serde_json::from_value(a.clone()).map_err(|e| CmdError::Params(e.to_string()))?;
// A new source's tag is made from its author and year; an edit keeps the tag it has.
if src.tag.is_empty() {
src.tag = auto_tag(&s.doc, &src);
}
// Edit Source keeps the source's place in the list and refreshes its citations.
match s.doc.sources.iter().position(|x| x.tag == src.tag) {
Some(i) => {
if let Some(x) = s.doc.sources.get_mut(i) {
*x = src;
}
update_citations(s)?;
}
None => s.doc.sources.push(src),
}
s.touch();
add_source(s, a)?;
}
if let Some(t) = p::str(v, "remove") {
s.doc.sources.retain(|x| x.tag != t);
@@ -63,6 +48,28 @@ pub(super) fn sources(s: &mut Session, v: &Value) -> CmdResult {
Ok(serde_json::to_value(&s.doc.sources).unwrap_or(Value::Null))
}
/// Adds a source, or edits the one with its tag, and returns that tag (#7443).
fn add_source(s: &mut Session, a: &Value) -> Result<String, CmdError> {
let mut src: Source = serde_json::from_value(a.clone()).map_err(|e| CmdError::Params(e.to_string()))?;
// A new source's tag is made from its author and year; an edit keeps the tag it has.
if src.tag.is_empty() {
src.tag = auto_tag(&s.doc, &src);
}
let tag = src.tag.clone();
// Edit Source keeps the source's place in the list and refreshes its citations.
match s.doc.sources.iter().position(|x| x.tag == src.tag) {
Some(i) => {
if let Some(x) = s.doc.sources.get_mut(i) {
*x = src;
}
update_citations(s)?;
}
None => s.doc.sources.push(src),
}
s.touch();
Ok(tag)
}
/// The largest bibliography sources file imported from disk.
#[cfg(not(target_arch = "wasm32"))]
const MAX_SOURCES_FILE: u64 = 32 << 20;
@@ -126,15 +133,16 @@ fn import_sources(s: &mut Session, path: &str) -> Result<(), CmdError> {
}
pub(super) fn citation(s: &mut Session, v: &Value) -> CmdResult {
if v.get("source").is_some() {
sources(s, &json!({"add": v.get("source")}))?;
}
let tag = match p::str(v, "tag") {
Some(t) => t.to_string(),
None => match v.get("source") {
Some(_) => s.doc.sources.last().map(|x| x.tag.clone()).unwrap_or_default(),
None => return Err(CmdError::Params("give `tag` or `source`".into())),
},
// The source just added or edited is the one cited when no `tag` is given, wherever it sits
// in the list (#7443).
let added = match v.get("source") {
Some(a) => Some(add_source(s, a)?),
None => None,
};
let tag = match (p::str(v, "tag"), added) {
(Some(t), _) => t.to_string(),
(None, Some(t)) => t,
(None, None) => return Err(CmdError::Params("give `tag` or `source`".into())),
};
let src = s.doc.sources.iter().find(|x| x.tag == tag).cloned().ok_or_else(|| CmdError::Params(format!("no source `{tag}`")))?;
let pages = p::str(v, "pages").unwrap_or("").to_string();
+16
View File
@@ -597,6 +597,22 @@ fn editing_author_and_year_keeps_the_tag_and_updates_the_citation_text() {
assert!(f[0].1.contains("Jones") && f[0].1.contains("2021"), "{:?}", f[0].1);
}
#[test]
fn citing_an_edited_source_that_is_not_last_cites_that_source() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.sources", &json!({"add": src_of("Alice, Ann", "2000")})).unwrap();
s.run("references.sources", &json!({"add": src_of("Bob, Ben", "2001")})).unwrap();
let mut edited = src_of("Alice Edited, Ann", "2000");
edited["tag"] = json!("Ali00");
let r = s.run("references.citation", &json!({"source": edited})).unwrap();
assert_eq!(r["tag"], "Ali00");
let tags: Vec<_> = s.doc.sources.iter().map(|x| x.tag.as_str()).collect();
assert_eq!(tags, ["Ali00", "Bob01"]);
let f = fields(&s);
assert_eq!(f[0].0, "CITATION Ali00");
assert!(f[0].1.contains("Alice Edited") && f[0].1.contains("2000"), "{:?}", f[0].1);
}
#[test]
fn a_new_sources_tag_is_three_letters_and_two_year_digits() {
let mut s = Session::new(wordcraft_doc::Document::new());
+13
View File
@@ -182,6 +182,9 @@ 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)?;
@@ -209,6 +212,16 @@ 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();
+43 -5
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use std::sync::Arc;
use wordcraft_doc::props::{Border, BorderStyle, Borders, CharProps, LineSpacing, Rgb, TextColor};
use wordcraft_doc::{Watermark, styles};
use wordcraft_doc::{StyleKind, Watermark, styles};
use super::sel_result;
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
@@ -209,9 +209,16 @@ fn para_spacing(s: &mut Session, v: &Value) -> CmdResult {
"double" => (0.0, 8.0, 2.0),
_ => (0.0, 8.0, 1.15),
};
Arc::make_mut(&mut s.doc.styles).default_para.space_before = Some(before);
Arc::make_mut(&mut s.doc.styles).default_para.space_after = Some(after);
Arc::make_mut(&mut s.doc.styles).default_para.line_spacing = Some(LineSpacing::Multiple(line));
let st = Arc::make_mut(&mut s.doc.styles);
let apply = |p: &mut wordcraft_doc::props::ParaProps| {
p.space_before = Some(before);
p.space_after = Some(after);
p.line_spacing = Some(LineSpacing::Multiple(line));
};
apply(&mut st.default_para);
for style in st.styles.iter_mut().filter(|style| style.builtin && style.kind == StyleKind::Paragraph) {
apply(&mut style.para);
}
sel_result(s)
}
@@ -287,7 +294,7 @@ fn page_borders(s: &mut Session, v: &Value) -> CmdResult {
};
let blocks: Vec<usize> = match p::str(v, "applyTo") {
Some("document") => s.doc.sections().iter().map(|(end, _)| *end).collect(),
Some("section") | None => vec![s.sel.focus.path.0.first().copied().unwrap_or(0) as usize],
Some("section") | None => vec![super::page::section_end_of_focus(s)],
Some(x) => return Err(CmdError::Params(format!("unknown `applyTo` `{x}`"))),
};
for block in blocks {
@@ -295,3 +302,34 @@ fn page_borders(s: &mut Session, v: &Value) -> CmdResult {
}
sel_result(s)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use wordcraft_doc::{Document, Style};
#[test]
fn paragraph_spacing_preset_updates_builtin_styles_and_keeps_custom_styles() {
let mut s = Session::new(Document::new());
Arc::make_mut(&mut s.doc.styles).styles.push(Style {
id: "CustomSpacing".into(),
name: "Custom Spacing".into(),
kind: StyleKind::Paragraph,
builtin: false,
para: wordcraft_doc::props::ParaProps { space_after: Some(24.0), ..Default::default() },
..Default::default()
});
s.run("design.paragraphSpacing", &json!({"value": "double"})).unwrap();
let normal = s.doc.styles.get("Normal").unwrap();
assert_eq!(normal.para.line_spacing, Some(LineSpacing::Multiple(2.0)));
let heading = s.doc.styles.get("Heading1").unwrap();
assert_eq!((heading.para.space_before, heading.para.space_after), (Some(0.0), Some(8.0)));
assert_eq!(heading.para.line_spacing, Some(LineSpacing::Multiple(2.0)));
let custom = s.doc.styles.get("CustomSpacing").unwrap();
assert_eq!(custom.para.space_after, Some(24.0));
assert_eq!(custom.para.line_spacing, None);
}
}
+98 -12
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, or whole table cells (an empty cell's selection has no length, #1744).
/// Something to cut: text, an object, 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(),
CommandSpec::new("edit.copy", "Copy", "Home › Clipboard", copy).key("Mod+C / Mod+Insert").pure().when(has_sel),
// 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,6 +89,8 @@ 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"),
@@ -159,7 +161,7 @@ pub fn specs() -> Vec<CommandSpec> {
.params(r#"{"tab"?: "find|replace|goto" (default replace)}"#)
.pure(),
CommandSpec::new("edit.replaceAll", "Replace All", "Home › Editing › Replace", replace_all)
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find}"#),
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find} (with AutoFormat's smart quotes on, a " or ' typed in `with` goes in curly by the character before it, as typing does, except with regex or special: false (taken as written); ^034 and ^039 stay straight; a match that already reads so, curled the same kind, is left and not counted)"#),
CommandSpec::new("edit.goto", "Go To", "Home › Editing › Find", goto)
.key("Mod+Alt+G / F5")
.params(r#"{"page"?: n, "pageBy"?: int (pages forward, negative back, from the caret's page), "bookmark"?: string (selects its text), "paragraph"?: n}; none opens Find and Replace on its Go To tab"#)
@@ -185,6 +187,7 @@ 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())
@@ -218,6 +221,7 @@ 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();
}
@@ -241,6 +245,7 @@ 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())?;
@@ -301,13 +306,30 @@ 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 {
match super::paste::paste_content(s, v)? {
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::Text(text) => super::paste::insert_text(s, &text)?,
}
sel_result(s)
}
/// Merge Formatting: the pasted text takes the destination's formatting, keeping its emphasis.
fn paste_merge(s: &mut Session, v: &Value) -> CmdResult {
let mut frag = super::paste::paste_fragment(s, v)?;
@@ -444,11 +466,17 @@ 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 mut r = sel_result(s)?;
let multiple = all.len() > 1;
for f in all {
r = paste_clip(s, f)?;
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);
}
}
Ok(r)
sel_result(s)
}
fn paste_text(s: &mut Session, v: &Value) -> CmdResult {
@@ -468,6 +496,9 @@ pub(crate) struct Found {
pub a: Pos,
pub b: Pos,
pub rep: Option<String>,
/// With smart quotes on, the match already is its replacement with the quotes curled the
/// same kind (a curly apostrophe a typed `'` found): Replace leaves it and doesn't count it.
pub keep: bool,
}
/// A stretch of searched text: `len` bytes from `hay` are paragraph `para`'s bytes from `raw`.
@@ -507,6 +538,13 @@ fn find_opts(f: &crate::session::FindState) -> find_pattern::Opts {
/// wildcard groups). A pattern that can match a paragraph mark (`^p`) reads runs of sibling
/// paragraphs as one text with a mark between them; otherwise each paragraph is read alone.
pub(crate) fn search_full(s: &Session, story: StoryRef, with_rep: bool) -> Result<Vec<Found>, CmdError> {
search_matches(s, story, with_rep, false)
}
/// [`search_full`]. With `chain` (Replace All, which replaces every match), a quote typed in
/// Replace with curls by the previous match's replacement when the two touch; without it, by the
/// text as it is, since Replace changes only the selected match (#7307).
fn search_matches(s: &Session, story: StoryRef, with_rep: bool, chain: bool) -> Result<Vec<Found>, CmdError> {
use regex_automata::{Input, meta, util::syntax};
let f = &s.find;
if f.query.is_empty() {
@@ -523,6 +561,9 @@ pub(crate) fn search_full(s: &Session, story: StoryRef, with_rep: bool) -> Resul
let index = |name: &str| re.group_info().to_index(regex_automata::PatternID::ZERO, name);
find_pattern::resolve_names(find_pattern::parse_replace(&f.replace, &opts), &index)
});
// "Straight quotes with smart quotes" curls a quote typed in Replace with (#7307).
let ac = &s.prefs.autocorrect;
let smart = ac.enabled && ac.smart_quotes && pieces.as_deref().is_some_and(find_pattern::has_typed_quote);
let paths = s.doc.para_paths(story);
// Paragraphs read as one text: consecutive siblings when the pattern spans paragraphs.
let mut chunks: Vec<std::ops::Range<usize>> = Vec::new();
@@ -585,6 +626,8 @@ pub(crate) fn search_full(s: &Session, story: StoryRef, with_rep: bool) -> Resul
};
cuts.push(hay.len());
let mut from = 0;
// Where the last match ends and the character that stands there once it is replaced.
let mut last: Option<(usize, Option<char>)> = None;
for cut in cuts {
if cut <= from {
continue;
@@ -608,11 +651,24 @@ pub(crate) fn search_full(s: &Session, story: StoryRef, with_rep: bool) -> Resul
continue;
}
let (Some(a), Some(b)) = (pos_of(m.start(), false), pos_of(m.end(), true)) else { continue };
let found = hay.get(m.range()).unwrap_or("");
// A quote curls by the character in front of the match as it will read: with
// `chain`, the previous match's replacement when the two touch. A section mark
// starts a paragraph.
let before = match last {
Some((end, c)) if chain && end == m.start() => c,
_ => hay.get(..m.start()).and_then(|t| t.chars().next_back()),
}
.filter(|c| *c != find_pattern::SECT_MARK);
let quotes = if smart { find_pattern::Quotes::Smart { before } } else { find_pattern::Quotes::Straight };
let rep = pieces.as_ref().map(|pc| {
let group = |n: usize| caps.get_group(n).and_then(|g| hay.get(g.range())).map(str::to_string);
find_pattern::expand(pc, hay.get(m.range()).unwrap_or(""), &group, &s.clipboard_text)
find_pattern::expand(pc, found, &group, &s.clipboard_text, quotes)
});
out.push(Found { a, b, rep });
let keep = smart && rep.as_deref().is_some_and(|r| find_pattern::already_curled(found, r));
let stays = if keep { found } else { rep.as_deref().unwrap_or(found) };
last = Some((m.end(), stays.chars().next_back().or(before)));
out.push(Found { a, b, rep, keep });
if out.len() >= 100_000 {
return Ok(out);
}
@@ -751,7 +807,8 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
// Replace the current match if selected, then move to the next. The result says which
// happened (#6877): a first call that only selects a match reads as `replaced: 0`.
let mut replaced = 0;
if let Some(f) = results.into_iter().find(|f| f.a == a && f.b == b) {
// A match already curled as the replacement would curl it is left as it is (#7307).
if let Some(f) = results.into_iter().find(|f| f.a == a && f.b == b && !f.keep) {
super::paste_text(s, &f.rep.unwrap_or_default())?;
replaced = 1;
}
@@ -771,10 +828,11 @@ fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
need_query(s, v)?;
read_opts(s, v);
let story = s.sel.focus.story;
let results = search_full(s, story, true)?;
// Matches already curled as the replacement would curl them are left and not counted (#7307).
let results: Vec<Found> = search_matches(s, story, true, true)?.into_iter().filter(|f| !f.keep).collect();
let n = results.len();
super::controls::check_deletions(s, story, results.iter().map(|f| (&f.a, &f.b)))?;
for Found { a, b, rep } in results.into_iter().rev() {
for Found { a, b, rep, .. } in results.into_iter().rev() {
let with = rep.unwrap_or_default();
if s.doc.settings.track_changes {
// Same path as a single replace, so the change is a reviewable revision.
@@ -927,4 +985,32 @@ mod shortcut_tests {
}
}
}
#[test]
fn copy_format_web_alias_respects_user_removal_and_reassignment() {
use craft_keymap::{Binding, Chord, CommandRef, Overrides, Policy};
let mut commands = super::super::registry().all().to_vec();
commands.iter_mut().find(|c| c.id == "edit.copyFormat").unwrap().shortcut = copy_format_shortcut(true);
let registry = Registry::new(commands);
let mut keymap = crate::keymap::registry_keymap(&registry, &Overrides::default());
let copy_cmd = CommandRef::new("edit.copyFormat");
let bold_cmd = CommandRef::new("format.bold");
let chord = Chord::parse("Mod+Alt+Shift+C").unwrap();
let binding = Binding::parse("Mod+Alt+Shift+C").unwrap();
assert!(keymap.bindings(&copy_cmd).iter().any(|b| b.trigger.chord == chord));
assert!(keymap.remove(&copy_cmd, &binding));
assert_eq!(keymap.holder(&chord), None);
keymap.assign(&bold_cmd, binding, Policy::Steal).unwrap();
assert_eq!(keymap.holder(&chord).as_ref().map(|c| c.id.as_str()), Some("format.bold"));
assert_eq!(keymap.holder(&Chord::parse("Mod+Shift+C").unwrap()).as_ref().map(|c| c.id.as_str()), Some("edit.copyFormat"));
let overrides = keymap.overrides().clone();
let restored = crate::keymap::registry_keymap(&registry, &overrides);
assert_eq!(restored.holder(&chord).as_ref().map(|c| c.id.as_str()), Some("format.bold"));
assert_eq!(restored.holder(&Chord::parse("Mod+Shift+C").unwrap()).as_ref().map(|c| c.id.as_str()), Some("edit.copyFormat"));
}
}
+6 -2
View File
@@ -261,6 +261,11 @@ fn insert_nodes_as_equation(s: &mut Session, nodes: Arg, v: &Value) -> CmdResult
/// Starts editing the equation at the caret, materializing lazy nodes and clamping the requested
/// position, and returns the equation and caret.
fn edit(s: &mut Session, v: &Value) -> CmdResult {
edit_at(s, v.get("pos").and_then(|p| serde_json::from_value::<MathPos>(p.clone()).ok()))
}
/// [`edit`] at `pos` in the equation, or at its end without one.
pub(super) fn edit_at(s: &mut Session, pos: Option<MathPos>) -> CmdResult {
let at = equation_at_caret(s).ok_or_else(|| CmdError::Disabled("no equation at the caret".into()))?;
let nodes = match s.doc.para_at(&at).and_then(|p| p.object_at(at.off)) {
Some(InlineObject::Equation { math, linear, .. }) => {
@@ -272,8 +277,7 @@ fn edit(s: &mut Session, v: &Value) -> CmdResult {
}
_ => return Err(CmdError::Failed("no equation there".into())),
};
let pos =
v.get("pos").and_then(|p| serde_json::from_value::<MathPos>(p.clone()).ok()).unwrap_or_else(|| MathPos::new(Vec::new(), me::units(&nodes)));
let pos = pos.unwrap_or_else(|| MathPos::new(Vec::new(), me::units(&nodes)));
let Some(session) = crate::next_math_session() else {
return Err(CmdError::Failed("no equation editing session available".into()));
};
+68
View File
@@ -59,6 +59,74 @@ fn structures_symbols_and_navigation() {
assert!(s.math.is_none());
}
#[test]
fn left_and_right_step_into_an_equation_next_to_the_caret() {
let mut s = session();
s.run("document.setText", &json!({"text": "ab\ncd"})).unwrap();
let p0 = s.doc.start_of(s.sel.focus.story);
let p1 = Pos { path: s.doc.next_para(p0.story, &p0.path).unwrap(), ..p0.clone() };
// An equation between "a" and "b", and another one between "c" and "d".
for p in [&p0, &p1] {
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p.clone() }})).unwrap();
s.run("insert.equation", &json!({"linear": "x+y", "edit": false})).unwrap();
}
let after = 1 + OBJ.len_utf8();
let editing = |s: &Session| s.math.as_ref().map(|m| (m.at.path.clone(), m.at.off, m.pos.clone()));
// Right from "a|" enters the equation at its start.
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap();
s.run("caret.right", &json!({})).unwrap();
assert_eq!(editing(&s), Some((p0.path.clone(), 1, MathPos::default())));
// Leaving it to the right, the next Right goes on to the text, not back in.
for _ in 0..10 {
if s.math.is_none() {
break;
}
s.run("equation.move", &json!({"dir": "right"})).unwrap();
}
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after));
s.run("caret.right", &json!({})).unwrap();
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after + 1));
// Left from just after the equation in the second paragraph enters it at its end.
s.run("caret.set", &json!({"pos": Pos { off: after, ..p1.clone() }})).unwrap();
s.run("caret.left", &json!({})).unwrap();
let end = MathPos::new(Vec::new(), me::units(&nodes_of(&s, &Pos { off: 1, ..p1.clone() }).unwrap()));
assert_eq!(editing(&s), Some((p1.path.clone(), 1, end)));
for _ in 0..10 {
if s.math.is_none() {
break;
}
s.run("equation.move", &json!({"dir": "left"})).unwrap();
}
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 1));
s.run("caret.left", &json!({})).unwrap();
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 0));
// Shift+Right selects over the equation, as before.
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap();
s.run("caret.right", &json!({"extend": true})).unwrap();
assert_eq!((s.math.is_none(), s.sel.anchor.off, s.sel.focus.off), (true, 1, after));
// caret.left/right sent while editing (the arrow keys go to equation.move instead) leave
// the equation and move on, as before, rather than opening the equation they land next to.
s.run("caret.set", &json!({"pos": Pos { off: after, ..p0.clone() }})).unwrap();
s.run("equation.edit", &json!({})).unwrap();
s.run("caret.left", &json!({})).unwrap();
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 1));
// With two equations side by side, Right from the first goes on past the second.
s.run("caret.set", &json!({"pos": Pos { off: after, ..p1.clone() }})).unwrap();
s.run("insert.equation", &json!({"linear": "z", "edit": false})).unwrap();
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p1.clone() }})).unwrap();
s.run("equation.edit", &json!({})).unwrap();
s.run("caret.right", &json!({})).unwrap();
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after + OBJ.len_utf8()));
// That holds only for the command that left the equation: the next Right opens one again.
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap();
s.run("caret.right", &json!({})).unwrap();
assert_eq!(editing(&s), Some((p0.path.clone(), 1, MathPos::default())));
}
#[test]
fn numbering_conversion_and_display() {
let mut s = session();
+22
View File
@@ -398,6 +398,28 @@ mod tests {
assert!(!page_text(&mut s).contains("{ AUTHOR }"));
}
/// #980: F11 is full screen, as people expect of a desktop app; the field walk keeps Word's
/// other keys, Alt+F1 and Alt+Shift+F1 (and Shift+F11).
#[test]
fn f11_is_full_screen_and_alt_f1_walks_fields() {
let s = Session::new(wordcraft_doc::Document::new());
let keymap = crate::keymap::registry_keymap(&s.registry, s.keymap());
let chord = |c: &str| craft_keymap::Chord::parse(c).unwrap();
let key = |k: &str| keymap.holder(&chord(k)).map(|c| c.id);
assert_eq!(key("F11").as_deref(), Some("view.fullScreen"));
assert_eq!(key("Alt+F1").as_deref(), Some("fields.next"));
assert_eq!(key("Alt+Shift+F1").as_deref(), Some("fields.previous"));
assert_eq!(key("Shift+F11").as_deref(), Some("fields.previous"));
assert_eq!(key("Mod+F11").as_deref(), Some("fields.lock"));
let shortcut = s.registry.get("view.fullScreen").map(|c| c.shortcut);
if cfg!(target_os = "macos") {
assert_eq!(shortcut, Some("Mod+Ctrl+F / F11"));
assert_eq!(key("Mod+Ctrl+F").as_deref(), Some("view.fullScreen"));
} else {
assert_eq!(shortcut, Some("F11"));
}
}
/// Editing a code changes the instruction and the result; lock keeps a result through updates;
/// unlink turns the field into its text in one undo step; Alt+F1/Shift+F11 walk the fields.
#[test]
+1 -1
View File
@@ -20,7 +20,7 @@ pub const MAX_AUTHOR_CHARS: usize = 255;
/// carry an author.
pub fn normalize_author(name: &str) -> Result<String, CmdError> {
let name: String = name.trim().chars().filter(|c| !c.is_control()).take(MAX_AUTHOR_CHARS).collect();
let name = name.trim_end();
let name = name.trim();
if name.is_empty() {
return Err(CmdError::Params("`name` must not be blank".into()));
}
+88 -2
View File
@@ -359,6 +359,20 @@ pub enum Piece {
Named(String),
/// `^c`: the clipboard.
Clip,
/// A straight `"` or `'` typed as itself (not a regex, not with special characters off, which
/// takes the text as written, and not given by its code such as `^034`): curled with smart
/// quotes on, as typing curls it ([`Quotes`]).
Quote(char),
}
/// How a quote typed in Replace with goes in (#7307).
#[derive(Clone, Copy, Debug)]
pub enum Quotes {
/// As typed.
Straight,
/// Curled by the typing rule ("straight quotes with smart quotes"): `before` is the character
/// in front of the match, `None` at a paragraph's start.
Smart { before: Option<char> },
}
/// Read Replace with text: `^` codes (unless `literal`), `\1`–`\9` with wildcards, and with a
@@ -438,6 +452,11 @@ pub fn parse_replace(with: &str, o: &Opts) -> Vec<Piece> {
i += used;
continue;
}
if matches!(c, '"' | '\'') && !o.regex {
flush_literal(&mut cur, &mut out);
out.push(Piece::Quote(c));
continue;
}
cur.push(c);
}
flush_literal(&mut cur, &mut out);
@@ -511,7 +530,8 @@ fn as_inserted(s: &str) -> String {
}
/// Fill in Replace with text for one match: `found` is the matched text, `group(n)` a group's.
pub fn expand(pieces: &[Piece], found: &str, group: &dyn Fn(usize) -> Option<String>, clip: &str) -> String {
/// A typed quote is curled by what goes in before it: the replacement so far, else `before`.
pub fn expand(pieces: &[Piece], found: &str, group: &dyn Fn(usize) -> Option<String>, clip: &str, quotes: Quotes) -> String {
let mut out = String::new();
for p in pieces {
match p {
@@ -520,11 +540,39 @@ pub fn expand(pieces: &[Piece], found: &str, group: &dyn Fn(usize) -> Option<Str
Piece::Group(n) => out.push_str(&as_inserted(&group(*n).unwrap_or_default())),
Piece::Clip => out.push_str(&clip.replace("\r\n", "\r").replace('\n', "\r")),
Piece::Named(_) => {}
Piece::Quote(q) => {
let curly = match quotes {
Quotes::Smart { before } => super::text::smart_quote(out.chars().next_back().or(before), *q),
Quotes::Straight => None,
};
match curly {
Some(c) => out.push_str(c),
None => out.push(*q),
}
}
}
}
out
}
/// Whether Replace with has a quote typed as itself, which smart quotes curl.
pub fn has_typed_quote(pieces: &[Piece]) -> bool {
pieces.iter().any(|p| matches!(p, Piece::Quote(_)))
}
/// The match already reads as its replacement: the same text, with a curly quote of the same
/// kind (single or double) wherever the replacement has a curly one. Replace leaves such a match
/// alone and doesn't count it (#7307), so a typed `'` that also finds curly apostrophes keeps one
/// set the other way on purpose (’90s).
pub fn already_curled(found: &str, rep: &str) -> bool {
let kind = |c: char| match c {
'\u{2018}' | '\u{2019}' => Some('\''),
'\u{201C}' | '\u{201D}' => Some('"'),
_ => None,
};
found.chars().count() == rep.chars().count() && found.chars().zip(rep.chars()).all(|(f, r)| f == r || (kind(f).is_some() && kind(f) == kind(r)))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -535,7 +583,45 @@ mod tests {
}
fn replaced(with: &str) -> String {
expand(&parse_replace(with, &Opts::default()), "", &|_| None, "")
expand(&parse_replace(with, &Opts::default()), "", &|_| None, "", Quotes::Straight)
}
fn curled(with: &str, o: &Opts, before: Option<char>) -> String {
expand(&parse_replace(with, o), "", &|_| None, "", Quotes::Smart { before })
}
#[test]
fn a_typed_quote_curls_by_what_goes_before_it_and_a_coded_one_stays_straight() {
let o = Opts::default();
// Opening at a paragraph's start or after a space, closing after a letter.
assert_eq!(curled("\"", &o, None), "\u{201C}");
assert_eq!(curled("\"", &o, Some(' ')), "\u{201C}");
assert_eq!(curled("\"", &o, Some('d')), "\u{201D}");
assert_eq!(curled("'", &o, Some('n')), "\u{2019}");
// Inside the replacement, the text before it decides.
assert_eq!(curled("\"quoted\"", &o, Some(' ')), "\u{201C}quoted\u{201D}");
assert_eq!(curled(" 'a'", &o, Some('x')), " \u{2018}a\u{2019}");
assert_eq!(curled("^p\"", &o, Some('x')), "\r\u{201C}");
// Given by its code, a quote stays straight; with smart quotes off, typed ones do too.
for code in ["^034", "^039", "^u34", "^0039"] {
let straight = if code.ends_with("34") { "\"" } else { "'" };
assert_eq!(curled(code, &o, Some('x')), straight, "{code}");
}
assert_eq!(replaced("\"a'"), "\"a'");
// A regex replacement and an escaped wildcard one are taken as written.
assert_eq!(curled("\"", &Opts { regex: true, ..o }, None), "\"");
assert_eq!(curled("\\\"", &Opts { wildcards: true, ..o }, None), "\"");
assert_eq!(curled("\"", &Opts { wildcards: true, ..o }, None), "\u{201C}");
}
#[test]
fn a_match_already_curled_the_same_kind_reads_as_its_replacement() {
assert!(already_curled("\u{2019}", "\u{2018}"));
assert!(already_curled("don\u{2019}t", "don\u{2019}t"));
assert!(already_curled("\u{201C}", "\u{201D}"));
assert!(!already_curled("'", "\u{2019}"), "a straight quote is curled");
assert!(!already_curled("\u{2019}", "\u{201D}"), "a single quote isn't a double one");
assert!(!already_curled("dont", "don\u{2019}t"));
}
#[test]
+2 -2
View File
@@ -53,11 +53,11 @@ impl Recorder<'_> {
if let Some(r) = self.rid {
return r;
}
let found = self.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == self.author && r.date == self.date);
let found = self.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == self.author && r.instant() == self.date);
let r = match found {
Some(i) => i as u32,
None => {
self.revisions.push(Revision { kind: RevisionKind::Format, author: self.author.clone(), date: self.date.clone(), move_name: None });
self.revisions.push(crate::cmd::made_revision(RevisionKind::Format, self.author.clone(), self.date.clone()));
self.revisions.len().saturating_sub(1) as u32
}
};
+95
View File
@@ -1,5 +1,7 @@
//! Character formatting (Home › Font).
use std::sync::{Arc, PoisonError};
use serde_json::{Value, json};
use wordcraft_doc::eq::{EncloseShape, EncloseStyle, Enclosure};
use wordcraft_doc::props::{Border, CharProps, Highlight, Rgb, TextColor, Underline, VertAlign};
@@ -8,8 +10,44 @@ use wordcraft_doc::{InlineObject, PartKind, Pos, RevisionKind, StoryRef};
use super::sel_result;
use super::tools::{is_turkic, lower_char, upper_char};
use crate::doc_state::{ColumnBlock, Selection};
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
#[derive(Clone, PartialEq)]
struct StateKey {
document_id: u64,
rev: u64,
sel: Selection,
pending: Option<CharProps>,
pending_at: Option<Pos>,
column: Option<ColumnBlock>,
font_gen: u64,
}
/// Cached result of [`cached_state`] and the session inputs it depends on.
pub(crate) struct StateCache {
key: StateKey,
value: Arc<Value>,
}
impl StateCache {
pub(crate) fn rev(&self) -> u64 {
self.key.rev
}
}
fn state_key(s: &Session) -> StateKey {
StateKey {
document_id: s.document_id(),
rev: s.rev(),
sel: s.sel.clone(),
pending: s.pending.clone(),
pending_at: s.pending_at.clone(),
column: s.column.clone(),
font_gen: wordcraft_fonts::FontDb::global().generation(),
}
}
/// Word's font size list.
pub const SIZES: [f32; 17] = [8.0, 9.0, 10.0, 10.5, 11.0, 12.0, 14.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 36.0, 48.0, 72.0];
@@ -879,8 +917,30 @@ fn set(s: &mut Session, v: &Value) -> CmdResult {
apply(s, &|c| c.overlay(&props))
}
/// What the ribbon shows: the formatting at the selection (mixed values are null), cached per
/// document revision, selection, pending caret state, column selection, and font generation.
pub fn cached_state(s: &Session) -> Arc<Value> {
let key = state_key(s);
{
let cache = s.format_state.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(cached) = cache.as_ref()
&& cached.key == key
{
return Arc::clone(&cached.value);
}
}
let value = Arc::new(compute_state(s));
let mut cache = s.format_state.lock().unwrap_or_else(PoisonError::into_inner);
*cache = Some(StateCache { key, value: Arc::clone(&value) });
value
}
/// What the ribbon shows: the formatting at the selection (mixed values are null).
pub fn state(s: &Session) -> Value {
(*cached_state(s)).clone()
}
fn compute_state(s: &Session) -> Value {
let all = resolved(s);
let first = all.first().cloned();
let same = |f: &dyn Fn(&ResolvedChar) -> Value| -> Value {
@@ -906,6 +966,7 @@ pub fn state(s: &Session) -> Value {
"italic": all.iter().all(shown_italic),
"underline": all.iter().all(|r| r.underline != Underline::None),
"underlineColor": same(&|r| json!(r.underline_color.map_or_else(|| "auto".to_string(), |c| c.hex()))),
"shading": same(&|r| json!(r.shading.map(|c| c.hex()))),
"strike": all.iter().all(|r| r.strike),
"border": all.iter().all(|r| r.border.is_some()),
"subscript": all.iter().all(|r| r.vert_align == VertAlign::Subscript),
@@ -927,6 +988,14 @@ pub fn state(s: &Session) -> Value {
})
}
/// The selection's uniform highlight colour (`Some(None)` when uniformly unhighlighted), or `None`
/// when the selection is mixed or empty.
pub fn uniform_highlight(s: &Session) -> Option<Option<Rgb>> {
let all = resolved(s);
let first = all.first()?.highlight;
all.iter().all(|r| r.highlight == first).then_some(first)
}
/// What Enclose Characters works on: the selected text (one full-width or up to two half-width
/// characters), or enclosed characters already there (selected, or beside the caret).
#[derive(Clone, Debug, PartialEq)]
@@ -1054,4 +1123,30 @@ mod tests {
assert_eq!(convert("one 3.14 apples and two 2.5 pears.", "sentence", true), "One 3.14 apples and two 2.5 pears.");
assert_eq!(convert("pi is 3.14. next sentence.", "sentence", true), "Pi is 3.14. Next sentence.");
}
#[test]
fn cached_state_hits_until_selection_format_or_pending_changes() {
use serde_json::json;
use std::sync::Arc;
let mut s = crate::Session::new(wordcraft_doc::Document::new());
let a = super::cached_state(&s);
let b = super::cached_state(&s);
assert!(Arc::ptr_eq(&a, &b), "unchanged session should reuse cached format state Arc");
s.run("text.insert", &json!({"text": "hello world"})).unwrap();
let c = super::cached_state(&s);
assert!(!Arc::ptr_eq(&b, &c), "text edit bumps rev and invalidates cache");
s.run("format.bold", &json!({})).unwrap();
let d = super::cached_state(&s);
assert!(!Arc::ptr_eq(&c, &d), "pending bold changes caret formatting");
assert_eq!(d["bold"], json!(true));
assert!(Arc::ptr_eq(&d, &super::cached_state(&s)));
s.run("select.text", &json!({"text": "hello"})).unwrap();
let e = super::cached_state(&s);
assert!(!Arc::ptr_eq(&d, &e), "selection change updates format state");
assert_eq!(e["bold"], json!(false));
}
}
+196
View File
@@ -27,6 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
r#"{"type"?: "indented|runIn", "columns"?: 1-4, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none", "headings"?: bool (letter headings)} (replaces an existing index's settings)"#,
),
CommandSpec::new("references.updateIndex", "Update Index", "References › Index", |s, _| {
check_index_reachable(s)?;
super::citations::update_generated(s)?;
sel_result(s)
}),
@@ -135,8 +136,63 @@ fn index_field(s: &Session) -> Option<(usize, String)> {
})
}
/// Whether an INDEX field (a plain one or a range field, as Word files hold it) sits in the main
/// text's own paragraphs (`main`), or anywhere else a reader sees: a table cell, a text box, a
/// header or a footer in use. Stored headers and footers no page shows (a first-page header
/// while Different First Page is off) don't count. Only an index in the main text is rebuilt.
fn has_index(s: &Session, main: bool) -> bool {
s.doc.shown_stories().into_iter().any(|story| {
s.doc
.para_paths(story)
.iter()
.filter(|path| (story == StoryRef::Body && path.depth() == 0) == main)
.filter_map(|path| s.doc.para(story, path))
.any(|p| {
p.objects.iter().any(|o| {
matches!(o, InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX")
})
})
})
}
/// Refuses Insert and Update Index when the document has an index they can't rebuild, even beside
/// one in the main text, rather than adding a second index or reporting an update that left it
/// unchanged.
fn check_index_reachable(s: &Session) -> Result<(), CmdError> {
if has_index(s, false) {
return Err(CmdError::Failed(
"the index is in a table, text box, header or footer, where it can't be updated; move it into the main text, then use Update Index"
.into(),
));
}
// A range-field index after text in its paragraph is not rebuilt either: Update Index only
// takes one that starts its paragraph.
if range_index_after_text(s) {
return Err(CmdError::Failed(
"the index follows text in its paragraph, where it can't be updated; put it at the start of its own paragraph in the main text".into(),
));
}
Ok(())
}
/// Whether a main-text range-field INDEX has text before it in its paragraph.
fn range_index_after_text(s: &Session) -> bool {
s.doc.body.iter().filter_map(|b| b.as_para()).any(|p| {
p.objects_with_offsets().any(|(off, o)| {
matches!(o, InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX")
&& !p.text.get(..off).is_some_and(|t| t.chars().all(|c| c.is_whitespace() || c == wordcraft_doc::para::OBJ))
})
})
}
fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
let instr = index_instr(v);
check_index_reachable(s)?;
// An index Word wrote as a range field is rebuilt by Update Index; Insert Index would add a
// second one beside it (#8034).
if index_field(s).is_none() && has_index(s, true) {
return Err(CmdError::Failed("the document already has an index; use Update Index to rebuild it".into()));
}
match index_field(s) {
Some((i, _)) => {
// Settings for the index that is there: a new field code, then rebuild it.
@@ -484,4 +540,144 @@ mod tests {
let (i, _) = index_field(&s).unwrap();
assert_eq!(s.doc.body[i + 2].as_para().unwrap().props.tabs.as_ref().unwrap()[0].leader, TabLeader::Hyphen);
}
/// #3670: an index in a table cell or a text box (as imported documents have it) can't be
/// rebuilt where it is, so Insert and Update Index say so, and Insert Index doesn't add a
/// second index at the caret.
#[test]
fn an_index_outside_the_main_text_is_refused_not_doubled() {
let indexes = |s: &Session| {
std::iter::once(StoryRef::Body)
.chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)))
.flat_map(|story| s.doc.para_paths(story).into_iter().filter_map(move |path| s.doc.para(story, &path).cloned()))
.flat_map(|p| p.objects)
.filter(|o| matches!(o, InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX"))
.count()
};
for in_box in [false, true] {
let mut s = Session::new(wordcraft_doc::Document::from_text(
"Kilns are hot.
End.",
));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
let at = if in_box {
s.run("insert.textBox", &json!({"text": "Box"})).unwrap();
let id = s.doc.parts.iter().find(|(_, p)| p.kind == wordcraft_doc::PartKind::TextBox).map(|(id, _)| *id).unwrap();
Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 }
} else {
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
let cell = s.doc.para_paths(StoryRef::Body).into_iter().find(|path| path.depth() > 0).unwrap();
Pos { story: StoryRef::Body, path: cell, off: 0 }
};
// A range field, as a Word file holds its index.
let p = s.doc.para_mut(at.story, &at.path).unwrap();
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
let r = s.run("references.index", &json!({"columns": 2}));
assert!(r.is_err(), "Insert Index with the index in a {}: {r:?}", if in_box { "text box" } else { "table" });
assert_eq!(indexes(&s), 1, "INDEX fields after Insert Index");
assert!(s.run("references.updateIndex", &json!({})).is_err(), "Update Index reports the index it can't rebuild");
}
}
/// #3670: an index in a table is refused even when the main text also has one, so the update
/// can't report success and leave the table's index as it was.
#[test]
fn an_index_in_a_table_is_refused_beside_one_in_the_main_text() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("references.index", &json!({})).unwrap();
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
let cell = s.doc.para_paths(StoryRef::Body).into_iter().find(|path| path.depth() > 0).unwrap();
let p = s.doc.para_mut(StoryRef::Body, &cell).unwrap();
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default()).unwrap();
assert!(s.run("references.index", &json!({"columns": 2})).is_err());
assert!(s.run("references.updateIndex", &json!({})).is_err());
}
/// #3670: only the headers a page shows count. An INDEX in a first-page header is out of
/// reach while Different First Page is on, and doesn't block Insert Index while it is off.
#[test]
fn an_index_in_a_header_blocks_insert_only_while_the_header_is_shown() {
let with_header_index = |first: bool, title_page: bool| {
let mut d = wordcraft_doc::Document::from_text("Kilns are hot.");
let mut p = wordcraft_doc::Paragraph::new();
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
let id = d.add_part(wordcraft_doc::PartKind::Header, vec![std::sync::Arc::new(wordcraft_doc::Block::Para(p))]);
if first {
d.last_section.headers.first = Some(id);
} else {
d.last_section.headers.default = Some(id);
}
d.last_section.title_page = title_page;
let mut s = Session::new(d);
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s
};
let body_has_index = |s: &Session| index_field(s).is_some();
// Linked (default) header: shown, so Insert Index is refused.
let mut s = with_header_index(false, false);
assert!(s.run("references.index", &json!({})).is_err());
assert!(!body_has_index(&s));
// First-page header with Different First Page off: hidden, so the body gets its index.
let mut s = with_header_index(true, false);
s.run("references.index", &json!({})).unwrap();
assert!(body_has_index(&s));
// The same header with Different First Page on is shown again.
let mut s = with_header_index(true, true);
assert!(s.run("references.index", &json!({})).is_err());
assert!(!body_has_index(&s));
}
/// An index Word wrote as a range field in the main text is rebuilt by Update Index; Insert
/// Index says so instead of adding a second one (#8034).
#[test]
fn insert_index_leaves_a_range_field_index_in_the_main_text_to_update_index() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
let at = s.doc.body.len();
let mut para = wordcraft_doc::para::Paragraph::new();
para.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
para.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
s.doc.insert_block(StoryRef::Body, &Path::top(at), wordcraft_doc::Block::Para(para)).unwrap();
let before = s.doc.body.len();
assert!(s.run("references.index", &json!({})).is_err());
assert_eq!(s.doc.body.len(), before, "no second index was added");
s.run("references.updateIndex", &json!({})).unwrap();
let text: String =
s.doc.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.replace(wordcraft_doc::para::OBJ, "")).collect::<Vec<_>>().join(
"
",
);
assert!(text.contains("Kilns are hot."), "the text before the index survives: {text:?}");
assert!(text.contains("Kilns, 1"), "Update Index generated an entry: {text:?}");
}
#[test]
fn a_range_field_index_after_text_is_refused_not_reported_updated() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
let p = s.doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
let end = p.len();
p.insert_object(end, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(end, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
assert!(s.run("references.updateIndex", &json!({})).is_err());
assert!(s.run("references.index", &json!({})).is_err());
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ pub use items::{
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
use links::{bookmark, delete_bookmark, link, link_targets};
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span};
pub use objects::{base64_decode, base64_encode};
pub use objects::{MAX_TABLE_ROWS, base64_decode, base64_encode};
use objects::{icon, shape, table, text_box};
pub(crate) use objects::{image_ext, picture};
+7 -10
View File
@@ -7,7 +7,7 @@ use super::{
/// even page or the default), made when there is none: with Different First Page on, a header
/// inserted on page 1 is the one page 1 shows (#2826).
pub(super) fn hf_part(s: &mut Session, header: bool) -> u32 {
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
let block = crate::cmd::page::section_end_of_focus(s);
let layout = s.layout();
let page = if s.sel.focus.story == StoryRef::Body { layout.page_of(&s.sel.focus) } else { Some(s.page_hint) };
let slot = page.and_then(|pg| layout.pages.get(pg)).map(|pg| pg.hf_slot).unwrap_or_default();
@@ -98,15 +98,12 @@ pub(super) fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
let shown = match page {
Some(page) => shown_hf(s, page, header)?,
None => {
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
let set = s
.doc
.sections()
.into_iter()
.find(|(end, _)| block <= *end)
.or_else(|| s.doc.sections().pop())
.map(|(_, sp)| if header { sp.headers.default } else { sp.footers.default });
set.flatten().filter(|id| s.doc.parts.contains_key(id))
// The caret's section's own, else the one it is linked to from a section before it, as
// layout shows it (#3639): editing that one keeps the link.
let section = crate::cmd::page::hf_section_of_focus(s);
let sections = s.doc.sections();
let set = sections.iter().take(section + 1).rev().find_map(|(_, sp)| if header { sp.headers.default } else { sp.footers.default });
set.filter(|id| s.doc.parts.contains_key(id))
}
};
let Some(id) = shown else {
+1 -1
View File
@@ -311,7 +311,7 @@ pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d:
('m', _) => out.push_str(&mm.to_string()),
('s', 2..) => out.push_str(&format!("{ss:02}")),
('s', _) => out.push_str(&ss.to_string()),
('a' | 'A', _) => out.push_str(if hh < 12 { "AM" } else { "PM" }),
// Bare `a`/`A` is literal; AM/PM is the `am/pm` token (#3488).
_ => {
for _ in 0..n {
out.push(c);
+30 -3
View File
@@ -23,8 +23,13 @@ fn insert_block_at_caret(s: &mut Session, block: Block) -> Result<Path, CmdError
Ok(insert_at)
}
/// Most rows an inserted table has. The table model holds more, but an inserted table starts
/// small: the command that inserts one clamps to this, so the others read it rather than
/// repeating the number.
pub const MAX_TABLE_ROWS: usize = 1_000;
pub(super) fn table(s: &mut Session, v: &Value) -> CmdResult {
let rows = p::u64(v, "rows").unwrap_or(2).clamp(1, 1000) as usize;
let rows = p::u64(v, "rows").unwrap_or(2).clamp(1, MAX_TABLE_ROWS as u64) as usize;
let cols = p::u64(v, "cols").unwrap_or(2).clamp(1, 63) as usize;
let width = s.doc.sections().first().map(|(_, sp)| sp.text_width()).unwrap_or(468.0);
let mut t = Table::new(rows, cols, width);
@@ -37,6 +42,7 @@ pub(super) fn table(s: &mut Session, v: &Value) -> CmdResult {
if s.doc.para_at(&s.sel.focus).is_some_and(|p| s.doc.styles.resolve_para(&p.props).bidi) {
t.props.bidi_visual = true;
}
cells_in_language(&mut t, &s.typing_props());
let story = s.sel.focus.story;
let path = insert_block_at_caret(s, Block::Table(t))?;
let mut first = path.0.clone();
@@ -45,6 +51,27 @@ pub(super) fn table(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"table": path.0}))
}
/// Like Word, a new table is in the language of the text it is inserted in (#6013): each cell's
/// paragraph mark takes `at`'s languages and Do not check spelling, so what is typed in the cells
/// is proofed in that language rather than the document's default. Unset ones stay unset.
fn cells_in_language(t: &mut Table, at: &CharProps) {
for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) {
for b in &mut cell.blocks {
if let Block::Para(p) = std::sync::Arc::make_mut(b) {
let mark = &mut p.mark;
for (to, from) in [(&mut mark.lang, &at.lang), (&mut mark.lang_ea, &at.lang_ea), (&mut mark.lang_bidi, &at.lang_bidi)] {
if from.is_some() {
to.clone_from(from);
}
}
if at.no_proof.is_some() {
mark.no_proof = at.no_proof;
}
}
}
}
}
/// Minimal base64 (standard alphabet, padding optional, whitespace ignored).
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(s.len() * 3 / 4);
@@ -117,9 +144,9 @@ fn place_picture(s: &mut Session, bytes: Vec<u8>, width: Option<f32>, alt: &str)
None => return Err(CmdError::Failed("not a supported image (PNG, JPEG, GIF, WebP, BMP, TIFF, WMF, EMF)".into())),
},
};
// Fitted to the room where it goes: the table cell, the column, its own section (#5428).
let max_w = s.room_at(&s.sel.ordered().0);
let key = s.doc.add_media(bytes, ext);
// Fitted to the text width.
let max_w = s.doc.sections().first().map(|(_, sp)| sp.text_width()).unwrap_or(468.0);
let (mut w, mut h) = (natural_w, natural_h);
if let Some(want) = width {
// At most 22 inches, as for icons: a huge width made the height of a tall picture infinite.
+2
View File
@@ -358,6 +358,8 @@ fn date_pictures_keep_quoted_text() {
// Two quotes outside quoted text are one too (an apostrophe), not an empty quoted text.
assert_eq!(format_date_parts("yyyy '' MM", 2026, 10, 21, (0, 0, 0), 0), "2026 ' 10");
assert_eq!(format_date_parts("d''MM", 2026, 10, 21, (0, 0, 0), 0), "21'10");
// Bare `a` is literal, not AM/PM (#3488).
assert_eq!(format_date_parts("yyyy a", 2026, 10, 21, (14, 30, 0), 0), "2026 a");
}
#[test]
+1 -1
View File
@@ -27,7 +27,7 @@ pub use merge::{merge_range, refresh};
#[cfg(test)]
use merge::{mergefield_name, placeholder};
use recipients::recipients;
pub use recipients::{RECIPIENT_EXTENSIONS, is_spreadsheet_name, parse_csv};
pub use recipients::{CsvLimits, MAX_CELLS, MAX_FIELDS, MAX_TEXT_BYTES, RECIPIENT_EXTENSIONS, RECIPIENT_LIMITS, is_spreadsheet_name, parse_csv};
/// The mail-merge data source and preview state (lives in the session, not the document).
#[derive(Clone, Debug, Default)]
+76 -20
View File
@@ -19,22 +19,32 @@ fn csv_separator(text: &str) -> char {
[',', ';', '\t'].into_iter().max_by_key(|c| unquoted.matches(*c).count()).unwrap_or(',')
}
/// Ends the current row: kept when it has any non-empty field, otherwise dropped.
fn push_csv_row(rows: &mut Vec<Vec<String>>, row: &mut Vec<String>) {
if row.iter().any(|x| !x.is_empty()) {
rows.push(std::mem::take(row));
} else {
row.clear();
}
/// What a CSV may hold while it is read: the parser refuses a list that is over these, so a
/// hostile file is never built and then cut.
#[derive(Clone, Copy)]
pub struct CsvLimits {
/// Most columns in a record.
pub fields: usize,
/// Most cells in the list: its records times its widest record.
pub cells: usize,
/// Most bytes of cell text in all.
pub text: usize,
}
/// Parse CSV (RFC 4180-ish: quotes, doubled quotes, commas/semicolons/tabs).
pub fn parse_csv(text: &str) -> Vec<Vec<String>> {
///
/// The limits are kept while the list is read, not after it: a record wider than
/// `limits.fields`, a list of more than `limits.cells` cells, or more than `limits.text` bytes
/// of cell text is refused, rather than built and then cut.
pub fn parse_csv(text: &str, limits: &CsvLimits) -> Result<Vec<Vec<String>>, CmdError> {
let sep = csv_separator(text);
let mut rows = Vec::new();
let mut row = Vec::new();
let mut cell = String::new();
let mut q = false;
// The widest record read so far, and the bytes of cell text read so far.
let mut widest = 0usize;
let mut text_bytes = 0usize;
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if q {
@@ -51,29 +61,75 @@ pub fn parse_csv(text: &str) -> Vec<Vec<String>> {
} else if c == '"' {
q = true;
} else if c == sep {
row.push(std::mem::take(&mut cell));
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
} else if c == '\n' || c == '\r' {
if c == '\r' && chars.peek() == Some(&'\n') {
chars.next();
}
row.push(std::mem::take(&mut cell));
push_csv_row(&mut rows, &mut row);
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
end_row(&mut rows, &mut row, &mut widest, limits)?;
} else {
cell.push(c);
}
// The text read so far: the finished cells and the one being read.
if text_bytes.saturating_add(cell.len()) > limits.text {
return Err(CmdError::Failed(format!("the CSV can't have more than {} of text", text_size(limits.text))));
}
if rows.len() > 100_000 {
break;
}
}
row.push(cell);
push_csv_row(&mut rows, &mut row);
rows
// The last cell, when the file doesn't end with a line break.
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
end_row(&mut rows, &mut row, &mut widest, limits)?;
Ok(rows)
}
/// A finished cell joins the record: the record's width stays inside the limit.
fn end_cell(row: &mut Vec<String>, cell: &mut String, text_bytes: &mut usize, limits: &CsvLimits) -> Result<(), CmdError> {
*text_bytes = text_bytes.saturating_add(cell.len());
row.push(std::mem::take(cell));
if row.len() > limits.fields {
return Err(CmdError::Failed(format!("the CSV can't have more than {} columns", limits.fields)));
}
Ok(())
}
/// A finished record joins the list (an empty one is dropped). The list costs its records times
/// its widest record — a recipient list pads every record to the header's width — so a list
/// over the limit is refused here, while it is read.
fn end_row(rows: &mut Vec<Vec<String>>, row: &mut Vec<String>, widest: &mut usize, limits: &CsvLimits) -> Result<(), CmdError> {
if row.iter().any(|x| !x.is_empty()) {
*widest = (*widest).max(row.len());
rows.push(std::mem::take(row));
} else {
row.clear();
}
if rows.len().saturating_mul(*widest) > limits.cells {
return Err(CmdError::Failed(format!("the CSV can't have more than {} cells (its records times its widest record)", limits.cells)));
}
Ok(())
}
/// A byte budget, said the way a reader says it.
fn text_size(bytes: usize) -> String {
if bytes >= 1 << 20 { format!("{} MB", bytes >> 20) } else { format!("{bytes} bytes") }
}
/// Most records and fields a recipient list keeps.
const MAX_RECORDS: usize = 100_000;
const MAX_FIELDS: usize = 1_000;
pub const MAX_FIELDS: usize = 1_000;
/// Most cells a recipient list keeps: its records times its fields. A recipient list pads every
/// record to the header's width, so this is what a list costs, not how many values it says.
pub const MAX_CELLS: usize = 2_000_000;
/// Most bytes of cell text a recipient list keeps. The table path keeps the same budget.
pub const MAX_TEXT_BYTES: usize = 64 << 20;
/// The limits a recipient list keeps.
pub const RECIPIENT_LIMITS: CsvLimits = CsvLimits { fields: MAX_FIELDS, cells: MAX_CELLS, text: MAX_TEXT_BYTES };
pub(super) fn cell(x: &Value) -> String {
match x {
@@ -117,12 +173,12 @@ fn table_from_rows(fields: Option<&Vec<Value>>, arr: &[Value]) -> Result<(Vec<St
/// Skip unquoted blank prefix lines only when a text recipient list has a header.
/// Headerless lists and the shared CSV reader keep whitespace records.
fn recipient_csv(text: &str, headers: bool) -> Vec<Vec<String>> {
fn recipient_csv(text: &str, headers: bool) -> Result<Vec<Vec<String>>, CmdError> {
let prefix = text
.split_inclusive(['\n', '\r'])
.take_while(|line| headers && line.trim().is_empty())
.fold(0_usize, |bytes, line| bytes.saturating_add(line.len()));
parse_csv(text.get(prefix..).unwrap_or_default())
parse_csv(text.get(prefix..).unwrap_or_default(), &RECIPIENT_LIMITS)
}
pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
@@ -131,7 +187,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
table_from_rows(v.get("fields").and_then(Value::as_array), arr)?
} else {
let all = if let Some(c) = p::str(v, "csv") {
recipient_csv(c, p::bool(v, "headers").unwrap_or(true))
recipient_csv(c, p::bool(v, "headers").unwrap_or(true))?
} else {
let (bytes, ext) = if let Some(d) = p::str(v, "data") {
let b = crate::cmd::insert::base64_decode(d.trim()).ok_or_else(|| CmdError::Params("`data` isn't valid base64".into()))?;
@@ -176,7 +232,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
}
Pick::Index(0)
}
Some(_) => return Err(CmdError::Params("`sheet` must be a sheet name or number".into())),
Some(_) => return Err(CmdError::Params("`sheet` must be a sheet name or positive integer (1 = the first sheet)".into())),
};
let (names, rows) = read_rows(&bytes, pick).map_err(CmdError::Failed)?;
let chosen = match pick {
@@ -188,7 +244,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
sheet = json!(chosen);
rows
} else {
recipient_csv(&decode(&bytes, v)?, p::bool(v, "headers").unwrap_or(true))
recipient_csv(&decode(&bytes, v)?, p::bool(v, "headers").unwrap_or(true))?
}
};
header_split(all, p::bool(v, "headers").unwrap_or(true))?
+75 -17
View File
@@ -2,9 +2,54 @@ use super::*;
#[test]
fn csv_parsing() {
let r = parse_csv("Name,City\n\"Smith, Ann\",Paris\r\nBo,\"Oslo \"\"N\"\"\"\n\n");
let r = parse_csv("Name,City\n\"Smith, Ann\",Paris\r\nBo,\"Oslo \"\"N\"\"\"\n\n", &RECIPIENT_LIMITS).unwrap();
assert_eq!(r, vec![vec!["Name", "City"], vec!["Smith, Ann", "Paris"], vec!["Bo", "Oslo \"N\""]]);
assert_eq!(parse_csv("a;b\n1;2")[1], vec!["1", "2"]);
assert_eq!(parse_csv("a;b\n1;2", &RECIPIENT_LIMITS).unwrap()[1], vec!["1", "2"]);
}
/// The parser keeps its limits while it reads the list, so a hostile list is refused
/// instead of being built and then cut.
#[test]
fn csv_parsing_refuses_a_list_over_its_limits() {
// A record wider than the limit.
let e = parse_csv("a,b,c,d,e", &CsvLimits { fields: 4, cells: 100, text: 1_000 }).unwrap_err();
assert!(e.to_string().contains("4 columns"), "{e}");
// More cells than the list keeps.
let e = parse_csv("a,b\nc,d\ne,f\ng,h\ni,j\nk,l", &CsvLimits { fields: 10, cells: 10, text: 1_000 }).unwrap_err();
assert!(e.to_string().contains("10 cells"), "{e}");
// More text than the list keeps.
let e = parse_csv("abcdefghij", &CsvLimits { fields: 10, cells: 100, text: 8 }).unwrap_err();
assert!(e.to_string().contains("of text"), "{e}");
// A list inside the limits still parses.
let limits = CsvLimits { fields: 4, cells: 10, text: 1_000 };
assert_eq!(parse_csv("a,b\nc,d", &limits).unwrap(), vec![vec!["a", "b"], vec!["c", "d"]]);
}
/// A recipient list over its limits is refused, not built.
#[test]
fn a_recipient_list_over_its_limits_is_refused() {
// A record wider than the list's fields.
let wide = format!("{}\nvalue", "f,".repeat(MAX_FIELDS + 1));
let e = parse_csv(&wide, &RECIPIENT_LIMITS).unwrap_err();
assert!(e.to_string().contains(&format!("{MAX_FIELDS} columns")), "{e}");
// A record of exactly the limit's width is kept.
let exact = format!("{}\nvalue", "f,".repeat(MAX_FIELDS - 1));
assert_eq!(parse_csv(&exact, &RECIPIENT_LIMITS).unwrap()[0].len(), MAX_FIELDS);
// A wide header over many records: the list would cost more cells than it keeps, and
// every record is padded to the header's width.
let mut csv = format!("{}\n", (0..MAX_FIELDS).map(|i| format!("f{i}")).collect::<Vec<_>>().join(","));
for _ in 0..=MAX_CELLS / MAX_FIELDS {
csv.push_str("value\n");
}
let e = parse_csv(&csv, &RECIPIENT_LIMITS).unwrap_err();
assert!(e.to_string().contains(&format!("{MAX_CELLS} cells")), "{e}");
// The command refuses it too, with a message of its own.
let mut s = Session::new(Document::new());
let e = s.run("mailings.recipients", &json!({"csv": wide})).unwrap_err();
assert!(e.to_string().contains("columns"), "{e}");
}
/// #4001: finishing a merge opens a new document, with a new undo history. It is not an
@@ -56,13 +101,16 @@ fn csv_delimiter_reads_complete_header_record() {
let quoted = header.replace('"', "\"\"");
let text = format!("\"{quoted}\"{sep}City{sep}{sep}\r\nAda{sep}Paris{sep}{sep}\nBo{sep}Oslo{sep}{sep}");
assert_eq!(
parse_csv(&text),
parse_csv(&text, &RECIPIENT_LIMITS).unwrap(),
vec![vec![header.as_str(), "City", "", ""], vec!["Ada", "Paris", "", ""], vec!["Bo", "Oslo", "", ""]],
"separator {sep:?}, embedded newline {newline:?}"
);
// A multiline field after an ordinary column must not end detection either.
let text = format!("ID{sep}\"{quoted}\"{sep}City\n1{sep}Ada{sep}Paris\n2{sep}Bo{sep}Oslo");
assert_eq!(parse_csv(&text), vec![vec!["ID", header.as_str(), "City"], vec!["1", "Ada", "Paris"], vec!["2", "Bo", "Oslo"]]);
assert_eq!(
parse_csv(&text, &RECIPIENT_LIMITS).unwrap(),
vec![vec!["ID", header.as_str(), "City"], vec!["1", "Ada", "Paris"], vec!["2", "Bo", "Oslo"]]
);
}
}
}
@@ -74,7 +122,7 @@ fn csv_delimiter_reads_multiline_headers_after_blank_lines() {
let header = format!("Given{newline}Family");
for prefix in ["\n\r\n", "\r", "\r\r"] {
let text = format!("{prefix}\"{header}\"{sep}City\rAda{sep}Paris");
assert_eq!(parse_csv(&text), vec![vec![header.as_str(), "City"], vec!["Ada", "Paris"]]);
assert_eq!(parse_csv(&text, &RECIPIENT_LIMITS).unwrap(), vec![vec![header.as_str(), "City"], vec!["Ada", "Paris"]]);
}
}
}
@@ -99,34 +147,41 @@ fn recipient_csv_blank_prefix_keeps_columns_without_dropping_literal_records() {
let rows = s.merge.rows.clone();
assert!(s.run("mailings.recipients", &json!({"csv": " \t\r\n \r"})).is_err());
assert_eq!(s.merge.rows, rows, "an empty headered list must not replace existing recipients");
assert_eq!(parse_csv(" \nName,Email\nAda,ada@example.com")[0], vec![" "], "the shared CSV reader keeps literal whitespace rows");
assert_eq!(
parse_csv(" \nName,Email\nAda,ada@example.com", &RECIPIENT_LIMITS).unwrap()[0],
vec![" "],
"the shared CSV reader keeps literal whitespace rows"
);
}
#[test]
fn csv_delimiter_keeps_record_boundaries_and_ties() {
// Later records cannot choose the header's delimiter.
assert_eq!(parse_csv("Name;City\rAda;Paris,,,,\rBo;Oslo"), vec![vec!["Name", "City"], vec!["Ada", "Paris,,,,"], vec!["Bo", "Oslo"]]);
assert_eq!(
parse_csv("Name;City\rAda;Paris,,,,\rBo;Oslo", &RECIPIENT_LIMITS).unwrap(),
vec![vec!["Name", "City"], vec!["Ada", "Paris,,,,"], vec!["Bo", "Oslo"]]
);
// Existing ties prefer tab, then semicolon, then comma.
assert_eq!(parse_csv("A,B;C\n1,2;3"), vec![vec!["A,B", "C"], vec!["1,2", "3"]]);
assert_eq!(parse_csv("A;B\tC\n1;2\t3"), vec![vec!["A;B", "C"], vec!["1;2", "3"]]);
assert_eq!(parse_csv("Name\nAda,Paris;Oslo"), vec![vec!["Name"], vec!["Ada,Paris;Oslo"]]);
assert!(parse_csv("").is_empty());
assert_eq!(parse_csv("\nName\nAda"), vec![vec!["Name"], vec!["Ada"]]);
assert_eq!(parse_csv("A,B;C\n1,2;3", &RECIPIENT_LIMITS).unwrap(), vec![vec!["A,B", "C"], vec!["1,2", "3"]]);
assert_eq!(parse_csv("A;B\tC\n1;2\t3", &RECIPIENT_LIMITS).unwrap(), vec![vec!["A;B", "C"], vec!["1;2", "3"]]);
assert_eq!(parse_csv("Name\nAda,Paris;Oslo", &RECIPIENT_LIMITS).unwrap(), vec![vec!["Name"], vec!["Ada,Paris;Oslo"]]);
assert!(parse_csv("", &RECIPIENT_LIMITS).unwrap().is_empty());
assert_eq!(parse_csv("\nName\nAda", &RECIPIENT_LIMITS).unwrap(), vec![vec!["Name"], vec!["Ada"]]);
// The reader remains permissive about an unterminated quoted cell.
assert_eq!(parse_csv("Name,City\nAda,\"Paris\nOslo"), vec![vec!["Name", "City"], vec!["Ada", "Paris\nOslo"]]);
assert_eq!(parse_csv("Name,City\nAda,\"Paris\nOslo", &RECIPIENT_LIMITS).unwrap(), vec![vec!["Name", "City"], vec!["Ada", "Paris\nOslo"]]);
}
#[test]
fn csv_delimiter_ignores_quoted_text() {
let r = parse_csv("\"Name, first, last\";City\nAnn;Paris\n");
let r = parse_csv("\"Name, first, last\";City\nAnn;Paris\n", &RECIPIENT_LIMITS).unwrap();
assert_eq!(r, vec![vec!["Name, first, last", "City"], vec!["Ann", "Paris"]]);
}
#[test]
fn csv_delimiter_skips_leading_blank_lines() {
let want = vec![vec!["Name", "Email"], vec!["Ann", "ann@x.org"]];
assert_eq!(parse_csv("\nName,Email\nAnn,ann@x.org\n"), want);
assert_eq!(parse_csv("\r\n\r\nName;Email\r\nAnn;ann@x.org"), want);
assert_eq!(parse_csv("\nName,Email\nAnn,ann@x.org\n", &RECIPIENT_LIMITS).unwrap(), want);
assert_eq!(parse_csv("\r\n\r\nName;Email\r\nAnn;ann@x.org", &RECIPIENT_LIMITS).unwrap(), want);
}
/// Field types ignore case (ECMA-376 Part 1, 17.16.1), and `MERGEFIELDX` is another field.
@@ -242,7 +297,10 @@ fn recipients_from_a_workbook_ask_for_the_sheet_when_there_are_several() {
assert_eq!(r["fields"], json!(["Column 1", "Column 2", "Column 3"]));
assert_eq!(r["records"], 3);
assert!(s.run("mailings.recipients", &json!({"data": data, "sheet": 3})).is_err());
assert!(s.run("mailings.recipients", &json!({"data": data, "sheet": 0})).is_err());
assert!(matches!(
s.run("mailings.recipients", &json!({"data": data, "sheet": 0})),
Err(CmdError::Params(message)) if message == "`sheet` must be a sheet name or positive integer (1 = the first sheet)"
));
assert!(s.run("mailings.recipients", &json!({"data": "%%%"})).is_err());
}
+3 -3
View File
@@ -56,7 +56,7 @@ pub fn cut_tracked(s: &mut Session) -> Result<bool, CmdError> {
if !s.doc.settings.track_changes || !s.doc.settings.track_moves || a == b || a.story != b.story || !move_sized(&s.clipboard_text) {
return Ok(false);
}
s.doc.revisions.push(Revision::new(RevisionKind::Delete, s.author.clone(), now_iso()));
s.doc.revisions.push(crate::cmd::made_revision(RevisionKind::Delete, s.author.clone(), now_iso()));
let rid = (s.doc.revisions.len() - 1) as u32;
let at = track_delete_as(s, &a, &b, rid)?.at;
s.sel = Selection::caret(at);
@@ -75,13 +75,13 @@ pub fn take_paste(s: &mut Session, frag: &Fragment) -> Option<u32> {
return None;
}
let src = s.doc.revisions.get(m.rev as usize).filter(|r| r.kind == RevisionKind::Delete && r.move_name.is_none())?;
let date = src.date.clone();
let (date, date_utc) = (src.date.clone(), src.date_utc.clone());
let taken: BTreeSet<&str> = s.doc.revisions.iter().filter_map(|r| r.move_name.as_deref()).collect();
let name = (1..).map(|n: u64| format!("move{n}")).find(|n| !taken.contains(n.as_str()))?;
if let Some(r) = s.doc.revisions.get_mut(m.rev as usize) {
r.move_name = Some(name.clone());
}
s.doc.revisions.push(Revision { kind: RevisionKind::Insert, author: s.author.clone(), date, move_name: Some(name) });
s.doc.revisions.push(Revision { kind: RevisionKind::Insert, author: s.author.clone(), date, move_name: Some(name), date_utc });
Some((s.doc.revisions.len() - 1) as u32)
}
+3 -2
View File
@@ -29,14 +29,15 @@ pub use picture::{OriginalSize, PictureLook, cropped_original_size, fit_size, or
use picture::{clear_background, grown, picture_style};
#[cfg(test)]
pub(crate) use select::all_objects;
pub(crate) use select::select_object;
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};
pub use select::{min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects};
#[cfg(test)]
use shape::can_link;
pub(crate) use shape::set_text_body;
pub use shape::text_box_target;
pub use shape::{text_box_target, text_box_targets};
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, with_obj};
use super::select::{edit_float, min_size, movable_story, obj_size, select_object, selected_or_text_box, 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(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let (pos, obj) = selected_or_text_box(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(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let (pos, obj) = selected_or_text_box(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(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let (pos, obj) = selected_or_text_box(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(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let (pos, obj) = selected_or_text_box(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)}));
+48 -18
View File
@@ -1,5 +1,5 @@
use super::select::{obj_size, selected, with_obj};
use super::{CmdError, CmdResult, InlineObject, Rgb, Session, Value, Wrap, p};
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 wordcraft_doc::picfx::PicFx;
/// `picture.crop`: the crop, and optionally the new display size, as one edit. With a size, a
@@ -70,19 +70,15 @@ 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])))
}
/// 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()))?;
fn planned_size(s: &Session, o: &InlineObject, v: &Value) -> Result<(f32, f32), CmdError> {
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 {
@@ -118,21 +114,55 @@ pub(super) fn size(s: &mut Session, v: &Value) -> CmdResult {
// Sides set in proportion (from the original, or from a size whose sides both have a length)
// fit the limits together. Otherwise each side the call sets fits on its own, and a side it
// leaves as it was keeps its size, a straight line's 0 too.
let (w, h) = if keep && (original || (w0 > 0.0 && h0 > 0.0 && (w, h) != (w0, h0))) {
fit_size(w, h, true)
if keep && (original || (w0 > 0.0 && h0 > 0.0 && (w, h) != (w0, h0))) {
Ok(fit_size(w, h, true))
} else {
let (fw, fh) = fit_size(w, h, false);
let left = |new: f32, old: f32| !original && new == old;
(if left(w, w0) { w } else { fw }, if left(h, h0) { h } else { fh })
};
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<_>, _>>()?;
// 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();
with_obj(s, |o| {
o.set_size(w, h);
crate::cmd::chart::redraw(o, &theme);
crate::cmd::smart_art::redraw(o, &theme);
})
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")
}
/// An object size within 1–4000 pt. With `keep`, both sides scale by one factor, the one nearest

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